|
| 1 | +/* |
| 2 | + * Bandwidth |
| 3 | + * |
| 4 | + * Bandwidth's Communication APIs |
| 5 | + * |
| 6 | + * The version of the OpenAPI document: 1.0.0 |
| 7 | + * Contact: letstalk@bandwidth.com |
| 8 | + * Generated by: https://github.com/openapitools/openapi-generator.git |
| 9 | + */ |
| 10 | + |
| 11 | + |
| 12 | +using System; |
| 13 | +using System.Net; |
| 14 | +using System.Net.Sockets; |
| 15 | +using System.Text; |
| 16 | +using System.Threading; |
| 17 | +using System.Threading.Tasks; |
| 18 | +using Xunit; |
| 19 | +using Newtonsoft.Json; |
| 20 | +using Bandwidth.Standard.Client; |
| 21 | +using Bandwidth.Standard.Client.Auth; |
| 22 | + |
| 23 | +namespace Bandwidth.Standard.Test.Unit.Client |
| 24 | +{ |
| 25 | + /// <summary> |
| 26 | + /// Class for testing OAuthAuthenticator token handling and caching. |
| 27 | + /// </summary> |
| 28 | + public class OAuthAuthenticatorTests : IDisposable |
| 29 | + { |
| 30 | + private readonly HttpListener _listener; |
| 31 | + private readonly string _tokenUrl; |
| 32 | + private readonly string _clientId; |
| 33 | + private const string ClientSecret = "test-secret"; |
| 34 | + private const string AccessToken = "test-access-token"; |
| 35 | + |
| 36 | + // Each call to the fake token endpoint increments this so tests can assert how |
| 37 | + // many times a token was actually fetched from the server. |
| 38 | + private int _tokenRequestCount; |
| 39 | + private string _lastAuthorizationHeader; |
| 40 | + |
| 41 | + // Controls whether the fake endpoint returns expires_in; toggled per test. |
| 42 | + private int _expiresInSeconds = 3600; |
| 43 | + private bool _includeExpiresIn = true; |
| 44 | + |
| 45 | + public OAuthAuthenticatorTests() |
| 46 | + { |
| 47 | + // Unique client id per test keeps the authenticator's process-wide static |
| 48 | + // token cache isolated between tests (cache key is tokenUrl + clientId). |
| 49 | + _clientId = "test-client-" + Guid.NewGuid().ToString("N"); |
| 50 | + |
| 51 | + int port = GetFreeTcpPort(); |
| 52 | + _tokenUrl = $"http://localhost:{port}/oauth2/token"; |
| 53 | + |
| 54 | + _listener = new HttpListener(); |
| 55 | + _listener.Prefixes.Add($"http://localhost:{port}/"); |
| 56 | + _listener.Start(); |
| 57 | + _ = Task.Run(ServeTokenRequestsAsync); |
| 58 | + } |
| 59 | + |
| 60 | + public void Dispose() |
| 61 | + { |
| 62 | + if (_listener.IsListening) |
| 63 | + _listener.Stop(); |
| 64 | + _listener.Close(); |
| 65 | + } |
| 66 | + |
| 67 | + /// <summary> |
| 68 | + /// A valid token (with expires_in) should be fetched once and reused on subsequent calls. |
| 69 | + /// </summary> |
| 70 | + [Fact] |
| 71 | + public async Task GetAuthenticationParameter_CachesToken_FetchesOnlyOnce() |
| 72 | + { |
| 73 | + var authenticator = CreateAuthenticator(); |
| 74 | + |
| 75 | + string first = await authenticator.GetAuthHeaderAsync(); |
| 76 | + string second = await authenticator.GetAuthHeaderAsync(); |
| 77 | + |
| 78 | + Assert.Equal($"Bearer {AccessToken}", first); |
| 79 | + Assert.Equal(first, second); |
| 80 | + Assert.Equal(1, _tokenRequestCount); |
| 81 | + } |
| 82 | + |
| 83 | + /// <summary> |
| 84 | + /// The token request should authenticate with the client credentials via HTTP Basic auth. |
| 85 | + /// </summary> |
| 86 | + [Fact] |
| 87 | + public async Task GetAuthenticationParameter_SendsClientCredentialsAsBasicAuth() |
| 88 | + { |
| 89 | + var authenticator = CreateAuthenticator(); |
| 90 | + |
| 91 | + await authenticator.GetAuthHeaderAsync(); |
| 92 | + |
| 93 | + string expected = "Basic " + Convert.ToBase64String( |
| 94 | + Encoding.UTF8.GetBytes($"{_clientId}:{ClientSecret}")); |
| 95 | + Assert.Equal(expected, _lastAuthorizationHeader); |
| 96 | + } |
| 97 | + |
| 98 | + /// <summary> |
| 99 | + /// When the server omits expires_in, the token must not be cached (falls back to fetching per call). |
| 100 | + /// </summary> |
| 101 | + [Fact] |
| 102 | + public async Task GetAuthenticationParameter_WithoutExpiresIn_FetchesEachTime() |
| 103 | + { |
| 104 | + _includeExpiresIn = false; |
| 105 | + var authenticator = CreateAuthenticator(); |
| 106 | + |
| 107 | + await authenticator.GetAuthHeaderAsync(); |
| 108 | + await authenticator.GetAuthHeaderAsync(); |
| 109 | + |
| 110 | + Assert.Equal(2, _tokenRequestCount); |
| 111 | + } |
| 112 | + |
| 113 | + private TestableOAuthAuthenticator CreateAuthenticator() |
| 114 | + { |
| 115 | + return new TestableOAuthAuthenticator( |
| 116 | + _tokenUrl, |
| 117 | + _clientId, |
| 118 | + ClientSecret, |
| 119 | + OAuthFlow.APPLICATION, |
| 120 | + new JsonSerializerSettings(), |
| 121 | + new Configuration()); |
| 122 | + } |
| 123 | + |
| 124 | + private async Task ServeTokenRequestsAsync() |
| 125 | + { |
| 126 | + while (_listener.IsListening) |
| 127 | + { |
| 128 | + HttpListenerContext context; |
| 129 | + try |
| 130 | + { |
| 131 | + context = await _listener.GetContextAsync(); |
| 132 | + } |
| 133 | + catch |
| 134 | + { |
| 135 | + // Listener stopped/disposed during teardown. |
| 136 | + break; |
| 137 | + } |
| 138 | + |
| 139 | + Interlocked.Increment(ref _tokenRequestCount); |
| 140 | + _lastAuthorizationHeader = context.Request.Headers["Authorization"]; |
| 141 | + |
| 142 | + string body = _includeExpiresIn |
| 143 | + ? $"{{\"token_type\":\"Bearer\",\"access_token\":\"{AccessToken}\",\"expires_in\":{_expiresInSeconds}}}" |
| 144 | + : $"{{\"token_type\":\"Bearer\",\"access_token\":\"{AccessToken}\"}}"; |
| 145 | + |
| 146 | + byte[] bytes = Encoding.UTF8.GetBytes(body); |
| 147 | + context.Response.ContentType = "application/json"; |
| 148 | + context.Response.ContentLength64 = bytes.Length; |
| 149 | + await context.Response.OutputStream.WriteAsync(bytes, 0, bytes.Length); |
| 150 | + context.Response.Close(); |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + private static int GetFreeTcpPort() |
| 155 | + { |
| 156 | + var listener = new TcpListener(IPAddress.Loopback, 0); |
| 157 | + listener.Start(); |
| 158 | + int port = ((IPEndPoint)listener.LocalEndpoint).Port; |
| 159 | + listener.Stop(); |
| 160 | + return port; |
| 161 | + } |
| 162 | + |
| 163 | + /// <summary> |
| 164 | + /// Exposes the protected GetAuthenticationParameter as the resolved Authorization header value. |
| 165 | + /// </summary> |
| 166 | + private sealed class TestableOAuthAuthenticator : OAuthAuthenticator |
| 167 | + { |
| 168 | + public TestableOAuthAuthenticator( |
| 169 | + string tokenUrl, |
| 170 | + string clientId, |
| 171 | + string clientSecret, |
| 172 | + OAuthFlow? flow, |
| 173 | + JsonSerializerSettings serializerSettings, |
| 174 | + IReadableConfiguration configuration) |
| 175 | + : base(tokenUrl, clientId, clientSecret, flow, serializerSettings, configuration) |
| 176 | + { |
| 177 | + } |
| 178 | + |
| 179 | + public async Task<string> GetAuthHeaderAsync() |
| 180 | + { |
| 181 | + var parameter = await GetAuthenticationParameter(string.Empty); |
| 182 | + return parameter.Value?.ToString(); |
| 183 | + } |
| 184 | + } |
| 185 | + } |
| 186 | +} |
0 commit comments