prole/etc/onboard_engineer.sh
chrisfu 00f0ebec07 Merge claude/crazy-bose-fec256 into main
Bringing the long-running session-feature branch back into main in one
deliberate sweep. The branch carried the cluster work that's been live for
weeks (cross-cluster CNPG metrics, Grafana w/ Google OAuth, supabase
oauth2-proxy, cluster recovery, pg.0.knoe.dev + per-engineer onboarding,
GCS-backed CNPG backups via Workload Identity, the env-contamination
guard, the Junie brief queue, the cnpg-grafana CSRF + memory-request
fixes from today), while main accumulated Junie's parallel knoe-auth
Phase 2 OIDC work (full provider surface: discovery, authorize, token,
userinfo, JWKS, RS256 signing, code exchange, session services).

Key decision: the two branches did COMPETING rebrands off the same
starting point (5ba9b63, 2026-04-27):

  - claude branch (commit b355855, earlier): org.prole.authority.* →
                                              dev.knoe.auth.*
                                              (artifact renamed to
                                              knoe-auth.jar)
  - main (commit 9daa94b, recent): org.prole.authority.* →
                                    dev.knoe.authority.*
                                    (kept "authority" artifact name)

dev.knoe.auth wins: cluster runs from this name, the Maven artifact is
already knoe-auth.jar, and the broader rename is the documented
namespace direction (per ~/.claude/projects/-Users-chrisfu-dev-knoe-db/
memory/MEMORY.md). All of main's recent Phase 2 OIDC content was ported
from authority/src/.../dev/knoe/authority/ into
authority/src/.../dev/knoe/auth/ with package declarations rewritten.

== File-level resolution summary ==

Textual conflicts (4):

  authority/pom.xml
    - Took our artifactId="auth"
    - Took our branch's removal of spring-security-kerberos-client
      (verified: Junie's Phase 2 OIDC code does not import it; the dep
      was already-dead config)

  docs/pipeline-phases.md
    - Took our branch's "Phase 1 not started" status. Main had a
      misplaced " Complete" with a knoe-auth-Phase-1 commit ref
      in the autobuild Phase 1 section — different domain.

  docs/plans/knoe-auth-round-1.md
    - Took our branch's dev.knoe.auth file table (vs main's
      dev.knoe.authority listing). Pure rename mismatch.

  supabase/helm/knoe-supabase/templates/kong/config.yaml
    - Took our branch's onboard route + plain dashboard wiring.
      Main had an oauth2proxy.enabled toggle that put oauth2-proxy as
      a Kong upstream — but the deployed architecture (commit 25f1b2e)
      has oauth2-proxy in FRONT of Kong, not behind. Main's wrapper
      reflected an architecture that was never deployed.
    - Took our branch's removal of basic-auth from dashboard route
      (queue #15 brief still tracks the matching values.yaml /
      kong/deployment.yaml cleanup).

Java tree reconciliation (44 file-pairs):

  20 dual-path source files + 2 dual-path tests
    Body-identical between main's authority/ and our branch's auth/
    after stripping package decls — main's commit 9daa94b was a pure
    rebrand. Took our branch's auth/ version for all 22.

  8 main-only source files (Phase 2 OIDC), ported into auth/:
    web/JwksController.java
    web/OidcAuthorizeController.java
    web/OidcDiscoveryController.java
    web/OidcTokenController.java
    web/OidcUserInfoController.java
    session/OidcCodeService.java
    session/OidcTokenService.java
    session/SessionService.java

  12 main-only test files, ported into auth/:
    HealthControllerTest.java
    enroll/EnrollValueTypesTest.java
    enroll/EnrollmentControllerTest.java
    enroll/TotpServiceTest.java
    kerberos/KadminClientTest.java
    kerberos/KerberosSpnegoResultTest.java
    web/LoginControllerTest.java
    admin/AdminControllerTest.java
    user/PrincipalNormalizerTest.java
    regression/IdentityRegressionTest.java
    session/OidcCodeServiceTest.java
    session/SessionServiceTest.java

  Port mechanics: read main:authority/...<file> via git show, then sed
  rewrite `package dev.knoe.authority` → `package dev.knoe.auth` and
  `import dev.knoe.authority` → `import dev.knoe.auth`. Body content
  unchanged.

  authority/src/main/java/dev/knoe/authority/ — DELETED (duplicate)
  authority/src/test/java/dev/knoe/authority/  — DELETED (duplicate)

== Verification ==

- grep -rln '<<<<<<<' across .java/.md/.yaml/.yml/.sh/.xml/.tpl: clean
- find authority/src -path '*/dev/knoe/authority*': empty (subtree gone)
- grep 'package dev.knoe.authority' across repo: clean
- bash -n install.sh deploy.sh etc/preflight_kubecontext.sh: clean
- git ls-files -u | wc -l: 0 unmerged paths
- helm lint supabase/helm/knoe-supabase: pre-existing failure on
  studioIngress.enabled undefined in values.yaml (introduced by Junie
  on main; unrelated to this merge — flagging as follow-up).

== Followups (carried into TODO ranked queue or noted here) ==

  - helm lint failure: studioIngress block in values.yaml is missing
    enable flag; templates/studio/{ingress,oauth2proxy-deployment,
    oauth2proxy-service}.yaml all reference studioIngress.enabled with
    no default. Pre-existing on main; not introduced by this merge.
  - The five Junie briefs filed on this branch are now reachable from
    main at docs/plans/junie/{02,06,07,13,15}-*.md. Junie can pick them
    up in any order.
  - knoe-auth Phase 2 OIDC source (now at dev.knoe.auth.*) is not yet
    deployed to the cluster. Deployment is its own task.
  - The branch claude/crazy-bose-fec256 stays in place (worktree at
    .claude/worktrees/crazy-bose-fec256 may have ongoing context for
    Claude Code sessions). Safe to delete once next session starts
    cleanly from main.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 16:39:10 -07:00

238 lines
7.6 KiB
Bash
Executable File

#!/usr/bin/env bash
# onboard_engineer.sh — provision a per-engineer postgres role + 24h temp
# password, then emit a one-time onboarding URL (and QR-code rendering of it)
# that the new engineer redeems at https://db.0.knoe.dev/onboard.html.
#
# This is the Phase 1 bridge while Junie's Phase 2 (libpq OAUTHBEARER) is in
# flight. When OAUTHBEARER lands, the temp-password mechanism goes away and
# this script's role-creation step is replaced by an INSERT into
# `knoe.oauth_role_map`. The engineer-facing URL stays the same (the page just
# stops showing a password and instead displays the OAUTH connection string).
#
# Usage:
# ./etc/onboard_engineer.sh <username> <email>
# ./etc/onboard_engineer.sh --revoke <username>
#
# Env (resolved from knoe_cfg.sh / KUBECONTEXT etc):
# DB_CLUSTER_KUBECONTEXT — the CNPG cluster context (knoe-dev-cnpg-0)
# DB_NAMESPACE — defaults to knoe-db-0
# DB_PRIMARY_POD — auto-discovered if unset
# ONBOARD_HOST — defaults to db.0.knoe.dev
# ONBOARD_TTL_HOURS — defaults to 24
set -euo pipefail
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
REPO_ROOT=$(cd "$SCRIPT_DIR/.." && pwd)
DB_CTX="${DB_CLUSTER_KUBECONTEXT:-${KUBECONTEXT:-gke_plenary-truck-485623-p7_us-west3_knoe-dev-cnpg-0}}"
DB_NS="${DB_NAMESPACE:-knoe-db-0}"
ONBOARD_HOST="${ONBOARD_HOST:-db.0.knoe.dev}"
ONBOARD_TTL_HOURS="${ONBOARD_TTL_HOURS:-24}"
log() { printf '[%s] %s\n' "$(date +%H:%M:%S)" "$*"; }
warn() { printf '\033[33m[!]\033[0m %s\n' "$*" >&2; }
err() { printf '\033[31m[ERROR]\033[0m %s\n' "$*" >&2; exit 1; }
usage() {
cat <<EOF
Usage:
$(basename "$0") <username> <email> # provision new engineer
$(basename "$0") --revoke <username> # drop role + cancel access
$(basename "$0") --rotate <username> # generate a fresh 24h temp password
Examples:
$(basename "$0") ron ron@knoey.com
$(basename "$0") --revoke test-user
EOF
exit 1
}
primary_pod() {
if [[ -n "${DB_PRIMARY_POD:-}" ]]; then printf '%s' "$DB_PRIMARY_POD"; return; fi
kubectl --context="$DB_CTX" -n "$DB_NS" get pod \
-l cnpg.io/cluster=knoe-db,cnpg.io/instanceRole=primary \
-o jsonpath='{.items[0].metadata.name}'
}
run_psql() {
local sql="$1"
local pod
pod=$(primary_pod)
printf '%s' "$sql" | kubectl --context="$DB_CTX" -n "$DB_NS" exec -i "$pod" -c postgres -- \
psql -U postgres -d postgres -v ON_ERROR_STOP=1 -X --quiet 2>&1
}
ensure_dependencies() {
command -v kubectl >/dev/null 2>&1 || err "kubectl not found"
command -v openssl >/dev/null 2>&1 || err "openssl not found"
command -v base64 >/dev/null 2>&1 || err "base64 not found"
if ! command -v qrencode >/dev/null 2>&1; then
warn "qrencode not installed — output will be URL-only (brew install qrencode for QR rendering)"
fi
}
current_iso8601() {
date -u "+%Y-%m-%dT%H:%M:%SZ"
}
ttl_iso8601() {
# macOS date and GNU date have different flag syntax; both ISO 8601 a
# given offset-from-now expressed in hours. Use python as a portable fallback.
python3 - <<EOF
from datetime import datetime, timedelta, timezone
print((datetime.now(timezone.utc) + timedelta(hours=$ONBOARD_TTL_HOURS)).strftime("%Y-%m-%dT%H:%M:%SZ"))
EOF
}
validate_username() {
local u="$1"
[[ "$u" =~ ^[a-z][a-z0-9_-]{1,30}$ ]] || err "username must match [a-z][a-z0-9_-]{1,30}: $u"
}
validate_email() {
local e="$1"
[[ "$e" =~ ^[^@[:space:]]+@knoey\.com$ ]] || err "email must be *@knoey.com (got: $e). To override, edit the script."
}
action_provision() {
local user="$1" email="$2"
validate_username "$user"
validate_email "$email"
local pw exp ttl_hint
pw=$(openssl rand -base64 24)
exp=$(ttl_iso8601)
ttl_hint="${ONBOARD_TTL_HOURS}h"
log "==> provisioning postgres role: $user (email: $email, valid for $ttl_hint)"
# SQL is idempotent: works for fresh CREATE and re-onboarding.
local sql
sql=$(cat <<SQL
DO \$do\$ BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='$user') THEN
CREATE ROLE "$user" LOGIN INHERIT VALID UNTIL '$exp';
RAISE NOTICE 'created role %', '$user';
ELSE
RAISE NOTICE 'role % exists; updating password and VALID UNTIL', '$user';
END IF;
END \$do\$;
ALTER ROLE "$user" PASSWORD '$pw' VALID UNTIL '$exp';
GRANT knoe_developer TO "$user";
\\echo '=== verification ==='
SELECT rolname, rolcanlogin, rolvaliduntil
FROM pg_roles WHERE rolname='$user';
SELECT 'is_developer' AS check, pg_has_role('$user','knoe_developer','MEMBER') AS ok;
SQL
)
run_psql "$sql"
# URL-safe base64: replace + with -, / with _, drop = padding.
local pw_url
pw_url=$(printf '%s' "$pw" | base64 | tr -d '\n' | tr '+/' '-_' | tr -d '=')
# Wait — pw is already base64 from openssl rand. Encode the *literal text* of
# the password in url-safe base64 so the page can decode and display it
# exactly as typed back into psql. atob() in the browser handles both
# standard and url-safe base64 (after replacement).
local url
url="https://${ONBOARD_HOST}/onboard.html#user=${user}&pw=${pw_url}&exp=${exp}"
printf '\n'
log "==> onboarding link"
printf '\n %s\n\n' "$url"
if command -v qrencode >/dev/null 2>&1; then
log "==> QR code (scan with engineer's phone camera)"
printf '\n'
qrencode -t ANSI256 -m 1 "$url"
printf '\n'
fi
log "==> engineer's plaintext password (fallback if URL is unusable)"
printf '\n %s\n\n' "$pw"
cat <<EOF
==================================================================
DELIVERY:
• Best: Show the QR above on screenshare while $user scans with phone.
Phone opens URL → page shows password + connection string.
• Async: Compose Gmail to $email, paste the URL above, send.
Recipient clicks → page shows password + connection string.
• Last: Hand the plaintext password over a secure channel (Signal).
Less ideal — the page bundles the connection-string UX.
THE TEMP PASSWORD EXPIRES IN ${ttl_hint}.
Engineer should rotate immediately on first connect via: postgres=> \\password
==================================================================
EOF
}
action_revoke() {
local user="$1"
validate_username "$user"
log "==> revoking role: $user"
local sql
sql=$(cat <<SQL
DO \$do\$ BEGIN
IF EXISTS (SELECT FROM pg_roles WHERE rolname='$user') THEN
REVOKE knoe_developer FROM "$user";
DROP ROLE "$user";
RAISE NOTICE 'dropped role %', '$user';
ELSE
RAISE NOTICE 'role % does not exist; nothing to do', '$user';
END IF;
END \$do\$;
SQL
)
run_psql "$sql"
log "==> revocation complete"
}
action_rotate() {
local user="$1"
validate_username "$user"
local pw exp pw_url url
pw=$(openssl rand -base64 24)
exp=$(ttl_iso8601)
log "==> rotating temp password for $user (valid ${ONBOARD_TTL_HOURS}h)"
local sql
sql=$(cat <<SQL
DO \$do\$ BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='$user') THEN
RAISE EXCEPTION 'role % does not exist; use provision action instead', '$user';
END IF;
END \$do\$;
ALTER ROLE "$user" PASSWORD '$pw' VALID UNTIL '$exp';
SQL
)
run_psql "$sql"
pw_url=$(printf '%s' "$pw" | base64 | tr -d '\n' | tr '+/' '-_' | tr -d '=')
url="https://${ONBOARD_HOST}/onboard.html#user=${user}&pw=${pw_url}&exp=${exp}"
printf '\n %s\n\n' "$url"
if command -v qrencode >/dev/null 2>&1; then
qrencode -t ANSI256 -m 1 "$url"; printf '\n'
fi
printf '\n plaintext: %s\n\n' "$pw"
}
# --- main ---
ensure_dependencies
case "${1:-}" in
""|"-h"|"--help") usage ;;
"--revoke") [[ $# -eq 2 ]] || usage; action_revoke "$2" ;;
"--rotate") [[ $# -eq 2 ]] || usage; action_rotate "$2" ;;
*) [[ $# -eq 2 ]] || usage; action_provision "$1" "$2" ;;
esac