Elffuss BraidHub

kikocis/EDC public

feat: STS client SQL store implementation (#4474)

* feat: STS client SQL store implementation

* pr remarks

* chore: deps file
Changeset548b9b363586814ccdfe6a9ef7d33d67845a55e48e5db4b203444e5987172ca5
AuthorEnrico Risa <enrico.risa@gmail.com> · 2024-09-16 10:02 +02:00
CommitterGitHub <noreply@github.com> · 2024-09-16 10:02 +02:00
Parentsc0226904a0b9

Browse the files at this changeset

26 files changed

modified DEPENDENCIES +1 −1
@@ -81,7 +81,7 @@
8181 maven/mavencentral/com.lmax/disruptor/3.4.4, Apache-2.0, approved, clearlydefined
8282 maven/mavencentral/com.networknt/json-schema-validator/1.0.76, Apache-2.0, approved, CQ22638
8383 maven/mavencentral/com.nimbusds/nimbus-jose-jwt/9.28, Apache-2.0, approved, clearlydefined
84-maven/mavencentral/com.nimbusds/nimbus-jose-jwt/9.41.1, , restricted, clearlydefined
84+maven/mavencentral/com.nimbusds/nimbus-jose-jwt/9.41.1, Apache-2.0, approved, clearlydefined
8585 maven/mavencentral/com.puppycrawl.tools/checkstyle/10.18.1, LGPL-2.1-or-later AND (Apache-2.0 AND LGPL-2.1-or-later) AND Apache-2.0, approved, #16060
8686 maven/mavencentral/com.samskivert/jmustache/1.15, BSD-2-Clause AND BSD-3-Clause, approved, clearlydefined
8787 maven/mavencentral/com.squareup.okhttp3/okhttp-dnsoverhttps/4.12.0, Apache-2.0, approved, #11159
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-api/src/test/java/org/eclipse/edc/api/iam/identitytrust/sts/controller/SecureServiceTokenApiControllerTest.java +4 −1
@@ -55,14 +55,17 @@
5555 var did = "did:example:subject";
5656 var audience = "audience";
5757 var token = "token";
58+ var publicKeyReference = "publicKeyReference";
59+ var name = "Name";
5860 var expiresIn = 3600;
5961
6062 var client = StsClient.Builder.newInstance()
6163 .id(id)
6264 .clientId(clientId)
63- .name("Name")
65+ .name(name)
6466 .secretAlias(clientKeyAlias)
6567 .privateKeyAlias(privateKeyAlias)
68+ .publicKeyReference(publicKeyReference)
6669 .did(did)
6770 .build();
6871
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-client-configuration/src/test/java/org/eclipse/edc/iam/identitytrust/sts/client/configuration/StsClientConfigurationExtensionTest.java +7 −2
@@ -32,6 +32,7 @@
3232 import static org.eclipse.edc.iam.identitytrust.sts.client.configuration.StsClientConfigurationExtension.CLIENT_ID;
3333 import static org.eclipse.edc.iam.identitytrust.sts.client.configuration.StsClientConfigurationExtension.CLIENT_NAME;
3434 import static org.eclipse.edc.iam.identitytrust.sts.client.configuration.StsClientConfigurationExtension.CLIENT_PRIVATE_KEY_ALIAS;
35+import static org.eclipse.edc.iam.identitytrust.sts.client.configuration.StsClientConfigurationExtension.CLIENT_PUBLIC_KEY_REFERENCE;
3536 import static org.eclipse.edc.iam.identitytrust.sts.client.configuration.StsClientConfigurationExtension.CLIENT_SECRET_ALIAS;
3637 import static org.eclipse.edc.iam.identitytrust.sts.client.configuration.StsClientConfigurationExtension.CONFIG_PREFIX;
3738 import static org.eclipse.edc.iam.identitytrust.sts.client.configuration.StsClientConfigurationExtension.ID;
@@ -65,6 +66,7 @@
6566 .privateKeyAlias("pAlias")
6667 .secretAlias("sAlias")
6768 .did("did:example:subject")
69+ .publicKeyReference("publicReference")
6870 .build();
6971 var clientAlias = "client";
7072 var config = ConfigFactory.fromMap(clientConfig(client, clientAlias));
@@ -74,7 +76,9 @@
7476 var capture = ArgumentCaptor.forClass(StsClient.class);
7577 verify(clientStore).create(capture.capture());
7678
77- assertThat(capture.getValue()).usingRecursiveComparison().isEqualTo(client);
79+ assertThat(capture.getValue()).usingRecursiveComparison()
80+ .ignoringFields("createdAt")
81+ .isEqualTo(client);
7882 }
7983
8084 private Map<String, String> clientConfig(StsClient client, String clientAlias) {
@@ -84,7 +88,8 @@
8488 clientAlias + "." + CLIENT_ID, client.getClientId(),
8589 clientAlias + "." + CLIENT_SECRET_ALIAS, client.getSecretAlias(),
8690 clientAlias + "." + CLIENT_DID, client.getDid(),
87- clientAlias + "." + CLIENT_PRIVATE_KEY_ALIAS, client.getPrivateKeyAlias()
91+ clientAlias + "." + CLIENT_PRIVATE_KEY_ALIAS, client.getPrivateKeyAlias(),
92+ clientAlias + "." + CLIENT_PUBLIC_KEY_REFERENCE, client.getPublicKeyReference()
8893 );
8994 }
9095
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-core/build.gradle.kts +2 −0
@@ -11,11 +11,13 @@
1111 implementation(project(":spi:common:keys-spi"))
1212 implementation(project(":extensions:common:iam:identity-trust:identity-trust-sts:identity-trust-sts-embedded"))
1313 implementation(project(":core:common:token-core"))
14+ implementation(project(":core:common:lib:store-lib"))
1415
1516 testImplementation(testFixtures(project(":spi:common:identity-trust-sts-spi")))
1617 testImplementation(project(":core:common:lib:boot-lib"))
1718 testImplementation(project(":core:common:lib:crypto-common-lib"))
1819 testImplementation(project(":core:common:lib:keys-lib"))
1920 testImplementation(project(":core:common:junit"))
21+ testImplementation(project(":core:common:lib:query-lib"))
2022 testImplementation(libs.nimbus.jwt)
2123 }
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-core/src/main/java/org/eclipse/edc/iam/identitytrust/sts/defaults/StsDefaultStoresExtension.java +6 −1
@@ -17,7 +17,9 @@
1717 import org.eclipse.edc.iam.identitytrust.sts.defaults.store.InMemoryStsClientStore;
1818 import org.eclipse.edc.iam.identitytrust.sts.spi.store.StsClientStore;
1919 import org.eclipse.edc.runtime.metamodel.annotation.Extension;
20+import org.eclipse.edc.runtime.metamodel.annotation.Inject;
2021 import org.eclipse.edc.runtime.metamodel.annotation.Provider;
22+import org.eclipse.edc.spi.query.CriterionOperatorRegistry;
2123 import org.eclipse.edc.spi.system.ServiceExtension;
2224
2325 @Extension(StsDefaultStoresExtension.NAME)
@@ -25,6 +27,9 @@
2527
2628 public static final String NAME = "Secure Token Service Default Stores";
2729
30+ @Inject
31+ private CriterionOperatorRegistry criterionOperatorRegistry;
32+
2833 @Override
2934 public String name() {
3035 return NAME;
@@ -32,6 +37,6 @@
3237
3338 @Provider(isDefault = true)
3439 public StsClientStore clientStore() {
35- return new InMemoryStsClientStore();
40+ return new InMemoryStsClientStore(criterionOperatorRegistry);
3641 }
3742 }
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-core/src/main/java/org/eclipse/edc/iam/identitytrust/sts/defaults/store/InMemoryStsClientStore.java +45 −4
@@ -16,11 +16,17 @@
1616
1717 import org.eclipse.edc.iam.identitytrust.sts.spi.model.StsClient;
1818 import org.eclipse.edc.iam.identitytrust.sts.spi.store.StsClientStore;
19+import org.eclipse.edc.spi.query.CriterionOperatorRegistry;
20+import org.eclipse.edc.spi.query.QueryResolver;
21+import org.eclipse.edc.spi.query.QuerySpec;
1922 import org.eclipse.edc.spi.result.StoreResult;
23+import org.eclipse.edc.store.ReflectionBasedQueryResolver;
24+import org.jetbrains.annotations.NotNull;
2025
2126 import java.util.Map;
2227 import java.util.Optional;
2328 import java.util.concurrent.ConcurrentHashMap;
29+import java.util.stream.Stream;
2430
2531 import static java.lang.String.format;
2632
@@ -29,19 +35,54 @@
2935 */
3036 public class InMemoryStsClientStore implements StsClientStore {
3137
38+ // we store it by clientId
3239 private final Map<String, StsClient> clients = new ConcurrentHashMap<>();
40+ private final QueryResolver<StsClient> queryResolver;
41+
42+
43+ public InMemoryStsClientStore(CriterionOperatorRegistry criterionOperatorRegistry) {
44+ queryResolver = new ReflectionBasedQueryResolver<>(StsClient.class, criterionOperatorRegistry);
45+ }
3346
3447 @Override
3548 public StoreResult<StsClient> create(StsClient client) {
3649 return Optional.ofNullable(clients.putIfAbsent(client.getClientId(), client))
37- .map(old -> StoreResult.<StsClient>alreadyExists(format("Client with id %s already exists", client.getClientId())))
50+ .map(old -> StoreResult.<StsClient>alreadyExists(format(CLIENT_EXISTS_TEMPLATE, client.getClientId())))
3851 .orElseGet(() -> StoreResult.success(client));
3952 }
4053
4154 @Override
42- public StoreResult<StsClient> findByClientId(String id) {
43- return Optional.ofNullable(clients.get(id))
55+ public StoreResult<Void> update(StsClient stsClient) {
56+ var prev = clients.replace(stsClient.getClientId(), stsClient);
57+ return Optional.ofNullable(prev)
58+ .map(a -> StoreResult.<Void>success())
59+ .orElse(StoreResult.notFound(format(CLIENT_NOT_FOUND_BY_ID_TEMPLATE, stsClient.getId())));
60+ }
61+
62+ @Override
63+ public @NotNull Stream<StsClient> findAll(QuerySpec spec) {
64+ return queryResolver.query(clients.values().stream(), spec);
65+ }
66+
67+ @Override
68+ public StoreResult<StsClient> findById(String id) {
69+ return clients.values().stream()
70+ .filter(client -> client.getId().equals(id))
71+ .findFirst()
72+ .map(StoreResult::success)
73+ .orElseGet(() -> StoreResult.notFound(format(CLIENT_NOT_FOUND_BY_ID_TEMPLATE, id)));
74+ }
75+
76+ @Override
77+ public StoreResult<StsClient> findByClientId(String clientId) {
78+ return Optional.ofNullable(clients.get(clientId))
4479 .map(StoreResult::success)
45- .orElseGet(() -> StoreResult.notFound(format("Client with id %s not found.", id)));
80+ .orElseGet(() -> StoreResult.notFound(format(CLIENT_NOT_FOUND_BY_CLIENT_ID_TEMPLATE, clientId)));
81+ }
82+
83+ @Override
84+ public StoreResult<StsClient> deleteById(String id) {
85+ return findById(id)
86+ .onSuccess(client -> clients.remove(client.getClientId()));
4687 }
4788 }
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-core/src/test/java/org/eclipse/edc/iam/identitytrust/sts/defaults/StsClientTokenIssuanceIntegrationTest.java +2 −1
@@ -29,6 +29,7 @@
2929 import org.eclipse.edc.keys.keyparsers.PemParser;
3030 import org.eclipse.edc.keys.spi.KeyParserRegistry;
3131 import org.eclipse.edc.keys.spi.PrivateKeyResolver;
32+import org.eclipse.edc.query.CriterionOperatorRegistryImpl;
3233 import org.eclipse.edc.security.token.jwt.DefaultJwsSignerProvider;
3334 import org.eclipse.edc.spi.security.Vault;
3435 import org.eclipse.edc.token.JwtGenerationService;
@@ -56,7 +57,7 @@
5657 @ComponentTest
5758 public class StsClientTokenIssuanceIntegrationTest {
5859
59- private final InMemoryStsClientStore clientStore = new InMemoryStsClientStore();
60+ private final InMemoryStsClientStore clientStore = new InMemoryStsClientStore(CriterionOperatorRegistryImpl.ofDefaults());
6061 private final Vault vault = new InMemoryVault(mock());
6162 private final KeyParserRegistry keyParserRegistry = new KeyParserRegistryImpl();
6263 private StsClientServiceImpl clientService;
modified extensions/common/iam/identity-trust/identity-trust-sts/identity-trust-sts-core/src/test/java/org/eclipse/edc/iam/identitytrust/sts/defaults/store/InMemoryStsClientStoreTest.java +2 −1
@@ -16,6 +16,7 @@
1616
1717 import org.eclipse.edc.iam.identitytrust.sts.spi.store.StsClientStore;
1818 import org.eclipse.edc.iam.identitytrust.sts.spi.store.fixtures.StsClientStoreTestBase;
19+import org.eclipse.edc.query.CriterionOperatorRegistryImpl;
1920 import org.junit.jupiter.api.BeforeEach;
2021
2122 public class InMemoryStsClientStoreTest extends StsClientStoreTestBase {
@@ -24,7 +25,7 @@
2425
2526 @BeforeEach
2627 void setUp() {
27- store = new InMemoryStsClientStore();
28+ store = new InMemoryStsClientStore(CriterionOperatorRegistryImpl.ofDefaults());
2829 }
2930
3031 @Override
added extensions/common/store/sql/sts-client-store-sql/build.gradle.kts +31 −0
@@ -0,0 +1,31 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+plugins {
16+ `java-library`
17+}
18+
19+dependencies {
20+ api(project(":spi:common:core-spi"))
21+ api(project(":spi:common:transaction-spi"))
22+
23+ implementation(project(":extensions:common:sql:sql-core"))
24+ implementation(project(":extensions:common:sql:sql-bootstrapper"))
25+ implementation(project(":spi:common:identity-trust-sts-spi"))
26+ implementation(project(":spi:common:transaction-datasource-spi"))
27+ testImplementation(project(":core:common:junit"))
28+ testImplementation(testFixtures(project(":extensions:common:sql:sql-core")))
29+ testImplementation(testFixtures(project(":spi:common:identity-trust-sts-spi")))
30+
31+}
No newline at the end of the file
added extensions/common/store/sql/sts-client-store-sql/src/main/java/org/eclipse/edc/iam/identitytrust/sts/store/SqlStsClientStore.java +188 −0
@@ -0,0 +1,188 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.iam.identitytrust.sts.store;
16+
17+import com.fasterxml.jackson.databind.ObjectMapper;
18+import org.eclipse.edc.iam.identitytrust.sts.spi.model.StsClient;
19+import org.eclipse.edc.iam.identitytrust.sts.spi.store.StsClientStore;
20+import org.eclipse.edc.iam.identitytrust.sts.store.schema.StsClientStatements;
21+import org.eclipse.edc.spi.persistence.EdcPersistenceException;
22+import org.eclipse.edc.spi.query.QuerySpec;
23+import org.eclipse.edc.spi.result.StoreResult;
24+import org.eclipse.edc.sql.QueryExecutor;
25+import org.eclipse.edc.sql.store.AbstractSqlStore;
26+import org.eclipse.edc.transaction.datasource.spi.DataSourceRegistry;
27+import org.eclipse.edc.transaction.spi.TransactionContext;
28+import org.jetbrains.annotations.NotNull;
29+
30+import java.sql.Connection;
31+import java.sql.ResultSet;
32+import java.sql.SQLException;
33+import java.util.Objects;
34+import java.util.stream.Stream;
35+
36+import static java.lang.String.format;
37+
38+public class SqlStsClientStore extends AbstractSqlStore implements StsClientStore {
39+
40+ private final StsClientStatements statements;
41+
42+ public SqlStsClientStore(DataSourceRegistry dataSourceRegistry, String dataSourceName, TransactionContext transactionContext,
43+ ObjectMapper objectMapper, StsClientStatements statements, QueryExecutor queryExecutor) {
44+ super(dataSourceRegistry, dataSourceName, transactionContext, objectMapper, queryExecutor);
45+ this.statements = statements;
46+ }
47+
48+ @Override
49+ public StoreResult<StsClient> create(StsClient client) {
50+ return transactionContext.execute(() -> {
51+ try (var connection = getConnection()) {
52+ if (findById(connection, client.getId()) != null) {
53+ var msg = format(CLIENT_EXISTS_TEMPLATE, client.getId());
54+ return StoreResult.alreadyExists(msg);
55+ }
56+
57+ queryExecutor.execute(connection, statements.getInsertTemplate(),
58+ client.getId(),
59+ client.getName(),
60+ client.getClientId(),
61+ client.getDid(),
62+ client.getSecretAlias(),
63+ client.getPrivateKeyAlias(),
64+ client.getPublicKeyReference(),
65+ client.getCreatedAt()
66+ );
67+
68+ return StoreResult.success();
69+ } catch (Exception e) {
70+ throw new EdcPersistenceException(e);
71+ }
72+ });
73+ }
74+
75+ @Override
76+ public StoreResult<Void> update(StsClient stsClient) {
77+ return transactionContext.execute(() -> {
78+ try (var connection = getConnection()) {
79+ if (findById(connection, stsClient.getId()) != null) {
80+ updateInternal(connection, stsClient);
81+ return StoreResult.success();
82+ } else {
83+ return StoreResult.notFound(format(CLIENT_NOT_FOUND_BY_ID_TEMPLATE, stsClient.getId()));
84+ }
85+ } catch (Exception e) {
86+ throw new EdcPersistenceException(e.getMessage(), e);
87+ }
88+ });
89+ }
90+
91+ @Override
92+ public @NotNull Stream<StsClient> findAll(QuerySpec spec) {
93+ return transactionContext.execute(() -> {
94+ Objects.requireNonNull(spec);
95+
96+ try {
97+ var queryStmt = statements.createQuery(spec);
98+ return queryExecutor.query(getConnection(), true, this::mapResultSet, queryStmt.getQueryAsString(), queryStmt.getParameters());
99+ } catch (SQLException exception) {
100+ throw new EdcPersistenceException(exception);
101+ }
102+ });
103+ }
104+
105+ @Override
106+ public StoreResult<StsClient> findById(String id) {
107+ return transactionContext.execute(() -> {
108+ try (var connection = getConnection()) {
109+ var client = findById(connection, id);
110+ if (client == null) {
111+ return StoreResult.notFound(format(CLIENT_NOT_FOUND_BY_ID_TEMPLATE, id));
112+ }
113+ return StoreResult.success(client);
114+ } catch (Exception e) {
115+ throw new EdcPersistenceException(e);
116+ }
117+ });
118+ }
119+
120+ @Override
121+ public StoreResult<StsClient> findByClientId(String clientId) {
122+ return transactionContext.execute(() -> {
123+ try (var connection = getConnection()) {
124+ var client = findByClientIdId(connection, clientId);
125+ if (client == null) {
126+ return StoreResult.notFound(format(CLIENT_NOT_FOUND_BY_CLIENT_ID_TEMPLATE, clientId));
127+ }
128+ return StoreResult.success(client);
129+ } catch (Exception e) {
130+ throw new EdcPersistenceException(e);
131+ }
132+ });
133+ }
134+
135+ @Override
136+ public StoreResult<StsClient> deleteById(String id) {
137+ return transactionContext.execute(() -> {
138+ try (var connection = getConnection()) {
139+ var entity = findById(connection, id);
140+ if (entity != null) {
141+ queryExecutor.execute(connection, statements.getDeleteByIdTemplate(), id);
142+ return StoreResult.success(entity);
143+ } else {
144+ return StoreResult.notFound(format(CLIENT_NOT_FOUND_BY_ID_TEMPLATE, id));
145+ }
146+
147+ } catch (Exception e) {
148+ throw new EdcPersistenceException(e.getMessage(), e);
149+ }
150+ });
151+ }
152+
153+ private void updateInternal(Connection connection, StsClient stsClient) {
154+ queryExecutor.execute(connection, statements.getUpdateTemplate(),
155+ stsClient.getId(),
156+ stsClient.getName(),
157+ stsClient.getClientId(),
158+ stsClient.getDid(),
159+ stsClient.getSecretAlias(),
160+ stsClient.getPrivateKeyAlias(),
161+ stsClient.getPublicKeyReference(),
162+ stsClient.getCreatedAt(),
163+ stsClient.getId());
164+ }
165+
166+ private StsClient findById(Connection connection, String id) {
167+ var sql = statements.getFindByTemplate();
168+ return queryExecutor.single(connection, false, this::mapResultSet, sql, id);
169+ }
170+
171+ private StsClient findByClientIdId(Connection connection, String id) {
172+ var sql = statements.getFindByClientIdTemplate();
173+ return queryExecutor.single(connection, false, this::mapResultSet, sql, id);
174+ }
175+
176+ private StsClient mapResultSet(ResultSet resultSet) throws Exception {
177+ return StsClient.Builder.newInstance()
178+ .id(resultSet.getString(statements.getIdColumn()))
179+ .did(resultSet.getString(statements.getDidColumn()))
180+ .name(resultSet.getString(statements.getNameColumn()))
181+ .clientId(resultSet.getString(statements.getClientIdColumn()))
182+ .secretAlias(resultSet.getString(statements.getSecretAliasColumn()))
183+ .privateKeyAlias(resultSet.getString(statements.getPrivateKeyAliasColumn()))
184+ .publicKeyReference(resultSet.getString(statements.getPublicKeyReferenceColumn()))
185+ .createdAt(resultSet.getLong(statements.getCreatedAtColumn()))
186+ .build();
187+ }
188+}
added extensions/common/store/sql/sts-client-store-sql/src/main/java/org/eclipse/edc/iam/identitytrust/sts/store/SqlStsClientStoreExtension.java +76 −0
@@ -0,0 +1,76 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.iam.identitytrust.sts.store;
16+
17+
18+import org.eclipse.edc.iam.identitytrust.sts.spi.store.StsClientStore;
19+import org.eclipse.edc.iam.identitytrust.sts.store.schema.StsClientStatements;
20+import org.eclipse.edc.iam.identitytrust.sts.store.schema.postgres.PostgresDialectStatements;
21+import org.eclipse.edc.runtime.metamodel.annotation.Extension;
22+import org.eclipse.edc.runtime.metamodel.annotation.Inject;
23+import org.eclipse.edc.runtime.metamodel.annotation.Provides;
24+import org.eclipse.edc.runtime.metamodel.annotation.Setting;
25+import org.eclipse.edc.spi.system.ServiceExtension;
26+import org.eclipse.edc.spi.system.ServiceExtensionContext;
27+import org.eclipse.edc.spi.types.TypeManager;
28+import org.eclipse.edc.sql.QueryExecutor;
29+import org.eclipse.edc.sql.bootstrapper.SqlSchemaBootstrapper;
30+import org.eclipse.edc.transaction.datasource.spi.DataSourceRegistry;
31+import org.eclipse.edc.transaction.spi.TransactionContext;
32+
33+import static org.eclipse.edc.transaction.datasource.spi.DataSourceRegistry.DEFAULT_DATASOURCE;
34+
35+@Provides({ StsClientStore.class })
36+@Extension(value = "SQL sts client store")
37+public class SqlStsClientStoreExtension implements ServiceExtension {
38+
39+ @Setting(value = "The datasource to be used", defaultValue = DEFAULT_DATASOURCE)
40+ public static final String DATASOURCE_NAME = "edc.sql.store.stsclient.datasource";
41+
42+ @Inject
43+ private DataSourceRegistry dataSourceRegistry;
44+
45+ @Inject
46+ private TransactionContext transactionContext;
47+
48+ @Inject(required = false)
49+ private StsClientStatements statements;
50+
51+ @Inject
52+ private QueryExecutor queryExecutor;
53+
54+ @Inject
55+ private TypeManager typeManager;
56+
57+ @Inject
58+ private SqlSchemaBootstrapper sqlSchemaBootstrapper;
59+
60+ @Override
61+ public void initialize(ServiceExtensionContext context) {
62+ var dataSourceName = context.getSetting(DATASOURCE_NAME, DEFAULT_DATASOURCE);
63+
64+ var sqlStore = new SqlStsClientStore(dataSourceRegistry, dataSourceName, transactionContext, typeManager.getMapper(),
65+ getStatementImpl(), queryExecutor);
66+
67+ context.registerService(StsClientStore.class, sqlStore);
68+
69+ sqlSchemaBootstrapper.addStatementFromResource(dataSourceName, "sts-client-schema.sql");
70+ }
71+
72+ private StsClientStatements getStatementImpl() {
73+ return statements == null ? new PostgresDialectStatements() : statements;
74+ }
75+
76+}
added extensions/common/store/sql/sts-client-store-sql/src/main/java/org/eclipse/edc/iam/identitytrust/sts/store/schema/BaseSqlDialectStatements.java +83 −0
@@ -0,0 +1,83 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.iam.identitytrust.sts.store.schema;
16+
17+import org.eclipse.edc.iam.identitytrust.sts.store.schema.postgres.StsClientMapping;
18+import org.eclipse.edc.spi.query.QuerySpec;
19+import org.eclipse.edc.sql.translation.SqlOperatorTranslator;
20+import org.eclipse.edc.sql.translation.SqlQueryStatement;
21+
22+import static java.lang.String.format;
23+
24+public class BaseSqlDialectStatements implements StsClientStatements {
25+
26+ protected final SqlOperatorTranslator operatorTranslator;
27+
28+ public BaseSqlDialectStatements(SqlOperatorTranslator operatorTranslator) {
29+ this.operatorTranslator = operatorTranslator;
30+ }
31+
32+ @Override
33+ public String getDeleteByIdTemplate() {
34+ return executeStatement().delete(getStsClientTable(), getIdColumn());
35+ }
36+
37+ @Override
38+ public String getFindByTemplate() {
39+ return format("SELECT * FROM %s WHERE %s = ?", getStsClientTable(), getIdColumn());
40+ }
41+
42+ @Override
43+ public String getFindByClientIdTemplate() {
44+ return format("SELECT * FROM %s WHERE %s = ?", getStsClientTable(), getClientIdColumn());
45+ }
46+
47+ @Override
48+ public String getInsertTemplate() {
49+ return executeStatement()
50+ .column(getIdColumn())
51+ .column(getNameColumn())
52+ .column(getClientIdColumn())
53+ .column(getDidColumn())
54+ .column(getSecretAliasColumn())
55+ .column(getPrivateKeyAliasColumn())
56+ .column(getPublicKeyReferenceColumn())
57+ .column(getCreatedAtColumn())
58+ .insertInto(getStsClientTable());
59+ }
60+
61+
62+ @Override
63+ public String getUpdateTemplate() {
64+ return executeStatement()
65+ .column(getIdColumn())
66+ .column(getNameColumn())
67+ .column(getClientIdColumn())
68+ .column(getDidColumn())
69+ .column(getSecretAliasColumn())
70+ .column(getPrivateKeyAliasColumn())
71+ .column(getPublicKeyReferenceColumn())
72+ .column(getCreatedAtColumn())
73+ .update(getStsClientTable(), getIdColumn());
74+
75+ }
76+
77+ @Override
78+ public SqlQueryStatement createQuery(QuerySpec querySpec) {
79+ var select = format("SELECT * FROM %s", getStsClientTable());
80+ return new SqlQueryStatement(select, querySpec, new StsClientMapping(this), operatorTranslator);
81+ }
82+
83+}
added extensions/common/store/sql/sts-client-store-sql/src/main/java/org/eclipse/edc/iam/identitytrust/sts/store/schema/StsClientStatements.java +75 −0
@@ -0,0 +1,75 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.iam.identitytrust.sts.store.schema;
16+
17+import org.eclipse.edc.iam.identitytrust.sts.spi.model.StsClient;
18+import org.eclipse.edc.spi.query.QuerySpec;
19+import org.eclipse.edc.sql.statement.SqlStatements;
20+import org.eclipse.edc.sql.translation.SqlQueryStatement;
21+
22+/**
23+ * Defines all statements that are needed for the {@link StsClient} store
24+ */
25+public interface StsClientStatements extends SqlStatements {
26+
27+ default String getIdColumn() {
28+ return "id";
29+ }
30+
31+ default String getDidColumn() {
32+ return "did";
33+ }
34+
35+ default String getClientIdColumn() {
36+ return "client_id";
37+ }
38+
39+ default String getStsClientTable() {
40+ return "edc_sts_client";
41+ }
42+
43+ default String getNameColumn() {
44+ return "name";
45+ }
46+
47+ default String getSecretAliasColumn() {
48+ return "secret_alias";
49+ }
50+
51+ default String getPrivateKeyAliasColumn() {
52+ return "private_key_alias";
53+ }
54+
55+ default String getPublicKeyReferenceColumn() {
56+ return "public_key_reference";
57+ }
58+
59+ default String getCreatedAtColumn() {
60+ return "created_at";
61+ }
62+
63+ String getDeleteByIdTemplate();
64+
65+ String getFindByTemplate();
66+
67+ String getFindByClientIdTemplate();
68+
69+ String getInsertTemplate();
70+
71+ String getUpdateTemplate();
72+
73+ SqlQueryStatement createQuery(QuerySpec querySpec);
74+
75+}
added extensions/common/store/sql/sts-client-store-sql/src/main/java/org/eclipse/edc/iam/identitytrust/sts/store/schema/postgres/PostgresDialectStatements.java +35 −0
@@ -0,0 +1,35 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.iam.identitytrust.sts.store.schema.postgres;
16+
17+import org.eclipse.edc.iam.identitytrust.sts.store.schema.BaseSqlDialectStatements;
18+import org.eclipse.edc.sql.dialect.PostgresDialect;
19+import org.eclipse.edc.sql.translation.PostgresqlOperatorTranslator;
20+
21+/**
22+ * Contains Postgres-specific SQL statements
23+ */
24+public class PostgresDialectStatements extends BaseSqlDialectStatements {
25+
26+ public PostgresDialectStatements() {
27+ super(new PostgresqlOperatorTranslator());
28+ }
29+
30+ @Override
31+ public String getFormatAsJsonOperator() {
32+ return PostgresDialect.getJsonCastOperator();
33+ }
34+
35+}
added extensions/common/store/sql/sts-client-store-sql/src/main/java/org/eclipse/edc/iam/identitytrust/sts/store/schema/postgres/StsClientMapping.java +36 −0
@@ -0,0 +1,36 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.iam.identitytrust.sts.store.schema.postgres;
16+
17+import org.eclipse.edc.iam.identitytrust.sts.spi.model.StsClient;
18+import org.eclipse.edc.iam.identitytrust.sts.store.schema.StsClientStatements;
19+import org.eclipse.edc.sql.translation.TranslationMapping;
20+
21+/**
22+ * Maps fields of a {@link StsClient} onto the
23+ * corresponding SQL schema (= column names)
24+ */
25+public class StsClientMapping extends TranslationMapping {
26+ public StsClientMapping(StsClientStatements statements) {
27+ add("id", statements.getIdColumn());
28+ add("name", statements.getNameColumn());
29+ add("clientId", statements.getClientIdColumn());
30+ add("did", statements.getDidColumn());
31+ add("secretAlias", statements.getSecretAliasColumn());
32+ add("privateKeyAlias", statements.getPrivateKeyAliasColumn());
33+ add("publicKeyReference", statements.getPublicKeyReferenceColumn());
34+ add("createdAt", statements.getCreatedAtColumn());
35+ }
36+}
added extensions/common/store/sql/sts-client-store-sql/src/main/resources/META-INF/services/org.eclipse.edc.spi.system.ServiceExtension +15 −0
@@ -0,0 +1,15 @@
1+#
2+# Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+#
4+# This program and the accompanying materials are made available under the
5+# terms of the Apache License, Version 2.0 which is available at
6+# https://www.apache.org/licenses/LICENSE-2.0
7+#
8+# SPDX-License-Identifier: Apache-2.0
9+#
10+# Contributors:
11+# Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+#
13+#
14+
15+org.eclipse.edc.iam.identitytrust.sts.store.SqlStsClientStoreExtension
No newline at the end of the file
added extensions/common/store/sql/sts-client-store-sql/src/main/resources/sts-client-schema.sql +18 −0
@@ -0,0 +1,18 @@
1+-- THIS SCHEMA HAS BEEN WRITTEN AND TESTED ONLY FOR POSTGRES
2+
3+-- table: edc_sts_client
4+
5+CREATE TABLE IF NOT EXISTS edc_sts_client
6+(
7+ id VARCHAR NOT NULL PRIMARY KEY,
8+ client_id VARCHAR NOT NULL,
9+ did VARCHAR NOT NULL,
10+ name VARCHAR NOT NULL,
11+ secret_alias VARCHAR NOT NULL,
12+ private_key_alias VARCHAR NOT NULL,
13+ public_key_reference VARCHAR NOT NULL,
14+ created_at BIGINT NOT NULL
15+);
16+
17+
18+CREATE UNIQUE INDEX IF NOT EXISTS sts_client_client_id_index ON edc_sts_client (client_id);
No newline at the end of the file
added extensions/common/store/sql/sts-client-store-sql/src/test/java/org/eclipse/edc/iam/identitytrust/sts/store/SqlStsClientStoreExtensionTest.java +56 −0
@@ -0,0 +1,56 @@
1+/*
2+ * Copyright (c) 2023 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.iam.identitytrust.sts.store;
16+
17+import org.eclipse.edc.iam.identitytrust.sts.spi.store.StsClientStore;
18+import org.eclipse.edc.json.JacksonTypeManager;
19+import org.eclipse.edc.junit.extensions.DependencyInjectionExtension;
20+import org.eclipse.edc.spi.system.ServiceExtensionContext;
21+import org.eclipse.edc.spi.system.configuration.Config;
22+import org.eclipse.edc.spi.types.TypeManager;
23+import org.junit.jupiter.api.BeforeEach;
24+import org.junit.jupiter.api.Test;
25+import org.junit.jupiter.api.extension.ExtendWith;
26+
27+import static org.assertj.core.api.Assertions.assertThat;
28+import static org.eclipse.edc.iam.identitytrust.sts.store.SqlStsClientStoreExtension.DATASOURCE_NAME;
29+import static org.mockito.ArgumentMatchers.any;
30+import static org.mockito.ArgumentMatchers.eq;
31+import static org.mockito.Mockito.mock;
32+import static org.mockito.Mockito.verify;
33+import static org.mockito.Mockito.when;
34+
35+@ExtendWith(DependencyInjectionExtension.class)
36+public class SqlStsClientStoreExtensionTest {
37+
38+ @BeforeEach
39+ void setUp(ServiceExtensionContext context) {
40+ context.registerService(TypeManager.class, new JacksonTypeManager());
41+ }
42+
43+ @Test
44+ void shouldInitializeTheStore(SqlStsClientStoreExtension extension, ServiceExtensionContext context) {
45+ var config = mock(Config.class);
46+ when(context.getConfig()).thenReturn(config);
47+ when(config.getString(any(), any())).thenReturn("test");
48+
49+ extension.initialize(context);
50+
51+ var service = context.getService(StsClientStore.class);
52+ assertThat(service).isInstanceOf(SqlStsClientStore.class);
53+
54+ verify(config).getString(eq(DATASOURCE_NAME), any());
55+ }
56+}
added extensions/common/store/sql/sts-client-store-sql/src/test/java/org/eclipse/edc/iam/identitytrust/sts/store/SqlStsClientStoreTest.java +61 −0
@@ -0,0 +1,61 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.iam.identitytrust.sts.store;
16+
17+import com.fasterxml.jackson.databind.ObjectMapper;
18+import org.eclipse.edc.iam.identitytrust.sts.spi.store.StsClientStore;
19+import org.eclipse.edc.iam.identitytrust.sts.spi.store.fixtures.StsClientStoreTestBase;
20+import org.eclipse.edc.iam.identitytrust.sts.store.schema.BaseSqlDialectStatements;
21+import org.eclipse.edc.iam.identitytrust.sts.store.schema.postgres.PostgresDialectStatements;
22+import org.eclipse.edc.json.JacksonTypeManager;
23+import org.eclipse.edc.junit.annotations.ComponentTest;
24+import org.eclipse.edc.junit.testfixtures.TestUtils;
25+import org.eclipse.edc.policy.model.PolicyRegistrationTypes;
26+import org.eclipse.edc.sql.QueryExecutor;
27+import org.eclipse.edc.sql.testfixtures.PostgresqlStoreSetupExtension;
28+import org.junit.jupiter.api.AfterEach;
29+import org.junit.jupiter.api.BeforeEach;
30+import org.junit.jupiter.api.extension.ExtendWith;
31+
32+@ComponentTest
33+@ExtendWith(PostgresqlStoreSetupExtension.class)
34+public class SqlStsClientStoreTest extends StsClientStoreTestBase {
35+
36+ private final BaseSqlDialectStatements sqlStatements = new PostgresDialectStatements();
37+
38+ private SqlStsClientStore stsClientStore;
39+
40+ @BeforeEach
41+ void setUp(PostgresqlStoreSetupExtension setupExtension, QueryExecutor queryExecutor) {
42+ var typeManager = new JacksonTypeManager();
43+ typeManager.registerTypes(PolicyRegistrationTypes.TYPES.toArray(Class<?>[]::new));
44+
45+ stsClientStore = new SqlStsClientStore(setupExtension.getDataSourceRegistry(), setupExtension.getDatasourceName(),
46+ setupExtension.getTransactionContext(), new ObjectMapper(), sqlStatements, queryExecutor);
47+
48+ var schema = TestUtils.getResourceFileContentAsString("sts-client-schema.sql");
49+ setupExtension.runQuery(schema);
50+ }
51+
52+ @AfterEach
53+ void tearDown(PostgresqlStoreSetupExtension setupExtension) {
54+ setupExtension.runQuery("DROP TABLE " + sqlStatements.getStsClientTable() + " CASCADE");
55+ }
56+
57+ @Override
58+ protected StsClientStore getStsClientStore() {
59+ return stsClientStore;
60+ }
61+}
modified settings.gradle.kts +1 −0
@@ -155,6 +155,7 @@
155155 include(":extensions:common:validator:validator-data-address-kafka")
156156 include(":extensions:common:vault:vault-hashicorp")
157157 include(":extensions:common:store:sql:edr-index-sql")
158+include(":extensions:common:store:sql:sts-client-store-sql")
158159
159160 include(":extensions:common:api:control-api-configuration")
160161 include(":extensions:common:api:management-api-configuration")
modified spi/common/identity-trust-sts-spi/src/main/java/org/eclipse/edc/iam/identitytrust/sts/spi/model/StsClient.java +30 −33
@@ -14,6 +14,7 @@
1414
1515 package org.eclipse.edc.iam.identitytrust.sts.spi.model;
1616
17+import org.eclipse.edc.spi.entity.Entity;
1718 import org.eclipse.edc.spi.security.Vault;
1819
1920 import java.util.Objects;
@@ -21,8 +22,7 @@
2122 /**
2223 * The {@link StsClient} contains information about STS clients.
2324 */
24-public class StsClient {
25- private String id;
25+public class StsClient extends Entity {
2626 private String clientId;
2727 private String did;
2828 private String name;
@@ -33,15 +33,6 @@
3333 private StsClient() {
3434 }
3535
36- /**
37- * Unique identifier of the {@link StsClient}
38- *
39- * @return The ID of the Client
40- */
41- public String getId() {
42- return id;
43- }
44-
4536 /**
4637 * The alias of the {@link StsClient} secret stored in the {@link Vault}
4738 *
@@ -101,63 +92,69 @@
10192 }
10293
10394
104- public static class Builder {
95+ public static class Builder extends Entity.Builder<StsClient, Builder> {
10596
106- private final StsClient client;
10797
108- private Builder(StsClient client) {
109- this.client = client;
98+ private Builder() {
99+ super(new StsClient());
110100 }
111101
112102 public static Builder newInstance() {
113- return new Builder(new StsClient());
103+ return new Builder();
114104 }
115105
116106
117107 public Builder id(String id) {
118- client.id = id;
108+ entity.id = id;
109+ return this;
110+ }
111+
112+ @Override
113+ public Builder self() {
119114 return this;
120115 }
121116
117+ @Override
118+ public StsClient build() {
119+ Objects.requireNonNull(entity.id, "Client id");
120+ Objects.requireNonNull(entity.clientId, "Client client_id");
121+ Objects.requireNonNull(entity.name, "Client name");
122+ Objects.requireNonNull(entity.did, "Client DID");
123+ Objects.requireNonNull(entity.secretAlias, "Client secret alias");
124+ Objects.requireNonNull(entity.privateKeyAlias, "Client private key alias");
125+ Objects.requireNonNull(entity.publicKeyReference, "Client public key reference");
126+ return super.build();
127+ }
128+
122129 public Builder clientId(String clientId) {
123- client.clientId = clientId;
130+ entity.clientId = clientId;
124131 return this;
125132 }
126133
127134 public Builder name(String name) {
128- client.name = name;
135+ entity.name = name;
129136 return this;
130137 }
131138
132139 public Builder did(String did) {
133- client.did = did;
140+ entity.did = did;
134141 return this;
135142 }
136143
137144 public Builder secretAlias(String secretAlias) {
138- client.secretAlias = secretAlias;
145+ entity.secretAlias = secretAlias;
139146 return this;
140147 }
141148
142149 public Builder privateKeyAlias(String privateKeyAlias) {
143- client.privateKeyAlias = privateKeyAlias;
150+ entity.privateKeyAlias = privateKeyAlias;
144151 return this;
145152 }
146153
147154 public Builder publicKeyReference(String publicKeyReference) {
148- client.publicKeyReference = publicKeyReference;
155+ entity.publicKeyReference = publicKeyReference;
149156 return this;
150157 }
151158
152- public StsClient build() {
153- Objects.requireNonNull(client.id, "Client id");
154- Objects.requireNonNull(client.clientId, "Client client_id");
155- Objects.requireNonNull(client.name, "Client name");
156- Objects.requireNonNull(client.did, "Client DID");
157- Objects.requireNonNull(client.secretAlias, "Client secret alias");
158- Objects.requireNonNull(client.privateKeyAlias, "Client private key alias");
159- return client;
160- }
161-
162159 }
163160 }
modified spi/common/identity-trust-sts-spi/src/main/java/org/eclipse/edc/iam/identitytrust/sts/spi/store/StsClientStore.java +44 −2
@@ -17,7 +17,11 @@
1717
1818 import org.eclipse.edc.iam.identitytrust.sts.spi.model.StsClient;
1919 import org.eclipse.edc.runtime.metamodel.annotation.ExtensionPoint;
20+import org.eclipse.edc.spi.query.QuerySpec;
2021 import org.eclipse.edc.spi.result.StoreResult;
22+import org.jetbrains.annotations.NotNull;
23+
24+import java.util.stream.Stream;
2125
2226 /**
2327 * Persists and retrieves {@link StsClient}s.
@@ -25,13 +29,44 @@
2529 @ExtensionPoint
2630 public interface StsClientStore {
2731
32+ String CLIENT_EXISTS_TEMPLATE = "Client with ID %s already exists";
33+ String CLIENT_NOT_FOUND_BY_CLIENT_ID_TEMPLATE = "Client with clientID %s not found";
34+ String CLIENT_NOT_FOUND_BY_ID_TEMPLATE = "Client with id %s not found";
35+
2836 /**
2937 * Stores the {@link StsClient}
3038 *
31- * @param client The client
39+ * @param stsClient The client
3240 * @return successful when the client is stored, failure otherwise
3341 */
34- StoreResult<StsClient> create(StsClient client);
42+ StoreResult<StsClient> create(StsClient stsClient);
43+
44+
45+ /**
46+ * Update the {@link StsClient} if am sts client with the same ID exists.
47+ *
48+ * @param stsClient {@link StsClient} to update.
49+ * @return {@link StoreResult#success()} if the sts client was updates, {@link StoreResult#notFound(String)} if the sts client identified by the ID was not found.
50+ */
51+ StoreResult<Void> update(StsClient stsClient);
52+
53+ /**
54+ * Returns all the sts clients in the store that are covered by a given {@link QuerySpec}.
55+ * <p>
56+ * Note: supplying a sort field that does not exist on the {@link StsClient} may cause some implementations
57+ * to return an empty Stream, others will return an unsorted Stream, depending on the backing storage
58+ * implementation.
59+ */
60+ @NotNull
61+ Stream<StsClient> findAll(QuerySpec spec);
62+
63+ /**
64+ * Returns an {@link StsClient} by its id
65+ *
66+ * @param id id of the client
67+ * @return the client successful if found, failure otherwise
68+ */
69+ StoreResult<StsClient> findById(String id);
3570
3671 /**
3772 * Returns an {@link StsClient} by its clientId
@@ -41,4 +76,11 @@
4176 */
4277 StoreResult<StsClient> findByClientId(String clientId);
4378
79+ /**
80+ * Deletes the sts client with the given id.
81+ *
82+ * @param id A String that represents the {@link StsClient} ID, in most cases this will be a UUID.
83+ * @return {@link StoreResult#success()}} if the sts client was deleted, {@link StoreResult#notFound(String)} if the sts client was not found in the store.
84+ */
85+ StoreResult<StsClient> deleteById(String id);
4486 }
modified spi/common/identity-trust-sts-spi/src/testFixtures/java/org/eclipse/edc/iam/identitytrust/sts/spi/store/fixtures/StsClientStoreTestBase.java +337 −4
@@ -14,16 +14,38 @@
1414
1515 package org.eclipse.edc.iam.identitytrust.sts.spi.store.fixtures;
1616
17+import org.eclipse.edc.iam.identitytrust.sts.spi.model.StsClient;
1718 import org.eclipse.edc.iam.identitytrust.sts.spi.store.StsClientStore;
19+import org.eclipse.edc.spi.query.Criterion;
20+import org.eclipse.edc.spi.query.QuerySpec;
21+import org.eclipse.edc.spi.query.SortOrder;
1822 import org.eclipse.edc.spi.result.StoreFailure;
1923 import org.junit.jupiter.api.DisplayName;
2024 import org.junit.jupiter.api.Nested;
2125 import org.junit.jupiter.api.Test;
26+import org.junit.jupiter.api.extension.ExtensionContext;
27+import org.junit.jupiter.params.ParameterizedTest;
28+import org.junit.jupiter.params.provider.Arguments;
29+import org.junit.jupiter.params.provider.ArgumentsProvider;
30+import org.junit.jupiter.params.provider.ArgumentsSource;
31+import org.junit.jupiter.params.provider.ValueSource;
2232
33+import java.util.Comparator;
34+import java.util.List;
2335 import java.util.UUID;
36+import java.util.function.Function;
37+import java.util.stream.Collectors;
38+import java.util.stream.IntStream;
39+import java.util.stream.Stream;
2440
2541 import static org.assertj.core.api.Assertions.assertThat;
42+import static org.assertj.core.api.Assertions.assertThatThrownBy;
43+import static org.eclipse.edc.iam.identitytrust.sts.spi.store.fixtures.TestFunctions.createClient;
44+import static org.eclipse.edc.iam.identitytrust.sts.spi.store.fixtures.TestFunctions.createClientBuilder;
2645 import static org.eclipse.edc.junit.assertions.AbstractResultAssert.assertThat;
46+import static org.eclipse.edc.spi.query.Criterion.criterion;
47+import static org.eclipse.edc.spi.result.StoreFailure.Reason.ALREADY_EXISTS;
48+import static org.eclipse.edc.spi.result.StoreFailure.Reason.NOT_FOUND;
2749
2850 /**
2951 * Base compliance tests for implementors of {@link StsClientStore}.
@@ -36,35 +58,275 @@
3658 return UUID.randomUUID().toString();
3759 }
3860
61+ private List<StsClient> createClients(int size) {
62+ return IntStream.range(0, size).mapToObj(i -> createClient("id" + i))
63+ .toList();
64+ }
65+
66+ private void delay(long ms) {
67+ try {
68+ Thread.sleep(ms);
69+ } catch (InterruptedException e) {
70+ throw new RuntimeException(e);
71+ }
72+ }
73+
74+ private void saveClients(List<StsClient> clients) {
75+ clients.forEach(getStsClientStore()::create);
76+ }
77+
3978 @Nested
4079 class Create {
4180
4281 @Test
4382 @DisplayName("Save a single client that not exists")
4483 void create() {
45- var client = TestFunctions.createClient(getRandomId());
84+ var client = createClient(getRandomId());
4685 assertThat(getStsClientStore().create(client)).isSucceeded();
4786
4887 var clientFromDb = getStsClientStore().findByClientId(client.getId()).getContent();
4988 assertThat(client).usingRecursiveComparison().isEqualTo(clientFromDb);
5089 }
90+
91+
92+ @Test
93+ @DisplayName("Saves multiple client that not exists")
94+ void create_MultipleClients() {
95+
96+ var clients = IntStream.range(0, 10)
97+ .mapToObj(i -> createClient("id" + i))
98+ .peek(getStsClientStore()::create)
99+ .toList();
100+
101+ var result = getStsClientStore().findAll(QuerySpec.max());
102+
103+ assertThat(result).hasSize(clients.size())
104+ .usingRecursiveFieldByFieldElementComparator()
105+ .containsAll(clients);
106+ }
107+
108+ @Test
109+ @DisplayName("Shouldn't save a single client that already exists")
110+ void alreadyExist_shouldNotUpdate() {
111+ var client = createClient("id");
112+ getStsClientStore().create(client);
113+ var saveResult = getStsClientStore().create(createClient("id"));
114+
115+ assertThat(saveResult.failed()).isTrue();
116+ assertThat(saveResult.reason()).isEqualTo(ALREADY_EXISTS);
117+
118+ var result = getStsClientStore().findAll(QuerySpec.max());
119+
120+ assertThat(result).hasSize(1)
121+ .usingRecursiveFieldByFieldElementComparator()
122+ .containsExactly(client);
123+ }
124+ }
125+
126+ @Nested
127+ class FindAll {
128+
129+ @ParameterizedTest
130+ @ValueSource(ints = { 49, 50, 51, 100 })
131+ void verifyQueryDefaults(int size) {
132+ var all = IntStream.range(0, size).mapToObj(i -> createClient("id" + i))
133+ .peek(getStsClientStore()::create)
134+ .collect(Collectors.toList());
135+
136+ assertThat(getStsClientStore().findAll(QuerySpec.max())).hasSize(size)
137+ .usingRecursiveFieldByFieldElementComparator()
138+ .isSubsetOf(all);
139+ }
140+
141+ @Test
142+ @DisplayName("Find all clients with limit and offset")
143+ void withSpec() {
144+ var limit = 20;
145+
146+ IntStream.range(0, 50).mapToObj(i -> createClient("id" + i))
147+ .forEach(getStsClientStore()::create);
148+
149+ var spec = QuerySpec.Builder.newInstance()
150+ .limit(limit)
151+ .offset(20)
152+ .build();
153+
154+ var resultClients = getStsClientStore().findAll(spec);
155+
156+ assertThat(resultClients).isNotNull().hasSize(limit);
157+ }
158+
159+ @ParameterizedTest
160+ @ArgumentsSource(FilterArgumentProvider.class)
161+ void query_withQuerySpec(String field, Function<StsClient, String> mapping) {
162+ var clients = createClients(10);
163+ saveClients(clients);
164+
165+
166+ var client = createClientBuilder("id")
167+ .name("client_name")
168+ .clientId("client_id")
169+ .did("did:web:client")
170+ .secretAlias("secret_alias")
171+ .privateKeyAlias("private_key_alias")
172+ .publicKeyReference("public_key_reference")
173+ .build();
174+
175+ getStsClientStore().create(client);
176+
177+ var filter = Criterion.Builder.newInstance()
178+ .operandLeft(field)
179+ .operator("=")
180+ .operandRight(mapping.apply(client))
181+ .build();
182+
183+ var results = getStsClientStore().findAll(QuerySpec.Builder.newInstance().filter(filter).build());
184+
185+ assertThat(results).usingRecursiveFieldByFieldElementComparator()
186+ .containsOnly(client);
187+
188+ }
189+
190+ @Test
191+ @DisplayName("Verify empty result when query contains a nonexistent value")
192+ void queryByNonexistentValue() {
193+
194+ var clients = createClients(20);
195+ saveClients(clients);
196+
197+ var spec = QuerySpec.Builder.newInstance()
198+ .filter(List.of(new Criterion("client_id", "=", "somevalue")))
199+ .build();
200+
201+ assertThat(getStsClientStore().findAll(spec)).isEmpty();
202+ }
203+
204+ @Test
205+ void invalidOperator() {
206+
207+ var stsClients = createClients(20);
208+ saveClients(stsClients);
209+
210+ var spec = QuerySpec.Builder.newInstance()
211+ .filter(List.of(new Criterion("did", "sqrt", "foobar"))) //sqrt is invalid
212+ .build();
213+
214+ assertThatThrownBy(() -> getStsClientStore().findAll(spec)).isInstanceOf(IllegalArgumentException.class);
215+ }
216+
217+
218+ @Test
219+ void verifyPaging() {
220+ var stsClients = createClients(10);
221+ saveClients(stsClients);
222+
223+ // page size fits
224+ assertThat(getStsClientStore().findAll(QuerySpec.Builder.newInstance().offset(4).limit(2).build())).hasSize(2);
225+
226+ // page size larger than collection
227+ assertThat(getStsClientStore().findAll(QuerySpec.Builder.newInstance().offset(5).limit(100).build())).hasSize(5);
228+ }
229+
230+ @Test
231+ void shouldReturnEmpty_whenQueryByInvalidKey() {
232+ var stsClients = createClients(5);
233+ saveClients(stsClients);
234+
235+ var spec = QuerySpec.Builder.newInstance()
236+ .filter(criterion("not-exist", "=", "some-value"))
237+ .build();
238+
239+ assertThat(getStsClientStore().findAll(spec)).isEmpty();
240+ }
241+
242+ @Test
243+ void verifySorting() {
244+
245+ var stsClients = IntStream.range(0, 10).mapToObj(idx -> {
246+ delay(10);
247+ return createClient("id" + idx);
248+ }).toList();
249+
250+ saveClients(stsClients);
251+
252+
253+ assertThat(getStsClientStore().findAll(QuerySpec.Builder.newInstance().sortField("createdAt").sortOrder(SortOrder.ASC).build()))
254+ .hasSize(10)
255+ .isSortedAccordingTo(Comparator.comparing(StsClient::getCreatedAt));
256+
257+ assertThat(getStsClientStore().findAll(QuerySpec.Builder.newInstance().sortField("createdAt").sortOrder(SortOrder.DESC).build()))
258+ .hasSize(10)
259+ .isSortedAccordingTo((c1, c2) -> Long.compare(c2.getCreatedAt(), c1.getCreatedAt()));
260+ }
261+
262+ @Test
263+ void verifySorting_invalidProperty() {
264+ var stsClients = createClients(10);
265+ saveClients(stsClients);
266+
267+ var query = QuerySpec.Builder.newInstance().sortField("not-exist").sortOrder(SortOrder.DESC).build();
268+
269+ // must actually collect, otherwise the stream is not materialized
270+ assertThatThrownBy(() -> getStsClientStore().findAll(query).toList()).isInstanceOf(IllegalArgumentException.class);
271+ }
272+
273+ static class FilterArgumentProvider implements ArgumentsProvider {
274+ @Override
275+ public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
276+
277+ return Stream.of(
278+ Arguments.of("id", (Function<StsClient, String>) StsClient::getId),
279+ Arguments.of("clientId", (Function<StsClient, String>) StsClient::getClientId),
280+ Arguments.of("name", (Function<StsClient, String>) StsClient::getName),
281+ Arguments.of("did", (Function<StsClient, String>) StsClient::getDid),
282+ Arguments.of("secretAlias", (Function<StsClient, String>) StsClient::getSecretAlias),
283+ Arguments.of("privateKeyAlias", (Function<StsClient, String>) StsClient::getPrivateKeyAlias),
284+ Arguments.of("publicKeyReference", (Function<StsClient, String>) StsClient::getPublicKeyReference)
285+ );
286+ }
287+ }
51288 }
52289
53290 @Nested
54291 class FindById {
292+
55293 @Test
56294 @DisplayName("Find client by ID that exists")
57295 void whenPresent() {
58- var client = TestFunctions.createClient(getRandomId());
296+ var client = createClient(getRandomId(), "alias", getRandomId());
59297 getStsClientStore().create(client);
60298
61- var policyFromDb = getStsClientStore().findByClientId(client.getId()).getContent();
299+ var clientFromDb = getStsClientStore().findById(client.getId()).getContent();
62300
63- assertThat(client).usingRecursiveComparison().isEqualTo(policyFromDb);
301+ assertThat(client).usingRecursiveComparison().isEqualTo(clientFromDb);
64302 }
65303
66304 @Test
67305 @DisplayName("Find client by ID when not exists")
306+ void whenNonexistent() {
307+ assertThat(getStsClientStore().findById("nonexistent"))
308+ .isFailed()
309+ .extracting(StoreFailure::getReason)
310+ .isEqualTo(StoreFailure.Reason.NOT_FOUND);
311+ }
312+ }
313+
314+ @Nested
315+ class FindByClientId {
316+
317+ @Test
318+ @DisplayName("Find client by Client ID that exists")
319+ void whenPresent() {
320+ var client = createClient(getRandomId(), "alias", getRandomId());
321+ getStsClientStore().create(client);
322+
323+ var clientFromDb = getStsClientStore().findByClientId(client.getClientId()).getContent();
324+
325+ assertThat(client).usingRecursiveComparison().isEqualTo(clientFromDb);
326+ }
327+
328+ @Test
329+ @DisplayName("Find client by Client ID when not exists")
68330 void whenNonexistent() {
69331 assertThat(getStsClientStore().findByClientId("nonexistent"))
70332 .isFailed()
@@ -72,4 +334,75 @@
72334 .isEqualTo(StoreFailure.Reason.NOT_FOUND);
73335 }
74336 }
337+
338+ @Nested
339+ class Update {
340+ @Test
341+ @DisplayName("Update a non-existing Client")
342+ void doesNotExist_shouldNotCreate() {
343+ var client = createClient(getRandomId(), "alias", getRandomId());
344+
345+ var result = getStsClientStore().update(client);
346+
347+ assertThat(result.failed()).isTrue();
348+ assertThat(result.reason()).isEqualTo(NOT_FOUND);
349+
350+ var existing = getStsClientStore().findAll(QuerySpec.max());
351+
352+ assertThat(existing).hasSize(0);
353+ }
354+
355+ @Test
356+ @DisplayName("Update an existing client")
357+ void exists() {
358+ var client1 = createClient("id", "alias", getRandomId());
359+ var client2 = createClientBuilder("id")
360+ .clientId(client1.getClientId())
361+ .name("nameChanged")
362+ .privateKeyAlias("privateAliasChanged")
363+ .publicKeyReference("publicRefChanged")
364+ .did("didChanged")
365+ .secretAlias("aliasChanged")
366+ .build();
367+
368+
369+ getStsClientStore().create(client1);
370+ getStsClientStore().update(client2);
371+
372+ var clients = getStsClientStore().findAll(QuerySpec.none()).collect(Collectors.toList());
373+
374+ assertThat(clients).isNotNull().hasSize(1).first().satisfies(client -> {
375+ assertThat(client.getId()).isEqualTo(client2.getId());
376+ assertThat(client.getName()).isEqualTo(client2.getName());
377+ assertThat(client.getDid()).isEqualTo(client2.getDid());
378+ assertThat(client.getSecretAlias()).isEqualTo(client2.getSecretAlias());
379+ assertThat(client.getPrivateKeyAlias()).isEqualTo(client2.getPrivateKeyAlias());
380+ assertThat(client.getPublicKeyReference()).isEqualTo(client2.getPublicKeyReference());
381+ assertThat(client.getClientId()).isEqualTo(client2.getClientId());
382+ });
383+ }
384+ }
385+
386+ @Nested
387+ class Delete {
388+ @Test
389+ void shouldDelete() {
390+ var client = createClient(getRandomId(), "alias", getRandomId());
391+ getStsClientStore().create(client);
392+ assertThat(getStsClientStore().findAll(QuerySpec.max())).hasSize(1);
393+
394+ var deleted = getStsClientStore().deleteById(client.getId());
395+
396+ assertThat(deleted.succeeded()).isTrue();
397+ assertThat(deleted.getContent()).isNotNull().usingRecursiveComparison().isEqualTo(client);
398+ assertThat(getStsClientStore().findAll(QuerySpec.max())).isEmpty();
399+ }
400+
401+ @Test
402+ void shouldNotDelete_whenEntityDoesNotExist() {
403+ var deleted = getStsClientStore().deleteById("test-id1");
404+
405+ assertThat(deleted).isFailed().extracting(StoreFailure::getReason).isEqualTo(NOT_FOUND);
406+ }
407+ }
75408 }
modified spi/common/identity-trust-sts-spi/src/testFixtures/java/org/eclipse/edc/iam/identitytrust/sts/spi/store/fixtures/TestFunctions.java +4 −0
@@ -25,6 +25,10 @@
2525 return createClient(id, secretAlias, id, secretAlias, "did:example:subject");
2626 }
2727
28+ public static StsClient createClient(String id, String secretAlias, String clientId) {
29+ return createClient(id, secretAlias, clientId, secretAlias, "did:example:subject");
30+ }
31+
2832 public static StsClient createClient(String id, String secretAlias, String clientId, String publicKeyReference, String did) {
2933 return createClientBuilder(id)
3034 .clientId(clientId)
modified system-tests/sts-api/sts-api-test-runner/build.gradle.kts +2 −0
@@ -29,6 +29,8 @@
2929
3030 testCompileOnly(project(":system-tests:sts-api:sts-api-test-runtime"))
3131 testImplementation(testFixtures(project(":spi:common:identity-trust-sts-spi")))
32+ testImplementation(testFixtures(project(":extensions:common:sql:sql-core")))
33+ testImplementation(project(":extensions:common:transaction:transaction-local"))
3234 testImplementation(libs.nimbus.jwt)
3335 testImplementation(libs.bouncyCastle.bcpkixJdk18on)
3436
modified system-tests/sts-api/sts-api-test-runner/src/test/java/org/eclipse/edc/test/e2e/sts/api/StsApiEndToEndTest.java +203 −155
@@ -17,9 +17,13 @@
1717 import io.restassured.response.ValidatableResponse;
1818 import io.restassured.specification.RequestSpecification;
1919 import org.eclipse.edc.junit.annotations.EndToEndTest;
20+import org.eclipse.edc.junit.annotations.PostgresqlIntegrationTest;
2021 import org.eclipse.edc.junit.extensions.EmbeddedRuntime;
2122 import org.eclipse.edc.junit.extensions.RuntimePerClassExtension;
23+import org.eclipse.edc.sql.testfixtures.PostgresqlEndToEndInstance;
24+import org.junit.jupiter.api.Nested;
2225 import org.junit.jupiter.api.Test;
26+import org.junit.jupiter.api.extension.ExtensionContext;
2327 import org.junit.jupiter.api.extension.RegisterExtension;
2428
2529 import java.io.IOException;
@@ -39,174 +43,218 @@
3943 import static org.assertj.core.api.Assertions.assertThat;
4044 import static org.eclipse.edc.iam.identitytrust.spi.SelfIssuedTokenConstants.PRESENTATION_TOKEN_CLAIM;
4145 import static org.eclipse.edc.jwt.spi.JwtRegisteredClaimNames.CLIENT_ID;
46+import static org.eclipse.edc.sql.testfixtures.PostgresqlEndToEndInstance.createDatabase;
4247 import static org.eclipse.edc.util.io.Ports.getFreePort;
4348 import static org.hamcrest.Matchers.is;
4449 import static org.hamcrest.Matchers.notNullValue;
4550
46-@EndToEndTest
47-public class StsApiEndToEndTest extends StsEndToEndTestBase {
51+public class StsApiEndToEndTest {
4852
4953 public static final int PORT = getFreePort();
5054 public static final String BASE_STS = "http://localhost:" + PORT + "/sts";
5155 private static final String GRANT_TYPE = "client_credentials";
5256
53-
54- @RegisterExtension
55- static RuntimePerClassExtension sts = new RuntimePerClassExtension(new EmbeddedRuntime(
56- "sts",
57- new HashMap<>() {
58- {
59- put("web.http.path", "/");
60- put("web.http.port", String.valueOf(getFreePort()));
61- put("web.http.sts.path", "/sts");
62- put("web.http.sts.port", String.valueOf(PORT));
63- }
64- },
65- ":system-tests:sts-api:sts-api-test-runtime"
66- ));
67-
68- @Test
69- void requestToken() throws ParseException {
70- var audience = "audience";
71- var clientSecret = "client_secret";
72- var expiresIn = 300;
73-
74- var client = initClient(clientSecret);
75-
76- var params = Map.of(
77- "client_id", client.getClientId(),
78- "audience", audience,
79- "client_secret", clientSecret);
80-
81- var token = tokenRequest(params)
82- .statusCode(200)
83- .contentType(JSON)
84- .body("access_token", notNullValue())
85- .body("expires_in", is(expiresIn))
86- .extract()
87- .body()
88- .jsonPath().getString("access_token");
89-
90- assertThat(parseClaims(token))
91- .containsEntry(ISSUER, client.getDid())
92- .containsEntry(SUBJECT, client.getDid())
93- .containsEntry(AUDIENCE, List.of(audience))
94- .doesNotContainKey(CLIENT_ID)
95- .containsKeys(JWT_ID, EXPIRATION_TIME, ISSUED_AT);
96- }
97-
98-
99- @Test
100- void requestToken_withBearerScope() throws ParseException {
101- var clientSecret = "client_secret";
102- var audience = "audience";
103- var bearerAccessScope = "org.test.Member:read org.test.GoldMember:read";
104- var expiresIn = 300;
105-
106- var client = initClient(clientSecret);
107-
108-
109- var params = Map.of(
110- "client_id", client.getClientId(),
111- "audience", audience,
112- "bearer_access_scope", bearerAccessScope,
113- "client_secret", clientSecret);
114-
115- var token = tokenRequest(params)
116- .statusCode(200)
117- .contentType(JSON)
118- .body("access_token", notNullValue())
119- .body("expires_in", is(expiresIn))
120- .extract()
121- .body()
122- .jsonPath().getString("access_token");
123-
124-
125- assertThat(parseClaims(token))
126- .containsEntry(ISSUER, client.getDid())
127- .containsEntry(SUBJECT, client.getDid())
128- .containsEntry(AUDIENCE, List.of(audience))
129- .doesNotContainKey(CLIENT_ID)
130- .containsKeys(JWT_ID, EXPIRATION_TIME, ISSUED_AT)
131- .hasEntrySatisfying(PRESENTATION_TOKEN_CLAIM, (accessToken) -> {
132- assertThat(parseClaims((String) accessToken))
133- .containsEntry(ISSUER, client.getDid())
134- .containsEntry(SUBJECT, audience)
135- .containsEntry(AUDIENCE, List.of(client.getDid()))
136- .containsKeys(JWT_ID, EXPIRATION_TIME, ISSUED_AT);
137- });
138- }
139-
140- @Test
141- void requestToken_withAttachedAccessScope() throws IOException, ParseException {
142- var clientSecret = "client_secret";
143- var audience = "audience";
144- var token = "test_token";
145- var expiresIn = 300;
146- var client = initClient(clientSecret);
147-
148-
149- var params = Map.of(
150- "client_id", client.getClientId(),
151- "audience", audience,
152- "token", token,
153- "client_secret", clientSecret);
154-
155- var accessToken = tokenRequest(params)
156- .statusCode(200)
157- .contentType(JSON)
158- .body("access_token", notNullValue())
159- .body("expires_in", is(expiresIn))
160- .extract()
161- .body()
162- .jsonPath().getString("access_token");
163-
164-
165- assertThat(parseClaims(accessToken))
166- .containsEntry(ISSUER, client.getDid())
167- .containsEntry(SUBJECT, client.getDid())
168- .containsEntry(AUDIENCE, List.of(audience))
169- .doesNotContainKey(CLIENT_ID)
170- .containsEntry(PRESENTATION_TOKEN_CLAIM, token)
171- .containsKeys(JWT_ID, EXPIRATION_TIME, ISSUED_AT);
172- }
173-
174- @Test
175- void requestToken_shouldReturnError_whenClientNotFound() {
176-
177- var clientId = "client_id";
178- var clientSecret = "client_secret";
179- var audience = "audience";
180-
181- var params = Map.of(
182- "client_id", clientId,
183- "audience", audience,
184- "client_secret", clientSecret);
185-
186- tokenRequest(params)
187- .statusCode(401)
188- .contentType(JSON);
189- }
190-
191- protected ValidatableResponse tokenRequest(Map<String, String> params) {
192-
193- var req = baseRequest()
194- .contentType("application/x-www-form-urlencoded")
195- .formParam("grant_type", GRANT_TYPE);
196- params.forEach(req::formParam);
197- return req.post("/token").then();
57+ abstract static class Tests extends StsEndToEndTestBase {
58+
59+ @Test
60+ void requestToken() throws ParseException {
61+ var audience = "audience";
62+ var clientSecret = "client_secret";
63+ var expiresIn = 300;
64+
65+ var client = initClient(clientSecret);
66+
67+ var params = Map.of(
68+ "client_id", client.getClientId(),
69+ "audience", audience,
70+ "client_secret", clientSecret);
71+
72+ var token = tokenRequest(params)
73+ .statusCode(200)
74+ .contentType(JSON)
75+ .body("access_token", notNullValue())
76+ .body("expires_in", is(expiresIn))
77+ .extract()
78+ .body()
79+ .jsonPath().getString("access_token");
80+
81+ assertThat(parseClaims(token))
82+ .containsEntry(ISSUER, client.getDid())
83+ .containsEntry(SUBJECT, client.getDid())
84+ .containsEntry(AUDIENCE, List.of(audience))
85+ .doesNotContainKey(CLIENT_ID)
86+ .containsKeys(JWT_ID, EXPIRATION_TIME, ISSUED_AT);
87+ }
88+
89+ @Test
90+ void requestToken_withBearerScope() throws ParseException {
91+ var clientSecret = "client_secret";
92+ var audience = "audience";
93+ var bearerAccessScope = "org.test.Member:read org.test.GoldMember:read";
94+ var expiresIn = 300;
95+
96+ var client = initClient(clientSecret);
97+
98+
99+ var params = Map.of(
100+ "client_id", client.getClientId(),
101+ "audience", audience,
102+ "bearer_access_scope", bearerAccessScope,
103+ "client_secret", clientSecret);
104+
105+ var token = tokenRequest(params)
106+ .statusCode(200)
107+ .contentType(JSON)
108+ .body("access_token", notNullValue())
109+ .body("expires_in", is(expiresIn))
110+ .extract()
111+ .body()
112+ .jsonPath().getString("access_token");
113+
114+
115+ assertThat(parseClaims(token))
116+ .containsEntry(ISSUER, client.getDid())
117+ .containsEntry(SUBJECT, client.getDid())
118+ .containsEntry(AUDIENCE, List.of(audience))
119+ .doesNotContainKey(CLIENT_ID)
120+ .containsKeys(JWT_ID, EXPIRATION_TIME, ISSUED_AT)
121+ .hasEntrySatisfying(PRESENTATION_TOKEN_CLAIM, (accessToken) -> {
122+ assertThat(parseClaims((String) accessToken))
123+ .containsEntry(ISSUER, client.getDid())
124+ .containsEntry(SUBJECT, audience)
125+ .containsEntry(AUDIENCE, List.of(client.getDid()))
126+ .containsKeys(JWT_ID, EXPIRATION_TIME, ISSUED_AT);
127+ });
128+ }
129+
130+ @Test
131+ void requestToken_withAttachedAccessScope() throws IOException, ParseException {
132+ var clientSecret = "client_secret";
133+ var audience = "audience";
134+ var token = "test_token";
135+ var expiresIn = 300;
136+ var client = initClient(clientSecret);
137+
138+
139+ var params = Map.of(
140+ "client_id", client.getClientId(),
141+ "audience", audience,
142+ "token", token,
143+ "client_secret", clientSecret);
144+
145+ var accessToken = tokenRequest(params)
146+ .statusCode(200)
147+ .contentType(JSON)
148+ .body("access_token", notNullValue())
149+ .body("expires_in", is(expiresIn))
150+ .extract()
151+ .body()
152+ .jsonPath().getString("access_token");
153+
154+
155+ assertThat(parseClaims(accessToken))
156+ .containsEntry(ISSUER, client.getDid())
157+ .containsEntry(SUBJECT, client.getDid())
158+ .containsEntry(AUDIENCE, List.of(audience))
159+ .doesNotContainKey(CLIENT_ID)
160+ .containsEntry(PRESENTATION_TOKEN_CLAIM, token)
161+ .containsKeys(JWT_ID, EXPIRATION_TIME, ISSUED_AT);
162+ }
163+
164+ @Test
165+ void requestToken_shouldReturnError_whenClientNotFound() {
166+
167+ var clientId = "client_id";
168+ var clientSecret = "client_secret";
169+ var audience = "audience";
170+
171+ var params = Map.of(
172+ "client_id", clientId,
173+ "audience", audience,
174+ "client_secret", clientSecret);
175+
176+ tokenRequest(params)
177+ .statusCode(401)
178+ .contentType(JSON);
179+ }
180+
181+ protected ValidatableResponse tokenRequest(Map<String, String> params) {
182+
183+ var req = baseRequest()
184+ .contentType("application/x-www-form-urlencoded")
185+ .formParam("grant_type", GRANT_TYPE);
186+ params.forEach(req::formParam);
187+ return req.post("/token").then();
188+ }
189+
190+ protected RequestSpecification baseRequest() {
191+ return given()
192+ .port(PORT)
193+ .baseUri(BASE_STS)
194+ .when();
195+ }
198196 }
199197
200- protected RequestSpecification baseRequest() {
201- return given()
202- .port(PORT)
203- .baseUri(BASE_STS)
204- .when();
198+ @Nested
199+ @EndToEndTest
200+ class InMemory extends Tests {
201+
202+ @RegisterExtension
203+ static RuntimePerClassExtension sts = new RuntimePerClassExtension(new EmbeddedRuntime(
204+ "sts",
205+ new HashMap<>() {
206+ {
207+ put("web.http.path", "/");
208+ put("web.http.port", String.valueOf(getFreePort()));
209+ put("web.http.sts.path", "/sts");
210+ put("web.http.sts.port", String.valueOf(PORT));
211+ }
212+ },
213+ ":system-tests:sts-api:sts-api-test-runtime"
214+ ));
215+
216+ @Override
217+ protected RuntimePerClassExtension getRuntime() {
218+ return sts;
219+ }
205220 }
206221
207- @Override
208- protected RuntimePerClassExtension getRuntime() {
209- return sts;
222+ @Nested
223+ @PostgresqlIntegrationTest
224+ class Postgres extends Tests {
225+
226+
227+ @RegisterExtension
228+ static RuntimePerClassExtension sts = new RuntimePerClassExtension(new EmbeddedRuntime(
229+ "sts",
230+ new HashMap<>() {
231+ {
232+ put("web.http.path", "/");
233+ put("web.http.port", String.valueOf(getFreePort()));
234+ put("web.http.sts.path", "/sts");
235+ put("web.http.sts.port", String.valueOf(PORT));
236+ put("edc.datasource.default.url", PostgresqlEndToEndInstance.JDBC_URL_PREFIX + "runtime");
237+ put("edc.datasource.default.user", PostgresqlEndToEndInstance.USER);
238+ put("edc.datasource.default.password", PostgresqlEndToEndInstance.PASSWORD);
239+ put("edc.sql.schema.autocreate", "true");
240+ }
241+ },
242+ ":system-tests:sts-api:sts-api-test-runtime",
243+ ":extensions:common:store:sql:sts-client-store-sql",
244+ ":extensions:common:sql:sql-pool:sql-pool-apache-commons",
245+ ":extensions:common:transaction:transaction-local"
246+ )) {
247+ @Override
248+ public void beforeAll(ExtensionContext extensionContext) {
249+ createDatabase("runtime");
250+ super.beforeAll(extensionContext);
251+ }
252+ };
253+
254+ @Override
255+ protected RuntimePerClassExtension getRuntime() {
256+ return sts;
257+ }
210258 }
211259
212260 }