Search in sources :

Example 1 with RSocketAppPrincipal

use of com.alibaba.spring.boot.rsocket.broker.security.RSocketAppPrincipal in project alibaba-rsocket-broker by alibaba.

the class RSocketBrokerHandlerRegistryImpl method accept.

@Override
@NotNull
public Mono<RSocket> accept(@NotNull final ConnectionSetupPayload setupPayload, @NotNull final RSocket requesterSocket) {
    // parse setup payload
    RSocketCompositeMetadata compositeMetadata = null;
    AppMetadata appMetadata = null;
    String credentials = "";
    RSocketAppPrincipal principal = null;
    String errorMsg = null;
    try {
        compositeMetadata = RSocketCompositeMetadata.from(setupPayload.metadata());
        if (!authRequired) {
            // authentication not required
            principal = appNameBasedPrincipal("MockApp");
            credentials = UUID.randomUUID().toString();
        } else if (compositeMetadata.contains(RSocketMimeType.BearerToken)) {
            BearerTokenMetadata bearerTokenMetadata = BearerTokenMetadata.from(compositeMetadata.getMetadata(RSocketMimeType.BearerToken));
            credentials = new String(bearerTokenMetadata.getBearerToken());
            principal = authenticationService.auth("JWT", credentials);
        } else {
            // no jwt token supplied
            errorMsg = RsocketErrorCode.message("RST-500405");
        }
        // validate application information
        if (principal != null && compositeMetadata.contains(RSocketMimeType.Application)) {
            AppMetadata temp = AppMetadata.from(compositeMetadata.getMetadata(RSocketMimeType.Application));
            // App registration validation: app id: UUID and unique in server
            if (temp.getUuid() == null || temp.getUuid().isEmpty()) {
                temp.setUuid(UUID.randomUUID().toString());
            }
            String appId = temp.getUuid();
            // validate appId data format
            if (appId != null && appId.length() >= 32) {
                Integer instanceId = MurmurHash3.hash32(credentials + ":" + temp.getUuid());
                temp.setId(instanceId);
                // application instance not connected
                if (!routingSelector.containInstance(instanceId)) {
                    appMetadata = temp;
                    appMetadata.setConnectedAt(new Date());
                } else {
                    // application connected already
                    errorMsg = RsocketErrorCode.message("RST-500409");
                }
            } else {
                // illegal application id, appID should be UUID
                errorMsg = RsocketErrorCode.message("RST-500410", appId == null ? "" : appId);
            }
        }
        if (errorMsg == null) {
            // Security authentication
            if (appMetadata != null) {
                appMetadata.addMetadata("_orgs", String.join(",", principal.getOrganizations()));
                appMetadata.addMetadata("_roles", String.join(",", principal.getRoles()));
                appMetadata.addMetadata("_serviceAccounts", String.join(",", principal.getServiceAccounts()));
            } else {
                errorMsg = RsocketErrorCode.message("RST-500411");
            }
        }
    } catch (Exception e) {
        log.error(RsocketErrorCode.message("RST-500402"), e);
        errorMsg = RsocketErrorCode.message("RST-600500", e.getMessage());
    }
    // validate connection legal or not
    if (principal == null) {
        errorMsg = RsocketErrorCode.message("RST-500405");
    }
    if (errorMsg != null) {
        return returnRejectedRSocket(errorMsg, requesterSocket);
    }
    // create handler
    try {
        RSocketBrokerResponderHandler brokerResponderHandler = new RSocketBrokerResponderHandler(setupPayload, compositeMetadata, appMetadata, principal, requesterSocket, routingSelector, eventProcessor, this, serviceMeshInspector, getUpstreamRSocket());
        brokerResponderHandler.setFilterChain(rsocketFilterChain);
        brokerResponderHandler.setLocalReactiveServiceCaller(localReactiveServiceCaller);
        brokerResponderHandler.onClose().doOnTerminate(() -> onHandlerDisposed(brokerResponderHandler)).subscribeOn(Schedulers.parallel()).subscribe();
        // handler registration notify
        onHandlerRegistered(brokerResponderHandler);
        log.info(RsocketErrorCode.message("RST-500200", appMetadata.getName()));
        return Mono.just(brokerResponderHandler);
    } catch (Exception e) {
        log.error(RsocketErrorCode.message("RST-500406", e.getMessage()), e);
        return returnRejectedRSocket(RsocketErrorCode.message("RST-500406", e.getMessage()), requesterSocket);
    }
}
Also used : RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) BearerTokenMetadata(com.alibaba.rsocket.metadata.BearerTokenMetadata) AppMetadata(com.alibaba.rsocket.metadata.AppMetadata) RSocketAppPrincipal(com.alibaba.spring.boot.rsocket.broker.security.RSocketAppPrincipal) RejectedSetupException(io.rsocket.exceptions.RejectedSetupException) ApplicationErrorException(io.rsocket.exceptions.ApplicationErrorException) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with RSocketAppPrincipal

use of com.alibaba.spring.boot.rsocket.broker.security.RSocketAppPrincipal in project alibaba-rsocket-broker by alibaba.

the class RSocketRestApiController method handle.

@RequestMapping(value = "/{serviceName}/{method}", produces = { MediaType.APPLICATION_JSON_VALUE })
public Mono<ResponseEntity<String>> handle(@PathVariable("serviceName") String serviceName, @PathVariable("method") String method, @RequestParam(name = "group", required = false, defaultValue = "") String group, @RequestParam(name = "version", required = false, defaultValue = "") String version, @RequestBody(required = false) byte[] body, @RequestHeader(name = "X-Endpoint", required = false, defaultValue = "") String endpoint, @RequestHeader(name = "Authorization", required = false, defaultValue = "") String authorizationValue) {
    try {
        GSVRoutingMetadata routingMetadata = new GSVRoutingMetadata(group, serviceName, method, version);
        Integer serviceHashCode = routingMetadata.id();
        Integer targetHandlerId = routingSelector.findHandler(serviceHashCode);
        if (!endpoint.isEmpty() && endpoint.startsWith("id:")) {
            targetHandlerId = Integer.valueOf(endpoint.substring(3).trim());
        }
        return Optional.ofNullable(targetHandlerId).flatMap(handlerId -> Optional.ofNullable(handlerRegistry.findById(handlerId))).map(targetHandler -> {
            if (authRequired) {
                RSocketAppPrincipal principal = authAuthorizationValue(authorizationValue);
                if (principal == null || !serviceMeshInspector.isRequestAllowed(principal, routingMetadata.gsv(), targetHandler.getPrincipal())) {
                    return Mono.just(error(RsocketErrorCode.message("RST-900401", routingMetadata.gsv())));
                }
            }
            RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(routingMetadata, jsonMetaEncoding);
            ByteBuf bodyBuf = body == null ? EMPTY_BUFFER : Unpooled.wrappedBuffer(body);
            return targetHandler.requestResponse(DefaultPayload.create(bodyBuf, compositeMetadata.getContent())).map(payload -> {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.setCacheControl(CacheControl.noCache().getHeaderValue());
                return new ResponseEntity<>(payload.getDataUtf8(), headers, HttpStatus.OK);
            });
        }).orElseGet(() -> Mono.just(error(RsocketErrorCode.message("RST-900404", routingMetadata.gsv()))));
    } catch (Exception e) {
        return Mono.just(error(e.getMessage()));
    }
}
Also used : RSocketMimeType(com.alibaba.rsocket.metadata.RSocketMimeType) EMPTY_BUFFER(io.netty.buffer.Unpooled.EMPTY_BUFFER) org.springframework.http(org.springframework.http) RsocketErrorCode(com.alibaba.rsocket.observability.RsocketErrorCode) Autowired(org.springframework.beans.factory.annotation.Autowired) Mono(reactor.core.publisher.Mono) ServiceRoutingSelector(com.alibaba.spring.boot.rsocket.broker.route.ServiceRoutingSelector) RSocketAppPrincipal(com.alibaba.spring.boot.rsocket.broker.security.RSocketAppPrincipal) RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) RSocketBrokerHandlerRegistry(com.alibaba.spring.boot.rsocket.broker.responder.RSocketBrokerHandlerRegistry) Unpooled(io.netty.buffer.Unpooled) GSVRoutingMetadata(com.alibaba.rsocket.metadata.GSVRoutingMetadata) Value(org.springframework.beans.factory.annotation.Value) Nullable(org.jetbrains.annotations.Nullable) MessageMimeTypeMetadata(com.alibaba.rsocket.metadata.MessageMimeTypeMetadata) ByteBuf(io.netty.buffer.ByteBuf) AuthenticationService(com.alibaba.spring.boot.rsocket.broker.security.AuthenticationService) DefaultPayload(io.rsocket.util.DefaultPayload) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) Optional(java.util.Optional) ServiceMeshInspector(com.alibaba.spring.boot.rsocket.broker.route.ServiceMeshInspector) RSocketCompositeMetadata(com.alibaba.rsocket.metadata.RSocketCompositeMetadata) GSVRoutingMetadata(com.alibaba.rsocket.metadata.GSVRoutingMetadata) ByteBuf(io.netty.buffer.ByteBuf) RSocketAppPrincipal(com.alibaba.spring.boot.rsocket.broker.security.RSocketAppPrincipal)

Aggregations

RSocketCompositeMetadata (com.alibaba.rsocket.metadata.RSocketCompositeMetadata)2 RSocketAppPrincipal (com.alibaba.spring.boot.rsocket.broker.security.RSocketAppPrincipal)2 AppMetadata (com.alibaba.rsocket.metadata.AppMetadata)1 BearerTokenMetadata (com.alibaba.rsocket.metadata.BearerTokenMetadata)1 GSVRoutingMetadata (com.alibaba.rsocket.metadata.GSVRoutingMetadata)1 MessageMimeTypeMetadata (com.alibaba.rsocket.metadata.MessageMimeTypeMetadata)1 RSocketMimeType (com.alibaba.rsocket.metadata.RSocketMimeType)1 RsocketErrorCode (com.alibaba.rsocket.observability.RsocketErrorCode)1 RSocketBrokerHandlerRegistry (com.alibaba.spring.boot.rsocket.broker.responder.RSocketBrokerHandlerRegistry)1 ServiceMeshInspector (com.alibaba.spring.boot.rsocket.broker.route.ServiceMeshInspector)1 ServiceRoutingSelector (com.alibaba.spring.boot.rsocket.broker.route.ServiceRoutingSelector)1 AuthenticationService (com.alibaba.spring.boot.rsocket.broker.security.AuthenticationService)1 ByteBuf (io.netty.buffer.ByteBuf)1 Unpooled (io.netty.buffer.Unpooled)1 EMPTY_BUFFER (io.netty.buffer.Unpooled.EMPTY_BUFFER)1 ApplicationErrorException (io.rsocket.exceptions.ApplicationErrorException)1 RejectedSetupException (io.rsocket.exceptions.RejectedSetupException)1 DefaultPayload (io.rsocket.util.DefaultPayload)1 Optional (java.util.Optional)1 NotNull (org.jetbrains.annotations.NotNull)1