Search in sources :

Example 1 with WonMessageDirection

use of won.protocol.message.WonMessageDirection in project webofneeds by researchstudio-sat.

the class SocketTypeExtractor method process.

@Override
public void process(Exchange exchange) throws Exception {
    WonMessage msg = getMessageRequired(exchange);
    WonMessageDirection direction = getDirectionRequired(exchange);
    Optional<URI> socketURI = Optional.empty();
    if (direction.isFromExternal()) {
        socketURI = Optional.ofNullable(msg.getRecipientSocketURI());
    } else {
        socketURI = Optional.ofNullable(msg.getSenderSocketURI());
    }
    if (socketURI.isPresent()) {
        Optional<Socket> socket = socketService.getSocket(socketURI.get());
        if (socket.isPresent()) {
            putSocketTypeURI(exchange, socket.get().getTypeURI());
        } else {
            throw new NoSuchSocketException(socketURI.get());
        }
    }
}
Also used : NoSuchSocketException(won.protocol.exception.NoSuchSocketException) WonMessage(won.protocol.message.WonMessage) WonMessageDirection(won.protocol.message.WonMessageDirection) URI(java.net.URI) Socket(won.protocol.model.Socket)

Example 2 with WonMessageDirection

use of won.protocol.message.WonMessageDirection in project webofneeds by researchstudio-sat.

the class FailResponder method process.

@Override
public void process(final Exchange exchange) throws Exception {
    Exception exception = null;
    WonMessage originalMessage = null;
    try {
        originalMessage = (WonMessage) exchange.getIn().getHeader(WonCamelConstants.MESSAGE_HEADER);
        if (originalMessage == null) {
            // we didn't find the original message, so we can't send a response.
            // Log all we can so that we can start debugging the problem
            logger.warn("Could not obtain original message from camel header {} for error {}", new Object[] { WonCamelConstants.MESSAGE_HEADER, exchange.getProperty(Exchange.EXCEPTION_CAUGHT) });
            logger.warn("original exception:", exchange.getProperty(Exchange.EXCEPTION_CAUGHT));
            return;
        }
        exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
        String errormessage = null;
        if (exception != null) {
            errormessage = exception.getClass().getSimpleName() + ": " + exception.getMessage();
        }
        if (errormessage != null) {
            errormessage = String.format("An error occurred while processing message %s (type: %s): %s", originalMessage.getMessageURI(), originalMessage.getMessageType(), errormessage);
        }
        if (exception instanceof WonProtocolException) {
            if (logger.isDebugEnabled()) {
                if (exception != null) {
                    logger.debug("Caught protocol exception. Sending FailureResponse ", exception);
                }
            }
        } else {
            logger.warn("Caught unexpected exception while processing WON message {} (type:{}) : {} - sending FailureResponse", new Object[] { originalMessage.getMessageURI(), originalMessage.getMessageType(), errormessage });
            logger.warn("Full stacktrace: ", exception);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("original message: {}", RdfUtils.toString(Prefixer.setPrefixes(originalMessage.getCompleteDataset())));
        }
        if (WonMessageType.FAILURE_RESPONSE == originalMessage.getMessageType()) {
            // do not throw failures back and forth. If the original message is already a
            // failure message
            // that indicates a problem processing a failure message, log this and stop.
            logger.info("Encountered an error processing a FailureResponse. The FailureResponse is " + "logged at log level DEBUG. Its message URI is {}", originalMessage.getMessageURI(), exception);
            StringWriter sw = new StringWriter();
            RDFDataMgr.write(sw, Prefixer.setPrefixes(originalMessage.getCompleteDataset()), Lang.TRIG);
            logger.warn("FailureResponse to FailureResponse that raised the error:\n{}", sw.toString());
            return;
        }
        if (originalMessage.getMessageTypeRequired().isResponseMessage()) {
            // not sending a failure response for a response
            return;
        }
        WonMessageDirection direction = getDirectionRequired(exchange);
        ResponseBuilder responseBuilder = WonMessageBuilder.response();
        // about them by using them as the senderURI property in the response.
        if (originalMessage.getMessageTypeRequired().isConnectionSpecificMessage()) {
            Optional<Connection> con = connectionService.getConnectionForMessage(originalMessage, getDirectionRequired(exchange));
            if (con.isPresent()) {
                responseBuilder.fromConnection(con.get().getConnectionURI());
            }
        } else if (originalMessage.getMessageTypeRequired().isAtomSpecificMessage()) {
            responseBuilder.fromAtom(originalMessage.getAtomURIRequired());
        }
        WonMessage responseMessage = responseBuilder.respondingToMessage(originalMessage, getDirectionRequired(exchange)).failure().content().text(errormessage).build();
        responseMessage = signatureAddingWonMessageProcessor.signWithDefaultKey(responseMessage);
        putResponse(exchange, responseMessage);
        putMessageToSend(exchange, responseMessage);
        // extract the routing information
        URI atom = messageRoutingInfoService.recipientAtom(responseMessage).orElseThrow(() -> new IllegalArgumentException("Cannot dertermine recipient atom for response"));
        // the sender node is not there in the case of hint messages.
        Optional<URI> senderNode = messageRoutingInfoService.senderNode(responseMessage);
        URI recipientNode = messageRoutingInfoService.recipientNode(responseMessage).orElseThrow(() -> new IllegalArgumentException("Cannot dertermine node for response"));
        if (senderNode.isPresent()) {
            putSenderNodeURI(exchange, senderNode.get());
        }
        putRecipientNodeURI(exchange, recipientNode);
        putRecipientAtomURI(exchange, atom);
        // send the message
        if (direction.isFromExternal()) {
            messagingService.send(exchange, "direct:sendToNode");
        } else if (direction.isFromOwner()) {
            messagingService.send(exchange, "direct:sendToOwner");
        }
    } catch (Throwable t) {
        // something went wrong - we can't inform the sender of the message.
        // now:
        // 1. log the error we had here
        // 2. log the original error, otherwise it is swallowed completely
        logger.warn("Error in failure response handling!");
        URI originalMessageURI = null;
        try {
            originalMessageURI = originalMessage == null ? null : originalMessage.getMessageURI();
        } catch (Exception e) {
            logger.error("Error getting message URI from WonMessage");
        }
        if (exception != null && exception.getClass() != null) {
            logger.warn(String.format("Could not send FailureResponse for original Exception %s (message: %s) that occurred while processing message %s.", exception.getClass().getSimpleName(), exception.getMessage(), originalMessageURI), t);
            logger.warn("original error: ", exception);
        } else {
            logger.warn(String.format("Could not send FailureResponse to original message %s.", originalMessageURI), t);
            logger.warn("original error: ", exception);
        }
    }
}
Also used : WonProtocolException(won.protocol.exception.WonProtocolException) Connection(won.protocol.model.Connection) URI(java.net.URI) WonProtocolException(won.protocol.exception.WonProtocolException) StringWriter(java.io.StringWriter) WonMessage(won.protocol.message.WonMessage) ResponseBuilder(won.protocol.message.builder.ResponseBuilder) WonMessageDirection(won.protocol.message.WonMessageDirection)

Example 3 with WonMessageDirection

use of won.protocol.message.WonMessageDirection in project webofneeds by researchstudio-sat.

the class AclChecker method process.

@Override
public void process(Exchange exchange) throws Exception {
    URI recipientAtomUri = WonCamelHelper.getRecipientAtomURIRequired(exchange);
    WonMessage message = WonCamelHelper.getMessageRequired(exchange);
    if (message.getMessageType().isCreateAtom()) {
        // no checks required for a create message
        return;
    }
    if (message.getMessageType().isHintMessage()) {
        // no checks required for a hint message
        return;
    }
    URI signer = message.getSignerURIRequired();
    URI sender = message.getSenderAtomURIRequired();
    URI senderNode = message.getSenderNodeURIRequired();
    WonMessageDirection direction = WonCamelHelper.getDirectionRequired(exchange);
    if (direction.isFromExternal() || direction.isFromSystem()) {
        if (signer.equals(senderNode)) {
            // nodes are allowed to messages on behalf of an atom (for now)
            return;
        }
    }
    Atom atom = atomService.getAtomForMessageRequired(message, direction);
    Optional<Graph> aclGraph = atom.getAclGraph();
    if (aclGraph.isEmpty()) {
        // no checks if no acl present
        if (!sender.equals(signer)) {
            throw new IllegalMessageSignerException(String.format("%s must not be signer of %s message %s", signer, message.getMessageTypeRequired(), message.getMessageURIRequired()));
        }
        return;
    }
    boolean isMessageOnBehalf = false;
    URI requestor = sender;
    if (direction.isFromOwner()) {
        if (signer.equals(sender)) {
            // no checks if the owner is the signer
            return;
        } else {
            isMessageOnBehalf = true;
            requestor = signer;
        }
    }
    OperationRequest operationRequest = OperationRequest.builder().setReqAtom(atom.getAtomURI()).setReqAtomState(AuthUtils.toAuthAtomState(atom.getState())).setRequestor(requestor).build();
    if (message.getMessageType().isConnectionSpecificMessage()) {
        if (direction.isFromOwner() || direction.isFromSystem()) {
            Optional<Socket> s = socketService.getSocket(message.getSenderSocketURIRequired());
            operationRequest.setReqSocketType(s.get().getTypeURI());
            operationRequest.setReqSocket(s.get().getSocketURI());
        } else if (direction.isFromExternal()) {
            Optional<Socket> s = socketService.getSocket(message.getRecipientSocketURIRequired());
            operationRequest.setReqSocketType(s.get().getTypeURI());
            operationRequest.setReqSocket(s.get().getSocketURI());
        }
    } else {
        operationRequest.setReqPosition(POSITION_ROOT);
    }
    Optional<Connection> con = WonCamelHelper.getConnection(exchange, connectionService);
    if (con.isPresent()) {
        operationRequest.setReqPosition(POSITION_CONNECTION);
        Connection c = con.get();
        operationRequest.setReqConnection(c.getConnectionURI());
        operationRequest.setReqConnectionTargetAtom(c.getTargetAtomURI());
        operationRequest.setReqConnectionState(AuthUtils.toAuthConnectionState(c.getState()));
        // we already set these values, but now that we know we have a connection, make
        // sure these values match the connection's
        operationRequest.setReqSocketType(c.getTypeURI());
        operationRequest.setReqSocket(c.getSocketURI());
    } else {
        operationRequest.setReqPosition(POSITION_SOCKET);
    }
    if (isMessageOnBehalf) {
        operationRequest.setOperationMessageOperationExpression(MessageOperationExpression.builder().addMessageOnBehalfsMessageType(AuthUtils.toAuthMessageType(message.getMessageType())).build());
    } else {
        operationRequest.setOperationMessageOperationExpression(MessageOperationExpression.builder().addMessageTosMessageType(AuthUtils.toAuthMessageType(message.getMessageType())).build());
    }
    WonAclEvaluator evaluator = wonAclEvaluatorFactory.create(aclGraph.get());
    if (message.getMessageType().isReplace()) {
    // decision for replace messages is deferred to where replacement actually
    // happens
    } else {
        AclEvalResult result = evaluator.decide(operationRequest);
        if (DecisionValue.ACCESS_DENIED.equals(result.getDecision())) {
            throw new ForbiddenMessageException(String.format("Message not allowed"));
        }
    }
    WonCamelHelper.putWonAclEvaluator(exchange, evaluator);
    WonCamelHelper.putWonAclOperationRequest(exchange, operationRequest);
}
Also used : Optional(java.util.Optional) OperationRequest(won.auth.model.OperationRequest) Connection(won.protocol.model.Connection) WonAclEvaluator(won.auth.WonAclEvaluator) AclEvalResult(won.auth.model.AclEvalResult) URI(java.net.URI) Atom(won.protocol.model.Atom) Graph(org.apache.jena.graph.Graph) ForbiddenMessageException(won.protocol.exception.ForbiddenMessageException) WonMessage(won.protocol.message.WonMessage) IllegalMessageSignerException(won.protocol.exception.IllegalMessageSignerException) WonMessageDirection(won.protocol.message.WonMessageDirection) Socket(won.protocol.model.Socket)

Example 4 with WonMessageDirection

use of won.protocol.message.WonMessageDirection in project webofneeds by researchstudio-sat.

the class WonCamelHelper method getConnection.

// // connection
public static Optional<Connection> getConnection(Exchange exchange, ConnectionService connectionService) {
    Objects.requireNonNull(exchange);
    Objects.requireNonNull(connectionService);
    Connection con = (Connection) exchange.getIn().getHeader(WonCamelConstants.CONNECTION_HEADER);
    if (con != null) {
        return Optional.of(con);
    }
    Optional<WonMessage> msg = getMessage(exchange);
    Optional<WonMessageDirection> direction = getDirection(exchange);
    if (msg.isPresent() && direction.isPresent()) {
        return connectionService.getConnectionForMessage(msg.get(), direction.get());
    }
    return Optional.empty();
}
Also used : WonMessage(won.protocol.message.WonMessage) Connection(won.protocol.model.Connection) WonMessageDirection(won.protocol.message.WonMessageDirection)

Example 5 with WonMessageDirection

use of won.protocol.message.WonMessageDirection in project webofneeds by researchstudio-sat.

the class UriConsistencyCheckingWonMessageProcessor method checkDirection.

private void checkDirection(final WonMessage message, final URI ownNode) {
    WonMessageDirection direction = message.getEnvelopeType();
    URI receiverNode = message.getReceiverNodeURI();
    URI senderNode = message.getSenderNodeURI();
    URI node;
    switch(direction) {
        case FROM_EXTERNAL:
            // my node should be a receiver node
            if (!ownNode.equals(receiverNode)) {
                throw new UriNodePathException(receiverNode + " is expected to be " + ownNode);
            }
            break;
        case FROM_OWNER:
            // my node should be a sender node
            if (!ownNode.equals(senderNode)) {
                throw new UriNodePathException(senderNode + " is expected to be " + ownNode);
            }
            break;
        case FROM_SYSTEM:
            // my node should be a sender node
            if (!ownNode.equals(senderNode)) {
                throw new UriNodePathException(senderNode + " is expected to be " + ownNode);
            }
            break;
    }
}
Also used : WonMessageDirection(won.protocol.message.WonMessageDirection) URI(java.net.URI) UriNodePathException(won.protocol.message.processor.exception.UriNodePathException)

Aggregations

WonMessageDirection (won.protocol.message.WonMessageDirection)11 URI (java.net.URI)10 WonMessage (won.protocol.message.WonMessage)8 Connection (won.protocol.model.Connection)3 StopWatch (org.springframework.util.StopWatch)2 Socket (won.protocol.model.Socket)2 StringWriter (java.io.StringWriter)1 Optional (java.util.Optional)1 Graph (org.apache.jena.graph.Graph)1 WonAclEvaluator (won.auth.WonAclEvaluator)1 AclEvalResult (won.auth.model.AclEvalResult)1 OperationRequest (won.auth.model.OperationRequest)1 ForbiddenMessageException (won.protocol.exception.ForbiddenMessageException)1 IllegalMessageSignerException (won.protocol.exception.IllegalMessageSignerException)1 NoSuchSocketException (won.protocol.exception.NoSuchSocketException)1 WonMessageNotWellFormedException (won.protocol.exception.WonMessageNotWellFormedException)1 WonMessageProcessingException (won.protocol.exception.WonMessageProcessingException)1 WonProtocolException (won.protocol.exception.WonProtocolException)1 EnvelopePropertyCheckResult (won.protocol.message.WonMessage.EnvelopePropertyCheckResult)1 WonMessageType (won.protocol.message.WonMessageType)1