-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathAgenticIT.java
More file actions
557 lines (465 loc) · 25.8 KB
/
AgenticIT.java
File metadata and controls
557 lines (465 loc) · 25.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.aad.msal4j;
import com.microsoft.aad.msal4j.labapi.KeyVaultSecretsProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import static org.junit.jupiter.api.Assertions.*;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
/**
* Integration tests for agentic (agent identity) scenarios using MSAL Java APIs.
* Corresponds to .NET's Agentic.cs — tests the MSAL-level APIs for the agent identity flow
* (specifically the FMI portions that are available on this branch, plus FIC user_fic flows).
*
* <p>These tests use MSAL token acquisition APIs (unlike AgenticRawHttpIT which uses raw HTTP).
*
* <p>Test configuration:
* <ul>
* <li>RMA app: see {@link TestConstants#AGENTIC_RMA_CLIENT_ID}</li>
* <li>Agent app: see {@link TestConstants#AGENTIC_AGENT_APP_ID}</li>
* <li>Tenant: see {@link TestConstants#AGENTIC_TENANT_ID}</li>
* </ul>
*
* <p>Flows tested:
* <ul>
* <li>Assertion callback receives correct context (AssertionRequestOptions)</li>
* <li>Cache isolation between different fmi_path values</li>
* <li>Full 3-leg flow: FMI → assertion → user_fic → user token</li>
* <li>Multi-user cache isolation via user_fic</li>
* </ul>
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class AgenticIT {
private static final String AUTHORITY = "https://login.microsoftonline.com/" + TestConstants.AGENTIC_TENANT_ID + "/";
private PrivateKey privateKey;
private X509Certificate certificate;
@BeforeAll
void init() throws KeyStoreException, NoSuchProviderException,
IOException, NoSuchAlgorithmException, CertificateException,
UnrecoverableKeyException {
KeyStore keystore = CertificateHelper.createKeyStore();
keystore.load(null, null);
privateKey = (PrivateKey) keystore.getKey(KeyVaultSecretsProvider.CERTIFICATE_ALIAS, null);
certificate = (X509Certificate) keystore.getCertificate(KeyVaultSecretsProvider.CERTIFICATE_ALIAS);
assertNotNull(privateKey, "Lab private key not found. Ensure the lab cert is installed.");
assertNotNull(certificate, "Lab certificate not found. Ensure the lab cert is installed.");
}
/**
* Agent gets an app-only token for Graph using an FMI-sourced client assertion.
* This tests Leg 2 of the agent identity flow:
* 1. Blueprint CCA acquires FMI credential (fmi_path = agentAppId)
* 2. Agent CCA uses that credential as client_assertion to get Graph token
*
* Corresponds to .NET's AgentGetsAppTokenForGraphTest.
*/
@Test
void agentGetsAppToken_UsingFmiAssertion() throws Exception {
// The assertion callback simulates what an SDK or middleware would do:
// it calls the blueprint app to get an FMI credential for the agent
Function<AssertionRequestOptions, String> assertionProvider = options -> {
try {
return acquireFmiCredentialForAgent(TestConstants.AGENTIC_AGENT_APP_ID);
} catch (Exception e) {
throw new RuntimeException("Failed to acquire FMI credential", e);
}
};
IClientCredential credential = ClientCredentialFactory.createFromCallback(assertionProvider);
ConfidentialClientApplication agentCca = ConfidentialClientApplication.builder(TestConstants.AGENTIC_AGENT_APP_ID, credential)
.authority(AUTHORITY)
.build();
IAuthenticationResult result = agentCca.acquireToken(ClientCredentialParameters
.builder(Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE))
.build())
.get();
assertNotNull(result, "Auth result should not be null");
assertNotNull(result.accessToken(), "Access token should not be null");
assertFalse(result.accessToken().isEmpty(), "Access token should not be empty");
}
/**
* Verifies that the context-aware assertion callback receives the correct fmiPath
* when the ClientCredentialParameters include an fmiPath.
*
* This tests the assertion context propagation: when acquiring an FMI credential
* using a context-aware callback, the fmiPath from the parameters flows to the callback.
*/
@Test
void assertionCallback_ReceivesFmiPathContext() throws Exception {
AtomicReference<AssertionRequestOptions> capturedOptions = new AtomicReference<>();
Function<AssertionRequestOptions, String> assertionProvider = options -> {
capturedOptions.set(options);
try {
return acquireFmiCredentialFromRma();
} catch (Exception e) {
throw new RuntimeException("Failed to acquire FMI credential", e);
}
};
IClientCredential credential = ClientCredentialFactory.createFromCallback(assertionProvider);
ConfidentialClientApplication cca = ConfidentialClientApplication.builder(
"urn:microsoft:identity:fmi", credential)
.authority(AUTHORITY)
.azureRegion(TestConstants.AGENTIC_AZURE_REGION)
.build();
ClientCredentialParameters params = ClientCredentialParameters
.builder(Collections.singleton(TestConstants.AGENTIC_FMI_EXCHANGE_SCOPE))
.fmiPath(TestConstants.AGENTIC_AGENT_APP_ID)
.skipCache(true)
.build();
IAuthenticationResult result = cca.acquireToken(params).get();
// Verify assertion callback received the correct context
assertNotNull(capturedOptions.get(), "AssertionRequestOptions should have been passed to callback");
assertEquals(TestConstants.AGENTIC_AGENT_APP_ID, capturedOptions.get().clientAssertionFmiPath(),
"clientAssertionFmiPath in callback should match the one set in parameters");
assertEquals("urn:microsoft:identity:fmi", capturedOptions.get().clientId(),
"clientId in callback should match the CCA client ID");
assertNotNull(capturedOptions.get().tokenEndpoint(),
"tokenEndpoint should be available in callback");
// Verify token was acquired
assertNotNull(result.accessToken(), "Access token should not be null");
}
/**
* Verifies that tokens acquired with different fmi_paths are isolated in cache
* even when using the same agent CCA.
*/
@Test
void agentFmiToken_CacheIsolation_DifferentFmiPaths() throws Exception {
Function<AssertionRequestOptions, String> assertionProvider = options -> {
try {
return acquireFmiCredentialFromRma();
} catch (Exception e) {
throw new RuntimeException("Failed to acquire FMI credential", e);
}
};
IClientCredential credential = ClientCredentialFactory.createFromCallback(assertionProvider);
ConfidentialClientApplication cca = ConfidentialClientApplication.builder(
"urn:microsoft:identity:fmi", credential)
.authority(AUTHORITY)
.azureRegion(TestConstants.AGENTIC_AZURE_REGION)
.build();
// Acquire with first fmi_path
ClientCredentialParameters params1 = ClientCredentialParameters
.builder(Collections.singleton(TestConstants.AGENTIC_FMI_EXCHANGE_SCOPE))
.fmiPath(TestConstants.AGENTIC_AGENT_APP_ID)
.build();
IAuthenticationResult result1 = cca.acquireToken(params1).get();
// Acquire with different fmi_path
ClientCredentialParameters params2 = ClientCredentialParameters
.builder(Collections.singleton(TestConstants.AGENTIC_FMI_EXCHANGE_SCOPE))
.fmiPath("SomeFmiPath/DifferentAgent")
.build();
IAuthenticationResult result2 = cca.acquireToken(params2).get();
// Should have separate cache entries
assertEquals(2, cca.tokenCache.accessTokens.size(),
"Different fmi_paths should produce separate cache entries");
assertNotEquals(result1.accessToken(), result2.accessToken(),
"Tokens for different fmi_paths should be different");
}
/**
* Full 3-leg agent identity flow: FMI → assertion → user_fic → user-scoped Graph token.
* Uses the assertion callback pattern where the blueprint CCA acquires the FMI credential
* and the agent CCA exchanges it for a user token.
*/
@Test
void agentUserIdentity_GetsTokenForGraph() throws Exception {
// Build agent CCA with assertion callback that acquires FMI credential
Function<AssertionRequestOptions, String> assertionProvider = options -> {
try {
return acquireFmiCredentialForAgent(TestConstants.AGENTIC_AGENT_APP_ID);
} catch (Exception e) {
throw new RuntimeException("Failed to acquire FMI credential", e);
}
};
IClientCredential credential = ClientCredentialFactory.createFromCallback(assertionProvider);
ConfidentialClientApplication agentCca = ConfidentialClientApplication.builder(TestConstants.AGENTIC_AGENT_APP_ID, credential)
.authority(AUTHORITY)
.build();
// Get instance token (T2) for user_fic exchange
String t2 = acquireInstanceTokenForAgent();
// Exchange T2 for user-scoped token via user_fic grant
UserFederatedIdentityCredentialParameters params = UserFederatedIdentityCredentialParameters
.builder(Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), TestConstants.AGENTIC_USER_UPN, t2)
.build();
IAuthenticationResult result = agentCca.acquireToken(params).get();
assertNotNull(result, "Auth result should not be null");
assertNotNull(result.accessToken(), "Access token should not be null");
assertFalse(result.accessToken().isEmpty(), "Access token should not be empty");
assertNotNull(result.account(), "Account should not be null (user token)");
// Verify token is cached and silent retrieval works
Set<IAccount> accounts = agentCca.getAccounts().get();
assertFalse(accounts.isEmpty(), "Accounts should be in cache");
IAccount account = accounts.iterator().next();
IAuthenticationResult silentResult = agentCca.acquireTokenSilently(
SilentParameters.builder(Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), account).build()).get();
assertEquals(result.accessToken(), silentResult.accessToken(),
"Silent call should return cached token");
}
/**
* Verifies that user_fic tokens and app-only tokens are isolated in cache
* on the same agent CCA instance. App token acquisition should not interfere
* with user token acquisition.
*/
@Test
void agentCca_AppAndUserTokens_CacheIsolation() throws Exception {
Function<AssertionRequestOptions, String> assertionProvider = options -> {
try {
return acquireFmiCredentialForAgent(TestConstants.AGENTIC_AGENT_APP_ID);
} catch (Exception e) {
throw new RuntimeException("Failed to acquire FMI credential", e);
}
};
IClientCredential credential = ClientCredentialFactory.createFromCallback(assertionProvider);
ConfidentialClientApplication agentCca = ConfidentialClientApplication.builder(TestConstants.AGENTIC_AGENT_APP_ID, credential)
.authority(AUTHORITY)
.build();
// Acquire app-only token
IAuthenticationResult appResult = agentCca.acquireToken(ClientCredentialParameters
.builder(Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE))
.build())
.get();
assertNotNull(appResult.accessToken());
// Acquire user token via user_fic (needs T2 = instance token)
String t2 = acquireInstanceTokenForAgent();
UserFederatedIdentityCredentialParameters userParams = UserFederatedIdentityCredentialParameters
.builder(Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), TestConstants.AGENTIC_USER_UPN, t2)
.build();
IAuthenticationResult userResult = agentCca.acquireToken(userParams).get();
assertNotNull(userResult.accessToken());
assertNotNull(userResult.account(), "User token should have an account");
// Tokens should be different (app vs user scoped)
assertNotEquals(appResult.accessToken(), userResult.accessToken(),
"App token and user token should be different");
// App cache should have 1 entry, user cache should have user account
assertEquals(2, agentCca.tokenCache.accessTokens.size(),
"Cache should have exactly 2 entries (app + user)");
}
// ========================================================================
// High-level AcquireTokenForAgent tests (composite API)
// ========================================================================
/**
* Tests the high-level acquireTokenForAgent API with a UPN-based AgentIdentity.
* Exercises the full 3-leg flow orchestrated internally by AcquireTokenForAgentSupplier.
*/
@Test
void acquireTokenForAgent_withUpn_fullFlow() throws Exception {
IClientCertificate clientCert = ClientCredentialFactory.createFromCertificate(privateKey, certificate);
ConfidentialClientApplication blueprintCca = ConfidentialClientApplication.builder(
TestConstants.AGENTIC_BLUEPRINT_CLIENT_ID, clientCert)
.authority(AUTHORITY)
.sendX5c(true)
.azureRegion(TestConstants.AGENTIC_AZURE_REGION)
.build();
AgentIdentity agentId = AgentIdentity.withUsername(TestConstants.AGENTIC_AGENT_APP_ID, TestConstants.AGENTIC_USER_UPN);
IAuthenticationResult result = blueprintCca.acquireTokenForAgent(
AcquireTokenForAgentParameters.builder(
Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), agentId).build()
).get();
assertNotNull(result, "Result should not be null");
assertNotNull(result.accessToken(), "Access token should not be null");
assertFalse(result.accessToken().isEmpty(), "Access token should not be empty");
assertNotNull(result.account(), "Account should not be null for user token");
}
/**
* Tests the high-level acquireTokenForAgent API for app-only (no user) scenarios.
* Only Legs 1-2 are performed.
*/
@Test
void acquireTokenForAgent_appOnly() throws Exception {
IClientCertificate clientCert = ClientCredentialFactory.createFromCertificate(privateKey, certificate);
ConfidentialClientApplication blueprintCca = ConfidentialClientApplication.builder(
TestConstants.AGENTIC_BLUEPRINT_CLIENT_ID, clientCert)
.authority(AUTHORITY)
.sendX5c(true)
.azureRegion(TestConstants.AGENTIC_AZURE_REGION)
.build();
AgentIdentity agentId = AgentIdentity.appOnly(TestConstants.AGENTIC_AGENT_APP_ID);
IAuthenticationResult result = blueprintCca.acquireTokenForAgent(
AcquireTokenForAgentParameters.builder(
Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), agentId).build()
).get();
assertNotNull(result, "Result should not be null");
assertNotNull(result.accessToken(), "Access token should not be null");
assertFalse(result.accessToken().isEmpty(), "Access token should not be empty");
}
/**
* Tests the high-level acquireTokenForAgent API with ForceRefresh.
* First call populates cache, second call (forceRefresh) bypasses it.
*/
@Test
void acquireTokenForAgent_forceRefresh() throws Exception {
IClientCertificate clientCert = ClientCredentialFactory.createFromCertificate(privateKey, certificate);
ConfidentialClientApplication blueprintCca = ConfidentialClientApplication.builder(
TestConstants.AGENTIC_BLUEPRINT_CLIENT_ID, clientCert)
.authority(AUTHORITY)
.sendX5c(true)
.azureRegion(TestConstants.AGENTIC_AZURE_REGION)
.build();
AgentIdentity agentId = AgentIdentity.withUsername(TestConstants.AGENTIC_AGENT_APP_ID, TestConstants.AGENTIC_USER_UPN);
// First call — populates cache
IAuthenticationResult result1 = blueprintCca.acquireTokenForAgent(
AcquireTokenForAgentParameters.builder(
Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), agentId).build()
).get();
assertNotNull(result1.accessToken());
// Second call without forceRefresh — should return cached token
IAuthenticationResult result2 = blueprintCca.acquireTokenForAgent(
AcquireTokenForAgentParameters.builder(
Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), agentId).build()
).get();
assertEquals(result1.accessToken(), result2.accessToken(),
"Second call should return cached token");
// Third call with forceRefresh — should get a fresh token
IAuthenticationResult result3 = blueprintCca.acquireTokenForAgent(
AcquireTokenForAgentParameters.builder(
Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), agentId)
.forceRefresh(true).build()
).get();
assertNotNull(result3.accessToken());
// The fresh token may be the same string (if not expired) but the flow exercised network
}
/**
* Tests cache isolation between two blueprint CCA instances.
* Each blueprint should have its own agent CCA cache.
*/
@Test
void acquireTokenForAgent_cacheIsolation_twoBlueprintCcas() throws Exception {
IClientCertificate clientCert = ClientCredentialFactory.createFromCertificate(privateKey, certificate);
ConfidentialClientApplication blueprint1 = ConfidentialClientApplication.builder(
TestConstants.AGENTIC_BLUEPRINT_CLIENT_ID, clientCert)
.authority(AUTHORITY)
.sendX5c(true)
.azureRegion(TestConstants.AGENTIC_AZURE_REGION)
.build();
ConfidentialClientApplication blueprint2 = ConfidentialClientApplication.builder(
TestConstants.AGENTIC_BLUEPRINT_CLIENT_ID, clientCert)
.authority(AUTHORITY)
.sendX5c(true)
.azureRegion(TestConstants.AGENTIC_AZURE_REGION)
.build();
AgentIdentity agentId = AgentIdentity.withUsername(TestConstants.AGENTIC_AGENT_APP_ID, TestConstants.AGENTIC_USER_UPN);
// Acquire via blueprint1
IAuthenticationResult result1 = blueprint1.acquireTokenForAgent(
AcquireTokenForAgentParameters.builder(
Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), agentId).build()
).get();
assertNotNull(result1.accessToken());
// Blueprint1 should have agent CCA cached, blueprint2 should not
assertEquals(1, blueprint1.agentCcaCache.size(),
"Blueprint1 should have one cached agent CCA");
assertTrue(blueprint2.agentCcaCache.isEmpty(),
"Blueprint2 should have no cached agent CCAs (no bleed)");
// Acquire via blueprint2
IAuthenticationResult result2 = blueprint2.acquireTokenForAgent(
AcquireTokenForAgentParameters.builder(
Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), agentId).build()
).get();
assertNotNull(result2.accessToken());
// Both should now have their own cache entries
assertEquals(1, blueprint1.agentCcaCache.size());
assertEquals(1, blueprint2.agentCcaCache.size());
}
/**
* Tests that a UPN-based token can be found by OID lookup on the same blueprint.
* Discovers the OID via the UPN flow, then verifies OID-based call returns cached token.
*/
@Test
void acquireTokenForAgent_upnThenOid_sharesCache() throws Exception {
IClientCertificate clientCert = ClientCredentialFactory.createFromCertificate(privateKey, certificate);
ConfidentialClientApplication blueprintCca = ConfidentialClientApplication.builder(
TestConstants.AGENTIC_BLUEPRINT_CLIENT_ID, clientCert)
.authority(AUTHORITY)
.sendX5c(true)
.azureRegion(TestConstants.AGENTIC_AZURE_REGION)
.build();
// Step 1: Acquire via UPN
AgentIdentity upnIdentity = AgentIdentity.withUsername(TestConstants.AGENTIC_AGENT_APP_ID, TestConstants.AGENTIC_USER_UPN);
IAuthenticationResult upnResult = blueprintCca.acquireTokenForAgent(
AcquireTokenForAgentParameters.builder(
Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), upnIdentity).build()
).get();
assertNotNull(upnResult.account(), "Account should not be null");
// Extract OID from account's homeAccountId (format: oid.tid)
String homeAccountId = upnResult.account().homeAccountId();
assertNotNull(homeAccountId);
String oidString = homeAccountId.contains(".")
? homeAccountId.substring(0, homeAccountId.indexOf('.'))
: homeAccountId;
java.util.UUID userOid = java.util.UUID.fromString(oidString);
// Step 2: Acquire via OID — should come from cache
AgentIdentity oidIdentity = new AgentIdentity(TestConstants.AGENTIC_AGENT_APP_ID, userOid);
IAuthenticationResult oidResult = blueprintCca.acquireTokenForAgent(
AcquireTokenForAgentParameters.builder(
Collections.singleton(TestConstants.AGENTIC_GRAPH_SCOPE), oidIdentity).build()
).get();
// Should return the same cached token
assertEquals(upnResult.accessToken(), oidResult.accessToken(),
"OID-based call should return the same cached token as UPN-based call");
}
// ========================================================================
// Helpers
// ========================================================================
/**
* Helper: acquires an FMI credential from the RMA (Resource Management Application).
* Uses TestConstants.AGENTIC_FMI_EXCHANGE_SCOPE, matching FmiIT's Flow3 pattern.
* Suitable for use as client_assertion when client_id = "urn:microsoft:identity:fmi".
*/
private String acquireFmiCredentialFromRma() throws Exception {
IClientCertificate clientCert = ClientCredentialFactory.createFromCertificate(privateKey, certificate);
ConfidentialClientApplication rmaCca = ConfidentialClientApplication.builder(
TestConstants.AGENTIC_RMA_CLIENT_ID, clientCert)
.authority(AUTHORITY)
.sendX5c(true)
.azureRegion(TestConstants.AGENTIC_AZURE_REGION)
.build();
ClientCredentialParameters params = ClientCredentialParameters
.builder(Collections.singleton(TestConstants.AGENTIC_FMI_EXCHANGE_SCOPE))
.fmiPath("SomeFmiPath/FmiCredentialPath")
.build();
IAuthenticationResult result = rmaCca.acquireToken(params).get();
return result.accessToken();
}
/**
* Helper: acquires an FMI credential from the blueprint app for the given agent app ID.
* This is Leg 1 of the agent identity flow — returns T1.
*/
private String acquireFmiCredentialForAgent(String agentAppId) throws Exception {
IClientCertificate clientCert = ClientCredentialFactory.createFromCertificate(privateKey, certificate);
ConfidentialClientApplication blueprintCca = ConfidentialClientApplication.builder(
TestConstants.AGENTIC_BLUEPRINT_CLIENT_ID, clientCert)
.authority(AUTHORITY)
.sendX5c(true)
.azureRegion(TestConstants.AGENTIC_AZURE_REGION)
.build();
ClientCredentialParameters params = ClientCredentialParameters
.builder(Collections.singleton(TestConstants.AGENTIC_TOKEN_EXCHANGE_SCOPE))
.fmiPath(agentAppId)
.build();
IAuthenticationResult result = blueprintCca.acquireToken(params).get();
return result.accessToken();
}
/**
* Helper: acquires an instance token (T2) for the agent app via the full 2-leg flow.
* Leg 1: Blueprint → T1 (FMI credential)
* Leg 2: Agent uses T1 as client_assertion → T2 (instance token)
* T2 is used as the user_federated_identity_credential in Leg 3 (user_fic exchange).
*/
private String acquireInstanceTokenForAgent() throws Exception {
String t1 = acquireFmiCredentialForAgent(TestConstants.AGENTIC_AGENT_APP_ID);
IClientCredential agentCredential = ClientCredentialFactory.createFromClientAssertion(t1);
ConfidentialClientApplication agentCca = ConfidentialClientApplication.builder(TestConstants.AGENTIC_AGENT_APP_ID, agentCredential)
.authority(AUTHORITY)
.build();
ClientCredentialParameters instanceParams = ClientCredentialParameters
.builder(Collections.singleton(TestConstants.AGENTIC_TOKEN_EXCHANGE_SCOPE))
.skipCache(true)
.build();
IAuthenticationResult instanceResult = agentCca.acquireToken(instanceParams).get();
return instanceResult.accessToken();
}
}