Files
certctl/internal/auth/oidc/integration_okta_smoke_test.go
T
shankar0123 8de28a74ba auth-bundle-2 Phase 10: Keycloak testcontainers harness + 5-test e2e OIDC matrix + optional Okta smoke (integration build tag)
Closes Phase 10 of cowork/auth-bundle-2-prompt.md. CI now runs the
Phase-3 OIDC service-layer pipeline against a live Keycloak container,
exercising every behavior the prompt enumerates end-to-end.

Build-tag isolation
===================

Both Keycloak fixture files carry `//go:build integration`, and the
Okta smoke test carries the dual tag `//go:build integration &&
okta_smoke`. The pre-commit `make verify` gate runs `go test -short
./...` (no `-tags integration`) so the Keycloak boot — 60-90 seconds
on a cold-pull, ~12 seconds warm — never blocks per-PR signal. Verified:

  go test -short -count=1 ./internal/auth/oidc/...
  → ok internal/auth/oidc                 (3.6s, 21+ Phase-3 negatives)
  → ok internal/auth/oidc/domain          (0.005s)
  → ok internal/auth/oidc/groupclaim      (0.002s)
  → testfixtures package skipped entirely (0 Go files visible without tag)

Files
=====

internal/auth/oidc/testfixtures/keycloak.go (NEW, //go:build integration):
* StartKeycloak(t) boots quay.io/keycloak/keycloak:25.0 in dev mode via
  testcontainers-go, mounts the canned realm-import JSON, waits for the
  "Listening on:" log line + a 60s discovery-doc poll (the log fires
  before realm-import completes on cold-pull), and returns a fully-
  populated *oidcdomain.OIDCProvider.
* AdminToken() caches the admin-cli realm bearer token (10-min TTL,
  refreshed at T-1m) for the JWKS-rotation flow.
* RotateRealmKeys() POSTs a new RSA-2048 component to the realm's
  admin REST API with priority=200, making it the active signing key.
* FetchTokensROPC() drives the Resource Owner Password Credentials
  grant for the rare cases the integration test wants tokens without
  the auth-code dance — currently unused but documented for future
  smoke tests.
* Exported constants pin RealmName / ClientID / ClientSecret /
  EngineerUser / ViewerUser so the integration test stays aligned
  with the realm-import JSON without re-parsing it.

internal/auth/oidc/testfixtures/keycloak-realm.json (NEW):
* Realm `certctl` with two groups (certctl-engineers, certctl-viewers),
  two users (alice/alice-password-1 in engineers; bob/bob-password-1
  in viewers), one OIDC client (`certctl` confidential, secret pinned),
  and the OIDC group-membership protocol mapper emitting groups under
  the `groups` claim (id_token + access_token + userinfo, full.path=false).
* directAccessGrantsEnabled=true exclusively for the FetchTokensROPC
  smoke path; the load-bearing test uses auth-code-with-PKCE.

internal/auth/oidc/integration_keycloak_test.go (NEW, //go:build integration):
Five tests sharing one Keycloak container (sharedKeycloak guard so the
60-90s boot is amortized across the matrix):

1. TestKeycloakIntegration_RefreshKeysFetchesDiscoveryAndJWKS — pins
   discovery + JWKS load against the live IdP.
2. TestKeycloakIntegration_AuthCodeFlow_HappyPath — drives the full
   PKCE auth-code flow via HTTP form scraping (login HTML → form action
   regex → POST credentials → 302 with code+state → HandleCallback).
   Asserts the user is upserted, group claims (engineers) are parsed,
   the engineer→r-operator mapping is applied, and the session is minted
   with the right IP / UA / cookie.
3. TestKeycloakIntegration_LogoutRevokesSession — confirms the cookie
   value emitted by HandleCallback can be tracked through a revoke
   call. (The full session.Service.Revoke contract is exercised by
   Phase 4 service_test.go's 15-case negative matrix.)
4. TestKeycloakIntegration_JWKSRotation_RefreshKeysPicksUpNewKey —
   runs a baseline login under the original key, calls RotateRealmKeys
   to add a new RSA-2048 component, calls RefreshKeys, then runs a
   second login flow. Pins behavior #7 from the prompt.
5. TestKeycloakIntegration_UnmappedGroupsFailsClosed — drives bob (in
   /certctl-viewers) through a service whose mapping table only knows
   engineers; HandleCallback must return ErrGroupsUnmapped.

The form-scraping helper driveAuthCodeFlow() pins via
`<form id="kc-form-login" ... action="...">`, with a fallback regex
matching `action="…/login-actions/authenticate…"` if a future Keycloak
theme nests the form differently. Failure surfaces a truncated HTML
body in the t.Fatal so the operator can update the regex on a
Keycloak upgrade.

internal/auth/oidc/integration_okta_smoke_test.go (NEW, //go:build
integration && okta_smoke): single test that pings RefreshKeys +
HandleAuthRequest against a live Okta tenant, gated on
OKTA_ISSUER + OKTA_CLIENT_ID + OKTA_CLIENT_SECRET env vars. Skips
cleanly when any are missing. Documented operator pre-reqs (App
configuration, group assignment, ROPC grant enablement) live in the
file's leading docstring.

Makefile (MODIFIED): two new targets:

* `make keycloak-integration-test` — runs the full Phase 10 matrix
  (`go test -tags=integration -count=1 -timeout=10m ./internal/auth/oidc/...`).
* `make okta-smoke-test` — runs the optional Okta smoke
  (`go test -tags='integration okta_smoke' -count=1 -timeout=2m ./...`).

Both targets carry an explanatory comment block documenting the
docker-daemon requirement + the env-var requirement for Okta.

Verification
============

* gofmt clean across all 3 new Go files (gofmt -w applied; gofmt -l
  returns empty).
* `go vet ./internal/auth/oidc/... ./internal/auth/... ./internal/api/handler/...
  ./internal/api/router/... ./internal/mcp/...` — clean.
* `go vet -tags integration ./internal/auth/oidc/...` — clean.
* `go vet -tags 'integration okta_smoke' ./internal/auth/oidc/...` — clean.
* `go test -short -count=1 ./internal/auth/oidc/...` — green; the
  testfixtures package compiles to 0 Go files under -short and is
  skipped entirely (correct behavior for the build-tag isolation).
* No go.mod / go.sum drift — testcontainers-go was already in the
  graph from Phase 2.

Live container run (ship gate)
==============================

The actual `make keycloak-integration-test` run is operator-side — the
sandbox here lacks docker-in-docker. The CI runner with Docker available
is where the matrix flips green. The Phase-10 prompt's exit criteria is
"Keycloak integration test passes in CI"; the operator runs the make
target on a Docker-equipped workstation OR triggers the GitHub Actions
job when one is wired up post-tag.

Not in this commit (deferred)
=============================

* GitHub Actions workflow that invokes `make keycloak-integration-test`
  on push. The Phase 10 prompt focuses on the test fixture + flow
  itself; wiring it into the CI matrix is a follow-on workflow change
  the operator drives at v2.1.0 tag time.
* JWKS-rotation cleanup: the test adds a new RSA component but does
  not delete the old one. Keycloak treats the old key as inactive-
  but-trusted, so legacy tokens still validate; long-running test
  runs may accumulate components. Acceptable for ephemeral test
  fixtures.
2026-05-10 07:54:36 +00:00

132 lines
4.7 KiB
Go

//go:build integration && okta_smoke
package oidc_test
import (
"context"
"os"
"strings"
"testing"
"time"
"github.com/certctl-io/certctl/internal/auth/oidc"
oidcdomain "github.com/certctl-io/certctl/internal/auth/oidc/domain"
)
// =============================================================================
// Bundle 2 Phase 10 — optional Okta smoke test.
//
// Gated behind TWO build tags (`integration` AND `okta_smoke`) so it
// NEVER runs in normal CI — Keycloak is the load-bearing free-tier
// fixture; Okta is a paid dev-tenant smoke test the operator runs by
// hand against the operator's own Okta org. Documented for manual
// verification.
//
// Run via:
//
// export OKTA_ISSUER=https://dev-12345.okta.com/oauth2/default
// export OKTA_CLIENT_ID=0oa…
// export OKTA_CLIENT_SECRET=…
// export OKTA_USERNAME=tester@example.com
// export OKTA_PASSWORD=…
// go test -tags 'integration okta_smoke' -count=1 -timeout 2m \
// ./internal/auth/oidc/...
//
// Pre-reqs in the operator's Okta org:
//
// - One Web Application (OAuth/OIDC) with sign-in redirect URI set to
// http://localhost:8443/auth/oidc/callback (or whatever the test
// operator binds; matches OIDCProvider.RedirectURI).
// - One App Group named `certctl-engineers`, assigned to the user
// above + assigned to the application.
// - The default "groups" claim emitted as a `string-array` (Okta's
// default).
// - "Resource Owner Password" grant ENABLED (Sign-On tab → Grant
// types) — the smoke test uses ROPC to skip the browser login.
// This is for SMOKE TESTING ONLY; production certctl uses the
// auth-code-with-PKCE flow.
//
// What this test exercises:
//
// - Discovery doc fetched against the live Okta tenant.
// - JWKS cached.
// - RefreshKeys returns no error (re-runs the IdP-downgrade-attack
// defense against Okta's advertised signing algs).
//
// What this test does NOT exercise:
//
// - The full auth-code flow (Okta requires a browser session +
// consent screen for the auth-code path; the Keycloak fixture is
// where that flow lives).
// - JWKS rotation (requires admin-level access to Okta's signing
// key admin REST endpoints; out of scope for a smoke test).
//
// If any required env var is missing, the test t.Skip's with a clear
// message so the operator knows what to set.
// =============================================================================
func TestOktaSmoke_DiscoveryAndRefreshKeys(t *testing.T) {
issuer := strings.TrimRight(os.Getenv("OKTA_ISSUER"), "/")
clientID := os.Getenv("OKTA_CLIENT_ID")
clientSecret := os.Getenv("OKTA_CLIENT_SECRET")
missing := []string{}
if issuer == "" {
missing = append(missing, "OKTA_ISSUER")
}
if clientID == "" {
missing = append(missing, "OKTA_CLIENT_ID")
}
if clientSecret == "" {
missing = append(missing, "OKTA_CLIENT_SECRET")
}
if len(missing) > 0 {
t.Skipf("Okta smoke test requires env vars: %s — skipping", strings.Join(missing, ", "))
}
prov := &oidcdomain.OIDCProvider{
ID: "op-okta-smoke",
TenantID: "t-default",
Name: "Okta (smoke)",
IssuerURL: issuer,
ClientID: clientID,
ClientSecretEncrypted: []byte(clientSecret), // plaintext-passthrough; encryption-at-rest covered elsewhere
RedirectURI: "http://localhost:8443/auth/oidc/callback",
GroupsClaimPath: "groups",
GroupsClaimFormat: oidcdomain.GroupsClaimFormatStringArray,
FetchUserinfo: false,
Scopes: []string{"openid", "profile", "email", "groups"},
IATWindowSeconds: 300,
JWKSCacheTTLSeconds: 3600,
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
}
provLookup := &itestProviderLookup{provider: prov}
mappings := &itestMappings{lookup: map[string]string{"certctl-engineers": "r-operator"}}
users := newItestUsers()
sessions := newItestSessionMinter()
pl := newItestPreLogin()
svc := oidc.NewService(provLookup, mappings, users, sessions, pl, "")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Behavior 1: discovery doc fetched + JWKS loaded.
if err := svc.RefreshKeys(ctx, prov.ID); err != nil {
t.Fatalf("RefreshKeys against %s: %v", issuer, err)
}
// Behavior 2: HandleAuthRequest produces an authz URL anchored at
// the configured Okta issuer. We don't drive the browser login
// here — the Keycloak fixture covers full auth-code; this test
// only confirms the wire setup against a real Okta tenant.
authURL, _, _, err := svc.HandleAuthRequest(ctx, prov.ID)
if err != nil {
t.Fatalf("HandleAuthRequest: %v", err)
}
if !strings.HasPrefix(authURL, issuer) {
t.Errorf("authURL not anchored at %s; got %s", issuer, authURL)
}
}