diff --git a/.github/workflows/identity-github-actions-credential.yml b/.github/workflows/identity-github-actions-credential.yml new file mode 100644 index 0000000000000..a92490f5eedde --- /dev/null +++ b/.github/workflows/identity-github-actions-credential.yml @@ -0,0 +1,66 @@ +name: Identity GitHub Actions credential + +on: + push: + branches: + - vcolin7-github-actions-credential + workflow_dispatch: + +permissions: + contents: read + +jobs: + authenticate: + name: ${{ matrix.package }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + id-token: write + strategy: + fail-fast: false + matrix: + include: + - package: com.azure:azure-identity + pom: sdk/identity/azure-identity/pom.xml + - package: com.azure.v2:azure-identity + pom: sdk/identity-v2/azure-identity/pom.xml + env: + AZURE_TENANT_ID: ${{ vars.AZURE_IDENTITY_GITHUB_ACTIONS_TENANT_ID }} + AZURE_CLIENT_ID: ${{ vars.AZURE_IDENTITY_GITHUB_ACTIONS_CLIENT_ID }} + AZURE_TEST_MODE: LIVE + RUN_GITHUB_ACTIONS_CREDENTIAL_LIVE_TESTS: 'true' + SDK_COORDINATES: ${{ matrix.package }} + SDK_POM: ${{ matrix.pom }} + steps: + - name: Check test identity configuration + shell: bash + run: | + if [[ -z "$AZURE_TENANT_ID" || -z "$AZURE_CLIENT_ID" ]]; then + echo "::error::Set AZURE_IDENTITY_GITHUB_ACTIONS_TENANT_ID and AZURE_IDENTITY_GITHUB_ACTIONS_CLIENT_ID repository variables." + exit 1 + fi + + - name: Checkout code + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + + - name: Set up JDK 25 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 + with: + distribution: temurin + java-version: '25' + cache: maven + + - name: Build the selected SDK and its dependencies + shell: bash + run: > + mvn -B -ntp -f pom.xml -pl "$SDK_COORDINATES" -am + install -DskipTests -Djacoco.skip=true -Dgpg.skip=true + + - name: Authenticate through GitHub OIDC and Microsoft Entra + shell: bash + run: > + mvn -B -ntp -f "$SDK_POM" + test -Dtest=GitHubActionsCredentialLiveTest diff --git a/sdk/identity-v2/azure-identity/CHANGELOG.md b/sdk/identity-v2/azure-identity/CHANGELOG.md index b52c100ddf485..9c6737b549aae 100644 --- a/sdk/identity-v2/azure-identity/CHANGELOG.md +++ b/sdk/identity-v2/azure-identity/CHANGELOG.md @@ -4,17 +4,10 @@ ### Features Added -- Added support for user-assigned managed identities on Azure Arc in `ManagedIdentityCredential` and `DefaultAzureCredential`. - ### Breaking Changes ### Bugs Fixed -- Fixed `DefaultAzureCredential` failing after a credential successfully acquired a token. -- Aligned user-assigned managed identity validation for Azure Service Fabric with `azure-identity`. - ### Other Changes #### Dependency Updates - -- Upgraded `msal4j` from `1.23.1` to `1.26.0`. diff --git a/sdk/identity-v2/azure-identity/README.md b/sdk/identity-v2/azure-identity/README.md index f69486778d5b0..eb080f43e7843 100644 --- a/sdk/identity-v2/azure-identity/README.md +++ b/sdk/identity-v2/azure-identity/README.md @@ -30,9 +30,71 @@ To take dependency on a particular version of the library that isn't present in ## Examples +### Authenticate GitHub Actions workflows + +`com.azure.v2.identity.GitHubActionsCredential` authenticates through GitHub Actions OIDC federation. +Configure an Entra application's federated identity credential to trust your GitHub workflow's issuer, subject, +and audience, following [GitHub's Azure OIDC setup guide][github_oidc]. + +The workflow needs `permissions: id-token: write`. Set `AZURE_TENANT_ID` and `AZURE_CLIENT_ID` in the workflow +environment. GitHub supplies `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN`; do not +configure those values as repository secrets or print them. No client secret, certificate, or `azure/login` +step is required. + +```java readme-sample-v2-github-actions-credential +TokenCredential gitHubCredential = new GitHubActionsCredentialBuilder().build(); +``` + +The builder also accepts explicit IDs, which override the environment variables: + +```java readme-sample-v2-github-actions-credential-explicit +TokenCredential explicitCredential + = new GitHubActionsCredentialBuilder().tenantId("").clientId("").build(); +``` + +The v2 credential uses `com.azure.v2.core.credentials.TokenCredential` and its synchronous `getToken` API. +It is not included in `DefaultAzureCredential`. + +An explicit `authorityHost` takes precedence over `AZURE_AUTHORITY_HOST`, followed by Azure Public. +The assertion audience is derived from the effective authority; configure the same audience on the federated +identity credential: + +| Authority host | Audience | +| --- | --- | +| `https://login.microsoftonline.com/` | `api://AzureADTokenExchange` | +| `https://login.chinacloudapi.cn/` | `api://AzureADTokenExchangeChina` | +| `https://login.microsoftonline.us/` | `api://AzureADTokenExchangeUSGov` | +| `https://login.sovcloud-identity.fr/` | `api://AzureADTokenExchangeFrance` | +| `https://login.sovcloud-identity.de/` | `api://AzureADTokenExchangeGermany` | +| `https://login.sovcloud-identity.sg/` | `api://AzureADTokenExchangeGovSG` | + +### Run the opt-in end-to-end test + +The [Identity GitHub Actions credential workflow][github_oidc_workflow] builds both Identity +packages from source and requests a public-cloud ARM access token from each, without calling Azure resources or +logging token values. It runs on pushes to `vcolin7-github-actions-credential` and also supports manual dispatch. + +Configure a test application's federated identity credential for your repository's actual issuer and subject +(including immutable IDs when applicable), the ref to be tested, and audience `api://AzureADTokenExchange`. +Set repository variables `AZURE_IDENTITY_GITHUB_ACTIONS_TENANT_ID` and `AZURE_IDENTITY_GITHUB_ACTIONS_CLIENT_ID`, +then push the workflow and SDK changes to `vcolin7-github-actions-credential` in your fork. +For manual runs, the workflow must first be present on the repository's default branch; you can then dispatch +it on a trusted ref. The workflow does not create cloud resources or repository settings. + +The dedicated live test is skipped unless `RUN_GITHUB_ACTIONS_CREDENTIAL_LIVE_TESTS=true`, `AZURE_TEST_MODE=LIVE`, +and `GITHUB_ACTIONS=true`. The workflow supplies those settings. ## Troubleshooting +`GitHubActionsCredentialBuilder.build()` raises `CredentialUnavailableException` when required configuration is +missing, the runner request URL is invalid, or the authority has no supported audience mapping. Supply the Azure IDs +through the builder or environment and ensure the job has `permissions: id-token: write`. The runner request URL +must be an absolute HTTPS URL. + +GitHub OIDC HTTP or response-parsing failures raise `CredentialAuthenticationException`. For HTTP 401/403, +check the workflow permissions and run the SDK in the step where GitHub provides its OIDC variables. +For Entra federation errors, verify that the issuer, subject, and audience match the application's federated +identity credential. Error messages do not include the assertion or raw OIDC response body. ## Next steps @@ -47,3 +109,5 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ +[github_oidc]: https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-azure +[github_oidc_workflow]: https://github.com/Azure/azure-sdk-for-java/blob/main/.github/workflows/identity-github-actions-credential.yml diff --git a/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java new file mode 100644 index 0000000000000..ac12ab1d18b5b --- /dev/null +++ b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredential.java @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.identity; + +import com.azure.v2.core.credentials.TokenCredential; +import com.azure.v2.core.credentials.TokenRequestContext; +import com.azure.v2.identity.exceptions.CredentialAuthenticationException; +import com.azure.v2.identity.implementation.models.ConfidentialClientOptions; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.models.CoreException; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.serialization.json.JsonReader; +import io.clientcore.core.serialization.json.JsonToken; +import io.clientcore.core.utils.CoreUtils; + +import java.io.IOException; + +/** + * Authenticates an application in GitHub Actions using an OIDC federated identity credential. + * + *

Configure a federated identity credential on the Microsoft Entra application that trusts the GitHub workflow's + * issuer, subject, and audience. The workflow needs {@code permissions: id-token: write}. GitHub supplies the + * OIDC request URL and bearer token. The client and tenant IDs default to {@code AZURE_CLIENT_ID} and + * {@code AZURE_TENANT_ID}; they can also be set on {@link GitHubActionsCredentialBuilder}.

+ * + *

The assertion audience is selected from the authority host. This credential supports Azure Public, China, + * US Government, France Government, Germany Government, and Singapore Government. It is not included in + * {@link DefaultAzureCredential}.

+ * + * + *
+ * GitHubActionsCredential credential = new GitHubActionsCredentialBuilder().build();
+ * 
+ * + * + * @see GitHubActionsCredentialBuilder + */ +public class GitHubActionsCredential implements TokenCredential { + private static final ClientLogger LOGGER = new ClientLogger(GitHubActionsCredential.class); + private final ClientAssertionCredential clientAssertionCredential; + + GitHubActionsCredential(String requestUrl, String requestToken, ConfidentialClientOptions options) { + options.setClientAssertionFunction(pipeline -> { + HttpRequest request = new HttpRequest().setMethod(HttpMethod.GET) + .setUri(requestUrl) + .setHeaders(new HttpHeaders().set(HttpHeaderName.AUTHORIZATION, "Bearer " + requestToken)); + try (Response response = pipeline.send(request)) { + if (response.getStatusCode() != 200) { + throw authenticationError("OIDC request returned status code " + response.getStatusCode() + "."); + } + return readAssertion(response); + } + }); + clientAssertionCredential = new ClientAssertionCredential(options); + } + + /** + * Acquires an access token, using the token cache when possible. + * + *

Requests with a Continuous Access Evaluation (CAE) claims challenge acquire a new token instead of reusing a + * cached token.

+ * + * @param request the scopes, tenant, and authentication options for the token request. + * @return the access token. + * @throws CredentialAuthenticationException if the GitHub OIDC request fails or returns an invalid assertion response. + */ + @Override + public AccessToken getToken(TokenRequestContext request) { + try { + return clientAssertionCredential.getToken(request); + } catch (CoreException e) { + // Preserve the OIDC failure category through client-assertion delegation. + Throwable cause = e.getCause(); + if (cause instanceof CredentialAuthenticationException) { + throw (CredentialAuthenticationException) cause; + } + throw e; + } + } + + private static String readAssertion(Response response) { + BinaryData body = response.getValue(); + String text = body == null ? null : body.toString(); + if (CoreUtils.isNullOrEmpty(text)) { + throw authenticationError("Received null token from OIDC request."); + } + try (JsonReader reader = JsonReader.fromString(text)) { + JsonToken token = reader.nextToken(); + if (token == JsonToken.END_DOCUMENT) { + throw authenticationError("Failed to parse OIDC response."); + } + String assertion = null; + if (token == JsonToken.START_OBJECT) { + assertion = reader.readObject(objectReader -> { + String value = null; + while (objectReader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = objectReader.getFieldName(); + objectReader.nextToken(); + if ("value".equals(fieldName)) { + if (objectReader.currentToken() == JsonToken.STRING) { + value = objectReader.getString(); + } else { + value = null; + objectReader.skipChildren(); + } + } else { + objectReader.skipChildren(); + } + } + return value; + }); + } else { + reader.skipChildren(); + } + if (reader.nextToken() != JsonToken.END_DOCUMENT) { + throw authenticationError("Failed to parse OIDC response."); + } + if (CoreUtils.isNullOrEmpty(assertion)) { + throw authenticationError("\"value\" field not detected in the response."); + } + return assertion; + } catch (IOException | IllegalStateException e) { + String message = "GitHubActionsCredential: Authentication Failed. Failed to parse OIDC response."; + throw LOGGER.throwableAtError() + .log(message, sanitizedCause(e), + (ignored, cause) -> new CredentialAuthenticationException(message, cause)); + } + } + + // Parser and URI exception messages can contain secrets. Retain their type and stack trace, not their input. + static RuntimeException sanitizedCause(Exception exception) { + if (exception == null) { + return null; + } + RuntimeException sanitized + = new IllegalArgumentException(exception.getClass().getSimpleName() + " (input redacted)"); + sanitized.setStackTrace(exception.getStackTrace()); + return sanitized; + } + + private static CredentialAuthenticationException authenticationError(String message) { + throw LOGGER.throwableAtError() + .addKeyValue("reason", message) + .log("GitHubActionsCredential: Authentication Failed.", ignored -> new CredentialAuthenticationException( + "GitHubActionsCredential: Authentication Failed. " + message)); + } +} diff --git a/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredentialBuilder.java b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredentialBuilder.java new file mode 100644 index 0000000000000..ef1eb8b388c5d --- /dev/null +++ b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/GitHubActionsCredentialBuilder.java @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.identity; + +import com.azure.v2.identity.exceptions.CredentialUnavailableException; +import com.azure.v2.identity.implementation.models.ClientOptions; +import com.azure.v2.identity.implementation.models.ConfidentialClientOptions; +import com.azure.v2.identity.implementation.util.ValidationUtil; +import com.azure.v2.identity.models.TokenCachePersistenceOptions; +import io.clientcore.core.instrumentation.logging.ClientLogger; +import io.clientcore.core.utils.CoreUtils; +import io.clientcore.core.utils.UriBuilder; +import io.clientcore.core.utils.configuration.Configuration; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * Fluent builder for {@link GitHubActionsCredential}. + * + *

Client and tenant IDs can be supplied explicitly or through {@code AZURE_CLIENT_ID} and + * {@code AZURE_TENANT_ID}. GitHub supplies {@code ACTIONS_ID_TOKEN_REQUEST_URL} and + * {@code ACTIONS_ID_TOKEN_REQUEST_TOKEN} to workflow steps with {@code permissions: id-token: write}.

+ * + * + *
+ * GitHubActionsCredential credential = new GitHubActionsCredentialBuilder().build();
+ * 
+ * + * + * @see GitHubActionsCredential + */ +public class GitHubActionsCredentialBuilder extends EntraIdCredentialBuilderBase { + private static final ClientLogger LOGGER = new ClientLogger(GitHubActionsCredentialBuilder.class); + private final ConfidentialClientOptions confidentialClientOptions = new ConfidentialClientOptions(); + private String authorityHost; + + /** + * Creates a builder for a GitHub Actions credential. + */ + public GitHubActionsCredentialBuilder() { + } + + @Override + public GitHubActionsCredentialBuilder authorityHost(String authorityHost) { + super.authorityHost(authorityHost); + this.authorityHost = authorityHost; + return this; + } + + /** + * Enables the persistent token cache with the specified options. Persistence is disabled by default. + * + * @param tokenCachePersistenceOptions the persistent token cache options. + * @return this builder. + */ + public GitHubActionsCredentialBuilder + tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { + confidentialClientOptions.setTokenCacheOptions(tokenCachePersistenceOptions); + return this; + } + + /** + * Builds a credential using the configured values and the GitHub Actions environment. + * + *

An explicit client ID, tenant ID, or authority host takes precedence over its environment variable. + * The default authority is Azure Public. The assertion audience is derived from the authority host. + * Missing GitHub runner variables are reported together with a link to troubleshooting guidance.

+ * + * @return the configured credential. + * @throws CredentialUnavailableException if required configuration is missing, the GitHub request URL is + * invalid, or the authority host does not have a supported token-exchange audience. + * @throws IllegalArgumentException if the tenant ID is invalid. + */ + public GitHubActionsCredential build() { + Configuration configuration = confidentialClientOptions.getConfiguration(); + if (configuration == null) { + configuration = Configuration.getGlobalConfiguration(); + } + String clientId = required("AZURE_CLIENT_ID", + CoreUtils.isNullOrEmpty(confidentialClientOptions.getClientId()) + ? configuration.get("AZURE_CLIENT_ID") + : confidentialClientOptions.getClientId()); + String tenantId = required("AZURE_TENANT_ID", + CoreUtils.isNullOrEmpty(confidentialClientOptions.getTenantId()) + ? configuration.get("AZURE_TENANT_ID") + : confidentialClientOptions.getTenantId()); + ValidationUtil.validateTenantIdCharacterRange(tenantId, LOGGER); + String requestUrl = configuration.get("ACTIONS_ID_TOKEN_REQUEST_URL"); + String requestToken = configuration.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN"); + List missing = new ArrayList<>(2); + if (CoreUtils.isNullOrEmpty(requestUrl)) { + missing.add("ACTIONS_ID_TOKEN_REQUEST_URL"); + } + if (CoreUtils.isNullOrEmpty(requestToken)) { + missing.add("ACTIONS_ID_TOKEN_REQUEST_TOKEN"); + } + if (!missing.isEmpty()) { + String missingSettings = String.join(", ", missing); + String message + = "GitHubActionsCredential requires " + missingSettings + ". Run in a GitHub Actions workflow with " + + "'permissions: id-token: write'. For troubleshooting information, see " + + "https://aka.ms/azsdk/java/identity/troubleshoot."; + throw LOGGER.throwableAtError() + .addKeyValue("setting", missingSettings) + .log("GitHubActionsCredential configuration is incomplete.", + ignored -> new CredentialUnavailableException(message)); + } + String resolvedAuthority = authorityHost == null ? configuration.get("AZURE_AUTHORITY_HOST") : authorityHost; + if (resolvedAuthority == null) { + resolvedAuthority = AzureAuthorityHosts.AZURE_PUBLIC_CLOUD; + } + String audience = audienceForAuthority(resolvedAuthority); + ConfidentialClientOptions options = new ConfidentialClientOptions(confidentialClientOptions); + options.setClientId(clientId).setTenantId(tenantId).setAuthorityHost(resolvedAuthority); + return new GitHubActionsCredential(requestUrlWithAudience(requestUrl, audience), requestToken, options); + } + + @Override + ClientOptions getClientOptions() { + return confidentialClientOptions; + } + + private static String required(String name, String value) { + if (CoreUtils.isNullOrEmpty(value)) { + String message = "GitHubActionsCredential requires " + name + + ". Configure the Azure client and tenant IDs and run in a GitHub Actions workflow with " + + "'permissions: id-token: write'."; + throw LOGGER.throwableAtError() + .addKeyValue("setting", name) + .log("GitHubActionsCredential configuration is incomplete.", + ignored -> new CredentialUnavailableException(message)); + } + return value; + } + + private static String audienceForAuthority(String authority) { + try { + URI uri = new URI(authority); + if ("https".equalsIgnoreCase(uri.getScheme()) && uri.getHost() != null && uri.getUserInfo() == null) { + switch (uri.getHost().toLowerCase(Locale.ROOT)) { + case "login.microsoftonline.com": + return "api://AzureADTokenExchange"; + + case "login.chinacloudapi.cn": + return "api://AzureADTokenExchangeChina"; + + case "login.microsoftonline.us": + return "api://AzureADTokenExchangeUSGov"; + + case "login.sovcloud-identity.fr": + return "api://AzureADTokenExchangeFrance"; + + case "login.sovcloud-identity.de": + return "api://AzureADTokenExchangeGermany"; + + case "login.sovcloud-identity.sg": + return "api://AzureADTokenExchangeGovSG"; + + default: + break; + } + } + } catch (URISyntaxException e) { + throw unsupportedAuthority(e); + } + throw unsupportedAuthority(null); + } + + private static CredentialUnavailableException unsupportedAuthority(Exception cause) { + throw LOGGER.throwableAtError() + .log( + "GitHubActionsCredential does not support the configured authority host. " + + "Use an Azure Public, China, US Government, France Government, Germany Government, " + + "or Singapore Government authority.", + GitHubActionsCredential.sanitizedCause(cause), CredentialUnavailableException::new); + } + + private static String requestUrlWithAudience(String requestUrl, String audience) { + try { + URI uri = new URI(requestUrl); + if (!"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getUserInfo() != null + || uri.getFragment() != null) { + throw invalidRequestUrl(null); + } + return UriBuilder.parse(requestUrl) + .setQueryParameter("audience", URLEncoder.encode(audience, StandardCharsets.UTF_8.name())) + .toString(); + } catch (URISyntaxException | IOException e) { + throw invalidRequestUrl(e); + } + } + + private static CredentialUnavailableException invalidRequestUrl(Exception cause) { + throw LOGGER.throwableAtError() + .log( + "GitHubActionsCredential requires ACTIONS_ID_TOKEN_REQUEST_URL to be an absolute HTTPS URL " + + "without user information or a fragment.", + GitHubActionsCredential.sanitizedCause(cause), CredentialUnavailableException::new); + } +} diff --git a/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/implementation/client/ConfidentialClient.java b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/implementation/client/ConfidentialClient.java index 04ad98a803dbf..6bd495389cb0b 100644 --- a/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/implementation/client/ConfidentialClient.java +++ b/sdk/identity-v2/azure-identity/src/main/java/com/azure/v2/identity/implementation/client/ConfidentialClient.java @@ -89,6 +89,10 @@ public AccessToken authenticate(TokenRequestContext request) { builder.clientCredential(ClientCredentialFactory.createFromClientAssertion( confidentialClientOptions.getClientAssertionFunction().apply(getPipeline()))); } + if (request.isCaeEnabled() && request.getClaims() != null) { + ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims()); + builder.claims(claimsRequest).skipCache(true); + } try { return new MsalToken(confidentialClient.acquireToken(builder.build()).get()); } catch (InterruptedException | ExecutionException e) { @@ -116,6 +120,9 @@ public AccessToken authenticateWithCache(TokenRequestContext request) { */ @SuppressWarnings("deprecation") public AccessToken authenticateWithCache(TokenRequestContext request, IAccount account) { + if (account == null && request.isCaeEnabled() && request.getClaims() != null) { + return null; + } ConfidentialClientApplication confidentialClientApplication = getConfidentialClientInstance(request).getValue(); SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder(new HashSet<>(request.getScopes())) diff --git a/sdk/identity-v2/azure-identity/src/samples/java/com/azure/v2/identity/GitHubActionsCredentialJavaDocCodeSnippets.java b/sdk/identity-v2/azure-identity/src/samples/java/com/azure/v2/identity/GitHubActionsCredentialJavaDocCodeSnippets.java new file mode 100644 index 0000000000000..9faa752f6549c --- /dev/null +++ b/sdk/identity-v2/azure-identity/src/samples/java/com/azure/v2/identity/GitHubActionsCredentialJavaDocCodeSnippets.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.identity; + +import com.azure.v2.core.credentials.TokenCredential; + +class GitHubActionsCredentialJavaDocCodeSnippets { + void construct() { + // BEGIN: com.azure.v2.identity.credential.githubactionscredential.construct + GitHubActionsCredential credential = new GitHubActionsCredentialBuilder().build(); + // END: com.azure.v2.identity.credential.githubactionscredential.construct + + // BEGIN: readme-sample-v2-github-actions-credential + TokenCredential gitHubCredential = new GitHubActionsCredentialBuilder().build(); + // END: readme-sample-v2-github-actions-credential + + // BEGIN: readme-sample-v2-github-actions-credential-explicit + TokenCredential explicitCredential + = new GitHubActionsCredentialBuilder().tenantId("").clientId("").build(); + // END: readme-sample-v2-github-actions-credential-explicit + } +} diff --git a/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialBuilderTest.java b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialBuilderTest.java new file mode 100644 index 0000000000000..17c9062c22740 --- /dev/null +++ b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialBuilderTest.java @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.identity; + +import com.azure.v2.core.credentials.TokenRequestContext; +import com.azure.v2.identity.exceptions.CredentialUnavailableException; +import io.clientcore.core.utils.configuration.Configuration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Map; + +import static com.azure.v2.identity.GitHubActionsCredentialTest.SCOPE; +import static com.azure.v2.identity.GitHubActionsCredentialTest.credentialBuilder; +import static com.azure.v2.identity.GitHubActionsCredentialTest.configuration; +import static com.azure.v2.identity.GitHubActionsCredentialTest.parseForm; +import static com.azure.v2.identity.GitHubActionsCredentialTest.settings; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GitHubActionsCredentialBuilderTest { + @ParameterizedTest + @ValueSource( + strings = { + "AZURE_TENANT_ID", + "AZURE_CLIENT_ID", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN" }) + void validatesEveryRequiredSettingBeforeHttp(String setting) { + for (String value : new String[] { null, "" }) { + Map values = settings(); + values.put(setting, value); + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + CredentialUnavailableException error = assertThrows(CredentialUnavailableException.class, + () -> credentialBuilder(http).configuration(configuration(values)).build()); + assertTrue(error.getMessage().contains(setting)); + assertTrue(error.getMessage().contains("id-token: write")); + assertFalse(error.getMessage().contains("runner-token-sentinel")); + if (setting.startsWith("ACTIONS_ID_TOKEN_REQUEST_")) { + assertTrue(error.getMessage().contains("https://aka.ms/azsdk/java/identity/troubleshoot")); + String configuredSetting + = setting.endsWith("_URL") ? "ACTIONS_ID_TOKEN_REQUEST_TOKEN" : "ACTIONS_ID_TOKEN_REQUEST_URL"; + assertFalse(error.getMessage().contains(configuredSetting)); + } + assertEquals(0, http.oidcRequests.get()); + } + } + + @ParameterizedTest + @CsvSource(value = { "null,null", "null,''", "'',null", "'',''" }, nullValues = "null") + void reportsBothMissingGitHubVariables(String requestUrl, String requestToken) { + Map values = settings(); + values.put("ACTIONS_ID_TOKEN_REQUEST_URL", requestUrl); + values.put("ACTIONS_ID_TOKEN_REQUEST_TOKEN", requestToken); + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + CredentialUnavailableException error = assertThrows(CredentialUnavailableException.class, + () -> credentialBuilder(http).configuration(configuration(values)).build()); + assertTrue(error.getMessage().contains("ACTIONS_ID_TOKEN_REQUEST_URL, ACTIONS_ID_TOKEN_REQUEST_TOKEN")); + assertTrue(error.getMessage().contains("permissions: id-token: write")); + assertTrue(error.getMessage().contains("https://aka.ms/azsdk/java/identity/troubleshoot")); + assertEquals(0, http.oidcRequests.get()); + } + + @Test + void explicitIdsOverrideEnvironmentAndCredentialsSnapshotBuilderValues() { + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + GitHubActionsCredentialBuilder builder + = credentialBuilder(http).clientId("explicit-client").tenantId("explicit-tenant"); + GitHubActionsCredential first = builder.build(); + GitHubActionsCredential second = builder.clientId("second-client").tenantId("second-tenant").build(); + assertEquals(0, http.oidcRequests.get()); + first.getToken(new TokenRequestContext().addScopes(SCOPE)); + assertEquals("explicit-client", http.tokenForms.get(0).get("client_id")); + assertTrue(http.lastTokenPath.contains("explicit-tenant")); + second.getToken(new TokenRequestContext().addScopes(SCOPE)); + assertEquals("second-client", http.tokenForms.get(1).get("client_id")); + assertTrue(http.lastTokenPath.contains("second-tenant")); + } + + @Test + void disabledConfigurationDoesNotFallBackToTheEnvironment() { + assertThrows(CredentialUnavailableException.class, + () -> new GitHubActionsCredentialBuilder().configuration(Configuration.none()).build()); + } + + @ParameterizedTest + @CsvSource({ + "login.microsoftonline.com,AzureADTokenExchange", + "login.chinacloudapi.cn,AzureADTokenExchangeChina", + "login.microsoftonline.us,AzureADTokenExchangeUSGov", + "login.sovcloud-identity.fr,AzureADTokenExchangeFrance", + "login.sovcloud-identity.de,AzureADTokenExchangeGermany", + "login.sovcloud-identity.sg,AzureADTokenExchangeGovSG", + "LOGIN.MICROSOFTONLINE.COM,AzureADTokenExchange" }) + void derivesTheAudienceFromTheConfiguredAuthority(String host, String audience) { + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + Map values = settings(); + values.put("AZURE_AUTHORITY_HOST", "https://" + host + "/"); + values.put("ACTIONS_ID_TOKEN_REQUEST_URL", + "https://github-oidc.test/token?encoded=a%2Fb&audience=old&audience=duplicate"); + credentialBuilder(http).configuration(configuration(values)) + .build() + .getToken(new TokenRequestContext().addScopes(SCOPE)); + String query = http.oidcRequest.getUri().getRawQuery(); + assertEquals("api://" + audience, parseForm(query).get("audience")); + assertEquals("a/b", parseForm(query).get("encoded")); + assertEquals(1, query.split("audience=", -1).length - 1); + assertTrue(query.contains("api%3A%2F%2F")); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void explicitAuthorityWinsRegardlessOfConfigurationSetterOrder(boolean configurationFirst) { + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + Map values = settings(); + values.put("AZURE_AUTHORITY_HOST", AzureAuthorityHosts.AZURE_CHINA); + GitHubActionsCredentialBuilder builder = credentialBuilder(http); + if (configurationFirst) { + builder.configuration(configuration(values)).authorityHost(AzureAuthorityHosts.AZURE_GOVERNMENT); + } else { + builder.authorityHost(AzureAuthorityHosts.AZURE_GOVERNMENT).configuration(configuration(values)); + } + builder.build().getToken(new TokenRequestContext().addScopes(SCOPE)); + assertEquals("api://AzureADTokenExchangeUSGov", + parseForm(http.oidcRequest.getUri().getRawQuery()).get("audience")); + assertEquals("login.microsoftonline.us", http.tokenRequest.getUri().getHost()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "https://unsupported.test", + "https://login.microsoftonline.com.attacker.test", + "https://login.microsoftonline.de", + "https://user:secret@login.microsoftonline.com" }) + void rejectsUnsupportedAuthorityHosts(String authority) { + assertThrows(CredentialUnavailableException.class, + () -> credentialBuilder(new GitHubActionsCredentialTest.FakeHttpClient()).authorityHost(authority).build()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "not a URI", + "/relative", + "http://github-oidc.test/token", + "https:///token", + "https://user:secret@github-oidc.test/token", + "https://github-oidc.test/token#fragment" }) + void rejectsInvalidRunnerUrls(String url) { + Map values = settings(); + values.put("ACTIONS_ID_TOKEN_REQUEST_URL", url); + CredentialUnavailableException error = assertThrows(CredentialUnavailableException.class, + () -> credentialBuilder(new GitHubActionsCredentialTest.FakeHttpClient()) + .configuration(configuration(values)) + .build()); + assertFalse(error.getMessage().contains("secret")); + } + + @Test + void validatesEnvironmentTenantAndSupportsUrlsWithoutQueries() { + Map values = settings(); + values.put("AZURE_TENANT_ID", "invalid/tenant"); + assertThrows(IllegalArgumentException.class, + () -> credentialBuilder(new GitHubActionsCredentialTest.FakeHttpClient()) + .configuration(configuration(values)) + .build()); + values.put("AZURE_TENANT_ID", "valid-tenant"); + values.put("ACTIONS_ID_TOKEN_REQUEST_URL", "https://github-oidc.test/token"); + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + assertNotNull(credentialBuilder(http).configuration(configuration(values)) + .build() + .getToken(new TokenRequestContext().addScopes(SCOPE))); + assertEquals("api://AzureADTokenExchange", parseForm(http.oidcRequest.getUri().getRawQuery()).get("audience")); + } +} diff --git a/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialLiveTest.java b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialLiveTest.java new file mode 100644 index 0000000000000..a4e0470f6ce4c --- /dev/null +++ b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialLiveTest.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.identity; + +import com.azure.v2.core.credentials.TokenRequestContext; +import io.clientcore.core.credentials.oauth.AccessToken; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; + +import java.time.OffsetDateTime; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@EnabledIfEnvironmentVariable(named = "RUN_GITHUB_ACTIONS_CREDENTIAL_LIVE_TESTS", matches = "true") +@EnabledIfEnvironmentVariable(named = "AZURE_TEST_MODE", matches = "LIVE") +@EnabledIfEnvironmentVariable(named = "GITHUB_ACTIONS", matches = "true") +class GitHubActionsCredentialLiveTest { + @Test + void acquiresTokenFromGitHubActions() { + AccessToken token = new GitHubActionsCredentialBuilder().build() + .getToken(new TokenRequestContext().addScopes("https://management.azure.com/.default")); + assertNotNull(token); + assertFalse(token.getToken().isEmpty()); + assertTrue(token.getExpiresAt().isAfter(OffsetDateTime.now())); + } +} diff --git a/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java new file mode 100644 index 0000000000000..e8b87e43edbed --- /dev/null +++ b/sdk/identity-v2/azure-identity/src/test/java/com/azure/v2/identity/GitHubActionsCredentialTest.java @@ -0,0 +1,299 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.v2.identity; + +import com.azure.v2.core.credentials.TokenRequestContext; +import com.azure.v2.identity.exceptions.CredentialAuthenticationException; +import io.clientcore.core.credentials.oauth.AccessToken; +import io.clientcore.core.http.client.HttpClient; +import io.clientcore.core.http.models.HttpHeaderName; +import io.clientcore.core.http.models.HttpHeaders; +import io.clientcore.core.http.models.HttpMethod; +import io.clientcore.core.http.models.HttpRequest; +import io.clientcore.core.http.models.Response; +import io.clientcore.core.models.binarydata.BinaryData; +import io.clientcore.core.utils.configuration.Configuration; +import io.clientcore.core.utils.configuration.ConfigurationSource; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.UnsupportedEncodingException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GitHubActionsCredentialTest { + static final String CLIENT_ID = "00000000-0000-0000-0000-000000000002"; + static final String TENANT_ID = "contoso.onmicrosoft.com"; + static final String SCOPE = "https://management.azure.com/.default"; + static final String ASSERTION = "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjQxMDI0NDQ4MDB9.signature"; + + @Test + void exchangesAssertionAndUsesAccessTokenCache() { + FakeHttpClient http = new FakeHttpClient(); + GitHubActionsCredential credential = credentialBuilder(http).build(); + TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE); + AccessToken token = credential.getToken(request); + assertNotNull(token); + assertEquals("access-token-1", token.getToken()); + assertTrue(token.getExpiresAt().isAfter(OffsetDateTime.now())); + assertEquals(CLIENT_ID, http.tokenForms.get(0).get("client_id")); + assertEquals(ASSERTION, http.tokenForms.get(0).get("client_assertion")); + assertEquals("client_credentials", http.tokenForms.get(0).get("grant_type")); + assertEquals("urn:ietf:params:oauth:client-assertion-type:jwt-bearer", + http.tokenForms.get(0).get("client_assertion_type")); + assertTrue(http.tokenForms.get(0).get("scope").contains("https://management.azure.com/")); + assertTrue(http.lastTokenPath.contains(TENANT_ID)); + int assertionRequests = http.oidcRequests.get(); + assertEquals(token.getToken(), credential.getToken(request).getToken()); + assertEquals(assertionRequests, http.oidcRequests.get()); + assertEquals(1, http.tokenForms.size()); + assertEquals(http.oidcRequests.get(), http.closedResponses.get()); + } + + @Test + void refreshesAssertionWhenAccessTokenIsNearExpiry() { + FakeHttpClient http = new FakeHttpClient(); + http.expiresIn = 60; + GitHubActionsCredential credential = credentialBuilder(http).build(); + TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE); + credential.getToken(request); + int assertionRequests = http.oidcRequests.get(); + assertEquals("access-token-2", credential.getToken(request).getToken()); + assertTrue(http.oidcRequests.get() > assertionRequests); + assertEquals(2, http.tokenForms.size()); + } + + @ParameterizedTest + @ValueSource(ints = { 204, 400, 401 }) + void rejectsHttpFailuresWithoutDisclosingResponse(int status) { + FakeHttpClient http = new FakeHttpClient(); + http.oidcStatus = status; + http.oidcBody = "{\"value\":\"response-secret-sentinel\"}"; + CredentialAuthenticationException error = assertThrows(CredentialAuthenticationException.class, + () -> credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE))); + assertEquals( + "GitHubActionsCredential: Authentication Failed. OIDC request returned status code " + status + ".", + error.getMessage()); + assertFalse(error.getMessage().contains("response-secret-sentinel")); + assertNull(error.getCause()); + assertEquals(0, http.tokenForms.size()); + assertEquals(http.oidcRequests.get(), http.closedResponses.get()); + } + + @ParameterizedTest + @CsvSource( + delimiter = '|', + value = { + "|Received null token from OIDC request.", + "''|Received null token from OIDC request.", + "' '|Failed to parse OIDC response.", + "null|\"value\" field not detected in the response.", + "[]|\"value\" field not detected in the response.", + "true|\"value\" field not detected in the response.", + "42|\"value\" field not detected in the response.", + "{}|\"value\" field not detected in the response.", + "{\"value\":null}|\"value\" field not detected in the response.", + "{\"value\":42}|\"value\" field not detected in the response.", + "{\"value\":true}|\"value\" field not detected in the response.", + "{\"value\":{}}|\"value\" field not detected in the response.", + "{\"value\":[]}|\"value\" field not detected in the response.", + "{\"value\":\"\"}|\"value\" field not detected in the response.", + "response-secret-sentinel|Failed to parse OIDC response.", + "{\"value\":\"response-secret-sentinel\"|Failed to parse OIDC response.", + "{\"value\":\"response-secret-sentinel\"} {}|Failed to parse OIDC response.", + "{\"value\":\"response-secret-sentinel\"} trailing|Failed to parse OIDC response." }) + void rejectsInvalidResponsesWithoutDisclosingAssertions(String body, String reason) { + FakeHttpClient http = new FakeHttpClient(); + http.oidcBody = body; + CredentialAuthenticationException error = assertThrows(CredentialAuthenticationException.class, + () -> credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE))); + assertEquals("GitHubActionsCredential: Authentication Failed. " + reason, error.getMessage()); + StringWriter diagnostics = new StringWriter(); + error.printStackTrace(new PrintWriter(diagnostics)); + assertFalse(diagnostics.toString().contains("response-secret-sentinel")); + assertEquals(0, http.tokenForms.size()); + assertEquals(http.oidcRequests.get(), http.closedResponses.get()); + } + + @Test + void propagatesTransportAndEntraFailures() { + FakeHttpClient http = new FakeHttpClient(); + http.transportFailure = new IllegalStateException("GitHub transport unavailable"); + RuntimeException transportError = assertThrows(RuntimeException.class, + () -> credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE))); + assertTrue(transportError.getMessage().contains("GitHub transport unavailable")); + assertEquals(0, http.tokenForms.size()); + + http.transportFailure = null; + http.tokenStatus = 400; + RuntimeException tokenError = assertThrows(RuntimeException.class, + () -> credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE))); + assertTrue(tokenError.getMessage().contains("bad-federation")); + } + + @Test + void forwardsTenantAndCaeOptions() { + FakeHttpClient http = new FakeHttpClient(); + GitHubActionsCredential credential + = credentialBuilder(http).additionallyAllowedTenants("other.contoso.com").build(); + TokenRequestContext request + = new TokenRequestContext().addScopes(SCOPE).setTenantId("other.contoso.com").setCaeEnabled(true); + credential.getToken(request); + assertTrue(http.lastTokenPath.contains("other.contoso.com")); + String claims = http.tokenForms.get(0).get("claims"); + assertNotNull(claims); + assertTrue(claims.contains("CP1"), claims); + } + + @Test + void refreshesCachedTokenForCaeClaims() { + FakeHttpClient http = new FakeHttpClient(); + GitHubActionsCredential credential = credentialBuilder(http).build(); + TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE).setCaeEnabled(true); + assertEquals("access-token-1", credential.getToken(request).getToken()); + assertEquals("access-token-1", credential.getToken(request).getToken()); + assertEquals(1, http.tokenForms.size()); + + TokenRequestContext claimsRequest = new TokenRequestContext().addScopes(SCOPE) + .setCaeEnabled(true) + .setClaims("{\"access_token\":{\"auth_time\":{\"essential\":true}}}"); + assertEquals("access-token-2", credential.getToken(claimsRequest).getToken()); + assertEquals(2, http.tokenForms.size()); + String claims = http.tokenForms.get(1).get("claims"); + assertNotNull(claims); + assertTrue(claims.contains("auth_time"), claims); + assertTrue(claims.contains("CP1"), claims); + } + + static GitHubActionsCredentialBuilder credentialBuilder(FakeHttpClient http) { + return new GitHubActionsCredentialBuilder().configuration(configuration(settings())) + .httpClient(http) + .disableInstanceDiscovery(); + } + + static Map settings() { + Map settings = new HashMap<>(); + settings.put("AZURE_CLIENT_ID", CLIENT_ID); + settings.put("AZURE_TENANT_ID", TENANT_ID); + settings.put("ACTIONS_ID_TOKEN_REQUEST_URL", "https://github-oidc.test/token?api-version=1"); + settings.put("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "runner-token-sentinel"); + return settings; + } + + static Configuration configuration(Map settings) { + return Configuration.from(new ConfigurationSource() { + @Override + public String getProperty(String name) { + return settings.get(name); + } + + @Override + public boolean isMutable() { + return false; + } + }); + } + + static Map parseForm(String body) { + Map result = new HashMap<>(); + for (String parameter : body.split("&")) { + String[] parts = parameter.split("=", 2); + try { + result.put(URLDecoder.decode(parts[0], StandardCharsets.UTF_8.name()), + parts.length == 1 ? "" : URLDecoder.decode(parts[1], StandardCharsets.UTF_8.name())); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException(e); + } + } + return result; + } + + static class FakeHttpClient implements HttpClient { + final AtomicInteger oidcRequests = new AtomicInteger(); + final AtomicInteger closedResponses = new AtomicInteger(); + final List> tokenForms = Collections.synchronizedList(new ArrayList<>()); + volatile HttpRequest oidcRequest; + volatile HttpRequest tokenRequest; + volatile String lastTokenPath; + int oidcStatus = 200; + int tokenStatus = 200; + int expiresIn = 3600; + String oidcBody = "{\"ignored\":{\"nested\":[1,2]},\"value\":\"" + ASSERTION + "\"}"; + RuntimeException transportFailure; + + @Override + public Response send(HttpRequest request) { + if ("github-oidc.test".equals(request.getUri().getHost())) { + if (transportFailure != null) { + throw transportFailure; + } + oidcRequest = request; + oidcRequests.incrementAndGet(); + assertEquals(HttpMethod.GET, request.getHttpMethod()); + assertEquals("Bearer runner-token-sentinel", + request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION)); + AtomicBoolean closed = new AtomicBoolean(); + return new Response(request, oidcStatus, jsonHeaders(), + oidcBody == null ? null : BinaryData.fromString(oidcBody)) { + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + closedResponses.incrementAndGet(); + } + super.close(); + } + }; + } + String authority = "https://" + request.getUri().getAuthority(); + String tenant = request.getUri().getPath().split("/")[1]; + if (request.getUri().getPath().contains(".well-known/openid-configuration")) { + String endpoint = authority + "/" + tenant + "/oauth2/v2.0/"; + return response(request, 200, + "{\"token_endpoint\":\"" + endpoint + "token\"," + "\"issuer\":\"" + authority + "/" + tenant + + "/v2.0\"," + "\"authorization_endpoint\":\"" + endpoint + "authorize\"}"); + } + assertTrue(request.getUri().getPath().endsWith("/token"), "Unexpected request: " + request.getUri()); + assertEquals(HttpMethod.POST, request.getHttpMethod()); + tokenRequest = request; + lastTokenPath = request.getUri().getPath(); + Map form = parseForm(request.getBody().toString()); + tokenForms.add(form); + if (tokenStatus != 200) { + return response(request, tokenStatus, + "{\"error\":\"invalid_grant\",\"error_description\":\"bad-federation\"}"); + } + return response(request, 200, + "{\"token_type\":\"Bearer\",\"scope\":\"" + form.get("scope") + "\",\"expires_in\":" + expiresIn + + ",\"ext_expires_in\":" + expiresIn + ",\"access_token\":\"access-token-" + tokenForms.size() + + "\"}"); + } + + private static HttpHeaders jsonHeaders() { + return new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); + } + + private static Response response(HttpRequest request, int status, String body) { + return new Response<>(request, status, jsonHeaders(), BinaryData.fromString(body)); + } + } +} diff --git a/sdk/identity-v2/cspell.yml b/sdk/identity-v2/cspell.yml index 47699c91f6e88..fd57e4f94e7e3 100644 --- a/sdk/identity-v2/cspell.yml +++ b/sdk/identity-v2/cspell.yml @@ -8,3 +8,4 @@ import: - ../../.vscode/cspell.json words: - "toolsl" + - "sovcloud" diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index bf9a632ac68c3..1063d2de929d1 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -4,10 +4,15 @@ ### Features Added +- Added `GitHubActionsCredential` and `GitHubActionsCredentialBuilder` for authentication using GitHub Actions OIDC federation. ([#50916](https://github.com/Azure/azure-sdk-for-java/pull/50916)) + ### Breaking Changes ### Bugs Fixed +- Fixed an initial OIDC request failure preventing later authentication attempts with the same `AzurePipelinesCredential` or `GitHubActionsCredential` instance. ([#50916](https://github.com/Azure/azure-sdk-for-java/pull/50916)) +- Fixed client-credentials authentication to acquire a new token when handling a Continuous Access Evaluation (CAE) claims challenge. ([#50916](https://github.com/Azure/azure-sdk-for-java/pull/50916))` + ### Other Changes ## 1.19.0 (2026-10-29) diff --git a/sdk/identity/azure-identity/README.md b/sdk/identity/azure-identity/README.md index dfbc788bf5244..a568669a5dbef 100644 --- a/sdk/identity/azure-identity/README.md +++ b/sdk/identity/azure-identity/README.md @@ -250,6 +250,7 @@ Not all credentials honor this configuration. Credentials that authenticate thro | Credential | Usage | Example | Reference | |-----------------------------------------|-------------------------------------------------------------------|-----------------------------|--------------------------------------------| | [AzurePipelinesCredential][cred_apc] | Authenticates with a service connection in Azure Pipelines. | | [Manage service connections][cred_apc_ref] | +| [GitHubActionsCredential](#authenticate-github-actions-workflows) | Authenticates a GitHub Actions workflow using OIDC federation | [example](#authenticate-github-actions-workflows) | [Configure federation with Azure][github_oidc] | | [ClientAssertionCredential][cred_cac] | Authenticates a service principal using a signed client assertion | | | | [ClientCertificateCredential][cred_ccc] | Authenticates a service principal using a certificate | [example][cred_ccc_example] | [Service principal authentication][sp] | | [ClientSecretCredential][cred_csc] | Authenticates a service principal using a secret | [example][cred_csc_example] | [Service principal authentication][sp] | @@ -275,6 +276,78 @@ Not all credentials honor this configuration. Credentials that authenticate thro > __Note:__ All credential implementations in the Azure Identity library are threadsafe, and a single credential instance can be used to create multiple service clients. +## Authenticate GitHub Actions workflows + +`GitHubActionsCredential` exchanges a GitHub Actions OIDC token for a Microsoft Entra access token. +Configure a federated identity credential on your Entra application that trusts the workflow's issuer, +subject, and audience. Follow [GitHub's Azure OIDC setup guide][github_oidc], then set these workflow permissions +and environment variables: + +```yaml +permissions: + contents: read + id-token: write + +env: + AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }} +``` + +GitHub provides `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN` to the workflow step. +Do not configure those values as repository secrets or print them. No client secret, certificate, or +`azure/login` step is required for this credential. + +```java readme-sample-github-actions-credential +TokenCredential gitHubCredential = new GitHubActionsCredentialBuilder().build(); +``` + +You can override the Azure IDs without changing the runner-provided OIDC configuration: + +```java readme-sample-github-actions-credential-explicit +TokenCredential explicitCredential = new GitHubActionsCredentialBuilder() + .tenantId("") + .clientId("") + .build(); +``` + +The effective authority is the builder's `authorityHost`, followed by `AZURE_AUTHORITY_HOST`, then Azure Public. +The credential derives the assertion audience from that authority. Configure the same audience in the federated +identity credential: + +| Authority host | Audience | +| --- | --- | +| `https://login.microsoftonline.com/` | `api://AzureADTokenExchange` | +| `https://login.chinacloudapi.cn/` | `api://AzureADTokenExchangeChina` | +| `https://login.microsoftonline.us/` | `api://AzureADTokenExchangeUSGov` | +| `https://login.sovcloud-identity.fr/` | `api://AzureADTokenExchangeFrance` | +| `https://login.sovcloud-identity.de/` | `api://AzureADTokenExchangeGermany` | +| `https://login.sovcloud-identity.sg/` | `api://AzureADTokenExchangeGovSG` | + +Unsupported authorities fail rather than defaulting to the public-cloud audience. Missing configuration fails +during `build()`, before a token request is attempted. This standalone credential is not part of +`DefaultAzureCredential`. + +### Run the opt-in end-to-end test + +The [Identity GitHub Actions credential workflow][github_oidc_workflow] builds and tests both Identity packages +against GitHub's OIDC provider and Entra. It runs on pushes to `vcolin7-github-actions-credential` and also +supports manual dispatch. + +1. Configure a test application's federated identity credential with the actual GitHub issuer and subject for + the repository and ref you will run, and the public-cloud audience `api://AzureADTokenExchange`. + Subject formats can include immutable owner/repository IDs; do not assume the legacy subject format. +2. Set repository variables `AZURE_IDENTITY_GITHUB_ACTIONS_TENANT_ID` and + `AZURE_IDENTITY_GITHUB_ACTIONS_CLIENT_ID` to the test application's tenant and client IDs. +3. Push the workflow and SDK changes to `vcolin7-github-actions-credential` in your fork to run the tests. + For manual runs, the workflow must first be present on the repository's default branch. Then select + **Actions**, **Identity GitHub Actions credential**, **Run workflow**, and a ref trusted by the federated + identity credential. + +The live tests request a public-cloud ARM token without calling Azure resources or logging token values. +They are skipped in ordinary local and CI runs. The dedicated workflow enables them with +`RUN_GITHUB_ACTIONS_CREDENTIAL_LIVE_TESTS=true`, `AZURE_TEST_MODE=LIVE`, and the GitHub Actions environment. +No federation resources or repository settings are created by the workflow. + ## Environment variables `DefaultAzureCredential` and `EnvironmentCredential` can be configured with environment variables. Each type of authentication requires values for specific variables. @@ -390,6 +463,8 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con [cred_wic_example]: https://learn.microsoft.com/azure/aks/workload-identity-overview?tabs=java#azure-identity-client-libraries [cred_wic_ref]: https://learn.microsoft.com/azure/aks/workload-identity-overview [entraid_doc]: https://learn.microsoft.com/entra/identity/ +[github_oidc]: https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-azure +[github_oidc_workflow]: https://github.com/Azure/azure-sdk-for-java/blob/main/.github/workflows/identity-github-actions-credential.yml [javadoc]: https://learn.microsoft.com/java/api/com.azure.identity?view=azure-java-stable [jdk_link]: https://learn.microsoft.com/java/azure/jdk/?view=azure-java-stable [secrets_client_library]: https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/keyvault/azure-security-keyvault-secrets diff --git a/sdk/identity/azure-identity/TROUBLESHOOTING.md b/sdk/identity/azure-identity/TROUBLESHOOTING.md index 352bfe8e6dc9c..cee27d89e545d 100644 --- a/sdk/identity/azure-identity/TROUBLESHOOTING.md +++ b/sdk/identity/azure-identity/TROUBLESHOOTING.md @@ -23,6 +23,7 @@ This troubleshooting guide covers failure investigation techniques, common error - [Troubleshoot IntelliJCredential authentication issues](#troubleshoot-intellijcredential-authentication-issues) - [Troubleshoot VisualStudioCodeCredential authentication issues](#troubleshoot-visualstudiocodecredential-authentication-issues) - [Troubleshoot AzurePipelinesCredential authentication issues](#troubleshoot-azurepipelinescredential-authentication-issues) +- [Troubleshoot GitHubActionsCredential authentication issues](#troubleshoot-githubactionscredential-authentication-issues) - [Troubleshoot authentication timeout issues](#troubleshoot-authentication-timeout-issues) - [Using a dedicated thread pool](#using-thread-pool) - [Virtual-thread carrier starvation](#virtual-thread-carrier-starvation) @@ -317,6 +318,28 @@ As of version 1.17.0-beta.1, `VisualStudioCodeCredential` uses broker authentica |AADSTS700016: Application with identifier 'clientId' was not found in the directory 'Microsoft'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.|The `` provided is invalid|Verify the client ID argument is valid. If the service connection's federated identity was registered via a user-assigned managed identity, the client ID of the managed identity should be provided. If the service connection's federated identity is registered via an app registration, the Application (client) ID from your app registration should be provided.| +## Troubleshoot `GitHubActionsCredential` authentication issues + +`GitHubActionsCredential` is a standalone credential for GitHub Actions OIDC federation. It is not part of +`DefaultAzureCredential`. Missing configuration fails during `GitHubActionsCredentialBuilder.build()`, so +constructing an unconfigured credential does not defer failure to a manually composed credential chain. + +| Error | Cause | Mitigation | +| --- | --- | --- | +| `CredentialUnavailableException` naming `AZURE_CLIENT_ID` or `AZURE_TENANT_ID` | The Azure application IDs are missing. | Set the environment variables or call `clientId` and `tenantId` on the builder. | +| `CredentialUnavailableException` naming `ACTIONS_ID_TOKEN_REQUEST_URL` or `ACTIONS_ID_TOKEN_REQUEST_TOKEN` | The process is outside an OIDC-enabled workflow step. | Grant the job `permissions: id-token: write` and run the SDK in that GitHub Actions step. Do not supply the runner token manually. | +| Invalid runner request URL | The configured URL is not an absolute HTTPS URL, or contains user information or a fragment. | Use the URL supplied by the GitHub Actions runner. | +| Unsupported authority host | There is no supported audience mapping for the authority. | Use one of the [documented cloud authorities](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/identity/azure-identity/README.md#authenticate-github-actions-workflows). Custom audiences and authorities are not supported. | +| GitHub OIDC HTTP 401/403 | GitHub rejected the runner request. | Check the job's OIDC permissions and ensure the request variables belong to the current workflow step. | +| `Received null token from OIDC request.` | The GitHub OIDC response body is missing or empty. | Check connectivity and any proxy affecting the GitHub OIDC endpoint. | +| `"value" field not detected in the response.` | The JSON response does not contain a nonempty string `value`. | Check that the request reaches the GitHub OIDC endpoint. Do not log the response body; it can contain an assertion. | +| `Failed to parse OIDC response.` | The response contains malformed JSON or trailing content. | Check connectivity and any proxy affecting the GitHub OIDC endpoint. Do not log the response body. | +| Entra reports no matching federated identity record | The presented issuer, subject, or audience does not match the app's federation configuration. | Match the actual claims for the repository/ref, including immutable subject IDs when applicable, and the audience derived from the authority host. | + +See [GitHub's Azure OIDC setup guide](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-azure) +for federation prerequisites. Never include the runner bearer token, OIDC assertion, access token, or raw token +response in diagnostic logs. + ## Troubleshoot multi-tenant authentication issues `ClientAuthenticationException` diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java new file mode 100644 index 0000000000000..1d351f4475bff --- /dev/null +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredential.java @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity; + +import com.azure.core.annotation.Immutable; +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenCredential; +import com.azure.core.credential.TokenRequestContext; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.HttpResponse; +import com.azure.core.util.BinaryData; +import com.azure.core.util.Context; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.identity.implementation.IdentityClient; +import com.azure.identity.implementation.IdentityClientBuilder; +import com.azure.identity.implementation.IdentityClientOptions; +import com.azure.identity.implementation.IdentitySyncClient; +import com.azure.identity.implementation.util.IdentityUtil; +import com.azure.identity.implementation.util.LoggingUtil; +import com.azure.json.JsonProviders; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +import java.io.IOException; + +/** + * Authenticates an application in GitHub Actions using an OIDC federated identity credential. + * + *

Configure a federated identity credential on the Microsoft Entra application that trusts the GitHub workflow's + * issuer, subject, and audience. The workflow needs {@code permissions: id-token: write}. GitHub supplies the + * OIDC request URL and bearer token. The client and tenant IDs default to {@code AZURE_CLIENT_ID} and + * {@code AZURE_TENANT_ID}; they can also be set on {@link GitHubActionsCredentialBuilder}.

+ * + *

The assertion audience is selected from the authority host. This credential supports Azure Public, China, + * US Government, France Government, Germany Government, and Singapore Government. It is not included in + * {@link DefaultAzureCredential}.

+ * + * + *
+ * GitHubActionsCredential credential = new GitHubActionsCredentialBuilder().build();
+ * 
+ * + * + * @see GitHubActionsCredentialBuilder + */ +@Immutable +public class GitHubActionsCredential implements TokenCredential { + private static final ClientLogger LOGGER = new ClientLogger(GitHubActionsCredential.class); + private final IdentityClient identityClient; + private final IdentitySyncClient identitySyncClient; + + GitHubActionsCredential(String clientId, String tenantId, String requestUrl, String requestToken, + IdentityClientOptions options) { + IdentityClientBuilder builder = new IdentityClientBuilder().clientId(clientId) + .tenantId(tenantId) + .identityClientOptions(options) + .clientAssertionSupplierWithHttpPipeline(pipeline -> { + HttpRequest request = new HttpRequest(HttpMethod.GET, requestUrl) + .setHeader(HttpHeaderName.AUTHORIZATION, "Bearer " + requestToken); + try (HttpResponse response = pipeline.sendSync(request, Context.NONE)) { + if (response.getStatusCode() != 200) { + throw authenticationError("OIDC request returned status code " + response.getStatusCode() + ".", + response); + } + return readAssertion(response); + } + }); + identityClient = builder.build(); + identitySyncClient = builder.buildSyncClient(); + } + + /** + * Asynchronously acquires an access token, using the token cache when possible. + * + *

GitHub OIDC failures can be retried without rebuilding the credential. Requests with a Continuous Access + * Evaluation (CAE) claims challenge acquire a new token instead of reusing a cached token.

+ * + * @param request the scopes, tenant, and authentication options for the token request. + * @return a publisher containing the access token, or an authentication error. + */ + @Override + public Mono getToken(TokenRequestContext request) { + // The confidential-client assertion callback performs synchronous HTTP I/O. + return Mono.defer(() -> identityClient.authenticateWithConfidentialClientCache(request) + .onErrorResume(Exception.class, error -> { + IdentityUtil.rethrowIfShutdownSignal(error); + return Mono.empty(); + }) + .switchIfEmpty(Mono.defer(() -> identityClient.authenticateWithConfidentialClient(request)))) + .subscribeOn(Schedulers.boundedElastic()) + .doOnNext(token -> LoggingUtil.logTokenSuccess(LOGGER, request)) + .doOnError( + error -> LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, error)); + } + + /** + * Synchronously acquires an access token, using the token cache when possible. + * + *

Requests with a Continuous Access Evaluation (CAE) claims challenge acquire a new token instead of reusing a + * cached token.

+ * + * @param request the scopes, tenant, and authentication options for the token request. + * @return the access token. + * @throws ClientAuthenticationException if the GitHub OIDC request fails or returns an invalid assertion response. + */ + @Override + public AccessToken getTokenSync(TokenRequestContext request) { + try { + AccessToken token = identitySyncClient.authenticateWithConfidentialClientCache(request); + if (token != null) { + LoggingUtil.logTokenSuccess(LOGGER, request); + return token; + } + } catch (RuntimeException e) { + IdentityUtil.rethrowIfShutdownSignal(e); + } + try { + AccessToken token = identitySyncClient.authenticateWithConfidentialClient(request); + LoggingUtil.logTokenSuccess(LOGGER, request); + return token; + } catch (RuntimeException e) { + LoggingUtil.logTokenError(LOGGER, identityClient.getIdentityClientOptions(), request, e); + IdentityUtil.rethrowIfShutdownSignal(e); + throw LOGGER.logExceptionAsError(e); + } + } + + private static String readAssertion(HttpResponse response) { + BinaryData body = response.getBodyAsBinaryData(); + String text = body == null ? null : body.toString(); + if (CoreUtils.isNullOrEmpty(text)) { + throw authenticationError("Received null token from OIDC request.", response); + } + try (JsonReader reader = JsonProviders.createReader(text)) { + JsonToken token = reader.nextToken(); + if (token == JsonToken.END_DOCUMENT) { + throw authenticationError("Failed to parse OIDC response.", response); + } + String assertion = null; + if (token == JsonToken.START_OBJECT) { + assertion = reader.readObject(objectReader -> { + String value = null; + while (objectReader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = objectReader.getFieldName(); + objectReader.nextToken(); + if ("value".equals(fieldName)) { + if (objectReader.currentToken() == JsonToken.STRING) { + value = objectReader.getString(); + } else { + value = null; + objectReader.skipChildren(); + } + } else { + objectReader.skipChildren(); + } + } + return value; + }); + } else { + reader.skipChildren(); + } + if (reader.nextToken() != JsonToken.END_DOCUMENT) { + throw authenticationError("Failed to parse OIDC response.", response); + } + if (CoreUtils.isNullOrEmpty(assertion)) { + throw authenticationError("\"value\" field not detected in the response.", response); + } + return assertion; + } catch (IOException | IllegalStateException e) { + throw LOGGER.logExceptionAsError(new ClientAuthenticationException( + "GitHubActionsCredential: Authentication Failed. Failed to parse OIDC response.", response, + sanitizedCause(e))); + } + } + + // Parser and URI exception messages can contain secrets. Retain their type and stack trace, not their input. + static RuntimeException sanitizedCause(Exception exception) { + if (exception == null) { + return null; + } + RuntimeException sanitized + = new IllegalArgumentException(exception.getClass().getSimpleName() + " (input redacted)"); + sanitized.setStackTrace(exception.getStackTrace()); + return sanitized; + } + + private static RuntimeException authenticationError(String message, HttpResponse response) { + return LOGGER.logExceptionAsError( + new ClientAuthenticationException("GitHubActionsCredential: Authentication Failed. " + message, response)); + } +} diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java new file mode 100644 index 0000000000000..23d9e1d6da579 --- /dev/null +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/GitHubActionsCredentialBuilder.java @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity; + +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.UrlBuilder; +import com.azure.core.util.logging.ClientLogger; +import com.azure.identity.implementation.IdentityClientOptions; +import com.azure.identity.implementation.util.ValidationUtil; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * Fluent builder for {@link GitHubActionsCredential}. + * + *

Client and tenant IDs can be supplied explicitly or through {@code AZURE_CLIENT_ID} and + * {@code AZURE_TENANT_ID}. GitHub supplies {@code ACTIONS_ID_TOKEN_REQUEST_URL} and + * {@code ACTIONS_ID_TOKEN_REQUEST_TOKEN} to workflow steps with {@code permissions: id-token: write}.

+ * + * + *
+ * GitHubActionsCredential credential = new GitHubActionsCredentialBuilder().build();
+ * 
+ * + * + * @see GitHubActionsCredential + */ +public class GitHubActionsCredentialBuilder extends AadCredentialBuilderBase { + private static final ClientLogger LOGGER = new ClientLogger(GitHubActionsCredentialBuilder.class); + private String authorityHost; + + /** + * Creates a builder for a GitHub Actions credential. + */ + public GitHubActionsCredentialBuilder() { + } + + @Override + public GitHubActionsCredentialBuilder authorityHost(String authorityHost) { + super.authorityHost(authorityHost); + this.authorityHost = authorityHost; + return this; + } + + /** + * Enables the persistent token cache with the specified options. Persistence is disabled by default. + * + * @param tokenCachePersistenceOptions the persistent token cache options. + * @return this builder. + */ + public GitHubActionsCredentialBuilder + tokenCachePersistenceOptions(TokenCachePersistenceOptions tokenCachePersistenceOptions) { + identityClientOptions.setTokenCacheOptions(tokenCachePersistenceOptions); + return this; + } + + /** + * Builds a credential using the configured values and the GitHub Actions environment. + * + *

An explicit client ID, tenant ID, or authority host takes precedence over its environment variable. + * The default authority is Azure Public. The assertion audience is derived from the authority host. + * Missing GitHub runner variables are reported together with a link to troubleshooting guidance.

+ * + * @return the configured credential. + * @throws CredentialUnavailableException if required configuration is missing, the GitHub request URL is + * invalid, or the authority host does not have a supported token-exchange audience. + * @throws IllegalArgumentException if the tenant ID is invalid. + */ + public GitHubActionsCredential build() { + Configuration configuration = identityClientOptions.getConfiguration(); + if (configuration == null) { + configuration = Configuration.getGlobalConfiguration(); + } + String resolvedClientId = required("AZURE_CLIENT_ID", + CoreUtils.isNullOrEmpty(clientId) ? configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID) : clientId); + String resolvedTenantId = required("AZURE_TENANT_ID", + CoreUtils.isNullOrEmpty(tenantId) ? configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID) : tenantId); + ValidationUtil.validateTenantIdCharacterRange(resolvedTenantId, LOGGER); + String requestUrl = configuration.get("ACTIONS_ID_TOKEN_REQUEST_URL"); + String requestToken = configuration.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN"); + List missing = new ArrayList<>(2); + if (CoreUtils.isNullOrEmpty(requestUrl)) { + missing.add("ACTIONS_ID_TOKEN_REQUEST_URL"); + } + if (CoreUtils.isNullOrEmpty(requestToken)) { + missing.add("ACTIONS_ID_TOKEN_REQUEST_TOKEN"); + } + if (!missing.isEmpty()) { + throw LOGGER.logExceptionAsError(new CredentialUnavailableException("GitHubActionsCredential requires " + + String.join(", ", missing) + ". Run in a GitHub Actions workflow with " + + "'permissions: id-token: write'. For troubleshooting information, see " + + "https://aka.ms/azsdk/java/identity/troubleshoot.")); + } + String resolvedAuthority = authorityHost == null + ? configuration.get(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD) + : authorityHost; + String audience = audienceForAuthority(resolvedAuthority); + IdentityClientOptions options = identityClientOptions.clone().setAuthorityHost(resolvedAuthority); + return new GitHubActionsCredential(resolvedClientId, resolvedTenantId, + requestUrlWithAudience(requestUrl, audience), requestToken, options); + } + + private static String required(String name, String value) { + if (CoreUtils.isNullOrEmpty(value)) { + throw LOGGER.logExceptionAsError(new CredentialUnavailableException("GitHubActionsCredential requires " + + name + ". Configure the Azure client and tenant IDs and run in a GitHub Actions workflow with " + + "'permissions: id-token: write'.")); + } + return value; + } + + private static String audienceForAuthority(String authority) { + try { + URI uri = new URI(authority); + if ("https".equalsIgnoreCase(uri.getScheme()) && uri.getHost() != null && uri.getUserInfo() == null) { + switch (uri.getHost().toLowerCase(Locale.ROOT)) { + case "login.microsoftonline.com": + return "api://AzureADTokenExchange"; + + case "login.chinacloudapi.cn": + return "api://AzureADTokenExchangeChina"; + + case "login.microsoftonline.us": + return "api://AzureADTokenExchangeUSGov"; + + case "login.sovcloud-identity.fr": + return "api://AzureADTokenExchangeFrance"; + + case "login.sovcloud-identity.de": + return "api://AzureADTokenExchangeGermany"; + + case "login.sovcloud-identity.sg": + return "api://AzureADTokenExchangeGovSG"; + + default: + break; + } + } + } catch (URISyntaxException e) { + throw unsupportedAuthority(e); + } + throw unsupportedAuthority(null); + } + + private static RuntimeException unsupportedAuthority(Exception cause) { + return LOGGER.logExceptionAsError(new CredentialUnavailableException( + "GitHubActionsCredential does not support the configured authority host. " + + "Use an Azure Public, China, US Government, France Government, Germany Government, " + + "or Singapore Government authority.", + GitHubActionsCredential.sanitizedCause(cause))); + } + + private static String requestUrlWithAudience(String requestUrl, String audience) { + try { + URI uri = new URI(requestUrl); + if (!"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getUserInfo() != null + || uri.getFragment() != null) { + throw invalidRequestUrl(null); + } + return UrlBuilder.parse(requestUrl) + .setQueryParameter("audience", URLEncoder.encode(audience, StandardCharsets.UTF_8.name())) + .toString(); + } catch (URISyntaxException | IOException e) { + throw invalidRequestUrl(e); + } + } + + private static RuntimeException invalidRequestUrl(Exception cause) { + return LOGGER.logExceptionAsError(new CredentialUnavailableException( + "GitHubActionsCredential requires ACTIONS_ID_TOKEN_REQUEST_URL to be an absolute HTTPS URL " + + "without user information or a fragment.", + GitHubActionsCredential.sanitizedCause(cause))); + } +} diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClient.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClient.java index 229d5b5bd78a3..e95c8335910e4 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClient.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClient.java @@ -555,7 +555,7 @@ public Mono authenticateWithConfidentialClient(TokenRequestContext if (request.isCaeEnabled() && request.getClaims() != null) { ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims()); - builder.claims(claimsRequest); + builder.claims(claimsRequest).skipCache(true); } return builder; } @@ -706,6 +706,9 @@ public Mono authenticateWithConfidentialClientCache(TokenRequestCon */ @SuppressWarnings("deprecation") public Mono authenticateWithConfidentialClientCache(TokenRequestContext request, IAccount account) { + if (account == null && request.isCaeEnabled() && request.getClaims() != null) { + return Mono.empty(); + } return getConfidentialClientInstance(request).getValue().flatMap(confidentialClient -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder(new HashSet<>(request.getScopes())) diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClientBase.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClientBase.java index 704348b3ce41d..168efacc7da76 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClientBase.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentityClientBase.java @@ -225,8 +225,9 @@ ConfidentialClientApplication getConfidentialClient(boolean enableCae) { } else if (clientAssertionSupplier != null) { credential = ClientCredentialFactory.createFromClientAssertion(clientAssertionSupplier.get()); } else if (clientAssertionSupplierWithHttpPipeline != null) { + // Fetch remote assertions during token acquisition, not permanently cached client initialization. credential = ClientCredentialFactory - .createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(getPipeline())); + .createFromCallback(() -> clientAssertionSupplierWithHttpPipeline.apply(getPipeline())); } else { throw LOGGER.logExceptionAsError( new IllegalArgumentException("Must provide client secret or client certificate path." diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentitySyncClient.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentitySyncClient.java index 313f8a1fdd016..2befa7e935525 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentitySyncClient.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/IdentitySyncClient.java @@ -134,6 +134,10 @@ public AccessToken authenticateWithConfidentialClient(TokenRequestContext reques builder.clientCredential(ClientCredentialFactory .createFromClientAssertion(clientAssertionSupplierWithHttpPipeline.apply(getPipeline()))); } + if (request.isCaeEnabled() && request.getClaims() != null) { + ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims()); + builder.claims(claimsRequest).skipCache(true); + } try { return new MsalToken(awaitTokenResult(confidentialClient.acquireToken(builder.build()))); } catch (ExecutionException e) { @@ -160,17 +164,14 @@ private SynchronousAccessor getPublicClientInstance(Tok */ @SuppressWarnings("deprecation") public AccessToken authenticateWithConfidentialClientCache(TokenRequestContext request) { + if (request.isCaeEnabled() && request.getClaims() != null) { + return null; + } ConfidentialClientApplication confidentialClientApplication = getConfidentialClientInstance(request).getValue(); SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder(new HashSet<>(request.getScopes())) .tenant(IdentityUtil.resolveTenantId(tenantId, request, options)); - if (request.isCaeEnabled() && request.getClaims() != null) { - ClaimsRequest claimsRequest = ClaimsRequest.formatAsClaimsRequest(request.getClaims()); - parametersBuilder.claims(claimsRequest); - parametersBuilder.forceRefresh(true); - } - try { IAuthenticationResult authenticationResult = awaitTokenResult(confidentialClientApplication.acquireTokenSilently(parametersBuilder.build())); diff --git a/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java b/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java index 437f0f99bad18..6803cec3f7967 100644 --- a/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java +++ b/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java @@ -39,6 +39,8 @@ import com.azure.identity.DeviceCodeCredentialBuilder; import com.azure.identity.EnvironmentCredential; import com.azure.identity.EnvironmentCredentialBuilder; +import com.azure.identity.GitHubActionsCredential; +import com.azure.identity.GitHubActionsCredentialBuilder; import com.azure.identity.IntelliJCredential; import com.azure.identity.IntelliJCredentialBuilder; import com.azure.identity.InteractiveBrowserCredential; @@ -313,6 +315,26 @@ public void azurePipelinesCredentialCodeSnippets() { // END: com.azure.identity.credential.azurepipelinescredential.construct } + /** + * Code snippets for {@link GitHubActionsCredential}. + */ + public void gitHubActionsCredentialCodeSnippets() { + // BEGIN: com.azure.identity.credential.githubactionscredential.construct + GitHubActionsCredential credential = new GitHubActionsCredentialBuilder().build(); + // END: com.azure.identity.credential.githubactionscredential.construct + + // BEGIN: readme-sample-github-actions-credential + TokenCredential gitHubCredential = new GitHubActionsCredentialBuilder().build(); + // END: readme-sample-github-actions-credential + + // BEGIN: readme-sample-github-actions-credential-explicit + TokenCredential explicitCredential = new GitHubActionsCredentialBuilder() + .tenantId("") + .clientId("") + .build(); + // END: readme-sample-github-actions-credential-explicit + } + public void silentAuthenticationSnippets() { // BEGIN: com.azure.identity.silentauthentication String authenticationRecordPath = "path/to/authentication-record.json"; diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java new file mode 100644 index 0000000000000..98c150dee6e21 --- /dev/null +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialBuilderTest.java @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity; + +import com.azure.core.credential.TokenRequestContext; +import com.azure.core.util.Configuration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Map; + +import static com.azure.identity.GitHubActionsCredentialTest.SCOPE; +import static com.azure.identity.GitHubActionsCredentialTest.credentialBuilder; +import static com.azure.identity.GitHubActionsCredentialTest.configuration; +import static com.azure.identity.GitHubActionsCredentialTest.parseForm; +import static com.azure.identity.GitHubActionsCredentialTest.settings; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GitHubActionsCredentialBuilderTest { + @ParameterizedTest + @ValueSource( + strings = { + "AZURE_TENANT_ID", + "AZURE_CLIENT_ID", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ACTIONS_ID_TOKEN_REQUEST_TOKEN" }) + void validatesEveryRequiredSettingBeforeHttp(String setting) { + for (String value : new String[] { null, "" }) { + Map values = settings(); + values.put(setting, value); + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + CredentialUnavailableException error = assertThrows(CredentialUnavailableException.class, + () -> credentialBuilder(http).configuration(configuration(values)).build()); + assertTrue(error.getMessage().contains(setting)); + assertTrue(error.getMessage().contains("id-token: write")); + assertFalse(error.getMessage().contains("runner-token-sentinel")); + if (setting.startsWith("ACTIONS_ID_TOKEN_REQUEST_")) { + assertTrue(error.getMessage().contains("https://aka.ms/azsdk/java/identity/troubleshoot")); + String configuredSetting + = setting.endsWith("_URL") ? "ACTIONS_ID_TOKEN_REQUEST_TOKEN" : "ACTIONS_ID_TOKEN_REQUEST_URL"; + assertFalse(error.getMessage().contains(configuredSetting)); + } + assertEquals(0, http.oidcRequests.get()); + } + } + + @ParameterizedTest + @CsvSource(value = { "null,null", "null,''", "'',null", "'',''" }, nullValues = "null") + void reportsBothMissingGitHubVariables(String requestUrl, String requestToken) { + Map values = settings(); + values.put("ACTIONS_ID_TOKEN_REQUEST_URL", requestUrl); + values.put("ACTIONS_ID_TOKEN_REQUEST_TOKEN", requestToken); + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + CredentialUnavailableException error = assertThrows(CredentialUnavailableException.class, + () -> credentialBuilder(http).configuration(configuration(values)).build()); + assertTrue(error.getMessage().contains("ACTIONS_ID_TOKEN_REQUEST_URL, ACTIONS_ID_TOKEN_REQUEST_TOKEN")); + assertTrue(error.getMessage().contains("permissions: id-token: write")); + assertTrue(error.getMessage().contains("https://aka.ms/azsdk/java/identity/troubleshoot")); + assertEquals(0, http.oidcRequests.get()); + } + + @Test + void explicitIdsOverrideEnvironmentAndCredentialsSnapshotBuilderValues() { + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + GitHubActionsCredentialBuilder builder + = credentialBuilder(http).clientId("explicit-client").tenantId("explicit-tenant"); + GitHubActionsCredential first = builder.build(); + GitHubActionsCredential second = builder.clientId("second-client").tenantId("second-tenant").build(); + assertEquals(0, http.oidcRequests.get()); + first.getTokenSync(new TokenRequestContext().addScopes(SCOPE)); + assertEquals("explicit-client", http.tokenForms.get(0).get("client_id")); + assertTrue(http.lastTokenPath.contains("explicit-tenant")); + second.getTokenSync(new TokenRequestContext().addScopes(SCOPE)); + assertEquals("second-client", http.tokenForms.get(1).get("client_id")); + assertTrue(http.lastTokenPath.contains("second-tenant")); + } + + @Test + void disabledConfigurationDoesNotFallBackToTheEnvironment() { + assertThrows(CredentialUnavailableException.class, + () -> new GitHubActionsCredentialBuilder().configuration(Configuration.NONE).build()); + } + + @ParameterizedTest + @CsvSource({ + "login.microsoftonline.com,AzureADTokenExchange", + "login.chinacloudapi.cn,AzureADTokenExchangeChina", + "login.microsoftonline.us,AzureADTokenExchangeUSGov", + "login.sovcloud-identity.fr,AzureADTokenExchangeFrance", + "login.sovcloud-identity.de,AzureADTokenExchangeGermany", + "login.sovcloud-identity.sg,AzureADTokenExchangeGovSG", + "LOGIN.MICROSOFTONLINE.COM,AzureADTokenExchange" }) + void derivesTheAudienceFromTheConfiguredAuthority(String host, String audience) { + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + Map values = settings(); + values.put("AZURE_AUTHORITY_HOST", "https://" + host + "/"); + values.put("ACTIONS_ID_TOKEN_REQUEST_URL", + "https://github-oidc.test/token?encoded=a%2Fb&audience=old&audience=duplicate"); + credentialBuilder(http).configuration(configuration(values)) + .build() + .getTokenSync(new TokenRequestContext().addScopes(SCOPE)); + String query = http.oidcRequest.getUrl().getQuery(); + assertEquals("api://" + audience, parseForm(query).get("audience")); + assertEquals("a/b", parseForm(query).get("encoded")); + assertEquals(1, query.split("audience=", -1).length - 1); + assertTrue(query.contains("api%3A%2F%2F")); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void explicitAuthorityWinsRegardlessOfConfigurationSetterOrder(boolean configurationFirst) { + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + Map values = settings(); + values.put("AZURE_AUTHORITY_HOST", AzureAuthorityHosts.AZURE_CHINA); + GitHubActionsCredentialBuilder builder = credentialBuilder(http); + if (configurationFirst) { + builder.configuration(configuration(values)).authorityHost(AzureAuthorityHosts.AZURE_GOVERNMENT); + } else { + builder.authorityHost(AzureAuthorityHosts.AZURE_GOVERNMENT).configuration(configuration(values)); + } + builder.build().getTokenSync(new TokenRequestContext().addScopes(SCOPE)); + assertEquals("api://AzureADTokenExchangeUSGov", + parseForm(http.oidcRequest.getUrl().getQuery()).get("audience")); + assertEquals("login.microsoftonline.us", http.tokenRequest.getUrl().getHost()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "https://unsupported.test", + "https://login.microsoftonline.com.attacker.test", + "https://login.microsoftonline.de", + "https://user:secret@login.microsoftonline.com" }) + void rejectsUnsupportedAuthorityHosts(String authority) { + assertThrows(CredentialUnavailableException.class, + () -> credentialBuilder(new GitHubActionsCredentialTest.FakeHttpClient()).authorityHost(authority).build()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "not a URI", + "/relative", + "http://github-oidc.test/token", + "https:///token", + "https://user:secret@github-oidc.test/token", + "https://github-oidc.test/token#fragment" }) + void rejectsInvalidRunnerUrls(String url) { + Map values = settings(); + values.put("ACTIONS_ID_TOKEN_REQUEST_URL", url); + CredentialUnavailableException error = assertThrows(CredentialUnavailableException.class, + () -> credentialBuilder(new GitHubActionsCredentialTest.FakeHttpClient()) + .configuration(configuration(values)) + .build()); + assertFalse(error.getMessage().contains("secret")); + } + + @Test + void validatesEnvironmentTenantAndSupportsUrlsWithoutQueries() { + Map values = settings(); + values.put("AZURE_TENANT_ID", "invalid/tenant"); + assertThrows(IllegalArgumentException.class, + () -> credentialBuilder(new GitHubActionsCredentialTest.FakeHttpClient()) + .configuration(configuration(values)) + .build()); + values.put("AZURE_TENANT_ID", "valid-tenant"); + values.put("ACTIONS_ID_TOKEN_REQUEST_URL", "https://github-oidc.test/token"); + GitHubActionsCredentialTest.FakeHttpClient http = new GitHubActionsCredentialTest.FakeHttpClient(); + assertNotNull(credentialBuilder(http).configuration(configuration(values)) + .build() + .getTokenSync(new TokenRequestContext().addScopes(SCOPE))); + assertEquals("api://AzureADTokenExchange", parseForm(http.oidcRequest.getUrl().getQuery()).get("audience")); + } +} diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialLiveTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialLiveTest.java new file mode 100644 index 0000000000000..1a3df837616aa --- /dev/null +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialLiveTest.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity; + +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenRequestContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; +import reactor.test.StepVerifier; + +import java.time.Duration; +import java.time.OffsetDateTime; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@EnabledIfEnvironmentVariable(named = "RUN_GITHUB_ACTIONS_CREDENTIAL_LIVE_TESTS", matches = "true") +@EnabledIfEnvironmentVariable(named = "AZURE_TEST_MODE", matches = "LIVE") +@EnabledIfEnvironmentVariable(named = "GITHUB_ACTIONS", matches = "true") +class GitHubActionsCredentialLiveTest { + @Test + void acquiresTokenFromGitHubActions() { + GitHubActionsCredential credential = new GitHubActionsCredentialBuilder().build(); + TokenRequestContext request = new TokenRequestContext().addScopes("https://management.azure.com/.default"); + assertValidToken(credential.getTokenSync(request)); + StepVerifier.create(credential.getToken(request)) + .assertNext(GitHubActionsCredentialLiveTest::assertValidToken) + .expectComplete() + .verify(Duration.ofMinutes(2)); + } + + private static void assertValidToken(AccessToken token) { + assertNotNull(token); + assertFalse(token.getToken().isEmpty()); + assertTrue(token.getExpiresAt().isAfter(OffsetDateTime.now())); + } +} diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java new file mode 100644 index 0000000000000..4ee8981724aa7 --- /dev/null +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/GitHubActionsCredentialTest.java @@ -0,0 +1,423 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity; + +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenRequestContext; +import com.azure.core.exception.ClientAuthenticationException; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.AddHeadersPolicy; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.core.test.utils.TestConfigurationSource; +import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.identity.util.TestUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; +import reactor.test.StepVerifier; + +import java.io.UnsupportedEncodingException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GitHubActionsCredentialTest { + static final String CLIENT_ID = "00000000-0000-0000-0000-000000000002"; + static final String TENANT_ID = "contoso.onmicrosoft.com"; + static final String SCOPE = "https://management.azure.com/.default"; + static final String ASSERTION = "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjQxMDI0NDQ4MDB9.signature"; + static final Duration TIMEOUT = Duration.ofSeconds(20); + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void exchangesAssertionAndUsesAccessTokenCache(boolean async) { + FakeHttpClient http = new FakeHttpClient(); + GitHubActionsCredential credential = credentialBuilder(http).build(); + TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE); + AccessToken token = getToken(credential, request, async); + assertNotNull(token); + assertEquals("access-token-1", token.getToken()); + assertTrue(token.getExpiresAt().isAfter(OffsetDateTime.now())); + assertEquals(CLIENT_ID, http.tokenForms.get(0).get("client_id")); + assertEquals(ASSERTION, http.tokenForms.get(0).get("client_assertion")); + assertEquals("client_credentials", http.tokenForms.get(0).get("grant_type")); + assertEquals("urn:ietf:params:oauth:client-assertion-type:jwt-bearer", + http.tokenForms.get(0).get("client_assertion_type")); + assertTrue(http.tokenForms.get(0).get("scope").contains("https://management.azure.com/")); + assertTrue(http.lastTokenPath.contains(TENANT_ID)); + int assertionRequests = http.oidcRequests.get(); + assertEquals(token.getToken(), getToken(credential, request, async).getToken()); + assertEquals(assertionRequests, http.oidcRequests.get()); + assertEquals(1, http.tokenForms.size()); + assertEquals(http.oidcRequests.get(), http.closedResponses.get()); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void refreshesAssertionWhenAccessTokenIsNearExpiry(boolean async) { + FakeHttpClient http = new FakeHttpClient(); + http.expiresIn = 60; + GitHubActionsCredential credential = credentialBuilder(http).build(); + TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE); + getToken(credential, request, async); + int assertionRequests = http.oidcRequests.get(); + assertEquals("access-token-2", getToken(credential, request, async).getToken()); + assertTrue(http.oidcRequests.get() > assertionRequests); + assertEquals(2, http.tokenForms.size()); + } + + @ParameterizedTest + @ValueSource(ints = { 204, 400, 401 }) + void rejectsHttpFailuresWithoutDisclosingResponse(int status) { + FakeHttpClient http = new FakeHttpClient(); + http.oidcStatus = status; + http.oidcBody = "{\"value\":\"response-secret-sentinel\"}"; + ClientAuthenticationException error = assertThrows(ClientAuthenticationException.class, + () -> credentialBuilder(http).build().getTokenSync(new TokenRequestContext().addScopes(SCOPE))); + assertEquals( + "GitHubActionsCredential: Authentication Failed. OIDC request returned status code " + status + ".", + error.getMessage()); + assertFalse(error.getMessage().contains("response-secret-sentinel")); + assertNull(error.getCause()); + assertEquals(0, http.tokenForms.size()); + assertEquals(http.oidcRequests.get(), http.closedResponses.get()); + } + + @ParameterizedTest + @CsvSource( + delimiter = '|', + value = { + "|Received null token from OIDC request.", + "''|Received null token from OIDC request.", + "' '|Failed to parse OIDC response.", + "null|\"value\" field not detected in the response.", + "[]|\"value\" field not detected in the response.", + "true|\"value\" field not detected in the response.", + "42|\"value\" field not detected in the response.", + "{}|\"value\" field not detected in the response.", + "{\"value\":null}|\"value\" field not detected in the response.", + "{\"value\":42}|\"value\" field not detected in the response.", + "{\"value\":true}|\"value\" field not detected in the response.", + "{\"value\":{}}|\"value\" field not detected in the response.", + "{\"value\":[]}|\"value\" field not detected in the response.", + "{\"value\":\"\"}|\"value\" field not detected in the response.", + "response-secret-sentinel|Failed to parse OIDC response.", + "{\"value\":\"response-secret-sentinel\"|Failed to parse OIDC response.", + "{\"value\":\"response-secret-sentinel\"} {}|Failed to parse OIDC response.", + "{\"value\":\"response-secret-sentinel\"} trailing|Failed to parse OIDC response." }) + void rejectsInvalidResponsesWithoutDisclosingAssertions(String body, String reason) { + FakeHttpClient http = new FakeHttpClient(); + http.oidcBody = body; + ClientAuthenticationException error = assertThrows(ClientAuthenticationException.class, + () -> credentialBuilder(http).build().getTokenSync(new TokenRequestContext().addScopes(SCOPE))); + assertEquals("GitHubActionsCredential: Authentication Failed. " + reason, error.getMessage()); + StringWriter diagnostics = new StringWriter(); + error.printStackTrace(new PrintWriter(diagnostics)); + assertFalse(diagnostics.toString().contains("response-secret-sentinel")); + assertEquals(0, http.tokenForms.size()); + assertEquals(http.oidcRequests.get(), http.closedResponses.get()); + } + + @Test + void asyncHttpFailureRetainsAuthenticationException() { + FakeHttpClient http = new FakeHttpClient(); + http.oidcStatus = 401; + StepVerifier.create(credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE))) + .expectErrorSatisfies(error -> { + assertTrue(error instanceof ClientAuthenticationException); + assertEquals("GitHubActionsCredential: Authentication Failed. OIDC request returned status code 401.", + error.getMessage()); + }) + .verify(TIMEOUT); + assertEquals(0, http.tokenForms.size()); + } + + @ParameterizedTest + @CsvSource( + delimiter = '|', + value = { + "|Received null token from OIDC request.", + "''|Received null token from OIDC request.", + "null|\"value\" field not detected in the response.", + "response-secret-sentinel|Failed to parse OIDC response." }) + void asyncInvalidResponseRetainsAuthenticationException(String body, String reason) { + FakeHttpClient http = new FakeHttpClient(); + http.oidcBody = body; + StepVerifier.create(credentialBuilder(http).build().getToken(new TokenRequestContext().addScopes(SCOPE))) + .expectErrorSatisfies(error -> { + assertTrue(error instanceof ClientAuthenticationException); + assertEquals("GitHubActionsCredential: Authentication Failed. " + reason, error.getMessage()); + StringWriter diagnostics = new StringWriter(); + error.printStackTrace(new PrintWriter(diagnostics)); + assertFalse(diagnostics.toString().contains("response-secret-sentinel")); + }) + .verify(TIMEOUT); + assertEquals(0, http.tokenForms.size()); + assertEquals(http.oidcRequests.get(), http.closedResponses.get()); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void retriesAsyncAuthenticationAfterOidcFailure(boolean caeEnabled) { + FakeHttpClient http = new FakeHttpClient(); + http.oidcStatus = 401; + GitHubActionsCredential credential = credentialBuilder(http).build(); + TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE).setCaeEnabled(caeEnabled); + Mono token = credential.getToken(request); + StepVerifier.create(token).expectError(ClientAuthenticationException.class).verify(TIMEOUT); + int failedRequests = http.oidcRequests.get(); + assertTrue(failedRequests > 0); + assertEquals(0, http.tokenForms.size()); + + http.oidcStatus = 200; + StepVerifier.create(token) + .assertNext(value -> assertEquals("access-token-1", value.getToken())) + .expectComplete() + .verify(TIMEOUT); + int successfulRequests = http.oidcRequests.get(); + assertTrue(successfulRequests > failedRequests); + assertEquals("access-token-1", getToken(credential, request, true).getToken()); + assertEquals(successfulRequests, http.oidcRequests.get()); + assertEquals(1, http.tokenForms.size()); + assertEquals(http.oidcRequests.get(), http.closedResponses.get()); + } + + @Test + void asyncRequestIsLazyAndDoesNotPerformHttpOnAnEventLoop() { + FakeHttpClient http = new FakeHttpClient(); + GitHubActionsCredential credential = credentialBuilder(http).build(); + Mono token = credential.getToken(new TokenRequestContext().addScopes(SCOPE)); + assertEquals(0, http.oidcRequests.get()); + StepVerifier.create(token.subscribeOn(Schedulers.parallel())) + .assertNext(value -> assertEquals("access-token-1", value.getToken())) + .expectComplete() + .verify(TIMEOUT); + assertFalse(http.nonBlockingOidcThread.get()); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void propagatesTransportAndEntraFailures(boolean async) { + FakeHttpClient http = new FakeHttpClient(); + http.transportFailure = new IllegalStateException("GitHub transport unavailable"); + RuntimeException transportError = assertThrows(RuntimeException.class, + () -> getToken(credentialBuilder(http).build(), new TokenRequestContext().addScopes(SCOPE), async)); + Throwable cause = transportError; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertSame(http.transportFailure, cause); + assertEquals(0, http.tokenForms.size()); + + http.transportFailure = null; + http.tokenStatus = 400; + RuntimeException tokenError = assertThrows(RuntimeException.class, + () -> getToken(credentialBuilder(http).build(), new TokenRequestContext().addScopes(SCOPE), async)); + assertTrue(tokenError.getMessage().contains("bad-federation")); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void forwardsTenantAndCaeOptions(boolean async) { + FakeHttpClient http = new FakeHttpClient(); + GitHubActionsCredential credential + = credentialBuilder(http).additionallyAllowedTenants("other.contoso.com").build(); + TokenRequestContext request + = new TokenRequestContext().addScopes(SCOPE).setTenantId("other.contoso.com").setCaeEnabled(true); + getToken(credential, request, async); + assertTrue(http.lastTokenPath.contains("other.contoso.com")); + String claims = http.tokenForms.get(0).get("claims"); + assertNotNull(claims); + assertTrue(claims.contains("CP1"), claims); + } + + @Test + void forwardsClaimsOnAsyncTokenRequests() { + FakeHttpClient http = new FakeHttpClient(); + TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE) + .setCaeEnabled(true) + .setClaims("{\"access_token\":{\"auth_time\":{\"essential\":true}}}"); + getToken(credentialBuilder(http).build(), request, true); + assertTrue(http.tokenForms.get(0).get("claims").contains("auth_time")); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + void refreshesCachedTokenForCaeClaims(boolean async) { + FakeHttpClient http = new FakeHttpClient(); + GitHubActionsCredential credential = credentialBuilder(http).build(); + TokenRequestContext request = new TokenRequestContext().addScopes(SCOPE).setCaeEnabled(true); + assertEquals("access-token-1", getToken(credential, request, async).getToken()); + assertEquals("access-token-1", getToken(credential, request, async).getToken()); + assertEquals(1, http.tokenForms.size()); + + TokenRequestContext claimsRequest = new TokenRequestContext().addScopes(SCOPE) + .setCaeEnabled(true) + .setClaims("{\"access_token\":{\"auth_time\":{\"essential\":true}}}"); + assertEquals("access-token-2", getToken(credential, claimsRequest, async).getToken()); + assertEquals(2, http.tokenForms.size()); + String claims = http.tokenForms.get(1).get("claims"); + assertNotNull(claims); + assertTrue(claims.contains("auth_time"), claims); + assertTrue(claims.contains("CP1"), claims); + } + + @Test + void usesTheSuppliedPipelineForBothRequests() { + FakeHttpClient http = new FakeHttpClient(); + HttpHeaderName header = HttpHeaderName.fromString("x-test-credential"); + GitHubActionsCredential credential = credentialBuilder(http).pipeline(new HttpPipelineBuilder().httpClient(http) + .policies(new AddHeadersPolicy(new HttpHeaders().set(header, "custom-pipeline"))) + .build()).build(); + credential.getTokenSync(new TokenRequestContext().addScopes(SCOPE)); + assertEquals("custom-pipeline", http.oidcRequest.getHeaders().getValue(header)); + assertEquals("custom-pipeline", http.tokenRequest.getHeaders().getValue(header)); + } + + static GitHubActionsCredentialBuilder credentialBuilder(FakeHttpClient http) { + return new GitHubActionsCredentialBuilder().configuration(configuration(settings())) + .httpClient(http) + .disableInstanceDiscovery(); + } + + static Map settings() { + Map settings = new HashMap<>(); + settings.put("AZURE_CLIENT_ID", CLIENT_ID); + settings.put("AZURE_TENANT_ID", TENANT_ID); + settings.put("ACTIONS_ID_TOKEN_REQUEST_URL", "https://github-oidc.test/token?api-version=1"); + settings.put("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "runner-token-sentinel"); + return settings; + } + + static Configuration configuration(Map settings) { + TestConfigurationSource source = new TestConfigurationSource(); + settings.forEach(source::put); + return TestUtils.createTestConfiguration(source); + } + + private static AccessToken getToken(GitHubActionsCredential credential, TokenRequestContext request, + boolean async) { + return async ? credential.getToken(request).block(TIMEOUT) : credential.getTokenSync(request); + } + + static Map parseForm(String body) { + Map result = new HashMap<>(); + for (String parameter : body.split("&")) { + String[] parts = parameter.split("=", 2); + try { + result.put(URLDecoder.decode(parts[0], StandardCharsets.UTF_8.name()), + parts.length == 1 ? "" : URLDecoder.decode(parts[1], StandardCharsets.UTF_8.name())); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException(e); + } + } + return result; + } + + static class FakeHttpClient implements HttpClient { + final AtomicInteger oidcRequests = new AtomicInteger(); + final AtomicInteger closedResponses = new AtomicInteger(); + final AtomicBoolean nonBlockingOidcThread = new AtomicBoolean(); + final List> tokenForms = Collections.synchronizedList(new ArrayList<>()); + volatile HttpRequest oidcRequest; + volatile HttpRequest tokenRequest; + volatile String lastTokenPath; + int oidcStatus = 200; + int tokenStatus = 200; + int expiresIn = 3600; + String oidcBody = "{\"ignored\":{\"nested\":[1,2]},\"value\":\"" + ASSERTION + "\"}"; + RuntimeException transportFailure; + + @Override + public Mono send(HttpRequest request) { + return Mono.fromSupplier(() -> sendSync(request, Context.NONE)); + } + + @Override + public HttpResponse sendSync(HttpRequest request, Context context) { + if ("github-oidc.test".equals(request.getUrl().getHost())) { + if (transportFailure != null) { + throw transportFailure; + } + oidcRequest = request; + oidcRequests.incrementAndGet(); + if (Schedulers.isInNonBlockingThread()) { + nonBlockingOidcThread.set(true); + } + assertEquals(HttpMethod.GET, request.getHttpMethod()); + assertEquals("Bearer runner-token-sentinel", + request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION)); + AtomicBoolean closed = new AtomicBoolean(); + return new MockHttpResponse(request, oidcStatus, jsonHeaders(), + oidcBody == null ? null : oidcBody.getBytes(StandardCharsets.UTF_8)) { + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + closedResponses.incrementAndGet(); + } + super.close(); + } + }; + } + String authority = "https://" + request.getUrl().getAuthority(); + String tenant = request.getUrl().getPath().split("/")[1]; + if (request.getUrl().getPath().contains(".well-known/openid-configuration")) { + String endpoint = authority + "/" + tenant + "/oauth2/v2.0/"; + return response(request, 200, + "{\"token_endpoint\":\"" + endpoint + "token\"," + "\"issuer\":\"" + authority + "/" + tenant + + "/v2.0\"," + "\"authorization_endpoint\":\"" + endpoint + "authorize\"}"); + } + assertTrue(request.getUrl().getPath().endsWith("/token"), "Unexpected request: " + request.getUrl()); + assertEquals(HttpMethod.POST, request.getHttpMethod()); + tokenRequest = request; + lastTokenPath = request.getUrl().getPath(); + Map form = parseForm(request.getBodyAsBinaryData().toString()); + tokenForms.add(form); + if (tokenStatus != 200) { + return response(request, tokenStatus, + "{\"error\":\"invalid_grant\",\"error_description\":\"bad-federation\"}"); + } + return response(request, 200, + "{\"token_type\":\"Bearer\",\"scope\":\"" + form.get("scope") + "\",\"expires_in\":" + expiresIn + + ",\"ext_expires_in\":" + expiresIn + ",\"access_token\":\"access-token-" + tokenForms.size() + + "\"}"); + } + + private static HttpHeaders jsonHeaders() { + return new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"); + } + + private static HttpResponse response(HttpRequest request, int status, String body) { + return new MockHttpResponse(request, status, jsonHeaders(), body.getBytes(StandardCharsets.UTF_8)); + } + } +} diff --git a/sdk/identity/cspell.yml b/sdk/identity/cspell.yml index 7a4a6dc172f24..f1799a81359ca 100644 --- a/sdk/identity/cspell.yml +++ b/sdk/identity/cspell.yml @@ -20,3 +20,4 @@ words: - "maanged" - "obocredential" - "psql" + - "sovcloud"