Search in sources :

Example 6 with Recipient

use of com.quorum.tessera.partyinfo.model.Recipient in project tessera by ConsenSys.

the class PartyInfoResourceTest method validationDisabledPassesAllKeysToStore.

@Test
public void validationDisabledPassesAllKeysToStore() {
    this.partyInfoResource = new PartyInfoResource(discovery, partyInfoParser, restClient, enclave, payloadEncoder, false, partyStore);
    final byte[] payload = "Test message".getBytes();
    final String url = "http://www.bogus.com";
    final String otherurl = "http://www.randomaddress.com";
    final PublicKey recipientKey = PublicKey.from("recipientKey".getBytes());
    final Set<Recipient> recipientList = new HashSet<>(Arrays.asList(Recipient.of(recipientKey, url), Recipient.of(recipientKey, otherurl)));
    final PartyInfo partyInfo = new PartyInfo(url, recipientList, Collections.emptySet());
    final NodeInfo nodeInfo = NodeInfoUtil.from(partyInfo, null);
    final ArgumentCaptor<PartyInfo> captor = ArgumentCaptor.forClass(PartyInfo.class);
    final byte[] serialisedData = "SERIALISED".getBytes();
    when(partyInfoParser.from(payload)).thenReturn(partyInfo);
    when(discovery.getCurrent()).thenReturn(nodeInfo);
    when(partyInfoParser.to(captor.capture())).thenReturn(serialisedData);
    final Response callResponse = partyInfoResource.partyInfo(payload, null);
    final byte[] data = (byte[]) callResponse.getEntity();
    assertThat(captor.getValue().getUrl()).isEqualTo(url);
    assertThat(captor.getValue().getRecipients()).isEmpty();
    assertThat(captor.getValue().getParties()).isEmpty();
    assertThat(new String(data)).isEqualTo("SERIALISED");
    verify(partyInfoParser).from(payload);
    verify(partyInfoParser).to(any(PartyInfo.class));
    final ArgumentCaptor<NodeInfo> modifiedPartyInfoCaptor = ArgumentCaptor.forClass(NodeInfo.class);
    verify(discovery).onUpdate(modifiedPartyInfoCaptor.capture());
    final NodeInfo modified = modifiedPartyInfoCaptor.getValue();
    assertThat(modified.getUrl()).isEqualTo(url);
    Set<com.quorum.tessera.partyinfo.node.Recipient> updatedRecipients = modified.getRecipients();
    assertThat(updatedRecipients).containsExactlyInAnyOrder(com.quorum.tessera.partyinfo.node.Recipient.of(recipientKey, url), com.quorum.tessera.partyinfo.node.Recipient.of(recipientKey, otherurl));
    verify(discovery).getCurrent();
}
Also used : PublicKey(com.quorum.tessera.encryption.PublicKey) Recipient(com.quorum.tessera.partyinfo.model.Recipient) PartyInfo(com.quorum.tessera.partyinfo.model.PartyInfo) Response(jakarta.ws.rs.core.Response) NodeInfo(com.quorum.tessera.partyinfo.node.NodeInfo) Test(org.junit.Test)

Example 7 with Recipient

use of com.quorum.tessera.partyinfo.model.Recipient in project tessera by ConsenSys.

the class PartyInfoResource method getPartyInfo.

@Operation(summary = "/partyinfo", description = "fetch network/peer information")
@ApiResponse(responseCode = "200", description = "server's partyinfo data", content = @Content(schema = @Schema(implementation = GetPartyInfoResponse.class)))
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getPartyInfo() {
    final NodeInfo current = this.discovery.getCurrent();
    final JsonArrayBuilder peersBuilder = Json.createArrayBuilder();
    partyStore.getParties().stream().map(party -> Json.createObjectBuilder().add("url", party.toString()).build()).forEach(peersBuilder::add);
    final JsonArrayBuilder recipientBuilder = Json.createArrayBuilder();
    current.getRecipients().stream().map(recipient -> Json.createObjectBuilder().add("key", recipient.getKey().encodeToBase64()).add("url", recipient.getUrl()).build()).forEach(recipientBuilder::add);
    final String output = Json.createObjectBuilder().add("url", current.getUrl()).add("peers", peersBuilder.build()).add("keys", recipientBuilder.build()).build().toString();
    LOGGER.debug("Sending json {} from {}", output, current);
    return Response.status(Response.Status.OK).entity(output).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) NodeInfo(com.quorum.tessera.partyinfo.node.NodeInfo) JsonArrayBuilder(jakarta.json.JsonArrayBuilder) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse)

Example 8 with Recipient

use of com.quorum.tessera.partyinfo.model.Recipient in project tessera by ConsenSys.

the class PartyInfoParser method from.

/**
 * Decodes a set of PartyInfo to the format that is shared between nodes
 *
 * @param encoded the encoded information that needs to be read
 * @return the decoded {@link PartyInfo} which contains the other nodes information
 */
default PartyInfo from(final byte[] encoded) {
    final ByteBuffer byteBuffer = ByteBuffer.wrap(encoded);
    final int urlLength = toIntExact(byteBuffer.getLong());
    checkLength(urlLength);
    final byte[] urlBytes = new byte[urlLength];
    byteBuffer.get(urlBytes);
    final String url = new String(urlBytes, UTF_8);
    final int numberOfRecipients = toIntExact(byteBuffer.getLong());
    checkLength(numberOfRecipients);
    final Set<Recipient> recipients = new HashSet<>();
    for (int i = 0; i < numberOfRecipients; i++) {
        final int recipientKeyLength = toIntExact(byteBuffer.getLong());
        checkLength(recipientKeyLength);
        final byte[] recipientKeyBytes = new byte[recipientKeyLength];
        byteBuffer.get(recipientKeyBytes);
        final int recipientUrlValueLength = toIntExact(byteBuffer.getLong());
        checkLength(recipientUrlValueLength);
        final byte[] urlValueData = new byte[recipientUrlValueLength];
        byteBuffer.get(urlValueData);
        final String recipientUrl = new String(urlValueData, UTF_8);
        recipients.add(Recipient.of(PublicKey.from(recipientKeyBytes), recipientUrl));
    }
    final int partyCount = toIntExact(byteBuffer.getLong());
    checkLength(partyCount);
    final Set<Party> parties = new HashSet<>();
    for (int i = 0; i < partyCount; i++) {
        long partyElementLength = byteBuffer.getLong();
        checkLength(partyElementLength);
        byte[] ptyData = new byte[toIntExact(partyElementLength)];
        byteBuffer.get(ptyData);
        parties.add(new Party(new String(ptyData, UTF_8)));
    }
    return new PartyInfo(url, recipients, parties);
}
Also used : Party(com.quorum.tessera.partyinfo.model.Party) Recipient(com.quorum.tessera.partyinfo.model.Recipient) ByteBuffer(java.nio.ByteBuffer) PartyInfo(com.quorum.tessera.partyinfo.model.PartyInfo) HashSet(java.util.HashSet)

Example 9 with Recipient

use of com.quorum.tessera.partyinfo.model.Recipient in project tessera by ConsenSys.

the class PartyInfoParserTest method from.

@Test
public void from() {
    PartyInfo result = partyInfoParser.from(dataOne);
    assertThat(result).isNotNull();
    assertThat(result.getUrl()).isEqualTo("http://localhost:8000");
    assertThat(result.getRecipients()).hasSize(1);
    final Recipient recipient = result.getRecipients().iterator().next();
    assertThat(recipient.getUrl()).isEqualTo("http://localhost:8001");
    assertThat(recipient.getKey()).isNotNull();
    assertThat(result.getParties()).hasSize(1);
    assertThat(result.getParties()).containsExactly(new Party("http://localhost:8001"));
}
Also used : Party(com.quorum.tessera.partyinfo.model.Party) Recipient(com.quorum.tessera.partyinfo.model.Recipient) PartyInfo(com.quorum.tessera.partyinfo.model.PartyInfo) Test(org.junit.Test)

Example 10 with Recipient

use of com.quorum.tessera.partyinfo.model.Recipient 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)

Aggregations

PartyInfo (com.quorum.tessera.partyinfo.model.PartyInfo)15 Recipient (com.quorum.tessera.partyinfo.model.Recipient)15 PublicKey (com.quorum.tessera.encryption.PublicKey)13 Entity (jakarta.ws.rs.client.Entity)12 Response (jakarta.ws.rs.core.Response)12 Test (org.junit.Test)12 PartyInfoParser (com.quorum.tessera.p2p.partyinfo.PartyInfoParser)7 Client (jakarta.ws.rs.client.Client)7 MediaType (jakarta.ws.rs.core.MediaType)7 java.util (java.util)7 Collectors (java.util.stream.Collectors)7 JsonObject (jakarta.json.JsonObject)6 Config (com.quorum.tessera.config.Config)5 EncryptorConfig (com.quorum.tessera.config.EncryptorConfig)5 ServerConfig (com.quorum.tessera.config.ServerConfig)5 ConfigKeyPair (com.quorum.tessera.config.keypairs.ConfigKeyPair)5 KeyEncryptor (com.quorum.tessera.config.keys.KeyEncryptor)5 KeyEncryptorFactory (com.quorum.tessera.config.keys.KeyEncryptorFactory)5 KeyDataUtil (com.quorum.tessera.config.util.KeyDataUtil)5 EncodedPayload (com.quorum.tessera.enclave.EncodedPayload)5