Skip to content

Fix CORS issues, probably #67

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

Merged
merged 3 commits into from
Mar 3, 2025
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
3 changes: 3 additions & 0 deletions rubberduckvba.Server/Api/Admin/AdminController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

Expand All @@ -13,6 +14,7 @@ public class AdminController(ConfigurationOptions options, HangfireLauncherServi
/// </summary>
/// <returns>The unique identifier of the enqueued job.</returns>
[Authorize("github")]
[EnableCors("CorsPolicy")]
[HttpPost("admin/update/xmldoc")]
public IActionResult UpdateXmldocContent()
{
Expand All @@ -25,6 +27,7 @@ public IActionResult UpdateXmldocContent()
/// </summary>
/// <returns>The unique identifier of the enqueued job.</returns>
[Authorize("github")]
[EnableCors("CorsPolicy")]
[HttpPost("admin/update/tags")]
public IActionResult UpdateTagMetadata()
{
Expand Down
2 changes: 2 additions & 0 deletions rubberduckvba.Server/Api/Admin/WebhookController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;

Expand All @@ -21,6 +22,7 @@ public WebhookController(
}

[Authorize("webhook")]
[EnableCors("webhookPolicy")]
[HttpPost("webhook/github")]
public async Task<IActionResult> GitHub([FromBody] dynamic body) =>
GuardInternalAction(() =>
Expand Down
3 changes: 3 additions & 0 deletions rubberduckvba.Server/Api/Auth/AuthController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Octokit;
Expand Down Expand Up @@ -70,6 +71,7 @@ public IActionResult Index()
}

[HttpPost("auth/signin")]
[EnableCors("CorsPolicy")]
[AllowAnonymous]
public IActionResult SessionSignIn(SignInViewModel vm)
{
Expand Down Expand Up @@ -106,6 +108,7 @@ public IActionResult SessionSignIn(SignInViewModel vm)
}

[HttpPost("auth/github")]
[EnableCors("CorsPolicy")]
[AllowAnonymous]
public IActionResult OnGitHubCallback(SignInViewModel vm)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public LoadGitHubTagsBlock(PipelineSection<SyncContext> parent, CancellationToke

public override async Task<SyncContext> TransformAsync(SyncRequestParameters input)
{
var githubTags = await _github.GetAllTagsAsync(); // does not get the assets
var githubTags = await _github.GetAllTagsAsync(Context.RubberduckDbMain.Name);
var (gitHubMain, gitHubNext, gitHubOthers) = githubTags.GetLatestTags();

Context.LoadGitHubTags(gitHubMain, gitHubNext, gitHubOthers);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ protected override async Task ActionAsync(SyncRequestParameters input)
{
Context.LoadParameters(input);

var githubTags = await _github.GetAllTagsAsync();
var dbMain = await _content.GetLatestTagAsync(RepositoryId.Rubberduck, includePreRelease: false);
var githubTags = await _github.GetAllTagsAsync(dbMain.Name);

// LoadInspectionDefaultConfig
var config = await _github.GetCodeAnalysisDefaultsConfigAsync();
Expand All @@ -115,7 +116,6 @@ await Task.WhenAll([

await Task.Delay(TimeSpan.FromSeconds(2)); // just in case the tags job was scheduled at/around the same time

var dbMain = await _content.GetLatestTagAsync(RepositoryId.Rubberduck, includePreRelease: false);
var dbNext = await _content.GetLatestTagAsync(RepositoryId.Rubberduck, includePreRelease: true);

var dbTags = _tagServices.GetAllTags().ToDictionary(e => e.Name);
Expand Down
18 changes: 1 addition & 17 deletions rubberduckvba.Server/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public static void Main(string[] args)

builder.Services.AddCors(builder =>
{
builder.AddDefaultPolicy(policy =>
builder.AddPolicy("CorsPolicy", policy =>
{
policy
.SetIsOriginAllowed(origin => true)
Expand All @@ -54,22 +54,6 @@ public static void Main(string[] args)
.AllowCredentials()
.Build();
});

builder.AddPolicy("webhookPolicy", policy =>
{
policy
#if DEBUG
.SetIsOriginAllowed(origin => true)
#else
.SetIsOriginAllowedToAllowWildcardSubdomains()
.WithOrigins("*.github.com")
#endif
.WithHeaders("Content-Type", "X-GitHub-Event", "X-GitHub-Delivery", "X-GitHub-Hook-ID", "X-Hub-Signature", "X-Hub-Signature256")
.WithMethods("POST")
.DisallowCredentials()
.SetPreflightMaxAge(TimeSpan.FromHours(48))
.Build();
});
});

builder.Services.AddAuthentication(options =>
Expand Down
19 changes: 16 additions & 3 deletions rubberduckvba.Server/Services/GitHubClientService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using rubberduckvba.Server.ContentSynchronization.XmlDoc.Schema;
using rubberduckvba.Server.Model;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
using System.Text;
using System.Web;
Expand All @@ -16,13 +17,20 @@ namespace rubberduckvba.Server.Services;
public interface IGitHubClientService
{
Task<ClaimsPrincipal?> ValidateTokenAsync(string token);
Task<IEnumerable<TagGraph>> GetAllTagsAsync();
Task<IEnumerable<TagGraph>> GetAllTagsAsync(string? dbMainTagName);
Task<TagGraph> GetTagAsync(string? token, string name);
Task<IEnumerable<InspectionDefaultConfig>> GetCodeAnalysisDefaultsConfigAsync();
}

public class GitHubClientService(IOptions<GitHubSettings> configuration, ILogger<ServiceLogger> logger) : IGitHubClientService
{
private class ReleaseComparer : IEqualityComparer<Release>
{
public bool Equals(Release? x, Release? y) => x?.Name == y?.Name;

public int GetHashCode([DisallowNull] Release obj) => HashCode.Combine(obj.Name);
}

public async Task<ClaimsPrincipal?> ValidateTokenAsync(string? token)
{
if (token is null)
Expand Down Expand Up @@ -52,13 +60,18 @@ public class GitHubClientService(IOptions<GitHubSettings> configuration, ILogger
return new ClaimsPrincipal(identity);
}

public async Task<IEnumerable<TagGraph>> GetAllTagsAsync()
public async Task<IEnumerable<TagGraph>> GetAllTagsAsync(string? dbMainTagName)
{
var config = configuration.Value;
var credentials = new Credentials(config.OrgToken);
var client = new GitHubClient(new ProductHeaderValue(config.UserAgent), new InMemoryCredentialStore(credentials));

var releases = await client.Repository.Release.GetAll(config.OwnerOrg, config.Rubberduck, new ApiOptions { PageCount = 1, PageSize = 10 });

var getReleases = client.Repository.Release.GetAll(config.OwnerOrg, config.Rubberduck, new ApiOptions { PageCount = 1, PageSize = 10 });
var getKnownMain = client.Repository.Release.Get(config.OwnerOrg, config.Rubberduck, dbMainTagName);
await Task.WhenAll(getReleases, getKnownMain);

var releases = (await getReleases).Append(await getKnownMain).ToHashSet(new ReleaseComparer());

return (from release in releases
let installer = release.Assets.SingleOrDefault(asset => asset.Name.EndsWith(".exe") && asset.Name.StartsWith("Rubberduck.Setup"))
Expand Down