From 2e764032762f6fc1928bc5b090971b70384b4b53 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Sat, 14 Nov 2026 19:58:43 -0800 Subject: [PATCH 1/2] feat: expose the running build's commit at GET /version Post-deploy smoke tests need to confirm the new revision is serving traffic before testing it (az containerapp update returns before traffic shifts). .git is excluded from the Docker build context, so the image could not know which commit it was built from. - Dockerfile: SOURCE_REVISION build arg -> -p:SourceRevisionId, so AssemblyInformationalVersion becomes 1.0.0+. Declared after COPY . . so restore layers stay cached. - Workflow: pass SOURCE_REVISION=${{ github.sha }} to both image builds (production imports the same image, so it reports the same commit). - GET/HEAD /version returns {version, commit}: no-store, not rate limited, excluded from tracing like /health and /alive. Not shown in the site UI. --- .github/workflows/Build-Test-And-Deploy.yml | 5 +- .../VersionEndpointTests.cs | 78 +++++++++++++++++++ EssentialCSharp.Web/Dockerfile | 8 +- EssentialCSharp.Web/Program.cs | 10 ++- EssentialCSharp.Web/Services/BuildInfo.cs | 36 +++++++++ 5 files changed, 134 insertions(+), 3 deletions(-) create mode 100644 EssentialCSharp.Web.Tests/VersionEndpointTests.cs create mode 100644 EssentialCSharp.Web/Services/BuildInfo.cs diff --git a/.github/workflows/Build-Test-And-Deploy.yml b/.github/workflows/Build-Test-And-Deploy.yml index cb441a0b..29a434ad 100644 --- a/.github/workflows/Build-Test-And-Deploy.yml +++ b/.github/workflows/Build-Test-And-Deploy.yml @@ -141,6 +141,7 @@ jobs: context: . secret-files: | "nuget_config=${{ runner.temp }}/nuget/NuGet.Config" + build-args: SOURCE_REVISION=${{ github.sha }} outputs: type=docker,dest=${{ github.workspace }}/essentialcsharpwebimage.tar cache-from: type=gha,scope=essentialcsharpweb-main cache-to: type=gha,mode=max,scope=essentialcsharpweb-main @@ -270,7 +271,9 @@ jobs: type=gha,scope=essentialcsharpweb-main type=gha,scope=essentialcsharpweb-pr cache-to: type=gha,mode=min,scope=essentialcsharpweb-pr - build-args: ACCESS_TO_NUGET_FEED=false + build-args: | + ACCESS_TO_NUGET_FEED=false + SOURCE_REVISION=${{ github.sha }} deploy-development: if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' diff --git a/EssentialCSharp.Web.Tests/VersionEndpointTests.cs b/EssentialCSharp.Web.Tests/VersionEndpointTests.cs new file mode 100644 index 00000000..bf62b7e5 --- /dev/null +++ b/EssentialCSharp.Web.Tests/VersionEndpointTests.cs @@ -0,0 +1,78 @@ +using System.Net; +using System.Reflection; +using System.Text.Json; +using EssentialCSharp.Web.Services; + +namespace EssentialCSharp.Web.Tests; + +public class VersionEndpointTests : IntegrationTestBase +{ + [Test] + public async Task GetVersion_ReturnsRunningAssemblyBuildInfo_WithoutCaching() + { + using HttpClient client = CreateClientWithoutAutoRedirect(); + + using HttpResponseMessage response = await client.GetAsync("/version"); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(response.Headers.CacheControl?.NoStore).IsTrue(); + + string? expectedVersion = typeof(Program).Assembly + .GetCustomAttribute()?.InformationalVersion; + using JsonDocument payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + await Assert.That(payload.RootElement.GetProperty("version").GetString()).IsEqualTo(expectedVersion); + await Assert.That(payload.RootElement.GetProperty("commit").GetString()) + .IsEqualTo(BuildInfo.FromInformationalVersion(expectedVersion).Commit); + } + + [Test] + public async Task HeadVersion_ReturnsOk() + { + using HttpClient client = CreateClientWithoutAutoRedirect(); + using var request = new HttpRequestMessage(HttpMethod.Head, "/version"); + + using HttpResponseMessage response = await client.SendAsync(request); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + [Test] + public async Task BuildInfo_InGitHubActions_IsStampedWithCheckedOutCommit() + { + // Locally the stamp depends on the developer's checkout, so only enforce it in CI, where the + // checked-out commit is GITHUB_SHA and the SDK's SourceLink stamps it into the informational version. + if (!string.Equals(Environment.GetEnvironmentVariable("GITHUB_ACTIONS"), "true", StringComparison.OrdinalIgnoreCase)) + { + return; + } + + await Assert.That(BuildInfo.Current.Commit).IsEqualTo(Environment.GetEnvironmentVariable("GITHUB_SHA")); + } + + [Test] + public async Task GetVersion_IsNotRateLimited() + { + // Deployment checks poll /version until the new revision answers; the global limiter must not reject them. + using HttpClient client = CreateClientWithoutAutoRedirect(); + + for (int i = 0; i < 40; i++) + { + using HttpResponseMessage response = await client.GetAsync("/version"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + } + + [Test] + [Arguments("1.0.0+0123456789abcdef0123456789abcdef01234567", "1.0.0+0123456789abcdef0123456789abcdef01234567", "0123456789abcdef0123456789abcdef01234567")] + [Arguments("1.0.0", "1.0.0", null)] + [Arguments("1.0.0+", "1.0.0+", null)] + [Arguments(null, null, null)] + [Arguments("", null, null)] + public async Task FromInformationalVersion_ExtractsCommitAfterPlus(string? informationalVersion, string? expectedVersion, string? expectedCommit) + { + BuildInfo info = BuildInfo.FromInformationalVersion(informationalVersion); + + await Assert.That(info.Version).IsEqualTo(expectedVersion); + await Assert.That(info.Commit).IsEqualTo(expectedCommit); + } +} diff --git a/EssentialCSharp.Web/Dockerfile b/EssentialCSharp.Web/Dockerfile index 2a24f044..b14160bb 100644 --- a/EssentialCSharp.Web/Dockerfile +++ b/EssentialCSharp.Web/Dockerfile @@ -31,10 +31,16 @@ RUN --mount=type=secret,id=nuget_config,required=false,target=/root/.nuget/NuGet dotnet restore "EssentialCSharp.Web/EssentialCSharp.Web.csproj" -p:AccessToNugetFeed=$ACCESS_TO_NUGET_FEED COPY . . COPY --from=frontend-build /frontend/EssentialCSharp.Web/wwwroot/dist ./EssentialCSharp.Web/wwwroot/dist +# Commit SHA the image is built from. .git is excluded from the build context, so CI passes it in; +# it becomes the "+" suffix of AssemblyInformationalVersion and is reported by GET /version. +# Declared here (after COPY . .) so a new value does not invalidate the cached restore layer. +ARG SOURCE_REVISION= RUN --mount=type=cache,id=essentialcsharp-web-nuget,target=/root/.nuget/packages \ - dotnet build "EssentialCSharp.Web/EssentialCSharp.Web.csproj" -c Release --no-restore -p:AccessToNugetFeed=$ACCESS_TO_NUGET_FEED -p:ReleaseDateAttribute=True -p:SkipFrontendBuild=true + dotnet build "EssentialCSharp.Web/EssentialCSharp.Web.csproj" -c Release --no-restore -p:AccessToNugetFeed=$ACCESS_TO_NUGET_FEED -p:ReleaseDateAttribute=True -p:SkipFrontendBuild=true -p:SourceRevisionId=$SOURCE_REVISION RUN --mount=type=cache,id=essentialcsharp-web-nuget,target=/root/.nuget/packages \ dotnet publish "EssentialCSharp.Web/EssentialCSharp.Web.csproj" -c Release -p:PublishDir=/app/publish -p:UseAppHost=false -p:AccessToNugetFeed=$ACCESS_TO_NUGET_FEED -p:SkipFrontendBuild=true --no-build +# The bundle step rebuilds without SourceRevisionId; that's fine because /app/publish already holds the +# stamped web assembly and the bundle only writes efbundle. Keep publish before this step. RUN --mount=type=cache,id=essentialcsharp-web-nuget,target=/root/.nuget/packages \ dotnet tool restore && \ ASPNETCORE_ENVIRONMENT=Development SkipFrontendBuild=true dotnet ef migrations bundle \ diff --git a/EssentialCSharp.Web/Program.cs b/EssentialCSharp.Web/Program.cs index 1cb4de2a..d7593f5b 100644 --- a/EssentialCSharp.Web/Program.cs +++ b/EssentialCSharp.Web/Program.cs @@ -66,7 +66,8 @@ private static void Main(string[] args) { options.Filter = ctx => !ctx.Request.Path.StartsWithSegments("/health") - && !ctx.Request.Path.StartsWithSegments("/alive"); + && !ctx.Request.Path.StartsWithSegments("/alive") + && !ctx.Request.Path.StartsWithSegments("/version"); // EnrichWithHttpResponse fires after the authentication middleware has run, // so HttpContext.User is populated and IsAuthenticated is reliable. options.EnrichWithHttpResponse = (activity, response) => @@ -558,6 +559,13 @@ await McpJsonRpcResponseWriter.WriteErrorAsync( Predicate = r => r.Tags.Contains("live") }).DisableRateLimiting(); + // Machine-readable build identity for deployment checks (not linked from or shown in the UI). + app.MapMethods("/version", [HttpMethods.Get, HttpMethods.Head], (HttpResponse response) => + { + response.Headers.CacheControl = "no-store"; + return Results.Ok(BuildInfo.Current); + }).DisableRateLimiting(); + if (!app.Environment.IsDevelopment()) { app.UseHttpsRedirection(); diff --git a/EssentialCSharp.Web/Services/BuildInfo.cs b/EssentialCSharp.Web/Services/BuildInfo.cs new file mode 100644 index 00000000..29fd31a4 --- /dev/null +++ b/EssentialCSharp.Web/Services/BuildInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; + +namespace EssentialCSharp.Web.Services; + +/// +/// Identifies the build that is running, for GET /version. Deployment checks poll it to confirm +/// a new revision is serving traffic before smoke testing it. Nothing here is shown in the site UI. +/// +/// The assembly's informational version, e.g. 1.0.0+<sha>. +/// The source revision (git SHA) the build came from, or when the build was not stamped. +public sealed record BuildInfo(string? Version, string? Commit) +{ + public static BuildInfo Current { get; } = FromAssembly(typeof(BuildInfo).Assembly); + + public static BuildInfo FromAssembly(Assembly assembly) => + FromInformationalVersion(assembly.GetCustomAttribute()?.InformationalVersion); + + /// + /// The SDK appends +$(SourceRevisionId) to the informational version when a source revision is known + /// (from SourceLink locally, or the SOURCE_REVISION Docker build argument in CI). + /// + public static BuildInfo FromInformationalVersion(string? informationalVersion) + { + if (string.IsNullOrWhiteSpace(informationalVersion)) + { + return new BuildInfo(null, null); + } + + int plus = informationalVersion.IndexOf('+', StringComparison.Ordinal); + string? commit = plus >= 0 && plus < informationalVersion.Length - 1 + ? informationalVersion[(plus + 1)..] + : null; + + return new BuildInfo(informationalVersion, commit); + } +} From a10b60c2eca2de49447ab543793c8824042634f5 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Sat, 14 Nov 2026 20:07:59 -0800 Subject: [PATCH 2/2] test: assert /version contract with TUnit JSON assertions Use HasJsonContent, IsValidJsonObject and JsonElement IsDeepEqualTo so a renamed or extra field in the /version payload fails the test. --- .../VersionEndpointTests.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/EssentialCSharp.Web.Tests/VersionEndpointTests.cs b/EssentialCSharp.Web.Tests/VersionEndpointTests.cs index bf62b7e5..87d5e386 100644 --- a/EssentialCSharp.Web.Tests/VersionEndpointTests.cs +++ b/EssentialCSharp.Web.Tests/VersionEndpointTests.cs @@ -16,13 +16,21 @@ public async Task GetVersion_ReturnsRunningAssemblyBuildInfo_WithoutCaching() await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); await Assert.That(response.Headers.CacheControl?.NoStore).IsTrue(); + await Assert.That(response).HasJsonContent(); + string body = await response.Content.ReadAsStringAsync(); + await Assert.That(body).IsValidJsonObject(); + + // Deep equality pins the whole contract that deployment checks rely on: no renamed or extra fields. string? expectedVersion = typeof(Program).Assembly .GetCustomAttribute()?.InformationalVersion; - using JsonDocument payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); - await Assert.That(payload.RootElement.GetProperty("version").GetString()).IsEqualTo(expectedVersion); - await Assert.That(payload.RootElement.GetProperty("commit").GetString()) - .IsEqualTo(BuildInfo.FromInformationalVersion(expectedVersion).Commit); + using JsonDocument expected = JsonDocument.Parse(JsonSerializer.Serialize(new + { + version = expectedVersion, + commit = BuildInfo.FromInformationalVersion(expectedVersion).Commit, + })); + using JsonDocument actual = JsonDocument.Parse(body); + await Assert.That(actual.RootElement).IsDeepEqualTo(expected.RootElement); } [Test]