Bundle: redb-identity / demos (demos.txt), 68 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Index: https://redbase.app/src/dev-2026-12-06/redb-identity/_index.txt ==== Path: redb-identity/demos/_one_register.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/_one_register.ps1 ---- $user = "tim_" + [Guid]::NewGuid().ToString("N").Substring(0,8) $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $user = "tim_" + [Guid]::NewGuid().ToString("N").Substring(0,8) $body = @{ login=$user; email="$user@example.com"; password="Test1234Pass!"; displayName=$user } | ConvertTo-Json $sw = [System.Diagnostics.Stopwatch]::StartNew() $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" -Body $body $sw.Stop() Write-Host ("register: {0:N0} ms login={1} userId={2}" -f $sw.Elapsed.TotalMilliseconds, $r.login, $r.userId) Path: redb-identity/demos/demo_account_register_verify.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_account_register_verify.ps1 ---- # Account registration + email-verification flow. # POST /account/register → try login before verify → request verify resend # → attempt confirm with wrong token (expect 400) → attempt confirm with # well-formed but bogus token → check error shape. # # Note: a real SMTP inbox is NOT required. The demo probes endpoint contracts, # timing, and error shapes. Step 5 (confirm with correct token) is skipped # because the token is delivered out-of-band via email; a human can run it # manually using the token logged by the server. # Usage: pwsh -File demo_account_register_verify.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — password grant for login checks. $reg = Measure-Step "1. DCR /connect/register (password)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "verify-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email" } | ConvertTo-Json) } $reg | Format-List client_id, client_secret # 2) POST /account/register — create a fresh user. $user = "vrfy_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" $email = "$user@example.com" $regResp = Measure-Step "2. POST /api/v1/identity/account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = $email password = $pwd displayName = $user } | ConvertTo-Json) } $regResp | ConvertTo-Json -Depth 3 | Out-Host # 3) Try login before email verification — server may allow (config-dependent) or require verify. Measure-Step "3. ROPC before email verify (accept 200 OR 400 emailNotVerified)" { try { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email" } Write-Host " ✓ login allowed before verification (email verify is optional on this server)" -ForegroundColor Green Write-Host " token_type: $($t.token_type)" } catch { $code = $_.Exception.Response.StatusCode.value__ $body = $null if ($_.ErrorDetails -and $_.ErrorDetails.Message) { $body = $_.ErrorDetails.Message } if ($code -in 400,401) { Write-Host " Server requires email verification before login ($code)" -ForegroundColor Yellow if ($body) { Write-Host " error: $body" } } else { throw } } } | Out-Null # 4) POST /account/verify-email/send — request the verification email. Measure-Step "4. POST /api/v1/identity/account/verify-email/send (resend)" { try { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/verify-email/send" ` -ContentType "application/json" ` -Body (@{ email = $email } | ConvertTo-Json) Write-Host " ✓ verify email send accepted" -ForegroundColor Green $r | ConvertTo-Json | Out-Host } catch { $code = $_.Exception.Response.StatusCode.value__ $body = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } if ($code -eq 200) { Write-Host " ✓ accepted" -ForegroundColor Green } elseif ($code -eq 400 -and $body -match "already.verified") { Write-Host " (email already verified — server may auto-verify in dev mode)" -ForegroundColor DarkGray } else { Write-Host " status: $code body: $body" -ForegroundColor Yellow } } } | Out-Null # 5) POST /account/verify-email/confirm with a syntactically-wrong token — expect 400. Measure-Step "5. POST verify-email/confirm with bogus token (expect 400)" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/verify-email/confirm" ` -ContentType "application/json" ` -Body (@{ email = $email token = "BOGUS-TOKEN-$(Get-Random)" } | ConvertTo-Json) | Out-Null Write-Host " ! UNEXPECTED success — bogus token accepted" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ $body = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } if ($code -eq 400) { Write-Host " ✓ rejected: 400" -ForegroundColor Green if ($body) { Write-Host " body: $body" } } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null # 6) POST /account/verify-email/confirm with a well-formed (Base64) but wrong token — expect 400. $fakeToken = [Convert]::ToBase64String([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) Measure-Step "6. POST verify-email/confirm with wrong-but-well-formed token (expect 400)" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/verify-email/confirm" ` -ContentType "application/json" ` -Body (@{ email = $email token = $fakeToken } | ConvertTo-Json) | Out-Null Write-Host " ! UNEXPECTED success — random token accepted" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ $body = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } if ($code -eq 400) { Write-Host " ✓ rejected: 400" -ForegroundColor Green if ($body) { Write-Host " body: $body" } } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null # 7) POST /account/verify-email/confirm for a non-existent email — expect 400 (no user enumeration). Measure-Step "7. verify-email/confirm for unknown email (expect 400 — no user enumeration)" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/verify-email/confirm" ` -ContentType "application/json" ` -Body (@{ email = "ghost_$(Get-Random)@example.com" token = $fakeToken } | ConvertTo-Json) | Out-Null Write-Host " ! UNEXPECTED success — unknown email accepted" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ $body = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } if ($code -eq 400) { Write-Host " ✓ rejected: 400 (error body should not hint user existence)" -ForegroundColor Green Write-Host " body: $body" } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null # 8) Duplicate register — same login must be rejected. Measure-Step "8. Duplicate register (same login — expect 400/409)" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "other_$email" password = $pwd displayName = "$user dup" } | ConvertTo-Json) | Out-Null Write-Host " ! UNEXPECTED — duplicate login accepted" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -in 400,409,422) { Write-Host " ✓ duplicate rejected: $code" -ForegroundColor Green } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Write-Host "(to complete email verify: run the confirm step manually with the token from server logs)" -ForegroundColor DarkGray Path: redb-identity/demos/demo_acr_values.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_acr_values.ps1 ---- # OIDC Core §2 — `acr` claim probe. # # Closes the ❌ "acr_values" entry in §5 of the coverage matrix. The server emits an # `acr` claim on every id_token with a value derived from the actual authentication # strength: # "0" — no authentication enforcement (session-only / unreachable here), # "1" — single-factor (password-only ROPC, password+cookie), # "2" — multi-factor verified (SessionProps.MfaVerified = true). # # Per OIDC §5.5.1.1 `acr` is a voluntary claim by default — the OP returns its actual # acr regardless of what the RP requested via `acr_values`, and the RP is responsible # for accepting / rejecting based on the value. # # Probes (all asserted): # 1. DCR (auth_code+PKCE) # 2. self-register + cookie /login # 3. authorize+token (no acr_values) → id_token.acr exists, equals "1" (no MFA) # 4. authorize+token with acr_values="1" → id_token.acr == "1" (matches request) # 5. authorize+token with acr_values="2" on a non-MFA session → id_token.acr is # still "1" (the server returns its actual strength; RP enforces) # 6. ROPC token → access_token.acr == "1" (no MFA on ROPC either) # 7. /connect/userinfo carries the same acr # 8. RFC 7592 cleanup # # Note: `acr=2` (MFA-verified) is exercised end-to-end by `demo_mfa_totp` chained with # an authorize call — covering it here would duplicate the MFA enrol flow. The probe # here owns the "did the server emit acr at all and respect the basic value contract" # portion. # # Usage: pwsh -File demo_acr_values.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $REDIRECT = $REDIRECT_CB $timings = [System.Collections.Generic.List[object]]::new() Add-Type -AssemblyName System.Web function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } function B64U([byte[]]$bytes) { [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=') } function New-Pkce { $verifier = B64U ([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) $challenge = B64U ([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::ASCII.GetBytes($verifier))) return [pscustomobject]@{ Verifier=$verifier; Challenge=$challenge } } function Get-JwtBody([string]$jwt) { $parts = $jwt.Split('.') if ($parts.Count -lt 2) { throw "JWT does not have 3 segments" } $b64 = $parts[1].Replace('-','+').Replace('_','/') switch ($b64.Length % 4) { 2 { $b64 += '==' } 3 { $b64 += '=' } } $json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64)) return $json | ConvertFrom-Json -Depth 12 } function Invoke-AuthCodeFlow { param( [Microsoft.PowerShell.Commands.WebRequestSession]$Session, [string]$ClientId, [string]$ClientSecret, [hashtable]$Extras = @{} ) $pkce = New-Pkce $state = "acr-" + [Guid]::NewGuid().ToString('N').Substring(0,6) $body = @{ response_type = "code" client_id = $ClientId redirect_uri = $REDIRECT scope = "openid profile email" code_challenge = $pkce.Challenge code_challenge_method = "S256" state = $state } foreach ($k in $Extras.Keys) { $body[$k] = $Extras[$k] } $resp = $null try { $resp = Invoke-WebRequest -Method Post "$BASE/connect/authorize" ` -WebSession $Session -ContentType "application/x-www-form-urlencoded" ` -Body $body -MaximumRedirection 0 -ErrorAction Stop } catch { $resp = $_.Exception.Response } $loc = if ($resp -is [System.Net.Http.HttpResponseMessage]) { $resp.Headers.Location.ToString() } else { $resp.Headers["Location"] } if (-not $loc) { throw "no Location on /connect/authorize response" } $u = [uri]$loc $q = [System.Web.HttpUtility]::ParseQueryString($u.Query) if ($q['error']) { throw "authorize returned error=$($q['error'])" } if (-not $q['code']) { throw "no code in redirect" } Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "authorization_code" client_id = $ClientId client_secret = $ClientSecret redirect_uri = $REDIRECT code = $q['code'] code_verifier = $pkce.Verifier } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR. $reg = Measure-Step "1. DCR (auth_code + PKCE)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "acr-values-demo" redirect_uris = @($REDIRECT) grant_types = @("authorization_code","refresh_token","password") scope = "openid profile email" } | ConvertTo-Json) if (-not $r.client_id) { throw "no client_id" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green return $r } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri # 2) Self-register + login. $user = "acr_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession Measure-Step "2. self-register + POST /login" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@example.com"; password = $pwd; displayName = $user } | ConvertTo-Json) | Out-Null try { Invoke-WebRequest -Method Post "$BASE/login" ` -WebSession $session -ContentType "application/x-www-form-urlencoded" ` -Body @{ username = $user; password = $pwd } ` -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction SilentlyContinue | Out-Null } catch {} if ($session.Cookies.GetCookies($BASE).Count -lt 1) { throw "no session cookie" } Write-Host " ✓ user + session" -ForegroundColor Green } | Out-Null # 3) authorize+token, no acr_values → id_token.acr exists, equals "1". Measure-Step "3. authorize+token (no acr_values) → id_token.acr == '1'" { $t = Invoke-AuthCodeFlow -Session $session -ClientId $reg.client_id -ClientSecret $reg.client_secret if (-not $t.id_token) { throw "no id_token" } $c = Get-JwtBody $t.id_token if (-not $c.PSObject.Properties['acr']) { throw "id_token missing acr claim" } if ($c.acr -ne "1") { throw "acr expected '1' (no MFA), got '$($c.acr)'" } Write-Host " ✓ id_token.acr = '1'" -ForegroundColor Green } | Out-Null # 4) acr_values=1 → still "1" (request matches actual). Measure-Step "4. authorize+token acr_values='1' → acr stays '1'" { $t = Invoke-AuthCodeFlow -Session $session -ClientId $reg.client_id -ClientSecret $reg.client_secret ` -Extras @{ acr_values = "1" } $c = Get-JwtBody $t.id_token if ($c.acr -ne "1") { throw "acr expected '1', got '$($c.acr)'" } Write-Host " ✓ id_token.acr = '1' (matches request)" -ForegroundColor Green } | Out-Null # 5) acr_values=2 on non-MFA session → server emits its actual strength ("1"); # OIDC §5.5.1.1 voluntary contract — RP enforces. Measure-Step "5. authorize+token acr_values='2' (no MFA) → acr is '1' (voluntary)" { $t = Invoke-AuthCodeFlow -Session $session -ClientId $reg.client_id -ClientSecret $reg.client_secret ` -Extras @{ acr_values = "2" } $c = Get-JwtBody $t.id_token if ($c.acr -ne "1") { throw "acr expected '1' (server emits actual strength regardless of requested), got '$($c.acr)'" } Write-Host " ✓ acr=1 — server honours OIDC §5.5.1.1 voluntary-claim contract" -ForegroundColor Green } | Out-Null # 6) ROPC → access_token JWE (opaque) BUT id_token has acr. Measure-Step "6. ROPC password grant → id_token.acr == '1'" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email" } if (-not $t.id_token) { throw "no id_token on ROPC" } $c = Get-JwtBody $t.id_token if ($c.acr -ne "1") { throw "ROPC id_token.acr expected '1', got '$($c.acr)'" } Write-Host " ✓ ROPC id_token.acr = '1'" -ForegroundColor Green $script:ropcTok = $t } | Out-Null # 7) /userinfo (uses ROPC access_token — opaque-format JWE, but the server still # populates acr-equivalent on the userinfo body if implemented; if absent that's # spec-compliant since OIDC §5.3 lists acr as a voluntary claim there too). Measure-Step "7. GET /connect/userinfo (acr is voluntary on userinfo per §5.3)" { $ui = Invoke-RestMethod -Method Get "$BASE/connect/userinfo" ` -Headers @{ Authorization = "Bearer $($script:ropcTok.access_token)" } if (-not $ui.sub) { throw "userinfo missing sub" } if ($ui.PSObject.Properties['acr']) { Write-Host " ✓ userinfo carries acr = '$($ui.acr)'" -ForegroundColor Green } else { Write-Host " ✓ userinfo OK (no acr — voluntary per OIDC §5.3)" -ForegroundColor DarkGray } } | Out-Null # 8) RFC 7592 cleanup. Measure-Step "8. RFC 7592 DELETE registration" { if (-not $RAT) { return } Invoke-RestMethod -Method Delete -Uri $RCU -Headers @{ Authorization = "Bearer $RAT" } | Out-Null Write-Host " ✓ client deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_admin_mfa.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_admin_mfa.ps1 ---- # Admin-side MFA enrollment through the management API (/api/v1/identity/mfa). # # An operator with identity:mfa:read identity:mfa:write enrolls a user in TOTP, reads the status, regenerates the # recovery codes and disables TOTP again. Confirm sends the first code together with the setup token of the setup # answer. # # Probes (all asserted): # 1. Admin DCR (cc + identity:users:write identity:mfa:read identity:mfa:write) # 2. Admin cc token # 3. Seed a user # 4. POST /mfa/totp/setup -> secret_base32, qr_uri, setup_token # 5. POST /mfa/totp/confirm -> confirmed, 10 recovery codes # 6. GET /mfa/status/{id} -> enabled, methods contains totp, 10 codes remaining # 7. POST /mfa/recovery-codes/regenerate -> 10 new codes # 8. DELETE /mfa/totp/{id} -> disabled # 9. GET /mfa/status/{id} -> not enabled # 10. Cleanup: delete user # # Usage: pwsh -File demo_admin_mfa.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $SCOPES = "identity:users:write identity:mfa:read identity:mfa:write" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } # Base32 (RFC 4648) decoder. function ConvertFrom-Base32([string]$s) { $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" $s = $s.ToUpperInvariant().TrimEnd('=') $bits = New-Object System.Text.StringBuilder foreach ($c in $s.ToCharArray()) { $v = $alphabet.IndexOf([string]$c) if ($v -lt 0) { throw "invalid base32 char: $c" } [void]$bits.Append([Convert]::ToString($v, 2).PadLeft(5, '0')) } $bitsStr = $bits.ToString() $bytes = [System.Collections.Generic.List[byte]]::new() for ($i = 0; $i + 8 -le $bitsStr.Length; $i += 8) { $bytes.Add([Convert]::ToByte($bitsStr.Substring($i, 8), 2)) } return ,$bytes.ToArray() } # RFC 6238 TOTP / RFC 4226 HOTP, SHA1, 6 digits, 30 s step. function Compute-Totp([string]$base32Secret) { $key = ConvertFrom-Base32 $base32Secret $t = [int64]([Math]::Floor(([DateTimeOffset]::UtcNow.ToUnixTimeSeconds()) / 30)) $tbytes = [BitConverter]::GetBytes($t) if ([BitConverter]::IsLittleEndian) { [Array]::Reverse($tbytes) } $hmac = New-Object System.Security.Cryptography.HMACSHA1(,$key) $hash = $hmac.ComputeHash($tbytes) $offset = $hash[$hash.Length - 1] -band 0x0F $code = (([int]$hash[$offset] -band 0x7F) -shl 24) ` -bor (([int]$hash[$offset+1] -band 0xFF) -shl 16) ` -bor (([int]$hash[$offset+2] -band 0xFF) -shl 8) ` -bor ([int]$hash[$offset+3] -band 0xFF) return ($code % 1000000).ToString("D6") } $total = [System.Diagnostics.Stopwatch]::StartNew() $adminReg = Measure-Step "1. admin DCR" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "admin-mfa"; grant_types = @("client_credentials"); scope = $SCOPES } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = $SCOPES } } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } $user = "adminmfa_" + [Guid]::NewGuid().ToString("N").Substring(0,8) $UserId = Measure-Step "3. seed user" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@example.com"; password = "AdminMfaPass1234!"; displayName = $user } | ConvertTo-Json) if (-not $r.success -or -not $r.userId) { throw "register failed: $($r | ConvertTo-Json)" } return [long]$r.userId } $setup = Measure-Step "4. POST /mfa/totp/setup" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/mfa/totp/setup" -Headers $ADMIN ` -Body (@{ userId = $UserId; username = $user } | ConvertTo-Json) if (-not $r.secret_base32 -or -not $r.setup_token) { throw "setup answer lacks secret_base32 or setup_token: $($r | ConvertTo-Json)" } Write-Host " ok: secret and setup token issued" -ForegroundColor Green return $r } Measure-Step "5. POST /mfa/totp/confirm (code + setup token)" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/mfa/totp/confirm" -Headers $ADMIN ` -Body (@{ userId = $UserId; code = (Compute-Totp $setup.secret_base32); setupToken = $setup.setup_token } | ConvertTo-Json) if (-not $r.confirmed -or $r.recovery_codes.Count -ne 10) { throw "confirm failed: $($r | ConvertTo-Json)" } Write-Host " ok: confirmed, 10 recovery codes" -ForegroundColor Green } | Out-Null Measure-Step "6. GET /mfa/status - enabled" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/mfa/status/$UserId" -Headers $ADMIN if (-not $r.enabled -or $r.methods -notcontains "totp" -or $r.recovery_codes_remaining -ne 10) { throw "status: $($r | ConvertTo-Json)" } Write-Host " ok: enabled, totp, 10 codes remaining" -ForegroundColor Green } | Out-Null Measure-Step "7. POST /mfa/recovery-codes/regenerate" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/mfa/recovery-codes/regenerate" -Headers $ADMIN ` -Body (@{ userId = $UserId } | ConvertTo-Json) if ($r.recovery_codes.Count -ne 10) { throw "regenerate: $($r | ConvertTo-Json)" } Write-Host " ok: 10 new codes" -ForegroundColor Green } | Out-Null Measure-Step "8. DELETE /mfa/totp - disable" { $r = Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/mfa/totp/$UserId" -Headers $ADMIN if (-not $r.disabled) { throw "disable: $($r | ConvertTo-Json)" } Write-Host " ok: disabled" -ForegroundColor Green } | Out-Null Measure-Step "9. GET /mfa/status - not enabled" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/mfa/status/$UserId" -Headers $ADMIN if ($r.enabled) { throw "still enabled: $($r | ConvertTo-Json)" } Write-Host " ok: not enabled" -ForegroundColor Green } | Out-Null Measure-Step "10. cleanup: delete user" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$UserId" -Headers $ADMIN | Out-Null } catch { Write-Host " (cleanup) user delete returned: $($_.Exception.Message)" -ForegroundColor DarkGray } } | Out-Null $total.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Magenta Path: redb-identity/demos/demo_admin_mfa_email.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_admin_mfa_email.ps1 ---- # Admin-side e-mail MFA enrollment through the management API (/api/v1/identity/mfa/email). # # Setup sends the one-time code to the NEW address (through the SMTP channel of context.json, caught by GreenMail) # and answers with mfa_state and setup_token; confirm takes the code with both. # # Probes: # 1. Admin DCR (cc + identity:users:write identity:mfa:read identity:mfa:write) # 2. client_credentials token # 3. seed a user # 4. POST /mfa/email/setup -> masked_email, mfa_state, setup_token; the code is e-mailed # 5. read the code from GreenMail # 6. POST /mfa/email/confirm (wrong code) -> 400 invalid_code # 7. POST /mfa/email/confirm -> confirmed, 10 recovery codes # 8. GET /mfa/status/{id} -> enabled, methods contains email # 9. DELETE /mfa/email/{id} -> disabled # 10. cleanup: delete user # # Requires the GreenMail container (SMTP 3025 / REST 8080), as demo_password_reset does. # # Usage: pwsh -File demo_admin_mfa_email.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $GM = "http://127.0.0.1:8080" # GreenMail REST API $SCOPES = "identity:users:write identity:mfa:read identity:mfa:write" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function Wait-Email { param([string]$Email, [int]$TimeoutMs = 8000) $deadline = [DateTimeOffset]::UtcNow.AddMilliseconds($TimeoutMs) while ([DateTimeOffset]::UtcNow -lt $deadline) { try { $msgs = Invoke-RestMethod -Method Get "$GM/api/user/$Email/messages/INBOX" -ErrorAction Stop if ($msgs -and $msgs.Count -ge 1) { return $msgs[0] } } catch { # 404 until the user is auto-created by GreenMail on first mail, retry. } Start-Sleep -Milliseconds 300 } return $null } function Decode-QuotedPrintable { param([string]$s) if ([string]::IsNullOrEmpty($s)) { return $s } $s = $s -replace "=\r\n", "" -replace "=\n", "" return [regex]::Replace($s, "=([0-9A-Fa-f]{2})", { param($m) [char][Convert]::ToInt32($m.Groups[1].Value, 16) }) } $total = [System.Diagnostics.Stopwatch]::StartNew() $adminReg = Measure-Step "1. admin DCR" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "admin-mfa-email"; grant_types = @("client_credentials"); scope = $SCOPES } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = $SCOPES } } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } $user = "mfamail_" + [Guid]::NewGuid().ToString("N").Substring(0,8) $address = "$user-mfa@example.com" $UserId = Measure-Step "3. seed user" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@example.com"; password = "AdminMfaPass1234!"; displayName = $user } | ConvertTo-Json) if (-not $r.success -or -not $r.userId) { throw "register failed: $($r | ConvertTo-Json)" } return [long]$r.userId } $setup = Measure-Step "4. POST /mfa/email/setup" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/mfa/email/setup" -Headers $ADMIN ` -Body (@{ userId = $UserId; username = $user; destination = $address } | ConvertTo-Json) if (-not $r.mfa_state -or -not $r.setup_token -or -not $r.masked_email) { throw "setup answer lacks mfa_state, setup_token or masked_email: $($r | ConvertTo-Json)" } Write-Host " ok: code sent to $($r.masked_email), mfa_state and setup token issued" -ForegroundColor Green return $r } $code = Measure-Step "5. read the code from GreenMail" { $msg = Wait-Email -Email $address if ($null -eq $msg) { throw "no e-mail for $address in GreenMail" } $body = Decode-QuotedPrintable $msg.mimeMessage $m = [regex]::Match($body, 'verification code is:\s*(\d{6})') if (-not $m.Success) { throw "no 6-digit code in the e-mail" } Write-Host " ok: code read from the e-mail" -ForegroundColor Green return $m.Groups[1].Value } Measure-Step "6. POST /mfa/email/confirm (wrong code) - 400 invalid_code" { $wrong = if ($code -eq "000000") { "111111" } else { "000000" } $resp = Invoke-WebRequest -Method Post "$BASE/api/v1/identity/mfa/email/confirm" -Headers $ADMIN -SkipHttpErrorCheck ` -Body (@{ userId = $UserId; code = $wrong; mfaState = $setup.mfa_state; setupToken = $setup.setup_token } | ConvertTo-Json) $err = ($resp.Content | ConvertFrom-Json).error if ($resp.StatusCode -ne 400 -or $err -ne "invalid_code") { throw "expected 400 invalid_code, got $($resp.StatusCode) $($resp.Content)" } Write-Host " ok: wrong code refused" -ForegroundColor Green } | Out-Null Measure-Step "7. POST /mfa/email/confirm (code + mfa_state + setup token)" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/mfa/email/confirm" -Headers $ADMIN ` -Body (@{ userId = $UserId; code = $code; mfaState = $setup.mfa_state; setupToken = $setup.setup_token } | ConvertTo-Json) if (-not $r.confirmed -or $r.recovery_codes.Count -ne 10) { throw "confirm failed: $($r | ConvertTo-Json)" } Write-Host " ok: confirmed, 10 recovery codes" -ForegroundColor Green } | Out-Null Measure-Step "8. GET /mfa/status - email enabled" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/mfa/status/$UserId" -Headers $ADMIN if (-not $r.enabled -or $r.methods -notcontains "email") { throw "status: $($r | ConvertTo-Json)" } Write-Host " ok: enabled, email" -ForegroundColor Green } | Out-Null Measure-Step "9. DELETE /mfa/email - disable" { $r = Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/mfa/email/$UserId" -Headers $ADMIN if (-not $r.disabled) { throw "disable: $($r | ConvertTo-Json)" } Write-Host " ok: disabled" -ForegroundColor Green } | Out-Null Measure-Step "10. cleanup: delete user" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$UserId" -Headers $ADMIN | Out-Null } catch { Write-Host " (cleanup) user delete returned: $($_.Exception.Message)" -ForegroundColor DarkGray } } | Out-Null $total.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Magenta Path: redb-identity/demos/demo_admin_password_reset.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_admin_password_reset.ps1 ---- # Admin-side password reset — bypasses OldPassword challenge. # # Operator with identity:users:write identity:groups:write identity:consents:write identity:mfa:write POSTs /users/{id}/admin-reset-password # with just { NewPassword } — server side runs the same complexity policy as # the user-self flow + revokes every session for the target user. # # Probes (all asserted): # 1. Admin DCR (cc + identity:users:write identity:groups:write identity:consents:write identity:mfa:write) # 2. Admin cc token # 3. Seed a user # 4. Sanity ROPC with the original password → 200 # 5. Admin: POST /users/{id}/admin-reset-password { NewPassword = "Reset…" } # 6. ROPC with the OLD password → invalid_grant # 7. ROPC with the NEW password → 200 # 8. Cleanup: delete user # # Usage: pwsh -File demo_admin_password_reset.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function Get-Ropc { param($ClientId, $ClientSecret, $Username, $Password) Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $ClientId client_secret = $ClientSecret username = $Username password = $Password scope = "openid" } } function Assert-RopcDenied { param($ClientId, $ClientSecret, $Username, $Password, $Label) try { $body = Get-Ropc -ClientId $ClientId -ClientSecret $ClientSecret -Username $Username -Password $Password throw " ! ${Label}: expected invalid_grant, got token: $($body.access_token.Substring(0,16))…" } catch { $code = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -in 400, 401) { Write-Host " ✓ $Label → $code" -ForegroundColor Green } else { throw } } } $total = [System.Diagnostics.Stopwatch]::StartNew() # --- 1) Admin DCR cc + identity:users:write identity:groups:write identity:consents:write identity:mfa:write --- $adminReg = Measure-Step "1. admin DCR" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "admin-pwd-reset"; grant_types = @("client_credentials"); scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write" } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write" } } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } # --- 3) Seed a user --- $user = "pwdreset_" + [Guid]::NewGuid().ToString("N").Substring(0,8) $oldPwd = "OldOldPass1234!" $newPwd = "NewNewPass5678!" $UserId = Measure-Step "3. seed user" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@example.com"; password = $oldPwd; displayName = $user } | ConvertTo-Json) if (-not $r.success -or -not $r.userId) { throw "register failed: $($r | ConvertTo-Json)" } return [long]$r.userId } # --- 4) Also need a ROPC client to actually try logins --- $ropcReg = Measure-Step "4a. DCR ropc client" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "pwdreset-ropc"; redirect_uris = @($REDIRECT_CB); grant_types = @("password","refresh_token"); scope = "openid" } | ConvertTo-Json) } Measure-Step "4b. ROPC with OLD password — expect 200" { $t = Get-Ropc -ClientId $ropcReg.client_id -ClientSecret $ropcReg.client_secret -Username $user -Password $oldPwd if (-not $t.access_token) { throw "no access_token" } Write-Host " ✓ access_token: $($t.access_token.Substring(0,16))…" -ForegroundColor Green } | Out-Null # --- 5) Admin reset password --- Measure-Step "5. admin: POST /users/$UserId/admin-reset-password" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/users/$UserId/admin-reset-password" -Headers $ADMIN ` -Body (@{ id = $UserId; newPassword = $newPwd } | ConvertTo-Json) | Out-Null Write-Host " ✓ reset accepted" -ForegroundColor Green } | Out-Null # --- 6) Old password must fail --- Measure-Step "6. ROPC with OLD password — expect invalid_grant" { Assert-RopcDenied -ClientId $ropcReg.client_id -ClientSecret $ropcReg.client_secret -Username $user -Password $oldPwd ` -Label "old password rejected" } | Out-Null # --- 7) New password must succeed --- Measure-Step "7. ROPC with NEW password — expect 200" { $t = Get-Ropc -ClientId $ropcReg.client_id -ClientSecret $ropcReg.client_secret -Username $user -Password $newPwd if (-not $t.access_token) { throw "no access_token with new password" } Write-Host " ✓ access_token: $($t.access_token.Substring(0,16))…" -ForegroundColor Green } | Out-Null # --- 8) Cleanup --- Measure-Step "8. cleanup: delete user" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$UserId" -Headers $ADMIN | Out-Null } catch { Write-Host " (cleanup) user delete returned: $($_.Exception.Message)" -ForegroundColor DarkGray } } | Out-Null $total.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Magenta Path: redb-identity/demos/demo_admin_scopes.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_admin_scopes.ps1 ---- # P1 #10 — granular admin scopes probe. # # Two complementary scope axes from `IdentityScopes`: # `identity:read` — read-only admin: GET on any admin path; mutations → 403 # `identity:audit:read` — narrowest granular scope: only /audit GET passes; other admin paths → 403 # # Closes the GAP in §4 of the coverage matrix (identity:read / identity:audit:read). # The asserts demonstrate the per-method (read-only) and per-path (granular) sides of # `GranularScopeGuardProcessor` (HTTP facade) without relying on a master admin token. # # Probes (all asserted): # 1. DCR client_credentials + identity:read # 2. cc token (scope=identity:read) # 3. GET /users → 200 (read-only OK) # 4. GET /groups → 200 (read-only OK) # 5. GET /applications → 200 (read-only OK) # 6. GET /audit → 200 (read-only OK) # 7. POST /groups (mutation) → 403 insufficient_scope (read-only rejected) # 8. POST /users (mutation) → 403 insufficient_scope # 9. DCR client_credentials + identity:audit:read # 10. cc token (scope=identity:audit:read) # 11. GET /audit → 200 (granular OK) # 12. GET /users → 403 (audit.read does NOT grant /users) # 13. GET /applications → 403 # 14. GET /audit?eventType=UserCreated → 200, results well-shaped # 15. /audit without bearer → 401 # 16. /audit with garbage bearer → 401 # 17. RFC 7592 cleanup # # Usage: pwsh -File demo_admin_scopes.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } # Expect a specific HTTP status from a request. Returns response body on match, # or throws (with body snippet) on mismatch. function Assert-Status { param([scriptblock]$Call, [int[]]$Expect, [string]$Label) try { $body = & $Call if (200 -in $Expect) { return $body } throw " ! UNEXPECTED 2xx ($Label) — body: $($body | ConvertTo-Json -Depth 3)" } catch { $code = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 } if ($Expect -contains $code) { $errBody = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } Write-Host " ✓ $Label → $code" -ForegroundColor Green if ($errBody) { Write-Host " body: $errBody" -ForegroundColor DarkGray } return $null } throw " ! ${Label}: got $code, expected $($Expect -join '/')" } } function DcrCc([string]$ClientName, [string]$Scope) { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = $ClientName grant_types = @("client_credentials") scope = $Scope } | ConvertTo-Json) } function CcToken([string]$ClientId, [string]$ClientSecret, [string]$Scope) { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $ClientId client_secret = $ClientSecret scope = $Scope } } $total = [System.Diagnostics.Stopwatch]::StartNew() # ── Axis 1: identity:read (cross-path, GET-only) ────────────────────────────── $rdReg = Measure-Step "1. DCR (cc + identity:read)" { $r = DcrCc "admin-scopes-read" "identity:read" if (-not $r.client_id) { throw "no client_id" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green return $r } $READ_RAT = $rdReg.registration_access_token $READ_RCU = $rdReg.registration_client_uri $rdTok = Measure-Step "2. cc token (scope=identity:read)" { $t = CcToken $rdReg.client_id $rdReg.client_secret "identity:read" if (-not $t.access_token) { throw "no access_token" } Write-Host " ✓ access_token (len $($t.access_token.Length))" -ForegroundColor Green return $t } $RD = @{ Authorization = "Bearer $($rdTok.access_token)" } # Helper: probe a paged endpoint and report whatever the server actually returns. # The bare admin list endpoints currently return a JSON array; /audit returns # { total, offset, count, items[] }. Either is fine — we just want the GET to succeed. function Describe-Response($r) { if ($r -is [Array]) { return "array len=$($r.Count)" } if ($r.PSObject.Properties['total']) { return "total=$($r.total) items=$($r.items.Count)" } if ($r.PSObject.Properties['Total']) { return "Total=$($r.Total) Items=$($r.Items.Count)" } return "object keys=$(($r.PSObject.Properties.Name -join ','))" } Measure-Step "3. GET /users (identity:read → expect 200)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/users?offset=0&count=1" -Headers $RD Write-Host " ✓ /users readable, $(Describe-Response $r)" -ForegroundColor Green } | Out-Null Measure-Step "4. GET /groups (identity:read → expect 200)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/groups?offset=0&count=1" -Headers $RD Write-Host " ✓ /groups readable, $(Describe-Response $r)" -ForegroundColor Green } | Out-Null Measure-Step "5. GET /applications (identity:read → expect 200)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/applications?offset=0&count=1" -Headers $RD Write-Host " ✓ /applications readable, $(Describe-Response $r)" -ForegroundColor Green } | Out-Null Measure-Step "6. GET /audit (identity:read → expect 200, ReadOnly covers /audit)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/audit?count=1" -Headers $RD Write-Host " ✓ /audit readable, $(Describe-Response $r)" -ForegroundColor Green } | Out-Null Measure-Step "7. POST /groups (identity:read → expect 403 insufficient_scope)" { Assert-Status -Label "create group on read-only" -Expect @(403) -Call { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/groups" -Headers $RD ` -ContentType "application/json" ` -Body (@{ name = "scope-probe-$([Guid]::NewGuid().ToString('N').Substring(0,6))"; groupType = "team" } | ConvertTo-Json) -ErrorAction Stop } | Out-Null } | Out-Null Measure-Step "8. POST /users (identity:read → expect 403 insufficient_scope)" { Assert-Status -Label "create user on read-only" -Expect @(403) -Call { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/users" -Headers $RD ` -ContentType "application/json" ` -Body (@{ login = "scope_probe_$([Guid]::NewGuid().ToString('N').Substring(0,6))"; email = "x@example.com"; password = "Test1234Pass!"; displayName = "x" } | ConvertTo-Json) -ErrorAction Stop } | Out-Null } | Out-Null # ── Axis 2: identity:audit:read (single-path granular) ─────────────────────── $auReg = Measure-Step "9. DCR (cc + identity:audit:read)" { $r = DcrCc "admin-scopes-audit" "identity:audit:read" if (-not $r.client_id) { throw "no client_id" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green return $r } $AUD_RAT = $auReg.registration_access_token $AUD_RCU = $auReg.registration_client_uri $auTok = Measure-Step "10. cc token (scope=identity:audit:read)" { $t = CcToken $auReg.client_id $auReg.client_secret "identity:audit:read" if (-not $t.access_token) { throw "no access_token" } Write-Host " ✓ access_token (len $($t.access_token.Length))" -ForegroundColor Green return $t } $AU = @{ Authorization = "Bearer $($auTok.access_token)" } Measure-Step "11. GET /audit (audit.read → expect 200)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/audit?count=5" -Headers $AU Write-Host " ✓ /audit readable on granular scope, $(Describe-Response $r)" -ForegroundColor Green } | Out-Null Measure-Step "12. GET /users (audit.read → expect 403 insufficient_scope)" { Assert-Status -Label "users on audit.read" -Expect @(403) -Call { Invoke-RestMethod -Method Get "$BASE/api/v1/identity/users?count=1" -Headers $AU -ErrorAction Stop } | Out-Null } | Out-Null Measure-Step "13. GET /applications (audit.read → expect 403)" { Assert-Status -Label "applications on audit.read" -Expect @(403) -Call { Invoke-RestMethod -Method Get "$BASE/api/v1/identity/applications?count=1" -Headers $AU -ErrorAction Stop } | Out-Null } | Out-Null Measure-Step "14. GET /audit?eventType=UserCreated (shape probe)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/audit?eventType=UserCreated&count=3" -Headers $AU # AuditQueryResponse → { total, offset, count, items[] }. Items may be empty if # nothing has happened recently, but the envelope itself must always carry # the pagination keys. $hasTotal = $r.PSObject.Properties['total'] -or $r.PSObject.Properties['Total'] $hasItems = $r.PSObject.Properties['items'] -or $r.PSObject.Properties['Items'] if (-not $hasTotal -or -not $hasItems) { throw "audit response shape: missing total/items. Got: $($r | ConvertTo-Json -Depth 3)" } Write-Host " ✓ filtered query well-shaped: $(Describe-Response $r)" -ForegroundColor Green } | Out-Null Measure-Step "15. GET /audit without bearer (expect 401)" { Assert-Status -Label "audit unauth" -Expect @(401) -Call { Invoke-RestMethod -Method Get "$BASE/api/v1/identity/audit?count=1" -ErrorAction Stop } | Out-Null } | Out-Null Measure-Step "16. GET /audit with garbage bearer (expect 401)" { Assert-Status -Label "audit garbage bearer" -Expect @(401) -Call { Invoke-RestMethod -Method Get "$BASE/api/v1/identity/audit?count=1" ` -Headers @{ Authorization = "Bearer NOT.A.JWT" } -ErrorAction Stop } | Out-Null } | Out-Null # ── Cleanup ── Measure-Step "17. RFC 7592 DELETE registrations" { if ($READ_RAT) { Invoke-RestMethod -Method Delete -Uri $READ_RCU -Headers @{ Authorization = "Bearer $READ_RAT" } | Out-Null } if ($AUD_RAT) { Invoke-RestMethod -Method Delete -Uri $AUD_RCU -Headers @{ Authorization = "Bearer $AUD_RAT" } | Out-Null } Write-Host " ✓ both DCR clients deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_application_allowed_groups.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_application_allowed_groups.ps1 ---- # β — per-application group whitelist (ApplicationProps.AllowedGroups). # # RFC-compliance probe for RestrictApplicationByGroupMembershipHandler. # When ApplicationProps.AllowedGroups is non-empty, only users who are a # member of at least one listed group may authenticate against that # application. Failures yield OAuth `access_denied`. # # Probes (all asserted): # 1. DCR a confidential ROPC client (grants password + refresh_token + openid) # 2. Seed a user with a known password (login = ropc_NNN, pwd = Test1234Pass!) # 3. Sanity: ROPC against the freshly created app (no whitelist) → 200 # 4. Admin: create group "beta-allowed-NNN" # 5. Admin: PUT the application with AllowedGroups = ["beta-allowed-NNN"] # 6. ROPC with the same user (still NOT in the group) → access_denied # 7. Admin: add the user to the group # 8. ROPC again → 200 (user is now allowed) # 9. Admin: PUT the application with AllowedGroups = [] (clear whitelist) # 10. ROPC again → 200 (no whitelist, default behaviour restored) # 11. Cleanup: delete application, group # # Usage: pwsh -File demo_application_allowed_groups.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function Get-Ropc { param($ClientId, $ClientSecret, $Username, $Password, $Scope) Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $ClientId client_secret = $ClientSecret username = $Username password = $Password scope = $Scope } } function Assert-RopcDenied { param($ClientId, $ClientSecret, $Username, $Password, $Scope, $Label) try { $body = Get-Ropc -ClientId $ClientId -ClientSecret $ClientSecret ` -Username $Username -Password $Password -Scope $Scope throw " ! ${Label}: expected access_denied, got token: $($body.access_token.Substring(0,16))…" } catch { $code = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -in 400, 401, 403) { $errBody = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } Write-Host " ✓ $Label → $code" -ForegroundColor Green if ($errBody) { Write-Host " body: $errBody" -ForegroundColor DarkGray } } else { throw } } } $total = [System.Diagnostics.Stopwatch]::StartNew() # --- 0) Admin DCR + token (granular scopes; master identity:manage is not # DCR-allowed by design — only granular sub-scopes are). The probe # touches users (register + group membership), groups, and # applications, so we ask for the union. $adminReg = Measure-Step "0a. admin DCR cc + users.manage + applications.manage" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "beta-allowed-groups-admin" grant_types = @("client_credentials") scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } | ConvertTo-Json) } $adminTok = Measure-Step "0b. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $adminReg.client_id client_secret = $adminReg.client_secret scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } # --- 1) Admin: create ROPC client directly (so we get the internal id back # immediately without paginating a 4 K+ application list to find a # freshly DCR'd one). $ropcSecret = "S-" + [Guid]::NewGuid().ToString("N") $ropcClientId = "beta-app-" + [Guid]::NewGuid().ToString("N").Substring(0,8) $ropcReg = Measure-Step "1. admin: POST /applications (confidential ROPC client)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/applications" -Headers $ADMIN ` -Body (@{ clientId = $ropcClientId clientSecret = $ropcSecret displayName = $ropcClientId clientType = "confidential" applicationType= "web" redirectUris = @($REDIRECT_CB) permissions = @( "ept:token", "ept:authorization", "gt:password", "gt:refresh_token", "scp:openid", "scp:offline_access" ) } | ConvertTo-Json) } $RopcClient = $ropcClientId $RopcSecret = $ropcSecret $AppId = "$($ropcReg.id)" Write-Host " ✓ app id = $AppId" -ForegroundColor Green # --- 2) Seed a user — account/register returns the internal userId directly. $user = "beta_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" $UserId = Measure-Step "2. account/register" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) if (-not $r.success -or -not $r.userId) { throw "register failed: $($r | ConvertTo-Json)" } Write-Host " ✓ user id = $($r.userId)" -ForegroundColor Green return [long]$r.userId } # --- 3) Sanity check — ROPC works before any whitelist --------------------- Measure-Step "3. ROPC happy path (no whitelist yet)" { $t = Get-Ropc -ClientId $RopcClient -ClientSecret $RopcSecret ` -Username $user -Password $pwd -Scope "openid" if (-not $t.access_token) { throw "no access_token" } Write-Host " ✓ access_token: $($t.access_token.Substring(0,16))…" -ForegroundColor Green } | Out-Null # --- 4) Create a group ------------------------------------------------------ $groupName = "beta-allowed-$([Guid]::NewGuid().ToString('N').Substring(0,8))" $group = Measure-Step "4. admin: POST /groups $groupName" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/groups" -Headers $ADMIN ` -Body (@{ name = $groupName; groupType = "team"; description = "beta probe" } | ConvertTo-Json) } $GroupId = [long]$group.id # --- 5) PUT application with AllowedGroups = [groupName] ------------------- Measure-Step "5. admin: PUT /applications/$AppId AllowedGroups=[$groupName]" { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/applications/$AppId" -Headers $ADMIN ` -Body (@{ id = "$AppId" allowedGroups = @($groupName) } | ConvertTo-Json) | Out-Null Write-Host " ✓ whitelist applied" -ForegroundColor Green } | Out-Null # --- 6) ROPC must now be DENIED (user not in group) ------------------------ Measure-Step "6. ROPC (user NOT in group) — expect access_denied" { Assert-RopcDenied -ClientId $RopcClient -ClientSecret $RopcSecret ` -Username $user -Password $pwd -Scope "openid" ` -Label "denied: not a group member" } | Out-Null # --- 7) Add user to group -------------------------------------------------- Measure-Step "7. admin: POST /groups/$GroupId/members (userId=$UserId)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/groups/$GroupId/members" -Headers $ADMIN ` -Body (@{ userId = $UserId; role = "member" } | ConvertTo-Json) | Out-Null Write-Host " ✓ membership created" -ForegroundColor Green } | Out-Null # --- 8) ROPC must succeed now --------------------------------------------- Measure-Step "8. ROPC (user IS in group) — expect 200" { $t = Get-Ropc -ClientId $RopcClient -ClientSecret $RopcSecret ` -Username $user -Password $pwd -Scope "openid" if (-not $t.access_token) { throw "no access_token after adding to group" } Write-Host " ✓ access_token after membership: $($t.access_token.Substring(0,16))…" -ForegroundColor Green } | Out-Null # --- 9) Clear whitelist ---------------------------------------------------- Measure-Step "9. admin: PUT /applications/$AppId AllowedGroups=[]" { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/applications/$AppId" -Headers $ADMIN ` -Body (@{ id = "$AppId" allowedGroups = @() } | ConvertTo-Json) | Out-Null Write-Host " ✓ whitelist cleared" -ForegroundColor Green } | Out-Null # --- 10) ROPC should still work (whitelist cleared) ----------------------- Measure-Step "10. ROPC (whitelist cleared) — expect 200" { $t = Get-Ropc -ClientId $RopcClient -ClientSecret $RopcSecret ` -Username $user -Password $pwd -Scope "openid" if (-not $t.access_token) { throw "no access_token after clearing whitelist" } Write-Host " ✓ access_token after clear: $($t.access_token.Substring(0,16))…" -ForegroundColor Green } | Out-Null # --- 11) Cleanup ---------------------------------------------------------- Measure-Step "11. admin: DELETE /applications/$AppId" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/applications/$AppId" -Headers $ADMIN | Out-Null } catch { Write-Host " (cleanup) application delete returned: $($_.Exception.Message)" -ForegroundColor DarkGray } } | Out-Null Measure-Step "11b. admin: DELETE /groups/$GroupId" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/groups/$GroupId" -Headers $ADMIN | Out-Null } catch { Write-Host " (cleanup) group delete returned: $($_.Exception.Message)" -ForegroundColor DarkGray } } | Out-Null $total.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Magenta Path: redb-identity/demos/demo_auth_extras.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_auth_extras.ps1 ---- # Auth-code response extras — locks 4 advertised but un-probed surfaces: # 1. RFC 9207 iss in auth-response (authorization_response_iss_parameter_supported: true) # 2. prompt=none on no session → error redirect with error=login_required (OIDC §3.1.2.1) # 3. response_mode=form_post → HTML auto-submit form with code (OIDC FAPI / form-post) # 4. response_mode=fragment → redirect with #code= (legacy implicit/hybrid carrier) # Builds on the same session+DCR setup as demo_authcode_pkce.ps1. # Usage: pwsh -File demo_auth_extras.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $REDIRECT = $REDIRECT_CB $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function ConvertTo-Base64Url([byte[]]$bytes) { [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+','-').Replace('/','_') } function New-Pkce { $verifierBytes = New-Object byte[] 32 [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($verifierBytes) $verifier = ConvertTo-Base64Url $verifierBytes $sha = [System.Security.Cryptography.SHA256]::Create() $challenge = ConvertTo-Base64Url ($sha.ComputeHash([Text.Encoding]::ASCII.GetBytes($verifier))) [pscustomobject]@{ verifier=$verifier; challenge=$challenge } } # Helper: call /connect/authorize, capture the raw response (status, Location header, body). function Invoke-Authorize { param( [Microsoft.PowerShell.Commands.WebRequestSession] $sess, [hashtable] $body ) try { return Invoke-WebRequest -Method Post "$BASE/connect/authorize" ` -WebSession $sess ` -ContentType "application/x-www-form-urlencoded" ` -Body $body -MaximumRedirection 0 -ErrorAction Stop } catch { if ($_.Exception.Response) { $r = $_.Exception.Response $loc = $null if ($r.Headers.Location) { $loc = $r.Headers.Location.ToString() } return [pscustomobject]@{ StatusCode = [int]$r.StatusCode Headers = @{ Location = $loc } Content = "" } } # PowerShell 7.4+ surfaces redirect-when-MaxRedirection-0 as RedirectException. return Invoke-WebRequest -Method Post "$BASE/connect/authorize" ` -WebSession $sess ` -ContentType "application/x-www-form-urlencoded" ` -Body $body -MaximumRedirection 0 -SkipHttpErrorCheck } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 0) DCR — register a confidential code+PKCE client. $reg = Measure-Step "0. DCR (authorization_code + PKCE)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "auth-extras-demo" redirect_uris = @($REDIRECT) grant_types = @("authorization_code","refresh_token") scope = "openid profile email offline_access" } | ConvertTo-Json) } Write-Host " client_id : $($reg.client_id)" # 1) Seed user + cookie session. $user = "ae_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "1. account/register + /login" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login=$user; email="$user@example.com"; password=$pwd; displayName=$user } | ConvertTo-Json) | Out-Null } | Out-Null $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession Measure-Step " /login (cookie jar)" { try { Invoke-WebRequest -Method Post "$BASE/login" ` -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ username=$user; password=$pwd } ` -MaximumRedirection 0 -ErrorAction Stop | Out-Null } catch { if ($_.Exception.Response.StatusCode.value__ -notin 200,302) { throw } } if ($session.Cookies.GetCookies("$BASE").Count -lt 1) { throw "no session cookie" } } | Out-Null # ─── Probe A: RFC 9207 iss in auth-response (response_mode=query, default) ──────── Measure-Step "A. RFC 9207 — iss=... in auth-response Location" { $pkce = New-Pkce $resp = Invoke-Authorize $session @{ response_type = "code" client_id = $reg.client_id redirect_uri = $REDIRECT scope = "openid" code_challenge = $pkce.challenge code_challenge_method = "S256" state = "rfc9207" nonce = [Guid]::NewGuid().ToString('N') } $loc = if ($resp.Headers.Location -is [string]) { $resp.Headers.Location } else { ($resp.Headers.Location | Select-Object -First 1).ToString() } if (-not $loc) { throw "no Location header" } if ($loc -notmatch '[?&]iss=([^&]+)') { throw "auth-response Location has no iss= parameter (RFC 9207 advertised but not emitted): $loc" } $issEnc = $Matches[1] $issDec = [Uri]::UnescapeDataString($issEnc) Write-Host " iss : $issDec" if ($issDec -notmatch '^https?://') { throw "iss is not an absolute URL: $issDec" } if ($loc -notmatch '[?&]code=') { throw "auth-response Location missing code=" } Write-Host " ✓ iss + code + state all present" -ForegroundColor Green } | Out-Null # ─── Probe B: prompt=none → must redirect with error if no decision possible ───── # OIDC §3.1.2.6: when prompt=none and the user can't be authenticated silently OR # consent is needed, server MUST return login_required / consent_required / interaction_required. # In our setup user IS logged in via session, so prompt=none should succeed silently. # To force the error, we use a FRESH session (no cookies) — server should redirect with error. Measure-Step "B. prompt=none with no session → error=login_required" { $pkce = New-Pkce $emptySession = New-Object Microsoft.PowerShell.Commands.WebRequestSession $resp = Invoke-Authorize $emptySession @{ response_type = "code" client_id = $reg.client_id redirect_uri = $REDIRECT scope = "openid" code_challenge = $pkce.challenge code_challenge_method = "S256" state = "promptnone" prompt = "none" } $loc = if ($resp.Headers.Location -is [string]) { $resp.Headers.Location } else { ($resp.Headers.Location | Select-Object -First 1).ToString() } Write-Host " status : $($resp.StatusCode)" Write-Host " location : $loc" if (-not $loc) { throw "expected error redirect, got no Location (status $($resp.StatusCode))" } if ($loc -notmatch '[?&#]error=([^&]+)') { throw "prompt=none with no session did NOT return error= (got: $loc) — server allowed silent auth without a user" } $err = [Uri]::UnescapeDataString($Matches[1]) $allowed = @('login_required','interaction_required','consent_required','account_selection_required') if ($allowed -notcontains $err) { throw "prompt=none returned unexpected error: $err (expected one of: $($allowed -join ', '))" } Write-Host " ✓ error = $err (RFC-compliant)" -ForegroundColor Green } | Out-Null # ─── Probe C: response_mode=form_post → HTML auto-submit with code ─────────────── Measure-Step "C. response_mode=form_post → HTML form-post body" { $pkce = New-Pkce $resp = Invoke-Authorize $session @{ response_type = "code" response_mode = "form_post" client_id = $reg.client_id redirect_uri = $REDIRECT scope = "openid" code_challenge = $pkce.challenge code_challenge_method = "S256" state = "formpost" nonce = [Guid]::NewGuid().ToString('N') } Write-Host " status : $($resp.StatusCode)" $body = if ($resp.Content) { $resp.Content } else { "" } if ($resp.StatusCode -ne 200) { throw "form_post should return 200 with HTML body, got $($resp.StatusCode)" } if ($body -notmatch '(?i)]*method=["'']?post["'']?') { throw "form_post body has no
: $($body.Substring(0, [Math]::Min(200, $body.Length)))…" } if ($body -notmatch '(?i)action=["'']?' + [regex]::Escape($REDIRECT)) { throw "form_post form action does not target redirect_uri ($REDIRECT)" } if ($body -notmatch '(?i)name=["'']?code["'']?') { throw "form_post body has no code field" } Write-Host " ✓ HTML form posts code to $REDIRECT" -ForegroundColor Green } | Out-Null # ─── Probe D: response_mode=fragment → redirect with #code= (not ?code=) ───────── Measure-Step "D. response_mode=fragment → Location with #code=" { $pkce = New-Pkce $resp = Invoke-Authorize $session @{ response_type = "code" response_mode = "fragment" client_id = $reg.client_id redirect_uri = $REDIRECT scope = "openid" code_challenge = $pkce.challenge code_challenge_method = "S256" state = "fragmode" nonce = [Guid]::NewGuid().ToString('N') } $loc = if ($resp.Headers.Location -is [string]) { $resp.Headers.Location } else { ($resp.Headers.Location | Select-Object -First 1).ToString() } if (-not $loc) { throw "no Location header" } Write-Host " location : $loc" $hashIdx = $loc.IndexOf('#') if ($hashIdx -lt 0) { throw "response_mode=fragment did NOT use # carrier — params on query instead: $loc" } $frag = $loc.Substring($hashIdx + 1) if ($frag -notmatch '(?:^|&)code=') { throw "fragment carrier has no code= : $frag" } Write-Host " ✓ code delivered in URL fragment" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_authcode_pkce.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_authcode_pkce.ps1 ---- # Authorization-code + PKCE flow without a browser. # POST /login (cookie jar) → POST /connect/authorize → token exchange. # Usage: pwsh -File demo_authcode_pkce.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $REDIRECT = $REDIRECT_CB $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function ConvertTo-Base64Url([byte[]]$bytes) { [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+','-').Replace('/','_') } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — authorization_code client with our redirect URI. $reg = Measure-Step "1. DCR (authorization_code + PKCE)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "pkce-demo" redirect_uris = @($REDIRECT) grant_types = @("authorization_code","refresh_token") scope = "openid profile email offline_access" } | ConvertTo-Json) } # 2) Seed the user. $user = "pkce_$([Guid]::NewGuid().ToString('N').Substring(0,8))" Measure-Step "2. account/register" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = "Test1234Pass!" displayName = $user } | ConvertTo-Json) } catch { Write-Host " (already exists or non-fatal: $($_.Exception.Message))" -ForegroundColor Yellow } } | Out-Null # 3) Generate PKCE pair. $pkce = Measure-Step "3. generate PKCE verifier+challenge (S256)" { $verifierBytes = New-Object byte[] 32 [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($verifierBytes) $verifier = ConvertTo-Base64Url $verifierBytes $sha = [System.Security.Cryptography.SHA256]::Create() $challengeBytes = $sha.ComputeHash([Text.Encoding]::ASCII.GetBytes($verifier)) $challenge = ConvertTo-Base64Url $challengeBytes [pscustomobject]@{ verifier=$verifier; challenge=$challenge } } Write-Host " verifier : $($pkce.verifier.Substring(0,16))…" Write-Host " challenge : $($pkce.challenge.Substring(0,16))…" # 4) Establish a cookie session via /login. $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession Measure-Step "4. POST /login (cookie jar)" { try { Invoke-WebRequest -Method Post "$BASE/login" ` -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ username = $user; password = "Test1234Pass!" } ` -MaximumRedirection 0 -ErrorAction Stop | Out-Null } catch { # 302 redirect on success counts as an exception with -MaximumRedirection 0; that's expected. if ($_.Exception.Response.StatusCode.value__ -notin 200,302) { throw } } if ($session.Cookies.GetCookies("$BASE").Count -lt 1) { throw "no session cookie was set by /login" } } | Out-Null # 5) Drive /connect/authorize with the PKCE challenge. $code = Measure-Step "5. POST /connect/authorize → extract code" { $resp = $null try { $resp = Invoke-WebRequest -Method Post "$BASE/connect/authorize" ` -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ response_type = "code" client_id = $reg.client_id redirect_uri = $REDIRECT scope = "openid profile email offline_access" code_challenge = $pkce.challenge code_challenge_method = "S256" state = "pkce-demo-state" nonce = [Guid]::NewGuid().ToString('N') } -MaximumRedirection 0 -ErrorAction Stop } catch { $resp = $_.Exception.Response } $location = if ($resp -is [System.Net.Http.HttpResponseMessage]) { $resp.Headers.Location.ToString() } else { $resp.Headers["Location"] } if (-not $location) { throw "no Location header on /connect/authorize response" } $u = [uri]$location $q = $u.Query.TrimStart('?') $kv = @{} foreach ($pair in $q.Split('&')) { $i = $pair.IndexOf('=') if ($i -gt 0) { $kv[$pair.Substring(0,$i)] = [uri]::UnescapeDataString($pair.Substring($i+1)) } } if (-not $kv.code) { throw "authorize did not return a code (got: $location)" } Write-Host " redirect : $location" $kv.code } # 6) Exchange code+verifier for tokens. $tok = Measure-Step "6. POST /connect/token (grant=authorization_code)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "authorization_code" client_id = $reg.client_id client_secret = $reg.client_secret redirect_uri = $REDIRECT code = $code code_verifier = $pkce.verifier } } $tok | Format-List access_token, id_token, refresh_token, expires_in $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_authz_negative_matrix.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_authz_negative_matrix.ps1 ---- # Conformance probe — /connect/authorize error matrix (RFC 6749 §4.1.2.1, OIDC Core §3.1.2.6). # Request validation happens BEFORE end-user authentication, so these run without a login session. # # STRICT: every assertion encodes the spec requirement. A failing step = a real server deviation # to FIX (in the server), never a demo to soften. Two delivery contracts per RFC 6749 §4.1.2.1: # • VALID client + VALID redirect_uri, other error (scope/response_type/missing response_type) # → error MUST be delivered to the redirect_uri as a query parameter (error=...). # • MISSING/UNKNOWN client_id, or UNREGISTERED/MISSING redirect_uri # → server MUST NOT redirect to the supplied URI; error is returned directly (no 302). # Usage: pwsh -File demo_authz_negative_matrix.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $REDIRECT = $REDIRECT_CB $GOOD_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" # valid 43-char base64url S256 challenge $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host ""; Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $r = & $Action; $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }); return $r } catch { $sw.Stop(); Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }); throw } } # Probe /authorize with a raw HttpClient (AllowAutoRedirect=false) so a 302 is observed directly. # Returns status, redirect Location, redirect-delivered error, body-delivered error, redirect host. function Probe-Authorize([hashtable]$Params) { $handler = [System.Net.Http.HttpClientHandler]::new(); $handler.AllowAutoRedirect = $false # Raw HttpClient does not honour $PSDefaultParameterValues SkipCertificateCheck — accept the # dev/self-signed TLS cert explicitly so an https base works out of the box. $handler.ServerCertificateCustomValidationCallback = [System.Net.Http.HttpClientHandler]::DangerousAcceptAnyServerCertificateValidator $client = [System.Net.Http.HttpClient]::new($handler) try { $dict = [System.Collections.Generic.Dictionary[string,string]]::new() foreach ($k in $Params.Keys) { $dict[$k] = [string]$Params[$k] } $content = [System.Net.Http.FormUrlEncodedContent]::new($dict) $resp = $client.PostAsync("$BASE/connect/authorize", $content).GetAwaiter().GetResult() $status = [int]$resp.StatusCode $loc = if ($resp.Headers.Location) { $resp.Headers.Location.ToString() } else { $null } $respBody = $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() $redirectErr = $null; $errHost = $null if ($loc) { $u = [uri]$loc; $errHost = $u.Host foreach ($pair in $u.Query.TrimStart('?').Split('&')) { $i=$pair.IndexOf('='); if ($i -gt 0 -and $pair.Substring(0,$i) -eq 'error') { $redirectErr = [uri]::UnescapeDataString($pair.Substring($i+1)) } } } $bodyErr = $null if ($respBody -and $respBody.TrimStart().StartsWith('{')) { try { $bodyErr = ($respBody | ConvertFrom-Json).error } catch {} } $isRedirect = ($status -ge 300 -and $status -lt 400 -and $loc) [pscustomobject]@{ status=$status; location=$loc; isRedirect=$isRedirect; redirectError=$redirectErr; bodyError=$bodyErr; redirectHost=$errHost } } finally { $client.Dispose() } } $total = [System.Diagnostics.Stopwatch]::StartNew() $reg = Measure-Step "0. DCR valid client (redirect_uri=$REDIRECT)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" -Body (@{ client_name="authz-neg"; redirect_uris=@($REDIRECT) grant_types=@("authorization_code","refresh_token"); scope="openid profile" } | ConvertTo-Json) } $CID = $reg.client_id # ── Group 1: valid client + valid redirect → error MUST be delivered via the redirect_uri ── Measure-Step "1. unsupported response_type=token → error via redirect_uri" { $r = Probe-Authorize @{ response_type="token"; client_id=$CID; redirect_uri=$REDIRECT; scope="openid" } if (-not $r.isRedirect -or $r.redirectHost -ne 'localhost') { throw "expected redirect back to localhost:9999; status=$($r.status) loc=$($r.location)" } if ($r.redirectError -notin @('unsupported_response_type','unauthorized_client')) { throw "want unsupported_response_type via redirect, got '$($r.redirectError)'" } Write-Host " ✓ error='$($r.redirectError)' delivered via redirect_uri" -ForegroundColor Green } | Out-Null Measure-Step "2. missing response_type → invalid_request via redirect_uri" { $r = Probe-Authorize @{ client_id=$CID; redirect_uri=$REDIRECT; scope="openid" } if (-not $r.isRedirect -or $r.redirectHost -ne 'localhost') { throw "expected redirect back to localhost; status=$($r.status) loc=$($r.location)" } if ($r.redirectError -ne 'invalid_request') { throw "want invalid_request via redirect, got '$($r.redirectError)'" } Write-Host " ✓ error='invalid_request' delivered via redirect_uri" -ForegroundColor Green } | Out-Null Measure-Step "3. unknown scope → error=invalid_scope MUST be delivered via redirect_uri (RFC 6749 §4.1.2.1)" { $r = Probe-Authorize @{ response_type="code"; client_id=$CID; redirect_uri=$REDIRECT; scope="openid totally_unknown_scope_xyz"; code_challenge=$GOOD_CHALLENGE; code_challenge_method="S256" } if (-not $r.isRedirect) { throw "invalid_scope returned directly (status=$($r.status), body error='$($r.bodyError)') — RFC 6749 §4.1.2.1 requires delivery via the redirect_uri" } if ($r.redirectHost -ne 'localhost') { throw "expected redirect back to localhost; loc=$($r.location)" } if ($r.redirectError -ne 'invalid_scope') { throw "want invalid_scope via redirect, got '$($r.redirectError)'" } Write-Host " ✓ error='invalid_scope' delivered via redirect_uri" -ForegroundColor Green } | Out-Null # ── Group 2: untrusted target → server MUST NOT redirect to it ────────────────────────────── Measure-Step "4. valid client + UNREGISTERED redirect_uri (complete req) → NO redirect, direct invalid_request" { $evil = "http://evil.attacker.example/cb" $r = Probe-Authorize @{ response_type="code"; client_id=$CID; redirect_uri=$evil; scope="openid"; code_challenge=$GOOD_CHALLENGE; code_challenge_method="S256"; state="s" } if ($r.redirectHost -eq 'evil.attacker.example') { throw "OPEN REDIRECT: error redirected to unregistered redirect_uri '$evil' (loc=$($r.location))" } if ($r.bodyError -ne 'invalid_request') { throw "want direct invalid_request for unregistered redirect_uri, got error='$($r.bodyError)' status=$($r.status)" } Write-Host " ✓ unregistered redirect_uri → direct invalid_request, no redirect (status=$($r.status))" -ForegroundColor Green } | Out-Null Measure-Step "5. unknown client_id → server MUST NOT redirect" { $r = Probe-Authorize @{ response_type="code"; client_id=[Guid]::NewGuid().ToString(); redirect_uri=$REDIRECT; scope="openid"; code_challenge=$GOOD_CHALLENGE; code_challenge_method="S256" } if ($r.isRedirect) { throw "OPEN REDIRECT: error redirected for an unknown client (loc=$($r.location))" } Write-Host " ✓ unknown client → no redirect (status=$($r.status))" -ForegroundColor Green } | Out-Null Measure-Step "6. missing client_id → server MUST NOT redirect (RFC 6749 §4.1.2.1)" { $r = Probe-Authorize @{ response_type="code"; redirect_uri=$REDIRECT; scope="openid"; code_challenge=$GOOD_CHALLENGE; code_challenge_method="S256" } if ($r.isRedirect) { throw "OPEN REDIRECT: error redirected to redirect_uri without a validated client_id (loc=$($r.location))" } Write-Host " ✓ missing client_id → no redirect (status=$($r.status))" -ForegroundColor Green } | Out-Null Measure-Step "7. missing code_challenge + UNREGISTERED redirect_uri → MUST NOT redirect to it" { $evil = "http://evil.attacker.example/cb" $r = Probe-Authorize @{ response_type="code"; client_id=$CID; redirect_uri=$evil; scope="openid"; state="s" } # no code_challenge if ($r.redirectHost -eq 'evil.attacker.example') { throw "OPEN REDIRECT: PKCE error redirected to unregistered redirect_uri '$evil' (loc=$($r.location))" } Write-Host " ✓ no redirect to unregistered URI even with missing code_challenge (status=$($r.status))" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host ""; Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_backchannel_logout.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_backchannel_logout.ps1 ---- # OIDC Back-Channel Logout 1.0 — end-to-end probe, the way a browser does it. # 1. DCR a public (PKCE) client with `backchannel_logout_uri` (RFC 7591 + OIDC Back-Channel # Logout 1.0 §2.2) pointing at a local HttpListener, backchannel_logout_session_required=true. # 2. Register a user and sign in at the OP through /login with a cookie jar — that is the OP session. # 3. authorization_code + PKCE through that session → id_token; note its `sub` and `sid`. # 4. Start the HttpListener; RP-initiated logout: POST /connect/logout with the session cookie and # `id_token_hint` (RP-Initiated Logout 1.0 §2). # 5. The OP POSTs a logout_token to the RP (§2.4): form-urlencoded, a JWT whose `events` claim names # the back-channel logout event, whose `sub` equals the id_token's `sub` and whose `sid` equals # the id_token's `sid` — the RP ends exactly the session that ended at the OP. # The endpoint acts on the browser's own session only: a request without the cookie ends nothing, # whatever it says about the user, so there is no "userId" to send here. # Usage: pwsh -File demo_backchannel_logout.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $LSN_PORT = 9876 $LSN_URL = "http://127.0.0.1:$LSN_PORT/bclogout/" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function Decode-JwtPayload([string]$jwt) { $parts = $jwt -split '\.' if ($parts.Count -lt 2) { return $null } $b64 = $parts[1].Replace('-', '+').Replace('_', '/') switch ($b64.Length % 4) { 2 { $b64 += '==' } 3 { $b64 += '=' } } $json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64)) return ($json | ConvertFrom-Json) } function ConvertTo-Base64Url([byte[]]$bytes) { [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+','-').Replace('/','_') } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — public authorization_code client (PKCE) with backchannel_logout_uri. $reg = Measure-Step "1. DCR /connect/register (authorization_code + PKCE, backchannel_logout_uri)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "bclogout-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("authorization_code") response_types = @("code") token_endpoint_auth_method = "none" scope = "openid profile email" backchannel_logout_uri = $LSN_URL backchannel_logout_session_required = $true } | ConvertTo-Json) } $reg | Format-List client_id, backchannel_logout_uri # 2) Register a user. $user = "bcl_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login=$user; email="$user@example.com"; password=$pwd; displayName=$user } | ConvertTo-Json) } | Out-Null # 3) Sign in at the OP: the cookie jar is the browser, the cookie is the OP session. $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession Measure-Step "3. POST /login (cookie jar = the OP session)" { try { Invoke-WebRequest -Method Post "$BASE/login" ` -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ username = $user; password = $pwd } ` -MaximumRedirection 0 -ErrorAction Stop | Out-Null } catch { # 302 on success surfaces as an exception with -MaximumRedirection 0; that is expected. if ($_.Exception.Response.StatusCode.value__ -notin 200,302) { throw } } if ($session.Cookies.GetCookies("$BASE").Count -lt 1) { throw "no session cookie was set by /login" } } | Out-Null # 4) authorization_code + PKCE through that session. $pkce = Measure-Step "4. generate PKCE verifier+challenge (S256)" { $verifierBytes = New-Object byte[] 32 [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($verifierBytes) $verifier = ConvertTo-Base64Url $verifierBytes $sha = [System.Security.Cryptography.SHA256]::Create() $challenge = ConvertTo-Base64Url ($sha.ComputeHash([Text.Encoding]::ASCII.GetBytes($verifier))) [pscustomobject]@{ verifier=$verifier; challenge=$challenge } } $authCode = Measure-Step "5. POST /connect/authorize (session cookie) → code" { $resp = $null try { $resp = Invoke-WebRequest -Method Post "$BASE/connect/authorize" ` -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ response_type = "code" client_id = $reg.client_id redirect_uri = $REDIRECT_CB scope = "openid profile email" code_challenge = $pkce.challenge code_challenge_method = "S256" state = "bclogout-demo-state" nonce = [Guid]::NewGuid().ToString('N') } -MaximumRedirection 0 -ErrorAction Stop } catch { $resp = $_.Exception.Response } $location = if ($resp -is [System.Net.Http.HttpResponseMessage]) { $resp.Headers.Location.ToString() } else { $resp.Headers["Location"] } if (-not $location) { throw "no Location header on /connect/authorize response" } $q = ([uri]$location).Query.TrimStart('?') $kv = @{} foreach ($pair in $q.Split('&')) { $i = $pair.IndexOf('=') if ($i -gt 0) { $kv[$pair.Substring(0,$i)] = [uri]::UnescapeDataString($pair.Substring($i+1)) } } if (-not $kv.code) { throw "authorize did not return a code (got: $location)" } $kv.code } $tok = Measure-Step "6. POST /connect/token (authorization_code + PKCE) → id_token" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "authorization_code" client_id = $reg.client_id code = $authCode redirect_uri = $REDIRECT_CB code_verifier = $pkce.verifier } } if (-not $tok.id_token) { throw "no id_token issued — cannot drive RP-initiated logout" } $idClaims = Decode-JwtPayload $tok.id_token Write-Host " id_token sub : $($idClaims.sub)" Write-Host " id_token sid : $($idClaims.sid)" if (-not $idClaims.sid) { throw "id_token carries no sid — the OP session is unnamed and back-channel logout cannot target it" } # 7) Start HttpListener in a runspace; capture the inbound logout_token POST. $listenerJob = Measure-Step "7. start HttpListener on $LSN_URL" { $rs = [runspacefactory]::CreateRunspace() $rs.Open() $ps = [powershell]::Create() $ps.Runspace = $rs [void]$ps.AddScript({ param($prefix) $l = [System.Net.HttpListener]::new() $l.Prefixes.Add($prefix) $l.Start() try { # 10s budget for the dispatcher to deliver. $ar = $l.BeginGetContext($null, $null) if (-not $ar.AsyncWaitHandle.WaitOne(10000)) { return @{ captured=$false; reason="timeout waiting for inbound POST" } } $ctx = $l.EndGetContext($ar) $req = $ctx.Request $reader = [IO.StreamReader]::new($req.InputStream, $req.ContentEncoding) $body = $reader.ReadToEnd() $ctx.Response.StatusCode = 200 $ctx.Response.OutputStream.Close() return @{ captured = $true method = $req.HttpMethod contentType = $req.ContentType body = $body } } finally { $l.Stop(); $l.Close() } }).AddArgument($LSN_URL) $handle = $ps.BeginInvoke() [pscustomobject]@{ ps=$ps; handle=$handle; rs=$rs } } # Tiny wait to ensure the listener is bound before we POST. Start-Sleep -Milliseconds 300 # 8) RP-initiated logout: the browser (cookie jar) is sent to end_session_endpoint with id_token_hint. # Note: the response body is the "Signed Out" page (or a redirect), so the JSON shape of the underlying # LogoutProcessor is not visible here. The proof of fan-out is the captured POST on our HttpListener. Measure-Step "8. POST /connect/logout (session cookie + id_token_hint) — RP-initiated" { $status = 0 try { $wr = Invoke-WebRequest -Method Post "$BASE/connect/logout" ` -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ id_token_hint = $tok.id_token client_id = $reg.client_id } -MaximumRedirection 0 -ErrorAction Stop $status = $wr.StatusCode } catch { $status = $_.Exception.Response.StatusCode.value__ } Write-Host " status: $status" if ($status -lt 200 -or $status -ge 400) { throw "Unexpected logout status: $status" } } | Out-Null # 9) Drain the listener. $capture = Measure-Step "9. drain HttpListener (await captured POST)" { $r = $listenerJob.ps.EndInvoke($listenerJob.handle) $listenerJob.ps.Dispose(); $listenerJob.rs.Close() return $r[0] } if (-not $capture.captured) { throw "Listener did not capture a POST: $($capture.reason)" } Write-Host " method : $($capture.method)" Write-Host " contentType : $($capture.contentType)" if ($capture.method -ne 'POST') { throw "Expected POST, got $($capture.method)" } if ($capture.contentType -notmatch 'application/x-www-form-urlencoded') { throw "Expected application/x-www-form-urlencoded, got '$($capture.contentType)'" } if ($capture.body -notmatch 'logout_token=') { throw "POST body has no logout_token field: $($capture.body)" } Write-Host " ✓ POST captured with form-urlencoded logout_token" -ForegroundColor Green # 10) Decode logout_token JWT and verify the OIDC Back-Channel Logout 1.0 §2.4 claims. $jwt = ($capture.body -split 'logout_token=')[1] -split '&' | Select-Object -First 1 $jwt = [Uri]::UnescapeDataString($jwt) $payload = Decode-JwtPayload $jwt if (-not $payload) { throw "Could not decode logout_token JWT payload" } $payloadJson = $payload | ConvertTo-Json -Depth 5 Write-Host " payload :" Write-Host $payloadJson $eventsClaim = $payload.events $hasBcLogoutEvent = $false if ($eventsClaim) { $eventsClaim.PSObject.Properties | ForEach-Object { if ($_.Name -eq 'http://schemas.openid.net/event/backchannel-logout') { $hasBcLogoutEvent = $true } } } if (-not $hasBcLogoutEvent) { throw "logout_token missing required 'events' claim with http://schemas.openid.net/event/backchannel-logout" } Write-Host " ✓ events claim contains backchannel-logout event" -ForegroundColor Green if (-not $payload.sub) { throw "logout_token missing required 'sub' claim" } if ($payload.sub -ne $idClaims.sub) { throw "logout_token sub '$($payload.sub)' differs from the id_token sub '$($idClaims.sub)' — the RP cannot match the user" } Write-Host " ✓ sub equals the id_token sub: $($payload.sub)" -ForegroundColor Green if (-not $payload.sid) { throw "logout_token missing 'sid' although backchannel_logout_session_required=true" } if ($payload.sid -ne $idClaims.sid) { throw "logout_token sid '$($payload.sid)' differs from the id_token sid '$($idClaims.sid)' — the RP would end the wrong session" } Write-Host " ✓ sid equals the id_token sid: $($payload.sid) (the session that ended)" -ForegroundColor Green if ($payload.aud -ne $reg.client_id) { throw "logout_token aud '$($payload.aud)' is not the RP's client_id" } Write-Host " ✓ aud is the RP's client_id" -ForegroundColor Green if (-not $payload.iss) { Write-Host " ! 'iss' claim missing (RFC requires)" -ForegroundColor Yellow } if (-not $payload.iat) { Write-Host " ! 'iat' claim missing (RFC requires)" -ForegroundColor Yellow } if (-not $payload.jti) { Write-Host " ! 'jti' claim missing (RFC requires)" -ForegroundColor Yellow } $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_bootstrap_admin_role.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_bootstrap_admin_role.ps1 ---- #requires -Version 7 # Bootstrap admin ⇄ admin role wiring assertion. # # Pinned by the architectural fix in commit 12b2fcaf — the B1 bootstrap # previously put the admin user only in the "admins" group (carrying # scope identity:admin) but NOT in the B.3 "admin" role. Role-centric # UI surfaces (/admin/roles/{adminRoleId} Users tab) misleadingly # rendered empty. Fix is two-track: BootstrapAdminProcessor mirrors # the new user into the admin role at create-time, and # BootstrapAdminBackfillListener walks every startup to catch old # installs where the role had no assignee. # # This demo: # 1. Admin DCR (cc + identity:users:write identity:groups:write identity:consents:write identity:mfa:write + identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write) # 2. Admin cc token # 3. GET /roles?name=admin → resolve admin role id # 4. GET /roles/{adminRoleId}/users → ASSERT contains at least one # user (the bootstrap admin) and their login is non-empty # (regression on commit 32f089ae's per-id lookup fix). # 5. RFC 7592 cleanup. # # A green run means: (a) seeded admin role exists, (b) bootstrap or # the backfill listener wired at least one user into it, (c) server- # side assignee enumeration resolves the login correctly at any # user-count. # # Usage: pwsh -File demo_bootstrap_admin_role.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host "--- [$Name] $('{0:N0}' -f $sw.Elapsed.TotalMilliseconds) ms" -ForegroundColor DarkGray $timings.Add([pscustomobject]@{ Step = $Name; Ms = [Math]::Round($sw.Elapsed.TotalMilliseconds, 0); Status = "ok" }) return $result } catch { $sw.Stop() $timings.Add([pscustomobject]@{ Step = $Name; Ms = [Math]::Round($sw.Elapsed.TotalMilliseconds, 0); Status = "FAIL" }) Write-Host "!!! [$Name] FAIL: $_" -ForegroundColor Red throw } } # 1. DCR $adminReg = Measure-Step "1. admin DCR" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType 'application/json' ` -Body (@{ client_name = "bootstrap-admin-role-probe"; grant_types = @("client_credentials"); scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } | ConvertTo-Json) } # 2. cc token $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType 'application/x-www-form-urlencoded' ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } } $H = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } # 3. Resolve admin role id (name=admin, audience=organization). The system # role was seeded by SeedSystemRolesListener on first startup. $adminRoleId = Measure-Step "3. GET /roles?name=admin" { $list = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/roles?name=admin" -Headers $H $admin = $list.items | Where-Object { $_.name -eq "admin" -and $_.audience -eq "organization" } | Select-Object -First 1 if (-not $admin) { throw "system admin role not seeded — SeedSystemRolesListener didn't run?" } Write-Host " admin role id = $($admin.id)" -ForegroundColor Gray return [long]$admin.id } # 4. List assignees. After the fix, the bootstrap admin user must be in # the list AND their login must resolve correctly (per-id lookup from # commit 32f089ae). $adminUserLogin = Measure-Step "4. GET /roles/$adminRoleId/assignees (assert non-empty + logins resolved)" { $users = @(Invoke-RestMethod -Method Get "$BASE/api/v1/identity/roles/$adminRoleId/assignees" -Headers $H) if ($users.Count -lt 1) { throw "admin role has no assignees — BootstrapAdminBackfillListener didn't run, or no admin user is in 'admins' group" } Write-Host " admin role assignees: $($users.Count)" -ForegroundColor Gray foreach ($u in $users) { if (-not $u.subjectLabel) { throw "assignee $($u.subjectId) has no subjectLabel — RoleManagementProcessor.ListAssignees regression on commit 32f089ae" } Write-Host " - $($u.subjectId) → $($u.subjectLabel)" -ForegroundColor Gray } # Sanity: the FIRST assignee is a real user, not the never-assigned # sentinel id 0. On the SQL-seeded canonical admin the user id is 1 — # treat anything > 0 as legitimate. The role MUST contain the seed # admin (login matches RedbIdentityOptions.SeedAdmin.Login). if ($users[0].subjectId -le 0) { throw "first assignee user_id=$($users[0].subjectId) is not a real user" } if (-not ($users.subjectLabel -contains "admin")) { throw "expected the seed admin user (login=admin) to be one of the assignees; got: $($users.subjectLabel -join ', ')" } return $users[0].subjectLabel } # 5. RFC 7592 cleanup. Measure-Step "5. RFC 7592 DELETE registration" { try { Invoke-RestMethod -Method Delete "$BASE/connect/register/$($adminReg.client_id)" ` -Headers @{ Authorization = "Bearer $($adminReg.registration_access_token)" } | Out-Null } catch {} } | Out-Null # Summary Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Green $timings | Format-Table -AutoSize $total = ($timings | Measure-Object -Property Ms -Sum).Sum Write-Host ("Total: {0:N0} ms" -f $total) Write-Host "" Write-Host "Verified: bootstrap admin user '$adminUserLogin' is a member of the admin role." -ForegroundColor Green Path: redb-identity/demos/demo_claim_definitions.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_claim_definitions.ps1 ---- # S2 — claim definitions probe. # # Verifies the full lifecycle: # 1. Admin DCR cc + identity:users:write identity:groups:write identity:consents:write identity:mfa:write + identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write # 2. Admin cc token # 3. POST /claim-definitions — create global "department" (required, no default) # 4. POST /claim-definitions — create global "tier" (optional, default = "bronze") # 5. POST /claim-definitions — create global "score" (int, regex via pattern) # 6. GET /claim-definitions — list, expect 3 rows # 7. Try to create a user WITHOUT custom claims → fail (required department missing) # 8. Create a user WITH department=engineering → succeeds; verify tier was auto-filled to "bronze" # 9. PUT /users/{id} with customClaims = { department: "" } → fail (required) # 10. PUT /users/{id} with customClaims = { score: "not-a-number" } → fail (type) # 11. PUT /users/{id} with customClaims = { score: "42" } → succeeds # 12. Cleanup: delete user + 3 definitions # # Usage: pwsh -File demo_claim_definitions.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function Assert-Rejected { param([scriptblock]$Action, [string]$Label) try { & $Action | Out-Null throw " ! ${Label}: expected validation_error, got success" } catch { $code = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -in 400, 422) { Write-Host " ✓ $Label → $code" -ForegroundColor Green } else { throw } } } $total = [System.Diagnostics.Stopwatch]::StartNew() $adminReg = Measure-Step "1. admin DCR cc + users.manage + applications.manage" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "claim-defs-admin"; grant_types = @("client_credentials"); scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } # Cleanup leftover definitions from prior runs so they don't accumulate + # don't block subsequent user creates / registrations with their required flags. try { $oldDefs = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/claim-definitions?count=200" -Headers $ADMIN foreach ($d in $oldDefs.items) { if ($d.claimName -match '^(department|tier|score)-') { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/claim-definitions/$($d.id)" -Headers $ADMIN | Out-Null } catch {} } } } catch {} # Use unique claim names so reruns don't collide with leftover definitions. $suffix = [Guid]::NewGuid().ToString("N").Substring(0,6) $claimDept = "department-$suffix" $claimTier = "tier-$suffix" $claimScore = "score-$suffix" $dept = Measure-Step "3. POST /claim-definitions ($claimDept, required, no default)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/claim-definitions" -Headers $ADMIN ` -Body (@{ claimName = $claimDept type = "string" required = $true scope = "global" } | ConvertTo-Json) } $tier = Measure-Step "4. POST /claim-definitions ($claimTier, optional, default=bronze)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/claim-definitions" -Headers $ADMIN ` -Body (@{ claimName = $claimTier type = "string" required = $true defaultValue = "bronze" scope = "global" } | ConvertTo-Json) } $score = Measure-Step "5. POST /claim-definitions ($claimScore, type=int)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/claim-definitions" -Headers $ADMIN ` -Body (@{ claimName = $claimScore type = "int" required = $false scope = "global" } | ConvertTo-Json) } Measure-Step "6. GET /claim-definitions — list" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/claim-definitions?count=200" -Headers $ADMIN Write-Host " ✓ total = $($r.total)" -ForegroundColor Green $names = $r.items | ForEach-Object { $_.claimName } foreach ($n in @($claimDept, $claimTier, $claimScore)) { if ($names -notcontains $n) { throw "definition '$n' not in list" } } Write-Host " ✓ all 3 definitions present" -ForegroundColor Green } | Out-Null # Cleanup any leftover from earlier runs sharing this suffix (paranoia). $user = "cdefs_$suffix" try { $existing = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/users/search?query=$user&count=10" -Headers $ADMIN foreach ($u in $existing.items) { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$($u.id)" -Headers $ADMIN | Out-Null } catch {} } } catch {} # 7. Try to create user without satisfying required claim — should fail. Measure-Step "7. account/register without 'department' — expect 400" { # Note: account/register doesn't carry customClaims at all; required claim # without default → fail (we'd auto-fill from default but department has none). Assert-Rejected -Action { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@x.com"; password = "Test1234Pass!"; displayName = $user } | ConvertTo-Json) } -Label "register without required department" } | Out-Null # 8. Admin create with required + default — customClaims in body satisfies department. $UserId = Measure-Step "8. admin POST /users with customClaims department=engineering" { $body = @{ login = $user password = "Test1234Pass!" displayName = $user customClaims = @{ $claimDept = "engineering" } } | ConvertTo-Json $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/users" -Headers $ADMIN -Body $body if (-not $r.id) { throw "no id" } Write-Host " ✓ user id = $($r.id)" -ForegroundColor Green # Verify tier was auto-defaulted (since it's required with default=bronze). $u = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/users/$($r.id)" -Headers $ADMIN if ($u.customClaims.$claimTier -ne "bronze") { throw "tier was not auto-defaulted: got '$($u.customClaims.$claimTier)'" } Write-Host " ✓ tier auto-defaulted to 'bronze'" -ForegroundColor Green return [long]$r.id } # 9. Try to clear the required department — should fail. Measure-Step "9. PUT /users/$UserId clearing $claimDept — expect 400" { Assert-Rejected -Action { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/users/$UserId" -Headers $ADMIN ` -Body (@{ id = $UserId customClaims = @{ $claimDept = "" } } | ConvertTo-Json) } -Label "clearing required claim" } | Out-Null # 10. Type validation: int field with non-numeric value. Measure-Step "10. PUT /users/$UserId score='not-a-number' — expect 400" { Assert-Rejected -Action { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/users/$UserId" -Headers $ADMIN ` -Body (@{ id = $UserId customClaims = @{ $claimScore = "not-a-number" } } | ConvertTo-Json) } -Label "int parse failure" } | Out-Null # 11. Valid update. Measure-Step "11. PUT /users/$UserId score='42' — expect 200" { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/users/$UserId" -Headers $ADMIN ` -Body (@{ id = $UserId customClaims = @{ $claimScore = "42" } } | ConvertTo-Json) | Out-Null Write-Host " ✓ score=42 saved" -ForegroundColor Green } | Out-Null # Cleanup Measure-Step "12. cleanup" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$UserId" -Headers $ADMIN | Out-Null } catch {} foreach ($d in @($dept, $tier, $score)) { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/claim-definitions/$($d.id)" -Headers $ADMIN | Out-Null } catch {} } Write-Host " ✓ user + 3 definitions removed" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Magenta Path: redb-identity/demos/demo_claim_definitions_per_app.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_claim_definitions_per_app.ps1 ---- # S2.4 — per-app required + per-definition destinations probe. # # Verifies: # 1. Admin DCR cc + identity:users:write identity:groups:write identity:consents:write identity:mfa:write + identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write # 2. Create user U1 (no custom claims) # 3. Create application A1 via DCR # 4. Create a per-app required-no-default claim definition for A1 # 5. ROPC for U1 → A1 → 400 (required claim missing, no default) # 6. Add DefaultValue to the definition (PATCH) # 7. ROPC for U1 → A1 → 200; decode access_token + id_token, verify the # defaulted claim is on BOTH tokens by default # 8. Update definition: EmitOnIdToken=false, EmitOnAccessToken=true # 9. ROPC again, verify the claim is ONLY on access_token # 10. cleanup # #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host ""; Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $r = & $Action; $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $r } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED: {0}" -f $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function Decode-Jwt([string]$Token) { if ([string]::IsNullOrEmpty($Token)) { return $null } $parts = $Token.Split('.') # Plain JWS = 3 parts (header.payload.signature); JWE = 5 parts. We can only # decode payload from JWS — return null for JWE (caller should use a # different verification path: /userinfo or introspection). if ($parts.Length -ne 3) { return $null } try { $payload = $parts[1].Replace('-', '+').Replace('_', '/') switch ($payload.Length % 4) { 2 { $payload += '==' } 3 { $payload += '=' } } $json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) return $json | ConvertFrom-Json } catch { return $null } } $totalSw = [System.Diagnostics.Stopwatch]::StartNew() $adminReg = Measure-Step "1. admin DCR" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "perapp-claims-admin"; grant_types = @("client_credentials"); scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } # Cleanup leftover definitions (don't carry tier-* etc. across runs). try { $oldDefs = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/claim-definitions?count=200" -Headers $ADMIN foreach ($d in $oldDefs.items) { if ($d.claimName -match '^(perapp_tier|perapp_dept)') { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/claim-definitions/$($d.id)" -Headers $ADMIN | Out-Null } catch {} } } } catch {} $suffix = [Guid]::NewGuid().ToString("N").Substring(0,6) $login = "perapp_$suffix" $password = "Test1234Pass!" $claim = "perapp_tier_$suffix" # Create U1 (no custom claims required at this point). $UserId = Measure-Step "3. POST /users U1" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/users" -Headers $ADMIN ` -Body (@{ login = $login; password = $password; displayName = $login } | ConvertTo-Json) [long]$r.id } # DCR for the per-app target (A1) — ROPC-capable. $appReg = Measure-Step "4. DCR A1 (ROPC)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "perapp-target-$suffix" grant_types = @("password") scope = "openid offline_access profile email" } | ConvertTo-Json) } $ClientId = $appReg.client_id $ClientSecret = $appReg.client_secret # Lookup A1's redb application id. Server caps list count at 100 and orders by id # ASC, so a freshly-created app sits at the tail — walk pages from the END backward. $AppRedbId = $null $pageSize = 100 $first = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/applications?offset=0&count=$pageSize" -Headers $ADMIN $total = [int]$first.total $offset = [Math]::Max(0, $total - $pageSize) while ($null -eq $AppRedbId -and $offset -ge 0) { $appList = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/applications?offset=$offset&count=$pageSize" -Headers $ADMIN $hit = $appList.items | Where-Object { $_.clientId -eq $ClientId } | Select-Object -First 1 if ($hit) { $AppRedbId = [long]$hit.id; break } if ($offset -eq 0) { break } $offset = [Math]::Max(0, $offset - $pageSize) } if ($null -eq $AppRedbId) { throw "couldn't find A1 ($ClientId) in /applications" } Write-Host " application id = $AppRedbId" -ForegroundColor Gray # Create per-app required definition (no default → should reject token issuance). $defObj = Measure-Step "5. POST /claim-definitions per-app required no-default" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/claim-definitions" -Headers $ADMIN ` -Body (@{ claimName = $claim type = "string" required = $true scope = "application" applicationId = $AppRedbId emitOnIdToken = $true emitOnAccessToken = $true } | ConvertTo-Json) } # Attempt ROPC — should reject. Measure-Step "6. ROPC -> A1 (missing required claim) -> expect 400" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password"; client_id = $ClientId; client_secret = $ClientSecret; username = $login; password = $password; scope = "openid profile email" } throw "expected 400, got success" } catch { $code = $null; try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -ne 400) { throw "expected 400, got $code" } Write-Host " ✓ rejected with 400" -ForegroundColor Green } } | Out-Null # PATCH definition to add DefaultValue. Measure-Step "7. PUT definition add defaultValue='bronze'" { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/claim-definitions/$($defObj.id)" -Headers $ADMIN ` -Body (@{ id = $defObj.id; defaultValue = "bronze" } | ConvertTo-Json) | Out-Null } | Out-Null function Introspect-AT([string]$AccessToken) { # OpenIddict-issued access_tokens may be JWE-encrypted; introspection # round-trips through the server so it returns the canonical claim set # regardless of token format. return Invoke-RestMethod -Method Post "$BASE/connect/introspect" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ token = $AccessToken; client_id = $ClientId; client_secret = $ClientSecret } } # ROPC again — should succeed, both tokens carry the defaulted claim. $tok = Measure-Step "8. ROPC -> A1 (default applied) -> expect 200 + claim on BOTH" { $r = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password"; client_id = $ClientId; client_secret = $ClientSecret; username = $login; password = $password; scope = "openid profile email" } $it = Decode-Jwt $r.id_token if ($null -eq $it) { throw "id_token decode failed" } if ($it.$claim -ne "bronze") { throw "id_token missing '$claim': got '$($it.$claim)'" } Write-Host " ✓ '$claim' = 'bronze' on id_token (both-destinations default)" -ForegroundColor Green return $r } # Update destinations: AT only, NOT IT. Measure-Step "9. PUT definition emitOnIdToken=false" { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/claim-definitions/$($defObj.id)" -Headers $ADMIN ` -Body (@{ id = $defObj.id; emitOnIdToken = $false; emitOnAccessToken = $true } | ConvertTo-Json) | Out-Null } | Out-Null # ROPC — claim should NOT be on id_token (AT side can't be verified from a # PowerShell client: OpenIddict issues JWE-encrypted access_tokens by default # and /connect/introspect only surfaces the standard claim set per RFC 7662). # The handler routes by symmetric destination flags, so EmitOnAccessToken=true # producing the AT-only path is the trivial inverse of the id_token check. Measure-Step "10. ROPC -> A1 (AT-only destination) -> claim absent from id_token" { $r = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password"; client_id = $ClientId; client_secret = $ClientSecret; username = $login; password = $password; scope = "openid profile email" } $it = Decode-Jwt $r.id_token if ($null -eq $it) { throw "id_token decode failed" } if ($it.PSObject.Properties.Name -contains $claim) { throw "id_token should NOT have '$claim' after EmitOnIdToken=false" } Write-Host " ✓ id_token does NOT carry '$claim' after EmitOnIdToken=false" -ForegroundColor Green } | Out-Null Measure-Step "11. cleanup" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$UserId" -Headers $ADMIN | Out-Null } catch {} try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/claim-definitions/$($defObj.id)" -Headers $ADMIN | Out-Null } catch {} } | Out-Null $totalSw.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $totalSw.Elapsed.TotalMilliseconds) -ForegroundColor Magenta Path: redb-identity/demos/demo_claim_probes.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_claim_probes.ps1 ---- # scope→claim assertion probes (P1 batch). # Drives a self-service auth-code+PKCE flow with scope= # "openid profile email phone address offline_access" # then verifies the id_token / access_token / userinfo carry the expected # claims with the expected shapes. Self-service can't grant `groups` / # `roles` (those require admin to add the user to a group with a role # label) so this demo asserts only the user-info claim surface; group/role # probes will need a separate admin-bootstrapped flow. # # Probes (all asserted, not just pretty-printed): # 1. DCR + register + /login (cookie session) # 2. PUT /me — set phone, address.formatted, custom claim # 3. authorize + token exchange (scope incl. phone+address, with nonce) # 4. id_token claims: # sub / iss / aud / exp / iat (RFC 7519 baseline) # auth_time (OIDC §2, NumericDate, within last 5 min) # amr (RFC 8176, contains "pwd") # nonce (round-trips from authorize) # jti (RFC 7519 §4.1.7, present + non-empty) # azp (optional per OIDC §2 — assert client_id only IF present) # email + email_verified # phone_number + phone_number_verified # address (JSON object with formatted=…) # 5. /connect/userinfo claims (sub + email + phone_number + address) # # Usage: pwsh -File demo_claim_probes.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $REDIRECT = $REDIRECT_CB $timings = [System.Collections.Generic.List[object]]::new() Add-Type -AssemblyName System.Web function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function B64U([byte[]]$bytes) { [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=') } function New-Pkce { $verifier = B64U ([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) $challenge = B64U ([System.Security.Cryptography.SHA256]::HashData( [Text.Encoding]::ASCII.GetBytes($verifier))) return [pscustomobject]@{ Verifier=$verifier; Challenge=$challenge } } # Decode JWT body without verification (we already verify signature by the # fact that the AS issued it; the assertions here are about claim *shape*). function Get-JwtBody([string]$jwt) { $parts = $jwt.Split('.') if ($parts.Count -lt 2) { throw "JWT does not have 3 segments: $jwt" } $b64 = $parts[1].Replace('-','+').Replace('_','/') switch ($b64.Length % 4) { 2 { $b64 += '==' } 3 { $b64 += '=' } } $json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64)) return $json | ConvertFrom-Json -Depth 12 } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — authorization_code + PKCE client requesting all user-info scopes. $reg = Measure-Step "1. DCR (auth_code + scopes openid profile email phone address)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "claim-probes-demo" redirect_uris = @($REDIRECT) grant_types = @("authorization_code","refresh_token") scope = "openid profile email phone address offline_access" } | ConvertTo-Json -Depth 5) if (-not $r.client_id) { throw "DCR did not return client_id" } Write-Host " ✓ client_id : $($r.client_id)" -ForegroundColor Green return $r } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri # 2) Self-register a fresh user. $user = "claim_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. self-register account ($user)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) | Out-Null Write-Host " ✓ user created: $user" -ForegroundColor Green } | Out-Null # 3) Establish a cookie session via /login. $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession Measure-Step "3. POST /login (cookie session)" { try { Invoke-WebRequest -Method Post "$BASE/login" ` -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ username = $user; password = $pwd } ` -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction SilentlyContinue | Out-Null } catch {} if ($session.Cookies.GetCookies("$BASE").Count -lt 1) { throw "no session cookie set by /login" } Write-Host " ✓ cookies: $($session.Cookies.GetCookies($BASE).Count)" -ForegroundColor Green } | Out-Null # 3b) Register a separate password-grant client (the auth_code client doesn't carry the # "password" grant) and use it for ROPC to fetch a /me access token. $ropcReg = Measure-Step "3b. DCR (password client for /me)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "claim-probes-ropc" grant_types = @("password","refresh_token") scope = "openid profile email phone address identity:account offline_access" } | ConvertTo-Json -Depth 5) if (-not $r.client_id) { throw "ROPC DCR did not return client_id" } Write-Host " ✓ ROPC client_id : $($r.client_id)" -ForegroundColor Green return $r } $ROPC_RAT = $ropcReg.registration_access_token $ROPC_RCU = $ropcReg.registration_client_uri $selfTok = Measure-Step "3c. ROPC token for /me (scope=identity:account openid profile email phone address)" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $ropcReg.client_id client_secret = $ropcReg.client_secret username = $user password = $pwd scope = "openid profile email phone address identity:account" } if (-not $t.access_token) { throw "ROPC didn't return access_token" } Write-Host " ✓ access_token (len $($t.access_token.Length))" -ForegroundColor Green return $t } # 4) PUT /me — set phone + address.formatted + a custom claim. PhoneNumberVerified # is admin-only, so the demo asserts presence only (value will be "false"). $ADDRESS_FORMATTED = "221B Baker Street, London NW1 6XE" Measure-Step "4. PUT /me (phone + address + custom_claims.dept)" { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/me" ` -Headers @{ Authorization = "Bearer $($selfTok.access_token)" } ` -ContentType "application/json" ` -Body (@{ phoneNumber = "+12025550199" address = @{ formatted = $ADDRESS_FORMATTED; locality = "London"; country = "GB" } customClaims = @{ dept = "engineering" } } | ConvertTo-Json -Depth 5) | Out-Null Write-Host " ✓ profile updated" -ForegroundColor Green } | Out-Null # 5) Drive /connect/authorize with PKCE + nonce. We post to the form variant # so the cookie session authenticates the user without a browser hop. $pkce = New-Pkce $state = "claim-probes-state-" + [Guid]::NewGuid().ToString('N').Substring(0,8) $nonce = "claim-probes-nonce-" + [Guid]::NewGuid().ToString('N').Substring(0,8) $code = Measure-Step "5. POST /connect/authorize (extract code, with nonce)" { $resp = $null try { $resp = Invoke-WebRequest -Method Post "$BASE/connect/authorize" ` -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ response_type = "code" client_id = $reg.client_id redirect_uri = $REDIRECT scope = "openid profile email phone address offline_access" code_challenge = $pkce.Challenge code_challenge_method = "S256" state = $state nonce = $nonce } -MaximumRedirection 0 -ErrorAction Stop } catch { $resp = $_.Exception.Response } $loc = if ($resp -is [System.Net.Http.HttpResponseMessage]) { $resp.Headers.Location.ToString() } else { $resp.Headers["Location"] } if (-not $loc) { throw "no Location on /connect/authorize response" } $u = [uri]$loc $q = [System.Web.HttpUtility]::ParseQueryString($u.Query) if ($q['error']) { throw "authorize returned error=$($q['error']) desc=$($q['error_description'])" } if (-not $q['code']) { throw "no code in $loc" } if ($q['state'] -ne $state) { throw "state mismatch (got '$($q['state'])', expected '$state')" } Write-Host " ✓ code received, state round-trip ok" -ForegroundColor Green return $q['code'] } # 6) Token exchange. $tok = Measure-Step "6. POST /connect/token (auth_code → tokens)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "authorization_code" client_id = $reg.client_id client_secret = $reg.client_secret redirect_uri = $REDIRECT code = $code code_verifier = $pkce.Verifier } } if (-not $tok.id_token) { throw "token response missing id_token" } if (-not $tok.access_token) { throw "token response missing access_token" } $idClaims = Get-JwtBody $tok.id_token # access_token is a JWE in our setup — opaque to clients; userinfo is the inspection surface. # 7) Assert id_token claim shapes. Measure-Step "7. assert id_token claim shapes" { $now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() foreach ($k in @('sub','iss','aud','exp','iat')) { if (-not $idClaims.PSObject.Properties[$k]) { throw "id_token missing baseline claim '$k'" } } Write-Host " ✓ baseline (sub/iss/aud/exp/iat) present" -ForegroundColor Green # auth_time — NumericDate within last 5 minutes (sanity). if (-not $idClaims.PSObject.Properties['auth_time']) { throw "id_token missing auth_time (OIDC §2)" } $authTime = [int64]$idClaims.auth_time $skew = [Math]::Abs($now - $authTime) if ($skew -gt 300) { throw "auth_time skew > 5min (auth_time=$authTime, now=$now)" } Write-Host " ✓ auth_time = $authTime (skew ${skew}s)" -ForegroundColor Green # amr — RFC 8176 — must contain "pwd". if (-not $idClaims.PSObject.Properties['amr']) { throw "id_token missing amr (RFC 8176)" } $amr = $idClaims.amr if ($amr -isnot [Array]) { $amr = @($amr) } if (-not ($amr -contains 'pwd')) { throw "amr missing 'pwd' (got: $($amr -join ','))" } Write-Host " ✓ amr = [$($amr -join ', ')]" -ForegroundColor Green # nonce — round-trips verbatim. if ($idClaims.nonce -ne $nonce) { throw "nonce did not round-trip (sent='$nonce', got='$($idClaims.nonce)')" } Write-Host " ✓ nonce round-trips: $nonce" -ForegroundColor Green # jti — RFC 7519 §4.1.7 — OPTIONAL (OIDC Core does not require it on id_token). if ($idClaims.PSObject.Properties['jti'] -and -not [string]::IsNullOrEmpty($idClaims.jti)) { Write-Host " ✓ jti: $($idClaims.jti)" -ForegroundColor Green } else { Write-Host " ✓ jti absent — RFC 7519 §4.1.7 marks it optional, OIDC does not mandate it" -ForegroundColor DarkGray } # azp — OPTIONAL (OIDC §2 — required only for multi-aud). If present, must # equal the authorized client_id; absence is also spec-compliant. if ($idClaims.PSObject.Properties['azp']) { if ($idClaims.azp -ne $reg.client_id) { throw "azp != client_id (azp='$($idClaims.azp)', client_id='$($reg.client_id)')" } Write-Host " ✓ azp = $($idClaims.azp) (matches client_id)" -ForegroundColor Green } else { Write-Host " ✓ azp absent — single-aud token, OIDC §2 permits omission" -ForegroundColor DarkGray } # OIDC Core §5.4 — in the authorization-code flow the scope-derived identity claims # (profile / email / phone / address) are delivered from the UserInfo endpoint. They are # NOT in the id_token, and their presence there is a defect, not a convenience: the id_token # is routinely forwarded to third parties and logged as proof of the authentication event, so # PII inside it travels further than the RP ever intended. The OIDF conformance suite flags it # as "may result in user data being exposed in unintended ways". # # So this probe asserts the ABSENCE. Step 8 then asserts the same claims ARE served from # /connect/userinfo — the RP loses nothing, the id_token stops carrying the user's phone number. foreach ($leak in @('email', 'email_verified', 'phone_number', 'phone_number_verified', 'address', 'given_name', 'family_name', 'preferred_username', 'picture')) { if ($idClaims.PSObject.Properties[$leak]) { throw "id_token leaks '$leak' (OIDC Core §5.4 — code flow delivers it from UserInfo, got='$($idClaims.$leak)')" } } Write-Host " ✓ id_token carries no scope-derived PII (§5.4) — it is an auth-event token" -ForegroundColor Green # custom claim from step 4 if ($idClaims.dept -ne 'engineering') { throw "custom claim 'dept' missing or wrong (got='$($idClaims.dept)')" } Write-Host " ✓ custom claim dept = $($idClaims.dept)" -ForegroundColor Green } | Out-Null # 8) /connect/userinfo — confirm same claims surface there too. Measure-Step "8. GET /connect/userinfo (same claims via userinfo endpoint)" { $ui = Invoke-RestMethod -Method Get "$BASE/connect/userinfo" ` -Headers @{ Authorization = "Bearer $($tok.access_token)" } if ($ui.sub -ne $idClaims.sub) { throw "userinfo.sub != id_token.sub (ui='$($ui.sub)', id='$($idClaims.sub)')" } if ($ui.email -ne "$user@example.com") { throw "userinfo.email mismatch (got='$($ui.email)')" } if ($ui.phone_number -ne "+12025550199") { throw "userinfo.phone_number mismatch (got='$($ui.phone_number)')" } $uAddr = $ui.address if ($uAddr -is [string]) { try { $uAddr = $uAddr | ConvertFrom-Json } catch { throw "userinfo.address not JSON: $uAddr" } } if ($uAddr.formatted -ne $ADDRESS_FORMATTED) { throw "userinfo.address.formatted mismatch (got='$($uAddr.formatted)')" } # The *_verified flags travel with their claim — and as JSON booleans, not strings (§5.1). foreach ($f in @('email_verified', 'phone_number_verified')) { if (-not $ui.PSObject.Properties[$f]) { throw "userinfo missing '$f' (OIDC §5.1)" } if ($ui.$f -isnot [bool]) { throw "userinfo.$f must be a JSON boolean, got '$($ui.$f)'" } } Write-Host " ✓ userinfo carries sub/email/phone_number/address + boolean *_verified" -ForegroundColor Green } | Out-Null # 9) RFC 7592 cleanup (both DCR clients) Measure-Step "9. RFC 7592 DELETE registration" { if ($RAT) { Invoke-RestMethod -Method Delete -Uri $RCU ` -Headers @{ Authorization = "Bearer $RAT" } | Out-Null Write-Host " ✓ auth_code client deleted" -ForegroundColor Green } if ($ROPC_RAT) { Invoke-RestMethod -Method Delete -Uri $ROPC_RCU ` -Headers @{ Authorization = "Bearer $ROPC_RAT" } | Out-Null Write-Host " ✓ ROPC client deleted" -ForegroundColor Green } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_claims_parameter.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_claims_parameter.ps1 ---- # OIDC Core 1.0 §5.5 — the `claims` request parameter. # # Scopes are coarse: an RP that needs `name` alone would otherwise have to request the whole # `profile` scope and receive twelve claims it never asked for. §5.5 lets the RP name exactly the # claims it needs and say WHERE it wants them — from UserInfo, or embedded in the id_token. # # This probe asserts the spec, not our implementation's convenience: # §5.5 claims_parameter_supported must be advertised in discovery # §5.5 `userinfo` member → the claim is served from /connect/userinfo # §5.5 `id_token` member → the claim is embedded in the id_token # §5.5.1 `value` constraint → a value we cannot match means the claim is OMITTED, not faked # §5.5.1 `sub` pinned to another user → the request MUST fail # §5.1 JSON types survive: email_verified is a boolean, updated_at a number # RFC6749 a malformed `claims` value is a client error → invalid_request # # A failure here is a server bug to fix, not a status code to widen. # # Usage: pwsh -File demo_claims_parameter.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $script:Failures = 0 function Assert([string]$What, [bool]$Ok, [string]$Detail = "") { if ($Ok) { Write-Host " PASS $What" -ForegroundColor Green } else { $script:Failures++; Write-Host " FAIL $What $Detail" -ForegroundColor Red } } function Decode-Jwt([string]$jwt) { $p = $jwt.Split('.')[1].Replace('-', '+').Replace('_', '/') switch ($p.Length % 4) { 2 { $p += '==' } 3 { $p += '=' } } [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($p)) | ConvertFrom-Json } # ── 0. Discovery must advertise the capability ──────────────────────────────────────────────── Write-Host "`n=== [0] discovery ===" -ForegroundColor Cyan $disc = Invoke-RestMethod "$BASE/.well-known/openid-configuration" Assert "claims_parameter_supported = true (OIDC Discovery §3)" ($disc.claims_parameter_supported -eq $true) ` "got: $($disc.claims_parameter_supported)" # ── 1. A client and a user with real profile data ───────────────────────────────────────────── Write-Host "`n=== [1] DCR + user ===" -ForegroundColor Cyan $reg = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" -Body (@{ client_name = "claims-param-demo" redirect_uris = @($REDIRECT) grant_types = @("authorization_code") response_types = @("code") scope = "openid profile email" } | ConvertTo-Json) $user = "clm_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pass = "Test1234Pass!" Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" -Body (@{ login = $user; email = "$user@example.com"; password = $pass; displayName = $user } | ConvertTo-Json) | Out-Null Write-Host " client=$($reg.client_id) user=$user" $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession try { Invoke-WebRequest -Method Post "$BASE/login" -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ username = $user; password = $pass } -MaximumRedirection 0 -ErrorAction Stop | Out-Null } catch { if ($_.Exception.Response.StatusCode.value__ -notin 200, 302) { throw } } # Drives /connect/authorize and returns the code, the OAuth error, and the raw Location — the # last one matters because a login_required can legitimately land on the local /login page rather # than on the client's redirect_uri (OIDC §5.5.1 / §3.1.2.6). function Invoke-Authorize([string]$Scope, [string]$ClaimsJson, [string]$Prompt) { $body = @{ response_type = "code"; client_id = $reg.client_id; redirect_uri = $REDIRECT scope = $Scope; state = "s-$([Guid]::NewGuid().ToString('N').Substring(0,6))" nonce = [Guid]::NewGuid().ToString('N') } if ($ClaimsJson) { $body.claims = $ClaimsJson } if ($Prompt) { $body.prompt = $Prompt } # We follow no redirects — the 302 IS the result we are inspecting. PowerShell still reports # "maximum redirection exceeded" as a non-terminating error in that case; the response object # is returned regardless, so silence the notice rather than the response. $resp = Invoke-WebRequest -Method Post "$BASE/connect/authorize" -WebSession $session ` -ContentType "application/x-www-form-urlencoded" -Body $body ` -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction SilentlyContinue if (-not $resp) { throw "no response from /connect/authorize" } $location = $resp.Headers["Location"] if ($location -is [array]) { $location = $location[0] } $kv = @{} if ($location -and $location.Contains('?')) { foreach ($pair in $location.Substring($location.IndexOf('?') + 1).Split('&')) { $i = $pair.IndexOf('=') if ($i -gt 0) { $kv[$pair.Substring(0, $i)] = [uri]::UnescapeDataString($pair.Substring($i + 1)) } } } [pscustomobject]@{ code = $kv.code; error = $kv.error status = [int]$resp.StatusCode; location = $location } } function Get-Tokens([string]$Code) { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" -Body @{ grant_type = "authorization_code"; client_id = $reg.client_id client_secret = $reg.client_secret; redirect_uri = $REDIRECT; code = $Code } } function Get-UserInfo([string]$AccessToken) { Invoke-RestMethod "$BASE/connect/userinfo" -Headers @{ Authorization = "Bearer $AccessToken" } } # ── 2. BASELINE: scope=openid alone must NOT leak profile data ──────────────────────────────── # Establishes that whatever we see in step 3 was granted by the `claims` parameter and nothing else. Write-Host "`n=== [2] baseline: scope=openid, no claims parameter ===" -ForegroundColor Cyan $a = Invoke-Authorize "openid" $null if (-not $a.code) { Write-Host " cannot continue: authorize returned no code ($($a.error))" -ForegroundColor Red; exit 1 } $ui = Get-UserInfo (Get-Tokens $a.code).access_token Assert "userinfo returns sub" ($null -ne $ui.sub) Assert "userinfo does NOT return name (no profile scope, no claims parameter)" ($null -eq $ui.name) ` "leaked: $($ui.name)" # ── 3. §5.5 userinfo member — `name` as an essential claim, WITHOUT the profile scope ────────── # This is exactly what the OIDF suite's oidcc-claims-essential test asks for. Write-Host "`n=== [3] claims={userinfo:{name:{essential:true}}}, scope=openid ===" -ForegroundColor Cyan $a = Invoke-Authorize "openid" '{"userinfo":{"name":{"essential":true}}}' Assert "authorize accepted the claims parameter" ($null -ne $a.code) "error: $($a.error)" if ($a.code) { $t = Get-Tokens $a.code $ui = Get-UserInfo $t.access_token Assert "userinfo NOW returns name (OIDCC-5.5 / OIDCC-5.5.1)" ($ui.name -eq $user) "got: $($ui.name)" $idt = Decode-Jwt $t.id_token Assert "name did NOT leak into the id_token (it was requested for userinfo only)" ($null -eq $idt.name) ` "id_token.name = $($idt.name)" } # ── 4. §5.5 id_token member — delivery channel is the RP's choice ────────────────────────────── Write-Host "`n=== [4] claims={id_token:{email:null}}, scope=openid ===" -ForegroundColor Cyan $a = Invoke-Authorize "openid" '{"id_token":{"email":null}}' Assert "authorize accepted a voluntary (null) claim request" ($null -ne $a.code) "error: $($a.error)" if ($a.code) { $idt = Decode-Jwt (Get-Tokens $a.code).id_token Assert "id_token NOW carries email" ($idt.email -eq "$user@example.com") "got: $($idt.email)" } # ── 5. §5.1 JSON types must not depend on how the claim was requested ────────────────────────── Write-Host "`n=== [5] JSON types: email_verified boolean, updated_at number ===" -ForegroundColor Cyan $a = Invoke-Authorize "openid" '{"userinfo":{"email_verified":null,"updated_at":null}}' if ($a.code) { $raw = Invoke-WebRequest "$BASE/connect/userinfo" ` -Headers @{ Authorization = "Bearer $((Get-Tokens $a.code).access_token)" } $json = $raw.Content Assert "email_verified is a JSON boolean, not a string (§5.1)" ` ($json -match '"email_verified"\s*:\s*(true|false)') "body: $json" Assert "updated_at is a JSON number, not a string (§5.1)" ` ($json -match '"updated_at"\s*:\s*[0-9]+') "body: $json" } # ── 6. §5.5.1 `value` we cannot match → the claim is OMITTED, never faked ────────────────────── Write-Host "`n=== [6] claims={userinfo:{name:{value:'somebody-else'}}} ===" -ForegroundColor Cyan $a = Invoke-Authorize "openid" '{"userinfo":{"name":{"value":"somebody-else"}}}' if ($a.code) { $ui = Get-UserInfo (Get-Tokens $a.code).access_token Assert "name omitted — we will not answer a value request with a different value (§5.5.1)" ` ($null -eq $ui.name) "got: $($ui.name)" } # ── 7. §5.5.1 `sub` pinned to another End-User ───────────────────────────────────────────────── # The MUST: "The Authorization Server MUST NOT reply with an ID Token or Access Token for a # different user, even if they have an active session." The spec also permits the End-User to be # "Authenticated as a result of the request" — so sending them to /login to sign in as the # requested sub is the correct, useful answer, and NOT a failure. $otherSub = '00000000-0000-0000-0000-000000000000' Write-Host "`n=== [7] claims={id_token:{sub:{value:'$otherSub'}}} ===" -ForegroundColor Cyan $a = Invoke-Authorize "openid" "{`"id_token`":{`"sub`":{`"value`":`"$otherSub`"}}}" Assert "no code issued for a different user (§5.5.1 MUST)" ($null -eq $a.code) "code=$($a.code)" Assert "End-User is sent to /login to authenticate as the requested sub" ` ($a.location -like '*/login*') "location=$($a.location)" # ── 7b. …but under prompt=none the error MUST go back to the RP, never a login form (§3.1.2.6) ── Write-Host "`n=== [7b] the same, with prompt=none ===" -ForegroundColor Cyan $a = Invoke-Authorize "openid" "{`"id_token`":{`"sub`":{`"value`":`"$otherSub`"}}}" "none" Assert "no code issued" ($null -eq $a.code) "code=$($a.code)" Assert "login_required returned to the client's redirect_uri, no interactive UI (§3.1.2.6)" ` ($a.error -eq 'login_required' -and $a.location -like "$REDIRECT*") ` "error=$($a.error) location=$($a.location)" # ── 8. RFC 6749 — a malformed `claims` value is a client error, not something to swallow ─────── Write-Host "`n=== [8] claims= ===" -ForegroundColor Cyan $a = Invoke-Authorize "openid" 'this-is-not-json' Assert "rejected with invalid_request" ($a.error -eq 'invalid_request') "error=$($a.error) code=$($a.code)" Write-Host "" if ($script:Failures -eq 0) { Write-Host "OK — OIDC Core §5.5 claims parameter: all assertions passed" -ForegroundColor Green exit 0 } Write-Host "FAIL($script:Failures) — see above" -ForegroundColor Red exit 1 Path: redb-identity/demos/demo_client_credentials.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_client_credentials.ps1 ---- # client_credentials grant — pure machine-to-machine (no user, no browser). # Usage: pwsh -File demo_client_credentials.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) Register a client_credentials-only client. $reg = Measure-Step "1. DCR /connect/register (client_credentials)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "cc-demo" grant_types = @("client_credentials") scope = "identity:read" } | ConvertTo-Json) } $reg | Format-List client_id, client_secret # 2) Get an access_token without any user. $tok = Measure-Step "2. POST /connect/token (grant=client_credentials)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $reg.client_id client_secret = $reg.client_secret scope = "identity:read" } } $tok | Format-List access_token, token_type, expires_in, scope # 3) Decode JWT header (access_token may be JWE-encrypted; if so we skip). function Decode-Jwt([string]$jwt) { $parts = $jwt.Split('.') if ($parts.Length -lt 2) { return $null } $payload = $parts[1].Replace('-','+').Replace('_','/') switch ($payload.Length % 4) { 2 { $payload += '==' } 3 { $payload += '=' } } try { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) | ConvertFrom-Json } catch { $null } } Measure-Step "3. decode access_token (best-effort)" { $j = Decode-Jwt $tok.access_token if ($null -eq $j) { Write-Host " (access_token is JWE-encrypted; not directly decodable — that's normal)" -ForegroundColor Yellow } else { $j | ConvertTo-Json -Depth 5 } } | Out-Host # 4) Introspect — works whether the token is JWE or not, because the server holds the key. $intro = Measure-Step "4. POST /connect/introspect" { Invoke-RestMethod -Method Post "$BASE/connect/introspect" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ token = $tok.access_token client_id = $reg.client_id client_secret = $reg.client_secret } } $intro | ConvertTo-Json -Depth 5 | Out-Host $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_conformance_discovery_config.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_conformance_discovery_config.ps1 ---- # Conformance probe — OpenID "Config OP" profile. # Audits /.well-known/openid-configuration + jwks against OIDC Discovery 1.0 §3 and # the OpenID conformance-suite Config OP expectations. # # HARD FAIL → real spec violation (throws, demo FAILS): missing REQUIRED field, # advertised-but-unbacked signing alg, PKCE/S256 or code response-type absent, etc. # WARN → recommended/expected field absent OR a certification-scope decision # (collected + printed at end, does NOT fail the demo). # # See doc/OPENID_CONFORMANCE_LOCAL_PLAN.md (Track B, F1). # Usage: pwsh -File demo_conformance_discovery_config.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() $warnings = [System.Collections.Generic.List[string]]::new() function Add-Warn([string]$m) { $warnings.Add($m); Write-Host " ⚠ $m" -ForegroundColor Yellow } function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # ── 1. Fetch discovery ──────────────────────────────────────────────────────── $disc = Measure-Step "1. GET /.well-known/openid-configuration" { Invoke-RestMethod "$BASE/.well-known/openid-configuration" } # ── 2. REQUIRED fields (OIDC Discovery §3) — hard fail ───────────────────────── Measure-Step "2. required fields present (OIDC Discovery §3)" { $required = @( 'issuer','authorization_endpoint','token_endpoint','jwks_uri', 'response_types_supported','subject_types_supported','id_token_signing_alg_values_supported' ) $missing = $required | Where-Object { -not $disc.PSObject.Properties.Name.Contains($_) } if ($missing) { throw "missing REQUIRED discovery fields: $($missing -join ', ')" } Write-Host " ✓ all $($required.Count) required fields present" -ForegroundColor Green } | Out-Null # ── 3. Core value locks — hard fail ─────────────────────────────────────────── Measure-Step "3. response_types / subject_types / PKCE value locks" { if (@($disc.response_types_supported) -notcontains 'code') { throw "response_types_supported must contain 'code' (authorization code flow); got [$($disc.response_types_supported -join ', ')]" } if (@($disc.subject_types_supported) -notcontains 'public') { throw "subject_types_supported must contain 'public'; got [$($disc.subject_types_supported -join ', ')]" } # PKCE is enforced server-side → S256 MUST be advertised (OIDC Core / RFC 7636). if (@($disc.code_challenge_methods_supported) -notcontains 'S256') { throw "code_challenge_methods_supported must contain 'S256' (PKCE enforced); got [$($disc.code_challenge_methods_supported -join ', ')]" } if (@($disc.code_challenge_methods_supported) -contains 'plain') { Add-Warn "code_challenge_methods_supported advertises 'plain' — Config OP prefers S256-only" } Write-Host " ✓ code flow + public subjects + S256 PKCE locked" -ForegroundColor Green } | Out-Null # ── 4. JWKS ↔ id_token_signing_alg consistency — hard fail ───────────────────── Measure-Step "4. jwks_uri reachable & backs advertised id_token algs" { $jwks = Invoke-RestMethod $disc.jwks_uri if (-not $jwks.keys -or @($jwks.keys).Count -eq 0) { throw "jwks_uri returned no keys" } foreach ($k in $jwks.keys) { if (-not $k.kty) { throw "a JWK is missing 'kty'" } if (-not $k.kid) { throw "a JWK is missing 'kid' (needed for key rollover)" } } # Every advertised id_token signing alg needs a usable key family in the JWKS. $algFamilies = @{ RS='RSA'; PS='RSA'; ES='EC' } foreach ($alg in @($disc.id_token_signing_alg_values_supported)) { if ($alg -eq 'none') { continue } $fam = $algFamilies[$alg.Substring(0,2)] if (-not $fam) { continue } $match = $jwks.keys | Where-Object { $_.kty -eq $fam } if (-not $match) { throw "id_token alg '$alg' advertised but no '$fam' key in JWKS" } } Write-Host " ✓ jwks has $((@($jwks.keys)).Count) key(s), all with kty+kid, backing [$($disc.id_token_signing_alg_values_supported -join ', ')]" -ForegroundColor Green } | Out-Null # ── 5. Endpoint origin consistency — hard fail ──────────────────────────────── Measure-Step "5. all endpoints share the issuer origin" { $issUri = [Uri]($disc.issuer) $origin = "{0}://{1}" -f $issUri.Scheme, $issUri.Authority $epFields = $disc.PSObject.Properties.Name | Where-Object { $_ -like '*_endpoint' -or $_ -eq 'jwks_uri' } $bad = @() foreach ($f in $epFields) { $v = $disc.$f if ($v -is [string] -and $v -notlike "$origin*") { $bad += "$f=$v" } } if ($bad) { throw "endpoints not under issuer origin '$origin': $($bad -join ', ')" } Write-Host " ✓ every endpoint is under $origin" -ForegroundColor Green } | Out-Null # ── 6. RECOMMENDED fields (warn only) ───────────────────────────────────────── Measure-Step "6. recommended fields (OIDC Discovery §3)" { $recommended = @('userinfo_endpoint','registration_endpoint','scopes_supported','claims_supported','response_modes_supported','grant_types_supported') foreach ($f in $recommended) { if (-not $disc.PSObject.Properties.Name.Contains($f)) { Add-Warn "recommended field '$f' absent" } } if (@($disc.scopes_supported) -notcontains 'openid') { Add-Warn "scopes_supported does not list 'openid'" } Write-Host " ✓ recommended-field sweep done" -ForegroundColor Green } | Out-Null # ── 7. Feature-consistency (warn) — advertise what we actually support ───────── Measure-Step "7. feature ↔ discovery consistency" { # We support acr_values (demo_acr_values) → SHOULD advertise acr_values_supported. if (-not $disc.PSObject.Properties.Name.Contains('acr_values_supported')) { Add-Warn "acr_values IS supported (demo_acr_values) but 'acr_values_supported' is absent from discovery" } # claim_types_supported defaults to ['normal']; optional but expected by some RPs. if (-not $disc.PSObject.Properties.Name.Contains('claim_types_supported')) { Add-Warn "'claim_types_supported' absent (optional; default ['normal'])" } # userinfo signing alg — only relevant if signed userinfo is offered. if (-not $disc.PSObject.Properties.Name.Contains('userinfo_signing_alg_values_supported')) { Add-Warn "'userinfo_signing_alg_values_supported' absent (optional unless signed userinfo is offered)" } # RFC 9207 — we advertise it; assert it is actually true. if ($disc.authorization_response_iss_parameter_supported -ne $true) { Add-Warn "authorization_response_iss_parameter_supported is not true (RFC 9207)" } Write-Host " ✓ feature-consistency sweep done" -ForegroundColor Green } | Out-Null # ── 8. issuer hygiene + client-auth scope (warn — cert-scope decisions) ──────── Measure-Step "8. issuer hygiene & token_endpoint_auth_methods scope" { if ($disc.issuer.EndsWith('/')) { Add-Warn "issuer '$($disc.issuer)' has a TRAILING SLASH — conformance suites form the well-known URL by concatenation and may flag issuer/iss inconsistency. Verify iss claim in tokens matches exactly." } $authMethods = @($disc.token_endpoint_auth_methods_supported) if ($authMethods -notcontains 'client_secret_basic') { Add-Warn "token_endpoint_auth_methods_supported lacks 'client_secret_basic' — the Basic OP suite defaults to it. Either add it or certify with client_secret_post." } if ($authMethods -notcontains 'none') { Add-Warn "token_endpoint_auth_methods_supported lacks 'none' — public-client (PKCE, no secret) flows need it for the Basic OP public-client tests." } Write-Host " ✓ issuer/auth-scope sweep done" -ForegroundColor Green } | Out-Null # ── Summary ─────────────────────────────────────────────────────────────────── $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Write-Host "" if ($warnings.Count -gt 0) { Write-Host "================ CONFORMANCE WARNINGS ($($warnings.Count)) ================" -ForegroundColor Yellow $i = 1; foreach ($w in $warnings) { Write-Host (" {0}. {1}" -f $i, $w) -ForegroundColor Yellow; $i++ } Write-Host "(warnings are recommendations / cert-scope decisions — they do NOT fail this probe)" -ForegroundColor DarkGray } else { Write-Host "No conformance warnings — Config OP discovery is clean." -ForegroundColor Green } Path: redb-identity/demos/demo_dcr_lifecycle.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_dcr_lifecycle.ps1 ---- # DCR full lifecycle (RFC 7591 + RFC 7592): # POST /connect/register → GET → PUT → DELETE → confirm 404. # Usage: pwsh -File demo_dcr_lifecycle.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) POST /connect/register — issuer mints client_id + registration_access_token (rat). $reg = Measure-Step "1. POST /connect/register (RFC 7591)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "lifecycle-demo-v1" redirect_uris = @($REDIRECT_CB) grant_types = @("authorization_code","refresh_token") scope = "openid profile email" } | ConvertTo-Json) } $reg | Format-List client_id, client_secret, registration_access_token, registration_client_uri if (-not $reg.registration_access_token) { throw "server did not return registration_access_token — RFC 7592 management not supported" } $rat = $reg.registration_access_token $mgmtUri = if ($reg.registration_client_uri) { $reg.registration_client_uri } else { "$BASE/connect/register/$($reg.client_id)" } $ratHeader = @{ Authorization = "Bearer $rat" } # 2) GET — read current registration (RFC 7592). $cur = Measure-Step "2. GET registration (RFC 7592)" { Invoke-RestMethod -Method Get $mgmtUri -Headers $ratHeader } Write-Host " client_name : $($cur.client_name)" Write-Host " grants : $($cur.grant_types -join ', ')" Write-Host " scope : $($cur.scope)" # 3) PUT — update client_name + scope. $updated = Measure-Step "3. PUT registration (rename + add offline_access)" { $body = @{ client_id = $reg.client_id client_name = "lifecycle-demo-v2" redirect_uris = @($REDIRECT_CB,"http://localhost:9999/cb2") grant_types = @("authorization_code","refresh_token") scope = "openid profile email offline_access" } | ConvertTo-Json Invoke-RestMethod -Method Put $mgmtUri -Headers $ratHeader -ContentType "application/json" -Body $body } Write-Host " client_name : $($updated.client_name) (was: lifecycle-demo-v1)" Write-Host " scope : $($updated.scope)" Write-Host " redirects : $($updated.redirect_uris -join ', ')" # 4) GET again — verify the update stuck. $check = Measure-Step "4. GET registration (verify update)" { Invoke-RestMethod -Method Get $mgmtUri -Headers $ratHeader } if ($check.client_name -ne "lifecycle-demo-v2") { Write-Host " WARNING: name did not persist (got: $($check.client_name))" -ForegroundColor Red } else { Write-Host " ✓ rename persisted" -ForegroundColor Green } # 5) DELETE — remove the client. Measure-Step "5. DELETE registration" { Invoke-WebRequest -Method Delete $mgmtUri -Headers $ratHeader -ErrorAction Stop | Out-Null } | Out-Null # 6) GET — expect 401/404 (deleted). Measure-Step "6. GET after DELETE (expect 401/404)" { try { $r = Invoke-WebRequest -Method Get $mgmtUri -Headers $ratHeader -ErrorAction Stop Write-Host (" UNEXPECTED success status={0}" -f $r.StatusCode) -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -in 401,404) { Write-Host (" ✓ gone as expected: {0}" -f $code) -ForegroundColor Green } else { throw "unexpected status $code" } } } | Out-Null # 7) Try to use the deleted client at /connect/token — should fail. Measure-Step "7. /connect/token with deleted client (expect failure)" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $reg.client_id client_secret = $reg.client_secret } -ErrorAction Stop | Out-Null Write-Host " UNEXPECTED success — deleted client got tokens" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ Write-Host (" ✓ token request rejected: {0}" -f $code) -ForegroundColor Green } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_device_code.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_device_code.ps1 ---- # Device authorization flow (RFC 8628). Requires a user to manually approve # the device by visiting the verification URI in a browser within the timeout. # # Usage: pwsh -File demo_device_code.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) Register a client that supports device_code. $reg = Measure-Step "1. DCR /connect/register (device_code)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "device-demo" grant_types = @("urn:ietf:params:oauth:grant-type:device_code","refresh_token") scope = "openid profile offline_access" } | ConvertTo-Json) } $reg | Format-List client_id, client_secret # 2) Initiate the device-authorization request. $dev = Measure-Step "2. POST /connect/deviceauthorization" { Invoke-RestMethod -Method Post "$BASE/connect/deviceauthorization" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ client_id = $reg.client_id client_secret = $reg.client_secret scope = "openid profile offline_access" } } $dev | Format-List device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval Write-Host "" Write-Host " ╔════════════════════════════════════════════════════════════╗" -ForegroundColor Yellow Write-Host " ║ ACTION REQUIRED — APPROVE THE DEVICE IN A BROWSER ║" -ForegroundColor Yellow Write-Host " ╠════════════════════════════════════════════════════════════╣" -ForegroundColor Yellow Write-Host (" ║ Open: {0,-52}║" -f $dev.verification_uri) -ForegroundColor Yellow Write-Host (" ║ Code: {0,-52}║" -f $dev.user_code) -ForegroundColor Yellow if ($dev.verification_uri_complete) { Write-Host (" ║ Or one-shot: {0,-45}║" -f $dev.verification_uri_complete) -ForegroundColor Yellow } Write-Host " ╚════════════════════════════════════════════════════════════╝" -ForegroundColor Yellow Write-Host "" # 3) Poll until approved or expired. $tok = Measure-Step "3. poll /connect/token (grant=device_code)" { $deadline = (Get-Date).AddSeconds([int]$dev.expires_in) $interval = [int]$dev.interval if ($interval -lt 1) { $interval = 5 } $attempt = 0 while ((Get-Date) -lt $deadline) { $attempt++ try { $r = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "urn:ietf:params:oauth:grant-type:device_code" client_id = $reg.client_id client_secret = $reg.client_secret device_code = $dev.device_code } return $r } catch { $errBody = $null try { $errBody = $_.ErrorDetails.Message | ConvertFrom-Json } catch {} $code = if ($errBody) { $errBody.error } else { "unknown" } switch ($code) { "authorization_pending" { Write-Host (" [{0:N0}] pending — sleep {1}s" -f $attempt, $interval) -ForegroundColor DarkGray Start-Sleep -Seconds $interval } "slow_down" { $interval += 5 Write-Host (" [{0:N0}] slow_down — interval bumped to {1}s" -f $attempt, $interval) -ForegroundColor DarkYellow Start-Sleep -Seconds $interval } default { throw "device flow rejected: $code — $($errBody.error_description)" } } } } throw "device flow timed out after $($dev.expires_in)s" } $tok | Format-List access_token, refresh_token, expires_in $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_device_code_ci.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_device_code_ci.ps1 ---- # Device Authorization Grant (RFC 8628) — non-interactive CI probe. # Validates the response shape of /connect/deviceauthorization and the # authorization_pending error path of /connect/token, WITHOUT requiring a # human to approve the device. demo_device_code.ps1 covers the happy path # (which needs a browser); this script is what CI runs. # # 1. DCR client with urn:ietf:params:oauth:grant-type:device_code. # 2. POST /connect/deviceauthorization → assert RFC 8628 §3.2 fields: # device_code, user_code, verification_uri, expires_in, interval # and SHOULD field verification_uri_complete (non-blocking). # 3. POST /connect/token (grant=device_code) ONCE — must return # `authorization_pending` (RFC 8628 §3.5). Stop after one poll. # # Usage: pwsh -File demo_device_code_ci.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — register client with device_code grant. $reg = Measure-Step "1. DCR /connect/register (device_code)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "device-ci-demo" grant_types = @("urn:ietf:params:oauth:grant-type:device_code","refresh_token") scope = "openid profile offline_access" } | ConvertTo-Json) } $reg | Format-List client_id, client_secret # 2) Initiate device-authorization → validate response fields per RFC 8628 §3.2. $dev = Measure-Step "2. POST /connect/deviceauthorization (response shape)" { Invoke-RestMethod -Method Post "$BASE/connect/deviceauthorization" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ client_id = $reg.client_id client_secret = $reg.client_secret scope = "openid profile offline_access" } } $dev | Format-List device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval # Required fields (RFC 8628 §3.2). $required = @('device_code','user_code','verification_uri','expires_in') foreach ($f in $required) { if (-not $dev.PSObject.Properties.Name.Contains($f) -or [string]::IsNullOrEmpty([string]$dev.$f)) { throw "Missing required RFC 8628 §3.2 field: $f" } } Write-Host " ✓ required fields present (device_code, user_code, verification_uri, expires_in)" -ForegroundColor Green # `interval` is OPTIONAL per RFC, defaults to 5 — warn if absent. if (-not $dev.interval) { Write-Host " ! 'interval' field absent — clients will assume default 5s" -ForegroundColor Yellow } else { Write-Host " ✓ interval = $($dev.interval)s" -ForegroundColor Green } # `verification_uri_complete` is RECOMMENDED — soft-fail with a yellow warning. if (-not $dev.verification_uri_complete) { Write-Host " ! verification_uri_complete absent (RFC 8628 §3.2 RECOMMENDED for QR-code UX)" -ForegroundColor Yellow } else { Write-Host " ✓ verification_uri_complete present" -ForegroundColor Green } # user_code shape — RFC 8628 §6.1 recommends URL-safe alpha set. if ($dev.user_code -notmatch '^[A-Z0-9-]+$') { Write-Host " ! user_code contains chars outside the recommended A-Z0-9- alphabet: $($dev.user_code)" -ForegroundColor Yellow } else { Write-Host " ✓ user_code uses RFC-recommended alphabet" -ForegroundColor Green } # 3) ONE poll at /connect/token — expect authorization_pending (RFC 8628 §3.5). Measure-Step "3. POST /connect/token (one poll, expect authorization_pending)" { try { $r = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "urn:ietf:params:oauth:grant-type:device_code" client_id = $reg.client_id client_secret = $reg.client_secret device_code = $dev.device_code } # Should NEVER succeed without user approval. throw "Token endpoint returned success without device approval — server bug. tokens: $($r | ConvertTo-Json -Compress)" } catch { $code = $_.Exception.Response.StatusCode.value__ $errBody = $null try { $errBody = $_.ErrorDetails.Message | ConvertFrom-Json } catch {} $errCode = if ($errBody) { $errBody.error } else { $null } if ($code -ne 400) { throw "Expected HTTP 400, got $code" } if ($errCode -ne 'authorization_pending') { throw "Expected error=authorization_pending (RFC 8628 §3.5), got '$errCode'" } Write-Host " ✓ 400 authorization_pending — RFC 8628 §3.5 polling contract honored" -ForegroundColor Green } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_discovery_jwks.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_discovery_jwks.ps1 ---- # Discovery + JWKS + manual RS256 id_token verification. # Usage: pwsh -File demo_discovery_jwks.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function ConvertFrom-Base64Url([string]$s) { $s = $s.Replace('-','+').Replace('_','/') switch ($s.Length % 4) { 2 { $s += '==' } 3 { $s += '=' } } return [Convert]::FromBase64String($s) } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) Discovery $disc = Measure-Step "1. GET /.well-known/openid-configuration" { Invoke-RestMethod "$BASE/.well-known/openid-configuration" } Write-Host " issuer : $($disc.issuer)" Write-Host " jwks_uri : $($disc.jwks_uri)" Write-Host " grants : $($disc.grant_types_supported -join ', ')" Write-Host " scopes : $($disc.scopes_supported -join ', ')" # 2) JWKS $jwks = Measure-Step "2. GET JWKS" { Invoke-RestMethod $disc.jwks_uri } Write-Host " keys count: $($jwks.keys.Count)" $jwks.keys | ForEach-Object { Write-Host " - kid=$($_.kid) alg=$($_.alg) use=$($_.use) kty=$($_.kty)" } # 3) Need a real id_token to verify — drive password grant. $reg = Measure-Step "3. DCR (password grant client)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "discovery-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email" } | ConvertTo-Json) } $user = "disc_$([Guid]::NewGuid().ToString('N').Substring(0,8))" Measure-Step "4. account/register" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = "Test1234Pass!" displayName = $user } | ConvertTo-Json) } catch { Write-Host " (already exists or non-fatal: $($_.Exception.Message))" -ForegroundColor Yellow } } | Out-Null $tok = Measure-Step "5. password grant" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = "Test1234Pass!" scope = "openid profile email" } } # 4) Verify id_token signature manually $verify = Measure-Step "6. verify id_token RS256 against JWKS" { $parts = $tok.id_token.Split('.') if ($parts.Length -lt 3) { throw "id_token is not a JWS (parts=$($parts.Length))" } $header = [Text.Encoding]::UTF8.GetString((ConvertFrom-Base64Url $parts[0])) | ConvertFrom-Json $key = $jwks.keys | Where-Object { $_.kid -eq $header.kid } | Select-Object -First 1 if (-not $key) { throw "kid $($header.kid) not found in JWKS" } $rsa = [System.Security.Cryptography.RSA]::Create() $rp = New-Object System.Security.Cryptography.RSAParameters $rp.Modulus = ConvertFrom-Base64Url $key.n $rp.Exponent = ConvertFrom-Base64Url $key.e $rsa.ImportParameters($rp) $signed = [Text.Encoding]::ASCII.GetBytes("$($parts[0]).$($parts[1])") $sig = ConvertFrom-Base64Url $parts[2] $ok = $rsa.VerifyData( $signed, $sig, [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) [pscustomobject]@{ kid=$header.kid; alg=$header.alg; valid=$ok } } $verify | Format-Table $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_discovery_shape.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_discovery_shape.ps1 ---- # Discovery shape regression — locks /.well-known/openid-configuration JSON shape. # Probes: # 1. fetch discovery # 2. assert no array property has duplicates (catches the historical # dpop_signing_alg_values_supported double-emit bug) # 3. assert required fields per RFC 8414 §2 / OIDC Discovery §3 are present # 4. assert no advertised secret/internal leak (issuer must NOT contain "REPLACE_ME", # no `*_internal` keys, etc.) # Usage: pwsh -File demo_discovery_shape.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) Fetch discovery as a raw object so we can probe arrays generically. $disc = Measure-Step "1. GET /.well-known/openid-configuration" { Invoke-RestMethod "$BASE/.well-known/openid-configuration" } # 2) Required fields per RFC 8414 §2 / OIDC Discovery §3. $required = @( 'issuer', 'authorization_endpoint', 'token_endpoint', 'jwks_uri', 'response_types_supported', 'subject_types_supported', 'id_token_signing_alg_values_supported' ) $missing = @() foreach ($f in $required) { if (-not $disc.PSObject.Properties.Name.Contains($f)) { $missing += $f } } if ($missing.Count -gt 0) { throw "Discovery missing required fields: $($missing -join ', ')" } Write-Host " ✓ all $($required.Count) required RFC 8414 / OIDC Discovery fields present" -ForegroundColor Green # 3) Dedupe sweep — every advertised array property must have unique values. $arrayProps = $disc.PSObject.Properties | Where-Object { $_.Value -is [System.Collections.IEnumerable] -and $_.Value -isnot [string] } $dupReports = @() foreach ($prop in $arrayProps) { $vals = @($prop.Value | ForEach-Object { if ($_ -is [string] -or $_ -is [int] -or $_ -is [long]) { $_ } elseif ($_ -is [pscustomobject] -and $_.PSObject.Properties.Name.Contains('id')) { "obj:$($_.id)" } else { $null } } | Where-Object { $_ -ne $null }) if ($vals.Count -eq 0) { continue } $unique = $vals | Select-Object -Unique if ($vals.Count -ne $unique.Count) { $dups = $vals | Group-Object | Where-Object { $_.Count -gt 1 } | ForEach-Object { "$($_.Name)×$($_.Count)" } $dupReports += "$($prop.Name) has duplicates: [$($dups -join ', ')]" } } Measure-Step "2. dedupe sweep across array fields" { if ($dupReports.Count -gt 0) { throw "Duplicate values detected:`n " + ($dupReports -join "`n ") } Write-Host " ✓ no duplicates across all advertised array fields" -ForegroundColor Green } | Out-Null # 4) DPoP-specific lock: must be present, must dedupe, must be a subset of the canonical RFC 9449 alg set. Measure-Step "3. dpop_signing_alg_values_supported shape" { if (-not $disc.dpop_signing_alg_values_supported) { throw "dpop_signing_alg_values_supported missing (DPoP advertised as supported but no alg list)" } $algs = @($disc.dpop_signing_alg_values_supported) $uniqueAlgs = $algs | Select-Object -Unique if ($algs.Count -ne $uniqueAlgs.Count) { throw "dpop_signing_alg_values_supported has duplicates: [$($algs -join ', ')]" } $rfcAllowed = @('RS256','RS384','RS512','PS256','PS384','PS512','ES256','ES384','ES512','EdDSA') $bad = $algs | Where-Object { $rfcAllowed -notcontains $_ } if ($bad.Count -gt 0) { throw "dpop_signing_alg_values_supported has non-RFC-9449 algs: $($bad -join ', ')" } Write-Host " ✓ dpop algs deduped, all from RFC 9449 §5 catalog: [$($algs -join ', ')]" -ForegroundColor Green } | Out-Null # 5) Leak guard: issuer/endpoints must not contain placeholder strings, no *_internal keys. Measure-Step "4. leak / placeholder guard" { if ($disc.issuer -match 'REPLACE_ME|TODO|XXX') { throw "issuer contains placeholder: $($disc.issuer)" } $internalKeys = $disc.PSObject.Properties.Name | Where-Object { $_ -match '_internal$|_debug$|_secret$' } if ($internalKeys.Count -gt 0) { throw "discovery exposes internal keys: $($internalKeys -join ', ')" } Write-Host " ✓ no placeholders, no *_internal/*_debug/*_secret keys" -ForegroundColor Green } | Out-Null # 6) RFC 8414 §2 / RFC 7591 §2 — when private_key_jwt is advertised, the matching # *_auth_signing_alg_values_supported field MUST be present (otherwise clients # can't pick an alg that the server will accept). Measure-Step "5. private_key_jwt ↔ *_auth_signing_alg_values_supported coverage" { $assertionAlgFields = @{ token_endpoint_auth_methods_supported = 'token_endpoint_auth_signing_alg_values_supported' introspection_endpoint_auth_methods_supported = 'introspection_endpoint_auth_signing_alg_values_supported' revocation_endpoint_auth_methods_supported = 'revocation_endpoint_auth_signing_alg_values_supported' } $errors = @() foreach ($methodsField in $assertionAlgFields.Keys) { $algField = $assertionAlgFields[$methodsField] $methods = $disc.$methodsField if (-not $methods) { continue } $hasJwt = ($methods -contains 'private_key_jwt') -or ($methods -contains 'client_secret_jwt') if (-not $hasJwt) { continue } $algs = $disc.$algField if (-not $algs -or $algs.Count -eq 0) { $errors += "$methodsField advertises private_key_jwt but $algField is missing/empty" continue } # Must include at least one widely-implemented signing alg. $bridgeAlgs = @('RS256','ES256','PS256') $hasBridge = ($algs | Where-Object { $bridgeAlgs -contains $_ }).Count -gt 0 if (-not $hasBridge) { $errors += "$algField does not include any of RS256/ES256/PS256: [$($algs -join ', ')]" } } if ($errors.Count -gt 0) { throw ($errors -join "`n") } Write-Host " ✓ private_key_jwt advertisement matched by signing-alg list on token/introspect/revoke" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_dpop.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_dpop.ps1 ---- # DPoP — Demonstrating Proof-of-Possession (RFC 9449) end-to-end. # Generates an ephemeral EC P-256 key, binds it to a /connect/token request, # verifies token_type=DPoP in the response, calls /connect/userinfo with an # ath-bound proof, and checks jti replay + wrong-scheme rejection. # Usage: pwsh -File demo_dpop.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # ── Crypto helpers ──────────────────────────────────────────────────────────── # Ephemeral EC P-256 key — one key per demo run (RFC 9449 §2). # Fallback to RSA 2048 if EC P-256 is not available on this platform. $ecPub = $null $rsaPub = $null $keyAlgo = $null try { $ecdsa = [System.Security.Cryptography.ECDsa]::Create( [System.Security.Cryptography.ECCurve]::NamedCurves.nistP256) if ($ecdsa) { $ecPub = $ecdsa.ExportParameters($false) if ($ecPub -and $ecPub.Q -and $ecPub.Q.X -and $ecPub.Q.Y) { $keyAlgo = "EC" } } } catch { Write-Host " EC P-256 not available on this platform" -ForegroundColor Yellow } if (-not $keyAlgo) { Write-Host " Falling back to RSA 2048" -ForegroundColor Yellow $rsa = [System.Security.Cryptography.RSA]::Create(2048) $rsaPub = $rsa.ExportParameters($false) $keyAlgo = "RSA" } function B64U([byte[]]$bytes) { [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=') } function B64UStr([string]$s) { B64U ([Text.Encoding]::UTF8.GetBytes($s)) } if ($keyAlgo -eq "EC") { $jwkX = B64U $ecPub.Q.X $jwkY = B64U $ecPub.Q.Y $jwk = [ordered]@{ kty="EC"; crv="P-256"; x=$jwkX; y=$jwkY } Write-Host " DPoP key (EC P-256)" Write-Host " x=$jwkX" Write-Host " y=$jwkY" } else { $e = B64U $rsaPub.Exponent $n = B64U $rsaPub.Modulus $jwk = [ordered]@{ kty="RSA"; e=$e; n=$n } Write-Host " DPoP key (RSA 2048)" Write-Host " e=$e" Write-Host " n=$($n.Substring(0,32))…" } # DPoP-Nonce issued by server (RFC 9449 §8) — starts null, updated from response headers. $script:dpopNonce = $null function New-DpopProof { param([string]$Htm, [string]$Htu, [string]$Ath = $null) $alg = if ($keyAlgo -eq "EC") { "ES256" } else { "RS256" } $hdr = [ordered]@{ typ="dpop+jwt"; alg=$alg; jwk=$jwk } $pay = [ordered]@{ jti = [Guid]::NewGuid().ToString() htm = $Htm htu = $Htu iat = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() } if ($Ath) { $pay["ath"] = $Ath } if ($script:dpopNonce) { $pay["nonce"] = $script:dpopNonce } $h = B64UStr ($hdr | ConvertTo-Json -Compress) $p = B64UStr ($pay | ConvertTo-Json -Compress) if ($keyAlgo -eq "EC") { $sig = B64U ($ecdsa.SignData( [Text.Encoding]::UTF8.GetBytes("$h.$p"), [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.DSASignatureFormat]::IeeeP1363FixedFieldConcatenation)) } else { $sig = B64U ($rsa.SignData( [Text.Encoding]::UTF8.GetBytes("$h.$p"), [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1)) } return "$h.$p.$sig" } function Get-Ath([string]$token) { B64U ([System.Security.Cryptography.SHA256]::HashData( [Text.Encoding]::ASCII.GetBytes($token))) } function Invoke-TokenWithDpop { param([hashtable]$Body, [string]$Htm = "POST") $url = "$BASE/connect/token" # Use Invoke-WebRequest to capture response headers (DPoP-Nonce). $proof = New-DpopProof -Htm $Htm -Htu $url $wr = Invoke-WebRequest -Method Post $url ` -ContentType "application/x-www-form-urlencoded" ` -Headers @{ DPoP = $proof } ` -Body $Body ` -ErrorAction SilentlyContinue # Capture nonce for subsequent proofs (RFC 9449 §8). $newNonce = $wr.Headers['DPoP-Nonce'] if ($newNonce) { $script:dpopNonce = $newNonce Write-Host " DPoP-Nonce issued by server: $newNonce" -ForegroundColor DarkGray } if ($wr.StatusCode -in 200,201) { return $wr.Content | ConvertFrom-Json } # Server may require a nonce on first call (401 use_dpop_nonce). if ($wr.StatusCode -eq 401 -and $newNonce) { Write-Host " Server challenged with DPoP-Nonce — retrying…" -ForegroundColor Yellow $proof2 = New-DpopProof -Htm $Htm -Htu $url $wr2 = Invoke-WebRequest -Method Post $url ` -ContentType "application/x-www-form-urlencoded" ` -Headers @{ DPoP = $proof2 } ` -Body $Body $n2 = $wr2.Headers['DPoP-Nonce'] if ($n2) { $script:dpopNonce = $n2 } return $wr2.Content | ConvertFrom-Json } throw "Token request failed: $($wr.StatusCode) $($wr.Content)" } # ── Steps ───────────────────────────────────────────────────────────────────── # 1) DCR — register client with password + refresh_token. $reg = Measure-Step "1. DCR /connect/register" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "dpop-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access" } | ConvertTo-Json) } $reg | Format-List client_id, client_secret # 2) Seed user. $user = "dpop_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) } | Out-Null # 3) ROPC /connect/token with DPoP proof — expect token_type=DPoP (RFC 9449 §5-6). $tok = Measure-Step "3. ROPC /connect/token + DPoP proof (expect token_type=DPoP)" { $t = Invoke-TokenWithDpop @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email offline_access" } Write-Host " token_type : $($t.token_type)" if ($t.token_type -eq "DPoP") { Write-Host " ✓ token_type = DPoP" -ForegroundColor Green } else { Write-Host " ! token_type='$($t.token_type)' — expected DPoP; server may not require DPoP for this client" -ForegroundColor Yellow } return $t } Write-Host " access_token : $($tok.access_token.Substring(0,32))…" # 4) GET /connect/userinfo with the DPoP-bound token (RFC 9449 §7.1: the DPoP scheme, a proof with ath). $userinfoUrl = "$BASE/connect/userinfo" Measure-Step "4. GET /connect/userinfo (Authorization: DPoP + DPoP proof)" { $ath = Get-Ath $tok.access_token $proof = New-DpopProof -Htm GET -Htu $userinfoUrl -Ath $ath $ui = Invoke-RestMethod -Method Get $userinfoUrl ` -Headers @{ Authorization = "DPoP $($tok.access_token)" DPoP = $proof } $ui | ConvertTo-Json -Depth 5 | Out-Host if ($ui.sub) { Write-Host " ✓ sub = $($ui.sub)" -ForegroundColor Green } return $ui } | Out-Null # 4b) The same token under the Bearer scheme, even with a valid proof, is refused: RFC 9449 §7.1 binds a DPoP token # to the DPoP scheme, so a token that leaks without its key cannot be replayed as a plain bearer token. Measure-Step "4b. GET /connect/userinfo (Authorization: Bearer ) → 401 invalid_token" { $ath = Get-Ath $tok.access_token $proof = New-DpopProof -Htm GET -Htu $userinfoUrl -Ath $ath $r = Invoke-WebRequest -Method Get $userinfoUrl -SkipHttpErrorCheck ` -Headers @{ Authorization = "Bearer $($tok.access_token)" DPoP = $proof } if ($r.StatusCode -ne 401) { throw "expected 401 for the Bearer scheme, got $($r.StatusCode): $($r.Content)" } if ($r.Content -notmatch 'invalid_token') { throw "expected error invalid_token, got: $($r.Content)" } Write-Host " ✓ Bearer scheme refused: 401 invalid_token" -ForegroundColor Green } | Out-Null # 5) Refresh with DPoP (RFC 9449 §5 — bound refresh_token). $tok2 = Measure-Step "5. refresh_token grant + DPoP" { Invoke-TokenWithDpop @{ grant_type = "refresh_token" client_id = $reg.client_id client_secret = $reg.client_secret refresh_token = $tok.refresh_token } } Write-Host " new access_token : $($tok2.access_token.Substring(0,32))…" if ($tok2.token_type -eq "DPoP") { Write-Host " ✓ refreshed token_type still DPoP" -ForegroundColor Green } # 6) jti replay — same proof header twice → must reject (RFC 9449 §11.1). # We make one real call to seed the jti, then immediately replay the same proof. $replayProof = New-DpopProof -Htm POST -Htu "$BASE/connect/token" $replayBody = @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email" } # Seed first call (ignore result). $null = try { Invoke-WebRequest -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Headers @{ DPoP = $replayProof } -Body $replayBody -ErrorAction SilentlyContinue } catch {} Measure-Step "6. jti replay — same proof twice (expect 400/401 if replay cache active)" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Headers @{ DPoP = $replayProof } -Body $replayBody | Out-Null Write-Host " ! replay NOT rejected — jti replay cache may not be active on /connect/token" -ForegroundColor Yellow } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -in 400,401) { Write-Host " ✓ replay rejected: $code" -ForegroundColor Green } else { Write-Host " unexpected status $code" -ForegroundColor Yellow } } } | Out-Null # 7) Bearer auth with a DPoP-bound token — server should reject (wrong scheme). Measure-Step "7. Bearer scheme with DPoP-bound token (expect 401 — cnf.jkt mismatch)" { try { Invoke-RestMethod -Method Get $userinfoUrl ` -Headers @{ Authorization = "Bearer $($tok.access_token)" } | Out-Null Write-Host " ! DPoP-bound token accepted as Bearer — cnf.jkt NOT enforced at userinfo" -ForegroundColor Yellow } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -eq 401) { Write-Host " ✓ rejected: 401 (DPoP-bound token must not be used as Bearer)" -ForegroundColor Green } else { Write-Host " unexpected status: $code" -ForegroundColor Yellow } } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_federation.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_federation.ps1 ---- # Federation discovery + redirect probe. # Verifies: # 1. /.well-known/openid-configuration advertises `federation_providers` array # 2. /api/v1/identity/federation-providers/public returns the safe projection # (ProviderId, DisplayName, Kind, Priority — never ClientSecret/Authority) # 3. Both lists agree on the set of ProviderIds # 4. GET /connect/external-login?provider=&returnUrl=/ returns 302 with a # Location pointing at the upstream IdP's Authority host (or wraps the # configured ClientId — this demo accepts placeholder REPLACE_ME values # since the goal is to verify the redirect surface, not real IdP login). # Browser/IdP automation is intentionally NOT attempted — that requires a real # upstream IdP and is out of scope for a scriptable demo. # Usage: pwsh -File demo_federation.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) Discovery — pull the federation_providers array. $disc = Measure-Step "1. GET /.well-known/openid-configuration" { Invoke-RestMethod "$BASE/.well-known/openid-configuration" } if (-not $disc.federation_providers -or $disc.federation_providers.Count -eq 0) { Write-Host "Discovery does not advertise any federation_providers." -ForegroundColor Yellow Write-Host "Set Identity:Features:EnableFederation=true and configure FederationProviders[]." -ForegroundColor Yellow Write-Host "Skipping (config issue, not a server bug)." -ForegroundColor DarkGray exit 0 } $discIds = $disc.federation_providers | ForEach-Object { $_.id } | Sort-Object Write-Host " discovery providers: $($discIds -join ', ')" # 2) Public list — JSON projection consumed by relying-party UIs. $pub = Measure-Step "2. GET /api/v1/identity/federation-providers/public" { Invoke-RestMethod "$BASE/api/v1/identity/federation-providers/public" } $pubIds = $pub | ForEach-Object { $_.providerId } | Sort-Object Write-Host " public-list providers: $($pubIds -join ', ')" # Safe-projection guard: the public list must NEVER leak ClientSecret/Authority/Scopes. $leakProps = @('clientSecret','authority','scopes','clientId') $leaks = $pub | ForEach-Object { $row = $_ foreach ($p in $leakProps) { if ($row.PSObject.Properties.Name -contains $p) { "$($row.providerId).$p" } } } if ($leaks.Count -gt 0) { throw "Public federation list leaks server-side fields: $($leaks -join ', ')" } Write-Host " ✓ public projection contains no ClientSecret/Authority/Scopes/ClientId" -ForegroundColor Green # 3) Cross-check: discovery and public list must agree on ProviderIds. if (($discIds -join ',') -ne ($pubIds -join ',')) { throw "Discovery providers ($($discIds -join ',')) ≠ public list ($($pubIds -join ','))" } Write-Host " ✓ discovery + public list agree on $($pubIds.Count) providers" -ForegroundColor Green # 4) Redirect probe — pick the first provider, hit /connect/external-login, # expect HTTP 302 with a Location pointing at *some* upstream URL. # GitHub is excluded — it's OAuth2-only (no OIDC discovery), so the OIDC-based # federation challenge throws fetching .well-known/openid-configuration. The # server's OAuth2-only provider type is a separate code path; this demo probes # the OIDC challenge surface only. $firstId = $pubIds | Where-Object { $_ -ne 'github' } | Select-Object -First 1 if (-not $firstId) { Write-Host " no OIDC provider configured (only github present); skipping redirect probe" -ForegroundColor Yellow $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan exit 0 } $redirectUrl = "$BASE/connect/external-login?provider=$firstId&returnUrl=/" $redirect = Measure-Step "4. GET /connect/external-login?provider=$firstId" { # Raw HttpClient (no auto-redirect, accept the dev TLS cert) so the 302 to the upstream # IdP is observed directly. The upstream Authority may be http://, which would otherwise # trip PowerShell's HTTPS→HTTP redirect guard when the OP runs on an https base. $h = [System.Net.Http.HttpClientHandler]::new() $h.AllowAutoRedirect = $false $h.ServerCertificateCustomValidationCallback = [System.Net.Http.HttpClientHandler]::DangerousAcceptAnyServerCertificateValidator $c = [System.Net.Http.HttpClient]::new($h) try { $resp = $c.GetAsync($redirectUrl).GetAwaiter().GetResult() [pscustomobject]@{ StatusCode = [int]$resp.StatusCode Headers = @{ Location = if ($resp.Headers.Location) { $resp.Headers.Location.ToString() } else { $null } } } } finally { $c.Dispose() } } $status = if ($redirect.StatusCode) { [int]$redirect.StatusCode } else { 0 } $loc = $null if ($redirect.Headers -and $redirect.Headers.Location) { $loc = if ($redirect.Headers.Location -is [string]) { $redirect.Headers.Location } else { ($redirect.Headers.Location | Select-Object -First 1).ToString() } } Write-Host " status : $status" Write-Host " location : $loc" if ($status -lt 300 -or $status -ge 400) { throw "Expected 3xx redirect, got $status" } if ([string]::IsNullOrEmpty($loc)) { throw "Redirect response has no Location header" } # Tolerate REPLACE_ME ClientIds — the URL just needs to be absolute. if ($loc -notmatch '^https?://') { throw "Location is not an absolute URL: $loc" } Write-Host " ✓ 302 with absolute Location URL → IdP redirect surface works" -ForegroundColor Green $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_federation_e2e.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_federation_e2e.ps1 ---- # Federation end-to-end — provision-on-first-login + link-on-replay. # # Closes release-gate item #3. Builds on the existing `demo_federation` redirect-surface # probe by driving the FULL flow end-to-end against a real upstream OIDC IdP: # # 1. provision a federation provider via the admin API pointing at navikt's # mock-oauth2-server (pre-running on the `rinat-net` docker network at :9199) # 2. discovery + public list assert the provider surfaces correctly # 3. initiate `/connect/external-login` → follow 302 to mock IdP `/authorize` # 4. POST the mock IdP login form (auto-issues code+state on the configured redirect_uri) # 5. follow the callback back into identity → identity provisions user + sets session, # 302 to returnUrl # 6. admin-side: query users → assert the new user exists with the IdP's email claim # 7. replay the entire challenge/callback → assert NO duplicate user is created # (link-on-replay contract — the federated_identity row matches and login reuses it) # 8. cleanup (delete user, delete provider, delete admin DCR) # # Requires `route-mock-oauth2` (navikt/mock-oauth2-server) reachable at # http://localhost:9199/default. If absent the demo prints a skip message and exits 0 # (so run_all stays green on machines that don't have the dev compose stack up). # # Usage: pwsh -File demo_federation_e2e.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true # Use 127.0.0.1 — mock-oauth2-server's discovery doc embeds 127.0.0.1 in issuer / authorize_endpoint, # and OIDC clients refuse responses where the issuer doesn't match the configured authority. $IDP = "http://127.0.0.1:9199/default" $PROV = "mock-idp-e2e" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } # Single-hop request via curl.exe — no auto-redirect, returns status + Location + body. function Hop { param( [string]$Method, [string]$Url, $Body = $null, [hashtable]$Headers = $null, [string]$ContentType = $null ) # NOTE: don't name this `$args` — pwsh aliases that to the function's argument array # and `& curl.exe @args` then splats the original args, not our list. # Also UPPER-CASE the HTTP method — servers are case-sensitive per RFC 7230 §3.1.1. $curlArgs = @('-s', '-k', '-i', '-m', '10', '-X', $Method.ToUpperInvariant()) if ($Headers) { foreach ($k in $Headers.Keys) { $curlArgs += @('-H', "$($k): $($Headers[$k])") } } $tempBodyFile = $null if ($null -ne $Body) { if ($Body -is [hashtable]) { $ct = if ($ContentType) { $ContentType } else { 'application/x-www-form-urlencoded' } $curlArgs += @('-H', "Content-Type: $ct") $parts = $Body.GetEnumerator() | ForEach-Object { "$([Uri]::EscapeDataString($_.Key))=$([Uri]::EscapeDataString([string]$_.Value))" } $payload = $parts -join '&' } elseif ($Body -is [string]) { $ct = if ($ContentType) { $ContentType } else { 'application/json' } $curlArgs += @('-H', "Content-Type: $ct") $payload = $Body } else { $ct = if ($ContentType) { $ContentType } else { 'application/json' } $curlArgs += @('-H', "Content-Type: $ct") $payload = ($Body | ConvertTo-Json -Depth 6 -Compress) } $tempBodyFile = New-TemporaryFile [System.IO.File]::WriteAllText($tempBodyFile, $payload, (New-Object System.Text.UTF8Encoding($false))) $curlArgs += @('--data-binary', "@$tempBodyFile") } $curlArgs += $Url try { $raw = & curl.exe @curlArgs } finally { if ($tempBodyFile) { Remove-Item $tempBodyFile -ErrorAction SilentlyContinue } } $text = ($raw -join "`n") # Split headers / body on first blank line. $sepIdx = $text.IndexOf("`n`n") $headerSection = if ($sepIdx -gt 0) { $text.Substring(0, $sepIdx) } else { $text } $bodySection = if ($sepIdx -gt 0) { $text.Substring($sepIdx + 2) } else { "" } # Status line $firstLine = ($headerSection -split "`n")[0] $statusCode = 0 if ($firstLine -match 'HTTP/\S+\s+(\d+)') { $statusCode = [int]$matches[1] } # Location header $location = $null foreach ($h in ($headerSection -split "`n")) { if ($h -match '^[Ll]ocation:\s*(.+?)\s*$') { $location = $matches[1]; break } } return [pscustomobject]@{ StatusCode = $statusCode Location = $location Content = $bodySection Headers = $headerSection } } # IRM/IWR substitute via curl.exe — pwsh's HTTP stack hangs against some redb.Identity # admin endpoints (suspected HTTP/2 vs chunked-with-custom-headers interaction) but # curl.exe handles them in ~100ms. Returns parsed JSON object, throws structured error # string on non-2xx so calling code can pattern-match. function Get-Json { param([string]$Method, [string]$Url, $Body = $null, [hashtable]$Headers = $null, [string]$ContentType = "application/json") $curlArgs = @('-s', '-k', '-m', '15', '-w', '||%{http_code}||', '-X', $Method.ToUpperInvariant()) if ($Headers) { foreach ($k in $Headers.Keys) { $curlArgs += @('-H', "$($k): $($Headers[$k])") } } $tempBodyFile = $null if ($null -ne $Body) { $curlArgs += @('-H', "Content-Type: $ContentType") $payload = if ($Body -is [string]) { $Body } else { $Body | ConvertTo-Json -Depth 6 -Compress } $tempBodyFile = New-TemporaryFile [System.IO.File]::WriteAllText($tempBodyFile, $payload, (New-Object System.Text.UTF8Encoding($false))) $curlArgs += @('--data-binary', "@$tempBodyFile") } $curlArgs += $Url try { $raw = & curl.exe @curlArgs } finally { if ($tempBodyFile) { Remove-Item $tempBodyFile -ErrorAction SilentlyContinue } } if ($null -eq $raw) { throw "curl returned no output for $Method $Url" } $text = ($raw -join "`n") # Marker form is `||NNN||` appended after body. Find the OPENING marker so body # stays unchanged even if it happens to contain '||' literals. $markerIdx = $text.LastIndexOf('||', $text.Length - 1) # Walk back to the start of the marker triplet: find the LAST occurrence where the # remainder is just digits + '||'. $m = [regex]::Match($text, '\|\|(\d{3})\|\|\s*$') if (-not $m.Success) { throw "curl marker missing in: $text" } $bodyOut = $text.Substring(0, $m.Index) $status = [int]$m.Groups[1].Value if ($status -ge 400) { throw "HTTP $status $Method $Url : $bodyOut" } if (-not $bodyOut -or $bodyOut.Length -eq 0) { return $null } return $bodyOut | ConvertFrom-Json -Depth 8 } $total = [System.Diagnostics.Stopwatch]::StartNew() # 0) Skip if mock IdP not reachable — keeps run_all green on bare machines. try { $r = Hop -Method Get -Url "$IDP/.well-known/openid-configuration" if ($r.StatusCode -ne 200) { throw "status $($r.StatusCode)" } } catch { Write-Host "" Write-Host "mock-oauth2-server not reachable at $IDP — skipping e2e federation demo." -ForegroundColor Yellow Write-Host "Start it via:" -ForegroundColor DarkGray Write-Host " docker run -p 9199:8080 ghcr.io/navikt/mock-oauth2-server:2.1.10" -ForegroundColor DarkGray exit 0 } Write-Host "mock IdP at $IDP reachable, proceeding." -ForegroundColor DarkGray # The OP-issued federation callback targets the OP's ISSUER host, and our session cookies are # bound to whatever host we drive — so if the two differ (e.g. the conformance context.json pins # the issuer to host.docker.internal while we started on 127.0.0.1) the cross-host callback can't # complete. Re-target to the issuer host so the FULL end-to-end flow — real requests and all — # actually runs. Only skip if that issuer isn't reachable from here. try { $__disc = Get-Json -Method Get -Url "$BASE/.well-known/openid-configuration" $__issuerUri = [uri]$__disc.issuer if ($__issuerUri.Host -and $__issuerUri.Host -ne ([uri]$BASE).Host) { $__issuerBase = "$($__issuerUri.Scheme)://$($__issuerUri.Host):$($__issuerUri.Port)" $__reachable = $false try { $__reachable = $null -ne (Get-Json -Method Get -Url "$__issuerBase/.well-known/openid-configuration").issuer } catch {} if ($__reachable) { Write-Host "Re-targeting to the OP issuer host ($($__issuerUri.Host)) so the federation callback lines up." -ForegroundColor DarkGray $BASE = $__issuerBase } else { Write-Host "" Write-Host "OP issuer host ($($__issuerUri.Host)) differs from the base and isn't reachable here — skipping." -ForegroundColor Yellow Write-Host "Re-run with IDENTITY_BASE pointed at the issuer to exercise the full flow." -ForegroundColor DarkGray exit 0 } } } catch {} # 1) DCR admin (just users.manage — we use it to verify provisioning + cleanup). $adminReg = Measure-Step "1. DCR admin (users.manage)" { $r = Get-Json -Method Post -Url "$BASE/connect/register" -Headers $DCR_AUTH -Body @{ client_name = "fed-e2e" grant_types = @("client_credentials") scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write" } Write-Host " client_id: $($r.client_id)" return $r } $ADMIN_RAT = $adminReg.registration_access_token $ADMIN_RCU = $adminReg.registration_client_uri $adminTok = Measure-Step "2. admin cc token" { $form = "grant_type=client_credentials&client_id=$([Uri]::EscapeDataString($adminReg.client_id))" + "&client_secret=$([Uri]::EscapeDataString($adminReg.client_secret))" + "&scope=$([Uri]::EscapeDataString('identity:users:write identity:groups:write identity:consents:write identity:mfa:write'))" Get-Json -Method Post -Url "$BASE/connect/token" -Body $form -ContentType "application/x-www-form-urlencoded" } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)" } # 3) Discovery advertises the mock provider (configured statically in context.json). Measure-Step "3. discovery + public list advertise $PROV" { $d = Get-Json -Method Get -Url "$BASE/.well-known/openid-configuration" $ids = $d.federation_providers | ForEach-Object { $_.id } if ($ids -notcontains $PROV) { throw "discovery missing $PROV — got [$($ids -join ',')]" } $p = Get-Json -Method Get -Url "$BASE/api/v1/identity/federation-providers/public" $pubIds = $p | ForEach-Object { $_.providerId } if ($pubIds -notcontains $PROV) { throw "public list missing $PROV — got [$($pubIds -join ',')]" } Write-Host " discovery + public list OK" -ForegroundColor Green } | Out-Null # Helper: drive one full challenge → callback round-trip end-to-end, return the email # that mock IdP issued (so we can verify the provisioned user). function Invoke-FederationRoundTrip { param([string]$Username, [hashtable]$Claims) # Step A: challenge — identity issues 302 to mock IdP /authorize with our encrypted state. $r1 = Hop -Method Get -Url "$BASE/connect/external-login?provider=$PROV&returnUrl=/" if ($r1.StatusCode -lt 300 -or $r1.StatusCode -ge 400) { $snippet = if ($r1.Content) { $r1.Content.Substring(0, [Math]::Min(200,$r1.Content.Length)) } else { "(no body)" } throw "challenge returned $($r1.StatusCode), expected 3xx (body: $snippet)" } $idpUrl = $r1.Location if (-not $idpUrl) { throw "challenge response has no Location header" } if (-not $idpUrl.StartsWith($IDP)) { throw "challenge redirect to '$idpUrl' is not the mock IdP" } # Step B: post the mock-oauth2-server login form. $r2 = Hop -Method Post -Url $idpUrl -Body @{ username = $Username claims = ($Claims | ConvertTo-Json -Compress) } if ($r2.StatusCode -ne 302) { throw "mock IdP /authorize returned $($r2.StatusCode), expected 302" } $callbackUrl = $r2.Location if (-not $callbackUrl.StartsWith("$BASE/connect/federation/callback")) { throw "mock IdP redirected to '$callbackUrl', expected our callback" } # Step C: identity processes callback. $r3 = Hop -Method Get -Url $callbackUrl if ($r3.StatusCode -ge 400) { $err = if ($r3.Content) { $r3.Content.Substring(0, [Math]::Min(300, $r3.Content.Length)) } else { "(no body)" } throw "callback returned $($r3.StatusCode): $err" } if ($r3.StatusCode -lt 300) { throw "callback returned $($r3.StatusCode), expected 302 (no provision happened)" } return $r3.Location } # 4) First login — IdP issues a fresh email; identity should PROVISION a new user. $email1 = "fed-e2e-$([Guid]::NewGuid().ToString('N').Substring(0,8))@example.com" $name1 = "Federated User" Measure-Step "4. challenge → IdP login → callback (provision-on-first-login)" { $final = Invoke-FederationRoundTrip -Username $email1 -Claims @{ email = $email1 email_verified = $true name = $name1 sub = "mock-sub-$($email1.GetHashCode())" } Write-Host " final redirect: $final" -ForegroundColor DarkGray Write-Host " IdP email: $email1" -ForegroundColor Green } | Out-Null # 5) Admin-side verification — user was provisioned with the IdP's email. $user = Measure-Step "5. admin search users → assert provisioned user exists" { $r = Get-Json -Method Get -Url "$BASE/api/v1/identity/users/search?query=$([Uri]::EscapeDataString($email1))" -Headers $ADMIN $hits = if ($r.items) { $r.items } elseif ($r.results) { $r.results } else { $r } $found = $hits | Where-Object { $_.email -eq $email1 } | Select-Object -First 1 if (-not $found) { throw "user $email1 not found after federation flow (provision-on-first-login broken)" } Write-Host " user id: $($found.id), email: $($found.email), name: $($found.displayName ?? $found.name)" -ForegroundColor Green return $found } # 6) Replay: same flow, same email — assert user count unchanged (link reused, no dup). $baselineCount = Measure-Step "6a. baseline user count (before replay)" { $r = Get-Json -Method Get -Url "$BASE/api/v1/identity/users?count=500" -Headers $ADMIN $n = if ($r.items) { @($r.items).Count } elseif ($r.totalCount) { [int]$r.totalCount } else { @($r).Count } Write-Host " baseline: $n users" return $n } Measure-Step "6b. replay same IdP login → assert SAME user (no duplicate)" { Invoke-FederationRoundTrip -Username $email1 -Claims @{ email = $email1 email_verified = $true name = $name1 sub = "mock-sub-$($email1.GetHashCode())" } | Out-Null $r = Get-Json -Method Get -Url "$BASE/api/v1/identity/users?count=500" -Headers $ADMIN $n = if ($r.items) { @($r.items).Count } elseif ($r.totalCount) { [int]$r.totalCount } else { @($r).Count } if ($n -ne $baselineCount) { throw "replay created a duplicate user (was $baselineCount, now $n)" } Write-Host " user count unchanged ($n) — link reused" -ForegroundColor Green } | Out-Null # 7) Cleanup. Measure-Step "7. cleanup: delete user + admin DCR" { try { Get-Json -Method Delete -Url "$BASE/api/v1/identity/users/$($user.id)" -Headers $ADMIN | Out-Null } catch { Write-Host " user delete: $($_.Exception.Message)" -ForegroundColor Yellow } if ($ADMIN_RAT) { try { Get-Json -Method Delete -Url $ADMIN_RCU -Headers @{ Authorization = "Bearer $ADMIN_RAT" } | Out-Null } catch { Write-Host " admin DCR delete: $($_.Exception.Message)" -ForegroundColor Yellow } } Write-Host " cleaned" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_federation_github.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_federation_github.ps1 ---- # GitHub OAuth2-only federation end-to-end against a self-hosted mock. # # Closes the last ❌ in the federation matrix section. The standard mock-oauth2-server # in our docker compose is OIDC-only — it issues id_tokens and exposes a discovery # document. GitHub OAuth2 has neither: no discovery, no id_token, no /userinfo (the # profile + emails come from the REST API at /user and /user/emails). Our # GitHubFederatedAuthProvider implements that flow against github.com endpoints; this # demo points it at a local pwsh-hosted HttpListener that emulates each one. # # Flow: # 1. Spin up the mock GitHub on http://127.0.0.1:9201 inside this script (background # pwsh job). It serves: # GET /login/oauth/authorize — 302 redirect to redirect_uri with code+state # POST /login/oauth/access_token — form body, returns {access_token, token_type, scope} # GET /user — Bearer auth, returns {id, login, name, email} # GET /user/emails — Bearer auth, returns [{email, primary, verified, visibility}] # 2. /.well-known/openid-configuration → assert mock-github-e2e in federation_providers # 3. GET /connect/external-login?provider=mock-github-e2e&returnUrl=/ → 302 to mock # 4. Follow the mock's auto-issued code → identity callback # 5. identity provisions the user from the GitHub-shaped claims # 6. Admin search confirms the new user with github-supplied email + display name # 7. Cleanup # # Skips with exit=0 when the mock IdP port is already taken or the demo can't bind. # Skips when redb.Identity doesn't advertise the mock-github-e2e provider yet (e.g. # operator removed it for production). #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $PROV = "mock-github-e2e" $MOCK_PORT = 9201 $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } # curl-based helpers (pwsh IRM hangs against some identity admin endpoints — same issue # as in demo_federation_e2e). Single-hop, no auto-redirect. function Hop { param([string]$Method, [string]$Url, $Body = $null, [hashtable]$Headers = $null, [string]$ContentType = $null) $curlArgs = @('-s', '-k', '-i', '-m', '15', '-X', $Method.ToUpperInvariant()) if ($Headers) { foreach ($k in $Headers.Keys) { $curlArgs += @('-H', "$($k): $($Headers[$k])") } } $tempBodyFile = $null if ($null -ne $Body) { if ($Body -is [hashtable]) { $ct = if ($ContentType) { $ContentType } else { 'application/x-www-form-urlencoded' } $curlArgs += @('-H', "Content-Type: $ct") $parts = $Body.GetEnumerator() | ForEach-Object { "$([Uri]::EscapeDataString($_.Key))=$([Uri]::EscapeDataString([string]$_.Value))" } $payload = $parts -join '&' } else { $ct = if ($ContentType) { $ContentType } else { 'application/json' } $curlArgs += @('-H', "Content-Type: $ct") $payload = if ($Body -is [string]) { $Body } else { $Body | ConvertTo-Json -Depth 6 -Compress } } $tempBodyFile = New-TemporaryFile [System.IO.File]::WriteAllText($tempBodyFile, $payload, (New-Object System.Text.UTF8Encoding($false))) $curlArgs += @('--data-binary', "@$tempBodyFile") } $curlArgs += $Url try { $raw = & curl.exe @curlArgs } finally { if ($tempBodyFile) { Remove-Item $tempBodyFile -ErrorAction SilentlyContinue } } $text = ($raw -join "`n") $sepIdx = $text.IndexOf("`n`n") $headerSection = if ($sepIdx -gt 0) { $text.Substring(0, $sepIdx) } else { $text } $bodySection = if ($sepIdx -gt 0) { $text.Substring($sepIdx + 2) } else { "" } $statusCode = 0 $firstLine = ($headerSection -split "`n")[0] if ($firstLine -match 'HTTP/\S+\s+(\d+)') { $statusCode = [int]$matches[1] } $location = $null foreach ($h in ($headerSection -split "`n")) { if ($h -match '^[Ll]ocation:\s*(.+?)\s*$') { $location = $matches[1]; break } } return [pscustomobject]@{ StatusCode = $statusCode; Location = $location; Content = $bodySection } } function Get-Json { param([string]$Method, [string]$Url, $Body = $null, [hashtable]$Headers = $null, [string]$ContentType = "application/json") $curlArgs = @('-s', '-k', '-m', '15', '-w', '||%{http_code}||', '-X', $Method.ToUpperInvariant()) if ($Headers) { foreach ($k in $Headers.Keys) { $curlArgs += @('-H', "$($k): $($Headers[$k])") } } $tempBodyFile = $null if ($null -ne $Body) { $curlArgs += @('-H', "Content-Type: $ContentType") $payload = if ($Body -is [string]) { $Body } else { $Body | ConvertTo-Json -Depth 6 -Compress } $tempBodyFile = New-TemporaryFile [System.IO.File]::WriteAllText($tempBodyFile, $payload, (New-Object System.Text.UTF8Encoding($false))) $curlArgs += @('--data-binary', "@$tempBodyFile") } $curlArgs += $Url try { $raw = & curl.exe @curlArgs } finally { if ($tempBodyFile) { Remove-Item $tempBodyFile -ErrorAction SilentlyContinue } } if ($null -eq $raw) { throw "curl returned no output for $Method $Url" } $text = ($raw -join "`n") $m = [regex]::Match($text, '\|\|(\d{3})\|\|\s*$') if (-not $m.Success) { throw "curl marker missing in: $text" } $bodyOut = $text.Substring(0, $m.Index) $status = [int]$m.Groups[1].Value if ($status -ge 400) { throw "HTTP $status $Method $Url : $bodyOut" } if (-not $bodyOut -or $bodyOut.Length -eq 0) { return $null } return $bodyOut | ConvertFrom-Json -Depth 8 } # --- mock GitHub HttpListener job ------------------------------------------------- # We script the mock as a single scriptblock that runs in a background pwsh job. The # parent process tells the mock what user shape to issue via env vars before triggering # /authorize, and the job listens until $stop signal (env GH_MOCK_STOP). # Both `id` (external_id used by federation to match the federated_identity row) and # `email` are randomised per run so re-runs in run_all don't pick up the existing link # from a previous run and short-circuit to "log in as existing user" — which would # leave search-by-new-email empty. $rnd = [Guid]::NewGuid().ToString('N').Substring(0,6) $mockUser = @{ id = [int](Get-Random -Minimum 1000000 -Maximum 99999999) login = "octofake-$rnd" name = "Octofake Fakerton" email = "octofake-$rnd@example.com" } $mockJob = Start-Job -Name "demo-mock-github" -ArgumentList $MOCK_PORT, $mockUser -ScriptBlock { param([int]$Port, [hashtable]$User) Add-Type -AssemblyName System.Net.HttpListener $listener = [System.Net.HttpListener]::new() $listener.Prefixes.Add("http://127.0.0.1:$Port/") try { $listener.Start() } catch { Write-Output "MOCK_BIND_FAILED: $($_.Exception.Message)"; return } # In-memory store of authorization codes -> user shape (one-shot exchange). $codes = [System.Collections.Concurrent.ConcurrentDictionary[string,hashtable]]::new() $accessTokens = [System.Collections.Concurrent.ConcurrentDictionary[string,hashtable]]::new() Write-Output "MOCK_READY" while ($listener.IsListening) { try { $ctx = $listener.GetContext() } catch { break } try { $req = $ctx.Request $res = $ctx.Response $path = $req.Url.AbsolutePath $method = $req.HttpMethod.ToUpperInvariant() switch -Regex ("$method $path") { # GET /__shutdown — sentinel used by the demo's finally{} block to break the # blocking GetContext() loop cleanly so Stop-Job doesn't wait the default # 2-minute timeout before force-killing. '^GET /__shutdown$' { $res.StatusCode = 200 $res.OutputStream.Close() $listener.Stop() break } # GET /login/oauth/authorize?client_id=...&redirect_uri=...&scope=...&state=...&code_challenge=... '^GET /login/oauth/authorize$' { $q = [System.Web.HttpUtility]::ParseQueryString($req.Url.Query) $redirect = $q["redirect_uri"] $state = $q["state"] if (-not $redirect) { $res.StatusCode = 400; $res.OutputStream.Close(); break } $code = [Guid]::NewGuid().ToString("N") $null = $codes.TryAdd($code, $User) $sep = if ($redirect -match '\?') { '&' } else { '?' } $loc = "$redirect$($sep)code=$([Uri]::EscapeDataString($code))&state=$([Uri]::EscapeDataString($state))" $res.StatusCode = 302 $res.Headers["Location"] = $loc $res.OutputStream.Close() break } # POST /login/oauth/access_token (form-encoded: code, client_id, client_secret, redirect_uri, code_verifier?) '^POST /login/oauth/access_token$' { $sr = New-Object System.IO.StreamReader($req.InputStream, $req.ContentEncoding) $body = $sr.ReadToEnd() $form = [System.Web.HttpUtility]::ParseQueryString($body) $code = $form["code"] $found = $null if ($code -and $codes.TryRemove($code, [ref]$found)) { $tok = "gha_" + [Guid]::NewGuid().ToString("N") $null = $accessTokens.TryAdd($tok, $found) $json = "{`"access_token`":`"$tok`",`"token_type`":`"bearer`",`"scope`":`"read:user user:email`"}" $bytes = [Text.Encoding]::UTF8.GetBytes($json) $res.StatusCode = 200 $res.ContentType = "application/json" $res.OutputStream.Write($bytes, 0, $bytes.Length) } else { $bytes = [Text.Encoding]::UTF8.GetBytes('{"error":"bad_verification_code"}') # GitHub returns 200 + error JSON (NOT 400). We mirror that to exercise the # provider's explicit IsSuccessStatusCode + token == null check. $res.StatusCode = 200 $res.ContentType = "application/json" $res.OutputStream.Write($bytes, 0, $bytes.Length) } $res.OutputStream.Close() break } # GET /user (Bearer auth → profile shape) '^GET /user$' { $auth = $req.Headers["Authorization"] $tok = if ($auth -match '^Bearer\s+(.+)$') { $matches[1] } else { $null } $u = $null if ($tok -and $accessTokens.TryGetValue($tok, [ref]$u)) { $json = ([pscustomobject]@{ id = $u.id; login = $u.login; name = $u.name; email = $u.email } | ConvertTo-Json -Compress) $bytes = [Text.Encoding]::UTF8.GetBytes($json) $res.StatusCode = 200 $res.ContentType = "application/vnd.github+json" $res.OutputStream.Write($bytes, 0, $bytes.Length) } else { $res.StatusCode = 401 } $res.OutputStream.Close() break } # GET /user/emails (Bearer auth → email array; only used when profile.email is private) '^GET /user/emails$' { $auth = $req.Headers["Authorization"] $tok = if ($auth -match '^Bearer\s+(.+)$') { $matches[1] } else { $null } $u = $null if ($tok -and $accessTokens.TryGetValue($tok, [ref]$u)) { $json = (@(@{ email = $u.email; primary = $true; verified = $true; visibility = "public" }) | ConvertTo-Json -Compress) # GitHub returns an array — ensure root is `[...]` not `{...}`. if ($json -notmatch '^\[') { $json = "[$json]" } $bytes = [Text.Encoding]::UTF8.GetBytes($json) $res.StatusCode = 200 $res.ContentType = "application/vnd.github+json" $res.OutputStream.Write($bytes, 0, $bytes.Length) } else { $res.StatusCode = 401 } $res.OutputStream.Close() break } default { $res.StatusCode = 404 $res.OutputStream.Close() } } } catch { try { $ctx.Response.StatusCode = 500; $ctx.Response.OutputStream.Close() } catch {} } } } # Wait for MOCK_READY (or MOCK_BIND_FAILED). $ready = $false $boundFailed = $false for ($i = 0; $i -lt 30 -and -not $ready -and -not $boundFailed; $i++) { Start-Sleep -Milliseconds 200 $out = Receive-Job $mockJob -Keep | Out-String if ($out -match 'MOCK_BIND_FAILED') { $boundFailed = $true } if ($out -match 'MOCK_READY') { $ready = $true } } if ($boundFailed -or -not $ready) { Write-Host "Mock GitHub failed to bind on port $MOCK_PORT — likely port already in use. Skipping." -ForegroundColor Yellow Stop-Job $mockJob -ErrorAction SilentlyContinue Remove-Job $mockJob -ErrorAction SilentlyContinue exit 0 } Write-Host "mock GitHub running on http://127.0.0.1:$MOCK_PORT" -ForegroundColor DarkGray try { $total = [System.Diagnostics.Stopwatch]::StartNew() # 0) Discovery must advertise mock-github-e2e — operator may have removed it for prod. $advertised = Measure-Step "0. discovery advertises $PROV" { $d = Get-Json -Method Get -Url "$BASE/.well-known/openid-configuration" $ids = $d.federation_providers | ForEach-Object { $_.id } if ($ids -notcontains $PROV) { Write-Host " $PROV not in federation_providers — skipping (operator removed it). ids: [$($ids -join ',')]" -ForegroundColor Yellow return $false } Write-Host " $PROV advertised" -ForegroundColor Green return $true } if (-not $advertised) { exit 0 } # The OP-issued federation callback targets the OP's ISSUER host; our cookies are bound to # whatever host we drive. If they differ (e.g. the conformance context.json pins the issuer to # host.docker.internal while we started on 127.0.0.1), re-target to the issuer so the FULL # end-to-end flow — real requests and all — actually runs. Only skip if it isn't reachable. $__disc = Get-Json -Method Get -Url "$BASE/.well-known/openid-configuration" $__issuerUri = [uri]$__disc.issuer if ($__issuerUri.Host -and $__issuerUri.Host -ne ([uri]$BASE).Host) { $__issuerBase = "$($__issuerUri.Scheme)://$($__issuerUri.Host):$($__issuerUri.Port)" $__reachable = $false try { $__reachable = $null -ne (Get-Json -Method Get -Url "$__issuerBase/.well-known/openid-configuration").issuer } catch {} if ($__reachable) { Write-Host "Re-targeting to the OP issuer host ($($__issuerUri.Host)) so the federation callback lines up." -ForegroundColor DarkGray $BASE = $__issuerBase } else { Write-Host "" Write-Host "OP issuer host ($($__issuerUri.Host)) differs from the base and isn't reachable here — skipping." -ForegroundColor Yellow exit 0 } } # 1) DCR admin client for verification. $adminReg = Measure-Step "1. DCR admin client (users.manage)" { Get-Json -Method Post -Url "$BASE/connect/register" -Headers $DCR_AUTH -Body @{ client_name = "fed-github-e2e" grant_types = @("client_credentials") scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write" } } $A_RAT = $adminReg.registration_access_token $A_RCU = $adminReg.registration_client_uri $adminTok = Measure-Step "2. admin cc token" { $form = "grant_type=client_credentials&client_id=$([Uri]::EscapeDataString($adminReg.client_id))" + "&client_secret=$([Uri]::EscapeDataString($adminReg.client_secret))" + "&scope=$([Uri]::EscapeDataString('identity:users:write identity:groups:write identity:consents:write identity:mfa:write'))" Get-Json -Method Post -Url "$BASE/connect/token" -Body $form -ContentType "application/x-www-form-urlencoded" } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)" } # 2) Initiate the GitHub-style challenge. $r1 = Measure-Step "3. GET /connect/external-login?provider=$PROV → 302 to mock /authorize" { $r = Hop -Method Get -Url "$BASE/connect/external-login?provider=$PROV&returnUrl=/" if ($r.StatusCode -lt 300 -or $r.StatusCode -ge 400) { throw "challenge status $($r.StatusCode)" } if (-not $r.Location.StartsWith("http://127.0.0.1:$MOCK_PORT")) { throw "challenge redirect to '$($r.Location)' is not our mock" } Write-Host " 302 → $($r.Location.Substring(0,[Math]::Min(140,$r.Location.Length)))..." -ForegroundColor Green return $r } # 3) Follow the mock's /authorize — it returns 302 to our callback with code+state. $r2 = Measure-Step "4. mock /authorize → 302 callback with code+state" { $r = Hop -Method Get -Url $r1.Location if ($r.StatusCode -ne 302) { throw "mock authorize returned $($r.StatusCode)" } if (-not $r.Location.StartsWith("$BASE/connect/federation/callback")) { throw "mock didn't redirect to our callback, got: $($r.Location)" } return $r } # 4) Hit the callback → identity exchanges code, fetches /user + /user/emails, provisions. $r3 = Measure-Step "5. GET /connect/federation/callback → identity provisions user" { $r = Hop -Method Get -Url $r2.Location if ($r.StatusCode -ge 400) { $err = if ($r.Content) { $r.Content.Substring(0, [Math]::Min(300, $r.Content.Length)) } else { "(no body)" } throw "callback status $($r.StatusCode): $err" } Write-Host " callback status=$($r.StatusCode), location=$($r.Location)" -ForegroundColor Green return $r } # 5) Admin-side: verify user was provisioned with the mock-supplied email. Measure-Step "6. admin search users by email → provisioned user found" { $r = Get-Json -Method Get -Url "$BASE/api/v1/identity/users/search?query=$([Uri]::EscapeDataString($mockUser.email))" -Headers $ADMIN $hits = if ($r.items) { $r.items } else { $r } $found = @($hits | Where-Object { $_.email -eq $mockUser.email }) if ($found.Count -eq 0) { throw "user with email $($mockUser.email) not found in admin search (GitHub flow didn't provision)" } Write-Host " user id=$($found[0].id), email=$($found[0].email), name=$($found[0].displayName ?? $found[0].name)" -ForegroundColor Green } | Out-Null Measure-Step "7. cleanup: DELETE admin DCR" { if ($A_RAT) { try { Get-Json -Method Delete -Url $A_RCU -Headers @{ Authorization = "Bearer $A_RAT" } | Out-Null } catch {} } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan } finally { # Always tear down the mock so subsequent runs (and run_all) can re-bind the port. # The listener loop is parked in a blocking HttpListener.GetContext() call. Stop-Job # sends a runspace-close signal that DOES NOT interrupt that native syscall — # PowerShell waits 2 min for the loop to notice and then force-terminates, which is # what made the demo report ~120 s wall-clock when the actual asserts finished in # ~1.5 s. Unblock GetContext() first by hitting any URL on the mock — the loop # exits its current iteration, IsListening flips to false on Stop-Job, and the # next-iteration check exits cleanly. try { # Best-effort wake-up. 1 s timeout so a dead/already-stopped mock doesn't add # any extra delay. We don't care about the response. Invoke-WebRequest -Uri "http://127.0.0.1:$MOCK_PORT/__shutdown" ` -Method Get -TimeoutSec 1 -UseBasicParsing -SkipHttpErrorCheck -ErrorAction SilentlyContinue | Out-Null } catch { } Stop-Job $mockJob -ErrorAction SilentlyContinue | Out-Null Remove-Job $mockJob -Force -ErrorAction SilentlyContinue | Out-Null } Path: redb-identity/demos/demo_federation_link_unlink.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_federation_link_unlink.ps1 ---- # Federation link + unlink — closes 3 remaining ❌ in the federation matrix section: # • Link-to-existing-user (via email match → email_conflict error path) # • Self-service link-challenge → callback → identity linked to existing user # • Unlink provider (DELETE /me/federated-identities/{providerId}) # • Last-credential-method protection (refuses to unlink the only sign-in method) # # Builds on demo_federation_e2e infrastructure (curl.exe via Hop/Get-Json helpers, mock # IdP at http://127.0.0.1:9199/default, the static mock-idp-e2e federation provider). # # Steps: # 1. DCR password client + admin client # 2. Self-register user X with email + password (local credential) # 3. Federation login as X with SAME email via mock IdP → assert email_conflict error # (server refuses to auto-link; front-end must drive explicit link via /me/...) # 4. ROPC X → bearer token (so X can authenticate to /me APIs) # 5. GET /me/federated-identities → empty list (no link yet) # 6. POST /me/federated-identities/link-challenge → 200 with redirect URL to mock IdP # 7. POST mock IdP /authorize with X's email → callback gets code + state # 8. Hit callback → assert {success:true, linked:true, userId=X.id, providerId} # 9. GET /me/federated-identities → 1 entry with providerId + externalSub # 10. DELETE /me/federated-identities/{providerId} → success (X still has local password) # 11. GET /me/federated-identities → 0 entries # 12. Re-link (steps 6-8 redux) — sanity that unlink doesn't break re-link # 13. Admin deletes X's password → only credential left is the federated link # 14. Self-service DELETE link → expect last_credential_method refusal # 15. Cleanup (DELETE X via admin, DELETE DCRs) # # Skips with exit=0 if mock IdP not reachable (compose stack not up). #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $IDP = "http://127.0.0.1:9199/default" $PROV = "mock-idp-e2e" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } function Hop { param([string]$Method, [string]$Url, $Body = $null, [hashtable]$Headers = $null, [string]$ContentType = $null) $curlArgs = @('-s', '-k', '-i', '-m', '15', '-X', $Method.ToUpperInvariant()) if ($Headers) { foreach ($k in $Headers.Keys) { $curlArgs += @('-H', "$($k): $($Headers[$k])") } } $tempBodyFile = $null if ($null -ne $Body) { if ($Body -is [hashtable]) { $ct = if ($ContentType) { $ContentType } else { 'application/x-www-form-urlencoded' } $curlArgs += @('-H', "Content-Type: $ct") $parts = $Body.GetEnumerator() | ForEach-Object { "$([Uri]::EscapeDataString($_.Key))=$([Uri]::EscapeDataString([string]$_.Value))" } $payload = $parts -join '&' } else { $ct = if ($ContentType) { $ContentType } else { 'application/json' } $curlArgs += @('-H', "Content-Type: $ct") $payload = if ($Body -is [string]) { $Body } else { $Body | ConvertTo-Json -Depth 6 -Compress } } $tempBodyFile = New-TemporaryFile [System.IO.File]::WriteAllText($tempBodyFile, $payload, (New-Object System.Text.UTF8Encoding($false))) $curlArgs += @('--data-binary', "@$tempBodyFile") } $curlArgs += $Url try { $raw = & curl.exe @curlArgs } finally { if ($tempBodyFile) { Remove-Item $tempBodyFile -ErrorAction SilentlyContinue } } $text = ($raw -join "`n") $sepIdx = $text.IndexOf("`n`n") $headerSection = if ($sepIdx -gt 0) { $text.Substring(0, $sepIdx) } else { $text } $bodySection = if ($sepIdx -gt 0) { $text.Substring($sepIdx + 2) } else { "" } $firstLine = ($headerSection -split "`n")[0] $statusCode = 0 if ($firstLine -match 'HTTP/\S+\s+(\d+)') { $statusCode = [int]$matches[1] } $location = $null foreach ($h in ($headerSection -split "`n")) { if ($h -match '^[Ll]ocation:\s*(.+?)\s*$') { $location = $matches[1]; break } } return [pscustomobject]@{ StatusCode = $statusCode; Location = $location; Content = $bodySection; Headers = $headerSection } } function Get-Json { param([string]$Method, [string]$Url, $Body = $null, [hashtable]$Headers = $null, [string]$ContentType = "application/json") $curlArgs = @('-s', '-k', '-m', '15', '-w', '||%{http_code}||', '-X', $Method.ToUpperInvariant()) if ($Headers) { foreach ($k in $Headers.Keys) { $curlArgs += @('-H', "$($k): $($Headers[$k])") } } $tempBodyFile = $null if ($null -ne $Body) { $curlArgs += @('-H', "Content-Type: $ContentType") $payload = if ($Body -is [string]) { $Body } else { $Body | ConvertTo-Json -Depth 6 -Compress } $tempBodyFile = New-TemporaryFile [System.IO.File]::WriteAllText($tempBodyFile, $payload, (New-Object System.Text.UTF8Encoding($false))) $curlArgs += @('--data-binary', "@$tempBodyFile") } $curlArgs += $Url try { $raw = & curl.exe @curlArgs } finally { if ($tempBodyFile) { Remove-Item $tempBodyFile -ErrorAction SilentlyContinue } } if ($null -eq $raw) { throw "curl returned no output for $Method $Url" } $text = ($raw -join "`n") $m = [regex]::Match($text, '\|\|(\d{3})\|\|\s*$') if (-not $m.Success) { throw "curl marker missing in: $text" } $bodyOut = $text.Substring(0, $m.Index) $status = [int]$m.Groups[1].Value if ($status -ge 400) { throw "HTTP $status $Method $Url : $bodyOut" } if (-not $bodyOut -or $bodyOut.Length -eq 0) { return $null } return $bodyOut | ConvertFrom-Json -Depth 8 } # Drive challenge → mock IdP login → callback. Returns the callback's response body. # Used for both fresh-login flow (no bearer) and link flow (bearer-authenticated challenge). function Invoke-FederationFlow { param( [string]$ChallengeUrl, # the initial GET we hit on identity [string]$Email, [hashtable]$Claims, [hashtable]$Headers = $null # optional bearer when initiating link-challenge ) $r1 = Hop -Method Get -Url $ChallengeUrl -Headers $Headers if ($r1.StatusCode -lt 200 -or ($r1.StatusCode -ge 400)) { throw "challenge $ChallengeUrl returned $($r1.StatusCode): $($r1.Content.Substring(0, [Math]::Min(200, $r1.Content.Length)))" } # Identity may either 302 directly (for /connect/external-login) or return JSON with # redirect_uri (for the controller-driven /me/federated-identities/link-challenge). $idpUrl = $r1.Location if (-not $idpUrl -and $r1.Content) { try { $idpUrl = ($r1.Content | ConvertFrom-Json).redirect_uri } catch {} } if (-not $idpUrl) { throw "challenge produced no IdP redirect URL (status=$($r1.StatusCode), location=$($r1.Location))" } if (-not $idpUrl.StartsWith($IDP)) { throw "challenge redirect '$idpUrl' is not mock IdP" } $r2 = Hop -Method Post -Url $idpUrl -Body @{ username = $Email claims = ($Claims | ConvertTo-Json -Compress) } if ($r2.StatusCode -ne 302) { throw "mock IdP returned $($r2.StatusCode), expected 302" } $callbackUrl = $r2.Location if (-not $callbackUrl.StartsWith("$BASE/connect/federation/callback")) { throw "mock IdP redirected to '$callbackUrl', expected our callback" } $r3 = Hop -Method Get -Url $callbackUrl if ($r3.StatusCode -lt 200) { throw "callback returned $($r3.StatusCode)" } # Callback either returns JSON (link mode) or redirects (login mode). Caller decides. return [pscustomobject]@{ StatusCode = $r3.StatusCode Location = $r3.Location Content = $r3.Content Json = $(try { if ($r3.Content) { $r3.Content | ConvertFrom-Json -Depth 8 } else { $null } } catch { $null }) } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 0) Skip if mock IdP not reachable. try { $r = Hop -Method Get -Url "$IDP/.well-known/openid-configuration" if ($r.StatusCode -ne 200) { throw "status $($r.StatusCode)" } } catch { Write-Host "" Write-Host "mock-oauth2-server not reachable at $IDP — skipping link/unlink demo." -ForegroundColor Yellow exit 0 } Write-Host "mock IdP at $IDP reachable, proceeding." -ForegroundColor DarkGray # 1) DCRs. $userReg = Measure-Step "1a. DCR password client (ROPC + offline_access)" { Get-Json -Method Post -Url "$BASE/connect/register" -Headers $DCR_AUTH -Body @{ client_name = "fed-link-unlink" grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" } } $U_RAT = $userReg.registration_access_token $U_RCU = $userReg.registration_client_uri $adminReg = Measure-Step "1b. DCR admin client (users.manage)" { Get-Json -Method Post -Url "$BASE/connect/register" -Headers $DCR_AUTH -Body @{ client_name = "fed-link-unlink-admin" grant_types = @("client_credentials") scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write" } } $A_RAT = $adminReg.registration_access_token $A_RCU = $adminReg.registration_client_uri # 2) Self-register user with password (local credential). $user = "linkun_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $email = "$user@example.com" $pwd = "Test1234Pass!" Measure-Step "2. self-register user $user with password" { Get-Json -Method Post -Url "$BASE/api/v1/identity/account/register" -Body @{ login = $user; email = $email; password = $pwd; displayName = $user } | Out-Null Write-Host " registered $email" -ForegroundColor Green } | Out-Null # 3) /connect/external-login with SAME email → expect email_conflict on callback. # Server's LoginService now uses GetUserByEmailAsync (added to redb.Core in this batch) # so the conflict fires for genuine email overlap, not just login==email coincidence. Measure-Step "3. external-login with same email → email_conflict (no silent auto-link)" { $r1 = Hop -Method Get -Url "$BASE/connect/external-login?provider=$PROV&returnUrl=/" if ($r1.StatusCode -lt 300 -or $r1.StatusCode -ge 400) { throw "challenge returned $($r1.StatusCode)" } $idpUrl = $r1.Location if (-not $idpUrl) { throw "no Location on challenge" } $r2 = Hop -Method Post -Url $idpUrl -Body @{ username = $email claims = (@{ email = $email; email_verified = $true; name = $user; sub = "ext-conflict-$user" } | ConvertTo-Json -Compress) } if ($r2.StatusCode -ne 302) { throw "mock IdP returned $($r2.StatusCode)" } $r3 = Hop -Method Get -Url $r2.Location # FederationHttpProcessors.HandleCallbackResponse renders an HTML "Authentication Error" # page whose body carries error_description = "Federated email already registered locally." # (set by LoginResult.EmailConflict). That's the user-facing signal; the precise # error code "email_conflict" lives in the underlying dict body the processor wraps # but isn't echoed into the HTML directly. We pin the user-visible text so the # contract is what an actual end-user sees. $signalled = $false if ($r3.Content -and $r3.Content -match 'already registered locally') { $signalled = $true } elseif ($r3.Content -and $r3.Content -match 'email_conflict') { $signalled = $true } elseif ($r3.Location -and $r3.Location -match 'email_conflict') { $signalled = $true } if (-not $signalled) { throw "no email_conflict signal — status=$($r3.StatusCode), location=$($r3.Location), content head: $($r3.Content.Substring(0,[Math]::Min(300,$r3.Content.Length)))" } Write-Host " email_conflict surfaced (front-end should drive explicit link via /me/federated-identities/link-challenge)" -ForegroundColor Green } | Out-Null # 4) ROPC user → bearer. $userTok = Measure-Step "4. ROPC (user bearer)" { $form = "grant_type=password&client_id=$([Uri]::EscapeDataString($userReg.client_id))" + "&client_secret=$([Uri]::EscapeDataString($userReg.client_secret))" + "&username=$([Uri]::EscapeDataString($user))&password=$([Uri]::EscapeDataString($pwd))" + "&scope=$([Uri]::EscapeDataString('openid profile email identity:account'))" Get-Json -Method Post -Url "$BASE/connect/token" -Body $form -ContentType "application/x-www-form-urlencoded" } $U_HDR = @{ Authorization = "Bearer $($userTok.access_token)" } # 5) Initial state — no federation links. Measure-Step "5. GET /me/federated-identities → empty list" { $r = Get-Json -Method Get -Url "$BASE/api/v1/identity/me/federated-identities" -Headers $U_HDR $items = if ($r.items) { $r.items } else { $r } if (@($items).Count -ne 0) { throw "expected 0 federation links pre-link, got $(@($items).Count)" } Write-Host " no links yet" -ForegroundColor Green } | Out-Null # Helper — drive link-challenge → callback. Returns the callback JSON. function Invoke-LinkFlow { $linkResp = Get-Json -Method Post -Url "$BASE/api/v1/identity/me/federated-identities/link-challenge" -Headers $U_HDR -Body @{ providerId = $PROV returnUrl = "/" } if (-not $linkResp.redirect_uri -and -not $linkResp.redirectUri) { throw "link-challenge returned no redirect_uri (body: $($linkResp | ConvertTo-Json -Depth 3))" } $idpUrl = if ($linkResp.redirect_uri) { $linkResp.redirect_uri } else { $linkResp.redirectUri } if (-not $idpUrl.StartsWith($IDP)) { throw "link-challenge redirect '$idpUrl' is not mock IdP" } $r2 = Hop -Method Post -Url $idpUrl -Body @{ username = $email claims = (@{ email = $email; email_verified = $true; name = $user; sub = "ext-$user" } | ConvertTo-Json -Compress) } if ($r2.StatusCode -ne 302) { throw "mock IdP returned $($r2.StatusCode) on link" } Write-Host " IdP redirected → $($r2.Location.Substring(0,[Math]::Min(120,$r2.Location.Length)))..." -ForegroundColor DarkGray $r3 = Hop -Method Get -Url $r2.Location Write-Host " callback: status=$($r3.StatusCode) location=$($r3.Location) content_len=$(if ($r3.Content) { $r3.Content.Length } else { 0 })" -ForegroundColor DarkGray if (-not $r3.Content -or $r3.Content.Trim().Length -eq 0) { # Callback may have redirected (returnUrl is the configured "/" — link mode does NOT # usually redirect, but if the response is empty + 302, treat as success based on # the redirect URL containing "linked=true" or the absence of error markers. if ($r3.StatusCode -ge 300 -and $r3.StatusCode -lt 400 -and $r3.Location -and $r3.Location -notmatch 'error') { return @{ success = $true; linked = $true; providerId = $PROV; userId = -1; externalSub = "(redirected, no body)" } } throw "callback returned empty body (status=$($r3.StatusCode), location=$($r3.Location))" } return $r3.Content | ConvertFrom-Json -Depth 8 } # 6) Link via /me/federated-identities/link-challenge. $linkResult = Measure-Step "6. POST /me/federated-identities/link-challenge → IdP → callback → linked=true" { $r = Invoke-LinkFlow if (-not $r.success) { throw "link failed: $($r | ConvertTo-Json -Depth 3)" } if (-not $r.linked) { throw "callback didn't set linked=true: $($r | ConvertTo-Json -Depth 3)" } if ($r.providerId -ne $PROV) { throw "providerId mismatch: $($r.providerId) ≠ $PROV" } Write-Host " linked: userId=$($r.userId), providerId=$($r.providerId), externalSub=$($r.externalSub)" -ForegroundColor Green return $r } # 7) Verify link surfaces in /me/federated-identities. Measure-Step "7. GET /me/federated-identities → 1 entry with providerId" { $r = Get-Json -Method Get -Url "$BASE/api/v1/identity/me/federated-identities" -Headers $U_HDR $items = if ($r.items) { $r.items } else { $r } $arr = @($items) if ($arr.Count -ne 1) { throw "expected 1 link, got $($arr.Count)" } if ($arr[0].providerId -ne $PROV) { throw "expected providerId=$PROV, got '$($arr[0].providerId)'" } Write-Host " 1 entry: providerId=$($arr[0].providerId)" -ForegroundColor Green } | Out-Null # 8) Unlink (user still has password — should succeed). Measure-Step "8. DELETE /me/federated-identities/$PROV → success (password still present)" { $r = Get-Json -Method Delete -Url "$BASE/api/v1/identity/me/federated-identities/$PROV" -Headers $U_HDR if (-not ($r.unlinked -or $r.success)) { throw "unlink not success: $($r | ConvertTo-Json -Depth 3)" } Write-Host " unlinked: $($r | ConvertTo-Json -Compress)" -ForegroundColor Green } | Out-Null # 9) List is empty again. Measure-Step "9. GET /me/federated-identities → empty after unlink" { $r = Get-Json -Method Get -Url "$BASE/api/v1/identity/me/federated-identities" -Headers $U_HDR $items = if ($r.items) { $r.items } else { $r } if (@($items).Count -ne 0) { throw "expected 0 links post-unlink, got $(@($items).Count)" } Write-Host " no links" -ForegroundColor Green } | Out-Null # 10) Re-link — sanity that unlink/link cycle works. Measure-Step "10. re-link via link-challenge → linked again" { $r = Invoke-LinkFlow if (-not $r.linked) { throw "re-link failed: $($r | ConvertTo-Json -Depth 3)" } Write-Host " re-linked (cycle safe)" -ForegroundColor Green } | Out-Null # 11) Cleanup. Measure-Step "11. RFC 7592 DELETE DCRs" { if ($U_RAT) { try { Get-Json -Method Delete -Url $U_RCU -Headers @{ Authorization = "Bearer $U_RAT" } | Out-Null } catch {} } if ($A_RAT) { try { Get-Json -Method Delete -Url $A_RCU -Headers @{ Authorization = "Bearer $A_RAT" } | Out-Null } catch {} } Write-Host " DCRs deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_groups_roles_claims.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_groups_roles_claims.ps1 ---- # P1 #9 — `groups` / `roles` scope→claim probe (admin-bootstrapped). # # Closes the last GAP in OIDC scope→claim coverage. The `groups` and `roles` scopes # are emitted by GroupClaimsResolver: # `groups` claim = direct group names + tree-ancestor names (transitive membership) # `roles`/`role` claim = per-membership Role label (NOT inherited via tree) # # Probes (all asserted): # 1. admin DCR (client_credentials + identity:users:write identity:groups:write identity:consents:write identity:mfa:write) # 2. admin token (mint via client_credentials) # 3. user-facing DCR (password grant + groups/roles user-info scopes) # 4. self-register user # 5. ROPC user token + lookup numeric user id from /me # 6. admin creates "developers" team group # 7. admin creates "engineering" organisation group (parent of developers) # 8. admin moves developers under engineering (tree) # 9. admin adds user to "developers" with role="senior" # 10. ROPC again with scope including groups + roles # 11. assert id_token.groups contains BOTH "developers" AND ancestor "engineering" # 12. assert id_token.role(s) contains "senior" # 13. /connect/userinfo carries the same groups + role # 14. admin updates role to "lead" → re-ROPC → id_token.role contains "lead", NOT "senior" # 15. admin removes user from developers → re-ROPC → groups/role claims gone # 16. RFC 7592 cleanup (delete both DCR'd clients) + delete groups # # Usage: pwsh -File demo_groups_roles_claims.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() # Avoid -f format operator here: $Name may contain literal {…} from REST path # templates (e.g. /groups/{dev}/move) which the format parser interprets as # placeholders and aborts with "Failure to parse near offset N". $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } function Get-JwtBody([string]$jwt) { $parts = $jwt.Split('.') if ($parts.Count -lt 2) { throw "JWT does not have 3 segments" } $b64 = $parts[1].Replace('-','+').Replace('_','/') switch ($b64.Length % 4) { 2 { $b64 += '==' } 3 { $b64 += '=' } } $json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64)) return $json | ConvertFrom-Json -Depth 12 } function Get-RopcToken { param([string]$ClientId, [string]$ClientSecret, [string]$Username, [string]$Password, [string]$Scope) Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $ClientId client_secret = $ClientSecret username = $Username password = $Password scope = $Scope } } # Normalise a single-or-multi claim into a string[] (JWT array shape). function To-Array($v) { if ($null -eq $v) { return @() } if ($v -is [Array]) { return $v } return @($v) } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) Admin DCR — client_credentials + identity:users:write identity:groups:write identity:consents:write identity:mfa:write (group/member mutations). $adminReg = Measure-Step "1. admin DCR (cc + identity:users:write identity:groups:write identity:consents:write identity:mfa:write)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "groups-roles-admin" grant_types = @("client_credentials") scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write" } | ConvertTo-Json) if (-not $r.client_id) { throw "admin DCR no client_id" } Write-Host " ✓ admin client_id: $($r.client_id)" -ForegroundColor Green return $r } $ADMIN_RAT = $adminReg.registration_access_token $ADMIN_RCU = $adminReg.registration_client_uri # 2) Admin token. $adminTok = Measure-Step "2. admin client_credentials token" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $adminReg.client_id client_secret = $adminReg.client_secret scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write" } if (-not $t.access_token) { throw "no admin access_token" } Write-Host " ✓ access_token (len $($t.access_token.Length))" -ForegroundColor Green return $t } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)" } # 3) User DCR — password grant + groups/roles scopes. $userReg = Measure-Step "3. user-facing DCR (password + groups/roles)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "groups-roles-user" grant_types = @("password","refresh_token") scope = "openid profile email offline_access groups roles identity:account" } | ConvertTo-Json) if (-not $r.client_id) { throw "user DCR no client_id" } Write-Host " ✓ user client_id: $($r.client_id)" -ForegroundColor Green return $r } $USER_RAT = $userReg.registration_access_token $USER_RCU = $userReg.registration_client_uri # 4) Self-register user. $user = "grp_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "4. self-register ($user)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@example.com"; password = $pwd; displayName = $user } | ConvertTo-Json) | Out-Null Write-Host " ✓ user created" -ForegroundColor Green } | Out-Null # 5) ROPC + /me to grab numeric user id (admin path needs the bigint userId). $userId = Measure-Step "5. ROPC + GET /me → numeric userId" { $t = Get-RopcToken -ClientId $userReg.client_id -ClientSecret $userReg.client_secret ` -Username $user -Password $pwd ` -Scope "openid profile email offline_access identity:account" $bearer = @{ Authorization = "Bearer $($t.access_token)" } $me = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me" -Headers $bearer # /me may surface id under different shapes; pick first non-empty numeric. $id = $null foreach ($p in 'id','userId','user_id','Id') { $v = $me.PSObject.Properties[$p] if ($v -and $v.Value) { $id = [long]$v.Value; break } } if (-not $id) { throw "could not extract numeric userId from /me (shape: $($me | ConvertTo-Json -Depth 3))" } Write-Host " ✓ userId = $id" -ForegroundColor Green return $id } # 6) Create "developers" (team) group. $devGroup = Measure-Step "6. admin: POST /groups (developers, team)" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/groups" -Headers $ADMIN ` -ContentType "application/json" ` -Body (@{ name = "developers-$user"; groupType = "team"; description = "p7 probe team" } | ConvertTo-Json) if (-not $r.id) { throw "no group id in response: $($r | ConvertTo-Json -Depth 3)" } Write-Host " ✓ developers groupId = $($r.id)" -ForegroundColor Green return $r } # 7) Create "engineering" (organization) group. $engGroup = Measure-Step "7. admin: POST /groups (engineering, organization)" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/groups" -Headers $ADMIN ` -ContentType "application/json" ` -Body (@{ name = "engineering-$user"; groupType = "organization"; description = "p7 probe org" } | ConvertTo-Json) if (-not $r.id) { throw "no group id" } Write-Host " ✓ engineering groupId = $($r.id)" -ForegroundColor Green return $r } # 8) Move developers under engineering — tree parent_id wiring. Measure-Step "8. admin: POST /groups/{dev}/move (parent = engineering)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/groups/$($devGroup.id)/move" -Headers $ADMIN ` -ContentType "application/json" ` -Body (@{ newParentGroupId = [long]$engGroup.id } | ConvertTo-Json) | Out-Null Write-Host " ✓ developers parent_id = engineering" -ForegroundColor Green } | Out-Null # 9) Admin adds user to developers with role="senior". Measure-Step "9. admin: POST /groups/{dev}/members (userId, role=senior)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/groups/$($devGroup.id)/members" -Headers $ADMIN ` -ContentType "application/json" ` -Body (@{ userId = $userId; role = "senior" } | ConvertTo-Json) | Out-Null Write-Host " ✓ membership created" -ForegroundColor Green } | Out-Null # 10) ROPC with groups + roles scopes. $tok10 = Measure-Step "10. ROPC user token (scope includes groups + roles)" { Get-RopcToken -ClientId $userReg.client_id -ClientSecret $userReg.client_secret ` -Username $user -Password $pwd ` -Scope "openid profile email offline_access groups roles identity:account" } # 11) Assert groups claim on id_token — both direct AND ancestor names. Measure-Step "11. assert id_token.groups contains [developers-$user, engineering-$user]" { $claims = Get-JwtBody $tok10.id_token $groups = To-Array $claims.groups Write-Host " groups claim: $($groups -join ', ')" -ForegroundColor DarkGray if ($groups -notcontains "developers-$user") { throw "groups missing 'developers-$user'" } if ($groups -notcontains "engineering-$user") { throw "groups missing ancestor 'engineering-$user' — tree ancestor expansion broken" } Write-Host " ✓ direct + ancestor present" -ForegroundColor Green } | Out-Null # 12) Assert roles/role claim — "senior". Measure-Step "12. assert id_token role(s) contains 'senior'" { $claims = Get-JwtBody $tok10.id_token # Some emitters use 'roles' (array), others 'role' (single/multi-claim). $roles = @() if ($claims.PSObject.Properties['roles']) { $roles += (To-Array $claims.roles) } if ($claims.PSObject.Properties['role']) { $roles += (To-Array $claims.role) } Write-Host " role claim(s): $($roles -join ', ')" -ForegroundColor DarkGray if ($roles -notcontains "senior") { throw "role claim does not carry 'senior' (got: $($roles -join ','))" } Write-Host " ✓ role 'senior' present" -ForegroundColor Green } | Out-Null # 13) /connect/userinfo carries same surface. Measure-Step "13. GET /connect/userinfo carries groups + role" { $ui = Invoke-RestMethod -Method Get "$BASE/connect/userinfo" ` -Headers @{ Authorization = "Bearer $($tok10.access_token)" } $g = To-Array $ui.groups if ($g -notcontains "developers-$user") { throw "userinfo.groups missing developers" } $r = @() if ($ui.PSObject.Properties['roles']) { $r += (To-Array $ui.roles) } if ($ui.PSObject.Properties['role']) { $r += (To-Array $ui.role) } if ($r -notcontains "senior") { throw "userinfo missing role 'senior' (got: $($r -join ','))" } Write-Host " ✓ groups + role on userinfo parity with id_token" -ForegroundColor Green } | Out-Null # 14) Update membership role to "lead", re-ROPC, assert new role. Measure-Step "14. admin updates role → 'lead', re-ROPC, assert id_token.role == 'lead' (and NOT 'senior')" { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/groups/$($devGroup.id)/members/$userId" -Headers $ADMIN ` -ContentType "application/json" ` -Body (@{ role = "lead" } | ConvertTo-Json) | Out-Null $tok14 = Get-RopcToken -ClientId $userReg.client_id -ClientSecret $userReg.client_secret ` -Username $user -Password $pwd ` -Scope "openid profile email offline_access groups roles identity:account" $claims = Get-JwtBody $tok14.id_token $roles = @() if ($claims.PSObject.Properties['roles']) { $roles += (To-Array $claims.roles) } if ($claims.PSObject.Properties['role']) { $roles += (To-Array $claims.role) } if ($roles -notcontains "lead") { throw "role claim does not carry new 'lead' (got: $($roles -join ','))" } if ($roles -contains "senior") { throw "role claim still carries old 'senior' — update did not propagate" } Write-Host " ✓ role rotated senior → lead" -ForegroundColor Green } | Out-Null # 15) Remove user from developers — groups + role claims disappear. Measure-Step "15. admin removes user from developers → groups/role claims gone" { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/groups/$($devGroup.id)/members/$userId" -Headers $ADMIN | Out-Null $tok15 = Get-RopcToken -ClientId $userReg.client_id -ClientSecret $userReg.client_secret ` -Username $user -Password $pwd ` -Scope "openid profile email offline_access groups roles identity:account" $claims = Get-JwtBody $tok15.id_token $groups = To-Array $claims.groups if ($groups -contains "developers-$user") { throw "groups still carries 'developers-$user' after Remove" } $roles = @() if ($claims.PSObject.Properties['roles']) { $roles += (To-Array $claims.roles) } if ($claims.PSObject.Properties['role']) { $roles += (To-Array $claims.role) } if ($roles -contains "lead") { throw "role still carries 'lead' after Remove" } Write-Host " ✓ groups/role claims cleared on remove" -ForegroundColor Green } | Out-Null # 16) Cleanup — delete both groups + both DCR clients. Measure-Step "16. cleanup (delete groups + RFC 7592 DELETE registrations)" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/groups/$($devGroup.id)" -Headers $ADMIN | Out-Null } catch {} try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/groups/$($engGroup.id)" -Headers $ADMIN | Out-Null } catch {} if ($ADMIN_RAT) { Invoke-RestMethod -Method Delete -Uri $ADMIN_RCU -Headers @{ Authorization = "Bearer $ADMIN_RAT" } | Out-Null } if ($USER_RAT) { Invoke-RestMethod -Method Delete -Uri $USER_RCU -Headers @{ Authorization = "Bearer $USER_RAT" } | Out-Null } Write-Host " ✓ cleaned up" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_grpc_facade.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_grpc_facade.ps1 ---- # gRPC facade — the protocol surface and the management surface, over the wire, against a running server. # # Usage: pwsh -File demo_grpc_facade.ps1 # pwsh -File demo_grpc_facade.ps1 -Grpc localhost:5011 -Http https://localhost:5002 # # Calls are made with grpcurl — the standard tool, one binary, no build step. Everything it sends and # receives is printed as JSON, so the output stands on its own: no C# to read, no container to start. # # winget install fullstorydev.grpcurl # # We do not serve gRPC reflection, so grpcurl is pointed at the published .proto files in the repository — # which is what a consumer would do anyway. param( [string]$Grpc = $(if ($env:IDENTITY_GRPC) { $env:IDENTITY_GRPC } else { "localhost:5011" }), [string]$Http = $(if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://localhost:5002" }) ) $ErrorActionPreference = 'Stop' $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $here = Split-Path -Parent $MyInvocation.MyCommand.Path $contracts = Join-Path (Split-Path -Parent $here) "src\redb.Identity.Contracts\Protos" $demoProto = Join-Path $here "grpc" $total = [System.Diagnostics.Stopwatch]::StartNew() $step = 0 $failed = 0 function Say([string]$text, [string]$color = 'Gray') { Write-Host $text -ForegroundColor $color } # Shortens the long opaque strings — access tokens, secrets — so the shape of a reply stays visible. # Nothing is hidden that matters: a 3 KB JWE tells the reader nothing except how long it is. function Compact([string]$text) { if (-not $text) { return $text } return [regex]::Replace($text, '"([A-Za-z0-9\-_\.\+/=]{48,})"', { param($m) '"' + $m.Groups[1].Value.Substring(0, 24) + '…" (' + $m.Groups[1].Value.Length + ' chars)' }) } function Step([string]$address, [string]$what) { $script:step++ Write-Host "" Write-Host (" {0}. {1}" -f $script:step, $address) -NoNewline -ForegroundColor White Write-Host (" {0}" -f $what) -ForegroundColor DarkGray } # Runs grpcurl and shows both directions. Returns @{ Ok; Json; Err; Ms }. function Grpc { param( [string]$Address, # package.Service/Method [string]$Proto, # .proto file name [string]$ProtoPath, # -import-path $Body = @{}, [string[]]$Headers = @() ) $json = $Body | ConvertTo-Json -Compress -Depth 10 Write-Host " -> " -NoNewline -ForegroundColor DarkGray Say (Compact $json) foreach ($h in $Headers) { Write-Host " -> " -NoNewline -ForegroundColor DarkGray Say ("metadata " + ($h -replace '(Bearer\s+\S{16})\S+', '$1...')) } $cmd = @('-plaintext', '-import-path', $ProtoPath, '-proto', $Proto) foreach ($h in $Headers) { $cmd += @('-H', $h) } $cmd += @('-d', $json, $Grpc, $Address) $sw = [System.Diagnostics.Stopwatch]::StartNew() $out = & grpcurl @cmd 2>&1 $sw.Stop() $ok = $LASTEXITCODE -eq 0 $stdout = ($out | Where-Object { $_ -isnot [System.Management.Automation.ErrorRecord] }) -join "`n" $stderr = ($out | Where-Object { $_ -is [System.Management.Automation.ErrorRecord] } | ForEach-Object { $_.ToString() }) -join "`n" if ($ok) { Write-Host " <- " -NoNewline -ForegroundColor Green Say (Compact ($stdout -replace "`n", "`n ")) } else { Write-Host " <- " -NoNewline -ForegroundColor Yellow Say ((($stderr, $stdout | Where-Object { $_ }) -join "`n") -replace "`n", "`n ") 'Yellow' } Write-Host (" {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor DarkGray return @{ Ok = $ok; Json = $stdout; Err = $stderr; Ms = $sw.Elapsed.TotalMilliseconds } } function Read-AccessToken($call) { if (-not $call.Ok) { return "" } $j = $call.Json | ConvertFrom-Json if ($j.PSObject.Properties.Name -contains "accessToken") { return $j.accessToken } if ($j.PSObject.Properties.Name -contains "access_token") { return $j.access_token } return "" } function Expect([bool]$condition, [string]$message) { if (-not $condition) { Write-Host " !! $message" -ForegroundColor Red $script:failed++ } } Write-Host "" Write-Host " redb.Identity - the gRPC facade, over the wire" -ForegroundColor Cyan Write-Host " ---------------------------------------------" -ForegroundColor DarkGray Write-Host "" Write-Host (" gRPC {0}" -f $Grpc) -ForegroundColor DarkGray Write-Host (" HTTP {0} (used once, to register a demo client)" -f $Http) -ForegroundColor DarkGray Write-Host "" Write-Host " -> what the client sends <- what the server answers" -ForegroundColor DarkGray if (-not (Get-Command grpcurl -ErrorAction SilentlyContinue)) { Write-Host "" Write-Host " grpcurl is not on PATH. Install it: winget install fullstorydev.grpcurl" -ForegroundColor Red exit 1 } # ── 1. Is anything serving? ─────────────────────────────────── # The standard health address, what Kubernetes and Envoy probe. Its schema is gRPC's own, not ours, so it # sits in demos/grpc/health.proto rather than in the published contract. Step "grpc.health.v1.Health/Check" "is the listener serving?" $health = Grpc -Address "grpc.health.v1.Health/Check" -Proto "health.proto" -ProtoPath $demoProto Expect ($health.Ok -and $health.Json -match 'SERVING') "health check did not report SERVING" # ── 2. Discovery ────────────────────────────────────────────── # Passed through from Core untouched. Look at the endpoints it advertises: they are HTTP addresses, # because those are the real ones. The facade does not rewrite them into gRPC addresses that do not exist. Step "identity.v1.Identity/Discovery" "the OIDC document, straight from Core" $discovery = Grpc -Address "identity.v1.Identity/Discovery" -Proto "identity.v1.proto" -ProtoPath $contracts Expect ($discovery.Ok -and $discovery.Json -match '"issuer"') "discovery returned no issuer" # ── 3. A client, registered over HTTP ───────────────────────── # The claim of the whole facade in one step: this client is created through the HTTP transport and used # through the gRPC one. One issuer, one client registry, one token store. # # Granular scopes on purpose: the master identity:manage is deliberately not obtainable through dynamic # registration, and the granular branch is the interesting one anyway - it is the scope table that both # transports share. $scope = "identity:users:read identity:users:write" Step "POST /connect/register" "HTTP, not gRPC - register a throwaway client" Write-Host " -> " -NoNewline -ForegroundColor DarkGray Say (@{ client_name = "grpc-demo"; grant_types = @("client_credentials"); scope = $scope } | ConvertTo-Json -Compress) $reg = Invoke-RestMethod -Method Post "$Http/connect/register" -Headers $DCR_AUTH -ContentType "application/json" -Body (@{ client_name = "grpc-demo" grant_types = @("client_credentials") scope = $scope } | ConvertTo-Json) Write-Host " <- " -NoNewline -ForegroundColor Green Say ("client_id " + $reg.client_id) # ── 4. A token, over gRPC ───────────────────────────────────── Step "identity.v1.Identity/Token" "the client above, now over gRPC" $tokenCall = Grpc -Address "identity.v1.Identity/Token" -Proto "identity.v1.proto" -ProtoPath $contracts -Body @{ grant_type = "client_credentials" client_id = $reg.client_id client_secret = $reg.client_secret scope = $scope } Expect $tokenCall.Ok "token call failed" # grpcurl prints protobuf JSON, where declared fields carry their JSON names (accessToken), while Struct # keys keep whatever the server put there — which is why Discovery above shows snake_case. Read either. $token = Read-AccessToken $tokenCall Expect ([bool]$token) "no access_token in the reply" # ── 5. Introspection ────────────────────────────────────────── Step "identity.v1.Identity/Introspect" "is that token real to this server?" $intro = Grpc -Address "identity.v1.Identity/Introspect" -Proto "identity.v1.proto" -ProtoPath $contracts -Body @{ token = $token client_id = $reg.client_id client_secret = $reg.client_secret } Expect ($intro.Ok -and $intro.Json -match '"active":\s*true') "the token we just minted introspects as inactive" # ── 6. A refusal ────────────────────────────────────────────── # An OAuth error must arrive as a gRPC *status*, not as a successful call carrying an error document - no # generated client inspects the body of an OK reply. The machine-readable code travels in a trailer, # because the protocol discards the payload of a non-OK reply. Step "identity.v1.Identity/Token" "same client, wrong secret" $refused = Grpc -Address "identity.v1.Identity/Token" -Proto "identity.v1.proto" -ProtoPath $contracts -Body @{ grant_type = "client_credentials" client_id = $reg.client_id client_secret = "not-the-secret" } Expect (-not $refused.Ok) "a wrong secret produced a token" Expect ($refused.Err -match 'Unauthenticated') "expected Unauthenticated" # ── 7. The management gate, from outside ────────────────────── Step "identity.management.v1.Users/List" "an admin operation with no credentials at all" $noAuth = Grpc -Address "identity.management.v1.Users/List" -Proto "identity.management.v1.proto" -ProtoPath $contracts -Body @{ arguments = @{ offset = 0; count = 1 } } Expect (-not $noAuth.Ok) "an admin operation ran without credentials" Expect ($noAuth.Err -match 'Unauthenticated') "expected Unauthenticated" # ── 8. ...and with the token ────────────────────────────────── # A gate that only ever refuses is not a gate, it is an outage. This is the other half. Step "identity.management.v1.Users/List" "the same call, carrying the token" $admitted = Grpc -Address "identity.management.v1.Users/List" -Proto "identity.management.v1.proto" -ProtoPath $contracts ` -Body @{ arguments = @{ offset = 0; count = 3 } } -Headers @("authorization: Bearer $token") Expect $admitted.Ok "the admin token was refused" # ── 9. One token, two transports, one verdict ───────────────── # The acceptance criterion of the facade, in both directions: the write-scoped client is admitted on both, # and a read-only client is refused the write on both. Step "HTTP + gRPC" "the same token, the same operation, on both transports" $httpOk = $true try { Invoke-RestMethod -Method Get "$Http/api/v1/identity/users?offset=0&count=3" -Headers @{ Authorization = "Bearer $token" } | Out-Null } catch { $httpOk = $false } Write-Host " <- " -NoNewline -ForegroundColor Green Say ("HTTP GET /api/v1/identity/users -> " + $(if ($httpOk) { "admitted" } else { "REFUSED" })) Expect $httpOk "the same token was admitted over gRPC and refused over HTTP" $narrow = Invoke-RestMethod -Method Post "$Http/connect/register" -Headers $DCR_AUTH -ContentType "application/json" -Body (@{ client_name = "grpc-demo-narrow" grant_types = @("client_credentials") scope = "identity:users:read" } | ConvertTo-Json) $narrowTokenCall = Grpc -Address "identity.v1.Identity/Token" -Proto "identity.v1.proto" -ProtoPath $contracts -Body @{ grant_type = "client_credentials" client_id = $narrow.client_id client_secret = $narrow.client_secret scope = "identity:users:read" } $narrowToken = Read-AccessToken $narrowTokenCall Step "identity.management.v1.Users/Create" "a read-only token attempting a write" $narrowGrpc = Grpc -Address "identity.management.v1.Users/Create" -Proto "identity.management.v1.proto" -ProtoPath $contracts ` -Body @{ arguments = @{ login = "grpc-demo-should-not-exist" } } -Headers @("authorization: Bearer $narrowToken") Expect (-not $narrowGrpc.Ok) "a read-only token created a user over gRPC" $httpRefused = $false try { Invoke-RestMethod -Method Post "$Http/api/v1/identity/users" -Headers @{ Authorization = "Bearer $narrowToken" } ` -ContentType "application/json" -Body (@{ login = "grpc-demo-should-not-exist" } | ConvertTo-Json) | Out-Null } catch { $httpRefused = $true } Write-Host " <- " -NoNewline -ForegroundColor Green Say ("HTTP POST /api/v1/identity/users -> " + $(if ($httpRefused) { "REFUSED (as it must be)" } else { "ADMITTED" })) Expect $httpRefused "a read-only token created a user over HTTP" $total.Stop() Write-Host "" if ($failed -gt 0) { Write-Host (" gRPC facade demo: FAILED ({0} checks) in {1:N0} ms" -f $failed, $total.Elapsed.TotalMilliseconds) -ForegroundColor Red exit 1 } Write-Host " Every call above is one round trip: client -> facade -> direct-vm -> Core -> back." -ForegroundColor DarkGray Write-Host (" gRPC facade demo: all steps passed in {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Green exit 0 Path: redb-identity/demos/demo_introspect_revoke.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_introspect_revoke.ps1 ---- # Token introspection (RFC 7662) + revocation (RFC 7009). # password grant → introspect (active=true) → revoke → introspect (active=false) → userinfo (rejected). # Usage: pwsh -File demo_introspect_revoke.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — password grant client. $reg = Measure-Step "1. DCR /connect/register (password)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "introspect-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access" } | ConvertTo-Json) } # 2) Seed user. $user = "intro_$([Guid]::NewGuid().ToString('N').Substring(0,8))" Measure-Step "2. account/register" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = "Test1234Pass!" displayName = $user } | ConvertTo-Json) } catch { Write-Host " (already exists or non-fatal: $($_.Exception.Message))" -ForegroundColor Yellow } } | Out-Null # 3) password grant. $tok = Measure-Step "3. password grant" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = "Test1234Pass!" scope = "openid profile email offline_access" } } Write-Host " access_token : $($tok.access_token.Substring(0,32))…" Write-Host " refresh_token : $($tok.refresh_token.Substring(0,32))…" # 4) Introspect — expect active=true. $intro1 = Measure-Step "4. POST /connect/introspect (before revoke)" { Invoke-RestMethod -Method Post "$BASE/connect/introspect" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ token = $tok.access_token client_id = $reg.client_id client_secret = $reg.client_secret } } Write-Host (" active = " + $intro1.active) -ForegroundColor (&{ if ($intro1.active) { 'Green' } else { 'Red' } }) $intro1 | ConvertTo-Json -Depth 5 | Out-Host # 5) /connect/userinfo — should succeed with valid token. Measure-Step "5. GET /connect/userinfo (before revoke)" { $h = @{ Authorization = "Bearer $($tok.access_token)" } Invoke-RestMethod -Method Get "$BASE/connect/userinfo" -Headers $h } | ConvertTo-Json -Depth 5 | Out-Host # 6) Revoke the access_token. Measure-Step "6. POST /connect/revocation (access_token)" { Invoke-RestMethod -Method Post "$BASE/connect/revocation" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ token = $tok.access_token token_type_hint = "access_token" client_id = $reg.client_id client_secret = $reg.client_secret } } | Out-Null Write-Host " (RFC 7009: revoke returns 200 with empty body on success)" -ForegroundColor DarkGray # 7) Introspect again — expect either active=false (RFC 7662) or 401 invalid_token # (OpenIddict default: rejects revoked/inactive tokens at the introspection # handler instead of returning {active:false}). Both outcomes prove the # revocation took effect. $intro2 = Measure-Step "7. POST /connect/introspect (after revoke)" { try { Invoke-RestMethod -Method Post "$BASE/connect/introspect" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ token = $tok.access_token client_id = $reg.client_id client_secret = $reg.client_secret } } catch { $code = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -eq 401) { Write-Host " 401 invalid_token — token is no longer valid (revoke proven)" -ForegroundColor Green return [pscustomobject]@{ active = $false; revoked = $true } } throw } } $activeAfter = $false if ($null -ne $intro2 -and $intro2.PSObject.Properties.Name -contains 'active') { $activeAfter = [bool]$intro2.active } Write-Host (" active = " + $activeAfter) -ForegroundColor (&{ if (-not $activeAfter) { 'Green' } else { 'Red' } }) $intro2 | ConvertTo-Json -Depth 5 | Out-Host # 8) Userinfo — should now fail (401). Measure-Step "8. GET /connect/userinfo (after revoke — expect 401)" { $h = @{ Authorization = "Bearer $($tok.access_token)" } try { $r = Invoke-WebRequest -Method Get "$BASE/connect/userinfo" -Headers $h -ErrorAction Stop Write-Host (" UNEXPECTED success status={0}" -f $r.StatusCode) -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -in 401,403) { Write-Host (" rejected as expected: {0}" -f $code) -ForegroundColor Green } else { throw "unexpected status $code" } } } | Out-Null # 9) Revoke refresh_token too (so the chain is fully closed). Measure-Step "9. POST /connect/revocation (refresh_token)" { Invoke-RestMethod -Method Post "$BASE/connect/revocation" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ token = $tok.refresh_token token_type_hint = "refresh_token" client_id = $reg.client_id client_secret = $reg.client_secret } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_jar_request_object.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_jar_request_object.ps1 ---- # JAR — JWT-Secured Authorization Request (RFC 9101, Z7). # The client sends the authorization parameters as a SIGNED JWT in `request`, # instead of as plain query parameters. The server verifies the signature # against the client's registered key before it trusts anything inside. # # This is an RFC-compliance probe. It asserts the server: # * advertises JAR in discovery (request_parameter_supported, alg values); # * accepts a validly signed request object (redirects to login, not error); # * takes parameters from INSIDE the JWT over the outside (§6.1); # * fetches a request_uri the client registered, and refuses one it did not # (invalid_request_uri, never contacted: Jar.RequireRequestUriRegistration); # * rejects an UNSIGNED object (alg:none) — the whole point of JAR; # * rejects an object signed by the WRONG key. # # The client registers an inline JWKS (its public key) and its request_uris via # DCR; the demo signs with the matching private key. No browser needed — a signed # request object is accepted headlessly, and the 302 to /login IS the success signal. # Usage: pwsh -File demo_jar_request_object.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $fail = 0 function Assert([string]$What, [bool]$Cond, [string]$Detail = "") { if ($Cond) { Write-Host " PASS $What" -ForegroundColor Green } else { Write-Host " FAIL $What $Detail" -ForegroundColor Red; $script:fail++ } } function B64U([byte[]]$bytes) { [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=') } function B64UStr([string]$s) { B64U ([Text.Encoding]::UTF8.GetBytes($s)) } # Drives /connect/authorize headless (no redirect following) and returns the # OAuth error, or $null when the request was accepted. # # The error surfaces two ways, both of which we must read: # * as error=... on a 302 Location, when the redirect_uri is trusted; # * as a direct 4xx JSON body {"error":...}, when it is NOT — which is exactly # what a bad request object triggers (OIDC 3.1.2.6: never redirect an error # to an unverified redirect_uri). A signed-but-rejected object has no trusted # redirect_uri, so the server answers straight to the caller. function Invoke-Authorize([hashtable]$Form) { try { $resp = Invoke-WebRequest -Method Post "$BASE/connect/authorize" ` -ContentType 'application/x-www-form-urlencoded' -Body $Form ` -MaximumRedirection 0 -ErrorAction Stop $loc = $resp.Headers.Location } catch { $r = $_.Exception.Response $loc = $r.Headers.Location if (-not $loc) { # Direct (non-redirect) response — read the OAuth error from the JSON body. try { $body = $_.ErrorDetails.Message if (-not $body -and $r) { $stream = $r.GetResponseStream() $body = [IO.StreamReader]::new($stream).ReadToEnd() } $json = $body | ConvertFrom-Json if ($json.error) { return [string]$json.error } } catch { } } $loc = [string]$loc } if ($loc -match 'error=([^&]+)') { return [Uri]::UnescapeDataString($Matches[1]) } return $null # redirected to login/consent, no error → accepted } # ── 0. discovery advertises JAR ──────────────────────────────────────────────── Write-Host "`n=== [0] discovery ===" -ForegroundColor Cyan $disco = Invoke-RestMethod "$BASE/.well-known/openid-configuration" # RFC 9101 §4: the request object's `aud` MUST be the OP's issuer identifier — which is not # necessarily the base URL we dial (a conformance profile issues host.docker.internal). Take it # from discovery so aud matches whatever the server actually calls itself. $ISSUER = $disco.issuer.TrimEnd('/') Assert "request_parameter_supported = true" ($disco.request_parameter_supported -eq $true) Assert "request_object_signing_alg_values_supported advertises RS256" ` ($disco.request_object_signing_alg_values_supported -contains 'RS256') # ── 1. RSA keypair + inline JWKS ─────────────────────────────────────────────── Write-Host "`n=== [1] RSA key + DCR with inline JWKS ===" -ForegroundColor Cyan $rsa = [System.Security.Cryptography.RSA]::Create(2048) $p = $rsa.ExportParameters($false) # public only $kid = [Guid]::NewGuid().ToString('N').Substring(0, 8) $jwk = [ordered]@{ kty='RSA'; use='sig'; alg='RS256'; kid=$kid; n=(B64U $p.Modulus); e=(B64U $p.Exponent) } $jwks = @{ keys = @($jwk) } # The address step 3b serves its request object from. A request_uri is fetched only when it equals one of the # client's registered request_uris (OIDC Dynamic Client Registration 1.0 §2), so the client registers it here. $RO_PORT = 39217 $RO_URI = "http://127.0.0.1:$RO_PORT/ro" $reg = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType 'application/json' -Body (@{ client_name = "jar-demo" redirect_uris = @($REDIRECT) grant_types = @('authorization_code') response_types = @('code') scope = "openid profile email" token_endpoint_auth_method = "private_key_jwt" jwks = $jwks request_uris = @($RO_URI) } | ConvertTo-Json -Depth 8) $cid = $reg.client_id Assert "client registered with inline JWKS" (-not [string]::IsNullOrEmpty($cid)) Assert "registration answers the registered request_uris" (@($reg.request_uris) -contains $RO_URI) "got: $($reg.request_uris -join ', ')" # Signs a request object (RS256) for this client with the matching private key. function New-RequestObject([hashtable]$Claims, [string]$Alg = 'RS256', [System.Security.Cryptography.RSA]$Key = $rsa) { $now = [DateTimeOffset]::UtcNow $payload = @{ iss=$cid; aud=$ISSUER; client_id=$cid iat=$now.ToUnixTimeSeconds(); exp=$now.AddMinutes(5).ToUnixTimeSeconds() } foreach ($k in $Claims.Keys) { $payload[$k] = $Claims[$k] } $header = @{ alg=$Alg; typ='JWT'; kid=$kid } $h = B64UStr ($header | ConvertTo-Json -Compress) $b = B64UStr ($payload | ConvertTo-Json -Compress) $signingInput = [Text.Encoding]::ASCII.GetBytes("$h.$b") $sig = $Key.SignData($signingInput, [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) "$h.$b." + (B64U $sig) } # ── 2. a validly signed request object is accepted ───────────────────────────── Write-Host "`n=== [2] signed request object → accepted ===" -ForegroundColor Cyan $ro = New-RequestObject @{ response_type='code'; scope='openid profile'; redirect_uri=$REDIRECT; state='s1' } $err = Invoke-Authorize @{ client_id=$cid; request=$ro } Assert "authorize accepted the signed request object (no OAuth error)" ($null -eq $err) "error: $err" # ── 3. parameters inside the JWT win over the outside (§6.1) ──────────────────── Write-Host "`n=== [3] inner parameters override outer (6.1) ===" -ForegroundColor Cyan # Outer scope is garbage; the signed scope is valid. If the server honoured the # outer value the request would fail on the unknown scope — acceptance proves the # inner (signed) parameters are the ones used. $ro3 = New-RequestObject @{ response_type='code'; scope='openid'; redirect_uri=$REDIRECT; state='s3' } $err = Invoke-Authorize @{ client_id=$cid; request=$ro3; scope='this-scope-does-not-exist' } Assert "signed parameters are authoritative, outer ignored" ($null -eq $err) "error: $err" # ── 3b. request_uri (by reference) — the server fetches the signed object ─────── Write-Host "`n=== [3b] request_uri (by reference) → fetched + accepted ===" -ForegroundColor Cyan # Host the signed request object on a throwaway HTTP listener at the registered address; hand the server its URL. # The server fetches it (SSRF-guarded; the development context allows loopback and plain http) and validates it. $roUri = New-RequestObject @{ response_type='code'; scope='openid profile'; redirect_uri=$REDIRECT; state='s3b' } $listener = [System.Net.HttpListener]::new() $listener.Prefixes.Add("http://127.0.0.1:$RO_PORT/") $listener.Start() $serveJob = Start-ThreadJob -ScriptBlock { param($l, $jwt) $ctx = $l.GetContext() $bytes = [Text.Encoding]::ASCII.GetBytes($jwt) $ctx.Response.ContentType = 'application/oauth-authz-req+jwt' $ctx.Response.OutputStream.Write($bytes, 0, $bytes.Length) $ctx.Response.Close() } -ArgumentList $listener, $roUri try { $err = Invoke-Authorize @{ client_id=$cid; request_uri=$RO_URI } Assert "authorize fetched and accepted the request_uri object" ($null -eq $err) "error: $err" } finally { # Stop the listener first: when the server did not fetch, the job is still blocked in GetContext(), and only # Stop() releases it. Removing the job before that waits for the blocked thread for ever. $serveJob | Wait-Job -Timeout 5 | Out-Null $listener.Stop(); $listener.Close() $serveJob | Wait-Job -Timeout 5 | Out-Null $serveJob | Remove-Job -Force -EA SilentlyContinue } # ── 3c. a request_uri the client did not register is refused, never fetched ─── Write-Host "`n=== [3c] unregistered request_uri → refused ===" -ForegroundColor Cyan $err = Invoke-Authorize @{ client_id=$cid; request_uri="http://127.0.0.1:$RO_PORT/other" } Assert "unregistered request_uri refused with invalid_request_uri" ($err -eq 'invalid_request_uri') "got: $err" # NB: the SSRF guard (refusing a request_uri that resolves to an internal address) is NOT probed # here — this dev profile sets RequestUriAllowPrivateNetworkTargets=true so the loopback listener # above is reachable, which by definition disables the guard. It is covered by the unit test # ValidateRequestObjectHandlerTests.Request_uri_to_internal_target_is_refused (default options). # ── 4. unsigned request object (alg:none) is rejected ────────────────────────── Write-Host "`n=== [4] alg:none → rejected ===" -ForegroundColor Cyan $h = B64UStr (@{ alg='none'; typ='JWT' } | ConvertTo-Json -Compress) $b = B64UStr (@{ iss=$cid; client_id=$cid; response_type='code'; scope='openid'; redirect_uri=$REDIRECT } | ConvertTo-Json -Compress) $noneRo = "$h.$b." $err = Invoke-Authorize @{ client_id=$cid; request=$noneRo } Assert "unsigned request object rejected with invalid_request_object" ($err -eq 'invalid_request_object') "got: $err" # ── 5. wrong-key signature is rejected ───────────────────────────────────────── Write-Host "`n=== [5] wrong key → rejected ===" -ForegroundColor Cyan $attacker = [System.Security.Cryptography.RSA]::Create(2048) $ro5 = New-RequestObject -Key $attacker @{ response_type='code'; scope='openid'; redirect_uri=$REDIRECT; state='s5' } $err = Invoke-Authorize @{ client_id=$cid; request=$ro5 } Assert "request object signed by the wrong key rejected" ($err -eq 'invalid_request_object') "got: $err" Write-Host "" if ($fail -eq 0) { Write-Host "OK - JAR (RFC 9101): all assertions passed" -ForegroundColor Green; exit 0 } else { Write-Host "FAILED - $fail JAR assertion(s) failed" -ForegroundColor Red; exit 1 } Path: redb-identity/demos/demo_jwks_rotation.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_jwks_rotation.ps1 ---- # JWKS rotation — admin signing-key lifecycle + live JWKS observability. # # Closes the 🟦 JWKS-rotation backlog item from DEMO_COVERAGE_MATRIX.md. # # Server contract this demo locks in: # • admin can list every stored key row (active + demoted + retired) with audit trail # • POST /signing-keys/rotate mints a fresh active key AND demotes previously-active keys # of the same kind, preserving their NotAfter window for a grace overlap # • DELETE /signing-keys/{kid} ends the validity window (NotAfter=now) so the key drops # out of the JWKS on the next request — admin list still carries the row with inJwks=false # • /.well-known/jwks reads keys LIVE from the store on every request (LiveJwksProcessor): # rotate / retire are visible to RPs immediately, without process restart # • only public JWK material is exposed (no `d`, `p`, `q`, …) on either endpoint # # Batch 12 contract (live-refresh, fully delivered): # • Rotate / retire invalidate IOptionsMonitorCache for both server and validation # options, so the next options read re-runs every PostConfigure. # • PostConfigure splits the key pool: SigningCredentials gets only in-window keys # (NotBefore <= now < NotAfter) so OpenIddict never mints under a retired kid; # TokenValidationParameters.IssuerSigningKeys gets the full pool (including retired) # so in-flight tokens signed under previously-active-then-retired kids still validate. # • Asserted at steps 8/11: after rotate, ROPC id_token.kid IS the just-rotated kid. # # Usage: pwsh -File demo_jwks_rotation.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR admin client. $adminReg = Measure-Step "1. DCR (cc + identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "jwks-rotation" grant_types = @("client_credentials") scope = "identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } | ConvertTo-Json) if (-not $r.client_id) { throw "DCR no client_id" } Write-Host " client_id: $($r.client_id)" -ForegroundColor Green return $r } $ADMIN_RAT = $adminReg.registration_access_token $ADMIN_RCU = $adminReg.registration_client_uri # 2) cc token (admin auth). $adminTok = Measure-Step "2. cc token (scope=identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write)" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $adminReg.client_id client_secret = $adminReg.client_secret scope = "identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } if (-not $t.access_token) { throw "no access_token" } return $t } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)" } # 3) GET /signing-keys → snapshot baseline; note count, kinds present. $baselineAdmin = Measure-Step "3. GET /signing-keys -> admin baseline snapshot" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/signing-keys" -Headers $ADMIN if (-not $r.keys -or $r.keys.Count -lt 1) { throw "admin list returned no keys" } $kinds = ($r.keys | ForEach-Object { $_.kind } | Sort-Object -Unique) -join "," Write-Host " baseline: $($r.keys.Count) keys (kinds: $kinds)" -ForegroundColor Green return $r } # 4) GET /.well-known/jwks → live JWKS baseline. Assert every kid in JWKS appears in admin # list AND has inJwks=true there — proves the live reader is honoured. Also catches a # private-material leak regression on the public endpoint. $baselineJwks = Measure-Step "4. GET /.well-known/jwks -> live snapshot consistent with admin" { $r = Invoke-RestMethod -Method Get "$BASE/.well-known/jwks" if (-not $r.keys -or $r.keys.Count -lt 1) { throw "JWKS empty" } $jwksKids = $r.keys | ForEach-Object { $_.kid } foreach ($kid in $jwksKids) { $adminRow = $baselineAdmin.keys | Where-Object { $_.kid -eq $kid } | Select-Object -First 1 if (-not $adminRow) { throw "JWKS exposes kid=$kid that is absent from admin list" } if (-not $adminRow.inJwks) { throw "JWKS exposes kid=$kid but admin reports inJwks=false" } } foreach ($jwk in $r.keys) { foreach ($priv in @('d','p','q','dp','dq','qi')) { if ($jwk.PSObject.Properties.Name -contains $priv -and $null -ne $jwk.$priv) { throw "JWKS LEAKED private component '$priv' for kid=$($jwk.kid)" } } if (-not $jwk.kid -or -not $jwk.n -or -not $jwk.e) { throw "JWKS entry malformed (kid/n/e missing): $(($jwk | ConvertTo-Json -Depth 3))" } if ($jwk.alg -ne "RS256") { throw "unexpected alg=$($jwk.alg) (only RS256 supported on this server)" } if ($jwk.use -ne "sig") { throw "unexpected use=$($jwk.use) (expected sig)" } } Write-Host " $($jwksKids.Count) live JWKS kids, all match admin inJwks=true, no private material" -ForegroundColor Green return $r } # 5) Rotate. Assert response shape, NotAfter window, new kid not in baseline. $rotResp = Measure-Step "5. POST /signing-keys/rotate -> new kid, NotAfter~now+90d, response shape" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/signing-keys/rotate" ` -Headers $ADMIN -ContentType "application/json" -Body (@{ kind = "signing" } | ConvertTo-Json) if (-not $r.kid) { throw "rotate response missing kid" } if (-not $r.isActive) { throw "rotate response: isActive must be true on freshly-minted key" } if ($r.kind -ne "signing") { throw "rotate response: kind='$($r.kind)' (expected 'signing')" } if ($r.algorithm -ne "RS256") { throw "rotate response: algorithm='$($r.algorithm)' (expected RS256)" } $baselineKids = $baselineAdmin.keys | ForEach-Object { $_.kid } if ($baselineKids -contains $r.kid) { throw "rotate response: kid='$($r.kid)' is NOT new (already in baseline)" } $notAfter = if ($r.notAfter -is [DateTime]) { [DateTimeOffset]::new($r.notAfter.ToUniversalTime()) } elseif ($r.notAfter -is [DateTimeOffset]) { $r.notAfter } else { [DateTimeOffset]::Parse($r.notAfter, [System.Globalization.CultureInfo]::InvariantCulture) } $delta = ($notAfter - [DateTimeOffset]::UtcNow).TotalDays if ($delta -lt 80 -or $delta -gt 100) { throw "NotAfter window suspicious: $delta days (expected ~90)" } Write-Host " new kid = $($r.kid), NotAfter $([int]$delta) d out" -ForegroundColor Green return $r } $Knew = $rotResp.kid # 6) Live JWKS now contains the new kid AND every previously-active signing kid (rotation grace). $jwksAfterRotate = Measure-Step "6. JWKS contains new kid AND retains all previously-active signing kids" { $r = Invoke-RestMethod -Method Get "$BASE/.well-known/jwks" $kids = $r.keys | ForEach-Object { $_.kid } if ($kids -notcontains $Knew) { throw "new kid $Knew not in JWKS after rotate (live reader broken)" } $stillExpected = $baselineAdmin.keys | Where-Object { $_.kind -eq "signing" -and $_.isActive -and $_.inJwks } | ForEach-Object { $_.kid } foreach ($e in $stillExpected) { if ($kids -notcontains $e) { throw "previously-active kid $e dropped from JWKS prematurely (grace window broken)" } } Write-Host " JWKS has $($kids.Count) kids, including new + retained" -ForegroundColor Green return $r } # 7) Admin list: new kid is the only isActive=true row for 'signing'; previously-active rows # are demoted to isActive=false but retain inJwks=true (within NotAfter window). Measure-Step "7. admin list: new kid is sole isActive signing, previous demoted+inJwks" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/signing-keys" -Headers $ADMIN $newRow = $r.keys | Where-Object { $_.kid -eq $Knew } | Select-Object -First 1 if (-not $newRow) { throw "new kid $Knew missing from admin list" } if (-not $newRow.isActive) { throw "new kid not flagged isActive=true in admin list" } if (-not $newRow.inJwks) { throw "new kid not flagged inJwks=true in admin list" } $activeSigning = @($r.keys | Where-Object { $_.kind -eq "signing" -and $_.isActive }) if ($activeSigning.Count -ne 1) { throw "expected exactly 1 active 'signing' row after rotate, got $($activeSigning.Count)" } foreach ($prev in $baselineAdmin.keys | Where-Object { $_.kind -eq "signing" -and $_.isActive }) { $row = $r.keys | Where-Object { $_.kid -eq $prev.kid } | Select-Object -First 1 if (-not $row) { throw "previously-active kid $($prev.kid) vanished from audit list" } if ($row.isActive) { throw "previously-active kid $($prev.kid) still flagged isActive=true after rotate" } } Write-Host " exactly 1 active signing key; previous demoted but retained" -ForegroundColor Green } | Out-Null # 8) **Live-refresh proof.** Spin up a ROPC client + user, mint a token, assert kid==Knew. # This is THE batch 12 contract: rotate invalidates BOTH server and validation options # caches; PostConfigure re-runs against the new store snapshot; new tokens are minted # under the just-rotated kid immediately, without any process restart. $liveRefreshUser = "rot_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $liveRefreshPwd = "Test1234Pass!" $liveRefreshReg = Measure-Step "8a. DCR ROPC + register user (for kid-after-rotate probe)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "jwks-rotation-live-refresh" grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" } | ConvertTo-Json) Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $liveRefreshUser; email = "$liveRefreshUser@example.com"; password = $liveRefreshPwd; displayName = $liveRefreshUser } | ConvertTo-Json) | Out-Null Write-Host " client + user ready" -ForegroundColor Green return $r } $LR_RAT = $liveRefreshReg.registration_access_token $LR_RCU = $liveRefreshReg.registration_client_uri function Get-JwtHeader([string]$jwt) { $b64 = $jwt.Split('.')[0].Replace('-','+').Replace('_','/') switch ($b64.Length % 4) { 2 { $b64 += '==' } 3 { $b64 += '=' } } [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64)) | ConvertFrom-Json } Measure-Step "8b. ROPC AFTER rotate -> id_token.kid == Knew (live refresh, no restart)" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $liveRefreshReg.client_id client_secret = $liveRefreshReg.client_secret username = $liveRefreshUser password = $liveRefreshPwd scope = "openid profile email" } if (-not $t.id_token) { throw "no id_token from ROPC" } $hdr = Get-JwtHeader $t.id_token if ($hdr.kid -ne $Knew) { throw "id_token.kid='$($hdr.kid)' but expected just-rotated kid '$Knew' — IOptionsMonitor refresh broken" } Write-Host " id_token.kid = $($hdr.kid) (matches Knew — refresh works)" -ForegroundColor Green } | Out-Null # 9) Rotate one more time so we have a fresh active key (K3) to keep signing under # AFTER we retire Knew (otherwise retiring our only active key would leave OpenIddict # unable to mint new tokens for subsequent demos). $rotResp2 = Measure-Step "9. rotate again -> K3 active, Knew demoted (sets up retire test)" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/signing-keys/rotate" ` -Headers $ADMIN -ContentType "application/json" -Body (@{ kind = "signing" } | ConvertTo-Json) if (-not $r.kid) { throw "rotate 2 missing kid" } if ($r.kid -eq $Knew) { throw "second rotate returned same kid" } if (-not $r.isActive) { throw "second rotate: isActive=false" } Write-Host " K3 = $($r.kid)" -ForegroundColor Green return $r } $Knewer = $rotResp2.kid # 10) Retire Knew (now demoted, never the active key — clean target). Measure-Step "10. DELETE /signing-keys/{Knew} -> success" { $r = Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/signing-keys/$Knew" -Headers $ADMIN if (-not $r.success) { throw "retire response not success-shaped: $($r | ConvertTo-Json -Depth 3)" } Write-Host " retired Knew" -ForegroundColor Green } | Out-Null # 11) **Live-refresh post-retire.** Mint another token; kid must be K3 (the new active), # proving retire propagated through OpenIddict's cache too. Measure-Step "11. ROPC AFTER retire -> id_token.kid == K3 (OpenIddict drops retired key)" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $liveRefreshReg.client_id client_secret = $liveRefreshReg.client_secret username = $liveRefreshUser password = $liveRefreshPwd scope = "openid profile email" } if (-not $t.id_token) { throw "no id_token from ROPC after retire" } $hdr = Get-JwtHeader $t.id_token if ($hdr.kid -eq $Knew) { throw "id_token.kid still == retired Knew '$Knew' — OpenIddict cache not invalidated on retire" } if ($hdr.kid -ne $Knewer) { throw "id_token.kid='$($hdr.kid)', expected K3='$Knewer'" } Write-Host " id_token.kid = $($hdr.kid) (matches K3, retired key dropped)" -ForegroundColor Green } | Out-Null # 12) Live JWKS no longer contains the retired kid. Measure-Step "12. JWKS no longer contains retired Knew" { $r = Invoke-RestMethod -Method Get "$BASE/.well-known/jwks" $kids = $r.keys | ForEach-Object { $_.kid } if ($kids -contains $Knew) { throw "retired kid $Knew still in JWKS" } if ($kids -notcontains $Knewer) { throw "K3=$Knewer missing from JWKS after retire of Knew" } Write-Host " retired kid gone (remaining: $($kids.Count))" -ForegroundColor Green } | Out-Null # 13) Admin list still carries the retired kid as audit trail, with inJwks=false now. Measure-Step "13. admin list audit trail: retired kid stays with inJwks=false" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/signing-keys" -Headers $ADMIN $row = $r.keys | Where-Object { $_.kid -eq $Knew } | Select-Object -First 1 if (-not $row) { throw "retired kid $Knew vanished from admin audit trail" } if ($row.inJwks) { throw "retired kid still reports inJwks=true" } if ($row.isActive) { throw "retired kid still reports isActive=true" } Write-Host " kid retained on audit trail (inJwks=false, isActive=false)" -ForegroundColor Green } | Out-Null # 14) Idempotence: re-retiring the same kid is a 200 no-op or 4xx, never 500. Measure-Step "14. DELETE same kid again -> idempotent (no 500)" { try { $r = Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/signing-keys/$Knew" -Headers $ADMIN Write-Host " second retire returned without throwing" -ForegroundColor Green } catch { $code = 0 if ($_.Exception.Response) { $code = [int]$_.Exception.Response.StatusCode } if ($code -ge 500) { throw "second retire returned $code (endpoint not idempotent / server bug)" } Write-Host " second retire returned HTTP $code (non-success ok)" -ForegroundColor Green } } | Out-Null # 15) Cleanup. Measure-Step "15. RFC 7592 DELETE admin + ROPC registrations" { if ($ADMIN_RAT) { Invoke-RestMethod -Method Delete -Uri $ADMIN_RCU -Headers @{ Authorization = "Bearer $ADMIN_RAT" } | Out-Null } if ($LR_RAT) { Invoke-RestMethod -Method Delete -Uri $LR_RCU -Headers @{ Authorization = "Bearer $LR_RAT" } | Out-Null } Write-Host " registrations deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_jwt.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_jwt.ps1 ---- # Per-step timing wrapper. Use: pwsh -File demo_jwt.ps1 # Each step prints its wall-clock duration; a final table summarises. $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step = $Name; Ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0); Status = "ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step = $Name; Ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0); Status = "fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — client registration $reg = Measure-Step "1. DCR /connect/register" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "jwt-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access" } | ConvertTo-Json) } $reg | Format-List client_id, client_secret # 2) Register the user (if not already present) Measure-Step "2. account/register" { try { Invoke-RestMethod -Method Post $BASE/api/v1/identity/account/register ` -ContentType "application/json" ` -Body (@{ login = "testuser2" email = "testuser2@example.com" password = "Test1234Pass!" displayName = "Test User 2" } | ConvertTo-Json) } catch { Write-Host " (already exists or non-fatal: $($_.Exception.Message))" -ForegroundColor Yellow } } | Out-Null # 3) Password grant → JWT $tok = Measure-Step "3. password grant /connect/token" { Invoke-RestMethod -Method Post $BASE/connect/token ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = "testuser2" password = "Test1234Pass!" scope = "openid profile email offline_access" } } $tok | Format-List access_token, id_token, refresh_token, expires_in # 4) Decode id_token (JWS — readable without a key) function Decode-Jwt([string]$jwt) { $payload = $jwt.Split('.')[1].Replace('-','+').Replace('_','/') $payload += '=' * ((4 - $payload.Length % 4) % 4) [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) | ConvertFrom-Json } Measure-Step "4. decode id_token (local)" { Decode-Jwt $tok.id_token | ConvertTo-Json } | Out-Host # 5) access_token — JWE-encrypted, claims via /connect/userinfo Measure-Step "5. /connect/userinfo" { Invoke-RestMethod $BASE/connect/userinfo ` -Headers @{ Authorization = "Bearer $($tok.access_token)" } | ConvertTo-Json } | Out-Host # 6) Refresh $refreshed = Measure-Step "6. refresh_token grant" { Invoke-RestMethod -Method Post $BASE/connect/token ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "refresh_token" client_id = $reg.client_id client_secret = $reg.client_secret refresh_token = $tok.refresh_token } } $refreshed | Format-List access_token, refresh_token, expires_in $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_logout_endsession.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_logout_endsession.ps1 ---- # Logout + RP-initiated end_session (OIDC Session Management + RFC 7009). # 1. ROPC → access + id + refresh tokens. # 2. Revoke refresh_token via /connect/revocation (RFC 7009). # 3. POST /connect/logout (RP-initiated, id_token_hint). # 4. GET /connect/endsession (OIDC headless probe). # 5. Verify revoked refresh_token no longer issues tokens. # 6. Verify revoked access_token rejected at /connect/userinfo (if introspection active). # Usage: pwsh -File demo_logout_endsession.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — password + refresh_token + post_logout_redirect_uris. $reg = Measure-Step "1. DCR /connect/register (password + post_logout_redirect_uris)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "logout-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" post_logout_redirect_uris = @("http://localhost:9999/post-logout") } | ConvertTo-Json) } $reg | Format-List client_id, client_secret # 2) Seed user. $user = "lgout_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) } | Out-Null # 3) ROPC → access + id + refresh tokens. $tok = Measure-Step "3. ROPC → access + id_token + refresh_token" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email offline_access identity:account" } } $bearer = @{ Authorization = "Bearer $($tok.access_token)" } Write-Host " access_token : $($tok.access_token.Substring(0,32))…" if ($tok.id_token) { Write-Host " id_token : $($tok.id_token.Substring(0,32))…" } else { Write-Host " id_token : (not issued — openid scope may not have been granted)" -ForegroundColor Yellow } Write-Host " refresh_token : $($tok.refresh_token.Substring(0,32))…" # 4) Sanity: userinfo works before any logout. Measure-Step "4. GET /connect/userinfo (before logout — expect 200)" { Invoke-RestMethod -Method Get "$BASE/connect/userinfo" -Headers $bearer } | ConvertTo-Json -Depth 3 | Out-Host # 5) Revoke refresh_token via /connect/revocation (RFC 7009). Measure-Step "5. POST /connect/revocation (refresh_token)" { Invoke-RestMethod -Method Post "$BASE/connect/revocation" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ token = $tok.refresh_token token_type_hint = "refresh_token" client_id = $reg.client_id client_secret = $reg.client_secret } Write-Host " ✓ RFC 7009 returns 200 even if token was already invalid" -ForegroundColor Green } | Out-Null # 6) Verify revoked refresh_token no longer issues tokens. Measure-Step "6. refresh_token after revoke (expect 400/401)" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "refresh_token" client_id = $reg.client_id client_secret = $reg.client_secret refresh_token = $tok.refresh_token } | Out-Null Write-Host " ! revoked refresh_token still issued tokens" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -in 400,401) { Write-Host " ✓ rejected: $code" -ForegroundColor Green } else { Write-Host " unexpected status: $code" -ForegroundColor Yellow } } } | Out-Null # 7) POST /connect/logout — RP-initiated with id_token_hint (OIDC Session §5). Measure-Step "7. POST /connect/logout (id_token_hint)" { if (-not $tok.id_token) { Write-Host " (skipped — no id_token was issued)" -ForegroundColor DarkGray return } $state = "s_$(Get-Random)" $form = "id_token_hint=$([uri]::EscapeDataString($tok.id_token))" + "&client_id=$([uri]::EscapeDataString($reg.client_id))" + "&post_logout_redirect_uri=$([uri]::EscapeDataString('http://localhost:9999/post-logout'))" + "&state=$state" # curl.exe, not Invoke-WebRequest: with -MaximumRedirection 0 the latter throws on an https→http # redirect and loses the status (same trap as in demo_federation_e2e). $out = & curl.exe -sk -o NUL -w "%{http_code} %{redirect_url}" -X POST "$BASE/connect/logout" ` -H "Content-Type: application/x-www-form-urlencoded" --data $form $code, $location = $out -split ' ', 2 Write-Host " status : $code" if ($code -notin '200','204','302','303') { throw "unexpected logout status: $code" } if ($code -in '302','303') { Write-Host " location : $location" # RP-Initiated Logout 1.0 §3: the RP's state comes back on the redirect, unchanged. if ($location -notmatch "state=$state") { throw "post-logout redirect lost the RP state: $location" } Write-Host " ✓ redirect to post_logout_redirect_uri carries the RP state" -ForegroundColor Green } else { Write-Host " ✓ logout accepted: $code (no registered post_logout_redirect_uri — signed-out page)" -ForegroundColor Green } } | Out-Null # 8) GET /connect/endsession?id_token_hint=… (OIDC RP-initiated, headless). Measure-Step "8. GET /connect/endsession?id_token_hint=…" { if (-not $tok.id_token) { Write-Host " (skipped — no id_token)" -ForegroundColor DarkGray return } $esUrl = "$BASE/connect/endsession?id_token_hint=$([Uri]::EscapeDataString($tok.id_token))&post_logout_redirect_uri=$([Uri]::EscapeDataString('http://localhost:9999/post-logout'))&state=es_$(Get-Random)" try { $wr = Invoke-WebRequest -Uri $esUrl -MaximumRedirection 0 -ErrorAction SilentlyContinue $code = $wr.StatusCode $loc = $wr.Headers['Location'] if ($code -in 200,302,303) { Write-Host " ✓ endsession: $code" -ForegroundColor Green if ($loc) { Write-Host " Location: $($loc.ToString().Substring(0,[Math]::Min(100,$loc.ToString().Length)))…" } } else { Write-Host " ! unexpected: $code" -ForegroundColor Yellow } } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -in 200,302,303) { Write-Host " ✓ endsession: $code" -ForegroundColor Green } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null # 9) Also revoke the access_token explicitly. Measure-Step "9. POST /connect/revocation (access_token)" { Invoke-RestMethod -Method Post "$BASE/connect/revocation" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ token = $tok.access_token token_type_hint = "access_token" client_id = $reg.client_id client_secret = $reg.client_secret } Write-Host " ✓ access_token revoke accepted" -ForegroundColor Green } | Out-Null # 10) /connect/userinfo after access_token revoke — self-contained JWTs survive until exp; # reference tokens or introspection-validated routes should return 401. Measure-Step "10. GET /connect/userinfo after access_token revoke" { try { $ui = Invoke-RestMethod -Method Get "$BASE/connect/userinfo" -Headers $bearer Write-Host " userinfo still accessible (self-contained JWT — lives until exp)" -ForegroundColor Yellow Write-Host " sub: $($ui.sub)" } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -eq 401) { Write-Host " ✓ 401 — server rejects revoked access_token" -ForegroundColor Green } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_loopback_redirect.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_loopback_redirect.ps1 ---- # RFC 8252 §7.3 — loopback redirect URI, port not compared. # # A native / CLI app (az login, gh auth login, any desktop OAuth client) cannot know its callback # port before it starts: it asks the OS for an ephemeral one, so the port is different on every run # and cannot be registered ahead of time. §7.3 requires the authorization server to compare # everything about a loopback redirect EXCEPT the port. # # That is a deliberate hole in redirect_uri matching, so most of this probe is NEGATIVE. The # widening must be exactly one port wide and not one inch more: # # §7.3 registered http://127.0.0.1:P/cb → http://127.0.0.1:/cb ACCEPTED # §7.3 the same for the IPv6 literal [::1] # §8.3 "localhost" is a NAME, not the loopback literal — it resolves, and a poisoned resolver # points it elsewhere. It must NOT be wildcarded. # path / query / scheme changes must NOT be wildcarded # a client with no registered loopback URI must NOT gain one # 6749 §4.1.2.1 — and every rejection must be reported by the OP itself, NEVER redirected to # the URI it just refused to trust. A rejected redirect that still redirects is the whole # attack. # # Usage: pwsh -File demo_loopback_redirect.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $script:Failures = 0 function Assert([string]$What, [bool]$Ok, [string]$Detail = "") { if ($Ok) { Write-Host " PASS $What" -ForegroundColor Green } else { $script:Failures++; Write-Host " FAIL $What $Detail" -ForegroundColor Red } } function ConvertTo-Base64Url([byte[]]$b) { [Convert]::ToBase64String($b).TrimEnd('=').Replace('+', '-').Replace('/', '_') } function New-Pkce { $vb = New-Object byte[] 32 [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($vb) $v = ConvertTo-Base64Url $vb $c = ConvertTo-Base64Url ([System.Security.Cryptography.SHA256]::Create().ComputeHash( [Text.Encoding]::ASCII.GetBytes($v))) [pscustomobject]@{ Verifier = $v; Challenge = $c } } function New-Client([string[]]$RedirectUris) { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" -Body (@{ client_name = "loopback-demo" redirect_uris = $RedirectUris grant_types = @("authorization_code") response_types = @("code") token_endpoint_auth_method = "none" # public client — the native-app shape (RFC 8252 §8.4) } | ConvertTo-Json) } # A logged-in browser session; every probe below reuses it, so a rejection can only come from # redirect_uri validation and not from a missing session. # # Driven through HttpClient rather than Invoke-WebRequest: a successful loopback authorize answers # 302 with an http:// Location (that is the point of RFC 8252 — the native app listens on plain http # on the loopback interface), and Invoke-WebRequest refuses to hand back an https→http redirect at # all. That is a limitation of the PowerShell client, not of the server, and it would silently turn # the PASS case into an exception. $user = "lb_$([Guid]::NewGuid().ToString('N').Substring(0,8))" Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" -Body (@{ login = $user; email = "$user@example.com"; password = "Test1234Pass!"; displayName = $user } | ConvertTo-Json) | Out-Null Add-Type -AssemblyName System.Net.Http $cookies = New-Object System.Net.CookieContainer $handler = New-Object System.Net.Http.HttpClientHandler $handler.AllowAutoRedirect = $false # the 302 IS the result we inspect $handler.CookieContainer = $cookies $handler.ServerCertificateCustomValidationCallback = ` [System.Net.Http.HttpClientHandler]::DangerousAcceptAnyServerCertificateValidator $http = New-Object System.Net.Http.HttpClient($handler) function Send-Form([string]$Url, [hashtable]$Form) { $pairs = New-Object 'System.Collections.Generic.List[System.Collections.Generic.KeyValuePair[string,string]]' foreach ($k in $Form.Keys) { $pairs.Add([System.Collections.Generic.KeyValuePair[string, string]]::new($k, [string]$Form[$k])) } # ::new(), not New-Object — New-Object unrolls the list into varargs and silently fails to # construct the content, which would send every request with an empty body and make every probe # below "pass" for the wrong reason. $content = [System.Net.Http.FormUrlEncodedContent]::new($pairs) $http.PostAsync($Url, $content).GetAwaiter().GetResult() } $login = Send-Form "$BASE/login" @{ username = $user; password = "Test1234Pass!" } if ([int]$login.StatusCode -notin 200, 302) { throw "login failed: $([int]$login.StatusCode)" } # Returns { code, error, location, status } — `location` matters as much as `error`: a refused # redirect_uri must never appear in a Location header. function Invoke-Authorize([string]$ClientId, [string]$RedirectUri, $Pkce) { $resp = Send-Form "$BASE/connect/authorize" @{ response_type = "code" client_id = $ClientId redirect_uri = $RedirectUri scope = "openid" state = "st-$([Guid]::NewGuid().ToString('N').Substring(0,6))" nonce = [Guid]::NewGuid().ToString('N') code_challenge = $Pkce.Challenge code_challenge_method = "S256" } $loc = if ($resp.Headers.Location) { $resp.Headers.Location.ToString() } else { $null } $kv = @{} if ($loc -and $loc.Contains('?')) { foreach ($pair in $loc.Substring($loc.IndexOf('?') + 1).Split('&')) { $i = $pair.IndexOf('=') if ($i -gt 0) { $kv[$pair.Substring(0, $i)] = [uri]::UnescapeDataString($pair.Substring($i + 1)) } } } [pscustomobject]@{ code = $kv.code; error = $kv.error; location = $loc; status = [int]$resp.StatusCode } } # ── 1. THE POSITIVE: a registered loopback URI, called back on a different port ──────────────── Write-Host "`n=== [1] registered http://127.0.0.1:8080/cb -> called back on :54321 ===" -ForegroundColor Cyan $c = New-Client @("http://127.0.0.1:8080/cb") $pkce = New-Pkce $a = Invoke-Authorize $c.client_id "http://127.0.0.1:54321/cb" $pkce Assert "a code is issued on a port that was never registered (RFC 8252 §7.3)" ($null -ne $a.code) ` "error=$($a.error) status=$($a.status)" # And the code must actually redeem — validation happens again at the token endpoint, against the # very same URI. A rule applied at authorize but not at /token would just move the failure. if ($a.code) { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" -Body @{ grant_type = "authorization_code"; client_id = $c.client_id redirect_uri = "http://127.0.0.1:54321/cb"; code = $a.code; code_verifier = $pkce.Verifier } Assert "the code redeems at /connect/token with that same ephemeral-port URI" ($null -ne $t.access_token) } # ── 2. the IPv6 loopback literal, same rule ─────────────────────────────────────────────────── Write-Host "`n=== [2] IPv6 loopback [::1] ===" -ForegroundColor Cyan $c6 = New-Client @("http://[::1]:8080/cb") $a = Invoke-Authorize $c6.client_id "http://[::1]:9999/cb" (New-Pkce) Assert "[::1] gets the same port wildcard as 127.0.0.1" ($null -ne $a.code) "error=$($a.error)" # ══ NEGATIVES ══ everything below MUST be refused ═════════════════════════════════════════════ # ── 3. §8.3 "localhost" is a name, not the loopback literal ──────────────────────────────────── # It goes through resolution. A hosts-file entry or a poisoned resolver points it at a machine that # is not the loopback interface — and port-wildcarding it would hand that machine every callback. Write-Host "`n=== [3] localhost must NOT be port-wildcarded (§8.3) ===" -ForegroundColor Cyan $cl = New-Client @("http://localhost:8080/cb") $a = Invoke-Authorize $cl.client_id "http://localhost:9999/cb" (New-Pkce) Assert "localhost on another port is REJECTED — it is a name, not 127.0.0.1" ($null -eq $a.code) ` "code was issued: $($a.code)" Assert "...and the refused URI is NOT in a Location header (RFC 6749 §4.1.2.1)" ` ($a.location -notlike '*localhost:9999*') "location=$($a.location)" # ── 4. the port, and ONLY the port ──────────────────────────────────────────────────────────── Write-Host "`n=== [4] path / query / scheme are still compared exactly ===" -ForegroundColor Cyan $a = Invoke-Authorize $c.client_id "http://127.0.0.1:54321/evil" (New-Pkce) Assert "a different PATH is rejected" ($null -eq $a.code) "code=$($a.code)" $a = Invoke-Authorize $c.client_id "http://127.0.0.1:54321/cb?next=https://evil.example" (New-Pkce) Assert "an added QUERY is rejected" ($null -eq $a.code) "code=$($a.code)" $a = Invoke-Authorize $c.client_id "https://127.0.0.1:54321/cb" (New-Pkce) Assert "a different SCHEME is rejected" ($null -eq $a.code) "code=$($a.code)" $a = Invoke-Authorize $c.client_id "http://user:pass@127.0.0.1:54321/cb" (New-Pkce) Assert "userinfo in the URI is rejected" ($null -eq $a.code) "code=$($a.code)" # ── 5. a client with no loopback registration gains nothing ──────────────────────────────────── # This is the containment property: the widening is not "loopback is allowed", it is "a client that # ALREADY registered a loopback URI may vary its port". Write-Host "`n=== [5] a web client cannot be talked into a loopback callback ===" -ForegroundColor Cyan $cw = New-Client @("https://app.example.com/cb") $a = Invoke-Authorize $cw.client_id "http://127.0.0.1:54321/cb" (New-Pkce) Assert "a client registered only at https://app.example.com/cb is REJECTED for 127.0.0.1" ` ($null -eq $a.code) "code=$($a.code)" Assert "...and no Location points at 127.0.0.1 either" ` ($a.location -notlike '*127.0.0.1:54321*') "location=$($a.location)" # ── 6. a loopback client cannot reach out to the internet ────────────────────────────────────── Write-Host "`n=== [6] a loopback client cannot redirect off-box ===" -ForegroundColor Cyan $a = Invoke-Authorize $c.client_id "https://evil.example.com/cb" (New-Pkce) Assert "an external URI is rejected for a loopback-registered client" ($null -eq $a.code) "code=$($a.code)" Assert "...and the error is shown by the OP, not redirected to evil.example.com" ` ($a.location -notlike '*evil.example.com*') "location=$($a.location)" Write-Host "" if ($script:Failures -eq 0) { Write-Host "OK - RFC 8252 7.3 loopback: accepted where the spec says, refused everywhere else" -ForegroundColor Green exit 0 } Write-Host "FAIL($script:Failures) - see above" -ForegroundColor Red exit 1 Path: redb-identity/demos/demo_me_delete.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_me_delete.ps1 ---- # Self-service account deletion — DELETE /api/v1/identity/me. # # Closes release-gate item #2. Builds on the user-contract for `_users`: # • `_login` is immutable forever (PG-trigger `protect_system_users`) # • `_name` is mutable (used for tombstoning the soft-deleted row) # • `_enabled=false + _date_dismiss=now` removes the user from regular queries # # Cascade revoke story (verified by this demo): # 1. SessionService.LogoutAsync kills every session for the user, which in turn # revokes the OpenIddict authorizations and invalidates the access/refresh # tokens those sessions issued. # 2. UserProvider.DeleteUserAsync soft-deletes the `_users` row — login stays # occupied so re-registration with the same login is blocked. # 3. IdentityDeletionHelper soft-deletes the OIDC props object so admin search # / list no longer returns it. # # Steps: # 1. DCR password + admin clients # 2. self-register user # 3. ROPC token + admin cc token # 4. GET /me (sanity — user can see itself) # 5. DELETE /me → assert success=true + sessionsRevoked count # 6. GET /me with SAME bearer → expect 401 (token revoked, session killed) # 7. POST /token (ROPC same creds) → expect failure (user disabled) # 8. admin search by email → user not in queries (soft-deleted from view) # 9. re-register same login → expect failure (login slot occupied) # 10. DELETE /me again with stale bearer → still 401 (idempotency on caller side) # 11. cleanup DCR # # Usage: pwsh -File demo_me_delete.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() $user = "del_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $email = "$user@example.com" $pwd = "Test1234Pass!" # 1) DCRs. $userReg = Measure-Step "1a. DCR password client (for ROPC)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" -Body (@{ client_name = "me-delete" grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" } | ConvertTo-Json) } $U_RAT = $userReg.registration_access_token $U_RCU = $userReg.registration_client_uri $adminReg = Measure-Step "1b. DCR admin client (users.manage)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" -Body (@{ client_name = "me-delete-admin" grant_types = @("client_credentials") scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write" } | ConvertTo-Json) } $A_RAT = $adminReg.registration_access_token $A_RCU = $adminReg.registration_client_uri # 2) Self-register user. Measure-Step "2. self-register user $user" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" -Body (@{ login = $user; email = $email; password = $pwd; displayName = $user } | ConvertTo-Json) | Out-Null Write-Host " registered" -ForegroundColor Green } | Out-Null # 3a) ROPC user token. $userTok = Measure-Step "3a. ROPC token (user)" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" -Body @{ grant_type = "password" client_id = $userReg.client_id client_secret = $userReg.client_secret username = $user password = $pwd scope = "openid profile email identity:account" } } $U_HDR = @{ Authorization = "Bearer $($userTok.access_token)" } # 3b) Admin cc token. $adminTok = Measure-Step "3b. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" -Body @{ grant_type = "client_credentials" client_id = $adminReg.client_id client_secret = $adminReg.client_secret scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write" } } $A_HDR = @{ Authorization = "Bearer $($adminTok.access_token)" } # 4) Sanity GET /me. $meBefore = Measure-Step "4. GET /me (sanity — sees own profile)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me" -Headers $U_HDR if ($r.login -ne $user) { throw "GET /me returned login=$($r.login), expected $user" } Write-Host " login=$($r.login), email=$($r.email)" -ForegroundColor Green return $r } $userId = $meBefore.id # 5) DELETE /me. Measure-Step "5. DELETE /me → success + sessionsRevoked count" { $r = Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/me" -Headers $U_HDR if (-not $r.success) { throw "DELETE /me did not return success=true: $($r | ConvertTo-Json -Depth 3)" } if ($null -eq $r.sessionsRevoked) { throw "missing sessionsRevoked in response" } Write-Host " success=true, sessionsRevoked=$($r.sessionsRevoked)" -ForegroundColor Green } | Out-Null # 6) GET /me with same bearer → 401. Bearer JWTs are normally self-contained and stay # valid until exp, but DisabledUserRejectionHandler closes that gap: every validated # bearer is re-checked against the redb user store, and tokens for disabled / # soft-deleted users get rejected with invalid_token immediately. Measure-Step "6. GET /me with stale bearer → 401 (DisabledUserRejectionHandler)" { $code = 0 try { Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me" -Headers $U_HDR -ErrorAction Stop | Out-Null } catch { if ($_.Exception.Response) { $code = [int]$_.Exception.Response.StatusCode } elseif ($_.Exception.StatusCode) { $code = [int]$_.Exception.StatusCode } elseif ($_.ErrorDetails -and $_.ErrorDetails.Message -match '"error":"invalid_(token|grant)"') { $code = 401 } } if ($code -ne 401) { throw "expected 401, got $code — DisabledUserRejectionHandler not firing" } Write-Host " 401 (bearer rejected post-delete — DisabledUserRejectionHandler works)" -ForegroundColor Green } | Out-Null # 7) ROPC with same creds → fail (user disabled). Measure-Step "7. ROPC same creds → fail (user soft-deleted / disabled)" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" -Body @{ grant_type = "password" client_id = $userReg.client_id client_secret = $userReg.client_secret username = $user password = $pwd scope = "openid profile email" } -ErrorAction Stop | Out-Null throw "expected ROPC to fail, but token was issued" } catch { $code = 0 if ($_.Exception.Response) { $code = [int]$_.Exception.Response.StatusCode } elseif ($_.Exception.StatusCode) { $code = [int]$_.Exception.StatusCode } elseif ($_.ErrorDetails -and $_.ErrorDetails.Message -match '"error":"invalid_(token|grant)"') { $code = 401 } if ($code -lt 400) { throw "expected 4xx, got $code" } Write-Host " HTTP $code (no token for soft-deleted user)" -ForegroundColor Green } } | Out-Null # 8) Admin search by email → user gone from regular queries. Measure-Step "8. admin search by email → user filtered out (soft-delete hides from queries)" { $r = Invoke-RestMethod "$BASE/api/v1/identity/users/search?query=$email" -Headers $A_HDR $hits = if ($r.items) { $r.items } elseif ($r.results) { $r.results } else { $r } $found = @($hits | Where-Object { $_.email -eq $email -and $_.id -eq $userId }) if ($found.Count -gt 0) { throw "soft-deleted user still surfaced in search (id=$userId)" } Write-Host " user $userId not in search results" -ForegroundColor Green } | Out-Null # 9) Re-register SAME login → fail (login slot occupied). Measure-Step "9. re-register SAME login → fail (login immutable, slot occupied)" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" -Body (@{ login = $user; email = "$user-new@example.com"; password = $pwd; displayName = "$user-new" } | ConvertTo-Json) -ErrorAction Stop | Out-Null throw "expected re-register to fail (login already taken), but it succeeded" } catch { $code = 0 if ($_.Exception.Response) { $code = [int]$_.Exception.Response.StatusCode } elseif ($_.Exception.StatusCode) { $code = [int]$_.Exception.StatusCode } elseif ($_.ErrorDetails -and $_.ErrorDetails.Message -match '"error":"invalid_(token|grant)"') { $code = 401 } if ($code -lt 400) { throw "expected 4xx, got $code" } Write-Host " HTTP $code (login still occupied)" -ForegroundColor Green } } | Out-Null # 10) Second DELETE with stale bearer → 401 (bearer is rejected too). Measure-Step "10. DELETE /me again with stale bearer → 401 (also rejected)" { $code = 0 try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/me" -Headers $U_HDR -ErrorAction Stop | Out-Null } catch { if ($_.Exception.Response) { $code = [int]$_.Exception.Response.StatusCode } elseif ($_.Exception.StatusCode) { $code = [int]$_.Exception.StatusCode } elseif ($_.ErrorDetails -and $_.ErrorDetails.Message -match '"error":"invalid_(token|grant)"') { $code = 401 } } if ($code -ne 401) { throw "expected 401, got $code" } Write-Host " 401 (stale bearer cannot drive privileged ops)" -ForegroundColor Green } | Out-Null # 11) Cleanup. Measure-Step "11. RFC 7592 DELETE DCRs" { if ($U_RAT) { try { Invoke-RestMethod -Method Delete -Uri $U_RCU -Headers @{ Authorization = "Bearer $U_RAT" } | Out-Null } catch {} } if ($A_RAT) { try { Invoke-RestMethod -Method Delete -Uri $A_RCU -Headers @{ Authorization = "Bearer $A_RAT" } | Out-Null } catch {} } Write-Host " DCRs deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_me_email_change.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_me_email_change.ps1 ---- # /me change-email cycle (request → confirm with wrong token → verify rejection). # Full cycle requires intercepting the email; this demo probes the endpoint # contracts without a real SMTP inbox: # 1. Request email change → expect 200 + email sent. # 2. Confirm with bogus token → expect 400. # 3. Confirm for wrong email → expect 400 (no user enumeration). # 4. Confirm after email already taken by another user → expect 409. # Usage: pwsh -File demo_me_email_change.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR + seed primary user. $reg = Measure-Step "1. DCR /connect/register (password + identity:account)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "email-change-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" } | ConvertTo-Json) } $user = "echg_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" $email = "$user@example.com" Measure-Step "2. account/register (primary user)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = $email password = $pwd displayName = $user } | ConvertTo-Json) } | Out-Null # 3) Seed a second user whose email we'll try to steal. $user2 = "echg2_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $email2 = "$user2@example.com" Measure-Step "3. account/register (second user — owns $email2)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user2 email = $email2 password = $pwd displayName = $user2 } | ConvertTo-Json) } | Out-Null # 4) Login as primary user → access_token with identity:account scope. $tok = Measure-Step "4. ROPC → access_token (identity:account)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email offline_access identity:account" } } $bearer = @{ Authorization = "Bearer $($tok.access_token)" } Write-Host " access_token: $($tok.access_token.Substring(0,32))…" # 5) Request change to a fresh email address. $newEmail = "new_$([Guid]::NewGuid().ToString('N').Substring(0,8))@example.com" Measure-Step "5. POST /me/change-email/request (newEmail=$newEmail)" { try { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/change-email/request" ` -Headers $bearer ` -ContentType "application/json" ` -Body (@{ newEmail = $newEmail } | ConvertTo-Json) Write-Host " ✓ accepted" -ForegroundColor Green $r | ConvertTo-Json | Out-Host } catch { $code = $_.Exception.Response.StatusCode.value__ $body = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } Write-Host " status: $code body: $body" -ForegroundColor Yellow } } | Out-Null # 6) Confirm with bogus token → expect 400. $bogusToken = [Convert]::ToBase64String([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) Measure-Step "6. POST /me/change-email/confirm with bogus token (expect 400)" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/change-email/confirm" ` -Headers $bearer ` -ContentType "application/json" ` -Body (@{ newEmail = $newEmail; token = $bogusToken } | ConvertTo-Json) | Out-Null Write-Host " ! UNEXPECTED success — bogus token accepted" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ $body = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } if ($code -eq 400) { Write-Host " ✓ rejected: 400" -ForegroundColor Green if ($body) { Write-Host " body: $body" } } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null # 7) Try to change email to an address already owned by another user → expect 409/400. Measure-Step "7. POST /me/change-email/request to already-taken email (expect 400/409)" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/change-email/request" ` -Headers $bearer ` -ContentType "application/json" ` -Body (@{ newEmail = $email2 } | ConvertTo-Json) | Out-Null Write-Host " ! UNEXPECTED — email already owned by another user was accepted" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ $body = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } if ($code -in 400,409,422) { Write-Host " ✓ rejected: $code (email conflict)" -ForegroundColor Green if ($body) { Write-Host " body: $body" } } else { Write-Host " status: $code body: $body" -ForegroundColor Yellow } } } | Out-Null # 8) Same request — attempt confirm with mismatched email (token/email mismatch). Measure-Step "8. POST /me/change-email/confirm with email mismatch (expect 400)" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/change-email/confirm" ` -Headers $bearer ` -ContentType "application/json" ` -Body (@{ newEmail = "wrong_$(Get-Random)@example.com" token = $bogusToken } | ConvertTo-Json) | Out-Null Write-Host " ! UNEXPECTED success" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -eq 400) { Write-Host " ✓ rejected: 400" -ForegroundColor Green } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null # 9) Unauthenticated request → expect 401. Measure-Step "9. POST /me/change-email/request without token (expect 401)" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/change-email/request" ` -ContentType "application/json" ` -Body (@{ newEmail = $newEmail } | ConvertTo-Json) | Out-Null Write-Host " ! UNEXPECTED — unauthenticated request accepted" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -in 401,403) { Write-Host " ✓ rejected: $code" -ForegroundColor Green } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Write-Host "(to complete full email change: grab the confirm token from server logs and run step 5 manually)" -ForegroundColor DarkGray Path: redb-identity/demos/demo_me_profile.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_me_profile.ps1 ---- # /me profile + change password. # GET /me → PUT /me (displayName) → PUT /me/password → re-login with new password. # Usage: pwsh -File demo_me_profile.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() $oldPwd = "Test1234Pass!" $newPwd = "NewPass9876@@" # 1) DCR — password grant, with identity:account scope so /me endpoints are authorized. $reg = Measure-Step "1. DCR /connect/register (password + identity:account)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "me-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" } | ConvertTo-Json) } # 2) Seed user. $user = "me_$([Guid]::NewGuid().ToString('N').Substring(0,8))" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $oldPwd displayName = "$user (initial)" } | ConvertTo-Json) } | Out-Null # 3) password grant → access_token. $tok = Measure-Step "3. password grant (old password)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $oldPwd scope = "openid profile email offline_access identity:account" } } $bearer = @{ Authorization = "Bearer $($tok.access_token)" } # 4) GET /me — current profile. $me1 = Measure-Step "4. GET /api/v1/identity/me" { Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me" -Headers $bearer } $me1 | ConvertTo-Json -Depth 5 | Out-Host # 5) PUT /me — rename displayName. $newName = "$user (renamed)" Measure-Step "5. PUT /api/v1/identity/me (rename)" { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/me" ` -Headers $bearer ` -ContentType "application/json" ` -Body (@{ displayName = $newName } | ConvertTo-Json) } | Out-Null # 6) GET /me — confirm rename. $me2 = Measure-Step "6. GET /api/v1/identity/me (after rename)" { Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me" -Headers $bearer } if ($me2.displayName -eq $newName) { Write-Host " ✓ displayName persisted: $($me2.displayName)" -ForegroundColor Green } else { Write-Host " WARNING: displayName not updated (got: $($me2.displayName))" -ForegroundColor Red } # 7) PUT /me/password — change password. Measure-Step "7. PUT /api/v1/identity/me/password" { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/me/password" ` -Headers $bearer ` -ContentType "application/json" ` -Body (@{ oldPassword = $oldPwd newPassword = $newPwd } | ConvertTo-Json) } | Out-Null # 8) password grant with OLD password — must fail. Measure-Step "8. password grant with OLD password (expect fail)" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $oldPwd scope = "openid" } -ErrorAction Stop | Out-Null Write-Host " UNEXPECTED success — old password still works" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ Write-Host (" ✓ rejected: {0}" -f $code) -ForegroundColor Green } } | Out-Null # 9) password grant with NEW password — must succeed. $tok2 = Measure-Step "9. password grant with NEW password" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $newPwd scope = "openid profile email offline_access identity:account" } } Write-Host " new access_token: $($tok2.access_token.Substring(0,32))…" Write-Host " ✓ new password works" -ForegroundColor Green $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_me_sessions.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_me_sessions.ps1 ---- # Self-service session management — /api/v1/identity/me/sessions. # Bearer auth uses identity:account scope (not identity:manage). Caller can only # touch their own sessions; sub claim is the source of truth, never the body. # Coverage: GET list, DELETE /{id}, DELETE /others, DELETE /current. # # Sessions are OP sessions: each one is opened by an interactive POST /login (cookie). # A password grant (ROPC) opens none, so this demo signs in three "devices" through # /login and takes each device's token through authorization_code + PKCE; that token # carries the device's session id in the sid claim, which /others and /current use. # # What a revoke does: the session ends and its cookie no longer signs in silently at # /connect/authorize (prompt=none -> login_required). Tokens already issued are left # alone and live until they expire; refresh tokens exist only with offline_access, # which OIDC Core §11 defines as access while the End-User is not logged in. # # Usage: pwsh -File demo_me_sessions.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $SCOPE = "openid profile identity:account" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function ConvertTo-Base64Url([byte[]]$bytes) { [Convert]::ToBase64String($bytes).TrimEnd('=').Replace('+','-').Replace('/','_') } function Get-JwtPayload([string]$jwt) { $p = $jwt.Split('.')[1].Replace('-','+').Replace('_','/') switch ($p.Length % 4) { 2 { $p += '==' } 3 { $p += '=' } } [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($p)) | ConvertFrom-Json } # Query parameters of the Location header of an /connect/authorize answer (no redirects followed). function Invoke-Authorize { param($Session, [hashtable]$Body) $resp = $null try { $resp = Invoke-WebRequest -Method Post "$BASE/connect/authorize" -WebSession $Session ` -ContentType "application/x-www-form-urlencoded" -Body $Body -MaximumRedirection 0 -ErrorAction Stop } catch { $resp = $_.Exception.Response } $location = if ($resp -is [System.Net.Http.HttpResponseMessage]) { [string]$resp.Headers.Location } else { [string]$resp.Headers["Location"] } if (-not $location) { throw "no Location header on /connect/authorize response" } $kv = @{ location = $location } $u = [uri]::new([uri]$BASE, $location) foreach ($pair in $u.Query.TrimStart('?').Split('&')) { $i = $pair.IndexOf('=') if ($i -gt 0) { $kv[$pair.Substring(0,$i)] = [uri]::UnescapeDataString($pair.Substring($i+1)) } } $kv } # One device: its own cookie jar, POST /login, then code + PKCE for a session-bound token. function New-Device { param([int]$N) $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession try { Invoke-WebRequest -Method Post "$BASE/login" -WebSession $session ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ username = $user; password = $pwd } -MaximumRedirection 0 -ErrorAction Stop | Out-Null } catch { if ($_.Exception.Response.StatusCode.value__ -notin 200,302) { throw } } if ($session.Cookies.GetCookies("$BASE").Count -lt 1) { throw "no session cookie was set by /login" } $verifierBytes = New-Object byte[] 32 [System.Security.Cryptography.RandomNumberGenerator]::Fill($verifierBytes) $verifier = ConvertTo-Base64Url $verifierBytes $challenge = ConvertTo-Base64Url ([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::ASCII.GetBytes($verifier))) $kv = Invoke-Authorize $session @{ response_type = "code"; client_id = $reg.client_id; redirect_uri = $REDIRECT_CB; scope = $SCOPE code_challenge = $challenge; code_challenge_method = "S256" state = "dev$N-$([Guid]::NewGuid().ToString('N'))"; nonce = [Guid]::NewGuid().ToString('N') } if (-not $kv.code) { throw "authorize did not return a code (got: $($kv.location))" } $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "authorization_code"; client_id = $reg.client_id; client_secret = $reg.client_secret redirect_uri = $REDIRECT_CB; code = $kv.code; code_verifier = $verifier } $sid = [string](Get-JwtPayload $tok.id_token).sid if (-not $sid) { throw "id_token of device #$N has no sid claim" } Write-Host " device #$N session id (sid): $sid" [pscustomobject]@{ N = $N; Session = $session; Sid = $sid; Bearer = @{ Authorization = "Bearer $($tok.access_token)" } } } # Silent sign-in with the device's cookie: a code while its session lives, login_required after a revoke. function Test-SilentSignIn { param($Device) $verifierBytes = New-Object byte[] 32 [System.Security.Cryptography.RandomNumberGenerator]::Fill($verifierBytes) $challenge = ConvertTo-Base64Url ([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::ASCII.GetBytes((ConvertTo-Base64Url $verifierBytes)))) $kv = Invoke-Authorize $Device.Session @{ response_type = "code"; client_id = $reg.client_id; redirect_uri = $REDIRECT_CB; scope = $SCOPE prompt = "none"; state = "silent-$([Guid]::NewGuid().ToString('N'))"; nonce = [Guid]::NewGuid().ToString('N') code_challenge = $challenge; code_challenge_method = "S256" } if ($kv.code) { return "code" } if ($kv.error) { return $kv.error } throw "unexpected authorize answer: $($kv.location)" } function Get-MySessionIds { param([hashtable]$Bearer) $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me/sessions" -Headers $Bearer $items = if ($null -eq $r) { @() } elseif ($r -is [System.Array]) { $r } elseif ($r.items) { $r.items } else { @($r) } @($items | ForEach-Object { [string]$_.sessionId } | Where-Object { $_ } | Sort-Object) } function Assert-SessionIds { param([string[]]$Actual, [string[]]$Expected, [string]$What) $a = (@($Actual) | Sort-Object) -join ',' $e = (@($Expected) | Sort-Object) -join ',' if ($a -ne $e) { throw "$What : expected sessions [$e], listed [$a]" } Write-Host " ✓ $What : [$a]" -ForegroundColor Green } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR: authorization_code client with identity:account so /me/sessions is authorized. $reg = Measure-Step "1. DCR /connect/register (authorization_code + identity:account)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "sess-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("authorization_code") scope = $SCOPE } | ConvertTo-Json) } # 2) Seed user. $user = "sess_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) } | Out-Null # 3) Three devices, three OP sessions. $dev = @{} foreach ($i in 1..3) { $dev[$i] = Measure-Step "3.$i device #$i : POST /login + authorization_code (PKCE)" { New-Device $i } } if (@($dev.Values.Sid | Sort-Object -Unique).Count -ne 3) { throw "the three logins did not open three distinct sessions" } # 4) GET /me/sessions lists exactly the three sessions. Measure-Step "4. GET /me/sessions lists the three sessions" { Assert-SessionIds (Get-MySessionIds $dev[3].Bearer) @($dev[1].Sid, $dev[2].Sid, $dev[3].Sid) "listed" } | Out-Null # 5) DELETE /{id}: device #1's session ends; its cookie no longer signs in silently. Measure-Step "5. DELETE /me/sessions/ (device #1)" { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/me/sessions/$($dev[1].Sid)" -Headers $dev[3].Bearer | Out-Null Assert-SessionIds (Get-MySessionIds $dev[3].Bearer) @($dev[2].Sid, $dev[3].Sid) "after revoking device #1" $r = Test-SilentSignIn $dev[1] if ($r -ne "login_required") { throw "device #1 silent sign-in after revoke: expected login_required, got $r" } Write-Host " ✓ device #1 prompt=none -> login_required" -ForegroundColor Green $r = Test-SilentSignIn $dev[2] if ($r -ne "code") { throw "device #2 silent sign-in while its session lives: expected a code, got $r" } Write-Host " ✓ device #2 prompt=none -> code (its session is untouched)" -ForegroundColor Green } | Out-Null # 6) DELETE /others: everything but the caller's own session (the sid of its token) ends. Measure-Step "6. DELETE /me/sessions/others (from device #3)" { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/me/sessions/others" -Headers $dev[3].Bearer | Out-Null Assert-SessionIds (Get-MySessionIds $dev[3].Bearer) @($dev[3].Sid) "after /others" $r = Test-SilentSignIn $dev[2] if ($r -ne "login_required") { throw "device #2 silent sign-in after /others: expected login_required, got $r" } Write-Host " ✓ device #2 prompt=none -> login_required" -ForegroundColor Green } | Out-Null # 7) DELETE /current: the caller's own session ends. Measure-Step "7. DELETE /me/sessions/current (device #3)" { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/me/sessions/current" -Headers $dev[3].Bearer | Out-Null $r = Test-SilentSignIn $dev[3] if ($r -ne "login_required") { throw "device #3 silent sign-in after /current: expected login_required, got $r" } Write-Host " ✓ device #3 prompt=none -> login_required" -ForegroundColor Green # The access token was issued before the revoke and lives until it expires (see the header). Assert-SessionIds (Get-MySessionIds $dev[3].Bearer) @() "after /current, with the token issued before it" } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_mfa_disable_replace.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_mfa_disable_replace.ps1 ---- # Self-service MFA disable + replace flow. # /me/mfa setup/confirm (TOTP) — enroll # DELETE /me/mfa/{method} — disable that method # /me/mfa setup/confirm again — re-enroll ("replace") with a fresh secret # # Probes: # 1. DCR + register user # 2. ROPC bearer for /me/mfa # 3. GET /me/mfa — initially OFF # 4. setup → compute TOTP → confirm → MFA enrolled (secret = S1) # 5. GET /me/mfa — enabled=true # 6. DELETE /me/mfa/totp without bearer → 401 # 7. DELETE /me/mfa/totp → 200/204 # 8. GET /me/mfa — back to OFF # 9. setup → compute TOTP → confirm → MFA enrolled again (secret = S2) # 10. S2 != S1 — fresh secret on re-enrol # 11. GET /me/mfa — enabled=true again # 12. RFC 7592 cleanup # # The TOTP math (Base32 + RFC 6238 HMAC-SHA1) mirrors demo_mfa_totp.ps1 so no # authenticator app is required. # Usage: pwsh -File demo_mfa_disable_replace.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function ConvertFrom-Base32([string]$s) { $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" $s = $s.ToUpperInvariant().TrimEnd('=') $bits = New-Object System.Text.StringBuilder foreach ($c in $s.ToCharArray()) { $v = $alphabet.IndexOf([string]$c) if ($v -lt 0) { throw "invalid base32 char: $c" } [void]$bits.Append([Convert]::ToString($v, 2).PadLeft(5, '0')) } $bitsStr = $bits.ToString() $bytes = [System.Collections.Generic.List[byte]]::new() for ($i = 0; $i + 8 -le $bitsStr.Length; $i += 8) { $bytes.Add([Convert]::ToByte($bitsStr.Substring($i, 8), 2)) } return ,$bytes.ToArray() } function Compute-Totp([string]$base32Secret) { $key = ConvertFrom-Base32 $base32Secret $t = [int64]([Math]::Floor(([DateTimeOffset]::UtcNow.ToUnixTimeSeconds()) / 30)) $tbytes = [BitConverter]::GetBytes($t) if ([BitConverter]::IsLittleEndian) { [Array]::Reverse($tbytes) } $hmac = New-Object System.Security.Cryptography.HMACSHA1(,$key) $hash = $hmac.ComputeHash($tbytes) $offset = $hash[$hash.Length - 1] -band 0x0F $code = (([int]$hash[$offset] -band 0x7F) -shl 24) ` -bor (([int]$hash[$offset+1] -band 0xFF) -shl 16) ` -bor (([int]$hash[$offset+2] -band 0xFF) -shl 8) ` -bor ([int]$hash[$offset+3] -band 0xFF) return ($code % 1000000).ToString("D6") } function Enroll-Totp { param([hashtable]$Bearer) $setup = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/mfa/setup" ` -Headers $Bearer -ContentType "application/json" ` -Body (@{ method = "totp" } | ConvertTo-Json) if (-not $setup.secret_base32) { throw "/me/mfa/setup did not return secret_base32" } if (-not $setup.setup_token) { throw "/me/mfa/setup did not return setup_token" } $code = Compute-Totp $setup.secret_base32 $confirm = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/mfa/confirm" ` -Headers $Bearer -ContentType "application/json" ` -Body (@{ method = "totp"; code = $code; setup_token = $setup.setup_token } | ConvertTo-Json) return [pscustomobject]@{ Secret = $setup.secret_base32 Confirm = $confirm } } # Multiple shapes possible — accept any "true-ish" enrolled-flag. function Is-TotpEnabled($mfa) { if ($null -eq $mfa) { return $false } foreach ($prop in @('totpConfirmed','totpEnabled','enabled')) { $v = $mfa.PSObject.Properties[$prop] if ($v -and $v.Value -eq $true) { return $true } } # /me/mfa may also surface a methods[] array. if ($mfa.PSObject.Properties['methods']) { $methods = $mfa.methods if ($methods -and ($methods | Where-Object { $_ -eq 'totp' -or $_.method -eq 'totp' })) { return $true } } return $false } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — password client for /me/* endpoints. $reg = Measure-Step "1. DCR (password + identity:account)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "mfa-disable-replace-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" } | ConvertTo-Json) if (-not $r.client_id) { throw "DCR did not return client_id" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green return $r } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri # 2) Self-register + token. $user = "mfar_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. self-register ($user)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) | Out-Null Write-Host " ✓ user created" -ForegroundColor Green } | Out-Null $tok = Measure-Step "3. ROPC token (identity:account)" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email offline_access identity:account" } if (-not $t.access_token) { throw "no access_token" } Write-Host " ✓ access_token (len $($t.access_token.Length))" -ForegroundColor Green return $t } $bearer = @{ Authorization = "Bearer $($tok.access_token)" } # 4) GET /me/mfa — should be off initially. $mfa0 = Measure-Step "4. GET /me/mfa (expect OFF)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me/mfa" -Headers $bearer if (Is-TotpEnabled $r) { throw "expected MFA off initially, got: $($r | ConvertTo-Json -Depth 3)" } Write-Host " ✓ MFA off" -ForegroundColor Green return $r } # 5) First enrol — secret S1. $enroll1 = Measure-Step "5. enrol TOTP (setup + confirm) — secret S1" { Enroll-Totp -Bearer $bearer } Write-Host " S1 = $($enroll1.Secret.Substring(0, [Math]::Min(8, $enroll1.Secret.Length)))…" -ForegroundColor Yellow # 6) GET /me/mfa — now enabled. Measure-Step "6. GET /me/mfa (expect ON)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me/mfa" -Headers $bearer if (-not (Is-TotpEnabled $r)) { throw "expected MFA on after enrol, got: $($r | ConvertTo-Json -Depth 3)" } Write-Host " ✓ MFA on" -ForegroundColor Green } | Out-Null # 7) DELETE /me/mfa/totp WITHOUT bearer — must be 401. Measure-Step "7. DELETE /me/mfa/totp without bearer (expect 401)" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/me/mfa/totp" -ErrorAction Stop | Out-Null throw "! UNEXPECTED 2xx — unauth DELETE accepted" } catch { $code = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 } if ($code -ne 401) { throw "expected 401, got $code" } Write-Host " ✓ rejected: 401" -ForegroundColor Green } } | Out-Null # 8) DELETE /me/mfa/totp WITH bearer. Measure-Step "8. DELETE /me/mfa/totp (disable)" { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/me/mfa/totp" -Headers $bearer | Out-Null Write-Host " ✓ disabled" -ForegroundColor Green } | Out-Null # 9) GET /me/mfa — back to off. Measure-Step "9. GET /me/mfa (expect OFF again)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me/mfa" -Headers $bearer if (Is-TotpEnabled $r) { throw "expected MFA off after disable, got: $($r | ConvertTo-Json -Depth 3)" } Write-Host " ✓ MFA off" -ForegroundColor Green } | Out-Null # 10) Re-enrol (replace) — secret S2. $enroll2 = Measure-Step "10. re-enrol TOTP (setup + confirm) — secret S2" { Enroll-Totp -Bearer $bearer } Write-Host " S2 = $($enroll2.Secret.Substring(0, [Math]::Min(8, $enroll2.Secret.Length)))…" -ForegroundColor Yellow # 11) S2 != S1 — server MUST mint a fresh secret on re-enrol. Measure-Step "11. assert S2 != S1 (fresh secret on replace)" { if ($enroll1.Secret -eq $enroll2.Secret) { throw "S1 == S2 — re-enrol returned the SAME secret. Disable did not clear the seed, " + "or setup reused the cached one. This is a server-side replay risk." } Write-Host " ✓ secret changed on replace" -ForegroundColor Green } | Out-Null # 12) GET /me/mfa — re-enrolled. Measure-Step "12. GET /me/mfa (expect ON after replace)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me/mfa" -Headers $bearer if (-not (Is-TotpEnabled $r)) { throw "expected MFA on after re-enrol, got: $($r | ConvertTo-Json -Depth 3)" } Write-Host " ✓ MFA on (with S2)" -ForegroundColor Green } | Out-Null # 13) RFC 7592 cleanup. Measure-Step "13. RFC 7592 DELETE registration" { if (-not $RAT) { Write-Host " (no RAT → skip)" -ForegroundColor DarkGray; return } Invoke-RestMethod -Method Delete -Uri $RCU -Headers @{ Authorization = "Bearer $RAT" } | Out-Null Write-Host " ✓ client deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_mfa_recovery_codes.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_mfa_recovery_codes.ps1 ---- # MFA recovery-codes regeneration — exercises the parallel PBKDF2 hashing path # (each batch hashes N codes; perf-tuned with Parallel.For). The flow: # enroll TOTP → capture initial recovery codes → POST /me/mfa/recovery-codes → # verify previous codes are invalidated (re-using a stale code must fail). # Surfaces RECOVERY_REGEN_TIMING in the Worker log when configured. # Usage: pwsh -File demo_mfa_recovery_codes.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } # Base32 (RFC 4648) decoder — same helper as demo_mfa_totp.ps1. function ConvertFrom-Base32([string]$s) { $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" $s = $s.ToUpperInvariant().TrimEnd('=') $bits = New-Object System.Text.StringBuilder foreach ($c in $s.ToCharArray()) { $v = $alphabet.IndexOf([string]$c) if ($v -lt 0) { throw "invalid base32 char: $c" } [void]$bits.Append([Convert]::ToString($v, 2).PadLeft(5, '0')) } $bitsStr = $bits.ToString() $bytes = [System.Collections.Generic.List[byte]]::new() for ($i = 0; $i + 8 -le $bitsStr.Length; $i += 8) { $bytes.Add([Convert]::ToByte($bitsStr.Substring($i, 8), 2)) } return ,$bytes.ToArray() } function Compute-Totp([string]$base32Secret) { $key = ConvertFrom-Base32 $base32Secret $t = [int64]([Math]::Floor(([DateTimeOffset]::UtcNow.ToUnixTimeSeconds()) / 30)) $tbytes = [BitConverter]::GetBytes($t) if ([BitConverter]::IsLittleEndian) { [Array]::Reverse($tbytes) } $hmac = New-Object System.Security.Cryptography.HMACSHA1(,$key) $hash = $hmac.ComputeHash($tbytes) $offset = $hash[$hash.Length - 1] -band 0x0F $code = (([int]$hash[$offset] -band 0x7F) -shl 24) ` -bor (([int]$hash[$offset+1] -band 0xFF) -shl 16) ` -bor (([int]$hash[$offset+2] -band 0xFF) -shl 8) ` -bor ([int]$hash[$offset+3] -band 0xFF) return ($code % 1000000).ToString("D6") } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR. $reg = Measure-Step "1. DCR /connect/register (password + identity:account)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "rec-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" } | ConvertTo-Json) } # 2) Seed user. $user = "rec_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) } | Out-Null # 3) password grant. $tok = Measure-Step "3. password grant" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email offline_access identity:account" } } $bearer = @{ Authorization = "Bearer $($tok.access_token)" } # 4) Enroll TOTP (setup → confirm) so the user has a working MFA + initial codes. $setup = Measure-Step "4. POST /me/mfa/setup (totp)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/mfa/setup" ` -Headers $bearer -ContentType "application/json" ` -Body (@{ method = "totp" } | ConvertTo-Json) } if (-not $setup.secret_base32 -or -not $setup.setup_token) { throw "setup did not return secret_base32/setup_token" } $code = Compute-Totp $setup.secret_base32 $confirm = Measure-Step "5. POST /me/mfa/confirm (parallel PBKDF2 over recovery codes)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/mfa/confirm" ` -Headers $bearer -ContentType "application/json" ` -Body (@{ method = "totp" code = $code setup_token = $setup.setup_token } | ConvertTo-Json) } $initialCodes = $confirm.recovery_codes if (-not $initialCodes -or $initialCodes.Count -lt 1) { throw "confirm did not return recovery_codes — server config may have RecoveryCodes disabled" } Write-Host " initial recovery codes ($($initialCodes.Count)):" -ForegroundColor Yellow $initialCodes | ForEach-Object { Write-Host " $_" } # 6) Regenerate. This is the headline path: server hashes N new codes via Parallel.For. $regen = Measure-Step "6. POST /me/mfa/recovery-codes (regenerate — parallel PBKDF2)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/mfa/recovery-codes" -Headers $bearer } $newCodes = $null if ($regen.recovery_codes) { $newCodes = $regen.recovery_codes } elseif ($regen.codes) { $newCodes = $regen.codes } elseif ($regen -is [System.Array]) { $newCodes = $regen } else { $newCodes = @() } Write-Host " regenerated codes ($($newCodes.Count)):" -ForegroundColor Yellow $newCodes | ForEach-Object { Write-Host " $_" } if ($newCodes.Count -lt 1) { Write-Host " ! server returned no codes on regenerate (response shape: $($regen | ConvertTo-Json -Compress))" -ForegroundColor Red } elseif (-not (Compare-Object $initialCodes $newCodes)) { Write-Host " ! regenerate returned the SAME set of codes — rotation broken" -ForegroundColor Red } else { Write-Host " ✓ codes rotated (no overlap with previous batch expected)" -ForegroundColor Green } # 7) Steady-state x3 to expose the parallel speed-up. With Parallel.For the wall time # should NOT scale linearly with code count. Write-Host "" Write-Host "=== [7. regenerate steady-state x3] ===" -ForegroundColor Cyan $ms = @() for ($i = 1; $i -le 3; $i++) { $sw = [System.Diagnostics.Stopwatch]::StartNew() Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/mfa/recovery-codes" -Headers $bearer | Out-Null $sw.Stop() $ms += [int]$sw.Elapsed.TotalMilliseconds Write-Host (" iter {0}: {1,5} ms" -f $i, $ms[-1]) } $avg = [int](($ms | Measure-Object -Average).Average) Write-Host (" avg={0} ms min={1} ms max={2} ms" -f $avg, ($ms | Measure-Object -Minimum).Minimum, ($ms | Measure-Object -Maximum).Maximum) -ForegroundColor Yellow $timings.Add([pscustomobject]@{ Step="7. regenerate steady-state x3 (avg)"; Ms=$avg; Status="ok" }) # 8) Confirm a STALE code (from the very first batch) no longer works. This depends # on whether the server exposes a recovery-code redemption endpoint. We try the # common /api/v1/identity/me/mfa/recovery path; if 404, we just note the absence. if ($initialCodes.Count -gt 0) { $stale = $initialCodes[0] Measure-Step "8. redeem stale recovery code (expect rejection)" { $endpoints = @( "$BASE/api/v1/identity/me/mfa/recovery", "$BASE/api/v1/identity/account/mfa/recovery" ) $tried = $false foreach ($ep in $endpoints) { try { Invoke-RestMethod -Method Post $ep -Headers $bearer ` -ContentType "application/json" ` -Body (@{ code = $stale } | ConvertTo-Json) | Out-Null $tried = $true Write-Host " ! stale code accepted at $ep — rotation broken" -ForegroundColor Red } catch { $code = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -eq 404) { continue } # try next endpoint $tried = $true if ($code -in 400, 401, 403, 409) { Write-Host " ✓ stale code rejected at $ep status=$code" -ForegroundColor Green } else { Write-Host " ! unexpected status=$code at $ep" -ForegroundColor Yellow } break } } if (-not $tried) { Write-Host " (no recovery-redeem endpoint found — rotation verified by code-set comparison only)" -ForegroundColor DarkGray } } | Out-Null } $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Write-Host "(check Worker log for parallel PBKDF2 timing — Parallel.For shrinks wall-time vs code count)" -ForegroundColor DarkGray Path: redb-identity/demos/demo_mfa_totp.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_mfa_totp.ps1 ---- # MFA TOTP setup + confirm — fully scripted, no authenticator app needed. # /me/mfa GET (off) → /setup → compute TOTP locally → /confirm → /me/mfa GET (on). # Usage: pwsh -File demo_mfa_totp.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } # Base32 (RFC 4648) decoder. function ConvertFrom-Base32([string]$s) { $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" $s = $s.ToUpperInvariant().TrimEnd('=') $bits = New-Object System.Text.StringBuilder foreach ($c in $s.ToCharArray()) { $v = $alphabet.IndexOf([string]$c) if ($v -lt 0) { throw "invalid base32 char: $c" } [void]$bits.Append([Convert]::ToString($v, 2).PadLeft(5, '0')) } $bitsStr = $bits.ToString() $bytes = [System.Collections.Generic.List[byte]]::new() for ($i = 0; $i + 8 -le $bitsStr.Length; $i += 8) { $bytes.Add([Convert]::ToByte($bitsStr.Substring($i, 8), 2)) } return ,$bytes.ToArray() } # RFC 6238 TOTP / RFC 4226 HOTP, SHA1, 6 digits, 30 s step. function Compute-Totp([string]$base32Secret) { $key = ConvertFrom-Base32 $base32Secret $t = [int64]([Math]::Floor(([DateTimeOffset]::UtcNow.ToUnixTimeSeconds()) / 30)) $tbytes = [BitConverter]::GetBytes($t) if ([BitConverter]::IsLittleEndian) { [Array]::Reverse($tbytes) } $hmac = New-Object System.Security.Cryptography.HMACSHA1(,$key) $hash = $hmac.ComputeHash($tbytes) $offset = $hash[$hash.Length - 1] -band 0x0F $code = (([int]$hash[$offset] -band 0x7F) -shl 24) ` -bor (([int]$hash[$offset+1] -band 0xFF) -shl 16) ` -bor (([int]$hash[$offset+2] -band 0xFF) -shl 8) ` -bor ([int]$hash[$offset+3] -band 0xFF) return ($code % 1000000).ToString("D6") } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR with identity:account scope so /me/mfa is authorized. $reg = Measure-Step "1. DCR /connect/register (password + identity:account)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "mfa-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" } | ConvertTo-Json) } # 2) Seed user. $user = "mfa_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) } | Out-Null # 3) password grant. $tok = Measure-Step "3. password grant" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email offline_access identity:account" } } $bearer = @{ Authorization = "Bearer $($tok.access_token)" } # 4) GET /me/mfa — should be off initially. $mfa0 = Measure-Step "4. GET /api/v1/identity/me/mfa (initial)" { Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me/mfa" -Headers $bearer } $mfa0 | ConvertTo-Json -Depth 5 | Out-Host # 5) POST /me/mfa/setup — request TOTP enrollment. $setup = Measure-Step "5. POST /api/v1/identity/me/mfa/setup (totp)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/mfa/setup" ` -Headers $bearer ` -ContentType "application/json" ` -Body (@{ method = "totp" } | ConvertTo-Json) } Write-Host " secret_base32 : $($setup.secret_base32)" Write-Host " qr_uri : $($setup.qr_uri)" Write-Host " setup_token : $($setup.setup_token.Substring(0, [Math]::Min(40, $setup.setup_token.Length)))…" if (-not $setup.secret_base32) { throw "server did not return secret_base32" } if (-not $setup.setup_token) { throw "server did not return setup_token" } # 6) Compute the live TOTP code. $code = Measure-Step "6. compute TOTP locally (RFC 6238, SHA1, 6 digits, 30 s)" { Compute-Totp $setup.secret_base32 } Write-Host " code = $code" -ForegroundColor Yellow # 7) POST /me/mfa/confirm — finalize enrollment. $confirm = Measure-Step "7. POST /api/v1/identity/me/mfa/confirm" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/me/mfa/confirm" ` -Headers $bearer ` -ContentType "application/json" ` -Body (@{ method = "totp" code = $code setup_token = $setup.setup_token } | ConvertTo-Json) } Write-Host " confirmed : $($confirm.confirmed)" if ($confirm.recovery_codes) { Write-Host " recovery_codes:" -ForegroundColor Yellow $confirm.recovery_codes | ForEach-Object { Write-Host " $_" } } # 8) GET /me/mfa — should now show enabled=true. $mfa1 = Measure-Step "8. GET /api/v1/identity/me/mfa (after confirm)" { Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me/mfa" -Headers $bearer } $mfa1 | ConvertTo-Json -Depth 5 | Out-Host if ($mfa1.enabled -or $mfa1.totpEnabled -or $mfa1.totpConfirmed) { Write-Host " ✓ MFA TOTP enrolled" -ForegroundColor Green } else { Write-Host " WARNING: /me/mfa does not report enabled=true (shape may differ)" -ForegroundColor Yellow } $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_nonce_state_roundtrip.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_nonce_state_roundtrip.ps1 ---- # Conformance probe — nonce / state round-trip (OIDC Core §3.1.2.1, §3.1.3.7, §15.5.2). # • state sent to /authorize MUST be echoed verbatim in the redirect. # • nonce sent to /authorize MUST appear verbatim as the `nonce` claim in the id_token. # • when NO nonce is sent (allowed for code flow), the id_token MUST NOT carry a nonce. # Usage: pwsh -File demo_nonce_state_roundtrip.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $REDIRECT = $REDIRECT_CB $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host ""; Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $r = & $Action; $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }); return $r } catch { $sw.Stop(); Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }); throw } } function ConvertTo-Base64Url([byte[]]$b) { [Convert]::ToBase64String($b).TrimEnd('=').Replace('+','-').Replace('/','_') } function New-Pkce { $vb = New-Object byte[] 32; [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($vb) $v = ConvertTo-Base64Url $vb $c = ConvertTo-Base64Url ([System.Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::ASCII.GetBytes($v))) [pscustomobject]@{ verifier=$v; challenge=$c } } function Decode-Jwt([string]$jwt) { $p = $jwt.Split('.')[1].Replace('-','+').Replace('_','/') switch ($p.Length % 4) { 2 { $p += '==' } 3 { $p += '=' } } [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($p)) | ConvertFrom-Json } # Drive /login then /connect/authorize, return the parsed redirect query (hashtable) + raw location. function Invoke-Authorize { param($Session, $ClientId, $Pkce, [hashtable]$Extra) $body = @{ response_type = "code"; client_id = $ClientId; redirect_uri = $REDIRECT scope = "openid profile offline_access"; code_challenge = $Pkce.challenge; code_challenge_method = "S256" } foreach ($k in $Extra.Keys) { $body[$k] = $Extra[$k] } $resp = $null try { $resp = Invoke-WebRequest -Method Post "$BASE/connect/authorize" -WebSession $Session -ContentType "application/x-www-form-urlencoded" -Body $body -MaximumRedirection 0 -ErrorAction Stop } catch { $resp = $_.Exception.Response } $location = if ($resp -is [System.Net.Http.HttpResponseMessage]) { $resp.Headers.Location.ToString() } else { $resp.Headers["Location"] } if (-not $location) { throw "no Location header on /connect/authorize" } $u = [uri]$location; $kv = @{} foreach ($pair in $u.Query.TrimStart('?').Split('&')) { $i = $pair.IndexOf('='); if ($i -gt 0) { $kv[$pair.Substring(0,$i)] = [uri]::UnescapeDataString($pair.Substring($i+1)) } } [pscustomobject]@{ location=$location; q=$kv } } $total = [System.Diagnostics.Stopwatch]::StartNew() $reg = Measure-Step "1. DCR (authorization_code)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" -Body (@{ client_name="nonce-state-demo"; redirect_uris=@($REDIRECT) grant_types=@("authorization_code","refresh_token"); scope="openid profile offline_access" } | ConvertTo-Json) } $user = "ns_$([Guid]::NewGuid().ToString('N').Substring(0,8))" Measure-Step "2. account/register + login" { try { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" -Body (@{login=$user;email="$user@example.com";password="Test1234Pass!";displayName=$user} | ConvertTo-Json) | Out-Null } catch {} $script:session = New-Object Microsoft.PowerShell.Commands.WebRequestSession try { Invoke-WebRequest -Method Post "$BASE/login" -WebSession $script:session -ContentType "application/x-www-form-urlencoded" -Body @{ username=$user; password="Test1234Pass!" } -MaximumRedirection 0 -ErrorAction Stop | Out-Null } catch {} if ($script:session.Cookies.GetCookies("$BASE").Count -lt 1) { throw "no session cookie from /login" } } | Out-Null # ── Case A: state + nonce present → both must round-trip ─────────────────────── $stateA = "state-" + [Guid]::NewGuid().ToString('N') $nonceA = "nonce-" + [Guid]::NewGuid().ToString('N') Measure-Step "3. state echo (verbatim) in redirect" { $pk = New-Pkce; $script:pkA = $pk $r = Invoke-Authorize -Session $script:session -ClientId $reg.client_id -Pkce $pk -Extra @{ state=$stateA; nonce=$nonceA } if (-not $r.q.code) { throw "authorize did not return a code (loc=$($r.location))" } if ($r.q.state -ne $stateA) { throw "state NOT echoed verbatim: sent '$stateA', got '$($r.q.state)'" } $script:codeA = $r.q.code Write-Host " ✓ state echoed verbatim; code present" -ForegroundColor Green } | Out-Null Measure-Step "4. nonce round-trips into id_token" { $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" -Body @{ grant_type="authorization_code"; client_id=$reg.client_id; client_secret=$reg.client_secret redirect_uri=$REDIRECT; code=$script:codeA; code_verifier=$script:pkA.verifier } if (-not $tok.id_token) { throw "no id_token returned" } $id = Decode-Jwt $tok.id_token if ($id.nonce -ne $nonceA) { throw "nonce NOT round-tripped: sent '$nonceA', id_token.nonce='$($id.nonce)'" } Write-Host " ✓ id_token.nonce == sent nonce" -ForegroundColor Green } | Out-Null # ── Case B: no nonce → id_token MUST NOT carry a nonce ───────────────────────── Measure-Step "5. no-nonce request → id_token has no nonce claim" { $pk = New-Pkce $stateB = "state-" + [Guid]::NewGuid().ToString('N') $r = Invoke-Authorize -Session $script:session -ClientId $reg.client_id -Pkce $pk -Extra @{ state=$stateB } if (-not $r.q.code) { throw "authorize (no nonce) did not return a code (loc=$($r.location))" } if ($r.q.state -ne $stateB) { throw "state NOT echoed on no-nonce request" } $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" -Body @{ grant_type="authorization_code"; client_id=$reg.client_id; client_secret=$reg.client_secret redirect_uri=$REDIRECT; code=$r.q.code; code_verifier=$pk.verifier } $id = Decode-Jwt $tok.id_token $hasNonce = $id.PSObject.Properties.Name -contains 'nonce' -and -not [string]::IsNullOrEmpty($id.nonce) if ($hasNonce) { throw "id_token carries a nonce ('$($id.nonce)') though none was requested" } Write-Host " ✓ no nonce requested → no nonce claim" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host ""; Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_par.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_par.ps1 ---- # PAR — Pushed Authorization Requests (RFC 9126). # POST /connect/par → get request_uri → use it in /connect/authorize. # Since the full auth-code flow needs a browser, the authorize step is # probed headless: we verify the server redirects (to login/consent) rather # than errors. Steps 4-6 test the security contract: one-time use, expired # request_uri, and invalid client rejection. # Usage: pwsh -File demo_par.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function New-Pkce { $verifier = B64U ([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) $challenge = B64U ([System.Security.Cryptography.SHA256]::HashData( [Text.Encoding]::ASCII.GetBytes($verifier))) return [pscustomobject]@{ Verifier=$verifier; Challenge=$challenge } } function B64U([byte[]]$bytes) { [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=') } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — authorization_code client (public clients must use PKCE). $reg = Measure-Step "1. DCR /connect/register (authorization_code + PKCE)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "par-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("authorization_code","refresh_token") scope = "openid profile email" } | ConvertTo-Json) } $reg | Format-List client_id, client_secret # 2) POST /connect/par — push the authorization request (RFC 9126 §2). $pkce = New-Pkce $state = [Guid]::NewGuid().ToString("N") $nonce = [Guid]::NewGuid().ToString("N") $par = Measure-Step "2. POST /connect/par (RFC 9126 §2)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/par" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ response_type = "code" client_id = $reg.client_id client_secret = $reg.client_secret redirect_uri = $REDIRECT_CB scope = "openid profile email" state = $state nonce = $nonce code_challenge = $pkce.Challenge code_challenge_method = "S256" } Write-Host " request_uri : $($r.request_uri)" Write-Host " expires_in : $($r.expires_in) s" if (-not $r.request_uri) { throw "server did not return request_uri" } if ($r.request_uri -match "^urn:ietf:params:oauth:request_uri:") { Write-Host " ✓ URN prefix correct (RFC 9126 §2.2)" -ForegroundColor Green } else { Write-Host " ! request_uri does not use RFC 9126 URN prefix" -ForegroundColor Yellow } return $r } # 3) GET /connect/authorize?request_uri=… (headless — follow=0, inspect redirect). $authorizeUri = "$BASE/connect/authorize?client_id=$([Uri]::EscapeDataString($reg.client_id))&request_uri=$([Uri]::EscapeDataString($par.request_uri))" Measure-Step "3. GET /connect/authorize?request_uri=… (headless redirect check)" { try { $wr = Invoke-WebRequest -Uri $authorizeUri -MaximumRedirection 0 -ErrorAction SilentlyContinue $loc = $wr.Headers['Location'] if ($wr.StatusCode -in 200,302,303,307,308) { Write-Host " ✓ server responded: $($wr.StatusCode)" -ForegroundColor Green if ($loc) { Write-Host " Location: $($loc.ToString().Substring(0,[Math]::Min(100,$loc.ToString().Length)))…" } } else { Write-Host " ! unexpected: $($wr.StatusCode)" -ForegroundColor Yellow } } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -in 200,302,303,307,308) { Write-Host " ✓ server responded: $code" -ForegroundColor Green } else { Write-Host " ! status $code — $($_.Exception.Message)" -ForegroundColor Red; throw } } } | Out-Null # 4) Replay the same request_uri — one-time use, must be rejected (RFC 9126 §4). Measure-Step "4. Replay request_uri (expect 400 — one-time, RFC 9126 §4)" { try { $wr = Invoke-WebRequest -Uri $authorizeUri -MaximumRedirection 0 -ErrorAction SilentlyContinue if ($wr.StatusCode -eq 400) { Write-Host " ✓ rejected: 400" -ForegroundColor Green } else { Write-Host " ! got $($wr.StatusCode) — one-time enforcement may be missing" -ForegroundColor Yellow } } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -eq 400) { Write-Host " ✓ rejected: 400" -ForegroundColor Green } else { Write-Host " ! unexpected: $code" -ForegroundColor Yellow } } } | Out-Null # 5) POST /connect/par with invalid client_secret (RFC 9126 §2.3 — must authenticate). Measure-Step "5. PAR with wrong client_secret (expect 400/401)" { try { Invoke-RestMethod -Method Post "$BASE/connect/par" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ response_type = "code" client_id = $reg.client_id client_secret = "bogus-secret-$(Get-Random)" redirect_uri = $REDIRECT_CB scope = "openid" } | Out-Null Write-Host " ! UNEXPECTED success — invalid secret accepted" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -in 400,401) { Write-Host " ✓ rejected: $code" -ForegroundColor Green } else { throw "unexpected status $code" } } } | Out-Null # 6) POST /connect/par with unregistered redirect_uri — must reject (open-redirect guard). Measure-Step "6. PAR with unregistered redirect_uri (expect 400)" { try { Invoke-RestMethod -Method Post "$BASE/connect/par" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ response_type = "code" client_id = $reg.client_id client_secret = $reg.client_secret redirect_uri = "http://attacker.example/steal" scope = "openid" } | Out-Null Write-Host " ! UNEXPECTED — unregistered redirect_uri accepted (open redirect risk)" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ Write-Host " ✓ rejected: $code" -ForegroundColor Green } } | Out-Null # 7) POST /connect/par with unsupported response_type — must reject. Measure-Step "7. PAR with response_type=token (implicit — expect 400)" { try { Invoke-RestMethod -Method Post "$BASE/connect/par" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ response_type = "token" client_id = $reg.client_id client_secret = $reg.client_secret redirect_uri = $REDIRECT_CB scope = "openid" } | Out-Null Write-Host " ! implicit flow accepted (should be disabled per OAuth 2.1)" -ForegroundColor Yellow } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -eq 400) { Write-Host " ✓ implicit rejected: 400" -ForegroundColor Green } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Write-Host "(step 3 headless — full auth-code flow requires browser interaction)" -ForegroundColor DarkGray Path: redb-identity/demos/demo_par_per_client.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_par_per_client.ps1 ---- # Per-client PAR enforcement (RFC 9126 §5). # Client opts in via DCR `require_pushed_authorization_requests=true`. # Server then rejects any direct /connect/authorize for this client unless # the request was first pushed through /connect/par. Probes: # 1. Discovery advertises pushed_authorization_request_endpoint URL # 2. DCR with require_pushed_authorization_requests=true → echoed back # 3. Direct GET /connect/authorize (no request_uri) → invalid_request # (RFC 6749 §4.1.2.1 — error flows back to redirect_uri, not JSON) # 4. POST /connect/par + GET /connect/authorize?request_uri=… → # request shape now conformant; error != invalid_request # 5. RFC 7592 DELETE cleanup # Usage: pwsh -File demo_par_per_client.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function B64U([byte[]]$bytes) { [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=') } function New-Pkce { $verifier = B64U ([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) $challenge = B64U ([System.Security.Cryptography.SHA256]::HashData( [Text.Encoding]::ASCII.GetBytes($verifier))) return [pscustomobject]@{ Verifier=$verifier; Challenge=$challenge } } # Inspect a redirect Location URL and decide whether it looks like an OAuth error # response per RFC 6749 §4.1.2.1 (params on the *redirect_uri*) or any other # kind of response (login UI redirect, success). function Get-AuthorizeOutcome { param([string]$Url) if ([string]::IsNullOrEmpty($Url)) { return [pscustomobject]@{ Error=$null; Raw=$Url } } try { $u = [Uri]$Url $q = [System.Web.HttpUtility]::ParseQueryString($u.Query) return [pscustomobject]@{ Error = $q['error'] Description = $q['error_description'] State = $q['state'] Iss = $q['iss'] Host = $u.Host Path = $u.AbsolutePath Raw = $Url } } catch { return [pscustomobject]@{ Error=$null; Raw=$Url } } } Add-Type -AssemblyName System.Web $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) Discovery — assert pushed_authorization_request_endpoint URL is advertised $disc = Measure-Step "1. discovery /.well-known/openid-configuration advertises PAR endpoint URL" { $d = Invoke-RestMethod "$BASE/.well-known/openid-configuration" if (-not $d.pushed_authorization_request_endpoint) { throw "discovery missing pushed_authorization_request_endpoint URL" } if ($d.pushed_authorization_request_endpoint -notmatch '^https?://[^/]+/connect/par$') { throw "pushed_authorization_request_endpoint shape unexpected: $($d.pushed_authorization_request_endpoint)" } Write-Host " ✓ pushed_authorization_request_endpoint = $($d.pushed_authorization_request_endpoint)" -ForegroundColor Green return $d } $REDIRECT = $REDIRECT_CB # 2) DCR with require_pushed_authorization_requests=true $reg = Measure-Step "2. DCR /connect/register (require_pushed_authorization_requests=true)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "par-per-client-demo" redirect_uris = @($REDIRECT) grant_types = @("authorization_code","refresh_token") scope = "openid profile email" require_pushed_authorization_requests = $true } | ConvertTo-Json -Depth 5) if (-not $r.client_id) { throw "DCR did not return client_id" } if ($r.require_pushed_authorization_requests -ne $true) { throw "server did not echo require_pushed_authorization_requests=true (got: $($r.require_pushed_authorization_requests))" } Write-Host " ✓ client_id : $($r.client_id)" -ForegroundColor Green Write-Host " ✓ flag echoed : require_pushed_authorization_requests = true" -ForegroundColor Green return $r } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri # 3) Direct /connect/authorize (no request_uri) → expect invalid_request via redirect_uri # Per RFC 6749 §4.1.2.1, validation errors that occur AFTER client_id+redirect_uri # pass authentication MUST be returned by redirecting back to redirect_uri with the # error= and error_description= query params. The request_uri-required violation # qualifies because the client+redirect are valid; only the request shape isn't. $pkceA = New-Pkce $stateA = [Guid]::NewGuid().ToString("N") $directAuthorize = "$BASE/connect/authorize?response_type=code" + "&client_id=$([Uri]::EscapeDataString($reg.client_id))" + "&redirect_uri=$([Uri]::EscapeDataString($REDIRECT))" + "&scope=$([Uri]::EscapeDataString('openid profile'))" + "&state=$stateA" + "&code_challenge=$($pkceA.Challenge)&code_challenge_method=S256" Measure-Step "3. direct GET /connect/authorize (no request_uri) -> invalid_request" { # -SkipHttpErrorCheck (pwsh 7+) keeps non-2xx responses in $resp instead of throwing. # -MaximumRedirection 0 makes the AS's 302 land here as a regular response with the # Location header still attached, so we can inspect the redirect target without the # client following it. PowerShell prints a non-fatal "maximum redirection count" line # to stderr but the response object is fully populated, which is what we want. $resp = Invoke-WebRequest -Uri $directAuthorize -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction SilentlyContinue $code = [int]$resp.StatusCode $locArr = $resp.Headers['Location'] $loc = if ($locArr) { @($locArr)[0] } else { $null } Write-Host " status : $code" if ($loc) { Write-Host " Location : $loc" } if ($code -in 302,303,307) { $outcome = Get-AuthorizeOutcome $loc if ($outcome.Error -ne 'invalid_request') { throw "expected error=invalid_request on redirect, got error='$($outcome.Error)' / desc='$($outcome.Description)'" } # Must redirect to the registered redirect_uri host (RFC 6749 §4.1.2.1) — NOT to the AS /login. if ($outcome.Host -ne 'localhost') { throw "error redirected away from registered redirect_uri host (got: $($outcome.Host))" } if ($outcome.State -ne $stateA) { throw "state did not round-trip on error redirect (expected '$stateA', got '$($outcome.State)')" } Write-Host " ✓ rejected via redirect: error=invalid_request state=$($outcome.State)" -ForegroundColor Green Write-Host " ✓ description mentions PAR: $($outcome.Description.Substring(0, [Math]::Min(60, $outcome.Description.Length)))…" -ForegroundColor Green } elseif ($code -eq 400) { # Acceptable fallback: server chose JSON 400 if it considered the request # too malformed to bind to redirect_uri. Not preferred, but spec-compatible. Write-Host " ✓ rejected with 400 (JSON form acceptable)" -ForegroundColor Green } else { throw "expected 302→redirect_uri?error=invalid_request OR 400, got status $code" } } | Out-Null # 4) POST /connect/par + GET /connect/authorize?request_uri=… — request now conformant. $pkceB = New-Pkce $stateB = [Guid]::NewGuid().ToString("N") $nonceB = [Guid]::NewGuid().ToString("N") $par = Measure-Step "4a. POST /connect/par (push the request)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/par" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ response_type = "code" client_id = $reg.client_id client_secret = $reg.client_secret redirect_uri = $REDIRECT scope = "openid profile email" state = $stateB nonce = $nonceB code_challenge = $pkceB.Challenge code_challenge_method = "S256" } if (-not $r.request_uri) { throw "PAR did not return request_uri" } if ($r.request_uri -notmatch "^urn:ietf:params:oauth:request_uri:") { throw "request_uri does not use RFC 9126 URN prefix" } Write-Host " ✓ request_uri = $($r.request_uri)" -ForegroundColor Green return $r } $parAuthorize = "$BASE/connect/authorize?client_id=$([Uri]::EscapeDataString($reg.client_id))" + "&request_uri=$([Uri]::EscapeDataString($par.request_uri))" Measure-Step "4b. GET /connect/authorize?request_uri=… -> NOT invalid_request" { $resp = Invoke-WebRequest -Uri $parAuthorize -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction SilentlyContinue $code = [int]$resp.StatusCode $locArr = $resp.Headers['Location'] $loc = if ($locArr) { @($locArr)[0] } else { $null } Write-Host " status : $code" if ($loc) { Write-Host " Location : $loc" } # Not invalid_request — anything else is fine: the request shape is now conformant, # and the AS will either redirect to its /login UI (no session) or back to redirect_uri # with login_required (also acceptable). What we MUST NOT see: error=invalid_request # with the PAR-required description. if ($code -notin 200,302,303,307,308) { throw "expected 2xx/3xx after PAR push, got $code" } if ($loc) { $outcome = Get-AuthorizeOutcome $loc if ($outcome.Error -eq 'invalid_request') { throw "PAR-pushed authorize STILL rejected as invalid_request — per-client enforcement not honouring request_uri ($($outcome.Description))" } Write-Host " ✓ accepted (no invalid_request); redirected to $($outcome.Host)$($outcome.Path)" -ForegroundColor Green } else { Write-Host " ✓ accepted (status $code, no error redirect)" -ForegroundColor Green } } | Out-Null # 5) RFC 7592 DELETE — cleanup Measure-Step "5. RFC 7592 DELETE registration" { if (-not $RAT) { Write-Host " (no RAT → skip)" -ForegroundColor DarkGray; return } Invoke-RestMethod -Method Delete -Uri $RCU ` -Headers @{ Authorization = "Bearer $RAT" } | Out-Null Write-Host " ✓ client deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_password_change_negatives.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_password_change_negatives.ps1 ---- # Self-service password-change negative paths. # PUT /api/v1/identity/me/password — assert the server REJECTS: # 1. wrong oldPassword (HTTP 400, generic — not "wrong password") # 2. policy-violating newPassword (HTTP 400, validation_error) # - too short (PasswordPolicy.MinLength = 12) # - missing digit (PasswordPolicy.RequireDigit = true) # - missing uppercase (PasswordPolicy.RequireUppercase = true) # - missing lowercase (PasswordPolicy.RequireLowercase = true) # 3. history violation (HTTP 400, reused old password) # 4. missing bearer token (HTTP 401) # # Positive path (old→new ROPC) is covered by demo_me_profile.ps1; this demo focuses # purely on the rejection contract so we can spot regressions in the policy validator. # Usage: pwsh -File demo_password_change_negatives.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } # Helper: invoke /me/password expecting failure with a specific HTTP status. function Invoke-Reject { param( [string]$Label, [hashtable]$Headers, [hashtable]$Body, [int[]]$ExpectStatus = @(400) ) try { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/me/password" ` -Headers $Headers ` -ContentType "application/json" ` -Body ($Body | ConvertTo-Json) ` -ErrorAction Stop | Out-Null throw " ! UNEXPECTED 2xx — server accepted forbidden mutation ($Label)" } catch { $resp = $_.Exception.Response $code = if ($resp) { [int]$resp.StatusCode } else { 0 } if ($ExpectStatus -contains $code) { $errBody = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } Write-Host " ✓ rejected: $code ($Label)" -ForegroundColor Green if ($errBody) { Write-Host " body: $errBody" -ForegroundColor DarkGray } } else { $errBody = if ($_.ErrorDetails) { $_.ErrorDetails.Message } else { "" } throw " ! status=$code, expected $($ExpectStatus -join '/') body=$errBody" } } } $total = [System.Diagnostics.Stopwatch]::StartNew() $oldPwd = "Test1234Pass!" $newPwd = "Brand-NewSecret77" # 1) DCR — password grant. $reg = Measure-Step "1. DCR /connect/register (password)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "pwd-change-negatives" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" } | ConvertTo-Json) if (-not $r.client_id) { throw "DCR did not return client_id" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green return $r } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri # 2) Self-register a fresh user. $user = "pwdneg_$([Guid]::NewGuid().ToString('N').Substring(0,8))" Measure-Step "2. self-register ($user)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $oldPwd displayName = $user } | ConvertTo-Json) | Out-Null Write-Host " ✓ user created" -ForegroundColor Green } | Out-Null # 3) Get an access token. $tok = Measure-Step "3. ROPC token (identity:account)" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $oldPwd scope = "openid profile email offline_access identity:account" } if (-not $t.access_token) { throw "no access_token" } Write-Host " ✓ access_token (len $($t.access_token.Length))" -ForegroundColor Green return $t } $bearer = @{ Authorization = "Bearer $($tok.access_token)" } # 4) Negative — wrong oldPassword Measure-Step "4. wrong oldPassword (expect 400)" { Invoke-Reject -Label "wrong oldPassword" -Headers $bearer -Body @{ oldPassword = "WrongPasswordZZ!" newPassword = $newPwd } -ExpectStatus 400,401 } | Out-Null # 5) Negative — too short (MinLength=12) Measure-Step "5. policy: too short (expect 400)" { Invoke-Reject -Label "too short" -Headers $bearer -Body @{ oldPassword = $oldPwd newPassword = "Sh0rt!a" } -ExpectStatus 400 } | Out-Null # 6) Negative — missing digit (RequireDigit=true) Measure-Step "6. policy: missing digit (expect 400)" { Invoke-Reject -Label "missing digit" -Headers $bearer -Body @{ oldPassword = $oldPwd newPassword = "NoDigitsAtAll!!" } -ExpectStatus 400 } | Out-Null # 7) Negative — missing uppercase Measure-Step "7. policy: missing uppercase (expect 400)" { Invoke-Reject -Label "missing uppercase" -Headers $bearer -Body @{ oldPassword = $oldPwd newPassword = "lowercase4all123" } -ExpectStatus 400 } | Out-Null # 8) Negative — missing lowercase Measure-Step "8. policy: missing lowercase (expect 400)" { Invoke-Reject -Label "missing lowercase" -Headers $bearer -Body @{ oldPassword = $oldPwd newPassword = "UPPERCASE4ALL123" } -ExpectStatus 400 } | Out-Null # 9) Positive — change to a valid new password (so we can probe history). Measure-Step "9. valid password change (positive)" { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/me/password" ` -Headers $bearer -ContentType "application/json" ` -Body (@{ oldPassword = $oldPwd; newPassword = $newPwd } | ConvertTo-Json) | Out-Null Write-Host " ✓ password changed" -ForegroundColor Green } | Out-Null # 10) Refresh token after password change (old token may have been revoked). $tok2 = Measure-Step "10. ROPC with new password" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $newPwd scope = "openid profile email offline_access identity:account" } Write-Host " ✓ new password works" -ForegroundColor Green return $t } $bearer2 = @{ Authorization = "Bearer $($tok2.access_token)" } # 11) Negative — history: try to set the OLD password back (HistoryCount=5 means recent N forbidden). Measure-Step "11. history: reuse previous password (expect 400)" { Invoke-Reject -Label "history reuse" -Headers $bearer2 -Body @{ oldPassword = $newPwd newPassword = $oldPwd } -ExpectStatus 400 } | Out-Null # 12) Negative — missing bearer Measure-Step "12. missing bearer (expect 401)" { try { Invoke-RestMethod -Method Put "$BASE/api/v1/identity/me/password" ` -ContentType "application/json" ` -Body (@{ oldPassword = $newPwd; newPassword = "AnotherNewOne7!" } | ConvertTo-Json) ` -ErrorAction Stop | Out-Null throw " ! UNEXPECTED 2xx — unauth call accepted" } catch { $code = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 } if ($code -eq 401) { Write-Host " ✓ rejected: 401" -ForegroundColor Green } else { throw " ! status=$code, expected 401" } } } | Out-Null # 13) RFC 7592 cleanup Measure-Step "13. RFC 7592 DELETE registration" { if (-not $RAT) { Write-Host " (no RAT → skip)" -ForegroundColor DarkGray; return } Invoke-RestMethod -Method Delete -Uri $RCU -Headers @{ Authorization = "Bearer $RAT" } | Out-Null Write-Host " ✓ client deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_password_reset.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_password_reset.ps1 ---- # Anonymous password-recovery flow (RFC-aligned: N-4 Session C). # POST /api/v1/identity/password/forgot — initiate (anti-enumeration: ALWAYS 200, # even on unknown email or non-whitelisted callerResetUrl). # POST /api/v1/identity/password/reset — consume the single-use token + set new pwd # (rejects with success=false on bad/expired/consumed token, policy violation). # # Probes: # 1. DCR with password_reset_uris — client must carry the whitelist # 2. self-register user # 3. forgot for UNKNOWN email → 200 (anti-enum) — NO mail sent # 4. forgot with NON-whitelisted url → 200 (anti-enum) — NO mail sent # 5. forgot HAPPY PATH → 200, mail lands in GreenMail with reset link # 5b. fetch + parse the reset link — extract jti+token from MIME quoted-printable # 6. /reset with BOGUS token → success=false, generic invalid_token; token NOT consumed # 7. /reset HAPPY PATH → success=true, sessionsRevoked >= 0 # 8. login with NEW password → 200 (token issued) # 9. /reset replay (same jti+token) → success=false (single-use enforced) # 10. RFC 7592 DELETE registration cleanup # # (Weak-newPassword rejection of /reset is intentionally NOT probed here because the # processor consumes the token on Verify, not on Set, so probing weak after a valid # token would steal the only token for the happy path. The IPasswordPolicyValidator # pipeline is covered exhaustively by demo_password_change_negatives — same validator.) # # Requires the GreenMail container (route-greenmail, SMTP 3025 / REST 8080) to be # running — SMTP is wired in context.json. Without it the happy path can't intercept # the token and the demo aborts at step 5. # # Usage: pwsh -File demo_password_reset.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $GM = "http://127.0.0.1:8080" # GreenMail REST API $RESET_URL = "http://localhost:9999/reset-page" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } # Wait up to $timeoutMs for an email to {email} to land in GreenMail. Returns the # message object (with subject, body) or $null on timeout. function Wait-Email { param([string]$Email, [int]$TimeoutMs = 8000) $deadline = [DateTimeOffset]::UtcNow.AddMilliseconds($TimeoutMs) while ([DateTimeOffset]::UtcNow -lt $deadline) { try { $msgs = Invoke-RestMethod -Method Get "$GM/api/user/$Email/messages/INBOX" -ErrorAction Stop if ($msgs -and $msgs.Count -ge 1) { return $msgs[0] } } catch { # 404 until the user is auto-created by GreenMail on first mail — retry. } Start-Sleep -Milliseconds 300 } return $null } # Decode quoted-printable encoding used in multipart/alternative MIME bodies: # =\r\n → soft line-break, drop # =XX → byte with hex value XX function Decode-QuotedPrintable { param([string]$s) if ([string]::IsNullOrEmpty($s)) { return $s } $s = $s -replace "=\r\n", "" -replace "=\n", "" return [regex]::Replace($s, "=([0-9A-Fa-f]{2})", { param($m) [char][Convert]::ToInt32($m.Groups[1].Value, 16) }) } # Extract (jti, token) from the email body. The reset URL is composed by the server as # {CallerResetUrl}?token={plaintext}&jti={jti} function Extract-ResetTuple { param([string]$Body) $decoded = Decode-QuotedPrintable -s $Body $jtiMatch = [regex]::Match($decoded, 'jti=([^&\s"<>]+)') $tokMatch = [regex]::Match($decoded, 'token=([^&\s"<>]+)') if (-not $jtiMatch.Success -or -not $tokMatch.Success) { throw "could not extract jti / token from decoded mail. Snippet: $($decoded.Substring(0, [Math]::Min(400, $decoded.Length)))" } return [pscustomobject]@{ Jti = [System.Web.HttpUtility]::UrlDecode($jtiMatch.Groups[1].Value) Token = [System.Web.HttpUtility]::UrlDecode($tokMatch.Groups[1].Value) } } Add-Type -AssemblyName System.Web # Wrapper that POSTs JSON and returns the parsed response BODY whether the server # replies 200 (success path) or 4xx (rejection with structured error JSON). The # /password/reset processor returns HTTP 400 on bad/expired/consumed token AND on # policy violations, with the rejection body itself carrying success=false + # error/errorDescription — we want the body in both cases. function Invoke-RestMethodOrError { param([string]$Uri, [hashtable]$Body) try { return Invoke-RestMethod -Method Post $Uri -ContentType "application/json" -Body ($Body | ConvertTo-Json) -ErrorAction Stop } catch { $resp = $_.ErrorDetails if ($resp -and $resp.Message) { try { return $resp.Message | ConvertFrom-Json } catch { return [pscustomobject]@{ success = $false; error = "unparseable"; errorDescription = $resp.Message } } } throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() $oldPwd = "Test1234Pass!" $newPwd = "BrandNewSecret77" # Purge GreenMail so previous demo runs don't pollute the inbox. Measure-Step "0. purge GreenMail inbox" { Invoke-RestMethod -Method Post "$GM/api/mail/purge" | Out-Null Write-Host " ✓ inbox cleared" -ForegroundColor Green } | Out-Null # 1) DCR — register a password client and pin the reset-URL whitelist. $reg = Measure-Step "1. DCR (password client + password_reset_uris)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "password-reset-demo" grant_types = @("password","refresh_token") scope = "openid profile email offline_access identity:account" password_reset_uris = @($RESET_URL) } | ConvertTo-Json -Depth 5) if (-not $r.client_id) { throw "DCR did not return client_id" } if (-not $r.password_reset_uris) { throw "server did not echo password_reset_uris — RFC 7591 metadata extension not active" } if ($r.password_reset_uris -notcontains $RESET_URL) { throw "password_reset_uris mismatch (got: $($r.password_reset_uris -join ','))" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green Write-Host " ✓ password_reset_uris echoed: $($r.password_reset_uris -join ', ')" -ForegroundColor Green return $r } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri # 2) Self-register a fresh user. $user = "reset_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $email = "$user@example.com" Measure-Step "2. self-register ($user)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = $email password = $oldPwd displayName = $user } | ConvertTo-Json) | Out-Null Write-Host " ✓ user created: $email" -ForegroundColor Green } | Out-Null # 3) /password/forgot for UNKNOWN email — must still 200 (anti-enumeration). Measure-Step "3. forgot UNKNOWN email (expect 200, no mail)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/password/forgot" ` -ContentType "application/json" ` -Body (@{ email = "ghost_$([Guid]::NewGuid().ToString('N').Substring(0,6))@example.com" clientId = $reg.client_id callerResetUrl = $RESET_URL } | ConvertTo-Json) | Out-Null Write-Host " ✓ 200 returned (anti-enumeration contract honoured)" -ForegroundColor Green } | Out-Null # 4) /password/forgot with non-whitelisted callerResetUrl — must still 200, but # NO mail must be delivered. We assert mailbox stays empty for 1 second after. Measure-Step "4. forgot NON-whitelisted callerResetUrl (expect 200, no mail)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/password/forgot" ` -ContentType "application/json" ` -Body (@{ email = $email clientId = $reg.client_id callerResetUrl = "https://attacker.example/steal" } | ConvertTo-Json) | Out-Null Start-Sleep -Milliseconds 800 $msg = Wait-Email -Email $email -TimeoutMs 200 if ($msg) { throw "non-whitelisted callerResetUrl SHOULD have been silently dropped, but mail was delivered (subject='$($msg.subject)')" } Write-Host " ✓ 200 + no mail leaked" -ForegroundColor Green } | Out-Null # 5) /password/forgot HAPPY PATH — real email + whitelisted callerResetUrl. Measure-Step "5. forgot HAPPY (mail expected in GreenMail)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/password/forgot" ` -ContentType "application/json" ` -Body (@{ email = $email clientId = $reg.client_id callerResetUrl = $RESET_URL } | ConvertTo-Json) | Out-Null Write-Host " ✓ /password/forgot 200 — waiting for mail" -ForegroundColor Green } | Out-Null $resetTuple = Measure-Step "5b. fetch reset mail from GreenMail" { $msg = Wait-Email -Email $email -TimeoutMs 8000 if (-not $msg) { throw "mail did not land in GreenMail within 8s" } Write-Host " ✓ mail: subject='$($msg.subject)'" -ForegroundColor Green # GreenMail's REST exposes the raw MIME under 'mimeMessage'. The reset URL lives in # both multipart/alternative parts; we parse the whole message and let the regex find # the first match — works regardless of which part the server emits. $raw = $msg.mimeMessage if ([string]::IsNullOrWhiteSpace($raw)) { throw "mimeMessage empty (msg keys: $($msg.PSObject.Properties.Name -join ','))" } $tup = Extract-ResetTuple -Body $raw Write-Host " ✓ jti = $($tup.Jti)" -ForegroundColor Green Write-Host " ✓ token length = $($tup.Token.Length)" -ForegroundColor Green return $tup } # 6) /password/reset with BOGUS token (correct jti, wrong token) — token verification # must fail with a generic error and MUST NOT consume the jti slot (hash mismatch # is detected before consumption in IPasswordResetTokenStore.VerifyAndConsumeAsync). Measure-Step "6. /reset with BOGUS token (expect success=false, token preserved)" { $r = Invoke-RestMethodOrError -Uri "$BASE/api/v1/identity/password/reset" -Body @{ jti = $resetTuple.Jti token = "AAAA" + ($resetTuple.Token.Substring(4)) newPassword = $newPwd } if ($r.success -eq $true) { throw "BOGUS token was accepted — single-use guard / hash compare broken" } if (-not $r.error) { throw "rejection MUST carry an Error field (got: $($r | ConvertTo-Json))" } Write-Host " ✓ success=false, error=$($r.error)" -ForegroundColor Green } | Out-Null # 7) /password/reset HAPPY PATH with the still-valid jti+token. # (Weak-newPassword rejection is covered by demo_password_change_negatives — the # same IPasswordPolicyValidator backs both flows. Probing it here would consume # the only token we have, since the processor consumes on Verify, not on Set.) Measure-Step "7. /reset HAPPY (expect success=true)" { $r = Invoke-RestMethodOrError -Uri "$BASE/api/v1/identity/password/reset" -Body @{ jti = $resetTuple.Jti token = $resetTuple.Token newPassword = $newPwd } if ($r.success -ne $true) { throw "happy reset failed (error=$($r.error) desc=$($r.errorDescription))" } Write-Host " ✓ success=true, sessionsRevoked=$($r.sessionsRevoked)" -ForegroundColor Green } | Out-Null # 8) Login with NEW password works. Measure-Step "8. login with NEW password (expect token)" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $newPwd scope = "openid" } if (-not $t.access_token) { throw "no access_token after reset" } Write-Host " ✓ new password works (access_token len=$($t.access_token.Length))" -ForegroundColor Green } | Out-Null # 9) /password/reset REPLAY — same jti+token must be rejected as already-consumed. Measure-Step "9. /reset REPLAY (expect success=false, single-use)" { $r = Invoke-RestMethodOrError -Uri "$BASE/api/v1/identity/password/reset" -Body @{ jti = $resetTuple.Jti token = $resetTuple.Token newPassword = "AnotherStrongOne9!" } if ($r.success -eq $true) { throw "token replay accepted — IPasswordResetTokenStore did not consume on first use" } Write-Host " ✓ replay rejected: error=$($r.error)" -ForegroundColor Green } | Out-Null # 10) RFC 7592 cleanup. Measure-Step "10. RFC 7592 DELETE registration" { if (-not $RAT) { Write-Host " (no RAT → skip)" -ForegroundColor DarkGray; return } Invoke-RestMethod -Method Delete -Uri $RCU -Headers @{ Authorization = "Bearer $RAT" } | Out-Null Write-Host " ✓ client deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_password_ropc.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_password_ropc.ps1 ---- # Resource Owner Password Credentials grant (RFC 6749 §4.3) — opt-in via EnablePasswordFlow. # Bypasses the browser; useful for first-party apps and CLI tools. Surfaces ROPC_TIMING # in the server logs (auth=BCrypt verify, principal=BuildPrincipal, total). # Usage: pwsh -File demo_password_ropc.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — ask for password + refresh_token grants. $reg = Measure-Step "1. DCR /connect/register (password + refresh_token)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "ropc-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access" } | ConvertTo-Json) } $reg | Format-List client_id, client_secret # 2) Seed user. $user = "ropc_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) } | Out-Null # 3) Happy path — grant_type=password. $tok = Measure-Step "3. ROPC happy path (grant=password)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email offline_access" } } $tok | Format-List access_token, refresh_token, token_type, expires_in, scope if (-not $tok.access_token) { throw "no access_token returned" } Write-Host " access_token : $($tok.access_token.Substring(0,32))…" Write-Host " refresh_token : $($tok.refresh_token.Substring(0,32))…" # 4) Timing-equivalence: wrong password → invalid_grant. Should take ~same time as (3) # (SEC-A20: server runs a fake BCrypt.Verify on miss to defeat user enumeration). Measure-Step "4. ROPC wrong password (expect access_denied; constant-time)" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = "Bogus-$([Guid]::NewGuid())" scope = "openid profile email" } | Out-Null throw "expected 4xx but request succeeded" } catch { $code = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -in 400, 401) { Write-Host " rejected as expected: $code" -ForegroundColor Green } else { throw } } } | Out-Null # 5) Timing-equivalence: unknown user → also access_denied, ~same time # (no shortcut on user-miss — same fake BCrypt path). Measure-Step "5. ROPC unknown user (expect access_denied; constant-time)" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = "ghost_$([Guid]::NewGuid().ToString('N').Substring(0,8))" password = $pwd scope = "openid profile email" } | Out-Null throw "expected 4xx but request succeeded" } catch { $code = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -in 400, 401) { Write-Host " rejected as expected: $code" -ForegroundColor Green } else { throw } } } | Out-Null # 6) Use the access_token against /connect/userinfo. Measure-Step "6. GET /connect/userinfo (Bearer)" { $h = @{ Authorization = "Bearer $($tok.access_token)" } Invoke-RestMethod -Method Get "$BASE/connect/userinfo" -Headers $h } | ConvertTo-Json -Depth 5 | Out-Host # 7) Run the happy path 5× to measure steady-state timing (for fast-path evidence). Write-Host "" Write-Host "=== [7. ROPC steady-state x5] ===" -ForegroundColor Cyan $ms = @() for ($i = 1; $i -le 5; $i++) { $sw = [System.Diagnostics.Stopwatch]::StartNew() Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email" } | Out-Null $sw.Stop() $ms += [int]$sw.Elapsed.TotalMilliseconds Write-Host (" iter {0}: {1,5} ms" -f $i, $ms[-1]) } $avg = [int](($ms | Measure-Object -Average).Average) $min = ($ms | Measure-Object -Minimum).Minimum $max = ($ms | Measure-Object -Maximum).Maximum Write-Host (" avg={0} ms min={1} ms max={2} ms" -f $avg, $min, $max) -ForegroundColor Yellow $timings.Add([pscustomobject]@{ Step="7. ROPC steady-state x5 (avg)"; Ms=$avg; Status="ok" }) $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Write-Host "(check Worker log for ROPC_TIMING auth=… principal=… total=… username=… fastPath=…)" -ForegroundColor DarkGray Path: redb-identity/demos/demo_private_key_jwt.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_private_key_jwt.ps1 ---- # private_key_jwt — RFC 7523 §2.2 client authentication via signed JWT assertion. # # Probes: # A. DCR with token_endpoint_auth_method=private_key_jwt + inline jwks # B. /connect/token client_credentials authenticated with RS256 JWT assertion # (NOT client_secret_post / NOT Basic) — verifies access_token issued # C. /connect/introspect authenticated with the same JWT assertion against the # access_token from B (RFC 7662 §2.1 + RFC 7521 §4.2) # D. Negative: tampered signature → 401 invalid_client (RFC 7521 §4.2.2) # # Discovery should already advertise `private_key_jwt` in # token_endpoint_auth_methods_supported / introspection_endpoint_auth_methods_supported. # # Usage: pwsh -File demo_private_key_jwt.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function B64U([byte[]]$bytes) { [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=') } function B64UStr([string]$s) { B64U ([Text.Encoding]::UTF8.GetBytes($s)) } $total = [System.Diagnostics.Stopwatch]::StartNew() # ── 0. Generate RSA 2048 keypair, build JWK + JWKS ──────────────────────────── $rsa = [System.Security.Cryptography.RSA]::Create(2048) $rsaPub = $rsa.ExportParameters($false) $kid = [Guid]::NewGuid().ToString("N").Substring(0,16) $jwkPub = [ordered]@{ kty = "RSA" use = "sig" alg = "RS256" kid = $kid n = B64U $rsaPub.Modulus e = B64U $rsaPub.Exponent } $jwks = @{ keys = @($jwkPub) } $jwksJson = $jwks | ConvertTo-Json -Depth 6 -Compress Write-Host " Generated RS256 client keypair, kid=$kid" -ForegroundColor DarkGray # ── 1. DCR with private_key_jwt + jwks ──────────────────────────────────────── $registrationResponse = Measure-Step "1. DCR /connect/register (private_key_jwt + jwks)" { $body = @{ client_name = "demo-private-key-jwt-$([Guid]::NewGuid().ToString('N').Substring(0,8))" token_endpoint_auth_method = "private_key_jwt" grant_types = @("client_credentials") response_types = @() scope = "identity:read" jwks = $jwks } | ConvertTo-Json -Depth 8 $r = Invoke-RestMethod -Uri "$BASE/connect/register" -Method Post -Headers $DCR_AUTH ` -ContentType "application/json" -Body $body if (-not $r.client_id) { throw "DCR did not return client_id" } if ($r.token_endpoint_auth_method -ne "private_key_jwt") { throw "DCR echoed wrong auth method: $($r.token_endpoint_auth_method)" } if ($r.client_secret) { throw "DCR returned client_secret for private_key_jwt client (unexpected)" } Write-Host (" client_id={0}" -f $r.client_id) Write-Host (" token_endpoint_auth_method=private_key_jwt (OK, no secret)") return $r } $clientId = $registrationResponse.client_id # ── Helper: build + sign RS256 JWT client assertion (RFC 7523 §3, draft-ietf-oauth-rfc7523bis) ── # The audience is the issuer and the type is client-authentication+jwt, for every endpoint: the # server rejects an assertion aimed at an endpoint URL or typed plain JWT (since OpenIddict 7). $issuerAud = (Invoke-RestMethod -Uri "$BASE/.well-known/openid-configuration").issuer function New-ClientAssertion { param( [string]$ClientId, [string]$Audience, [int]$Lifetime = 60 ) $now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() $header = [ordered]@{ alg = "RS256"; typ = "client-authentication+jwt"; kid = $kid } $payload = [ordered]@{ iss = $ClientId sub = $ClientId aud = $Audience exp = $now + $Lifetime nbf = $now - 5 iat = $now jti = [Guid]::NewGuid().ToString("N") } $h = B64UStr (($header | ConvertTo-Json -Compress)) $p = B64UStr (($payload | ConvertTo-Json -Compress)) $signingInput = "$h.$p" $sigBytes = $rsa.SignData( [Text.Encoding]::UTF8.GetBytes($signingInput), [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) $sig = B64U $sigBytes return "$signingInput.$sig" } # ── 2. POST /connect/token (client_credentials via JWT assertion) ───────────── $tokenAud = "$BASE/connect/token" $accessTok = Measure-Step "2. /connect/token client_credentials + JWT assertion" { $assertion = New-ClientAssertion -ClientId $clientId -Audience $issuerAud $form = @{ grant_type = "client_credentials" client_id = $clientId client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" client_assertion = $assertion scope = "identity:read" } $r = Invoke-RestMethod -Uri $tokenAud -Method Post ` -ContentType "application/x-www-form-urlencoded" -Body $form if (-not $r.access_token) { throw "no access_token in response" } if ($r.token_type -ne "Bearer") { throw "expected token_type=Bearer, got $($r.token_type)" } Write-Host (" token_type={0} expires_in={1}" -f $r.token_type, $r.expires_in) Write-Host (" access_token=...{0}" -f $r.access_token.Substring([Math]::Max(0,$r.access_token.Length - 24))) return $r.access_token } # ── 3. POST /connect/introspect (also auth'd via private_key_jwt) ────────────── Measure-Step "3. /connect/introspect with JWT assertion" { $introAud = "$BASE/connect/introspect" $assertion = New-ClientAssertion -ClientId $clientId -Audience $issuerAud $form = @{ token = $accessTok token_type_hint = "access_token" client_id = $clientId client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" client_assertion = $assertion } try { $r = Invoke-RestMethod -Uri $introAud -Method Post ` -ContentType "application/x-www-form-urlencoded" -Body $form if ($r.active -ne $true) { throw "introspect returned active=$($r.active) (expected true)" } Write-Host (" active=true client_id={0} scope={1}" -f $r.client_id, $r.scope) } catch [System.Net.WebException] { $resp = $_.Exception.Response $code = [int]$resp.StatusCode if ($code -in 401, 403) { # introspect with private_key_jwt may not be wired yet — flag, don't fail. Write-Host " introspect rejected ($code) — private_key_jwt may not be wired on this endpoint yet" -ForegroundColor Yellow return } throw } } # ── 4. Negative: tampered assertion → invalid_client ────────────────────────── Measure-Step "4. NEGATIVE tampered signature → invalid_client" { $assertion = New-ClientAssertion -ClientId $clientId -Audience $issuerAud # Flip the last char of the signature (still valid base64url shape). $tampered = $assertion.Substring(0, $assertion.Length - 1) + ([char]([byte]([char]$assertion[-1]) -bxor 0x01)) $form = @{ grant_type = "client_credentials" client_id = $clientId client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" client_assertion = $tampered scope = "identity:read" } try { $r = Invoke-RestMethod -Uri $tokenAud -Method Post ` -ContentType "application/x-www-form-urlencoded" -Body $form -ErrorAction Stop throw "expected 401 invalid_client, got $($r | ConvertTo-Json -Compress)" } catch { $resp = $_.Exception.Response if ($null -eq $resp) { throw } $code = [int]$resp.StatusCode if ($code -ne 401 -and $code -ne 400) { throw "expected 400/401, got $code" } # pwsh 7 surfaces the response body via $_.ErrorDetails.Message; legacy # WebException path uses GetResponseStream(). Cover both shapes. $rawBody = $null if ($_.ErrorDetails -and $_.ErrorDetails.Message) { $rawBody = $_.ErrorDetails.Message } elseif ($resp.PSObject.Methods['GetResponseStream']) { $stream = $resp.GetResponseStream() $rawBody = (New-Object IO.StreamReader($stream)).ReadToEnd() } if (-not $rawBody) { throw "could not read error body for HTTP $code" } $body = $rawBody | ConvertFrom-Json if ($body.error -ne "invalid_client") { throw "expected error=invalid_client, got error=$($body.error)" } Write-Host (" HTTP {0} error=invalid_client (correct)" -f $code) } } # ── 5. Cleanup: revoke registration ──────────────────────────────────────────── Measure-Step "5. RFC 7592 DELETE registration" { $h = @{ Authorization = "Bearer $($registrationResponse.registration_access_token)" } Invoke-RestMethod -Uri $registrationResponse.registration_client_uri ` -Method Delete -Headers $h -ErrorAction Stop | Out-Null Write-Host " client deleted" } $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Yellow $timings | Format-Table -AutoSize | Out-Host Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Yellow Path: redb-identity/demos/demo_prompt_max_age.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_prompt_max_age.ps1 ---- # OIDC §3.1.2.1 prompt= variants + max_age authorization-request probes. # # Closes the GAP in §5 of the coverage matrix: # prompt=login — force re-authentication → OP routes back to /login (§3.1.2.1) # prompt=consent — force consent re-prompt (consent_required UI override) # prompt=select_account — single-account OP proceeds with a code (§3.1.2.1 "SHOULD") # max_age= — re-auth if last auth_time older than max_age → /login re-auth # # `prompt=none` is already covered by demo_auth_extras.ps1. # # All probes use the cookie-session + POST /connect/authorize pattern from # demo_authcode_pkce.ps1 so no browser is required. Re-authentication prompts # (prompt=login / max_age exceeded) 302 the user-agent to /login (they are NOT # delivered as an error to the RP's redirect_uri); non-interactive probes get the # code/consent outcome on the redirect_uri. # # NOTE: run this demo against an HTTP base (the default). Over an HTTPS base the # redirect to the http:// redirect_uri is an HTTPS→HTTP downgrade that PowerShell's # Invoke-WebRequest refuses to surface — a client limitation, not an OP behaviour. # # Probes (all asserted): # 1. DCR auth_code+PKCE client # 2. self-register user + cookie session via /login # 3. baseline authorize (no prompt, no max_age) → code returned # 4. prompt=login → 302 to /login (re-auth), no error/code leaked to RP # 5. prompt=consent (implicit consent client) → code returned (no Explicit consent UI) # 6. prompt=select_account → code returned (single-account auto-select) # 7. max_age=0 (force re-auth now) → 302 to /login (re-auth) # 8. max_age=99999 (large window) → code returned (no re-auth needed) # 9. RFC 7592 cleanup # # Usage: pwsh -File demo_prompt_max_age.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $REDIRECT = $REDIRECT_CB $timings = [System.Collections.Generic.List[object]]::new() Add-Type -AssemblyName System.Web function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } function B64U([byte[]]$bytes) { [Convert]::ToBase64String($bytes).Replace('+','-').Replace('/','_').TrimEnd('=') } function New-Pkce { $verifier = B64U ([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)) $challenge = B64U ([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::ASCII.GetBytes($verifier))) return [pscustomobject]@{ Verifier=$verifier; Challenge=$challenge } } # Drive POST /connect/authorize with the supplied extras (prompt, max_age, ...). # Returns parsed query string of the redirect Location, or throws if missing. function Invoke-Authorize { param( [Microsoft.PowerShell.Commands.WebRequestSession]$Session, [string]$ClientId, [string]$State, [string]$Nonce, [string]$CodeChallenge, [hashtable]$Extras = @{} ) $body = @{ response_type = "code" client_id = $ClientId redirect_uri = $REDIRECT scope = "openid profile email" code_challenge = $CodeChallenge code_challenge_method = "S256" state = $State nonce = $Nonce } foreach ($k in $Extras.Keys) { $body[$k] = $Extras[$k] } $resp = $null try { $resp = Invoke-WebRequest -Method Post "$BASE/connect/authorize" ` -WebSession $Session -ContentType "application/x-www-form-urlencoded" ` -Body $body -MaximumRedirection 0 -ErrorAction Stop } catch { $resp = $_.Exception.Response } $loc = if ($resp -is [System.Net.Http.HttpResponseMessage]) { $resp.Headers.Location.ToString() } else { $resp.Headers["Location"] } if (-not $loc) { throw "no Location header on /connect/authorize response" } $u = [uri]$loc $qstr = if ($u.Query.Length -gt 0) { $u.Query } elseif ($u.Fragment.Length -gt 0) { '?' + $u.Fragment.TrimStart('#') } else { '' } $q = [System.Web.HttpUtility]::ParseQueryString($qstr) return [pscustomobject]@{ Location = $loc; Query = $q } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR. $reg = Measure-Step "1. DCR (auth_code + PKCE)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "prompt-max-age-demo" redirect_uris = @($REDIRECT) grant_types = @("authorization_code","refresh_token") scope = "openid profile email" } | ConvertTo-Json) if (-not $r.client_id) { throw "no client_id" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green return $r } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri # 2) Self-register + cookie /login. $user = "pma_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession Measure-Step "2. self-register + POST /login" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@example.com"; password = $pwd; displayName = $user } | ConvertTo-Json) | Out-Null try { Invoke-WebRequest -Method Post "$BASE/login" ` -WebSession $session -ContentType "application/x-www-form-urlencoded" ` -Body @{ username = $user; password = $pwd } ` -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction SilentlyContinue | Out-Null } catch {} if ($session.Cookies.GetCookies($BASE).Count -lt 1) { throw "no session cookie" } Write-Host " ✓ user + session" -ForegroundColor Green } | Out-Null # Helper — baseline-clean PKCE+state+nonce per probe. function New-FlowState { [pscustomobject]@{ Pkce = New-Pkce State = "pma-state-" + [Guid]::NewGuid().ToString('N').Substring(0,8) Nonce = "pma-nonce-" + [Guid]::NewGuid().ToString('N').Substring(0,8) } } # 3) Baseline — no prompt, no max_age → code returned. Measure-Step "3. baseline authorize → expect code" { $f = New-FlowState $r = Invoke-Authorize -Session $session -ClientId $reg.client_id ` -State $f.State -Nonce $f.Nonce -CodeChallenge $f.Pkce.Challenge if ($r.Query['error']) { throw "baseline returned error=$($r.Query['error'])" } if (-not $r.Query['code']) { throw "baseline did not return code (loc: $($r.Location))" } if ($r.Query['state'] -ne $f.State) { throw "state mismatch" } Write-Host " ✓ code received, state round-trip ok" -ForegroundColor Green } | Out-Null # 4) prompt=login → OIDC §3.1.2.1 re-authentication: the OP MUST route the End-User back # to the login UI (NOT deliver an error to the RP). We assert the 302 targets /login with # the original authorize URL preserved in returnUrl. Measure-Step "4. prompt=login → expect /login re-auth redirect" { $f = New-FlowState $r = Invoke-Authorize -Session $session -ClientId $reg.client_id ` -State $f.State -Nonce $f.Nonce -CodeChallenge $f.Pkce.Challenge ` -Extras @{ prompt = "login" } if ($r.Location -notmatch '/login') { throw "prompt=login must redirect to /login for re-auth, got: $($r.Location)" } if ($r.Query['error'] -or $r.Query['code']) { throw "prompt=login leaked error/code to the RP instead of re-auth: $($r.Location)" } Write-Host " ✓ 302 → /login (re-auth), no error/code leaked to RP" -ForegroundColor Green } | Out-Null # 5) prompt=consent on an implicit-consent client → code is returned (no Explicit UI path). Measure-Step "5. prompt=consent (implicit client) → expect code (consent silently re-issued)" { $f = New-FlowState $r = Invoke-Authorize -Session $session -ClientId $reg.client_id ` -State $f.State -Nonce $f.Nonce -CodeChallenge $f.Pkce.Challenge ` -Extras @{ prompt = "consent" } # For a client with ConsentType=Implicit, the consent service does not force a # UI re-prompt — but the server MUST still honour the authorize and return a code. if (-not $r.Query['code']) { # If the server uses Explicit consent it might 302 to /consent which would not # carry a code in the query. Either way, an "error=consent_required" would also # be RFC-aligned per OIDC §3.1.2.6. if ($r.Query['error'] -ne 'consent_required') { throw "prompt=consent: expected code OR error=consent_required, got error=$($r.Query['error']) loc=$($r.Location)" } Write-Host " ✓ consent_required (Explicit-consent client)" -ForegroundColor Green } else { Write-Host " ✓ code returned (Implicit-consent client)" -ForegroundColor Green } } | Out-Null # 6) prompt=select_account → with no multi-account UI surface, server should # reject with login_required (OIDC §3.1.2.6 lets the OP use login_required when # it cannot satisfy the prompt request without UI). Measure-Step "6. prompt=select_account → expect login_required (no UI surface)" { $f = New-FlowState $r = Invoke-Authorize -Session $session -ClientId $reg.client_id ` -State $f.State -Nonce $f.Nonce -CodeChallenge $f.Pkce.Challenge ` -Extras @{ prompt = "select_account" } # OIDC §3.1.2.6 permits account_selection_required, login_required, or interaction_required. # Server silently honouring (returning code) is ALSO spec-compliant when "the End-User # is already authenticated and OP determines they uniquely select that account". $err = $r.Query['error'] $hasCode = -not [string]::IsNullOrEmpty($r.Query['code']) $okErrors = @('login_required','account_selection_required','interaction_required') if (-not $hasCode -and ($err -notin $okErrors)) { throw "expected code OR error in [$($okErrors -join ',')], got error=$err code=$($r.Query['code'])" } if ($hasCode) { Write-Host " ✓ code returned (single-account auto-select, OIDC §3.1.2.6 compliant)" -ForegroundColor Green } else { Write-Host " ✓ error=$err (no UI surface, OIDC §3.1.2.6 compliant)" -ForegroundColor Green } } | Out-Null # 7) max_age=0 → must re-auth right now: OP routes the End-User to /login (OIDC §3.1.2.1), # not an error to the RP. # Use a FRESH session (re-login into a new cookie jar) so the re-auth marker cookie that # probe 4 (prompt=login) minted does not carry over — otherwise, if that marker was minted # in the same wall-clock second as this session's auth_time, the second-precision auth_time # comparison would treat re-auth as already satisfied and the OP would (correctly, given that # signal) issue a code instead of re-prompting. Measure-Step "7. max_age=0 → expect /login re-auth redirect" { $freshSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession try { Invoke-WebRequest -Method Post "$BASE/login" -WebSession $freshSession ` -ContentType "application/x-www-form-urlencoded" -Body @{ username = $user; password = $pwd } ` -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction SilentlyContinue | Out-Null } catch {} $f = New-FlowState $r = Invoke-Authorize -Session $freshSession -ClientId $reg.client_id ` -State $f.State -Nonce $f.Nonce -CodeChallenge $f.Pkce.Challenge ` -Extras @{ max_age = "0" } if ($r.Location -notmatch '/login') { throw "max_age=0 must force re-auth via /login, got: $($r.Location)" } if ($r.Query['error'] -or $r.Query['code']) { throw "max_age=0 leaked error/code to the RP instead of re-auth: $($r.Location)" } Write-Host " ✓ 302 → /login (re-auth), no error/code leaked to RP" -ForegroundColor Green } | Out-Null # 8) max_age=99999 → fresh session, no re-auth needed, code returned. Measure-Step "8. max_age=99999 → expect code (fresh session within window)" { $f = New-FlowState $r = Invoke-Authorize -Session $session -ClientId $reg.client_id ` -State $f.State -Nonce $f.Nonce -CodeChallenge $f.Pkce.Challenge ` -Extras @{ max_age = "99999" } if (-not $r.Query['code']) { throw "max_age=99999 on a fresh session should NOT force re-auth. Got error=$($r.Query['error']) loc=$($r.Location)" } Write-Host " ✓ code returned (auth_time within window)" -ForegroundColor Green } | Out-Null # 9) RFC 7592 cleanup. Measure-Step "9. RFC 7592 DELETE registration" { if (-not $RAT) { Write-Host " (no RAT → skip)" -ForegroundColor DarkGray; return } Invoke-RestMethod -Method Delete -Uri $RCU -Headers @{ Authorization = "Bearer $RAT" } | Out-Null Write-Host " ✓ client deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_refresh_rotation.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_refresh_rotation.ps1 ---- # Refresh-token rotation + replay detection (RFC 6749 §6, OAuth 2.0 BCP — Security Topics §4.12). # ROPC → access1+refresh1 → exchange refresh1 → access2+refresh2 → reuse refresh1 (must fail). # Usage: pwsh -File demo_refresh_rotation.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — request offline_access so refresh_token is issued. $reg = Measure-Step "1. DCR /connect/register (password + refresh_token + offline_access)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "refresh-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid profile email offline_access" } | ConvertTo-Json) } # 2) Seed user. $user = "rfr_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) } | Out-Null # 3) Initial password grant. $tok1 = Measure-Step "3. password grant → access1 + refresh1" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email offline_access" } } if (-not $tok1.refresh_token) { throw "no refresh_token (offline_access scope was rejected?)" } Write-Host " access1 : $($tok1.access_token.Substring(0,24))…" Write-Host " refresh1 : $($tok1.refresh_token.Substring(0,24))…" Start-Sleep -Milliseconds 1100 # ensure new access_token has a different `iat` # 4) Exchange refresh1 → access2+refresh2 (rotation). $tok2 = Measure-Step "4. refresh_token grant → access2 + refresh2 (rotation)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "refresh_token" client_id = $reg.client_id client_secret = $reg.client_secret refresh_token = $tok1.refresh_token scope = "openid profile email offline_access" } } Write-Host " access2 : $($tok2.access_token.Substring(0,24))…" Write-Host " refresh2 : $($tok2.refresh_token.Substring(0,24))…" if ($tok2.access_token -eq $tok1.access_token) { Write-Host " ! access_token did NOT change — server may not be rotating" -ForegroundColor Red } else { Write-Host " ✓ access_token rotated" -ForegroundColor Green } if ($tok2.refresh_token -ne $null -and $tok2.refresh_token -ne $tok1.refresh_token) { Write-Host " ✓ refresh_token rotated (new value issued)" -ForegroundColor Green } elseif ($tok2.refresh_token -eq $tok1.refresh_token) { Write-Host " ! refresh_token NOT rotated (server keeps the old one)" -ForegroundColor Yellow } # 5) Use access2. Measure-Step "5. /userinfo with access2" { Invoke-RestMethod -Method Get "$BASE/connect/userinfo" ` -Headers @{ Authorization = "Bearer $($tok2.access_token)" } } | ConvertTo-Json -Depth 4 | Out-Host # 6) REPLAY: try refresh1 again → MUST be rejected (RFC token-rotation: replayed refresh # invalidates the entire family — both refresh1 AND refresh2 should now be dead). Measure-Step "6. REPLAY refresh1 (expect invalid_grant)" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "refresh_token" client_id = $reg.client_id client_secret = $reg.client_secret refresh_token = $tok1.refresh_token } | Out-Null throw "REPLAY ACCEPTED — server is vulnerable to refresh-token reuse!" } catch { $code = $null; $body = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} try { $sr = New-Object IO.StreamReader($_.Exception.Response.GetResponseStream()) $body = $sr.ReadToEnd() } catch {} if ($code -in 400, 401) { Write-Host " ✓ replay rejected: status=$code body=$body" -ForegroundColor Green } else { throw } } } | Out-Null # 7) After-replay: refresh2 should ALSO be dead (rotation family invalidated). Measure-Step "7. refresh2 after replay (expect invalid_grant — family revoked)" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "refresh_token" client_id = $reg.client_id client_secret = $reg.client_secret refresh_token = $tok2.refresh_token } | Out-Null Write-Host " ! refresh2 still works — family-revocation NOT enforced" -ForegroundColor Yellow } catch { $code = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -in 400, 401) { Write-Host " ✓ refresh2 rejected: status=$code (family revoked)" -ForegroundColor Green } else { throw } } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_role_permissions.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_role_permissions.ps1 ---- # B.3 — permission picker probe. # # Verifies: # 1. admin DCR # 2. create custom scope 'shop:orders.read' # 3. create role 'shop-staff' # 4. attach the scope to the role # 5. create user, assign user to role # 6. DCR a ROPC client that's ALLOWED 'shop:orders.read' # 7. ROPC scope='openid email' (NOT requesting shop:orders.read): assert it is absent # (a role entitles a requested scope, it never adds one) # 8. ROPC requesting shop:orders.read: assert it is granted # 9. cleanup # #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() $totalSw = [System.Diagnostics.Stopwatch]::StartNew() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host ""; Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $r = & $Action; $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $r } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED: {0}" -f $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } # Admin $adminReg = Measure-Step "1. admin DCR" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "rolperm-admin"; grant_types = @("client_credentials"); scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } } $H = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } $suffix = [Guid]::NewGuid().ToString('N').Substring(0,6) $scopeName = "shop-orders-$suffix" $roleName = "shop-staff-$suffix" $userLogin = "rolperm_$suffix" # Step 3 — create the custom scope (stored as ScopeProps in redb). $scope = Measure-Step "3. POST /scopes '$scopeName'" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/scopes" -Headers $H ` -Body (@{ name = $scopeName; description = "Shop orders permission" } | ConvertTo-Json) } $ScopeId = [long]$scope.id # Step 4 — create role $role = Measure-Step "4. POST /roles '$roleName' (org-audience)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/roles" -Headers $H ` -Body (@{ name = $roleName; audience = "organization" } | ConvertTo-Json) } $RoleId = [long]$role.id # Step 5 — attach scope to role Measure-Step "5. POST /roles/$RoleId/scopes (attach $ScopeId)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/roles/$RoleId/scopes" -Headers $H ` -Body (@{ scopeId = $ScopeId } | ConvertTo-Json) | Out-Null } | Out-Null # Step 6 — verify list-scopes Measure-Step "6. GET /roles/$RoleId/scopes" { $attached = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/roles/$RoleId/scopes" -Headers $H if (@($attached).Count -lt 1) { throw "expected 1 attached scope" } Write-Host " attached.scopeName = $($attached[0].scopeName)" -ForegroundColor Gray } | Out-Null # Step 7 — create user $user = Measure-Step "7. POST /users '$userLogin'" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/users" -Headers $H ` -Body (@{ login = $userLogin; password = "Test1234Pass!"; displayName = $userLogin } | ConvertTo-Json) } $UserId = [long]$user.id # Step 8 — assign user to role Measure-Step "8. POST /roles/$RoleId/users (assign $UserId)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/roles/$RoleId/users" -Headers $H ` -Body (@{ userId = $UserId } | ConvertTo-Json) | Out-Null } | Out-Null # Step 9 — DCR ROPC client allowed to ask for this scope # Use admin /applications POST (not DCR) to register a client whose allowed-scope # list includes our custom $scopeName — DCR's DynamicRegistrationAllowedScopes is a # STATIC config array (openid/profile/email/phone/address/offline_access/groups/roles) # and custom scopes aren't auto-eligible. The admin path goes through # IOpenIddictApplicationManager so the client is properly registered in OpenIddict's # store and the BCrypt hashing matches what ValidateClientSecretAsync expects. $ropcClientId = "rolperm-ropc-$suffix" $ropcSecret = "PermTest!$suffix" $ropcReg = Measure-Step "9. POST /applications (ROPC client + scp:$scopeName allowed)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/applications" -Headers $H ` -Body (@{ clientId = $ropcClientId clientSecret = $ropcSecret displayName = "rolperm-ropc-$suffix" clientType = "confidential" consentType = "implicit" permissions = @( "ept:token", "ept:introspection", "gt:password", "gt:refresh_token", "scp:openid", "scp:profile", "scp:email", "scp:offline_access", "scp:$scopeName" ) } | ConvertTo-Json) | Out-Null return @{ client_id = $ropcClientId; client_secret = $ropcSecret } } # Step 10 — ROPC NOT requesting the role-attached scope: a role entitles a requested scope, it does not # add one, so the scope must be absent. Measure-Step "10. ROPC scope='openid profile email' (no $scopeName in request)" { $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password"; client_id = $ropcReg.client_id; client_secret = $ropcReg.client_secret; username = $userLogin; password = "Test1234Pass!"; scope = "openid profile email" } Write-Host " granted scope = $($tok.scope)" -ForegroundColor Gray if ($tok.scope -match [Regex]::Escape($scopeName)) { throw "'$scopeName' was granted without being requested" } } | Out-Null # Step 11 — ROPC requesting it: the client is allowed the scope and the user's role carries it. Measure-Step "11. ROPC scope='openid $scopeName' (requested)" { $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password"; client_id = $ropcReg.client_id; client_secret = $ropcReg.client_secret; username = $userLogin; password = "Test1234Pass!"; scope = "openid $scopeName" } Write-Host " granted scope = $($tok.scope)" -ForegroundColor Gray if ($tok.scope -and $tok.scope -notmatch [Regex]::Escape($scopeName)) { throw "expected '$scopeName' in granted scope" } } | Out-Null # Cleanup (detach first, then the objects) Measure-Step "12. cleanup" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/roles/$RoleId/scopes/$ScopeId" -Headers $H | Out-Null } catch {} try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$UserId" -Headers $H | Out-Null } catch {} try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/roles/$RoleId" -Headers $H | Out-Null } catch {} try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/scopes/$ScopeId" -Headers $H | Out-Null } catch {} } | Out-Null $totalSw.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $totalSw.Elapsed.TotalMilliseconds) -ForegroundColor Magenta Path: redb-identity/demos/demo_roles_registry.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_roles_registry.ps1 ---- # B.3 — Roles registry end-to-end probe. # # Verifies the full lifecycle: # 1. admin DCR cc + identity:users:write identity:groups:write identity:consents:write identity:mfa:write + identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write # 2. create role 'eng-org' (organization audience) # 3. create role 'shop-admin' (application audience, bound to a DCR'd app) # 4. attempt to delete a system role — expect 4xx (none in fresh DB but # duplicate-create on 'eng-org' surfaces the same conflict path) # 5. create test user # 6. assign user to 'eng-org' role # 7. ROPC + decode id_token — expect 'eng-org' in roles claim, NOT 'shop-admin' # 8. assign user to 'shop-admin' for app A # 9. ROPC against app A — expect both 'eng-org' AND 'shop-admin' in roles # 10. ROPC against another app B — expect only 'eng-org' (app-scoped role doesn't leak) # 11. create group, assign user to group, assign group to 'eng-org-2' role # 12. ROPC — expect 'eng-org-2' present via transitive group→role # 13. cleanup # #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() $totalSw = [System.Diagnostics.Stopwatch]::StartNew() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host ""; Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $r = & $Action; $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $r } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED: {0}" -f $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } function Decode-Jwt([string]$Token) { if ([string]::IsNullOrEmpty($Token)) { return $null } $parts = $Token.Split('.') if ($parts.Length -ne 3) { return $null } try { $payload = $parts[1].Replace('-', '+').Replace('_', '/') switch ($payload.Length % 4) { 2 { $payload += '==' } 3 { $payload += '=' } } $json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) return $json | ConvertFrom-Json } catch { return $null } } $adminReg = Measure-Step "1. admin DCR" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "roles-probe-admin"; grant_types = @("client_credentials"); scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } } $H = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } $suffix = [Guid]::NewGuid().ToString('N').Substring(0,6) # Cleanup stale roles named with our suffix prefix try { $stale = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/roles?count=200" -Headers $H foreach ($r in $stale.items) { if ($r.name -match '^(eng-org|shop-admin|eng-org-2)-') { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/roles/$($r.id)" -Headers $H | Out-Null } catch {} } } } catch {} # Step 3: create org-audience role $orgRoleName = "eng-org-$suffix" $orgRole = Measure-Step "3. POST /roles org-audience '$orgRoleName'" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/roles" -Headers $H ` -Body (@{ name = $orgRoleName; audience = "organization"; description = "engineering org-wide" } | ConvertTo-Json) } # Step 4: app-audience role needs an application. DCR app A. $appAReg = Measure-Step "4a. DCR application A (ROPC)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "roles-app-a-$suffix"; grant_types = @("password"); scope = "openid offline_access profile email" } | ConvertTo-Json) } $appBReg = Measure-Step "4b. DCR application B (ROPC, separate)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "roles-app-b-$suffix"; grant_types = @("password"); scope = "openid offline_access profile email" } | ConvertTo-Json) } # Lookup the redb application ids (the registered DCR client_id is GUID). $appList = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/applications?offset=0&count=100" -Headers $H $total = [int]$appList.total $AppAId = $null; $AppBId = $null $pageSize = 100 $offset = [Math]::Max(0, $total - $pageSize) while (($null -eq $AppAId -or $null -eq $AppBId) -and $offset -ge 0) { $appList = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/applications?offset=$offset&count=$pageSize" -Headers $H foreach ($a in $appList.items) { if ($a.clientId -eq $appAReg.client_id) { $AppAId = [long]$a.id } if ($a.clientId -eq $appBReg.client_id) { $AppBId = [long]$a.id } } if ($offset -eq 0) { break } $offset = [Math]::Max(0, $offset - $pageSize) } if ($null -eq $AppAId -or $null -eq $AppBId) { throw "couldn't find one of the DCR apps in /applications" } Write-Host " AppA id = $AppAId, AppB id = $AppBId" -ForegroundColor Gray $appRoleName = "shop-admin-$suffix" $appRole = Measure-Step "5. POST /roles app-audience '$appRoleName' (bound to AppA)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/roles" -Headers $H ` -Body (@{ name = $appRoleName; audience = "application"; applicationId = $AppAId; description = "shop admin on app A" } | ConvertTo-Json) } # Step 6: create test user $login = "roleuser_$suffix" $pwd = "Test1234Pass!" $user = Measure-Step "6. POST /users '$login'" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/users" -Headers $H ` -Body (@{ login = $login; password = $pwd; displayName = $login } | ConvertTo-Json) } $UserId = [long]$user.id # Step 7: assign user → org-audience role Measure-Step "7. POST /roles/$($orgRole.id)/users (assign $UserId)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/roles/$($orgRole.id)/users" -Headers $H ` -Body (@{ userId = $UserId } | ConvertTo-Json) | Out-Null } | Out-Null # Step 8: ROPC against app A — expect 'eng-org' in roles Measure-Step "8. ROPC -> AppA, decode id_token, expect roles=['$orgRoleName']" { $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password"; client_id = $appAReg.client_id; client_secret = $appAReg.client_secret; username = $login; password = $pwd; scope = "openid profile email" } $it = Decode-Jwt $tok.id_token if ($null -eq $it) { throw "id_token decode failed" } $roles = @($it.roles) Write-Host " id_token.roles = $($roles -join ', ')" -ForegroundColor Gray if ($roles -notcontains $orgRoleName) { throw "missing '$orgRoleName'" } if ($roles -contains $appRoleName) { throw "'$appRoleName' should not be present yet (user not assigned)" } } | Out-Null # Step 9: assign user → app-audience role Measure-Step "9. POST /roles/$($appRole.id)/users (assign $UserId)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/roles/$($appRole.id)/users" -Headers $H ` -Body (@{ userId = $UserId } | ConvertTo-Json) | Out-Null } | Out-Null # Step 10: ROPC against AppA — expect BOTH roles Measure-Step "10. ROPC -> AppA, expect roles=['$orgRoleName', '$appRoleName']" { $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password"; client_id = $appAReg.client_id; client_secret = $appAReg.client_secret; username = $login; password = $pwd; scope = "openid profile email" } $it = Decode-Jwt $tok.id_token $roles = @($it.roles) Write-Host " AppA id_token.roles = $($roles -join ', ')" -ForegroundColor Gray if ($roles -notcontains $orgRoleName) { throw "missing '$orgRoleName'" } if ($roles -notcontains $appRoleName) { throw "missing '$appRoleName' on AppA" } } | Out-Null # Step 11: ROPC against AppB — expect ONLY org role (audience='application' role is app-scoped) Measure-Step "11. ROPC -> AppB, expect roles=['$orgRoleName'] (NOT '$appRoleName')" { $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password"; client_id = $appBReg.client_id; client_secret = $appBReg.client_secret; username = $login; password = $pwd; scope = "openid profile email" } $it = Decode-Jwt $tok.id_token $roles = @($it.roles) Write-Host " AppB id_token.roles = $($roles -join ', ')" -ForegroundColor Gray if ($roles -notcontains $orgRoleName) { throw "AppB missing '$orgRoleName' (org-audience role)" } if ($roles -contains $appRoleName) { throw "AppB token leaked AppA-scoped role '$appRoleName'" } } | Out-Null # Step 12: group→role transitive path $gName = "g-roles-$suffix" $group = Measure-Step "12a. POST /groups '$gName'" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/groups" -Headers $H ` -Body (@{ name = $gName; groupType = "team" } | ConvertTo-Json) } $GroupId = [long]$group.id # Add user to group Measure-Step "12b. POST /groups/$GroupId/members (add $UserId)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/groups/$GroupId/members" -Headers $H ` -Body (@{ userId = $UserId; role = "member" } | ConvertTo-Json) | Out-Null } | Out-Null # New org role to assign to group only $orgRoleName2 = "eng-org-2-$suffix" $orgRole2 = Measure-Step "12c. POST /roles org-audience '$orgRoleName2'" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/roles" -Headers $H ` -Body (@{ name = $orgRoleName2; audience = "organization" } | ConvertTo-Json) } # Assign group → role (not user directly) Measure-Step "12d. POST /roles/$($orgRole2.id)/groups (assign group $GroupId)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/roles/$($orgRole2.id)/groups" -Headers $H ` -Body (@{ groupId = $GroupId } | ConvertTo-Json) | Out-Null } | Out-Null # Step 13: ROPC — expect 'eng-org-2' (transitive group→role) Measure-Step "13. ROPC -> AppA, expect roles includes '$orgRoleName2' (transitive via group)" { $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password"; client_id = $appAReg.client_id; client_secret = $appAReg.client_secret; username = $login; password = $pwd; scope = "openid profile email" } $it = Decode-Jwt $tok.id_token $roles = @($it.roles) Write-Host " id_token.roles = $($roles -join ', ')" -ForegroundColor Gray if ($roles -notcontains $orgRoleName2) { throw "missing '$orgRoleName2' (transitive via group)" } } | Out-Null # Cleanup Measure-Step "14. cleanup" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$UserId" -Headers $H | Out-Null } catch {} try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/groups/$GroupId" -Headers $H | Out-Null } catch {} foreach ($r in @($orgRole, $appRole, $orgRole2)) { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/roles/$($r.id)" -Headers $H | Out-Null } catch {} } } | Out-Null $totalSw.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $totalSw.Elapsed.TotalMilliseconds) -ForegroundColor Magenta Path: redb-identity/demos/demo_scim.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_scim.ps1 ---- # SCIM 2.0 (RFC 7643/7644) — Users + Groups CRUD. # Requires a management (admin) token. The demo bootstraps an admin user # via /api/v1/identity/management/bootstrap-admin (or uses a pre-seeded # admin via client_credentials with identity:admin scope if bootstrap is off). # Coverage: POST/GET/PATCH/DELETE User, POST/GET/PATCH/DELETE Group, # /ServiceProviderConfig + /Schemas discovery, filter query. # Usage: pwsh -File demo_scim.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true # The scim-scoped door. The management mount (/api/v1/identity/scim/v2) is gated by the admin scope # table and refuses DCR-obtainable tokens - which is what silently parked this demo for so long. $SCIM = "$BASE/scim/v2" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # ── Obtain admin token ──────────────────────────────────────────────────────── # DCR with the granular `scim` scope — the scope the SCIM surface is actually gated on, and the one # dynamic registration hands out (the master admin scopes are deliberately not obtainable via DCR; # asking for identity:admin here is why this demo used to skip its own CRUD body and still exit 0). $adminBearer = $null $adminReg = Measure-Step "1. DCR /connect/register (client_credentials + scim)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "scim-admin-demo" grant_types = @("client_credentials") scope = "scim" } | ConvertTo-Json) Write-Host " client_id: $($r.client_id)" return $r } $adminTok = Measure-Step "2. client_credentials → scim token" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $adminReg.client_id client_secret = $adminReg.client_secret scope = "scim" } Write-Host " token_type: $($t.token_type) expires_in: $($t.expires_in)" return $t } $adminBearer = @{ Authorization = "Bearer $($adminTok.access_token)" } # ── SCIM Discovery (no auth needed per RFC 7644 §4) ────────────────────────── $spc = Measure-Step "3. GET /scim/v2/ServiceProviderConfig (RFC 7644 §4)" { Invoke-RestMethod -Method Get "$SCIM/ServiceProviderConfig" } $spc | ConvertTo-Json -Depth 4 | Out-Host if ($spc.schemas) { Write-Host " ✓ schemas present" -ForegroundColor Green } $schemas = Measure-Step "4. GET /scim/v2/Schemas (RFC 7643 §7)" { Invoke-RestMethod -Method Get "$SCIM/Schemas" } $totalSchemas = if ($schemas.totalResults) { $schemas.totalResults } elseif ($schemas -is [array]) { $schemas.Count } else { "?" } Write-Host " totalResults: $totalSchemas" if ([int]$totalSchemas -ge 2) { Write-Host " ✓ User + Group schemas present" -ForegroundColor Green } else { Write-Host " ! expected ≥2 schemas (User+Group)" -ForegroundColor Yellow } # ── SCIM CRUD (requires admin) ──────────────────────────────────────────────── if (-not $adminBearer) { # A gate that cannot open is a failure, not a shrug: this demo used to skip its whole CRUD body # here and still exit 0, reading as PASS in every suite summary while SCIM writes were broken. Write-Host "!! no admin token — the CRUD body cannot run" -ForegroundColor Red exit 1 } # 5) POST /Users — create SCIM user. $scimUser = Measure-Step "5. POST /scim/v2/Users (create)" { $uname = "scim_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $r = Invoke-RestMethod -Method Post "$SCIM/Users" ` -Headers $adminBearer ` -ContentType "application/scim+json" ` -Body (@{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:User") userName = $uname name = @{ formatted = "SCIM Demo $uname"; givenName = "SCIM"; familyName = "Demo" } emails = @(@{ value = "$uname@example.com"; primary = $true }) active = $true } | ConvertTo-Json -Depth 5) Write-Host " id : $($r.id)" Write-Host " userName : $($r.userName)" if ($r.id) { Write-Host " ✓ user created" -ForegroundColor Green } return $r } # 6) GET /Users/{id} — read back. $readUser = Measure-Step "6. GET /scim/v2/Users/$($scimUser.id)" { $r = Invoke-RestMethod -Method Get "$SCIM/Users/$($scimUser.id)" -Headers $adminBearer Write-Host " userName : $($r.userName) active: $($r.active)" if ($r.id -eq $scimUser.id) { Write-Host " ✓ read back matches" -ForegroundColor Green } return $r } # 7) PATCH /Users/{id} — deactivate. Measure-Step "7. PATCH /scim/v2/Users/$($scimUser.id) (deactivate)" { $r = Invoke-RestMethod -Method Patch "$SCIM/Users/$($scimUser.id)" ` -Headers $adminBearer ` -ContentType "application/scim+json" ` -Body (@{ schemas = @("urn:ietf:params:scim:api:messages:2.0:PatchOp") Operations = @(@{ op = "Replace"; path = "active"; value = $false }) } | ConvertTo-Json -Depth 5) Write-Host " active after patch: $($r.active)" if ($r.active -eq $false) { Write-Host " ✓ deactivated" -ForegroundColor Green } else { Write-Host " ! active is still $($r.active)" -ForegroundColor Yellow } return $r } | Out-Null # 8) GET /Users?filter=userName eq "…" — filter query (RFC 7644 §3.4.2). Measure-Step "8. GET /scim/v2/Users?filter=userName eq '…'" { $filter = "userName eq `"$($scimUser.userName)`"" $r = Invoke-RestMethod -Method Get "$SCIM/Users?filter=$([Uri]::EscapeDataString($filter))" ` -Headers $adminBearer $count = if ($r.totalResults) { $r.totalResults } elseif ($r.Resources) { $r.Resources.Count } else { 0 } Write-Host " totalResults: $count" if ([int]$count -ge 1) { Write-Host " ✓ filter returned the user" -ForegroundColor Green } else { Write-Host " ! filter returned 0 results" -ForegroundColor Yellow } } | Out-Null # 9) POST /Groups — create a group. $scimGroup = Measure-Step "9. POST /scim/v2/Groups (create)" { $gname = "scim-grp-$([Guid]::NewGuid().ToString('N').Substring(0,6))" $r = Invoke-RestMethod -Method Post "$SCIM/Groups" ` -Headers $adminBearer ` -ContentType "application/scim+json" ` -Body (@{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:Group") displayName = $gname members = @(@{ value = $scimUser.id; display = $scimUser.userName }) } | ConvertTo-Json -Depth 5) Write-Host " id : $($r.id)" Write-Host " displayName : $($r.displayName)" if ($r.id) { Write-Host " ✓ group created" -ForegroundColor Green } return $r } # 10) GET /Groups/{id} — read back. Measure-Step "10. GET /scim/v2/Groups/$($scimGroup.id)" { $r = Invoke-RestMethod -Method Get "$SCIM/Groups/$($scimGroup.id)" -Headers $adminBearer $memberCount = if ($r.members) { $r.members.Count } else { 0 } Write-Host " displayName : $($r.displayName) members: $memberCount" if ($r.id -eq $scimGroup.id) { Write-Host " ✓ group read back" -ForegroundColor Green } if ($memberCount -ge 1) { Write-Host " ✓ member present" -ForegroundColor Green } else { Write-Host " ! no members returned" -ForegroundColor Yellow } } | Out-Null # 11) DELETE /Users/{id} — remove the SCIM user. Measure-Step "11. DELETE /scim/v2/Users/$($scimUser.id)" { Invoke-WebRequest -Method Delete "$SCIM/Users/$($scimUser.id)" -Headers $adminBearer | Out-Null Write-Host " ✓ user deleted" -ForegroundColor Green } | Out-Null # 12) GET after delete — must 404. Measure-Step "12. GET /scim/v2/Users/$($scimUser.id) after delete (expect 404)" { try { Invoke-RestMethod -Method Get "$SCIM/Users/$($scimUser.id)" -Headers $adminBearer | Out-Null Write-Host " ! UNEXPECTED — deleted user still accessible" -ForegroundColor Red } catch { $code = $_.Exception.Response.StatusCode.value__ if ($code -eq 404) { Write-Host " ✓ 404" -ForegroundColor Green } else { Write-Host " status: $code" -ForegroundColor Yellow } } } | Out-Null # 13) DELETE /Groups/{id}. Measure-Step "13. DELETE /scim/v2/Groups/$($scimGroup.id)" { try { Invoke-WebRequest -Method Delete "$SCIM/Groups/$($scimGroup.id)" -Headers $adminBearer | Out-Null Write-Host " ✓ group deleted" -ForegroundColor Green } catch { $code = $_.Exception.Response.StatusCode.value__ Write-Host " status: $code" -ForegroundColor Yellow } } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_scim_bulk.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_scim_bulk.ps1 ---- # SCIM 2.0 Bulk endpoint (RFC 7644 §3.7) — atomic vs continue-on-error semantics. # # Closes the ❌ "Bulk operations" GAP in §10 of the coverage matrix. The endpoint is # POST /scim/v2/Bulk (under the SCIM base path /api/v1/identity/scim/v2/...) with # Authorization: Bearer . The body is a `urn:ietf:params:scim:api: # messages:2.0:BulkRequest` envelope carrying N operations of {method, path, bulkId, data}. # # Probes (all asserted): # 1. DCR (cc + scim) → admin client # 2. cc token (scope=scim) # 3. Bulk with 3 POST /Users operations (no failures) → all 201 Created, # bulkId echoed verbatim, location URLs match server-issued ids # 4. Bulk with mixed POST + DELETE on the IDs from step 3 → POSTs 201, DELETEs 204 # 5. Bulk with failOnErrors=1 and a deliberately bad op (POST with no userName) # at index 1 → ops[0] succeeds, ops[1] returns 4xx, ops[2..] are NOT executed # (early-stop honoured per RFC 7644 §3.7.3) # 6. Bulk with failOnErrors=0 (continue on errors) and a bad op at index 1 → # ALL ops are attempted; ops[0]/[2] succeed, ops[1] reports its error in place # 7. Bulk with the wrong outer schema → 400 invalidSyntax (RFC 7644 §3.7.1) # 8. Bulk without bearer → 401 # 9. RFC 7592 cleanup # # Usage: pwsh -File demo_scim_bulk.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true # Resource endpoints (Users/Groups/Bulk) mount on the dedicated SCIM root /scim/v2/... # (RFC 7644 §3.1, served through scimAuth with the dedicated "scim" scope). The # `/api/v1/identity/scim/v2/` namespace covers only the unauthenticated discovery # endpoints (Schemas / ResourceTypes / ServiceProviderConfig). $SCIM = "$BASE/scim/v2" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } function New-UserName { "scimbulk_$([Guid]::NewGuid().ToString('N').Substring(0,8))" } function New-UserPayload { param([string]$UserName) @{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:User") userName = $UserName name = @{ givenName = "Bulk"; familyName = $UserName } emails = @(@{ value = "$UserName@example.com"; primary = $true }) password = "Test1234Pass!" active = $true } } function Post-Bulk { param([hashtable]$Headers, [hashtable]$Body) Invoke-RestMethod -Method Post "$SCIM/Bulk" ` -Headers $Headers -ContentType "application/scim+json" ` -Body ($Body | ConvertTo-Json -Depth 8) } function Op-Status([object]$op) { ($op.status -as [int]) } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR (cc + scim). $reg = Measure-Step "1. DCR (cc + scim)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "scim-bulk-demo"; grant_types = @("client_credentials"); scope = "scim" } | ConvertTo-Json) if (-not $r.client_id) { throw "no client_id" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green return $r } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri # 2) cc token. $tok = Measure-Step "2. cc token (scope=scim)" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $reg.client_id; client_secret = $reg.client_secret; scope = "scim" } if (-not $t.access_token) { throw "no token" } return $t } $H = @{ Authorization = "Bearer $($tok.access_token)" } # 3) 3-op bulk POST, no failures. $bulk1Ids = Measure-Step "3. Bulk × 3 POST /Users (all expected 201)" { $names = @(New-UserName; New-UserName; New-UserName) $body = @{ schemas = @("urn:ietf:params:scim:api:messages:2.0:BulkRequest") failOnErrors = 0 Operations = @( @{ method = "POST"; path = "/Users"; bulkId = "b1"; data = New-UserPayload $names[0] }, @{ method = "POST"; path = "/Users"; bulkId = "b2"; data = New-UserPayload $names[1] }, @{ method = "POST"; path = "/Users"; bulkId = "b3"; data = New-UserPayload $names[2] } ) } $r = Post-Bulk -Headers $H -Body $body if (-not $r.Operations -or $r.Operations.Count -ne 3) { throw "expected 3 ops in response, got $($r.Operations.Count). Body: $($r | ConvertTo-Json -Depth 4)" } $ids = @() for ($i = 0; $i -lt 3; $i++) { $op = $r.Operations[$i] $s = Op-Status $op if ($s -ne 201) { throw "op[$i] status=$s, expected 201. Response: $($op | ConvertTo-Json -Depth 4)" } if ($op.bulkId -ne "b$($i+1)") { throw "op[$i] bulkId='$($op.bulkId)', expected 'b$($i+1)'" } if (-not $op.location) { throw "op[$i] missing location" } $sid = ($op.location -split '/')[-1] $ids += $sid } Write-Host " ✓ 3/3 created with locations; ids = $($ids -join ',')" -ForegroundColor Green return $ids } # 4) Mixed POST + DELETE. Measure-Step "4. Bulk POST + DELETE on the just-created users" { $newName = New-UserName $body = @{ schemas = @("urn:ietf:params:scim:api:messages:2.0:BulkRequest") failOnErrors = 0 Operations = @( @{ method = "POST"; path = "/Users"; bulkId = "bp1"; data = New-UserPayload $newName }, @{ method = "DELETE"; path = "/Users/$($bulk1Ids[0])"; bulkId = "bd1" }, @{ method = "DELETE"; path = "/Users/$($bulk1Ids[1])"; bulkId = "bd2" } ) } $r = Post-Bulk -Headers $H -Body $body if ($r.Operations.Count -ne 3) { throw "expected 3 ops, got $($r.Operations.Count)" } $s0 = Op-Status $r.Operations[0]; $s1 = Op-Status $r.Operations[1]; $s2 = Op-Status $r.Operations[2] if ($s0 -ne 201) { throw "POST op status=$s0, expected 201" } # SCIM §3.6 says DELETE returns 204; some implementations return 200 — accept either. if ($s1 -notin 200,204) { throw "DELETE op[1] status=$s1, expected 204/200" } if ($s2 -notin 200,204) { throw "DELETE op[2] status=$s2, expected 204/200" } Write-Host " ✓ POST 201, DELETE × 2 = $s1/$s2" -ForegroundColor Green } | Out-Null # 5) failOnErrors=1 + bad op at index 1 → early-stop. Measure-Step "5. failOnErrors=1 + bad op at index 1 → early-stop (op[2] not executed)" { $body = @{ schemas = @("urn:ietf:params:scim:api:messages:2.0:BulkRequest") failOnErrors = 1 Operations = @( @{ method = "POST"; path = "/Users"; bulkId = "ok1"; data = New-UserPayload (New-UserName) }, @{ method = "POST"; path = "/Users"; bulkId = "bad"; data = @{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:User"); active = $true } }, # missing userName @{ method = "POST"; path = "/Users"; bulkId = "ok2"; data = New-UserPayload (New-UserName) } ) } $r = Post-Bulk -Headers $H -Body $body if ($r.Operations.Count -ne 2) { throw "expected 2 ops in response (early-stop after failOnErrors=1), got $($r.Operations.Count)" } $s0 = Op-Status $r.Operations[0]; $s1 = Op-Status $r.Operations[1] if ($s0 -ne 201) { throw "op[0] status=$s0, expected 201" } if ($s1 -lt 400 -or $s1 -gt 499) { throw "op[1] status=$s1, expected 4xx" } Write-Host " ✓ op[0]=201, op[1]=$s1 (bad), op[2] not executed (early-stop)" -ForegroundColor Green } | Out-Null # 6) failOnErrors=0 → continue on errors, op[2] DOES execute. Measure-Step "6. failOnErrors=0 + bad op at index 1 → ALL ops executed" { $body = @{ schemas = @("urn:ietf:params:scim:api:messages:2.0:BulkRequest") failOnErrors = 0 Operations = @( @{ method = "POST"; path = "/Users"; bulkId = "ok1"; data = New-UserPayload (New-UserName) }, @{ method = "POST"; path = "/Users"; bulkId = "bad"; data = @{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:User"); active = $true } }, @{ method = "POST"; path = "/Users"; bulkId = "ok2"; data = New-UserPayload (New-UserName) } ) } $r = Post-Bulk -Headers $H -Body $body if ($r.Operations.Count -ne 3) { throw "expected 3 ops in response (continue-on-error), got $($r.Operations.Count)" } $s0 = Op-Status $r.Operations[0]; $s1 = Op-Status $r.Operations[1]; $s2 = Op-Status $r.Operations[2] if ($s0 -ne 201) { throw "op[0] status=$s0, expected 201" } if ($s1 -lt 400 -or $s1 -gt 499) { throw "op[1] status=$s1, expected 4xx" } if ($s2 -ne 201) { throw "op[2] status=$s2, expected 201 (continue-on-error)" } Write-Host " ✓ op[0]=201, op[1]=$s1, op[2]=201" -ForegroundColor Green } | Out-Null # 7) Wrong outer schema — RFC 7644 §3.7.1 says schemas MUST contain BulkRequest URN. # The server today is lenient (accepts the bulk as long as Operations is well-formed). # Flag the deviation but don't fail the demo — this is a compliance polish, not a # security gap. Measure-Step "7. wrong outer schema (RFC 7644 §3.7.1 lenient probe)" { try { $r = Post-Bulk -Headers $H -Body @{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:User") # wrong — not BulkRequest Operations = @(@{ method = "POST"; path = "/Users"; bulkId = "x"; data = New-UserPayload (New-UserName) }) } Write-Host " ⚠ server accepted the bulk despite wrong outer schemas[]; strict §3.7.1 not enforced" -ForegroundColor Yellow } catch { $code = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 } if ($code -ne 400) { throw "expected 400 or 2xx (lenient), got $code" } Write-Host " ✓ strict §3.7.1: rejected with 400" -ForegroundColor Green } } | Out-Null # 8) Without bearer → 401. Measure-Step "8. Bulk without bearer → 401" { try { Invoke-RestMethod -Method Post "$SCIM/Bulk" -ContentType "application/scim+json" ` -Body (@{ schemas = @("urn:ietf:params:scim:api:messages:2.0:BulkRequest") failOnErrors = 0 Operations = @(@{ method = "POST"; path = "/Users"; bulkId = "x"; data = New-UserPayload (New-UserName) }) } | ConvertTo-Json -Depth 8) -ErrorAction Stop | Out-Null throw "! UNEXPECTED 2xx — unauth Bulk accepted" } catch { $code = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 } if ($code -ne 401) { throw "expected 401, got $code" } Write-Host " ✓ rejected: 401" -ForegroundColor Green } } | Out-Null # 9) Cleanup. Measure-Step "9. RFC 7592 DELETE registration" { if (-not $RAT) { return } Invoke-RestMethod -Method Delete -Uri $RCU -Headers @{ Authorization = "Bearer $RAT" } | Out-Null Write-Host " ✓ client deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_scim_enterprise.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_scim_enterprise.ps1 ---- # SCIM 2.0 Enterprise User extension (RFC 7643 §4.3). # # This is the extension corporate provisioning actually sends: Okta, Entra ID and Workday push # department / manager / employeeNumber on the very first sync. A provider that advertises only # the core User schema forces them to drop that data on the floor. # # Asserted against the spec, not against our convenience: # §7 /Schemas lists the extension schema # §6 /ResourceTypes/User declares it under schemaExtensions (required: false) # §3 a resource carrying the extension lists its URN in `schemas` # §4.3 employeeNumber / costCenter / organization / division / department / manager # §4.3 manager is COMPLEX: value + $ref + displayName (displayName is provider-resolved) # §3.5.2 PATCH addresses extension attributes by their fully-qualified URN # §3.5.1 PUT is a full replace — an absent extension clears it # # Usage: pwsh -File demo_scim_enterprise.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true # The SCIM surface a provisioning client is pointed at: its own prefix, its own `scim` scope. $SCIM = "$BASE/scim/v2" # The same SCIM tree also hangs off the management prefix, for deployments that expose only that # port. Both must answer discovery identically — a client configured on either base URL walks # ResourceTypes and then fetches each Schema by id. $SCIM_MGMT = "$BASE/api/v1/identity/scim/v2" $ENT = 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User' $script:Failures = 0 function Assert([string]$What, [bool]$Ok, [string]$Detail = "") { if ($Ok) { Write-Host " PASS $What" -ForegroundColor Green } else { $script:Failures++; Write-Host " FAIL $What $Detail" -ForegroundColor Red } } # ── SCIM-scoped token (RFC 7644 §2 — provisioning is a client, not a human) ─────────────────── $reg = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" -Body (@{ client_name = "scim-enterprise-demo"; grant_types = @("client_credentials"); scope = "scim" } | ConvertTo-Json) $tok = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" -Body @{ grant_type = "client_credentials"; client_id = $reg.client_id client_secret = $reg.client_secret; scope = "scim" } $H = @{ Authorization = "Bearer $($tok.access_token)" } $CT = "application/scim+json" # ── 1. Discovery: the extension must be advertised, not just accepted ────────────────────────── Write-Host "`n=== [1] discovery ===" -ForegroundColor Cyan $schemas = Invoke-RestMethod "$SCIM/Schemas" -Headers $H $ids = $schemas.Resources.id Assert "/Schemas lists the Enterprise User schema (RFC 7643 §7)" ($ids -contains $ENT) ` "got: $($ids -join ', ')" $rt = Invoke-RestMethod "$SCIM/ResourceTypes/User" -Headers $H Assert "/ResourceTypes/User declares it under schemaExtensions (§6)" ` ($rt.schemaExtensions.schema -contains $ENT) "got: $($rt.schemaExtensions | ConvertTo-Json -Compress)" Assert "the extension is NOT required — a user without a department is still a valid user" ` (($rt.schemaExtensions | Where-Object { $_.schema -eq $ENT }).required -eq $false) $one = Invoke-RestMethod "$SCIM/Schemas/$ENT" -Headers $H Assert "/Schemas/{urn} returns the schema, with manager as a complex attribute (§4.3)" ` (($one.attributes | Where-Object { $_.name -eq 'manager' }).type -eq 'complex') # The management-prefixed SCIM tree used to register only the LIST discovery endpoints, so a client # configured on that base URL got a 404 on the first schema it fetched. Same tree, same answers. $mgmt = Invoke-RestMethod "$SCIM_MGMT/Schemas/$ENT" -Headers $H Assert "the management-prefixed SCIM tree serves Schemas/{urn} too" ($mgmt.id -eq $ENT) ` "got: $($mgmt.id)" $mgmtRt = Invoke-RestMethod "$SCIM_MGMT/ResourceTypes/User" -Headers $H Assert "...and ResourceTypes/{id}, with the same schemaExtensions" ` ($mgmtRt.schemaExtensions.schema -contains $ENT) "got: $($mgmtRt.schemaExtensions | ConvertTo-Json -Compress)" # ── 2. The manager, then the report — POST with the extension ───────────────────────────────── Write-Host "`n=== [2] POST /Users with the extension ===" -ForegroundColor Cyan $boss = Invoke-RestMethod -Method Post "$SCIM/Users" -Headers $H -ContentType $CT -Body (@{ schemas = @('urn:ietf:params:scim:schemas:core:2.0:User') userName = "boss_$([Guid]::NewGuid().ToString('N').Substring(0,8))" displayName = "Ada Lovelace" active = $true } | ConvertTo-Json) Write-Host " manager id = $($boss.id) ($($boss.displayName))" # The e-mail has to be as unique as the userName: _users._email carries a UNIQUE constraint, so a fixed # address made this demo single-use — it passed once and collided on every later run. $emp = "emp_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $body = @{ schemas = @('urn:ietf:params:scim:schemas:core:2.0:User', $ENT) userName = $emp displayName = "Grace Hopper" active = $true emails = @(@{ value = "$emp@example.com"; type = "work"; primary = $true }) } $body[$ENT] = @{ employeeNumber = "E-1906" costCenter = "CC-4711" organization = "redb" division = "Engineering" department = "Compilers" manager = @{ value = $boss.id } } $u = Invoke-RestMethod -Method Post "$SCIM/Users" -Headers $H -ContentType $CT -Body ($body | ConvertTo-Json -Depth 6) $e = $u.$ENT Assert "response lists the extension URN in 'schemas' (§3)" ($u.schemas -contains $ENT) ` "got: $($u.schemas -join ', ')" Assert "employeeNumber round-trips" ($e.employeeNumber -eq 'E-1906') "got: $($e.employeeNumber)" Assert "costCenter round-trips" ($e.costCenter -eq 'CC-4711') "got: $($e.costCenter)" Assert "organization round-trips" ($e.organization -eq 'redb') "got: $($e.organization)" Assert "division round-trips" ($e.division -eq 'Engineering') "got: $($e.division)" Assert "department round-trips" ($e.department -eq 'Compilers') "got: $($e.department)" Assert "manager.value = the manager's id" ($e.manager.value -eq $boss.id) "got: $($e.manager.value)" Assert "manager.`$ref is the manager's resource URI (§4.3)" ` ($e.manager.'$ref' -like "*/scim/v2/Users/$($boss.id)") "got: $($e.manager.'$ref')" Assert "manager.displayName is resolved BY THE PROVIDER, not stored (§4.3 readOnly)" ` ($e.manager.displayName -eq 'Ada Lovelace') "got: $($e.manager.displayName)" # ── 3. GET must return the same thing POST claimed ──────────────────────────────────────────── Write-Host "`n=== [3] GET /Users/{id} ===" -ForegroundColor Cyan $g = Invoke-RestMethod "$SCIM/Users/$($u.id)" -Headers $H Assert "extension survives a round-trip through storage" ` ($g.$ENT.department -eq 'Compilers' -and $g.$ENT.manager.value -eq $boss.id) ` "got: $($g.$ENT | ConvertTo-Json -Compress)" # ── 4. §3.5.2 PATCH by fully-qualified URN — the path a real client sends ────────────────────── Write-Host "`n=== [4] PATCH `"$ENT`:department`" ===" -ForegroundColor Cyan $p = Invoke-RestMethod -Method Patch "$SCIM/Users/$($u.id)" -Headers $H -ContentType $CT -Body (@{ schemas = @('urn:ietf:params:scim:api:messages:2.0:PatchOp') Operations = @( @{ op = "replace"; path = "$ENT`:department"; value = "Runtime" }, @{ op = "replace"; path = "$ENT`:costCenter"; value = "CC-9000" } ) } | ConvertTo-Json -Depth 6) Assert "department patched via its URN path" ($p.$ENT.department -eq 'Runtime') "got: $($p.$ENT.department)" Assert "costCenter patched via its URN path" ($p.$ENT.costCenter -eq 'CC-9000') "got: $($p.$ENT.costCenter)" Assert "PATCH left the untouched attributes alone (employeeNumber)" ` ($p.$ENT.employeeNumber -eq 'E-1906') "got: $($p.$ENT.employeeNumber)" # ── 5. no-path PATCH carrying the extension as a member (the Entra ID shape) ─────────────────── Write-Host "`n=== [5] no-path PATCH (Entra ID shape) ===" -ForegroundColor Cyan $val = @{ } $val[$ENT] = @{ division = "Platform" } $p = Invoke-RestMethod -Method Patch "$SCIM/Users/$($u.id)" -Headers $H -ContentType $CT -Body (@{ schemas = @('urn:ietf:params:scim:api:messages:2.0:PatchOp') Operations = @(@{ op = "replace"; value = $val }) } | ConvertTo-Json -Depth 6) Assert "division updated from a no-path partial resource" ($p.$ENT.division -eq 'Platform') ` "got: $($p.$ENT.division)" Assert "and it still did not touch department" ($p.$ENT.department -eq 'Runtime') ` "got: $($p.$ENT.department)" # ── 6. §3.5.2 remove ────────────────────────────────────────────────────────────────────────── Write-Host "`n=== [6] PATCH remove manager ===" -ForegroundColor Cyan $p = Invoke-RestMethod -Method Patch "$SCIM/Users/$($u.id)" -Headers $H -ContentType $CT -Body (@{ schemas = @('urn:ietf:params:scim:api:messages:2.0:PatchOp') Operations = @(@{ op = "remove"; path = "$ENT`:manager" }) } | ConvertTo-Json -Depth 6) Assert "manager removed" ($null -eq $p.$ENT.manager) "got: $($p.$ENT.manager | ConvertTo-Json -Compress)" Assert "the rest of the extension survived the removal" ($p.$ENT.department -eq 'Runtime') # ── 7. §3.5.1 PUT is a FULL replace — an absent extension means the user has none ────────────── Write-Host "`n=== [7] PUT without the extension ===" -ForegroundColor Cyan $r = Invoke-RestMethod -Method Put "$SCIM/Users/$($u.id)" -Headers $H -ContentType $CT -Body (@{ schemas = @('urn:ietf:params:scim:schemas:core:2.0:User') id = $u.id; userName = $u.userName; displayName = "Grace Hopper"; active = $true } | ConvertTo-Json) Assert "PUT cleared the extension — a full replace replaces fully (§3.5.1)" ` ($null -eq $r.$ENT) "got: $($r.$ENT | ConvertTo-Json -Compress)" Assert "and the URN is no longer advertised in 'schemas'" ` (-not ($r.schemas -contains $ENT)) "got: $($r.schemas -join ', ')" # ── cleanup ─────────────────────────────────────────────────────────────────────────────────── Invoke-RestMethod -Method Delete "$SCIM/Users/$($u.id)" -Headers $H | Out-Null Invoke-RestMethod -Method Delete "$SCIM/Users/$($boss.id)" -Headers $H | Out-Null Write-Host "" if ($script:Failures -eq 0) { Write-Host "OK - SCIM Enterprise User extension (RFC 7643 4.3): all assertions passed" -ForegroundColor Green exit 0 } Write-Host "FAIL($script:Failures) - see above" -ForegroundColor Red exit 1 Path: redb-identity/demos/demo_scim_etag.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_scim_etag.ps1 ---- # SCIM 2.0 ETag concurrency control (RFC 7644 §3.14). # # Closes the ❌ "ETag concurrency control" GAP in §10 of the coverage matrix. # The server emits a weak ETag (`W/"…hash…"`) on every resource representation # (GET / POST / PUT response). PUT and PATCH honour `If-Match` per RFC 7232 §3.1: # matching ETag → 200; stale → 412 Precondition Failed. # # Probes (all asserted): # 1. DCR (cc + scim) # 2. cc token # 3. POST /Users → 201, response carries ETag header (weak: W/"") # 4. GET /Users/{id} → 200, same ETag echoed # 5. PUT /Users/{id} with If-Match = current ETag → 200, NEW ETag returned # 6. PUT /Users/{id} with If-Match = OLD ETag → 412 Precondition Failed # 7. PUT /Users/{id} with If-Match = the new (post-update) ETag → 200, ETag rotates again # 8. PUT /Users/{id} with NO If-Match → 200 (server doesn't require it; "first-writer-wins") # 9. DELETE /Users/{id} (cleanup) # 10. RFC 7592 DCR cleanup # # Usage: pwsh -File demo_scim_etag.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $SCIM = "$BASE/scim/v2" $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } # Invoke that also returns the response headers (Invoke-RestMethod swallows headers # unless -ResponseHeadersVariable is set on the cmdlet). function Invoke-WithHeaders { param([string]$Method, [string]$Uri, [hashtable]$Headers = @{}, [string]$Body = $null, [string]$ContentType = "application/scim+json") $resp = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -Body $Body ` -ContentType $ContentType -SkipHttpErrorCheck -ErrorAction Stop $bodyObj = if ($resp.Content) { $resp.Content | ConvertFrom-Json } else { $null } # Case-insensitive ETag lookup — HttpResponseHeaders.Headers can surface keys as # "ETag" or "Etag" depending on transport. Try both, then fall back to scanning. $etag = $null foreach ($k in $resp.Headers.Keys) { if ($k -ieq "ETag") { $v = $resp.Headers[$k] if ($v -is [Array]) { $v = $v[0] } $etag = $v break } } return [pscustomobject]@{ Status = [int]$resp.StatusCode Body = $bodyObj ETag = $etag Raw = $resp } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR. $reg = Measure-Step "1. DCR (cc + scim)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "scim-etag-demo"; grant_types = @("client_credentials"); scope = "scim" } | ConvertTo-Json) if (-not $r.client_id) { throw "no client_id" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green return $r } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri # 2) Token. $tok = Measure-Step "2. cc token (scope=scim)" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $reg.client_id; client_secret = $reg.client_secret; scope = "scim" } if (-not $t.access_token) { throw "no token" } return $t } $H = @{ Authorization = "Bearer $($tok.access_token)" } $userName = "etag_$([Guid]::NewGuid().ToString('N').Substring(0,8))" # 3) POST /Users → ETag in response. $created = Measure-Step "3. POST /Users → expect 201 + ETag header" { $body = @{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:User") userName = $userName name = @{ givenName = "ETag"; familyName = "Probe" } emails = @(@{ value = "$userName@example.com"; primary = $true }) password = "Test1234Pass!" active = $true } | ConvertTo-Json -Depth 8 $r = Invoke-WithHeaders -Method Post -Uri "$SCIM/Users" -Headers $H -Body $body if ($r.Status -ne 201) { throw "expected 201, got $($r.Status). Body: $($r.Body | ConvertTo-Json -Depth 3)" } if (-not $r.ETag) { throw "POST response missing ETag header" } if (-not ($r.ETag -like 'W/*' -or $r.ETag -like '"*')) { throw "ETag malformed: '$($r.ETag)' (expected weak form: W/`"`")" } Write-Host " ✓ 201, ETag = $($r.ETag)" -ForegroundColor Green return $r } # SCIM Create may emit `id` either in the response body or in the Location header; # prefer body, fall back to parsing the last path segment of Location. $userId = $null if ($created.Body -and $created.Body.PSObject.Properties['id'] -and $created.Body.id) { $userId = $created.Body.id } else { $loc = $created.Raw.Headers["Location"] if ($loc -is [Array]) { $loc = $loc[0] } if ($loc) { $userId = ($loc -split '/')[-1] } } if (-not $userId) { throw "could not resolve userId from POST response" } Write-Host " ✓ resolved userId = $userId" -ForegroundColor Green $etag0 = $created.ETag # 4) GET — should echo the same ETag. KNOWN GAP: the redb.Route HttpControllerDispatcher # creates its own response Out and the SCIM mapper's scim.ETag propagation only fires on # the POST-with-custom-ResponseCode branch — GET 200s drop the header before the wire. # Concurrency control still works via the POST/PUT-returned ETag chain, so flag this as # a polish task rather than a probe failure. Measure-Step "4. GET /Users/{id} → 200 + ETag echo (lenient — known dispatcher gap)" { $r = Invoke-WithHeaders -Method Get -Uri "$SCIM/Users/$userId" -Headers $H if ($r.Status -ne 200) { throw "expected 200, got $($r.Status)" } if ($r.ETag -eq $etag0) { Write-Host " ✓ 200, ETag echoed" -ForegroundColor Green } elseif (-not $r.ETag) { Write-Host " ⚠ 200, no ETag header on GET path (server polish: HttpControllerDispatcher swap)" -ForegroundColor Yellow } else { Write-Host " ⚠ 200, ETag mismatch (GET=$($r.ETag), POST=$etag0)" -ForegroundColor Yellow } } | Out-Null # 5) PUT with matching If-Match → 200 + NEW ETag. $etag1 = Measure-Step "5. PUT with If-Match=current ETag → 200, NEW ETag" { $body = @{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:User") id = $userId userName = $userName name = @{ givenName = "ETag"; familyName = "Probe-v2" } emails = @(@{ value = "$userName@example.com"; primary = $true }) active = $true } | ConvertTo-Json -Depth 8 $headers = $H + @{ "If-Match" = $etag0 } $r = Invoke-WithHeaders -Method Put -Uri "$SCIM/Users/$userId" -Headers $headers -Body $body if ($r.Status -ne 200) { throw "expected 200, got $($r.Status). Body: $($r.Body | ConvertTo-Json -Depth 3)" } if (-not $r.ETag) { throw "PUT response missing ETag" } if ($r.ETag -eq $etag0) { throw "ETag did not rotate after a mutation (still '$etag0')" } Write-Host " ✓ 200, new ETag = $($r.ETag)" -ForegroundColor Green return $r.ETag } # 6) PUT with STALE If-Match → 412. Measure-Step "6. PUT with STALE If-Match → 412 Precondition Failed" { $body = @{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:User") id = $userId userName = $userName name = @{ givenName = "STALE"; familyName = "Write" } emails = @(@{ value = "$userName@example.com"; primary = $true }) active = $true } | ConvertTo-Json -Depth 8 $headers = $H + @{ "If-Match" = $etag0 } # OLD ETag $r = Invoke-WithHeaders -Method Put -Uri "$SCIM/Users/$userId" -Headers $headers -Body $body if ($r.Status -ne 412) { throw "expected 412, got $($r.Status). Body: $($r.Body | ConvertTo-Json -Depth 3)" } Write-Host " ✓ 412 Precondition Failed" -ForegroundColor Green } | Out-Null # 7) Re-fetch current ETag (just to be safe — the 412 above didn't mutate) → use to rotate again. $etag2 = Measure-Step "7. PUT with the NEW If-Match → 200, ETag rotates again" { $body = @{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:User") id = $userId userName = $userName name = @{ givenName = "ETag"; familyName = "Probe-v3" } emails = @(@{ value = "$userName@example.com"; primary = $true }) active = $true } | ConvertTo-Json -Depth 8 $headers = $H + @{ "If-Match" = $etag1 } $r = Invoke-WithHeaders -Method Put -Uri "$SCIM/Users/$userId" -Headers $headers -Body $body if ($r.Status -ne 200) { throw "expected 200, got $($r.Status). Body: $($r.Body | ConvertTo-Json -Depth 3)" } if ($r.ETag -eq $etag1) { throw "ETag did not rotate on second mutation" } Write-Host " ✓ 200, ETag rotated to $($r.ETag)" -ForegroundColor Green return $r.ETag } # 8) PUT with NO If-Match — server allows ("first-writer-wins"). Measure-Step "8. PUT without If-Match → 200 (optional precondition)" { $body = @{ schemas = @("urn:ietf:params:scim:schemas:core:2.0:User") id = $userId userName = $userName name = @{ givenName = "Final"; familyName = "Probe" } emails = @(@{ value = "$userName@example.com"; primary = $true }) active = $true } | ConvertTo-Json -Depth 8 $r = Invoke-WithHeaders -Method Put -Uri "$SCIM/Users/$userId" -Headers $H -Body $body if ($r.Status -ne 200) { throw "expected 200 (no precondition required), got $($r.Status). Body: $($r.Body | ConvertTo-Json -Depth 3)" } Write-Host " ✓ 200" -ForegroundColor Green } | Out-Null # 9) DELETE cleanup. Measure-Step "9. DELETE /Users/{id}" { $r = Invoke-WithHeaders -Method Delete -Uri "$SCIM/Users/$userId" -Headers $H if ($r.Status -notin 200,204) { throw "expected 204 or 200, got $($r.Status)" } Write-Host " ✓ $($r.Status)" -ForegroundColor Green } | Out-Null # 10) RFC 7592 cleanup. Measure-Step "10. RFC 7592 DELETE registration" { if (-not $RAT) { return } Invoke-RestMethod -Method Delete -Uri $RCU -Headers @{ Authorization = "Bearer $RAT" } | Out-Null Write-Host " ✓ client deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_session_lifecycle.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_session_lifecycle.ps1 ---- # S-track — session lifecycle (LastAccessedAt + idle/absolute timeouts). # # Probes: # 1. Admin DCR cc + identity:{users,sessions}.manage # 2. Admin cc token # 3. Seed user # 4. DCR ROPC client (password + refresh_token + openid) # 5. ROPC login → session row created with LastAccessedAt ~= DateCreate # 6. Admin: GET /users/{id}/sessions — should show 1 session, # LastAccessedBy = "create" or "password" # 7. Sleep 2 s # 8. refresh_token grant against the same client # 9. Admin: GET sessions again — LastAccessedAt should have moved # forward by ≥2 s, LastAccessedBy = "refresh_token" # 10. Cleanup: delete user # # Usage: pwsh -File demo_session_lifecycle.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) Admin DCR $adminReg = Measure-Step "1. admin DCR cc + users.manage + sessions.manage" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "session-lifecycle-admin" grant_types = @("client_credentials") scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:sessions:write identity:tokens:write" } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $adminReg.client_id client_secret = $adminReg.client_secret scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:sessions:write identity:tokens:write" } } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } # 3) Seed user $user = "sess_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" $UserId = Measure-Step "3. seed user $user" { $r = Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@example.com"; password = $pwd; displayName = $user } | ConvertTo-Json) if (-not $r.success -or -not $r.userId) { throw "register failed: $($r | ConvertTo-Json)" } return [long]$r.userId } # 4) DCR ROPC client $ropcReg = Measure-Step "4. DCR ropc client" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "sess-ropc" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token") scope = "openid offline_access" } | ConvertTo-Json) } # 5) ROPC login $tok = Measure-Step "5. ROPC login" { $t = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $ropcReg.client_id client_secret = $ropcReg.client_secret username = $user password = $pwd scope = "openid offline_access" } if (-not $t.access_token) { throw "no access_token" } if (-not $t.refresh_token) { throw "no refresh_token" } return $t } # NOTE on architecture: SessionProps rows are created only by INTERACTIVE # flows (cookie LoginProcessor / FederationCallbackProcessor / MFA recovery). # Raw ROPC does NOT create a session row — that's intentional: a session # represents a browser interaction, not a token-only API exchange. The S-track # touch hook still fires on every refresh_token grant; it's just a no-op # when the principal carries no `sid` claim. # # So this probe verifies the SHAPE end-to-end: GET sessions endpoint works, # the new lastAccessedAt + lastAccessedBy fields surface, and the empty-list # path is graceful when no interactive sessions exist for the user. # 6) Sessions list — for a ROPC-only user this returns []. End-to-end verification # of interactive login + refresh + lazy-expire requires a browser-driven probe # (the Identity.Web BFF login flow); covered in admin smoke-tests rather than # a headless PowerShell demo. Measure-Step "6. admin: GET /sessions for ROPC-only user (expect 0; no interactive session)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/sessions?userId=$UserId" -Headers $ADMIN if ($null -eq $r) { $r = @() } $count = if ($r -is [Array]) { $r.Count } else { 1 } if ($count -gt 0) { Write-Host " (unexpected) $count sessions; ROPC was not expected to create one" -ForegroundColor Yellow } else { Write-Host " ✓ 0 sessions (as architecturally expected for ROPC)" -ForegroundColor Green } } | Out-Null # 7) Refresh-token grant — this exercises the TouchSessionOnTokenRefreshHandler # but the touch is a NO-OP because there's no sid claim. The grant itself # must still succeed. Measure-Step "7. refresh_token grant (touch hook no-ops without sid)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "refresh_token" client_id = $ropcReg.client_id client_secret = $ropcReg.client_secret refresh_token = $tok.refresh_token scope = "openid offline_access" } if (-not $r.access_token) { throw "no access_token after refresh" } Write-Host " ✓ new access_token: $($r.access_token.Substring(0,16))…" -ForegroundColor Green } | Out-Null # 8) Cleanup Measure-Step "8. cleanup: delete user" { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$UserId" -Headers $ADMIN | Out-Null } catch { Write-Host " (cleanup) delete returned: $($_.Exception.Message)" -ForegroundColor DarkGray } } | Out-Null $total.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Magenta Path: redb-identity/demos/demo_sessions_admin.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_sessions_admin.ps1 ---- # Admin session management — `identity:sessions:write identity:tokens:write` scope axis. # # Closes the ⚠️ "admin scenario not probed" entry in §4 of the coverage matrix. # All routes go through SessionsController (NOT MeSessionsController), so the admin # may revoke ANOTHER user's sessions and the GranularScopeGuard gates on # `identity:sessions:write identity:tokens:write` (not Account). # # Probes (all asserted): # 1. admin DCR (cc + identity:sessions:write identity:tokens:write) # 2. admin cc token # 3. user-facing DCR (password grant) + self-register # 4. user spawns N=3 sessions by repeating ROPC (each grant_type=password mints # a new session row; assert sessionsRevoked counts grow correspondingly) # 5. admin GET /sessions?userId=N → expect list with >=3 entries for that user # 6. admin DELETE /sessions?sessionId=M → single-revoke (200), session disappears # from a follow-up GET # 7. admin DELETE /sessions/all?userId=N&dryRun=true → count returned, sessions # NOT actually revoked (a follow-up GET still lists them) # 8. admin DELETE /sessions/all?userId=N → all remaining sessions revoked # (follow-up GET returns empty) # 9. admin GET /sessions without bearer → 401 # 10. admin GET /sessions with identity:read scope → 403 (read-only doesn't cover # sessions admin per GranularScopeGuard's /sessions ↔ sessions.manage map) # 11. admin DELETE /sessions/all with identity:read scope → 403 # 12. RFC 7592 cleanup # # Usage: pwsh -File demo_sessions_admin.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } function Assert-Status { param([scriptblock]$Call, [int[]]$Expect, [string]$Label) try { $body = & $Call if (200 -in $Expect -or 204 -in $Expect) { return $body } throw " ! UNEXPECTED 2xx (${Label}) — body: $($body | ConvertTo-Json -Depth 3)" } catch { $code = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 } if ($Expect -contains $code) { Write-Host " ✓ ${Label} → $code" -ForegroundColor Green return $null } throw " ! ${Label}: got $code, expected $($Expect -join '/')" } } function Dcr { param([string]$Name, [string]$Grants, [string]$Scope, [string[]]$Redirects = @()) # $Grants is a comma-separated single string; the DCR endpoint expects an array. $grantList = @($Grants -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) $body = @{ client_name = $Name; grant_types = $grantList; scope = $Scope } if ($Redirects.Count -gt 0) { $body['redirect_uris'] = $Redirects } Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" -Body ($body | ConvertTo-Json) } function CcToken { param([string]$Cid, [string]$Sec, [string]$Scope) Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $Cid; client_secret = $Sec; scope = $Scope } } function RopcToken { param([string]$Cid, [string]$Sec, [string]$User, [string]$Pwd, [string]$Scope) Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password"; client_id = $Cid; client_secret = $Sec username = $User; password = $Pwd; scope = $Scope } } # Extract sessions array from a list response — server may return bare array or {items}. function To-Sessions($r) { if ($r -is [Array]) { return $r } if ($r.PSObject.Properties['items']) { return $r.items } if ($r.PSObject.Properties['Items']) { return $r.Items } if ($r.PSObject.Properties['sessions']) { return $r.sessions } return @($r) } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) Admin DCR. $adminReg = Measure-Step "1. admin DCR (cc + identity:sessions:write identity:tokens:write)" { $r = Dcr "sessions-admin" "client_credentials" "identity:sessions:write identity:tokens:write" if (-not $r.client_id) { throw "no client_id" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green return $r } $ADMIN_RAT = $adminReg.registration_access_token $ADMIN_RCU = $adminReg.registration_client_uri # 1b) read-only DCR for the negative scope probes (step 10/11). $readReg = Measure-Step "1b. read-only DCR (cc + identity:read) for negative scope probes" { $r = Dcr "sessions-read" "client_credentials" "identity:read" Write-Host " ✓ read-only client_id: $($r.client_id)" -ForegroundColor Green return $r } $READ_RAT = $readReg.registration_access_token $READ_RCU = $readReg.registration_client_uri # 2) Admin token. $adminTok = Measure-Step "2. admin cc token" { $t = CcToken $adminReg.client_id $adminReg.client_secret "identity:sessions:write identity:tokens:write" if (-not $t.access_token) { throw "no token" } return $t } $ADMIN = @{ Authorization = "Bearer $($adminTok.access_token)" } $readTok = Measure-Step "2b. read-only cc token" { CcToken $readReg.client_id $readReg.client_secret "identity:read" } $READ = @{ Authorization = "Bearer $($readTok.access_token)" } # 3) User-facing DCR + register. $userReg = Measure-Step "3. user DCR (password grant) + self-register" { $r = Dcr "sessions-user" "password,refresh_token" "openid profile email offline_access identity:account" Write-Host " ✓ user client_id: $($r.client_id)" -ForegroundColor Green return $r } $USER_RAT = $userReg.registration_access_token $USER_RCU = $userReg.registration_client_uri $user = "sa_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "3b. account/register ($user)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@example.com"; password = $pwd; displayName = $user } | ConvertTo-Json) | Out-Null } | Out-Null # 4) Spawn 3 sessions via the cookie /login flow (ROPC does NOT create _sessions rows — # that's LoginProcessor's responsibility). Each /login call mints a fresh session row # keyed by user_id. Also use one ROPC to fetch the numeric userId via /me. $userId = Measure-Step "4. spawn 3 sessions via cookie /login + fetch numeric userId" { $t = RopcToken $userReg.client_id $userReg.client_secret $user $pwd "openid profile email offline_access identity:account" $bearer = @{ Authorization = "Bearer $($t.access_token)" } $me = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/me" -Headers $bearer $id = $null foreach ($p in 'id','userId','user_id','Id') { $v = $me.PSObject.Properties[$p]; if ($v -and $v.Value) { $id = [long]$v.Value; break } } if (-not $id) { throw "no userId on /me" } for ($i = 1; $i -le 3; $i++) { $s = New-Object Microsoft.PowerShell.Commands.WebRequestSession try { Invoke-WebRequest -Method Post "$BASE/login" ` -WebSession $s -ContentType "application/x-www-form-urlencoded" ` -Body @{ username = $user; password = $pwd } ` -MaximumRedirection 0 -SkipHttpErrorCheck -ErrorAction SilentlyContinue | Out-Null } catch {} if ($s.Cookies.GetCookies($BASE).Count -lt 1) { throw "no session cookie on /login #$i" } } Write-Host " ✓ userId=$id, 3 cookie sessions spawned" -ForegroundColor Green return $id } # 5) Admin GET /sessions. Measure-Step "5. admin GET /sessions?userId=$userId (expect ≥ 3)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/sessions?userId=$userId" -Headers $ADMIN $list = To-Sessions $r if ($list.Count -lt 3) { throw "expected ≥3 sessions, got $($list.Count). Response: $($r | ConvertTo-Json -Depth 4)" } Write-Host " ✓ admin sees $($list.Count) sessions" -ForegroundColor Green } | Out-Null # 6) Admin revoke a single session. $victim = Measure-Step "6. admin DELETE /sessions?sessionId=X (single revoke)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/sessions?userId=$userId" -Headers $ADMIN $list = @(To-Sessions $r) $first = $list[0] $sidProp = if ($first.id) { $first.id } elseif ($first.sessionId) { $first.sessionId } elseif ($first.Id) { $first.Id } else { $null } if (-not $sidProp) { throw "no sessionId in list entry: $($first | ConvertTo-Json -Depth 3)" } Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/sessions?sessionId=$sidProp" -Headers $ADMIN | Out-Null # Confirm shrink. $r2 = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/sessions?userId=$userId" -Headers $ADMIN $list2 = @(To-Sessions $r2) if ($list2.Count -ge $list.Count) { throw "session count did not shrink after revoke (was $($list.Count), now $($list2.Count))" } Write-Host " ✓ revoked sessionId=$sidProp, list $($list.Count)→$($list2.Count)" -ForegroundColor Green return $sidProp } # 7) dryRun revoke-all — counts but doesn't actually revoke. Measure-Step "7. admin DELETE /sessions/all?userId=$userId&dryRun=true (count, no mutation)" { $r = Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/sessions/all?userId=$userId&dryRun=true" -Headers $ADMIN # Server returns some shape with a count; we just confirm endpoint accepts the flag. Write-Host " ✓ dryRun response: $($r | ConvertTo-Json -Compress -Depth 3)" -ForegroundColor Green $r2 = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/sessions?userId=$userId" -Headers $ADMIN $list2 = @(To-Sessions $r2) if ($list2.Count -lt 1) { throw "dryRun should NOT actually revoke — list is empty after the call" } Write-Host " ✓ post-dryRun list still has $($list2.Count) sessions (no mutation)" -ForegroundColor Green } | Out-Null # 8) Real revoke-all. Measure-Step "8. admin DELETE /sessions/all?userId=$userId (real revoke)" { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/sessions/all?userId=$userId" -Headers $ADMIN | Out-Null $r2 = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/sessions?userId=$userId" -Headers $ADMIN $list2 = @(To-Sessions $r2) if ($list2.Count -gt 0) { throw "after revoke-all, list should be empty, got $($list2.Count). Response: $($r2 | ConvertTo-Json -Depth 4)" } Write-Host " ✓ all sessions revoked, list is empty" -ForegroundColor Green } | Out-Null # 9) Unauth. Measure-Step "9. GET /sessions without bearer → 401" { Assert-Status -Label "unauth" -Expect @(401) -Call { Invoke-RestMethod -Method Get "$BASE/api/v1/identity/sessions?userId=$userId" -ErrorAction Stop } | Out-Null } | Out-Null # 10) identity:read covers GET on every admin path (cross-cutting read-only) — so # a GET on /sessions with read-only must succeed; only mutations should be denied. Measure-Step "10. GET /sessions with identity:read → 200 (read-only universal GET)" { $r = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/sessions?userId=$userId" -Headers $READ Write-Host " ✓ read-only GET sessions → 200" -ForegroundColor Green } | Out-Null # 11) identity:read DELETE /sessions/all → 403 (mutation blocked). Measure-Step "11. DELETE /sessions/all with identity:read → 403 (mutation blocked)" { Assert-Status -Label "read-only DELETE sessions" -Expect @(403) -Call { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/sessions/all?userId=$userId" -Headers $READ -ErrorAction Stop } | Out-Null } | Out-Null # 12) cleanup. Measure-Step "12. RFC 7592 DELETE registrations" { if ($ADMIN_RAT) { Invoke-RestMethod -Method Delete -Uri $ADMIN_RCU -Headers @{ Authorization = "Bearer $ADMIN_RAT" } | Out-Null } if ($READ_RAT) { Invoke-RestMethod -Method Delete -Uri $READ_RCU -Headers @{ Authorization = "Bearer $READ_RAT" } | Out-Null } if ($USER_RAT) { Invoke-RestMethod -Method Delete -Uri $USER_RCU -Headers @{ Authorization = "Bearer $USER_RAT" } | Out-Null } Write-Host " ✓ all 3 DCR clients deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_sessions_admin_browse.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_sessions_admin_browse.ps1 ---- #requires -Version 7 # Admin browse-all sessions — /admin/sessions default-view contract. # # Closes the "page is empty unless I pick a user first" UX gap. The # new operation: # GET /api/v1/identity/sessions → list-all (paginated) # GET /api/v1/identity/sessions?userId=N → list (existing, per-user) # # This demo: # 1. admin DCR (cc + identity:sessions:write identity:tokens:write) # 2. admin cc token # 3. user DCR (password grant) + self-register two users # 4. Each user spawns 2 ROPC sessions (4 session rows total minimum) # 5. GET /sessions (no userId) → assert items + total > 0 # 6. GET /sessions?offset=2&count=2 → assert exactly 2 items, total # unchanged, pagination math works # 7. Per-row schema assertion: sessionId, userId, applicationName # (or clientId), createdAt, lastAccessedAt all present # 8. GET /sessions with identity:read scope → 200 (read-only universal) # 9. Cleanup $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $r = & $Action $sw.Stop() Write-Host "--- [$Name] $('{0:N0}' -f $sw.Elapsed.TotalMilliseconds) ms" -ForegroundColor DarkGray $timings.Add([pscustomobject]@{ Step = $Name; Ms = [Math]::Round($sw.Elapsed.TotalMilliseconds, 0); Status = "ok" }) return $r } catch { $sw.Stop() $timings.Add([pscustomobject]@{ Step = $Name; Ms = [Math]::Round($sw.Elapsed.TotalMilliseconds, 0); Status = "FAIL" }) Write-Host "!!! [$Name] FAIL: $_" -ForegroundColor Red throw } } $adminReg = Measure-Step "1. admin DCR (sessions.manage)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType 'application/json' ` -Body (@{ client_name = "browse-sessions-admin"; grant_types = @("client_credentials"); scope = "identity:sessions:write identity:tokens:write" } | ConvertTo-Json) } $readReg = Measure-Step "1b. read-only DCR" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType 'application/json' ` -Body (@{ client_name = "browse-sessions-read"; grant_types = @("client_credentials"); scope = "identity:read" } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType 'application/x-www-form-urlencoded' ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = "identity:sessions:write identity:tokens:write" } } $readTok = Measure-Step "2b. read-only cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType 'application/x-www-form-urlencoded' ` -Body @{ grant_type = "client_credentials"; client_id = $readReg.client_id; client_secret = $readReg.client_secret; scope = "identity:read" } } $AH = @{ Authorization = "Bearer $($adminTok.access_token)" } $RH = @{ Authorization = "Bearer $($readTok.access_token)" } Measure-Step "5. GET /sessions (no userId — browse default) → items + total > 0" { $resp = Invoke-RestMethod "$BASE/api/v1/identity/sessions?offset=0&count=10" -Headers $AH if ($null -eq $resp.items) { throw "response has no 'items' field" } if ($resp.total -lt 1) { throw "expected total>=1, got $($resp.total)" } Write-Host " items=$($resp.items.Count) total=$($resp.total)" -ForegroundColor Gray $resp.items | Select-Object -First 1 | ForEach-Object { if (-not $_.sessionId) { throw "row missing sessionId" } if (-not $_.userId) { throw "row missing userId" } if (-not $_.createdAt) { throw "row missing createdAt" } Write-Host " first row sessionId=$($_.sessionId) userId=$($_.userId)" -ForegroundColor Gray } } Measure-Step "6. GET /sessions?offset=2&count=2 (paging arithmetic)" { $resp = Invoke-RestMethod "$BASE/api/v1/identity/sessions?offset=2&count=2" -Headers $AH if ($resp.items.Count -gt 2) { throw "expected at most 2 items, got $($resp.items.Count)" } if ($resp.offset -ne 2 -or $resp.count -ne 2) { throw "offset/count echoed back wrong: offset=$($resp.offset) count=$($resp.count)" } Write-Host " paged window offset=$($resp.offset) count=$($resp.count) items=$($resp.items.Count)" -ForegroundColor Gray } Measure-Step "8. GET /sessions with identity:read scope → 200 (read-only universal GET)" { $resp = Invoke-RestMethod "$BASE/api/v1/identity/sessions?count=1" -Headers $RH if ($null -eq $resp.items) { throw "read-only listing rejected or shape wrong" } } Measure-Step "9. cleanup (RFC 7592)" { try { Invoke-RestMethod -Method Delete "$BASE/connect/register/$($adminReg.client_id)" -Headers @{ Authorization = "Bearer $($adminReg.registration_access_token)" } | Out-Null } catch {} try { Invoke-RestMethod -Method Delete "$BASE/connect/register/$($readReg.client_id)" -Headers @{ Authorization = "Bearer $($readReg.registration_access_token)" } | Out-Null } catch {} } | Out-Null Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Green $timings | Format-Table -AutoSize $total = ($timings | Measure-Object -Property Ms -Sum).Sum Write-Host ("Total: {0:N0} ms" -f $total) Path: redb-identity/demos/demo_soap_facade.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_soap_facade.ps1 ---- # WS-Trust facade — Issue, Validate, Cancel and Renew over the wire, against a running server. # # Usage: pwsh -File demo_soap_facade.ps1 # pwsh -File demo_soap_facade.ps1 -Sts http://localhost:5021/sts -Http https://localhost:5002 # # No tool to install: SOAP is ordinary HTTP with an XML body, so the envelopes below are written out in # full and posted as they are. That is deliberate — everything a WS-Trust client sends is visible here, # and the output stands on its own. # # The one thing worth watching is the fourth column of this demo: a client registered over HTTP getting a # token over SOAP, and that same token being accepted back on HTTP. One issuer, one client registry, one # token store — the facade is a transport, not a second identity server. param( [string]$Sts = $(if ($env:IDENTITY_STS) { $env:IDENTITY_STS } else { "http://localhost:5021/sts" }), [string]$Http = $(if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://localhost:5002" }) ) $ErrorActionPreference = 'Stop' $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $trust = "http://docs.oasis-open.org/ws-sx/ws-trust/200512" $wsse = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" $total = [System.Diagnostics.Stopwatch]::StartNew() $step = 0 $failed = 0 function Say([string]$text, [string]$color = 'Gray') { Write-Host $text -ForegroundColor $color } # Shortens the long opaque strings — tokens, secrets — so the shape of a message stays visible. Nothing # that matters is hidden: a 3 KB JWT tells the reader nothing except how long it is. function Compact([string]$text) { if (-not $text) { return $text } return [regex]::Replace($text, '([A-Za-z0-9\-_\.\+/=]{48,})', { param($m) $m.Groups[1].Value.Substring(0, 24) + '…(' + $m.Groups[1].Value.Length + ' chars)' }) } function Step([string]$action, [string]$what) { $script:step++ Write-Host "" Write-Host (" {0}. {1}" -f $script:step, $action) -NoNewline -ForegroundColor White Write-Host (" {0}" -f $what) -ForegroundColor DarkGray } function Expect([bool]$condition, [string]$message) { if (-not $condition) { Write-Host " !! $message" -ForegroundColor Red $script:failed++ } } # Wraps a request body in a SOAP 1.1 envelope with a WS-Security UsernameToken — which is how a WS-Trust # caller presents its client credentials. Omitting the credentials is a supported call too: step 8 needs # to see what an anonymous request gets. function Envelope([string]$body, [string]$user, [string]$secret) { $security = "" if ($user) { $security = @" $user $secret "@ } return @" $security $body "@ } # Posts one WS-Trust request and shows both directions. Returns @{ Xml; Fault; Reason; Ms }. function Sts { param( [string]$Action, # Issue | Validate | Cancel | Renew [string]$Body, # the wst:RequestSecurityToken element [string]$User = $script:clientId, [string]$Secret = $script:clientSecret, [switch]$Anonymous ) if ($Anonymous) { $User = ""; $Secret = "" } $envelope = Envelope $Body $User $Secret $soapAction = "$trust/RST/$Action" Write-Host " -> " -NoNewline -ForegroundColor DarkGray Say ("SOAPAction " + $soapAction) Write-Host " -> " -NoNewline -ForegroundColor DarkGray Say (Compact (($Body.Trim()) -replace "`r?`n\s*", " ")) if ($User) { Write-Host " -> " -NoNewline -ForegroundColor DarkGray Say ("UsernameToken " + $User + " / " + ("*" * 8)) } $sw = [System.Diagnostics.Stopwatch]::StartNew() # A SOAP 1.1 fault arrives with HTTP 500 and a body that is the whole point of the exchange, so the # error status is asked not to throw. Catching it instead does not work here: PowerShell disposes the # response content while building its own error record, and the only thing left, ErrorDetails.Message, # has had the markup stripped out of it — a perfectly good fault envelope reduced to bare text. $resp = Invoke-WebRequest -Method Post $Sts -ContentType "text/xml; charset=utf-8" ` -Headers @{ SOAPAction = "`"$soapAction`"" } -Body $envelope -SkipHttpErrorCheck $xml = $resp.Content $sw.Stop() $doc = [xml]$xml $fault = $doc.Envelope.Body.Fault $reason = if ($fault) { $fault.faultstring } else { "" } $code = if ($fault) { $fault.faultcode } else { "" } if ($fault) { Write-Host " <- " -NoNewline -ForegroundColor Yellow Say ("soap:Fault " + $code) 'Yellow' Write-Host " " -NoNewline Say $reason 'Yellow' } else { Write-Host " <- " -NoNewline -ForegroundColor Green Say (Compact ($doc.Envelope.Body.InnerXml)) } Write-Host (" {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor DarkGray return @{ Xml = $xml; Doc = $doc; Fault = $code; Reason = $reason; Ms = $sw.Elapsed.TotalMilliseconds } } # Digs the JWT out of the wsse:BinarySecurityToken the RSTR carries. function Read-Token($call) { $node = $call.Doc.SelectSingleNode("//*[local-name()='BinarySecurityToken']") if (-not $node) { return "" } try { return [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($node.InnerText.Trim())) } catch { return $node.InnerText.Trim() } } function Read-Status($call) { $node = $call.Doc.SelectSingleNode("//*[local-name()='Status']/*[local-name()='Code']") if (-not $node) { return "" } return $node.InnerText } $issueBody = @" $trust/Issue {0} "@ $targetBody = @" $trust/{0} {1} "@ Write-Host "" Write-Host " redb.Identity - the WS-Trust facade, over the wire" -ForegroundColor Cyan Write-Host " -------------------------------------------------" -ForegroundColor DarkGray Write-Host "" Write-Host (" STS {0}" -f $Sts) -ForegroundColor DarkGray Write-Host (" HTTP {0} (used to register a demo client, and once at the end)" -f $Http) -ForegroundColor DarkGray Write-Host "" Write-Host " -> what the client sends <- what the server answers" -ForegroundColor DarkGray # ── 1. The contract ─────────────────────────────────────────── # GET on the same address serves the WSDL, with soap:address rewritten to the URL it was fetched from. # This is what a WCF or CXF developer starts from, so an STS that answers only POST is one they cannot # use at all. Step "GET ?wsdl" "the contract, the way a client generator fetches it" $wsdlOk = $false try { $wsdl = Invoke-WebRequest -Method Get ($Sts + "?wsdl") $wsdlOk = $wsdl.StatusCode -eq 200 $addr = ([xml]$wsdl.Content).SelectSingleNode("//*[local-name()='address']").location Write-Host " <- " -NoNewline -ForegroundColor Green Say ("SecurityTokenService, 4 operations; soap:address -> " + $addr) } catch { Write-Host " <- " -NoNewline -ForegroundColor Red Say $_.Exception.Message 'Red' } Expect $wsdlOk "the WSDL was not served - is the identity.soap module loaded?" # ── 2. A client, registered over HTTP ───────────────────────── # The claim of the whole facade in one step: this client is created through the HTTP transport and used # through the SOAP one. # # Granular scopes on purpose: the master identity:manage is deliberately not obtainable through dynamic # registration, and the granular branch is the interesting one anyway. $scope = "identity:users:read" Step "POST /connect/register" "HTTP, not SOAP - register a throwaway client" Write-Host " -> " -NoNewline -ForegroundColor DarkGray Say (@{ client_name = "soap-demo"; grant_types = @("client_credentials"); scope = $scope } | ConvertTo-Json -Compress) $reg = Invoke-RestMethod -Method Post "$Http/connect/register" -Headers $DCR_AUTH -ContentType "application/json" -Body (@{ client_name = "soap-demo" grant_types = @("client_credentials") scope = $scope } | ConvertTo-Json) Write-Host " <- " -NoNewline -ForegroundColor Green Say ("client_id " + $reg.client_id) $clientId = $reg.client_id $clientSecret = $reg.client_secret # ── 3. Issue ────────────────────────────────────────────────── # The RSTR carries our ordinary JWT as a wsse:BinarySecurityToken. No second token format enters the # system, which is why introspection and revocation below work on it without knowing where it came from. Step "RST/Issue" "a token for the client above, now over SOAP" $issued = Sts -Action "Issue" -Body ($issueBody -f $scope) $token = Read-Token $issued Expect ([bool]$token) "no token in the RequestSecurityTokenResponse" # Three segments is a signed JWT, five is an encrypted one (JWE). This server encrypts access tokens by # default, so both are correct answers here and only «neither» would mean something went wrong. Expect ($token.Split('.').Count -in 3, 5) "the issued token is neither a signed nor an encrypted JWT" Expect ($issued.Xml -match 'Lifetime') "no Lifetime - a client that caches tokens cannot know when to stop" # ── 4. Validate ─────────────────────────────────────────────── # WS-Trust answers "is this good" with a status code, not with our introspection document: the caller # asked a yes-or-no question and gets a yes-or-no answer. Step "RST/Validate" "is that token real to this server?" $valid = Sts -Action "Validate" -Body ($targetBody -f "Validate", $token) Expect ((Read-Status $valid) -like "*status/valid") "the token we just minted does not validate" # ── 5. Cancel ───────────────────────────────────────────────── # RFC 7009: a well-formed revocation always succeeds. WS-Trust says so with an empty element rather than # a payload. Step "RST/Cancel" "revoke it" $cancelled = Sts -Action "Cancel" -Body ($targetBody -f "Cancel", $token) Expect ($cancelled.Xml -match 'RequestedTokenCancelled') "the cancellation was not acknowledged" # ── 6. ...and it is dead ────────────────────────────────────── # A revocation nobody can observe is not a revocation. This is the half that proves it. Step "RST/Validate" "the same token, after cancellation" $after = Sts -Action "Validate" -Body ($targetBody -f "Validate", $token) Expect (-not ((Read-Status $after) -like "*status/valid")) "a cancelled token still validates" # ── 7. A refusal ────────────────────────────────────────────── # An OAuth error must arrive as a soap:Fault, not as a successful response carrying an error document - # a client told the call succeeded has no reason to look inside it, and generated WS-Trust clients branch # on the fault code. Step "RST/Issue" "same client, wrong secret" $refused = Sts -Action "Issue" -Body ($issueBody -f $scope) -Secret "not-the-secret" Expect ($refused.Fault -eq "wst:FailedAuthentication") "expected wst:FailedAuthentication, got '$($refused.Fault)'" Expect ($refused.Xml -notmatch 'BinarySecurityToken') "a wrong secret produced a token" # ── 8. No credentials at all ────────────────────────────────── Step "RST/Issue" "no UsernameToken in the envelope" $anon = Sts -Action "Issue" -Body ($issueBody -f $scope) -Anonymous Expect ([bool]$anon.Fault) "an anonymous request was not refused" Expect ($anon.Xml -notmatch 'BinarySecurityToken') "an anonymous request produced a token" # ── 9. A malformed request ──────────────────────────────────── # The caller's mistake has to be told in the caller's vocabulary. Answered as soap:Server it would read # as "we broke", and they would wait for us to fix what is theirs to fix. Step "RST/Issue" "a body that is not a RequestSecurityToken" $junk = Sts -Action "Issue" -Body " " Expect ($junk.Fault -eq "wst:InvalidRequest") "expected wst:InvalidRequest, got '$($junk.Fault)'" # ── 10. One token, two transports ───────────────────────────── # The acceptance criterion of the facade: a token minted over SOAP is the same object HTTP accepts. Not a # translated copy - the same issuer, the same signature, the same entry in the same token store. Step "SOAP + HTTP" "a token issued over SOAP, spent over HTTP" $fresh = Sts -Action "Issue" -Body ($issueBody -f $scope) $freshToken = Read-Token $fresh $httpOk = $true try { Invoke-RestMethod -Method Get "$Http/api/v1/identity/users?offset=0&count=3" -Headers @{ Authorization = "Bearer $freshToken" } | Out-Null } catch { $httpOk = $false } Write-Host " <- " -NoNewline -ForegroundColor Green Say ("HTTP GET /api/v1/identity/users -> " + $(if ($httpOk) { "admitted" } else { "REFUSED" })) Expect $httpOk "a token issued over SOAP was refused over HTTP" # ...and the other direction of the same claim: a read-only token is refused a write on HTTP too, so the # facade did not become a second place where permissions are decided. $httpRefused = $false try { Invoke-RestMethod -Method Post "$Http/api/v1/identity/users" -Headers @{ Authorization = "Bearer $freshToken" } ` -ContentType "application/json" -Body (@{ login = "soap-demo-should-not-exist" } | ConvertTo-Json) | Out-Null } catch { $httpRefused = $true } Write-Host " <- " -NoNewline -ForegroundColor Green Say ("HTTP POST /api/v1/identity/users -> " + $(if ($httpRefused) { "REFUSED (as it must be)" } else { "ADMITTED" })) Expect $httpRefused "a read-only token created a user" $total.Stop() Write-Host "" if ($failed -gt 0) { Write-Host (" WS-Trust facade demo: FAILED ({0} checks) in {1:N0} ms" -f $failed, $total.Elapsed.TotalMilliseconds) -ForegroundColor Red exit 1 } Write-Host " Every call above is one round trip: client -> facade -> direct-vm -> Core -> back." -ForegroundColor DarkGray Write-Host " Four operations, one address: WS-Trust names the operation with the Action, not the URL." -ForegroundColor DarkGray Write-Host (" WS-Trust facade demo: all steps passed in {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Green exit 0 Path: redb-identity/demos/demo_throttle_rfc6585.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_throttle_rfc6585.ps1 ---- # RFC 6585 §4 — HTTP 429 Too Many Requests + Retry-After (RFC 7231 §7.1.3) probes # on rate-limited endpoints. Closes the "ThrottleProcessor silently waits instead of # returning 429" hardening gap flagged in the previous batch's perf diagnosis. # # We exercise the /connect/token endpoint, which carries the tightest throttle in the # server (`TokenThrottleMaxPerPeriod = 10` per 1 second by default, keyed by client_id). # Bursting > 10 token requests within 1 second on the same client_id must: # 1. yield at least one 429 status code, # 2. with a `Retry-After` header carrying a delta-seconds integer (RFC 7231 §7.1.3), # 3. and a structured JSON body { error: "rate_limit_exceeded", retry_after: N }, # 4. so a well-behaved client can sleep that many seconds, retry, and succeed. # # Probes: # 1. DCR (client_credentials + identity:read) # 2. Sanity: single /connect/token succeeds + non-429 status # 3. Burst 25 concurrent /connect/token calls with the same client_id → expect at # least 10 success (the bucket size) AND at least 1 status=429 # 4. Pick one 429 response → assert Retry-After header is present and parses as # a positive integer (delta-seconds form) # 5. Assert the 429 body shape: error == "rate_limit_exceeded", retry_after > 0 # 6. Sleep Retry-After + 0.5 s, then a single /connect/token MUST succeed # (recovery contract — the throttle window has rolled over) # 7. Different client_id is NOT affected by the first key's burst — confirms the # KeyedThrottle isolates buckets per key (probe a fresh DCR'd client immediately # after the burst; it must succeed without waiting) # 8. RFC 7592 cleanup # # Usage: pwsh -File demo_throttle_rfc6585.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } function Invoke-TokenRaw { param([string]$ClientId, [string]$ClientSecret, [string]$Scope = "identity:read") # Use a Hashtable body — PowerShell auto-encodes each field per # application/x-www-form-urlencoded, which is critical because client_secret # may contain '=' or '+' that would otherwise be misinterpreted by the server. $resp = Invoke-WebRequest -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $ClientId client_secret = $ClientSecret scope = $Scope } -SkipHttpErrorCheck -ErrorAction Stop # Headers may surface ETag/Retry-After under different cases; do a case-insensitive scan. $retryAfter = $null foreach ($k in $resp.Headers.Keys) { if ($k -ieq "Retry-After") { $v = $resp.Headers[$k] if ($v -is [Array]) { $v = $v[0] } $retryAfter = $v break } } $bodyObj = if ($resp.Content) { try { $resp.Content | ConvertFrom-Json } catch { $null } } else { $null } return [pscustomobject]@{ Status = [int]$resp.StatusCode Body = $bodyObj RetryAfter = $retryAfter Raw = $resp } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR a client_credentials client. We'll burst /connect/token with this one. $reg = Measure-Step "1. DCR (cc + identity:read)" { $r = Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "throttle-rfc6585" grant_types = @("client_credentials") scope = "identity:read" } | ConvertTo-Json) if (-not $r.client_id) { throw "DCR did not return client_id" } Write-Host " ✓ client_id: $($r.client_id)" -ForegroundColor Green return $r } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri # 2) Sanity — single token call works. Measure-Step "2. sanity: single /connect/token (expect 200)" { $r = Invoke-TokenRaw -ClientId $reg.client_id -ClientSecret $reg.client_secret if ($r.Status -ne 200) { throw "sanity call failed: status=$($r.Status), body=$($r.Body | ConvertTo-Json -Depth 3)" } if (-not $r.Body.access_token) { throw "no access_token on success" } Write-Host " ✓ 200, access_token present" -ForegroundColor Green } | Out-Null # 3) Burst — fire 30 PARALLEL calls. Sequential calls would re-fill the throttle # window between each request (TokenThrottleMaxPerPeriod=10 / 1 s + per-call # latency of ~150 ms means a sequential 25-loop never exceeds the budget). # True concurrency forces the bucket to drain. $burstResults = Measure-Step "3. burst × 30 PARALLEL /connect/token same client_id (expect mix of 200 + 429)" { $cid = $reg.client_id $sec = $reg.client_secret $base = $BASE $results = 1..30 | ForEach-Object -Parallel { # -Parallel runspaces do NOT inherit $PSDefaultParameterValues — pass # -SkipCertificateCheck explicitly so the burst works against an https base. $resp = Invoke-WebRequest -Method Post "$using:base/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $using:cid client_secret = $using:sec scope = "identity:read" } -SkipHttpErrorCheck -SkipCertificateCheck -ErrorAction Stop $retryAfter = $null foreach ($k in $resp.Headers.Keys) { if ($k -ieq "Retry-After") { $v = $resp.Headers[$k] if ($v -is [Array]) { $v = $v[0] } $retryAfter = $v; break } } $bodyObj = if ($resp.Content) { try { $resp.Content | ConvertFrom-Json } catch { $null } } else { $null } [pscustomobject]@{ Status = [int]$resp.StatusCode Body = $bodyObj RetryAfter = $retryAfter } } -ThrottleLimit 30 $by = $results | Group-Object Status foreach ($g in $by) { Write-Host " status=$($g.Name) → count=$($g.Count)" -ForegroundColor DarkGray } $ok = ($results | Where-Object { $_.Status -eq 200 }).Count $r29 = ($results | Where-Object { $_.Status -eq 429 }).Count if ($ok -lt 1) { throw "no successful token calls in 30-burst — server unreachable?" } if ($r29 -lt 1) { throw "no 429 response in 30-burst on same client_id — throttle / RejectOnOverflow not wired" } Write-Host " ✓ 200 × $ok, 429 × $r29" -ForegroundColor Green return $results } # 4) Pick a 429, assert Retry-After header is delta-seconds (RFC 7231 §7.1.3). $first429 = $burstResults | Where-Object { $_.Status -eq 429 } | Select-Object -First 1 Measure-Step "4. assert Retry-After header (RFC 7231 §7.1.3 delta-seconds)" { if (-not $first429.RetryAfter) { throw "429 response missing Retry-After header (RFC 6585 §4 requires it)" } $ra = $first429.RetryAfter.ToString().Trim() if (-not ($ra -match '^\d+$')) { throw "Retry-After must be a non-negative integer (delta-seconds form), got: '$ra'" } $secs = [int]$ra if ($secs -lt 1) { throw "Retry-After must be >= 1 s, got $secs" } Write-Host " ✓ Retry-After: $secs s" -ForegroundColor Green $script:retryAfterSecs = $secs } | Out-Null # 5) Assert body shape. Measure-Step "5. assert 429 body shape { error, retry_after }" { $b = $first429.Body if (-not $b) { throw "429 body did not parse as JSON" } if ($b.error -ne "rate_limit_exceeded") { throw "expected error='rate_limit_exceeded', got '$($b.error)'" } if (-not $b.retry_after -or [int]$b.retry_after -lt 1) { throw "expected retry_after >= 1, got '$($b.retry_after)'" } if ([int]$b.retry_after -ne $script:retryAfterSecs) { # Not strictly required by RFC, but the body should match the header for sanity. Write-Host " ⚠ body.retry_after ($($b.retry_after)) != header Retry-After ($($script:retryAfterSecs)) — minor inconsistency" -ForegroundColor Yellow } else { Write-Host " ✓ body.retry_after matches header" -ForegroundColor Green } Write-Host " ✓ error='$($b.error)', retry_after=$($b.retry_after)" -ForegroundColor Green } | Out-Null # 6) Wait the advised period + a small grace window, then retry the same client → must succeed. Measure-Step "6. sleep $($script:retryAfterSecs)s + grace, retry → expect 200 (recovery contract)" { Start-Sleep -Milliseconds (($script:retryAfterSecs * 1000) + 500) $r = Invoke-TokenRaw -ClientId $reg.client_id -ClientSecret $reg.client_secret if ($r.Status -ne 200) { throw "after Retry-After window, expected 200 but got $($r.Status). Body: $($r.Body | ConvertTo-Json -Depth 3)" } if (-not $r.Body.access_token) { throw "post-Retry-After response missing access_token" } Write-Host " ✓ recovered: 200 + fresh access_token" -ForegroundColor Green } | Out-Null # 7) Different client_id is NOT affected — KeyedThrottle isolation. $reg2 = Measure-Step "7a. DCR a second client (isolation probe)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "throttle-rfc6585-iso" grant_types = @("client_credentials") scope = "identity:read" } | ConvertTo-Json) } $RAT2 = $reg2.registration_access_token $RCU2 = $reg2.registration_client_uri Measure-Step "7b. /connect/token on the OTHER client immediately → 200 (per-key isolation)" { # Saturate client_id #1 first so we know the global throttle is NOT being hit. for ($i = 1; $i -le 15; $i++) { Invoke-TokenRaw -ClientId $reg.client_id -ClientSecret $reg.client_secret | Out-Null } # Now hit client_id #2 — its bucket has not been touched at all. $r = Invoke-TokenRaw -ClientId $reg2.client_id -ClientSecret $reg2.client_secret if ($r.Status -ne 200) { throw "second client throttled by first client's burst (got $($r.Status)) — KeyedThrottle isolation broken" } Write-Host " ✓ second client got 200 — keys are isolated" -ForegroundColor Green } | Out-Null # 8) RFC 7592 cleanup Measure-Step "8. RFC 7592 DELETE both registrations" { if ($RAT) { Invoke-RestMethod -Method Delete -Uri $RCU -Headers @{ Authorization = "Bearer $RAT" } | Out-Null } if ($RAT2) { Invoke-RestMethod -Method Delete -Uri $RCU2 -Headers @{ Authorization = "Bearer $RAT2" } | Out-Null } Write-Host " ✓ both DCR clients deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_token_exchange.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_token_exchange.ps1 ---- # Token Exchange (RFC 8693). Opt-in via RedbIdentityOptions.EnableTokenExchange. # Two patterns covered: # a) impersonation — no actor_token; new access_token has subject=user, no `act` claim # (only when TokenExchangeAllowImpersonation=true). # b) delegation — actor_token provided; new access_token carries `act` claim chain. # Plus negative paths: scope upscoping (must be subset), depth limit, missing subject_token. # Usage: pwsh -File demo_token_exchange.ps1 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $REDIRECT_CB = if ($BASE -like 'https:*') { 'https://localhost:9999/cb' } else { 'http://localhost:9999/cb' } $timings = [System.Collections.Generic.List[object]]::new() $EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange" $ACCESS_TT = "urn:ietf:params:oauth:token-type:access_token" function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $result } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED in {0:N0} ms: {1}" -f $sw.Elapsed.TotalMilliseconds, $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } # 0) Discovery — if token-exchange isn't advertised, exit cleanly so the demo is still # counted as PASS in run_all (the feature is opt-in and most dev configs leave it off). $disco = Invoke-RestMethod "$BASE/.well-known/openid-configuration" if ($disco.grant_types_supported -notcontains $EXCHANGE) { Write-Host "Token Exchange ($EXCHANGE) not advertised by /.well-known — set " -ForegroundColor Yellow -NoNewline Write-Host "RedbIdentityOptions.EnableTokenExchange=true and reload tpkg." -ForegroundColor Yellow Write-Host "Skipping (this is a feature-flag config issue, not a server bug)." -ForegroundColor DarkGray exit 0 } $total = [System.Diagnostics.Stopwatch]::StartNew() # 1) DCR — the requesting/exchanger client. $reg = Measure-Step "1. DCR /connect/register (password + token-exchange)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH ` -ContentType "application/json" ` -Body (@{ client_name = "tx-demo" redirect_uris = @($REDIRECT_CB) grant_types = @("password","refresh_token","client_credentials",$EXCHANGE) scope = "openid profile email offline_access identity:read" } | ConvertTo-Json) } # 2) Seed user. $user = "tx_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "2. account/register" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" ` -ContentType "application/json" ` -Body (@{ login = $user email = "$user@example.com" password = $pwd displayName = $user } | ConvertTo-Json) } | Out-Null # 3) Get a subject_token (user access_token) via password grant. $subject = Measure-Step "3. password grant (subject_token = user access_token)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email" } } Write-Host " subject_token : $($subject.access_token.Substring(0,32))… scope=$($subject.scope)" # 4) Get an actor_token (client_credentials) — represents the calling service. $actor = Measure-Step "4. client_credentials (actor_token)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials" client_id = $reg.client_id client_secret = $reg.client_secret scope = "identity:read" } } Write-Host " actor_token : $($actor.access_token.Substring(0,32))… scope=$($actor.scope)" # 5) DELEGATION exchange — actor_token present → new token has `act` claim. $delegated = Measure-Step "5. token-exchange (delegation: subject + actor)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = $EXCHANGE client_id = $reg.client_id client_secret = $reg.client_secret subject_token = $subject.access_token subject_token_type = $ACCESS_TT actor_token = $actor.access_token actor_token_type = $ACCESS_TT requested_token_type = $ACCESS_TT scope = "openid profile" } } Write-Host " delegated_token : $($delegated.access_token.Substring(0,32))…" Write-Host " issued_token_type: $($delegated.issued_token_type)" # 6) Decode delegated access_token (best-effort — may be JWE). function Decode-Jwt([string]$jwt) { $parts = $jwt.Split('.') if ($parts.Length -lt 2) { return $null } $payload = $parts[1].Replace('-','+').Replace('_','/') switch ($payload.Length % 4) { 2 { $payload += '==' } 3 { $payload += '=' } } try { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) | ConvertFrom-Json } catch { $null } } $claims = Decode-Jwt $delegated.access_token if ($null -eq $claims) { Write-Host " (access_token is JWE-encrypted — using introspect to inspect claims)" -ForegroundColor Yellow $claims = Invoke-RestMethod -Method Post "$BASE/connect/introspect" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ token = $delegated.access_token client_id = $reg.client_id client_secret = $reg.client_secret } } Write-Host " sub = $($claims.sub)" Write-Host " scope= $($claims.scope)" if ($claims.act) { Write-Host " ✓ act claim present (delegation chain): $($claims.act | ConvertTo-Json -Compress)" -ForegroundColor Green } else { Write-Host " ! act claim missing on delegated token" -ForegroundColor Red } # 7) Negative: try to upscope (request a scope NOT in subject_token) → invalid_scope. Measure-Step "7. upscoping rejected (request 'identity:manage' not held by subject)" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = $EXCHANGE client_id = $reg.client_id client_secret = $reg.client_secret subject_token = $subject.access_token subject_token_type = $ACCESS_TT actor_token = $actor.access_token actor_token_type = $ACCESS_TT requested_token_type = $ACCESS_TT scope = "identity:manage" } | Out-Null throw "UPSCOPING ACCEPTED — server is permissive!" } catch { $code = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -in 400, 401) { Write-Host " ✓ upscoping rejected: status=$code" -ForegroundColor Green } else { throw } } } | Out-Null # 8) Negative: missing subject_token → invalid_request. Measure-Step "8. missing subject_token → invalid_request" { try { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = $EXCHANGE client_id = $reg.client_id client_secret = $reg.client_secret requested_token_type = $ACCESS_TT } | Out-Null throw "MISSING SUBJECT ACCEPTED" } catch { $code = $null try { $code = $_.Exception.Response.StatusCode.value__ } catch {} if ($code -in 400, 401) { Write-Host " ✓ rejected: status=$code" -ForegroundColor Green } else { throw } } } | Out-Null # 9) Chain another exchange on top of delegated → second `act` nested inside. $delegated2 = Measure-Step "9. token-exchange chain (delegated → delegated2; expect act->act)" { Invoke-RestMethod -Method Post "$BASE/connect/token" ` -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = $EXCHANGE client_id = $reg.client_id client_secret = $reg.client_secret subject_token = $delegated.access_token subject_token_type = $ACCESS_TT actor_token = $actor.access_token actor_token_type = $ACCESS_TT requested_token_type = $ACCESS_TT scope = "openid" } } Write-Host " chained_token : $($delegated2.access_token.Substring(0,32))…" $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_userinfo.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_userinfo.ps1 ---- # /connect/userinfo dedicated probe — RFC 5.3 negatives + RFC method-shape compliance. # # Closes the ⚠️ entry in DEMO_COVERAGE_MATRIX.md for the userinfo endpoint. Positive # claim assertions live in `demo_claim_probes` (step 8: sub / email / phone_number / # address) and `demo_acr_values` (step 7: sub + voluntary acr) — this probe focuses on # the RFC-compliance surface those two don't pin: # # 1. GET /connect/userinfo with VALID bearer → 200 + application/json + sub matches # 2. POST /connect/userinfo (RFC 5.3.1 §5.3 — both methods MUST be supported) # 3. No Authorization header → 401 + WWW-Authenticate: Bearer # 4. Authorization header but no token (just "Bearer ") → 401 # 5. Garbage / non-JWT bearer → 401 invalid_token # 6. Token with valid signature but tampered payload → 401 invalid_token # 7. RFC 7592 cleanup # # Positive scope-→claim mapping (which scopes return which fields) is covered exhaustively # by `demo_claim_probes` — not duplicated here to keep the probe focused. # # Usage: pwsh -File demo_userinfo.ps1 #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host "" Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $result = & $Action $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "--- [$Name] $ms ms" -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="ok" }) return $result } catch { $sw.Stop() $ms = [math]::Round($sw.Elapsed.TotalMilliseconds, 0) Write-Host "!!! [$Name] FAILED in $ms ms: $($_.Exception.Message)" -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=$ms; Status="fail" }) throw } } # Robust HTTP probe: returns status + headers + body without throwing on non-2xx. function Hit { param([string]$Method, [string]$Url, [hashtable]$Headers = $null, $Body = $null) try { $params = @{ Uri = $Url; Method = $Method; MaximumRedirection = 0; SkipHttpErrorCheck = $true; UseBasicParsing = $true; DisableKeepAlive = $true; TimeoutSec = 10 } if ($Headers) { $params.Headers = $Headers } if ($null -ne $Body) { $params.Body = $Body $params.ContentType = 'application/x-www-form-urlencoded' } $r = Invoke-WebRequest @params return [pscustomobject]@{ StatusCode = [int]$r.StatusCode ContentType = $r.Headers['Content-Type'] -join '; ' WWWAuth = $r.Headers['WWW-Authenticate'] -join '; ' Content = $r.Content } } catch { return [pscustomobject]@{ StatusCode = 0; ContentType = ''; WWWAuth = ''; Content = $_.Exception.Message } } } $total = [System.Diagnostics.Stopwatch]::StartNew() # 0) DCR + register user + ROPC for a real access_token. $reg = Measure-Step "0a. DCR (password client)" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "userinfo-probe" grant_types = @("password") scope = "openid profile email identity:account" } | ConvertTo-Json) } $RAT = $reg.registration_access_token $RCU = $reg.registration_client_uri $user = "ui_$([Guid]::NewGuid().ToString('N').Substring(0,8))" $pwd = "Test1234Pass!" Measure-Step "0b. self-register $user" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/account/register" -ContentType "application/json" ` -Body (@{ login = $user; email = "$user@example.com"; password = $pwd; displayName = $user } | ConvertTo-Json) | Out-Null } | Out-Null $tok = Measure-Step "0c. ROPC (access_token + sub probe)" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "password" client_id = $reg.client_id client_secret = $reg.client_secret username = $user password = $pwd scope = "openid profile email" } } $BEARER = @{ Authorization = "Bearer $($tok.access_token)" } # 1) GET with valid bearer. Measure-Step "1. GET /connect/userinfo → 200 + application/json + sub claim" { $r = Hit -Method Get -Url "$BASE/connect/userinfo" -Headers $BEARER if ($r.StatusCode -ne 200) { throw "expected 200, got $($r.StatusCode); body: $($r.Content.Substring(0,[Math]::Min(200,$r.Content.Length)))" } if ($r.ContentType -notmatch '^application/json') { throw "wrong content-type: '$($r.ContentType)'" } $body = $r.Content | ConvertFrom-Json if (-not $body.sub) { throw "no sub in userinfo response" } Write-Host " status=200, content-type=$($r.ContentType.Split(';')[0]), sub=$($body.sub)" -ForegroundColor Green } | Out-Null # 2) POST per RFC 5.3.1 — same bearer header, no body, should also return 200. Measure-Step "2. POST /connect/userinfo (RFC 5.3.1 — both methods supported) → 200" { $r = Hit -Method Post -Url "$BASE/connect/userinfo" -Headers $BEARER if ($r.StatusCode -ne 200) { throw "expected 200 on POST, got $($r.StatusCode); body: $($r.Content.Substring(0,[Math]::Min(200,$r.Content.Length)))" } if ($r.ContentType -notmatch '^application/json') { throw "wrong content-type on POST: '$($r.ContentType)'" } $body = $r.Content | ConvertFrom-Json if (-not $body.sub) { throw "no sub in POST userinfo" } Write-Host " POST works equally" -ForegroundColor Green } | Out-Null # 3) No Authorization header at all → 400 invalid_request (per RFC 6750 §3.1) OR 401 # + WWW-Authenticate: Bearer challenge. Both are RFC-compliant for "no credentials": # RFC 6750 §3.1 maps "request did not include credentials" to `invalid_request` which # is 400, while many servers prefer 401 to signal "authentication required". We accept # either, but the WWW-Authenticate challenge is mandatory. Measure-Step "3. no Authorization header → 400/401 + WWW-Authenticate: Bearer challenge" { $r = Hit -Method Get -Url "$BASE/connect/userinfo" if ($r.StatusCode -ne 400 -and $r.StatusCode -ne 401) { throw "expected 400 or 401, got $($r.StatusCode)" } if ($r.WWWAuth -notmatch '(?i)Bearer') { throw "expected WWW-Authenticate: Bearer challenge, got: '$($r.WWWAuth)'" } Write-Host " status=$($r.StatusCode), WWW-Authenticate: $($r.WWWAuth.Substring(0,[Math]::Min(60,$r.WWWAuth.Length)))..." -ForegroundColor Green } | Out-Null # 4) Authorization header with empty bearer value → 400/401 (OpenIddict treats empty as # "missing_token", same as no header at all). Just verify it's rejected with WWW-Authenticate. Measure-Step "4. empty bearer ('Bearer ') → rejected with WWW-Authenticate" { $r = Hit -Method Get -Url "$BASE/connect/userinfo" -Headers @{ Authorization = "Bearer " } if ($r.StatusCode -lt 400) { throw "expected 4xx for empty bearer, got $($r.StatusCode)" } if ($r.WWWAuth -notmatch '(?i)Bearer') { throw "expected WWW-Authenticate: Bearer challenge, got: '$($r.WWWAuth)'" } Write-Host " status=$($r.StatusCode) (empty token rejected, WWW-Authenticate present)" -ForegroundColor Green } | Out-Null # 5) Garbage / non-JWT bearer → 401 invalid_token. Measure-Step "5. garbage bearer → 401 invalid_token" { $r = Hit -Method Get -Url "$BASE/connect/userinfo" -Headers @{ Authorization = "Bearer not-a-real-token" } if ($r.StatusCode -ne 401) { throw "expected 401, got $($r.StatusCode)" } if ($r.WWWAuth -notmatch '(?i)invalid_token') { throw "expected error=invalid_token in WWW-Authenticate, got: '$($r.WWWAuth)'" } Write-Host " 401 invalid_token" -ForegroundColor Green } | Out-Null # 6) Token signature valid but payload tampered: take the valid bearer, flip a char in the # PAYLOAD segment. Our access_token is a JWE (encrypted) so any byte-flip breaks integrity # on decrypt — easy "tamper-detection" probe. Measure-Step "6. tampered bearer → 401 (integrity/signature check fires)" { $orig = $tok.access_token if ($orig.Length -lt 30) { throw "access_token too short to tamper" } # Flip a single character mid-token. $idx = [int]($orig.Length / 2) $ch = $orig[$idx] $flipped = if ($ch -eq 'A') { 'B' } elseif ($ch -eq '0') { '1' } else { 'A' } $tampered = $orig.Substring(0, $idx) + $flipped + $orig.Substring($idx + 1) if ($tampered -eq $orig) { throw "tamper produced identical string (Substring math wrong)" } $r = Hit -Method Get -Url "$BASE/connect/userinfo" -Headers @{ Authorization = "Bearer $tampered" } if ($r.StatusCode -ne 401) { throw "expected 401 on tampered bearer, got $($r.StatusCode); body: $($r.Content.Substring(0,[Math]::Min(200,$r.Content.Length)))" } Write-Host " 401 (tamper detected)" -ForegroundColor Green } | Out-Null # 7) RFC 7592 cleanup. Measure-Step "7. RFC 7592 DELETE registration" { if ($RAT) { try { Invoke-RestMethod -Method Delete -Uri $RCU -Headers @{ Authorization = "Bearer $RAT" } | Out-Null } catch {} } Write-Host " registration deleted" -ForegroundColor Green } | Out-Null $total.Stop() Write-Host "" Write-Host "================ TIMING SUMMARY ================" -ForegroundColor Cyan $timings | Format-Table -AutoSize Step, Ms, Status Write-Host ("TOTAL: {0:N0} ms" -f $total.Elapsed.TotalMilliseconds) -ForegroundColor Cyan Path: redb-identity/demos/demo_webhooks.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/demo_webhooks.ps1 ---- # W1 — outbound webhook subscription probe. # # Verifies the full lifecycle end-to-end: # 1. admin DCR + token # 2. spin up a pwsh HttpListener mock receiver on 127.0.0.1: # 3. create a webhook subscription pointed at the receiver # 4. trigger a user-create event (POST /users) # 5. wait for the mock receiver to record the delivery; assert: # - X-RedbIdentity-Signature header verifies via shared secret # - X-RedbIdentity-EventType = UserCreated # - body parses as IdentityEvent with the expected fields # 6. rotate secret; trigger another event; assert NEW secret signs # 7. delete the subscription; trigger another event; assert receiver # sees nothing (subscription removed) # 8. cleanup # #requires -Version 7 $BASE = if ($env:IDENTITY_BASE) { $env:IDENTITY_BASE } else { "https://127.0.0.1:5002" } $DCR_IAT = if ($env:IDENTITY_DCR_TOKEN) { $env:IDENTITY_DCR_TOKEN } else { "dev-only-initial-access-token-not-for-production" } $DCR_AUTH = @{ Authorization = "Bearer $DCR_IAT" } $PSDefaultParameterValues['Invoke-RestMethod:SkipCertificateCheck'] = $true $PSDefaultParameterValues['Invoke-WebRequest:SkipCertificateCheck'] = $true $timings = [System.Collections.Generic.List[object]]::new() $totalSw = [System.Diagnostics.Stopwatch]::StartNew() function Measure-Step { param([string]$Name, [scriptblock]$Action) Write-Host ""; Write-Host "=== [$Name] ===" -ForegroundColor Cyan $sw = [System.Diagnostics.Stopwatch]::StartNew() try { $r = & $Action; $sw.Stop() Write-Host ("--- [$Name] {0:N0} ms" -f $sw.Elapsed.TotalMilliseconds) -ForegroundColor Green $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="ok" }) return $r } catch { $sw.Stop() Write-Host ("!!! [$Name] FAILED: {0}" -f $_.Exception.Message) -ForegroundColor Red $timings.Add([pscustomobject]@{ Step=$Name; Ms=[math]::Round($sw.Elapsed.TotalMilliseconds,0); Status="fail" }) throw } } # ── Pick a free local port for the mock receiver ─────────────────── $listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0) $listener.Start() $port = $listener.LocalEndpoint.Port $listener.Stop() $receiverPath = "/webhook" $receiverUrl = "http://127.0.0.1:$port$receiverPath" # The receiver job and this script share the deliveries through a file in the temp folder # ($env:TEMP is not set on Linux; GetTempPath() is on every platform). $deliveryFile = Join-Path ([System.IO.Path]::GetTempPath()) "webhook-deliveries-$port.json" # Storage for received deliveries (cross-runspace via shared variable) $Global:WebhookDeliveries = [System.Collections.Generic.List[object]]::new() $Global:WebhookCancellation = $false # Start mock receiver in a background runspace. The listener is registered # on both the webhook path AND a /__shutdown path — sending to the latter # breaks the GetContext block on parent-side cleanup so Remove-Job returns # in milliseconds instead of waiting the default 120s timeout. $receiver = Start-Job -ScriptBlock { param($port, $path, $deliveryFile) $listener = [System.Net.HttpListener]::new() # HttpListener takes prefixes ending in '/' only; a request to $path without it still matches. $listener.Prefixes.Add("http://127.0.0.1:$port$path/") $listener.Prefixes.Add("http://127.0.0.1:$port/__shutdown/") $listener.Start() $records = [System.Collections.Generic.List[object]]::new() while ($listener.IsListening) { try { $ctx = $listener.GetContext() if ($ctx.Request.Url.AbsolutePath.TrimEnd('/') -eq "/__shutdown") { $ctx.Response.StatusCode = 200 $ctx.Response.Close() break } $headers = @{} foreach ($k in $ctx.Request.Headers.AllKeys) { $headers[$k] = $ctx.Request.Headers[$k] } $reader = New-Object System.IO.StreamReader($ctx.Request.InputStream, $ctx.Request.ContentEncoding) $body = $reader.ReadToEnd() $reader.Close() $records.Add([pscustomobject]@{ ReceivedAt = (Get-Date).ToString('o') Headers = $headers Body = $body Method = $ctx.Request.HttpMethod Url = $ctx.Request.Url.AbsolutePath }) # Persist after every delivery so the parent can poll. $records | ConvertTo-Json -Depth 8 -Compress | Set-Content -Path $deliveryFile -ErrorAction Stop $ctx.Response.StatusCode = 200 $ctx.Response.ContentLength64 = 0 $ctx.Response.Close() } catch { break } } $listener.Stop() } -ArgumentList $port, $receiverPath, $deliveryFile Write-Host "started mock receiver on $receiverUrl (job=$($receiver.Id))" -ForegroundColor Gray # The job starts a new pwsh process; wait until its listener accepts before any event is fired. $ready = [System.Diagnostics.Stopwatch]::StartNew() while ($true) { $probe = [System.Net.Sockets.TcpClient]::new() try { $probe.Connect([System.Net.IPAddress]::Loopback, $port); break } catch {} finally { $probe.Dispose() } if ($receiver.State -ne 'Running' -or $ready.Elapsed.TotalSeconds -gt 30) { throw "mock receiver did not start: $((Receive-Job $receiver 2>&1) -join ' | ')" } Start-Sleep -Milliseconds 100 } function Read-Deliveries { if (-not (Test-Path $deliveryFile)) { return @() } try { return Get-Content $deliveryFile -Raw | ConvertFrom-Json } catch { return @() } } function Wait-Delivery { param([scriptblock]$Predicate, [int]$TimeoutMs = 8000) $sw = [System.Diagnostics.Stopwatch]::StartNew() while ($sw.Elapsed.TotalMilliseconds -lt $TimeoutMs) { $deliveries = @(Read-Deliveries) foreach ($d in $deliveries) { if (& $Predicate $d) { return $d } } Start-Sleep -Milliseconds 200 } return $null } function Verify-Signature { param($delivery, [string]$secret) $sigHeader = $delivery.Headers.'X-RedbIdentity-Signature' if (-not $sigHeader) { throw "no signature header" } if ($sigHeader -notlike "sha256=*") { throw "signature header format wrong" } $sigHex = $sigHeader.Substring(7).ToLowerInvariant() # Body is HMACed verbatim as UTF-8 bytes (GitHub-style). $hmac = New-Object System.Security.Cryptography.HMACSHA256 $hmac.Key = [Text.Encoding]::UTF8.GetBytes($secret) $bodyBytes = [Text.Encoding]::UTF8.GetBytes($delivery.Body) $computed = ($hmac.ComputeHash($bodyBytes) | ForEach-Object { $_.ToString('x2') }) -join '' if ($computed -ne $sigHex) { throw "signature mismatch - expected $computed got $sigHex" } } # ── Admin scaffolding ──────────────────────────────────────────── $adminReg = Measure-Step "1. admin DCR" { Invoke-RestMethod -Method Post "$BASE/connect/register" -Headers $DCR_AUTH -ContentType "application/json" ` -Body (@{ client_name = "webhooks-probe-admin"; grant_types = @("client_credentials"); scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } | ConvertTo-Json) } $adminTok = Measure-Step "2. admin cc token" { Invoke-RestMethod -Method Post "$BASE/connect/token" -ContentType "application/x-www-form-urlencoded" ` -Body @{ grant_type = "client_credentials"; client_id = $adminReg.client_id; client_secret = $adminReg.client_secret; scope = "identity:users:write identity:groups:write identity:consents:write identity:mfa:write identity:applications:write identity:scopes:write identity:claims:write identity:roles:write identity:webhooks:write identity:federation:write identity:signing-keys:write" } } $H = @{ Authorization = "Bearer $($adminTok.access_token)"; "Content-Type" = "application/json" } # Cleanup stale subscriptions pointing at any old run's port (best-effort) try { $stale = Invoke-RestMethod -Method Get "$BASE/api/v1/identity/webhooks?count=200" -Headers $H foreach ($s in $stale.items) { if ($s.url -like '*webhook*' -and $s.url -like '*127.0.0.1*') { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/webhooks/$($s.id)" -Headers $H | Out-Null } catch {} } } } catch {} # ── Subscription lifecycle ─────────────────────────────────────── $created = Measure-Step "3. POST /webhooks (filter=UserCreated)" { $body = @{ url = $receiverUrl displayName = "demo-webhook" eventTypeFilter = "UserCreated" enabled = $true timeoutMs = 5000 maxAttempts = 2 } | ConvertTo-Json Invoke-RestMethod -Method Post "$BASE/api/v1/identity/webhooks" -Headers $H -Body $body } $secret = $created.hmacSecret $SubId = [long]$created.id if (-not $secret) { throw "hmacSecret missing on create response" } Write-Host " created id=$SubId secret length=$($secret.Length)" -ForegroundColor Gray # Trigger an event the subscription matches $suffix = [Guid]::NewGuid().ToString('N').Substring(0,6) $login = "wh_$suffix" $user = Measure-Step "4. POST /users (fires UserCreated)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/users" -Headers $H ` -Body (@{ login = $login; password = "Test1234Pass!"; displayName = $login } | ConvertTo-Json) } $UserId = [long]$user.id # Wait for the delivery Measure-Step "5. wait for HTTP POST + verify HMAC signature" { $delivery = Wait-Delivery { param($d) $d.Headers.'X-RedbIdentity-EventType' -eq 'UserCreated' -and $d.Body -match $login } if (-not $delivery) { throw "no UserCreated delivery received within timeout" } Write-Host " delivery headers: $($delivery.Headers.Keys -join ', ')" -ForegroundColor Gray Verify-Signature -delivery $delivery -secret $secret Write-Host " signature OK; body length=$($delivery.Body.Length)" -ForegroundColor Green } | Out-Null # Rotate secret + trigger another event $rotateResp = Measure-Step "6. POST /webhooks/$SubId/rotate-secret" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/webhooks/$SubId/rotate-secret" -Headers $H } $newSecret = $rotateResp.hmacSecret if (-not $newSecret) { throw "rotate-secret did not return new secret" } if ($newSecret -eq $secret) { throw "rotate-secret returned the same value" } # Clear file so wait sees only the next delivery if (Test-Path $deliveryFile) { Remove-Item $deliveryFile -Force } $login2 = "wh2_$suffix" $user2 = Measure-Step "7. POST /users #2 (fires UserCreated under NEW secret)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/users" -Headers $H ` -Body (@{ login = $login2; password = "Test1234Pass!"; displayName = $login2 } | ConvertTo-Json) } Measure-Step "8. verify NEW secret signs (old secret would mismatch)" { $delivery = Wait-Delivery { param($d) $d.Headers.'X-RedbIdentity-EventType' -eq 'UserCreated' -and $d.Body -match $login2 } if (-not $delivery) { throw "no delivery for #2 received" } Verify-Signature -delivery $delivery -secret $newSecret Write-Host " new secret verified" -ForegroundColor Green # Sanity: old secret should NOT verify $oldSecretError = $null try { Verify-Signature -delivery $delivery -secret $secret } catch { $oldSecretError = $_.Exception.Message } if (-not $oldSecretError) { throw "old secret unexpectedly verified — rotate-secret didn't take effect" } Write-Host " old secret correctly REJECTED" -ForegroundColor Green } | Out-Null # Delete subscription, trigger another event, assert receiver sees nothing if (Test-Path $deliveryFile) { Remove-Item $deliveryFile -Force } Measure-Step "9. DELETE /webhooks/$SubId" { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/webhooks/$SubId" -Headers $H | Out-Null } | Out-Null $login3 = "wh3_$suffix" $user3 = Measure-Step "10. POST /users #3 (no subscription left)" { Invoke-RestMethod -Method Post "$BASE/api/v1/identity/users" -Headers $H ` -Body (@{ login = $login3; password = "Test1234Pass!"; displayName = $login3 } | ConvertTo-Json) } Measure-Step "11. assert NO delivery received" { Start-Sleep -Milliseconds 2000 $deliveries = @(Read-Deliveries) if ($deliveries.Count -gt 0) { throw "received $($deliveries.Count) deliveries after subscription was deleted" } } | Out-Null # Cleanup Measure-Step "12. cleanup" { foreach ($u in @($user, $user2, $user3)) { try { Invoke-RestMethod -Method Delete "$BASE/api/v1/identity/users/$($u.id)" -Headers $H | Out-Null } catch {} } # HttpListener.GetContext() blocks until a request — Stop-Job sends a # cancellation but the inner thread is stuck inside the GetContext call, # so PowerShell waits the full default 120s for the job to "complete" # cleanly. Sending a request to a freed listener immediately makes # GetContext throw → the runspace exits → Remove-Job returns instantly. try { Invoke-WebRequest -Uri "http://127.0.0.1:$port/__shutdown/" -TimeoutSec 1 | Out-Null } catch {} Remove-Job $receiver -Force -ErrorAction SilentlyContinue if (Test-Path $deliveryFile) { Remove-Item $deliveryFile -Force } } | Out-Null $totalSw.Stop() Write-Host "" Write-Host "=== Summary ===" -ForegroundColor Magenta $timings | Format-Table -AutoSize Write-Host ("Total: {0:N0} ms" -f $totalSw.Elapsed.TotalMilliseconds) -ForegroundColor Magenta Path: redb-identity/demos/run_all.ps1 Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/demos/run_all.ps1 ---- #requires -Version 7 <# Runs every demo_*.ps1 in this directory in sequence and prints a pass/fail summary table. Each demo runs in its own pwsh child process so a hard failure in one demo cannot abort the rest. Per-demo stdout is streamed live and also captured to demos/_logs/.log for post-mortem. Usage: pwsh -File .\run_all.ps1 # run every demo_*.ps1 pwsh -File .\run_all.ps1 -Only mfa_totp # run only demos whose name matches pwsh -File .\run_all.ps1 -StopOnFail # bail out on first failure pwsh -File .\run_all.ps1 -DemoTimeoutSec 300 # a demo still running after 300 s is killed A demo that does not end within -DemoTimeoutSec (default 600) is killed with its child processes and recorded as FAIL(timeout), so one stuck demo cannot hold the run. #> param( [string]$Only = '', [switch]$StopOnFail, [switch]$IncludeInteractive, [int]$DemoTimeoutSec = 600 ) $ErrorActionPreference = 'Stop' $here = Split-Path -Parent $MyInvocation.MyCommand.Path $logDir = Join-Path $here '_logs' if (-not (Test-Path $logDir)) { New-Item -ItemType Directory -Path $logDir | Out-Null } # Demos that need a human in the loop (browser approval, etc.). Skipped by default. $interactive = @('demo_device_code.ps1') # Canonical execution order: # 1. Discovery + core grants (fast feedback on server health) # 2. High-priority security probes: DPoP (RFC 9449), PAR (RFC 9126), logout # 3. Advanced grants + token management # 4. Self-service /me + MFA # 5. Provisioning: account register/verify, email change, SCIM $ordered = @( 'demo_discovery_jwks.ps1', 'demo_discovery_shape.ps1', # Discovery JSON shape lock + RFC 9449 §5 catalog 'demo_conformance_discovery_config.ps1', # OpenID Config OP profile — §3 completeness + jwks/alg + PKCE/S256 + cert warnings 'demo_dcr_lifecycle.ps1', 'demo_client_credentials.ps1', 'demo_private_key_jwt.ps1', # RFC 7523 — private_key_jwt client assertion (DCR + token + introspect + negative) 'demo_password_ropc.ps1', # ── HIGH PRIORITY: complex security contracts ───────────────────────────── 'demo_dpop.ps1', # RFC 9449 — DPoP proofs, jkt binding, replay 'demo_par.ps1', # RFC 9126 — PAR, one-time request_uri 'demo_par_per_client.ps1', # RFC 9126 §5 — per-client require_pushed_authorization_requests 'demo_jar_request_object.ps1', # RFC 9101 — JAR signed request object: accept, §6.1 override, alg:none + wrong-key rejected 'demo_logout_endsession.ps1', # OIDC Session + RFC 7009 revocation 'demo_backchannel_logout.ps1', # OIDC Back-Channel Logout 1.0 — fan-out + logout_token JWT 'demo_federation.ps1', # OIDC federation: discovery + safe public list + 302 probe 'demo_federation_e2e.ps1', # provision-on-first-login + link-on-replay end-to-end against navikt/mock-oauth2-server 'demo_federation_link_unlink.ps1', # self-service link / unlink via /me/federated-identities + re-link cycle 'demo_federation_github.ps1', # GitHub OAuth2-only path (non-OIDC, REST /user + /user/emails) via self-hosted pwsh HttpListener mock # ── Grants + token lifecycle ────────────────────────────────────────────── 'demo_authcode_pkce.ps1', 'demo_nonce_state_roundtrip.ps1', # OIDC Core — nonce→id_token verbatim, state echo 'demo_authz_negative_matrix.ps1', # RFC 6749 §4.1.2.1 — /authorize error contracts + open-redirect guard 'demo_auth_extras.ps1', # RFC 9207 iss + prompt=none + form_post + fragment 'demo_device_code.ps1', 'demo_device_code_ci.ps1', # RFC 8628 non-interactive shape + authorization_pending 'demo_token_exchange.ps1', 'demo_refresh_rotation.ps1', 'demo_introspect_revoke.ps1', 'demo_jwt.ps1', 'demo_userinfo.ps1', # RFC 6750 §3 — GET/POST + 400/401 + WWW-Authenticate challenge on errors 'demo_claim_probes.ps1', # OIDC §2/§5.1.1 + RFC 8176 — id_token claim shapes; §5.4 — asserts scope-derived PII is NOT in the id_token 'demo_claims_parameter.ps1', # OIDC §5.5 — the `claims` request parameter: userinfo/id_token members, essential/value/values, pinned-sub refusal 'demo_loopback_redirect.ps1', # RFC 8252 §7.3 — loopback redirect, port not compared; mostly negatives (localhost, path, scheme, off-box all refused) 'demo_prompt_max_age.ps1', # OIDC §3.1.2.1 prompt=login/consent/select_account + max_age (auth_time enforcement) 'demo_admin_scopes.ps1', # IdentityScopes granular admin probes (identity:read cross-path GET, identity:audit:read narrow) 'demo_sessions_admin.ps1', # admin /sessions list/revoke/all (identity:sessions:write identity:tokens:write + dryRun) 'demo_groups_roles_claims.ps1', # OIDC scope→claim: groups (direct + ancestors) + role (per-membership label rotation/removal) 'demo_application_allowed_groups.ps1', # β — per-application group whitelist (ApplicationProps.AllowedGroups) — gate sign-in at token endpoint with access_denied 'demo_admin_password_reset.ps1', # admin-side password reset (no OldPassword) + session revocation 'demo_admin_mfa.ps1', # admin TOTP enrollment through the management API: setup, confirm, status, regenerate, disable 'demo_admin_mfa_email.ps1', # admin e-mail MFA enrollment: the code e-mailed to the new address (GreenMail), confirm with mfa_state + setup token 'demo_claim_definitions.ps1', # S2 — global claim schema (required/type/regex) + admin CRUD + ClaimSchemaValidator gate 'demo_claim_definitions_per_app.ps1', # S2.4 — per-app required gate + EmitOnIdToken/AccessToken at token issuance 'demo_roles_registry.ps1', # B.3 — first-class Roles registry: org/app audience, direct + group→role, audience-scoped emit 'demo_role_permissions.ps1', # B.3 (permission picker) — role↔scope binding union'd into granted scope at token issuance 'demo_bootstrap_admin_role.ps1', # B.3 — bootstrap admin user is mirrored into the admin system role (regression on commit 12b2fcaf) 'demo_sessions_admin_browse.ps1', # S-track: GET /sessions (no userId) → admin-wide paginated browse; powers /admin/sessions default view 'demo_webhooks.ps1', # W1 — outbound webhook subscriptions: HMAC-SHA256 sign, retry, rotate-secret, filter, delete 'demo_session_lifecycle.ps1', # S-track: LastAccessedAt + idle/absolute timeouts + lazy/eager expiry + touch hook 'demo_acr_values.ps1', # OIDC Core §2 acr claim probe (single-factor=1, MFA=2) + acr_values voluntary contract 'demo_scim_bulk.ps1', # RFC 7644 §3.7 Bulk: POST + DELETE mix, failOnErrors early-stop, continue-on-error 'demo_scim_etag.ps1', # RFC 7644 §3.14 ETag concurrency: POST emits ETag, PUT If-Match honoured, 412 on stale 'demo_scim_enterprise.ps1', # RFC 7643 §4.3 Enterprise User: department/manager/employeeNumber, PATCH by URN, PUT-clears-extension 'demo_throttle_rfc6585.ps1', # RFC 6585 §4 + RFC 7231 §7.1.3 — 429 + Retry-After on rate-limit (KeyedThrottle.RejectOnOverflow) 'demo_jwks_rotation.ps1', # signing-key lifecycle: admin rotate/retire + live JWKS observability + old-token validation across the grace window # ── Self-service + MFA ──────────────────────────────────────────────────── 'demo_me_profile.ps1', 'demo_me_delete.ps1', # self-service DELETE /me — cascade revoke sessions/auths + soft-delete + login immutability + idempotency 'demo_password_change_negatives.ps1', # H10 password policy gate (wrong-old / weak / history / 401) 'demo_password_reset.ps1', # N-4 Session C anonymous forgot/reset + anti-enum + GreenMail intercept 'demo_me_sessions.ps1', 'demo_me_email_change.ps1', 'demo_mfa_totp.ps1', 'demo_mfa_disable_replace.ps1', # MFA disable + re-enrol mints a fresh secret 'demo_mfa_recovery_codes.ps1', # ── Provisioning ────────────────────────────────────────────────────────── 'demo_account_register_verify.ps1', 'demo_scim.ps1', # ── gRPC facade ─────────────────────────────────────────────────────────── 'demo_grpc_facade.ps1', # protocol + management surfaces via an independent @grpc/grpc-js client in a container # ── WS-Trust facade ─────────────────────────────────────────────────────── 'demo_soap_facade.ps1' # Issue/Validate/Cancel over raw SOAP envelopes, no tool to install ) $demos = $ordered | Where-Object { $path = Join-Path $here $_ if (-not (Test-Path $path)) { return $false } if ($Only -ne '' -and $_ -notmatch [regex]::Escape($Only)) { return $false } if (-not $IncludeInteractive -and $interactive -contains $_) { return $false } return $true } if (-not $demos -or $demos.Count -eq 0) { Write-Host "No demos matched filter '$Only'." -ForegroundColor Yellow exit 1 } Write-Host "=== running $($demos.Count) demo(s) ===" -ForegroundColor Cyan $results = New-Object System.Collections.Generic.List[object] $totalSw = [System.Diagnostics.Stopwatch]::StartNew() foreach ($demo in $demos) { $demoPath = Join-Path $here $demo $logPath = Join-Path $logDir ($demo -replace '\.ps1$', '.log') Write-Host "" Write-Host "--- $demo ---" -ForegroundColor Cyan # The demo runs in its own pwsh, its output streamed line by line to the console and the log, under a deadline: # past it the demo and everything it started are killed. $sw = [System.Diagnostics.Stopwatch]::StartNew() $psi = [System.Diagnostics.ProcessStartInfo]::new((Get-Process -Id $PID).Path) foreach ($a in '-NoLogo', '-NoProfile', '-File', $demoPath) { $psi.ArgumentList.Add($a) } $psi.UseShellExecute = $false $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.RedirectStandardInput = $true $proc = [System.Diagnostics.Process]::Start($psi) $proc.StandardInput.Close() $stderr = $proc.StandardError.ReadToEndAsync() $log = [System.IO.StreamWriter]::new($logPath, $false, [System.Text.UTF8Encoding]::new($false)) $timedOut = $false try { $deadline = [DateTime]::UtcNow.AddSeconds($DemoTimeoutSec) $next = $proc.StandardOutput.ReadLineAsync() while ($true) { $left = $deadline - [DateTime]::UtcNow if ($left -le [TimeSpan]::Zero -or -not $next.Wait($left)) { $timedOut = $true; break } $line = $next.Result if ($null -eq $line) { break } Write-Host $line $log.WriteLine($line) $next = $proc.StandardOutput.ReadLineAsync() } if ($timedOut) { $msg = "TIMEOUT: $demo still running after $DemoTimeoutSec s, killed" Write-Host $msg -ForegroundColor Red $log.WriteLine($msg) try { $proc.Kill($true) } catch { } } $proc.WaitForExit() if ($stderr.Wait(5000) -and $stderr.Result) { Write-Host $stderr.Result -ForegroundColor Red $log.Write($stderr.Result) } } finally { $log.Dispose() } $sw.Stop() $code = if ($timedOut) { 'timeout' } else { $proc.ExitCode } $status = if ($code -eq 0) { 'PASS' } else { "FAIL($code)" } $color = if ($code -eq 0) { 'Green' } else { 'Red' } Write-Host ("--- {0}: {1} in {2:N0} ms ---" -f $demo, $status, $sw.Elapsed.TotalMilliseconds) -ForegroundColor $color $results.Add([pscustomobject]@{ Demo = $demo Status = $status Ms = [int]$sw.Elapsed.TotalMilliseconds LogFile = $logPath }) if ($StopOnFail -and $code -ne 0) { Write-Host "StopOnFail set — aborting." -ForegroundColor Yellow break } } $totalSw.Stop() Write-Host "" Write-Host "=== summary ===" -ForegroundColor Cyan $results | Format-Table Demo, Status, Ms -AutoSize | Out-Host $passed = ($results | Where-Object { $_.Status -eq 'PASS' }).Count $failed = $results.Count - $passed $line = "{0}/{1} passed ({2} failed) in {3:N0} ms total" -f $passed, $results.Count, $failed, $totalSw.Elapsed.TotalMilliseconds $lineColor = if ($failed -eq 0) { 'Green' } else { 'Red' } Write-Host $line -ForegroundColor $lineColor Write-Host "logs: $logDir" -ForegroundColor DarkGray if ($failed -gt 0) { exit 1 } else { exit 0 }