Search in sources :

Example 1 with CompositeChannelCredentials

use of io.grpc.CompositeChannelCredentials in project grpc-java by grpc.

the class ProtocolNegotiators method from.

public static FromChannelCredentialsResult from(ChannelCredentials creds) {
    if (creds instanceof TlsChannelCredentials) {
        TlsChannelCredentials tlsCreds = (TlsChannelCredentials) creds;
        Set<TlsChannelCredentials.Feature> incomprehensible = tlsCreds.incomprehensible(understoodTlsFeatures);
        if (!incomprehensible.isEmpty()) {
            return FromChannelCredentialsResult.error("TLS features not understood: " + incomprehensible);
        }
        SslContextBuilder builder = GrpcSslContexts.forClient();
        if (tlsCreds.getKeyManagers() != null) {
            builder.keyManager(new FixedKeyManagerFactory(tlsCreds.getKeyManagers()));
        } else if (tlsCreds.getPrivateKey() != null) {
            builder.keyManager(new ByteArrayInputStream(tlsCreds.getCertificateChain()), new ByteArrayInputStream(tlsCreds.getPrivateKey()), tlsCreds.getPrivateKeyPassword());
        }
        if (tlsCreds.getTrustManagers() != null) {
            builder.trustManager(new FixedTrustManagerFactory(tlsCreds.getTrustManagers()));
        } else if (tlsCreds.getRootCertificates() != null) {
            builder.trustManager(new ByteArrayInputStream(tlsCreds.getRootCertificates()));
        }
        // else use system default
        try {
            return FromChannelCredentialsResult.negotiator(tlsClientFactory(builder.build()));
        } catch (SSLException ex) {
            log.log(Level.FINE, "Exception building SslContext", ex);
            return FromChannelCredentialsResult.error("Unable to create SslContext: " + ex.getMessage());
        }
    } else if (creds instanceof InsecureChannelCredentials) {
        return FromChannelCredentialsResult.negotiator(plaintextClientFactory());
    } else if (creds instanceof CompositeChannelCredentials) {
        CompositeChannelCredentials compCreds = (CompositeChannelCredentials) creds;
        return from(compCreds.getChannelCredentials()).withCallCredentials(compCreds.getCallCredentials());
    } else if (creds instanceof NettyChannelCredentials) {
        NettyChannelCredentials nettyCreds = (NettyChannelCredentials) creds;
        return FromChannelCredentialsResult.negotiator(nettyCreds.getNegotiator());
    } else if (creds instanceof ChoiceChannelCredentials) {
        ChoiceChannelCredentials choiceCreds = (ChoiceChannelCredentials) creds;
        StringBuilder error = new StringBuilder();
        for (ChannelCredentials innerCreds : choiceCreds.getCredentialsList()) {
            FromChannelCredentialsResult result = from(innerCreds);
            if (result.error == null) {
                return result;
            }
            error.append(", ");
            error.append(result.error);
        }
        return FromChannelCredentialsResult.error(error.substring(2));
    } else {
        return FromChannelCredentialsResult.error("Unsupported credential type: " + creds.getClass().getName());
    }
}
Also used : CompositeChannelCredentials(io.grpc.CompositeChannelCredentials) InsecureChannelCredentials(io.grpc.InsecureChannelCredentials) TlsChannelCredentials(io.grpc.TlsChannelCredentials) SSLException(javax.net.ssl.SSLException) ByteArrayInputStream(java.io.ByteArrayInputStream) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) ChoiceChannelCredentials(io.grpc.ChoiceChannelCredentials) TlsChannelCredentials(io.grpc.TlsChannelCredentials) InsecureChannelCredentials(io.grpc.InsecureChannelCredentials) CompositeChannelCredentials(io.grpc.CompositeChannelCredentials) ChannelCredentials(io.grpc.ChannelCredentials) ChoiceChannelCredentials(io.grpc.ChoiceChannelCredentials)

Example 2 with CompositeChannelCredentials

use of io.grpc.CompositeChannelCredentials in project grpc-java by grpc.

the class ManagedChannelImplTest method oobChannelWithOobChannelCredsHasChannelCallCredentials.

@Test
public void oobChannelWithOobChannelCredsHasChannelCallCredentials() {
    Metadata.Key<String> metadataKey = Metadata.Key.of("token", Metadata.ASCII_STRING_MARSHALLER);
    String channelCredValue = "channel-provided call cred";
    when(mockTransportFactory.swapChannelCredentials(any(CompositeChannelCredentials.class))).thenAnswer(new Answer<SwapChannelCredentialsResult>() {

        @Override
        public SwapChannelCredentialsResult answer(InvocationOnMock invocation) {
            CompositeChannelCredentials c = invocation.getArgument(0, CompositeChannelCredentials.class);
            return new SwapChannelCredentialsResult(mockTransportFactory, c.getCallCredentials());
        }
    });
    channelBuilder = new ManagedChannelImplBuilder(TARGET, InsecureChannelCredentials.create(), new FakeCallCredentials(metadataKey, channelCredValue), new UnsupportedClientTransportFactoryBuilder(), new FixedPortProvider(DEFAULT_PORT));
    channelBuilder.disableRetry();
    configureBuilder(channelBuilder);
    createChannel();
    // Verify that the normal channel has call creds, to validate configuration
    Subchannel subchannel = createSubchannelSafely(helper, addressGroup, Attributes.EMPTY, subchannelStateListener);
    requestConnectionSafely(helper, subchannel);
    MockClientTransportInfo transportInfo = transports.poll();
    transportInfo.listener.transportReady();
    when(mockPicker.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel));
    updateBalancingStateSafely(helper, READY, mockPicker);
    String callCredValue = "per-RPC call cred";
    CallOptions callOptions = CallOptions.DEFAULT.withCallCredentials(new FakeCallCredentials(metadataKey, callCredValue));
    Metadata headers = new Metadata();
    ClientCall<String, Integer> call = channel.newCall(method, callOptions);
    call.start(mockCallListener, headers);
    verify(transportInfo.transport).newStream(same(method), same(headers), same(callOptions), ArgumentMatchers.<ClientStreamTracer[]>any());
    assertThat(headers.getAll(metadataKey)).containsExactly(channelCredValue, callCredValue).inOrder();
    // Verify that resolving oob channel with oob channel creds provides call creds
    String oobChannelCredValue = "oob-channel-provided call cred";
    ChannelCredentials oobChannelCreds = CompositeChannelCredentials.create(InsecureChannelCredentials.create(), new FakeCallCredentials(metadataKey, oobChannelCredValue));
    ManagedChannel oob = helper.createResolvingOobChannelBuilder("fake://oobauthority/", oobChannelCreds).nameResolverFactory(new FakeNameResolverFactory.Builder(URI.create("fake://oobauthority/")).build()).defaultLoadBalancingPolicy(MOCK_POLICY_NAME).idleTimeout(ManagedChannelImplBuilder.IDLE_MODE_MAX_TIMEOUT_DAYS, TimeUnit.DAYS).disableRetry().build();
    oob.getState(true);
    ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(Helper.class);
    verify(mockLoadBalancerProvider, times(2)).newLoadBalancer(helperCaptor.capture());
    Helper oobHelper = helperCaptor.getValue();
    subchannel = createSubchannelSafely(oobHelper, addressGroup, Attributes.EMPTY, subchannelStateListener);
    requestConnectionSafely(oobHelper, subchannel);
    transportInfo = transports.poll();
    transportInfo.listener.transportReady();
    SubchannelPicker mockPicker2 = mock(SubchannelPicker.class);
    when(mockPicker2.pickSubchannel(any(PickSubchannelArgs.class))).thenReturn(PickResult.withSubchannel(subchannel));
    updateBalancingStateSafely(oobHelper, READY, mockPicker2);
    headers = new Metadata();
    call = oob.newCall(method, callOptions);
    call.start(mockCallListener2, headers);
    // CallOptions may contain StreamTracerFactory for census that is added by default.
    verify(transportInfo.transport).newStream(same(method), same(headers), any(CallOptions.class), ArgumentMatchers.<ClientStreamTracer[]>any());
    assertThat(headers.getAll(metadataKey)).containsExactly(oobChannelCredValue, callCredValue).inOrder();
    oob.shutdownNow();
}
Also used : ClientStreamTracer(io.grpc.ClientStreamTracer) UnsupportedClientTransportFactoryBuilder(io.grpc.internal.ManagedChannelImplBuilder.UnsupportedClientTransportFactoryBuilder) ClientTransportFactoryBuilder(io.grpc.internal.ManagedChannelImplBuilder.ClientTransportFactoryBuilder) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) Helper(io.grpc.LoadBalancer.Helper) InsecureChannelCredentials(io.grpc.InsecureChannelCredentials) ChannelCredentials(io.grpc.ChannelCredentials) CompositeChannelCredentials(io.grpc.CompositeChannelCredentials) ManagedChannel(io.grpc.ManagedChannel) PickSubchannelArgs(io.grpc.LoadBalancer.PickSubchannelArgs) UnsupportedClientTransportFactoryBuilder(io.grpc.internal.ManagedChannelImplBuilder.UnsupportedClientTransportFactoryBuilder) CompositeChannelCredentials(io.grpc.CompositeChannelCredentials) SwapChannelCredentialsResult(io.grpc.internal.ClientTransportFactory.SwapChannelCredentialsResult) MockClientTransportInfo(io.grpc.internal.TestUtils.MockClientTransportInfo) SubchannelPicker(io.grpc.LoadBalancer.SubchannelPicker) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ForwardingSubchannel(io.grpc.util.ForwardingSubchannel) Subchannel(io.grpc.LoadBalancer.Subchannel) FixedPortProvider(io.grpc.internal.ManagedChannelImplBuilder.FixedPortProvider) Test(org.junit.Test)

Example 3 with CompositeChannelCredentials

use of io.grpc.CompositeChannelCredentials in project grpc-java by grpc.

the class OkHttpChannelBuilder method sslSocketFactoryFrom.

static SslSocketFactoryResult sslSocketFactoryFrom(ChannelCredentials creds) {
    if (creds instanceof TlsChannelCredentials) {
        TlsChannelCredentials tlsCreds = (TlsChannelCredentials) creds;
        Set<TlsChannelCredentials.Feature> incomprehensible = tlsCreds.incomprehensible(understoodTlsFeatures);
        if (!incomprehensible.isEmpty()) {
            return SslSocketFactoryResult.error("TLS features not understood: " + incomprehensible);
        }
        KeyManager[] km = null;
        if (tlsCreds.getKeyManagers() != null) {
            km = tlsCreds.getKeyManagers().toArray(new KeyManager[0]);
        } else if (tlsCreds.getPrivateKey() != null) {
            return SslSocketFactoryResult.error("byte[]-based private key unsupported. Use KeyManager");
        }
        // else don't have a client cert
        TrustManager[] tm = null;
        if (tlsCreds.getTrustManagers() != null) {
            tm = tlsCreds.getTrustManagers().toArray(new TrustManager[0]);
        } else if (tlsCreds.getRootCertificates() != null) {
            try {
                tm = createTrustManager(tlsCreds.getRootCertificates());
            } catch (GeneralSecurityException gse) {
                log.log(Level.FINE, "Exception loading root certificates from credential", gse);
                return SslSocketFactoryResult.error("Unable to load root certificates: " + gse.getMessage());
            }
        }
        // else use system default
        SSLContext sslContext;
        try {
            sslContext = SSLContext.getInstance("TLS", Platform.get().getProvider());
            sslContext.init(km, tm, null);
        } catch (GeneralSecurityException gse) {
            throw new RuntimeException("TLS Provider failure", gse);
        }
        return SslSocketFactoryResult.factory(sslContext.getSocketFactory());
    } else if (creds instanceof InsecureChannelCredentials) {
        return SslSocketFactoryResult.plaintext();
    } else if (creds instanceof CompositeChannelCredentials) {
        CompositeChannelCredentials compCreds = (CompositeChannelCredentials) creds;
        return sslSocketFactoryFrom(compCreds.getChannelCredentials()).withCallCredentials(compCreds.getCallCredentials());
    } else if (creds instanceof SslSocketFactoryChannelCredentials.ChannelCredentials) {
        SslSocketFactoryChannelCredentials.ChannelCredentials factoryCreds = (SslSocketFactoryChannelCredentials.ChannelCredentials) creds;
        return SslSocketFactoryResult.factory(factoryCreds.getFactory());
    } else if (creds instanceof ChoiceChannelCredentials) {
        ChoiceChannelCredentials choiceCreds = (ChoiceChannelCredentials) creds;
        StringBuilder error = new StringBuilder();
        for (ChannelCredentials innerCreds : choiceCreds.getCredentialsList()) {
            SslSocketFactoryResult result = sslSocketFactoryFrom(innerCreds);
            if (result.error == null) {
                return result;
            }
            error.append(", ");
            error.append(result.error);
        }
        return SslSocketFactoryResult.error(error.substring(2));
    } else {
        return SslSocketFactoryResult.error("Unsupported credential type: " + creds.getClass().getName());
    }
}
Also used : CompositeChannelCredentials(io.grpc.CompositeChannelCredentials) InsecureChannelCredentials(io.grpc.InsecureChannelCredentials) TlsChannelCredentials(io.grpc.TlsChannelCredentials) GeneralSecurityException(java.security.GeneralSecurityException) SSLContext(javax.net.ssl.SSLContext) TrustManager(javax.net.ssl.TrustManager) ChoiceChannelCredentials(io.grpc.ChoiceChannelCredentials) TlsChannelCredentials(io.grpc.TlsChannelCredentials) InsecureChannelCredentials(io.grpc.InsecureChannelCredentials) CompositeChannelCredentials(io.grpc.CompositeChannelCredentials) ChannelCredentials(io.grpc.ChannelCredentials) KeyManager(javax.net.ssl.KeyManager) ChoiceChannelCredentials(io.grpc.ChoiceChannelCredentials)

Aggregations

ChannelCredentials (io.grpc.ChannelCredentials)3 CompositeChannelCredentials (io.grpc.CompositeChannelCredentials)3 InsecureChannelCredentials (io.grpc.InsecureChannelCredentials)3 ChoiceChannelCredentials (io.grpc.ChoiceChannelCredentials)2 TlsChannelCredentials (io.grpc.TlsChannelCredentials)2 CallOptions (io.grpc.CallOptions)1 ClientStreamTracer (io.grpc.ClientStreamTracer)1 Helper (io.grpc.LoadBalancer.Helper)1 PickSubchannelArgs (io.grpc.LoadBalancer.PickSubchannelArgs)1 Subchannel (io.grpc.LoadBalancer.Subchannel)1 SubchannelPicker (io.grpc.LoadBalancer.SubchannelPicker)1 ManagedChannel (io.grpc.ManagedChannel)1 Metadata (io.grpc.Metadata)1 SwapChannelCredentialsResult (io.grpc.internal.ClientTransportFactory.SwapChannelCredentialsResult)1 ClientTransportFactoryBuilder (io.grpc.internal.ManagedChannelImplBuilder.ClientTransportFactoryBuilder)1 FixedPortProvider (io.grpc.internal.ManagedChannelImplBuilder.FixedPortProvider)1 UnsupportedClientTransportFactoryBuilder (io.grpc.internal.ManagedChannelImplBuilder.UnsupportedClientTransportFactoryBuilder)1 MockClientTransportInfo (io.grpc.internal.TestUtils.MockClientTransportInfo)1 ForwardingSubchannel (io.grpc.util.ForwardingSubchannel)1 SslContextBuilder (io.netty.handler.ssl.SslContextBuilder)1