Azure / Azure/azure-cli-extensions
az network bastion tunnel partially ignores `--subscription`
- Dominant language
- Python
- Stars
- 454
- Forks
- 1.7k
- Avg merge
- 2d 19h
- Merged PRs (30d)
- 64
Description
### Describe the bug
`az network bastion tunnel` command partially ignores user-supplied `--subscription`
For me issue looks like following:
* Subscription information **is used correctly**: Bastion metadata is fetched with with correct subscription information and tenant(= authentication token)
* https://github.com/Azure/azure-cli-extensions/blob/3e80e22f9232c90e2923d6b4cdddd391014513c2/src/bastion/azext_bastion/custom.py#L456
* From debug logs I can see correct GET request and response for `https://management.azure.com/.../Microsoft.Network/bastionHosts/?api-version=2024-01-01`
* Subscription information **is ignored**: As soon as native client connects to bastion tunnel TCP listeners `_handle_client()` fetch new authentication token from https://login.microsoftonline.com/
https://github.com/Azure/azure-cli-extensions/blob/3e80e22f9232c90e2923d6b4cdddd391014513c2/src/bastion/azext_bastion/tunnel.py#L80-L83
* Not sure if `cli_ctx` contains user-provided `--subscription` information. My assumptions are based on behaviour and logs
* After getting authentication token(SIC) `_get_auth_token()` fetch bastion-specific authentication token from `https://{self.bastion_endpoint}/api/tokens`
https://github.com/Azure/azure-cli-extensions/blob/3e80e22f9232c90e2923d6b4cdddd391014513c2/src/bastion/azext_bastion/tunnel.py#L99-L110
* From debug logs we can see that request was failed because authentication token it just fetched does not work
```
urllib3.connectionpool: Starting new HTTPS connection (1): bst-x-x-4c54-a6c3-42fe3a738a65.bastion.azure.com:443
urllib3.connectionpool: https://bst-x-x-4c54-a6c3-42fe3a738a65.bastion.azure.com:443 "POST /api/tokens HTTP/1.1" 403 None
cli.azext_bastion.tunnel: Exception in handling client: Bastion cannot be located by given credentials
```
### Related command
az network bastion tunnel
### Errors
Nope. There is no stack to share. Issue is silently ignored
without `--debug` or `--verbose`: Nothing is logged from listener code:
with `--verbose`: some information is logged from listener:
Even with `--debug` actual stack is missing:
### Issue script & Debug output
cli.knack.cli: Command arguments: ['network', 'bastion', 'tunnel', '--name', 'bname', '--resource-group', 'rgname', '--subscription', 'subscriptionname', '--target-resource-id', 'targetresId', '--resource-port', '3389', '--port', '13389', '--debug']
cli.knack.cli: __init__ debug log:
Enable color in terminal.
cli.knack.cli: Event: Cli.PreExecute []
cli.knack.cli: Event: CommandParser.OnGlobalArgumentsCreate [, , ]
cli.knack.cli: Event: CommandInvoker.OnPreCommandTableCreate []
cli.azure.cli.core: Modules found from index for 'network': ['azure.cli.command_modules.network', 'azure.cli.command_modules.privatedns', 'azext_bastion']
cli.azure.cli.core: Loading command modules:
cli.azure.cli.core: Name Load Time Groups Commands
cli.azure.cli.core: network 0.278 119 366
cli.azure.cli.core: privatedns 0.004 14 60
cli.azure.cli.core: Total (2) 0.282 133 426
cli.azure.cli.core: These extensions are not installed and will be skipped: ['azext_ai_examples', 'azext_next']
cli.azure.cli.core: Loading extensions:
cli.azure.cli.core: Name Load Time Groups Commands Directory
cli.azure.cli.core: bastion 0.002 2 9 /Users/janne.kujanpaa/.azure/cliextensions/bastion
cli.azure.cli.core: Total (1) 0.002 2 9
cli.azure.cli.core: Loaded 133 groups, 435 commands.
cli.azure.cli.core: Found a match in the command table.
cli.azure.cli.core: Raw command : network bastion tunnel
cli.azure.cli.core: Command table: network bastion tunnel
cli.knack.cli: Event: CommandInvoker.OnPreCommandTableTruncate []
cli.azure.cli.core.azlogging: metadata file logging enabled - writing logs to '/Users/janne.kujanpaa/.azure/commands/2025-06-14.16-32-36.network_bastion_tunnel.50061.log'.
az_command_data_logger: command args: network bastion tunnel --name {} --resource-group {} --subscription {} --target-resource-id {} --resource-port {} --port {} --debug
cli.knack.cli: Event: CommandInvoker.OnPreArgumentLoad [.add_subscription_parameter at 0x104590b80>]
cli.knack.cli: Event: CommandInvoker.OnPostArgumentLoad []
cli.knack.cli: Event: CommandInvoker.OnPostCommandTableCreate [.add_ids_arguments at 0x104593420>, .add_cache_arguments at 0x104593560>, .update_breaking_change_info at 0x104593600>]
cli.knack.cli: Event: CommandInvoker.OnCommandTableLoaded []
cli.knack.cli: Event: CommandInvoker.OnPreParseArgs []
cli.knack.cli: Event: CommandInvoker.OnPostParseArgs [, , .parse_ids_arguments at 0x1045934c0>]
az_command_data_logger: extension name: bastion
az_command_data_logger: extension version: 1.4.0
cli.azure.cli.core.auth.persistence: build_persistence: location='/Users/janne.kujanpaa/.azure/msal_token_cache.json', encrypt=False
cli.azure.cli.core.auth.binary_cache: load: /Users/janne.kujanpaa/.azure/msal_http_cache.bin
urllib3.util.retry: Converted retries value: 1 -> Retry(total=1, connect=None, read=None, redirect=None, status=None)
msal.authority: Initializing with Entra authority: https://login.microsoftonline.com/tenant1
msal.authority: openid_config("https://login.microsoftonline.com/tenant1/v2.0/.well-known/openid-configuration") = {'token_endpoint': 'https://login.microsoftonline.com/tenant1/oauth2/v2.0/token', 'token_endpoint_auth_methods_supported': ['client_secret_post', 'private_key_jwt', 'client_secret_basic'], 'jwks_uri': 'https://login.microsoftonline.com/tenant1/discovery/v2.0/keys', 'response_modes_supported': ['query', 'fragment', 'form_post'], 'subject_types_supported': ['pairwise'], 'id_token_signing_alg_values_supported': ['RS256'], 'response_types_supported': ['code', 'id_token', 'code id_token', 'id_token token'], 'scopes_supported': ['openid', 'profile', 'email', 'offline_access'], 'issuer': 'https://login.microsoftonline.com/tenant1/v2.0', 'request_uri_parameter_supported': False, 'userinfo_endpoint': 'https://graph.microsoft.com/oidc/userinfo', 'authorization_endpoint': 'https://login.microsoftonline.com/tenant1/oauth2/v2.0/authorize', 'device_authorization_endpoint': 'https://login.microsoftonline.com/tenant1/oauth2/v2.0/devicecode', 'http_logout_supported': True, 'frontchannel_logout_supported': True, 'end_session_endpoint': 'https://login.microsoftonline.com/tenant1/oauth2/v2.0/logout', 'claims_supported': ['sub', 'iss', 'cloud_instance_name', 'cloud_instance_host_name', 'cloud_graph_host_name', 'msgraph_host', 'aud', 'exp', 'iat', 'auth_time', 'acr', 'nonce', 'preferred_username', 'name', 'tid', 'ver', 'at_hash', 'c_hash', 'email'], 'kerberos_endpoint': 'https://login.microsoftonline.com/tenant1/kerberos', 'tenant_region_scope': 'EU', 'cloud_instance_name': 'microsoftonline.com', 'cloud_graph_host_name': 'graph.windows.net', 'msgraph_host': 'graph.microsoft.com', 'rbac_url': 'https://pas.windows.net'}
msal.application: Broker enabled? None
cli.azure.cli.core.auth.credential_adaptor: CredentialAdaptor.get_token: scopes=('https://management.core.windows.net//.default',), kwargs={}
cli.azure.cli.core.auth.msal_credentials: UserCredential.acquire_token: scopes=['https://management.core.windows.net//.default'], claims_challenge=None, kwargs={}
msal.application: Cache hit an AT
msal.telemetry: Generate or reuse correlation_id: 0694859c-3d5c-4e72-943d-e7d22f248ed1
cli.azure.cli.core.sdk.policies: Request URL: 'https://management.azure.com/subscriptions/bastionResourceSubscriptionID/resourceGroups/rgname/providers/Microsoft.Network/bastionHosts/bname?api-version=2024-01-01'
cli.azure.cli.core.sdk.policies: Request method: 'GET'
cli.azure.cli.core.sdk.policies: Request headers:
cli.azure.cli.core.sdk.policies: 'Accept': 'application/json'
cli.azure.cli.core.sdk.policies: 'x-ms-client-request-id': '08e3f5e6-4924-11f0-b2cb-6e97cdbf435a'
cli.azure.cli.core.sdk.policies: 'CommandName': 'network bastion tunnel'
cli.azure.cli.core.sdk.policies: 'ParameterSetName': '--name --resource-group --subscription --target-resource-id --resource-port --port --debug'
cli.azure.cli.core.sdk.policies: 'User-Agent': 'AZURECLI/2.74.0 (HOMEBREW) azsdk-python-core/1.31.0 Python/3.12.11 (macOS-15.5-arm64-arm-64bit)'
cli.azure.cli.core.sdk.policies: 'Authorization': '*****'
cli.azure.cli.core.sdk.policies: Request body:
cli.azure.cli.core.sdk.policies: This request has no body
urllib3.connectionpool: Starting new HTTPS connection (1): management.azure.com:443
urllib3.connectionpool: https://management.azure.com:443 "GET /subscriptions/bastionResourceSubscriptionID/resourceGroups/rgname/providers/Microsoft.Network/bastionHosts/bname?api-version=2024-01-01 HTTP/1.1" 200 1782
cli.azure.cli.core.sdk.policies: Response status: 200
cli.azure.cli.core.sdk.policies: Response headers:
cli.azure.cli.core.sdk.policies: 'Cache-Control': 'no-cache'
cli.azure.cli.core.sdk.policies: 'Pragma': 'no-cache'
cli.azure.cli.core.sdk.policies: 'Content-Length': '1782'
cli.azure.cli.core.sdk.policies: 'Content-Type': 'application/json; charset=utf-8'
cli.azure.cli.core.sdk.policies: 'Expires': '-1'
cli.azure.cli.core.sdk.policies: 'ETag': 'W/"849b4298-2984-42a7-8f90-ca7bbd04f3be"'
cli.azure.cli.core.sdk.policies: 'x-ms-request-id': '00d260e4-13b6-461d-8993-8a1c607e9146'
cli.azure.cli.core.sdk.policies: 'x-ms-correlation-request-id': '7451bd52-b676-4697-911c-067750be66c8'
cli.azure.cli.core.sdk.policies: 'x-ms-arm-service-request-id': '25b3ab43-442d-408b-a927-1704d9b88084'
cli.azure.cli.core.sdk.policies: 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
cli.azure.cli.core.sdk.policies: 'x-ms-ratelimit-remaining-subscription-reads': '249'
cli.azure.cli.core.sdk.policies: 'x-ms-ratelimit-remaining-subscription-global-reads': '3749'
cli.azure.cli.core.sdk.policies: 'x-ms-routing-request-id': 'WESTEUROPE:20250614T133237Z:7451bd52-b676-4697-911c-067750be66c8'
cli.azure.cli.core.sdk.policies: 'X-Content-Type-Options': 'nosniff'
cli.azure.cli.core.sdk.policies: 'X-Cache': 'CONFIG_NOCACHE'
cli.azure.cli.core.sdk.policies: 'X-MSEdge-Ref': 'Ref A: 480E7268C6D246C2868BAF945F2D4CE1 Ref B: GVX211060217054 Ref C: 2025-06-14T13:32:36Z'
cli.azure.cli.core.sdk.policies: 'Date': 'Sat, 14 Jun 2025 13:32:37 GMT'
cli.azure.cli.core.sdk.policies: Response content:
cli.azure.cli.core.sdk.policies: {"name":"bname","id":"/subscriptions/bastionResourceSubscriptionID/resourceGroups/rgname/providers/Microsoft.Network/bastionHosts/bname","etag":"W/\"849b4298-2984-42a7-8f90-ca7bbd04f3be\"","type":"Microsoft.Network/bastionHosts","location":"westeurope","tags":{},"properties":{"provisioningState":"Succeeded","dnsName":"bastionHost","scaleUnits":2,"enableTunneling":true,"enableIpConnect":true,"enableFileCopy":true,"disableCopyPaste":false,"enableShareableLink":false,"ipConfigurations":[{"name":"bastion-ip_configuration","id":"/subscriptions/bastionResourceSubscriptionID/resourceGroups/rgname/providers/Microsoft.Network/bastionHosts/bname/bastionHostIpConfigurations/bastion-ip_configuration","etag":"W/\"849b4298-2984-42a7-8f90-ca7bbd04f3be\"","type":"Microsoft.Network/bastionHosts/bastionHostIpConfigurations","properties":{"provisioningState":"Succeeded","privateIPAllocationMethod":"Dynamic","publicIPAddress":{"id":"/subscriptions/bastionResourceSubscriptionID/resourceGroups/rgname/providers/Microsoft.Network/publicIPAddresses/pip-hub-bastion-shared-westeurope-001"},"subnet":{"id":"/subscriptions/bastionResourceSubscriptionID/resourceGroups/rgname/providers/Microsoft.Network/virtualNetworks/vnet-hub-shared-westeurope-001/subnets/AzureBastionSubnet"}}}]},"sku":{"name":"Standard"}}
cli.azext_bastion.tunnel: Port 13389 is open
cli.azext_bastion.tunnel: Creating a socket on port: 13389
cli.azext_bastion.tunnel: Setting socket options
cli.azext_bastion.tunnel: Binding to socket on local address and port
cli.azext_bastion.tunnel: Finished initialization
cli.azext_bastion.custom: Opening tunnel on port: 13389
cli.azext_bastion.custom: Tunnel is ready, connect on port 13389
cli.azext_bastion.custom: Ctrl + C to close
cli.azext_bastion.tunnel: Got a connection, starting a new thread
urllib3.util.retry: Converted retries value: 1 -> Retry(total=1, connect=None, read=None, redirect=None, status=None)
msal.authority: Initializing with Entra authority: https://login.microsoftonline.com/tenant0a
msal.authority: openid_config("https://login.microsoftonline.com/tenant0a") = {'token_endpoint': 'https://login.microsoftonline.com/tenant0a/oauth2/v2.0/token', 'token_endpoint_auth_methods_supported': ['client_secret_post', 'private_key_jwt', 'client_secret_basic'], 'jwks_uri': 'https://login.microsoftonline.com/tenant0a/discovery/v2.0/keys', 'response_modes_supported': ['query', 'fragment', 'form_post'], 'subject_types_supported': ['pairwise'], 'id_token_signing_alg_values_supported': ['RS256'], 'response_types_supported': ['code', 'id_token', 'code id_token', 'id_token token'], 'scopes_supported': ['openid', 'profile', 'email', 'offline_access'], 'issuer': 'https://login.microsoftonline.com/tenant0a/v2.0', 'request_uri_parameter_supported': False, 'userinfo_endpoint': 'https://graph.microsoft.com/oidc/userinfo', 'authorization_endpoint': 'https://login.microsoftonline.com/tenant0a/oauth2/v2.0/authorize', 'device_authorization_endpoint': 'https://login.microsoftonline.com/tenant0a/oauth2/v2.0/devicecode', 'http_logout_supported': True, 'frontchannel_logout_supported': True, 'end_session_endpoint': 'https://login.microsoftonline.com/tenant0a/oauth2/v2.0/logout', 'claims_supported': ['sub', 'iss', 'cloud_instance_name', 'cloud_instance_host_name', 'cloud_graph_host_name', 'msgraph_host', 'aud', 'exp', 'iat', 'auth_time', 'acr', 'nonce', 'preferred_username', 'name', 'tid', 'ver', 'at_hash', 'c_hash', 'email'], 'kerberos_endpoint': 'https://login.microsoftonline.com/tenant0a/kerberos', 'tenant_region_scope': 'EU', 'cloud_instance_name': 'microsoftonline.com', 'cloud_graph_host_name': 'graph.windows.net', 'msgraph_host': 'graph.microsoft.com', 'rbac_url': 'https://pas.windows.net'}
msal.application: Broker enabled? None
cli.azure.cli.core.auth.credential_adaptor: CredentialAdaptor.get_token: scopes=('https://management.core.windows.net//.default',), kwargs={}
cli.azure.cli.core.auth.msal_credentials: UserCredential.acquire_token: scopes=['https://management.core.windows.net//.default'], claims_challenge=None, kwargs={}
msal.application: Cache hit an AT
msal.telemetry: Generate or reuse correlation_id: b7f1ef8b-4b30-4be4-b5d7-c86f2d649ca5
cli.azext_bastion.tunnel: Content: {'resourceId': 'targetresId', 'protocol': 'tcptunnel', 'workloadHostPort': '3389', 'aztoken': 'redacted', 'token': None}
urllib3.connectionpool: Starting new HTTPS connection (1): bastionHost:443
urllib3.connectionpool: https://bastionHost:443 "POST /api/tokens HTTP/1.1" 403 None
cli.azext_bastion.tunnel: Exception in handling client: Bastion cannot be located by given credentials
cli.azext_bastion.tunnel: Nothing to clean up.
cli.azext_bastion.tunnel: Both debugger and websocket threads stopped...
cli.azext_bastion.tunnel: Stopped local server..
^Ccli.azext_bastion.custom: Ctrl + C received. Clean up and then exit.
cli.azext_bastion.tunnel: Nothing to clean up.
cli.knack.cli: Event: Cli.PostExecute []
az_command_data_logger: exit code: None
cli.__main__: Command ran in 29.791 seconds (init: 0.066, invoke: 29.725)
telemetry.main: Begin splitting cli events and extra events, total events: 1
telemetry.client: Accumulated 0 events. Flush the clients.
telemetry.main: Finish splitting cli events and extra events, cli events: 1
telemetry.save: Save telemetry record of length 4110 in cache file under /Users/janne.kujanpaa/.azure/telemetry/20250614163306290
telemetry.main: Begin creating telemetry upload process.
telemetry.process: Creating upload process: "/opt/homebrew/Cellar/azure-cli/2.74.0/libexec/bin/python /opt/homebrew/Cellar/azure-cli/2.74.0/libexec/lib/python3.12/site-packages/azure/cli/telemetry/__init__.py /Users/janne.kujanpaa/.azure /Users/janne.kujanpaa/.azure/telemetry/20250614163306290"
telemetry.process: Return from creating process 50067
telemetry.main: Finish creating telemetry upload process.
### Expected behavior
`--subscription` should work
### Environment Summary
azure-cli 2.74.0
core 2.74.0
telemetry 1.1.0
Extensions:
azure-devops 1.0.1
bastion 1.4.0
Dependencies:
msal 1.32.3
azure-mgmt-resource 23.3.0
Python location '/opt/homebrew/Cellar/azure-cli/2.74.0/libexec/bin/python'
Config directory '/Users/janne.kujanpaa/.azure'
Extensions directory '/Users/janne.kujanpaa/.azure/cliextensions'
Python (Darwin) 3.12.11 (main, Jun 3 2025, 15:41:47) [Clang 17.0.0 (clang-1700.0.13.3)]
Legal docs and information: aka.ms/AzureCliLegal
Your CLI is up-to-date.
### Additional context
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.