#Requires -Version 7.0 <# .SYNOPSIS Checks staging OAuth discovery, or performs normal OAuth login and a bounded MCP read. .DESCRIPTION Run locally on the tester's machine. Manual browser login remains the default. The approved AutomaticTestLogin exception reads only the three fixed test users from Windows Credential Manager, automates the normal sign-in form and uses the same PKCE/callback checks. Codes, PKCE verifier and tokens stay in this process. The diagnostic token is revoked before completion. This does not authenticate a configured Codex MCP connection. Client registration creates one server-side OAuth client; successful registrations persist under server policy. .PARAMETER CheckOnly Check health, the unauthenticated MCP challenge and both metadata documents; no registration/login. .PARAMETER TokenRefreshCheck Check expiry, client binding, token rotation and revocation, with only the baseline customer read. .PARAMETER NoBrowser Print the authorization URL for the agent to open on this machine instead of starting a browser. .PARAMETER SchemaCheck Discover one custom master-data field and read at most three projected rows; emit metadata/counts only. .PARAMETER UserScenariosFor Run fixed Top-20 scenarios for one named test user using this same OAuth flow. Requires the repository's sibling McpUserScenarios.ps1. Does not authenticate a configured client. .PARAMETER AutomaticTestLogin Approved dummy users only; exact staging HTTPS by default, local Windows credentials, no browser UI. .PARAMETER OpenItemsCheck Separate bounded same-field sort/paging comparison in company 133515, JeppeR only. .PARAMETER QueryPagingContractCheck Fixed GL Account/Date/Voucher paging contract in dummy company 134547, JeppeR02 only. Uses repository siblings, records hashes/TraceIds and requires backend log verification. .PARAMETER JournalPagingCheck Fixed read-only journal paging/cache regression via the three-user coordinator. Without a coordination directory, only the separate JeppeR01 single-user supplement is allowed. .PARAMETER WorstPayerCounterCheck Five read-only calls in company 133515, JeppeR only. Compare ranking counters to complete open items. .PARAMETER SalesOrderReadCheck Fixed order 1001 read/paging/parent-key check in company 134548, JeppeR or JeppeR01 only. .EXAMPLE pwsh -File ./scripts/diagnostics/Test-McpOAuth.ps1 -CheckOnly .EXAMPLE pwsh -File ./scripts/diagnostics/Test-McpOAuth.ps1 -CompanyId 133515 -NoBrowser #> [CmdletBinding()] param( [uri]$BaseUrl = 'https://mcp-staging.uniconta.com', [ValidateRange(1, [int]::MaxValue)][int]$CompanyId = 133515, [switch]$CheckOnly, [switch]$TokenRefreshCheck, [switch]$SchemaCheck, [switch]$OpenItemsCheck, [ValidateSet('JeppeR', 'JeppeR01', 'JeppeR02')][string]$UserScenariosFor, [string]$ConcurrentRoundDirectory, [switch]$AgentTop20, [switch]$PaymentBehaviourCheck, [switch]$QueryPagingContractCheck, [switch]$JournalPagingCheck, [switch]$WorstPayerCounterCheck, [switch]$SalesOrderReadCheck, [switch]$AutomaticTestLogin, [switch]$AllowProductionAutomation, [switch]$NoBrowser, [ValidateRange(1, 10)][int]$LoginTimeoutMinutes = 10 ) [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) $ErrorActionPreference = 'Stop' $stage = 'configuration' $observations = [Collections.Generic.List[object]]::new() $token = $null; $clientId = $null; $listener = $null; $callbackConnection = $null $http = $null; $handler = $null; $failure = $null; $customers = @(); $revoked = $false $schemaResult = $null $scenarioResult = $null $automaticCallback = $null $refreshToken = $null; $refreshCheckResult = $null $cleanupFailure = $null $base = $BaseUrl.AbsoluteUri.TrimEnd('/') function Test-McpPeerAbort { if ($ConcurrentRoundDirectory -and (Test-Path -LiteralPath (Join-Path $ConcurrentRoundDirectory 'abort'))) { throw 'A concurrent participant failed; stopping this session for cleanup.' } } function Send-McpPeerAbort { if ($ConcurrentRoundDirectory) { try { $mark=[IO.File]::Open((Join-Path $ConcurrentRoundDirectory 'abort'), 'OpenOrCreate', 'Write', 'ReadWrite'); $mark.Dispose() } catch { } # Coordination I/O failure must never prevent token cleanup. } } function ConvertTo-Form($Fields) { ($Fields.GetEnumerator() | ForEach-Object { [uri]::EscapeDataString([string]$_.Key) + '=' + [uri]::EscapeDataString([string]$_.Value) }) -join '&' } function New-OAuthRandom { [Convert]::ToBase64String([Security.Cryptography.RandomNumberGenerator]::GetBytes(32)).TrimEnd('=').Replace('+', '-').Replace('/', '_') } function Invoke-OAuthHttp([string]$Method, [uri]$Uri, [string]$Body = '', [string]$ContentType = 'application/json', [switch]$Mcp, [string]$ToolName = 'query_entity', [string]$TraceParent = '', [string]$McpMethod = 'tools/call') { # Discovery must never move this diagnostic's credentials to another host or downgrade TLS. if ($Uri.GetLeftPart([UriPartial]::Authority) -cne $BaseUrl.GetLeftPart([UriPartial]::Authority)) { throw 'Discovery advertised an unexpected origin. No login was sent.' } $request = [Net.Http.HttpRequestMessage]::new([Net.Http.HttpMethod]::new($Method), $Uri) $response = $null $timer = [Diagnostics.Stopwatch]::StartNew() try { $request.Headers.Accept.ParseAdd('application/json') if ($Mcp) { $request.Headers.Accept.ParseAdd('text/event-stream') $request.Headers.Add('MCP-Protocol-Version', '2026-07-28') $request.Headers.Add('Mcp-Method', $McpMethod) if ($McpMethod -ceq 'tools/call') { $request.Headers.Add('Mcp-Name', $ToolName) } if ($TraceParent) { $request.Headers.Add('traceparent', $TraceParent) } $request.Headers.Authorization = [Net.Http.Headers.AuthenticationHeaderValue]::new('Bearer', $token) } if ($Body) { $request.Content = [Net.Http.StringContent]::new($Body, [Text.Encoding]::UTF8, $ContentType) } $response = $http.SendAsync($request).GetAwaiter().GetResult() $text = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() $challenge = $response.Headers.WwwAuthenticate.ToString() $observations.Add([pscustomobject]@{Stage=$stage;Uri=$Uri.GetLeftPart([UriPartial]::Path);HttpStatus=[int]$response.StatusCode;Milliseconds=$timer.ElapsedMilliseconds}) return @{Status=[int]$response.StatusCode;Body=$text;Challenge=$challenge;ContentType=$response.Content.Headers.ContentType.MediaType} } finally { if ($response) { $response.Dispose() }; $request.Dispose() } } function Read-OAuthJson($Response, [int]$ExpectedStatus = 200) { if ($Response.Status -ne $ExpectedStatus) { throw ('Unexpected HTTP status: ' + $Response.Status + '. See the failed stage and URI.') } try { $value = ConvertFrom-Json -InputObject $Response.Body -AsHashtable -NoEnumerate } catch { throw 'The endpoint did not return valid JSON.' } if ($value -isnot [Collections.IDictionary]) { throw 'Expected a JSON object.' } return $value } function Read-McpResult($Response) { if ($Response.Status -ne 200) { throw ('MCP HTTP status: ' + $Response.Status) } $messages = @($Response.Body) if ($Response.ContentType -eq 'text/event-stream') { $messages = @() foreach ($event in ($Response.Body -replace "`r`n", "`n") -split "`n`n") { $lines = @($event -split "`n" | Where-Object { $_.StartsWith('data:') } | ForEach-Object { $_.Substring(5).TrimStart(' ') }) if ($lines.Count -gt 0) { $messages += $lines -join "`n" } } } $envelopes = @() foreach ($message in $messages) { try { $item = ConvertFrom-Json -InputObject $message -AsHashtable -NoEnumerate } catch { throw 'MCP returned invalid JSON.' } if ($item -isnot [Collections.IDictionary] -or $item.jsonrpc -cne '2.0') { throw 'Unexpected JSON-RPC response.' } if ($item.id -eq 1) { $envelopes += ,$item } } if ($envelopes.Count -ne 1) { throw 'Expected exactly one matching JSON-RPC response.' } $envelope = $envelopes[0] if ($envelope.Contains('error')) { throw 'MCP returned a JSON-RPC error. Correlate this stage with the server log.' } if ($envelope.result.isError -eq $true) { throw 'MCP returned a tool error. Check company access and the server log at this time.' } $data = $envelope.result.structuredContent if ($data -isnot [Collections.IDictionary]) { throw 'MCP returned no structured result.' } return $data } function Read-CustomerResult($Response) { $data = Read-McpResult $Response if ($data.status -cne 'completed' -or $data.queryExecuted -ne $true) { throw 'The read was not completed; no approval is automatically accepted.' } if ($data.companyId -ne $CompanyId -or $data.entity -cne 'DebtorClient') { throw 'MCP returned an unexpected company or entity.' } if ($data.rows -isnot [array] -or $data.rows.Count -gt 3) { throw 'Unexpected customer rows or more than three rows.' } foreach ($row in $data.rows) { if ($row -isnot [Collections.IDictionary] -or -not $row.Contains('Account') -or $row.Account -isnot [string] -or [string]::IsNullOrWhiteSpace($row.Account)) { throw 'Customer row missing a valid string Account.' } # The adapter omits null properties. An unnamed customer is a valid row. if ($row.Contains('Name') -and $null -ne $row.Name -and $row.Name -isnot [string]) { throw 'Customer Name must be a string or null.' } } return $data } function Invoke-SchemaTool([string]$Tool, [hashtable]$Arguments) { if ($Tool -notin @('list_entities', 'describe_entity', 'query_entity')) { throw 'Diagnostic tool is not read-only.' } $script:stage = 'Bearer MCP schema check: ' + $Tool $payload = @{jsonrpc='2.0';id=1;method='tools/call';params=@{name=$Tool;arguments=$Arguments;_meta=@{'io.modelcontextprotocol/protocolVersion'='2026-07-28';'io.modelcontextprotocol/clientCapabilities'=@{}}}} | ConvertTo-Json -Depth 8 -Compress return Read-McpResult (Invoke-OAuthHttp POST ($base + '/mcp') $payload -Mcp -ToolName $Tool) } function Test-CompanySchema { $list = Invoke-SchemaTool 'list_entities' @{companyId=$CompanyId} if ($list.entities -isnot [array]) { throw 'Entity list was malformed.' } # Bounded discovery of ordinary master-data extensions; no broad history reads. foreach ($entity in @('DebtorClient', 'CreditorClient', 'GLAccountClient')) { $extended = $entity + 'User' if ($list.entities -cnotcontains $extended -or $list.entities -cnotcontains $entity) { continue } $standard = Invoke-SchemaTool 'describe_entity' @{companyId=$CompanyId;entity=$entity} $custom = Invoke-SchemaTool 'describe_entity' @{companyId=$CompanyId;entity=$extended} if ($standard.entity -cne $entity -or $custom.entity -cne $extended -or $standard.fields -isnot [array] -or $custom.fields -isnot [array]) { throw 'Entity schema was malformed.' } $extra = @($custom.fields | Where-Object { $_.name -is [string] -and $standard.fields.name -cnotcontains $_.name }) if ($extra.Count -eq 0) { continue } $field = [string]$extra[0].name if ($field.Contains(',') -or @($custom.fields.name) -cnotcontains 'Account' -or @($custom.fields.name) -cnotcontains 'Name') { throw 'Custom schema has no safe diagnostic projection.' } $allowed = @('Account', 'Name', $field) $rows = Invoke-SchemaTool 'query_entity' @{companyId=$CompanyId;entity=$extended;select=($allowed -join ',');orderBy='Account';skip=0;top=3} if ($rows.status -cne 'completed' -or $rows.queryExecuted -ne $true -or $rows.companyId -ne $CompanyId -or $rows.entity -cne $extended -or $rows.rows -isnot [array] -or $rows.rows.Count -gt 3) { throw 'Custom-field query did not complete in the approved company and scope.' } foreach ($row in $rows.rows) { if ($row -isnot [Collections.IDictionary] -or @($row.Keys | Where-Object { $allowed -cnotcontains $_ }).Count -gt 0) { throw 'Custom-field query returned unexpected fields.' } } # Only schema names/counts leave this function. All row values remain in memory. return [pscustomobject]@{CustomFieldsFound=$true;Entity=$extended;Field=$field;RowsChecked=$rows.rows.Count;QueryCompleted=$true} } return [pscustomobject]@{CustomFieldsFound=$false;EntitiesChecked=@('DebtorClient','CreditorClient','GLAccountClient');QueryCompleted=$false} } function Send-CallbackPage($Connection, [string]$Message, [int]$Status = 200) { $safe = [Net.WebUtility]::HtmlEncode($Message) $body = [Text.Encoding]::UTF8.GetBytes('Uniconta OAuth-kontrol

Uniconta OAuth-kontrol

' + $safe + '

Vend tilbage til agenten for testresultatet.

') $headers = [Text.Encoding]::ASCII.GetBytes("HTTP/1.1 $Status Response`r`nContent-Type: text/html; charset=utf-8`r`nContent-Length: $($body.Length)`r`nCache-Control: no-store`r`nReferrer-Policy: no-referrer`r`nContent-Security-Policy: default-src 'none'; style-src 'unsafe-inline'`r`nConnection: close`r`n`r`n") $stream = $Connection.GetStream() $stream.Write($headers, 0, $headers.Length); $stream.Write($body, 0, $body.Length); $stream.Flush() } try { if ($TokenRefreshCheck -and ($CheckOnly -or $SchemaCheck -or $SalesOrderReadCheck -or $WorstPayerCounterCheck -or $JournalPagingCheck -or $QueryPagingContractCheck -or $PaymentBehaviourCheck -or $AgentTop20 -or $OpenItemsCheck -or $ConcurrentRoundDirectory)) { throw 'Token refresh smoke check cannot be combined with another test round.' } if ($SalesOrderReadCheck -and (-not $AutomaticTestLogin -or $UserScenariosFor -cnotin @('JeppeR','JeppeR01') -or $ConcurrentRoundDirectory -or $WorstPayerCounterCheck -or $JournalPagingCheck -or $QueryPagingContractCheck -or $AgentTop20 -or $OpenItemsCheck -or $PaymentBehaviourCheck -or $CheckOnly -or $SchemaCheck -or $NoBrowser)) { throw 'Sales order regression requires only JeppeR or JeppeR01 automatic login in company 134548.' } if ($WorstPayerCounterCheck -and ($UserScenariosFor -cne 'JeppeR' -or $ConcurrentRoundDirectory -or $JournalPagingCheck -or $QueryPagingContractCheck -or $AgentTop20 -or $OpenItemsCheck -or $PaymentBehaviourCheck -or $CheckOnly -or $SchemaCheck)) { throw 'Worst-payer counter regression requires JeppeR/company 133515 without other scenarios.' } if ($JournalPagingCheck -and (-not $AutomaticTestLogin -or -not $UserScenariosFor -or (-not $ConcurrentRoundDirectory -and $UserScenariosFor -cne 'JeppeR01') -or $QueryPagingContractCheck -or $AgentTop20 -or $OpenItemsCheck -or $PaymentBehaviourCheck -or $CheckOnly -or $SchemaCheck -or $NoBrowser)) { throw 'Journal paging requires approved automatic three-user coordination or the separate JeppeR01-only supplement, without other scenarios.' } if ($QueryPagingContractCheck -and ($UserScenariosFor -cne 'JeppeR02' -or $ConcurrentRoundDirectory -or $AgentTop20 -or $OpenItemsCheck -or $PaymentBehaviourCheck -or $CheckOnly -or $SchemaCheck)) { throw 'Query paging contract requires JeppeR02 in company 134547 outside other rounds.' } if ($PaymentBehaviourCheck -and ($UserScenariosFor -cne 'JeppeR01' -or $ConcurrentRoundDirectory -or $AgentTop20 -or $OpenItemsCheck -or $CheckOnly -or $SchemaCheck)) { throw 'Payment behaviour regression requires JeppeR01 in company 134548 outside other rounds.' } if ($AgentTop20 -and (-not $AutomaticTestLogin -or -not $ConcurrentRoundDirectory -or $OpenItemsCheck -or $CheckOnly -or $SchemaCheck)) { throw 'Agent Top-20 requires automatic test login and a concurrent round directory.' } if ($OpenItemsCheck -and ($UserScenariosFor -cne 'JeppeR' -or $ConcurrentRoundDirectory -or $CheckOnly -or $SchemaCheck)) { throw 'Open-items comparison requires JeppeR, company 133515, outside the concurrent round.' } if ($AutomaticTestLogin) { if (-not $UserScenariosFor -or $CheckOnly -or $SchemaCheck -or $NoBrowser) { throw 'Automatic test login requires a fixed scenario user and no other login mode.' } if ($base -cne 'https://mcp-staging.uniconta.com' -and -not ($base -ceq 'https://mcp.uniconta.com' -and $AllowProductionAutomation)) { throw 'Automatic test login targets exact staging HTTPS by default. Production requires explicit BaseUrl and AllowProductionAutomation.' } . (Join-Path $PSScriptRoot 'McpTestCredentials.ps1') . (Join-Path $PSScriptRoot 'McpAutomaticLogin.ps1') # Fail before registration/network traffic if local setup is incomplete. $probePassword = Get-McpTestPassword $UserScenariosFor $BaseUrl $probePassword.Dispose(); $probePassword=$null } if ($UserScenariosFor -and ($CheckOnly -or $SchemaCheck)) { throw 'Choose user scenarios, discovery-only or schema check.' } if ($ConcurrentRoundDirectory -and (-not $UserScenariosFor -or -not (Test-Path -LiteralPath $ConcurrentRoundDirectory -PathType Container))) { throw 'Concurrent scenarios require a named user and an existing fresh coordination directory.' } if ($UserScenariosFor) { $CompanyId = switch ($UserScenariosFor) { 'JeppeR' { 133515 } 'JeppeR01' { 134548 } 'JeppeR02' { 134547 } } } if ($CheckOnly -and $SchemaCheck) { throw 'Choose discovery-only or schema check.' } if ($BaseUrl.UserInfo -or $BaseUrl.Query -or $BaseUrl.Fragment -or $BaseUrl.AbsolutePath -ne '/' -or ($BaseUrl.Scheme -ne 'https' -and -not ($BaseUrl.Scheme -eq 'http' -and $BaseUrl.IsLoopback))) { throw 'BaseUrl must be an HTTPS origin without credentials/path/query; HTTP is allowed only for loopback tests.' } $handler = [Net.Http.HttpClientHandler]::new(); $handler.AllowAutoRedirect = $false $http = [Net.Http.HttpClient]::new($handler); $http.Timeout = [TimeSpan]::FromSeconds(30) $stage = 'health' $health = Read-OAuthJson (Invoke-OAuthHttp GET ($base + '/health')) if ($health.status -cne 'ok') { throw 'Health did not confirm status ok.' } $stage = 'MCP OAuth challenge' $challengeResponse = Invoke-OAuthHttp GET ($base + '/mcp') $metadataMatch = [regex]::Match($challengeResponse.Challenge, 'resource_metadata="([^"]+)"') if ($challengeResponse.Status -ne 401 -or $challengeResponse.Challenge -notmatch '(?i)^Bearer\b' -or -not $metadataMatch.Success) { throw 'Expected HTTP 401 with a Bearer resource_metadata URL, not a Basic-login prompt.' } $stage = 'protected-resource metadata' $resource = Read-OAuthJson (Invoke-OAuthHttp GET ([uri]$metadataMatch.Groups[1].Value)) if ($resource.resource -cne ($base + '/mcp') -or @($resource.authorization_servers) -notcontains $base) { throw 'Resource metadata does not identify the expected MCP endpoint and issuer.' } $stage = 'authorization-server metadata' $metadata = Read-OAuthJson (Invoke-OAuthHttp GET ($base + '/.well-known/oauth-authorization-server')) if ($metadata.issuer -cne $base -or $metadata.authorization_endpoint -cne ($base + '/authorize') -or $metadata.token_endpoint -cne ($base + '/token') -or $metadata.registration_endpoint -cne ($base + '/register') -or $metadata.revocation_endpoint -cne ($base + '/revoke') -or @($metadata.code_challenge_methods_supported) -notcontains 'S256') { throw 'OAuth metadata has an unexpected issuer/endpoint or no PKCE S256 support.' } if (-not $CheckOnly) { $listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0); $listener.Start() $port = ([Net.IPEndPoint]$listener.LocalEndpoint).Port $callbackPath = '/oauth/callback/' + [Guid]::NewGuid().ToString('n') $redirect = 'http://127.0.0.1:' + $port + $callbackPath $verifier = New-OAuthRandom; $state = New-OAuthRandom $pkce = [Convert]::ToBase64String([Security.Cryptography.SHA256]::HashData([Text.Encoding]::ASCII.GetBytes($verifier))).TrimEnd('=').Replace('+','-').Replace('/','_') $stage = 'client registration' $registration = Read-OAuthJson (Invoke-OAuthHttp POST ([uri]$metadata.registration_endpoint) (@{redirect_uris=@($redirect);client_name='Uniconta OAuth diagnostic'} | ConvertTo-Json -Compress)) 201 $clientId = $registration.client_id if (-not $clientId) { throw 'Registration returned no client id.' } $authorize = $metadata.authorization_endpoint + '?' + (ConvertTo-Form @{client_id=$clientId;redirect_uri=$redirect;response_type='code';code_challenge=$pkce;code_challenge_method='S256';state=$state}) if ($AutomaticTestLogin) { $automaticCallback = Invoke-McpAutomaticLogin $authorize $redirect $UserScenariosFor } else { [pscustomobject]@{Status='waiting_for_browser_login';AuthorizeUrl=$authorize;CompanyId=$CompanyId;ExpiresInMinutes=$LoginTimeoutMinutes} | ConvertTo-Json -Compress [Console]::Out.Flush() if (-not $NoBrowser) { Start-Process -FilePath $authorize } } $stage = 'browser login and callback' $deadline = [DateTimeOffset]::UtcNow.AddMinutes($LoginTimeoutMinutes) $callbackQuery = $null while ([DateTimeOffset]::UtcNow -lt $deadline) { # A successful automatic sign-in already created a server-side authorization. # Validate/redeem its callback even if a peer failed meanwhile, then revoke it. if (-not $automaticCallback) { Test-McpPeerAbort } if (-not $listener.Pending()) { Start-Sleep -Milliseconds 100; continue } $candidate = $listener.AcceptTcpClient() $reader = $null try { $stream = $candidate.GetStream(); $stream.ReadTimeout = 5000 $reader = [IO.StreamReader]::new($stream, [Text.Encoding]::ASCII, $false, 1024, $true) $firstLine = $reader.ReadLine() if ($firstLine -notmatch '^GET (/\S*) HTTP/1\.[01]$') { Send-CallbackPage $candidate 'Uventet request.' 400; continue } $callbackUri = [uri]('http://127.0.0.1:' + $port + $Matches[1]) if ($callbackUri.AbsolutePath -cne $callbackPath) { Send-CallbackPage $candidate 'Forkert callback-adresse.' 404; continue } $query = @{} $valid = $true foreach ($part in $callbackUri.Query.TrimStart('?').Split('&')) { $pair = $part.Split('=', 2) $key = [uri]::UnescapeDataString($pair[0]) if ($query.ContainsKey($key)) { $valid = $false; break } $query[$key] = if ($pair.Length -eq 2) { [uri]::UnescapeDataString($pair[1].Replace('+',' ')) } else { '' } } if (-not $valid -or $query.ContainsKey('error') -or $query.state -cne $state -or [string]::IsNullOrWhiteSpace($query.code)) { Send-CallbackPage $candidate 'OAuth-state eller kode blev afvist. Brug det oprindelige login-link.' 400 if ($AutomaticTestLogin) { throw 'Automatic callback state or code rejected.' } continue } $callbackQuery = $query; $callbackConnection = $candidate; $candidate = $null; break } catch [IO.IOException] { # A disconnected browser/probe must not abort the pending login. } finally { if ($reader) { $reader.Dispose() }; if ($candidate) { $candidate.Dispose() } } } if (-not $callbackQuery) { throw 'No valid browser callback before the login deadline. Start a fresh flow.' } $stage = 'authorization-code exchange' $tokenResult = Read-OAuthJson (Invoke-OAuthHttp POST ([uri]$metadata.token_endpoint) (ConvertTo-Form @{grant_type='authorization_code';code=$callbackQuery.code;client_id=$clientId;redirect_uri=$redirect;code_verifier=$verifier}) 'application/x-www-form-urlencoded') $token = $tokenResult.access_token if ($TokenRefreshCheck) { $refreshToken = $tokenResult.refresh_token; $expiresIn = $tokenResult.expires_in } $tokenResult = $null if (-not $token) { throw 'Code exchange returned no access token.' } if ($TokenRefreshCheck) { if (-not $refreshToken -or $expiresIn -le 0 -or $expiresIn -gt 3600) { throw 'Missing refresh token or invalid expiry.' } $stage = 'reject refresh from another client' $wrongClient = Invoke-OAuthHttp POST ($base + '/token') (ConvertTo-Form @{grant_type='refresh_token';refresh_token=$refreshToken;client_id=(New-OAuthRandom)}) 'application/x-www-form-urlencoded' $denial = Read-OAuthJson $wrongClient 400 if ($denial.error -cne 'invalid_grant') { throw 'Wrong-client refresh was not refused.' } $stage = 'refresh diagnostic token' $renewed = Read-OAuthJson (Invoke-OAuthHttp POST ($base + '/token') (ConvertTo-Form @{grant_type='refresh_token';refresh_token=$refreshToken;client_id=$clientId}) 'application/x-www-form-urlencoded') if (-not $renewed.access_token -or -not $renewed.refresh_token -or $renewed.access_token -ceq $token -or $renewed.refresh_token -ceq $refreshToken -or $renewed.expires_in -le 0 -or $renewed.expires_in -gt 3600) { throw 'Refresh did not return a rotated token pair with expiry.' } $oldToken = $token $refreshToken = $renewed.refresh_token try { $stage = 'reject rotated access token' $oldProbe = Invoke-OAuthHttp GET ($base + '/mcp') -Mcp if ($oldProbe.Status -ne 401) { throw 'Rotated access token was not rejected.' } } finally { $token = $renewed.access_token; $renewed=$null; $oldToken=$null } $refreshCheckResult = [pscustomobject]@{ClientBinding=$true;Rotation=$true;OldAccessRejected=$true;RevokedRefreshRejected=$false} } Test-McpPeerAbort if ($UserScenariosFor -and -not $TokenRefreshCheck) { . (Join-Path $PSScriptRoot 'McpUserScenarios.ps1') if ($SalesOrderReadCheck) { . (Join-Path $PSScriptRoot 'McpSalesOrderReadCheck.ps1') Invoke-McpSalesOrderReadCheck $UserScenariosFor } elseif ($WorstPayerCounterCheck) { . (Join-Path $PSScriptRoot 'McpWorstPayerCounterCheck.ps1') Invoke-McpWorstPayerCounterCheck } elseif ($JournalPagingCheck) { Send-CallbackPage $callbackConnection 'Testlogin modtaget. Journaltesten kører; tokenet tilbagekaldes bagefter.' $callbackConnection.Dispose(); $callbackConnection=$null . (Join-Path $PSScriptRoot 'McpConcurrentScenarios.ps1') . (Join-Path $PSScriptRoot 'McpJournalPagingCheck.ps1') Invoke-McpJournalPagingCheck $UserScenariosFor $ConcurrentRoundDirectory } elseif ($QueryPagingContractCheck) { . (Join-Path $PSScriptRoot 'McpQueryPagingContract.ps1') Invoke-McpQueryPagingContract } elseif ($PaymentBehaviourCheck) { . (Join-Path $PSScriptRoot 'McpPaymentBehaviourCheck.ps1') Invoke-McpPaymentBehaviourCheck } elseif ($OpenItemsCheck) { . (Join-Path $PSScriptRoot 'McpOpenItemsComparison.ps1') Invoke-McpOpenItemsComparison } elseif ($ConcurrentRoundDirectory) { # Finish the browser callback now: keep this token only in process memory while # the other humans sign in. The final outcome is reported to the agent. Send-CallbackPage $callbackConnection ('Login modtaget for '+$UserScenariosFor+'. Sessionen venter på de andre brugere. Agenten gennemfører testen og tilbagekalder tokenet bagefter.') $callbackConnection.Dispose(); $callbackConnection = $null . (Join-Path $PSScriptRoot 'McpConcurrentScenarios.ps1') if ($AgentTop20) { . (Join-Path $PSScriptRoot 'McpTop20Agent.ps1') Invoke-McpTop20Agent $UserScenariosFor $ConcurrentRoundDirectory } else { Invoke-McpConcurrentUserScenarios $UserScenariosFor $ConcurrentRoundDirectory } } else { Invoke-McpUserScenarios $UserScenariosFor } if ($scenarioResult.HasErrors) { throw 'One or more user scenarios failed. See UserScenarios and correlate its TraceId with server logs.' } } elseif ($SchemaCheck) { $schemaResult = Test-CompanySchema } else { $stage = 'Bearer MCP customer query' $body = @{jsonrpc='2.0';id=1;method='tools/call';params=@{name='query_entity';arguments=@{companyId=$CompanyId;entity='DebtorClient';select='Account,Name';orderBy='Account';skip=0;top=3};_meta=@{'io.modelcontextprotocol/protocolVersion'='2026-07-28';'io.modelcontextprotocol/clientCapabilities'=@{}}}} | ConvertTo-Json -Depth 8 -Compress $data = Read-CustomerResult (Invoke-OAuthHttp POST ($base + '/mcp') $body -Mcp) $customers = @($data.rows | ForEach-Object { [pscustomobject]@{Account=[string]$_.Account;Name=[string]$_.Name} }) } } } catch { # Report only local diagnostic messages, never response bodies, callback URLs or tokens. $cause = $_.Exception.GetBaseException() $safeError = if ($AutomaticTestLogin) { 'Automatic test failed; inspect the stage and correlated server logs. No response details are saved.' } elseif ($cause -is [Net.Http.HttpRequestException]) { 'HTTPS request failed: ' + $cause.HttpRequestError } elseif ($cause -is [OperationCanceledException]) { 'HTTP request timed out (30 seconds).' } elseif ($cause -is [Management.Automation.RuntimeException]) { $cause.Message } else { 'Diagnostic failed: ' + $cause.GetType().Name } $failure = [pscustomobject]@{Stage=$stage;Error=$safeError} } finally { if ($failure -and $ConcurrentRoundDirectory -and (Test-Path -LiteralPath $ConcurrentRoundDirectory -PathType Container)) { Send-McpPeerAbort } if ($token -and $clientId) { $stage = 'revoke diagnostic token' try { $revocation = Invoke-OAuthHttp POST ($base + '/revoke') (ConvertTo-Form @{token=$token;client_id=$clientId}) 'application/x-www-form-urlencoded' if ($revocation.Status -ne 200) { throw 'Token revocation was not confirmed.' } $stage = 'verify revoked diagnostic token' $revokedProbe = Invoke-OAuthHttp GET ($base + '/mcp') -Mcp if ($revokedProbe.Status -ne 401) { throw 'Revoked diagnostic token was not rejected.' } $revoked = $true if ($TokenRefreshCheck -and $refreshToken) { $stage = 'verify revoked refresh token' $refused = Read-OAuthJson (Invoke-OAuthHttp POST ($base + '/token') (ConvertTo-Form @{grant_type='refresh_token';refresh_token=$refreshToken;client_id=$clientId}) 'application/x-www-form-urlencoded') 400 if ($refused.error -cne 'invalid_grant') { throw 'Revoked refresh token was not rejected.' } if ($refreshCheckResult) { $refreshCheckResult.RevokedRefreshRejected=$true } } } catch { $cleanupFailure = [pscustomobject]@{Stage=$stage;Error='Diagnostic token revocation/401 verification failed.'} if (-not $failure) { $failure = $cleanupFailure } Send-McpPeerAbort } } if ($callbackConnection) { try { $message = if ($failure) { 'Kontrollen fejlede ved ' + $failure.Stage + '. Se agentens testresultat.' } elseif ($UserScenariosFor) { 'Brugerscenarierne er gennemført. Testtokenet er tilbagekaldt og afvist med HTTP 401. Se agentens svar og begrænsninger.' } elseif ($SchemaCheck) { "Dit manuelle OAuth-login og den læsende schemakontrol i firma $CompanyId lykkedes. Testtokenet er tilbagekaldt og afvist med HTTP 401. Dette logger ikke din faste MCP-forbindelse ind." } else { "Dit manuelle OAuth-login og kundeudtræk i firma $CompanyId lykkedes. Testtokenet er tilbagekaldt. Dette er en lokal test, som ikke logger din faste MCP-forbindelse ind." } Send-CallbackPage $callbackConnection $message $(if ($failure) { 500 } else { 200 }) } catch {} finally { $callbackConnection.Dispose() } } $token=$null; $refreshToken=$null; $verifier=$null; $callbackQuery=$null; $body=$null $authorize=$null; $state=$null; $registration=$null; $tokenResult=$null if ($automaticCallback) { $automaticCallback.Dispose() } if ($listener) { $listener.Stop() }; if ($http) { $http.Dispose() }; if ($handler) { $handler.Dispose() } } [pscustomobject]@{ Status=$(if ($failure) {'failed'} else {'ok'}); CheckedAt=[DateTimeOffset]::UtcNow.ToString('o') Mode=$(if ($CheckOnly) {'discovery_only'} elseif ($AutomaticTestLogin) {'automatic_test_oauth'} else {'manual_browser_oauth'}); Endpoint=$base + '/mcp' CompanyId=$(if ($CheckOnly) {$null} else {$CompanyId}); Stages=$observations.ToArray() Failure=$failure; CleanupFailure=$cleanupFailure; Customers=$customers; SchemaCheck=$schemaResult; UserScenarios=$scenarioResult; DiagnosticTokenRevoked=$revoked TokenRefreshCheck=$refreshCheckResult } | ConvertTo-Json -Depth 12 if ($failure) { exit 1 }