Search in sources :

Example 1 with PartyStore

use of com.quorum.tessera.p2p.partyinfo.PartyStore in project tessera by ConsenSys.

the class P2PRestApp method getSingletons.

@Override
public Set<Object> getSingletons() {
    RuntimeContext runtimeContext = RuntimeContext.getInstance();
    List<URI> peers = runtimeContext.getPeers();
    LOGGER.debug("Found configured peers {}", peers);
    peers.stream().map(NodeUri::create).map(NodeUri::asURI).peek(u -> LOGGER.debug("Adding {} to party store", u)).forEach(partyStore::store);
    final PartyInfoResource partyInfoResource = new PartyInfoResource(discovery, partyInfoParser, runtimeContext.getP2pClient(), enclave, runtimeContext.isRemoteKeyValidation());
    final IPWhitelistFilter iPWhitelistFilter = new IPWhitelistFilter();
    final TransactionResource transactionResource = new TransactionResource(transactionManager, batchResendManager, legacyResendManager);
    final UpCheckResource upCheckResource = new UpCheckResource();
    final PrivacyGroupResource privacyGroupResource = new PrivacyGroupResource(privacyGroupManager);
    if (runtimeContext.isRecoveryMode()) {
        final RecoveryResource recoveryResource = new RecoveryResource(transactionManager, batchResendManager);
        return Set.of(partyInfoResource, iPWhitelistFilter, recoveryResource, upCheckResource);
    }
    return Set.of(partyInfoResource, iPWhitelistFilter, transactionResource, privacyGroupResource, upCheckResource);
}
Also used : PartyInfoParser(com.quorum.tessera.p2p.partyinfo.PartyInfoParser) AppType(com.quorum.tessera.config.AppType) Logger(org.slf4j.Logger) TransactionManager(com.quorum.tessera.transaction.TransactionManager) LoggerFactory(org.slf4j.LoggerFactory) BatchResendManager(com.quorum.tessera.recovery.workflow.BatchResendManager) Set(java.util.Set) PrivacyGroupManager(com.quorum.tessera.privacygroup.PrivacyGroupManager) NodeUri(com.quorum.tessera.discovery.NodeUri) PartyStore(com.quorum.tessera.p2p.partyinfo.PartyStore) Objects(java.util.Objects) Discovery(com.quorum.tessera.discovery.Discovery) ApplicationPath(jakarta.ws.rs.ApplicationPath) List(java.util.List) Stream(java.util.stream.Stream) UpCheckResource(com.quorum.tessera.api.common.UpCheckResource) GlobalFilter(com.quorum.tessera.api.filter.GlobalFilter) RuntimeContext(com.quorum.tessera.context.RuntimeContext) Enclave(com.quorum.tessera.enclave.Enclave) URI(java.net.URI) LegacyResendManager(com.quorum.tessera.recovery.workflow.LegacyResendManager) Collectors.toSet(java.util.stream.Collectors.toSet) IPWhitelistFilter(com.quorum.tessera.api.filter.IPWhitelistFilter) TesseraRestApplication(com.quorum.tessera.app.TesseraRestApplication) UpCheckResource(com.quorum.tessera.api.common.UpCheckResource) IPWhitelistFilter(com.quorum.tessera.api.filter.IPWhitelistFilter) NodeUri(com.quorum.tessera.discovery.NodeUri) RuntimeContext(com.quorum.tessera.context.RuntimeContext) URI(java.net.URI)

Example 2 with PartyStore

use of com.quorum.tessera.p2p.partyinfo.PartyStore in project tessera by ConsenSys.

the class PartyInfoResource method partyInfo.

/**
 * Update the local partyinfo store with the encoded partyinfo included in the request.
 *
 * @param payload The encoded partyinfo information pushed by the caller
 * @return an empty 200 OK Response if the local node is using remote key validation; a 200 OK
 *     Response wrapping an encoded partyinfo that contains only the local node's URL if not using
 *     remote key validation; a 500 Internal Server Error if remote key validation fails
 */
@Operation(summary = "/partyinfo", operationId = "broadcastPartyInfo", description = "broadcast partyinfo information to server")
@ApiResponse(responseCode = "200", description = "server successfully updated its party info", content = @Content(array = @ArraySchema(schema = @Schema(description = "empty if server is using remote key validation, else is encoded partyinfo object containing only the server's URL", type = "string", format = "byte"))))
@ApiResponse(responseCode = "500", description = "Validation failed (if server is using remote key validation)")
@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response partyInfo(@RequestBody(required = true, description = "partyinfo object") final byte[] payload, @HeaderParam(Constants.API_VERSION_HEADER) @Parameter(description = "client's supported API versions", array = @ArraySchema(schema = @Schema(type = "string"))) final List<String> headers) {
    final PartyInfo partyInfo = partyInfoParser.from(payload);
    final Set<String> versions = Optional.ofNullable(headers).orElse(emptyList()).stream().filter(Objects::nonNull).flatMap(v -> Arrays.stream(v.split(","))).collect(Collectors.toSet());
    final NodeInfo nodeInfo = NodeInfoUtil.from(partyInfo, versions);
    LOGGER.debug("Received PartyInfo from {}", partyInfo.getUrl());
    if (!enableKeyValidation) {
        LOGGER.debug("Key validation not enabled, passing PartyInfo through");
        discovery.onUpdate(nodeInfo);
        partyInfo.getParties().stream().map(Party::getUrl).map(NodeUri::create).map(NodeUri::asURI).forEach(partyStore::store);
        // create an empty party info object with our URL to send back
        // this is used by older versions (before 0.10.0), but we don't want to give any info back
        final PartyInfo emptyInfo = new PartyInfo(discovery.getCurrent().getUrl(), emptySet(), emptySet());
        final byte[] returnData = partyInfoParser.to(emptyInfo);
        return Response.ok(returnData).build();
    }
    final PublicKey localPublicKey = enclave.defaultPublicKey();
    final Predicate<Recipient> isValidRecipient = r -> {
        try {
            LOGGER.debug("Validating key {} for peer {}", r.getKey(), r.getUrl());
            final String dataToEncrypt = UUID.randomUUID().toString();
            final EncodedPayload encodedPayload = enclave.encryptPayload(dataToEncrypt.getBytes(), localPublicKey, List.of(r.getKey()), PrivacyMetadata.Builder.forStandardPrivate().build());
            final byte[] encodedPayloadBytes = payloadEncoder.encode(encodedPayload);
            try (Response response = restClient.target(r.getUrl()).path("partyinfo").path("validate").request().post(Entity.entity(encodedPayloadBytes, MediaType.APPLICATION_OCTET_STREAM))) {
                LOGGER.debug("Response code {} from peer {}", response.getStatus(), r.getUrl());
                final String responseData = response.readEntity(String.class);
                final boolean isValid = Objects.equals(responseData, dataToEncrypt);
                if (!isValid) {
                    LOGGER.warn("Validation of key {} for peer {} failed.  Key and peer will not be added to local partyinfo.", r.getKey(), r.getUrl());
                    LOGGER.debug("Response from {} was {}", r.getUrl(), responseData);
                }
                return isValid;
            }
        // Assume any and all exceptions to mean invalid. enclave bubbles up nacl array out of
        // bounds when calculating shared key from invalid data
        } catch (Exception ex) {
            LOGGER.debug(null, ex);
            return false;
        }
    };
    final String partyInfoSender = partyInfo.getUrl();
    final Predicate<Recipient> isSender = r -> NodeUri.create(r.getUrl()).equals(NodeUri.create(partyInfoSender));
    // Validate caller and treat no valid certs as security issue.
    final Set<com.quorum.tessera.partyinfo.node.Recipient> validatedSendersKeys = partyInfo.getRecipients().stream().filter(isSender.and(isValidRecipient)).map(r -> com.quorum.tessera.partyinfo.node.Recipient.of(r.getKey(), r.getUrl())).collect(Collectors.toSet());
    LOGGER.debug("Validated keys for peer {}: {}", partyInfoSender, validatedSendersKeys);
    if (validatedSendersKeys.isEmpty()) {
        throw new SecurityException("No validated keys found for peer " + partyInfoSender);
    }
    // End validation stuff
    final NodeInfo reducedNodeInfo = NodeInfo.Builder.create().withUrl(partyInfoSender).withSupportedApiVersions(versions).withRecipients(validatedSendersKeys).build();
    discovery.onUpdate(reducedNodeInfo);
    partyInfo.getParties().stream().map(Party::getUrl).map(NodeUri::create).map(NodeUri::asURI).forEach(partyStore::store);
    return Response.ok().build();
}
Also used : PublicKey(com.quorum.tessera.encryption.PublicKey) java.util(java.util) NodeInfoUtil(com.quorum.tessera.partyinfo.model.NodeInfoUtil) LoggerFactory(org.slf4j.LoggerFactory) Party(com.quorum.tessera.partyinfo.model.Party) GetPartyInfoResponse(com.quorum.tessera.p2p.model.GetPartyInfoResponse) Content(io.swagger.v3.oas.annotations.media.Content) Discovery(com.quorum.tessera.discovery.Discovery) Operation(io.swagger.v3.oas.annotations.Operation) Response(jakarta.ws.rs.core.Response) NodeInfo(com.quorum.tessera.partyinfo.node.NodeInfo) Objects.requireNonNull(java.util.Objects.requireNonNull) RequestBody(io.swagger.v3.oas.annotations.parameters.RequestBody) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) Constants(com.quorum.tessera.shared.Constants) Schema(io.swagger.v3.oas.annotations.media.Schema) PartyInfoParser(com.quorum.tessera.p2p.partyinfo.PartyInfoParser) Client(jakarta.ws.rs.client.Client) Logger(org.slf4j.Logger) Collections.emptySet(java.util.Collections.emptySet) Collections.emptyList(java.util.Collections.emptyList) Predicate(java.util.function.Predicate) com.quorum.tessera.enclave(com.quorum.tessera.enclave) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) NodeUri(com.quorum.tessera.discovery.NodeUri) jakarta.ws.rs(jakarta.ws.rs) Collectors(java.util.stream.Collectors) PartyStore(com.quorum.tessera.p2p.partyinfo.PartyStore) Json(jakarta.json.Json) Entity(jakarta.ws.rs.client.Entity) Parameter(io.swagger.v3.oas.annotations.Parameter) ArraySchema(io.swagger.v3.oas.annotations.media.ArraySchema) PartyInfo(com.quorum.tessera.partyinfo.model.PartyInfo) MediaType(jakarta.ws.rs.core.MediaType) Tag(io.swagger.v3.oas.annotations.tags.Tag) Recipient(com.quorum.tessera.partyinfo.model.Recipient) PublicKey(com.quorum.tessera.encryption.PublicKey) NodeUri(com.quorum.tessera.discovery.NodeUri) Recipient(com.quorum.tessera.partyinfo.model.Recipient) PartyInfo(com.quorum.tessera.partyinfo.model.PartyInfo) GetPartyInfoResponse(com.quorum.tessera.p2p.model.GetPartyInfoResponse) Response(jakarta.ws.rs.core.Response) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) NodeInfo(com.quorum.tessera.partyinfo.node.NodeInfo) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse)

Example 3 with PartyStore

use of com.quorum.tessera.p2p.partyinfo.PartyStore in project tessera by ConsenSys.

the class P2PRestAppTest method setUp.

@Before
public void setUp() {
    runtimeContext = mock(RuntimeContext.class);
    enclave = mock(Enclave.class);
    discovery = mock(Discovery.class);
    partyStore = mock(PartyStore.class);
    transactionManager = mock(TransactionManager.class);
    batchResendManager = mock(BatchResendManager.class);
    legacyResendManager = mock(LegacyResendManager.class);
    privacyGroupManager = mock(PrivacyGroupManager.class);
    p2PRestApp = new P2PRestApp(discovery, enclave, partyStore, transactionManager, batchResendManager, legacyResendManager, privacyGroupManager);
    Client client = mock(Client.class);
    when(runtimeContext.getP2pClient()).thenReturn(client);
    when(runtimeContext.isRemoteKeyValidation()).thenReturn(true);
    when(runtimeContext.getPeers()).thenReturn(List.of(peerUri));
}
Also used : BatchResendManager(com.quorum.tessera.recovery.workflow.BatchResendManager) PrivacyGroupManager(com.quorum.tessera.privacygroup.PrivacyGroupManager) Enclave(com.quorum.tessera.enclave.Enclave) TransactionManager(com.quorum.tessera.transaction.TransactionManager) PartyStore(com.quorum.tessera.p2p.partyinfo.PartyStore) Discovery(com.quorum.tessera.discovery.Discovery) LegacyResendManager(com.quorum.tessera.recovery.workflow.LegacyResendManager) RuntimeContext(com.quorum.tessera.context.RuntimeContext) Client(jakarta.ws.rs.client.Client) Before(org.junit.Before)

Aggregations

Discovery (com.quorum.tessera.discovery.Discovery)3 PartyStore (com.quorum.tessera.p2p.partyinfo.PartyStore)3 RuntimeContext (com.quorum.tessera.context.RuntimeContext)2 NodeUri (com.quorum.tessera.discovery.NodeUri)2 Enclave (com.quorum.tessera.enclave.Enclave)2 PartyInfoParser (com.quorum.tessera.p2p.partyinfo.PartyInfoParser)2 PrivacyGroupManager (com.quorum.tessera.privacygroup.PrivacyGroupManager)2 BatchResendManager (com.quorum.tessera.recovery.workflow.BatchResendManager)2 LegacyResendManager (com.quorum.tessera.recovery.workflow.LegacyResendManager)2 TransactionManager (com.quorum.tessera.transaction.TransactionManager)2 Client (jakarta.ws.rs.client.Client)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 UpCheckResource (com.quorum.tessera.api.common.UpCheckResource)1 GlobalFilter (com.quorum.tessera.api.filter.GlobalFilter)1 IPWhitelistFilter (com.quorum.tessera.api.filter.IPWhitelistFilter)1 TesseraRestApplication (com.quorum.tessera.app.TesseraRestApplication)1 AppType (com.quorum.tessera.config.AppType)1 com.quorum.tessera.enclave (com.quorum.tessera.enclave)1 PublicKey (com.quorum.tessera.encryption.PublicKey)1