Skip to content

Commit b33e90b

Browse files
feat: expose the running build's commit at GET /version (#1639)
## Why This is groundwork for post-deploy smoke tests that will gate production. `az containerapp update` returns about 45 s **before** traffic shifts to the new revision, so a smoke test that starts right away would test the old build. Today the site can't say which commit it is running. `.git` is excluded from the Docker build context, and nothing passes the SHA in. ## What - **Dockerfile:** a new `SOURCE_REVISION` build arg is passed to `dotnet build` as `-p:SourceRevisionId`, so `AssemblyInformationalVersion` becomes `1.0.0+<sha>`. - The ARG is declared after `COPY . .`, so restore layers stay cached. Every `RUN` after an `ARG` implicitly uses it. - A comment notes that publish must stay before the EF bundle step, which rebuilds without the property. - **Workflow:** passes `SOURCE_REVISION=${{ github.sha }}` to both image builds. `deploy-production` imports the same image from dev ACR, so prod reports the same commit. - **`GET`/`HEAD /version`** returns `{ "version": "1.0.0+<sha>", "commit": "<sha>" }`. - It sends `Cache-Control: no-store`, is not rate limited, and is excluded from tracing like `/health` and `/alive`. - It is **not** shown anywhere in the site UI. - The SHA is already public through the repo and the `deployed/prod/<sha>` tags. - For local builds, SourceLink already stamps the HEAD SHA, so `/version` works under `dotnet run` and Aspire too. ## Tests `VersionEndpointTests`: - Response shape and `no-store`. - `HEAD` returns 200. - 40 consecutive requests, above the 30/min global limit, all return 200. - `BuildInfo` parsing cases. - A CI-only check (`GITHUB_ACTIONS=true`) that the build is stamped with `GITHUB_SHA`. I simulated it locally: it passes with HEAD and fails with a wrong SHA. All 202 Web tests pass locally. I did not run a real `docker build` locally. Building with `-p:SourceRevisionId=deadbeefcafe` produced `1.0.0+deadbeefcafe`. The container-validation job builds the image, and the upcoming dev smoke step will assert that `/version`'s commit equals `github.sha`.
1 parent 18455d3 commit b33e90b

5 files changed

Lines changed: 142 additions & 3 deletions

File tree

‎.github/workflows/Build-Test-And-Deploy.yml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ jobs:
141141
context: .
142142
secret-files: |
143143
"nuget_config=${{ runner.temp }}/nuget/NuGet.Config"
144+
build-args: SOURCE_REVISION=${{ github.sha }}
144145
outputs: type=docker,dest=${{ github.workspace }}/essentialcsharpwebimage.tar
145146
cache-from: type=gha,scope=essentialcsharpweb-main
146147
cache-to: type=gha,mode=max,scope=essentialcsharpweb-main
@@ -270,7 +271,9 @@ jobs:
270271
type=gha,scope=essentialcsharpweb-main
271272
type=gha,scope=essentialcsharpweb-pr
272273
cache-to: type=gha,mode=min,scope=essentialcsharpweb-pr
273-
build-args: ACCESS_TO_NUGET_FEED=false
274+
build-args: |
275+
ACCESS_TO_NUGET_FEED=false
276+
SOURCE_REVISION=${{ github.sha }}
274277
275278
deploy-development:
276279
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
using System.Net;
2+
using System.Reflection;
3+
using System.Text.Json;
4+
using EssentialCSharp.Web.Services;
5+
6+
namespace EssentialCSharp.Web.Tests;
7+
8+
public class VersionEndpointTests : IntegrationTestBase
9+
{
10+
[Test]
11+
public async Task GetVersion_ReturnsRunningAssemblyBuildInfo_WithoutCaching()
12+
{
13+
using HttpClient client = CreateClientWithoutAutoRedirect();
14+
15+
using HttpResponseMessage response = await client.GetAsync("/version");
16+
17+
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
18+
await Assert.That(response.Headers.CacheControl?.NoStore).IsTrue();
19+
await Assert.That(response).HasJsonContent();
20+
21+
string body = await response.Content.ReadAsStringAsync();
22+
await Assert.That(body).IsValidJsonObject();
23+
24+
// Deep equality pins the whole contract that deployment checks rely on: no renamed or extra fields.
25+
string? expectedVersion = typeof(Program).Assembly
26+
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
27+
using JsonDocument expected = JsonDocument.Parse(JsonSerializer.Serialize(new
28+
{
29+
version = expectedVersion,
30+
commit = BuildInfo.FromInformationalVersion(expectedVersion).Commit,
31+
}));
32+
using JsonDocument actual = JsonDocument.Parse(body);
33+
await Assert.That(actual.RootElement).IsDeepEqualTo(expected.RootElement);
34+
}
35+
36+
[Test]
37+
public async Task HeadVersion_ReturnsOk()
38+
{
39+
using HttpClient client = CreateClientWithoutAutoRedirect();
40+
using var request = new HttpRequestMessage(HttpMethod.Head, "/version");
41+
42+
using HttpResponseMessage response = await client.SendAsync(request);
43+
44+
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
45+
}
46+
47+
[Test]
48+
public async Task BuildInfo_InGitHubActions_IsStampedWithCheckedOutCommit()
49+
{
50+
// Locally the stamp depends on the developer's checkout, so only enforce it in CI, where the
51+
// checked-out commit is GITHUB_SHA and the SDK's SourceLink stamps it into the informational version.
52+
if (!string.Equals(Environment.GetEnvironmentVariable("GITHUB_ACTIONS"), "true", StringComparison.OrdinalIgnoreCase))
53+
{
54+
return;
55+
}
56+
57+
await Assert.That(BuildInfo.Current.Commit).IsEqualTo(Environment.GetEnvironmentVariable("GITHUB_SHA"));
58+
}
59+
60+
[Test]
61+
public async Task GetVersion_IsNotRateLimited()
62+
{
63+
// Deployment checks poll /version until the new revision answers; the global limiter must not reject them.
64+
using HttpClient client = CreateClientWithoutAutoRedirect();
65+
66+
for (int i = 0; i < 40; i++)
67+
{
68+
using HttpResponseMessage response = await client.GetAsync("/version");
69+
await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
70+
}
71+
}
72+
73+
[Test]
74+
[Arguments("1.0.0+0123456789abcdef0123456789abcdef01234567", "1.0.0+0123456789abcdef0123456789abcdef01234567", "0123456789abcdef0123456789abcdef01234567")]
75+
[Arguments("1.0.0", "1.0.0", null)]
76+
[Arguments("1.0.0+", "1.0.0+", null)]
77+
[Arguments(null, null, null)]
78+
[Arguments("", null, null)]
79+
public async Task FromInformationalVersion_ExtractsCommitAfterPlus(string? informationalVersion, string? expectedVersion, string? expectedCommit)
80+
{
81+
BuildInfo info = BuildInfo.FromInformationalVersion(informationalVersion);
82+
83+
await Assert.That(info.Version).IsEqualTo(expectedVersion);
84+
await Assert.That(info.Commit).IsEqualTo(expectedCommit);
85+
}
86+
}

‎EssentialCSharp.Web/Dockerfile‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,16 @@ RUN --mount=type=secret,id=nuget_config,required=false,target=/root/.nuget/NuGet
3131
dotnet restore "EssentialCSharp.Web/EssentialCSharp.Web.csproj" -p:AccessToNugetFeed=$ACCESS_TO_NUGET_FEED
3232
COPY . .
3333
COPY --from=frontend-build /frontend/EssentialCSharp.Web/wwwroot/dist ./EssentialCSharp.Web/wwwroot/dist
34+
# Commit SHA the image is built from. .git is excluded from the build context, so CI passes it in;
35+
# it becomes the "+<sha>" suffix of AssemblyInformationalVersion and is reported by GET /version.
36+
# Declared here (after COPY . .) so a new value does not invalidate the cached restore layer.
37+
ARG SOURCE_REVISION=
3438
RUN --mount=type=cache,id=essentialcsharp-web-nuget,target=/root/.nuget/packages \
35-
dotnet build "EssentialCSharp.Web/EssentialCSharp.Web.csproj" -c Release --no-restore -p:AccessToNugetFeed=$ACCESS_TO_NUGET_FEED -p:ReleaseDateAttribute=True -p:SkipFrontendBuild=true
39+
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
3640
RUN --mount=type=cache,id=essentialcsharp-web-nuget,target=/root/.nuget/packages \
3741
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
42+
# The bundle step rebuilds without SourceRevisionId; that's fine because /app/publish already holds the
43+
# stamped web assembly and the bundle only writes efbundle. Keep publish before this step.
3844
RUN --mount=type=cache,id=essentialcsharp-web-nuget,target=/root/.nuget/packages \
3945
dotnet tool restore && \
4046
ASPNETCORE_ENVIRONMENT=Development SkipFrontendBuild=true dotnet ef migrations bundle \

‎EssentialCSharp.Web/Program.cs‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,8 @@ private static void Main(string[] args)
6666
{
6767
options.Filter = ctx =>
6868
!ctx.Request.Path.StartsWithSegments("/health")
69-
&& !ctx.Request.Path.StartsWithSegments("/alive");
69+
&& !ctx.Request.Path.StartsWithSegments("/alive")
70+
&& !ctx.Request.Path.StartsWithSegments("/version");
7071
// EnrichWithHttpResponse fires after the authentication middleware has run,
7172
// so HttpContext.User is populated and IsAuthenticated is reliable.
7273
options.EnrichWithHttpResponse = (activity, response) =>
@@ -558,6 +559,13 @@ await McpJsonRpcResponseWriter.WriteErrorAsync(
558559
Predicate = r => r.Tags.Contains("live")
559560
}).DisableRateLimiting();
560561

562+
// Machine-readable build identity for deployment checks (not linked from or shown in the UI).
563+
app.MapMethods("/version", [HttpMethods.Get, HttpMethods.Head], (HttpResponse response) =>
564+
{
565+
response.Headers.CacheControl = "no-store";
566+
return Results.Ok(BuildInfo.Current);
567+
}).DisableRateLimiting();
568+
561569
if (!app.Environment.IsDevelopment())
562570
{
563571
app.UseHttpsRedirection();
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System.Reflection;
2+
3+
namespace EssentialCSharp.Web.Services;
4+
5+
/// <summary>
6+
/// Identifies the build that is running, for <c>GET /version</c>. Deployment checks poll it to confirm
7+
/// a new revision is serving traffic before smoke testing it. Nothing here is shown in the site UI.
8+
/// </summary>
9+
/// <param name="Version">The assembly's informational version, e.g. <c>1.0.0+&lt;sha&gt;</c>.</param>
10+
/// <param name="Commit">The source revision (git SHA) the build came from, or <see langword="null"/> when the build was not stamped.</param>
11+
public sealed record BuildInfo(string? Version, string? Commit)
12+
{
13+
public static BuildInfo Current { get; } = FromAssembly(typeof(BuildInfo).Assembly);
14+
15+
public static BuildInfo FromAssembly(Assembly assembly) =>
16+
FromInformationalVersion(assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion);
17+
18+
/// <summary>
19+
/// The SDK appends <c>+$(SourceRevisionId)</c> to the informational version when a source revision is known
20+
/// (from SourceLink locally, or the <c>SOURCE_REVISION</c> Docker build argument in CI).
21+
/// </summary>
22+
public static BuildInfo FromInformationalVersion(string? informationalVersion)
23+
{
24+
if (string.IsNullOrWhiteSpace(informationalVersion))
25+
{
26+
return new BuildInfo(null, null);
27+
}
28+
29+
int plus = informationalVersion.IndexOf('+', StringComparison.Ordinal);
30+
string? commit = plus >= 0 && plus < informationalVersion.Length - 1
31+
? informationalVersion[(plus + 1)..]
32+
: null;
33+
34+
return new BuildInfo(informationalVersion, commit);
35+
}
36+
}

0 commit comments

Comments
 (0)