Skip to content

Commit 3c5b5ce

Browse files
Add max-context-population input to override Azure PowerShell MaxCont… (#642)
* Add max-context-population input to override Azure PowerShell MaxContextPopulation Azure PowerShell loads a maximum of 25 subscription contexts by default (MaxContextPopulation = 25). When enable-AzPSSession is true and the identity can access more than 25 subscriptions, only a subset of contexts is loaded, so downstream cmdlets that enumerate or target other subscriptions behave inconsistently. Previously the only workaround was to disable the PowerShell session and call Connect-AzAccount manually. Expose the existing Connect-AzAccount -MaxContextPopulation parameter through a new optional max-context-population input: - action.yml: new optional input (no default). - LoginConfig: reads and trims the value; validate() rejects non-integer or out-of-range values (must be -1 or a positive integer) and warns when it is set without enable-AzPSSession, where it has no effect. - AzPSScriptBuilder: passes -MaxContextPopulation only when the input is set. - AzPSLogin.ps1: adds an [int]$MaxContextPopulation param, forwarded to Connect-AzAccount only when bound so the default behavior is unchanged. - README: input table row and a max-context-population section, including a note that -1 loads all contexts and can slow login for large tenants. - Tests: cover the arg being passed when set and omitted when unset. Fully backward-compatible: when the input is unset, the parameter is never passed and the Azure PowerShell default of 25 applies. Only affects the enable-AzPSSession path. Fixes #606. Co-authored-by: Copilot <[email protected]> * Harden max-context-population validation to match Connect-AzAccount range Validate the raw input string rather than Number(), which accepts scientific, hex and float forms (1e3, 0x10, 5.0) and out-of-range values that then fail Connect-AzAccount's [int] binding with a confusing error. Accept only -1 or a plain positive integer within 1..2147483647, matching the cmdlet's ValidateRange(-1, 2147483647). Add unit tests for the accepted and rejected cases, and note the bound in the README. Co-authored-by: Copilot <[email protected]> * docs: note mask-client-id and max-context-population are available in azure/login@v3 Add an 'Available in azure/login@v3' label under each input heading. Both are v3-only inputs (not present in v2), so this documents the version and points consumers at v3. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Maddison Das <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent fcd0340 commit 3c5b5ce

7 files changed

Lines changed: 125 additions & 1 deletion

File tree

‎README.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
- [`allow-no-subscriptions`](#allow-no-subscriptions)
2121
- [`audience`](#audience)
2222
- [`auth-type`](#auth-type)
23+
- [`max-context-population`](#max-context-population)
2324
- [Workflow Examples](#workflow-examples)
2425
- [Login With OpenID Connect (OIDC) \[Recommended\]](#login-with-openid-connect-oidc-recommended)
2526
- [Login With a Service Principal Secret](#login-with-a-service-principal-secret)
@@ -157,6 +158,7 @@ uses: azure/login@<full-length-commit-sha> # v3.0.2
157158
|allow-no-subscriptions|false|boolean|false|if login without subscription is allowed|
158159
|audience|false|string|api://AzureADTokenExchange|the audience to get the JWT ID token from GitHub OIDC provider|
159160
|auth-type|false|string|SERVICE_PRINCIPAL|the auth type|
161+
|max-context-population|false|integer||only used when `enable-AzPSSession` is `true`; overrides the Azure PowerShell `MaxContextPopulation`. Defaults to the Azure PowerShell default of 25 when unset.|
160162
|mask-client-id|false|boolean|true|if the `client-id` value is masked in workflow logs|
161163

162164
### `client-id`
@@ -174,6 +176,8 @@ Refer to [Login With OpenID Connect (OIDC)](#login-with-openid-connect-oidc-reco
174176

175177
### `mask-client-id`
176178

179+
_Available in `azure/login@v3`._
180+
177181
The input parameter `mask-client-id` controls whether the login client id is registered as a secret and masked in the workflow logs. It defaults to `true`.
178182

179183
Set it to `false` when the client id is not treated as sensitive and masking gets in the way, for example when the same value appears in log output or command results that you need to read.
@@ -268,6 +272,28 @@ The input parameter `auth-type` specifies the type of authentication. The defaul
268272

269273
Refer to [Login With System-assigned Managed Identity](#login-with-system-assigned-managed-identity) and [Login With User-assigned Managed Identity](#login-with-user-assigned-managed-identity) for its usage.
270274

275+
### `max-context-population`
276+
277+
_Available in `azure/login@v3`._
278+
279+
The input parameter `max-context-population` is only used when [`enable-AzPSSession`](#enable-azpssession) is `true`. It overrides the Azure PowerShell `MaxContextPopulation` value that `Connect-AzAccount` uses, which controls how many subscription contexts are loaded into the session.
280+
281+
Azure PowerShell loads a maximum of 25 subscription contexts by default. When the identity has access to more than 25 subscriptions, only a subset is loaded, so commands that enumerate or target subscriptions outside that subset may behave inconsistently. Set `max-context-population` to `-1` to load all subscriptions, or to a positive integer (1 to 2147483647) to load a specific number. When it is unset, the Azure PowerShell default of 25 applies and behavior is unchanged.
282+
283+
```yaml
284+
- name: Azure login
285+
uses: azure/login@v3
286+
with:
287+
client-id: ${{ vars.AZURE_CLIENT_ID }}
288+
tenant-id: ${{ vars.AZURE_TENANT_ID }}
289+
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
290+
enable-AzPSSession: true
291+
max-context-population: -1
292+
```
293+
294+
> [!NOTE]
295+
> Loading all subscription contexts with `-1` makes `Connect-AzAccount` slower when the identity can access a large number of subscriptions, because every subscription is enumerated during login. Set it only when your workflow needs contexts beyond the default 25.
296+
271297
## Workflow Examples
272298

273299
### Login With OpenID Connect (OIDC) [Recommended]

‎__tests__/LoginConfig.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,4 +405,35 @@ describe("LoginConfig Test", () => {
405405
expect(loginConfig.subscriptionId).toBe("");
406406
});
407407

408+
async function initWithMaxContextPopulation(value: string): Promise<LoginConfig> {
409+
setEnv('environment', 'azurecloud');
410+
setEnv('enable-AzPSSession', 'true');
411+
setEnv('allow-no-subscriptions', 'true');
412+
setEnv('auth-type', 'SERVICE_PRINCIPAL');
413+
setEnv('tenant-id', 'tenant-id');
414+
setEnv('subscription-id', 'subscription-id');
415+
setEnv('client-id', 'client-id');
416+
setEnv('max-context-population', value);
417+
const loginConfig = new LoginConfig();
418+
await loginConfig.initialize();
419+
return loginConfig;
420+
}
421+
422+
test.each(['-1', '1', '25', '2147483647'])('validate accepts max-context-population=%s', async (value) => {
423+
const loginConfig = await initWithMaxContextPopulation(value);
424+
loginConfig.validate();
425+
expect(loginConfig.maxContextPopulation).toBe(value);
426+
});
427+
428+
test.each(['0', '-2', '1e3', '0x10', '5.0', '2147483648', 'abc'])('validate rejects invalid max-context-population=%s', async (value) => {
429+
const loginConfig = await initWithMaxContextPopulation(value);
430+
testValidateWithErrorMessage(loginConfig, "for 'max-context-population'. It must be -1");
431+
});
432+
433+
test('whitespace-only max-context-population is treated as unset', async () => {
434+
const loginConfig = await initWithMaxContextPopulation(' ');
435+
loginConfig.validate();
436+
expect(loginConfig.maxContextPopulation).toBe('');
437+
});
438+
408439
});

‎__tests__/PowerShell/AzPSScriptBuilder.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,49 @@ describe("Building the Az PS login invocation", () => {
160160
});
161161
});
162162

163+
test('max-context-population set: value passed as -MaxContextPopulation param', () => {
164+
setEnv('environment', 'azurecloud');
165+
setEnv('enable-AzPSSession', 'true');
166+
setEnv('allow-no-subscriptions', 'true');
167+
setEnv('auth-type', 'SERVICE_PRINCIPAL');
168+
setEnv('max-context-population', '-1');
169+
const creds = {
170+
'clientId': 'client-id',
171+
'clientSecret': 'client-secret',
172+
'tenantId': 'tenant-id',
173+
'subscriptionId': 'subscription-id'
174+
};
175+
setEnv('creds', JSON.stringify(creds));
176+
177+
const loginConfig = new LoginConfig();
178+
loginConfig.initialize();
179+
return AzPSScriptBuilder.getAzPSLoginInvocation(loginConfig).then(({ args }) => {
180+
expect(args).toEqual(expect.arrayContaining([
181+
'-MaxContextPopulation', '-1',
182+
]));
183+
});
184+
});
185+
186+
test('max-context-population unset: -MaxContextPopulation param omitted', () => {
187+
setEnv('environment', 'azurecloud');
188+
setEnv('enable-AzPSSession', 'true');
189+
setEnv('allow-no-subscriptions', 'true');
190+
setEnv('auth-type', 'SERVICE_PRINCIPAL');
191+
const creds = {
192+
'clientId': 'client-id',
193+
'clientSecret': 'client-secret',
194+
'tenantId': 'tenant-id',
195+
'subscriptionId': 'subscription-id'
196+
};
197+
setEnv('creds', JSON.stringify(creds));
198+
199+
const loginConfig = new LoginConfig();
200+
loginConfig.initialize();
201+
return AzPSScriptBuilder.getAzPSLoginInvocation(loginConfig).then(({ args }) => {
202+
expect(args).not.toContain('-MaxContextPopulation');
203+
});
204+
});
205+
163206
test('SECURITY: adversarial ArmEndpoint travels as a discrete argv element', () => {
164207
setEnv('environment', 'azurestack');
165208
setEnv('enable-AzPSSession', 'true');

‎action.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ inputs:
3434
description: 'The type of authentication. Supported values are SERVICE_PRINCIPAL, IDENTITY. Default value is SERVICE_PRINCIPAL'
3535
required: false
3636
default: 'SERVICE_PRINCIPAL'
37+
max-context-population:
38+
description: 'Only used when enable-AzPSSession is true. Overrides the Azure PowerShell MaxContextPopulation used by Connect-AzAccount (the number of subscription contexts loaded). Set to -1 to load all subscriptions, or a positive integer. When unset, the Azure PowerShell default of 25 applies.'
39+
required: false
3740
mask-client-id:
3841
description: 'Set this value to false to stop registering the client-id as a secret, so it is not masked in workflow logs'
3942
required: false

‎src/PowerShell/AzPSLogin.ps1‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ param(
1414

1515
[string]$ApplicationId,
1616

17-
[string]$ArmEndpoint
17+
[string]$ArmEndpoint,
18+
19+
[int]$MaxContextPopulation
1820
)
1921

2022
$ErrorActionPreference = 'Stop'
@@ -34,6 +36,7 @@ try {
3436
}
3537
if ($Tenant) { $connectArgs['Tenant'] = $Tenant }
3638
if ($Subscription) { $connectArgs['Subscription'] = $Subscription }
39+
if ($PSBoundParameters.ContainsKey('MaxContextPopulation')) { $connectArgs['MaxContextPopulation'] = $MaxContextPopulation }
3740

3841
if ($AuthType -eq 'SERVICE_PRINCIPAL') {
3942
$connectArgs['ServicePrincipal'] = $true

‎src/PowerShell/AzPSScriptBuilder.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ export default class AzPSScriptBuilder {
5353
if (loginConfig.environment.toLowerCase() === 'azurestack') {
5454
args.push('-ArmEndpoint', loginConfig.resourceManagerEndpointUrl);
5555
}
56+
if (loginConfig.maxContextPopulation) {
57+
args.push('-MaxContextPopulation', loginConfig.maxContextPopulation);
58+
}
5659

5760
if (loginConfig.authType === LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
5861
args.push('-ApplicationId', loginConfig.servicePrincipalId);

‎src/common/LoginConfig.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export class LoginConfig {
2525
enableAzPSSession: boolean;
2626
audience: string;
2727
federatedToken: string;
28+
maxContextPopulation: string;
2829
maskClientId: boolean;
2930

3031
async initialize() {
@@ -42,6 +43,7 @@ export class LoginConfig {
4243

4344
this.audience = core.getInput('audience', { required: false });
4445
this.federatedToken = null;
46+
this.maxContextPopulation = core.getInput('max-context-population', { required: false }).trim();
4547

4648
this.maskClientId = core.getInput('mask-client-id').toLowerCase() !== "false";
4749
if (this.maskClientId) {
@@ -110,6 +112,19 @@ export class LoginConfig {
110112
if (!this.subscriptionId && !this.allowNoSubscriptionsLogin) {
111113
throw new Error("Ensure 'subscription-id' is supplied or 'allow-no-subscriptions' is 'true'.");
112114
}
115+
if (this.maxContextPopulation) {
116+
// Validate the raw string (not Number(), which accepts 1e3/0x10/5.0
117+
// and out-of-range values that PowerShell's [int] then rejects).
118+
const INT32_MAX = 2147483647;
119+
const isValid = this.maxContextPopulation === '-1'
120+
|| (/^[1-9][0-9]*$/.test(this.maxContextPopulation) && Number(this.maxContextPopulation) <= INT32_MAX);
121+
if (!isValid) {
122+
throw new Error(`Invalid value '${this.maxContextPopulation}' for 'max-context-population'. It must be -1 (load all subscription contexts) or a positive integer between 1 and ${INT32_MAX}.`);
123+
}
124+
if (!this.enableAzPSSession) {
125+
core.warning("'max-context-population' is only applied when 'enable-AzPSSession' is 'true'. It has no effect on Azure CLI login and will be ignored.");
126+
}
127+
}
113128
}
114129

115130
mask(parameterValue: string) {

0 commit comments

Comments
 (0)