MetadataCredentialsTest.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. #region Copyright notice and license
  2. // Copyright 2015-2016 gRPC authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using Grpc.Core;
  23. using Grpc.Core.Utils;
  24. using Grpc.Testing;
  25. using NUnit.Framework;
  26. namespace Grpc.IntegrationTesting
  27. {
  28. public class MetadataCredentialsTest
  29. {
  30. const string Host = "localhost";
  31. Server server;
  32. Channel channel;
  33. TestService.TestServiceClient client;
  34. List<ChannelOption> options;
  35. AsyncAuthInterceptor asyncAuthInterceptor;
  36. [SetUp]
  37. public void Init()
  38. {
  39. // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755
  40. server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) })
  41. {
  42. Services = { TestService.BindService(new FakeTestService()) },
  43. Ports = { { Host, ServerPort.PickUnused, TestCredentials.CreateSslServerCredentials() } }
  44. };
  45. server.Start();
  46. options = new List<ChannelOption>
  47. {
  48. new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
  49. };
  50. asyncAuthInterceptor = new AsyncAuthInterceptor(async (context, metadata) =>
  51. {
  52. await Task.Delay(100).ConfigureAwait(false); // make sure the operation is asynchronous.
  53. metadata.Add("authorization", "SECRET_TOKEN");
  54. });
  55. }
  56. [TearDown]
  57. public void Cleanup()
  58. {
  59. channel.ShutdownAsync().Wait();
  60. server.ShutdownAsync().Wait();
  61. }
  62. [Test]
  63. public void MetadataCredentials()
  64. {
  65. var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(),
  66. CallCredentials.FromInterceptor(asyncAuthInterceptor));
  67. channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
  68. client = new TestService.TestServiceClient(channel);
  69. client.UnaryCall(new SimpleRequest { });
  70. }
  71. [Test]
  72. public void MetadataCredentials_PerCall()
  73. {
  74. channel = new Channel(Host, server.Ports.Single().BoundPort, TestCredentials.CreateSslCredentials(), options);
  75. client = new TestService.TestServiceClient(channel);
  76. var callCredentials = CallCredentials.FromInterceptor(asyncAuthInterceptor);
  77. client.UnaryCall(new SimpleRequest { }, new CallOptions(credentials: callCredentials));
  78. }
  79. [Test]
  80. public void MetadataCredentials_InterceptorLeavesMetadataEmpty()
  81. {
  82. var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(),
  83. CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) => TaskUtils.CompletedTask)));
  84. channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
  85. client = new TestService.TestServiceClient(channel);
  86. var ex = Assert.Throws<RpcException>(() => client.UnaryCall(new SimpleRequest { }));
  87. // StatusCode.Unknown as the server-side handler throws an exception after not receiving the authorization header.
  88. Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode);
  89. }
  90. [Test]
  91. public void MetadataCredentials_InterceptorThrows()
  92. {
  93. var callCredentials = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) =>
  94. {
  95. throw new Exception("Auth interceptor throws");
  96. }));
  97. var channelCredentials = ChannelCredentials.Create(TestCredentials.CreateSslCredentials(), callCredentials);
  98. channel = new Channel(Host, server.Ports.Single().BoundPort, channelCredentials, options);
  99. client = new TestService.TestServiceClient(channel);
  100. var ex = Assert.Throws<RpcException>(() => client.UnaryCall(new SimpleRequest { }));
  101. Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode);
  102. }
  103. private class FakeTestService : TestService.TestServiceBase
  104. {
  105. public override Task<SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context)
  106. {
  107. var authToken = context.RequestHeaders.First((entry) => entry.Key == "authorization").Value;
  108. Assert.AreEqual("SECRET_TOKEN", authToken);
  109. return Task.FromResult(new SimpleResponse());
  110. }
  111. }
  112. }
  113. }