Skip to content
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
66 changes: 43 additions & 23 deletions .github/workflows/preview.yml
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json

name: Publish Preview
run-name: '[Preview] PR #${{ github.event.pull_request.number }} — ${{ github.event.pull_request.title }}'
run-name: '[Preview] PR #${{ inputs.pr }}'

# Manual only: nuget.org versions are permanent, so a preview is published when a
# maintainer asks for one (Actions → Publish Preview → Run workflow), not on every push.
# Run it from the default branch so the trusted workflow file, not the PR's copy of it,
# holds the NuGet publishing rights.
on:
pull_request:
types: [opened, synchronize, reopened]
branches:
- main
- master
- develop

# Cancel any in-progress publish for the same PR when a new commit is pushed
workflow_dispatch:
inputs:
pr:
description: 'Pull request number to publish a preview package for'
required: true
type: number

concurrency:
group: preview-${{ github.event.pull_request.number }}
group: preview-${{ inputs.pr }}
cancel-in-progress: true

permissions:
Expand All @@ -32,18 +35,34 @@ defaults:
jobs:
publish-preview:
runs-on: ubuntu-latest
# Fork PRs (and dependabot PRs, which use a separate restricted secret store)
# run without repository secrets or a writable token, so NuGet login fails on
# the empty NUGET_USER and the PR comment couldn't be posted either. Skip the
# job instead of failing it — external contributions otherwise always show a
# red X they cannot fix. Build/test coverage for those PRs comes from the
# build and test workflows, which need no secrets.
if: >-
github.event.pull_request.head.repo.full_name == github.repository &&
github.actor != 'dependabot[bot]'
if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
steps:
# Only open PRs from branches in this repository: fork code is never published
# under the Facet package IDs.
- name: Resolve pull request
id: pr
uses: actions/github-script@v9
with:
script: |
const { data: pr } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: Number('${{ inputs.pr }}'),
});
if (pr.state !== 'open') {
core.setFailed(`PR #${pr.number} is ${pr.state}; previews are only published for open PRs.`);
return;
}
if (pr.head.repo?.full_name !== `${context.repo.owner}/${context.repo.repo}`) {
core.setFailed(`PR #${pr.number} comes from a fork; previews are only published for branches in this repository.`);
return;
}
core.setOutput('sha', pr.head.sha);
core.info(`Publishing PR #${pr.number} "${pr.title}" at ${pr.head.sha}`);

- uses: actions/checkout@v7
with:
ref: ${{ steps.pr.outputs.sha }}
fetch-depth: 0

- name: Setup .NET
Expand All @@ -66,7 +85,7 @@ jobs:
id: preview_version
shell: bash
run: |
PREVIEW_VERSION="${{ steps.base_version.outputs.VERSION }}-preview.pr${{ github.event.pull_request.number }}.${{ github.run_number }}"
PREVIEW_VERSION="${{ steps.base_version.outputs.VERSION }}-preview.pr${{ inputs.pr }}.${{ github.run_number }}"
echo "PREVIEW_VERSION=$PREVIEW_VERSION" >> "$GITHUB_OUTPUT"
echo "Preview version: $PREVIEW_VERSION"

Expand Down Expand Up @@ -95,6 +114,7 @@ jobs:
uses: actions/github-script@v9
with:
script: |
const issue_number = Number('${{ inputs.pr }}');
const version = '${{ steps.preview_version.outputs.PREVIEW_VERSION }}';
const body = [
'## 📦 Preview packages published',
Expand All @@ -106,12 +126,12 @@ jobs:
`dotnet add package Facet --version ${version}`,
'```',
'',
'_This pre-release is published automatically from this PR and will be overwritten on the next push._',
'_Published manually from this PR. Run the **Publish Preview** workflow again to publish a newer preview; earlier versions stay on NuGet._',
].join('\n');

// Update existing bot comment if present, otherwise create a new one
const { data: comments } = await github.rest.issues.listComments({
issue_number: context.issue.number,
issue_number,
owner: context.repo.owner,
repo: context.repo.repo,
});
Expand All @@ -129,7 +149,7 @@ jobs:
});
} else {
await github.rest.issues.createComment({
issue_number: context.issue.number,
issue_number,
owner: context.repo.owner,
repo: context.repo.repo,
body,
Expand Down
19 changes: 8 additions & 11 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json

name: test
run-name: '[Test] ${{ github.event.head_commit.message || github.event.pull_request.title || github.event.workflow_run.display_title || github.ref_name }}'
run-name: '[Test] ${{ github.event.head_commit.message || github.event.pull_request.title || github.ref_name }}'
# No workflow_run trigger: it runs in the base repository's context (secrets, write token)
# and would build fork PR code there. pull_request runs fork code with a read-only token.
on:
workflow_run:
workflows: ["build"]
types:
- completed
pull_request:
branches:
- "*"
Expand All @@ -17,7 +15,6 @@ on:
permissions:
contents: read
checks: write
pull-requests: write

env:
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1
Expand All @@ -30,14 +27,10 @@ defaults:
jobs:
test:
runs-on: ubuntu-latest
if: |
(github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success') ||
(github.event_name != 'workflow_run')
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
ref: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.head_sha || github.sha }}

- name: Setup .NET
uses: actions/setup-dotnet@v6
Expand All @@ -64,9 +57,13 @@ jobs:
path: TestResults/*.trx
retention-days: 7

# Fork PRs get a read-only token, so creating the check run would fail; the .trx
# artifact above still carries their results.
- name: Publish Test Results
uses: dorny/test-reporter@v3
if: success() || failure()
if: >-
(success() || failure()) &&
(github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository)
with:
name: Unit Test Results
path: TestResults/*.trx
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ All notable changes to Facet are documented in this file.

### Fixed

- **Security:** `Facet.Dashboard`'s `RequireAuthentication` / `AuthenticationPolicy` now also protect the JSON API endpoint (`{RoutePrefix}/api/facets`). Previously only the HTML page required authorization, so the JSON API, enabled by default, served the full source and facet model to anonymous callers.
- `CopyDocs` no longer drops inline markup from the copied documentation. `<see cref="..."/>` and `<see langword="..."/>` used to vanish from the sentence (a summary read "see ." in Swagger/Scalar), `<c>` and `<para>` lost their markup, and an escaped `&lt;` was written back unescaped (CS1570 in the consuming project). Crefs are copied in documentation-ID form (`P:Namespace.Type.Member`), which the compiler does not rebind, so a facet in another namespace than its source still gets no CS1574 (#45). A `paramref`/`typeparamref` to a parameter the facet does not have becomes `<c>name</c>`.
- `[GenerateDtos]` no longer fails with CS8784 ("Generator 'GenerateDtosGeneratorHoist' failed to initialize … FileNotFoundException … SourceGenerator.Foundations.Contracts") when the compiler server already holds a Facet of 6.6.8 or older, e.g. from another solution built on the same machine. The DTOs were then not generated at all (CS0246 wherever they are used). Fixed in SourceGenerator.Foundations 2.0.17, which resolves embedded assemblies by name and version instead of by simple name.

Expand Down
26 changes: 16 additions & 10 deletions src/Facet.Dashboard/FacetDashboardExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,23 @@ public static IEndpointRouteBuilder MapFacetDashboard(this IEndpointRouteBuilder

var routePrefix = options.RoutePrefix.TrimEnd('/');

// Every endpoint the dashboard maps, so authentication covers all of them
var endpoints = new List<IEndpointConventionBuilder>();

// Main dashboard HTML page
var dashboardEndpoint = app.MapGet(routePrefix, async context =>
endpoints.Add(app.MapGet(routePrefix, async context =>
{
var dashboardService = context.RequestServices.GetRequiredService<FacetDashboardService>();
var html = dashboardService.GetDashboardHtml();

context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync(html);
});
}));

// JSON API endpoint
if (options.EnableJsonApi)
{
app.MapGet($"{routePrefix}/api/facets", async context =>
endpoints.Add(app.MapGet($"{routePrefix}/api/facets", async context =>
{
var dashboardService = context.RequestServices.GetRequiredService<FacetDashboardService>();
var facets = dashboardService.GetFacetMappings();
Expand Down Expand Up @@ -122,17 +125,20 @@ public static IEndpointRouteBuilder MapFacetDashboard(this IEndpointRouteBuilder

context.Response.ContentType = "application/json; charset=utf-8";
await context.Response.WriteAsync(JsonSerializer.Serialize(result, jsonOptions));
});
}));
}

// Apply authentication if configured
if (options.RequireAuthentication && !string.IsNullOrEmpty(options.AuthenticationPolicy))
{
dashboardEndpoint.RequireAuthorization(options.AuthenticationPolicy);
}
else if (options.RequireAuthentication)
foreach (var endpoint in endpoints)
{
dashboardEndpoint.RequireAuthorization();
if (options.RequireAuthentication && !string.IsNullOrEmpty(options.AuthenticationPolicy))
{
endpoint.RequireAuthorization(options.AuthenticationPolicy);
}
else if (options.RequireAuthentication)
{
endpoint.RequireAuthorization();
}
}

return app;
Expand Down
1 change: 1 addition & 0 deletions src/Facet.Dashboard/FacetDashboardOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public sealed class FacetDashboardOptions

/// <summary>
/// Gets or sets whether the dashboard requires authentication.
/// Applies to the dashboard page and the JSON API endpoint.
/// Default is false.
/// </summary>
public bool RequireAuthentication { get; set; } = false;
Expand Down
2 changes: 2 additions & 0 deletions src/Facet.Dashboard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ builder.Services.AddFacetDashboard(options =>
});
```

Authentication applies to both the dashboard page and the JSON API endpoint.

### Additional Assemblies

By default, the dashboard scans the entry assembly and its references. You can add additional assemblies:
Expand Down
5 changes: 5 additions & 0 deletions test/Facet.Tests/Facet.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
<NoWarn>$(NoWarn);FAC004</NoWarn>
</PropertyGroup>

<ItemGroup>
<!-- Facet.Dashboard endpoint tests build a WebApplication -->
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
Expand Down Expand Up @@ -48,6 +52,7 @@
<ProjectReference Include="..\..\src\Facet.Extensions.EFCore\Facet.Extensions.EFCore.csproj" />
<ProjectReference Include="..\..\src\Facet.Extensions.EFCore.Mapping\Facet.Extensions.EFCore.Mapping.csproj" />
<ProjectReference Include="..\..\src\Facet.Mapping.Expressions\Facet.Mapping.Expressions.csproj" />
<ProjectReference Include="..\..\src\Facet.Dashboard\Facet.Dashboard.csproj" />
<ProjectReference Include="..\Facet.Tests.ExternalLib\Facet.Tests.ExternalLib.csproj" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using Facet.Dashboard;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;

namespace Facet.Tests.UnitTests.Extensions.Dashboard;

public class FacetDashboardAuthorizationTests
{
[Fact]
public void MapFacetDashboard_WithAuthenticationPolicy_ShouldProtectEveryEndpoint()
{
var endpoints = MapDashboard(options =>
{
options.RequireAuthentication = true;
options.AuthenticationPolicy = "AdminOnly";
});

endpoints.Should().HaveCount(2, "the dashboard maps the HTML page and the JSON API");
endpoints.Should().AllSatisfy(endpoint =>
endpoint.Metadata.GetOrderedMetadata<IAuthorizeData>()
.Should().Contain(a => a.Policy == "AdminOnly", endpoint.DisplayName));
}

[Fact]
public void MapFacetDashboard_WithAuthenticationWithoutPolicy_ShouldProtectEveryEndpoint()
{
var endpoints = MapDashboard(options => options.RequireAuthentication = true);

endpoints.Should().HaveCount(2);
endpoints.Should().AllSatisfy(endpoint =>
endpoint.Metadata.GetOrderedMetadata<IAuthorizeData>()
.Should().NotBeEmpty(endpoint.DisplayName));
}

[Fact]
public void MapFacetDashboard_WithoutAuthentication_ShouldNotRequireAuthorization()
{
var endpoints = MapDashboard(_ => { });

endpoints.Should().HaveCount(2);
endpoints.Should().AllSatisfy(endpoint =>
endpoint.Metadata.GetOrderedMetadata<IAuthorizeData>()
.Should().BeEmpty(endpoint.DisplayName));
}

private static List<Endpoint> MapDashboard(Action<FacetDashboardOptions> configure)
{
var builder = WebApplication.CreateBuilder();
builder.Services.AddFacetDashboard(configure);
var app = builder.Build();

app.MapFacetDashboard();

return ((IEndpointRouteBuilder)app).DataSources
.SelectMany(source => source.Endpoints)
.ToList();
}
}
Loading