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

feat: add Authorization to the Management API #242

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 @@ -44,11 +44,12 @@ public DidDocumentServiceImpl(TransactionContext transactionContext, DidResource
}

@Override
public ServiceResult<Void> store(DidDocument document) {
public ServiceResult<Void> store(DidDocument document, String participantId) {
return transactionContext.execute(() -> {
var res = DidResource.Builder.newInstance()
.document(document)
.did(document.getId())
.participantId(participantId)
.build();
var result = didResourceStore.save(res);
return result.succeeded() ?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,14 @@ void setUp() {
void store() {
var doc = createDidDocument().build();
when(storeMock.save(argThat(dr -> dr.getDocument().equals(doc)))).thenReturn(StoreResult.success());
assertThat(service.store(doc)).isSucceeded();
assertThat(service.store(doc, "test-participant")).isSucceeded();
}

@Test
void store_alreadyExists() {
var doc = createDidDocument().build();
when(storeMock.save(argThat(dr -> dr.getDocument().equals(doc)))).thenReturn(StoreResult.alreadyExists("foo"));
assertThat(service.store(doc)).isFailed().detail().isEqualTo("foo");
assertThat(service.store(doc, "test-participant")).isFailed().detail().isEqualTo("foo");
verify(storeMock).save(any());
verifyNoInteractions(publisherMock);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@
import java.security.PublicKey;
import java.text.ParseException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

import static java.util.Optional.ofNullable;
import static org.eclipse.edc.spi.result.ServiceResult.badRequest;
import static org.eclipse.edc.spi.result.ServiceResult.conflict;
import static org.eclipse.edc.spi.result.ServiceResult.fromFailure;
Expand Down Expand Up @@ -103,7 +103,7 @@ public ServiceResult<ParticipantContext> getParticipantContext(String participan
@Override
public ServiceResult<Void> deleteParticipantContext(String participantId) {
return transactionContext.execute(() -> {
var did = Optional.ofNullable(findByIdInternal(participantId)).map(ParticipantContext::getDid);
var did = ofNullable(findByIdInternal(participantId)).map(ParticipantContext::getDid);
var res = participantContextStore.deleteById(participantId);
if (res.failed()) {
return fromFailure(res);
Expand Down Expand Up @@ -155,7 +155,7 @@ private ServiceResult<Void> generateDidDocument(ParticipantManifest manifest, JW
.publicKeyJwk(publicKey.toJSONObject())
.build()))
.build();
return didDocumentService.store(doc)
return didDocumentService.store(doc, manifest.getParticipantId())
.compose(u -> manifest.isActive() ? didDocumentService.publish(doc.getId()) : success());
}

Expand Down Expand Up @@ -204,7 +204,7 @@ private ServiceResult<Void> createParticipantContext(ParticipantContext context)
}

private ParticipantContext findByIdInternal(String participantId) {
var resultStream = participantContextStore.query(QuerySpec.Builder.newInstance().filter(new Criterion("participantContext", "=", participantId)).build());
var resultStream = participantContextStore.query(QuerySpec.Builder.newInstance().filter(new Criterion("participantId", "=", participantId)).build());
if (resultStream.failed()) return null;
return resultStream.getContent().stream().findFirst().orElse(null);
}
Expand All @@ -213,6 +213,7 @@ private ParticipantContext findByIdInternal(String participantId) {
private ParticipantContext convert(ParticipantManifest manifest) {
return ParticipantContext.Builder.newInstance()
.participantId(manifest.getParticipantId())
.roles(manifest.getRoles())
.apiTokenAlias("%s-%s".formatted(manifest.getParticipantId(), API_KEY_ALIAS_SUFFIX))
.state(manifest.isActive() ? ParticipantContextState.ACTIVATED : ParticipantContextState.CREATED)
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class ParticipantContextServiceImplTest {
@BeforeEach
void setUp() {
didDocumentService = mock();
when(didDocumentService.store(any())).thenReturn(success());
when(didDocumentService.store(any(), anyString())).thenReturn(success());
when(didDocumentService.publish(anyString())).thenReturn(success());
var keyParserRegistry = new KeyParserRegistryImpl();
keyParserRegistry.register(new PemParser(mock()));
Expand Down Expand Up @@ -93,7 +93,7 @@ void createParticipantContext_withPublicKeyPem(boolean isActive) {
.isSucceeded();

verify(participantContextStore).create(any());
verify(didDocumentService).store(argThat(dd -> dd.getId().equals(ctx.getDid())));
verify(didDocumentService).store(argThat(dd -> dd.getId().equals(ctx.getDid())), anyString());
verify(didDocumentService, times(isActive ? 1 : 0)).publish(anyString());
verify(vault).storeSecret(eq(ctx.getParticipantId() + "-apikey"), anyString());
verifyNoMoreInteractions(vault, participantContextStore);
Expand All @@ -111,7 +111,7 @@ void createParticipantContext_withPublicKeyJwk(boolean isActive) {
.isSucceeded();

verify(participantContextStore).create(any());
verify(didDocumentService).store(argThat(dd -> dd.getId().equals(ctx.getDid())));
verify(didDocumentService).store(argThat(dd -> dd.getId().equals(ctx.getDid())), anyString());
verify(didDocumentService, times(isActive ? 1 : 0)).publish(anyString());
verify(vault).storeSecret(eq(ctx.getParticipantId() + "-apikey"), anyString());
verifyNoMoreInteractions(vault, participantContextStore);
Expand All @@ -135,7 +135,7 @@ void createParticipantContext_withKeyGenParams(boolean isActive) {
verify(vault).storeSecret(eq(ctx.getKey().getPrivateKeyAlias()), anyString());
verify(vault).storeSecret(eq(ctx.getParticipantId() + "-apikey"), anyString());

verify(didDocumentService).store(argThat(dd -> dd.getId().equals(ctx.getDid())));
verify(didDocumentService).store(argThat(dd -> dd.getId().equals(ctx.getDid())), anyString());
verify(didDocumentService, times(isActive ? 1 : 0)).publish(anyString());
verifyNoMoreInteractions(vault, participantContextStore);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* Copyright (c) 2024 Metaform Systems, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* Metaform Systems, Inc. - initial API and implementation
*
*/

package org.eclipse.edc.identityhub.tests;

import io.restassured.http.Header;
import org.eclipse.edc.identityhub.spi.model.participant.ParticipantContext;
import org.eclipse.edc.junit.annotations.EndToEndTest;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;

import static io.restassured.http.ContentType.JSON;

@EndToEndTest
public class DidManagementApiEndToEndTest extends ManagementApiEndToEndTest {

@Test
void publishDid_notOwner_expect403() {
var user1 = "user1";
createParticipant(user1);


// create second user
var user2 = "user2";
var user2Context = ParticipantContext.Builder.newInstance()
.participantId(user2)
.did("did:web:" + user2)
.apiTokenAlias(user2 + "-alias")
.build();
var user2Token = storeParticipant(user2Context);

// attempt to publish user1's DID document, which should fail
RUNTIME_CONFIGURATION.getManagementEndpoint().baseRequest()
.contentType(JSON)
.header(new Header("x-api-key", user2Token))
.body("""
{
"did": "did:web:user1"
}
""")
.post("/v1/dids/publish")
.then()
.log().ifValidationFails()
.statusCode(403)
.body(Matchers.notNullValue());
}

@Test
void publishDid() {

var user = "test-user";
var token = createParticipant(user);
RUNTIME_CONFIGURATION.getManagementEndpoint().baseRequest()
.contentType(JSON)
.header(new Header("x-api-key", token))
.body("""
{
"did": "did:web:test-user"
}
""")
.post("/v1/dids/publish")
.then()
.log().ifValidationFails()
.statusCode(204)
.body(Matchers.notNullValue());
}

@Test
void getState_nowOwner_expect403() {
var user1 = "user1";
createParticipant(user1);

var user2 = "user2";
var token2 = createParticipant(user2);

RUNTIME_CONFIGURATION.getManagementEndpoint().baseRequest()
.header(new Header("x-api-key", token2))
.contentType(JSON)
.body("""
{
"did": "did:web:user1"
}
""")
.post("/v1/dids/state")
.then()
.log().ifValidationFails()
.statusCode(403);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright (c) 2024 Metaform Systems, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* Metaform Systems, Inc. - initial API and implementation
*
*/

package org.eclipse.edc.identityhub.tests;

import org.eclipse.edc.iam.did.spi.document.Service;
import org.eclipse.edc.identityhub.participantcontext.ApiTokenGenerator;
import org.eclipse.edc.identityhub.spi.ParticipantContextService;
import org.eclipse.edc.identityhub.spi.model.participant.KeyDescriptor;
import org.eclipse.edc.identityhub.spi.model.participant.ParticipantContext;
import org.eclipse.edc.identityhub.spi.model.participant.ParticipantManifest;
import org.eclipse.edc.identityhub.spi.store.ParticipantContextStore;
import org.eclipse.edc.identityhub.tests.fixtures.IdentityHubRuntimeConfiguration;
import org.eclipse.edc.junit.extensions.EdcRuntimeExtension;
import org.eclipse.edc.spi.EdcException;
import org.eclipse.edc.spi.security.Vault;
import org.junit.jupiter.api.extension.RegisterExtension;

import java.util.Map;

/**
* Base class for all management API tests
*/
public abstract class ManagementApiEndToEndTest {
public static final String SUPER_USER = "super-user";
protected static final IdentityHubRuntimeConfiguration RUNTIME_CONFIGURATION = IdentityHubRuntimeConfiguration.Builder.newInstance()
.name("identity-hub")
.id("identity-hub")
.build();
@RegisterExtension
protected static final EdcRuntimeExtension RUNTIME = new EdcRuntimeExtension(":launcher", "identity-hub", RUNTIME_CONFIGURATION.controlPlaneConfiguration());

protected String getSuperUserApiKey() {
var vault = RUNTIME.getContext().getService(Vault.class);
return vault.resolveSecret("super-user-apikey");
}

protected String storeParticipant(ParticipantContext pc) {
var store = RUNTIME.getContext().getService(ParticipantContextStore.class);

var vault = RUNTIME.getContext().getService(Vault.class);
var token = createTokenFor(pc.getParticipantId());
vault.storeSecret(pc.getApiTokenAlias(), token);
store.create(pc).orElseThrow(f -> new RuntimeException(f.getFailureDetail()));
return token;
}

protected String createParticipant(String participantId) {
var manifest = ParticipantManifest.Builder.newInstance()
.participantId(participantId)
.active(true)
.serviceEndpoint(new Service("test-service-id", "test-type", "http://foo.bar.com"))
.did("did:web:" + participantId)
.key(KeyDescriptor.Builder.newInstance()
.privateKeyAlias(participantId + "-alias")
.keyId(participantId + "-key")
.keyGeneratorParams(Map.of("algorithm", "EC", "curve", "secp256r1"))
.build())
.build();
var srv = RUNTIME.getContext().getService(ParticipantContextService.class);
return srv.createParticipantContext(manifest).orElseThrow(f -> new EdcException(f.getFailureDetail()));
}

protected String createTokenFor(String userId) {
return new ApiTokenGenerator().generate(userId);
}

protected static ParticipantManifest createNewParticipant() {
var manifest = ParticipantManifest.Builder.newInstance()
.participantId("another-participant")
.active(false)
.did("did:web:another:participant")
.serviceEndpoint(new Service("test-service", "test-service-type", "https://test.com"))
.key(KeyDescriptor.Builder.newInstance()
.privateKeyAlias("another-alias")
.keyGeneratorParams(Map.of("algorithm", "EdDSA", "curve", "Ed25519"))
.keyId("another-keyid")
.build())
.build();
return manifest;
}
}
Loading
Loading