Skip to content
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

chore: refactor AudienceResolver with Result as return #4266

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,9 @@ public <T, M extends RemoteMessage> CompletableFuture<StatusResult<T>> dispatch(

}

var tokenParameters = tokenDecorator.decorate(tokenParametersBuilder)
.claims(AUDIENCE_CLAIM, audienceResolver.resolve(message)) // enforce the audience, ignore anything a decorator might have set
.build();

return identityService.obtainClientCredentials(tokenParameters)
return audienceResolver.resolve(message)
.map(audience -> tokenDecorator.decorate(tokenParametersBuilder).claims(AUDIENCE_CLAIM, audience).build()) // enforce the audience, ignore anything a decorator might have set
.compose(identityService::obtainClientCredentials)
.map(token -> {
var requestWithAuth = request.newBuilder()
.header("Authorization", token.getToken())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import org.eclipse.edc.boot.system.injection.ObjectFactory;
import org.eclipse.edc.junit.extensions.DependencyInjectionExtension;
import org.eclipse.edc.protocol.dsp.http.message.DspRequestHandlerImpl;
import org.eclipse.edc.spi.iam.AudienceResolver;
import org.eclipse.edc.spi.iam.IdentityService;
import org.eclipse.edc.spi.result.Result;
import org.eclipse.edc.spi.system.ServiceExtensionContext;
Expand All @@ -38,16 +39,19 @@ class DspHttpCoreExtensionTest {

public static final String SCOPE_CLAIM = "scope";
private final IdentityService identityService = mock();
private final AudienceResolver audienceResolver = mock();
private DspHttpCoreExtension extension;

@BeforeEach
void setUp(ServiceExtensionContext context) {
context.registerService(IdentityService.class, identityService);
context.registerService(AudienceResolver.class, audienceResolver);
}

@Test
@DisplayName("Assert usage of the default (noop) token decorator")
void createDispatcher_noTokenDecorator_shouldUseNoop(ServiceExtensionContext context, ObjectFactory factory) {
when(audienceResolver.resolve(any())).thenReturn(Result.success("audience"));
when(identityService.obtainClientCredentials(any())).thenReturn(Result.failure("not-important"));
context.registerService(TokenDecorator.class, null);

Expand All @@ -62,6 +66,7 @@ void createDispatcher_noTokenDecorator_shouldUseNoop(ServiceExtensionContext con
@Test
@DisplayName("Assert usage of an injected TokenDecorator")
void createDispatcher_withTokenDecorator_shouldUse(ServiceExtensionContext context, ObjectFactory factory) {
when(audienceResolver.resolve(any())).thenReturn(Result.success("audience"));
when(identityService.obtainClientCredentials(any())).thenReturn(Result.failure("not-important"));
context.registerService(TokenDecorator.class, (td) -> td.claims(SCOPE_CLAIM, "test-scope"));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ private static okhttp3.Response.Builder dummyResponseBuilder(int code) {

@BeforeEach
void setUp() {
when(audienceResolver.resolve(any())).thenReturn(AUDIENCE_VALUE);
when(tokenDecorator.decorate(any())).thenAnswer(a -> a.getArgument(0));
}

Expand All @@ -110,6 +109,7 @@ void dispatch_noScope() {
var authToken = "token";
Map<String, Object> additional = Map.of("foo", "bar");
var policy = Policy.Builder.newInstance().build();
when(audienceResolver.resolve(any())).thenReturn(Result.success(AUDIENCE_VALUE));
when(tokenDecorator.decorate(any())).thenAnswer(a -> a.getArgument(0, TokenParameters.Builder.class).claims(additional));
when(requestFactory.createRequest(any())).thenReturn(new Request.Builder().url("http://url").build());
when(httpClient.executeAsync(any(), isA(List.class))).thenReturn(completedFuture(dummyResponse(200)));
Expand Down Expand Up @@ -144,6 +144,7 @@ void dispatch_ensureTokenDecoratorScope() {
var authToken = "token";
Map<String, Object> additional = Map.of("foo", "bar");
var policy = Policy.Builder.newInstance().build();
when(audienceResolver.resolve(any())).thenReturn(Result.success(AUDIENCE_VALUE));
when(tokenDecorator.decorate(any())).thenAnswer(a -> a.getArgument(0, TokenParameters.Builder.class).claims(additional).claims(SCOPE_CLAIM, "test-scope"));
when(requestFactory.createRequest(any())).thenReturn(new Request.Builder().url("http://url").build());
when(httpClient.executeAsync(any(), isA(List.class))).thenReturn(completedFuture(dummyResponse(200)));
Expand Down Expand Up @@ -183,6 +184,7 @@ void dispatch_PolicyEvaluatedScope() {
var authToken = "token";
Map<String, Object> additional = Map.of("foo", "bar");
var policy = Policy.Builder.newInstance().build();
when(audienceResolver.resolve(any())).thenReturn(Result.success(AUDIENCE_VALUE));
when(tokenDecorator.decorate(any())).thenAnswer(a -> a.getArgument(0, TokenParameters.Builder.class).claims(additional));
when(requestFactory.createRequest(any())).thenReturn(new Request.Builder().url("http://url").build());
when(httpClient.executeAsync(any(), isA(List.class))).thenReturn(completedFuture(dummyResponse(200)));
Expand Down Expand Up @@ -232,6 +234,7 @@ void dispatch_messageNotRegistered_throwException() {
@Test
void dispatch_failedToObtainToken_throwException() {
dispatcher.registerMessage(TestMessage.class, requestFactory, mock());
when(audienceResolver.resolve(any())).thenReturn(Result.success(AUDIENCE_VALUE));
when(requestFactory.createRequest(any())).thenReturn(new Request.Builder().url("http://url").build());
when(identityService.obtainClientCredentials(any())).thenReturn(Result.failure("error"));

Expand All @@ -241,8 +244,21 @@ void dispatch_failedToObtainToken_throwException() {
verifyNoInteractions(httpClient);
}

@Test
void dispatch_failedToResolveAudience_throwException() {
dispatcher.registerMessage(TestMessage.class, requestFactory, mock());
when(audienceResolver.resolve(any())).thenReturn(Result.failure("audience fetch failure"));
when(requestFactory.createRequest(any())).thenReturn(new Request.Builder().url("http://url").build());

assertThat(dispatcher.dispatch(String.class, new TestMessage())).failsWithin(timeout)
.withThrowableThat().withCauseInstanceOf(EdcException.class).withMessageContaining("audience fetch failure");

verifyNoInteractions(httpClient);
}

@Test
void dispatch_shouldNotEvaluatePolicy_whenItIsNotRegistered() {
when(audienceResolver.resolve(any())).thenReturn(Result.success(AUDIENCE_VALUE));
when(requestFactory.createRequest(any())).thenReturn(new Request.Builder().url("http://url").build());
when(httpClient.executeAsync(any(), isA(List.class))).thenReturn(completedFuture(dummyResponse(200)));
when(identityService.obtainClientCredentials(any()))
Expand All @@ -258,6 +274,7 @@ void dispatch_shouldNotEvaluatePolicy_whenItIsNotRegistered() {
@Test
void dispatch_shouldEvaluatePolicy() {
var policy = Policy.Builder.newInstance().build();
when(audienceResolver.resolve(any())).thenReturn(Result.success(AUDIENCE_VALUE));
when(requestFactory.createRequest(any())).thenReturn(new Request.Builder().url("http://url").build());
when(httpClient.executeAsync(any(), isA(List.class))).thenReturn(completedFuture(dummyResponse(200)));
when(identityService.obtainClientCredentials(any()))
Expand Down Expand Up @@ -361,6 +378,7 @@ void shouldReturnRetryError_whenResponseIsServerError() {
}

private void respondWith(okhttp3.Response response, DspHttpResponseBodyExtractor<Object> bodyExtractor) {
when(audienceResolver.resolve(any())).thenReturn(Result.success(AUDIENCE_VALUE));
when(requestFactory.createRequest(any())).thenReturn(new Request.Builder().url("http://url").build());
when(httpClient.executeAsync(any(), isA(List.class))).thenReturn(completedFuture(response));
when(identityService.obtainClientCredentials(any()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
import org.eclipse.edc.runtime.metamodel.annotation.Provides;
import org.eclipse.edc.spi.iam.AudienceResolver;
import org.eclipse.edc.spi.iam.IdentityService;
import org.eclipse.edc.spi.result.Result;
import org.eclipse.edc.spi.system.ServiceExtension;
import org.eclipse.edc.spi.system.ServiceExtensionContext;
import org.eclipse.edc.spi.types.TypeManager;
import org.eclipse.edc.spi.types.domain.message.RemoteMessage;

/**
* An IAM provider mock used for testing.
Expand Down Expand Up @@ -51,6 +51,6 @@ public void initialize(ServiceExtensionContext context) {

@Provider
public AudienceResolver audienceResolver() {
return RemoteMessage::getCounterPartyAddress;
return (msg) -> Result.success(msg.getCounterPartyAddress());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@
import org.eclipse.edc.spi.EdcException;
import org.eclipse.edc.spi.iam.AudienceResolver;
import org.eclipse.edc.spi.iam.ClaimToken;
import org.eclipse.edc.spi.result.Result;
import org.eclipse.edc.spi.system.ServiceExtension;
import org.eclipse.edc.spi.system.ServiceExtensionContext;
import org.eclipse.edc.spi.types.domain.message.RemoteMessage;
import org.eclipse.edc.token.JwtGenerationService;

import java.security.PrivateKey;
Expand Down Expand Up @@ -107,7 +107,7 @@ public ScopeExtractorRegistry scopeExtractorRegistry() {
// Default audience for DCP is the counter-party id
@Provider(isDefault = true)
public AudienceResolver defaultAudienceResolver() {
return RemoteMessage::getCounterPartyId;
return (msg) -> Result.success(msg.getCounterPartyId());
}

// Default ClaimToken creator function, will use "vc" as key
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ void verify_defaultAudienceResolver(DcpDefaultServicesExtension ext) {
var id = "counterPartyId";
var remoteMessage = mock(RemoteMessage.class);
when(remoteMessage.getCounterPartyId()).thenReturn(id);
assertThat(ext.defaultAudienceResolver().resolve(remoteMessage)).isEqualTo(id);
assertThat(ext.defaultAudienceResolver().resolve(remoteMessage))
.extracting(Result::getContent)
.isEqualTo(id);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@

import org.eclipse.edc.runtime.metamodel.annotation.Provider;
import org.eclipse.edc.spi.iam.AudienceResolver;
import org.eclipse.edc.spi.result.Result;
import org.eclipse.edc.spi.system.ServiceExtension;
import org.eclipse.edc.spi.types.domain.message.RemoteMessage;

/**
* Provides default service implementations for fallback
Expand All @@ -35,6 +35,6 @@ public String name() {

@Provider(isDefault = true)
public AudienceResolver defaultAudienceResolver() {
return RemoteMessage::getCounterPartyAddress;
return (msg) -> Result.success(msg.getCounterPartyAddress());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package org.eclipse.edc.iam.oauth2;

import org.eclipse.edc.junit.extensions.DependencyInjectionExtension;
import org.eclipse.edc.spi.result.Result;
import org.eclipse.edc.spi.types.domain.message.RemoteMessage;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand All @@ -32,7 +33,9 @@ void defaultAudienceResolver(Oauth2ServiceDefaultServicesExtension extension) {
var address = "http://address";
var remoteMessage = mock(RemoteMessage.class);
when(remoteMessage.getCounterPartyAddress()).thenReturn(address);
assertThat(extension.defaultAudienceResolver().resolve(remoteMessage)).isEqualTo(address);
assertThat(extension.defaultAudienceResolver().resolve(remoteMessage))
.extracting(Result::getContent)
.isEqualTo(address);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package org.eclipse.edc.spi.iam;

import org.eclipse.edc.runtime.metamodel.annotation.ExtensionPoint;
import org.eclipse.edc.spi.result.Result;
import org.eclipse.edc.spi.types.domain.message.RemoteMessage;

/**
Expand All @@ -26,7 +27,7 @@
@FunctionalInterface
@ExtensionPoint
public interface AudienceResolver {
String resolve(RemoteMessage remoteMessage);

Result<String> resolve(RemoteMessage remoteMessage);

}
Loading