@@ -312,56 +312,79 @@ public async Task ExternalLike_QrOnlyFreshTray_RequiresExplicitDeviceApproval()
312312 var env = GatewayTokenEnv ( gateway . SharedGatewayToken ) ;
313313 var pendingBefore = await ReadPendingDeviceRequestIdsAsync ( ) ;
314314 var pendingNodeBefore = await ReadPendingNodeRequestIdsAsync ( ) ;
315+ var handledDeviceRequestIds = new HashSet < string > ( StringComparer . Ordinal ) ;
316+ var handledNodeRequestIds = new HashSet < string > ( StringComparer . Ordinal ) ;
315317 var setupCode = await MintRealGatewaySetupCodeAsync ( env , "mint real gateway setup code for external-like tray" ) ;
318+ IsolatedTrayInstance ? externalTray = null ;
319+ Exception ? testFailure = null ;
316320
317- await using var externalTray = await IsolatedTrayInstance . StartAsync ( _fixture . ArtifactDir , "external-qr-only" ) ;
318- using var applyDoc = await externalTray . Client . CallToolExpectSuccessAsync (
319- "app.connection.applySetupCode" ,
320- new { setupCode } ) ;
321- var apply = applyDoc . RootElement ;
322- Console . WriteLine ( $ "[E2E] external-like applySetupCode response: { apply . GetRawText ( ) } " ) ;
323- Assert . Equal ( "Success" , apply . GetProperty ( "outcome" ) . GetString ( ) ) ;
324-
325- var active = externalTray . ReadActiveGatewayRecord ( ) ;
326- Assert . NotNull ( active . GatewayUrl ) ;
327- Assert . Contains ( $ ": { _fixture . GatewayPort } " , active . GatewayUrl , StringComparison . Ordinal ) ;
328- Assert . True ( string . IsNullOrWhiteSpace ( active . SharedGatewayToken ) ,
329- "QR-only external-like onboarding must not invent or persist the shared gateway token." ) ;
330-
331- var credentials = externalTray . ReadCredentialState ( ) ;
332- Assert . False ( credentials . HasNodeToken , "QR-only external-like onboarding should wait for explicit device approval before persisting a node token." ) ;
333- Assert . False ( credentials . HasOperatorToken ,
334- "Current LKG QR-only external-like onboarding does not provide an admin operator token.") ;
335- Assert . True ( credentials . HasBootstrapToken ,
336- "Bootstrap remains as recovery material while explicit approval is pending .") ;
337-
338- using var statusDoc = await externalTray . Client . CallToolExpectSuccessAsync ( "app.status ") ;
339- var status = statusDoc . RootElement ;
340- var rawStatus = status . GetRawText ( ) ;
341- Assert . False ( status . GetProperty ( "nodeConnected" ) . GetBoolean ( ) , $ "Expected nodeConnected=false before approval; status= { rawStatus } " ) ;
342- Assert . False ( status . GetProperty ( "nodePaired" ) . GetBoolean ( ) , $ "Expected nodePaired=false before approval; status= { rawStatus } " ) ;
343- Assert . True ( status . TryGetProperty ( "operatorScopes" , out var scopes ) , $ "operatorScopes missing: { rawStatus } ") ;
344- Assert . DoesNotContain ( ReadStringArray ( scopes ) , scope => string . Equals ( scope , "operator.admin" , StringComparison . OrdinalIgnoreCase ) ) ;
345-
346- var requestId = await WaitForFirstPendingDeviceRequestIdAsync ( pendingBefore ) ;
347- Assert . False ( string . IsNullOrWhiteSpace ( requestId ) ) ;
348-
349- using var dashboardDoc = await externalTray . Client . CallToolExpectSuccessAsync ( "app.dashboard.url" ) ;
350- var dashboard = dashboardDoc . RootElement ;
351- Assert . Equal ( "record.BootstrapToken" , dashboard . GetProperty ( "credentialSource" ) . GetString ( ) ) ;
352- Assert . False ( dashboard . GetProperty ( "usesSharedGatewayToken" ) . GetBoolean ( ) ) ;
353- Assert . False ( dashboard . GetProperty ( "hasTokenQuery " ) . GetBoolean ( ) ) ;
354-
355- using var rejectDoc = await RejectDevicePairingFromConnectionPageAsync ( requestId ) ;
356- Console . WriteLine ( $ "[E2E] rejected external-like pending device request via Connection page: { rejectDoc . RootElement . GetRawText ( ) } " ) ;
357-
358- var nodeRequests = await ReadNewPendingNodeApprovalsUntilAsync (
359- pendingNodeBefore ,
360- TimeSpan . FromSeconds ( 10 ) ) ;
361- foreach ( var nodeRequest in nodeRequests )
321+ try
322+ {
323+ externalTray = await IsolatedTrayInstance . StartAsync ( _fixture . ArtifactDir , "external-qr-only" ) ;
324+ using var applyDoc = await externalTray . Client . CallToolExpectSuccessAsync (
325+ "app.connection.applySetupCode" ,
326+ new { setupCode } ) ;
327+ var apply = applyDoc . RootElement ;
328+ Console . WriteLine ( $ "[E2E] external-like applySetupCode response: { apply . GetRawText ( ) } " ) ;
329+ Assert . Equal ( "Success" , apply . GetProperty ( "outcome" ) . GetString ( ) ) ;
330+
331+ var active = externalTray . ReadActiveGatewayRecord ( ) ;
332+ Assert . NotNull ( active . GatewayUrl ) ;
333+ Assert . Contains ( $ ": { _fixture . GatewayPort } " , active . GatewayUrl , StringComparison . Ordinal ) ;
334+ Assert . True ( string . IsNullOrWhiteSpace ( active . SharedGatewayToken ) ,
335+ "QR-only external-like onboarding must not invent or persist the shared gateway token." ) ;
336+
337+ var credentials = externalTray . ReadCredentialState ( ) ;
338+ Assert . False ( credentials . HasNodeToken , " QR-only external-like onboarding should wait for explicit device approval before persisting a node token.") ;
339+ Assert . False ( credentials . HasOperatorToken ,
340+ "Current LKG QR-only external-like onboarding does not provide an admin operator token .") ;
341+ Assert . True ( credentials . HasBootstrapToken ,
342+ "Bootstrap remains as recovery material while explicit approval is pending. ") ;
343+
344+ using var statusDoc = await externalTray . Client . CallToolExpectSuccessAsync ( "app.status" ) ;
345+ var status = statusDoc . RootElement ;
346+ var rawStatus = status . GetRawText ( ) ;
347+ Assert . False ( status . GetProperty ( "nodeConnected" ) . GetBoolean ( ) , $ "Expected nodeConnected=false before approval; status= { rawStatus } ") ;
348+ Assert . False ( status . GetProperty ( "nodePaired" ) . GetBoolean ( ) , $ "Expected nodePaired=false before approval; status= { rawStatus } " ) ;
349+ Assert . True ( status . TryGetProperty ( "operatorScopes" , out var scopes ) , $ "operatorScopes missing: { rawStatus } " ) ;
350+ Assert . DoesNotContain ( ReadStringArray ( scopes ) , scope => string . Equals ( scope , "operator.admin" , StringComparison . OrdinalIgnoreCase ) ) ;
351+
352+ var requestId = await WaitForFirstPendingDeviceRequestIdAsync ( pendingBefore ) ;
353+ Assert . False ( string . IsNullOrWhiteSpace ( requestId ) ) ;
354+
355+ using var dashboardDoc = await externalTray . Client . CallToolExpectSuccessAsync ( "app. dashboard.url" ) ;
356+ var dashboard = dashboardDoc . RootElement ;
357+ Assert . Equal ( "record.BootstrapToken" , dashboard . GetProperty ( "credentialSource " ) . GetString ( ) ) ;
358+ Assert . False ( dashboard . GetProperty ( "usesSharedGatewayToken" ) . GetBoolean ( ) ) ;
359+ Assert . False ( dashboard . GetProperty ( "hasTokenQuery" ) . GetBoolean ( ) ) ;
360+
361+ using var rejectDoc = await RejectDevicePairingFromConnectionPageAsync ( requestId ) ;
362+ handledDeviceRequestIds . Add ( requestId ) ;
363+ Console . WriteLine ( $ "[E2E] rejected external-like pending device request via Connection page: { rejectDoc . RootElement . GetRawText ( ) } " ) ;
364+ }
365+ catch ( Exception ex )
362366 {
363- using var rejectNodeDoc = await RejectNodePairingFromConnectionPageAsync ( nodeRequest . RequestId ) ;
364- Console . WriteLine ( $ "[E2E] rejected external-like pending node-trust request via Connection page: { rejectNodeDoc . RootElement . GetRawText ( ) } ") ;
367+ testFailure = ex ;
368+ throw ;
369+ }
370+ finally
371+ {
372+ if ( externalTray is not null )
373+ await externalTray . DisposeAsync ( ) ;
374+
375+ try
376+ {
377+ await RejectNewPendingApprovalsUntilQuietAsync (
378+ pendingBefore ,
379+ pendingNodeBefore ,
380+ handledDeviceRequestIds ,
381+ handledNodeRequestIds ,
382+ TimeSpan . FromSeconds ( 45 ) ) ;
383+ }
384+ catch ( Exception ex ) when ( testFailure is not null )
385+ {
386+ Console . WriteLine ( $ "[E2E] Cleanup after failed external QR-only tray test also failed: { ex } ") ;
387+ }
365388 }
366389 }
367390
@@ -402,34 +425,66 @@ public async Task ExternalLike_FreshTray_SharedTokenFlow_PairsOperatorAndNode()
402425 var sharedGatewayToken = RequireSharedGatewayToken ( gateway . SharedGatewayToken ) ;
403426 var pendingBefore = await ReadPendingDeviceRequestIdsAsync ( ) ;
404427 var pendingNodeBefore = await ReadPendingNodeRequestIdsAsync ( ) ;
428+ var handledDeviceRequestIds = new HashSet < string > ( StringComparer . Ordinal ) ;
429+ var handledNodeRequestIds = new HashSet < string > ( StringComparer . Ordinal ) ;
430+ IsolatedTrayInstance ? externalTray = null ;
431+ Exception ? testFailure = null ;
405432
406- await using var externalTray = await IsolatedTrayInstance . StartAsync ( _fixture . ArtifactDir , "external-shared-token" ) ;
407- using var connectDoc = await externalTray . Client . CallToolExpectSuccessAsync (
408- "app.connection.connectSharedToken" ,
409- new { gatewayUrl = gateway . GatewayUrl , token = sharedGatewayToken } ) ;
410- var connect = connectDoc . RootElement ;
411- Console . WriteLine ( $ "[E2E] external shared-token connect response: { connect . GetRawText ( ) } ") ;
412- Assert . Equal ( "Success" , connect . GetProperty ( "outcome" ) . GetString ( ) ) ;
433+ try
434+ {
435+ externalTray = await IsolatedTrayInstance . StartAsync ( _fixture . ArtifactDir , "external-shared-token" ) ;
436+ using var connectDoc = await externalTray . Client . CallToolExpectSuccessAsync (
437+ "app.connection.connectSharedToken" ,
438+ new { gatewayUrl = gateway . GatewayUrl , token = sharedGatewayToken } ) ;
439+ var connect = connectDoc . RootElement ;
440+ Console . WriteLine ( $ "[E2E] external shared-token connect response: { connect . GetRawText ( ) } ") ;
441+ Assert . Equal ( "Success" , connect . GetProperty ( "outcome" ) . GetString ( ) ) ;
442+
443+ await ApproveNewPendingDeviceRequestsUntilReadyAsync ( pendingBefore , handledDeviceRequestIds , externalTray ) ;
444+ var nodeRequest = Assert . Single ( await ReadNewPendingNodeApprovalsUntilAsync (
445+ pendingNodeBefore ,
446+ TimeSpan . FromSeconds ( 30 ) ) ) ;
447+ using ( var approve = await ApproveNodePairingFromConnectionPageAsync ( nodeRequest . RequestId ) )
448+ {
449+ handledNodeRequestIds . Add ( nodeRequest . RequestId ) ;
450+ Console . WriteLine ( $ "[E2E] explicitly approved external node-trust request via Connection page: { approve . RootElement . GetRawText ( ) } ") ;
451+ }
413452
414- await ApproveNewPendingDeviceRequestsUntilReadyAsync ( pendingBefore , externalTray ) ;
415- var nodeRequest = Assert . Single ( await ReadNewPendingNodeApprovalsUntilAsync (
416- pendingNodeBefore ,
417- TimeSpan . FromSeconds ( 30 ) ) ) ;
418- using ( var approve = await ApproveNodePairingFromConnectionPageAsync ( nodeRequest . RequestId ) )
453+ using var reconnectNode = await externalTray . Client . CallToolExpectSuccessAsync ( "app.connection.reconnectNode" ) ;
454+ Assert . True ( reconnectNode . RootElement . GetProperty ( "reconnected" ) . GetBoolean ( ) ) ;
455+ await externalTray . WaitForConnectionReady ( TimeSpan . FromSeconds ( 120 ) ) ;
456+ await WaitForNodeEffectiveStateAsync (
457+ externalTray . Client ,
458+ nodeRequest . NodeId ,
459+ new CapabilitiesConfig { Tts = false } ,
460+ TimeSpan . FromSeconds ( 90 ) ) ;
461+ AssertExternalTrayDurablePairing ( externalTray ) ;
462+ await AssertGatewayCliStateHealthy ( ) ;
463+ }
464+ catch ( Exception ex )
419465 {
420- Console . WriteLine ( $ "[E2E] explicitly approved external node-trust request via Connection page: { approve . RootElement . GetRawText ( ) } ") ;
466+ testFailure = ex ;
467+ throw ;
421468 }
469+ finally
470+ {
471+ if ( externalTray is not null )
472+ await externalTray . DisposeAsync ( ) ;
422473
423- using var reconnectNode = await externalTray . Client . CallToolExpectSuccessAsync ( "app.connection.reconnectNode" ) ;
424- Assert . True ( reconnectNode . RootElement . GetProperty ( "reconnected" ) . GetBoolean ( ) ) ;
425- await externalTray . WaitForConnectionReady ( TimeSpan . FromSeconds ( 120 ) ) ;
426- await WaitForNodeEffectiveStateAsync (
427- externalTray . Client ,
428- nodeRequest . NodeId ,
429- new CapabilitiesConfig { Tts = false } ,
430- TimeSpan . FromSeconds ( 90 ) ) ;
431- AssertExternalTrayDurablePairing ( externalTray ) ;
432- await AssertGatewayCliStateHealthy ( ) ;
474+ try
475+ {
476+ await RejectNewPendingApprovalsUntilQuietAsync (
477+ pendingBefore ,
478+ pendingNodeBefore ,
479+ handledDeviceRequestIds ,
480+ handledNodeRequestIds ,
481+ TimeSpan . FromSeconds ( 45 ) ) ;
482+ }
483+ catch ( Exception ex ) when ( testFailure is not null )
484+ {
485+ Console . WriteLine ( $ "[E2E] Cleanup after failed external shared-token tray test also failed: { ex } ") ;
486+ }
487+ }
433488 }
434489
435490 [ E2EFact ]
@@ -713,9 +768,13 @@ private async Task<string> WaitForFirstPendingDeviceRequestIdAsync(
713768
714769 private async Task ApproveNewPendingDeviceRequestsUntilReadyAsync (
715770 HashSet < string > ignoredRequestIds ,
771+ HashSet < string > approvedRequestIds ,
716772 IsolatedTrayInstance tray )
717773 {
718774 var approved = new HashSet < string > ( ignoredRequestIds , StringComparer . Ordinal ) ;
775+ foreach ( var requestId in approvedRequestIds )
776+ approved . Add ( requestId ) ;
777+
719778 var deadline = DateTime . UtcNow . AddSeconds ( 90 ) ;
720779 string lastDevicesOutput = "<none>" ;
721780 while ( DateTime . UtcNow < deadline )
@@ -741,6 +800,7 @@ private async Task ApproveNewPendingDeviceRequestsUntilReadyAsync(
741800 {
742801 using var approve = await ApproveDevicePairingFromConnectionPageAsync ( requestId ) ;
743802 Console . WriteLine ( $ "[E2E] approved external-like device request via Connection page: { approve . RootElement . GetRawText ( ) } ") ;
803+ approvedRequestIds . Add ( requestId ) ;
744804 approvedAny = true ;
745805 }
746806
@@ -765,6 +825,78 @@ private async Task ApproveNewPendingDeviceRequestsUntilReadyAsync(
765825 throw new TimeoutException ( $ "Timed out waiting for clean external-like tray credentials. Last devices list: { lastDevicesOutput } ") ;
766826 }
767827
828+ private async Task RejectNewPendingApprovalsUntilQuietAsync (
829+ HashSet < string > deviceRequestIdsBefore ,
830+ HashSet < string > nodeRequestIdsBefore ,
831+ HashSet < string > handledDeviceRequestIds ,
832+ HashSet < string > handledNodeRequestIds ,
833+ TimeSpan timeout )
834+ {
835+ var deadline = DateTime . UtcNow . Add ( timeout ) ;
836+ DateTime ? quietSince = null ;
837+ string lastOutput = "<none>" ;
838+
839+ while ( DateTime . UtcNow < deadline )
840+ {
841+ using var approvals = await ReadPendingApprovalsFromConnectionPageAsync ( ) ;
842+ lastOutput = approvals . RootElement . GetRawText ( ) ;
843+ var rejectedAny = false ;
844+ var handledRequestStillVisible = false ;
845+
846+ foreach ( var requestId in ReadPendingApprovalIds ( approvals . RootElement , "devicePending" , "RequestId" , "DeviceId" )
847+ . ToArray ( ) )
848+ {
849+ if ( deviceRequestIdsBefore . Contains ( requestId ) )
850+ continue ;
851+
852+ if ( handledDeviceRequestIds . Contains ( requestId ) )
853+ {
854+ handledRequestStillVisible = true ;
855+ continue ;
856+ }
857+
858+ using var reject = await RejectDevicePairingFromConnectionPageAsync ( requestId ) ;
859+ handledDeviceRequestIds . Add ( requestId ) ;
860+ Console . WriteLine ( $ "[E2E] cleaned up pending device request { requestId } : { reject . RootElement . GetRawText ( ) } ") ;
861+ rejectedAny = true ;
862+ }
863+
864+ foreach ( var request in ReadPendingNodeApprovals ( approvals . RootElement )
865+ . ToArray ( ) )
866+ {
867+ if ( nodeRequestIdsBefore . Contains ( request . RequestId ) )
868+ continue ;
869+
870+ if ( handledNodeRequestIds . Contains ( request . RequestId ) )
871+ {
872+ handledRequestStillVisible = true ;
873+ continue ;
874+ }
875+
876+ using var reject = await RejectNodePairingFromConnectionPageAsync ( request . RequestId ) ;
877+ handledNodeRequestIds . Add ( request . RequestId ) ;
878+ Console . WriteLine ( $ "[E2E] cleaned up pending node-trust request { request . RequestId } for { request . NodeId } : { reject . RootElement . GetRawText ( ) } ") ;
879+ rejectedAny = true ;
880+ }
881+
882+ if ( rejectedAny || handledRequestStillVisible )
883+ {
884+ quietSince = null ;
885+ }
886+ else
887+ {
888+ quietSince ??= DateTime . UtcNow ;
889+ if ( DateTime . UtcNow - quietSince >= TimeSpan . FromSeconds ( 3 ) )
890+ return ;
891+ }
892+
893+ await Task . Delay ( 500 ) ;
894+ }
895+
896+ throw new TimeoutException (
897+ $ "Timed out waiting for external-tray pending approvals to remain clear. Last output: { lastOutput } ") ;
898+ }
899+
768900 private async Task < JsonDocument > ReadPendingApprovalsFromConnectionPageAsync ( )
769901 {
770902 await NavigateAdminTrayToConnectionPageAsync ( ) ;
0 commit comments