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)