-
Notifications
You must be signed in to change notification settings - Fork 1k
Add Athenz integration module #6321
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
cdfbe39
Add Athenz integration module
ikhoon 58f37b0
Exclude MRJARs files that are not compatible with the target Java ver…
ikhoon 144fdfb
fix javadoc compile errors
ikhoon 9d4ec15
use java11
ikhoon 14c9c69
set docker network
ikhoon da2cbf6
no mount log directories
ikhoon a3e013c
use local compose
ikhoon aab4934
change zt_store location
ikhoon 92fced3
detect docker correctly
ikhoon 743ffcc
lint
ikhoon 46f936f
launch docker compose per test suite
ikhoon ec87d91
add name for asyncloader and add test case for force reload
ikhoon aeecb50
add name to test
ikhoon 8ad7318
avoid possible context leak
ikhoon 4d519f7
fix
ikhoon 75e8156
Merge branch 'main' into athenz
ikhoon 357ad7b
Merge branch 'main' into athenz
ikhoon 2bb7e27
update javadoc
ikhoon 98ff748
Address comments by @minwoox
ikhoon fb2fa8a
revert javadoc
ikhoon 875b3d9
address comments by @jrhee17
ikhoon d597b5b
Merge branch 'main' into athenz
ikhoon 23a9f80
Merge branch 'main' into athenz
ikhoon c9bbe59
Merge branch 'athenz' of github.com:ikhoon/armeria into athenz
ikhoon 909b373
Merge branch 'main' into athenz
ikhoon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| /* | ||
| * Copyright 2025 LINE Corporation | ||
| * | ||
| * LINE Corporation licenses this file to you under the Apache License, | ||
| * version 2.0 (the "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at: | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
| * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
| * License for the specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| dependencies { | ||
| implementation project(":oauth2") | ||
| implementation libs.athenz.zts.client | ||
| implementation libs.athenz.zpe.client | ||
| implementation libs.caffeine | ||
|
|
||
| testImplementation libs.athenz.zms.client | ||
| testImplementation libs.jwt | ||
| testImplementation libs.testcontainers.junit.jupiter | ||
| } |
113 changes: 113 additions & 0 deletions
113
athenz/src/main/java/com/linecorp/armeria/client/athenz/AccessTokenClient.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| /* | ||
| * Copyright 2025 LINE Corporation | ||
| * | ||
| * LINE Corporation licenses this file to you under the Apache License, | ||
| * version 2.0 (the "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at: | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
| * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
| * License for the specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| package com.linecorp.armeria.client.athenz; | ||
|
|
||
| import static com.linecorp.armeria.client.athenz.RoleTokenClient.ROLE_JOINER; | ||
|
|
||
| import java.time.Duration; | ||
| import java.time.Instant; | ||
| import java.util.List; | ||
| import java.util.concurrent.CompletableFuture; | ||
| import java.util.concurrent.atomic.AtomicBoolean; | ||
|
|
||
| import com.google.common.collect.ImmutableList; | ||
| import com.yahoo.athenz.auth.AuthorityConsts; | ||
|
|
||
| import com.linecorp.armeria.client.auth.oauth2.AccessTokenRequest; | ||
| import com.linecorp.armeria.client.auth.oauth2.OAuth2AuthorizationGrant; | ||
| import com.linecorp.armeria.common.HttpHeadersBuilder; | ||
| import com.linecorp.armeria.common.QueryParamsBuilder; | ||
| import com.linecorp.armeria.common.athenz.AccessDeniedException; | ||
| import com.linecorp.armeria.common.auth.oauth2.ClientAuthentication; | ||
| import com.linecorp.armeria.common.auth.oauth2.GrantedOAuth2AccessToken; | ||
| import com.linecorp.armeria.common.util.Exceptions; | ||
|
|
||
| final class AccessTokenClient implements TokenClient { | ||
|
|
||
| private final AtomicBoolean tlsKeyPairUpdated = new AtomicBoolean(); | ||
|
|
||
| private final long refreshBeforeMillis; | ||
| private final String domainName; | ||
| private final List<String> roleNames; | ||
| private final OAuth2AuthorizationGrant authorizationGrant; | ||
|
|
||
| AccessTokenClient(ZtsBaseClient ztsBaseClient, String domainName, List<String> roleNames, | ||
| Duration refreshBefore) { | ||
| refreshBeforeMillis = refreshBefore.toMillis(); | ||
| this.domainName = domainName; | ||
| this.roleNames = roleNames; | ||
|
|
||
| ztsBaseClient.addTlsKeyPairListener(tlsKeyPair -> tlsKeyPairUpdated.set(true)); | ||
|
|
||
| // Scope syntax: | ||
| // - <domain-name>:domain | ||
| // - <domain-name>:role.<role-name> | ||
| // https://github.com/AthenZ/athenz/blob/5e064414224eca025c7a4ae1df5b5eb381e71a16/clients/java/zts/src/main/java/com/yahoo/athenz/zts/ZTSClient.java#L1446 | ||
| final ImmutableList.Builder<String> scopeBuilder = ImmutableList.builder(); | ||
| if (roleNames.isEmpty()) { | ||
| scopeBuilder.add(domainName + ":domain"); | ||
| } else { | ||
| for (String role : roleNames) { | ||
| scopeBuilder.add(domainName + AuthorityConsts.ROLE_SEP + role); | ||
| } | ||
| } | ||
| final AccessTokenRequest tokenRequest = AccessTokenRequest.ofClientCredentials( | ||
| NoopClientAuthentication.INSTANCE, scopeBuilder.build()); | ||
| authorizationGrant = OAuth2AuthorizationGrant.builder(ztsBaseClient.webClient(), | ||
| "/oauth2/token") | ||
| .accessTokenRequest(tokenRequest) | ||
| .refreshIf(this::shouldRefreshToken) | ||
| .build(); | ||
| } | ||
|
|
||
| private boolean shouldRefreshToken(GrantedOAuth2AccessToken token) { | ||
| if (tlsKeyPairUpdated.compareAndSet(true, false)) { | ||
| // If the TLS key pair is updated, we need to refresh the token. | ||
| return true; | ||
| } | ||
| final Duration expiresIn = token.expiresIn(); | ||
| if (expiresIn == null) { | ||
| return false; | ||
| } | ||
|
|
||
| return !token.isValid(Instant.now().plusMillis(refreshBeforeMillis)); | ||
| } | ||
|
|
||
| @Override | ||
| public CompletableFuture<String> getToken() { | ||
| return authorizationGrant.getAccessToken().handle((token, cause) -> { | ||
| if (cause != null) { | ||
| cause = Exceptions.peel(cause); | ||
| throw new AccessDeniedException("Failed to obtain an Athenz access token. (domain: " + | ||
| domainName + ", roles: " + ROLE_JOINER.join(roleNames) + ')', | ||
| cause); | ||
| } | ||
| return token.accessToken(); | ||
| }).toCompletableFuture(); | ||
| } | ||
|
|
||
| private enum NoopClientAuthentication implements ClientAuthentication { | ||
|
|
||
| INSTANCE; | ||
|
|
||
| @Override | ||
| public void addAsHeaders(HttpHeadersBuilder headersBuilder) {} | ||
|
|
||
| @Override | ||
| public void addAsBodyParams(QueryParamsBuilder formBuilder) {} | ||
| } | ||
| } |
178 changes: 178 additions & 0 deletions
178
athenz/src/main/java/com/linecorp/armeria/client/athenz/AthenzClient.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| /* | ||
| * Copyright 2025 LY Corporation | ||
| * | ||
| * LY Corporation licenses this file to you under the Apache License, | ||
| * version 2.0 (the "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at: | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
| * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
| * License for the specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
|
|
||
| package com.linecorp.armeria.client.athenz; | ||
|
|
||
| import static com.linecorp.armeria.internal.common.athenz.AthenzHeaderNames.YAHOO_ROLE_AUTH; | ||
| import static java.util.Objects.requireNonNull; | ||
|
|
||
| import java.time.Duration; | ||
| import java.util.List; | ||
| import java.util.concurrent.CompletableFuture; | ||
| import java.util.function.Function; | ||
|
|
||
| import com.google.common.collect.ImmutableList; | ||
|
|
||
| import com.linecorp.armeria.client.ClientRequestContext; | ||
| import com.linecorp.armeria.client.HttpClient; | ||
| import com.linecorp.armeria.client.SimpleDecoratingHttpClient; | ||
| import com.linecorp.armeria.common.HttpHeaderNames; | ||
| import com.linecorp.armeria.common.HttpRequest; | ||
| import com.linecorp.armeria.common.HttpResponse; | ||
| import com.linecorp.armeria.common.RequestHeadersBuilder; | ||
| import com.linecorp.armeria.common.annotation.UnstableApi; | ||
| import com.linecorp.armeria.common.athenz.TokenType; | ||
| import com.linecorp.armeria.common.util.Exceptions; | ||
|
|
||
| /** | ||
| * An {@link HttpClient} that adds an Athenz token to the request headers. | ||
| * {@link TokenType#ACCESS_TOKEN} and {@link TokenType#ROLE_TOKEN} are supported. | ||
| * | ||
| * <p>The acquired token is cached and automatically refreshed before it expires based on the specified | ||
| * duration. If not specified, the default refresh duration is 10 minutes before the token expires. | ||
| * | ||
| * <p>Example: | ||
| * <pre>{@code | ||
| * import com.linecorp.armeria.client.athenz.ZtsBaseClient; | ||
| * import com.linecorp.armeria.client.athenz.AthenzClient; | ||
| * | ||
| * ZtsBaseClient ztsBaseClient = | ||
| * ZtsBaseClient | ||
| * .builder("https://athenz.example.com:8443/zts/v1") | ||
| * .keyPair("/var/lib/athenz/service.key.pem", "/var/lib/athenz/service.cert.pem") | ||
| * .build(); | ||
| * | ||
| * WebClient | ||
| * .builder() | ||
| * .decorator(AthenzClient.newDecorator(ztsBaseClient, "my-domain", | ||
| * TokenType.ROLE_TOKEN) | ||
| * ... | ||
| * .build(); | ||
| * }</pre> | ||
| */ | ||
| @UnstableApi | ||
| public final class AthenzClient extends SimpleDecoratingHttpClient { | ||
|
|
||
| private static final Duration DEFAULT_REFRESH_BEFORE = Duration.ofMinutes(10); | ||
|
|
||
| /** | ||
| * Returns a new {@link HttpClient} decorator that obtains an Athenz token for the specified domain and | ||
| * adds it to the request headers. | ||
| * | ||
| * @param ztsBaseClient the ZTS base client to use to communicate with the ZTS server | ||
| * @param domainName the Athenz domain name | ||
| * @param tokenType the type of Athenz token to obtain | ||
| */ | ||
| public static Function<HttpClient, AthenzClient> newDecorator(ZtsBaseClient ztsBaseClient, | ||
| String domainName, TokenType tokenType) { | ||
| return newDecorator(ztsBaseClient, domainName, ImmutableList.of(), tokenType); | ||
| } | ||
|
|
||
| /** | ||
| * Returns a new {@link HttpClient} decorator that obtains an Athenz token for the specified domain and | ||
| * role name, and adds it to the request headers. | ||
| * | ||
| * @param ztsBaseClient the ZTS base client to use to communicate with the ZTS server | ||
| * @param domainName the Athenz domain name | ||
| * @param roleName the Athenz role name | ||
| * @param tokenType the type of Athenz token to obtain | ||
| */ | ||
| public static Function<HttpClient, AthenzClient> newDecorator(ZtsBaseClient ztsBaseClient, | ||
| String domainName, String roleName, | ||
| TokenType tokenType) { | ||
| return newDecorator(ztsBaseClient, domainName, ImmutableList.of(roleName), tokenType); | ||
| } | ||
|
|
||
| /** | ||
| * Returns a new {@link HttpClient} decorator that obtains an Athenz token for the specified domain and | ||
| * role names, and adds it to the request headers. | ||
| * | ||
| * @param ztsBaseClient the ZTS base client to use to communicate with the ZTS server | ||
| * @param domainName the Athenz domain name | ||
| * @param roleNames the list of Athenz role names | ||
| * @param tokenType the type of Athenz token to obtain | ||
| */ | ||
| public static Function<HttpClient, AthenzClient> newDecorator(ZtsBaseClient ztsBaseClient, | ||
| String domainName, List<String> roleNames, | ||
| TokenType tokenType) { | ||
| return newDecorator(ztsBaseClient, domainName, roleNames, tokenType, DEFAULT_REFRESH_BEFORE); | ||
| } | ||
|
|
||
| /** | ||
| * Returns a new {@link HttpClient} decorator that obtains an Athenz token for the specified domain and | ||
| * role names, and adds it to the request headers. | ||
| * | ||
| * @param ztsBaseClient the ZTS base client to use to communicate with the ZTS server | ||
| * @param domainName the Athenz domain name | ||
| * @param roleNames the list of Athenz role names | ||
| * @param tokenType the type of Athenz token to obtain | ||
| * @param refreshBefore the duration before the token expires to refresh it | ||
| */ | ||
| public static Function<HttpClient, AthenzClient> newDecorator(ZtsBaseClient ztsBaseClient, | ||
| String domainName, List<String> roleNames, | ||
| TokenType tokenType, Duration refreshBefore) { | ||
| requireNonNull(ztsBaseClient, "ztsBaseClient"); | ||
| requireNonNull(domainName, "domainName"); | ||
| requireNonNull(roleNames, "roleNames"); | ||
| final ImmutableList<String> roleNames0 = ImmutableList.copyOf(roleNames); | ||
| requireNonNull(tokenType, "tokenType"); | ||
| requireNonNull(refreshBefore, "refreshBefore"); | ||
| return delegate -> new AthenzClient(delegate, ztsBaseClient, domainName, roleNames0, | ||
| tokenType, refreshBefore); | ||
| } | ||
|
|
||
| private final TokenType tokenType; | ||
| private final TokenClient tokenClient; | ||
|
|
||
| private AthenzClient(HttpClient delegate, ZtsBaseClient ztsBaseClient, String domainName, | ||
| List<String> roleNames, TokenType tokenType, Duration refreshBefore) { | ||
| super(delegate); | ||
| this.tokenType = tokenType; | ||
| switch (tokenType) { | ||
| case ROLE_TOKEN: | ||
| tokenClient = new RoleTokenClient(ztsBaseClient, domainName, roleNames, refreshBefore); | ||
| break; | ||
| case ACCESS_TOKEN: | ||
| tokenClient = new AccessTokenClient(ztsBaseClient, domainName, roleNames, refreshBefore); | ||
| break; | ||
| default: | ||
| throw new Error("unknown auth type: " + tokenType); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception { | ||
| final CompletableFuture<HttpResponse> future = tokenClient.getToken().thenApply(token -> { | ||
| final HttpRequest newReq = req.mapHeaders(headers -> { | ||
| final RequestHeadersBuilder builder = headers.toBuilder(); | ||
| if (tokenType == TokenType.ROLE_TOKEN) { | ||
| builder.set(YAHOO_ROLE_AUTH, token); | ||
| } else { | ||
| builder.set(HttpHeaderNames.AUTHORIZATION, "Bearer " + token); | ||
| } | ||
| return builder.build(); | ||
| }); | ||
| ctx.updateRequest(newReq); | ||
| try { | ||
| return unwrap().execute(ctx, newReq); | ||
| } catch (Exception e) { | ||
| return Exceptions.throwUnsafely(e); | ||
| } | ||
| }); | ||
|
|
||
| return HttpResponse.of(future); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Question) I'm not sure of the environment, but is
TokenType.ROLE_TOKENoften used? I'm wondering ifTokenType.ACCESS_TOKENshould be the defaultUh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Some LY internal servers only support
ROLE_TOKENtype. So I wasn't sure ifACCESS_TOKENcould be a sensible default.