Esempio n. 1
0
        public void MetadataCredentials()
        {
            var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(),
                                                               CallCredentials.FromInterceptor(asyncAuthInterceptor));

            channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
            client  = new TestService.TestServiceClient(channel);

            client.UnaryCall(new SimpleRequest {
            });
        }
Esempio n. 2
0
        public void MetadataCredentials_InterceptorLeavesMetadataEmpty()
        {
            var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(),
                                                               CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => TaskUtils.CompletedTask)));

            channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
            client  = new TestService.TestServiceClient(channel);

            var ex = Assert.Throws <RpcException>(() => client.UnaryCall(new SimpleRequest {
            }));

            // StatusCode.Unknown as the server-side handler throws an exception after not receiving the authorization header.
            Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode);
        }
        public void MetadataCredentials_InterceptorLeavesMetadataEmpty()
        {
            serviceImpl.UnaryCallHandler = (req, context) =>
            {
                var authHeaderCount = context.RequestHeaders.Count((entry) => entry.Key == "authorization");
                Assert.AreEqual(0, authHeaderCount);
                return(Task.FromResult(new SimpleResponse()));
            };
            var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(),
                                                               CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => TaskUtils.CompletedTask)));

            channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
            client  = new TestService.TestServiceClient(channel);
            client.UnaryCall(new SimpleRequest {
            });
        }
        public void Init()
        {
            serviceImpl = new FakeTestService();
            // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755
            server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) })
            {
                Services = { TestService.BindService(serviceImpl) },
                Ports    = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
            };
            server.Start();

            options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };
        }
Esempio n. 5
0
        public void MetadataCredentials_InterceptorThrows()
        {
            var callCredentials = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) =>
            {
                throw new Exception("Auth interceptor throws");
            }));
            var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(), callCredentials);

            channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
            client  = new TestService.TestServiceClient(channel);

            var ex = Assert.Throws <RpcException>(() => client.UnaryCall(new SimpleRequest {
            }));

            Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
        }
Esempio n. 6
0
        /// <summary>
        /// Creates a started server runner.
        /// </summary>
        public static IServerRunner CreateStarted(ServerConfig config)
        {
            Grpc.Core.Utils.Preconditions.CheckArgument(config.ServerType == ServerType.ASYNC_SERVER);
            var credentials = config.SecurityParams != null?TestCredentials.CreateSslServerCredentials() : ServerCredentials.Insecure;

            // TODO: qps_driver needs to setup payload properly...
            int responseSize = config.PayloadConfig != null ? config.PayloadConfig.SimpleParams.RespSize : 0;
            var server       = new Server
            {
                Services = { BenchmarkService.BindService(new BenchmarkServiceImpl(responseSize)) },
                Ports    = { new ServerPort(config.Host, config.Port, credentials) }
            };

            server.Start();
            return(new ServerRunnerImpl(server));
        }
Esempio n. 7
0
        public void Init()
        {
            server = new Server();
            server.AddServiceDefinition(TestService.BindService(new TestServiceImpl()));
            int port = server.AddListeningPort(host, Server.PickUnusedPort, TestCredentials.CreateTestServerCredentials());

            server.Start();

            var options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

            channel = new Channel(host, port, TestCredentials.CreateTestClientCredentials(true), options);
            client  = TestService.NewClient(channel);
        }
Esempio n. 8
0
        public void Init()
        {
            GrpcEnvironment.Initialize();

            server = new Server();
            server.AddServiceDefinition(TestServiceGrpc.BindService(new TestServiceImpl()));
            int port = server.AddListeningPort(host + ":0", TestCredentials.CreateTestServerCredentials());

            server.Start();

            var channelArgs = ChannelArgs.CreateBuilder()
                              .AddString(ChannelArgs.SslTargetNameOverrideKey, TestCredentials.DefaultHostOverride).Build();

            channel = new Channel(host + ":" + port, TestCredentials.CreateTestClientCredentials(true), channelArgs);
            client  = TestServiceGrpc.NewStub(channel);
        }
Esempio n. 9
0
        /// <summary>
        /// Creates a started server runner.
        /// </summary>
        public static IServerRunner CreateStarted(ServerConfig config)
        {
            Logger.Debug("ServerConfig: {0}", config);
            var credentials = config.SecurityParams != null?TestCredentials.CreateSslServerCredentials() : ServerCredentials.Insecure;

            if (config.AsyncServerThreads != 0)
            {
                Logger.Warning("ServerConfig.AsyncServerThreads is not supported for C#. Ignoring the value");
            }
            if (config.CoreLimit != 0)
            {
                Logger.Warning("ServerConfig.CoreLimit is not supported for C#. Ignoring the value");
            }
            if (config.CoreList.Count > 0)
            {
                Logger.Warning("ServerConfig.CoreList is not supported for C#. Ignoring the value");
            }

            ServerServiceDefinition service = null;

            if (config.ServerType == ServerType.AsyncServer)
            {
                GrpcPreconditions.CheckArgument(config.PayloadConfig == null,
                                                "ServerConfig.PayloadConfig shouldn't be set for BenchmarkService based server.");
                service = BenchmarkService.BindService(new BenchmarkServiceImpl());
            }
            else if (config.ServerType == ServerType.AsyncGenericServer)
            {
                var genericService = new GenericServiceImpl(config.PayloadConfig.BytebufParams.RespSize);
                service = GenericService.BindHandler(genericService.StreamingCall);
            }
            else
            {
                throw new ArgumentException("Unsupported ServerType");
            }

            var channelOptions = new List <ChannelOption>(config.ChannelArgs.Select((arg) => arg.ToChannelOption()));
            var server         = new Server(channelOptions)
            {
                Services = { service },
                Ports    = { new ServerPort("[::]", config.Port, credentials) }
            };

            server.Start();
            return(new ServerRunnerImpl(server));
        }
Esempio n. 10
0
        public void Init()
        {
            server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports    = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
            };
            server.Start();

            var options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };
            int port = server.Ports.Single().BoundPort;

            channel = new Channel(Host, port, TestCredentials.CreateSslCredentials(), options);
            client  = TestService.NewClient(channel);
        }
        public void Init()
        {
            // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755
            server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) })
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports    = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
            };
            server.Start();

            var options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };
            int port = server.Ports.Single().BoundPort;

            channel = new Channel(Host, port, TestCredentials.CreateSslCredentials(), options);
            client  = new TestService.TestServiceClient(channel);
        }
Esempio n. 12
0
        public void Init()
        {
            server = new Server
            {
                Services = { TestService.BindService(new FakeTestService()) },
                Ports    = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
            };
            server.Start();

            options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

            asyncAuthInterceptor = new AsyncAuthInterceptor(async(context, metadata) =>
            {
                await Task.Delay(100).ConfigureAwait(false);  // make sure the operation is asynchronous.
                metadata.Add("authorization", "SECRET_TOKEN");
            });
        }
Esempio n. 13
0
        public void Init()
        {
            // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755
            server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) })
            {
                Services = { TestService.BindService(new FakeTestService()) },
                Ports    = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
            };
            server.Start();

            options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

            asyncAuthInterceptor = new AsyncAuthInterceptor(async(context, metadata) =>
            {
                await Task.Delay(100).ConfigureAwait(false);  // make sure the operation is asynchronous.
                metadata.Add("authorization", "SECRET_TOKEN");
            });
        }
Esempio n. 14
0
        private async Task <ChannelCredentials> CreateCredentialsAsync()
        {
            var credentials = options.UseTls.Value ? TestCredentials.CreateTestClientCredentials(options.UseTestCa.Value) : ChannelCredentials.Insecure;

            if (options.TestCase == "jwt_token_creds")
            {
                var googleCredential = await GoogleCredential.GetApplicationDefaultAsync();

                Assert.IsTrue(googleCredential.IsCreateScopedRequired);
                credentials = ChannelCredentials.Create(credentials, googleCredential.ToGrpcCredentials());
            }

            if (options.TestCase == "compute_engine_creds")
            {
                var googleCredential = await GoogleCredential.GetApplicationDefaultAsync();

                Assert.IsFalse(googleCredential.IsCreateScopedRequired);
                credentials = ChannelCredentials.Create(credentials, googleCredential.ToGrpcCredentials());
            }
            return(credentials);
        }
Esempio n. 15
0
        private void Run()
        {
            GrpcEnvironment.Initialize();

            Credentials credentials = null;

            if (options.useTls)
            {
                credentials = TestCredentials.CreateTestClientCredentials(options.useTestCa);
            }

            List <ChannelOption> channelOptions = null;

            if (!string.IsNullOrEmpty(options.serverHostOverride))
            {
                channelOptions = new List <ChannelOption>
                {
                    new ChannelOption(ChannelOptions.SslTargetNameOverride, options.serverHostOverride)
                };
            }

            using (Channel channel = new Channel(options.serverHost, options.serverPort.Value, credentials, channelOptions))
            {
                var stubConfig = StubConfiguration.Default;
                if (options.testCase == "service_account_creds" || options.testCase == "compute_engine_creds")
                {
                    var credential = GoogleCredential.GetApplicationDefault();
                    if (credential.IsCreateScopedRequired)
                    {
                        credential = credential.CreateScoped(new[] { AuthScope });
                    }
                    stubConfig = new StubConfiguration(OAuth2InterceptorFactory.Create(credential));
                }

                TestService.ITestServiceClient client = new TestService.TestServiceClient(channel, stubConfig);
                RunTestCase(options.testCase, client);
            }

            GrpcEnvironment.Shutdown();
        }
Esempio n. 16
0
        /// <summary>
        /// Creates a started client runner.
        /// </summary>
        public static IClientRunner CreateStarted(ClientConfig config)
        {
            string target = config.ServerTargets.Single();

            Grpc.Core.Utils.Preconditions.CheckArgument(config.LoadParams.LoadCase == LoadParams.LoadOneofCase.ClosedLoop);

            var credentials = config.SecurityParams != null?TestCredentials.CreateSslCredentials() : ChannelCredentials.Insecure;

            var channel = new Channel(target, credentials);

            switch (config.RpcType)
            {
            case RpcType.UNARY:
                return(new SyncUnaryClientRunner(channel,
                                                 config.PayloadConfig.SimpleParams.ReqSize,
                                                 config.HistogramParams));

            case RpcType.STREAMING:
            default:
                throw new ArgumentException("Unsupported RpcType.");
            }
        }
        public async Task MetadataCredentials_ComposedPerCall()
        {
            channel = new Channel(Host, server.Ports.Single().BoundPort, TestCredentials.CreateSslCredentials(), options);
            var client = new TestService.TestServiceClient(channel);
            var first  = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                metadata.Add("first_authorization", "FIRST_SECRET_TOKEN");
                return(TaskUtils.CompletedTask);
            }));
            var second = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                metadata.Add("second_authorization", "SECOND_SECRET_TOKEN");
                return(TaskUtils.CompletedTask);
            }));
            var third = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                metadata.Add("third_authorization", "THIRD_SECRET_TOKEN");
                return(TaskUtils.CompletedTask);
            }));
            var call = client.StreamingOutputCall(new StreamingOutputCallRequest {
            },
                                                  new CallOptions(credentials: CallCredentials.Compose(first, second, third)));

            Assert.IsTrue(await call.ResponseStream.MoveNext());
            Assert.IsFalse(await call.ResponseStream.MoveNext());
        }
Esempio n. 18
0
        private void Run()
        {
            var server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) }
            };

            string host = "0.0.0.0";
            int    port = options.Port;

            if (options.UseTls.Value)
            {
                server.Ports.Add(host, port, TestCredentials.CreateSslServerCredentials());
            }
            else
            {
                server.Ports.Add(host, options.Port, ServerCredentials.Insecure);
            }
            Console.WriteLine("Running server on " + string.Format("{0}:{1}", host, port));
            server.Start();

            server.ShutdownTask.Wait();
        }
        public void MetadataCredentials_PerCall()
        {
            serviceImpl.UnaryCallHandler = (req, context) =>
            {
                var authToken = context.RequestHeaders.First((entry) => entry.Key == "authorization").Value;
                Assert.AreEqual("SECRET_TOKEN", authToken);
                return(Task.FromResult(new SimpleResponse()));
            };

            var asyncAuthInterceptor = new AsyncAuthInterceptor(async(context, metadata) =>
            {
                await Task.Delay(100).ConfigureAwait(false);  // make sure the operation is asynchronous.
                metadata.Add("authorization", "SECRET_TOKEN");
            });

            channel = new Channel(Host, server.Ports.Single().BoundPort, TestCredentials.CreateSslCredentials(), options);
            client  = new TestService.TestServiceClient(channel);

            var callCredentials = CallCredentials.FromInterceptor(asyncAuthInterceptor);

            client.UnaryCall(new SimpleRequest {
            }, new CallOptions(credentials: callCredentials));
        }
        public async Task MetadataCredentials_Composed()
        {
            serviceImpl.StreamingOutputCallHandler = async(req, responseStream, context) =>
            {
                var firstAuth = context.RequestHeaders.Last((entry) => entry.Key == "first_authorization").Value;
                Assert.AreEqual("FIRST_SECRET_TOKEN", firstAuth);
                var secondAuth = context.RequestHeaders.First((entry) => entry.Key == "second_authorization").Value;
                Assert.AreEqual("SECOND_SECRET_TOKEN", secondAuth);
                var thirdAuth = context.RequestHeaders.First((entry) => entry.Key == "third_authorization").Value;
                Assert.AreEqual("THIRD_SECRET_TOKEN", thirdAuth);
                await responseStream.WriteAsync(new StreamingOutputCallResponse());
            };

            var first = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                // Attempt to exercise the case where async callback is inlineable/synchronously-runnable.
                metadata.Add("first_authorization", "FIRST_SECRET_TOKEN");
                return(TaskUtils.CompletedTask);
            }));
            var second = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                metadata.Add("second_authorization", "SECOND_SECRET_TOKEN");
                return(TaskUtils.CompletedTask);
            }));
            var third = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => {
                metadata.Add("third_authorization", "THIRD_SECRET_TOKEN");
                return(TaskUtils.CompletedTask);
            }));
            var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(),
                                                               CallCredentials.Compose(first, second, third));

            channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
            var client = new TestService.TestServiceClient(channel);
            var call   = client.StreamingOutputCall(new StreamingOutputCallRequest {
            });

            Assert.IsTrue(await call.ResponseStream.MoveNext());
            Assert.IsFalse(await call.ResponseStream.MoveNext());
        }
Esempio n. 21
0
        private async Task <ChannelCredentials> CreateCredentialsAsync()
        {
            var credentials = ChannelCredentials.Insecure;

            if (options.UseTls.Value)
            {
                credentials = options.UseTestCa.Value ? TestCredentials.CreateSslCredentials() : new SslCredentials();
            }

            if (options.TestCase == "jwt_token_creds")
            {
#if !NETCOREAPP1_0
                var googleCredential = await GoogleCredential.GetApplicationDefaultAsync();

                Assert.IsTrue(googleCredential.IsCreateScopedRequired);
                credentials = ChannelCredentials.Create(credentials, googleCredential.ToCallCredentials());
#else
                // TODO(jtattermusch): implement this
                throw new NotImplementedException("Not supported on CoreCLR yet");
#endif
            }

            if (options.TestCase == "compute_engine_creds")
            {
#if !NETCOREAPP1_0
                var googleCredential = await GoogleCredential.GetApplicationDefaultAsync();

                Assert.IsFalse(googleCredential.IsCreateScopedRequired);
                credentials = ChannelCredentials.Create(credentials, googleCredential.ToCallCredentials());
#else
                // TODO(jtattermusch): implement this
                throw new NotImplementedException("Not supported on CoreCLR yet");
#endif
            }
            return(credentials);
        }
Esempio n. 22
0
        private void Run()
        {
            var server = new Server();

            server.AddServiceDefinition(TestService.BindService(new TestServiceImpl()));

            string host = "0.0.0.0";
            int    port = options.port.Value;

            if (options.useTls)
            {
                server.AddListeningPort(host, port, TestCredentials.CreateTestServerCredentials());
            }
            else
            {
                server.AddListeningPort(host, options.port.Value);
            }
            Console.WriteLine("Running server on " + string.Format("{0}:{1}", host, port));
            server.Start();

            server.ShutdownTask.Wait();

            GrpcEnvironment.Shutdown();
        }
Esempio n. 23
0
        public void Init()
        {
            serviceMock = new Mock <TestService.ITestService>();
            serviceMock.Setup(m => m.UnaryCall(It.IsAny <SimpleRequest>(), It.IsAny <ServerCallContext>()))
            .Returns(new Func <SimpleRequest, ServerCallContext, Task <SimpleResponse> >(UnaryCallHandler));

            server = new Server
            {
                Services = { TestService.BindService(serviceMock.Object) },
                Ports    = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
            };
            server.Start();

            options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

            asyncAuthInterceptor = new AsyncAuthInterceptor(async(context, metadata) =>
            {
                await Task.Delay(100).ConfigureAwait(false);  // make sure the operation is asynchronous.
                metadata.Add("authorization", "SECRET_TOKEN");
            });
        }