mirror of
https://github.com/shankar0123/certctl.git
synced 2026-06-07 15:11:29 +00:00
2a1a0b347c
Audit 2026-05-10 MED-16 closure.
WHAT.
Binds the OIDC pre-login row to the (clientIP, userAgent) tuple of
the /auth/oidc/login request, and enforces a constant-time compare
against the /auth/oidc/callback request at consume time. Defeats
replay of a stolen pre-login cookie by a different browser /
source — the secondary defense layer recommended by RFC 9700 §4.7.1
when the primary layer (HMAC integrity + Path=/ + SameSite=Lax on
the cookie) is bypassed via CSRF / XSS / TLS-termination leak.
WHY.
Pre-fix, the pre-login cookie's HMAC verified only that 'some'
caller of /auth/oidc/login was talking to /auth/oidc/callback; it
did not verify that the SAME browser / source was on both sides.
An attacker who exfiltrated the cookie value via any vector could
replay the bytes through their own user-agent and ride the victim's
authorization. RFC 9700 §4.7.1 calls out the gap explicitly and
recommends binding state to a user-agent fingerprint + source IP.
HOW.
Migration:
migrations/000044_prelogin_uaip.up.sql
ALTER TABLE oidc_pre_login_sessions
ADD COLUMN IF NOT EXISTS client_ip TEXT,
ADD COLUMN IF NOT EXISTS user_agent TEXT;
Both nullable for in-flight rolling-deploy compat — the consume-
side check only enforces when both row AND request carry non-empty
values for the leg in question.
Domain:
internal/repository/oidc.go (PreLoginSession) — adds ClientIP +
UserAgent fields.
Repository:
internal/repository/postgres/oidc_prelogin.go — Create persists
via sql.NullString (empty → NULL); LookupAndConsume reads back.
Re-uses package-local nullableString from discovery.go.
Service:
internal/auth/oidc/service.go
- PreLoginStore.CreatePreLogin signature takes (clientIP,
userAgent) as positions 5–6.
- PreLoginStore.LookupAndConsume returns (clientIP, userAgent)
as positions 5–6.
- HandleAuthRequest signature gains (clientIP, userAgent),
threaded to the store.
- HandleCallback adds Step 1.5 — UA / IP constant-time compare
between stored row and incoming request. Per-leg toggles via
preLoginRequireUA / preLoginRequireIP service fields. Empty
values on either side pass through (rolling-deploy + headless-
proxy compat).
- New sentinels ErrPreLoginUAMismatch, ErrPreLoginIPMismatch.
- SetPreLoginBindingRequirements(requireUA, requireIP) helper
for main.go config wiring.
Adapter:
internal/auth/oidc/prelogin.go — PreLoginAdapter passes the new
fields through to the repo row.
Handler:
internal/api/handler/auth_session_oidc.go
- OIDCAuthHandshaker.HandleAuthRequest signature updated.
- LoginInitiate captures clientIPFromRequest + r.UserAgent()
and passes to the service.
- classifyOIDCFailure adds errors.Is dispatch for the two new
sentinels → prelogin_ua_mismatch / prelogin_ip_mismatch
audit categories.
Config:
internal/config/config.go
+ AuthConfig.OIDCPreLoginRequireUA (default true)
env CERTCTL_OIDC_PRELOGIN_REQUIRE_UA
+ AuthConfig.OIDCPreLoginRequireIP (default true)
env CERTCTL_OIDC_PRELOGIN_REQUIRE_IP
cmd/server/main.go calls oidcService.SetPreLoginBindingRequirements
from cfg.Auth.OIDCPreLoginRequire{UA,IP}.
Tests (internal/auth/oidc/service_test.go):
- TestService_HandleCallback_MED16_UAMismatchRejected
- TestService_HandleCallback_MED16_IPMismatchRejected
- TestService_HandleCallback_MED16_BothMatch_Succeeds
- TestService_HandleCallback_MED16_LegacyRowEmptyValues (rolling-
deploy compat — empty stored values pass through)
- TestService_HandleCallback_MED16_RequireUAFalse_AllowsMismatch
(operator escape-hatch — UA mismatch silently allowed)
Mechanical fan-out:
- stubPreLogin / stubPreLoginRepo signatures updated.
- All existing call sites in service_test.go (~40), prelogin_test.go,
bench_test.go, logging_test.go, provider_enabled_test.go,
integration_keycloak_test.go, integration_okta_smoke_test.go,
auth_session_oidc_test.go updated to pass empty strings for the
new params — pre-existing tests do not exercise UA/IP binding
semantics.
VERIFY.
- go vet ./internal/auth/oidc/... ./internal/api/handler/...
./internal/config/... PASS
- go test -short -count=1 -run MED16 ./internal/auth/oidc/... PASS (5/5)
- go test -short -count=1 ./internal/auth/oidc/... PASS (4.6s)
- go test -short -count=1 ./internal/api/handler/... PASS (4.3s)
- go test -short -count=1 ./internal/config/... PASS
Refs: cowork/auth-bundles-audit-2026-05-10.md MED-16
cowork/auth-bundles-fixes-2026-05-10/HANDOFF.md item 6
RFC 9700 §4.7.1 — OAuth 2.0 Security Best Current Practice
132 lines
4.7 KiB
Go
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)
|
|
}
|
|
}
|