From c313cde7e7061ba8c55ddc8595d449c06fdf09074897170c41877634e032f5af Mon Sep 17 00:00:00 2001 From: gsadmin Date: Mon, 10 Aug 2026 16:36:20 -0400 Subject: [PATCH 1/6] Triggers: groups-only targets, time-zone dropdown, enable/disable [skip ci] - Trigger target selector now offers All devices + groups only (no per-device list, which is unusable in large fleets). - The cadence editor time zone is a dropdown (full IANA list via Intl.supportedValuesOf, shortlist fallback) instead of free text. - Triggers can be disabled without deleting: new PATCH /api/triggers/{id} flips Enabled (re-enabling a recurring schedule advances NextRunUtc past due so it does not fire a backlog); the card shows an Enable/Disable button and dims disabled rows. The worker and lifecycle service already skip disabled triggers, so this actually gates firing. Backend builds; 103 backend tests pass; svelte-check clean. Co-Authored-By: Claude Fable 5 --- src/Backend/Groups/TriggerEndpoints.cs | 34 ++++++++++++ src/Shared.Contracts/Api/ResourceDtos.cs | 3 ++ src/WebUI/src/lib/api/client.ts | 2 + .../components/ScheduleCadenceEditor.svelte | 33 +++++++++++- .../src/lib/components/TriggersCard.svelte | 54 +++++++++++++------ .../src/routes/scripts/[id]/+page.svelte | 2 +- 6 files changed, 109 insertions(+), 19 deletions(-) diff --git a/src/Backend/Groups/TriggerEndpoints.cs b/src/Backend/Groups/TriggerEndpoints.cs index e714f0a..845a518 100644 --- a/src/Backend/Groups/TriggerEndpoints.cs +++ b/src/Backend/Groups/TriggerEndpoints.cs @@ -14,6 +14,7 @@ public static class TriggerEndpoints { app.MapGet(ApiRoutes.Triggers, ListAsync).RequirePermission(Permissions.AutomationView); app.MapPost(ApiRoutes.Triggers, CreateAsync).RequirePermission(Permissions.AutomationManage); + app.MapPatch(ApiRoutes.Trigger, SetEnabledAsync).RequirePermission(Permissions.AutomationManage); app.MapDelete(ApiRoutes.Trigger, DeleteAsync).RequirePermission(Permissions.AutomationManage); } @@ -109,6 +110,39 @@ public static class TriggerEndpoints return Results.Created(ApiRoutes.For.Trigger(entity.Id), new { id = entity.Id }); } + private static async Task SetEnabledAsync( + Guid id, SetTriggerEnabledRequest request, AppDbContext db, CancellationToken cancellationToken) + { + var entity = await db.ScriptTriggers.SingleOrDefaultAsync(t => t.Id == id, cancellationToken); + if (entity is null) + { + return Results.NotFound(); + } + + entity.Enabled = request.Enabled; + + // Re-enabling a recurring schedule whose next run already passed would + // fire a backlog on the next sweep; advance it to the next future run. + if (request.Enabled + && entity.TriggerType == ScriptTriggerType.Scheduled + && !string.IsNullOrWhiteSpace(entity.CronExpression) + && (entity.NextRunUtc is null || entity.NextRunUtc <= DateTimeOffset.UtcNow)) + { + try + { + entity.NextRunUtc = ScheduleCron.NextOccurrence( + entity.CronExpression!, entity.TimeZoneId, DateTimeOffset.UtcNow); + } + catch (Exception) + { + // An unparseable cron simply won't fire; leave NextRunUtc as-is. + } + } + + await db.SaveChangesAsync(cancellationToken); + return Results.NoContent(); + } + private static async Task DeleteAsync(Guid id, AppDbContext db, CancellationToken cancellationToken) { var entity = await db.ScriptTriggers.SingleOrDefaultAsync(t => t.Id == id, cancellationToken); diff --git a/src/Shared.Contracts/Api/ResourceDtos.cs b/src/Shared.Contracts/Api/ResourceDtos.cs index 8dddbbc..6209307 100644 --- a/src/Shared.Contracts/Api/ResourceDtos.cs +++ b/src/Shared.Contracts/Api/ResourceDtos.cs @@ -87,6 +87,9 @@ public sealed record SaveScriptTriggerRequest( string? TimeZoneId = null, IReadOnlyDictionary? Arguments = null); +/// PATCH /api/triggers/{id} — enable or disable a trigger without deleting it. +public sealed record SetTriggerEnabledRequest(bool Enabled); + /// Device detail for GET /api/devices/{clientId}. public sealed record DeviceDetailDto( DeviceDto Device, diff --git a/src/WebUI/src/lib/api/client.ts b/src/WebUI/src/lib/api/client.ts index 2504930..64719f5 100644 --- a/src/WebUI/src/lib/api/client.ts +++ b/src/WebUI/src/lib/api/client.ts @@ -246,6 +246,8 @@ export const api = { timeZoneId?: string; arguments?: Record; }) => request<{ id: string }>('/api/triggers', { method: 'POST', body: JSON.stringify(body) }), + setTriggerEnabled: (id: string, enabled: boolean) => + request(`/api/triggers/${id}`, { method: 'PATCH', body: JSON.stringify({ enabled }) }), deleteTrigger: (id: string) => request(`/api/triggers/${id}`, { method: 'DELETE' }), // Messaging diff --git a/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte b/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte index 4571261..5ad4ec2 100644 --- a/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte +++ b/src/WebUI/src/lib/components/ScheduleCadenceEditor.svelte @@ -54,6 +54,33 @@ const allDays = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']; + // Full IANA list where the browser exposes it (all modern engines do), + // falling back to a common shortlist. UTC is always first/selectable. + const timeZones: string[] = (() => { + try { + const all = (Intl as unknown as { supportedValuesOf?: (k: string) => string[] }) + .supportedValuesOf?.('timeZone'); + if (all && all.length > 0) { + return ['UTC', ...all.filter((z) => z !== 'UTC')]; + } + } catch { + // Older engine — fall through to the shortlist. + } + return [ + 'UTC', + 'America/New_York', + 'America/Chicago', + 'America/Denver', + 'America/Los_Angeles', + 'Europe/London', + 'Europe/Paris', + 'Europe/Berlin', + 'Asia/Tokyo', + 'Asia/Singapore', + 'Australia/Sydney' + ]; + })(); + const frequencies: { value: Freq; label: string }[] = [ { value: 'minutes', label: 'Every N minutes' }, { value: 'hours', label: 'Every N hours' }, @@ -180,7 +207,11 @@ {#if freq !== 'once'} {/if} diff --git a/src/WebUI/src/lib/components/TriggersCard.svelte b/src/WebUI/src/lib/components/TriggersCard.svelte index 21cc1d2..e394dfd 100644 --- a/src/WebUI/src/lib/components/TriggersCard.svelte +++ b/src/WebUI/src/lib/components/TriggersCard.svelte @@ -4,21 +4,14 @@ import ScheduleCadenceEditor, { type CadenceValue } from '$lib/components/ScheduleCadenceEditor.svelte'; - import type { - DeviceGroupDto, - DeviceDto, - ScriptTriggerDto, - ScriptTriggerType - } from '$lib/api/types'; + import type { DeviceGroupDto, ScriptTriggerDto, ScriptTriggerType } from '$lib/api/types'; let { scriptId, - groups, - devices = [] + groups }: { scriptId: string; groups: DeviceGroupDto[]; - devices?: DeviceDto[]; } = $props(); let triggers = $state([]); @@ -86,6 +79,11 @@ } } + async function toggle(trigger: ScriptTriggerDto) { + await api.setTriggerEnabled(trigger.id, !trigger.enabled).catch(() => {}); + await refresh(); + } + async function remove(id: string) { await api.deleteTrigger(id); await refresh(); @@ -126,11 +124,6 @@ {/each} - - {#each devices as device (device.clientId)} - - {/each} - @@ -144,16 +137,23 @@ {:else}
    {#each mine as trigger (trigger.id)} -
  • +
  • {whenLabel(trigger)} → {targetLabel(trigger)} - {#if trigger.triggerType === 'scheduled' && trigger.nextRunUtc} + {#if !trigger.enabled} + Disabled + {:else if trigger.triggerType === 'scheduled' && trigger.nextRunUtc} · next {new Date(trigger.nextRunUtc).toLocaleString()} {/if} {#if trigger.lastResult}· {trigger.lastResult}{/if}
    - +
    + + +
  • {/each}
@@ -222,10 +222,30 @@ gap: 6px; } + .tactions { + display: flex; + gap: 6px; + flex-shrink: 0; + } + .twhen { font-weight: 500; } + .list li.off { + opacity: 0.55; + } + + .pill { + font-size: 10.5px; + text-transform: uppercase; + letter-spacing: 0.04em; + padding: 1px 7px; + border-radius: 999px; + border: 1px solid var(--border); + color: var(--text-muted); + } + .tiny { padding: 3px 8px; font-size: 11px; diff --git a/src/WebUI/src/routes/scripts/[id]/+page.svelte b/src/WebUI/src/routes/scripts/[id]/+page.svelte index eb96643..cf19edd 100644 --- a/src/WebUI/src/routes/scripts/[id]/+page.svelte +++ b/src/WebUI/src/routes/scripts/[id]/+page.svelte @@ -587,7 +587,7 @@ {#if !isNew && loaded} - + {/if} -- 2.52.0 From c5c0432ad38454b74266e4eab9947f73480ee1fc2cc19386f0a4fc4016ebb30f Mon Sep 17 00:00:00 2001 From: gsadmin Date: Mon, 10 Aug 2026 16:47:55 -0400 Subject: [PATCH 2/6] Fix Linux/macOS remote shell: raw PTY I/O so input reaches the shell [skip ci] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The forkpty session drove both directions through one FileStream over the PTY master. On Unix, FileStream serializes its async read and write behind a single semaphore, so the always-pending output ReadAsync held it and every input WriteAsync blocked forever — the shell opened but keystrokes never arrived (`Shell session ... opened (/bin/bash)`, then dead). Windows was fine because ConPTY uses separate input/output pipes. Drive the master fd with raw read(2)/write(2)/close(2) instead: the read loop runs on a dedicated thread, writes take a short lock for ordering/partial writes, and the two directions no longer contend. Agent builds on both TFMs. Co-Authored-By: Claude Fable 5 --- src/Agent/Shell/UnixPtySession.cs | 87 +++++++++++++++++++++++-------- 1 file changed, 64 insertions(+), 23 deletions(-) diff --git a/src/Agent/Shell/UnixPtySession.cs b/src/Agent/Shell/UnixPtySession.cs index e544d59..7129966 100644 --- a/src/Agent/Shell/UnixPtySession.cs +++ b/src/Agent/Shell/UnixPtySession.cs @@ -1,7 +1,6 @@ #if !WINDOWS_AGENT using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; namespace Agent.Shell; @@ -12,12 +11,17 @@ namespace Agent.Shell; /// detection all work). Terminal output is delivered via /// ; input is written with /// . +/// +/// I/O goes straight through read(2)/write(2) on the master fd rather than a +/// FileStream: a FileStream serializes its async read and write behind one +/// semaphore, so the always-pending output read would block every input write +/// (the shell opens but you cannot type). The raw syscalls are independent. /// internal sealed class UnixPtySession : IPtySession { private int masterFd = -1; private int childPid = -1; - private FileStream? io; + private readonly Lock writeLock = new(); private readonly CancellationTokenSource lifetime = new(); private bool disposed; @@ -67,9 +71,10 @@ internal sealed class UnixPtySession : IPtySession childPid = pid; masterFd = Marshal.ReadInt32(masterPtr); - io = new FileStream(new SafeFileHandle((IntPtr)masterFd, ownsHandle: true), FileAccess.ReadWrite); - _ = Task.Run(PumpOutputAsync); + // Dedicated thread for the blocking read loop; a threadpool thread + // would be parked indefinitely waiting for terminal output. + new Thread(ReadLoop) { IsBackground = true, Name = "pty-read" }.Start(); _ = Task.Run(WatchProcessAsync); } finally @@ -82,15 +87,39 @@ internal sealed class UnixPtySession : IPtySession } } - public async Task WriteAsync(ReadOnlyMemory data, CancellationToken cancellationToken) + public Task WriteAsync(ReadOnlyMemory data, CancellationToken cancellationToken) { - if (io is null) + WriteAll(data.Span); + return Task.CompletedTask; + } + + // write(2) is independent of the read loop, so input is delivered even while + // a read is pending. The lock keeps concurrent writes in order and handles + // partial writes. + private unsafe void WriteAll(ReadOnlySpan data) + { + if (masterFd < 0) { return; } - await io.WriteAsync(data, cancellationToken); - await io.FlushAsync(cancellationToken); + lock (writeLock) + { + fixed (byte* p = data) + { + var total = 0; + while (total < data.Length) + { + var written = Native.write(masterFd, p + total, (nuint)(data.Length - total)); + if (written <= 0) + { + break; // fd closed on teardown, or EIO once the child exited + } + + total += (int)written; + } + } + } } public void Resize(int cols, int rows) @@ -108,26 +137,32 @@ internal sealed class UnixPtySession : IPtySession _ = Native.ioctl(masterFd, Native.TIOCSWINSZ, ref win); } - private async Task PumpOutputAsync() + private unsafe void ReadLoop() { var buffer = new byte[4096]; try { while (!lifetime.IsCancellationRequested) { - var read = await io!.ReadAsync(buffer, lifetime.Token); - if (read == 0) + nint read; + fixed (byte* p = buffer) { - break; + read = Native.read(masterFd, p, (nuint)buffer.Length); } - OutputReceived?.Invoke(buffer.AsMemory(0, read).ToArray()); + if (read <= 0) + { + break; // 0 = EOF; -1 = EIO on the master when the slave closes / fd closed + } + + var chunk = new byte[read]; + Buffer.BlockCopy(buffer, 0, chunk, 0, (int)read); + OutputReceived?.Invoke(chunk); } } catch (Exception) { - // EIO on the master when the slave closes (child exited), or the - // stream was disposed on shutdown. + // fd closed underneath the read on shutdown. } } @@ -163,20 +198,17 @@ internal sealed class UnixPtySession : IPtySession disposed = true; lifetime.Cancel(); - // Closing the master hangs up the slave (SIGHUP → the shell exits); - // send SIGTERM as well in case it ignores the hangup, then reap. + // Closing the master hangs up the slave (SIGHUP → the shell exits) and + // unblocks the read loop; SIGTERM covers a shell that ignores the hangup. if (childPid > 0) { _ = Native.kill(childPid, Native.SIGTERM); } - try + if (masterFd >= 0) { - io?.Dispose(); - } - catch (IOException) - { - // Master already closed. + _ = Native.close(masterFd); + masterFd = -1; } if (childPid > 0) @@ -324,6 +356,15 @@ internal sealed class UnixPtySession : IPtySession [DllImport("libc", SetLastError = true)] public static extern int kill(int pid, int sig); + + [DllImport("libc", SetLastError = true)] + public static extern unsafe nint read(int fd, byte* buf, nuint count); + + [DllImport("libc", SetLastError = true)] + public static extern unsafe nint write(int fd, byte* buf, nuint count); + + [DllImport("libc", SetLastError = true)] + public static extern int close(int fd); } } #endif -- 2.52.0 From 42645b293d8a6394ec0c174f4233e4d23bdff8746ba09f4e33582d2d95461659 Mon Sep 17 00:00:00 2001 From: gsadmin Date: Mon, 10 Aug 2026 16:59:32 -0400 Subject: [PATCH 3/6] Executions backend: group a runs per-device jobs under a RunId [skip ci] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Foundation for the Script > Executions > Targets > Target > Output drill-in. Every run (ad-hoc, group, or a trigger firing) stamps its jobs with a shared RunId; legacy jobs (null RunId) are treated as single-target runs keyed by their own JobId. New read endpoints: - GET /api/scripts/{scriptId}/executions — runs of a script, summarized (started, requester, total + per-state counts), newest first. - GET /api/executions/{runId} — the run and its target devices. Output is fetched per target via the existing job-output endpoint. Migration AddJobRunId (Sqlite/Postgres/SqlServer) adds the nullable column + (ScriptId, RunId) index. Backend builds; 103 tests pass; svelte-check clean. Co-Authored-By: Claude Fable 5 --- src/Backend/Data/AppDbContext.cs | 1 + src/Backend/Data/Entities.cs | 8 + .../20260810205443_AddJobRunId.Designer.cs | 733 ++++++++++++++++++ .../Postgres/20260810205443_AddJobRunId.cs | 38 + .../PostgresAppDbContextModelSnapshot.cs | 5 + .../20260810205500_AddJobRunId.Designer.cs | 733 ++++++++++++++++++ .../SqlServer/20260810205500_AddJobRunId.cs | 38 + .../SqlServerAppDbContextModelSnapshot.cs | 5 + .../20260810205428_AddJobRunId.Designer.cs | 720 +++++++++++++++++ .../Sqlite/20260810205428_AddJobRunId.cs | 38 + .../Sqlite/SqliteAppDbContextModelSnapshot.cs | 5 + src/Backend/Groups/ScriptTriggerService.cs | 2 +- src/Backend/Jobs/JobEndpoints.cs | 65 +- src/Backend/Jobs/JobRunner.cs | 4 +- src/Backend/Jobs/ScheduleWorker.cs | 3 +- src/Shared.Contracts/Api/ApiRoutes.cs | 6 + src/Shared.Contracts/Api/ResourceDtos.cs | 31 + src/WebUI/src/lib/api/client.ts | 5 + src/WebUI/src/lib/api/types.ts | 31 + 19 files changed, 2466 insertions(+), 5 deletions(-) create mode 100644 src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.Designer.cs create mode 100644 src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.cs create mode 100644 src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.Designer.cs create mode 100644 src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.cs create mode 100644 src/Backend/Data/Migrations/Sqlite/20260810205428_AddJobRunId.Designer.cs create mode 100644 src/Backend/Data/Migrations/Sqlite/20260810205428_AddJobRunId.cs diff --git a/src/Backend/Data/AppDbContext.cs b/src/Backend/Data/AppDbContext.cs index 3b3b5e2..0241bc0 100644 --- a/src/Backend/Data/AppDbContext.cs +++ b/src/Backend/Data/AppDbContext.cs @@ -104,6 +104,7 @@ public class AppDbContext(DbContextOptions options) : DbContext(op entity.HasKey(e => e.JobId); entity.HasIndex(e => e.ClientId); entity.HasIndex(e => e.CreatedUtc); + entity.HasIndex(e => new { e.ScriptId, e.RunId }); entity.Property(e => e.State).HasConversion(); }); diff --git a/src/Backend/Data/Entities.cs b/src/Backend/Data/Entities.cs index 5b751c7..c10889d 100644 --- a/src/Backend/Data/Entities.cs +++ b/src/Backend/Data/Entities.cs @@ -241,6 +241,14 @@ public sealed class FunctionModuleEntity public sealed class JobEntity { public Guid JobId { get; set; } + + /// + /// Groups every per-device job created by one run (ad-hoc, group, or a + /// trigger firing) so executions can be listed and drilled into. Null on + /// legacy jobs, which are treated as single-target executions. + /// + public Guid? RunId { get; set; } + public required string ClientId { get; set; } public Guid ScriptId { get; set; } public required string ScriptName { get; set; } diff --git a/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.Designer.cs b/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.Designer.cs new file mode 100644 index 0000000..0265ff6 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.Designer.cs @@ -0,0 +1,733 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + [DbContext(typeof(PostgresAppDbContext))] + [Migration("20260810205443_AddJobRunId")] + partial class AddJobRunId + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("IsSecret") + .HasColumnType("boolean"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("text"); + + b.Property("Actor") + .HasColumnType("text"); + + b.Property("Category") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("Detail") + .HasColumnType("text"); + + b.Property("RemoteIp") + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MaxUses") + .HasColumnType("integer"); + + b.Property("Note") + .HasColumnType("text"); + + b.Property("Revoked") + .HasColumnType("boolean"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("Uses") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("AgentVersion") + .HasColumnType("text"); + + b.Property("EnrolledUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("EnrollmentId") + .HasColumnType("uuid"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("text"); + + b.Property("IpAddressesJson") + .HasColumnType("text"); + + b.Property("IsOrphaned") + .HasColumnType("boolean"); + + b.Property("LastSeenUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Manufacturer") + .HasColumnType("text"); + + b.Property("Model") + .HasColumnType("text"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrphanedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OsCaption") + .HasColumnType("text"); + + b.Property("OsVersion") + .HasColumnType("text"); + + b.Property("PublicIp") + .HasColumnType("text"); + + b.Property("ReadyUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TagsJson") + .HasColumnType("text"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("RulesJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CompletedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ExitCode") + .HasColumnType("integer"); + + b.Property("OutputSummary") + .HasColumnType("text"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("RunId") + .HasColumnType("uuid"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("text"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("text"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("text"); + + b.Property("IsSystem") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("text"); + + b.Property("PermissionsJson") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Content") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasColumnType("text"); + + b.Property("FileBindingsJson") + .HasColumnType("text"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("text"); + + b.Property("Language") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParametersJson") + .HasColumnType("text"); + + b.Property("SecretBindingsJson") + .HasColumnType("text"); + + b.Property("SecretsVariableName") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ArgumentsJson") + .HasColumnType("text"); + + b.Property("ClientId") + .HasColumnType("text"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CronExpression") + .HasColumnType("text"); + + b.Property("Enabled") + .HasColumnType("boolean"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("LastResult") + .HasColumnType("text"); + + b.Property("LastRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("NextRunUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OncePerDevice") + .HasColumnType("boolean"); + + b.Property("RunOnceUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScriptId") + .HasColumnType("uuid"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("text"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("FiredUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("JobId") + .HasColumnType("uuid"); + + b.Property("TriggerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text"); + + b.Property("CloseReason") + .HasColumnType("text"); + + b.Property("ClosedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestedBy") + .HasColumnType("text"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .HasColumnType("text"); + + b.Property("ExternalId") + .HasColumnType("text"); + + b.Property("LastLoginUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MustChangePassword") + .HasColumnType("boolean"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.cs b/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.cs new file mode 100644 index 0000000..14e7d70 --- /dev/null +++ b/src/Backend/Data/Migrations/Postgres/20260810205443_AddJobRunId.cs @@ -0,0 +1,38 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Postgres +{ + /// + public partial class AddJobRunId : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "RunId", + table: "Jobs", + type: "uuid", + nullable: true); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_ScriptId_RunId", + table: "Jobs", + columns: new[] { "ScriptId", "RunId" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Jobs_ScriptId_RunId", + table: "Jobs"); + + migrationBuilder.DropColumn( + name: "RunId", + table: "Jobs"); + } + } +} diff --git a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs index 6ca627d..624cffa 100644 --- a/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/Postgres/PostgresAppDbContextModelSnapshot.cs @@ -321,6 +321,9 @@ namespace Backend.Data.Migrations.Postgres b.Property("RequestedBy") .HasColumnType("text"); + b.Property("RunId") + .HasColumnType("uuid"); + b.Property("ScriptId") .HasColumnType("uuid"); @@ -341,6 +344,8 @@ namespace Backend.Data.Migrations.Postgres b.HasIndex("CreatedUtc"); + b.HasIndex("ScriptId", "RunId"); + b.ToTable("Jobs", (string)null); }); diff --git a/src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.Designer.cs b/src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.Designer.cs new file mode 100644 index 0000000..db3e231 --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.Designer.cs @@ -0,0 +1,733 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20260810205500_AddJobRunId")] + partial class AddJobRunId + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("IsSecret") + .HasColumnType("bit"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Category") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("Detail") + .HasColumnType("nvarchar(max)"); + + b.Property("RemoteIp") + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExpiresUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MaxUses") + .HasColumnType("int"); + + b.Property("Note") + .HasColumnType("nvarchar(max)"); + + b.Property("Revoked") + .HasColumnType("bit"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Uses") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("AgentVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("EnrolledUtc") + .HasColumnType("datetimeoffset"); + + b.Property("EnrollmentId") + .HasColumnType("uniqueidentifier"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("IpAddressesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsOrphaned") + .HasColumnType("bit"); + + b.Property("LastSeenUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Manufacturer") + .HasColumnType("nvarchar(max)"); + + b.Property("Model") + .HasColumnType("nvarchar(max)"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OrphanedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OsCaption") + .HasColumnType("nvarchar(max)"); + + b.Property("OsVersion") + .HasColumnType("nvarchar(max)"); + + b.Property("PublicIp") + .HasColumnType("nvarchar(max)"); + + b.Property("ReadyUtc") + .HasColumnType("datetimeoffset"); + + b.Property("TagsJson") + .HasColumnType("nvarchar(max)"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("RulesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AddedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("nvarchar(450)"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CompletedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ExitCode") + .HasColumnType("int"); + + b.Property("OutputSummary") + .HasColumnType("nvarchar(max)"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("RunId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("StartedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("Sequence") + .HasColumnType("bigint"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Text") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimestampUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystem") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("PermissionsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("Content") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FileBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Language") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("ParametersJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretBindingsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("SecretsVariableName") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ArgumentsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ClientId") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CronExpression") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GroupId") + .HasColumnType("uniqueidentifier"); + + b.Property("LastResult") + .HasColumnType("nvarchar(max)"); + + b.Property("LastRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("NextRunUtc") + .HasColumnType("datetimeoffset"); + + b.Property("OncePerDevice") + .HasColumnType("bit"); + + b.Property("RunOnceUtc") + .HasColumnType("datetimeoffset"); + + b.Property("ScriptId") + .HasColumnType("uniqueidentifier"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("FiredUtc") + .HasColumnType("datetimeoffset"); + + b.Property("JobId") + .HasColumnType("uniqueidentifier"); + + b.Property("TriggerId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("UpdatedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("UpdatedUtc") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("CloseReason") + .HasColumnType("nvarchar(max)"); + + b.Property("ClosedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("RequestedBy") + .HasColumnType("nvarchar(max)"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("ExternalId") + .HasColumnType("nvarchar(max)"); + + b.Property("LastLoginUtc") + .HasColumnType("datetimeoffset"); + + b.Property("MustChangePassword") + .HasColumnType("bit"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("Role") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .HasColumnType("uniqueidentifier"); + + b.Property("Username") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.cs b/src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.cs new file mode 100644 index 0000000..e4b324e --- /dev/null +++ b/src/Backend/Data/Migrations/SqlServer/20260810205500_AddJobRunId.cs @@ -0,0 +1,38 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.SqlServer +{ + /// + public partial class AddJobRunId : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "RunId", + table: "Jobs", + type: "uniqueidentifier", + nullable: true); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_ScriptId_RunId", + table: "Jobs", + columns: new[] { "ScriptId", "RunId" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Jobs_ScriptId_RunId", + table: "Jobs"); + + migrationBuilder.DropColumn( + name: "RunId", + table: "Jobs"); + } + } +} diff --git a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs index de0d8a1..ca89ef0 100644 --- a/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/SqlServer/SqlServerAppDbContextModelSnapshot.cs @@ -321,6 +321,9 @@ namespace Backend.Data.Migrations.SqlServer b.Property("RequestedBy") .HasColumnType("nvarchar(max)"); + b.Property("RunId") + .HasColumnType("uniqueidentifier"); + b.Property("ScriptId") .HasColumnType("uniqueidentifier"); @@ -341,6 +344,8 @@ namespace Backend.Data.Migrations.SqlServer b.HasIndex("CreatedUtc"); + b.HasIndex("ScriptId", "RunId"); + b.ToTable("Jobs", (string)null); }); diff --git a/src/Backend/Data/Migrations/Sqlite/20260810205428_AddJobRunId.Designer.cs b/src/Backend/Data/Migrations/Sqlite/20260810205428_AddJobRunId.Designer.cs new file mode 100644 index 0000000..3805a80 --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260810205428_AddJobRunId.Designer.cs @@ -0,0 +1,720 @@ +// +using System; +using Backend.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + [DbContext(typeof(SqliteAppDbContext))] + [Migration("20260810205428_AddJobRunId")] + partial class AddJobRunId + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.10"); + + modelBuilder.Entity("Backend.Data.AppSettingEntity", b => + { + b.Property("Key") + .HasColumnType("TEXT"); + + b.Property("IsSecret") + .HasColumnType("INTEGER"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("AppSettings", (string)null); + }); + + modelBuilder.Entity("Backend.Data.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Action") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Actor") + .HasColumnType("TEXT"); + + b.Property("Category") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("Detail") + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TimestampUtc"); + + b.ToTable("AuditEvents", (string)null); + }); + + modelBuilder.Entity("Backend.Data.BootstrapTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExpiresUtc") + .HasColumnType("INTEGER"); + + b.Property("MaxUses") + .HasColumnType("INTEGER"); + + b.Property("Note") + .HasColumnType("TEXT"); + + b.Property("Revoked") + .HasColumnType("INTEGER"); + + b.Property("TokenHash") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Uses") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("BootstrapTokens", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("AgentVersion") + .HasColumnType("TEXT"); + + b.Property("EnrolledUtc") + .HasColumnType("INTEGER"); + + b.Property("EnrollmentId") + .HasColumnType("TEXT"); + + b.Property("Hostname") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("IpAddressesJson") + .HasColumnType("TEXT"); + + b.Property("IsOrphaned") + .HasColumnType("INTEGER"); + + b.Property("LastSeenUtc") + .HasColumnType("INTEGER"); + + b.Property("Manufacturer") + .HasColumnType("TEXT"); + + b.Property("Model") + .HasColumnType("TEXT"); + + b.Property("NkeyPublic") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OrphanedUtc") + .HasColumnType("INTEGER"); + + b.Property("OsCaption") + .HasColumnType("TEXT"); + + b.Property("OsVersion") + .HasColumnType("TEXT"); + + b.Property("PublicIp") + .HasColumnType("TEXT"); + + b.Property("ReadyUtc") + .HasColumnType("INTEGER"); + + b.Property("TagsJson") + .HasColumnType("TEXT"); + + b.HasKey("ClientId"); + + b.HasIndex("Hostname"); + + b.ToTable("Devices", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RulesJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("DeviceGroups", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceGroupMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("AddedUtc") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("GroupId", "ClientId") + .IsUnique(); + + b.ToTable("DeviceGroupMembers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("ReportJson") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("ClientId"); + + b.ToTable("DeviceInventory", (string)null); + }); + + modelBuilder.Entity("Backend.Data.FunctionModuleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("FunctionModules", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobEntity", b => + { + b.Property("JobId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CompletedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("ExitCode") + .HasColumnType("INTEGER"); + + b.Property("OutputSummary") + .HasColumnType("TEXT"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("RunId") + .HasColumnType("TEXT"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("ScriptName") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("StartedUtc") + .HasColumnType("INTEGER"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("JobId"); + + b.HasIndex("ClientId"); + + b.HasIndex("CreatedUtc"); + + b.HasIndex("ScriptId", "RunId"); + + b.ToTable("Jobs", (string)null); + }); + + modelBuilder.Entity("Backend.Data.JobOutputEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("Sequence") + .HasColumnType("INTEGER"); + + b.Property("Stream") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Text") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TimestampUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("JobId", "Sequence") + .IsUnique(); + + b.ToTable("JobOutput", (string)null); + }); + + modelBuilder.Entity("Backend.Data.OidcProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Authority") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("OidcProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("DeviceScopeGroupIdsJson") + .HasColumnType("TEXT"); + + b.Property("IsSystem") + .HasColumnType("INTEGER"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("OidcClaimValuesJson") + .HasColumnType("TEXT"); + + b.Property("PermissionsJson") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("Content") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Description") + .HasColumnType("TEXT"); + + b.Property("FileBindingsJson") + .HasColumnType("TEXT"); + + b.Property("FunctionModuleIdsJson") + .HasColumnType("TEXT"); + + b.Property("Language") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("ParametersJson") + .HasColumnType("TEXT"); + + b.Property("SecretBindingsJson") + .HasColumnType("TEXT"); + + b.Property("SecretsVariableName") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Scripts", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ArgumentsJson") + .HasColumnType("TEXT"); + + b.Property("ClientId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("CronExpression") + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("GroupId") + .HasColumnType("TEXT"); + + b.Property("LastResult") + .HasColumnType("TEXT"); + + b.Property("LastRunUtc") + .HasColumnType("INTEGER"); + + b.Property("NextRunUtc") + .HasColumnType("INTEGER"); + + b.Property("OncePerDevice") + .HasColumnType("INTEGER"); + + b.Property("RunOnceUtc") + .HasColumnType("INTEGER"); + + b.Property("ScriptId") + .HasColumnType("TEXT"); + + b.Property("TimeZoneId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TriggerType") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NextRunUtc"); + + b.HasIndex("TriggerType"); + + b.ToTable("ScriptTriggers", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ScriptTriggerRunEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("FiredUtc") + .HasColumnType("INTEGER"); + + b.Property("JobId") + .HasColumnType("TEXT"); + + b.Property("TriggerId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TriggerId", "ClientId") + .IsUnique(); + + b.ToTable("ScriptTriggerRuns", (string)null); + }); + + modelBuilder.Entity("Backend.Data.SecretsProviderEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ConfigProtected") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT"); + + b.Property("UpdatedUtc") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SecretsProviders", (string)null); + }); + + modelBuilder.Entity("Backend.Data.ShellSessionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CloseReason") + .HasColumnType("TEXT"); + + b.Property("ClosedUtc") + .HasColumnType("INTEGER"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("RequestedBy") + .HasColumnType("TEXT"); + + b.Property("State") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.ToTable("ShellSessions", (string)null); + }); + + modelBuilder.Entity("Backend.Data.UserEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("AuthProvider") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreatedUtc") + .HasColumnType("INTEGER"); + + b.Property("DisplayName") + .HasColumnType("TEXT"); + + b.Property("ExternalId") + .HasColumnType("TEXT"); + + b.Property("LastLoginUtc") + .HasColumnType("INTEGER"); + + b.Property("MustChangePassword") + .HasColumnType("INTEGER"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("Role") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("Username") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Backend.Data.DeviceInventoryEntity", b => + { + b.HasOne("Backend.Data.DeviceEntity", null) + .WithOne("Inventory") + .HasForeignKey("Backend.Data.DeviceInventoryEntity", "ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Backend.Data.DeviceEntity", b => + { + b.Navigation("Inventory"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/20260810205428_AddJobRunId.cs b/src/Backend/Data/Migrations/Sqlite/20260810205428_AddJobRunId.cs new file mode 100644 index 0000000..7f78ecb --- /dev/null +++ b/src/Backend/Data/Migrations/Sqlite/20260810205428_AddJobRunId.cs @@ -0,0 +1,38 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Backend.Data.Migrations.Sqlite +{ + /// + public partial class AddJobRunId : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "RunId", + table: "Jobs", + type: "TEXT", + nullable: true); + + migrationBuilder.CreateIndex( + name: "IX_Jobs_ScriptId_RunId", + table: "Jobs", + columns: new[] { "ScriptId", "RunId" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_Jobs_ScriptId_RunId", + table: "Jobs"); + + migrationBuilder.DropColumn( + name: "RunId", + table: "Jobs"); + } + } +} diff --git a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs index b3ac62a..089c2dc 100644 --- a/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs +++ b/src/Backend/Data/Migrations/Sqlite/SqliteAppDbContextModelSnapshot.cs @@ -312,6 +312,9 @@ namespace Backend.Data.Migrations.Sqlite b.Property("RequestedBy") .HasColumnType("TEXT"); + b.Property("RunId") + .HasColumnType("TEXT"); + b.Property("ScriptId") .HasColumnType("TEXT"); @@ -332,6 +335,8 @@ namespace Backend.Data.Migrations.Sqlite b.HasIndex("CreatedUtc"); + b.HasIndex("ScriptId", "RunId"); + b.ToTable("Jobs", (string)null); }); diff --git a/src/Backend/Groups/ScriptTriggerService.cs b/src/Backend/Groups/ScriptTriggerService.cs index dcc445d..64a00e9 100644 --- a/src/Backend/Groups/ScriptTriggerService.cs +++ b/src/Backend/Groups/ScriptTriggerService.cs @@ -69,7 +69,7 @@ public sealed class ScriptTriggerService( } var job = await runner.CreateJobAsync( - script, clientId, $"trigger:{triggerType}", cancellationToken); + script, clientId, $"trigger:{triggerType}", cancellationToken, Guid.NewGuid()); if (trigger.OncePerDevice) { diff --git a/src/Backend/Jobs/JobEndpoints.cs b/src/Backend/Jobs/JobEndpoints.cs index f737419..80499e0 100644 --- a/src/Backend/Jobs/JobEndpoints.cs +++ b/src/Backend/Jobs/JobEndpoints.cs @@ -19,6 +19,66 @@ public static class JobEndpoints app.MapPost(ApiRoutes.Jobs, CreateAsync).RequirePermission(Permissions.JobsRun); app.MapGet(ApiRoutes.Job, GetAsync).RequirePermission(Permissions.JobsView); app.MapGet(ApiRoutes.JobOutput, GetOutputAsync).RequirePermission(Permissions.JobsView); + app.MapGet(ApiRoutes.ScriptExecutions, ListExecutionsAsync).RequirePermission(Permissions.JobsView); + app.MapGet(ApiRoutes.Execution, GetExecutionAsync).RequirePermission(Permissions.JobsView); + } + + /// Executions of a script: its per-device jobs grouped by run (newest first). + private static async Task ListExecutionsAsync( + Guid scriptId, AppDbContext db, CancellationToken cancellationToken) + { + var jobs = await db.Jobs.AsNoTracking() + .Where(j => j.ScriptId == scriptId) + .OrderByDescending(j => j.CreatedUtc) + .Take(2000) + .Select(j => new { j.JobId, j.RunId, j.State, j.CreatedUtc, j.RequestedBy }) + .ToListAsync(cancellationToken); + + // Null RunId (legacy jobs) is treated as a single-target run keyed by its + // own JobId. Grouping is in-memory to keep the coalesce provider-agnostic. + var executions = jobs + .GroupBy(j => j.RunId ?? j.JobId) + .Select(g => new ExecutionSummaryDto( + g.Key, + scriptId, + g.Min(j => j.CreatedUtc), + g.Select(j => j.RequestedBy).FirstOrDefault(r => r is not null), + g.Count(), + g.Count(j => j.State == JobState.Succeeded), + g.Count(j => j.State is JobState.Failed or JobState.TimedOut), + g.Count(j => j.State is JobState.Queued or JobState.Running))) + .OrderByDescending(e => e.StartedUtc) + .Take(50) + .ToList(); + + return Results.Ok(executions); + } + + /// A single execution and the targets (devices) it ran on. + private static async Task GetExecutionAsync( + Guid runId, AppDbContext db, CancellationToken cancellationToken) + { + var jobs = await db.Jobs.AsNoTracking() + .Where(j => j.RunId == runId || j.JobId == runId) + .OrderBy(j => j.CreatedUtc) + .ToListAsync(cancellationToken); + if (jobs.Count == 0) + { + return Results.NotFound(); + } + + var hostnames = await db.Devices.AsNoTracking() + .Where(d => jobs.Select(j => j.ClientId).Contains(d.ClientId)) + .ToDictionaryAsync(d => d.ClientId, d => d.Hostname, cancellationToken); + + var targets = jobs.Select(j => new ExecutionTargetDto( + j.JobId, j.ClientId, hostnames.GetValueOrDefault(j.ClientId), j.State, j.ExitCode, + j.CreatedUtc, j.StartedUtc, j.CompletedUtc)).ToList(); + + var first = jobs[0]; + return Results.Ok(new ExecutionDetailDto( + runId, first.ScriptId, first.ScriptName, jobs.Min(j => j.CreatedUtc), + jobs.Select(j => j.RequestedBy).FirstOrDefault(r => r is not null), targets)); } private static async Task ListAsync( @@ -147,7 +207,7 @@ public static class JobEndpoints }); } - var job = await runner.CreateJobAsync(script, device.ClientId, actor, cancellationToken); + var job = await runner.CreateJobAsync(script, device.ClientId, actor, cancellationToken, Guid.NewGuid()); await runner.DispatchAsync( prepared, job, request.Arguments, $"Job “{script.Name}” queued for {device.Hostname}", cancellationToken); @@ -196,6 +256,7 @@ public static class JobEndpoints var jobs = new List(); var skipped = new List(); + var runId = Guid.NewGuid(); foreach (var device in devices) { @@ -205,7 +266,7 @@ public static class JobEndpoints continue; } - var job = await runner.CreateJobAsync(prepared.Script, device.ClientId, actor, cancellationToken); + var job = await runner.CreateJobAsync(prepared.Script, device.ClientId, actor, cancellationToken, runId); await runner.DispatchAsync( prepared, job, request.Arguments, $"Job “{prepared.Script.Name}” queued for {device.Hostname} (group “{group.Name}”)", diff --git a/src/Backend/Jobs/JobRunner.cs b/src/Backend/Jobs/JobRunner.cs index f7b80f7..2a6fee5 100644 --- a/src/Backend/Jobs/JobRunner.cs +++ b/src/Backend/Jobs/JobRunner.cs @@ -125,11 +125,13 @@ public sealed class JobRunner( } public async Task CreateJobAsync( - ScriptEntity script, string clientId, string? requestedBy, CancellationToken cancellationToken) + ScriptEntity script, string clientId, string? requestedBy, CancellationToken cancellationToken, + Guid? runId = null) { var job = new JobEntity { JobId = Guid.NewGuid(), + RunId = runId, ClientId = clientId, ScriptId = script.Id, ScriptName = script.Name, diff --git a/src/Backend/Jobs/ScheduleWorker.cs b/src/Backend/Jobs/ScheduleWorker.cs index 5aace29..69b7bbc 100644 --- a/src/Backend/Jobs/ScheduleWorker.cs +++ b/src/Backend/Jobs/ScheduleWorker.cs @@ -121,9 +121,10 @@ public sealed class ScheduleWorker(IServiceScopeFactory scopeFactory, ILogger>(trigger.ArgumentsJson); var queued = 0; + var runId = Guid.NewGuid(); foreach (var device in devices) { - var job = await runner.CreateJobAsync(script, device.ClientId, "schedule", cancellationToken); + var job = await runner.CreateJobAsync(script, device.ClientId, "schedule", cancellationToken, runId); await runner.DispatchAsync( prepared, job, arguments, $"Scheduled trigger queued “{script.Name}” for {device.Hostname}", diff --git a/src/Shared.Contracts/Api/ApiRoutes.cs b/src/Shared.Contracts/Api/ApiRoutes.cs index 259e65f..eca15c1 100644 --- a/src/Shared.Contracts/Api/ApiRoutes.cs +++ b/src/Shared.Contracts/Api/ApiRoutes.cs @@ -63,6 +63,10 @@ public static class ApiRoutes public const string Job = "/api/jobs/{jobId}"; public const string JobOutput = "/api/jobs/{jobId}/output"; + /// Executions of a script (per-device jobs grouped by run). + public const string ScriptExecutions = "/api/scripts/{scriptId}/executions"; + public const string Execution = "/api/executions/{runId}"; + public const string Dashboard = "/api/dashboard"; /// Public self-signed CA chain (root + intermediate) for agent trust. @@ -96,6 +100,8 @@ public static class ApiRoutes public static string SecretsProviderNames(Guid id) => $"/api/secrets/providers/{id:D}/secret-names"; public static string Job(Guid jobId) => $"/api/jobs/{jobId:D}"; public static string JobOutput(Guid jobId) => $"/api/jobs/{jobId:D}/output"; + public static string ScriptExecutions(Guid scriptId) => $"/api/scripts/{scriptId:D}/executions"; + public static string Execution(Guid runId) => $"/api/executions/{runId:D}"; public static string AdminBootstrapToken(Guid id) => $"/api/admin/bootstrap-tokens/{id:D}"; public static string AdminRole(Guid id) => $"/api/admin/roles/{id:D}"; public static string AdminUser(Guid id) => $"/api/admin/users/{id:D}"; diff --git a/src/Shared.Contracts/Api/ResourceDtos.cs b/src/Shared.Contracts/Api/ResourceDtos.cs index 6209307..5666381 100644 --- a/src/Shared.Contracts/Api/ResourceDtos.cs +++ b/src/Shared.Contracts/Api/ResourceDtos.cs @@ -90,6 +90,37 @@ public sealed record SaveScriptTriggerRequest( /// PATCH /api/triggers/{id} — enable or disable a trigger without deleting it. public sealed record SetTriggerEnabledRequest(bool Enabled); +/// One execution (run) of a script — the per-device jobs it created, summarized. +public sealed record ExecutionSummaryDto( + Guid RunId, + Guid ScriptId, + DateTimeOffset StartedUtc, + string? RequestedBy, + int Total, + int Succeeded, + int Failed, + int Pending); + +/// One device within an execution. +public sealed record ExecutionTargetDto( + Guid JobId, + string ClientId, + string? Hostname, + JobState State, + int? ExitCode, + DateTimeOffset CreatedUtc, + DateTimeOffset? StartedUtc, + DateTimeOffset? CompletedUtc); + +/// GET /api/executions/{runId} — a run and the targets it ran on. +public sealed record ExecutionDetailDto( + Guid RunId, + Guid ScriptId, + string ScriptName, + DateTimeOffset StartedUtc, + string? RequestedBy, + IReadOnlyList Targets); + /// Device detail for GET /api/devices/{clientId}. public sealed record DeviceDetailDto( DeviceDto Device, diff --git a/src/WebUI/src/lib/api/client.ts b/src/WebUI/src/lib/api/client.ts index 64719f5..16c099c 100644 --- a/src/WebUI/src/lib/api/client.ts +++ b/src/WebUI/src/lib/api/client.ts @@ -13,6 +13,8 @@ import type { JobDto, DashboardDto, JobOutputRecordDto, + ExecutionSummaryDto, + ExecutionDetailDto, AgentPackageStatusDto, AuthConfigDto, AuthSettingsDto, @@ -195,6 +197,9 @@ export const api = { request( `/api/jobs/${jobId}/output${afterSequence ? `?afterSequence=${afterSequence}` : ''}` ), + scriptExecutions: (scriptId: string) => + request(`/api/scripts/${scriptId}/executions`), + execution: (runId: string) => request(`/api/executions/${runId}`), createJob: (clientId: string, scriptId: string, args?: Record) => request('/api/jobs', { method: 'POST', diff --git a/src/WebUI/src/lib/api/types.ts b/src/WebUI/src/lib/api/types.ts index ab34607..b4a0e2b 100644 --- a/src/WebUI/src/lib/api/types.ts +++ b/src/WebUI/src/lib/api/types.ts @@ -451,6 +451,37 @@ export interface JobOutputRecordDto { text: string; } +export interface ExecutionSummaryDto { + runId: string; + scriptId: string; + startedUtc: string; + requestedBy?: string; + total: number; + succeeded: number; + failed: number; + pending: number; +} + +export interface ExecutionTargetDto { + jobId: string; + clientId: string; + hostname?: string; + state: JobState; + exitCode?: number; + createdUtc: string; + startedUtc?: string; + completedUtc?: string; +} + +export interface ExecutionDetailDto { + runId: string; + scriptId: string; + scriptName: string; + startedUtc: string; + requestedBy?: string; + targets: ExecutionTargetDto[]; +} + export interface SessionResponse { authenticated: boolean; username?: string; -- 2.52.0 From b07a077fbb34cbf23a438bff502c472719e16db2087d5337e5205219c9e85d0d Mon Sep 17 00:00:00 2001 From: gsadmin Date: Mon, 10 Aug 2026 17:10:07 -0400 Subject: [PATCH 4/6] Script page: groups-only Run + Executions drill-in, output off page [skip ci] Reworks the script page around the executions model (option A): - Run box: multi-select group checkboxes only (no per-device list); Run fans out across the deduped union of the selected groups as ONE execution (new multi-group run: CreateJobRequest.GroupIds -> RunOnGroupsAsync). - The inline Targets/Run/Output/History sections are gone. In their place a single Executions drill-in: Executions -> a run's Targets (devices) -> a Target's Output, with a breadcrumb to step back. - Output view is full-width and searchable, rendered line-by-line and kept intact (white-space: pre) so wide output like ifconfig scrolls horizontally instead of wrapping into a block. Fetched from stored job output and polled while the run is still active (replacing the live NATS stream on this page). Backend builds; 103 tests pass; svelte-check clean (0/0). Co-Authored-By: Claude Fable 5 --- src/Backend/Jobs/JobEndpoints.cs | 73 ++ src/Shared.Contracts/Api/ResourceDtos.cs | 3 +- src/WebUI/src/lib/api/client.ts | 5 + .../src/routes/scripts/[id]/+page.svelte | 688 +++++++----------- 4 files changed, 363 insertions(+), 406 deletions(-) diff --git a/src/Backend/Jobs/JobEndpoints.cs b/src/Backend/Jobs/JobEndpoints.cs index 80499e0..b8f50ff 100644 --- a/src/Backend/Jobs/JobEndpoints.cs +++ b/src/Backend/Jobs/JobEndpoints.cs @@ -176,6 +176,12 @@ public static class JobEndpoints return Results.Problem(ex.Message, statusCode: StatusCodes.Status502BadGateway); } + if (request.GroupIds is { Count: > 0 } groupIds) + { + return await RunOnGroupsAsync( + groupIds, prepared, request, db, runner, groups, scope, audit, actor, context, cancellationToken); + } + if (request.GroupId is { } groupId) { return await RunOnGroupAsync( @@ -281,6 +287,73 @@ public static class JobEndpoints return Results.Ok(new GroupRunDto(jobs, skipped)); } + /// Run across the deduped union of several groups' members, as one execution. + private static async Task RunOnGroupsAsync( + IReadOnlyList groupIds, + PreparedScript prepared, + CreateJobRequest request, + AppDbContext db, + JobRunner runner, + Backend.Groups.DeviceGroupService groups, + DeviceScopeService scope, + AuditService audit, + string? actor, + HttpContext context, + CancellationToken cancellationToken) + { + var selected = await db.DeviceGroups.AsNoTracking() + .Where(g => groupIds.Contains(g.Id)) + .ToListAsync(cancellationToken); + if (selected.Count == 0) + { + return Results.NotFound(new { error = "No matching groups." }); + } + + var memberIds = new HashSet(); + foreach (var group in selected) + { + foreach (var member in await groups.GetMembersAsync(group, cancellationToken)) + { + memberIds.Add(member); + } + } + + var allowed = await scope.GetAllowedClientIdsAsync(context.User, cancellationToken); + if (allowed is not null) + { + memberIds.IntersectWith(allowed); + } + + var devices = await db.Devices.AsNoTracking() + .Where(d => memberIds.Contains(d.ClientId)) + .ToListAsync(cancellationToken); + + var jobs = new List(); + var skipped = new List(); + var runId = Guid.NewGuid(); + + foreach (var device in devices) + { + if (device.IsOrphaned) + { + skipped.Add(device.Hostname); + continue; + } + + var job = await runner.CreateJobAsync(prepared.Script, device.ClientId, actor, cancellationToken, runId); + await runner.DispatchAsync( + prepared, job, request.Arguments, + $"Job “{prepared.Script.Name}” queued for {device.Hostname}", cancellationToken); + jobs.Add(ToDto(job, device.Hostname)); + } + + await audit.LogAsync(AuditCategories.Jobs, "group-run", actor, + detail: $"script={prepared.Script.Name} groups={selected.Count} jobs={jobs.Count} skipped={skipped.Count}", + cancellationToken: cancellationToken); + + return Results.Ok(new GroupRunDto(jobs, skipped)); + } + private static JobDto ToDto(JobEntity job, string? hostname) => new( job.JobId, job.ClientId, hostname, job.ScriptId, job.ScriptName, job.State, job.CreatedUtc, job.StartedUtc, job.CompletedUtc, job.ExitCode, job.RequestedBy, job.OutputSummary); diff --git a/src/Shared.Contracts/Api/ResourceDtos.cs b/src/Shared.Contracts/Api/ResourceDtos.cs index 5666381..85fcbc5 100644 --- a/src/Shared.Contracts/Api/ResourceDtos.cs +++ b/src/Shared.Contracts/Api/ResourceDtos.cs @@ -230,7 +230,8 @@ public sealed record CreateJobRequest( string? ClientId, Guid ScriptId, IReadOnlyDictionary? Arguments = null, - Guid? GroupId = null); + Guid? GroupId = null, + IReadOnlyList? GroupIds = null); /// Result of a group fan-out run: one job per eligible member. public sealed record GroupRunDto( diff --git a/src/WebUI/src/lib/api/client.ts b/src/WebUI/src/lib/api/client.ts index 16c099c..3fdb44e 100644 --- a/src/WebUI/src/lib/api/client.ts +++ b/src/WebUI/src/lib/api/client.ts @@ -210,6 +210,11 @@ export const api = { method: 'POST', body: JSON.stringify({ groupId, scriptId, arguments: args }) }), + createGroupsJob: (groupIds: string[], scriptId: string, args?: Record) => + request('/api/jobs', { + method: 'POST', + body: JSON.stringify({ groupIds, scriptId, arguments: args }) + }), // Groups diff --git a/src/WebUI/src/routes/scripts/[id]/+page.svelte b/src/WebUI/src/routes/scripts/[id]/+page.svelte index cf19edd..1a2914b 100644 --- a/src/WebUI/src/routes/scripts/[id]/+page.svelte +++ b/src/WebUI/src/routes/scripts/[id]/+page.svelte @@ -4,17 +4,15 @@ import { goto } from '$app/navigation'; import { api } from '$lib/api/client'; import type { - DeviceDto, DeviceGroupDto, FunctionModuleDto, - JobDto, - JobProgressPayload, - JobState, ScriptParameter, ScriptFileBinding, - SecretBinding + SecretBinding, + ExecutionSummaryDto, + ExecutionDetailDto, + ExecutionTargetDto } from '$lib/api/types'; - import { nats, type JobEvent } from '$lib/messaging/nats'; import { registerPowerShellCompletions } from '$lib/editor/powershell-completions'; import JobStateBadge from '$lib/components/JobStateBadge.svelte'; import ParameterSchemaEditor from '$lib/components/ParameterSchemaEditor.svelte'; @@ -38,33 +36,29 @@ let saving = $state(false); let statusText = $state(''); - let devices = $state([]); let allGroups = $state([]); - // Picker value ('device:' or 'group:') and the added set. - let targetKey = $state(''); - let targets = $state([]); - let history = $state([]); + // Run targets are groups only (multi-select); a fleet's device list is too + // long to pick from here — single-device runs live on the device page. + let selectedGroups = $state([]); + let running = $state(false); - function addTarget() { - if (targetKey && !targets.includes(targetKey)) targets = [...targets, targetKey]; + // Executions drill-in: list → a run's targets → one target's output. + let executions = $state([]); + let currentRun = $state(null); + let currentTarget = $state(null); + let pollTimer: ReturnType | null = null; + + const terminalStates = ['succeeded', 'failed', 'cancelled', 'timedOut']; + + function toggleGroup(id: string) { + selectedGroups = selectedGroups.includes(id) + ? selectedGroups.filter((g) => g !== id) + : [...selectedGroups, id]; } - function removeTarget(key: string) { - targets = targets.filter((t) => t !== key); - } - - function targetLabel(key: string) { - const id = key.slice(key.indexOf(':') + 1); - if (key.startsWith('group:')) { - const group = allGroups.find((g) => g.id === id); - return group ? `${group.name} (group)` : id; - } - return devices.find((d) => d.clientId === id)?.hostname ?? id; - } - - async function refreshHistory() { + async function loadExecutions() { if (isNew) return; - history = await api.jobs(undefined, 50, scriptId).catch(() => []); + executions = await api.scriptExecutions(scriptId).catch(() => []); } let parameters = $state([]); @@ -81,9 +75,7 @@ let intellisense = $state(true); let completionDisposable: { dispose(): void } | null = null; - // Live run state (single-device run) - let job = $state(null); - let jobState = $state(null); + // Output of the drilled-in target, fetched from stored job output. let outputLines = $state<{ seq: number; stream: string; text: string }[]>([]); let outputSearch = $state(''); let copiedOutput = $state(false); @@ -97,14 +89,6 @@ copiedOutput = true; setTimeout(() => (copiedOutput = false), 1400); } - let progress = $state(null); - let unsubscribeJob: (() => void) | null = null; - - // Live run state (group fan-out) - let groupJobs = $state([]); - let jobStates = $state>({}); - let skippedOrphaned = $state([]); - let focusJobId = $state(null); let editorHost: HTMLDivElement; // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -195,19 +179,12 @@ editor.onDidChangeModelContent(() => (content = editor.getValue())); applyIntellisense(); - [devices, allGroups] = await Promise.all([api.devices(), api.groups().catch(() => [])]); - const requested = page.url.searchParams.get('target'); - if (requested && devices.some((d) => d.clientId === requested)) { - targetKey = `device:${requested}`; - targets = [targetKey]; - } else if (devices.length > 0) { - targetKey = `device:${devices[0].clientId}`; - } - void refreshHistory(); + allGroups = await api.groups().catch(() => []); + void loadExecutions(); })(); return () => { - unsubscribeJob?.(); + stopPoll(); completionDisposable?.dispose(); editor?.dispose(); }; @@ -249,106 +226,96 @@ } } - function appendOutput(payload: { sequence: number; stream: string; text: string }) { - outputLines = [ - ...outputLines, - { seq: payload.sequence, stream: payload.stream, text: payload.text } - ].slice(-2000); - } - - /** Switches the output panel to one job of a group run. */ - async function focusJob(jobId: string) { - focusJobId = jobId; - outputLines = []; - progress = null; - const stored = await api.jobOutput(jobId).catch(() => []); - if (focusJobId === jobId && outputLines.length === 0) { - outputLines = stored.map((r) => ({ seq: r.sequence, stream: r.stream, text: r.text })); - } - } - - async function run() { + async function runNow() { const id = await save(); - if (!id || targets.length === 0) return; - - outputLines = []; - progress = null; - jobState = null; - job = null; - groupJobs = []; - jobStates = {}; - skippedOrphaned = []; - focusJobId = null; - + if (!id || selectedGroups.length === 0) return; + running = true; + statusText = ''; const args = paramInputs?.collect() ?? {}; - - // One or more targets: devices dispatch one job each, groups fan out - // per member. Everything lands in one per-device list below. try { - const runJobs: JobDto[] = []; - const skipped: string[] = []; - for (const key of targets) { - const targetId = key.slice(key.indexOf(':') + 1); - if (key.startsWith('group:')) { - const result = await api.createGroupJob(targetId, id, args); - runJobs.push(...result.jobs); - skipped.push(...result.skippedOrphaned); - } else { - runJobs.push(await api.createJob(targetId, id, args)); - } + const result = await api.createGroupsJob(selectedGroups, id, args); + await loadExecutions(); + if (result.skippedOrphaned.length > 0) { + statusText = `Skipped orphaned: ${result.skippedOrphaned.join(', ')}`; } - - groupJobs = runJobs; - skippedOrphaned = skipped; - for (const started of runJobs) { - jobStates[started.jobId] = started.state; + // Drill straight into the run we just started. + if (executions.length > 0) { + await openExecution(executions[0].runId); } - if (runJobs.length === 0) { - statusText = 'No devices were able to run this job.'; - return; - } - void focusJob(runJobs[0].jobId); } catch (e) { - statusText = e instanceof Error ? e.message : 'Failed to start job.'; - return; + statusText = e instanceof Error ? e.message : 'Failed to start run.'; + } finally { + running = false; } + } - unsubscribeJob?.(); - unsubscribeJob = nats.onJobEvent((jobId: string, event: JobEvent) => { - if (job && jobId === job.jobId) { - if (event.type === 'job.output') { - appendOutput(event.payload); - } else if (event.type === 'job.progress') { - progress = event.payload; - } else if (event.type === 'job.state') { - jobState = event.payload.state; - if (['succeeded', 'failed', 'cancelled', 'timedOut'].includes(event.payload.state)) { - progress = null; - } - } - return; - } + async function openExecution(runId: string) { + currentTarget = null; + outputLines = []; + currentRun = await api.execution(runId).catch(() => null); + schedulePoll(); + } - if (jobId in jobStates) { - if (event.type === 'job.state') { - jobStates[jobId] = event.payload.state; - } - if (jobId === focusJobId) { - if (event.type === 'job.output') { - appendOutput(event.payload); - } else if (event.type === 'job.progress') { - progress = event.payload; - } else if ( - event.type === 'job.state' && - ['succeeded', 'failed', 'cancelled', 'timedOut'].includes(event.payload.state) - ) { - progress = null; + async function openTarget(target: ExecutionTargetDto) { + currentTarget = target; + outputSearch = ''; + outputLines = []; + await loadOutput(); + schedulePoll(); + } + + async function loadOutput() { + if (!currentTarget) return; + const records = await api.jobOutput(currentTarget.jobId).catch(() => []); + outputLines = records.map((r) => ({ seq: r.sequence, stream: r.stream, text: r.text })); + } + + function backToExecutions() { + currentRun = null; + currentTarget = null; + stopPoll(); + void loadExecutions(); + } + + function backToTargets() { + currentTarget = null; + outputLines = []; + if (currentRun) void openExecution(currentRun.runId); + } + + function runActive(): boolean { + return currentRun?.targets.some((t) => !terminalStates.includes(t.state)) ?? false; + } + + // Output is persisted, so the drill-in polls it (and the targets' states) + // while anything is still running, then stops. + function schedulePoll() { + stopPoll(); + pollTimer = setInterval(async () => { + if (currentRun) { + const fresh = await api.execution(currentRun.runId).catch(() => null); + if (fresh) { + currentRun = fresh; + if (currentTarget) { + currentTarget = + fresh.targets.find((t) => t.jobId === currentTarget!.jobId) ?? currentTarget; } } } - }); + if (currentTarget) { + await loadOutput(); + } + if (!runActive()) { + stopPoll(); + } + }, 1600); + } - void refreshHistory(); + function stopPoll() { + if (pollTimer) { + clearInterval(pollTimer); + pollTimer = null; + } } async function remove() { @@ -385,19 +352,6 @@ } } - const terminal = ['succeeded', 'failed', 'cancelled', 'timedOut']; - const groupRunning = $derived( - groupJobs.some((g) => !terminal.includes(jobStates[g.jobId] ?? 'queued')) - ); - const groupFinished = $derived( - groupJobs.filter((g) => terminal.includes(jobStates[g.jobId] ?? 'queued')).length - ); - const running = $derived( - (jobState !== null && !terminal.includes(jobState)) || (groupJobs.length > 0 && groupRunning) - ); - const focusHostname = $derived( - groupJobs.find((g) => g.jobId === focusJobId)?.hostname ?? null - ); ⧉ Clone {/if} - @@ -535,49 +493,28 @@
-

Targets

-
- - -
- {#if targets.length > 0} -
    - {#each targets as key (key)} -
  • - {targetLabel(key)} - -
  • - {/each} -
- {:else} -

Add one or more devices or groups, then Run.

- {/if} - {#if targets.some((t) => t.startsWith('group:'))} +

Run

+ {#if allGroups.length === 0}

- Groups run on every non-orphaned member. Offline devices receive the job durably when - they reconnect. + No groups yet — create one under Groups, then run this script against it.

- {/if} - {#if devices.length === 0} -

No devices enrolled yet.

+ {:else} +

+ Select one or more groups. Each runs on every non-orphaned member; offline devices + receive the job when they reconnect. +

+
+ {#each allGroups as group (group.id)} + + {/each} +
{/if} {#if parameters.length > 0} @@ -591,110 +528,94 @@ {/if}
-{#if groupJobs.length > 0} -
-
-

Run

- {groupFinished}/{groupJobs.length} finished -
- {#if skippedOrphaned.length > 0} -

Skipped orphaned: {skippedOrphaned.join(', ')}

- {/if} -
    - {#each groupJobs as groupJob (groupJob.jobId)} -
  • - -
  • - {/each} -
-
-{/if} - -
-
-

Output{focusHostname ? ` — ${focusHostname}` : ''}

- {#if jobState} - - {/if} -
- {#if outputLines.length > 0} - - - {/if} -
-
- - {#if progress} -
-
- {progress.activity} - {progress.statusDescription ?? ''} -
-
-
-
-
- {progress.percentComplete ?? 0}% - {progress.secondsRemaining != null ? ` · ~${progress.secondsRemaining}s remaining` : ''} -
-
- {:else if running} -
Waiting for progress…
- {/if} - -
- {#if outputLines.length === 0} - - {job || groupJobs.length > 0 ? '—' : 'Run the script to see live progress and output.'} - - {:else if filteredOutput.length === 0} - No lines match “{outputSearch}”. - {:else} - {#each filteredOutput as line (line.seq)} -
{line.text}
- {/each} - {/if} -
-
- {#if !isNew}
-

History

- +

+ + {#if currentRun} + › + + {/if} + {#if currentTarget} + › + {currentTarget.hostname ?? currentTarget.clientId} + {/if} +

+ {#if !currentRun} + + {/if}
- {#if history.length === 0} -

No executions of this script yet.

- {:else} + + {#if !currentRun} + + {#if executions.length === 0} +

No executions yet. Select a group above and Run.

+ {:else} + + + + {#each executions as ex (ex.runId)} + openExecution(ex.runId)}> + + + + + + {/each} + +
StartedByTargetsResult
{new Date(ex.startedUtc).toLocaleString()}{ex.requestedBy ?? '—'}{ex.total} + {ex.succeeded}✓ + {#if ex.failed > 0}{ex.failed}✗{/if} + {#if ex.pending > 0}{ex.pending}…{/if} +
+ {/if} + {:else if !currentTarget} + - - - + - {#each history as h (h.jobId)} - goto(`/jobs?job=${h.jobId}`)}> - - - - + {#each currentRun.targets as t (t.jobId)} + openTarget(t)}> + + + + {/each}
StartedDeviceStateExit
DeviceStateExitFinished
{new Date(h.createdUtc).toLocaleString()}{h.hostname ?? h.clientId}{h.exitCode ?? '—'}
{t.hostname ?? t.clientId}{t.exitCode ?? '—'}{t.completedUtc ? new Date(t.completedUtc).toLocaleString() : '—'}
+ {:else} + +
+ + {#if outputLines.length > 0} + + + {/if} +
+
+ {#if outputLines.length === 0} + + {terminalStates.includes(currentTarget.state) ? 'No output.' : 'Waiting for output…'} + + {:else if filteredOutput.length === 0} + No lines match “{outputSearch}”. + {:else} + {#each filteredOutput as line (line.seq)} +
{line.text}
+ {/each} + {/if} +
{/if}
{/if} @@ -709,49 +630,84 @@ flex-wrap: wrap; } - .target-row { - display: flex; - gap: var(--space-2); - align-items: center; - } - - .chips { - list-style: none; - display: flex; - flex-wrap: wrap; - gap: var(--space-2); - margin: var(--space-2) 0 0; - padding: 0; - } - - .chip { - display: inline-flex; - align-items: center; - gap: 6px; - padding: 3px 8px; - border: 1px solid var(--border); - border-radius: 999px; - font-size: 12px; - background: var(--bg-subtle, transparent); - } - - .chip-x { - border: none; - background: none; - cursor: pointer; - color: var(--text-muted); - font-size: 11px; - padding: 0; - } - - .chip-x:hover { - color: var(--danger, #d33); - } - .clickable { cursor: pointer; } + .grouppick { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin-top: var(--space-2); + } + + .grp { + display: flex; + align-items: center; + gap: 6px; + border: 1px solid var(--border); + border-radius: 999px; + padding: 3px 12px; + font-size: 13px; + cursor: pointer; + } + + .grp.on { + border-color: var(--accent); + background: var(--accent-soft); + } + + .grp input { + accent-color: var(--accent); + } + + .crumbs-h { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 2px; + } + + .crumb { + background: none; + border: none; + padding: 0; + font: inherit; + color: var(--accent); + cursor: pointer; + } + + .crumb:disabled { + color: var(--text); + cursor: default; + } + + .crumb.current { + color: var(--text); + } + + .sep { + color: var(--text-muted); + margin: 0 6px; + } + + .tally { + font-size: 12px; + margin-right: 8px; + } + + .tally.ok { + color: var(--success); + } + + .tally.bad { + color: var(--danger); + } + + .tally.run { + color: var(--text-muted); + } + .crumbs { font-size: 12px; color: var(--text-muted); @@ -944,11 +900,6 @@ padding: var(--space-4); } - .target { - width: 100%; - margin-top: var(--space-2); - } - .exec-values { margin: var(--space-3) 0 var(--space-2); border-top: 1px solid var(--border); @@ -980,84 +931,10 @@ font-size: 12px; } - .group-jobs { - list-style: none; - margin: var(--space-2) 0 0; - padding: 0; - display: grid; - grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); - gap: 6px; - } - - .group-job { - width: 100%; - display: flex; - align-items: center; - justify-content: space-between; - gap: var(--space-2); - background: none; - border: 1px solid var(--border); - border-radius: var(--radius-sm); - padding: 6px 10px; - font-size: 13px; - color: var(--text); - cursor: pointer; - } - - .group-job.active { - border-color: var(--accent); - background: var(--accent-soft); - } - - .group-job .host { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } - - .warn { - color: var(--warning); - } - .small { font-size: 12px; } - .waiting { - margin-top: var(--space-2); - } - - .progress-block { - margin-top: var(--space-3); - } - - .progress-label { - display: flex; - justify-content: space-between; - font-size: 12.5px; - margin-bottom: 6px; - gap: var(--space-2); - } - - .progress-track { - height: 8px; - border-radius: 999px; - background: var(--surface-muted); - overflow: hidden; - } - - .progress-fill { - height: 100%; - border-radius: 999px; - background: var(--accent); - transition: width 0.4s ease; - } - - .progress-meta { - font-size: 11.5px; - margin-top: 4px; - } - .output { margin-top: var(--space-3); background: var(--bg); @@ -1071,9 +948,10 @@ line-height: 1.6; } + /* Terminal-style: keep each line intact and scroll wide output horizontally + (e.g. ifconfig) rather than wrapping it into a block. */ .output-line { - white-space: pre-wrap; - overflow-wrap: anywhere; + white-space: pre; } .output-line.error { -- 2.52.0 From 0d3a3e9da484799cc628aa81000d9152c19afa407f42a1a900fd2d4c6255d57a Mon Sep 17 00:00:00 2001 From: gsadmin Date: Tue, 11 Aug 2026 05:01:11 -0400 Subject: [PATCH 5/6] Pin the self-signed CA to a fingerprint carried in the bootstrap token [skip ci] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the trust-on-first-use MITM window on self-signed enrollment, without any extra plumbing. Server: when the managed self-signed chain is active, the minted bootstrap token becomes "secret.". The hash covers the whole string, so enrollment validation is unchanged, and the fingerprint travels wherever the token already goes (install command, MSI property, registry) — no separate value, endpoint, or CLI flag. Agent: enrollment is now connection-first. It attempts a normally-validated connection; only if the server certificate does not validate (self-signed, first contact) does it anchor trust — fetch the CA over the accept-any probe and pin it to the fingerprint parsed from the token. Match -> install + retry (validating against the just-verified chain, so it works in-process regardless of OS trust-store timing). Mismatch / no fingerprint / 404 -> refuse to enroll. A real or edge certificate simply validates and installs nothing (this also removes the old unconditional double-install). The pin is persisted to runtime state so the periodic CA refresh keeps THIS CA and refuses a later swap after the one-time token is cleared; re-anchoring a rotated CA requires a fresh token. Backend + agent build; Backend 103, Shared 89, Agent 60 tests pass. Co-Authored-By: Claude Fable 5 --- src/Agent/Configuration/AgentConfiguration.cs | 22 +++ .../Configuration/AgentConfigurationKeys.cs | 4 + src/Agent/Enrollment/EnrollmentService.cs | 126 ++++++++++++++---- src/Agent/Enrollment/ServerTrust.cs | 52 ++++++-- src/Agent/Service/CaRefreshService.cs | 25 ++-- src/Agent/Storage/RuntimeStateStore.cs | 7 + src/Backend/Api/BootstrapTokenEndpoints.cs | 12 ++ src/Backend/Tls/SelfSignedTlsManager.cs | 17 +++ 8 files changed, 220 insertions(+), 45 deletions(-) diff --git a/src/Agent/Configuration/AgentConfiguration.cs b/src/Agent/Configuration/AgentConfiguration.cs index c505c3a..81ea0ee 100644 --- a/src/Agent/Configuration/AgentConfiguration.cs +++ b/src/Agent/Configuration/AgentConfiguration.cs @@ -26,6 +26,28 @@ public sealed class AgentConfiguration Shared.Infrastructure.Routing.ServerUrl.TryParse(ServerUrlText.Value, out var parsed, out _) ? parsed : null; public bool HasBootstrapToken => !string.IsNullOrWhiteSpace(BootstrapToken.Value); + + /// + /// The server CA fingerprint (SHA-256, lowercase hex) the operator baked into + /// the bootstrap token as a "secret.fp" suffix, or null. The agent pins the CA + /// it fetches on first contact to this, so an on-path attacker cannot swap it. + /// The full token (with the suffix) is still what gets sent for validation. + /// + public string? ServerCaFingerprint + { + get + { + var token = BootstrapToken.Value; + var dot = token?.LastIndexOf('.') ?? -1; + if (token is null || dot < 0) + { + return null; + } + + var fp = token[(dot + 1)..]; + return fp.Length == 64 && fp.All(Uri.IsHexDigit) ? fp.ToLowerInvariant() : null; + } + } } /// Loads effective configuration using deterministic precedence. diff --git a/src/Agent/Configuration/AgentConfigurationKeys.cs b/src/Agent/Configuration/AgentConfigurationKeys.cs index b1822e0..7bf201c 100644 --- a/src/Agent/Configuration/AgentConfigurationKeys.cs +++ b/src/Agent/Configuration/AgentConfigurationKeys.cs @@ -46,4 +46,8 @@ public static class AgentRuntimeKeys public const string LastEnrollmentUtc = "LastEnrollmentUtc"; public const string LastConnectedUtc = "LastConnectedUtc"; public const string CredentialExpiresUtc = "CredentialExpiresUtc"; + + /// The CA fingerprint anchored at enrollment (the bootstrap token is + /// cleared afterwards, so the pin is kept here for the periodic refresh). + public const string ServerCaFingerprint = "ServerCaFingerprint"; } diff --git a/src/Agent/Enrollment/EnrollmentService.cs b/src/Agent/Enrollment/EnrollmentService.cs index 79ea6e7..ffd3f5f 100644 --- a/src/Agent/Enrollment/EnrollmentService.cs +++ b/src/Agent/Enrollment/EnrollmentService.cs @@ -1,4 +1,6 @@ using System.Net.Http.Json; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; using Agent.Configuration; using Agent.Identity; using Agent.Storage; @@ -80,35 +82,75 @@ public sealed class EnrollmentService( AgentVersion: BuildVersion.Resolve(typeof(EnrollmentService).Assembly), Device: ReadDeviceInfo()); - // Always probe for a self-signed CA first (the probe accepts any - // certificate — it only asks whether the server is self-signed and - // fetches public CA certs). A self-signed server's chain lands in the - // OS trust store so ordinary system validation succeeds below; a real - // certificate returns 404 and this is a no-op. Not pinned — a proxy - // with a real certificate added later still validates. - await ServerTrust.FetchAndInstallCaAsync(serverUrl, HttpClient.DefaultProxy, logger, cancellationToken); - - // TlsSkipVerify is the accept-any escape hatch; otherwise validate - // against the OS trust store (which now contains the CA above). - using var handler = new HttpClientHandler(); - if (configuration.TlsSkipVerify.Value) - { - handler.ServerCertificateCustomValidationCallback = - HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; - } - - using var http = new HttpClient(handler); var endpoint = serverUrl.ApiEndpoint(ApiRoutes.Bootstrap); logger.LogInformation("Bootstrapping client {ClientId} against {Endpoint}", clientId, endpoint); - using var response = await http.PostAsJsonAsync(endpoint, request, JsonDefaults.Options, cancellationToken); - if (!response.IsSuccessStatusCode) + // Connection-first trust: attempt a normally-validated connection. Only if + // the server certificate does not validate — a self-signed server on first + // contact — do we anchor trust by fetching its CA and pinning it to the + // fingerprint baked into the bootstrap token. A real/edge certificate, or a + // CA installed on a previous run, just validates and installs nothing. + HttpResponseMessage response; + if (configuration.TlsSkipVerify.Value) { - logger.LogError("Bootstrap rejected with HTTP {StatusCode}", (int)response.StatusCode); - return null; + // Manual accept-any escape hatch (CLI/GPO) — no anchoring. + using var skipHandler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator, + }; + response = await PostBootstrapAsync(skipHandler, endpoint, request, cancellationToken); + } + else + { + try + { + using var validating = new HttpClientHandler(); + response = await PostBootstrapAsync(validating, endpoint, request, cancellationToken); + } + catch (HttpRequestException ex) when (ex.HttpRequestError == HttpRequestError.SecureConnectionError) + { + var expectedFingerprint = configuration.ServerCaFingerprint; + if (expectedFingerprint is null) + { + logger.LogError( + "Server certificate is not trusted and the bootstrap token carries no CA fingerprint; refusing to enroll"); + return null; + } + + var (status, pinnedChain) = await ServerTrust.FetchAndInstallCaAsync( + serverUrl, HttpClient.DefaultProxy, logger, expectedFingerprint, cancellationToken); + if (status != ServerCaStatus.Installed) + { + logger.LogError("Could not anchor server trust ({Status}); refusing to enroll", status); + return null; + } + + // Remember the pin so the periodic refresh keeps THIS CA (and + // refuses a later swap) once the one-time token is cleared below. + runtimeState.ServerCaFingerprint = expectedFingerprint; + + // Retry, validating the leaf against the CA we just verified so it + // succeeds in-process regardless of OS trust-store timing. + using var pinnedHandler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = TrustPinnedChain(pinnedChain), + }; + response = await PostBootstrapAsync(pinnedHandler, endpoint, request, cancellationToken); + } + } + + BootstrapResponse? result; + using (response) + { + if (!response.IsSuccessStatusCode) + { + logger.LogError("Bootstrap rejected with HTTP {StatusCode}", (int)response.StatusCode); + return null; + } + + result = await response.Content.ReadFromJsonAsync(JsonDefaults.Options, cancellationToken); } - var result = await response.Content.ReadFromJsonAsync(JsonDefaults.Options, cancellationToken); if (result is null || string.IsNullOrWhiteSpace(result.UserJwt)) { logger.LogError("Bootstrap response was empty or invalid"); @@ -134,6 +176,44 @@ public sealed class EnrollmentService( return credentials; } + private static async Task PostBootstrapAsync( + HttpMessageHandler handler, Uri endpoint, BootstrapRequest request, CancellationToken cancellationToken) + { + using var http = new HttpClient(handler, disposeHandler: false); + return await http.PostAsJsonAsync(endpoint, request, JsonDefaults.Options, cancellationToken); + } + + /// + /// Validates the server leaf against a specific fetched-and-pinned CA chain + /// (custom root trust). Accepts only an untrusted-chain error — a name + /// mismatch or a missing certificate is still rejected. + /// + private static Func TrustPinnedChain( + X509Certificate2Collection pinned) + => (_, cert, _, errors) => + { + if (errors == SslPolicyErrors.None) + { + return true; + } + + if ((errors & ~SslPolicyErrors.RemoteCertificateChainErrors) != 0 || cert is null) + { + return false; + } + + using var chain = new X509Chain(); + chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + foreach (X509Certificate2 ca in pinned) + { + chain.ChainPolicy.CustomTrustStore.Add(ca); + chain.ChainPolicy.ExtraStore.Add(ca); + } + + return chain.Build(cert); + }; + /// /// Computes the deterministic client id, verifies it against the cached /// runtime value and refreshes the cache. diff --git a/src/Agent/Enrollment/ServerTrust.cs b/src/Agent/Enrollment/ServerTrust.cs index a8f32d8..67430dd 100644 --- a/src/Agent/Enrollment/ServerTrust.cs +++ b/src/Agent/Enrollment/ServerTrust.cs @@ -1,6 +1,8 @@ using System.Diagnostics; +using System.Linq; using System.Net; using System.Runtime.Versioning; +using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.Logging; using Shared.Contracts.Api; @@ -8,6 +10,22 @@ using Shared.Infrastructure.Routing; namespace Agent.Enrollment; +/// Outcome of probing and (maybe) installing the server's self-signed CA. +public enum ServerCaStatus +{ + /// 404 — the server is not self-signed (a real certificate is in front). + NotSelfSigned, + + /// The fetched CA matched the pinned fingerprint and was installed. + Installed, + + /// A chain was fetched but it did not match the pinned fingerprint — not installed. + FingerprintMismatch, + + /// The CA could not be fetched or parsed. + FetchFailed, +} + /// /// Makes the server's managed self-signed CA available to the OS trust store /// so ordinary system validation succeeds when the agent connects to the @@ -20,14 +38,16 @@ namespace Agent.Enrollment; public static class ServerTrust { /// - /// Fetches the server's CA chain and installs it into the OS trust store - /// (idempotent, best-effort). The fetch accepts any certificate — it is - /// retrieving public CA certs to establish trust — then verifies the - /// payload is real PEM certificates before installing. Returns true when - /// a chain was fetched. + /// Fetches the server's CA chain over an accept-any connection, verifies it + /// against (the pin the operator baked + /// into the bootstrap token), and — only on a match — installs it into the OS + /// trust store. The transport is untrusted by design; the fingerprint, not the + /// connection, is what authenticates the anchor. Returns the outcome and, when + /// installed, the verified chain (so the caller can validate the retry against + /// it directly, independent of OS trust-store timing). /// - public static async Task FetchAndInstallCaAsync( - ServerUrl serverUrl, IWebProxy? proxy, ILogger logger, CancellationToken cancellationToken) + public static async Task<(ServerCaStatus Status, X509Certificate2Collection Chain)> FetchAndInstallCaAsync( + ServerUrl serverUrl, IWebProxy? proxy, ILogger logger, string expectedFingerprint, CancellationToken cancellationToken) { using var handler = new HttpClientHandler { @@ -48,7 +68,7 @@ public static class ServerTrust using var response = await http.GetAsync(endpoint, cancellationToken); if (response.StatusCode == HttpStatusCode.NotFound) { - return false; // Server is not self-signed — nothing to install. + return (ServerCaStatus.NotSelfSigned, []); } response.EnsureSuccessStatusCode(); @@ -57,13 +77,23 @@ public static class ServerTrust if (chain.Count == 0) { logger.LogWarning("Server CA response contained no certificates"); - return false; + return (ServerCaStatus.FetchFailed, []); } } catch (Exception ex) { logger.LogWarning(ex, "Could not fetch the server CA from {Endpoint}", endpoint); - return false; + return (ServerCaStatus.FetchFailed, []); + } + + var expected = expectedFingerprint.Trim().ToLowerInvariant(); + var matched = chain.Cast() + .Any(c => Convert.ToHexStringLower(SHA256.HashData(c.RawData)) == expected); + if (!matched) + { + logger.LogError( + "Fetched server CA does not match the fingerprint pinned in the bootstrap token; refusing to trust (possible MITM)"); + return (ServerCaStatus.FingerprintMismatch, []); } if (OperatingSystem.IsWindows()) @@ -79,7 +109,7 @@ public static class ServerTrust InstallLinux(pem, logger); } - return true; + return (ServerCaStatus.Installed, chain); } [SupportedOSPlatform("windows")] diff --git a/src/Agent/Service/CaRefreshService.cs b/src/Agent/Service/CaRefreshService.cs index 412fd4b..0cfae32 100644 --- a/src/Agent/Service/CaRefreshService.cs +++ b/src/Agent/Service/CaRefreshService.cs @@ -1,22 +1,23 @@ using Agent.Configuration; using Agent.Enrollment; +using Agent.Storage; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Agent.Service; /// -/// Keeps the server's self-signed CA present in the OS trust store: probes -/// GET /api/enrollment/ca on start and every few hours, installing the chain -/// when the server is self-signed so a server-side rotation stays trusted -/// without operator action. The probe accepts any certificate (it is only -/// asking whether the server is self-signed and fetching public CA certs); a -/// 404 means the server is not self-signed, so it is a harmless no-op. It never -/// forces validation against the CA — a proxy with a real certificate is -/// unaffected. +/// Keeps the *pinned* self-signed CA present in the OS trust store: every few +/// hours it re-fetches GET /api/enrollment/ca and re-installs the chain only +/// when it still matches the fingerprint anchored at enrollment. A rotated or +/// substituted CA fails the check and is never installed, so trust is never +/// silently re-anchored — that requires a fresh bootstrap token. The pin comes +/// from the token before enrollment and from runtime state afterwards (the +/// one-time token is cleared once enrolled). A real/edge certificate has no +/// pin and needs no refresh — this is a no-op there. /// public sealed class CaRefreshService( - AgentConfigurationLoader loader, ILogger logger) : BackgroundService + AgentConfigurationLoader loader, RuntimeStateStore runtimeState, ILogger logger) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { @@ -25,10 +26,12 @@ public sealed class CaRefreshService( { do { - if (loader.Load().ServerUrl is { } serverUrl) + var config = loader.Load(); + var fingerprint = config.ServerCaFingerprint ?? runtimeState.ServerCaFingerprint; + if (config.ServerUrl is { } serverUrl && fingerprint is not null) { await ServerTrust.FetchAndInstallCaAsync( - serverUrl, System.Net.Http.HttpClient.DefaultProxy, logger, stoppingToken); + serverUrl, System.Net.Http.HttpClient.DefaultProxy, logger, fingerprint, stoppingToken); } } while (await timer.WaitForNextTickAsync(stoppingToken)); diff --git a/src/Agent/Storage/RuntimeStateStore.cs b/src/Agent/Storage/RuntimeStateStore.cs index c2aa28d..8beadfe 100644 --- a/src/Agent/Storage/RuntimeStateStore.cs +++ b/src/Agent/Storage/RuntimeStateStore.cs @@ -39,6 +39,13 @@ public sealed class RuntimeStateStore(IRegistryStore registry) set => WriteTimestamp(AgentRuntimeKeys.CredentialExpiresUtc, value); } + /// CA fingerprint pinned at enrollment, for the periodic CA refresh. + public string? ServerCaFingerprint + { + get => registry.ReadString(Branding.AgentRuntimeRegistryKey, AgentRuntimeKeys.ServerCaFingerprint); + set => WriteOrDelete(AgentRuntimeKeys.ServerCaFingerprint, value); + } + /// Removes the one-time bootstrap token from the normal registry key. public void ClearBootstrapToken() => registry.DeleteValue(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken); diff --git a/src/Backend/Api/BootstrapTokenEndpoints.cs b/src/Backend/Api/BootstrapTokenEndpoints.cs index f1b0a46..d08b879 100644 --- a/src/Backend/Api/BootstrapTokenEndpoints.cs +++ b/src/Backend/Api/BootstrapTokenEndpoints.cs @@ -1,6 +1,7 @@ using Backend.Auth; using Backend.Data; using Backend.Security; +using Backend.Tls; using Microsoft.EntityFrameworkCore; using Shared.Contracts.Api; using Shared.Infrastructure.Constants; @@ -47,7 +48,18 @@ public static class BootstrapTokenEndpoints var maxUses = request?.MaxUses ?? ProtocolDefaults.BootstrapTokenDefaultMaxUses; // Plaintext exists exactly once: in this response. Only the hash is stored. + // When the server runs the managed self-signed chain, append its CA + // fingerprint (token = "secret.fp"): the agent pins the CA it fetches on + // first contact to this value, so an on-path attacker cannot substitute a + // CA. The fp travels wherever the token does — no extra plumbing — and the + // hash covers the whole string, so enrollment validation is unchanged. var token = TokenGenerator.CreateUrlSafeToken(ProtocolDefaults.BootstrapTokenEntropyBytes); + var caFingerprint = context.RequestServices.GetService()?.CaFingerprint(); + if (caFingerprint is not null) + { + token += "." + caFingerprint; + } + var actor = context.User.Identity?.Name; var entity = new BootstrapTokenEntity diff --git a/src/Backend/Tls/SelfSignedTlsManager.cs b/src/Backend/Tls/SelfSignedTlsManager.cs index 18cc847..27db00c 100644 --- a/src/Backend/Tls/SelfSignedTlsManager.cs +++ b/src/Backend/Tls/SelfSignedTlsManager.cs @@ -80,6 +80,23 @@ public sealed class SelfSignedTlsManager } } + /// + /// SHA-256 (lowercase hex) of the root CA certificate. Baked into bootstrap + /// tokens so an enrolling agent can pin the CA it fetches over the untrusted + /// first-contact channel to the one this server actually publishes. Null + /// before the chain exists. + /// + public string? CaFingerprint() + { + lock (gate) + { + var root = persistence.Load(TlsRole.Root); + return root is null + ? null + : Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(root.RawData)); + } + } + /// /// Creates or re-issues whatever links are missing, expiring, or no /// longer signed by the current parent (a rotated root cascades down). -- 2.52.0 From 938f4e2ccb0b945ebb8ed264d33cce233f48c07900a400f4e9ef18e8513c191f Mon Sep 17 00:00:00 2001 From: gsadmin Date: Tue, 11 Aug 2026 05:41:44 -0400 Subject: [PATCH 6/6] Graceful root renewal (same key) + authenticated CA refresh [skip ci] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit So a root that reaches its renewal margin no longer breaks enrolled agents. Server: the root is now renewed IN PLACE with the same key — only the certificate validity is extended (RenewRoot). Same subject + key means the same Subject Key Identifier, so the existing intermediate/leaf keep chaining to it; agents that already trust the root keep validating across the handoff. A true key rotation stays a deliberate re-enrollment event. (File persistence now loads keys Exportable, matching the Windows-store backend, so the in-place renewal can re-use the key.) Agent: the periodic CA refresh (CaRefreshService) now runs over a NORMALLY- VALIDATED connection (ServerTrust.RefreshCaAsync) and installs whatever the trusted server serves — so a renewed root (or new intermediate) is picked up before the old cert expires, no operator action. The fingerprint pin is enforced only at first-contact enrollment (unauthenticated); ongoing refresh is authenticated by the transport, so the persisted-pin machinery is gone. A full key rotation simply can't validate and is left for a fresh token. New test drives an in-place renewal and asserts the root cert changes, the key does not, the intermediate/leaf are untouched, and a leaf still validates against the ORIGINAL root. Backend 104, Shared 89, Agent 60 tests pass. Co-Authored-By: Claude Fable 5 --- .../Configuration/AgentConfigurationKeys.cs | 4 -- src/Agent/Enrollment/EnrollmentService.cs | 4 -- src/Agent/Enrollment/ServerTrust.cs | 63 +++++++++++++++++++ src/Agent/Service/CaRefreshService.cs | 28 ++++----- src/Agent/Storage/RuntimeStateStore.cs | 7 --- src/Backend/Tls/SelfSignedTlsManager.cs | 54 ++++++++++++++-- src/Backend/Tls/TlsPersistence.cs | 9 ++- tests/Backend.Tests/SelfSignedTlsTests.cs | 43 +++++++++++++ 8 files changed, 175 insertions(+), 37 deletions(-) diff --git a/src/Agent/Configuration/AgentConfigurationKeys.cs b/src/Agent/Configuration/AgentConfigurationKeys.cs index 7bf201c..b1822e0 100644 --- a/src/Agent/Configuration/AgentConfigurationKeys.cs +++ b/src/Agent/Configuration/AgentConfigurationKeys.cs @@ -46,8 +46,4 @@ public static class AgentRuntimeKeys public const string LastEnrollmentUtc = "LastEnrollmentUtc"; public const string LastConnectedUtc = "LastConnectedUtc"; public const string CredentialExpiresUtc = "CredentialExpiresUtc"; - - /// The CA fingerprint anchored at enrollment (the bootstrap token is - /// cleared afterwards, so the pin is kept here for the periodic refresh). - public const string ServerCaFingerprint = "ServerCaFingerprint"; } diff --git a/src/Agent/Enrollment/EnrollmentService.cs b/src/Agent/Enrollment/EnrollmentService.cs index ffd3f5f..56377c6 100644 --- a/src/Agent/Enrollment/EnrollmentService.cs +++ b/src/Agent/Enrollment/EnrollmentService.cs @@ -125,10 +125,6 @@ public sealed class EnrollmentService( return null; } - // Remember the pin so the periodic refresh keeps THIS CA (and - // refuses a later swap) once the one-time token is cleared below. - runtimeState.ServerCaFingerprint = expectedFingerprint; - // Retry, validating the leaf against the CA we just verified so it // succeeds in-process regardless of OS trust-store timing. using var pinnedHandler = new HttpClientHandler diff --git a/src/Agent/Enrollment/ServerTrust.cs b/src/Agent/Enrollment/ServerTrust.cs index 67430dd..e18ad3e 100644 --- a/src/Agent/Enrollment/ServerTrust.cs +++ b/src/Agent/Enrollment/ServerTrust.cs @@ -112,6 +112,69 @@ public static class ServerTrust return (ServerCaStatus.Installed, chain); } + /// + /// Post-enrollment CA refresh over a NORMALLY-VALIDATED connection. The agent + /// already trusts the current CA, so an updated chain served over that trusted + /// connection — a root renewed in place (same key, longer validity) or a new + /// intermediate — is authentic and installed. No pin here: the validated + /// transport, not a fingerprint, authenticates it (first contact was pinned at + /// enrollment). A 404 (real certificate) or a validation failure is a harmless + /// no-op. Returns true when a chain was installed. + /// + public static async Task RefreshCaAsync( + ServerUrl serverUrl, IWebProxy? proxy, ILogger logger, CancellationToken cancellationToken) + { + using var handler = new HttpClientHandler(); + if (proxy is not null) + { + handler.Proxy = proxy; + handler.UseProxy = true; + } + + using var http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) }; + var endpoint = serverUrl.ApiEndpoint(ApiRoutes.EnrollmentCaChain); + string pem; + X509Certificate2Collection chain = []; + try + { + using var response = await http.GetAsync(endpoint, cancellationToken); + if (response.StatusCode == HttpStatusCode.NotFound) + { + return false; + } + + response.EnsureSuccessStatusCode(); + pem = await response.Content.ReadAsStringAsync(cancellationToken); + chain.ImportFromPem(pem); + if (chain.Count == 0) + { + return false; + } + } + catch (Exception ex) + { + // Untrusted (root may have rotated its key — needs re-enrollment), + // unchanged, or unreachable: nothing to do this cycle. + logger.LogDebug(ex, "CA refresh skipped"); + return false; + } + + if (OperatingSystem.IsWindows()) + { + InstallWindows(chain, logger); + } + else if (OperatingSystem.IsMacOS()) + { + InstallMac(pem, logger); + } + else + { + InstallLinux(pem, logger); + } + + return true; + } + [SupportedOSPlatform("windows")] private static void InstallWindows(X509Certificate2Collection chain, ILogger logger) { diff --git a/src/Agent/Service/CaRefreshService.cs b/src/Agent/Service/CaRefreshService.cs index 0cfae32..d22f637 100644 --- a/src/Agent/Service/CaRefreshService.cs +++ b/src/Agent/Service/CaRefreshService.cs @@ -1,23 +1,23 @@ using Agent.Configuration; using Agent.Enrollment; -using Agent.Storage; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Agent.Service; /// -/// Keeps the *pinned* self-signed CA present in the OS trust store: every few -/// hours it re-fetches GET /api/enrollment/ca and re-installs the chain only -/// when it still matches the fingerprint anchored at enrollment. A rotated or -/// substituted CA fails the check and is never installed, so trust is never -/// silently re-anchored — that requires a fresh bootstrap token. The pin comes -/// from the token before enrollment and from runtime state afterwards (the -/// one-time token is cleared once enrolled). A real/edge certificate has no -/// pin and needs no refresh — this is a no-op there. +/// Keeps the server's CA current in the OS trust store after enrollment. Every +/// few hours it re-fetches GET /api/enrollment/ca over a NORMALLY-VALIDATED +/// connection and installs the chain, so a root renewed in place (same key, +/// extended validity) or a new intermediate is picked up before the old cert +/// expires — no operator action, no re-enrollment. The validated transport +/// authenticates the update, so no pin is needed here (first-contact trust was +/// pinned to the token at enrollment). A real/edge certificate returns 404 — a +/// no-op — and a full root *key* rotation cannot validate and is left for a +/// fresh bootstrap token. /// public sealed class CaRefreshService( - AgentConfigurationLoader loader, RuntimeStateStore runtimeState, ILogger logger) : BackgroundService + AgentConfigurationLoader loader, ILogger logger) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { @@ -26,12 +26,10 @@ public sealed class CaRefreshService( { do { - var config = loader.Load(); - var fingerprint = config.ServerCaFingerprint ?? runtimeState.ServerCaFingerprint; - if (config.ServerUrl is { } serverUrl && fingerprint is not null) + if (loader.Load().ServerUrl is { } serverUrl) { - await ServerTrust.FetchAndInstallCaAsync( - serverUrl, System.Net.Http.HttpClient.DefaultProxy, logger, fingerprint, stoppingToken); + await ServerTrust.RefreshCaAsync( + serverUrl, System.Net.Http.HttpClient.DefaultProxy, logger, stoppingToken); } } while (await timer.WaitForNextTickAsync(stoppingToken)); diff --git a/src/Agent/Storage/RuntimeStateStore.cs b/src/Agent/Storage/RuntimeStateStore.cs index 8beadfe..c2aa28d 100644 --- a/src/Agent/Storage/RuntimeStateStore.cs +++ b/src/Agent/Storage/RuntimeStateStore.cs @@ -39,13 +39,6 @@ public sealed class RuntimeStateStore(IRegistryStore registry) set => WriteTimestamp(AgentRuntimeKeys.CredentialExpiresUtc, value); } - /// CA fingerprint pinned at enrollment, for the periodic CA refresh. - public string? ServerCaFingerprint - { - get => registry.ReadString(Branding.AgentRuntimeRegistryKey, AgentRuntimeKeys.ServerCaFingerprint); - set => WriteOrDelete(AgentRuntimeKeys.ServerCaFingerprint, value); - } - /// Removes the one-time bootstrap token from the normal registry key. public void ClearBootstrapToken() => registry.DeleteValue(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken); diff --git a/src/Backend/Tls/SelfSignedTlsManager.cs b/src/Backend/Tls/SelfSignedTlsManager.cs index 27db00c..7ef1c5c 100644 --- a/src/Backend/Tls/SelfSignedTlsManager.cs +++ b/src/Backend/Tls/SelfSignedTlsManager.cs @@ -98,19 +98,23 @@ public sealed class SelfSignedTlsManager } /// - /// Creates or re-issues whatever links are missing, expiring, or no - /// longer signed by the current parent (a rotated root cascades down). + /// Creates or re-issues whatever links are missing, expiring, or no longer + /// signed by the current parent. The root is renewed in place with the + /// same key so the trust anchor stays continuous — already-enrolled + /// agents keep validating; only the certificate's validity is extended. /// Idempotent; returns true when anything was issued. /// - public bool EnsureChain(ILogger logger) + public bool EnsureChain(ILogger logger) => EnsureChain(logger, DateTimeOffset.UtcNow); + + /// Testable overload — the clock is injected so renewal can be exercised. + internal bool EnsureChain(ILogger logger, DateTimeOffset now) { lock (gate) { - var now = DateTimeOffset.UtcNow; var changed = false; var root = persistence.Load(TlsRole.Root); - if (!IsUsable(root, now, lifetimes.RootRenewalMargin)) + if (root is null) { root = persistence.Save(TlsRole.Root, CreateRoot(now)); logger.LogInformation( @@ -118,6 +122,17 @@ public sealed class SelfSignedTlsManager root.NotAfter.ToUniversalTime()); changed = true; } + else if (!IsUsable(root, now, lifetimes.RootRenewalMargin)) + { + // Renew with the SAME key: the intermediate/leaf still chain to it, + // and agents that already trust this root keep validating across the + // handoff. A true key rotation is a deliberate re-enrollment event. + root = persistence.Save(TlsRole.Root, RenewRoot(root, now)); + logger.LogInformation( + "Self-signed TLS: renewed the root CA in place (valid to {NotAfter:u})", + root.NotAfter.ToUniversalTime()); + changed = true; + } var intermediate = persistence.Load(TlsRole.Intermediate); if (!IsUsable(intermediate, now, lifetimes.IntermediateRenewalMargin) @@ -185,6 +200,35 @@ public sealed class SelfSignedTlsManager return request.CreateSelfSigned(now.AddMinutes(-5), now + lifetimes.Root); } + /// + /// Re-issues the root certificate with the same key and an extended + /// validity. Same subject + key means the same Subject Key Identifier, so the + /// existing intermediate (and everything under it) keeps chaining to it — the + /// only change agents see is a longer-lived root cert, picked up on refresh. + /// + private X509Certificate2 RenewRoot(X509Certificate2 existing, DateTimeOffset now) + { + // Rebuild a fresh ECDsa from the same key material (like CreateRoot's fresh + // key), so the renewed certificate owns a durable, exportable private key. + ECParameters parameters; + using (var existingKey = existing.GetECDsaPrivateKey() + ?? throw new InvalidOperationException("Root certificate has no ECDSA private key to renew from.")) + { + parameters = existingKey.ExportParameters(includePrivateParameters: true); + } + + using var key = ECDsa.Create(parameters); + var request = new CertificateRequest(TlsSubjects.Root, key, HashAlgorithmName.SHA384); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension( + certificateAuthority: true, hasPathLengthConstraint: true, pathLengthConstraint: 1, critical: true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension( + X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, critical: true)); + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( + [new Oid("1.3.6.1.5.5.7.3.1")], critical: false)); + request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); + return request.CreateSelfSigned(now.AddMinutes(-5), now + lifetimes.Root); + } + private X509Certificate2 CreateIntermediate(X509Certificate2 root, DateTimeOffset now) { using var key = ECDsa.Create(ECCurve.NamedCurves.nistP384); diff --git a/src/Backend/Tls/TlsPersistence.cs b/src/Backend/Tls/TlsPersistence.cs index 7be213a..4db8925 100644 --- a/src/Backend/Tls/TlsPersistence.cs +++ b/src/Backend/Tls/TlsPersistence.cs @@ -104,10 +104,15 @@ internal sealed class FileTlsPersistence(string directory) : ITlsPersistence + root.ExportCertificatePem() + '\n'); } - /// SChannel rejects ephemeral PEM keys; round-trip through PFX on Windows. + /// + /// SChannel rejects ephemeral PEM keys; round-trip through PFX on Windows. + /// Exportable mirrors the Windows-store backend and lets an in-place root + /// renewal re-use the key (it is already an exportable PEM on disk here). + /// private static X509Certificate2 WithUsableKey(X509Certificate2 certificate) => OperatingSystem.IsWindows() - ? X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx), null) + ? X509CertificateLoader.LoadPkcs12( + certificate.Export(X509ContentType.Pfx), null, X509KeyStorageFlags.Exportable) : certificate; private static void WriteSecret(string path, string content) diff --git a/tests/Backend.Tests/SelfSignedTlsTests.cs b/tests/Backend.Tests/SelfSignedTlsTests.cs index 2dc6a71..92c227b 100644 --- a/tests/Backend.Tests/SelfSignedTlsTests.cs +++ b/tests/Backend.Tests/SelfSignedTlsTests.cs @@ -111,6 +111,49 @@ public sealed class SelfSignedTlsTests : IDisposable Assert.Equal(oldRoot, File.ReadAllText(Path.Combine(directory, "root.crt"))); } + [Fact] + public void EnsureChain_RenewsRootInPlaceWithSameKey_SoEnrolledAgentsKeepValidating() + { + // Root life above the intermediate's renewal margin (so only the root is + // due to renew), but below its own renewal margin (so it renews now). + var lifetimes = TlsLifetimes.Default with + { + Root = TimeSpan.FromDays(300), + RootRenewalMargin = TimeSpan.FromDays(400), + }; + var manager = new SelfSignedTlsManager(Settings, lifetimes); + manager.EnsureChain(NullLogger.Instance); + + using var originalRoot = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(directory, "root.crt")); + var originalRootThumbprint = originalRoot.Thumbprint; + var originalRootKey = originalRoot.GetECDsaPublicKey()!.ExportSubjectPublicKeyInfo(); + var originalIntermediate = File.ReadAllText(Path.Combine(directory, "intermediate.crt")); + var originalLeaf = manager.ServerCertificate!.Thumbprint; + + var changed = manager.EnsureChain(NullLogger.Instance); + Assert.True(changed); + + using var renewedRoot = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(directory, "root.crt")); + + // The root certificate is a new one (extended validity) ... + Assert.NotEqual(originalRootThumbprint, renewedRoot.Thumbprint); + // ... but the same key, and the intermediate + leaf are untouched. + Assert.Equal(originalRootKey, renewedRoot.GetECDsaPublicKey()!.ExportSubjectPublicKeyInfo()); + Assert.Equal(originalIntermediate, File.ReadAllText(Path.Combine(directory, "intermediate.crt"))); + Assert.Equal(originalLeaf, manager.ServerCertificate!.Thumbprint); + + // The crux: an agent that still trusts only the ORIGINAL root validates the + // current leaf, because the chain signs to the same key — no break, no + // re-enrollment when the root renews. + using var intermediate = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(directory, "intermediate.crt")); + using var chain = new X509Chain(); + chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + chain.ChainPolicy.CustomTrustStore.Add(originalRoot); + chain.ChainPolicy.ExtraStore.Add(intermediate); + Assert.True(chain.Build(manager.ServerCertificate!), "leaf must still validate against the original root"); + } + [Fact] public void EnsureChain_RotatedRootCascadesToTheWholeChain() { -- 2.52.0