Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support multiple bearer tokens #13

Merged
merged 3 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .idea/.idea.Testably.Server/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions .idea/.idea.Testably.Server/.idea/encodings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions .idea/.idea.Testably.Server/.idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,23 @@
return BadRequest($"Only public repositories from '{string.Join(", ", RepositoryOwners)}' are supported!");
}

var bearerToken = _configuration.GetValue<string>("GithubBearerToken");
var bearerToken = pullRequestModel.Repository.Owner.Login switch
{
"Testably" => _configuration.GetValue<string>("testablyToken"),
"aweXpect" => _configuration.GetValue<string>("aweXpectToken"),
_ => ""
};
if (string.IsNullOrEmpty(bearerToken))
{
_logger.LogWarning("Could not find valid bearer token for {Organization}",
pullRequestModel.Repository.Owner.Login);
return StatusCode(StatusCodes.Status403Forbidden,
$"Could not find valid bearer token for {pullRequestModel.Repository.Owner.Login}");
}

using var client = _clientFactory.CreateClient("Proxied");
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Testably",
Assembly.GetExecutingAssembly().GetName().Version.ToString()));

Check warning on line 86 in Source/Testably.Server/Controllers/PullRequestStatusCheckController.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 86 in Source/Testably.Server/Controllers/PullRequestStatusCheckController.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", bearerToken);

Expand All @@ -85,6 +98,7 @@
if (!response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync();
_logger.LogWarning("GitHub API '{RequestUri}' not available: {ResponseContent}", requestUri, responseContent);
return StatusCode(StatusCodes.Status500InternalServerError,
$"GitHub API '{requestUri}' not available: {responseContent}");
}
Expand All @@ -96,6 +110,7 @@
if (!jsonDocument.RootElement.TryGetProperty("title", out var titleProperty) ||
titleProperty.GetString() == null)
{
_logger.LogWarning("GitHub API '{RequestUri}' returned an invalid response (missing title).", requestUri);
return StatusCode(StatusCodes.Status500InternalServerError,
$"GitHub API '{requestUri}' returned an invalid response (missing title).");
}
Expand All @@ -104,6 +119,7 @@
!headProperty.TryGetProperty("sha", out var shaProperty) ||
shaProperty.GetString() == null)
{
_logger.LogWarning("GitHub API '{RequestUri}' returned an invalid response (missing head.sha).", requestUri);
return StatusCode(StatusCodes.Status500InternalServerError,
$"GitHub API '{requestUri}' returned an invalid response (missing head.sha).");
}
Expand Down
1 change: 1 addition & 0 deletions Testably.Server.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,7 @@
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpRenamePlacementToArrangementMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpUseContinuousIndentInsideBracesMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002EMemberReordering_002EMigrations_002ECSharpFileLayoutPatternRemoveIsAttributeUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EAddAccessorOwnerDeclarationBracesMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EAlwaysTreatStructAsNotReorderableMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002ECSharpPlaceAttributeOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
Expand Down
25 changes: 22 additions & 3 deletions Tests/Testably.Server.Tests/TestFactory.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Testably.Server.Tests;

public class TestFactory : WebApplicationFactory<Program>
{
private readonly IConfiguration _configuration;
private readonly IHttpClientFactory? _httpClientFactory;

public TestFactory(IHttpClientFactory? httpClientFactory = null)
public TestFactory(IHttpClientFactory? httpClientFactory = null,
Action<Dictionary<string, string>>? configuration = null)
{
_httpClientFactory = httpClientFactory;
var builder = new ConfigurationBuilder();
var inMemoryConfiguration = new Dictionary<string, string>();
configuration?.Invoke(inMemoryConfiguration);
_configuration = builder.AddInMemoryCollection(inMemoryConfiguration!).Build();
}

/// <inheritdoc />
Expand All @@ -22,15 +30,26 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
{
if (_httpClientFactory != null)
{
var descriptor =
services.SingleOrDefault(d => d.ServiceType == _httpClientFactory.GetType());
var descriptor = services
.SingleOrDefault(d => d.ServiceType == _httpClientFactory.GetType());
if (descriptor != null)
{
services.Remove(descriptor);
}

services.AddSingleton(_httpClientFactory);
}

services.AddSingleton(_configuration);
});
}

/// <summary>
/// https://stackoverflow.com/a/69825605
/// </summary>
protected override IHost CreateHost(IHostBuilder builder)
{
builder.UseContentRoot(Directory.GetCurrentDirectory());
return base.CreateHost(builder);
}
}
3 changes: 2 additions & 1 deletion Tests/Testably.Server.Tests/WebhookTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ public async Task HappyCase_ShouldSucceed(string title, string status)
sentStatusCheck = c;
return "";
}));
await using var factory = new TestFactory(httpClientFactoryMock.Object);
await using var factory = new TestFactory(httpClientFactoryMock.Object,
c => c.Add("testablyToken", "foo"));
using var client = factory.CreateClient();
client.DefaultRequestHeaders.Add("x-github-event", "pull_request");
using var content = new StringContent(webhookPayload, mediaType: "application/json",
Expand Down