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: encode ContractId parts #3235

Merged
merged 3 commits into from
Jun 28, 2023
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 @@ -92,8 +92,8 @@ private Offer createOffer(ContractDefinition definition, String assetId) {
if (policyDefinition == null) {
return null;
}
var contractId = ContractId.createContractId(definition.getId(), assetId);
return new Offer(contractId, policyDefinition.getPolicy());
var contractId = ContractId.create(definition.getId(), assetId);
return new Offer(contractId.toString(), policyDefinition.getPolicy());
}

private static class Offer {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import static java.util.stream.IntStream.range;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.eclipse.edc.junit.assertions.AbstractResultAssert.assertThat;
import static org.eclipse.edc.policy.model.PolicyType.OFFER;
import static org.eclipse.edc.policy.model.PolicyType.SET;
import static org.eclipse.edc.spi.CoreConstants.EDC_NAMESPACE;
Expand Down Expand Up @@ -89,8 +90,7 @@ void query_shouldReturnOneDatasetPerAsset() {
assertThat(dataset.getId()).matches(isUuid());
assertThat(dataset.getDistributions()).hasSize(1).first().isEqualTo(distribution);
assertThat(dataset.getOffers()).hasSize(1).allSatisfy((id, policy) -> {
assertThat(id).startsWith("definitionId");
assertThat(ContractId.parse(id)).matches(ContractId::isValid);
assertThat(ContractId.parseId(id)).isSucceeded().extracting(ContractId::definitionPart).asString().isEqualTo("definitionId");
assertThat(policy.getTarget()).isEqualTo("assetId");
});
assertThat(dataset.getProperties()).contains(entry("key", "value"));
Expand Down Expand Up @@ -127,11 +127,11 @@ void query_shouldReturnOneDataset_whenMultipleDefinitionsOnSameAsset() {
assertThat(dataset.getId()).matches(isUuid());
assertThat(dataset.getOffers()).hasSize(2)
.anySatisfy((id, policy) -> {
assertThat(id).startsWith("definition1");
assertThat(ContractId.parseId(id)).isSucceeded().extracting(ContractId::definitionPart).asString().isEqualTo("definition1");
assertThat(policy.getType()).isEqualTo(SET);
})
.anySatisfy((id, policy) -> {
assertThat(id).startsWith("definition2");
assertThat(ContractId.parseId(id)).isSucceeded().extracting(ContractId::definitionPart).asString().isEqualTo("definition2");
assertThat(policy.getType()).isEqualTo(OFFER);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,16 +165,16 @@ private boolean processRequesting(ContractNegotiation negotiation) {
private boolean processAccepting(ContractNegotiation negotiation) {
var lastOffer = negotiation.getLastContractOffer();

var contractId = ContractId.parse(lastOffer.getId());
if (!contractId.isValid()) {
monitor.severe("ConsumerContractNegotiationManagerImpl.approveContractOffers(): Offer Id not correctly formatted.");
var contractIdResult = ContractId.parseId(lastOffer.getId());
if (contractIdResult.failed()) {
monitor.severe("ConsumerContractNegotiationManagerImpl.approveContractOffers(): Offer Id not correctly formatted: " + contractIdResult.getFailureDetail());
return false;
}
var definitionId = contractId.definitionPart();
var contractId = contractIdResult.getContent();

var policy = lastOffer.getPolicy();
var agreement = ContractAgreement.Builder.newInstance()
.id(ContractId.createContractId(definitionId, lastOffer.getAssetId()))
.id(contractId.derive().toString())
.contractSigningDate(clock.instant().getEpochSecond())
.providerId(negotiation.getCounterPartyId())
.consumerId(participantId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,15 +174,16 @@ private boolean processAgreeing(ContractNegotiation negotiation) {
if (retrievedAgreement == null) {
var lastOffer = negotiation.getLastContractOffer();

var contractId = ContractId.parse(lastOffer.getId());
if (!contractId.isValid()) {
monitor.severe("ProviderContractNegotiationManagerImpl.checkConfirming(): Offer Id not correctly formatted.");
var contractIdResult = ContractId.parseId(lastOffer.getId());
if (contractIdResult.failed()) {
monitor.severe("ProviderContractNegotiationManagerImpl.checkConfirming(): Offer Id not correctly formatted: " + contractIdResult.getFailureDetail());
return false;
}
var definitionId = contractId.definitionPart();

var contractId = contractIdResult.getContent();

agreement = ContractAgreement.Builder.newInstance()
.id(ContractId.createContractId(definitionId, lastOffer.getAssetId()))
.id(contractId.derive().toString())
.contractSigningDate(clock.instant().getEpochSecond())
.providerId(participantId)
.consumerId(negotiation.getCounterPartyId())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,16 @@ private Stream<ContractOffer.Builder> createContractOffers(ContractDefinition de
return Optional.of(definition.getContractPolicyId())
.map(policyStore::findById)
.map(policyDefinition -> assetIndex.queryAssets(assetQuerySpec)
.map(asset -> createContractOffer(definition, policyDefinition.getPolicy(), asset.getId())))
.map(asset -> ContractId.create(definition.getId(), asset.getId()))
.map(contractId -> createContractOffer(policyDefinition.getPolicy(), contractId)))
.orElse(Stream.empty());
}

@NotNull
private ContractOffer.Builder createContractOffer(ContractDefinition definition, Policy policy, String assetId) {
private ContractOffer.Builder createContractOffer(Policy policy, ContractId contractId) {
return ContractOffer.Builder.newInstance()
.id(ContractId.createContractId(definition.getId(), assetId))
.policy(policy.withTarget(assetId))
.assetId(assetId);
.id(contractId.toString())
.policy(policy.withTarget(contractId.assetIdPart()))
.assetId(contractId.assetIdPart());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import org.eclipse.edc.connector.contract.spi.offer.ContractDefinitionResolver;
import org.eclipse.edc.connector.contract.spi.types.agreement.ContractAgreement;
import org.eclipse.edc.connector.contract.spi.types.negotiation.ContractNegotiation;
import org.eclipse.edc.connector.contract.spi.types.offer.ContractDefinition;
import org.eclipse.edc.connector.contract.spi.types.offer.ContractOffer;
import org.eclipse.edc.connector.contract.spi.validation.ContractValidationService;
import org.eclipse.edc.connector.contract.spi.validation.ValidatedConsumerOffer;
Expand All @@ -42,7 +41,6 @@
import java.util.ArrayList;

import static java.lang.String.format;
import static org.eclipse.edc.connector.contract.spi.ContractId.createContractId;
import static org.eclipse.edc.spi.result.Result.failure;
import static org.eclipse.edc.spi.result.Result.success;

Expand Down Expand Up @@ -78,68 +76,47 @@ public ContractValidationServiceImpl(String participantId,
@Override
@NotNull
public Result<ValidatedConsumerOffer> validateInitialOffer(ClaimToken token, ContractOffer offer) {
var contractId = ContractId.parse(offer.getId());
if (!contractId.isValid()) {
return failure("Invalid id: " + offer.getId());
}

var agent = agentService.createFor(token);

var result = validateInitialOffer(contractId, agent);

return result.map(r ->
new ValidatedConsumerOffer(agent.getIdentity(),
ContractOffer.Builder.newInstance()
.id(offer.getId())
.assetId(contractId.assetIdPart())
.providerId(participantId)
.policy(r.getPolicy())
.build())
);
return validateInitialOffer(token, offer.getId());
}

@Override
public @NotNull Result<ValidatedConsumerOffer> validateInitialOffer(ClaimToken token, String offerId) {
var contractId = ContractId.parse(offerId);
if (!contractId.isValid()) {
return failure("Invalid id: " + offerId);
}

var agent = agentService.createFor(token);

var result = validateInitialOffer(contractId, agent);
return ContractId.parseId(offerId)
.compose(contractId -> {
var agent = agentService.createFor(token);

return result.map(r -> {
var offer = createContractOffer(result.getContent().getDefinition(), result.getContent().getPolicy(), contractId.assetIdPart());
return new ValidatedConsumerOffer(agent.getIdentity(), offer);
});
return validateInitialOffer(contractId, agent)
.map(sanitizedPolicy -> {
var offer = createContractOffer(sanitizedPolicy, contractId);
return new ValidatedConsumerOffer(agent.getIdentity(), offer);
});
});

}

@Override
@NotNull
public Result<ContractAgreement> validateAgreement(ClaimToken token, ContractAgreement agreement) {
var contractId = ContractId.parse(agreement.getId());
if (!contractId.isValid()) {
return failure(format("The contract id %s does not follow the expected scheme", agreement.getId()));
}
return ContractId.parseId(agreement.getId())
.compose(contractId -> {
var agent = agentService.createFor(token);
var consumerIdentity = agent.getIdentity();
if (consumerIdentity == null || !consumerIdentity.equals(agreement.getConsumerId())) {
return failure("Invalid provider credentials");
}

var policyContext = PolicyContextImpl.Builder.newInstance()
.additional(ParticipantAgent.class, agent)
.additional(ContractAgreement.class, agreement)
.additional(Instant.class, Instant.now())
.build();
var policyResult = policyEngine.evaluate(TRANSFER_SCOPE, agreement.getPolicy(), policyContext);
if (!policyResult.succeeded()) {
return failure(format("Policy does not fulfill the agreement %s, policy evaluation %s", agreement.getId(), policyResult.getFailureDetail()));
}
return success(agreement);
});

var agent = agentService.createFor(token);
var consumerIdentity = agent.getIdentity();
if (consumerIdentity == null || !consumerIdentity.equals(agreement.getConsumerId())) {
return failure("Invalid provider credentials");
}

var policyContext = PolicyContextImpl.Builder.newInstance()
.additional(ParticipantAgent.class, agent)
.additional(ContractAgreement.class, agreement)
.additional(Instant.class, Instant.now())
.build();
var policyResult = policyEngine.evaluate(TRANSFER_SCOPE, agreement.getPolicy(), policyContext);
if (!policyResult.succeeded()) {
return failure(format("Policy does not fulfill the agreement %s, policy evaluation %s", agreement.getId(), policyResult.getFailureDetail()));
}
return success(agreement);
}

@Override
Expand All @@ -157,29 +134,27 @@ public Result<Void> validateConfirmed(ClaimToken token, ContractAgreement agreem
return failure("No offer found");
}

var contractId = ContractId.parse(agreement.getId());
if (!contractId.isValid()) {
return failure(format("ContractId %s does not follow the expected schema.", agreement.getId()));
}
return ContractId.parseId(agreement.getId())
.compose(contractId -> {
var agent = agentService.createFor(token);
var providerIdentity = agent.getIdentity();
if (providerIdentity == null || !providerIdentity.equals(agreement.getProviderId())) {
return failure("Invalid provider credentials");
}

var agent = agentService.createFor(token);
var providerIdentity = agent.getIdentity();
if (providerIdentity == null || !providerIdentity.equals(agreement.getProviderId())) {
return failure("Invalid provider credentials");
}
if (!policyEquality.test(agreement.getPolicy().withTarget(latestOffer.getAssetId()), latestOffer.getPolicy())) {
return failure("Policy in the contract agreement is not equal to the one in the contract offer");
}

if (!policyEquality.test(agreement.getPolicy().withTarget(latestOffer.getAssetId()), latestOffer.getPolicy())) {
return failure("Policy in the contract agreement is not equal to the one in the contract offer");
}

return success();
return success();
});
}

/**
* Validates an initial contract offer, ensuring that the referenced asset exists, is selected by the corresponding policy definition and the agent fulfills the contract policy.
* A sanitized policy definition is returned to avoid clients injecting manipulated policies.
*/
private Result<SanitizedResult> validateInitialOffer(ContractId contractId, ParticipantAgent agent) {
private Result<Policy> validateInitialOffer(ContractId contractId, ParticipantAgent agent) {
var consumerIdentity = agent.getIdentity();
if (consumerIdentity == null) {
return failure("Invalid consumer identity");
Expand Down Expand Up @@ -214,36 +189,17 @@ private Result<SanitizedResult> validateInitialOffer(ContractId contractId, Part
if (policyResult.failed()) {
return failure(format("Policy %s not fulfilled", policyDefinition.getUid()));
}
return Result.success(new SanitizedResult(contractDefinition, policy));
return Result.success(policy);
}

@NotNull
private ContractOffer createContractOffer(ContractDefinition definition, Policy policy, String assetId) {
private ContractOffer createContractOffer(Policy policy, ContractId contractId) {
return ContractOffer.Builder.newInstance()
.id(createContractId(definition.getId(), assetId))
.id(contractId.toString())
.providerId(participantId)
.policy(policy)
.assetId(assetId)
.assetId(contractId.assetIdPart())
.build();
}

private static class SanitizedResult {
private final ContractDefinition definition;
private final Policy policy;

SanitizedResult(ContractDefinition definition, Policy policy) {
this.definition = definition;
this.policy = policy;
}

ContractDefinition getDefinition() {
return definition;
}

Policy getPolicy() {
return policy;
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ private CompletableFuture<?> toFuture(ServiceResult<ContractNegotiation> result)
*/
private ContractOffer getContractOffer() {
return ContractOffer.Builder.newInstance()
.id(ContractId.createContractId("1", "test-asset-id"))
.id(ContractId.create("1", "test-asset-id").toString())
.providerId("provider")
.assetId(randomUUID().toString())
.policy(Policy.Builder.newInstance()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ private ContractNegotiation.Builder contractNegotiationBuilder() {

private ContractAgreement.Builder contractAgreementBuilder() {
return ContractAgreement.Builder.newInstance()
.id(ContractId.createContractId(UUID.randomUUID().toString(), "test-asset-id"))
.id(ContractId.create(UUID.randomUUID().toString(), "test-asset-id").toString())
.providerId("any")
.consumerId("any")
.assetId("default")
Expand All @@ -257,7 +257,7 @@ private ContractAgreement.Builder contractAgreementBuilder() {

private ContractOffer contractOffer() {
return ContractOffer.Builder.newInstance()
.id(ContractId.createContractId("1", "test-asset-id"))
.id(ContractId.create("1", "test-asset-id").toString())
.policy(Policy.Builder.newInstance().build())
.assetId("assetId")
.providerId(PROVIDER_ID)
Expand Down
Loading