10 Commits

Author SHA256 Message Date
Alphaeus Mote b05837d51f feat(shell): choose which signed-in user a Run As shell opens as [skip ci]
The agent lists who is signed in with each shell state; the console's Run As
menu offers each name, and the agent opens as that user only while they are
signed in. Several users with nobody at the console is no longer a dead end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:04:50 -05:00
Alphaeus Mote 3832790484 Merge branch 'feat/install-repair' [skip ci] 2026-11-18 09:29:49 -05:00
Alphaeus Mote 21e9bad12f feat(groups): script groups, joined and left by what a script reports [skip ci]
- Every script gets built-ins: Set-ExecuteRGroupMembership (member when the
  value is true, above 0, a non-empty collection or yes-like text; pipe results
  in), Add-/Remove-ExecuteRGroupMembership, and executer_group in Bash. They
  need no credentials: the agent takes their lines out of the output and sends
  the answers with the job's final state.
- The server adds or removes the device in that script group, creating it (top
  level, kind Script) the first time a device joins. Each run decides again.
- Only script groups change: a curated group by that name is ignored, so a
  device can never add itself to one. Last answer per group wins; 25 a job.
- Console: Script kind in the group editor, tree and lists (reported devices,
  no hand-listing), editor completions and snippets for the built-ins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:29:48 -05:00
Alphaeus Mote 0b85bd5e8a feat(install): idempotent install scripts that upgrade or repair a failed agent [skip ci]
Every served install script (Windows/WinPE PowerShell 5.1, Linux and macOS
bash) now looks at the device before acting: a healthy, current agent
enrolled with this server is left alone (Already Installed), an older one is
upgraded in place with its enrollment kept, a failed one (service missing,
disabled, stopped or crash-looping, watchdog down, binary missing or broken,
Windows Installer registration or cache gone) is restarted through the
agent's own initialize and, if that does not help, reinstalled (MSI repair
REINSTALL=ALL REINSTALLMODE=vamus, cache restored from the kept package,
uninstall+install with ProgramData and the registry key set aside as a last
resort; Linux/macOS move files in one by one and re-register the unit or
daemon). The bootstrap token is used only when there is no usable credential
or the agent points at another server, never printed, and masked out of
failure messages. One setup at a time, leftovers of interrupted runs cleared.
Each run ends with one outcome line and exits 1 on failure.

The agent's status verb now prints a JSON line with version, server URL,
credential state (valid/missing/unreadable/other-device) and whether a
bootstrap token is pending, which the scripts read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:20:40 -05:00
Alphaeus Mote 505e9849eb Merge branch 'feat/log-format' [skip ci] 2026-11-18 09:03:20 -05:00
Alphaeus Mote 0e2056ca6c feat(runs): run again on a status's devices, the checked ones or the failed ones [skip ci]
- Each status tile of a run (Failed, Timed Out, Skipped, ...) has Run Again on
  These: right-click it or use its ⋯.
- Checked rows get Run Again on N beside Download Logs.
- The run page adds Run Again on N Failed (failed and timed out) next to Run Again.
- The same from a script's Executions panel. Each opens Run Script with those
  devices as targets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:03:11 -05:00
Alphaeus Mote 3e994102ed feat(agent): shells and scripts can run as the signed-in user [skip ci]
- Remote Shell gets Run As: Agent Account (default) or Signed-In User. Windows
  starts the shell with the user's own token, environment and profile folder on
  their desktop, headless; Linux and macOS start their login shell through su -l.
- Scripts get Run As Signed-In User. Every engine then runs out of process as the
  user (PowerShell 7 in the agent's built-in host, 5.1, Bash; su on unix), with
  no window, and the user is given that job folder only.
- The user is the console's, else the only one signed in; several and nobody at
  the console is refused rather than guessed.
- The server never sends either to agents older than 1.13.0 (they would ignore it
  and run as the agent's account): such jobs are created failed, the shell is
  refused. Migration for all three providers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:59:56 -05:00
Alphaeus Mote 28b2a53c29 feat(logging): one log line format everywhere, repeated warnings bounded [skip ci]
Every text line ExecuteR writes now reads
[2026-11-16T17:53:40.653Z] - [Category] - [LEVEL] - message key=value:
UTC time to the millisecond, a short category (the logging type without its
namespace, or Agent/Server), TRACE..FATAL, the rendered message and the
properties it did not use as key=value (correlation fields kept, enrichment
noise left out). Serilog writes it through LogLineFormatter (console, file
and the live views' message text); LOG_JSON keeps compact JSON. The watchdog
and its MSI/removal runners write the same format, and the Rust screen host
too (a tracing layer), with the agent taking each host line apart and logging
it once at the host's level and category, without a second timestamp.

LogLineParser reads the format back and the old ones still in device files
(services' [yyyy-MM-dd HH:mm:ss.fff LVL] Source: message, the watchdog's
...Z [LVL] message, tracing's default); the watchdog's live view uses it.

A warning, error or fatal that repeats (same level, SourceContext and
template) is written once, then counted for 60 s; the window's end writes one
line with repeated=N window=60s, a quiet window forgets it, at most 1,000 keys
are tracked and disposing writes open counts. The screen host does the same.

The console's log viewer shows the new level names and categories and copies
lines in the file format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:55:11 -05:00
Alphaeus Mote 09818d81c4 feat(console): agent downloads under Storage & Agent Packages, break-glass in the hover, more terminal themes [skip ci]
- The Agent Downloads card (public links, package list) moves from Enrollment
  Tokens to the Storage & Agent Packages tab.
- Built-In Sign-In drops the Break-Glass Account row; the card's hover names it.
- Eleven more terminal themes: Dracula, One Dark, Monokai, Nord, Gruvbox Dark,
  Tokyo Night, Ubuntu, High Contrast, Green Phosphor, Amber, Solarized Light.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:07:32 -05:00
Alphaeus Mote 34a46f3c40 feat(shell): terminal themes, text size and longer scrollback [skip ci]
Terminal Settings (per browser, live in every open shell, docked or popped
out): five themes, text size 9-28 px (Ctrl + = / - / 0 and Ctrl + wheel in
the terminal), scrollback 1,000-25,000 lines, 10,000 by default (was
xterm's 1,000).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 16:56:31 -05:00
97 changed files with 13260 additions and 489 deletions
+136 -3
View File
@@ -1042,7 +1042,7 @@ ExecuteR-Agent.exe start start the service
ExecuteR-Agent.exe stop stop the service
ExecuteR-Agent.exe initialize install + start
ExecuteR-Agent.exe remove stop + remove the service
ExecuteR-Agent.exe status machine- and human-readable state
ExecuteR-Agent.exe status JSON line (service, version, server, credential) + human-readable
ExecuteR-Agent.exe version unified build version
ExecuteR-Agent.exe run <name|id> start an On Demand script (see "On Demand and the device CLI")
ExecuteR-Agent.exe upload <path> send files up to S3 (see "Device uploads to S3")
@@ -1098,6 +1098,29 @@ back. Closing the window brings it back when the console is showing that
device's shell and ends the session otherwise; reloading or closing the
console tab ends every popped-out shell, since they run on its page.
**Terminal Settings** (the **Tt** button; theme and text size also sit in a
pop-out's toolbar) are remembered per browser and apply to every open shell at
once: a theme (Dark, Classic, PowerShell Blue, Solarized Dark, Dracula, One Dark,
Monokai, Nord, Gruvbox Dark, Tokyo Night, Ubuntu, High Contrast, Green Phosphor,
Amber, Light, Solarized Light), the text
size (9-28 px; in the terminal Ctrl + = / Ctrl + - or Ctrl + mouse wheel, Ctrl + 0
resets) and the scrollback, the output lines kept above the screen (1,000 to
25,000; 10,000 by default). Older lines drop off as new output arrives.
**Run As** picks whose account a new shell runs as: the **Agent Account**
(LocalSystem, root; the default each time) or the **Signed-In User**: the
console's user, else the only user signed in (several users and nobody at the
console is ambiguous, so the shell is refused rather than guessed), or one of
the signed-in users by name. The agent reports who is signed in with every
shell it opens, and with a refused run-as-user open, so the menu lists them;
it refuses a name that is not signed in (on macOS, anyone but the console's
user). Windows
starts the shell with that user's own token (`WTSQueryUserToken`), environment
and profile folder on their desktop, headless: no window appears for them.
Linux and macOS start the user's login shell through `su -l`. The server
refuses it for agents older than 1.13.0, which would ignore it and start the
agent's account instead; the audit entry records which account was asked for.
---
## Agent upgrades and the watchdog
@@ -1472,6 +1495,37 @@ The agent generates its NKey locally (the private seed never leaves the device),
bootstraps over HTTPS, receives a scoped NATS JWT, erases the token, and
connects over WSS. The device appears in the UI within seconds.
**Running the command again is safe.** Every script (Windows, Windows PE,
Linux, macOS) looks at the device before it acts and ends with one outcome
line — `Installed`, `Upgraded`, `Repaired`, `Already Installed` or
`Failed: <reason>` (exit code 1):
| What the device has | What the script does |
|---------------------|----------------------|
| No agent | Installs as above (MSI; the portable ZIP in Windows PE or with `&type=zip`) |
| A healthy agent, as new as the server's package or newer, enrolled with this server | Nothing |
| An older agent | Upgrades in place (the MSI as a major upgrade; Linux/macOS lay the files down again); the enrollment is kept |
| Service missing, disabled, stopped or crash-looping; watchdog not running | Restarts it through the agent's own `initialize` (re-registers the service as Automatic, starts agent and watchdog); if that does not help, installs the package again |
| Agent binary missing or not running; Windows Installer registration or its cached package gone | Installs the package again: the same MSI build as a repair (`REINSTALL=ALL REINSTALLMODE=vamus`, re-caching it; a lost cache is first restored from the MSI the agent keeps under `%ProgramData%\ExecuteR\packages`), another build as an upgrade, every file laid down (`amus`). Only when Windows Installer refuses that does it uninstall and install again, with `%ProgramData%\ExecuteR` and `HKLM\SOFTWARE\ExecuteR` set aside and put back, so the enrollment and settings survive. Linux/macOS move the files in one by one and register the unit / daemon again |
| No usable credential (missing, unreadable, of other hardware), or pointed at another server | Hands the agent this command's bootstrap token and restarts it. A valid enrollment is never replaced, so the device keeps its identity; re-enrolling the same hardware keeps the same device row anyway |
The decision reads `executer-agent status` / `ExecuteR-Agent.exe status`,
whose first line is JSON: service state, version, server URL, credential
(`valid`, `missing`, `unreadable`, `other-device`; an expired credential is
still `valid`, it renews itself) and whether a bootstrap token is pending —
never the token. Health means the service is registered, enabled and still
running a few seconds later, the watchdog runs, the credential is valid and
the server URL matches (case and a trailing slash aside; a Group Policy
`ServerURL` pointing elsewhere is a failure, not something the script
overrides). The script embeds the version the package link serves, so a
current device downloads nothing. Interrupted runs do not break a rerun: one
setup runs at a time (a global mutex on Windows, a lock directory on
Linux/macOS), leftover downloads and half-moved files are cleared, a Windows
Installer operation in progress is waited for, and data set aside by an
interrupted last-resort reinstall is put back first. The token goes only to
`msiexec`'s hidden `BOOTSTRAPTOKEN`, the agent's registry / `agent.json`, or
`configure --token`; it is masked out of failure messages.
![Add device](docs/screenshots/add-device.png)
---
@@ -1778,7 +1832,8 @@ Per-script options in the editor (Details):
| Option | Default | What it does |
|--------|---------|--------------|
| **Run From File** | off | PowerShell 7 stages the script in the job folder and runs it by path (`AddCommand`), not from memory. PowerShell 5 and Bash always run from a file. |
| **Set Working Directory to Script Folder** | off | Starts a staged script in its job folder (the process's directory for 5.1 and Bash; the runspace's location for PowerShell 7, never the shared agent process's). Only with a staged file. Off keeps the engine's usual directory: the agent's own (`C:\Windows\System32` for the service). |
| **Set Working Directory to Script Folder** | off | Starts a staged script in its job folder (the process's directory for 5.1 and Bash; the runspace's location for PowerShell 7, never the shared agent process's). Only with a staged file. Off keeps the engine's usual directory: the agent's own (`C:\Windows\System32` for the service), or the user's profile folder or home with Run As Signed-In User. |
| **Run As Signed-In User** | off | Runs the script as the person signed in on the device (the console's user, else the only one signed in) instead of the agent's account. Every engine runs out of process: PowerShell 7 in the agent's built-in host, 5.1 in `powershell.exe`, Bash in `bash` (through `su` on Linux and macOS), with output and errors but no progress records. Windows uses the user's token, environment (plus the bundled modules) and profile folder, headless, so nothing appears on their screen. The user is given that job folder only (Windows: Modify on it; Linux/macOS: it becomes theirs and the job root traverse-only). Nobody signed in, or several and nobody at the console, fails the job; so does an agent older than 1.13.0, which the server never sends it to. |
| **Clean Up After Run** | on | Deletes the job folder when the run ends. |
| **Restart After Run** | Off | Restarts the device after the run: **Always**, or **When the Script Asks**, with an optional delay (up to 60 minutes) and an optional warning for signed-in users. See [Restart After Run](#restart-after-run). |
@@ -2198,13 +2253,14 @@ way as manual runs.
## Device groups and script triggers
Groups form a **tree**. Each group is one of three kinds:
Groups form a **tree**. Each group is one of four kinds:
| Kind | Members |
|------|---------|
| **Folder** | None of its own — it organizes the groups nested under it |
| **Static** | An explicit list of devices |
| **Dynamic** | The devices matching its rules, evaluated against live device data |
| **Script** | The devices whose scripts last reported they belong ([Script groups](#script-groups)) |
A group's membership **includes every group nested under it**, so running,
scheduling or scoping a role on `Sites` reaches `Sites › Office › Web` too.
@@ -2315,6 +2371,41 @@ Windows PowerShell 5.1 and Bash, the `EXECUTER_TRIGGER_KIND`, `_USER`,
`_SESSION_ID`, `_OCCURRED_UTC` and `_SCHEDULE_ID` environment variables. `Kind`
is `enrollment`, `agent-ready`, `logon` or `device-cli`.
### Script groups
A script decides whether its device belongs in a group, on the device, and the
console follows: every script has the built-ins below (no credentials: the agent
carries the answer with the job's final state), the device joins or leaves the
named group when the job ends, and the group is created (top level, kind Script)
the first time a device joins it. Each run decides again, so a scheduled script
keeps the group current.
```powershell
# Member when the value is $true, above 0, a non-empty collection, or text other than false/0/no/off.
Get-Package -Name 'Java*' -ErrorAction SilentlyContinue | Set-ExecuteRGroupMembership 'Has Java'
Set-ExecuteRGroupMembership -Name 'Low Disk' -Value ((Get-PSDrive C).Free -lt 10GB)
Add-ExecuteRGroupMembership 'Pilot Ring'
Remove-ExecuteRGroupMembership 'Pilot Ring'
```
```bash
executer_group "Has Java" "$(pgrep -c java)" # true/false, a number (above 0) or text; default true
```
- The job's output shows each answer as a line (`Script group “Has Java”: this
device is a member.`); the built-ins' own marker lines never reach the log.
- Names are matched without regard to case; the last answer per group in a job
wins; a job reports on at most 25 groups.
- Only script groups change. A name that belongs to a static, dynamic or folder
group is ignored (logged on the server), so a device can never put itself into
a group an operator curates; a device only ever changes its own membership.
- Script groups can be renamed, moved into folders, targeted, scheduled and
used in role scopes like any group; their members cannot be listed by hand.
Saving one as dynamic or a folder drops its reported devices. Not being a
member of a group that does not exist yet creates nothing.
- Joins, leaves and the group's creation are audited (actor `script:<name>`)
and show in the activity feed.
### At Logon
The agent watches interactive sign-ins and reports each one with the user
@@ -2773,6 +2864,48 @@ cookies and authorization headers. A structured property with one of those names
(`{Password}`, `{Jwt}`, … see `Redaction.NeverLog`) is masked as `[redacted]`
before any sink sees it, live views included.
### Log line format
Every text line any ExecuteR process writes (server, agent, watchdog, MSI and
removal runners, screen host) has one shape:
```text
[2026-11-16T17:53:40.653Z] - [LeafRouter] - [INFO] - The site's leaf answers again; moving back to it from the hub leaf=wss://172.18.16.104:9001
[2026-11-16T17:53:40.687Z] - [EventBus] - [WARN] - The site's leaf could not be reached; the bus goes through the server meanwhile reason="TLS: certificate expired"
[2026-11-16T17:54:40.701Z] - [EventBus] - [WARN] - The site's leaf could not be reached; the bus goes through the server meanwhile reason="TLS: certificate expired" repeated=37 window=60s
```
- **Time**: UTC, ISO 8601, milliseconds, `Z`.
- **Category**: a short component name: the logging type without its namespace
or generic arguments (`Agent.Screen.ScreenSessions` → `ScreenSessions`, a
nested `Outer+Inner` → `Outer.Inner`); `Agent` or `Server` for a line with no
type; `Watchdog`, `MsiRunner`, `RemovalRunner` for the watchdog's;
`ScreenHost` (or a dependency's crate, `ironrdp_server`) for the screen host's.
- **Level**: `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`.
- **Message**: rendered with strings bare, then every property the message did
not use as ` key=value` (correlation fields such as `CorrelationId`,
`ClientId`, `JobId` included; `SourceContext`, `MachineName`, `Application`,
`EventId` and the framework's `RequestId`/`ConnectionId`/`ActionId` left out).
A value with whitespace, `=` or `"` is double-quoted with `\"` escaped; a
missing value is `null`. An exception follows on the next lines.
`LOG_JSON=1` writes compact JSON instead, unchanged. The live views carry the
same message text. Log files from earlier versions
(`[2026-11-06 12:00:00.000 INF] Source: message`, the watchdog's
`2026-11-06 12:00:00.000Z [INF] message`) are still read by the watchdog's live
view (`LogLineParser`).
**Repeats are bounded.** A warning, error or fatal is the same as another when
its level, category (full SourceContext) and message template match. The first
is written at once; the same one again within 60 s is only counted, and when the
window ends with any counted, one line is written: the last of them with
`repeated=N window=60s`. While it keeps repeating that summary comes once a
minute; a minute without it forgets it, so the next one is written at once. At
most 1,000 distinct events are tracked (the oldest goes first, with its count
written), and stopping the process writes every count still open. Information
and below are never held back. The screen host does the same for its own
warnings and errors.
### Live logs and log files in the console
Every process keeps its last 2,000 log lines in memory (a Serilog sink feeding a
@@ -59,7 +59,7 @@ public static class RemovalHost
DataDirectory = Path.GetFullPath(data),
SelfPath = null,
};
var log = new WatchdogLog(runnerDirectory, console: false, name: RemovalRunner.LogFileName);
var log = new WatchdogLog(runnerDirectory, console: false, name: RemovalRunner.LogFileName, category: "RemovalRunner");
var agentPath = Path.Combine(options.InstallDirectory, options.AgentExecutable);
IAgentService agent;
+1 -1
View File
@@ -192,7 +192,7 @@ public static class WatchdogCli
{
var (options, _) = ParseOptions(args);
options = options with { SelfPath = null };
var log = new WatchdogLog(options.LogDirectory, console: false, name: "ExecuteR-Watchdog-msi");
var log = new WatchdogLog(options.LogDirectory, console: false, name: "ExecuteR-Watchdog-msi", category: "MsiRunner");
var agent = new WindowsAgentService(Branding.AgentServiceName, Path.Combine(options.InstallDirectory, options.AgentExecutable), log);
var watchdog = new WindowsAgentService(Branding.WatchdogServiceName,
Path.Combine(options.InstallDirectory, Branding.WatchdogExecutableName), log);
+19 -6
View File
@@ -6,22 +6,31 @@ namespace Agent.Watchdog;
/// The watchdog's own log: one small rolling file in the agent's log folder
/// (<c>ExecuteR-Watchdog.log</c>, rolled at 1 MB, three files kept), the
/// console in the foreground, and the lines of the current upgrade run kept in
/// memory so a failure's outcome can carry them.
/// memory so a failure's outcome can carry them. Lines are ExecuteR's one log
/// format (as <c>Shared.Infrastructure.Logging.LogLineFormatter</c> writes it,
/// without Serilog, which the watchdog does not carry):
/// <c>[2026-11-16T17:53:40.653Z] - [Watchdog] - [INFO] - message</c>.
/// </summary>
public sealed class WatchdogLog
{
public const long RollBytes = 1024 * 1024;
public const int KeptFiles = 3;
/// <summary>The category of the watchdog's own lines.</summary>
public const string DefaultCategory = "Watchdog";
private readonly Lock gate = new();
private readonly string? path;
private readonly bool console;
private readonly string category;
private readonly List<string> run = [];
private bool fileBroken;
public WatchdogLog(string? directory, bool console, string? name = null)
/// <param name="category">The component each line names (<c>Watchdog</c>, <c>MsiRunner</c>, <c>RemovalRunner</c>).</param>
public WatchdogLog(string? directory, bool console, string? name = null, string category = DefaultCategory)
{
this.console = console;
this.category = category;
if (!string.IsNullOrWhiteSpace(directory))
{
name ??= Path.GetFileNameWithoutExtension(Environment.ProcessPath) is { Length: > 0 } exe
@@ -35,11 +44,11 @@ public sealed class WatchdogLog
/// <summary>Every line written, for tests and the foreground.</summary>
public event Action<string>? Written;
public void Info(string message) => Write("INF", message);
public void Info(string message) => Write("INFO", message);
public void Warn(string message, Exception? exception = null) => Write("WRN", With(message, exception));
public void Warn(string message, Exception? exception = null) => Write("WARN", With(message, exception));
public void Error(string message, Exception? exception = null) => Write("ERR", With(message, exception));
public void Error(string message, Exception? exception = null) => Write("ERROR", With(message, exception));
/// <summary>Starts collecting the lines of an upgrade run.</summary>
public void BeginRun()
@@ -59,12 +68,16 @@ public sealed class WatchdogLog
}
}
/// <summary>One line: <c>[2026-11-16T17:53:40.653Z] - [Watchdog] - [INFO] - message</c>.</summary>
public static string Format(DateTimeOffset time, string category, string level, string message)
=> $"[{time.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture)}] - [{category}] - [{level}] - {message}";
private static string With(string message, Exception? exception)
=> exception is null ? message : $"{message}: {exception.GetBaseException().Message}";
private void Write(string level, string message)
{
var line = $"{DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture)} [{level}] {message}";
var line = Format(DateTimeOffset.UtcNow, category, level, message);
lock (gate)
{
run.Add(line);
+31 -3
View File
@@ -94,7 +94,7 @@ public static class AgentCli
}
case "status":
return Lifecycle.Status();
return Status();
// Cross-platform enrollment configuration (registry on Windows,
// /etc/executer/agent.json elsewhere) — what the MSI does via
@@ -151,12 +151,20 @@ public static class AgentCli
public static int Remove() => ServiceLifecycle.Remove();
public static int Start() => ServiceLifecycle.Start();
public static int Stop() => ServiceLifecycle.Stop();
public static int Status() => ServiceLifecycle.Status();
public static (bool Installed, string State, string? StartType) Query() => ServiceLifecycle.Query();
public static string ServiceName => Branding.AgentServiceName;
/// <summary>Nothing after the human-readable lines on Windows.</summary>
public static int Status() => 0;
#else
public static int Install() => UnixServiceLifecycle.Install();
public static int Remove() => UnixServiceLifecycle.Remove();
public static int Start() => UnixServiceLifecycle.Start();
public static int Stop() => UnixServiceLifecycle.Stop();
public static (bool Installed, string State, string? StartType) Query() => UnixServiceLifecycle.Query();
public static string ServiceName => OperatingSystem.IsMacOS() ? Branding.AgentLaunchdLabel : Branding.AgentSystemdUnit;
/// <summary>systemctl status / launchctl print after the human-readable lines.</summary>
public static int Status() => UnixServiceLifecycle.Status();
#endif
}
@@ -187,6 +195,26 @@ public static class AgentCli
return exitCode;
}
/// <summary>
/// One JSON line first (service, state, version, server, credential: what the
/// install scripts read to decide between leave alone, repair and re-enroll),
/// the human-readable lines after it. Always 0: the report is the answer.
/// </summary>
private static int Status()
{
var (installed, state, startType) = Lifecycle.Query();
var report = AgentHealth.ReadLocal();
Console.WriteLine(AgentHealth.Json(Lifecycle.ServiceName, installed, state, startType, report));
Console.WriteLine($"Service '{Branding.AgentServiceDisplayName}': {state}{(startType is null ? "" : $" ({startType})")}");
foreach (var line in AgentHealth.Describe(report))
{
Console.WriteLine(line);
}
Lifecycle.Status();
return 0;
}
private static int Configure(string[] args)
{
string? url = null;
@@ -274,7 +302,7 @@ public static class AgentCli
Console.WriteLine(" start Start the installed service");
Console.WriteLine(" stop Stop the service (the watchdog never undoes a stop)");
Console.WriteLine(" initialize install + start (agent and watchdog)");
Console.WriteLine(" status Show service and enrollment state");
Console.WriteLine(" status Show service, version, server and enrollment state (JSON line first)");
Console.WriteLine(" version Print the build version");
Console.WriteLine(" run <name|id> [-p Name=Value]... [--wait] [--timeout <s>]");
Console.WriteLine(" Start an On Demand script (run --list shows them, run --help for more)");
+156
View File
@@ -0,0 +1,156 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using Agent.Configuration;
using Agent.Enrollment;
using Agent.Identity;
using Agent.Platform;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Infrastructure.Constants;
using Shared.Infrastructure.Versioning;
namespace Agent.Commands;
/// <summary>
/// What <c>status</c> reports beyond the service state: the version, the server the
/// agent is pointed at and whether its enrollment credential is usable. The install
/// scripts read it to choose between leaving a device alone, repairing it and
/// re-enrolling it with their bootstrap token. Never the token itself.
/// </summary>
public static class AgentHealth
{
/// <summary>The credential loads and belongs to this hardware (an expired one renews itself).</summary>
public const string CredentialValid = "valid";
/// <summary>No credential file: never enrolled, or purged.</summary>
public const string CredentialMissing = "missing";
/// <summary>A credential file that does not decrypt or parse.</summary>
public const string CredentialUnreadable = "unreadable";
/// <summary>A credential of another client id: the hardware changed; the agent re-enrolls as a new device.</summary>
public const string CredentialOtherDevice = "other-device";
public sealed record Report(
string Version,
string? ServerUrl,
string Credential,
string? EnrollmentId,
DateTimeOffset? CredentialExpiresUtc,
bool BootstrapTokenPending);
/// <summary>
/// The report from configuration (Group Policy first, as the agent reads it), the
/// credential store and the client id this hardware computes (null when it cannot
/// be read: the credential is then judged without it).
/// </summary>
public static Report Read(
AgentConfiguration configuration, ICredentialStore credentials, bool credentialFileExists, Func<string?> clientId, string version)
{
string credential;
AgentCredentials? stored = null;
if (!credentialFileExists)
{
credential = CredentialMissing;
}
else if ((stored = credentials.Load()) is null)
{
credential = CredentialUnreadable;
}
else if (clientId() is { } current && !string.Equals(current, stored.ClientId, StringComparison.Ordinal))
{
credential = CredentialOtherDevice;
}
else
{
credential = CredentialValid;
}
return new Report(
version,
string.IsNullOrWhiteSpace(configuration.ServerUrlText.Value) ? null : configuration.ServerUrlText.Value.Trim(),
credential,
stored?.EnrollmentId.ToString("D"),
stored?.ExpiresUtc,
configuration.HasBootstrapToken);
}
/// <summary>The report of this machine's installed agent.</summary>
public static Report ReadLocal()
{
var registry = PlatformServices.CreateRegistryStore();
var configuration = new AgentConfigurationLoader(registry, allowEnvironment: false).Load();
var store = new CredentialStore(NullLogger<CredentialStore>.Instance);
var file = Path.Combine(Branding.AgentProgramDataDirectory, Branding.CredentialFileName);
return Read(configuration, store, File.Exists(file), LocalClientId, BuildVersion.Resolve(typeof(AgentHealth).Assembly));
}
private static string? LocalClientId()
{
try
{
return ClientIdentityFactory.ComputeClientId(PlatformServices.CreateIdentitySource().Read());
}
catch (Exception)
{
// No hardware identity here (WinPE without WMI): judge the credential on its own.
return null;
}
}
/// <summary>
/// The machine-readable line <c>status</c> prints first: one JSON object, URLs
/// unescaped so a shell script can read fields with sed.
/// </summary>
public static string Json(string service, bool installed, string state, string? startType, Report report)
{
using var buffer = new MemoryStream();
using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }))
{
writer.WriteStartObject();
writer.WriteString("service", service);
writer.WriteBoolean("installed", installed);
writer.WriteString("state", state);
if (startType is not null)
{
writer.WriteString("startType", startType);
}
writer.WriteString("version", report.Version);
writer.WriteString("serverUrl", report.ServerUrl);
writer.WriteString("credential", report.Credential);
writer.WriteString("enrollmentId", report.EnrollmentId);
if (report.CredentialExpiresUtc is { } expires)
{
writer.WriteString("credentialExpiresUtc", expires.ToUniversalTime().ToString("O"));
}
else
{
writer.WriteNull("credentialExpiresUtc");
}
writer.WriteBoolean("bootstrapTokenPending", report.BootstrapTokenPending);
writer.WriteEndObject();
}
return System.Text.Encoding.UTF8.GetString(buffer.ToArray());
}
/// <summary>The human-readable lines after the JSON one.</summary>
public static IEnumerable<string> Describe(Report report)
{
yield return $"Version: {report.Version}";
yield return $"Server: {report.ServerUrl ?? "(not configured)"}";
yield return report.Credential switch
{
CredentialValid => $"Enrollment: {report.EnrollmentId ?? "enrolled"}",
CredentialMissing => "Enrollment: none",
CredentialUnreadable => "Enrollment: credential unreadable",
CredentialOtherDevice => "Enrollment: credential of another device",
_ => $"Enrollment: {report.Credential}",
};
if (report.BootstrapTokenPending)
{
yield return "Bootstrap token: present (enrollment pending)";
}
}
}
+11 -26
View File
@@ -1,6 +1,4 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using Shared.Contracts.Api;
using Shared.Infrastructure.Logging;
@@ -12,7 +10,7 @@ namespace Agent.Logs;
/// got shorter, or a different file, was rolled: it is read from its start. Only whole
/// lines are taken; a line still being written waits for the next poll.
/// </summary>
public sealed partial class LogFileFollower(Func<string?> locate)
public sealed class LogFileFollower(Func<string?> locate)
{
/// <summary>How much of the end of the file the first poll reads.</summary>
public const int Backlog = 64 * 1024;
@@ -96,33 +94,20 @@ public sealed partial class LogFileFollower(Func<string?> locate)
}
}
/// <summary><c>2026-11-06 12:00:00.000Z [INF] message</c>, as <c>WatchdogLog</c> writes it.</summary>
/// <summary>
/// <c>[2026-11-06T12:00:00.000Z] - [Watchdog] - [INFO] - message</c>, as <c>WatchdogLog</c>
/// writes it, or a line from before that format (see <see cref="LogLineParser"/>).
/// Anything else (an exception's stack) is a line of its own, as information.
/// </summary>
private void Add(string line)
{
var match = LinePattern().Match(line);
if (!match.Success)
if (LogLineParser.TryParse(line, out var parsed))
{
Live.Append(parsed.TimestampUtc, parsed.Level, parsed.Category, parsed.Message);
}
else
{
Live.Append(DateTimeOffset.UtcNow, LogLevels.Information, null, line);
return;
}
var time = DateTimeOffset.TryParseExact(
match.Groups["time"].Value, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var parsed)
? parsed
: DateTimeOffset.UtcNow;
var level = match.Groups["level"].Value switch
{
"VRB" => LogLevels.Verbose,
"DBG" => LogLevels.Debug,
"WRN" => LogLevels.Warning,
"ERR" => LogLevels.Error,
"FTL" => LogLevels.Fatal,
_ => LogLevels.Information,
};
Live.Append(time, level, null, match.Groups["message"].Value);
}
[GeneratedRegex(@"^(?<time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})Z \[(?<level>[A-Z]{3})\] (?<message>.*)$")]
private static partial Regex LinePattern();
}
+194
View File
@@ -0,0 +1,194 @@
#if WINDOWS_AGENT
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using Agent.Sessions;
namespace Agent.Platform;
/// <summary>
/// The signed-in user's primary token (<c>WTSQueryUserToken</c>, which only LocalSystem may
/// call), and what a process started with it gets: the user's own environment block and
/// profile folder, as Explorer would give it.
/// </summary>
internal sealed partial class WindowsUserToken : IDisposable
{
private const int ErrorPrivilegeNotHeld = 1314;
private WindowsUserToken(IntPtr handle, string name)
{
Handle = handle;
Name = name;
}
public IntPtr Handle { get; private set; }
/// <summary>DOMAIN\user, as the session reports it.</summary>
public string Name { get; }
/// <summary>The user's SID (for granting it a job folder).</summary>
public SecurityIdentifier? Sid
{
get
{
using var identity = new WindowsIdentity(Handle);
return identity.User;
}
}
public static WindowsUserToken Open(SignedInUser user)
{
if (user.WindowsSession is not { } session)
{
throw new InvalidOperationException($"{user.Name} has no session to run in.");
}
if (!WTSQueryUserToken((uint)session, out var token))
{
var error = Marshal.GetLastWin32Error();
throw new Win32Exception(error, error == ErrorPrivilegeNotHeld
? "Only an agent running as LocalSystem can start processes as the signed-in user."
: $"The token of {user.Name} could not be obtained.");
}
return new WindowsUserToken(token, user.Name);
}
/// <summary>The user's profile folder (C:\Users\name), or null when it cannot be read.</summary>
public string? ProfileDirectory()
{
uint size = 0;
GetUserProfileDirectoryW(Handle, null, ref size);
if (size == 0)
{
return null;
}
var buffer = new StringBuilder((int)size);
return GetUserProfileDirectoryW(Handle, buffer, ref size) ? buffer.ToString() : null;
}
/// <summary>
/// The user's environment (not the agent's) with <paramref name="overrides"/> applied and
/// <paramref name="modulePath"/> (the agent's bundled modules) added to PSModulePath, as a
/// CreateProcess block (CREATE_UNICODE_ENVIRONMENT). Free it with <see cref="Marshal.FreeHGlobal"/>.
/// </summary>
public IntPtr EnvironmentBlock(IReadOnlyDictionary<string, string>? overrides, string? modulePath = null)
{
var variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (CreateEnvironmentBlock(out var block, Handle, false))
{
try
{
foreach (var (name, value) in ReadBlock(block))
{
variables[name] = value;
}
}
finally
{
DestroyEnvironmentBlock(block);
}
}
foreach (var (name, value) in overrides ?? new Dictionary<string, string>())
{
// Keep the caller's spelling (bash under Git Bash is case-sensitive).
variables.Remove(name);
variables[name] = value;
}
if (modulePath is not null)
{
variables["PSModulePath"] = AppendPath(variables.GetValueOrDefault("PSModulePath"), modulePath);
}
return Marshal.StringToHGlobalUni(BuildBlock(variables));
}
/// <summary><paramref name="list"/> (a ;-separated path list) with <paramref name="path"/> at the end, once.</summary>
internal static string AppendPath(string? list, string path)
{
var parts = (list ?? string.Empty).Split(';', StringSplitOptions.RemoveEmptyEntries).ToList();
if (!parts.Contains(path, StringComparer.OrdinalIgnoreCase))
{
parts.Add(path);
}
return string.Join(';', parts);
}
/// <summary>The name=value pairs of a native environment block (UTF-16, double-NUL terminated).</summary>
internal static IEnumerable<KeyValuePair<string, string>> ReadBlock(IntPtr block)
{
var entries = new List<KeyValuePair<string, string>>();
var cursor = block;
while (true)
{
var entry = Marshal.PtrToStringUni(cursor);
if (string.IsNullOrEmpty(entry))
{
break;
}
// Names may start with '=' (per-drive folders): the separator is the next '='.
var equals = entry.IndexOf('=', 1);
if (equals > 0)
{
entries.Add(new(entry[..equals], entry[(equals + 1)..]));
}
cursor += (entry.Length + 1) * sizeof(char);
}
return entries;
}
/// <summary>A block CreateProcess accepts: sorted by name (case-insensitive), each "name=value\0", then a final "\0".</summary>
internal static string BuildBlock(IEnumerable<KeyValuePair<string, string>> variables)
{
var builder = new StringBuilder();
foreach (var (name, value) in variables.OrderBy(v => v.Key, StringComparer.OrdinalIgnoreCase))
{
builder.Append(name).Append('=').Append(value).Append('\0');
}
if (builder.Length == 0)
{
builder.Append('\0');
}
return builder.Append('\0').ToString();
}
public void Dispose()
{
if (Handle != IntPtr.Zero)
{
CloseHandle(Handle);
Handle = IntPtr.Zero;
}
}
[LibraryImport("wtsapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool WTSQueryUserToken(uint sessionId, out IntPtr token);
[LibraryImport("userenv.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool CreateEnvironmentBlock(out IntPtr environment, IntPtr token, [MarshalAs(UnmanagedType.Bool)] bool inherit);
[LibraryImport("userenv.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool DestroyEnvironmentBlock(IntPtr environment);
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetUserProfileDirectoryW(IntPtr token, StringBuilder? profileDirectory, ref uint size);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool CloseHandle(IntPtr handle);
}
#endif
+132 -18
View File
@@ -63,7 +63,8 @@ public static class ExternalScriptRunner
JobFolder? folder = null,
string scriptName = "script",
bool setWorkingDirectory = false,
JobTrigger? trigger = null)
JobTrigger? trigger = null,
Agent.Sessions.SignedInUser? runAs = null)
{
// Child processes inherit PSModulePath, so 5.1 also sees the bundled
// gallery modules (PSResourceGet supports Windows PowerShell 5.1+).
@@ -71,13 +72,22 @@ public static class ExternalScriptRunner
var owned = folder is null;
folder ??= JobFolder.Create(JobRoot.DefaultPath(), Guid.NewGuid());
var run = new ProcessRun(folder, setWorkingDirectory, runAs);
try
{
return engine == ScriptEngine.WindowsPowerShell
? await RunWindowsPowerShellAsync(
content, prelude, parameters, secrets, secretsVariableName, files, filesRoot, folder, scriptName, setWorkingDirectory, trigger, onRecord, cancellationToken)
: await RunBashAsync(
content, prelude, parameters, secrets, files, filesRoot, folder, scriptName, setWorkingDirectory, trigger, onRecord, cancellationToken);
return engine switch
{
ScriptEngine.Bash => await RunBashAsync(
content, prelude, parameters, secrets, files, filesRoot, folder, scriptName, trigger, run, onRecord, cancellationToken),
// PowerShell 7 as the signed-in user: the agent's own engine in a process of theirs
// (the built-in host), with the same wrapper as 5.1.
ScriptEngine.PowerShell => await RunWindowsPowerShellAsync(
content, prelude, parameters, secrets, secretsVariableName, files, filesRoot, folder, scriptName, trigger, run, onRecord, cancellationToken,
AgentLocation.ExecutablePath, [Agent.Shell.WindowsShellResolver.HostVerb]),
_ => await RunWindowsPowerShellAsync(
content, prelude, parameters, secrets, secretsVariableName, files, filesRoot, folder, scriptName, trigger, run, onRecord, cancellationToken,
WindowsPowerShellPath(runAs is not null), []),
};
}
finally
{
@@ -98,10 +108,12 @@ public static class ExternalScriptRunner
DirectoryInfo? filesRoot,
JobFolder folder,
string scriptName,
bool setWorkingDirectory,
JobTrigger? trigger,
ProcessRun run,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
CancellationToken cancellationToken,
string interpreter,
IReadOnlyList<string> interpreterArguments)
{
var scriptPath = folder.WriteScript(scriptName, ScriptEngine.WindowsPowerShell, content);
@@ -162,14 +174,19 @@ public static class ExternalScriptRunner
var wrapperPath = folder.WriteHelper(WrapperFileName, wrapper.ToString());
return await RunProcessAsync(
"powershell.exe",
$"-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{wrapperPath}\"",
interpreter,
[.. interpreterArguments, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", wrapperPath],
WindowsPowerShellEnvironment(folder, trigger),
setWorkingDirectory ? folder.Path : null,
run,
onRecord,
cancellationToken);
}
/// <summary>Windows PowerShell: by name for the agent's own processes; by full path for a user's (CreateProcessAsUser does not search PATH).</summary>
private static string WindowsPowerShellPath(bool fullPath) => fullPath
? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "WindowsPowerShell", "v1.0", "powershell.exe")
: "powershell.exe";
private static async Task<ExternalResult> RunBashAsync(
string content,
string? prelude,
@@ -179,8 +196,8 @@ public static class ExternalScriptRunner
DirectoryInfo? filesRoot,
JobFolder folder,
string scriptName,
bool setWorkingDirectory,
JobTrigger? trigger,
ProcessRun run,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
{
@@ -252,8 +269,17 @@ public static class ExternalScriptRunner
}
}
return await RunProcessAsync(
bash, $"\"{BashPath(scriptPath)}\"", environment, setWorkingDirectory ? folder.Path : null, onRecord, cancellationToken);
return await RunProcessAsync(bash, [BashPath(scriptPath)], environment, run, onRecord, cancellationToken);
}
/// <summary>
/// Where and as whom a script's process runs: the job folder (its working directory with
/// Set Working Directory) and, for Run As Signed-In User, the user.
/// </summary>
internal sealed record ProcessRun(JobFolder Folder, bool SetWorkingDirectory, Agent.Sessions.SignedInUser? RunAs)
{
/// <summary>The job folder with Set Working Directory; otherwise null (the agent's own folder, or the user's home).</summary>
public string? WorkingDirectory => SetWorkingDirectory ? Folder.Path : null;
}
/// <summary>The job folder (EXECUTER_JOB_DIR), the agent (EXECUTER_AGENT_*) and what started the job (EXECUTER_TRIGGER_*).</summary>
@@ -276,20 +302,36 @@ public static class ExternalScriptRunner
private static async Task<ExternalResult> RunProcessAsync(
string fileName,
string arguments,
IReadOnlyList<string> arguments,
IReadOnlyDictionary<string, string>? environment,
string? workingDirectory,
ProcessRun run,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
{
if (run.RunAs is { } user)
{
// The user reads (and may write) their job folder; nothing else of the agent's.
UserJobAccess.Grant(run.Folder.Path, user);
#if WINDOWS_AGENT
return await RunAsWindowsUserAsync(fileName, arguments, environment, run, user, onRecord, cancellationToken);
#else
// su (root needs no password) keeps this environment; the user's shell execs the
// interpreter, from their home unless Set Working Directory starts it in the job folder.
var command = run.SetWorkingDirectory ? "exec \"$0\" \"$@\"" : "cd 2>/dev/null; exec \"$0\" \"$@\"";
var su = new[] { "/bin/su", "/usr/bin/su" }.FirstOrDefault(File.Exists)
?? throw new InvalidOperationException("su is not available on this device.");
arguments = [user.Name, "-c", command, fileName, .. arguments];
fileName = su;
#endif
}
using var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
// Empty inherits the agent's current directory (unchanged default).
WorkingDirectory = workingDirectory ?? string.Empty,
WorkingDirectory = run.WorkingDirectory ?? string.Empty,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
@@ -297,6 +339,11 @@ public static class ExternalScriptRunner
StandardErrorEncoding = Encoding.UTF8,
},
};
foreach (var argument in arguments)
{
process.StartInfo.ArgumentList.Add(argument);
}
if (environment is not null)
{
foreach (var (key, value) in environment)
@@ -351,6 +398,73 @@ public static class ExternalScriptRunner
}
}
#if WINDOWS_AGENT
/// <summary>
/// The interpreter as the signed-in user: their token, environment (plus this run's variables and the
/// agent's bundled modules) and profile folder, headless (no window, hidden) in a kill-on-close job.
/// </summary>
private static async Task<ExternalResult> RunAsWindowsUserAsync(
string fileName,
IReadOnlyList<string> arguments,
IReadOnlyDictionary<string, string>? environment,
ProcessRun run,
Agent.Sessions.SignedInUser user,
Action<NormalizedOutputRecord> onRecord,
CancellationToken cancellationToken)
{
Agent.Screen.IScreenProcess process;
using (var token = Agent.Platform.WindowsUserToken.Open(user))
{
var block = token.EnvironmentBlock(environment, PowerShellRunspaceFactory.BundledModulesPath);
try
{
process = Agent.Screen.WindowsScreenProcessLauncher.Launch(
token.Handle, user.WindowsSession, fileName, arguments, block, run.WorkingDirectory ?? token.ProfileDirectory());
}
finally
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(block);
}
}
await using (process)
{
// Nothing is typed in: end of input at once.
await process.Input.DisposeAsync();
var output = PumpLinesAsync(process.Output, line => onRecord(new NormalizedOutputRecord(OutputStreamKind.Output, line.TrimEnd())));
var error = PumpLinesAsync(process.Error, line => onRecord(new NormalizedOutputRecord(OutputStreamKind.Error, line)));
try
{
var exitCode = await process.Exited.WaitAsync(cancellationToken);
await Task.WhenAll(output, error);
return new ExternalResult(exitCode, WasCancelled: false);
}
catch (OperationCanceledException)
{
// Disposing closes the job, which takes the whole tree.
process.Kill();
return new ExternalResult(-1, WasCancelled: true);
}
}
}
private static async Task PumpLinesAsync(Stream stream, Action<string> onLine)
{
using var reader = new StreamReader(stream, Encoding.UTF8);
try
{
while (await reader.ReadLineAsync() is { } line)
{
onLine(line);
}
}
catch (Exception exception) when (exception is IOException or ObjectDisposedException)
{
// The process went away.
}
}
#endif
private static string? ResolveBash()
{
if (!OperatingSystem.IsWindows())
+37 -7
View File
@@ -29,7 +29,8 @@ public sealed class PowerShellJobHandler(
Agent.LocalRun.JobObservers? observers = null,
JobStartClock? clock = null,
Agent.Restart.RestartCoordinator? restarts = null,
Func<bool>? allowRestart = null)
Func<bool>? allowRestart = null,
Agent.Sessions.ISignedInUserResolver? signedInUsers = null)
{
/// <summary>Most output lines a job that may restart keeps for sending again after the restart.</summary>
public const int MaxKeptOutputLines = 20_000;
@@ -54,6 +55,10 @@ public sealed class PowerShellJobHandler(
ScriptFileFetcher.FetchResult? fetch = null;
var tapId = command.Trigger?.RequestId;
// Script groups: the built-ins come before the script's own functions; their lines become the job's reports.
var prelude = ScriptGroupBuiltIns.Compose(command.Engine, command.Prelude);
var groupReports = new ScriptGroupReportCollector();
// A job that may restart the device keeps its output, so what has not reached the
// server when it restarts can be sent again (bounded; see RestartCoordinator).
var kept = command.RestartAfterRun != RestartAfterRun.Off ? new List<JobOutputPayload>() : null;
@@ -199,12 +204,34 @@ public sealed class PowerShellJobHandler(
}
}
// Run As Signed-In User: whose account, decided before anything runs. Nobody (or nobody
// clear) fails the job rather than running it as the agent's account.
Agent.Sessions.SignedInUser? runAs = null;
string? runAsFailure = null;
if (command.RunAsUser)
{
var lookup = (signedInUsers ?? Agent.Sessions.SignedInUsers.Default).Resolve();
runAs = lookup.User;
runAsFailure = runAs is null ? $"Not run as the signed-in user: {lookup.Reason}" : null;
if (runAs is not null)
{
logger.LogInformation("Job {JobId} runs as {User}", jobId, runAs.Name);
}
}
if (folderFailure is not null)
{
finalState = JobState.Failed;
exitCode = 1;
message = folderFailure;
}
else if (runAsFailure is not null)
{
finalState = JobState.Failed;
exitCode = 1;
message = runAsFailure;
await Task.WhenAll(pending);
}
else if (deliveryFailure is not null)
{
finalState = JobState.Failed;
@@ -222,9 +249,9 @@ public sealed class PowerShellJobHandler(
: $"Execution exceeded the {timeout.TotalSeconds:F0}s timeout while downloading files.";
await Task.WhenAll(pending);
}
else if (command.Engine != ScriptEngine.PowerShell)
else if (command.Engine != ScriptEngine.PowerShell || runAs is not null)
{
// Out-of-process engine: Windows PowerShell 5.1 or Bash.
// Out-of-process engine: Windows PowerShell 5.1 or Bash, or any engine as the signed-in user.
if (!ExternalScriptRunner.IsAvailable(command.Engine))
{
finalState = JobState.Failed;
@@ -239,7 +266,7 @@ public sealed class PowerShellJobHandler(
var external = await ExternalScriptRunner.RunAsync(
command.Engine,
command.Content,
command.Prelude,
prelude,
externalParameters,
command.Secrets,
string.IsNullOrWhiteSpace(command.SecretsVariableName) ? "Secrets" : command.SecretsVariableName,
@@ -258,7 +285,8 @@ public sealed class PowerShellJobHandler(
folder: folder,
scriptName: command.ScriptName,
setWorkingDirectory: command.SetWorkingDirectory,
trigger: command.Trigger);
trigger: command.Trigger,
runAs: runAs);
if (external.WasCancelled && cancellationToken.IsCancellationRequested)
{
@@ -298,7 +326,7 @@ public sealed class PowerShellJobHandler(
var result = await executionService.ExecuteAsync(
command.Content,
boundParameters,
command.Prelude,
prelude,
onRecord: record => pending.Add(PublishOutputAsync(record, Interlocked.Increment(ref sequence))),
onProgress: progress => pending.Add(PublishProgressAsync(progress)),
cancellationToken: timeoutCts.Token,
@@ -447,6 +475,7 @@ public sealed class PowerShellJobHandler(
async Task PublishOutputAsync(NormalizedOutputRecord record, long seq)
{
record = groupReports.Take(record);
observers?.Output(tapId, record.Stream, record.Text);
var line = new JobOutputPayload(jobId, publisher.ClientId, seq, record.Stream, DateTimeOffset.UtcNow, record.Text);
if (kept is not null)
@@ -511,7 +540,8 @@ public sealed class PowerShellJobHandler(
ErrorType: error?.Type, ErrorId: error?.Id, ErrorMessage: error?.Message,
Restart: plan?.State,
RestartDelaySeconds: plan is null ? null : (int)plan.Delay.TotalSeconds,
RestartMessage: plan?.Message);
RestartMessage: plan?.Message,
GroupMemberships: state is JobState.Running ? null : groupReports.Reports);
async Task PublishFinalAsync(JobStatePayload payload)
{
@@ -29,6 +29,10 @@ public static class PowerShellRunspaceFactory
/// both resolve them. Idempotent; a no-op for dev builds where the staged
/// directory does not exist.
/// </summary>
/// <summary>The agent's bundled Modules directory, or null when it has none (development builds).</summary>
public static string? BundledModulesPath =>
Directory.Exists(Path.Combine(AppContext.BaseDirectory, "Modules")) ? Path.Combine(AppContext.BaseDirectory, "Modules") : null;
public static void EnsureBundledModulesOnPath()
{
if (modulesPathEnsured)
+165
View File
@@ -0,0 +1,165 @@
using System.Text.Json;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
namespace Agent.PowerShell;
/// <summary>
/// The built-ins every script gets for script groups (<see cref="ScriptGroups"/>), and the
/// collector that takes their lines out of a job's output for the job's final state. The
/// built-ins only write a line: no credentials are involved, the agent carries the result.
/// </summary>
public static class ScriptGroupBuiltIns
{
/// <summary>PowerShell (7 and 5.1): Set-, Add- and Remove-ExecuteRGroupMembership.</summary>
public const string PowerShell = """
function Set-ExecuteRGroupMembership {
<#
.SYNOPSIS
Puts this device in an ExecuteR script group, or takes it out, from a result.
.DESCRIPTION
The device is a member when the value is $true, a number above 0, a non-empty
collection (pipe a command's results in), or text other than false/0/no/off.
The group is created the first time a device joins it. Each run decides again.
.EXAMPLE
Get-Package -Name 'Java*' -ErrorAction SilentlyContinue | Set-ExecuteRGroupMembership 'Has Java'
.EXAMPLE
Set-ExecuteRGroupMembership -Name 'Low Disk' -Value ((Get-PSDrive C).Free -lt 10GB)
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)][string] $Name,
[Parameter(Position = 1, ValueFromPipeline)] $Value
)
begin { $__items = [System.Collections.Generic.List[object]]::new() }
process { if ($MyInvocation.ExpectingInput) { $__items.Add($Value) } }
end {
if (-not $MyInvocation.ExpectingInput -and $PSBoundParameters.ContainsKey('Value')) {
if ($Value -is [System.Collections.IEnumerable] -and $Value -isnot [string]) { foreach ($__i in $Value) { $__items.Add($__i) } }
else { $__items.Add($Value) }
}
$__member = $false
if ($__items.Count -gt 1) { $__member = $true }
elseif ($__items.Count -eq 1) {
$__v = $__items[0]
if ($null -eq $__v) { $__member = $false }
elseif ($__v -is [bool]) { $__member = $__v }
elseif ($__v -is [byte] -or $__v -is [int16] -or $__v -is [int] -or $__v -is [long] -or $__v -is [double] -or $__v -is [decimal] -or $__v -is [single] -or $__v -is [uint32] -or $__v -is [uint64]) { $__member = $__v -gt 0 }
elseif ($__v -is [string]) { $__member = @('', 'false', '0', 'no', 'off') -notcontains $__v.Trim().ToLowerInvariant() }
else { $__member = $true }
}
Write-ExecuteRGroupMembership $Name $__member
}
}
function Add-ExecuteRGroupMembership {
<# .SYNOPSIS Puts this device in an ExecuteR script group (created if missing). #>
param([Parameter(Mandatory, Position = 0)][string] $Name)
Write-ExecuteRGroupMembership $Name $true
}
function Remove-ExecuteRGroupMembership {
<# .SYNOPSIS Takes this device out of an ExecuteR script group. #>
param([Parameter(Mandatory, Position = 0)][string] $Name)
Write-ExecuteRGroupMembership $Name $false
}
function Write-ExecuteRGroupMembership([string] $Name, [bool] $Member) {
$json = @{ group = $Name; member = $Member } | ConvertTo-Json -Compress
[Console]::Out.Flush()
Write-Host ('::executer-group::' + $json)
}
""";
/// <summary>Bash: executer_group NAME [VALUE] (VALUE: true/false, a number, or text; default true).</summary>
public const string Bash = """
executer_group() {
local name="$1" value="${2-true}" lower member=true
lower=$(printf '%s' "$value" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
case "$lower" in
''|false|0|no|off) member=false ;;
*) if printf '%s' "$lower" | grep -Eq '^-?[0-9]+$'; then [ "$lower" -gt 0 ] && member=true || member=false; fi ;;
esac
name=$(printf '%s' "$name" | sed 's/\\/\\\\/g; s/"/\\"/g')
printf '::executer-group::{"group":"%s","member":%s}\n' "$name" "$member"
}
""";
/// <summary>The prelude a job runs: the built-ins for its engine, then its own functions.</summary>
public static string Compose(ScriptEngine engine, string? prelude)
=> (engine == ScriptEngine.Bash ? Bash.Replace("\r\n", "\n") : PowerShell) + (prelude ?? string.Empty);
}
/// <summary>
/// Takes the built-ins' lines out of a job's output (any stream: in process they arrive as
/// information records, out of process as stdout) and keeps the last word per group.
/// </summary>
public sealed class ScriptGroupReportCollector
{
private readonly Lock gate = new();
private readonly List<GroupMembershipReport> reports = [];
/// <summary>What the job said, in order, the last per group (null when nothing).</summary>
public IReadOnlyList<GroupMembershipReport>? Reports
{
get
{
lock (gate)
{
return reports.Count == 0 ? null : [.. reports];
}
}
}
/// <summary>The record to publish: a report line becomes a readable one; anything else is unchanged.</summary>
public NormalizedOutputRecord Take(NormalizedOutputRecord record)
{
var text = record.Text?.TrimStart();
if (text is null || !text.StartsWith(ScriptGroups.Marker, StringComparison.Ordinal))
{
return record;
}
GroupMembershipReport? report = null;
try
{
using var json = JsonDocument.Parse(text[ScriptGroups.Marker.Length..]);
var root = json.RootElement;
if (root.TryGetProperty("group", out var group) && group.ValueKind == JsonValueKind.String
&& root.TryGetProperty("member", out var member) && member.ValueKind is JsonValueKind.True or JsonValueKind.False)
{
report = new GroupMembershipReport(group.GetString()!, member.GetBoolean());
}
}
catch (JsonException)
{
// Not ours after all: shown as written.
}
if (report is null)
{
return record;
}
if (ScriptGroups.Normalize(report.Group) is not { } name)
{
return new NormalizedOutputRecord(OutputStreamKind.Warning, $"Script group “{report.Group}” ignored: the name is empty, too long or has / or \\.");
}
lock (gate)
{
reports.RemoveAll(r => string.Equals(r.Group, name, StringComparison.OrdinalIgnoreCase));
if (reports.Count >= ScriptGroups.MaxReportsPerJob)
{
return new NormalizedOutputRecord(OutputStreamKind.Warning, $"Script group “{name}” ignored: a job reports on at most {ScriptGroups.MaxReportsPerJob} groups.");
}
reports.Add(report with { Group = name });
}
return new NormalizedOutputRecord(
OutputStreamKind.Information, report.Member ? $"Script group “{name}”: this device is a member." : $"Script group “{name}”: this device is not a member.");
}
}
+94
View File
@@ -0,0 +1,94 @@
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
#if WINDOWS_AGENT
using System.Security.AccessControl;
using System.Security.Principal;
#endif
using Agent.Sessions;
namespace Agent.PowerShell;
/// <summary>
/// Run As Signed-In User: hands one job folder to the user its script runs as, and nothing more.
/// Windows adds the user (Modify) to the folder and everything in it (the files carry their own
/// locked-down ACLs). Linux/macOS give the folder to the user and let others traverse (not list)
/// the job root, whose other folders stay root's own 0700.
/// </summary>
public static class UserJobAccess
{
public static void Grant(string folder, SignedInUser user)
{
#if WINDOWS_AGENT
using var token = Agent.Platform.WindowsUserToken.Open(user);
var sid = token.Sid ?? throw new InvalidOperationException($"The SID of {user.Name} could not be read.");
GrantWindows(new DirectoryInfo(folder), sid);
#else
if (OperatingSystem.IsWindows())
{
return;
}
var (uid, gid) = Ids(user.Name);
var root = Path.GetDirectoryName(Path.TrimEndingDirectorySeparator(folder));
if (!string.IsNullOrEmpty(root))
{
var mode = File.GetUnixFileMode(root);
File.SetUnixFileMode(root, mode | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute);
}
foreach (var path in Directory.EnumerateFileSystemEntries(folder, "*", SearchOption.AllDirectories).Prepend(folder))
{
if (lchown(path, uid, gid) != 0)
{
throw new InvalidOperationException($"{path} could not be given to {user.Name} (errno {Marshal.GetLastPInvokeError()}).");
}
}
#endif
}
#if WINDOWS_AGENT
private static void GrantWindows(DirectoryInfo folder, SecurityIdentifier sid)
{
var security = folder.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(
sid, FileSystemRights.Modify | FileSystemRights.Synchronize,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
folder.SetAccessControl(security);
foreach (var file in folder.EnumerateFiles())
{
var fileSecurity = file.GetAccessControl();
fileSecurity.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.Modify | FileSystemRights.Synchronize, AccessControlType.Allow));
file.SetAccessControl(fileSecurity);
}
foreach (var child in folder.EnumerateDirectories())
{
if ((child.Attributes & FileAttributes.ReparsePoint) == 0)
{
GrantWindows(child, sid);
}
}
}
#else
/// <summary>The user's uid and primary gid (<c>id -u</c>, <c>id -g</c>).</summary>
private static (uint Uid, uint Gid) Ids(string user)
=> (uint.Parse(Id("-u", user), NumberStyles.None, CultureInfo.InvariantCulture),
uint.Parse(Id("-g", user), NumberStyles.None, CultureInfo.InvariantCulture));
private static string Id(string flag, string user)
{
var start = new ProcessStartInfo("id") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
start.ArgumentList.Add(flag);
start.ArgumentList.Add(user);
using var process = Process.Start(start) ?? throw new InvalidOperationException("id could not be started.");
var output = process.StandardOutput.ReadToEnd().Trim();
process.WaitForExit(5000);
return process.ExitCode == 0 && output.Length > 0 ? output : throw new InvalidOperationException($"{user} is not a user on this device.");
}
[DllImport("libc", SetLastError = true)]
private static extern int lchown([MarshalAs(UnmanagedType.LPUTF8Str)] string path, uint owner, uint group);
#endif
}
+67
View File
@@ -0,0 +1,67 @@
using Microsoft.Extensions.Logging;
using Shared.Contracts.Api;
using Shared.Infrastructure.Logging;
namespace Agent.Screen;
/// <summary>
/// The screen host's own log lines (its stderr, <c>@event</c> lines aside) into the agent's
/// log. The host writes ExecuteR's one format; its time, category and level prefix is taken
/// apart here and the rest (message and <c>key=value</c> fields) logged again at the host's
/// level under the host's category, so the agent's file shows each host line once, in the
/// same format, without a second timestamp. The host bounds its own repeats; a line that
/// is not in a known format is logged whole, as information.
/// </summary>
public static class ScreenHostLog
{
/// <summary>The category of the host's own lines (and of any line that names none).</summary>
public const string Category = "ScreenHost";
/// <summary>How much of one line is kept.</summary>
public const int MaxLineChars = 2000;
/// <summary>Logs one stderr line of the host.</summary>
/// <param name="loggers">Where a category's logger comes from; without one, everything goes to <paramref name="fallback"/>.</param>
public static void Relay(string line, ILoggerFactory? loggers, ILogger fallback)
{
if (line.Length > MaxLineChars)
{
line = line[..MaxLineChars];
}
var (category, level, message) = LogLineParser.TryParse(line, out var parsed)
? (CategoryOf(parsed.Category), ToLogLevel(parsed.Level), parsed.Message)
: (Category, LogLevel.Information, line);
var logger = loggers?.CreateLogger(category) ?? fallback;
logger.Log(level, "{HostLine}", message);
}
/// <summary>A short, safe category for a host line: <c>ScreenHost</c>, or the crate it names (<c>ironrdp_server</c>).</summary>
public static string CategoryOf(string? category)
{
if (string.IsNullOrWhiteSpace(category))
{
return Category;
}
// An older host writes the tracing target (executer_screen::video).
var crate = category.Split("::", 2)[0];
if (crate.StartsWith("executer_screen", StringComparison.Ordinal) || crate.Length > 64
|| !crate.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-' or '.'))
{
return Category;
}
return crate;
}
public static LogLevel ToLogLevel(string level) => level switch
{
LogLevels.Verbose => LogLevel.Trace,
LogLevels.Debug => LogLevel.Debug,
LogLevels.Warning => LogLevel.Warning,
LogLevels.Error => LogLevel.Error,
LogLevels.Fatal => LogLevel.Critical,
_ => LogLevel.Information,
};
}
+7 -2
View File
@@ -26,6 +26,9 @@ public sealed class ScreenSessions : IAsyncDisposable
private readonly Func<bool> enabled;
private readonly Func<string?> logLevel;
private readonly ILogger logger;
/// <summary>Loggers for the screen host's own lines, by its category (<see cref="ScreenHostLog"/>).</summary>
private readonly ILoggerFactory? hostLoggers;
private readonly ConcurrentDictionary<Guid, ScreenStream> streams = new();
private readonly ConcurrentDictionary<Guid, (string Consent, DateTimeOffset Expires)> granted = new();
private readonly ConcurrentDictionary<Guid, ScreenBannerEntry> viewing = new();
@@ -45,10 +48,12 @@ public sealed class ScreenSessions : IAsyncDisposable
Func<string?>? logLevel = null,
TimeSpan? heartbeat = null,
TimeSpan? idle = null,
Agent.Sessions.SessionWatcher? watcher = null)
Agent.Sessions.SessionWatcher? watcher = null,
ILoggerFactory? hostLoggers = null)
{
this.host = host;
this.watcher = watcher;
this.hostLoggers = hostLoggers;
this.enabled = enabled;
this.logger = logger;
this.logLevel = logLevel ?? (() => null);
@@ -192,7 +197,7 @@ public sealed class ScreenSessions : IAsyncDisposable
return new ScreenOpenReply(ScreenOpenStatuses.Failed, "The console session changed; try again.");
}
var stream = new ScreenStream(request.SessionId, request.StreamId, process, publish, logger, request.ViewOnly, heartbeat, idle, cipher: cipher);
var stream = new ScreenStream(request.SessionId, request.StreamId, process, publish, logger, request.ViewOnly, heartbeat, idle, cipher: cipher, hostLoggers: hostLoggers);
streams[request.StreamId] = stream;
stream.Start();
_ = ForgetWhenDoneAsync(stream);
+7 -3
View File
@@ -9,7 +9,8 @@ namespace Agent.Screen;
/// (waiting while a window is unacknowledged, so a slow browser stalls the host's
/// writes instead of growing memory here), the server's bytes go to stdin (and are
/// acknowledged only once written), <c>@event</c> lines on stderr become state
/// frames and every other stderr line goes to the agent log. Ends when the host
/// frames and every other stderr line goes to the agent log (see
/// <see cref="ScreenHostLog"/>). Ends when the host
/// exits, the server ends the stream or goes silent, or <see cref="Stop"/> is
/// called; then the host is closed (stdin EOF), killed if it lingers, and
/// disposed.
@@ -21,6 +22,7 @@ public sealed class ScreenStream
private readonly IScreenProcess process;
private readonly ScreenStreamPump pump;
private readonly ILogger logger;
private readonly ILoggerFactory? hostLoggers;
private readonly TaskCompletionSource<string> stopped = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<ScreenHostEvent?> ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly CancellationTokenSource cancel = new();
@@ -38,13 +40,15 @@ public sealed class ScreenStream
TimeSpan? heartbeat = null,
TimeSpan? idle = null,
int windowBytes = ScreenStreamDefaults.WindowBytes,
StreamCipher? cipher = null)
StreamCipher? cipher = null,
ILoggerFactory? hostLoggers = null)
{
SessionId = sessionId;
StreamId = streamId;
ViewOnly = viewOnly;
this.process = process;
this.logger = logger;
this.hostLoggers = hostLoggers;
pump = new ScreenStreamPump(
publish,
windowBytes,
@@ -195,7 +199,7 @@ public sealed class ScreenStream
}
else if (line.Length > 0)
{
logger.LogInformation("Screen host: {Line}", line.Length <= 2000 ? line : line[..2000]);
ScreenHostLog.Relay(line, hostLoggers, logger);
}
}
}
+39 -22
View File
@@ -26,23 +26,16 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
public IScreenProcess Start(string fileName, IReadOnlyList<string> arguments)
{
var stdin = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
var stdout = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
var stderr = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
var token = IntPtr.Zero;
var job = IntPtr.Zero;
var attributeList = IntPtr.Zero;
var handleList = IntPtr.Zero;
var processInfo = default(PROCESS_INFORMATION);
try
{
uint? session = null;
int? session = null;
if (intoConsoleSession)
{
var console = WTSGetActiveConsoleSessionId();
if (console != InvalidSession)
{
session = console;
session = (int)console;
token = ConsoleToken(console);
}
else if (consoleRequired)
@@ -51,7 +44,36 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
}
}
// Only the three pipe ends cross into the host.
return Launch(token, session, fileName, arguments, IntPtr.Zero, Path.GetDirectoryName(fileName));
}
finally
{
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
}
}
/// <summary>
/// Starts <paramref name="fileName"/> on the interactive desktop with redirected stdio, no window and
/// only its three pipe ends inherited, in a kill-on-close job. With a <paramref name="token"/> it runs
/// as that token (the caller keeps it); <paramref name="environment"/> is a Unicode block or zero for
/// the token's defaults; <paramref name="session"/> is what <see cref="IScreenProcess.SessionId"/> reports.
/// </summary>
internal static IScreenProcess Launch(
IntPtr token, int? session, string fileName, IReadOnlyList<string> arguments, IntPtr environment, string? folder)
{
var stdin = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
var stdout = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
var stderr = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
var job = IntPtr.Zero;
var attributeList = IntPtr.Zero;
var handleList = IntPtr.Zero;
var processInfo = default(PROCESS_INFORMATION);
try
{
// Only the three pipe ends cross into the process.
var handles = new[]
{
stdin.ClientSafePipeHandle.DangerousGetHandle(),
@@ -69,7 +91,7 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
attributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handleList,
IntPtr.Size * handles.Length, IntPtr.Zero, IntPtr.Zero))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "The screen host's handle list could not be set.");
throw new Win32Exception(Marshal.GetLastWin32Error(), "The process's handle list could not be set.");
}
var startup = new STARTUPINFOEX { lpAttributeList = attributeList };
@@ -82,14 +104,14 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
startup.StartupInfo.hStdError = handles[2];
var commandLine = new StringBuilder(CommandLine(fileName, arguments));
var flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW | CREATE_SUSPENDED;
var folder = Path.GetDirectoryName(fileName);
var flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW | CREATE_SUSPENDED
| (environment != IntPtr.Zero ? CREATE_UNICODE_ENVIRONMENT : 0);
var started = token != IntPtr.Zero
? CreateProcessAsUserW(token, fileName, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, folder, ref startup, out processInfo)
: CreateProcess(fileName, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, folder, ref startup, out processInfo);
? CreateProcessAsUserW(token, fileName, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, environment, folder, ref startup, out processInfo)
: CreateProcess(fileName, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, environment, folder, ref startup, out processInfo);
if (!started)
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "The screen host did not start.");
throw new Win32Exception(Marshal.GetLastWin32Error(), $"{Path.GetFileName(fileName)} did not start.");
}
job = KillOnCloseJob();
@@ -108,7 +130,7 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
stdout.DisposeLocalCopyOfClientHandle();
stderr.DisposeLocalCopyOfClientHandle();
var process = new WindowsScreenProcess(processInfo.hProcess, job, stdin, stdout, stderr, session is { } id ? (int)id : null);
var process = new WindowsScreenProcess(processInfo.hProcess, job, stdin, stdout, stderr, session);
processInfo.hProcess = IntPtr.Zero;
job = IntPtr.Zero;
return process;
@@ -138,11 +160,6 @@ internal sealed class WindowsScreenProcessLauncher(bool intoConsoleSession, bool
}
finally
{
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (attributeList != IntPtr.Zero)
{
DeleteProcThreadAttributeList(attributeList);
+1 -1
View File
@@ -50,7 +50,7 @@ public static class AgentHost
// LOG_DIRECTORY moved the agent's).
var liveLog = new LiveLog();
builder.Logging.ClearProviders();
builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "agent", liveLog), dispose: true);
builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "Agent", liveLog), dispose: true);
builder.Services.AddSingleton(new Logs.AgentLogs(
liveLog, logSettings.Directory, Path.Combine(Upgrade.UpgradeFolders.Installed.InstallDirectory, "Logs")));
+2 -1
View File
@@ -175,7 +175,8 @@ public sealed class AgentSession : IAgentSession
() => configuration.AllowRemoteView.Value,
() => Agent.Screen.ScreenHost.PolicyOf(configuration),
screenLogger,
watcher: sessions);
watcher: sessions,
hostLoggers: loggerFactory);
// The Being Viewed banner (RemoteViewBanner, off by default; read at service start like the rest).
Agent.Screen.ScreenBanner? banner = null;
+19 -14
View File
@@ -237,24 +237,29 @@ public static class ServiceLifecycle
return 0;
}
public static int Status()
/// <summary>
/// The registration and state <c>status</c> reports: NotInstalled when the SCM has no
/// such service; the start type (Automatic, Manual, Disabled) is null when unreadable.
/// </summary>
public static (bool Installed, string State, string? StartType) Query()
{
string state;
var installed = Exists();
if (installed)
if (!Exists())
{
using var controller = new ServiceController(Branding.AgentServiceName);
state = controller.Status.ToString();
}
else
{
state = "NotInstalled";
return (false, "NotInstalled", null);
}
// Machine-readable line first, human-readable after.
Console.WriteLine($"{{\"service\":\"{Branding.AgentServiceName}\",\"installed\":{(installed ? "true" : "false")},\"state\":\"{state}\"}}");
Console.WriteLine($"Service '{Branding.AgentServiceDisplayName}': {state}");
return 0;
using var controller = new ServiceController(Branding.AgentServiceName);
string? startType;
try
{
startType = controller.StartType.ToString();
}
catch (InvalidOperationException)
{
startType = null;
}
return (true, controller.Status.ToString(), startType);
}
private static bool Exists()
+52
View File
@@ -99,11 +99,63 @@ public static class UnixServiceLifecycle
? Run("launchctl", $"kill SIGTERM system/{LaunchdLabel}", ignoreErrors: true)
: Run("systemctl", $"stop {SystemdUnit}", ignoreErrors: true);
/// <summary>The service manager's own description, after the JSON line <c>status</c> prints.</summary>
public static int Status()
=> OperatingSystem.IsMacOS()
? Run("launchctl", $"print system/{LaunchdLabel}", ignoreErrors: true)
: Run("systemctl", $"status {SystemdUnit} --no-pager", ignoreErrors: true);
/// <summary>
/// The registration and state <c>status</c> reports: the unit file / plist present,
/// and systemd's ActiveState (active, inactive, failed, activating) or launchd's
/// "running" / "not running" / "not loaded".
/// </summary>
public static (bool Installed, string State, string? StartType) Query()
{
if (OperatingSystem.IsMacOS())
{
var plist = $"/Library/LaunchDaemons/{LaunchdLabel}.plist";
var (code, output) = Capture("launchctl", $"print system/{LaunchdLabel}");
var state = code != 0 ? "not loaded" : output.Contains("state = running", StringComparison.Ordinal) ? "running" : "not running";
return (File.Exists(plist), state, null);
}
var unit = $"/etc/systemd/system/{SystemdUnit}.service";
var active = Capture("systemctl", $"is-active {SystemdUnit}").Output.Trim();
var enabled = Capture("systemctl", $"is-enabled {SystemdUnit}").Output.Trim();
return (File.Exists(unit), active.Length == 0 ? "unknown" : active, enabled.Length == 0 ? null : enabled);
}
private static (int ExitCode, string Output) Capture(string fileName, string arguments)
{
try
{
using var process = Process.Start(new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
});
if (process is null)
{
return (-1, string.Empty);
}
var errors = process.StandardError.ReadToEndAsync();
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
_ = errors.Result;
return (process.ExitCode, output);
}
catch (System.ComponentModel.Win32Exception)
{
// No systemctl / launchctl here (a container): nothing registered.
return (-1, string.Empty);
}
}
private static int InstallSystemd()
{
var unit = $"/etc/systemd/system/{SystemdUnit}.service";
+179
View File
@@ -0,0 +1,179 @@
using System.Diagnostics;
namespace Agent.Sessions;
/// <summary>
/// The account a shell or script runs as for Run As Signed-In User: its name (DOMAIN\user on
/// Windows) and, on Windows, the session whose token it uses.
/// </summary>
public sealed record SignedInUser(string Name, int? WindowsSession = null);
/// <summary>
/// Who to run as, or why nobody can be picked; <see cref="SignedIn"/> names everyone signed in
/// (sorted; null when the sessions could not be read), so the operator can choose one.
/// </summary>
public sealed record SignedInUserLookup(SignedInUser? User, string? Reason, IReadOnlyList<string>? SignedIn = null)
{
public static SignedInUserLookup Nobody(string reason, IReadOnlyList<string>? signedIn = null) => new(null, reason, signedIn);
public static SignedInUserLookup Of(SignedInUser user, IReadOnlyList<string>? signedIn = null) => new(user, null, signedIn ?? [user.Name]);
}
/// <summary>Finds the user to run as on this device.</summary>
public interface ISignedInUserResolver
{
/// <summary>
/// <paramref name="requested"/>: that signed-in user (by name, any case), refused when they are
/// not signed in; null: the usual rule (see <see cref="SignedInUsers.Pick"/>).
/// </summary>
SignedInUserLookup Resolve(string? requested = null);
}
/// <summary>
/// The rule every platform shares: the console's user when someone is at the console;
/// otherwise the only signed-in user. Several users and nobody at the console is ambiguous
/// (a terminal server), so nothing is picked rather than the wrong person.
/// </summary>
public static class SignedInUsers
{
public const string NobodyReason = "Nobody is signed in on the device.";
/// <summary>The resolver for this platform.</summary>
public static ISignedInUserResolver Default { get; } =
#if WINDOWS_AGENT
new WindowsSignedInUserResolver(new WindowsSessionQuery());
#else
OperatingSystem.IsMacOS() ? new MacSignedInUserResolver() : new LinuxSignedInUserResolver();
#endif
/// <summary>
/// Picks from <paramref name="sessions"/> (each with its user). <paramref name="requested"/>
/// names one: their console session when they have it, else their first; nobody when they
/// are not signed in (never an account that merely exists). Otherwise the console's user,
/// else the only user signed in.
/// </summary>
public static SignedInUserLookup Pick<TSession>(
IReadOnlyList<TSession> sessions, Func<TSession, string?> user, Func<TSession, bool> atConsole, Func<TSession, SignedInUser> toUser,
string? requested = null)
{
var signedIn = sessions.Where(s => !string.IsNullOrWhiteSpace(user(s))).ToList();
var names = signedIn.Select(s => user(s)!).Distinct(StringComparer.OrdinalIgnoreCase).Order(StringComparer.OrdinalIgnoreCase).ToList();
if (!string.IsNullOrWhiteSpace(requested))
{
// The exact name first (unix names are case-sensitive), else any case (Windows').
var theirs = signedIn.Where(s => string.Equals(user(s), requested.Trim(), StringComparison.Ordinal)).ToList();
if (theirs.Count == 0)
{
theirs = signedIn.Where(s => string.Equals(user(s), requested.Trim(), StringComparison.OrdinalIgnoreCase)).ToList();
}
return theirs.Count == 0
? SignedInUserLookup.Nobody($"{requested.Trim()} is not signed in on the device.", names)
: SignedInUserLookup.Of(toUser(theirs.FirstOrDefault(atConsole) ?? theirs[0]), names);
}
if (signedIn.FirstOrDefault(atConsole) is { } console)
{
return SignedInUserLookup.Of(toUser(console), names);
}
return names.Count switch
{
0 => SignedInUserLookup.Nobody(NobodyReason, names),
1 => SignedInUserLookup.Of(toUser(signedIn[0]), names),
_ => SignedInUserLookup.Nobody(
$"Several users are signed in ({string.Join(", ", names)}) and nobody is at the console; choose one under Run As.", names),
};
}
}
#if WINDOWS_AGENT
/// <summary>Terminal Services sessions: the active console session's user, else the only signed-in user.</summary>
public sealed class WindowsSignedInUserResolver(ISessionQuery query) : ISignedInUserResolver
{
public SignedInUserLookup Resolve(string? requested = null)
{
var console = query.ActiveConsoleSession();
var sessions = query.Enumerate();
if (sessions is null)
{
return SignedInUserLookup.Nobody("The device's sessions could not be read.");
}
return SignedInUsers.Pick(
sessions, s => s.User, s => s.SessionId == console, s => new SignedInUser(s.User!, s.SessionId), requested);
}
}
#endif
/// <summary>logind's user sessions: a local one's user (the seat's), else the only signed-in user.</summary>
public sealed class LinuxSignedInUserResolver(Func<IReadOnlyList<LogonEvent>?>? sessions = null) : ISignedInUserResolver
{
private readonly Func<IReadOnlyList<LogonEvent>?> current = sessions
?? (() => new LinuxLogonSource(Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance).Current());
public SignedInUserLookup Resolve(string? requested = null)
{
var list = current();
if (list is null)
{
return SignedInUserLookup.Nobody("The device's sessions could not be read (loginctl is unavailable).");
}
// Local sessions stand in for the console: with one local user that is the one. root's own
// sessions are never "the user" (it is the agent's account already).
var users = list.Where(l => !string.IsNullOrWhiteSpace(l.User) && l.User != "root").ToList();
var local = users.Where(l => l.Detail == "local").Select(l => l.User!).Distinct(StringComparer.Ordinal).ToList();
return SignedInUsers.Pick(
users,
l => l.User,
l => local.Count == 1 && l.User == local[0],
l => new SignedInUser(l.User!),
requested);
}
}
/// <summary>The owner of /dev/console (the user at the login window is root: nobody).</summary>
public sealed class MacSignedInUserResolver(Func<string?>? consoleOwner = null) : ISignedInUserResolver
{
private readonly Func<string?> owner = consoleOwner ?? ReadConsoleOwner;
public SignedInUserLookup Resolve(string? requested = null)
{
var name = owner()?.Trim();
if (string.IsNullOrEmpty(name) || name is "root" or "_mbsetupuser")
{
return SignedInUserLookup.Nobody(
string.IsNullOrWhiteSpace(requested) ? SignedInUsers.NobodyReason : $"{requested.Trim()} is not signed in on the device.", []);
}
// Only the console's user counts on macOS (fast user switching's others have no shell to lend).
return string.IsNullOrWhiteSpace(requested) || string.Equals(requested.Trim(), name, StringComparison.Ordinal)
? SignedInUserLookup.Of(new SignedInUser(name))
: SignedInUserLookup.Nobody($"{requested.Trim()} is not the user at the device's console.", [name]);
}
private static string? ReadConsoleOwner()
{
try
{
var start = new ProcessStartInfo("/usr/bin/stat") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
start.ArgumentList.Add("-f");
start.ArgumentList.Add("%Su");
start.ArgumentList.Add("/dev/console");
using var process = Process.Start(start);
if (process is null)
{
return null;
}
var output = process.StandardOutput.ReadToEnd();
return process.WaitForExit(5000) && process.ExitCode == 0 ? output : null;
}
catch (Exception exception) when (exception is System.ComponentModel.Win32Exception or InvalidOperationException or IOException)
{
return null;
}
}
}
+35 -1
View File
@@ -5,11 +5,19 @@ using static Agent.Shell.ConPtyInterop;
namespace Agent.Shell;
/// <summary>
/// Who a ConPTY shell runs as when not the agent's own account: a primary token (the caller
/// keeps it until <see cref="ConPtySession.Start"/> returns), its environment block and the
/// folder to start in.
/// </summary>
internal sealed record PtyUser(IntPtr Token, IntPtr Environment, string? Directory);
/// <summary>
/// A live ConPTY-backed shell process. Terminal output is delivered via
/// <see cref="OutputReceived"/>; input is written with <see cref="WriteAsync"/>.
/// With a <see cref="PtyUser"/> it starts as that user, on their desktop.
/// </summary>
public sealed class ConPtySession : IPtySession
internal sealed class ConPtySession(PtyUser? user = null) : IPtySession
{
private IntPtr pseudoConsole = IntPtr.Zero;
private IntPtr attributeList = IntPtr.Zero;
@@ -90,6 +98,32 @@ public sealed class ConPtySession : IPtySession
throw new InvalidOperationException("UpdateProcThreadAttribute failed.");
}
if (user is not null)
{
// On the user's desktop, so a window the shell opens shows there; the shell itself is
// headless (the pseudoconsole has no window) and starts hidden, so nothing flashes.
startupInfo.StartupInfo.lpDesktop = @"winsta0\default";
startupInfo.StartupInfo.dwFlags = Agent.Screen.WindowsScreenInterop.STARTF_USESHOWWINDOW;
startupInfo.StartupInfo.wShowWindow = 0;
if (!Agent.Screen.WindowsScreenInterop.CreateProcessAsUserW(
user.Token,
null,
new System.Text.StringBuilder(commandLine),
IntPtr.Zero,
IntPtr.Zero,
false,
EXTENDED_STARTUPINFO_PRESENT | Agent.Screen.WindowsScreenInterop.CREATE_UNICODE_ENVIRONMENT,
user.Environment,
user.Directory,
ref startupInfo,
out processInfo))
{
throw new InvalidOperationException($"CreateProcessAsUser failed (Win32 {Marshal.GetLastWin32Error()}).");
}
return;
}
if (!CreateProcessW(
lpApplicationName: null,
lpCommandLine: commandLine,
+113 -8
View File
@@ -1,4 +1,5 @@
using Agent.Messaging;
using Agent.Sessions;
using Microsoft.Extensions.Logging;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
@@ -13,8 +14,9 @@ namespace Agent.Shell;
/// one closes the previous. Output is published as base64 over Core NATS with
/// a monotonic sequence.
/// </summary>
public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDisposable
public sealed class ShellManager(AgentPublisher publisher, ILogger logger, ISignedInUserResolver? users = null) : IDisposable
{
private readonly ISignedInUserResolver signedIn = users ?? SignedInUsers.Default;
private readonly Lock gate = new();
private ActiveShell? current;
@@ -45,7 +47,42 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
return;
}
var pty = CreatePty();
// As the signed-in user: their token (Windows) or su -l (linux/macOS), never the agent's account.
string? asUser = null;
IDisposable? userResources = null;
IPtySession pty;
// Who is signed in travels with the state, so the console can offer each of them.
IReadOnlyList<string>? signedInUsers;
if (command.AsUser)
{
var lookup = signedIn.Resolve(command.User);
signedInUsers = lookup.SignedIn;
if (lookup.User is not { } user)
{
var reason = $"Not opened as the signed-in user: {lookup.Reason}";
logger.LogWarning("Shell session {SessionId} not opened: {Reason}", sessionId, reason);
PublishState(sessionId, ShellSessionState.Failed, reason, signedInUsers: signedInUsers);
return;
}
try
{
(pty, launch, userResources) = CreateUserPty(user, launch);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogWarning("Shell session {SessionId} not opened as {User}: {Reason}", sessionId, user.Name, ex.Message);
PublishState(sessionId, ShellSessionState.Failed, $"Not opened as {user.Name}: {ex.Message}", signedInUsers: signedInUsers);
return;
}
asUser = user.Name;
}
else
{
pty = CreatePty();
signedInUsers = SignedInNames();
}
var active = new ActiveShell
{
@@ -65,10 +102,19 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
try
{
pty.Start(launch.FileName, launch.Args, Math.Max(command.Cols, 1), Math.Max(command.Rows, 1));
PublishState(sessionId, ShellSessionState.Open, null, launch.Kind);
logger.LogInformation("Shell session {SessionId} opened: {Kind} ({Shell}, requested {Requested})",
sessionId, launch.Kind ?? "login shell", launch.FileName, command.Shell ?? ShellKinds.Auto);
try
{
pty.Start(launch.FileName, launch.Args, Math.Max(command.Cols, 1), Math.Max(command.Rows, 1));
}
finally
{
// The token and environment block are only needed to start the process.
userResources?.Dispose();
}
PublishState(sessionId, ShellSessionState.Open, null, launch.Kind, asUser, signedInUsers);
logger.LogInformation("Shell session {SessionId} opened: {Kind} ({Shell}, requested {Requested}) as {User}",
sessionId, launch.Kind ?? "login shell", launch.FileName, command.Shell ?? ShellKinds.Auto, asUser ?? "the agent's account");
}
catch (Exception ex)
{
@@ -78,6 +124,50 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
}
}
#if WINDOWS_AGENT
/// <summary>A ConPTY started with the user's token, environment and profile folder (the resources go once it has started).</summary>
private static (IPtySession Pty, ShellLaunch Launch, IDisposable Resources) CreateUserPty(SignedInUser user, ShellLaunch launch)
{
var token = Agent.Platform.WindowsUserToken.Open(user);
try
{
var environment = token.EnvironmentBlock(null);
var resources = new UserPtyResources(token, environment);
return (new ConPtySession(new PtyUser(token.Handle, environment, token.ProfileDirectory())), launch, resources);
}
catch
{
token.Dispose();
throw;
}
}
private sealed class UserPtyResources(Agent.Platform.WindowsUserToken token, IntPtr environment) : IDisposable
{
public void Dispose()
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(environment);
token.Dispose();
}
}
#else
/// <summary>The user's login shell through su (root needs no password); the requested shell does not apply.</summary>
private static (IPtySession Pty, ShellLaunch Launch, IDisposable Resources) CreateUserPty(SignedInUser user, ShellLaunch launch)
{
_ = launch;
var su = new[] { "/bin/su", "/usr/bin/su" }.FirstOrDefault(File.Exists)
?? throw new InvalidOperationException("su is not available on this device.");
return (new UnixPtySession(), new ShellLaunch(null, su, ["-l", user.Name]), new NoResources());
}
private sealed class NoResources : IDisposable
{
public void Dispose()
{
}
}
#endif
public async Task WriteAsync(ShellInputPayload input, CancellationToken cancellationToken)
{
ActiveShell? active;
@@ -170,12 +260,27 @@ public sealed class ShellManager(AgentPublisher publisher, ILogger logger) : IDi
payload);
}
private void PublishState(Guid sessionId, ShellSessionState state, string? message, string? shell = null)
private void PublishState(
Guid sessionId, ShellSessionState state, string? message, string? shell = null, string? user = null, IReadOnlyList<string>? signedInUsers = null)
{
_ = publisher.PublishAsync(
NatsSubjects.AgentShellState(publisher.ClientId, sessionId),
MessageTypes.ShellState,
new ShellStatePayload(sessionId, state, message, shell));
new ShellStatePayload(sessionId, state, message, shell, user, signedInUsers));
}
/// <summary>Who is signed in (for the console's Run As list); null when it cannot be read.</summary>
private IReadOnlyList<string>? SignedInNames()
{
try
{
return signedIn.Resolve().SignedIn;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
logger.LogDebug("Signed-in users could not be listed: {Message}", ex.Message);
return null;
}
}
private static void DisposeShell(ActiveShell? active, string reason)
+2
View File
@@ -649,6 +649,8 @@ public sealed class ScriptEntity : IFolderItem
/// <see cref="RestartOptions.MaxWarningSeconds"/>).
/// </summary>
public int RestartWarningSeconds { get; set; }
/// <summary>Run as the device's signed-in user (out of process) instead of the agent's account.</summary>
public bool RunAsUser { get; set; }
public DateTimeOffset CreatedUtc { get; set; }
public DateTimeOffset UpdatedUtc { get; set; }
public string? CreatedBy { get; set; }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Postgres
{
/// <inheritdoc />
public partial class ScriptRunAsUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "RunAsUser",
table: "Scripts",
type: "boolean",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RunAsUser",
table: "Scripts");
}
}
}
@@ -1122,6 +1122,9 @@ namespace Backend.Data.Migrations.Postgres
b.Property<int>("RestartWarningSeconds")
.HasColumnType("integer");
b.Property<bool>("RunAsUser")
.HasColumnType("boolean");
b.Property<bool>("RunFromFile")
.HasColumnType("boolean");
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.SqlServer
{
/// <inheritdoc />
public partial class ScriptRunAsUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "RunAsUser",
table: "Scripts",
type: "bit",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RunAsUser",
table: "Scripts");
}
}
}
@@ -1122,6 +1122,9 @@ namespace Backend.Data.Migrations.SqlServer
b.Property<int>("RestartWarningSeconds")
.HasColumnType("int");
b.Property<bool>("RunAsUser")
.HasColumnType("bit");
b.Property<bool>("RunFromFile")
.HasColumnType("bit");
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Backend.Data.Migrations.Sqlite
{
/// <inheritdoc />
public partial class ScriptRunAsUser : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "RunAsUser",
table: "Scripts",
type: "INTEGER",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RunAsUser",
table: "Scripts");
}
}
}
@@ -1111,6 +1111,9 @@ namespace Backend.Data.Migrations.Sqlite
b.Property<int>("RestartWarningSeconds")
.HasColumnType("INTEGER");
b.Property<bool>("RunAsUser")
.HasColumnType("INTEGER");
b.Property<bool>("RunFromFile")
.HasColumnType("INTEGER");
+90 -108
View File
@@ -12,7 +12,8 @@ namespace Backend.Enrollment;
///
/// The returned PowerShell downloads the agent package from this same origin
/// and installs it with SERVERURL + BOOTSTRAPTOKEN. The package is served from
/// AGENT_PACKAGE_PATH (default /data/agent).
/// AGENT_PACKAGE_PATH (default /data/agent). Every script is safe to run again:
/// it installs, upgrades, repairs or leaves the agent alone (<see cref="InstallScripts"/>).
/// </summary>
public static class InstallEndpoints
{
@@ -50,8 +51,9 @@ public static class InstallEndpoints
: Results.Text(pem, "application/x-pem-file; charset=utf-8");
}
private static IResult GetInstallScript(
HttpContext context, IConfiguration configuration, Backend.Tls.TlsSettings tls, string? token, string? type)
private static async Task<IResult> GetInstallScript(
HttpContext context, IConfiguration configuration, Backend.Tls.TlsSettings tls, Files.AgentPackageService packages,
Upgrades.AgentCatalogService catalog, string? token, string? type, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(token))
{
@@ -78,14 +80,24 @@ public static class InstallEndpoints
// scripts also work in Windows PE: there the MSI script switches to the
// portable package (Windows Installer does not run in WinPE).
// The package links carry the token: without public downloads, a live token is what lets them through.
// Each script compares the installed agent with the version the package link
// serves, so a rerun on a current, healthy device changes nothing.
var catalogued = (await catalog.NewestByTypeAsync(cancellationToken))
.ToDictionary(p => p.Key, p => p.Value.Version, StringComparer.OrdinalIgnoreCase);
string? Version(string packageType) => ServedVersion(packageType, catalogued, packages);
var tokenQuery = "token=" + Uri.EscapeDataString(token!);
var zipUrl = $"{baseUrl}{ApiRoutes.AgentPackage}?type=zip&{tokenQuery}";
var script = type?.ToLowerInvariant() switch
{
"linux" => BuildUnixScript(baseUrl, token!, "linux", tokenQuery, skipDownloadVerify, fingerprint),
"osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", tokenQuery, skipDownloadVerify, fingerprint),
"zip" => BuildZipScript(baseUrl, token!, zipUrl, skipDownloadVerify, fingerprint),
_ => BuildMsiScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi&{tokenQuery}", zipUrl, skipDownloadVerify, fingerprint),
"linux" => BuildUnixScript(baseUrl, token!, "linux", tokenQuery, skipDownloadVerify, fingerprint,
Version(AgentPackageTypes.LinuxX64), Version(AgentPackageTypes.LinuxArm64)),
"osx" or "mac" or "macos" or "darwin" => BuildUnixScript(baseUrl, token!, "osx", tokenQuery, skipDownloadVerify, fingerprint,
Version(AgentPackageTypes.MacX64), Version(AgentPackageTypes.MacArm64)),
"zip" => BuildWindowsScript(baseUrl, token!, msiUrl: null, zipUrl, msiVersion: null, Version(AgentPackageTypes.WindowsZip),
skipDownloadVerify, fingerprint),
_ => BuildWindowsScript(baseUrl, token!, $"{baseUrl}{ApiRoutes.AgentPackage}?type=msi&{tokenQuery}", zipUrl,
Version(AgentPackageTypes.Msi), Version(AgentPackageTypes.WindowsZip), skipDownloadVerify, fingerprint),
};
return Results.Text(script, "text/plain; charset=utf-8");
@@ -191,129 +203,99 @@ public static class InstallEndpoints
// an elevated PowerShell — the Add device modal states this prerequisite.
// Windows PE (the MiniNT key) has no Windows Installer, so there the MSI
// script takes the portable path instead — same service, same enrollment.
private static string BuildMsiScript(
string baseUrl, string token, string packageUrl, string zipUrl, bool skipDownloadVerify, string? fingerprint) => $$"""
// The body (InstallScripts) looks before it acts: install, upgrade, repair or
// nothing, and the token only where the enrollment needs it.
internal static string BuildWindowsScript(
string baseUrl, string token, string? msiUrl, string zipUrl, string? msiVersion, string? zipVersion,
bool skipDownloadVerify, string? fingerprint) => $$"""
$ErrorActionPreference = 'Stop'
{{PsDownloadTls}}
{{(skipDownloadVerify ? PsAcceptCert : "")}}
$server = '{{baseUrl}}'
$token = '{{token}}'
$server = {{PsQuote(baseUrl)}}
$token = {{PsQuote(token)}}
$msiUrl = {{PsQuote(msiUrl ?? "")}}
$zipUrl = {{PsQuote(zipUrl)}}
$msiVersion = {{PsQuote(msiVersion ?? "")}}
$zipVersion = {{PsQuote(zipVersion ?? "")}}
$portableOnly = {{(msiUrl is null ? "$true" : "$false")}}
{{PsDownload(fingerprint)}}
if (Test-Path '{{PsWinPeKey}}') {
Write-Host 'Windows PE detected: installing ExecuteR Agent (portable)...'
{{PortableInstall(zipUrl)}}
}
else {
Write-Host 'Installing ExecuteR Agent...'
$msi = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.msi')
try {
Save-ExecuteRFile '{{packageUrl}}' $msi
$arguments = @('/i', ('"' + $msi + '"'), '/qn', "SERVERURL=$server", "BOOTSTRAPTOKEN=$token")
$p = Start-Process msiexec.exe -ArgumentList $arguments -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "msiexec exited with $($p.ExitCode)" }
Write-Host 'ExecuteR Agent installed. It will enroll and start automatically.'
}
finally {
Remove-Item $msi -ErrorAction SilentlyContinue
}
}
""";
private const string PsWinPeKey = @"HKLM:\SYSTEM\CurrentControlSet\Control\MiniNT";
/// <summary>
/// The portable install body (expects <c>$server</c>/<c>$token</c>): unpack
/// the zip under Program Files (X:\ in Windows PE), seed enrollment, then
/// register and start the Windows service through the agent's own
/// <c>initialize</c> (Service Control Manager APIs, never sc.exe). Unzips
/// with System.IO.Compression rather than Expand-Archive, which a minimal
/// PowerShell (Windows PE) may lack; a re-run stops the running agent first
/// so its files can be replaced. ExtractToDirectory creates missing
/// parent folders.
/// </summary>
private static string PortableInstall(string packageUrl) => $$"""
$dest = Join-Path $env:ProgramFiles 'ExecuteR\Agent'
$exe = Join-Path $dest 'ExecuteR-Agent.exe'
$zip = Join-Path $env:TEMP ('ExecuteRAgent-' + [guid]::NewGuid().ToString('N') + '.zip')
$unpacked = $zip + '.d'
try {
Save-ExecuteRFile '{{packageUrl}}' $zip
Add-Type -AssemblyName System.IO.Compression.FileSystem
if (Test-Path $dest) {
[System.IO.Compression.ZipFile]::ExtractToDirectory($zip, $unpacked)
if (Test-Path $exe) { try { & $exe stop | Out-Null } catch { } }
Copy-Item -Path (Join-Path $unpacked '*') -Destination $dest -Recurse -Force
}
else {
# First install: unpack in place (Windows PE's RAM drive is small).
[System.IO.Compression.ZipFile]::ExtractToDirectory($zip, $dest)
}
# Windows PE: nobody signs in, so the Being Viewed banner has no place there.
if (Test-Path '{{PsWinPeKey}}') {
Remove-Item (Join-Path $dest '{{Shared.Infrastructure.Constants.Branding.BannerExecutableName}}') -Force -ErrorAction SilentlyContinue
}
# Seed configuration then install + start the service via the agent's own APIs.
New-Item -Path 'HKLM:\SOFTWARE\ExecuteR' -Force | Out-Null
Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'ServerURL' -Value $server
Set-ItemProperty -Path 'HKLM:\SOFTWARE\ExecuteR' -Name 'BootstrapToken' -Value $token
& $exe initialize
if ($LASTEXITCODE -ne 0) { throw "ExecuteR-Agent initialize exited with $LASTEXITCODE" }
Write-Host 'ExecuteR Agent installed and starting.'
}
finally {
Remove-Item $zip -ErrorAction SilentlyContinue
Remove-Item $unpacked -Recurse -Force -ErrorAction SilentlyContinue
}
{{InstallScripts.WindowsFunctions}}
{{InstallScripts.WindowsMain}}
""";
/// <summary>
/// linux/macOS installer: detects the architecture, downloads the matching
/// agent zip, unpacks to /opt/executer/agent, configures enrollment via
/// the agent's own CLI and registers the systemd unit / launchd daemon.
/// linux/macOS installer: detects the architecture, then installs, upgrades or
/// repairs the agent from the matching zip under /opt/executer/agent, configures
/// enrollment through the agent's own CLI and registers the systemd unit /
/// launchd daemon through its initialize (InstallScripts has the rules).
/// </summary>
// ReplaceLineEndings("\n"): the .cs source is checked out with CRLF on
// Windows, but a bash script with CRLF fails hard when piped to bash
// (`set -euo pipefail\r` -> ": invalid option namepefail"). Force LF.
private static string BuildUnixScript(string baseUrl, string token, string os, string tokenQuery, bool skipDownloadVerify, string? fingerprint) => ($$"""
// Everything runs from main() on the last line: bash reads a piped script as
// it goes, so a cut-off download runs nothing.
internal static string BuildUnixScript(
string baseUrl, string token, string os, string tokenQuery, bool skipDownloadVerify, string? fingerprint,
string? x64Version, string? arm64Version) => ($$"""
#!/usr/bin/env bash
set -euo pipefail
if [ "$(id -u)" -ne 0 ]; then echo 'Run with sudo/root.' >&2; exit 1; fi
server='{{baseUrl}}'
token='{{token}}'
if [ "$(id -u)" -ne 0 ]; then echo 'Failed: run with sudo/root.' >&2; exit 1; fi
server={{ShQuote(baseUrl)}}
token={{ShQuote(token)}}
os='{{os}}'
case "$(uname -m)" in
x86_64|amd64) arch=x64 ;;
aarch64|arm64) arch=arm64 ;;
*) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
*) echo "Failed: unsupported architecture $(uname -m)" >&2; exit 1 ;;
esac
pkg="{{baseUrl}}{{ApiRoutes.AgentPackage}}?type={{os}}-${arch}&{{tokenQuery}}"
case "$arch" in
x64) target={{ShQuote(x64Version ?? "")}} ;;
*) target={{ShQuote(arm64Version ?? "")}} ;;
esac
dest=/opt/executer/agent
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
lock=/var/run/executer-install.lock
reported=0
locked=0
tmp=$(mktemp -d "${TMPDIR:-/tmp}/executer-install.XXXXXX")
cleanup() {
local rc=$?
rm -rf "$tmp"
if [ "$locked" = 1 ]; then rm -rf "$lock"; fi
if [ "$rc" -ne 0 ] && [ "$reported" = 0 ]; then echo "Failed: the setup stopped unexpectedly (exit $rc)."; fi
}
trap cleanup EXIT
{{ShDownload(fingerprint, skipDownloadVerify)}}
echo "Installing ExecuteR Agent ({{os}}-${arch})..."
download "$pkg" "$tmp/agent.zip"
mkdir -p "$dest"
if command -v unzip >/dev/null 2>&1; then
unzip -oq "$tmp/agent.zip" -d "$dest"
else
python3 -m zipfile -e "$tmp/agent.zip" "$dest"
fi
chmod +x "$dest/executer-agent"
"$dest/executer-agent" configure --url "$server" --token "$token"
"$dest/executer-agent" initialize
echo 'ExecuteR Agent installed. It will enroll and start automatically.'
{{InstallScripts.UnixFunctions}}
main
""").ReplaceLineEndings("\n");
private static string BuildZipScript(string baseUrl, string token, string packageUrl, bool skipDownloadVerify, string? fingerprint) => $$"""
$ErrorActionPreference = 'Stop'
Write-Host 'Installing ExecuteR Agent (portable)...'
{{PsDownloadTls}}
{{(skipDownloadVerify ? PsAcceptCert : "")}}
$server = '{{baseUrl}}'
$token = '{{token}}'
{{PsDownload(fingerprint)}}
{{PortableInstall(packageUrl)}}
""";
/// <summary>A PowerShell single-quoted literal.</summary>
internal static string PsQuote(string value) => "'" + value.Replace("'", "''") + "'";
/// <summary>A bash single-quoted literal.</summary>
internal static string ShQuote(string value) => "'" + value.Replace("'", "'\\''") + "'";
/// <summary>
/// The version the package link serves for a type (as <see cref="ServePackageAsync"/>
/// picks: the catalog's newest unless this node holds a newer one), or null when
/// unknown. Only a version the comparison understands goes into a script.
/// </summary>
internal static string? ServedVersion(string packageType, IReadOnlyDictionary<string, string> catalogued, Files.AgentPackageService packages)
{
var path = packages.ResolveLocalPath(packageType);
var local = path is null ? null : Files.AgentPackageService.ReadVersionMarker(Path.GetDirectoryName(path));
var version = catalogued.TryGetValue(packageType, out var newest) && (path is null || !AgentVersions.IsNewer(local, newest))
? newest
: local;
return ScriptSafeVersion(version);
}
internal static string? ScriptSafeVersion(string? version)
=> version is not null && AgentVersions.IsValid(version)
&& version.Trim().All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '+' or '-')
? version.Trim()
: null;
/// <summary>
/// The CA fingerprint a bootstrap token carries ("secret.fp", 64 hex
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -145,7 +145,7 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv
var known = devices.Select(d => d.ClientId).ToHashSet(StringComparer.Ordinal);
var direct = groups.ToDictionary(g => g.Id, _ => new HashSet<string>(StringComparer.Ordinal));
var staticIds = groups.Where(g => g.Kind == GroupKind.Static).Select(g => g.Id).ToHashSet();
var staticIds = groups.Where(g => ScriptGroups.HasMemberRows(g.Kind)).Select(g => g.Id).ToHashSet();
foreach (var row in staticRows)
{
// Rows for deleted devices or non-static groups are ignored.
@@ -197,7 +197,7 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv
{
switch (group.Kind)
{
case GroupKind.Static:
case GroupKind.Static or GroupKind.Script:
return await db.DeviceGroupMembers.AsNoTracking()
.Where(m => m.GroupId == group.Id && db.Devices.Any(d => d.ClientId == m.ClientId))
.Select(m => m.ClientId)
@@ -306,7 +306,7 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv
var directIds = groups
.Where(group => group.Kind switch
{
GroupKind.Static => staticGroupIds.Contains(group.Id),
GroupKind.Static or GroupKind.Script => staticGroupIds.Contains(group.Id),
GroupKind.Dynamic => ParseRules(group.RulesJson) is { } rules && RuleEvaluator.Matches(rules, fields),
_ => false,
})
@@ -397,7 +397,7 @@ public sealed class DeviceGroupService(AppDbContext db, InventoryReportCache inv
return (await GetMembershipAsync(cancellationToken)).Effective(group.Id).Contains(clientId);
}
if (group.Kind == GroupKind.Static)
if (ScriptGroups.HasMemberRows(group.Kind))
{
return await db.DeviceGroupMembers.AsNoTracking()
.AnyAsync(m => m.GroupId == group.Id && m.ClientId == clientId, cancellationToken);
+9 -6
View File
@@ -127,9 +127,9 @@ public static class GroupEndpoints
return rulesProblem;
}
// Only static groups keep an explicit list; switching kind drops it so
// a later switch back does not resurrect stale members.
if (request.Kind != GroupKind.Static && entity.Kind == GroupKind.Static)
// Only static and script groups keep an explicit list; switching to a kind without one drops
// it so a later switch back does not resurrect stale members.
if (!ScriptGroups.HasMemberRows(request.Kind) && ScriptGroups.HasMemberRows(entity.Kind))
{
await db.DeviceGroupMembers.Where(m => m.GroupId == id).ExecuteDeleteAsync(cancellationToken);
}
@@ -292,9 +292,12 @@ public static class GroupEndpoints
{
return Results.BadRequest(new
{
error = entity.Kind == GroupKind.Dynamic
? "Membership of a dynamic group is determined by its rules."
: "A folder holds groups, not devices. Add the devices to a static group inside it.",
error = entity.Kind switch
{
GroupKind.Dynamic => "Membership of a dynamic group is determined by its rules.",
GroupKind.Script => "Membership of a script group is set by the scripts that report on it.",
_ => "A folder holds groups, not devices. Add the devices to a static group inside it.",
},
});
}
+122
View File
@@ -0,0 +1,122 @@
using Backend.Data;
using Backend.Security;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Models;
namespace Backend.Groups;
/// <summary>
/// Applies what a device's job said about its script groups (<see cref="ScriptGroups"/>): each named
/// script group gains or loses that device, and a group a device joins first is created (top level).
/// Only script groups change: a report naming a static, dynamic or folder group is ignored, so a
/// device can never put itself into a group an operator curates. One device's report only ever
/// changes that device's own membership.
/// </summary>
public sealed class ScriptGroupMembership(AppDbContext db, AuditService audit, ILogger<ScriptGroupMembership> logger)
{
/// <summary>What changed, for the activity feed.</summary>
public sealed record Outcome(IReadOnlyList<string> Joined, IReadOnlyList<string> Left, IReadOnlyList<string> Created, IReadOnlyList<string> Ignored)
{
public bool Changed => Joined.Count + Left.Count > 0;
}
public async Task<Outcome> ApplyAsync(
string clientId, string scriptName, IReadOnlyList<GroupMembershipReport> reports, CancellationToken cancellationToken)
{
var joined = new List<string>();
var left = new List<string>();
var created = new List<string>();
var ignored = new List<string>();
// The last word per group wins; past the limit nothing more is read.
var wanted = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
foreach (var report in reports.Take(ScriptGroups.MaxReportsPerJob))
{
if (ScriptGroups.Normalize(report.Group) is { } name)
{
wanted.Remove(name);
wanted[name] = report.Member;
}
}
if (wanted.Count == 0 || !await db.Devices.AnyAsync(d => d.ClientId == clientId, cancellationToken))
{
return new Outcome(joined, left, created, ignored);
}
var lowered = wanted.Keys.Select(k => k.ToLowerInvariant()).ToList();
var named = await db.DeviceGroups
.Where(g => lowered.Contains(g.Name.ToLower()))
.ToListAsync(cancellationToken);
var now = DateTimeOffset.UtcNow;
foreach (var (name, member) in wanted)
{
var matches = named.Where(g => string.Equals(g.Name, name, StringComparison.OrdinalIgnoreCase)).ToList();
var group = matches.FirstOrDefault(g => g.Kind == GroupKind.Script);
if (group is null && matches.Count > 0)
{
// A curated group by that name: never touched by a device.
ignored.Add(name);
continue;
}
if (group is null)
{
if (!member)
{
continue;
}
group = new DeviceGroupEntity
{
Id = Guid.NewGuid(),
Name = name,
Kind = GroupKind.Script,
Description = $"Devices whose scripts report they belong; first reported by “{scriptName}”.",
CreatedUtc = now,
UpdatedUtc = now,
UpdatedBy = $"script:{scriptName}",
};
db.DeviceGroups.Add(group);
named.Add(group);
created.Add(name);
}
var row = await db.DeviceGroupMembers.SingleOrDefaultAsync(m => m.GroupId == group.Id && m.ClientId == clientId, cancellationToken);
if (member && row is null)
{
db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity { GroupId = group.Id, ClientId = clientId, AddedUtc = now });
joined.Add(group.Name);
}
else if (!member && row is not null)
{
db.DeviceGroupMembers.Remove(row);
left.Add(group.Name);
}
}
await db.SaveChangesAsync(cancellationToken);
foreach (var name in created)
{
await audit.LogAsync(AuditCategories.Admin, "group-created", $"script:{scriptName}",
clientId: clientId, detail: $"{name} (Script)", cancellationToken: cancellationToken);
}
if (joined.Count + left.Count > 0)
{
await audit.LogAsync(AuditCategories.Admin, "group-members", $"script:{scriptName}", clientId: clientId,
detail: $"joined={string.Join(", ", joined)} left={string.Join(", ", left)}", cancellationToken: cancellationToken);
}
if (ignored.Count > 0)
{
logger.LogWarning(
"Device {ClientId} reported membership of {Groups} from “{Script}”; ignored: those are not script groups",
clientId, string.Join(", ", ignored), scriptName);
}
return new Outcome(joined, left, created, ignored);
}
}
+5
View File
@@ -155,6 +155,11 @@ public sealed class JobDispatcher(IServiceScopeFactory scopeFactory, ILogger<Job
skips.Add(new RunSkip(device.ClientId, device.Hostname, SkipReasons.Offline));
await RemoveAsync(db, job, cancellationToken);
}
else if (JobRunner.RunAsUserRefusal(snapshot.RunAsUser == true, device.AgentVersion) is { } refusal)
{
// An older agent would ignore Run As Signed-In User and run as its own account.
await FailAsync(runner, job, refusal, tally, cancellationToken);
}
else
{
sendable.Add((job, device));
+44 -4
View File
@@ -118,6 +118,22 @@ public sealed class JobRunner(
return job;
}
/// <summary>
/// Why a job of a Run As Signed-In User script cannot go to an agent at <paramref name="agentVersion"/>
/// (it would ignore the option and run as its own account), or null when it can.
/// </summary>
internal static string? RunAsUserRefusal(bool runAsUser, string? agentVersion)
=> runAsUser && !RunAsUser.Supported(agentVersion) ? RunAsUser.Unsupported(agentVersion) : null;
/// <summary>A job created already failed (never sent).</summary>
private static JobEntity Refused(JobEntity job, string message, DateTimeOffset now)
{
job.State = JobState.Failed;
job.CompletedUtc = now;
job.OutputSummary = message;
return job;
}
private static JobEntity NewJob(ScriptEntity script, string clientId, string? requestedBy, Guid? runId, DateTimeOffset createdUtc) => new()
{
JobId = Guid.NewGuid(),
@@ -192,10 +208,19 @@ public sealed class JobRunner(
foreach (var chunk in devices.Chunk(WriteBatch))
{
var now = DateTimeOffset.UtcNow;
var batch = chunk.Select(d => new Outgoing(NewJob(prepared.Script, d.ClientId, requestedBy, runId, now), activityText(d))).ToList();
// A device whose agent cannot honor Run As Signed-In User gets its job already failed.
var created = chunk.Select(d =>
{
var job = NewJob(prepared.Script, d.ClientId, requestedBy, runId, now);
return (Device: d, Job: RunAsUserRefusal(prepared.Script.RunAsUser, d.AgentVersion) is { } refusal ? Refused(job, refusal, now) : job);
}).ToList();
var batch = created
.Where(c => c.Job.State == JobState.Queued)
.Select(c => new Outgoing(c.Job, activityText(c.Device)))
.ToList();
undecided.UnionWith(batch.Select(o => o.Job));
await InsertAsync(batch.Select(o => o.Job).ToList(), cancellationToken);
jobs.AddRange(batch.Select(o => o.Job));
await InsertAsync(created.Select(c => c.Job).ToList(), cancellationToken);
jobs.AddRange(created.Select(c => c.Job));
var previous = sending;
var sent = publishing is null ? null : await publishing;
@@ -366,7 +391,8 @@ public sealed class JobRunner(
Trigger: trigger,
RestartAfterRun: script.RestartAfterRun,
RestartDelaySeconds: script.RestartDelaySeconds,
RestartWarningSeconds: script.RestartWarningSeconds),
RestartWarningSeconds: script.RestartWarningSeconds,
RunAsUser: script.RunAsUser),
cancellationToken);
}
@@ -604,6 +630,20 @@ public sealed class JobRunner(
DateTimeOffset? notBeforeUtc = null,
JobTrigger? trigger = null)
{
if (prepared.Script.RunAsUser)
{
var agentVersion = await db.Devices.AsNoTracking()
.Where(d => d.ClientId == job.ClientId)
.Select(d => d.AgentVersion)
.FirstOrDefaultAsync(cancellationToken);
if (RunAsUserRefusal(true, agentVersion) is { } refusal)
{
// Settled here: nothing for the dispatcher to retry.
await MarkFailedAsync(job, refusal, cancellationToken);
return true;
}
}
var dispatched = await PublishAsync(prepared, job, arguments, notBeforeUtc, trigger, cancellationToken);
if (dispatched)
+6 -2
View File
@@ -32,7 +32,9 @@ public sealed record RunSnapshot(
DateTimeOffset? NotBeforeUtc = null,
Shared.Contracts.Messages.JobTrigger? Trigger = null,
// Warn Signed-In Users; null in snapshots sealed before it existed (off).
int? RestartWarningSeconds = null)
int? RestartWarningSeconds = null,
// Run as the signed-in user; null in snapshots sealed before it existed (off).
bool? RunAsUser = null)
{
/// <summary>
/// The snapshot of a run; <paramref name="notBeforeUtc"/> and <paramref name="trigger"/> belong to
@@ -58,7 +60,8 @@ public sealed record RunSnapshot(
prepared.Script.RestartDelaySeconds,
notBeforeUtc,
trigger,
prepared.Script.RestartWarningSeconds);
prepared.Script.RestartWarningSeconds,
prepared.Script.RunAsUser);
/// <summary>A detached script entity to prepare and dispatch from.</summary>
public ScriptEntity ToScript() => new()
@@ -77,6 +80,7 @@ public sealed record RunSnapshot(
RestartAfterRun = RestartAfterRun ?? Shared.Contracts.Models.RestartAfterRun.Off,
RestartDelaySeconds = RestartDelaySeconds ?? 0,
RestartWarningSeconds = RestartWarningSeconds ?? 0,
RunAsUser = RunAsUser ?? false,
};
}
+28
View File
@@ -1461,6 +1461,34 @@ public sealed class MessagingWorkers(
await broadcaster.BroadcastActivityAsync(new ActivityEventPayload(
"job-completed", $"Job “{stored.ScriptName}” {payload.State.ToString().ToLowerInvariant()}",
payload.ClientId, payload.JobId, DateTimeOffset.UtcNow), cancellationToken);
// What the script said about its device's script groups, once (a redelivered final state is not applied).
if (stored.Applied && payload.GroupMemberships is { Count: > 0 } reports)
{
await ApplyGroupMembershipsAsync(payload, stored.ScriptName, reports, cancellationToken);
}
}
}
private async Task ApplyGroupMembershipsAsync(
JobStatePayload payload, string scriptName, IReadOnlyList<GroupMembershipReport> reports, CancellationToken cancellationToken)
{
try
{
using var scope = scopeFactory.CreateScope();
var outcome = await scope.ServiceProvider.GetRequiredService<Backend.Groups.ScriptGroupMembership>()
.ApplyAsync(payload.ClientId, scriptName, reports, cancellationToken);
if (outcome.Changed)
{
var parts = outcome.Joined.Select(g => $"joined “{g}”").Concat(outcome.Left.Select(g => $"left “{g}”"));
await broadcaster.BroadcastActivityAsync(new ActivityEventPayload(
"group-membership", $"“{scriptName}”: device {string.Join(", ", parts)}",
payload.ClientId, payload.JobId, DateTimeOffset.UtcNow), cancellationToken);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError(ex, "Job {JobId}: its script group memberships could not be applied", payload.JobId);
}
}
+2 -1
View File
@@ -90,7 +90,7 @@ var logSettings = LogSettings.FromConfiguration(
// The last lines in memory too, for Server Logs in the console.
var liveLog = new LiveLog();
builder.Logging.ClearProviders();
builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "backend", liveLog), dispose: true);
builder.Services.AddSerilog(LoggingSetup.CreateLogger(logSettings, "Server", liveLog), dispose: true);
builder.Services.AddSingleton(new Backend.Logs.ServerLogs(liveLog, logSettings.Directory));
builder.Services.ConfigureHttpJsonOptions(options =>
@@ -157,6 +157,7 @@ builder.Services.AddSingleton(DeviceLifecycleOptions.FromConfiguration(builder.C
builder.Services.AddSingleton<Backend.Groups.InventoryReportCache>();
builder.Services.AddSingleton<Backend.Dashboard.DashboardCache>();
builder.Services.AddScoped<DeviceGroupService>();
builder.Services.AddScoped<Backend.Groups.ScriptGroupMembership>();
builder.Services.AddScoped<ScriptTriggerService>();
builder.Services.AddScoped<Backend.Groups.DeviceRunService>();
+7 -4
View File
@@ -144,6 +144,7 @@ public static class ScriptEndpoints
RestartAfterRun = request.RestartAfterRun ?? RestartAfterRun.Off,
RestartDelaySeconds = request.RestartDelaySeconds ?? 0,
RestartWarningSeconds = request.RestartWarningSeconds ?? 0,
RunAsUser = request.RunAsUser ?? false,
CreatedUtc = now,
UpdatedUtc = now,
CreatedBy = actor,
@@ -220,6 +221,7 @@ public static class ScriptEndpoints
script.RestartAfterRun = request.RestartAfterRun ?? script.RestartAfterRun;
script.RestartDelaySeconds = request.RestartDelaySeconds ?? script.RestartDelaySeconds;
script.RestartWarningSeconds = request.RestartWarningSeconds ?? script.RestartWarningSeconds;
script.RunAsUser = request.RunAsUser ?? script.RunAsUser;
NormalizeOptions(script);
script.UpdatedUtc = DateTimeOffset.UtcNow;
script.UpdatedBy = context.User.Identity?.Name;
@@ -285,15 +287,16 @@ public static class ScriptEndpoints
script.SetWorkingDirectory,
script.RestartAfterRun,
script.RestartDelaySeconds,
script.RestartWarningSeconds);
script.RestartWarningSeconds,
script.RunAsUser);
/// <summary>
/// Set Working Directory needs a staged file: PowerShell 7 stages one only
/// with Run From File (5.1 and Bash always do), so without it the option is off.
/// Set Working Directory needs a staged file: PowerShell 7 stages one only with Run From
/// File or Run As Signed-In User (5.1 and Bash always do), so without either the option is off.
/// </summary>
internal static void NormalizeOptions(ScriptEntity script)
{
if (ParseEngine(script.Language) == ScriptEngine.PowerShell && !script.RunFromFile)
if (ParseEngine(script.Language) == ScriptEngine.PowerShell && !script.RunFromFile && !script.RunAsUser)
{
script.SetWorkingDirectory = false;
}
+6 -4
View File
@@ -40,15 +40,17 @@ public sealed class ShellBridge(
}
/// <summary>
/// Publishes the privileged shell.open command to the agent (<paramref name="shell"/>: a <see cref="ShellKinds"/> value);
/// false when it may not be sent (Require Sealed Agents, and the device does not seal).
/// Publishes the privileged shell.open command to the agent (<paramref name="shell"/>: a <see cref="ShellKinds"/> value;
/// <paramref name="asUser"/>: as the signed-in user); false when it may not be sent (Require Sealed Agents, and the
/// device does not seal).
/// </summary>
public async Task<bool> OpenAsync(ShellBinding binding, int cols, int rows, string? shell, CancellationToken cancellationToken)
public async Task<bool> OpenAsync(
ShellBinding binding, int cols, int rows, string? shell, CancellationToken cancellationToken, bool asUser = false, string? user = null)
{
var envelope = MessageEnvelope.Create(
MessageTypes.CommandShellOpen,
BackendSource,
new ShellOpenCommandPayload(binding.ShellId, cols, rows, shell),
new ShellOpenCommandPayload(binding.ShellId, cols, rows, shell, asUser, asUser ? user : null),
new EndpointRef(EndpointKinds.Agent, binding.ClientId));
if (!await PublishToAgentAsync(binding.ClientId, NatsSubjects.AgentCommandShellOpen(binding.ClientId), envelope, cancellationToken))
+16 -2
View File
@@ -61,6 +61,19 @@ public static class ShellEndpoints
return Results.NotFound();
}
// An older agent would ignore As Signed-In User and start the shell as its own account.
if (request.AsUser && !RunAsUser.Supported(device.AgentVersion))
{
return Results.Problem(statusCode: StatusCodes.Status409Conflict, title: RunAsUser.Unsupported(device.AgentVersion));
}
// A chosen signed-in user: a plain account name (a Windows domain account or a unix name), never a path or a list.
var user = string.IsNullOrWhiteSpace(request.User) ? null : request.User.Trim();
if (user is not null && (!request.AsUser || user.Length > 256 || user.Any(c => char.IsControl(c) || c is '/' or ':' or ',' or '"')))
{
return Results.BadRequest(new { error = "User must name one signed-in user, with Run As Signed-In User." });
}
var shellId = Guid.NewGuid();
var actor = context.User.Identity?.Name;
@@ -75,7 +88,8 @@ public static class ShellEndpoints
await db.SaveChangesAsync(cancellationToken);
var binding = bridge.Register(shellId, clientId, request.BrowserSessionId);
if (!await bridge.OpenAsync(binding, Math.Clamp(request.Cols, 1, 500), Math.Clamp(request.Rows, 1, 200), shell, cancellationToken))
if (!await bridge.OpenAsync(
binding, Math.Clamp(request.Cols, 1, 500), Math.Clamp(request.Rows, 1, 200), shell, cancellationToken, request.AsUser, user))
{
return Results.Problem(
statusCode: StatusCodes.Status409Conflict,
@@ -84,7 +98,7 @@ public static class ShellEndpoints
// The requested shell lives in the audit detail (the session row has no column for it).
await audit.LogAsync(AuditCategories.Shell, "opened", actor,
clientId: clientId, detail: $"shell={shellId} kind={shell}",
clientId: clientId, detail: $"shell={shellId} kind={shell} as={(request.AsUser ? user ?? "signed-in-user" : "agent")}",
remoteIp: Proxy.ClientIp.EffectiveText(context), cancellationToken: cancellationToken);
return Results.Ok(new CreateShellResponse(
+1 -1
View File
@@ -32,7 +32,7 @@ rayon = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "std"] }
tracing-subscriber = { version = "0.3", default-features = false, features = ["registry", "std"] }
[target.'cfg(windows)'.dependencies.windows]
version = "0.62"
+14 -1
View File
@@ -70,7 +70,20 @@ TLS). The username and password the client sends are ignored.
### stderr
Human log lines, plus machine events as single lines `@event <json>`:
Log lines in ExecuteR's one log format (`src/logging.rs`; see the root README, *Log line format*):
```text
[2026-11-16T17:53:40.653Z] - [ScreenHost] - [WARN] - hardware H.264 encoder failed; using software reason="MFT busy"
```
UTC time to the millisecond, the category `ScreenHost` (a dependency's events carry its crate name,
such as `ironrdp_server`), the level (`TRACE` … `ERROR`), the message and the event's fields as
`key=value`. A warning or error that repeats is written once, then counted for 60 s; the window's
end writes one line with `repeated=N window=60s` (the last of them), and a quiet window forgets it.
Counts still open are written before the host exits. The agent logs each such line once, under the
host's category and level with this prefix taken off, so its own file has no second timestamp.
Plus machine events as single lines `@event <json>`:
| Event | When |
|---|---|
+9 -2
View File
@@ -11,6 +11,7 @@ pub mod events;
pub mod geometry;
pub mod input;
pub mod keymap;
pub mod logging;
pub mod mux;
pub mod platform;
pub mod rdcleanpath;
@@ -18,7 +19,8 @@ pub mod session;
pub mod tls;
pub mod video;
/// Initialises stderr logging at the given level.
/// Initialises stderr logging at the given level, in ExecuteR's one log format with
/// repeated warnings and errors bounded (see [`logging`]).
pub fn init_logging(level: cli::LogLevel) {
use tracing_subscriber::filter::LevelFilter;
let filter = match level {
@@ -27,5 +29,10 @@ pub fn init_logging(level: cli::LogLevel) {
cli::LogLevel::Info => LevelFilter::INFO,
cli::LogLevel::Debug => LevelFilter::DEBUG,
};
let _ = tracing_subscriber::fmt().with_writer(std::io::stderr).with_ansi(false).with_max_level(filter).try_init();
logging::init(filter);
}
/// Writes the repeat counts still open; call before the process exits.
pub fn flush_logging() {
logging::flush();
}
+515
View File
@@ -0,0 +1,515 @@
//! The host's log lines on stderr, in ExecuteR's one log format:
//!
//! ```text
//! [2026-11-16T17:53:40.653Z] - [ScreenHost] - [WARN] - hardware H.264 encoder failed; using software reason="MFT busy"
//! ```
//!
//! UTC to the millisecond; the category `ScreenHost` (or the crate an event comes from, such as
//! `ironrdp_server`); TRACE, DEBUG, INFO, WARN or ERROR; the message, then the event's fields as
//! `key=value` (a value with whitespace, `=` or `"` double-quoted). The agent reads these lines
//! from stderr and logs each again under the host's category and level, without this prefix.
//!
//! A warning or error that repeats is written once; the same one again within a minute is
//! counted, and when the minute ends with any counted ONE line says so: the last of them with
//! `repeated=N window=60s`. A quiet minute forgets it (see [`Throttle`]).
use std::collections::HashMap;
use std::fmt::{self, Write as _};
use std::io::Write as _;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tracing::field::{Field, Visit};
use tracing::{Event, Level, Subscriber};
use tracing_subscriber::layer::{Context, Layer};
/// The category of the host's own lines.
pub const CATEGORY: &str = "ScreenHost";
/// How long repeats are counted before one summary line.
pub const REPEAT_WINDOW: Duration = Duration::from_secs(60);
/// How many distinct warnings and errors are tracked at once (the oldest goes first).
pub const MAX_KEYS: usize = 1000;
/// `2026-11-16T17:53:40.653Z`.
pub fn format_timestamp(time: SystemTime) -> String {
let since = time.duration_since(UNIX_EPOCH).unwrap_or_default();
let secs = since.as_secs();
let (year, month, day) = civil_from_days((secs / 86_400) as i64);
let rest = secs % 86_400;
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
rest / 3600,
rest % 3600 / 60,
rest % 60,
since.subsec_millis()
)
}
/// Days since 1970-01-01 as a proleptic Gregorian date (H. Hinnant's `civil_from_days`).
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
let year = yoe + era * 400 + i64::from(month <= 2);
(year, month, day)
}
/// The level as the line spells it.
pub fn level_name(level: Level) -> &'static str {
match level {
Level::TRACE => "TRACE",
Level::DEBUG => "DEBUG",
Level::INFO => "INFO",
Level::WARN => "WARN",
_ => "ERROR",
}
}
/// `ScreenHost` for the host's own code, the crate's name for a dependency's (`ironrdp_server`).
pub fn category(target: &str) -> String {
let krate = target.split("::").next().unwrap_or_default();
if krate.is_empty() || krate.to_ascii_lowercase().starts_with("executer_screen") {
CATEGORY.to_owned()
} else {
krate.to_owned()
}
}
/// A field value as a line shows it: bare, or double-quoted (escaping `"` and control
/// characters) when it is empty or holds whitespace, `=` or `"`.
pub fn quote(value: &str) -> String {
if !value.is_empty() && !value.chars().any(|c| c.is_whitespace() || c == '=' || c == '"' || c.is_control()) {
return value.to_owned();
}
let mut quoted = String::with_capacity(value.len() + 2);
quoted.push('"');
for c in value.chars() {
match c {
'"' => quoted.push_str("\\\""),
'\n' => quoted.push_str("\\n"),
'\r' => quoted.push_str("\\r"),
'\t' => quoted.push_str("\\t"),
c if c.is_control() => {
let _ = write!(quoted, "\\u{:04x}", u32::from(c));
}
c => quoted.push(c),
}
}
quoted.push('"');
quoted
}
/// What one line says, before its time is put on it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Line {
pub level: Level,
pub category: String,
/// The message and its `key=value` fields.
pub text: String,
}
impl Line {
/// The whole line, without its newline.
pub fn format(&self, time: SystemTime) -> String {
format!("[{}] - [{}] - [{}] - {}", format_timestamp(time), self.category, level_name(self.level), self.text)
}
}
/// Collects an event's message and its fields as `key=value`.
#[derive(Default)]
struct Fields {
message: String,
rest: String,
}
impl Fields {
fn push(&mut self, field: &Field, value: &str) {
if field.name() == "message" {
self.message.push_str(value);
} else {
let _ = write!(self.rest, " {}={}", field.name(), quote(value));
}
}
fn into_text(self) -> String {
self.message + &self.rest
}
}
impl Visit for Fields {
fn record_str(&mut self, field: &Field, value: &str) {
self.push(field, value);
}
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
self.push(field, &format!("{value:?}"));
}
}
/// What tells one warning from another: its level and where it is logged (target and callsite).
pub type Key = (Level, &'static str, &'static str);
struct Entry {
start: Instant,
order: u64,
suppressed: u64,
last: Option<Line>,
}
/// Bounds repeated warnings and errors: the first is written, the same one again within the
/// window is counted, the window's end writes one summary of what was counted and starts the
/// next, and a window with nothing counted forgets the key. Time comes in as an argument.
pub struct Throttle {
window: Duration,
max_keys: usize,
entries: HashMap<Key, Entry>,
order: u64,
}
impl Throttle {
pub fn new(window: Duration, max_keys: usize) -> Self {
Self { window, max_keys: max_keys.max(1), entries: HashMap::new(), order: 0 }
}
/// How many keys are tracked now.
pub fn tracked(&self) -> usize {
self.entries.len()
}
/// A warning or error at `now`: the lines to write (summaries first, then the line itself
/// unless it is held back as a repeat).
pub fn admit(&mut self, key: Key, now: Instant, line: Line) -> Vec<Line> {
let mut out = Vec::new();
if let Some(entry) = self.entries.get_mut(&key)
&& now.saturating_duration_since(entry.start) >= self.window
{
match Self::close(entry, now, self.window) {
Some(summary) => out.push(summary),
None => {
self.entries.remove(&key);
}
}
}
if let Some(entry) = self.entries.get_mut(&key) {
entry.suppressed += 1;
entry.last = Some(line);
return out;
}
if self.entries.len() >= self.max_keys
&& let Some(oldest) = self.entries.iter().min_by_key(|(_, e)| e.order).map(|(k, _)| *k)
&& let Some(evicted) = self.entries.remove(&oldest)
&& let Some(summary) = Self::summary(&evicted, self.window)
{
out.push(summary);
}
self.order += 1;
self.entries.insert(key, Entry { start: now, order: self.order, suppressed: 0, last: None });
out.push(line);
out
}
/// Ends every window that is over at `now`: the summaries to write.
pub fn sweep(&mut self, now: Instant) -> Vec<Line> {
let window = self.window;
let mut out = Vec::new();
self.entries.retain(|_, entry| {
if now.saturating_duration_since(entry.start) < window {
return true;
}
match Self::close(entry, now, window) {
Some(summary) => {
out.push(summary);
true
}
None => false,
}
});
out
}
/// Every count still open (at exit), oldest key first; nothing is tracked afterwards.
pub fn drain(&mut self) -> Vec<Line> {
let mut entries: Vec<Entry> = self.entries.drain().map(|(_, e)| e).collect();
entries.sort_by_key(|e| e.order);
entries.iter().filter_map(|e| Self::summary(e, self.window)).collect()
}
fn close(entry: &mut Entry, now: Instant, window: Duration) -> Option<Line> {
let summary = Self::summary(entry, window)?;
entry.start = now;
entry.suppressed = 0;
entry.last = None;
Some(summary)
}
fn summary(entry: &Entry, window: Duration) -> Option<Line> {
let last = entry.last.as_ref().filter(|_| entry.suppressed > 0)?;
let mut line = last.clone();
let _ = write!(line.text, " repeated={} window={}", entry.suppressed, format_window(window));
Some(line)
}
}
/// `60s`, `1.5s`, `250ms`.
pub fn format_window(window: Duration) -> String {
if window >= Duration::from_secs(1) {
let secs = window.as_secs_f64();
if secs.fract() == 0.0 { format!("{}s", window.as_secs()) } else { format!("{secs}s") }
} else {
format!("{}ms", window.as_millis())
}
}
type LineSink = Box<dyn Fn(&str) + Send + Sync>;
/// Where lines go (stderr, or a test's sink) and the repeat throttle in front of it.
pub struct HostLog {
throttle: Mutex<Throttle>,
sink: LineSink,
}
impl HostLog {
pub fn new(sink: LineSink) -> Self {
Self { throttle: Mutex::new(Throttle::new(REPEAT_WINDOW, MAX_KEYS)), sink }
}
/// Writes to stderr, one whole line per write.
pub fn stderr() -> Self {
Self::new(Box::new(|line| {
let mut stderr = std::io::stderr().lock();
let _ = stderr.write_all(format!("{line}\n").as_bytes());
let _ = stderr.flush();
}))
}
fn throttle(&self) -> std::sync::MutexGuard<'_, Throttle> {
self.throttle.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn write(&self, lines: Vec<Line>) {
let now = SystemTime::now();
for line in lines {
(self.sink)(&line.format(now));
}
}
/// One event's line: warnings and errors through the throttle, the rest straight out.
pub fn log(&self, key: Key, line: Line) {
if matches!(line.level, Level::WARN | Level::ERROR) {
let lines = self.throttle().admit(key, Instant::now(), line);
self.write(lines);
} else {
self.write(vec![line]);
}
}
/// Writes the summaries of windows that are over.
pub fn sweep(&self) {
let lines = self.throttle().sweep(Instant::now());
self.write(lines);
}
/// Writes every count still open (before the process exits).
pub fn flush(&self) {
let lines = self.throttle().drain();
self.write(lines);
}
}
/// The `tracing` layer that writes each event through a [`HostLog`].
pub struct HostLayer(pub Arc<HostLog>);
impl<S: Subscriber> Layer<S> for HostLayer {
fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
let metadata = event.metadata();
let mut fields = Fields::default();
event.record(&mut fields);
let line = Line { level: *metadata.level(), category: category(metadata.target()), text: fields.into_text() };
self.0.log((*metadata.level(), metadata.target(), metadata.name()), line);
}
}
static HOST_LOG: OnceLock<Arc<HostLog>> = OnceLock::new();
/// Installs stderr logging at `filter`, with a thread that writes repeat summaries as windows end.
pub fn init(filter: tracing_subscriber::filter::LevelFilter) {
use tracing_subscriber::layer::SubscriberExt as _;
use tracing_subscriber::util::SubscriberInitExt as _;
let log = Arc::clone(HOST_LOG.get_or_init(|| Arc::new(HostLog::stderr())));
if tracing_subscriber::registry().with(filter).with(HostLayer(Arc::clone(&log))).try_init().is_ok() {
let _ = std::thread::Builder::new().name("log-repeats".into()).spawn(move || {
loop {
std::thread::sleep(Duration::from_secs(1));
log.sweep();
}
});
}
}
/// Writes every repeat count still open; call before the process exits.
pub fn flush() {
if let Some(log) = HOST_LOG.get() {
log.flush();
}
}
#[cfg(test)]
mod tests {
use super::*;
use tracing_subscriber::layer::SubscriberExt as _;
fn line(level: Level, text: &str) -> Line {
Line { level, category: CATEGORY.to_owned(), text: text.to_owned() }
}
fn texts(lines: &[Line]) -> Vec<&str> {
lines.iter().map(|l| l.text.as_str()).collect()
}
const A: Key = (Level::WARN, "executer_screen::video", "event src/video.rs:94");
const B: Key = (Level::WARN, "executer_screen::video", "event src/video.rs:245");
const C: Key = (Level::ERROR, "executer_screen::session", "event src/session.rs:70");
#[test]
fn timestamps_are_utc_iso_with_milliseconds() {
assert_eq!(format_timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
assert_eq!(format_timestamp(UNIX_EPOCH + Duration::from_millis(1_794_851_620_653)), "2026-11-16T17:53:40.653Z");
assert_eq!(format_timestamp(UNIX_EPOCH + Duration::from_millis(1_709_251_199_999)), "2024-02-29T23:59:59.999Z");
assert_eq!(format_timestamp(UNIX_EPOCH + Duration::from_secs(951_868_800)), "2000-03-01T00:00:00.000Z");
}
#[test]
fn a_line_is_time_category_level_message() {
let l = Line { level: Level::WARN, category: "ScreenHost".into(), text: "slow reason=\"a b\"".into() };
assert_eq!(
l.format(UNIX_EPOCH + Duration::from_millis(1_794_851_620_653)),
"[2026-11-16T17:53:40.653Z] - [ScreenHost] - [WARN] - slow reason=\"a b\""
);
assert_eq!(level_name(Level::TRACE), "TRACE");
assert_eq!(level_name(Level::DEBUG), "DEBUG");
assert_eq!(level_name(Level::INFO), "INFO");
assert_eq!(level_name(Level::ERROR), "ERROR");
}
#[test]
fn values_are_quoted_only_when_they_must_be() {
assert_eq!(quote("plain"), "plain");
assert_eq!(quote("C:\\Windows"), "C:\\Windows");
assert_eq!(quote("two words"), "\"two words\"");
assert_eq!(quote("a=b"), "\"a=b\"");
assert_eq!(quote("say \"hi\""), "\"say \\\"hi\\\"\"");
assert_eq!(quote("line\nnext"), "\"line\\nnext\"");
assert_eq!(quote(""), "\"\"");
}
#[test]
fn the_category_is_screenhost_or_the_crate() {
assert_eq!(category("executer_screen::platform::windows::dxgi"), "ScreenHost");
assert_eq!(category("ExecuteR_Screen"), "ScreenHost");
assert_eq!(category("ironrdp_server::server"), "ironrdp_server");
assert_eq!(category(""), "ScreenHost");
}
#[test]
fn the_window_reads_short() {
assert_eq!(format_window(Duration::from_secs(60)), "60s");
assert_eq!(format_window(Duration::from_millis(1500)), "1.5s");
assert_eq!(format_window(Duration::from_millis(250)), "250ms");
}
#[test]
fn the_first_is_written_repeats_are_counted_and_the_window_ends_with_one_summary() {
let mut throttle = Throttle::new(REPEAT_WINDOW, MAX_KEYS);
let t0 = Instant::now();
assert_eq!(texts(&throttle.admit(A, t0, line(Level::WARN, "slow 1"))), ["slow 1"]);
for i in 2..=5 {
assert!(throttle.admit(A, t0 + Duration::from_secs(i), line(Level::WARN, &format!("slow {i}"))).is_empty());
}
assert!(throttle.sweep(t0 + Duration::from_secs(59)).is_empty());
assert_eq!(texts(&throttle.sweep(t0 + Duration::from_secs(60))), ["slow 5 repeated=4 window=60s"]);
}
#[test]
fn it_keeps_summarizing_once_per_window_and_a_quiet_window_starts_over() {
let mut throttle = Throttle::new(REPEAT_WINDOW, MAX_KEYS);
let t0 = Instant::now();
throttle.admit(C, t0, line(Level::ERROR, "broke 1"));
throttle.admit(C, t0, line(Level::ERROR, "broke 2"));
assert_eq!(texts(&throttle.sweep(t0 + REPEAT_WINDOW)), ["broke 2 repeated=1 window=60s"]);
let t1 = t0 + REPEAT_WINDOW;
assert!(throttle.admit(C, t1, line(Level::ERROR, "broke 3")).is_empty());
assert!(throttle.admit(C, t1, line(Level::ERROR, "broke 4")).is_empty());
assert_eq!(texts(&throttle.sweep(t1 + REPEAT_WINDOW)), ["broke 4 repeated=2 window=60s"]);
let t2 = t1 + REPEAT_WINDOW;
assert!(throttle.sweep(t2 + REPEAT_WINDOW).is_empty());
assert_eq!(throttle.tracked(), 0);
assert_eq!(texts(&throttle.admit(C, t2 + REPEAT_WINDOW, line(Level::ERROR, "broke 5"))), ["broke 5"]);
}
#[test]
fn a_repeat_after_the_window_without_a_sweep_gets_its_summary_first() {
let mut throttle = Throttle::new(REPEAT_WINDOW, MAX_KEYS);
let t0 = Instant::now();
throttle.admit(A, t0, line(Level::WARN, "slow 1"));
throttle.admit(A, t0, line(Level::WARN, "slow 2"));
let later = t0 + REPEAT_WINDOW + Duration::from_secs(1);
assert_eq!(texts(&throttle.admit(A, later, line(Level::WARN, "slow 3"))), ["slow 2 repeated=1 window=60s"]);
assert_eq!(texts(&throttle.drain()), ["slow 3 repeated=1 window=60s"]);
}
#[test]
fn keys_tell_events_apart_and_the_table_is_bounded() {
let mut throttle = Throttle::new(REPEAT_WINDOW, 2);
let t0 = Instant::now();
assert_eq!(texts(&throttle.admit(A, t0, line(Level::WARN, "a 1"))), ["a 1"]);
assert!(throttle.admit(A, t0, line(Level::WARN, "a 2")).is_empty());
assert_eq!(texts(&throttle.admit(B, t0, line(Level::WARN, "b 1"))), ["b 1"]);
assert_eq!(texts(&throttle.admit(C, t0, line(Level::ERROR, "c 1"))), ["a 2 repeated=1 window=60s", "c 1"]);
assert_eq!(throttle.tracked(), 2);
}
#[test]
fn the_layer_writes_the_format_and_bounds_repeats() {
let written = Arc::new(Mutex::new(Vec::<String>::new()));
let sink = Arc::clone(&written);
let log = Arc::new(HostLog::new(Box::new(move |l| sink.lock().unwrap().push(l.to_owned()))));
let subscriber = tracing_subscriber::registry().with(HostLayer(Arc::clone(&log)));
tracing::subscriber::with_default(subscriber, || {
tracing::info!(monitor = ?Some(1), name = "DISPLAY 1", "starting screen host");
for count in 0..3 {
tracing::warn!(reason = "MFT busy", count, "hardware H.264 encoder failed; using software");
}
});
log.flush();
let lines = written.lock().unwrap().clone();
assert_eq!(lines.len(), 3, "{lines:?}");
assert!(
lines[0].ends_with("] - [ScreenHost] - [INFO] - starting screen host monitor=Some(1) name=\"DISPLAY 1\""),
"{}",
lines[0]
);
assert!(lines[0].starts_with('['));
assert!(
lines[1].ends_with(
"] - [ScreenHost] - [WARN] - hardware H.264 encoder failed; using software reason=\"MFT busy\" count=0"
),
"{}",
lines[1]
);
assert!(lines[2].ends_with(" reason=\"MFT busy\" count=2 repeated=2 window=60s"), "{}", lines[2]);
}
}
+2
View File
@@ -42,6 +42,7 @@ fn main() -> ExitCode {
Command::Probe { log_level } => {
executer_screen::init_logging(log_level);
let report = platform::probe();
executer_screen::flush_logging();
match serde_json::to_string(&report) {
Ok(json) => println!("{json}"),
Err(e) => {
@@ -54,6 +55,7 @@ fn main() -> ExitCode {
Command::Serve(args) => {
executer_screen::init_logging(args.log_level);
let code = serve(&args);
executer_screen::flush_logging();
// Exit right away: a blocking stdin read must not keep the process alive.
std::process::exit(i32::from(code));
}
+15 -4
View File
@@ -348,7 +348,8 @@ public sealed record ScriptDto(
bool SetWorkingDirectory = false,
RestartAfterRun RestartAfterRun = RestartAfterRun.Off,
int RestartDelaySeconds = 0,
int RestartWarningSeconds = 0);
int RestartWarningSeconds = 0,
bool RunAsUser = false);
/// <summary>
/// POST/PUT /api/scripts request body. <c>Folder</c> places the script ("/"
@@ -358,6 +359,8 @@ public sealed record ScriptDto(
/// (0 to <see cref="RestartOptions.MaxDelaySeconds"/>) and <c>RestartWarningSeconds</c> (Warn
/// Signed-In Users: 0 for off, otherwise <see cref="RestartOptions.MinWarningSeconds"/> to
/// <see cref="RestartOptions.MaxWarningSeconds"/>) left out keep theirs too (off, 0 and off).
/// <c>RunAsUser</c> (run as the signed-in user instead of the agent's account) left out keeps
/// the stored value (off for a new script).
/// </summary>
public sealed record SaveScriptRequest(
string Name,
@@ -378,7 +381,8 @@ public sealed record SaveScriptRequest(
bool? SetWorkingDirectory = null,
RestartAfterRun? RestartAfterRun = null,
int? RestartDelaySeconds = null,
int? RestartWarningSeconds = null);
int? RestartWarningSeconds = null,
bool? RunAsUser = null);
/// <summary>A folder of a library (scripts, functions).</summary>
public sealed record FolderDto(string Path, string Name);
@@ -608,12 +612,19 @@ public sealed record JobOutputRecordDto(
DateTimeOffset TimestampUtc,
string Text);
/// <summary>POST /api/devices/{clientId}/shell request body; <c>Shell</c> is a <see cref="ShellKinds"/> value (null = automatic).</summary>
/// <summary>
/// POST /api/devices/{clientId}/shell request body; <c>Shell</c> is a <see cref="ShellKinds"/> value (null = automatic).
/// <c>AsUser</c> starts it as the device's signed-in user instead of the agent's account;
/// <c>User</c> names which of them (one the agent listed as signed in; null = the console's user,
/// else the only one).
/// </summary>
public sealed record CreateShellRequest(
string BrowserSessionId,
int Cols,
int Rows,
string? Shell = null);
string? Shell = null,
bool AsUser = false,
string? User = null);
/// <summary>POST /api/devices/{clientId}/shell response body.</summary>
public sealed record CreateShellResponse(
+21 -6
View File
@@ -101,6 +101,9 @@ public sealed record ScriptFileDelivery(
/// <see cref="RestartOptions.MinWarningSeconds"/> to <see cref="RestartOptions.MaxWarningSeconds"/>)
/// is the system's warning to signed-in users when the restart comes due and someone is signed
/// in. Older agents ignore it and hand the delay to the system as its grace period.
/// <see cref="RunAsUser"/> runs the script as the device's signed-in user (out of process,
/// whatever the engine); the server never sends it to agents older than
/// <see cref="Shared.Contracts.Models.RunAsUser.MinimumAgentVersion"/>, which would ignore it.
/// </summary>
public sealed record ScriptCommandPayload(
Guid JobId,
@@ -125,7 +128,8 @@ public sealed record ScriptCommandPayload(
JobTrigger? Trigger = null,
RestartAfterRun RestartAfterRun = RestartAfterRun.Off,
int RestartDelaySeconds = 0,
int RestartWarningSeconds = 0)
int RestartWarningSeconds = 0,
bool RunAsUser = false)
{
/// <summary>The command's Restart After Run as one record.</summary>
[System.Text.Json.Serialization.JsonIgnore]
@@ -271,7 +275,8 @@ public sealed record JobStatePayload(
int? RestartDelaySeconds = null,
string? RestartMessage = null,
DateTimeOffset? RestartBootUtc = null,
DateTimeOffset? RestartDueUtc = null);
DateTimeOffset? RestartDueUtc = null,
IReadOnlyList<GroupMembershipReport>? GroupMemberships = null);
/// <summary>
/// A job's restart: a request on the agent event subject (<see cref="MessageTypes.AgentJobRestart"/>),
@@ -331,13 +336,18 @@ public sealed record RestartCancelCommandPayload(Guid JobId, string Message, str
/// <summary>
/// Opens a remote shell; sent on <c>agent.&lt;clientId&gt;.command.shell.open</c>.
/// <c>Shell</c> is a <see cref="ShellKinds"/> value (null = automatic); unix
/// agents, and agents that predate it, ignore it.
/// agents, and agents that predate it, ignore it. <c>AsUser</c> starts the shell as the
/// signed-in user; the server refuses it for agents older than
/// <see cref="Shared.Contracts.Models.RunAsUser.MinimumAgentVersion"/>. <c>User</c> picks which
/// signed-in user (refused unless they are signed in); null applies the usual rule.
/// </summary>
public sealed record ShellOpenCommandPayload(
Guid SessionId,
int Cols,
int Rows,
string? Shell = null);
string? Shell = null,
bool AsUser = false,
string? User = null);
/// <summary>Terminal input bytes (base64) for an open shell session.</summary>
public sealed record ShellInputPayload(
@@ -363,13 +373,18 @@ public sealed record ShellOutputPayload(
/// <summary>
/// Shell session state on <c>agent.&lt;clientId&gt;.shell.&lt;sessionId&gt;.state</c>.
/// <c>Shell</c> is the <see cref="ShellKinds"/> value started (Windows agents, on <c>Open</c>).
/// <c>Shell</c> is the <see cref="ShellKinds"/> value started (Windows agents, on <c>Open</c>);
/// <c>User</c> the account it runs as when started as the signed-in user. <c>SignedInUsers</c>
/// lists who is signed in on the device (on <c>Open</c>, and on a <c>Failed</c> run-as-user open),
/// for the console to offer.
/// </summary>
public sealed record ShellStatePayload(
Guid SessionId,
ShellSessionState State,
string? Message,
string? Shell = null);
string? Shell = null,
string? User = null,
IReadOnlyList<string>? SignedInUsers = null);
/// <summary>System event: a device enrolled.</summary>
public sealed record AgentEnrolledEvent(
+37 -2
View File
@@ -2,16 +2,51 @@ namespace Shared.Contracts.Models;
/// <summary>
/// Static groups hold an explicit member list; dynamic groups evaluate rules;
/// folders hold no devices of their own and only organize nested groups.
/// Every kind also includes the devices of the groups nested under it.
/// folders hold no devices of their own and only organize nested groups;
/// script groups hold the devices whose scripts last reported them members
/// (<see cref="ScriptGroups"/>). Every kind also includes the devices of the
/// groups nested under it.
/// </summary>
public enum GroupKind
{
Static,
Dynamic,
Folder,
Script,
}
/// <summary>
/// Script groups: a script on the device says whether the device belongs (the built-in
/// <c>Set-ExecuteRGroupMembership</c>, or <c>executer_group</c> in Bash), the agent sends that with
/// the job's final state, and the server adds or removes the device, creating the group the first
/// time a device joins it. Each run says it again, so membership follows the device.
/// </summary>
public static class ScriptGroups
{
/// <summary>The line the built-ins write; the agent takes it out of the output.</summary>
public const string Marker = "::executer-group::";
/// <summary>The most groups one job may report on (the rest are ignored).</summary>
public const int MaxReportsPerJob = 25;
public const int MaxNameLength = 100;
/// <summary>Kinds whose members are rows (static, script), not rules.</summary>
public static bool HasMemberRows(GroupKind kind) => kind is GroupKind.Static or GroupKind.Script;
/// <summary>A usable group name (trimmed, no control characters or slashes, 1 to 100 long), or null.</summary>
public static string? Normalize(string? name)
{
var trimmed = name?.Trim();
return string.IsNullOrEmpty(trimmed) || trimmed.Length > MaxNameLength || trimmed.Any(c => char.IsControl(c) || c is '/' or '\\')
? null
: trimmed;
}
}
/// <summary>A device's own report that it belongs (or no longer belongs) in the named script group.</summary>
public sealed record GroupMembershipReport(string Group, bool Member);
/// <summary>How sibling conditions (or sibling groups) combine.</summary>
public enum RuleCombine
{
+19
View File
@@ -0,0 +1,19 @@
namespace Shared.Contracts.Models;
/// <summary>
/// Running a shell or a script as the device's signed-in user instead of the agent's own
/// account (LocalSystem, root). Agents older than <see cref="MinimumAgentVersion"/> ignore the
/// request and would run as the agent's account, so the server refuses it for them.
/// </summary>
public static class RunAsUser
{
/// <summary>The first agent version that honors the request.</summary>
public const string MinimumAgentVersion = "1.13.0";
/// <summary>True when an agent at <paramref name="agentVersion"/> honors the request.</summary>
public static bool Supported(string? agentVersion) => AgentVersions.Compare(agentVersion, MinimumAgentVersion) >= 0;
/// <summary>Why an agent at <paramref name="agentVersion"/> cannot run as the signed-in user.</summary>
public static string Unsupported(string? agentVersion) =>
$"The agent ({(string.IsNullOrWhiteSpace(agentVersion) ? "unknown version" : agentVersion)}) cannot run as the signed-in user; upgrade it to {MinimumAgentVersion} or later.";
}
@@ -1,25 +1,24 @@
using System.Globalization;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting.Display;
using Shared.Contracts.Api;
namespace Shared.Infrastructure.Logging;
/// <summary>Feeds every event the logger writes into a <see cref="LiveLog"/>, rendered as the log file renders it.</summary>
public sealed class LiveLogSink(LiveLog live) : ILogEventSink
/// <summary>
/// Feeds every event the logger writes into a <see cref="LiveLog"/>, rendered as the log file
/// renders it (the message, then its unused properties as <c>key=value</c>). The source is the
/// full SourceContext, or the application when there is none; a viewer shortens it to the
/// category as <see cref="LogLineFormatter.Category(string?, string)"/> does.
/// </summary>
public sealed class LiveLogSink(LiveLog live, string? application = null) : ILogEventSink
{
private static readonly MessageTemplateTextFormatter Message = new("{Message:lj}", CultureInfo.InvariantCulture);
public void Emit(LogEvent logEvent)
{
using var text = new StringWriter(CultureInfo.InvariantCulture);
Message.Format(logEvent, text);
live.Append(
logEvent.Timestamp.ToUniversalTime(),
LevelName(logEvent.Level),
logEvent.Properties.TryGetValue("SourceContext", out var source) && source is ScalarValue { Value: string name } ? name : null,
text.ToString(),
LogLineFormatter.SourceContext(logEvent) ?? application,
LogLineFormatter.RenderMessage(logEvent),
logEvent.Exception?.ToString());
}
@@ -0,0 +1,259 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Json;
using Shared.Contracts.Api;
namespace Shared.Infrastructure.Logging;
/// <summary>
/// ExecuteR's one text log format, for every line any of its processes writes:
/// <c>[2026-11-16T17:53:40.653Z] - [Category] - [LEVEL] - message key=value …</c>.
/// The time is UTC to the millisecond; the category is a short component name (the
/// logging type without its namespace); the level is TRACE, DEBUG, INFO, WARN, ERROR or
/// FATAL; the message is rendered with its strings unquoted, followed by the event's
/// properties the message did not use, as <c>key=value</c> (correlation fields among
/// them; enrichment noise left out). An exception follows on the next lines.
/// </summary>
public sealed partial class LogLineFormatter(string application) : ITextFormatter
{
/// <summary>The timestamp as written: UTC, ISO 8601, milliseconds, Z.</summary>
public const string TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss.fff'Z'";
/// <summary>Properties that say nothing a reader of one line needs (the file already names its machine and process).</summary>
public static readonly IReadOnlySet<string> Unlisted = new HashSet<string>(StringComparer.Ordinal)
{
"SourceContext", "MachineName", "Application", "EventId",
"RequestId", "RequestPath", "ConnectionId", "ActionId", "ActionName",
"SpanId", "TraceId", "ParentId", "Scope", "ThreadId", "ProcessId",
};
private static readonly JsonValueFormatter Json = new(typeTagName: null);
public void Format(LogEvent logEvent, TextWriter output)
{
WriteLine(
output,
logEvent.Timestamp,
Category(logEvent, application),
LevelName(logEvent.Level),
RenderMessage(logEvent));
if (logEvent.Exception is not null)
{
output.Write(logEvent.Exception.ToString());
output.Write(Environment.NewLine);
}
}
/// <summary>One whole line, its newline included.</summary>
public static void WriteLine(TextWriter output, DateTimeOffset timestamp, string category, string level, string message)
{
output.Write('[');
output.Write(timestamp.UtcDateTime.ToString(TimestampFormat, CultureInfo.InvariantCulture));
output.Write("] - [");
output.Write(category);
output.Write("] - [");
output.Write(level);
output.Write("] - ");
output.Write(message);
output.Write(Environment.NewLine);
}
/// <summary>One whole line, without its newline.</summary>
public static string Line(DateTimeOffset timestamp, string category, string level, string message)
{
using var text = new StringWriter(CultureInfo.InvariantCulture);
WriteLine(text, timestamp, category, level, message);
return text.ToString().TrimEnd('\r', '\n');
}
/// <summary>The level as the line spells it.</summary>
public static string LevelName(LogEventLevel level) => level switch
{
LogEventLevel.Verbose => "TRACE",
LogEventLevel.Debug => "DEBUG",
LogEventLevel.Information => "INFO",
LogEventLevel.Warning => "WARN",
LogEventLevel.Error => "ERROR",
_ => "FATAL",
};
/// <summary>The level as the line spells it, from a <see cref="LogLevels"/> name.</summary>
public static string LevelName(string level) => level switch
{
LogLevels.Verbose => "TRACE",
LogLevels.Debug => "DEBUG",
LogLevels.Warning => "WARN",
LogLevels.Error => "ERROR",
LogLevels.Fatal => "FATAL",
_ => "INFO",
};
/// <summary>The event's category: its SourceContext shortened, or the application.</summary>
public static string Category(LogEvent logEvent, string application)
=> Category(SourceContext(logEvent), application);
/// <summary>
/// A short component name from a logger's category: the type name without its
/// namespace or generic arguments, a nested type as <c>Outer.Inner</c>
/// (<c>Agent.Screen.ScreenHost+Session</c> is <c>ScreenHost.Session</c>). Nothing → <paramref name="fallback"/>.
/// </summary>
public static string Category(string? sourceContext, string fallback)
{
if (string.IsNullOrWhiteSpace(sourceContext))
{
return fallback;
}
var name = sourceContext.Trim();
var generic = name.IndexOfAny(['[', '<']);
if (generic > 0)
{
name = name[..generic];
}
name = Arity().Replace(name, string.Empty);
var parts = name.Split('+', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0)
{
return fallback;
}
parts[0] = parts[0][(parts[0].LastIndexOf('.') + 1)..];
var category = string.Join('.', parts.Where(p => p.Length > 0));
return category.Length > 0 ? category : fallback;
}
/// <summary>The SourceContext of an event, when it has one.</summary>
public static string? SourceContext(LogEvent logEvent)
=> logEvent.Properties.TryGetValue("SourceContext", out var source) && source is ScalarValue { Value: string name } ? name : null;
/// <summary>The message as rendered, then the properties it did not use as <c>key=value</c>.</summary>
public static string RenderMessage(LogEvent logEvent)
{
using var text = new StringWriter(CultureInfo.InvariantCulture);
WriteMessage(logEvent, text);
AppendProperties(logEvent, text);
return text.ToString();
}
/// <summary>
/// The message as <c>{Message:lj}</c> renders it (strings bare, structures as JSON), except
/// that other scalars are bare too: a Guid or a time reads as itself, not as a JSON string.
/// </summary>
public static void WriteMessage(LogEvent logEvent, TextWriter output)
{
foreach (var token in logEvent.MessageTemplate.Tokens)
{
if (token is not Serilog.Parsing.PropertyToken property)
{
token.Render(logEvent.Properties, output, CultureInfo.InvariantCulture);
}
else if (!logEvent.Properties.TryGetValue(property.PropertyName, out var value))
{
output.Write(property.ToString());
}
else if (value is ScalarValue { Value: string text })
{
output.Write(text);
}
else if (value is ScalarValue scalar)
{
scalar.Render(output, property.Format, CultureInfo.InvariantCulture);
}
else
{
Json.Format(value, output);
}
}
}
/// <summary>Writes <c> key=value</c> for each property of the event its message template does not name.</summary>
public static void AppendProperties(LogEvent logEvent, TextWriter output)
{
HashSet<string>? used = null;
foreach (var token in logEvent.MessageTemplate.Tokens)
{
if (token is Serilog.Parsing.PropertyToken property)
{
(used ??= new HashSet<string>(StringComparer.Ordinal)).Add(property.PropertyName);
}
}
foreach (var (name, value) in logEvent.Properties)
{
if (Unlisted.Contains(name) || (used?.Contains(name) ?? false))
{
continue;
}
output.Write(' ');
output.Write(name);
output.Write('=');
output.Write(Value(value));
}
}
/// <summary>A property value as a line shows it: bare, or double-quoted when it holds whitespace, '=' or '"'.</summary>
public static string Value(LogEventPropertyValue value)
{
var text = value switch
{
ScalarValue { Value: null } => "null",
ScalarValue { Value: string s } => Quote(s),
ScalarValue { Value: bool b } => b ? "true" : "false",
ScalarValue { Value: DateTimeOffset d } => d.ToString("O", CultureInfo.InvariantCulture),
ScalarValue { Value: DateTime d } => d.ToString("O", CultureInfo.InvariantCulture),
ScalarValue { Value: IFormattable f } => Quote(f.ToString(null, CultureInfo.InvariantCulture)),
ScalarValue { Value: var v } => Quote(v.ToString() ?? string.Empty),
_ => Quote(JsonText(value)),
};
return text;
}
/// <summary>Double-quotes a value that holds whitespace, '=' or '"' (or is empty), escaping quotes and control characters.</summary>
public static string Quote(string value)
{
if (value.Length > 0 && !value.Any(c => char.IsWhiteSpace(c) || c == '=' || c == '"' || char.IsControl(c)))
{
return value;
}
var quoted = new StringBuilder(value.Length + 2).Append('"');
foreach (var c in value)
{
switch (c)
{
case '"': quoted.Append("\\\""); break;
case '\n': quoted.Append("\\n"); break;
case '\r': quoted.Append("\\r"); break;
case '\t': quoted.Append("\\t"); break;
default:
if (char.IsControl(c))
{
quoted.Append(CultureInfo.InvariantCulture, $"\\u{(int)c:x4}");
}
else
{
quoted.Append(c);
}
break;
}
}
return quoted.Append('"').ToString();
}
private static string JsonText(LogEventPropertyValue value)
{
using var text = new StringWriter(CultureInfo.InvariantCulture);
Json.Format(value, text);
return text.ToString();
}
[GeneratedRegex(@"`\d+")]
private static partial Regex Arity();
}
@@ -0,0 +1,110 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text.RegularExpressions;
using Shared.Contracts.Api;
namespace Shared.Infrastructure.Logging;
/// <summary>One log line read back: when, how severe (a <see cref="LogLevels"/> name), from which component, and what.</summary>
public sealed record ParsedLogLine(DateTimeOffset TimestampUtc, string Level, string? Category, string Message);
/// <summary>
/// Reads a text log line back into its parts. Takes ExecuteR's format
/// (<c>[2026-11-16T17:53:40.653Z] - [Category] - [INFO] - message</c>, see
/// <see cref="LogLineFormatter"/>) and what was written before it, still in files on
/// devices: the services' <c>[2026-11-06 12:00:00.000 INF] Source: message</c> (local
/// time), the watchdog's <c>2026-11-06 12:00:00.000Z [INF] message</c>, and a screen
/// host's <c>2026-11-06T12:00:00.000000Z WARN target: message</c>.
/// </summary>
public static partial class LogLineParser
{
public static bool TryParse(string? line, [NotNullWhen(true)] out ParsedLogLine? parsed)
{
parsed = null;
if (string.IsNullOrEmpty(line))
{
return false;
}
if (Current().Match(line) is { Success: true } current)
{
var category = current.Groups["category"].Value;
parsed = new ParsedLogLine(
Utc(current.Groups["time"].Value, "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF'Z'", DateTimeStyles.AssumeUniversal),
Level(current.Groups["level"].Value),
category.Length > 0 ? category : null,
current.Groups["message"].Value);
return true;
}
if (Service().Match(line) is { Success: true } service)
{
var source = service.Groups["source"];
parsed = new ParsedLogLine(
Utc(service.Groups["time"].Value, "yyyy-MM-dd HH:mm:ss.fff", DateTimeStyles.AssumeLocal),
Level(service.Groups["level"].Value),
source.Success && source.Value.Length > 0 ? source.Value : null,
service.Groups["message"].Value);
return true;
}
if (Watchdog().Match(line) is { Success: true } watchdog)
{
parsed = new ParsedLogLine(
Utc(watchdog.Groups["time"].Value, "yyyy-MM-dd HH:mm:ss.fff", DateTimeStyles.AssumeUniversal),
Level(watchdog.Groups["level"].Value),
null,
watchdog.Groups["message"].Value);
return true;
}
if (Tracing().Match(line) is { Success: true } tracing)
{
parsed = new ParsedLogLine(
Utc(tracing.Groups["time"].Value, "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF'Z'", DateTimeStyles.AssumeUniversal),
Level(tracing.Groups["level"].Value),
tracing.Groups["source"].Value,
tracing.Groups["message"].Value);
return true;
}
return false;
}
/// <summary>A <see cref="LogLevels"/> name from any level spelling a line may carry.</summary>
public static string Level(string level) => level.ToUpperInvariant() switch
{
"TRACE" or "VRB" or "VERBOSE" => LogLevels.Verbose,
"DEBUG" or "DBG" => LogLevels.Debug,
"WARN" or "WRN" or "WARNING" => LogLevels.Warning,
"ERROR" or "ERR" => LogLevels.Error,
"FATAL" or "FTL" => LogLevels.Fatal,
_ => LogLevels.Information,
};
private static DateTimeOffset Utc(string text, string format, DateTimeStyles style)
{
// At most 7 fractional digits parse; a screen host writes up to 9.
var dot = text.IndexOf('.', StringComparison.Ordinal);
if (dot > 0 && text.EndsWith('Z') && text.Length - dot - 2 > 7)
{
text = string.Concat(text.AsSpan(0, dot + 8), "Z");
}
return DateTimeOffset.TryParseExact(text, format, CultureInfo.InvariantCulture, style | DateTimeStyles.AdjustToUniversal, out var time)
? time.ToUniversalTime()
: DateTimeOffset.UtcNow;
}
[GeneratedRegex(@"^\[(?<time>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?Z)\] - \[(?<category>[^\]]*)\] - \[(?<level>[A-Z]{4,5})\] - ?(?<message>.*)$")]
private static partial Regex Current();
[GeneratedRegex(@"^\[(?<time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}) (?<level>[A-Z]{3})\] (?:(?<source>\S*?): )?(?<message>.*)$")]
private static partial Regex Service();
[GeneratedRegex(@"^(?<time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})Z \[(?<level>[A-Z]{3})\] (?<message>.*)$")]
private static partial Regex Watchdog();
[GeneratedRegex(@"^(?<time>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z)\s+(?<level>TRACE|DEBUG|INFO|WARN|ERROR) (?<source>[A-Za-z0-9_:]+): (?<message>.*)$")]
private static partial Regex Tracing();
}
@@ -1,59 +1,48 @@
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Compact;
namespace Shared.Infrastructure.Logging;
/// <summary>
/// Builds the one Serilog pipeline every service uses: console (text or compact
/// JSON) plus a daily rolling file with size caps and retention. Correlation
/// fields (CorrelationId, ClientId, JobId, ShellSessionId, BrowserSessionId,
/// RemoteIp) flow through as structured properties from log scopes.
/// JSON) plus a daily rolling file with size caps and retention. Text lines are
/// ExecuteR's one format (<see cref="LogLineFormatter"/>):
/// <c>[2026-11-16T17:53:40.653Z] - [Category] - [INFO] - message key=value</c>.
/// Correlation fields (CorrelationId, ClientId, JobId, ShellSessionId,
/// BrowserSessionId, RemoteIp) flow through as structured properties from log
/// scopes and show as <c>key=value</c>. A warning or error that repeats is written
/// once and then counted (<see cref="RepeatThrottleSink"/>).
/// Secret material is never logged — see <see cref="Redaction"/>.
/// </summary>
public static class LoggingSetup
{
/// <summary>Human-readable console/file template including correlation context.</summary>
private const string TextTemplate =
"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj}" +
"{#if CorrelationId is not null} correlation={CorrelationId}{#end}" +
"{NewLine}{Exception}";
private const string SimpleTemplate =
"[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}";
/// <summary>
/// The pipeline for <paramref name="application"/>. With <paramref name="live"/>, every
/// event written also lands in that in-memory ring, for the console's live log views.
/// The pipeline for <paramref name="application"/> (also the category of a line
/// without a SourceContext: <c>Agent</c>, <c>Server</c>). With <paramref name="live"/>,
/// every event written also lands in that in-memory ring, for the console's live log
/// views. Events pass the level filter, the enrichers (redaction last) and the repeat
/// throttle before any sink sees them.
/// </summary>
public static Logger CreateLogger(LogSettings settings, string application, LiveLog? live = null)
public static Logger CreateLogger(LogSettings settings, string application, LiveLog? live = null, TimeProvider? clock = null)
{
var configuration = new LoggerConfiguration()
.MinimumLevel.Is(ParseLevel(settings.Level))
// Framework noise stays at Warning regardless of the app level.
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
.MinimumLevel.Override("System.Net.Http.HttpClient", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithProperty("Application", application)
// Last, so it also sees what log scopes added.
.Enrich.With<RedactionEnricher>();
var sinks = new LoggerConfiguration().MinimumLevel.Verbose();
var text = new LogLineFormatter(application);
if (live is not null)
{
configuration.WriteTo.Sink(new LiveLogSink(live));
sinks.WriteTo.Sink(new LiveLogSink(live, application));
}
if (settings.Json)
{
configuration.WriteTo.Console(new CompactJsonFormatter());
sinks.WriteTo.Console(new CompactJsonFormatter());
}
else
{
configuration.WriteTo.Console(outputTemplate: SimpleTemplate);
sinks.WriteTo.Console(text);
}
if (settings.FileEnabled)
@@ -67,28 +56,14 @@ public static class LoggingSetup
{
Directory.CreateDirectory(settings.Directory!);
if (settings.Json)
{
configuration.WriteTo.File(
new CompactJsonFormatter(),
path,
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true,
fileSizeLimitBytes: settings.FileSizeLimitBytes,
retainedFileCountLimit: settings.RetainedFileCount,
shared: true);
}
else
{
configuration.WriteTo.File(
path,
outputTemplate: SimpleTemplate,
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true,
fileSizeLimitBytes: settings.FileSizeLimitBytes,
retainedFileCountLimit: settings.RetainedFileCount,
shared: true);
}
sinks.WriteTo.File(
settings.Json ? new CompactJsonFormatter() : (ITextFormatter)text,
path,
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true,
fileSizeLimitBytes: settings.FileSizeLimitBytes,
retainedFileCountLimit: settings.RetainedFileCount,
shared: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
@@ -98,7 +73,24 @@ public static class LoggingSetup
}
}
return configuration.CreateLogger();
// The sinks sit behind the repeat throttle, which is behind the filters and
// enrichers: what is counted is already redacted, and disposing the logger
// writes any count still open before the sinks close.
var throttle = new RepeatThrottleSink(sinks.CreateLogger(), clock);
return new LoggerConfiguration()
.MinimumLevel.Is(ParseLevel(settings.Level))
// Framework noise stays at Warning regardless of the app level.
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
.MinimumLevel.Override("System.Net.Http.HttpClient", LogEventLevel.Warning)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithProperty("Application", application)
// Last, so it also sees what log scopes added.
.Enrich.With<RedactionEnricher>()
.WriteTo.Sink(throttle)
.CreateLogger();
}
private static LogEventLevel ParseLevel(string level)
@@ -0,0 +1,286 @@
using System.Globalization;
using Serilog.Core;
using Serilog.Events;
using Serilog.Parsing;
namespace Shared.Infrastructure.Logging;
/// <summary>
/// Keeps a warning, error or fatal that repeats from flooding the log. An event is the
/// same as another when its level, SourceContext and message template are (a template
/// that is only placeholders, such as a relayed <c>{Line}</c>, compares by its rendered
/// text instead). The first is written at once; the same event again within the window
/// is counted, not written; when the window ends with any counted, ONE line is written:
/// the last of them with <c>repeated=N window=60s</c> appended, and a new window starts.
/// A window with none counted forgets the event, so the next one is written at once.
/// At most <see cref="DefaultMaxKeys"/> events are tracked (the oldest goes first, its
/// count written); disposing writes every count still open. Information and below pass
/// straight through.
/// </summary>
public sealed class RepeatThrottleSink : ILogEventSink, IDisposable
{
public static readonly TimeSpan DefaultWindow = TimeSpan.FromSeconds(60);
public const int DefaultMaxKeys = 1000;
/// <summary>The property a summary line carries: how many more times the event happened.</summary>
public const string RepeatedProperty = "repeated";
/// <summary>The property a summary line carries: the window it counts (<c>60s</c>).</summary>
public const string WindowProperty = "window";
private const int RenderedKeyChars = 256;
private readonly ILogEventSink target;
private readonly bool ownsTarget;
private readonly TimeProvider clock;
private readonly TimeSpan window;
private readonly int maxKeys;
private readonly string windowText;
private readonly Lock gate = new();
private readonly Dictionary<Key, Entry> entries = [];
private readonly ITimer? timer;
private long order;
private bool disposed;
/// <param name="target">Where events go (the logger holding the console, file and live sinks).</param>
/// <param name="clock">Time, injectable for tests.</param>
/// <param name="window">How long repeats are counted before one summary line.</param>
/// <param name="maxKeys">How many distinct events are tracked at once.</param>
/// <param name="sweepEvery">How often ended windows are looked for; <see cref="Timeout.InfiniteTimeSpan"/> for never (tests call <see cref="Sweep"/>).</param>
/// <param name="ownsTarget">Dispose <paramref name="target"/> along with this sink.</param>
public RepeatThrottleSink(
ILogEventSink target,
TimeProvider? clock = null,
TimeSpan? window = null,
int maxKeys = DefaultMaxKeys,
TimeSpan? sweepEvery = null,
bool ownsTarget = true)
{
ArgumentNullException.ThrowIfNull(target);
ArgumentOutOfRangeException.ThrowIfLessThan(maxKeys, 1);
this.target = target;
this.ownsTarget = ownsTarget;
this.clock = clock ?? TimeProvider.System;
this.window = window ?? DefaultWindow;
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(this.window, TimeSpan.Zero, nameof(window));
this.maxKeys = maxKeys;
windowText = FormatWindow(this.window);
var every = sweepEvery ?? TimeSpan.FromSeconds(1);
if (every != Timeout.InfiniteTimeSpan)
{
timer = this.clock.CreateTimer(_ => SweepQuietly(), null, every, every);
}
}
/// <summary>How many distinct events are being tracked now.</summary>
public int Tracked
{
get
{
lock (gate)
{
return entries.Count;
}
}
}
public void Emit(LogEvent logEvent)
{
if (logEvent.Level < LogEventLevel.Warning)
{
target.Emit(logEvent);
return;
}
var key = KeyOf(logEvent);
LogEvent? evicted = null;
LogEvent? summary = null;
var write = true;
lock (gate)
{
if (!disposed)
{
var now = clock.GetUtcNow();
if (entries.TryGetValue(key, out var entry) && now - entry.Start >= window)
{
summary = Close(key, entry, now);
if (summary is null)
{
entry = null;
}
}
if (entry is null)
{
evicted = MakeRoom();
entries[key] = new Entry(now, ++order);
}
else
{
entry.Suppressed++;
entry.Last = logEvent;
write = false;
}
}
}
if (evicted is not null)
{
target.Emit(evicted);
}
if (summary is not null)
{
target.Emit(summary);
}
if (write)
{
target.Emit(logEvent);
}
}
/// <summary>Ends every window that is over: a summary line for each that counted repeats; the quiet ones are forgotten.</summary>
public void Sweep()
{
List<LogEvent>? summaries = null;
lock (gate)
{
if (disposed || entries.Count == 0)
{
return;
}
var now = clock.GetUtcNow();
foreach (var (key, entry) in entries.Where(e => now - e.Value.Start >= window).ToList())
{
if (Close(key, entry, now) is { } summary)
{
(summaries ??= []).Add(summary);
}
}
}
foreach (var summary in summaries ?? [])
{
target.Emit(summary);
}
}
/// <summary>Writes every count still open, then stops (events after this pass straight through).</summary>
public void Dispose()
{
List<LogEvent> summaries;
lock (gate)
{
if (disposed)
{
return;
}
disposed = true;
summaries = [.. entries.Values.Where(e => e.Suppressed > 0).OrderBy(e => e.Order).Select(Summary)];
entries.Clear();
}
timer?.Dispose();
foreach (var summary in summaries)
{
target.Emit(summary);
}
if (ownsTarget)
{
(target as IDisposable)?.Dispose();
}
}
/// <summary><c>60s</c>, <c>1.5s</c>, <c>250ms</c>.</summary>
public static string FormatWindow(TimeSpan window)
=> window.TotalSeconds >= 1
? window.TotalSeconds.ToString("0.###", CultureInfo.InvariantCulture) + "s"
: window.TotalMilliseconds.ToString("0", CultureInfo.InvariantCulture) + "ms";
private static Key KeyOf(LogEvent logEvent)
{
var template = logEvent.MessageTemplate;
var text = template.Tokens.Any(t => t is TextToken token && !string.IsNullOrWhiteSpace(token.Text))
? template.Text
: logEvent.RenderMessage(CultureInfo.InvariantCulture);
if (text.Length > RenderedKeyChars)
{
text = text[..RenderedKeyChars];
}
return new Key(logEvent.Level, LogLineFormatter.SourceContext(logEvent), text);
}
/// <summary>The window of <paramref name="entry"/> is over: its summary (and a new window), or nothing (and it is forgotten).</summary>
private LogEvent? Close(Key key, Entry entry, DateTimeOffset now)
{
if (entry.Suppressed == 0)
{
entries.Remove(key);
return null;
}
var summary = Summary(entry);
entry.Start = now;
entry.Suppressed = 0;
entry.Last = null;
return summary;
}
private LogEvent? MakeRoom()
{
if (entries.Count < maxKeys)
{
return null;
}
var oldest = entries.MinBy(e => e.Value.Order);
entries.Remove(oldest.Key);
return oldest.Value.Suppressed > 0 ? Summary(oldest.Value) : null;
}
private LogEvent Summary(Entry entry)
{
var last = entry.Last!;
var summary = new LogEvent(
clock.GetUtcNow(),
last.Level,
last.Exception,
last.MessageTemplate,
last.Properties.Select(p => new LogEventProperty(p.Key, p.Value)));
summary.AddOrUpdateProperty(new LogEventProperty(RepeatedProperty, new ScalarValue(entry.Suppressed)));
summary.AddOrUpdateProperty(new LogEventProperty(WindowProperty, new ScalarValue(windowText)));
return summary;
}
private void SweepQuietly()
{
try
{
Sweep();
}
catch (Exception exception)
{
// A sink that throws must never take the timer (or the process) down with it.
Serilog.Debugging.SelfLog.WriteLine("Repeat summary failed: {0}", exception);
}
}
private readonly record struct Key(LogEventLevel Level, string? Source, string Template);
private sealed class Entry(DateTimeOffset start, long order)
{
public DateTimeOffset Start { get; set; } = start;
public long Order { get; } = order;
public int Suppressed { get; set; }
public LogEvent? Last { get; set; }
}
}
+5 -2
View File
@@ -110,6 +110,7 @@ export interface SaveScriptBody {
runFromFile?: boolean;
cleanUpAfterRun?: boolean;
setWorkingDirectory?: boolean;
runAsUser?: boolean;
restartAfterRun?: RestartAfterRun;
restartDelaySeconds?: number;
restartWarningSeconds?: number;
@@ -298,8 +299,10 @@ export const api = {
devices: () => request<DeviceDto[]>('/api/devices'),
device: (clientId: string) => request<DeviceDetailDto>(`/api/devices/${enc(clientId)}`),
refreshInventory: (clientId: string) => request<void>(`/api/devices/${enc(clientId)}/inventory`, { method: 'POST' }),
openShell: (clientId: string, body: { browserSessionId: string; cols: number; rows: number; shell?: string }) =>
request<CreateShellResponse>(`/api/devices/${enc(clientId)}/shell`, json('POST', body)),
openShell: (
clientId: string,
body: { browserSessionId: string; cols: number; rows: number; shell?: string; asUser?: boolean; user?: string }
) => request<CreateShellResponse>(`/api/devices/${enc(clientId)}/shell`, json('POST', body)),
/** Remote View: a session and its first one-time socket ticket. */
openScreen: (clientId: string, body: { viewOnly: boolean; monitor?: number }) =>
request<CreateScreenResponse>(`/api/devices/${enc(clientId)}/screen`, json('POST', body)),
+7 -1
View File
@@ -53,7 +53,7 @@ export type AgentInstallKind = 'msi' | 'portable';
// ── Device grouping ───────────────────────────────────────────────────
/** Folders hold no devices of their own; every kind includes its nested groups' devices. */
export type GroupKind = 'static' | 'dynamic' | 'folder';
export type GroupKind = 'static' | 'dynamic' | 'folder' | 'script';
export type RuleCombine = 'and' | 'or';
export type RuleOperator =
| 'equals'
@@ -1198,6 +1198,8 @@ export interface ScriptDto {
cleanUpAfterRun?: boolean;
/** Start a file-run script in its job folder. */
setWorkingDirectory?: boolean;
/** Run as the device's signed-in user instead of the agent's account. */
runAsUser?: boolean;
restartAfterRun?: RestartAfterRun;
/** Seconds before the restart (0 to 3600). */
restartDelaySeconds?: number;
@@ -1763,6 +1765,10 @@ export interface ShellStatePayload {
message?: string;
/** The shell the agent started (a ShellKind; Windows agents, on open). */
shell?: string;
/** The account it runs as, when started as the signed-in user. */
user?: string;
/** Who is signed in on the device (on open, and when a run-as-user open failed). */
signedInUsers?: string[];
}
export interface DeviceFileRoot {
+29 -11
View File
@@ -40,12 +40,12 @@ interface Props {
}
const LEVELS: { level: LogLevel; tag: string; label: string; color: string; text: string }[] = [
{ level: 'verbose', tag: 'VRB', label: 'Verbose', color: 'text.disabled', text: 'text.secondary' },
{ level: 'debug', tag: 'DBG', label: 'Debug', color: 'text.disabled', text: 'text.secondary' },
{ level: 'information', tag: 'INF', label: 'Information', color: 'info.main', text: 'text.primary' },
{ level: 'warning', tag: 'WRN', label: 'Warning', color: 'warning.main', text: 'warning.dark' },
{ level: 'error', tag: 'ERR', label: 'Error', color: 'error.main', text: 'error.main' },
{ level: 'fatal', tag: 'FTL', label: 'Fatal', color: 'error.dark', text: 'error.dark' }
{ level: 'verbose', tag: 'TRACE', label: 'Verbose', color: 'text.disabled', text: 'text.secondary' },
{ level: 'debug', tag: 'DEBUG', label: 'Debug', color: 'text.disabled', text: 'text.secondary' },
{ level: 'information', tag: 'INFO', label: 'Information', color: 'info.main', text: 'text.primary' },
{ level: 'warning', tag: 'WARN', label: 'Warning', color: 'warning.main', text: 'warning.dark' },
{ level: 'error', tag: 'ERROR', label: 'Error', color: 'error.main', text: 'error.main' },
{ level: 'fatal', tag: 'FATAL', label: 'Fatal', color: 'error.dark', text: 'error.dark' }
];
const LEVEL = Object.fromEntries(LEVELS.map((l) => [l.level, l])) as Record<LogLevel, (typeof LEVELS)[number]>;
@@ -68,10 +68,28 @@ const sleep = (ms: number, signal: AbortSignal) =>
});
});
const lineText = (line: LogLineDto) =>
`${line.timestampUtc} ${LEVEL[line.level]?.tag ?? line.level} ${line.source ? `${line.source}: ` : ''}${line.message}${line.exception ? `\n${line.exception}` : ''}`;
/**
* The short component name a line shows, as the log files write it: the type name without its
* namespace or generic arguments, a nested type as Outer.Inner (Agent.Screen.ScreenHost+Session → ScreenHost.Session).
*/
function logCategory(source?: string | null): string {
const trimmed = source?.trim() ?? '';
if (!trimmed) return '';
const generic = trimmed.search(/[[<]/);
const parts = (generic > 0 ? trimmed.slice(0, generic) : trimmed).replace(/`\d+/g, '').split('+').filter(Boolean);
if (parts.length === 0) return trimmed;
parts[0] = parts[0].slice(parts[0].lastIndexOf('.') + 1);
return parts.filter(Boolean).join('.') || trimmed;
}
const shortSource = (source?: string) => (source ? source.slice(source.lastIndexOf('.') + 1) : '');
const isoTime = (value: string) => {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? value : date.toISOString();
};
/** A line as the log files write it: [time] - [Category] - [LEVEL] - message. */
const lineText = (line: LogLineDto) =>
`[${isoTime(line.timestampUtc)}] - [${logCategory(line.source)}] - [${LEVEL[line.level]?.tag ?? line.level.toUpperCase()}] - ${line.message}${line.exception ? `\n${line.exception}` : ''}`;
// ==============================|| LOG VIEWER ||============================== //
@@ -341,12 +359,12 @@ function LogLine({ line }: { line: LogLineDto }) {
<Box component="span" sx={{ color: 'text.disabled', mr: 1.5 }}>
{formatLogTime(line.timestampUtc)}
</Box>
<Box component="span" sx={{ color: level.color, fontWeight: 600, mr: 1.5 }}>
<Box component="span" sx={{ color: level.color, fontWeight: 600, mr: 1.5, display: 'inline-block', minWidth: '5ch' }}>
{level.tag}
</Box>
{line.source && (
<Box component="span" sx={{ color: 'text.secondary', mr: 1 }}>
{shortSource(line.source)}:
{logCategory(line.source)}:
</Box>
)}
{line.message}
+4 -2
View File
@@ -80,7 +80,7 @@ const removalRow = (removal: DeviceRemovalDto): ListRow => ({
const listRowId = (row: ListRow) => (row.removal ? `removal:${row.removal.id}` : row.clientId);
const KIND_LABEL = { static: 'Static Group', dynamic: 'Dynamic Group', folder: 'Folder' } as const;
const KIND_LABEL = { static: 'Static Group', dynamic: 'Dynamic Group', folder: 'Folder', script: 'Script Group' } as const;
function matches(device: ListRow, query: string): boolean {
return [
@@ -739,7 +739,9 @@ export default function DevicesPage() {
? 'No device matches the rules right now.'
: selectedGroup?.kind === 'folder'
? 'Shows devices of nested groups.'
: undefined
: selectedGroup?.kind === 'script'
? 'Devices appear when their scripts report they belong.'
: undefined
}
/>
) : (
+103 -8
View File
@@ -21,7 +21,9 @@ import useApi from 'hooks/useApi';
import useSession, { useGate } from 'hooks/useSession';
import DeviceToolFrame, { useToolSurface } from 'sections/deviceTools/DeviceToolFrame';
import { useIsPopOut } from 'sections/deviceTools/popOut';
import useRemoteShell, { SHELL_KINDS, shellLabel, ShellKind, ShellState, TERMINAL_THEME } from 'sections/shell/useRemoteShell';
import useRemoteShell, { SHELL_KINDS, shellLabel, ShellKind, ShellState } from 'sections/shell/useRemoteShell';
import TerminalSettings from 'sections/shell/TerminalSettings';
import { themeOf, useTerminalPrefs } from 'sections/shell/terminalPrefs';
import { keys } from 'api/client';
import type { DeviceDetailDto } from 'api/types';
@@ -77,6 +79,74 @@ function ShellPicker({ value, started, onChange }: { value: ShellKind; started?:
);
}
/** A Run As choice: the agent's account, the usual signed-in user, or one named user. */
const USER_PREFIX = 'user:';
/** Whose account the shell runs as; picking another opens a new session. */
function RunAsPicker({
asUser,
user,
started,
signedIn,
onChange
}: {
asUser: boolean;
user?: string;
started?: string;
signedIn?: string[];
onChange: (asUser: boolean, user?: string) => void;
}) {
// A chosen user stays listed even if the last report did not include them.
const names = [...new Set([...(signedIn ?? []), ...(user ? [user] : [])])];
return (
<TextField
select
size="small"
label="Run As"
value={!asUser ? 'agent' : user ? USER_PREFIX + user : 'user'}
onChange={(e) => {
const value = e.target.value;
if (value === 'agent') onChange(false);
else if (value === 'user') onChange(true);
else onChange(true, value.slice(USER_PREFIX.length));
}}
sx={{ minWidth: 190 }}
slotProps={{
select: {
// Signed-In User shows who once the session is open.
renderValue: (value) =>
value === 'agent'
? 'Agent Account'
: value === 'user'
? (started ?? 'Signed-In User')
: (value as string).slice(USER_PREFIX.length)
}
}}
>
<MenuItem value="agent">
<Tooltip title="LocalSystem on Windows, root on Linux and macOS." placement="right">
<span style={{ flex: 1 }}>Agent Account</span>
</Tooltip>
</MenuItem>
<MenuItem value="user">
<Tooltip
title="The person signed in on the device: the console's user, else the only one signed in; the names below pick one. Needs agent 1.13.0 or later."
placement="right"
>
<span style={{ flex: 1 }}>Signed-In User</span>
</Tooltip>
</MenuItem>
{names.map((name) => (
<MenuItem key={name} value={USER_PREFIX + name} sx={{ pl: 4 }}>
<Tooltip title={`Signed in on the device. Opens as ${name}.`} placement="right">
<span style={{ flex: 1 }}>{name}</span>
</Tooltip>
</MenuItem>
))}
</TextField>
);
}
function ShellView({ clientId }: { clientId: string }) {
const { can } = useSession();
const popout = useIsPopOut();
@@ -84,8 +154,24 @@ function ShellView({ clientId }: { clientId: string }) {
const gate = useGate('shell.use', 'Remote Shell');
const allowed = !gate;
const { data: detail } = useApi<DeviceDetailDto>(can('devices.view') ? keys.device(clientId) : null);
const { hostRef, state, message, poppedOut, shell, startedShell, controller, close, reconnect, focusWindow, chooseShell } =
useRemoteShell(clientId, allowed);
const {
hostRef,
state,
message,
poppedOut,
shell,
startedShell,
asUser,
user,
startedUser,
signedInUsers,
controller,
close,
reconnect,
focusWindow,
chooseShell,
chooseRunAs
} = useRemoteShell(clientId, allowed);
// The shell choice applies to Windows devices only (unix agents start the login shell).
const windows = platformOf(detail?.device.osCaption) === 'windows';
@@ -96,6 +182,7 @@ function ShellView({ clientId }: { clientId: string }) {
const active = ACTIVE.includes(state);
const status = STATUS[state];
const { theme } = themeOf(useTerminalPrefs());
// Bringing it back from this page never needs to navigate.
const bringBack = () => controller?.dock(() => {});
@@ -113,6 +200,10 @@ function ShellView({ clientId }: { clientId: string }) {
allowed && (
<>
{windows && controller && <ShellPicker value={shell} started={startedShell} onChange={chooseShell} />}
{controller && (
<RunAsPicker asUser={asUser} user={user} started={startedUser} signedIn={signedInUsers} onChange={chooseRunAs} />
)}
<TerminalSettings />
{poppedOut && !popout && (
<Button variant="outlined" color="secondary" startIcon={<ImportOutlined />} onClick={bringBack}>
Bring Back
@@ -143,7 +234,7 @@ function ShellView({ clientId }: { clientId: string }) {
{(state === 'failed' || state === 'noResponse') && message && (
<Alert severity={state === 'failed' ? 'error' : 'warning'}>{message}</Alert>
)}
<MainCard content={false} sx={{ bgcolor: TERMINAL_THEME.background, overflow: 'hidden', ...surface.card }}>
<MainCard content={false} sx={{ bgcolor: theme.background, overflow: 'hidden', ...surface.card }}>
<Box sx={{ position: 'relative', p: 1.5, ...surface.body }}>
{/* xterm sizes itself to this element (the padding lives on the parent so fitting stays exact).
It stays mounted while popped out so closing the window can dock the terminal straight back. */}
@@ -152,13 +243,13 @@ function ShellView({ clientId }: { clientId: string }) {
<Stack
sx={{ position: 'absolute', inset: 0, alignItems: 'center', justifyContent: 'center', gap: 2, p: 3, textAlign: 'center' }}
>
<ExportOutlined style={{ fontSize: '2rem', color: TERMINAL_THEME.cursor }} />
<ExportOutlined style={{ fontSize: '2rem', color: theme.cursor }} />
<Stack
direction="row"
sx={{
alignItems: 'center',
color: TERMINAL_THEME.foreground,
'& [tabindex]': { color: TERMINAL_THEME.foreground, opacity: 0.7 }
color: theme.foreground,
'& [tabindex]': { color: theme.foreground, opacity: 0.7 }
}}
>
<Typography variant="h5">This Shell Is In Its Own Window</Typography>
@@ -168,7 +259,11 @@ function ShellView({ clientId }: { clientId: string }) {
<Button variant="contained" startIcon={<ImportOutlined />} onClick={bringBack}>
Bring Back
</Button>
<Button variant="outlined" onClick={focusWindow} sx={{ color: TERMINAL_THEME.foreground, borderColor: '#2a3b5c' }}>
<Button
variant="outlined"
onClick={focusWindow}
sx={{ color: theme.foreground, borderColor: theme.selectionBackground }}
>
Show Window
</Button>
</Stack>
+20 -5
View File
@@ -41,7 +41,7 @@ import MoreOutlined from '@ant-design/icons/MoreOutlined';
import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined';
import PlusOutlined from '@ant-design/icons/PlusOutlined';
const KIND_LABEL = { static: 'Static', dynamic: 'Dynamic', folder: 'Folder' } as const;
const KIND_LABEL = { static: 'Static', dynamic: 'Dynamic', folder: 'Folder', script: 'Script' } as const;
// ==============================|| GROUPS ||============================== //
@@ -295,9 +295,18 @@ export default function GroupsPage() {
)}
</Stack>
)}
{group.kind === 'static' && (
{(group.kind === 'static' || group.kind === 'script') && (
<Stack sx={{ gap: 1 }}>
<Typography variant="subtitle1">Listed Devices</Typography>
<Typography variant="subtitle1">
{group.kind === 'script' ? 'Reported Devices' : 'Listed Devices'}
{group.kind === 'script' && (
<HoverHelp
title={
"Scripts add a device with Set-ExecuteRGroupMembership '<name>' <result> (true, above 0, or any results piped in), or executer_group in Bash; each run decides again."
}
/>
)}
</Typography>
<Stack direction="row" sx={{ gap: 0.75, flexWrap: 'wrap' }}>
{members
.filter((d) => d.groupIds?.includes(group.id))
@@ -316,8 +325,14 @@ export default function GroupsPage() {
{group.directMemberCount > 24 && <Chip size="small" label={`+${group.directMemberCount - 24} more`} />}
{group.directMemberCount === 0 && (
<Typography variant="body2" color="text.secondary">
None listed.
<HoverHelp title="Use Edit, or Add to Group on the Devices page." />
{group.kind === 'script' ? 'None reported.' : 'None listed.'}
<HoverHelp
title={
group.kind === 'script'
? "Scripts add a device with Set-ExecuteRGroupMembership '<name>' <result> (true, above 0, or any results piped in), or executer_group in Bash; each run decides again."
: 'Use Edit, or Add to Group on the Devices page.'
}
/>
</Typography>
)}
</Stack>
+36 -11
View File
@@ -22,6 +22,7 @@ import { useGate } from 'hooks/useSession';
// assets
import DownloadOutlined from '@ant-design/icons/DownloadOutlined';
import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined';
import ReloadOutlined from '@ant-design/icons/ReloadOutlined';
// types
import type { ExecutionDetailDto } from 'api/types';
@@ -62,16 +63,16 @@ export default function RunPage() {
{ replace: !jobId }
);
// The same script on the same devices (skipped ones included: they may be back).
const runAgain = () =>
// The same script on these devices (every target, skipped ones included: they may be back).
const runAgainOn = (clientIds: string[]) =>
run &&
openRun({
scriptId: run.scriptId,
targets: [...run.targets.map((t) => t.clientId), ...(run.skipped ?? []).map((s) => s.clientId)].map((id) => ({
kind: 'device' as const,
id
}))
targets: [...new Set(clientIds)].map((id) => ({ kind: 'device' as const, id }))
});
const runAgain = () => run && runAgainOn([...run.targets.map((t) => t.clientId), ...(run.skipped ?? []).map((s) => s.clientId)]);
// Failed and timed out: the ones that ran and did not succeed.
const failedTargets = (run?.targets ?? []).filter((t) => t.state === 'failed' || t.state === 'timedOut').map((t) => t.clientId);
return (
<Stack sx={{ gap: 3 }}>
@@ -108,11 +109,34 @@ export default function RunPage() {
)
}
secondaryActions={
<Tooltip title="Every target's output in one .log file.">
<Button variant="outlined" color="secondary" startIcon={<DownloadOutlined />} href={downloads.executionOutput(runId)} download>
Download Output
</Button>
</Tooltip>
<>
<Tooltip title="Every target's output in one .log file.">
<Button
variant="outlined"
color="secondary"
startIcon={<DownloadOutlined />}
href={downloads.executionOutput(runId)}
download
>
Download Output
</Button>
</Tooltip>
{failedTargets.length > 0 && (
<Tooltip title={runGate ? '' : 'The same script again on the devices that failed or timed out.'}>
<span>
<GatedButton
variant="outlined"
color="error"
startIcon={<ReloadOutlined />}
gate={runGate}
onClick={() => runAgainOn(failedTargets)}
>
{`Run Again on ${failedTargets.length} Failed`}
</GatedButton>
</span>
</Tooltip>
)}
</>
}
primaryAction={
<GatedButton variant="contained" startIcon={<PlayCircleOutlined />} gate={runGate} disabled={!run} onClick={runAgain}>
@@ -131,6 +155,7 @@ export default function RunPage() {
refreshing={execution.validating && !execution.loading}
openJobId={openJobId}
onOpenJob={setJob}
onRunAgain={runGate ? undefined : runAgainOn}
/>
)}
+13 -4
View File
@@ -117,7 +117,7 @@ function OptionSwitch(props: { label: string; help: string; checked: boolean; di
/** How the script runs on the device: from a staged file, cleanup and working directory. */
function RunOptions({ draft, edit, readOnly }: { draft: ScriptDraft; edit: (patch: Partial<ScriptDraft>) => void; readOnly: boolean }) {
const pwsh7 = draft.engine === 'PowerShell';
const staged = stagesFile(draft.engine, draft.runFromFile);
const staged = stagesFile(draft.engine, draft.runFromFile, draft.runAsUser);
return (
<Stack direction="row" sx={{ flexWrap: 'wrap', rowGap: 0.5 }}>
<OptionSwitch
@@ -127,17 +127,26 @@ function RunOptions({ draft, edit, readOnly }: { draft: ScriptDraft; edit: (patc
? 'Saves the script in its job folder and runs it by path, so $PSScriptRoot is set.'
: 'PowerShell 5 and Bash always run from a file.'
}
checked={staged}
checked={stagesFile(draft.engine, draft.runFromFile)}
disabled={readOnly || !pwsh7}
onChange={(runFromFile) => edit(runFromFile ? { runFromFile } : { runFromFile, setWorkingDirectory: false })}
onChange={(runFromFile) => edit(runFromFile || draft.runAsUser ? { runFromFile } : { runFromFile, setWorkingDirectory: false })}
/>
<OptionSwitch
label="Set Working Directory to Script Folder"
help={staged ? 'Starts the script in its job folder.' : 'Needs Run From File.'}
help={staged ? 'Starts the script in its job folder.' : 'Needs Run From File or Run As Signed-In User.'}
checked={staged && draft.setWorkingDirectory}
disabled={readOnly || !staged}
onChange={(setWorkingDirectory) => edit({ setWorkingDirectory })}
/>
<OptionSwitch
label="Run As Signed-In User"
help="Runs as the person signed in on the device (the console's user, else the only one) instead of the agent's account, out of sight. Fails when nobody is signed in, or on agents before 1.13.0."
checked={draft.runAsUser}
disabled={readOnly}
onChange={(runAsUser) =>
edit(runAsUser || stagesFile(draft.engine, draft.runFromFile) ? { runAsUser } : { runAsUser, setWorkingDirectory: false })
}
/>
<OptionSwitch
label="Clean Up After Run"
help="Deletes the job folder when the run ends. Off keeps it for 7 days; secrets never stay."
+1 -1
View File
@@ -49,7 +49,7 @@ const TABS: { id: string; label: string; icon: ReactElement; Section: ComponentT
{ id: 'secrets', label: 'Secrets Providers', icon: <SafetyCertificateOutlined />, Section: SecretsProviders, permission: 'secrets.use' },
{
id: 'storage',
label: 'Storage & Agent Package',
label: 'Storage & Agent Packages',
icon: <CloudServerOutlined />,
Section: StorageSettings,
permission: 'settings.manage'
@@ -359,7 +359,7 @@ function AddDeviceContent({ open, onClose }: Props) {
<Step
n={3}
title="Install"
help={`The agent downloads from this server, installs as a ${SERVICE_KIND[platform]} and enrolls automatically.`}
help={`The agent downloads from this server, installs as a ${SERVICE_KIND[platform]} and enrolls automatically. Safe to run again: it leaves a healthy agent alone, upgrades an older one and repairs a broken one, keeping its enrollment.`}
/>
{error && (
<Alert severity="error" sx={{ mb: 1.5 }}>
+21 -3
View File
@@ -48,7 +48,9 @@ interface Props {
const KIND_HELP: Record<GroupKind, string> = {
dynamic: 'Members are the devices matching the rules, re-evaluated as inventory, tags and status change.',
static: 'Members are the devices you list.',
folder: 'Holds no devices of its own; organizes groups nested under it.'
folder: 'Holds no devices of its own; organizes groups nested under it.',
script:
"Members are the devices whose scripts report they belong. Scripts add a device with Set-ExecuteRGroupMembership '<name>' <result> (true, above 0, or any results piped in), or executer_group in Bash; each run decides again."
};
const EMPTY_RULES: GroupRuleSet = { combine: 'and', groups: [] };
@@ -155,7 +157,10 @@ export default function GroupEditor({ open, onClose, group, preset, onSaved }: P
[groups, group]
);
const droppingMembers = group?.kind === 'static' && kind !== 'static' && initialMembers.length > 0;
// Static and script groups keep rows; saving as a kind without them drops them.
const keepsRows = (k: GroupKind) => k === 'static' || k === 'script';
const droppedCount = group?.kind === 'static' ? initialMembers.length : (group?.directMemberCount ?? 0);
const droppingMembers = Boolean(group) && keepsRows(group!.kind) && !keepsRows(kind) && droppedCount > 0;
const deviceById = useMemo(() => new Map((devices ?? []).map((d) => [d.clientId, d])), [devices]);
const save = async () => {
@@ -242,11 +247,13 @@ export default function GroupEditor({ open, onClose, group, preset, onSaved }: P
<ToggleButtonGroup exclusive size="small" value={kind} onChange={(_, value) => value && setKind(value)}>
<ToggleButton value="dynamic">Dynamic (Rules)</ToggleButton>
<ToggleButton value="static">Static (Listed)</ToggleButton>
<ToggleButton value="script">Script (Reported)</ToggleButton>
<ToggleButton value="folder">Folder</ToggleButton>
</ToggleButtonGroup>
{droppingMembers && (
<Alert severity="warning">
Saving as {kind === 'folder' ? 'a folder' : 'a dynamic group'} drops the {plural(initialMembers.length, 'listed device')}.
Saving as {kind === 'folder' ? 'a folder' : 'a dynamic group'} drops the{' '}
{plural(droppedCount, group?.kind === 'script' ? 'reported device' : 'listed device')}.
</Alert>
)}
</Stack>
@@ -340,6 +347,17 @@ export default function GroupEditor({ open, onClose, group, preset, onSaved }: P
</Stack>
)}
{kind === 'script' && (
<Typography variant="body2" color="text.secondary">
Scripts add and remove its devices.
<HoverHelp
title={
"Scripts add a device with Set-ExecuteRGroupMembership '<name>' <result> (true, above 0, or any results piped in), or executer_group in Bash; each run decides again."
}
/>
</Typography>
)}
{kind === 'folder' && (
<Typography variant="body2" color="text.secondary">
Add groups to it after saving.
@@ -19,6 +19,7 @@ import ApartmentOutlined from '@ant-design/icons/ApartmentOutlined';
import ClusterOutlined from '@ant-design/icons/ClusterOutlined';
import DisconnectOutlined from '@ant-design/icons/DisconnectOutlined';
import FilterOutlined from '@ant-design/icons/FilterOutlined';
import CodeOutlined from '@ant-design/icons/CodeOutlined';
import FolderOutlined from '@ant-design/icons/FolderOutlined';
import NodeCollapseOutlined from '@ant-design/icons/NodeCollapseOutlined';
import NodeExpandOutlined from '@ant-design/icons/NodeExpandOutlined';
@@ -30,7 +31,7 @@ export const UNGROUPED_NODE = 'ungrouped';
const EXPANDED_KEY = 'executer-group-tree-expanded';
const KIND_ICON = { folder: FolderOutlined, dynamic: FilterOutlined, static: ApartmentOutlined } as const;
const KIND_ICON = { folder: FolderOutlined, dynamic: FilterOutlined, static: ApartmentOutlined, script: CodeOutlined } as const;
function loadExpanded(): Set<string> {
try {
+132 -55
View File
@@ -8,8 +8,11 @@ import Button from '@mui/material/Button';
import ButtonBase from '@mui/material/ButtonBase';
import Chip from '@mui/material/Chip';
import CircularProgress from '@mui/material/CircularProgress';
import IconButton from '@mui/material/IconButton';
import InputAdornment from '@mui/material/InputAdornment';
import Link from '@mui/material/Link';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
@@ -33,6 +36,8 @@ import { BAR_ORDER, PENDING, RunFilter, runCounts, runFinished, Segment, segment
// assets
import DownloadOutlined from '@ant-design/icons/DownloadOutlined';
import EllipsisOutlined from '@ant-design/icons/EllipsisOutlined';
import PlayCircleOutlined from '@ant-design/icons/PlayCircleOutlined';
import SearchOutlined from '@ant-design/icons/SearchOutlined';
// types
@@ -129,7 +134,8 @@ function Counter({
help,
tone,
active,
onClick
onClick,
onRunAgain
}: {
label: string;
value: number;
@@ -137,40 +143,86 @@ function Counter({
tone?: SegmentTone;
active: boolean;
onClick: () => void;
/** Run Again on the tile's devices (right-click, or the ⋯ on hover). */
onRunAgain?: () => void;
}) {
const [menu, setMenu] = useState<{ top: number; left: number } | null>(null);
const actionable = Boolean(onRunAgain) && value > 0;
const openMenu = (event: MouseEvent<HTMLElement>, at?: { top: number; left: number }) => {
event.preventDefault();
event.stopPropagation();
const box = event.currentTarget.getBoundingClientRect();
setMenu(at ?? { top: box.bottom, left: box.left });
};
return (
<Tooltip title={help} enterDelay={500} disableInteractive>
<ButtonBase
onClick={onClick}
aria-pressed={active}
sx={(theme) => {
const color = tone ? theme.palette[tone].main : theme.palette.text.primary;
return {
flex: '1 1 96px',
minWidth: 96,
px: 1.75,
py: 1.25,
gap: 0.25,
flexDirection: 'column',
alignItems: 'flex-start',
borderRadius: 1.5,
border: '1px solid',
borderColor: active ? color : 'divider',
bgcolor: active ? alpha(color, 0.08) : 'transparent',
transition: 'border-color 120ms, background-color 120ms',
'&:hover': { borderColor: color, bgcolor: alpha(color, 0.05) },
'&.Mui-focusVisible': { outline: `2px solid ${theme.palette.primary.main}`, outlineOffset: 1 }
};
}}
>
<Typography variant="h4" sx={{ lineHeight: 1.1, color: tone && value ? `${tone}.main` : 'text.primary' }}>
{value.toLocaleString()}
</Typography>
<Typography variant="caption" color="text.secondary" sx={{ fontWeight: 500 }}>
{label}
</Typography>
</ButtonBase>
</Tooltip>
<Box
sx={{
position: 'relative',
flex: '1 1 96px',
minWidth: 96,
display: 'flex',
'&:hover .counter-more, & .counter-more.Mui-focusVisible': { opacity: 1 }
}}
>
<Tooltip title={help} enterDelay={500} disableInteractive>
<ButtonBase
onClick={onClick}
onContextMenu={actionable ? (e) => openMenu(e, { top: e.clientY, left: e.clientX }) : undefined}
aria-pressed={active}
sx={(theme) => {
const color = tone ? theme.palette[tone].main : theme.palette.text.primary;
return {
flex: 1,
px: 1.75,
py: 1.25,
gap: 0.25,
flexDirection: 'column',
alignItems: 'flex-start',
borderRadius: 1.5,
border: '1px solid',
borderColor: active ? color : 'divider',
bgcolor: active ? alpha(color, 0.08) : 'transparent',
transition: 'border-color 120ms, background-color 120ms',
'&:hover': { borderColor: color, bgcolor: alpha(color, 0.05) },
'&.Mui-focusVisible': { outline: `2px solid ${theme.palette.primary.main}`, outlineOffset: 1 }
};
}}
>
<Typography variant="h4" sx={{ lineHeight: 1.1, color: tone && value ? `${tone}.main` : 'text.primary' }}>
{value.toLocaleString()}
</Typography>
<Typography variant="caption" color="text.secondary" sx={{ fontWeight: 500 }}>
{label}
</Typography>
</ButtonBase>
</Tooltip>
{actionable && (
<>
<Tooltip title={`${label} Actions`}>
<IconButton
className="counter-more"
size="small"
aria-label={`${label} Actions`}
onClick={(e) => openMenu(e)}
sx={{ position: 'absolute', top: 4, right: 4, opacity: { xs: 1, md: 0 }, transition: 'opacity 120ms' }}
>
<EllipsisOutlined />
</IconButton>
</Tooltip>
<Menu open={Boolean(menu)} onClose={() => setMenu(null)} anchorReference="anchorPosition" anchorPosition={menu ?? undefined}>
<MenuItem
onClick={() => {
setMenu(null);
onRunAgain?.();
}}
>
<PlayCircleOutlined style={{ marginRight: 8 }} />
{value === 1 ? 'Run Again on This Device' : `Run Again on These ${value.toLocaleString()}`}
</MenuItem>
</Menu>
</>
)}
</Box>
);
}
@@ -178,11 +230,14 @@ function Counter({
export function RunCounters({
counts,
filter,
onFilter
onFilter,
onRunAgain
}: {
counts: RunCountsDto;
filter: RunFilter;
onFilter: (filter: RunFilter) => void;
/** Run Again on a tile's devices; without it the tiles have no actions. */
onRunAgain?: (filter: RunFilter) => void;
}) {
const toggle = (next: RunFilter) => onFilter(filter === next ? 'all' : next);
return (
@@ -193,6 +248,7 @@ export function RunCounters({
help="Every device this run reached."
active={filter === 'all'}
onClick={() => onFilter('all')}
onRunAgain={onRunAgain && (() => onRunAgain('all'))}
/>
<Counter
label="Online"
@@ -200,6 +256,7 @@ export function RunCounters({
help="Targets online now."
active={filter === 'online'}
onClick={() => toggle('online')}
onRunAgain={onRunAgain && (() => onRunAgain('online'))}
/>
{SEGMENTS.map((s) => (
<Counter
@@ -210,6 +267,7 @@ export function RunCounters({
tone={s.tone}
active={filter === s.key}
onClick={() => toggle(s.key)}
onRunAgain={onRunAgain && (() => onRunAgain(s.key))}
/>
))}
</Stack>
@@ -382,6 +440,8 @@ interface Props {
initialFilter?: RunFilter;
/** Shows the charts above the table (a page of its own), not only the counters in its toolbar. */
dashboard?: boolean;
/** The same script again on some of these devices (a status tile's, or the checked ones). */
onRunAgain?: (clientIds: string[]) => void;
}
/**
@@ -399,7 +459,8 @@ export default function RunProgress({
onOpenJob,
toolbarStart,
initialFilter = 'all',
dashboard
dashboard,
onRunAgain
}: Props) {
const [filter, setFilterState] = useState<RunFilter>(initialFilter);
const [detail, setDetail] = useState<RunDetailFilter | null>(null);
@@ -482,6 +543,13 @@ export default function RunProgress({
);
}, [rows, filter, detail, search]);
// A tile's devices (skipped ones included: they may be back), or the checked rows'.
const devicesOf = (rule: RunFilter) => [
...new Set((rows ?? []).filter((r) => rule === 'all' || (rule === 'online' ? r.online : segmentOf(r) === rule)).map((r) => r.clientId))
];
const runAgainOn = onRunAgain && ((rule: RunFilter) => onRunAgain(devicesOf(rule)));
const checkedDevices = [...new Set((rows ?? []).filter((r) => chosen.has(r.id)).map((r) => r.clientId))];
const starts = useMemo(() => (rows ?? []).flatMap((r) => (r.startsAt === undefined ? [] : [r.startsAt])).sort((a, b) => a - b), [rows]);
const jobCount = counts ? counts.targets - counts.skipped : 0;
@@ -500,7 +568,7 @@ export default function RunProgress({
</Stack>
<RunProgressBar counts={counts} />
</Stack>
<RunCounters counts={counts} filter={filter} onFilter={setFilter} />
<RunCounters counts={counts} filter={filter} onFilter={setFilter} onRunAgain={runAgainOn} />
</Stack>
);
@@ -544,25 +612,34 @@ export default function RunProgress({
/>
{detail && <Chip size="small" variant="light" color="primary" label={detail.label} onDelete={() => setDetail(null)} />}
</Stack>
<Tooltip
title={
chosen.size
? 'A zip with the checked devices’ logs, one .log each.'
: 'A zip with every device’s log, one .log each. Check devices to narrow it.'
}
>
<span>
<Button
variant="outlined"
size="small"
startIcon={saving ? <CircularProgress size={14} color="inherit" /> : <DownloadOutlined />}
disabled={saving || jobsInRun === 0}
onClick={() => void saveLogs()}
>
{chosen.size ? `Download ${chosen.size} ${chosen.size === 1 ? 'Log' : 'Logs'}` : 'Download All Logs'}
</Button>
</span>
</Tooltip>
<Stack direction="row" sx={{ gap: 1, alignItems: 'center' }}>
{onRunAgain && checkedDevices.length > 0 && (
<Tooltip title="The same script again on the checked devices.">
<Button variant="outlined" size="small" startIcon={<PlayCircleOutlined />} onClick={() => onRunAgain(checkedDevices)}>
{`Run Again on ${checkedDevices.length}`}
</Button>
</Tooltip>
)}
<Tooltip
title={
chosen.size
? 'A zip with the checked devices’ logs, one .log each.'
: 'A zip with every device’s log, one .log each. Check devices to narrow it.'
}
>
<span>
<Button
variant="outlined"
size="small"
startIcon={saving ? <CircularProgress size={14} color="inherit" /> : <DownloadOutlined />}
disabled={saving || jobsInRun === 0}
onClick={() => void saveLogs()}
>
{chosen.size ? `Download ${chosen.size} ${chosen.size === 1 ? 'Log' : 'Logs'}` : 'Download All Logs'}
</Button>
</span>
</Tooltip>
</Stack>
</Stack>
</Stack>
}
@@ -18,6 +18,8 @@ import RunProgress, { useRun } from 'sections/runs/RunProgress';
import { runColumns } from 'sections/runs/RecentRuns';
import { downloads, keys } from 'api/client';
import useApi from 'hooks/useApi';
import useAutomation from 'hooks/useAutomation';
import { useGate } from 'hooks/useSession';
import useLiveRefresh from 'hooks/useLiveRefresh';
import { formatAbsolute } from 'utils/format';
@@ -43,6 +45,11 @@ export default function ExecutionsPanel({ scriptId }: { scriptId: string }) {
const executions = useApi<ExecutionSummaryDto[]>(keys.scriptExecutions(scriptId));
const execution = useRun(runId);
const runGate = useGate('jobs.run', 'Run Jobs');
const automation = useAutomation();
// The same script again on some of the run's devices (a status tile's, or the checked ones).
const runAgainOn = (clientIds: string[]) =>
automation.openRun({ scriptId, targets: clientIds.map((id) => ({ kind: 'device' as const, id })) });
const run = execution.data;
const { mutate: mutateExecutions } = executions;
const refresh = useCallback(() => void mutateExecutions(), [mutateExecutions]);
@@ -66,6 +73,7 @@ export default function ExecutionsPanel({ scriptId }: { scriptId: string }) {
error={execution.error && !run ? execution.error.message : undefined}
openJobId={jobId}
onOpenJob={setJobId}
onRunAgain={runGate ? undefined : runAgainOn}
toolbarStart={
<Stack direction={{ xs: 'column', md: 'row' }} sx={{ gap: 1.5, alignItems: { md: 'center' }, justifyContent: 'space-between' }}>
<Breadcrumbs separator={<RightOutlined style={{ fontSize: '0.6rem' }} />} aria-label="Execution">
@@ -55,6 +55,7 @@ export interface ScriptDraft {
runFromFile: boolean;
cleanUpAfterRun: boolean;
setWorkingDirectory: boolean;
runAsUser: boolean;
restartAfterRun: RestartAfterRun;
restartDelaySeconds: number;
/** Warn Signed-In Users: 0 is off. */
@@ -80,6 +81,7 @@ export const NEW_SCRIPT_DRAFT: ScriptDraft = {
runFromFile: false,
cleanUpAfterRun: true,
setWorkingDirectory: false,
runAsUser: false,
restartAfterRun: 'off',
restartDelaySeconds: 0,
restartWarningSeconds: 0
@@ -102,6 +104,7 @@ export function draftFromScript(script: ScriptDto): ScriptDraft {
runFromFile: script.runFromFile ?? false,
cleanUpAfterRun: script.cleanUpAfterRun ?? true,
setWorkingDirectory: script.setWorkingDirectory ?? false,
runAsUser: script.runAsUser ?? false,
restartAfterRun: script.restartAfterRun ?? 'off',
restartDelaySeconds: script.restartDelaySeconds ?? 0,
restartWarningSeconds: script.restartWarningSeconds ?? 0
@@ -138,15 +141,17 @@ export function saveBody(draft: ScriptDraft, name = draft.name): SaveScriptBody
cleanUpFiles: stored.cleanUpFiles,
runFromFile: stored.runFromFile,
cleanUpAfterRun: stored.cleanUpAfterRun,
setWorkingDirectory: stagesFile(stored.engine, stored.runFromFile) && stored.setWorkingDirectory,
setWorkingDirectory: stagesFile(stored.engine, stored.runFromFile, stored.runAsUser) && stored.setWorkingDirectory,
runAsUser: stored.runAsUser,
restartAfterRun: stored.restartAfterRun,
restartDelaySeconds: stored.restartAfterRun === 'off' ? 0 : stored.restartDelaySeconds,
restartWarningSeconds: stored.restartAfterRun === 'off' ? 0 : stored.restartWarningSeconds
};
}
/** Windows PowerShell 5.1 and Bash always run from a staged file; PowerShell 7 only with Run From File. */
export const stagesFile = (engine: ScriptEngine, runFromFile: boolean) => engine !== 'PowerShell' || runFromFile;
/** Windows PowerShell 5.1 and Bash always run from a staged file; PowerShell 7 with Run From File or as the signed-in user. */
export const stagesFile = (engine: ScriptEngine, runFromFile: boolean, runAsUser = false) =>
engine !== 'PowerShell' || runFromFile || runAsUser;
/** Body for a copy of a stored script ("Name (copy)"). */
export const duplicateBody = (script: ScriptDto | ScriptDraft) => {
@@ -25,7 +25,6 @@ import useApi from 'hooks/useApi';
import useNow from 'hooks/useNow';
import { useGate } from 'hooks/useSession';
import Field from './Field';
import AgentDownloadsCard from './AgentDownloads';
import { CommandBox, PlatformPicker } from './InstallControls';
import { installCommand, InstallPlatform, msiexecCommand } from './installCommands';
import { SETTINGS_KEYS, SETTINGS_PERMISSION, SETTINGS_PERMISSION_LABEL } from './keys';
@@ -315,8 +314,6 @@ export default function EnrollmentTokens() {
onClose={() => setRevoking(null)}
/>
<AgentDownloadsCard />
<AddDeviceDialog open={addDeviceOpen} onClose={() => setAddDeviceOpen(false)} />
</Stack>
);
@@ -28,6 +28,7 @@ import { api, errorMessage } from 'api/client';
import useApi from 'hooks/useApi';
import { useGate } from 'hooks/useSession';
import { formatBytes } from 'utils/format';
import AgentDownloadsCard from './AgentDownloads';
import DeviceUploadsCard from './DeviceUploadsCard';
import Field from './Field';
import TestSteps from './TestSteps';
@@ -560,6 +561,8 @@ export default function StorageSettings() {
)}
</MainCard>
<AgentDownloadsCard />
<DeviceUploadsCard gate={gate} />
</Stack>
);
@@ -38,6 +38,12 @@ const LIFETIMES = [
// ==============================|| AUTHENTICATION › BUILT-IN ||============================== //
/** The card's hover: what the break-glass account is, and which one this server keeps. */
function breakGlassHelp(userName: string | null | undefined) {
const account = userName ? `The break-glass account (${userName})` : 'The break-glass account (removed)';
return `Accounts kept by this server. ${account} has full access through no binding, for recovery; the auth-reset verb on the server turns Built-In on and gives it a new one-time password.`;
}
export default function BuiltInSignInTab({ dirtyKey }: { dirtyKey: string }) {
const form = useSettingsForm<BuiltInSettings, Draft>(IdentityRoutes.builtIn, toDraft);
useReportDirty(dirtyKey, form.dirty);
@@ -49,7 +55,7 @@ export default function BuiltInSignInTab({ dirtyKey }: { dirtyKey: string }) {
return (
<Stack sx={{ gap: 3 }}>
<MainCard title={<CardTitle title="Built-In Sign-In" help="Accounts kept by this server, the break-glass account among them." />}>
<MainCard title={<CardTitle title="Built-In Sign-In" help={breakGlassHelp(view?.breakGlassUserName)} />}>
{form.loading ? (
<Skeleton variant="rounded" height={72} />
) : form.loadError ? (
@@ -63,33 +69,22 @@ export default function BuiltInSignInTab({ dirtyKey }: { dirtyKey: string }) {
summary={summary}
help="Off: only the other methods that are on can sign people in. Turning a method on or off asks you to confirm it is you."
/>
<Properties
labelWidth={170}
items={[
{
label: 'Break-Glass Account',
value: (
<>
{view.breakGlassUserName ?? 'Removed'}
<HoverHelp title="Full access through no binding, for recovery. The auth-reset verb on the server turns Built-In on and gives it a new one-time password." />
</>
)
},
...(view.forcedByEnvironment
? [
{
label: 'Built-In Form',
value: (
<>
{`Offered: ${view.forceVariable} is set`}
<HoverHelp title="The way back in when a provider fails. Remove the variable once sign-in works again." />
</>
)
}
]
: [])
]}
/>
{view.forcedByEnvironment && (
<Properties
labelWidth={170}
items={[
{
label: 'Built-In Form',
value: (
<>
{`Offered: ${view.forceVariable} is set`}
<HoverHelp title="The way back in when a provider fails. Remove the variable once sign-in works again." />
</>
)
}
]}
/>
)}
</Stack>
) : null}
</MainCard>
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom';
// project imports
import { shellLabel, shells, TERMINAL_THEME, type ShellController, type ShellState } from './shellSessions';
import { FONT_SIZE, TERMINAL_THEMES, terminalPrefs, useTerminalPrefs } from './terminalPrefs';
// assets
import ImportOutlined from '@ant-design/icons/ImportOutlined';
@@ -55,6 +56,11 @@ const CHROME_CSS = `
button.primary { border-color: #2a3b5c; }
button.danger:hover { background: rgba(248, 81, 73, 0.14); color: #ff7b72; }
.anticon { display: inline-flex; font-size: 14px; }
.prefs { display: flex; align-items: center; gap: 2px; padding-right: 6px; margin-right: 2px; border-right: 1px solid #1f2b40; }
.prefs button { padding: 0 8px; }
.prefs .size { min-width: 34px; text-align: center; color: #c9d4e5; font-variant-numeric: tabular-nums; }
select { height: 28px; border-radius: 4px; border: 1px solid #2a3b5c; background: #111a29; color: ${TERMINAL_THEME.foreground}; font: inherit; padding: 0 6px; }
select:focus-visible { outline: 2px solid ${TERMINAL_THEME.cursor}; outline-offset: 1px; }
`;
function Chrome({ controller }: { controller: ShellController }) {
@@ -63,6 +69,7 @@ function Chrome({ controller }: { controller: ShellController }) {
const started = shellLabel(startedShell);
const name = hostname || controller.clientId.slice(0, 12);
const active = ACTIVE.includes(state);
const prefs = useTerminalPrefs();
return (
<>
@@ -80,6 +87,37 @@ function Chrome({ controller }: { controller: ShellController }) {
)}
</div>
<div className="actions">
<div className="prefs">
<select
aria-label="Terminal Theme"
title="Terminal Theme"
value={prefs.themeId}
onChange={(e) => terminalPrefs.set({ themeId: e.target.value })}
>
{TERMINAL_THEMES.map((t) => (
<option key={t.id} value={t.id}>
{t.label}
</option>
))}
</select>
<button
type="button"
title="Smaller Text (Ctrl + -)"
disabled={prefs.fontSize <= FONT_SIZE.min}
onClick={() => terminalPrefs.zoom(-1)}
>
A−
</button>
<span className="size">{prefs.fontSize}</span>
<button
type="button"
title="Larger Text (Ctrl + =)"
disabled={prefs.fontSize >= FONT_SIZE.max}
onClick={() => terminalPrefs.zoom(1)}
>
A+
</button>
</div>
{active ? (
<button type="button" className="danger" onClick={() => controller.close()}>
<PoweroffOutlined /> Close Session
@@ -0,0 +1,135 @@
import { useState } from 'react';
// material-ui
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import ButtonBase from '@mui/material/ButtonBase';
import IconButton from '@mui/material/IconButton';
import MenuItem from '@mui/material/MenuItem';
import Popover from '@mui/material/Popover';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
// project imports
import HoverHelp from 'components/HoverHelp';
import { MONO_FONT_FAMILY } from 'config';
import { FONT_SIZE, SCROLLBACK_OPTIONS, TERMINAL_THEMES, terminalPrefs, useTerminalPrefs } from './terminalPrefs';
// assets
import FontSizeOutlined from '@ant-design/icons/FontSizeOutlined';
import MinusOutlined from '@ant-design/icons/MinusOutlined';
import PlusOutlined from '@ant-design/icons/PlusOutlined';
/** Theme, text size and scrollback of every terminal in this browser. */
export default function TerminalSettings() {
const prefs = useTerminalPrefs();
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
return (
<>
<Tooltip title="Terminal Settings">
<Button
variant="outlined"
color="secondary"
aria-label="Terminal Settings"
onClick={(e) => setAnchor(e.currentTarget)}
sx={{ minWidth: 0, px: 1.25 }}
>
<FontSizeOutlined />
</Button>
</Tooltip>
<Popover
open={Boolean(anchor)}
anchorEl={anchor}
onClose={() => setAnchor(null)}
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
slotProps={{ paper: { sx: { p: 2, width: 336 } } }}
>
<Stack sx={{ gap: 2 }}>
<Stack sx={{ gap: 1 }}>
<Typography variant="subtitle2">Theme</Typography>
<Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
{TERMINAL_THEMES.map(({ id, label, theme }) => (
<Tooltip key={id} title={label}>
<ButtonBase
aria-label={label}
aria-pressed={prefs.themeId === id}
onClick={() => terminalPrefs.set({ themeId: id })}
sx={{
width: 44,
height: 32,
borderRadius: 1,
bgcolor: theme.background,
color: theme.foreground,
fontFamily: MONO_FONT_FAMILY,
fontSize: 13,
border: 2,
borderColor: prefs.themeId === id ? 'primary.main' : 'divider'
}}
>
<Box component="span" sx={{ color: theme.green ?? theme.cursor }}>
&gt;
</Box>
_
</ButtonBase>
</Tooltip>
))}
</Stack>
</Stack>
<Stack sx={{ gap: 1 }}>
<Stack direction="row" sx={{ alignItems: 'center' }}>
<Typography variant="subtitle2">Text Size</Typography>
<HoverHelp title="In the terminal: Ctrl + = and Ctrl + - (or Ctrl + mouse wheel) change the size, Ctrl + 0 resets it." />
</Stack>
<Stack direction="row" sx={{ alignItems: 'center', gap: 1 }}>
<IconButton
size="small"
aria-label="Smaller"
onClick={() => terminalPrefs.zoom(-1)}
disabled={prefs.fontSize <= FONT_SIZE.min}
>
<MinusOutlined />
</IconButton>
<Typography sx={{ minWidth: 48, textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>{prefs.fontSize} px</Typography>
<IconButton size="small" aria-label="Larger" onClick={() => terminalPrefs.zoom(1)} disabled={prefs.fontSize >= FONT_SIZE.max}>
<PlusOutlined />
</IconButton>
<Button
size="small"
onClick={() => terminalPrefs.zoom(0)}
disabled={prefs.fontSize === FONT_SIZE.default}
sx={{ ml: 'auto' }}
>
Reset
</Button>
</Stack>
</Stack>
<Stack sx={{ gap: 1 }}>
<Stack direction="row" sx={{ alignItems: 'center' }}>
<Typography variant="subtitle2">Scrollback</Typography>
<HoverHelp title="Output lines kept above the screen; older lines drop off as new output arrives." />
</Stack>
<TextField
select
size="small"
aria-label="Scrollback"
value={prefs.scrollback}
onChange={(e) => terminalPrefs.set({ scrollback: Number(e.target.value) })}
>
{SCROLLBACK_OPTIONS.map((lines) => (
<MenuItem key={lines} value={lines}>
{lines.toLocaleString()} Lines
</MenuItem>
))}
</TextField>
</Stack>
</Stack>
</Popover>
</>
);
}
+75 -6
View File
@@ -7,6 +7,7 @@ import { api, errorMessage } from 'api/client';
import { MONO_FONT_FAMILY } from 'config';
import { POPOUT_SIZE, popOutWindowName } from 'sections/deviceTools/deviceTools';
import { nats, type ShellEvent } from 'messaging/nats';
import { terminalPrefs, themeOf } from './terminalPrefs';
// assets
import xtermCss from '@xterm/xterm/css/xterm.css?inline';
@@ -29,6 +30,14 @@ export interface ShellSnapshot {
shell: ShellKind;
/** The shell the agent reports it started (Windows agents only). */
startedShell?: string;
/** Start as the device's signed-in user rather than the agent's account (not remembered: asked for each time). */
asUser: boolean;
/** Which signed-in user to start as; none: the console's user, else the only one. */
user?: string;
/** Who the open shell runs as, when started as the signed-in user. */
startedUser?: string;
/** Who the agent last reported signed in on the device (kept across reconnects). */
signedInUsers?: string[];
}
/** The shells a Windows device can start (ShellKinds on the server). */
@@ -72,7 +81,7 @@ function rememberShell(kind: ShellKind) {
}
}
/** Dark terminal palette in every color scheme. */
/** The default (dark) palette: the pop-out window's toolbar keeps it whatever the terminal's theme. */
export const TERMINAL_THEME = { background: '#0d1420', foreground: '#e6ecf5', cursor: '#4c8dff', selectionBackground: '#2a3b5c' };
/** How long the agent gets to open the shell before the operator is told why it may not. */
@@ -146,8 +155,9 @@ export class ShellController {
private readonly fit = new FitAddon();
private term: Terminal | null = null;
private observer: ResizeObserver | null = null;
private offPrefs: (() => void) | null = null;
private session: Session | null = null;
private snapshot: ShellSnapshot = { state: 'connecting', hostname: '', poppedOut: false, shell: rememberedShell() };
private snapshot: ShellSnapshot = { state: 'connecting', hostname: '', poppedOut: false, shell: rememberedShell(), asUser: false };
private readonly listeners = new Set<() => void>();
/** The shell page's terminal host while that page is mounted. */
@@ -217,9 +227,18 @@ export class ShellController {
host.appendChild(this.element);
if (!this.term) {
this.term = new Terminal({ fontFamily: MONO_FONT_FAMILY, fontSize: 13, cursorBlink: true, theme: TERMINAL_THEME });
const prefs = terminalPrefs.get();
this.term = new Terminal({
fontFamily: MONO_FONT_FAMILY,
fontSize: prefs.fontSize,
scrollback: prefs.scrollback,
cursorBlink: true,
theme: themeOf(prefs).theme
});
this.term.loadAddon(this.fit);
this.term.open(this.element);
this.offPrefs = terminalPrefs.subscribe(() => this.applyPrefs());
this.bindZoom(this.term);
this.term.onResize(({ cols, rows }) => {
const session = this.session;
if (session?.id && !session.closed) publish(session.id, 'command.shell.resize', { sessionId: session.id, cols, rows });
@@ -241,6 +260,41 @@ export class ShellController {
this.term.focus();
}
/** Terminal Settings changed (here or in another window): restyle and refit. */
private applyPrefs() {
const term = this.term;
if (!term) return;
const prefs = terminalPrefs.get();
const { theme } = themeOf(prefs);
term.options.theme = theme;
term.options.fontSize = prefs.fontSize;
term.options.scrollback = prefs.scrollback;
if (this.popup && !this.popup.closed) this.popup.document.body.style.background = theme.background;
this.safeFit();
}
/** Ctrl (or Cmd) with = / - / 0, or with the wheel, sizes the text while the terminal has focus. */
private bindZoom(term: Terminal) {
term.attachCustomKeyEventHandler((event) => {
if (event.type !== 'keydown' || !(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey) return true;
const step = event.key === '=' || event.key === '+' ? 1 : event.key === '-' ? -1 : event.key === '0' ? 0 : null;
if (step === null) return true;
event.preventDefault();
terminalPrefs.zoom(step);
return false;
});
this.element.addEventListener(
'wheel',
(event) => {
if (!(event.ctrlKey || event.metaKey) || event.deltaY === 0) return;
event.preventDefault();
event.stopPropagation();
terminalPrefs.zoom(event.deltaY < 0 ? 1 : -1);
},
{ capture: true, passive: false }
);
}
private safeFit() {
// Hidden or zero-sized hosts cannot be measured; the observer refits once visible.
if (this.element.isConnected && this.element.clientWidth > 0) this.fit.fit();
@@ -284,6 +338,8 @@ export class ShellController {
host.id = 'shell-terminal';
doc.body.append(chrome, host);
doc.body.style.background = themeOf(terminalPrefs.get()).theme.background;
this.popup = popup;
this.chromeHost = chrome;
this.mount(host);
@@ -371,7 +427,7 @@ export class ShellController {
}
};
this.session = session;
this.update({ state: 'connecting', message: undefined, startedShell: undefined });
this.update({ state: 'connecting', message: undefined, startedShell: undefined, startedUser: undefined });
const handle = (event: ShellEvent) => {
if (event.type === 'shell.output') {
@@ -380,9 +436,10 @@ export class ShellController {
return;
}
const { state: next, message: detail } = event.payload;
if (event.payload.signedInUsers) this.update({ signedInUsers: event.payload.signedInUsers });
if (next === 'open') {
window.clearTimeout(timer);
this.update({ state: 'open', message: undefined, startedShell: event.payload.shell });
this.update({ state: 'open', message: undefined, startedShell: event.payload.shell, startedUser: event.payload.user });
this.setPopupTitle();
term.focus();
} else if (next === 'closed' || next === 'failed') {
@@ -414,7 +471,9 @@ export class ShellController {
browserSessionId: nats.browserSessionId,
cols: term.cols,
rows: term.rows,
shell: this.snapshot.shell
shell: this.snapshot.shell,
asUser: this.snapshot.asUser,
user: this.snapshot.asUser ? this.snapshot.user : undefined
});
// Ended (page left, operator closed it, reconnect) while the request was in flight.
if (disposed || session.closed) {
@@ -454,6 +513,14 @@ export class ShellController {
if (!this.disposed) this.update({ state: 'disconnected', message: undefined });
}
/** Opens a new session as a signed-in user (`user`, or the usual pick) or the agent's account. */
chooseRunAs(asUser: boolean, user?: string) {
const next = asUser ? user : undefined;
if (asUser === this.snapshot.asUser && next === this.snapshot.user) return;
this.update({ asUser, user: next });
if (this.term) this.reconnect();
}
/** Remembers the shell to start and opens a new session with it. */
chooseShell(kind: ShellKind) {
if (kind === this.snapshot.shell) return;
@@ -479,6 +546,8 @@ export class ShellController {
this.session = null;
this.closePopup();
this.observer?.disconnect();
this.offPrefs?.();
this.offPrefs = null;
this.term?.dispose();
this.term = null;
this.element.remove();
@@ -0,0 +1,479 @@
import { useSyncExternalStore } from 'react';
// third-party
import type { ITheme } from '@xterm/xterm';
/** A terminal palette; the card and the pop-out window around the terminal take its background. */
export interface TerminalTheme {
id: string;
label: string;
theme: ITheme & Required<Pick<ITheme, 'background' | 'foreground' | 'cursor' | 'selectionBackground'>>;
light?: boolean;
}
/** Palettes offered in Terminal Settings; the first is the default. */
export const TERMINAL_THEMES: TerminalTheme[] = [
{
id: 'dark',
label: 'Dark',
theme: { background: '#0d1420', foreground: '#e6ecf5', cursor: '#4c8dff', selectionBackground: '#2a3b5c' }
},
{
id: 'classic',
label: 'Classic',
theme: {
background: '#0c0c0c',
foreground: '#cccccc',
cursor: '#ffffff',
selectionBackground: '#3a3a3a',
black: '#0c0c0c',
red: '#c50f1f',
green: '#13a10e',
yellow: '#c19c00',
blue: '#0037da',
magenta: '#881798',
cyan: '#3a96dd',
white: '#cccccc',
brightBlack: '#767676',
brightRed: '#e74856',
brightGreen: '#16c60c',
brightYellow: '#f9f1a5',
brightBlue: '#3b78ff',
brightMagenta: '#b4009e',
brightCyan: '#61d6d6',
brightWhite: '#f2f2f2'
}
},
{
id: 'powershell',
label: 'PowerShell Blue',
theme: {
background: '#012456',
foreground: '#eeedf0',
cursor: '#fedba9',
selectionBackground: '#264f78',
black: '#000000',
red: '#c50f1f',
green: '#13a10e',
yellow: '#c19c00',
blue: '#0037da',
magenta: '#881798',
cyan: '#3a96dd',
white: '#cccccc',
brightBlack: '#767676',
brightRed: '#e74856',
brightGreen: '#16c60c',
brightYellow: '#f9f1a5',
brightBlue: '#3b78ff',
brightMagenta: '#b4009e',
brightCyan: '#61d6d6',
brightWhite: '#f2f2f2'
}
},
{
id: 'solarized',
label: 'Solarized Dark',
theme: {
background: '#002b36',
foreground: '#93a1a1',
cursor: '#93a1a1',
selectionBackground: '#073642',
black: '#073642',
red: '#dc322f',
green: '#859900',
yellow: '#b58900',
blue: '#268bd2',
magenta: '#d33682',
cyan: '#2aa198',
white: '#eee8d5',
brightBlack: '#586e75',
brightRed: '#cb4b16',
brightGreen: '#93a400',
brightYellow: '#c8a000',
brightBlue: '#4aa3e0',
brightMagenta: '#6c71c4',
brightCyan: '#3ec1b6',
brightWhite: '#fdf6e3'
}
},
{
id: 'dracula',
label: 'Dracula',
theme: {
background: '#282a36',
foreground: '#f8f8f2',
cursor: '#f8f8f2',
selectionBackground: '#44475a',
black: '#21222c',
red: '#ff5555',
green: '#50fa7b',
yellow: '#f1fa8c',
blue: '#bd93f9',
magenta: '#ff79c6',
cyan: '#8be9fd',
white: '#f8f8f2',
brightBlack: '#6272a4',
brightRed: '#ff6e6e',
brightGreen: '#69ff94',
brightYellow: '#ffffa5',
brightBlue: '#d6acff',
brightMagenta: '#ff92df',
brightCyan: '#a4ffff',
brightWhite: '#ffffff'
}
},
{
id: 'one-dark',
label: 'One Dark',
theme: {
background: '#282c34',
foreground: '#abb2bf',
cursor: '#528bff',
selectionBackground: '#3e4451',
black: '#282c34',
red: '#e06c75',
green: '#98c379',
yellow: '#e5c07b',
blue: '#61afef',
magenta: '#c678dd',
cyan: '#56b6c2',
white: '#abb2bf',
brightBlack: '#5c6370',
brightRed: '#e06c75',
brightGreen: '#98c379',
brightYellow: '#e5c07b',
brightBlue: '#61afef',
brightMagenta: '#c678dd',
brightCyan: '#56b6c2',
brightWhite: '#ffffff'
}
},
{
id: 'monokai',
label: 'Monokai',
theme: {
background: '#272822',
foreground: '#f8f8f2',
cursor: '#f8f8f0',
selectionBackground: '#49483e',
black: '#272822',
red: '#f92672',
green: '#a6e22e',
yellow: '#f4bf75',
blue: '#66d9ef',
magenta: '#ae81ff',
cyan: '#a1efe4',
white: '#f8f8f2',
brightBlack: '#75715e',
brightRed: '#f92672',
brightGreen: '#a6e22e',
brightYellow: '#f4bf75',
brightBlue: '#66d9ef',
brightMagenta: '#ae81ff',
brightCyan: '#a1efe4',
brightWhite: '#f9f8f5'
}
},
{
id: 'nord',
label: 'Nord',
theme: {
background: '#2e3440',
foreground: '#d8dee9',
cursor: '#d8dee9',
selectionBackground: '#434c5e',
black: '#3b4252',
red: '#bf616a',
green: '#a3be8c',
yellow: '#ebcb8b',
blue: '#81a1c1',
magenta: '#b48ead',
cyan: '#88c0d0',
white: '#e5e9f0',
brightBlack: '#4c566a',
brightRed: '#bf616a',
brightGreen: '#a3be8c',
brightYellow: '#ebcb8b',
brightBlue: '#81a1c1',
brightMagenta: '#b48ead',
brightCyan: '#8fbcbb',
brightWhite: '#eceff4'
}
},
{
id: 'gruvbox',
label: 'Gruvbox Dark',
theme: {
background: '#282828',
foreground: '#ebdbb2',
cursor: '#ebdbb2',
selectionBackground: '#504945',
black: '#282828',
red: '#cc241d',
green: '#98971a',
yellow: '#d79921',
blue: '#458588',
magenta: '#b16286',
cyan: '#689d6a',
white: '#a89984',
brightBlack: '#928374',
brightRed: '#fb4934',
brightGreen: '#b8bb26',
brightYellow: '#fabd2f',
brightBlue: '#83a598',
brightMagenta: '#d3869b',
brightCyan: '#8ec07c',
brightWhite: '#ebdbb2'
}
},
{
id: 'tokyo-night',
label: 'Tokyo Night',
theme: {
background: '#1a1b26',
foreground: '#c0caf5',
cursor: '#c0caf5',
selectionBackground: '#33467c',
black: '#15161e',
red: '#f7768e',
green: '#9ece6a',
yellow: '#e0af68',
blue: '#7aa2f7',
magenta: '#bb9af7',
cyan: '#7dcfff',
white: '#a9b1d6',
brightBlack: '#414868',
brightRed: '#f7768e',
brightGreen: '#9ece6a',
brightYellow: '#e0af68',
brightBlue: '#7aa2f7',
brightMagenta: '#bb9af7',
brightCyan: '#7dcfff',
brightWhite: '#c0caf5'
}
},
{
id: 'ubuntu',
label: 'Ubuntu',
theme: {
background: '#300a24',
foreground: '#eeeeec',
cursor: '#bbbbbb',
selectionBackground: '#5e2750',
black: '#2e3436',
red: '#cc0000',
green: '#4e9a06',
yellow: '#c4a000',
blue: '#3465a4',
magenta: '#75507b',
cyan: '#06989a',
white: '#d3d7cf',
brightBlack: '#555753',
brightRed: '#ef2929',
brightGreen: '#8ae234',
brightYellow: '#fce94f',
brightBlue: '#729fcf',
brightMagenta: '#ad7fa8',
brightCyan: '#34e2e2',
brightWhite: '#eeeeec'
}
},
{
id: 'high-contrast',
label: 'High Contrast',
theme: {
background: '#000000',
foreground: '#ffffff',
cursor: '#ffff00',
selectionBackground: '#264f78',
black: '#000000',
red: '#ff4040',
green: '#40ff40',
yellow: '#ffff40',
blue: '#4080ff',
magenta: '#ff40ff',
cyan: '#40ffff',
white: '#e0e0e0',
brightBlack: '#a0a0a0',
brightRed: '#ff8080',
brightGreen: '#80ff80',
brightYellow: '#ffff80',
brightBlue: '#80b0ff',
brightMagenta: '#ff80ff',
brightCyan: '#80ffff',
brightWhite: '#ffffff'
}
},
{
id: 'green-phosphor',
label: 'Green Phosphor',
theme: {
background: '#0a110b',
foreground: '#33ff66',
cursor: '#33ff66',
selectionBackground: '#1f4d2b',
black: '#0a110b',
red: '#2bd957',
green: '#33ff66',
yellow: '#66ff8c',
blue: '#1fa84a',
magenta: '#2bd957',
cyan: '#66ff8c',
white: '#33ff66',
brightBlack: '#1f7a3a',
brightRed: '#5cff85',
brightGreen: '#80ffa0',
brightYellow: '#b3ffc6',
brightBlue: '#40c060',
brightMagenta: '#5cff85',
brightCyan: '#b3ffc6',
brightWhite: '#ccffdb'
}
},
{
id: 'amber',
label: 'Amber',
theme: {
background: '#140c00',
foreground: '#ffb000',
cursor: '#ffb000',
selectionBackground: '#4d3500',
black: '#140c00',
red: '#e09a00',
green: '#ffb000',
yellow: '#ffc640',
blue: '#b37b00',
magenta: '#e09a00',
cyan: '#ffc640',
white: '#ffb000',
brightBlack: '#805800',
brightRed: '#ffc233',
brightGreen: '#ffcf66',
brightYellow: '#ffdc8c',
brightBlue: '#cc8c00',
brightMagenta: '#ffc233',
brightCyan: '#ffdc8c',
brightWhite: '#ffe7b3'
}
},
{
id: 'light',
label: 'Light',
light: true,
theme: {
background: '#fafbfc',
foreground: '#1f2328',
cursor: '#0969da',
selectionBackground: '#b6d5ff',
black: '#24292f',
red: '#cf222e',
green: '#116329',
yellow: '#7d4e00',
blue: '#0550ae',
magenta: '#8250df',
cyan: '#1b7c83',
white: '#6e7781',
brightBlack: '#57606a',
brightRed: '#a40e26',
brightGreen: '#1a7f37',
brightYellow: '#633c01',
brightBlue: '#218bff',
brightMagenta: '#a475f9',
brightCyan: '#3192aa',
brightWhite: '#8c959f'
}
},
{
id: 'solarized-light',
label: 'Solarized Light',
light: true,
theme: {
background: '#fdf6e3',
foreground: '#586e75',
cursor: '#586e75',
selectionBackground: '#eee8d5',
black: '#073642',
red: '#dc322f',
green: '#859900',
yellow: '#b58900',
blue: '#268bd2',
magenta: '#d33682',
cyan: '#2aa198',
white: '#eee8d5',
brightBlack: '#002b36',
brightRed: '#cb4b16',
brightGreen: '#586e75',
brightYellow: '#657b83',
brightBlue: '#839496',
brightMagenta: '#6c71c4',
brightCyan: '#93a1a1',
brightWhite: '#fdf6e3'
}
}
];
export const FONT_SIZE = { min: 9, max: 28, default: 13 };
/** Lines kept above the screen. xterm keeps 12 bytes a cell, so 25,000 lines of 200 columns is about 60 MB. */
export const SCROLLBACK_OPTIONS = [1_000, 5_000, 10_000, 25_000];
const DEFAULT_SCROLLBACK = 10_000;
export interface TerminalPrefs {
themeId: string;
fontSize: number;
scrollback: number;
}
const KEY = 'executer-terminal-prefs';
const DEFAULTS: TerminalPrefs = { themeId: TERMINAL_THEMES[0].id, fontSize: FONT_SIZE.default, scrollback: DEFAULT_SCROLLBACK };
function sanitize(value: Partial<TerminalPrefs> | null | undefined): TerminalPrefs {
const themeId = TERMINAL_THEMES.some((t) => t.id === value?.themeId) ? value!.themeId! : DEFAULTS.themeId;
const size = Number(value?.fontSize);
const fontSize = Number.isFinite(size) ? Math.min(FONT_SIZE.max, Math.max(FONT_SIZE.min, Math.round(size))) : DEFAULTS.fontSize;
const scrollback = SCROLLBACK_OPTIONS.includes(Number(value?.scrollback)) ? Number(value!.scrollback) : DEFAULTS.scrollback;
return { themeId, fontSize, scrollback };
}
function load(): TerminalPrefs {
try {
return sanitize(JSON.parse(localStorage.getItem(KEY) ?? 'null') as Partial<TerminalPrefs> | null);
} catch {
return DEFAULTS;
}
}
let current = load();
const listeners = new Set<() => void>();
/** The terminal settings, remembered per browser; every open terminal follows changes at once. */
export const terminalPrefs = {
get: () => current,
subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
set(patch: Partial<TerminalPrefs>) {
const next = sanitize({ ...current, ...patch });
if (next.themeId === current.themeId && next.fontSize === current.fontSize && next.scrollback === current.scrollback) return;
current = next;
try {
localStorage.setItem(KEY, JSON.stringify(current));
} catch {
// Private windows: the settings last for this page only.
}
listeners.forEach((listener) => listener());
},
/** Larger (+1), smaller (-1) or back to the default size (0). */
zoom(step: -1 | 0 | 1) {
terminalPrefs.set({ fontSize: step === 0 ? FONT_SIZE.default : current.fontSize + step });
}
};
export const themeOf = (prefs: TerminalPrefs) => TERMINAL_THEMES.find((t) => t.id === prefs.themeId) ?? TERMINAL_THEMES[0];
export function useTerminalPrefs(): TerminalPrefs {
return useSyncExternalStore(terminalPrefs.subscribe, terminalPrefs.get);
}
@@ -5,7 +5,7 @@ import { shells, type ShellController, type ShellKind, type ShellSnapshot } from
export { SHELL_KINDS, shellLabel, TERMINAL_THEME, type ShellKind, type ShellState } from './shellSessions';
const IDLE: ShellSnapshot = { state: 'connecting', hostname: '', poppedOut: false, shell: 'auto' };
const IDLE: ShellSnapshot = { state: 'connecting', hostname: '', poppedOut: false, shell: 'auto', asUser: false };
const noSubscribe = () => () => {};
// ==============================|| REMOTE SHELL SESSION ||============================== //
@@ -40,6 +40,7 @@ export default function useRemoteShell(clientId: string, enabled: boolean) {
const popOut = useCallback(() => controller?.popOut() ?? false, [controller]);
const focusWindow = useCallback(() => controller?.focusWindow(), [controller]);
const chooseShell = useCallback((kind: ShellKind) => controller?.chooseShell(kind), [controller]);
const chooseRunAs = useCallback((asUser: boolean, user?: string) => controller?.chooseRunAs(asUser, user), [controller]);
return { hostRef: setHost, ...snapshot, controller, close, reconnect, popOut, focusWindow, chooseShell };
return { hostRef: setHost, ...snapshot, controller, close, reconnect, popOut, focusWindow, chooseShell, chooseRunAs };
}
+21 -2
View File
@@ -18,6 +18,14 @@ const cmdlet = (name: string, synopsis: string, parameters = ''): CmdletInfo =>
});
export const CMDLETS: CmdletInfo[] = [
// ExecuteR built-ins (every script has them)
cmdlet(
'Set-ExecuteRGroupMembership',
'Puts this device in an ExecuteR script group, or takes it out: member when the value is $true, above 0, a non-empty collection or text other than false/0/no/off. Pipe results in.',
'Name Value'
),
cmdlet('Add-ExecuteRGroupMembership', 'Puts this device in an ExecuteR script group, created the first time a device joins it.', 'Name'),
cmdlet('Remove-ExecuteRGroupMembership', 'Takes this device out of an ExecuteR script group.', 'Name'),
// Files and the registry
cmdlet(
'Get-ChildItem',
@@ -606,7 +614,12 @@ export const SNIPPETS: SnippetInfo[] = [
detail: 'Comment-based help block',
insert: '<#\n.SYNOPSIS\n ${1:Short description}\n.DESCRIPTION\n ${2:Long description}\n.EXAMPLE\n ${3:Example}\n#>\n$0'
},
{ label: 'erroraction', detail: 'Stop on every error', insert: "\\$ErrorActionPreference = 'Stop'\n$0" }
{ label: 'erroraction', detail: 'Stop on every error', insert: "\\$ErrorActionPreference = 'Stop'\n$0" },
{
label: 'group-membership',
detail: 'Put this device in a script group from a result',
insert: "${1:Get-Process -Name 'java' -ErrorAction SilentlyContinue} | Set-ExecuteRGroupMembership '${2:Group Name}'\n$0"
}
];
export const BASH_SNIPPETS: SnippetInfo[] = [
@@ -622,10 +635,16 @@ export const BASH_SNIPPETS: SnippetInfo[] = [
detail: 'case statement',
insert: 'case "\\$${1:var}" in\n ${2:pattern})\n $3\n ;;\n *)\n $0\n ;;\nesac'
},
{ label: 'trap', detail: 'Clean up on exit', insert: 'trap \'${1:rm -rf "\\$tmp"}\' EXIT\n$0' }
{ label: 'trap', detail: 'Clean up on exit', insert: 'trap \'${1:rm -rf "\\$tmp"}\' EXIT\n$0' },
{
label: 'group-membership',
detail: 'Put this device in a script group from a result (true/false, a count, text)',
insert: 'executer_group "${1:Group Name}" "\\$(${2:pgrep -c java})"\n$0'
}
];
export const BASH_COMMANDS = [
'executer_group',
'echo',
'printf',
'cat',
+147
View File
@@ -0,0 +1,147 @@
using System.Text.Json;
using Agent.Commands;
using Agent.Configuration;
using Agent.Enrollment;
using Shared.Infrastructure.Constants;
using Xunit;
namespace Agent.Tests;
/// <summary>
/// The enrollment half of <c>status</c>, which the install scripts read to decide
/// between leaving a device alone, repairing it and re-enrolling it.
/// </summary>
public class AgentHealthTests
{
private const string ClientId = "client-a";
private static readonly Guid EnrollmentId = Guid.Parse("5b0e5a62-2f1d-4c3e-9a77-0c4d1b2e3f40");
private readonly InMemoryRegistryStore registry = new();
private readonly FixedCredentialStore credentials = new();
[Fact]
public void AnEnrolledAgentOfThisHardwareIsValid()
{
registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.ServerUrl, " https://control.example.com/ ");
credentials.Current = Credential(ClientId);
var report = Read(fileExists: true, clientId: ClientId);
Assert.Equal(AgentHealth.CredentialValid, report.Credential);
Assert.Equal("https://control.example.com/", report.ServerUrl);
Assert.Equal(EnrollmentId.ToString("D"), report.EnrollmentId);
Assert.False(report.BootstrapTokenPending);
Assert.Equal("1.4.0", report.Version);
}
[Fact]
public void NoCredentialFileIsMissingAndAPlacedTokenIsPending()
{
registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken, "secret");
var report = Read(fileExists: false, clientId: ClientId);
Assert.Equal(AgentHealth.CredentialMissing, report.Credential);
Assert.Null(report.ServerUrl);
Assert.Null(report.EnrollmentId);
Assert.True(report.BootstrapTokenPending);
}
[Fact]
public void AFileThatDoesNotLoadIsUnreadable()
{
credentials.Current = null;
Assert.Equal(AgentHealth.CredentialUnreadable, Read(fileExists: true, clientId: ClientId).Credential);
}
[Fact]
public void ACredentialOfOtherHardwareIsAnotherDevice()
{
credentials.Current = Credential("client-b");
Assert.Equal(AgentHealth.CredentialOtherDevice, Read(fileExists: true, clientId: ClientId).Credential);
}
[Fact]
public void WithoutAHardwareIdentityTheCredentialIsJudgedOnItsOwn()
{
credentials.Current = Credential("client-b");
Assert.Equal(AgentHealth.CredentialValid, Read(fileExists: true, clientId: null).Credential);
}
[Fact]
public void AnExpiredCredentialIsStillValidBecauseItRenewsItself()
{
credentials.Current = Credential(ClientId) with { ExpiresUtc = DateTimeOffset.UtcNow.AddDays(-3) };
Assert.Equal(AgentHealth.CredentialValid, Read(fileExists: true, clientId: ClientId).Credential);
}
[Fact]
public void GroupPolicyDecidesTheServer()
{
registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.ServerUrl, "https://local.example.com");
registry.SetString(Branding.AgentPolicyRegistryKey, AgentConfigurationKeys.ServerUrl, "https://policy.example.com");
Assert.Equal("https://policy.example.com", Read(fileExists: false, clientId: ClientId).ServerUrl);
}
[Fact]
public void TheJsonLineCarriesEveryFieldButNeverTheToken()
{
registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.ServerUrl, "https://control.example.com:8443/a+b");
registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.BootstrapToken, "very-secret-token");
credentials.Current = Credential(ClientId) with { ExpiresUtc = new DateTimeOffset(2027, 1, 2, 3, 4, 5, TimeSpan.Zero) };
var json = AgentHealth.Json("ExecuteRAgent", installed: true, "Running", "Automatic", Read(fileExists: true, clientId: ClientId));
Assert.DoesNotContain("very-secret-token", json);
Assert.DoesNotContain("\n", json);
// Shell scripts read fields with sed: the URL stays as written, no \u escapes.
Assert.Contains("\"serverUrl\":\"https://control.example.com:8443/a+b\"", json);
Assert.Contains("\"credential\":\"valid\"", json);
Assert.Contains("\"bootstrapTokenPending\":true", json);
using var document = JsonDocument.Parse(json);
var root = document.RootElement;
Assert.Equal("ExecuteRAgent", root.GetProperty("service").GetString());
Assert.True(root.GetProperty("installed").GetBoolean());
Assert.Equal("Running", root.GetProperty("state").GetString());
Assert.Equal("Automatic", root.GetProperty("startType").GetString());
Assert.Equal("1.4.0", root.GetProperty("version").GetString());
Assert.Equal(EnrollmentId.ToString("D"), root.GetProperty("enrollmentId").GetString());
Assert.Equal("2027-01-02T03:04:05.0000000+00:00", root.GetProperty("credentialExpiresUtc").GetString());
}
[Fact]
public void AnUnenrolledAgentWritesNulls()
{
var json = AgentHealth.Json("executer-agent", installed: false, "inactive", startType: null, Read(fileExists: false, clientId: ClientId));
using var document = JsonDocument.Parse(json);
var root = document.RootElement;
Assert.False(root.TryGetProperty("startType", out _));
Assert.Equal(JsonValueKind.Null, root.GetProperty("serverUrl").ValueKind);
Assert.Equal(JsonValueKind.Null, root.GetProperty("enrollmentId").ValueKind);
Assert.Equal("missing", root.GetProperty("credential").GetString());
}
private AgentHealth.Report Read(bool fileExists, string? clientId)
=> AgentHealth.Read(
new AgentConfigurationLoader(registry, allowEnvironment: false).Load(), credentials, fileExists, () => clientId, "1.4.0");
private static AgentCredentials Credential(string clientId)
=> new(AgentCredentials.CurrentVersion, clientId, EnrollmentId, "jwt", "seed", DateTimeOffset.UtcNow.AddDays(30));
private sealed class FixedCredentialStore : ICredentialStore
{
public AgentCredentials? Current { get; set; }
public AgentCredentials? Load() => Current;
public void Save(AgentCredentials credentials) => Current = credentials;
public void Delete() => Current = null;
}
}
+73
View File
@@ -315,4 +315,77 @@ public sealed class AgentLogsTests : IDisposable
follower.Poll();
Assert.Equal("fresh", follower.Live.Read(null, null).Lines[^1].Message);
}
[Fact]
public void AFollowedFileReadsTheFormat_AndLinesFromBeforeIt()
{
var path = Path.Combine(WatchdogFolder, "ExecuteR-Watchdog.log");
File.WriteAllText(
path,
"2026-11-06 10:00:00.000Z [WRN] from an older watchdog\n"
+ "[2026-11-06T10:00:01.500Z] - [MsiRunner] - [ERROR] - The MSI run failed code=1603\n"
+ " at a stack line\n");
var follower = new LogFileFollower(() => path);
follower.Poll();
var lines = follower.Live.Read(null, null).Lines;
Assert.Equal(["from an older watchdog", "The MSI run failed code=1603", " at a stack line"], lines.Select(l => l.Message));
Assert.Equal([LogLevels.Warning, LogLevels.Error, LogLevels.Information], lines.Select(l => l.Level));
Assert.Equal([null, "MsiRunner", null], lines.Select(l => l.Source));
Assert.Equal(new DateTimeOffset(2026, 11, 6, 10, 0, 1, 500, TimeSpan.Zero), lines[1].TimestampUtc);
}
[Fact]
public void TheWatchdogWritesTheOneFormat()
{
var written = new List<string>();
var watchdog = new WatchdogLog(directory: null, console: false);
watchdog.Written += written.Add;
watchdog.Warn("Agent beacon is stale");
watchdog.Error("It failed", new InvalidOperationException("broke"));
Assert.Matches(@"^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\] - \[Watchdog\] - \[WARN\] - Agent beacon is stale$", written[0]);
Assert.EndsWith(" - [Watchdog] - [ERROR] - It failed: broke", written[1]);
Assert.Equal(
"[2026-11-16T17:53:40.653Z] - [RemovalRunner] - [INFO] - Removed",
WatchdogLog.Format(new DateTimeOffset(2026, 11, 16, 18, 53, 40, 653, TimeSpan.FromHours(1)), "RemovalRunner", "INFO", "Removed"));
}
}
/// <summary>The screen host's stderr lines in the agent's log.</summary>
public sealed class ScreenHostLogTests
{
[Fact]
public void AHostLineIsLoggedOnce_AtItsLevel_UnderItsCategory()
{
var live = new LiveLog();
using (var serilog = LoggingSetup.CreateLogger(new LogSettings { Level = "Debug" }, "Agent", live))
using (var factory = new Serilog.Extensions.Logging.SerilogLoggerFactory(serilog))
{
var fallback = factory.CreateLogger("Agent.Screen.ScreenSessions");
Agent.Screen.ScreenHostLog.Relay(
"[2026-11-16T17:53:40.653Z] - [ScreenHost] - [WARN] - hardware H.264 encoder failed; using software reason=\"MFT busy\"", factory, fallback);
Agent.Screen.ScreenHostLog.Relay("[2026-11-16T17:53:40.700Z] - [ironrdp_server] - [DEBUG] - connected", factory, fallback);
Agent.Screen.ScreenHostLog.Relay("2026-11-16T17:53:40.653123Z ERROR executer_screen::session: refusing", factory, fallback);
Agent.Screen.ScreenHostLog.Relay("error: invalid --log-level 'x'", factory, fallback);
}
var lines = live.Read(null, null).Lines;
Assert.Equal(
["hardware H.264 encoder failed; using software reason=\"MFT busy\"", "connected", "refusing", "error: invalid --log-level 'x'"],
lines.Select(l => l.Message));
Assert.Equal([LogLevels.Warning, LogLevels.Debug, LogLevels.Error, LogLevels.Information], lines.Select(l => l.Level));
Assert.Equal(["ScreenHost", "ironrdp_server", "ScreenHost", "ScreenHost"], lines.Select(l => l.Source));
}
[Theory]
[InlineData(null, "ScreenHost")]
[InlineData("ScreenHost", "ScreenHost")]
[InlineData("executer_screen::video", "ScreenHost")]
[InlineData("ironrdp_server::server", "ironrdp_server")]
[InlineData("bad name with spaces", "ScreenHost")]
public void TheCategoryIsShortAndSafe(string? category, string expected)
=> Assert.Equal(expected, Agent.Screen.ScreenHostLog.CategoryOf(category));
}
+103
View File
@@ -0,0 +1,103 @@
using System.Security.Principal;
using System.Text;
using Agent.Platform;
using Agent.PowerShell;
using Agent.Sessions;
using Agent.Shell;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Xunit;
namespace Agent.Tests;
/// <summary>
/// The real thing: only as LocalSystem with someone signed in (run the suite as SYSTEM, e.g. from a
/// scheduled task, to exercise it). Elsewhere each test skips.
/// </summary>
public class RunAsUserLiveTests
{
private static SignedInUser RequireUser()
{
using var self = WindowsIdentity.GetCurrent();
Assert.SkipUnless(self.IsSystem, "Runs only as LocalSystem.");
var lookup = SignedInUsers.Default.Resolve();
Assert.SkipWhen(lookup.User is null, lookup.Reason ?? "Nobody is signed in.");
return lookup.User!;
}
[Fact]
public async Task WindowsPowerShellRunsAsTheSignedInUser()
{
var user = RequireUser();
var lines = new List<NormalizedOutputRecord>();
var result = await ExternalScriptRunner.RunAsync(
ScriptEngine.WindowsPowerShell,
"[Security.Principal.WindowsIdentity]::GetCurrent().Name; $env:USERPROFILE; (Get-Location).Path; $env:EXECUTER_JOB_DIR; Get-Content (Join-Path $env:EXECUTER_JOB_DIR 'probe.txt')",
prelude: null,
new Dictionary<string, object?>(),
secrets: null,
"Secrets",
record =>
{
lock (lines)
{
lines.Add(record);
}
},
TestContext.Current.CancellationToken,
runAs: user,
folder: WithProbe());
var output = string.Join("\n", lines.Select(l => $"{l.Stream}: {l.Text}"));
Assert.True(result.ExitCode == 0, output);
Assert.Contains(user.Name, output, StringComparison.OrdinalIgnoreCase);
Assert.Contains("probe-ok", output);
Assert.DoesNotContain(@"NT AUTHORITY\SYSTEM", output, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task ShellRunsAsTheSignedInUser()
{
var user = RequireUser();
using var token = WindowsUserToken.Open(user);
var environment = token.EnvironmentBlock(null);
var output = new StringBuilder();
var exited = new TaskCompletionSource();
using var pty = new ConPtySession(new PtyUser(token.Handle, environment, token.ProfileDirectory()));
pty.OutputReceived += data =>
{
lock (output)
{
output.Append(Encoding.UTF8.GetString(data.Span));
}
};
pty.Exited += () => exited.TrySetResult();
try
{
pty.Start(Path.Combine(Environment.SystemDirectory, "cmd.exe"), ["/c", "whoami"], 120, 30);
}
finally
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(environment);
}
await exited.Task.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken);
await Task.Delay(500, TestContext.Current.CancellationToken);
string text;
lock (output)
{
text = output.ToString();
}
var bare = user.Name.Split('\\').Last();
Assert.Contains(bare, text, StringComparison.OrdinalIgnoreCase);
}
private static JobFolder WithProbe()
{
var folder = JobFolder.Create(Path.Combine(Path.GetTempPath(), "executer-runas-" + Guid.NewGuid().ToString("N")), Guid.NewGuid());
folder.WriteHelper("probe.txt", "probe-ok");
return folder;
}
}
+188
View File
@@ -0,0 +1,188 @@
using System.Runtime.InteropServices;
using Agent.Platform;
using Agent.Sessions;
using Xunit;
namespace Agent.Tests;
public class RunAsUserTests
{
private sealed class FakeSessions(int? console, params SessionInfo[] sessions) : ISessionQuery
{
public int? ActiveConsoleSession() => console;
public IReadOnlyList<SessionInfo>? Enumerate() => sessions;
public SessionInfo? Query(int sessionId) => sessions.FirstOrDefault(s => s.SessionId == sessionId);
}
[Fact]
public void WindowsPicksTheConsoleUser()
{
var lookup = new WindowsSignedInUserResolver(new FakeSessions(
2, new SessionInfo(3, @"CONTOSO\bob", null), new SessionInfo(2, @"CONTOSO\ann", null))).Resolve();
Assert.Equal(new SignedInUser(@"CONTOSO\ann", 2), lookup.User);
}
[Fact]
public void WindowsFallsBackToTheOnlySignedInUser()
{
// Nobody at the console (it shows the logon screen); one remote session.
var lookup = new WindowsSignedInUserResolver(new FakeSessions(
1, new SessionInfo(1, null, null), new SessionInfo(4, @"CONTOSO\bob", null))).Resolve();
Assert.Equal(new SignedInUser(@"CONTOSO\bob", 4), lookup.User);
}
[Fact]
public void SeveralUsersAndNobodyAtTheConsolePicksNobody()
{
var lookup = new WindowsSignedInUserResolver(new FakeSessions(
null, new SessionInfo(3, @"CONTOSO\bob", null), new SessionInfo(4, @"CONTOSO\ann", null))).Resolve();
Assert.Null(lookup.User);
Assert.Contains(@"CONTOSO\ann, CONTOSO\bob", lookup.Reason);
Assert.Equal([@"CONTOSO\ann", @"CONTOSO\bob"], lookup.SignedIn);
}
[Fact]
public void AChosenSignedInUserIsUsedEvenWithSomeoneElseAtTheConsole()
{
var resolver = new WindowsSignedInUserResolver(new FakeSessions(
2, new SessionInfo(3, @"CONTOSO\bob", null), new SessionInfo(2, @"CONTOSO\ann", null), new SessionInfo(6, @"CONTOSO\bob", null)));
var lookup = resolver.Resolve(@"contoso\BOB");
Assert.Equal(new SignedInUser(@"CONTOSO\bob", 3), lookup.User);
Assert.Equal([@"CONTOSO\ann", @"CONTOSO\bob"], lookup.SignedIn);
}
[Fact]
public void AChosenUserWhoIsNotSignedInIsRefused()
{
var lookup = new WindowsSignedInUserResolver(new FakeSessions(
2, new SessionInfo(2, @"CONTOSO\ann", null))).Resolve(@"CONTOSO\administrator");
Assert.Null(lookup.User);
Assert.Contains("is not signed in", lookup.Reason);
Assert.Equal([@"CONTOSO\ann"], lookup.SignedIn);
}
[Fact]
public void LinuxCanChooseEitherRemoteUserButNeverRoot()
{
var resolver = new LinuxSignedInUserResolver(() =>
[
new LogonEvent("ann", 1, DateTimeOffset.UtcNow, "remote"),
new LogonEvent("bob", 2, DateTimeOffset.UtcNow, "remote"),
new LogonEvent("root", 3, DateTimeOffset.UtcNow, "remote"),
]);
Assert.Equal("bob", resolver.Resolve("bob").User?.Name);
Assert.Equal(["ann", "bob"], resolver.Resolve().SignedIn);
Assert.Null(resolver.Resolve("root").User);
}
[Fact]
public void MacOnlyOffersTheConsoleOwner()
{
var resolver = new MacSignedInUserResolver(() => "ann\n");
Assert.Equal("ann", resolver.Resolve("ann").User?.Name);
Assert.Null(resolver.Resolve("bob").User);
Assert.Equal(["ann"], resolver.Resolve("bob").SignedIn);
}
[Fact]
public void OneUserInSeveralSessionsIsStillOneUser()
{
var lookup = new WindowsSignedInUserResolver(new FakeSessions(
null, new SessionInfo(3, @"CONTOSO\bob", null), new SessionInfo(5, @"contoso\BOB", null))).Resolve();
Assert.Equal(3, lookup.User?.WindowsSession);
}
[Fact]
public void NobodySignedIn()
{
var lookup = new WindowsSignedInUserResolver(new FakeSessions(1, new SessionInfo(1, null, null))).Resolve();
Assert.Null(lookup.User);
Assert.Equal(SignedInUsers.NobodyReason, lookup.Reason);
}
[Fact]
public void LinuxPrefersTheLocalUserOverRemoteOnes()
{
var resolver = new LinuxSignedInUserResolver(() =>
[
new LogonEvent("ann", 1, DateTimeOffset.UtcNow, "local"),
new LogonEvent("bob", 2, DateTimeOffset.UtcNow, "remote"),
new LogonEvent("root", 3, DateTimeOffset.UtcNow, "local"),
]);
Assert.Equal("ann", resolver.Resolve().User?.Name);
}
[Fact]
public void LinuxWithTwoRemoteUsersPicksNobody()
{
var resolver = new LinuxSignedInUserResolver(() =>
[
new LogonEvent("ann", 1, DateTimeOffset.UtcNow, "remote"),
new LogonEvent("bob", 2, DateTimeOffset.UtcNow, "remote"),
]);
Assert.Null(resolver.Resolve().User);
}
[Fact]
public void LinuxWithoutLoginctlSaysSo()
=> Assert.Contains("loginctl", new LinuxSignedInUserResolver(() => null).Resolve().Reason);
[Theory]
[InlineData("ann", "ann")]
[InlineData("root", null)]
[InlineData("_mbsetupuser", null)]
[InlineData("", null)]
public void MacUsesTheConsoleOwner(string owner, string? expected)
=> Assert.Equal(expected, new MacSignedInUserResolver(() => owner + "\n").Resolve().User?.Name);
[Fact]
public void EnvironmentBlocksRoundTripSorted()
{
var block = WindowsUserToken.BuildBlock(
[
new("Path", @"C:\Windows"),
new("ApiKey", "a=b"),
new("=C:", @"C:\work"),
]);
Assert.Equal("=C:=C:\\work\0ApiKey=a=b\0Path=C:\\Windows\0\0", block);
var native = Marshal.StringToHGlobalUni(block);
try
{
Assert.Equal(
[new("=C:", @"C:\work"), new("ApiKey", "a=b"), new("Path", @"C:\Windows")],
WindowsUserToken.ReadBlock(native).ToList());
}
finally
{
Marshal.FreeHGlobal(native);
}
}
[Fact]
public void AnEmptyEnvironmentIsTwoNuls() => Assert.Equal("\0\0", WindowsUserToken.BuildBlock([]));
[Fact]
public void ModulePathIsAppendedOnce()
{
Assert.Equal(@"C:\Users\ann\Documents\PowerShell\Modules;C:\Agent\Modules",
WindowsUserToken.AppendPath(@"C:\Users\ann\Documents\PowerShell\Modules", @"C:\Agent\Modules"));
Assert.Equal(@"C:\a;c:\agent\modules", WindowsUserToken.AppendPath(@"C:\a;c:\agent\modules", @"C:\Agent\Modules"));
Assert.Equal(@"C:\Agent\Modules", WindowsUserToken.AppendPath(null, @"C:\Agent\Modules"));
}
}
+165
View File
@@ -0,0 +1,165 @@
using Agent.PowerShell;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Xunit;
namespace Agent.Tests;
public class ScriptGroupReportTests
{
private const string Script = """
Set-ExecuteRGroupMembership 'Bool True' $true
Set-ExecuteRGroupMembership 'Bool False' $false
Set-ExecuteRGroupMembership 'Count Three' 3
Set-ExecuteRGroupMembership 'Count Zero' 0
Set-ExecuteRGroupMembership 'Text No' 'no'
Set-ExecuteRGroupMembership 'Text Yes' 'present'
Set-ExecuteRGroupMembership 'Empty Array' @()
Set-ExecuteRGroupMembership 'Null' $null
1, 2 | Set-ExecuteRGroupMembership 'Piped Two'
@() | Set-ExecuteRGroupMembership 'Piped None'
Get-ChildItem -Path $env:windir -Filter 'no-such-file-*.xyz' | Set-ExecuteRGroupMembership 'Piped Nothing Found'
Add-ExecuteRGroupMembership 'Added'
Remove-ExecuteRGroupMembership 'Removed'
Add-ExecuteRGroupMembership 'Last Wins'
Remove-ExecuteRGroupMembership 'last wins'
Write-Output 'done'
""";
private static readonly Dictionary<string, bool> Expected = new()
{
["Bool True"] = true,
["Bool False"] = false,
["Count Three"] = true,
["Count Zero"] = false,
["Text No"] = false,
["Text Yes"] = true,
["Empty Array"] = false,
["Null"] = false,
["Piped Two"] = true,
["Piped None"] = false,
["Piped Nothing Found"] = false,
["Added"] = true,
["Removed"] = false,
["last wins"] = false,
};
private static void AssertReports(ScriptGroupReportCollector collector, List<NormalizedOutputRecord> published)
{
var reports = collector.Reports!.ToDictionary(r => r.Group, r => r.Member);
Assert.Equal(Expected.OrderBy(e => e.Key), reports.OrderBy(e => e.Key));
Assert.DoesNotContain(published, r => r.Text.Contains(ScriptGroups.Marker));
Assert.Contains(published, r => r.Text == "Script group “Added”: this device is a member.");
Assert.Contains(published, r => r.Text.Contains("done"));
}
[Fact]
public async Task PowerShell7BuiltInsDecideMembership()
{
var collector = new ScriptGroupReportCollector();
var published = new List<NormalizedOutputRecord>();
var result = await new PowerShellExecutionService().ExecuteAsync(
Script,
parameters: null,
prelude: ScriptGroupBuiltIns.Compose(ScriptEngine.PowerShell, null),
onRecord: r =>
{
lock (published)
{
published.Add(collector.Take(r));
}
},
onProgress: _ => { },
cancellationToken: TestContext.Current.CancellationToken);
Assert.False(result.HadErrors, string.Join("\n", published.Select(p => p.Text)));
AssertReports(collector, published);
}
[Fact]
public async Task WindowsPowerShellBuiltInsDecideMembership()
{
var collector = new ScriptGroupReportCollector();
var published = new List<NormalizedOutputRecord>();
var result = await ExternalScriptRunner.RunAsync(
ScriptEngine.WindowsPowerShell,
Script,
prelude: ScriptGroupBuiltIns.Compose(ScriptEngine.WindowsPowerShell, null),
parameters: new Dictionary<string, object?>(),
secrets: null,
"Secrets",
r =>
{
lock (published)
{
published.Add(collector.Take(r));
}
},
TestContext.Current.CancellationToken);
Assert.True(result.ExitCode == 0, string.Join("\n", published.Select(p => p.Text)));
AssertReports(collector, published);
}
[Fact]
public async Task BashBuiltInDecidesMembership()
{
Assert.SkipUnless(ExternalScriptRunner.IsAvailable(ScriptEngine.Bash), "bash is not installed.");
var collector = new ScriptGroupReportCollector();
var published = new List<NormalizedOutputRecord>();
var result = await ExternalScriptRunner.RunAsync(
ScriptEngine.Bash,
"""
executer_group "Yes"
executer_group "Count" "$(printf 'a\nb\n' | wc -l)"
executer_group "Zero" 0
executer_group "Word" "False"
executer_group 'Quote "and" \slash' true
echo done
""",
prelude: ScriptGroupBuiltIns.Compose(ScriptEngine.Bash, null),
parameters: new Dictionary<string, object?>(),
secrets: null,
"Secrets",
r =>
{
lock (published)
{
published.Add(collector.Take(r));
}
},
TestContext.Current.CancellationToken);
Assert.True(result.ExitCode == 0, string.Join("\n", published.Select(p => p.Text)));
var reports = collector.Reports!.ToDictionary(r => r.Group, r => r.Member);
Assert.True(reports["Yes"]);
Assert.True(reports["Count"]);
Assert.False(reports["Zero"]);
Assert.False(reports["Word"]);
// A backslash makes the name unusable: reported as a warning, not kept.
Assert.DoesNotContain(reports.Keys, k => k.Contains("Quote"));
Assert.Contains(published, r => r.Stream == OutputStreamKind.Warning && r.Text.Contains("Quote \"and\""));
}
[Fact]
public void LinesThatOnlyLookLikeReportsAreLeftAlone()
{
var collector = new ScriptGroupReportCollector();
var line = new NormalizedOutputRecord(OutputStreamKind.Output, ScriptGroups.Marker + "{not json");
Assert.Same(line, collector.Take(line));
Assert.Null(collector.Reports);
}
[Fact]
public void AJobReportsOnAtMostTheLimit()
{
var collector = new ScriptGroupReportCollector();
for (var i = 0; i < ScriptGroups.MaxReportsPerJob + 3; i++)
{
collector.Take(new NormalizedOutputRecord(OutputStreamKind.Information, $"{ScriptGroups.Marker}{{\"group\":\"G{i}\",\"member\":true}}"));
}
Assert.Equal(ScriptGroups.MaxReportsPerJob, collector.Reports!.Count);
}
}
@@ -25,7 +25,7 @@ public class CertificateTrustScriptTests(BackendTestFixture fixture) : IClassFix
// The one-liner's accept-any is undone before anything is downloaded.
var reset = script.IndexOf("ServerCertificateValidationCallback = $null", StringComparison.Ordinal);
var firstDownload = script.IndexOf("Save-ExecuteRFile '", StringComparison.Ordinal);
var firstDownload = script.IndexOf("Save-ExecuteRFile $", StringComparison.Ordinal);
Assert.True(reset >= 0 && reset < firstDownload, "validation is restored before the first download");
Assert.Contains($"$global:ExecuteRCaPin = '{Fingerprint}'", script);
Assert.Contains("TrustFailure", script);
@@ -0,0 +1,737 @@
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using Backend.Enrollment;
using Shared.Contracts.Models;
using Xunit;
namespace Backend.Tests;
/// <summary>
/// The served install scripts are safe to run any number of times: they parse (Windows
/// PowerShell 5.1, PowerShell 7, bash), decide from what is on the device between leaving
/// it alone, installing, upgrading, repairing and re-enrolling, and never print the token.
/// The decisions run the scripts' own functions against described device states; nothing
/// is installed.
/// </summary>
public partial class InstallScriptRepairTests
{
private const string Server = "https://control.example.com";
private const string Token = "s3cret-token.0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0";
private const string Fingerprint = "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0";
public static TheoryData<string> WindowsVariants => ["msi", "msi-pinned", "zip", "quote"];
public static TheoryData<string> UnixVariants => ["linux", "linux-pinned", "osx", "osx-pinned", "quote"];
private static string WindowsScript(string variant) => variant switch
{
"msi" => InstallEndpoints.BuildWindowsScript(Server, Token, $"{Server}/msi?token=t", $"{Server}/zip?token=t", "1.5.0", "1.5.0", false, null),
"msi-pinned" => InstallEndpoints.BuildWindowsScript(Server, Token, $"{Server}/msi?token=t", $"{Server}/zip?token=t", "1.5.0", null, false, Fingerprint),
"zip" => InstallEndpoints.BuildWindowsScript(Server, Token, null, $"{Server}/zip?token=t", null, "1.5.0.3", true, null),
_ => InstallEndpoints.BuildWindowsScript(Server, "it's", $"{Server}/msi?token=t", $"{Server}/zip?token=t", null, null, false, null),
};
private static string UnixScript(string variant) => variant switch
{
"linux" => InstallEndpoints.BuildUnixScript(Server, Token, "linux", "token=t", false, null, "1.5.0", "1.5.0"),
"linux-pinned" => InstallEndpoints.BuildUnixScript(Server, Token, "linux", "token=t", false, Fingerprint, "1.5.0", null),
"osx" => InstallEndpoints.BuildUnixScript(Server, Token, "osx", "token=t", true, null, null, "1.5.0"),
"osx-pinned" => InstallEndpoints.BuildUnixScript(Server, Token, "osx", "token=t", false, Fingerprint, "1.5.0", "1.5.0"),
_ => InstallEndpoints.BuildUnixScript(Server, "it's", "linux", "token=t", false, null, null, null),
};
[Theory]
[MemberData(nameof(WindowsVariants))]
public async Task WindowsScriptsParseInWindowsPowerShellAndPowerShell7(string variant)
{
var shells = new[] { WindowsPowerShell(), Pwsh() }.OfType<string>().ToList();
Assert.SkipWhen(shells.Count == 0, "Needs Windows PowerShell or pwsh.");
var check = """
$tokens = $null; $errors = $null
[void][System.Management.Automation.Language.Parser]::ParseInput([IO.File]::ReadAllText($args[0]), [ref]$tokens, [ref]$errors)
$errors | ForEach-Object { $_.Message + ' (line ' + $_.Extent.StartLineNumber + ')' }
exit $errors.Count
""";
using var folder = new ScratchFolder();
var script = folder.Write("install.ps1", WindowsScript(variant));
var checker = folder.Write("check.ps1", check);
foreach (var shell in shells)
{
var (code, output, _) = await RunAsync(shell, $"-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{checker}\" \"{script}\"");
Assert.True(code == 0, $"{Path.GetFileName(shell)}: {output}");
}
}
[Theory]
[MemberData(nameof(UnixVariants))]
public async Task UnixScriptsPassBashSyntaxCheck(string variant)
{
var bash = Bash();
Assert.SkipWhen(bash is null, "Needs bash (Git Bash on Windows).");
using var folder = new ScratchFolder();
var script = folder.Write("install.sh", UnixScript(variant));
var (code, output, _) = await RunAsync(bash!, $"-n \"{ForBash(script)}\"");
Assert.True(code == 0, output);
Assert.DoesNotContain("\r", UnixScript(variant));
}
[Fact]
public void TheTokenAndServerAreQuotedForEachShell()
{
Assert.Contains("$token = 'it''s'", WindowsScript("quote"));
Assert.Contains("token='it'\\''s'", UnixScript("quote"));
Assert.Equal("'a''b'", InstallEndpoints.PsQuote("a'b"));
Assert.Equal("'a'\\''b'", InstallEndpoints.ShQuote("a'b"));
}
[Fact]
public void TheServedVersionIsEmbeddedForTheComparison()
{
var msi = WindowsScript("msi");
Assert.Contains("$msiVersion = '1.5.0'", msi);
Assert.Contains("$portableOnly = $false", msi);
var zip = WindowsScript("zip");
Assert.Contains("$msiUrl = ''", zip);
Assert.Contains("$zipVersion = '1.5.0.3'", zip);
Assert.Contains("$portableOnly = $true", zip);
var osx = UnixScript("osx");
Assert.Contains("x64) target='' ;;", osx);
Assert.Contains("*) target='1.5.0' ;;", osx);
}
[Theory]
[InlineData("1.4.0", "1.4.0")]
[InlineData(" 1.4.0.7+1a2b3c4 ", "1.4.0.7+1a2b3c4")]
[InlineData("2026.10.23.1400", "2026.10.23.1400")]
[InlineData("0.0.0.0", null)]
[InlineData("1.4", null)]
[InlineData("1.4.0'; rm -rf /", null)]
[InlineData(null, null)]
public void OnlyAVersionTheComparisonUnderstandsGoesIntoAScript(string? version, string? expected)
=> Assert.Equal(expected, InstallEndpoints.ScriptSafeVersion(version));
[Theory]
[MemberData(nameof(WindowsVariants))]
public void TheWindowsTokenIsOnlyEverHandedToWindowsInstallerOrTheRegistry(string variant)
{
// Allowed: the assignment, masking it out of an error, msiexec's (hidden) property,
// the registry value the agent reads, and comparing it with a pending one.
string[] allowed =
[
@"^\$token = '",
@"^if \(\$token -and \$Text\) \{ return \$Text\.Replace\(\$token, '<token>'\) \}$",
@"^if \(\$Enroll\) \{ \$arguments \+= ""BOOTSTRAPTOKEN=\$token"" \}$",
@"Set-ItemProperty -Path \$executerKey -Name 'BootstrapToken' -Value \$token( \})?$",
@"^\$state\.TokenIsOurs = \[bool\]\(\$pending -and \$pending -ceq \$token\)$",
];
var script = WindowsScript(variant);
foreach (var line in Lines(script).Where(l => TokenVariable().IsMatch(l)))
{
Assert.True(allowed.Any(pattern => Regex.IsMatch(line, pattern)), $"unexpected use of $token: {line}");
}
if (variant != "quote")
{
Assert.Single(Lines(script), l => l.Contains(Token, StringComparison.Ordinal));
}
}
[Theory]
[MemberData(nameof(UnixVariants))]
public void TheUnixTokenIsOnlyEverHandedToTheAgentsConfiguration(string variant)
{
string[] allowed =
[
@"^token='",
@"^""\$exe"" configure --url ""\$server"" --token ""\$token"" >/dev/null$",
@"^if \[ ""\$pending"" = ""\$token"" \]; then pending_ours=1; fi$",
];
var script = UnixScript(variant);
foreach (var line in Lines(script).Where(l => TokenVariable().IsMatch(l)))
{
Assert.True(allowed.Any(pattern => Regex.IsMatch(line, pattern)), $"unexpected use of $token: {line}");
}
if (variant != "quote")
{
Assert.Single(Lines(script), l => l.Contains(Token, StringComparison.Ordinal));
}
}
[Theory]
[MemberData(nameof(WindowsVariants))]
public void WindowsScriptsEndWithOneOutcomeAndExitNonZeroOnFailure(string variant)
{
var script = WindowsScript(variant);
foreach (var outcome in new[] { "'Already Installed: ExecuteR Agent '", "{ 'Installed' }", "{ 'Upgraded' }", "{ 'Repaired' }", "('Failed: ' + $reason)" })
{
Assert.Contains(outcome, script);
}
Assert.Contains("if ($launchedForThis) { exit 1 }", script);
Assert.EndsWith("}", script.TrimEnd());
// Interrupted runs: one setup at a time, leftovers cleared, a kept enrollment put back.
Assert.Contains(@"'Global\ExecuteRAgentSetup'", script);
Assert.Contains("Clear-ExecuteRLeftovers", script);
Assert.Contains(@"'Global\_MSIExecute'", script);
Assert.Contains("Restore-ExecuteRKept", script);
}
[Theory]
[MemberData(nameof(UnixVariants))]
public void UnixScriptsRunEverythingFromTheLastLine(string variant)
{
var script = UnixScript(variant);
Assert.Equal("main", Lines(script).Last());
foreach (var outcome in new[] { "echo \"Already Installed: ExecuteR Agent", "outcome=Installed", "outcome=Upgraded", "outcome=Repaired", "echo \"Failed: $*\"" })
{
Assert.Contains(outcome, script);
}
Assert.Contains("mkdir \"$lock\"", script);
Assert.Contains("rm -rf \"$dest.staging\"", script);
}
/// <summary>A device state for the Windows plan: healthy, current (1.5.0), MSI, enrolled with this server.</summary>
private const string PsHealthy = """
@{ Present = $true; ExeExists = $true; ExeWorks = $true; Version = '1.5.0'; ServerUrl = 'https://control.example.com';
PolicyServerUrl = $null; Credential = 'valid'; TokenPending = $false; TokenIsOurs = $false; MsiMarker = $true;
Msi = @{ ProductCode = '{A}'; Version = '1.5.0.0'; CacheOk = $true };
Agent = @{ Exists = $true; Status = 'Running'; StartType = 'Automatic' };
Watchdog = @{ Exists = $true; Status = 'Running'; StartType = 'Automatic' }; WatchdogExpected = $true }
""";
private static readonly (string Name, string Changes, string Target, string Kind, string Action, bool Enroll, bool Pending)[] WindowsPlans =
{
// name, state changes, target, msi or zip script, expected action, enroll, enrollment pending
("healthy and current", "", "1.5.0", "msi", "None", false, false),
("healthy and newer than the server", "$s.Version = '1.6.0'", "1.5.0", "msi", "None", false, false),
("no package version known", "", "", "msi", "None", false, false),
("server with a trailing slash and other case", "$s.ServerUrl = 'HTTPS://Control.Example.com/'", "1.5.0", "msi", "None", false, false),
("nothing installed", "$s = @{ Present = $false }", "1.5.0", "msi", "Install", true, false),
("older", "$s.Version = '1.4.9'", "1.5.0", "msi", "Upgrade", false, false),
("a calendar-era build", "$s.Version = '2026.10.23.1400'", "1.5.0", "msi", "Upgrade", false, false),
("older and enrolled elsewhere", "$s.Version = '1.4.9'; $s.ServerUrl = 'https://old.example.com'", "1.5.0", "msi", "Upgrade", true, false),
("service stopped", "$s.Agent.Status = 'Stopped'", "1.5.0", "msi", "Repair", false, false),
("service disabled", "$s.Agent.StartType = 'Disabled'; $s.Agent.Status = 'Stopped'", "1.5.0", "msi", "Repair", false, false),
("service missing", "$s.Agent = @{ Exists = $false; Status = 'Missing'; StartType = 'Missing' }", "1.5.0", "msi", "Repair", false, false),
("watchdog stopped", "$s.Watchdog.Status = 'Stopped'", "1.5.0", "msi", "Repair", false, false),
("binary missing", "$s.ExeExists = $false; $s.ExeWorks = $false; $s.Version = $null", "1.5.0", "msi", "Repair", false, false),
("binary broken", "$s.ExeWorks = $false; $s.Version = $null", "1.5.0", "msi", "Repair", false, false),
("Windows Installer cache missing", "$s.Msi.CacheOk = $false", "1.5.0", "msi", "Repair", false, false),
("Windows Installer registration gone", "$s.Msi = $null", "1.5.0", "msi", "Repair", false, false),
("portable: no MSI is fine", "$s.Msi = $null; $s.MsiMarker = $false", "1.5.0", "zip", "None", false, false),
("enrolled elsewhere", "$s.ServerUrl = 'https://old.example.com'", "1.5.0", "msi", "Enroll", true, false),
("no server configured", "$s.ServerUrl = $null", "1.5.0", "msi", "Enroll", true, false),
("credential missing", "$s.Credential = 'missing'", "1.5.0", "msi", "Enroll", true, false),
("credential unreadable", "$s.Credential = 'unreadable'", "1.5.0", "msi", "Enroll", true, false),
("credential of other hardware", "$s.Credential = 'other-device'", "1.5.0", "msi", "Enroll", true, false),
("enrolling with this token already", "$s.Credential = 'missing'; $s.TokenPending = $true; $s.TokenIsOurs = $true", "1.5.0", "msi", "None", false, true),
("a pending token of another run", "$s.Credential = 'missing'; $s.TokenPending = $true", "1.5.0", "msi", "Enroll", true, false),
("stopped and without credential", "$s.Agent.Status = 'Stopped'; $s.Credential = 'missing'", "1.5.0", "msi", "Repair", true, false),
};
[Fact]
public async Task WindowsPlansFollowTheDeviceState()
{
var shell = WindowsPowerShell() ?? Pwsh();
Assert.SkipWhen(shell is null, "Needs Windows PowerShell or pwsh.");
var body = new StringBuilder("""
$server = 'https://control.example.com'
$token = 'tok'
$msiUrl = 'x'; $zipUrl = 'x'; $msiVersion = ''; $zipVersion = ''; $portableOnly = $false
""");
body.AppendLine(InstallScripts.WindowsFunctions);
var cases = WindowsPlans;
for (var i = 0; i < cases.Length; i++)
{
body.AppendLine($"$s = {PsHealthy}");
body.AppendLine(cases[i].Changes);
body.AppendLine($"$p = Get-ExecuteRPlan $s '{cases[i].Target}' ${(cases[i].Kind == "zip" ? "true" : "false")}");
body.AppendLine($"Write-Output ('{i}=' + $p.Action + '|' + $p.Enroll + '|' + $p.EnrollPending)");
}
using var folder = new ScratchFolder();
var script = folder.Write("plans.ps1", body.ToString());
var (code, output, _) = await RunAsync(shell!, $"-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{script}\"");
Assert.True(code == 0, output);
var results = Results(output);
for (var i = 0; i < cases.Length; i++)
{
var expected = $"{cases[i].Action}|{(cases[i].Enroll ? "True" : "False")}|{(cases[i].Pending ? "True" : "False")}";
Assert.True(results.TryGetValue(i.ToString(), out var actual) && actual == expected, $"{cases[i].Name}: expected {expected}, got {actual}\n{output}");
}
}
/// <summary>A device state for the unix plan: healthy, current (1.5.0), enrolled with this server.</summary>
private const string ShHealthy =
"present=1 works=1 version=1.5.0 configured=https://control.example.com credential=valid token_pending=0 pending_ours=0 "
+ "registered=1 agent_running=1 agent_disabled=0 watchdog_expected=1 watchdog_running=1";
private static readonly (string Name, string Changes, string Target, string Action, string Enroll, string Pending)[] UnixPlans =
{
// name, state changes, target, expected action, enroll, enrollment pending
("healthy and current", "", "1.5.0", "none", "0", "0"),
("healthy and newer than the server", "version=1.6.0", "1.5.0", "none", "0", "0"),
("no package version known", "", "", "none", "0", "0"),
("server with a trailing slash and other case", "configured=HTTPS://Control.Example.com/", "1.5.0", "none", "0", "0"),
("nothing installed", "present=0 works=0 registered=0 agent_running=0 watchdog_expected=0 watchdog_running=0", "1.5.0", "install", "1", "0"),
("older", "version=1.4.9", "1.5.0", "upgrade", "0", "0"),
("a calendar-era build", "version=2026.10.23.1400", "1.5.0", "upgrade", "0", "0"),
("older and enrolled elsewhere", "version=1.4.9 configured=https://old.example.com", "1.5.0", "upgrade", "1", "0"),
("service stopped", "agent_running=0", "1.5.0", "repair", "0", "0"),
("service disabled", "agent_running=0 agent_disabled=1", "1.5.0", "repair", "0", "0"),
("service not registered", "registered=0", "1.5.0", "repair", "0", "0"),
("watchdog stopped", "watchdog_running=0", "1.5.0", "repair", "0", "0"),
("binary broken", "works=0 version=", "1.5.0", "repair", "0", "0"),
("enrolled elsewhere", "configured=https://old.example.com", "1.5.0", "enroll", "1", "0"),
("no server configured", "configured=", "1.5.0", "enroll", "1", "0"),
("credential missing", "credential=missing", "1.5.0", "enroll", "1", "0"),
("credential of other hardware", "credential=other-device", "1.5.0", "enroll", "1", "0"),
("enrolling with this token already", "credential=missing token_pending=1 pending_ours=1", "1.5.0", "none", "0", "1"),
("a pending token of another run", "credential=missing token_pending=1", "1.5.0", "enroll", "1", "0"),
("stopped and without credential", "agent_running=0 credential=missing", "1.5.0", "repair", "1", "0"),
};
[Fact]
public async Task UnixPlansFollowTheDeviceState()
{
var bash = Bash();
Assert.SkipWhen(bash is null, "Needs bash (Git Bash on Windows).");
var body = new StringBuilder("""
set -euo pipefail
server='https://control.example.com'
token='tok'
os=linux arch=x64 pkg=x dest=/nonexistent/executer tmp=/nonexistent reported=0 locked=0 lock=/nonexistent/lock
""");
body.Append(InstallScripts.UnixFunctions.ReplaceLineEndings("\n")).Append('\n');
var cases = UnixPlans;
for (var i = 0; i < cases.Length; i++)
{
body.Append($"{ShHealthy}\n{cases[i].Changes}\ntarget='{cases[i].Target}'\nplan\necho \"{i}=$action|$enroll|$enroll_pending\"\n");
}
using var folder = new ScratchFolder();
var script = folder.Write("plans.sh", body.ToString());
var (code, output, _) = await RunAsync(bash!, $"\"{ForBash(script)}\"");
Assert.True(code == 0, output);
var results = Results(output);
for (var i = 0; i < cases.Length; i++)
{
var expected = $"{cases[i].Action}|{cases[i].Enroll}|{cases[i].Pending}";
Assert.True(results.TryGetValue(i.ToString(), out var actual) && actual == expected, $"{cases[i].Name}: expected {expected}, got {actual}\n{output}");
}
}
private static readonly (string Left, string Right)[] VersionPairs =
[
("1.5.0", "1.4.9"), ("1.4.9", "1.5.0"), ("1.5.0", "1.5.0.0"), ("1.5.0.1", "1.5.0"), ("1.5.0+abc", "1.5.0"),
("1.10.0", "1.9.0"), ("1.5.0", "2026.10.23.1400"), ("2026.10.23.1400", "2026.10.22.2359"), ("1.5.0", ""),
("", "1.5.0"), ("0.0.0.0", "1.0.0"), ("1.5", "1.5.0"), ("01.05.00", "1.5.0"), ("", ""), ("junk", "junk"),
];
[Fact]
public async Task WindowsVersionsCompareAsTheServerDoes()
{
var shell = WindowsPowerShell() ?? Pwsh();
Assert.SkipWhen(shell is null, "Needs Windows PowerShell or pwsh.");
var body = new StringBuilder("$server = 'x'; $token = 'x'\n").AppendLine(InstallScripts.WindowsFunctions);
for (var i = 0; i < VersionPairs.Length; i++)
{
body.AppendLine($"Write-Output ('{i}=' + (Compare-ExecuteRVersion '{VersionPairs[i].Left}' '{VersionPairs[i].Right}'))");
}
using var folder = new ScratchFolder();
var (code, output, _) = await RunAsync(shell!, $"-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{folder.Write("versions.ps1", body.ToString())}\"");
Assert.True(code == 0, output);
AssertVersionResults(Results(output), output);
}
[Fact]
public async Task UnixVersionsCompareAsTheServerDoes()
{
var bash = Bash();
Assert.SkipWhen(bash is null, "Needs bash (Git Bash on Windows).");
var body = new StringBuilder("set -euo pipefail\ndest=/nonexistent\n").Append(InstallScripts.UnixFunctions.ReplaceLineEndings("\n")).Append('\n');
for (var i = 0; i < VersionPairs.Length; i++)
{
body.Append($"echo \"{i}=$(version_compare '{VersionPairs[i].Left}' '{VersionPairs[i].Right}')\"\n");
}
using var folder = new ScratchFolder();
var (code, output, _) = await RunAsync(bash!, $"\"{ForBash(folder.Write("versions.sh", body.ToString()))}\"");
Assert.True(code == 0, output);
AssertVersionResults(Results(output), output);
}
/// <summary>
/// A stand-in for executer-agent: version, status (the JSON line), configure and
/// initialize, keeping its state in files under FAKE_STATE and noting each call
/// (configure with a token as configure-token, never the token itself).
/// </summary>
private const string FakeUnixAgent = """
#!/usr/bin/env bash
here=$(cd "$(dirname "$0")" && pwd)
S="$FAKE_STATE"
enroll() { if [ -f "$S/token" ]; then echo valid > "$S/credential"; rm -f "$S/token"; fi; }
case "$1" in
version) echo version >> "$S/calls"; cat "$here/AGENT_VERSION" ;;
status)
echo status >> "$S/calls"
srv=null; if [ -f "$S/server" ]; then srv="\"$(cat "$S/server")\""; fi
cred=missing; if [ -f "$S/credential" ]; then cred=$(cat "$S/credential"); fi
pending=false; if [ -f "$S/token" ]; then pending=true; fi
echo "{\"service\":\"executer-agent\",\"installed\":true,\"state\":\"active\",\"version\":\"$(cat "$here/AGENT_VERSION")\",\"serverUrl\":$srv,\"credential\":\"$cred\",\"enrollmentId\":null,\"credentialExpiresUtc\":null,\"bootstrapTokenPending\":$pending}"
echo "Service 'ExecuteR Agent': active" ;;
configure)
shift
call=configure
while [ $# -gt 0 ]; do
case "$1" in
--url) printf '%s' "$2" > "$S/server"; shift 2 ;;
--token) printf '%s' "$2" > "$S/token"; call=configure-token; shift 2 ;;
*) shift ;;
esac
done
echo "$call" >> "$S/calls" ;;
initialize)
echo initialize >> "$S/calls"
if [ -f "$S/fail-initialize" ]; then echo 'cannot register the service' >&2; exit 3; fi
touch "$S/registered.agent" "$S/running.executer-agent" "$S/running.executer-watchdog"
enroll
echo 'systemd unit executer-agent installed.' ;;
esac
""";
/// <summary>The service manager and the package download, stood in for after the script's own functions.</summary>
private const string UnixOverrides = """
mac=0
sleep() { case "$1" in 0.*) command sleep "$1" ;; esac; }
download() { : > "$2"; }
unpack() { cp -R "$FAKE_PACKAGE/." "$2/"; }
svc_registered() { [ -f "$FAKE_STATE/registered.$1" ]; }
systemctl() {
local verb=$1 u
shift
if [ "${1:-}" = --quiet ]; then shift; fi
case "$verb" in
is-active) [ -f "$FAKE_STATE/running.$1" ] ;;
is-enabled) echo enabled ;;
stop) for u in "$@"; do rm -f "$FAKE_STATE/running.$u"; done ;;
restart)
touch "$FAKE_STATE/running.$1"
if [ -f "$FAKE_STATE/token" ]; then echo valid > "$FAKE_STATE/credential"; rm -f "$FAKE_STATE/token"; fi ;;
*) return 0 ;;
esac
}
""";
[Fact]
public async Task TheUnixScriptInstallsThenLeavesAloneRepairsUpgradesAndReEnrolls()
{
var bash = Bash();
Assert.SkipWhen(bash is null, "Needs bash (Git Bash on Windows).");
using var folder = new ScratchFolder();
var root = ForBash(folder.Path);
var state = Directory.CreateDirectory(Path.Combine(folder.Path, "state")).FullName;
var package = Directory.CreateDirectory(Path.Combine(folder.Path, "package")).FullName;
Directory.CreateDirectory(Path.Combine(folder.Path, "tmp"));
File.WriteAllText(Path.Combine(package, "executer-agent"), FakeUnixAgent.ReplaceLineEndings("\n"));
File.WriteAllText(Path.Combine(package, "executer-watchdog"), "#!/usr/bin/env bash\n");
File.WriteAllText(Path.Combine(package, "AGENT_VERSION"), "1.5.0\n");
var dest = Path.Combine(folder.Path, "opt", "agent");
var calls = Path.Combine(state, "calls");
async Task<(int Code, string Last, string[] Calls, string Output)> Run(string target)
{
var before = File.Exists(calls) ? File.ReadAllLines(calls).Length : 0;
var script = InstallEndpoints.BuildUnixScript(Server, Token, "linux", "token=t", false, null, target, target)
.Replace("if [ \"$(id -u)\" -ne 0 ]; then echo 'Failed: run with sudo/root.' >&2; exit 1; fi\n", "")
.Replace("dest=/opt/executer/agent\n", $"dest='{root}/opt/agent'\n")
.Replace("lock=/var/run/executer-install.lock\n", $"lock='{root}/lock'\n");
Assert.EndsWith("\nmain", script.TrimEnd());
script = script.TrimEnd()[..^"main".Length] + UnixOverrides.ReplaceLineEndings("\n") + "\nmain\n";
var (code, output, stdout) = await RunAsync(bash!, $"\"{ForBash(folder.Write("install.sh", script))}\"", new()
{
["FAKE_STATE"] = ForBash(state),
["FAKE_PACKAGE"] = ForBash(package),
["TMPDIR"] = $"{root}/tmp",
});
Assert.DoesNotContain(Token, output);
var all = File.Exists(calls) ? File.ReadAllLines(calls) : [];
return (code, Lines(stdout).Last(), all[before..], output);
}
// Nothing there: installed and enrolled with the token.
var run = await Run("1.5.0");
Assert.True(run.Code == 0, run.Output);
Assert.StartsWith("Installed: ExecuteR Agent 1.5.0 is running for https://control.example.com, enrolled", run.Last);
Assert.Contains("configure-token", run.Calls);
Assert.Contains("initialize", run.Calls);
// Again: nothing changes.
run = await Run("1.5.0");
Assert.Equal(0, run.Code);
Assert.StartsWith("Already Installed: ExecuteR Agent 1.5.0 is running", run.Last);
Assert.All(run.Calls, call => Assert.Contains(call, new[] { "version", "status" }));
// Interrupted earlier runs leave a staging folder and a temp folder: both go, nothing else changes.
Directory.CreateDirectory(dest + ".staging");
Directory.CreateDirectory(Path.Combine(folder.Path, "tmp", "executer-install.stale"));
run = await Run("1.5.0");
Assert.StartsWith("Already Installed:", run.Last);
Assert.False(Directory.Exists(dest + ".staging"));
Assert.False(Directory.Exists(Path.Combine(folder.Path, "tmp", "executer-install.stale")));
// The service stopped: started again, the enrollment kept (no token).
File.Delete(Path.Combine(state, "running.executer-agent"));
run = await Run("1.5.0");
Assert.StartsWith("Repaired: ExecuteR Agent 1.5.0 is running", run.Last);
Assert.Contains("initialize", run.Calls);
Assert.DoesNotContain("configure-token", run.Calls);
// A newer package: upgraded in place, the enrollment kept.
File.WriteAllText(Path.Combine(package, "AGENT_VERSION"), "1.6.0\n");
run = await Run("1.6.0");
Assert.StartsWith("Upgraded: ExecuteR Agent 1.6.0 is running", run.Last);
Assert.Equal("1.6.0", File.ReadAllText(Path.Combine(dest, "AGENT_VERSION")).Trim());
Assert.DoesNotContain("configure-token", run.Calls);
// Enrolled with another server: pointed here and enrolled with the token.
File.WriteAllText(Path.Combine(state, "server"), "https://old.example.com");
run = await Run("1.6.0");
Assert.StartsWith("Repaired:", run.Last);
Assert.Contains("configure-token", run.Calls);
Assert.Equal(Server, File.ReadAllText(Path.Combine(state, "server")));
// A binary that no longer runs: the files laid down again.
File.WriteAllText(Path.Combine(dest, "executer-agent"), "\u007fELF garbage");
run = await Run("1.6.0");
Assert.StartsWith("Repaired: ExecuteR Agent 1.6.0 is running", run.Last);
Assert.Equal(FakeUnixAgent.ReplaceLineEndings("\n"), File.ReadAllText(Path.Combine(dest, "executer-agent")).ReplaceLineEndings("\n"));
// A device where the service cannot be registered: one Failed line and a non-zero exit.
foreach (var file in Directory.GetFiles(state))
{
File.Delete(file);
}
Directory.Delete(dest, recursive: true);
File.WriteAllText(Path.Combine(state, "fail-initialize"), "");
run = await Run("1.6.0");
Assert.Equal(1, run.Code);
Assert.StartsWith("Failed: ", run.Last);
}
/// <summary>
/// Everything of the Windows script that touches the machine (services, registry, Windows
/// Installer, files) replaced by a device kept in $F; the agent binary is Invoke-FakeAgent.
/// </summary>
private const string WindowsFakes = """
$global:Clock = 0
function Start-Sleep([int]$Seconds) { $global:Clock += $Seconds }
function Get-Date { [datetime]::Now.AddSeconds($global:Clock) }
function Test-ExecuteRElevated { $true }
function Clear-ExecuteRLeftovers { }
function Invoke-FakeAgent {
$F.Calls.Add('initialize')
if (-not $F.FailInitialize) { $F.Running = -not $F.FailStart }
if ($F.Running -and $F.Token) { $F.Credential = 'valid'; $F.Token = $null }
$global:LASTEXITCODE = 0
}
function Get-ExecuteRService([string]$Name) {
if (-not $F.Present) { return @{ Exists = $false; Status = 'Missing'; StartType = 'Missing' } }
return @{ Exists = $true; Status = $(if ($F.Running) { 'Running' } else { 'Stopped' }); StartType = 'Automatic' }
}
function Get-ExecuteRState([bool]$Portable) {
return @{
Present = $F.Present; Dir = 'C:\Fake'; Exe = 'Invoke-FakeAgent'; ExeExists = $F.Present; ExeWorks = ($F.Present -and $F.Works)
Version = $(if ($F.Present -and $F.Works) { $F.Version } else { $null }); ServerUrl = $F.Server; PolicyServerUrl = $null
Credential = $F.Credential; TokenPending = [bool]$F.Token; TokenIsOurs = [bool]($F.Token -and $F.Token -ceq $token); MsiMarker = $F.Present
Msi = $(if ($F.Present) { @{ ProductCode = '{A}'; Version = $F.Version; CacheOk = $true } } else { $null })
Agent = (Get-ExecuteRService $agentServiceName); Watchdog = (Get-ExecuteRService $watchdogServiceName); WatchdogExpected = $F.Present
}
}
function Get-ExecuteRStatus([string]$Exe) { [pscustomobject]@{ credential = $F.Credential; bootstrapTokenPending = [bool]$F.Token } }
function Install-ExecuteRPackage([bool]$Portable, [bool]$Enroll, [bool]$Downgrade) {
$F.Calls.Add('package:' + $Enroll)
$F.Present = $true; $F.Works = $true; $F.Version = $F.Package; $F.Server = $server
if ($Enroll) { $F.Token = $token }
$F.Running = -not $F.FailStart
if ($F.Running -and $F.Token) { $F.Credential = 'valid'; $F.Token = $null }
}
function Set-ExecuteREnrollment { $F.Calls.Add('enroll'); $F.Server = $server; $F.Token = $token }
function Stop-ExecuteRService([string]$Name) { $F.Calls.Add('stop:' + $Name); if ($Name -eq $agentServiceName) { $F.Running = $false } }
function Restart-ExecuteRAgent {
$F.Calls.Add('restart')
$F.Running = -not $F.FailStart
if ($F.Running -and $F.Token) { $F.Credential = 'valid'; $F.Token = $null }
}
""";
public static TheoryData<string, string, int, string, string, string> WindowsRuns => new()
{
// name, device ($F changes), exit code, outcome line start, calls (in order), calls that must not happen
{ "nothing installed", "$F.Present = $false", 0, "Installed: ExecuteR Agent 1.5.0 is running for https://control.example.com, enrolled", "package:True", "initialize" },
{ "healthy and current", "", 0, "Already Installed: ExecuteR Agent 1.5.0 is running for https://control.example.com", "", "package:True,package:False,initialize,enroll,restart" },
{ "older", "$F.Version = '1.4.0'", 0, "Upgraded: ExecuteR Agent 1.5.0 is running", "package:False", "enroll,initialize" },
{ "stopped", "$F.Running = $false", 0, "Repaired: ExecuteR Agent 1.5.0 is running", "initialize", "package:False,enroll" },
{ "restart does not help", "$F.Running = $false; $F.FailInitialize = $true", 0, "Repaired: ExecuteR Agent 1.5.0 is running", "initialize,package:False", "enroll" },
{ "binary broken", "$F.Works = $false", 0, "Repaired: ExecuteR Agent 1.5.0 is running", "package:False", "initialize,enroll" },
{ "enrolled elsewhere", "$F.Server = 'https://old.example.com'", 0, "Repaired: ExecuteR Agent 1.5.0 is running for https://control.example.com, enrolled", "enroll,restart", "package:False,initialize" },
{ "credential missing", "$F.Credential = 'missing'", 0, "Repaired: ExecuteR Agent 1.5.0 is running", "enroll,restart", "package:False" },
{ "keeps stopping", "$F.Running = $false; $F.FailStart = $true", 1, "Failed: the agent is not healthy: the agent service is stopped", "initialize,package:False", "" },
};
[Theory]
[MemberData(nameof(WindowsRuns))]
public async Task TheWindowsScriptDoesOnlyWhatTheDeviceNeeds(string name, string device, int exitCode, string outcome, string calls, string never)
{
var shell = WindowsPowerShell() ?? Pwsh();
Assert.SkipWhen(shell is null, "Needs Windows PowerShell or pwsh.");
var script = new StringBuilder("""
$ErrorActionPreference = 'Stop'
$server = 'https://control.example.com'
$token = 's3cret-token'
$msiUrl = 'x'; $zipUrl = 'x'; $msiVersion = '1.5.0'; $zipVersion = '1.5.0'; $portableOnly = $false
""")
.AppendLine(InstallScripts.WindowsFunctions)
.AppendLine(WindowsFakes)
.AppendLine("""
$F = @{ Present = $true; Works = $true; Version = '1.5.0'; Package = '1.5.0'; Running = $true; Server = 'https://control.example.com'
Credential = 'valid'; Token = $null; FailStart = $false; FailInitialize = $false; Calls = New-Object System.Collections.Generic.List[string] }
""")
.AppendLine(device)
.AppendLine("try {")
.AppendLine(InstallScripts.WindowsMain)
.AppendLine("} finally { Write-Host ('calls=' + ($F.Calls -join ',')) }");
using var folder = new ScratchFolder();
var (code, output, stdout) = await RunAsync(shell!, $"-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{folder.Write("run.ps1", script.ToString())}\"");
Assert.DoesNotContain("s3cret-token", output);
var lines = Lines(stdout).ToList();
var made = lines.Single(l => l.StartsWith("calls=", StringComparison.Ordinal))["calls=".Length..].Split(',', StringSplitOptions.RemoveEmptyEntries);
Assert.True(code == exitCode, $"{name}: exit {code}\n{output}");
Assert.True(lines.Any(l => l.StartsWith(outcome, StringComparison.Ordinal)), $"{name}: no '{outcome}'\n{output}");
Assert.True(lines.IndexOf(lines.First(l => l.StartsWith(outcome, StringComparison.Ordinal))) == lines.Count - 2, $"{name}: the outcome is not the last line\n{output}");
var expected = calls.Split(',', StringSplitOptions.RemoveEmptyEntries);
Assert.True(expected.SequenceEqual(made.Where(expected.Contains).Distinct()), $"{name}: calls {string.Join(',', made)}\n{output}");
foreach (var call in never.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
Assert.DoesNotContain(call, made);
}
}
[Fact]
public async Task AFailureMasksTheTokenInItsOutcomeLine()
{
var shell = WindowsPowerShell() ?? Pwsh();
Assert.SkipWhen(shell is null, "Needs Windows PowerShell or pwsh.");
var body = "$server = 'x'; $token = 'abc123'\n" + InstallScripts.WindowsFunctions + "\nWrite-Output (Hide-ExecuteRToken 'GET https://x/?token=abc123 failed')\n";
using var folder = new ScratchFolder();
var (code, output, _) = await RunAsync(shell!, $"-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{folder.Write("mask.ps1", body)}\"");
Assert.True(code == 0, output);
Assert.Contains("token=<token> failed", output);
Assert.DoesNotContain("abc123", output);
}
private static void AssertVersionResults(Dictionary<string, string> results, string output)
{
for (var i = 0; i < VersionPairs.Length; i++)
{
var expected = Math.Sign(AgentVersions.Compare(VersionPairs[i].Left, VersionPairs[i].Right)).ToString();
Assert.True(results.TryGetValue(i.ToString(), out var actual) && actual == expected,
$"{VersionPairs[i].Left} vs {VersionPairs[i].Right}: expected {expected}, got {actual}\n{output}");
}
}
private static Dictionary<string, string> Results(string output)
=> Lines(output)
.Select(line => ResultLine().Match(line))
.Where(match => match.Success)
.ToDictionary(match => match.Groups[1].Value, match => match.Groups[2].Value);
[GeneratedRegex(@"^(\d+)=(.*)$")]
private static partial Regex ResultLine();
/// <summary>The token variable itself ($token, ${token}), not $token_pending.</summary>
[GeneratedRegex(@"\$\{?token\b")]
private static partial Regex TokenVariable();
private static IEnumerable<string> Lines(string text)
=> text.Split('\n').Select(line => line.TrimEnd('\r').Trim()).Where(line => line.Length > 0);
private static string? WindowsPowerShell()
{
if (!OperatingSystem.IsWindows())
{
return null;
}
var path = Path.Combine(Environment.SystemDirectory, @"WindowsPowerShell\v1.0\powershell.exe");
return File.Exists(path) ? path : null;
}
private static string? Pwsh() => FindOnPath(OperatingSystem.IsWindows() ? "pwsh.exe" : "pwsh");
/// <summary>Git Bash first on Windows: System32's bash.exe is WSL's, which cannot take a Windows path.</summary>
private static string? Bash()
{
if (OperatingSystem.IsWindows())
{
var git = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Git\bin\bash.exe");
return File.Exists(git) ? git : null;
}
return FindOnPath("bash");
}
private static string? FindOnPath(string name)
=> (Environment.GetEnvironmentVariable("PATH") ?? "")
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)
.Select(directory => Path.Combine(directory, name))
.FirstOrDefault(File.Exists);
private static string ForBash(string path) => path.Replace('\\', '/');
private static async Task<(int Code, string Output, string Stdout)> RunAsync(string fileName, string arguments, Dictionary<string, string>? environment = null)
{
var info = new ProcessStartInfo(fileName, arguments)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
foreach (var (name, value) in environment ?? [])
{
info.Environment[name] = value;
}
using var process = Process.Start(info)!;
var output = process.StandardOutput.ReadToEndAsync();
var errors = process.StandardError.ReadToEndAsync();
using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(2));
await process.WaitForExitAsync(timeout.Token);
return (process.ExitCode, await output + await errors, await output);
}
private sealed class ScratchFolder : IDisposable
{
public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "executer-install-" + Guid.NewGuid().ToString("N"));
public ScratchFolder() => Directory.CreateDirectory(Path);
public string Write(string name, string content)
{
var file = System.IO.Path.Combine(Path, name);
File.WriteAllText(file, content);
return file;
}
public void Dispose() => Directory.Delete(Path, recursive: true);
}
}
+6 -7
View File
@@ -91,16 +91,15 @@ public class InstallScriptTests(BackendTestFixture fixture) : IClassFixture<Back
var url = "/api/enrollment/install?token=test-token" + (type is null ? "" : $"&type={type}");
var script = await (await client.GetAsync(url)).Content.ReadAsStringAsync();
var winPeCheck = script.IndexOf(@"Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Control\MiniNT'", StringComparison.Ordinal);
var portable = script.IndexOf("/api/enrollment/agent-package?type=zip", StringComparison.Ordinal);
var msiexec = script.IndexOf("msiexec", StringComparison.Ordinal);
Assert.True(winPeCheck >= 0, "WinPE detection missing");
Assert.True(portable > winPeCheck && portable < msiexec, "WinPE branch must use the zip before the MSI branch");
Assert.Matches(@"\$zipUrl = '[^']*/api/enrollment/agent-package\?type=zip&token=test-token'", script);
Assert.Contains(@"$portable = [bool]($portableOnly -or -not $msiUrl -or (Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Control\MiniNT'))", script);
Assert.Contains("if ($Portable) { Install-ExecuteRPortable $Enroll } else { Install-ExecuteRMsi $Enroll $Downgrade }", script);
Assert.Contains("& $exe initialize", script);
// No Being Viewed banner in Windows PE: the portable install drops it there.
// No Being Viewed banner in Windows PE: the portable install drops it there, before starting the agent.
var portable = script.IndexOf("function Install-ExecuteRPortable", StringComparison.Ordinal);
var dropBanner = script.IndexOf("Remove-Item (Join-Path $dest 'ExecuteR-Banner.exe')", StringComparison.Ordinal);
Assert.True(dropBanner > portable && dropBanner < script.IndexOf("& $exe initialize", StringComparison.Ordinal), "WinPE must drop the banner before starting the agent");
Assert.True(dropBanner > portable && dropBanner < script.IndexOf("& $exe initialize", portable, StringComparison.Ordinal), "WinPE must drop the banner before starting the agent");
Assert.True(script.LastIndexOf(@"Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Control\MiniNT'", dropBanner, StringComparison.Ordinal) > portable,
"Only Windows PE drops the banner");
}
+165
View File
@@ -0,0 +1,165 @@
using System.Net;
using System.Net.Http.Json;
using Backend.Jobs;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Api;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
/// <summary>
/// Run As Signed-In User: stored on the script, sealed into snapshots, carried to the agent, and
/// never sent to an agent too old to honor it (it would run the script as its own account).
/// </summary>
public class RunAsUserTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private const string Current = RunAsUser.MinimumAgentVersion;
private const string Old = "1.12.0";
private static async Task<ScriptDto> SaveAsync(HttpClient client, SaveScriptRequest request, Guid? id = null)
{
var response = id is null
? await client.PostAsJsonAsync(ApiRoutes.Scripts, request, JsonDefaults.Options)
: await client.PutAsJsonAsync(ApiRoutes.For.Script(id.Value), request, JsonDefaults.Options);
response.EnsureSuccessStatusCode();
return (await response.Content.ReadFromJsonAsync<ScriptDto>(JsonDefaults.Options))!;
}
private static SaveScriptRequest Request(string name, bool? asUser = null, ScriptEngine engine = ScriptEngine.PowerShell, bool? workingDirectory = null)
=> new(name, null, "'hello'", Engine: engine, RunAsUser: asUser, SetWorkingDirectory: workingDirectory);
[Fact]
public async Task TheOptionIsSavedAndLeftOutKeepsIt()
{
using var client = await fixture.SignedInAsync("runas-admin");
Assert.False((await SaveAsync(client, Request("runas-default"))).RunAsUser);
var created = await SaveAsync(client, Request("runas-saved", asUser: true));
Assert.True(created.RunAsUser);
Assert.True((await SaveAsync(client, Request("runas-saved"), created.Id)).RunAsUser);
Assert.False((await SaveAsync(client, Request("runas-saved", asUser: false), created.Id)).RunAsUser);
}
[Fact]
public async Task PowerShell7AsTheUserStagesAFileSoItKeepsTheWorkingDirectory()
{
using var client = await fixture.SignedInAsync("runas-admin");
Assert.True((await SaveAsync(client, Request("runas-wd", asUser: true, workingDirectory: true))).SetWorkingDirectory);
Assert.False((await SaveAsync(client, Request("runas-wd-off", asUser: false, workingDirectory: true))).SetWorkingDirectory);
}
[Fact]
public async Task ACurrentAgentGetsTheOptionAndAnOlderOneGetsAFailedJob()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("runas-admin");
var script = await SaveAsync(client, Request("runas-dispatch", asUser: true));
var current = await fixture.SeedDeviceAsync("RUNAS-NEW", agentVersion: Current);
var old = await fixture.SeedDeviceAsync("RUNAS-OLD", agentVersion: Old);
(await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, script.Id, ClientIds: [current, old]), JsonDefaults.Options))
.EnsureSuccessStatusCode();
Assert.True(Sent(current).Single().RunAsUser);
Assert.Empty(Sent(old));
var refused = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().SingleAsync(j => j.ClientId == old && j.ScriptId == script.Id));
Assert.Equal(JobState.Failed, refused.State);
Assert.Contains(RunAsUser.MinimumAgentVersion, refused.OutputSummary);
Assert.NotNull(refused.CompletedUtc);
}
[Fact]
public async Task TheDispatcherRefusesAnOlderAgentToo()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("runas-admin");
var script = await SaveAsync(client, Request("runas-stagger", asUser: true));
var current = await fixture.SeedDeviceAsync("RUNAS-STAG-NEW", agentVersion: Current);
var old = await fixture.SeedDeviceAsync("RUNAS-STAG-OLD", agentVersion: Old);
var response = await client.PostAsJsonAsync(
ApiRoutes.Jobs, new CreateJobRequest(null, script.Id, ClientIds: [current, old], StaggerSeconds: 600), JsonDefaults.Options);
response.EnsureSuccessStatusCode();
var run = (await response.Content.ReadFromJsonAsync<GroupRunDto>(JsonDefaults.Options))!;
var latest = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().Where(j => j.RunId == run.RunId).MaxAsync(j => j.NotBeforeUtc));
await new JobDispatcher(fixture.Services.GetRequiredService<IServiceScopeFactory>(), NullLogger<JobDispatcher>.Instance)
.RunPassAsync(latest!.Value.AddSeconds(1), CancellationToken.None);
Assert.True(Sent(current).Single().RunAsUser);
Assert.Empty(Sent(old));
var refused = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().SingleAsync(j => j.RunId == run.RunId && j.ClientId == old));
Assert.Equal(JobState.Failed, refused.State);
}
[Fact]
public async Task ScriptsThatRunAsTheAgentStillGoToOlderAgents()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("runas-admin");
var script = await SaveAsync(client, Request("runas-not-asked"));
var old = await fixture.SeedDeviceAsync("RUNAS-OLD-PLAIN", agentVersion: Old);
(await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(old, script.Id), JsonDefaults.Options)).EnsureSuccessStatusCode();
Assert.False(Sent(old).Single().RunAsUser);
}
[Theory]
[InlineData("1.13.0", true)]
[InlineData("1.14.2", true)]
[InlineData("1.12.9", false)]
[InlineData(null, false)]
[InlineData("2026.10.23.1400", false)]
public void OnlyNewEnoughAgentsHonorIt(string? version, bool supported)
{
Assert.Equal(supported, RunAsUser.Supported(version));
Assert.Equal(supported, JobRunner.RunAsUserRefusal(true, version) is null);
Assert.Null(JobRunner.RunAsUserRefusal(false, version));
}
[Fact]
public void OlderSnapshotsAndCommandsDoNotRunAsTheUser()
{
var snapshot = JsonDefaults.Deserialize<RunSnapshot>(
$$"""{"scriptId":"{{Guid.NewGuid()}}","name":"n","language":"PowerShell","content":"c"}""")!;
Assert.False(snapshot.ToScript().RunAsUser);
var command = JsonDefaults.Deserialize<ShellOpenCommandPayload>($$"""{"sessionId":"{{Guid.NewGuid()}}","cols":80,"rows":24}""")!;
Assert.False(command.AsUser);
}
private List<ScriptCommandPayload> Sent(string clientId)
{
lock (fixture.Scripts.Sent)
{
return fixture.Scripts.Sent.Where(s => s.ClientId == clientId).Select(s => s.Command).ToList();
}
}
[Fact]
public async Task AShellCanNameWhichSignedInUserButOnlyAsAPlainName()
{
using var client = await fixture.SignedInAsync("runas-shell-user");
using var nkey = NATS.NKeys.KeyPair.CreatePair(NATS.NKeys.PrefixByte.User);
var credential = await (await client.PostAsJsonAsync(ApiRoutes.BrowserNatsCredential,
new BrowserCredentialRequest(nkey.GetPublicKey(), null), JsonDefaults.Options))
.Content.ReadFromJsonAsync<BrowserCredentialResponse>(JsonDefaults.Options);
var device = await fixture.SeedDeviceAsync("RUNAS-SHELL", agentVersion: Current);
Task<HttpResponseMessage> OpenAsync(bool asUser, string user)
=> client.PostAsJsonAsync(ApiRoutes.For.DeviceShell(device),
new CreateShellRequest(credential!.BrowserSessionId, 80, 24, null, asUser, user), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, (await OpenAsync(false, "ann")).StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, (await OpenAsync(true, "ann,bob")).StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, (await OpenAsync(true, "../etc")).StatusCode);
// A domain account passes the check (the test server has no agent to send the open to).
Assert.NotEqual(HttpStatusCode.BadRequest, (await OpenAsync(true, @"CONTOSO\ann")).StatusCode);
}
}
+137
View File
@@ -0,0 +1,137 @@
using System.Net;
using System.Net.Http.Json;
using Backend.Data;
using Backend.Messaging;
using Microsoft.Extensions.Hosting;
using Shared.Contracts.Messages;
using Shared.Infrastructure.Nats;
using Backend.Groups;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shared.Contracts.Api;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
/// <summary>Script groups: a device's job reports which of them it belongs in.</summary>
public class ScriptGroupTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private static GroupMembershipReport R(string group, bool member) => new(group, member);
private async Task<ScriptGroupMembership.Outcome> ReportAsync(string clientId, params GroupMembershipReport[] reports)
{
using var scope = fixture.Services.CreateScope();
return await scope.ServiceProvider.GetRequiredService<ScriptGroupMembership>()
.ApplyAsync(clientId, "Inventory Check", reports, CancellationToken.None);
}
private async Task<IReadOnlyList<string>> MembersAsync(string groupName)
{
using var scope = fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var group = await db.DeviceGroups.AsNoTracking().SingleAsync(g => g.Name == groupName);
return await scope.ServiceProvider.GetRequiredService<DeviceGroupService>().GetMembersAsync(group, CancellationToken.None);
}
[Fact]
public async Task TheFirstMemberCreatesTheGroupAndLaterRunsFollowTheDevice()
{
var a = await fixture.SeedDeviceAsync("SG-A");
var b = await fixture.SeedDeviceAsync("SG-B");
var first = await ReportAsync(a, R("Has Java", true));
Assert.Equal(["Has Java"], first.Created);
await ReportAsync(b, R("has java", true));
Assert.Equal(new[] { a, b }.Order(), (await MembersAsync("Has Java")).Order());
var group = await fixture.WithDbAsync(db => db.DeviceGroups.AsNoTracking().SingleAsync(g => g.Name == "Has Java"));
Assert.Equal(GroupKind.Script, group.Kind);
// The next run says otherwise: the device leaves; the group stays.
var left = await ReportAsync(a, R("Has Java", false));
Assert.Equal(["Has Java"], left.Left);
Assert.Equal([b], await MembersAsync("Has Java"));
// Saying it again changes nothing.
Assert.False((await ReportAsync(b, R("Has Java", true))).Changed);
}
[Fact]
public async Task NotBeingAMemberOfAGroupThatDoesNotExistCreatesNothing()
{
var a = await fixture.SeedDeviceAsync("SG-NONE");
var outcome = await ReportAsync(a, R("Never Joined", false));
Assert.Empty(outcome.Created);
Assert.False(await fixture.WithDbAsync(db => db.DeviceGroups.AnyAsync(g => g.Name == "Never Joined")));
}
[Fact]
public async Task ADeviceCannotPutItselfInACuratedGroup()
{
var a = await fixture.SeedDeviceAsync("SG-CURATED");
await fixture.WithDbAsync(async db =>
{
db.DeviceGroups.Add(new DeviceGroupEntity { Id = Guid.NewGuid(), Name = "Admins Only", Kind = GroupKind.Static, CreatedUtc = DateTimeOffset.UtcNow });
await db.SaveChangesAsync();
return 0;
});
var outcome = await ReportAsync(a, R("Admins Only", true));
Assert.Equal(["Admins Only"], outcome.Ignored);
Assert.Empty(await MembersAsync("Admins Only"));
}
[Fact]
public async Task TheLastWordPerGroupWinsAndBadNamesAreDropped()
{
var a = await fixture.SeedDeviceAsync("SG-LAST");
var outcome = await ReportAsync(a, R("Flip", true), R("flip", false), R("Flip", true), R("a/b", true), R(" ", true));
Assert.Equal(["Flip"], outcome.Joined);
Assert.Equal([a], await MembersAsync("Flip"));
Assert.False(await fixture.WithDbAsync(db => db.DeviceGroups.AnyAsync(g => g.Name == "a/b")));
}
[Fact]
public async Task OperatorsCannotListDevicesInAScriptGroup()
{
var a = await fixture.SeedDeviceAsync("SG-MANUAL");
await ReportAsync(a, R("Reported Only", true));
var id = await fixture.WithDbAsync(db => db.DeviceGroups.Where(g => g.Name == "Reported Only").Select(g => g.Id).SingleAsync());
using var client = await fixture.SignedInAsync("script-group-admin");
var response = await client.PostAsJsonAsync(
ApiRoutes.For.GroupMembers(id), new UpdateGroupMembersRequest([a], []), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Contains("set by the scripts", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task AJobsFinalStateCarriesItsReportsToTheGroups()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("script-group-run");
var scriptId = await fixture.SeedScriptAsync("script-group-reporter");
var device = await fixture.SeedDeviceAsync("SG-RUN");
(await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(device, scriptId), JsonDefaults.Options)).EnsureSuccessStatusCode();
var job = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().SingleAsync(j => j.ClientId == device));
var state = new JobStatePayload(job.JobId, device, JobState.Succeeded, 0, DateTimeOffset.UtcNow, null,
GroupMemberships: [R("From The Agent", true)]);
var workers = fixture.Services.GetServices<IHostedService>().OfType<MessagingWorkers>().Single();
await workers.StoreJobStatesAsync(
[new MessagingWorkers.JobStateMessage(
NatsSubjects.JobState(job.JobId),
MessageEnvelope.Create(MessageTypes.JobState, new EndpointRef(EndpointKinds.Agent, device), state).ToUtf8Bytes(),
DateTimeOffset.UtcNow, _ => ValueTask.CompletedTask, _ => ValueTask.CompletedTask, (_, _) => ValueTask.CompletedTask)],
CancellationToken.None);
Assert.Equal([device], await MembersAsync("From The Agent"));
}
}
+2 -1
View File
@@ -141,7 +141,7 @@ internal static class TestClients
public static Task<string> SeedDeviceAsync(
this BackendTestFixture fixture, string hostname, bool online = false, bool orphaned = false,
IReadOnlyList<string>? tags = null)
IReadOnlyList<string>? tags = null, string? agentVersion = null)
=> fixture.WithDbAsync(async db =>
{
var clientId = $"client-{Guid.NewGuid():N}"[..20];
@@ -154,6 +154,7 @@ internal static class TestClients
LastSeenUtc = online ? DateTimeOffset.UtcNow : DateTimeOffset.UtcNow.AddDays(-2),
IsOrphaned = orphaned,
TagsJson = tags is { Count: > 0 } ? Shared.Contracts.Serialization.JsonDefaults.Serialize(tags) : null,
AgentVersion = agentVersion,
});
await db.SaveChangesAsync();
return clientId;
+393
View File
@@ -0,0 +1,393 @@
using System.Globalization;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Shared.Contracts.Api;
using Shared.Infrastructure.Logging;
using Xunit;
namespace Shared.Tests;
/// <summary>Captures what a logger writes, for formatting it by hand.</summary>
internal sealed class CollectingSink : ILogEventSink
{
public List<LogEvent> Events { get; } = [];
public void Emit(LogEvent logEvent)
{
lock (Events)
{
Events.Add(logEvent);
}
}
}
/// <summary>A clock that moves only when told.</summary>
internal sealed class ManualClock(DateTimeOffset start) : TimeProvider
{
public DateTimeOffset Now { get; private set; } = start;
public override DateTimeOffset GetUtcNow() => Now;
public void Advance(TimeSpan by) => Now += by;
}
/// <summary>ExecuteR's one text log format.</summary>
public sealed class LogLineFormatterTests
{
private static LogEvent Capture(Action<ILogger> log)
{
var sink = new CollectingSink();
using (var logger = new LoggerConfiguration().MinimumLevel.Verbose().Enrich.WithProperty("Application", "Agent").WriteTo.Sink(sink).CreateLogger())
{
log(logger);
}
return Assert.Single(sink.Events);
}
private static string Format(LogEvent logEvent)
{
using var text = new StringWriter(CultureInfo.InvariantCulture);
new LogLineFormatter("Agent").Format(logEvent, text);
return text.ToString();
}
[Fact]
public void ALineIsTimeCategoryLevelMessage_ThenTheUnusedPropertiesAsKeyValue()
{
var logEvent = Capture(logger => logger
.ForContext("SourceContext", "Agent.Fabric.EventBus")
.ForContext("CorrelationId", "c-1")
.ForContext("MachineName", "PC1")
.ForContext("RequestId", "r-1")
.Warning(
"The site's leaf could not be reached; the bus goes through the server meanwhile {Leaf}",
"wss://172.18.16.104:9001/"));
var withExtras = new LogEvent(
new DateTimeOffset(2026, 11, 16, 18, 53, 40, 687, TimeSpan.FromHours(1)),
logEvent.Level,
null,
logEvent.MessageTemplate,
logEvent.Properties.Select(p => new LogEventProperty(p.Key, p.Value)));
withExtras.AddOrUpdateProperty(new LogEventProperty("reason", new ScalarValue("TLS: The remote certificate is invalid")));
withExtras.AddOrUpdateProperty(new LogEventProperty("signer", new ScalarValue(null)));
withExtras.AddOrUpdateProperty(new LogEventProperty("count", new ScalarValue(1)));
withExtras.AddOrUpdateProperty(new LogEventProperty("ok", new ScalarValue(true)));
Assert.Equal(
"[2026-11-16T17:53:40.687Z] - [EventBus] - [WARN] - The site's leaf could not be reached; the bus goes through the server meanwhile wss://172.18.16.104:9001/"
+ " CorrelationId=c-1 reason=\"TLS: The remote certificate is invalid\" signer=null count=1 ok=true" + Environment.NewLine,
Format(withExtras));
}
[Fact]
public void WithoutASourceTheCategoryIsTheApplication_AndAnExceptionFollows()
{
var logEvent = Capture(logger => logger.Error(new InvalidOperationException("broke"), "It failed for {JobId}", Guid.Empty));
var lines = Format(logEvent).Split(Environment.NewLine);
Assert.Matches(@"^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\] - \[Agent\] - \[ERROR\] - It failed for 00000000-0000-0000-0000-000000000000$", lines[0]);
Assert.StartsWith("System.InvalidOperationException: broke", lines[1]);
}
[Fact]
public void StringsInTheMessageAreUnquoted_AndStructuresAreJson()
{
var logEvent = Capture(logger => logger
.ForContext("Extra", new { A = 1 }, destructureObjects: true)
.Information("Path {Path} took {Ms:0.0} ms for {@Item}", "C:\\x y", 1.234, new { B = "c" }));
Assert.EndsWith("- [INFO] - Path C:\\x y took 1.2 ms for {\"B\":\"c\"} Extra=\"{\\\"A\\\":1}\"" + Environment.NewLine, Format(logEvent));
}
[Theory]
[InlineData("Agent.Screen.ScreenHost", "ScreenHost")]
[InlineData("Agent.Screen.ScreenHost+Session", "ScreenHost.Session")]
[InlineData("Shared.Infrastructure.Cache`1[[System.String, System.Private.CoreLib]]", "Cache")]
[InlineData("Shared.Infrastructure.Cache`1+Entry", "Cache.Entry")]
[InlineData("Backend.Things.Repository<Backend.Device>", "Repository")]
[InlineData("Microsoft.Hosting.Lifetime", "Lifetime")]
[InlineData("ScreenHost", "ScreenHost")]
[InlineData("ironrdp_server", "ironrdp_server")]
[InlineData(null, "Server")]
[InlineData(" ", "Server")]
public void TheCategoryIsTheTypeNameAlone(string? source, string category)
=> Assert.Equal(category, LogLineFormatter.Category(source, "Server"));
[Theory]
[InlineData("plain", "plain")]
[InlineData("C:\\Windows", "C:\\Windows")]
[InlineData("two words", "\"two words\"")]
[InlineData("a=b", "\"a=b\"")]
[InlineData("say \"hi\"", "\"say \\\"hi\\\"\"")]
[InlineData("line\nnext", "\"line\\nnext\"")]
[InlineData("", "\"\"")]
public void AValueIsQuotedOnlyWhenItMustBe(string value, string written)
=> Assert.Equal(written, LogLineFormatter.Quote(value));
[Theory]
[InlineData(LogEventLevel.Verbose, "TRACE")]
[InlineData(LogEventLevel.Debug, "DEBUG")]
[InlineData(LogEventLevel.Information, "INFO")]
[InlineData(LogEventLevel.Warning, "WARN")]
[InlineData(LogEventLevel.Error, "ERROR")]
[InlineData(LogEventLevel.Fatal, "FATAL")]
public void LevelsAreSpelledOut(LogEventLevel level, string name)
=> Assert.Equal(name, LogLineFormatter.LevelName(level));
}
/// <summary>Reading log lines back, in this format and the ones before it.</summary>
public sealed class LogLineParserTests
{
[Fact]
public void ALineInTheFormatReadsBack()
{
var line = LogLineFormatter.Line(
new DateTimeOffset(2026, 11, 16, 17, 53, 40, 653, TimeSpan.Zero), "Fabric.Leaf", "INFO",
"The site's leaf answers again; moving back to it from the hub leaf=wss://172.18.16.104:9001");
Assert.True(LogLineParser.TryParse(line, out var parsed));
Assert.Equal(new DateTimeOffset(2026, 11, 16, 17, 53, 40, 653, TimeSpan.Zero), parsed.TimestampUtc);
Assert.Equal(LogLevels.Information, parsed.Level);
Assert.Equal("Fabric.Leaf", parsed.Category);
Assert.Equal("The site's leaf answers again; moving back to it from the hub leaf=wss://172.18.16.104:9001", parsed.Message);
}
[Fact]
public void AServiceLineFromBeforeReadsBack_InLocalTime()
{
Assert.True(LogLineParser.TryParse("[2026-11-06 12:00:00.250 WRN] Agent.Service.AgentSession: Lost it: twice", out var parsed));
Assert.Equal(new DateTimeOffset(new DateTime(2026, 11, 6, 12, 0, 0, 250, DateTimeKind.Local)), parsed.TimestampUtc);
Assert.Equal(TimeSpan.Zero, parsed.TimestampUtc.Offset);
Assert.Equal(LogLevels.Warning, parsed.Level);
Assert.Equal("Agent.Service.AgentSession", parsed.Category);
Assert.Equal("Lost it: twice", parsed.Message);
Assert.True(LogLineParser.TryParse("[2026-11-06 12:00:00.250 INF] : no source", out var bare));
Assert.Null(bare.Category);
Assert.Equal("no source", bare.Message);
}
[Fact]
public void AWatchdogLineFromBeforeReadsBack_InUtc()
{
Assert.True(LogLineParser.TryParse("2026-11-06 12:00:01.000Z [ERR] Restarted the agent", out var parsed));
Assert.Equal(new DateTimeOffset(2026, 11, 6, 12, 0, 1, TimeSpan.Zero), parsed.TimestampUtc);
Assert.Equal(LogLevels.Error, parsed.Level);
Assert.Null(parsed.Category);
Assert.Equal("Restarted the agent", parsed.Message);
}
[Fact]
public void AnOlderScreenHostLineReadsBack()
{
Assert.True(LogLineParser.TryParse("2026-11-06T12:00:01.123456789Z WARN executer_screen::video: hardware H.264 encoder failed reason=x", out var parsed));
Assert.Equal(new DateTimeOffset(2026, 11, 6, 12, 0, 1, 123, TimeSpan.Zero).AddTicks(4567), parsed.TimestampUtc);
Assert.Equal(LogLevels.Warning, parsed.Level);
Assert.Equal("executer_screen::video", parsed.Category);
Assert.Equal("hardware H.264 encoder failed reason=x", parsed.Message);
}
[Theory]
[InlineData(" at Agent.Thing.Do() in C:\\src\\Thing.cs:line 4")]
[InlineData("just words")]
[InlineData("")]
[InlineData(null)]
public void AnythingElseIsNotALine(string? line)
=> Assert.False(LogLineParser.TryParse(line, out _));
}
/// <summary>Repeated warnings and errors are written once, then counted.</summary>
public sealed class RepeatThrottleSinkTests
{
private readonly ManualClock clock = new(new DateTimeOffset(2026, 11, 16, 12, 0, 0, TimeSpan.Zero));
private readonly CollectingSink written = new();
private RepeatThrottleSink Throttle(int maxKeys = RepeatThrottleSink.DefaultMaxKeys)
=> new(written, clock, maxKeys: maxKeys, sweepEvery: Timeout.InfiniteTimeSpan);
private static LogEvent Event(LogEventLevel level, string template, params object[] values)
{
var sink = new CollectingSink();
using (var logger = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Sink(sink).CreateLogger())
{
logger.ForContext("SourceContext", "Agent.Fabric.EventBus").Write(level, template, values);
}
return sink.Events[0];
}
private static string Text(LogEvent logEvent) => LogLineFormatter.RenderMessage(logEvent);
[Fact]
public void TheFirstIsWritten_RepeatsAreCounted_AndTheWindowEndsWithOneSummary()
{
using var throttle = Throttle();
for (var i = 1; i <= 5; i++)
{
throttle.Emit(Event(LogEventLevel.Warning, "Leaf unreachable {Attempt}", i));
clock.Advance(TimeSpan.FromSeconds(5));
}
Assert.Equal(["Leaf unreachable 1"], written.Events.Select(Text));
throttle.Sweep();
Assert.Single(written.Events);
clock.Advance(TimeSpan.FromSeconds(40));
throttle.Sweep();
Assert.Equal(2, written.Events.Count);
Assert.Equal("Leaf unreachable 5 repeated=4 window=60s", Text(written.Events[1]));
Assert.Equal(LogEventLevel.Warning, written.Events[1].Level);
Assert.Equal(clock.Now, written.Events[1].Timestamp);
}
[Fact]
public void ItKeepsSummarizingOncePerWindow_AndAQuietWindowStartsOver()
{
using var throttle = Throttle();
throttle.Emit(Event(LogEventLevel.Error, "Broke {N}", 1));
throttle.Emit(Event(LogEventLevel.Error, "Broke {N}", 2));
clock.Advance(TimeSpan.FromSeconds(60));
throttle.Sweep();
Assert.Equal(["Broke 1", "Broke 2 repeated=1 window=60s"], written.Events.Select(Text));
// Still repeating: counted in the next window too.
throttle.Emit(Event(LogEventLevel.Error, "Broke {N}", 3));
throttle.Emit(Event(LogEventLevel.Error, "Broke {N}", 4));
throttle.Emit(Event(LogEventLevel.Error, "Broke {N}", 5));
clock.Advance(TimeSpan.FromSeconds(60));
throttle.Sweep();
Assert.Equal("Broke 5 repeated=3 window=60s", Text(written.Events[^1]));
Assert.Equal(1, throttle.Tracked);
// A whole window without it: forgotten, so the next is written at once.
clock.Advance(TimeSpan.FromSeconds(60));
throttle.Sweep();
Assert.Equal(0, throttle.Tracked);
throttle.Emit(Event(LogEventLevel.Error, "Broke {N}", 6));
Assert.Equal("Broke 6", Text(written.Events[^1]));
Assert.Equal(4, written.Events.Count);
}
[Fact]
public void ARepeatAfterTheWindowWithoutASweepStillGetsItsSummaryFirst()
{
using var throttle = Throttle();
throttle.Emit(Event(LogEventLevel.Warning, "Slow {Ms}", 1));
throttle.Emit(Event(LogEventLevel.Warning, "Slow {Ms}", 2));
clock.Advance(TimeSpan.FromSeconds(61));
throttle.Emit(Event(LogEventLevel.Warning, "Slow {Ms}", 3));
Assert.Equal(["Slow 1", "Slow 2 repeated=1 window=60s"], written.Events.Select(Text));
clock.Advance(TimeSpan.FromSeconds(61));
throttle.Emit(Event(LogEventLevel.Warning, "Slow {Ms}", 4));
Assert.Equal("Slow 3 repeated=1 window=60s", Text(written.Events[^1]));
}
[Fact]
public void InformationAndBelowAreNeverHeldBack()
{
using var throttle = Throttle();
for (var i = 0; i < 3; i++)
{
throttle.Emit(Event(LogEventLevel.Information, "Polled {N}", i));
throttle.Emit(Event(LogEventLevel.Debug, "Polled {N}", i));
}
Assert.Equal(6, written.Events.Count);
Assert.Equal(0, throttle.Tracked);
}
[Fact]
public void LevelSourceAndTemplateTellEventsApart_AndABarePlaceholderByItsText()
{
using var throttle = Throttle();
throttle.Emit(Event(LogEventLevel.Warning, "A {N}", 1));
throttle.Emit(Event(LogEventLevel.Error, "A {N}", 1));
throttle.Emit(Event(LogEventLevel.Warning, "B {N}", 1));
var other = Event(LogEventLevel.Warning, "A {N}", 2);
other.AddOrUpdateProperty(new LogEventProperty("SourceContext", new ScalarValue("Agent.Other")));
throttle.Emit(other);
throttle.Emit(Event(LogEventLevel.Warning, "{HostLine}", "one thing"));
throttle.Emit(Event(LogEventLevel.Warning, "{HostLine}", "another thing"));
throttle.Emit(Event(LogEventLevel.Warning, "{HostLine}", "one thing"));
Assert.Equal(6, written.Events.Count);
Assert.Equal(6, throttle.Tracked);
}
[Fact]
public void TheTableIsBounded_AndAnEvictedCountIsWritten()
{
using var throttle = Throttle(maxKeys: 2);
throttle.Emit(Event(LogEventLevel.Warning, "First {N}", 1));
throttle.Emit(Event(LogEventLevel.Warning, "First {N}", 2));
throttle.Emit(Event(LogEventLevel.Warning, "Second {N}", 1));
throttle.Emit(Event(LogEventLevel.Warning, "Third {N}", 1));
Assert.Equal(2, throttle.Tracked);
Assert.Equal(["First 1", "Second 1", "First 2 repeated=1 window=60s", "Third 1"], written.Events.Select(Text));
}
[Fact]
public void DisposingWritesEveryOpenCount()
{
var throttle = Throttle();
throttle.Emit(Event(LogEventLevel.Warning, "A {N}", 1));
throttle.Emit(Event(LogEventLevel.Warning, "A {N}", 2));
throttle.Emit(Event(LogEventLevel.Warning, "A {N}", 3));
throttle.Emit(Event(LogEventLevel.Error, "B {N}", 1));
throttle.Dispose();
Assert.Equal(["A 1", "B 1", "A 3 repeated=2 window=60s"], written.Events.Select(Text));
}
[Fact]
public void TheLoggerThrottles_AndClosingItWritesTheCount_InTheFileToo()
{
var folder = Directory.CreateTempSubdirectory("log-format-").FullName;
try
{
var live = new LiveLog();
using (var logger = LoggingSetup.CreateLogger(new LogSettings { Level = "Debug", Directory = folder }, "Agent", live, clock))
{
var bus = logger.ForContext("SourceContext", "Agent.Fabric.EventBus");
for (var i = 0; i < 3; i++)
{
bus.Warning("A key or trust mismatch was reported {Kind} with {Password}", "server-reply", "hunter2");
}
logger.Information("Started");
}
var lines = live.Read(null, null).Lines;
Assert.Equal(3, lines.Count);
Assert.Equal("A key or trust mismatch was reported server-reply with [redacted]", lines[0].Message);
Assert.Equal("Agent.Fabric.EventBus", lines[0].Source);
Assert.Equal("Agent", lines[1].Source);
Assert.Equal("A key or trust mismatch was reported server-reply with [redacted] repeated=2 window=60s", lines[2].Message);
var file = Assert.Single(Directory.GetFiles(folder, "*.log"));
var text = File.ReadAllLines(file);
Assert.Equal(3, text.Length);
Assert.Equal(
"[2026-11-16T12:00:00.000Z] - [EventBus] - [WARN] - A key or trust mismatch was reported server-reply with [redacted] repeated=2 window=60s",
text[2]);
Assert.Matches(@"^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\] - \[Agent\] - \[INFO\] - Started$", text[1]);
Assert.DoesNotContain(text, l => l.Contains("hunter2", StringComparison.Ordinal));
Assert.All(text, l => Assert.True(LogLineParser.TryParse(l, out _), l));
}
finally
{
Directory.Delete(folder, recursive: true);
}
}
}