Files
ExecuteR/tests/Backend.Tests/BootstrapEndpointTests.cs
Alphaeus Mote 3aee670bed feat(enrollment): the same install re-run on the same machine re-enrolls
Client ids are deterministic (SHA-256 over normalized hardware ids) and
re-enrollment was already idempotent per device — history, tags, groups
and schedules carry over and the new key is bound. But every bootstrap
spent a token use, so re-running the same install command (single-device
tokens: one use, 24 h) failed on the second redeploy.

Devices now record the token that last enrolled them. That token
re-enrolls the same device without spending a use, even once its uses are
gone, as long as it is not expired or revoked; any other device still
needs a use left. Repeat enrollments are marked in the audit trail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 23:13:51 -04:00

253 lines
10 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Text;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using NATS.Jwt;
using NATS.NKeys;
using Shared.Contracts.Api;
using Shared.Contracts.Serialization;
using Shared.Infrastructure.Security;
using Xunit;
namespace Backend.Tests;
public class BootstrapEndpointTests : IClassFixture<BackendTestFixture>
{
private const string ClientId = "aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899";
private readonly BackendTestFixture fixture;
public BootstrapEndpointTests(BackendTestFixture fixture) => this.fixture = fixture;
private async Task<string> CreateTokenAsync(
TimeSpan? lifetime = null, int maxUses = 1, bool revoked = false)
{
var token = TokenGenerator.CreateUrlSafeToken(32);
await fixture.WithDbAsync(async db =>
{
db.BootstrapTokens.Add(new BootstrapTokenEntity
{
Id = Guid.NewGuid(),
TokenHash = TokenHashing.Sha256Hex(token),
CreatedUtc = DateTimeOffset.UtcNow,
ExpiresUtc = DateTimeOffset.UtcNow + (lifetime ?? TimeSpan.FromHours(1)),
MaxUses = maxUses,
Revoked = revoked,
});
await db.SaveChangesAsync();
});
return token;
}
private static BootstrapRequest MakeRequest(string token, string clientId, string nkeyPublic)
=> new(
BootstrapToken: token,
ClientId: clientId,
NkeyPublic: nkeyPublic,
AgentVersion: "2026.08.06.0000",
Device: new EnrollDeviceInfo("PC-001", "Dell Inc.", "OptiPlex", "Windows 11", "10.0.26200"));
[Fact]
public async Task ValidBootstrapIssuesScopedJwtAndConsumesToken()
{
var token = await CreateTokenAsync();
using var userKey = KeyPair.CreatePair(PrefixByte.User);
using var client = fixture.CreateClient();
var response = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, ClientId, userKey.GetPublicKey()), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadFromJsonAsync<BootstrapResponse>(JsonDefaults.Options);
Assert.NotNull(body);
Assert.Equal(ClientId, body.ClientId);
// JWT is scoped to exactly this client id and signed by the signing key.
var claims = NatsJwt.DecodeUserClaims(body.UserJwt);
Assert.Equal(userKey.GetPublicKey(), claims.Subject);
Assert.Equal(fixture.SigningKey.GetPublicKey(), claims.Issuer);
Assert.Equal(fixture.AccountKey.GetPublicKey(), claims.User.IssuerAccount);
Assert.Contains($"agent.{ClientId}.presence", claims.User.Pub.Allow);
Assert.Contains($"agent.{ClientId}.command.>", claims.User.Sub.Allow);
Assert.DoesNotContain(claims.User.Pub.Allow, p => p == ">");
// Device persisted.
var device = await fixture.WithDbAsync(db => db.Devices.FindAsync(ClientId).AsTask());
Assert.NotNull(device);
Assert.Equal("PC-001", device.Hostname);
Assert.Equal(userKey.GetPublicKey(), device.NkeyPublic);
// One-time token: another device cannot use it (the same device
// reinstalling may; see TheSameDeviceRedeploysRepeatedlyOnItsSingleUseToken).
using var otherKey = KeyPair.CreatePair(PrefixByte.User);
var second = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, NewClientId(), otherKey.GetPublicKey()), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Unauthorized, second.StatusCode);
}
[Fact]
public async Task TheSameDeviceRedeploysRepeatedlyOnItsSingleUseToken()
{
var token = await CreateTokenAsync(maxUses: 1);
var clientId = NewClientId();
using var client = fixture.CreateClient();
string lastKey = string.Empty;
for (var install = 0; install < 3; install++)
{
using var userKey = KeyPair.CreatePair(PrefixByte.User);
lastKey = userKey.GetPublicKey();
var response = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, clientId, lastKey), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
var (uses, boundKey) = await fixture.WithDbAsync(async db => (
(await db.BootstrapTokens.SingleAsync(t => t.TokenHash == TokenHashing.Sha256Hex(token))).Uses,
(await db.Devices.SingleAsync(d => d.ClientId == clientId)).NkeyPublic));
Assert.Equal(1, uses); // one machine, one use, however often it is reinstalled
Assert.Equal(lastKey, boundKey); // the newest install's key is the one bound
}
[Fact]
public async Task ASpentTokenStillRefusesOtherDevices()
{
var token = await CreateTokenAsync(maxUses: 1);
using var client = fixture.CreateClient();
using var first = KeyPair.CreatePair(PrefixByte.User);
using var second = KeyPair.CreatePair(PrefixByte.User);
var enrolled = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, NewClientId(), first.GetPublicKey()), JsonDefaults.Options);
var other = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, NewClientId(), second.GetPublicKey()), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.OK, enrolled.StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, other.StatusCode);
}
[Fact]
public async Task ARevokedTokenRefusesEvenTheDeviceItEnrolled()
{
var token = await CreateTokenAsync(maxUses: 1);
var clientId = NewClientId();
using var client = fixture.CreateClient();
using var first = KeyPair.CreatePair(PrefixByte.User);
using var again = KeyPair.CreatePair(PrefixByte.User);
(await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, clientId, first.GetPublicKey()), JsonDefaults.Options)).EnsureSuccessStatusCode();
await fixture.WithDbAsync(async db =>
{
(await db.BootstrapTokens.SingleAsync(t => t.TokenHash == TokenHashing.Sha256Hex(token))).Revoked = true;
await db.SaveChangesAsync();
});
var response = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, clientId, again.GetPublicKey()), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
/// <summary>A fresh 64-hex client id (the shape the agent derives from hardware).</summary>
private static string NewClientId() => $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
[Fact]
public async Task ExpiredTokenIsRejected()
{
var token = await CreateTokenAsync(lifetime: TimeSpan.FromMinutes(-5));
using var userKey = KeyPair.CreatePair(PrefixByte.User);
using var client = fixture.CreateClient();
var response = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, ClientId, userKey.GetPublicKey()), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task RevokedTokenIsRejected()
{
var token = await CreateTokenAsync(revoked: true);
using var userKey = KeyPair.CreatePair(PrefixByte.User);
using var client = fixture.CreateClient();
var response = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, ClientId, userKey.GetPublicKey()), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task UnknownTokenIsRejected()
{
using var userKey = KeyPair.CreatePair(PrefixByte.User);
using var client = fixture.CreateClient();
var response = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest("never-issued", ClientId, userKey.GetPublicKey()), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Theory]
[InlineData("Has.Dots")]
[InlineData("has*star")]
[InlineData("")]
public async Task InvalidClientIdIsRejected(string clientId)
{
var token = await CreateTokenAsync();
using var userKey = KeyPair.CreatePair(PrefixByte.User);
using var client = fixture.CreateClient();
var response = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, clientId, userKey.GetPublicKey()), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task InvalidNkeyIsRejected()
{
var token = await CreateTokenAsync();
using var client = fixture.CreateClient();
var response = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, ClientId, "not-a-real-nkey"), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task CredentialRefreshVerifiesPossessionOfEnrolledKey()
{
var token = await CreateTokenAsync();
var clientId = "1111aaaa2222bbbb3333cccc4444dddd5555eeee6666ffff7777888899990000";
using var userKey = KeyPair.CreatePair(PrefixByte.User);
using var client = fixture.CreateClient();
var enroll = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap, MakeRequest(token, clientId, userKey.GetPublicKey()), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.OK, enroll.StatusCode);
// Correctly signed refresh succeeds.
var timestamp = DateTimeOffset.UtcNow;
var payload = Encoding.UTF8.GetBytes($"{clientId}|{timestamp:O}");
var signature = new byte[64];
userKey.Sign(payload, signature);
var refresh = await client.PostAsJsonAsync(ApiRoutes.RefreshCredential,
new CredentialRefreshRequest(clientId, userKey.GetPublicKey(), timestamp, Convert.ToBase64String(signature)),
JsonDefaults.Options);
Assert.Equal(HttpStatusCode.OK, refresh.StatusCode);
// A different key cannot refresh.
using var wrongKey = KeyPair.CreatePair(PrefixByte.User);
wrongKey.Sign(payload, signature);
var forged = await client.PostAsJsonAsync(ApiRoutes.RefreshCredential,
new CredentialRefreshRequest(clientId, userKey.GetPublicKey(), timestamp, Convert.ToBase64String(signature)),
JsonDefaults.Options);
Assert.Equal(HttpStatusCode.Unauthorized, forged.StatusCode);
}
}