Files
Alphaeus Mote 2df42b09ed feat(security): seal, sign and replay-protect every server/agent/browser message
Envelope v2 on top of TLS and NATS permissions: AES-256-GCM with a key per
message (HKDF-SHA256 over an ECDH P-256 secret, message id as salt, direction
as info), the header (kid, type, message id, issue/expiry, sender, subject) as
associated data, and an Ed25519 signature (server signing key / agent NKey)
over header, nonce and ciphertext. v1 is still parsed from unsealed agents.

- Keys: the server's signing + ECDH key set is a Data Protection-encrypted
  setting, current + previous (7 days), rotated from Settings > Message
  Security and announced to sealed agents signed with the old key. Agents keep
  an ECDH key with their credentials and pin the server's keys at enrollment,
  or for agents enrolled earlier at their first credential renewal (HTTPS,
  proof signed with the enrolled NKey covering the message key).
- Replay: issued/expiry on every message (live 2 min, queued commands 2 days,
  job states 7 days, 5 min skew, configurable both sides); seen ids persisted
  on the agent (job store), in the database for agent events, in a bounded
  window otherwise; queued messages remembered on ack.
- Remote View and file/log/registry transfers: per-stream AES-GCM frames with
  counter nonces; duplicates and reordering refused.
- Browser NATS traffic (events, job and shell output, keystrokes) sealed per
  session with a WebCrypto ECDH key.
- Rollout: Sealed chip on the device list and page, inventory reports it,
  Require Sealed Agents (off by default) refuses v1 and sends nothing to
  unsealed agents. Job messages must be signed by the device they name.
- Migrations MessageSecurity (Sqlite, Postgres, SqlServer); README Message
  security section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 18:10:22 -05:00

475 lines
25 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using Backend.Data;
using Backend.Messaging;
using Backend.Security.Messages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NATS.NKeys;
using Shared.Contracts.Api;
using Shared.Contracts.Messages;
using Shared.Contracts.Serialization;
using Shared.Infrastructure.Security;
using Shared.Infrastructure.Security.Messaging;
using Xunit;
namespace Backend.Tests;
/// <summary>
/// The server's end of sealed messaging, through the real enrollment and renewal
/// endpoints and the real sealing service, with an agent that seals the way the
/// agent does (the shared envelope code with its NKey and ECDH key).
/// </summary>
public sealed class MessageSecurityTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
/// <summary>One device's agent: its enrolled NKey, its message key, and what it pinned.</summary>
private sealed class FakeAgent : IDisposable
{
public string ClientId { get; } = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(32));
public KeyPair Nkey { get; } = KeyPair.CreatePair(PrefixByte.User);
public ECDiffieHellman Ecdh { get; } = MessageKeys.Create();
public string MessageKey => MessageKeys.PublicKeyOf(Ecdh);
public ServerMessageKeys? Pinned { get; set; }
public byte[] Seal(string subject, string type, byte[] plaintext, TimeSpan? lifetime = null, ServerKeyInfo? to = null)
{
var server = to ?? Pinned!.Current;
using var signer = new NkeySigner(Nkey.GetSeed());
var now = DateTimeOffset.UtcNow;
return MessageSealing.ToBytes(MessageSealing.Seal(
server.Kid, type, ClientId, subject, now, now + (lifetime ?? MessageSecurityDefaults.LiveLifetime),
MessageKeys.Agree(Ecdh, server.EcdhPublic), MessageDirections.AgentToServer, plaintext, signer));
}
/// <summary>What the agent does with a server message: the pinned server's signature, then the decryption.</summary>
public byte[]? Open(byte[] data, string subject, ServerKeyInfo? from = null)
{
var server = from ?? Pinned!.Current;
var envelope = MessageSealing.Parse(data);
return envelope is not null && envelope.Subject == subject && envelope.Kid == server.Kid
&& MessageSealing.VerifySignature(envelope, server.SigningPublic)
? MessageSealing.TryDecrypt(envelope, MessageKeys.Agree(Ecdh, server.EcdhPublic), MessageDirections.ServerToAgent)
: null;
}
public void Dispose()
{
Nkey.Dispose();
Ecdh.Dispose();
}
}
private ServerMessageSecurity Security => fixture.Services.GetRequiredService<ServerMessageSecurity>();
private async Task<string> TokenAsync()
{
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 + TimeSpan.FromHours(1),
MaxUses = 0,
});
await db.SaveChangesAsync();
});
return token;
}
private async Task<HttpResponseMessage> EnrollAsync(FakeAgent agent, bool withKey = true, string? messageKey = null)
{
using var client = fixture.CreateClient();
var response = await client.PostAsJsonAsync(ApiRoutes.Bootstrap, new BootstrapRequest(
await TokenAsync(), agent.ClientId, agent.Nkey.GetPublicKey(), "2026.11.06.0000",
new EnrollDeviceInfo("PC-" + agent.ClientId[..6], null, null, "Windows 11", "10.0.26200"),
withKey ? messageKey ?? agent.MessageKey : null), JsonDefaults.Options);
if (response.IsSuccessStatusCode)
{
agent.Pinned = (await response.Content.ReadFromJsonAsync<BootstrapResponse>(JsonDefaults.Options))!.ServerKeys;
}
return response;
}
private async Task<HttpResponseMessage> RenewAsync(FakeAgent agent, string? proof = null, KeyPair? signWith = null)
{
var timestamp = DateTimeOffset.UtcNow;
var signature = new byte[64];
(signWith ?? agent.Nkey).Sign(Encoding.UTF8.GetBytes(proof ?? MessageSecurityNames.KeyExchangeProof(agent.ClientId, timestamp, agent.MessageKey)), signature);
using var client = fixture.CreateClient();
var response = await client.PostAsJsonAsync(ApiRoutes.RefreshCredential, new CredentialRefreshRequest(
agent.ClientId, agent.Nkey.GetPublicKey(), timestamp, Convert.ToBase64String(signature), agent.MessageKey, "2026.11.06.0000"),
JsonDefaults.Options);
if (response.IsSuccessStatusCode)
{
agent.Pinned = (await response.Content.ReadFromJsonAsync<CredentialRefreshResponse>(JsonDefaults.Options))!.ServerKeys;
}
return response;
}
private Task<DeviceEntity?> DeviceAsync(string clientId)
=> fixture.WithDbAsync(db => db.Devices.AsNoTracking().SingleOrDefaultAsync(d => d.ClientId == clientId));
[Fact]
public async Task EnrollmentRecordsTheMessageKeyAndPinsTheServersKeys()
{
using var agent = new FakeAgent();
Assert.Equal(HttpStatusCode.OK, (await EnrollAsync(agent)).StatusCode);
Assert.NotNull(agent.Pinned);
Assert.Equal(Security.Keys.Current.Info, agent.Pinned!.Current);
var device = await DeviceAsync(agent.ClientId);
Assert.Equal(agent.MessageKey, device!.MessageKeyPublic);
Assert.Equal(device.MessageKeyUtc!.Value.ToUnixTimeMilliseconds(), agent.Pinned.SealedSinceUtc.ToUnixTimeMilliseconds());
Assert.Equal("2026.11.06.0000", device.MessageKeyAgentVersion);
using var admin = await fixture.SignedInAsync("sealing-admin");
var dto = await admin.GetFromJsonAsync<DeviceDetailDto>(ApiRoutes.For.Device(agent.ClientId), JsonDefaults.Options);
Assert.True(dto!.Device.Sealed);
}
[Fact]
public async Task AnOlderAgentEnrollsUnsealedAndReEnrollingWithoutAKeyDropsOne()
{
using var agent = new FakeAgent();
await EnrollAsync(agent);
Assert.NotNull((await DeviceAsync(agent.ClientId))!.MessageKeyPublic);
Assert.Equal(HttpStatusCode.OK, (await EnrollAsync(agent, withKey: false)).StatusCode);
Assert.Null(agent.Pinned);
Assert.Null((await DeviceAsync(agent.ClientId))!.MessageKeyPublic);
}
[Fact]
public async Task AMalformedMessageKeyIsRefused()
{
using var agent = new FakeAgent();
using var p384 = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP384);
Assert.Equal(HttpStatusCode.BadRequest, (await EnrollAsync(agent, messageKey: "garbage")).StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, (await EnrollAsync(agent, messageKey: Convert.ToBase64String(p384.ExportSubjectPublicKeyInfo()))).StatusCode);
}
[Fact]
public async Task AnExistingAgentExchangesKeysOverItsSignedRenewal()
{
using var agent = new FakeAgent();
await EnrollAsync(agent, withKey: false);
Assert.Null((await DeviceAsync(agent.ClientId))!.MessageKeyPublic);
// A proof that does not cover the message key (or another key's signature) is refused.
var timestamp = DateTimeOffset.UtcNow;
Assert.Equal(HttpStatusCode.Unauthorized, (await RenewAsync(agent, proof: $"{agent.ClientId}|{timestamp:O}")).StatusCode);
using var stranger = KeyPair.CreatePair(PrefixByte.User);
Assert.Equal(HttpStatusCode.Unauthorized, (await RenewAsync(agent, signWith: stranger)).StatusCode);
Assert.Null((await DeviceAsync(agent.ClientId))!.MessageKeyPublic);
Assert.Equal(HttpStatusCode.OK, (await RenewAsync(agent)).StatusCode);
Assert.Equal(agent.MessageKey, (await DeviceAsync(agent.ClientId))!.MessageKeyPublic);
Assert.Equal(Security.Keys.Current.Info, agent.Pinned!.Current);
Assert.True(await fixture.WithDbAsync(db => db.AuditEvents.AnyAsync(a => a.ClientId == agent.ClientId && a.Action == "message-key-recorded")));
// Renewing again with the same key keeps when it was recorded.
var since = agent.Pinned.SealedSinceUtc;
await RenewAsync(agent);
Assert.Equal(since, agent.Pinned.SealedSinceUtc);
}
[Fact]
public async Task WhatTheServerSendsASealedDeviceOnlyThatDeviceOpens()
{
using var agent = new FakeAgent();
using var other = new FakeAgent();
await EnrollAsync(agent);
await EnrollAsync(other);
var subject = $"agent.{agent.ClientId}.command.script";
var plaintext = Encoding.UTF8.GetBytes("""{"payload":{"script":"Write-Output $secret"}}""");
var outgoing = await Security.SealForAgentAsync(agent.ClientId, subject, MessageTypes.CommandScript, plaintext,
MessageSecurityDefaults.DurableCommandLifetime, fresh: true, cancellationToken: TestContext.Current.CancellationToken);
Assert.True(outgoing!.Sealed);
Assert.DoesNotContain("secret", Encoding.UTF8.GetString(outgoing.Data), StringComparison.Ordinal);
Assert.Equal(plaintext, agent.Open(outgoing.Data, subject));
Assert.Null(other.Open(outgoing.Data, subject));
Assert.Null(agent.Open(outgoing.Data, $"agent.{agent.ClientId}.command.file"));
var envelope = MessageSealing.Parse(outgoing.Data)!;
Assert.Equal(MessageSecurityDefaults.DurableCommandLifetime, envelope.ExpiresUtc - envelope.IssuedUtc);
}
[Fact]
public async Task ADeviceThatDoesNotSealIsSentV1UntilRequireSealedAgents()
{
using var agent = new FakeAgent();
await EnrollAsync(agent, withKey: false);
var plaintext = Encoding.UTF8.GetBytes("{}");
var subject = $"agent.{agent.ClientId}.command.inventory";
var outgoing = await Security.SealForAgentAsync(agent.ClientId, subject, MessageTypes.CommandInventory, plaintext, fresh: true,
cancellationToken: TestContext.Current.CancellationToken);
Assert.False(outgoing!.Sealed);
Assert.Same(plaintext, outgoing.Data);
var taken = await Security.OpenFromAgentAsync($"agent.{agent.ClientId}.presence", plaintext, agent.ClientId, ServerReceipt.Live,
cancellationToken: TestContext.Current.CancellationToken);
Assert.False(taken.Message!.Sealed);
using var admin = await fixture.SignedInAsync("sealing-require");
try
{
var saved = await (await admin.PutAsJsonAsync(ApiRoutes.MessageSecuritySettings, new SaveMessageSecuritySettingsRequest(true), JsonDefaults.Options))
.Content.ReadFromJsonAsync<MessageSecuritySettingsDto>(JsonDefaults.Options);
Assert.True(saved!.RequireSealed);
Assert.True(saved.UnsealedDevices >= 1);
Assert.Null(await Security.SealForAgentAsync(agent.ClientId, subject, MessageTypes.CommandInventory, plaintext, fresh: true,
cancellationToken: TestContext.Current.CancellationToken));
var refused = await Security.OpenFromAgentAsync($"agent.{agent.ClientId}.presence", plaintext, agent.ClientId, ServerReceipt.Live,
cancellationToken: TestContext.Current.CancellationToken);
Assert.Null(refused.Message);
Assert.False(await Security.AcceptsUnsealedAsync(agent.ClientId, null, TestContext.Current.CancellationToken));
}
finally
{
await admin.PutAsJsonAsync(ApiRoutes.MessageSecuritySettings, new SaveMessageSecuritySettingsRequest(false), JsonDefaults.Options);
}
Assert.False(Security.RequireSealed);
}
[Fact]
public async Task ASealedDevicesMessagesOpenOnlyFromItOnItsSubjectOnce()
{
using var agent = new FakeAgent();
using var impostor = new FakeAgent();
await EnrollAsync(agent);
await EnrollAsync(impostor);
var ct = TestContext.Current.CancellationToken;
var subject = $"agent.{agent.ClientId}.presence";
var wire = agent.Seal(subject, MessageTypes.AgentPresence, Encoding.UTF8.GetBytes("{\"payload\":{}}"));
var opened = await Security.OpenFromAgentAsync(subject, wire, agent.ClientId, ServerReceipt.Live, cancellationToken: ct);
Assert.True(opened.Message!.Sealed);
Assert.Equal(agent.ClientId, opened.Message.Sender);
// Again: a replay.
Assert.Equal(MessageRefusal.Replay, (await Security.OpenFromAgentAsync(subject, wire, agent.ClientId, ServerReceipt.Live, cancellationToken: ct)).Refusal);
// On another subject, or naming another device than the subject's.
Assert.Null((await Security.OpenFromAgentAsync($"agent.{agent.ClientId}.inventory", agent.Seal(subject, MessageTypes.AgentPresence, [1]), agent.ClientId, ServerReceipt.Live, cancellationToken: ct)).Message);
Assert.Null((await Security.OpenFromAgentAsync(subject, agent.Seal(subject, MessageTypes.AgentPresence, [1]), impostor.ClientId, ServerReceipt.Live, cancellationToken: ct)).Message);
// Another device claiming to be this one (its own key signs, the claimed one's does not verify).
var forged = MessageSealing.Parse(impostor.Seal(subject, MessageTypes.AgentPresence, [1]))! with { Sender = agent.ClientId };
Assert.Null((await Security.OpenFromAgentAsync(subject, MessageSealing.ToBytes(forged), agent.ClientId, ServerReceipt.Live, cancellationToken: ct)).Message);
// V1 from a device that seals.
var v1 = MessageEnvelope.Create(MessageTypes.AgentPresence, new EndpointRef(EndpointKinds.Agent, agent.ClientId), new { }).ToUtf8Bytes();
Assert.Null((await Security.OpenFromAgentAsync(subject, v1, agent.ClientId, ServerReceipt.Live, cancellationToken: ct)).Message);
}
[Fact]
public async Task OnAJobSubjectTheClaimedDeviceMustBeTheSender()
{
using var agent = new FakeAgent();
using var unsealed = new FakeAgent();
await EnrollAsync(agent);
await EnrollAsync(unsealed, withKey: false);
var ct = TestContext.Current.CancellationToken;
var subject = $"job.{Guid.NewGuid()}.output";
var opened = await Security.OpenFromAgentAsync(subject, agent.Seal(subject, MessageTypes.JobOutput, [1]), null, ServerReceipt.Live, cancellationToken: ct);
Assert.Equal(agent.ClientId, opened.Message!.Sender);
// Unsealed job messages are taken only for a device that does not seal.
var v1 = await Security.OpenFromAgentAsync(subject, Encoding.UTF8.GetBytes("{}"), null, ServerReceipt.Live, cancellationToken: ct);
Assert.False(v1.Message!.Sealed);
Assert.True(await Security.AcceptsUnsealedAsync(unsealed.ClientId, null, ct));
Assert.False(await Security.AcceptsUnsealedAsync(agent.ClientId, null, ct));
// Unless the stream stored it before the device's key was recorded.
var since = (await DeviceAsync(agent.ClientId))!.MessageKeyUtc!.Value;
Assert.True(await Security.AcceptsUnsealedAsync(agent.ClientId, since - TimeSpan.FromSeconds(1), ct));
}
[Fact]
public async Task AJobStateIsRememberedOnlyOnceAcknowledged()
{
using var agent = new FakeAgent();
await EnrollAsync(agent);
var ct = TestContext.Current.CancellationToken;
var subject = $"job.{Guid.NewGuid()}.state";
var wire = agent.Seal(subject, MessageTypes.JobState, [1], MessageSecurityDefaults.JobStateLifetime);
var first = await Security.OpenFromAgentAsync(subject, wire, null, ServerReceipt.Durable, DateTimeOffset.UtcNow, ct);
Assert.NotNull((await Security.OpenFromAgentAsync(subject, wire, null, ServerReceipt.Durable, DateTimeOffset.UtcNow, ct)).Message);
Security.Remember(first.Message!);
Assert.Equal(MessageRefusal.Replay, (await Security.OpenFromAgentAsync(subject, wire, null, ServerReceipt.Durable, DateTimeOffset.UtcNow, ct)).Refusal);
}
[Fact]
public async Task AnEventIsTakenOnceByEveryReplica()
{
using var agent = new FakeAgent();
await EnrollAsync(agent);
var ct = TestContext.Current.CancellationToken;
var subject = $"agent.{agent.ClientId}.event";
var wire = agent.Seal(subject, MessageTypes.AgentRunRequest, [1]);
Assert.NotNull((await Security.OpenFromAgentAsync(subject, wire, agent.ClientId, ServerReceipt.Event, cancellationToken: ct)).Message);
// Another replica: its own memory, the same database.
var replica = new ServerMessageSecurity(
Security.Keys, new DeviceKeyCache(fixture.Services.GetRequiredService<IServiceScopeFactory>()),
fixture.Services.GetRequiredService<IServiceScopeFactory>(), fixture.Services.GetRequiredService<IConfiguration>(),
NullLogger<ServerMessageSecurity>.Instance);
Assert.Equal(MessageRefusal.Replay, (await replica.OpenFromAgentAsync(subject, wire, agent.ClientId, ServerReceipt.Event, cancellationToken: ct)).Refusal);
var messageId = MessageSealing.Parse(wire)!.MessageId;
Assert.Equal(1, await fixture.WithDbAsync(db => db.SeenMessages.CountAsync(m => m.MessageId == messageId)));
}
[Fact]
public async Task AStaleMessageIsRefused()
{
using var agent = new FakeAgent();
await EnrollAsync(agent);
var subject = $"agent.{agent.ClientId}.presence";
using var signer = new NkeySigner(agent.Nkey.GetSeed());
var issued = DateTimeOffset.UtcNow - TimeSpan.FromMinutes(10);
var stale = MessageSealing.ToBytes(MessageSealing.Seal(
agent.Pinned!.Current.Kid, MessageTypes.AgentPresence, agent.ClientId, subject, issued, issued + MessageSecurityDefaults.LiveLifetime,
MessageKeys.Agree(agent.Ecdh, agent.Pinned.Current.EcdhPublic), MessageDirections.AgentToServer, [1], signer));
Assert.Null((await Security.OpenFromAgentAsync(subject, stale, agent.ClientId, ServerReceipt.Live, cancellationToken: TestContext.Current.CancellationToken)).Message);
Assert.Equal(TimeSpan.FromMinutes(5), Security.ClockSkew);
}
[Fact]
public async Task StreamKeysAgreeWithTheDevicesEnd()
{
using var agent = new FakeAgent();
await EnrollAsync(agent);
var streamId = Guid.NewGuid();
var opening = await Security.SealForAgentAsync(agent.ClientId, $"agent.{agent.ClientId}.command.screen.open", MessageTypes.CommandScreenOpen, [1],
cancellationToken: TestContext.Current.CancellationToken);
var server = Security.StreamCipher(opening!, streamId, StreamPurposes.Screen)!;
var device = StreamCipher.ForAgent(MessageKeys.Agree(agent.Ecdh, agent.Pinned!.Current.EcdhPublic), streamId, StreamPurposes.Screen);
Assert.Equal(new byte[] { 1, 2 }, device.Open(server.Seal([1, 2])));
Assert.Equal(new byte[] { 3 }, server.Open(device.Seal([3])));
}
[Fact]
public async Task ARotationKeepsTheOldKeyAcceptedAndIsAnnouncedUnderIt()
{
using var agent = new FakeAgent();
await EnrollAsync(agent);
var ct = TestContext.Current.CancellationToken;
var before = agent.Pinned!.Current;
using var admin = await fixture.SignedInAsync("sealing-rotate");
var rotation = await (await admin.PostAsync(ApiRoutes.MessageSecurityRotate, null, ct)).Content.ReadFromJsonAsync<MessageKeyRotationDto>(JsonDefaults.Options, ct);
Assert.Equal(before.Kid, rotation!.PreviousKeyId);
Assert.NotEqual(before.Kid, rotation.CurrentKeyId);
Assert.Equal(rotation.CurrentKeyId, Security.Keys.Current.Kid);
Assert.Equal(before.Kid, Security.Keys.Previous!.Kid);
// The agent still on the old key is understood, and is told about the new one under the old key.
var subject = $"agent.{agent.ClientId}.presence";
Assert.NotNull((await Security.OpenFromAgentAsync(subject, agent.Seal(subject, MessageTypes.AgentPresence, [1], to: before), agent.ClientId, ServerReceipt.Live, cancellationToken: ct)).Message);
var payload = new ServerKeyRotationPayload(Security.Keys.Current.Info, DateTimeOffset.UtcNow);
var keysSubject = $"agent.{agent.ClientId}.command.keys";
var announcement = await Security.SealForAgentAsync(agent.ClientId, keysSubject, MessageTypes.CommandKeyRotation,
JsonDefaults.SerializeToUtf8Bytes(payload), MessageSecurityDefaults.DurableCommandLifetime, true, Security.Keys.Previous, ct);
Assert.Equal(JsonDefaults.SerializeToUtf8Bytes(payload), agent.Open(announcement!.Data, keysSubject, from: before));
// The renewal hands out both.
await RenewAsync(agent);
Assert.Equal(rotation.CurrentKeyId, agent.Pinned!.Current.Kid);
Assert.Equal(before.Kid, agent.Pinned.Previous!.Kid);
// The settings say so.
var settings = await admin.GetFromJsonAsync<MessageSecuritySettingsDto>(ApiRoutes.MessageSecuritySettings, JsonDefaults.Options, ct);
Assert.Equal(rotation.CurrentKeyId, settings!.CurrentKeyId);
Assert.Equal(before.Kid, settings.PreviousKeyId);
}
[Fact]
public async Task ServerKeysAreKeptEncryptedInTheDatabase()
{
await Security.Keys.EnsureLoadedAsync(TestContext.Current.CancellationToken);
var row = await fixture.WithDbAsync(db => db.AppSettings.AsNoTracking().SingleAsync(s => s.Key == ServerKeyRing.KeysSetting));
Assert.True(row.IsSecret);
Assert.DoesNotContain("signingSeed", row.Value!, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("BEGIN", row.Value!, StringComparison.Ordinal);
}
[Fact]
public async Task AnUpgradeToAnOlderVersionThanTheKeyExchangeDropsTheKey()
{
using var agent = new FakeAgent();
await EnrollAsync(agent);
var ct = TestContext.Current.CancellationToken;
await Security.NoteUpgradeAsync(agent.ClientId, "2026.12.01.0000", ct);
Assert.NotNull((await DeviceAsync(agent.ClientId))!.MessageKeyPublic);
await Security.NoteUpgradeAsync(agent.ClientId, "2026.10.01.0000", ct);
Assert.Null((await DeviceAsync(agent.ClientId))!.MessageKeyPublic);
Assert.False((await Security.SealForAgentAsync(agent.ClientId, "agent.x.command.inventory", MessageTypes.CommandInventory, [1], fresh: true, cancellationToken: ct))!.Sealed);
}
[Fact]
public async Task ABrowserTabGetsASealedChannelAndOnlyItsSealedInputIsTaken()
{
using var client = await fixture.SignedInAsync("sealing-browser");
using var tab = MessageKeys.Create();
using var nkey = KeyPair.CreatePair(PrefixByte.User);
var ct = TestContext.Current.CancellationToken;
var credential = await (await client.PostAsJsonAsync(ApiRoutes.BrowserNatsCredential,
new BrowserCredentialRequest(nkey.GetPublicKey(), null, MessageKeys.PublicKeyOf(tab)), JsonDefaults.Options, ct))
.Content.ReadFromJsonAsync<BrowserCredentialResponse>(JsonDefaults.Options, ct);
Assert.NotNull(credential!.MessageKeyPublic);
var secret = MessageKeys.Agree(tab, credential.MessageKeyPublic!);
var sessions = fixture.Services.GetRequiredService<BrowserSessionRegistry>();
var broadcaster = fixture.Services.GetRequiredService<BrowserEventBroadcaster>();
var session = sessions.Find(credential.BrowserSessionId)!;
// Server to tab.
var eventSubject = $"browser.{credential.BrowserSessionId}.event";
var sealedEvent = MessageSealing.Parse(BrowserEventBroadcaster.SealForBrowser(session, eventSubject, MessageTypes.BrowserEvent, [4, 2]))!;
Assert.Equal(new byte[] { 4, 2 }, MessageSealing.TryDecrypt(sealedEvent, secret, MessageDirections.ServerToBrowser));
// Tab to server: sealed by the tab for its input subject, once.
var input = $"browser.{credential.BrowserSessionId}.shell.{Guid.NewGuid()}.input";
var now = DateTimeOffset.UtcNow;
var keystroke = MessageSealing.ToBytes(MessageSealing.Seal(credential.MessageKeyId!, "shell.input", credential.BrowserSessionId, input,
now, now + MessageSecurityDefaults.LiveLifetime, secret, MessageDirections.BrowserToServer, [7], signer: null));
Assert.Equal(new byte[] { 7 }, broadcaster.OpenFromBrowser(credential.BrowserSessionId, input, keystroke));
Assert.Null(broadcaster.OpenFromBrowser(credential.BrowserSessionId, input, keystroke));
Assert.Null(broadcaster.OpenFromBrowser(credential.BrowserSessionId, input, Encoding.UTF8.GetBytes("""{"messageType":"shell.input"}""")));
// The refreshed credential keeps the channel; another user cannot take the session over.
var refreshed = await (await client.PostAsJsonAsync(ApiRoutes.BrowserNatsCredential,
new BrowserCredentialRequest(nkey.GetPublicKey(), credential.BrowserSessionId, MessageKeys.PublicKeyOf(tab)), JsonDefaults.Options, ct))
.Content.ReadFromJsonAsync<BrowserCredentialResponse>(JsonDefaults.Options, ct);
Assert.Equal(credential.MessageKeyId, refreshed!.MessageKeyId);
using var other = await fixture.SignedInAsync("sealing-browser-other");
var taken = await (await other.PostAsJsonAsync(ApiRoutes.BrowserNatsCredential,
new BrowserCredentialRequest(nkey.GetPublicKey(), credential.BrowserSessionId, MessageKeys.PublicKeyOf(tab)), JsonDefaults.Options, ct))
.Content.ReadFromJsonAsync<BrowserCredentialResponse>(JsonDefaults.Options, ct);
Assert.NotEqual(credential.BrowserSessionId, taken!.BrowserSessionId);
}
}