Skip to content

Commit d725e0e

Browse files
bkudiessCopilot
andcommitted
fix(exec): restore V2 approval parity
Replace the stale V1-shaped Permissions editor with the file-backed V2 policy model, explicit validation, scoped rules, and CAS-safe persistence. Add upstream-compatible argument-bound generated grants so changed argv no longer reuses Allow Always authority. Co-authored-by: Copilot App <[email protected]>
1 parent aac07ab commit d725e0e

44 files changed

Lines changed: 3351 additions & 704 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/ARCHITECTURE.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
7777
| `src/OpenClaw.Tray.WinUI/Chat/OpenClawChatTimeline.cs` | `ReactorChatTimeline` (production `ItemsView` / `ItemContainer`), `ChatBubbleRenderer`, `ToolCallCardRenderer`, `PermissionRequestCard`, `AttachmentBubbleRenderer` |
7878
| `src/OpenClaw.Tray.WinUI/Chat/OpenClawComposer.cs` | `ComposerViewModel`, `SlashCommandPalette`, `AttachmentPreviewStrip`, `VoiceComposerController` |
7979
| `src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs` | `ConnectionPagePlan` (pure), `ConnectionPageViewModel`, gateway row models |
80+
| `src/OpenClaw.Tray.WinUI/Pages/PermissionsPage.xaml.cs` | `PermissionsPageViewModel`, capability projections, policy-store adapters |
8081
| `src/OpenClaw.Tray.WinUI/Pages/SettingsPage.xaml.cs` | settings read/persist → `SettingsPageViewModel` + `ISettingsStore`; keep gateway-uninstall, uptime timer, saved-indicator, and app-info in the view |
8182
| `src/OpenClaw.Tray.WinUI/Services/NodeService.cs` | `McpServerHost`, `CanvasWindowManager`, `MediaCapabilityHost`, `RecordingConsentService`, `NodeCapabilityRegistry` |
8283
| `src/OpenClaw.Shared/OpenClawGatewayClient.cs` | `PendingRequestRegistry`, `ConnectEnvelopeBuilder`, `GatewayMessageRouter`, per-domain API facades |
@@ -117,6 +118,7 @@ leading and trailing pipe. Columns, in order:
117118
| test-gateway-builder | authoritative | OpenClaw.Connection.Tests | per-file MakeRecord(id,url) helpers | OpenClaw.Connection.Tests.GatewayRecordBuilder | pre-existing MakeRecord until migrated | gateway record test data has one builder | TestSupportFixtureTests.GatewayRecordBuilder_BuildsRecord | behavioral | when MakeRecord helpers are removed |
118119
| test-settings-builder | authoritative | scattered test files | ad hoc SettingsData construction in migrated tests | OpenClaw.TestSupport.SettingsDataBuilder | pre-existing un-migrated tests until adopted | settings test data starts from production defaults | TestSupportFixtureTests.SettingsDataBuilder_StartsFromDefaults | behavioral | when settings tests adopt the builder |
119120
| json-read-helpers | authoritative | OpenClaw.Shared (multiple files) | duplicate non-nullable fallback-returning JsonElement getters | JsonReadHelpers | null-sentinel / non-negative / whitespace-absent / trimming variants stay separate | canonical non-nullable fallback JSON coercion; divergent-contract helpers are not blindly routed here | JsonReadHelpersTests.GetString_ReturnsNull_WhenPropertyMissing | behavioral | when the non-nullable fallback getters are all routed here |
121+
| exec-approval-rule-identity | authoritative | path-only generated exec approval grants | generated durable approval hashing and `(pattern,argPattern,source)` identity | ExecArgPattern + ExecAllowlistRuleIdentity | manual path-only rules remain intentionally broad | generated Allow Always rules use the upstream length-delimited SHA-256 argv-tail contract and policy currency compares full authority tuples | ExecApprovalV2EvaluatorTests.HashedArgPattern_MatchesUpstreamLengthDelimitedVectors | behavioral | - |
120122
| wsl-posix-quoting | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | ad hoc ShellEscape with divergent wrap semantics | WslShellQuoting | - | WSL command lines use POSIX single-quote quoting via WslShellQuoting not cmd/PowerShell quoting | WslShellQuotingTests.QuotePosixSingleQuote_WrapsAndEscapesEmbeddedQuote | behavioral | when no code builds WSL command lines outside WslShellQuoting |
121123
| setup-shellescape-closed | closed | src/OpenClaw.SetupEngine/SetupSteps.cs | private ShellEscape helpers with divergent wrap semantics | WslShellQuoting | - | SetupSteps builds WSL command lines only via WslShellQuoting; no local ShellEscape helper | SetupStepsShellEscapeClosureTests.SetupSteps_DoesNotReintroduce_PrivateShellEscape | source-shape | when SetupSteps.cs no longer builds any WSL command strings |
122124
| wsl-distro-install-path | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | inline Path.Combine wsl distro install-path derivation | DistroInstallPathPolicy | - | new installs use the strict supported name grammar; teardown accepts only unambiguous single-segment names whose canonical path is an immediate child of LocalDataDir\wsl with no aliases, case or Unicode collisions, or reparse points at the root or child | SetupStepsTests.DistroInstallPathPolicy_ResolvesImmediateChild | behavioral | - |
@@ -142,6 +144,8 @@ leading and trailing pipe. Columns, in order:
142144
| functional-chat-default-mount | closed | src/OpenClaw.Tray.WinUI/Chat/FunctionalChatHostExtensions.cs | mounting the FunctionalUI chat tree as the default ChatPage or ChatWindow surface | ReactorChatHostExtensions and OpenClawReactorChatRoot | legacy FunctionalUI chat files may remain for focused compatibility coverage only | ChatPage and ChatWindow mount the Reactor root directly into their existing ChatHost Borders; no FunctionalUI component mounts or nests Reactor on the default path | review-only: user explicitly deferred new tests for this migration; required build and existing shared/tray suites still run | review-only | when legacy FunctionalUI chat surfaces are removed |
143145
| settings-store | authoritative | src/OpenClaw.Tray.WinUI/Pages/SettingsPage.xaml.cs | hand-rolled save/echo suppression flags for two-way settings binding | ISettingsStore | PermissionsPage and other surfaces may read SettingsManager directly until migrated | a save originating from Update does not echo Changed to the caller and external saves are republished on the UI thread | SettingsStoreTests.Update_DoesNotEchoChangedToSelf | behavioral | when all settings surfaces read and write through ISettingsStore |
144146
| settings-page-vm | authoritative | src/OpenClaw.Tray.WinUI/Pages/SettingsPage.xaml.cs | settings load, persist, echo-guard, and auto-save wiring | SettingsPageViewModel | code-behind keeps gateway-uninstall, gateway-info and uptime timer, saved-indicator visual, and app-info population | each settings control persists its field through the store preserving mutate-save-notify order and does not re-persist on external change | SettingsPageViewModelTests.ExternalChange_ReloadsWithoutRePersisting | behavioral | when the Settings page holds no settings persistence logic in code-behind |
147+
| permissions-exec-policy-vm | authoritative | src/OpenClaw.Tray.WinUI/Pages/PermissionsPage.xaml.cs | exec approvals snapshot projection, scope selection, CAS mutation, conflict retry, and save rollback | PermissionsPageViewModel + IExecApprovalsPolicyStore | code-behind maps WinUI controls, localized copy, validation presentation, and saved/error status | valid V2 executable patterns persist to the selected scope and survive reload through the same authoritative ExecApprovalsStore | PermissionsPageViewModelTests.AddAllowlistEntry_ValidPatternPersistsToSelectedScopeAndSurvivesReload | behavioral | - |
148+
| permissions-page-exec-policy-closed | closed | src/OpenClaw.Tray.WinUI/Pages/PermissionsPage.xaml.cs | direct ExecApprovalsStore reads, writes, policy mutation, and main-only allowlist ownership | PermissionsPageViewModel + IExecApprovalsPolicyStore | view event forwarding and control projection only | PermissionsPage never regains direct store or file mutation and supports defaults, wildcard, main, and existing agent scopes | AppRefactorContractTests.PermissionsPage_ExecApprovals_StaysDelegatedToViewModel | source-shape | when PermissionsPage is replaced by a declarative binding-only view |
145149
<!-- LEDGER:END -->
146150

147151
## Deferred test builders

‎docs/WINDOWS_NODE_ARCHITECTURE.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,39 @@ would preserve parallel authorization paths and bypass drift.
477477
migration UI. Revisit this decision only if measured support impact justifies a separate
478478
compatibility feature.
479479

480+
#### Companion UI contract for V2
481+
482+
The Permissions page edits the same file-backed V2 snapshot used by the evaluator,
483+
`system.execApprovals.get/set`, local MCP, and the Gateway relay. It exposes:
484+
485+
- defaults, wildcard (`*`), `main`, and existing agent scopes;
486+
- `security`, `ask`, `askFallback`, and `autoAllowSkills`;
487+
- executable-path allowlist entries for wildcard and agent scopes;
488+
- compare-and-swap persistence with conflict reload and retry.
489+
490+
V2 allowlist entries match resolved executable paths. The UI rejects legacy command-text
491+
patterns such as `hostname` or `Get-*` and explains that a path pattern such as
492+
`**/hostname.exe` is required. Invalid input and persistence failures must remain visible;
493+
the page must not optimistically report a rule as saved.
494+
495+
Generated **Always Allow** entries also bind the exact approved argv tail. They persist
496+
`source: "allow-always"` and an upstream-compatible
497+
`argPattern: "sha256:argv:<digest>"`; matching requires both the executable path and
498+
the length-delimited UTF-8 argument hash. A changed argument list misses and follows
499+
the configured prompt/fallback behavior. Legacy generated path-only entries are ignored
500+
because they could authorize changed arguments after upgrade. Hand-authored path-only
501+
entries have no `source` or `argPattern` and intentionally remain broad.
502+
503+
The durable tuple does not bind cwd or file contents across later runs. The approved
504+
execution still pins the resolved executable and preserves the exact argv for the current
505+
launch. Canonical cwd filesystem identity and mutable script content revalidation remain
506+
separate launch-boundary hardening.
507+
508+
V2 does not currently define explicit denylist entries. Restoring deny semantics is a
509+
separate security design: durable denies must bind resolved executable identity and
510+
canonical argv, and destructive-operation guarantees require OS-enforced sandbox policy
511+
rather than command-name matching.
512+
480513
#### Decision: version the low-level `system.run` boundary as canonical argv
481514

482515
The V2 low-level node contract accepts `command` only as `string[]` canonical argv.

‎src/OpenClaw.Shared/Capabilities/SystemCapability.cs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -552,21 +552,21 @@ private static object ToExecApprovalsPayload(ExecApprovalsSnapshot snapshot)
552552

553553
ExecApprovalsAgent? currentAgent = null;
554554
current.Agents?.TryGetValue(agentId, out currentAgent);
555-
var currentPatterns = new HashSet<string>(
555+
var currentRules = new HashSet<ExecAllowlistRuleKey>(
556556
(currentAgent?.Allowlist ?? [])
557-
.Select(entry => entry.Pattern?.Trim())
558-
.Where(pattern => !string.IsNullOrWhiteSpace(pattern))!,
559-
StringComparer.OrdinalIgnoreCase);
557+
.Where(entry => !string.IsNullOrWhiteSpace(entry.Pattern))
558+
.Select(ExecAllowlistRuleIdentity.From),
559+
ExecAllowlistRuleIdentity.AuthorityComparer);
560560

561561
foreach (var entry in agent.Allowlist ?? [])
562562
{
563563
var pattern = entry.Pattern?.Trim();
564564
if (string.IsNullOrWhiteSpace(pattern))
565565
return "Empty allowlist patterns are not permitted.";
566-
if (!currentPatterns.Contains(pattern))
566+
if (!currentRules.Contains(ExecAllowlistRuleIdentity.From(entry)))
567567
{
568568
return
569-
$"Remote exec approval updates cannot add or change allowlist entries for agent '{agentId}'.";
569+
$"Remote exec approval updates cannot add or change allowlist authority for agent '{agentId}'.";
570570
}
571571
}
572572
}

‎src/OpenClaw.Shared/ExecApprovals/CanonicalCommandIdentity.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public sealed class CanonicalCommandIdentity
3232
public IReadOnlyList<ExecCommandResolution> AllowlistResolutions { get; }
3333

3434
// Suggested allowlist patterns for prompt/UI. Not a security decision.
35-
public IReadOnlyList<string> AllowAlwaysPatterns { get; }
35+
public IReadOnlyList<ExecAllowAlwaysPattern> AllowAlwaysPatterns { get; }
3636

3737
// ── Request context (carried from ValidatedRunRequest) ────────────────────
3838

@@ -48,7 +48,7 @@ internal CanonicalCommandIdentity(
4848
string? evaluationRawCommand,
4949
ExecCommandResolution? resolution,
5050
IReadOnlyList<ExecCommandResolution> allowlistResolutions,
51-
IReadOnlyList<string> allowAlwaysPatterns,
51+
IReadOnlyList<ExecAllowAlwaysPattern> allowAlwaysPatterns,
5252
string? cwd,
5353
int timeoutMs,
5454
IReadOnlyDictionary<string, string>? env,

‎src/OpenClaw.Shared/ExecApprovals/ExecAllowlistMatcher.cs‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,16 +25,31 @@ internal static class ExecAllowlistMatcher
2525
ExecCommandResolution resolution)
2626
{
2727
var target = NormalizeSeparators(resolution.ResolvedPath ?? resolution.RawExecutable);
28+
ExecAllowlistEntry? pathOnlyMatch = null;
2829
foreach (var entry in entries)
2930
{
3031
var pattern = entry.Pattern;
3132
if (string.IsNullOrWhiteSpace(pattern)) continue;
3233
var normalizedPattern = NormalizeSeparators(pattern);
3334
if (!IsValidNormalizedPattern(normalizedPattern)) continue;
34-
if (s_regexCache.GetOrAdd(normalizedPattern, BuildPatternRegex).IsMatch(target))
35+
if (!s_regexCache.GetOrAdd(normalizedPattern, BuildPatternRegex).IsMatch(target))
36+
continue;
37+
38+
if (string.IsNullOrEmpty(entry.ArgPattern))
39+
{
40+
if (string.Equals(
41+
entry.Source,
42+
ExecAllowlistEntry.AllowAlwaysSource,
43+
StringComparison.Ordinal))
44+
continue;
45+
pathOnlyMatch ??= entry;
46+
continue;
47+
}
48+
49+
if (ExecArgPattern.Matches(entry.ArgPattern, resolution.Argv))
3550
return entry;
3651
}
37-
return null;
52+
return pathOnlyMatch;
3853
}
3954

4055
// Returns one matching entry per resolution in input order.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
namespace OpenClaw.Shared.ExecApprovals;
2+
3+
internal readonly record struct ExecAllowlistRuleKey(
4+
string Pattern,
5+
string? ArgPattern,
6+
string? Source);
7+
8+
internal static class ExecAllowlistRuleIdentity
9+
{
10+
internal static IEqualityComparer<ExecAllowlistRuleKey> MatchComparer { get; } =
11+
new RuleComparer(includeSource: false);
12+
13+
internal static IEqualityComparer<ExecAllowlistRuleKey> AuthorityComparer { get; } =
14+
new RuleComparer(includeSource: true);
15+
16+
internal static ExecAllowlistRuleKey From(ExecAllowlistEntry entry) =>
17+
new(
18+
entry.Pattern?.Trim() ?? "",
19+
NormalizeExactOptional(entry.ArgPattern),
20+
NormalizeExactOptional(entry.Source));
21+
22+
internal static bool MatchKeyEquals(
23+
ExecAllowlistEntry left,
24+
ExecAllowlistEntry right) =>
25+
MatchComparer.Equals(From(left), From(right));
26+
27+
internal static bool AuthorityEquals(
28+
ExecAllowlistEntry left,
29+
ExecAllowlistEntry right) =>
30+
AuthorityComparer.Equals(From(left), From(right));
31+
32+
private static string? NormalizeExactOptional(string? value) =>
33+
string.IsNullOrEmpty(value) ? null : value;
34+
35+
private sealed class RuleComparer(bool includeSource)
36+
: IEqualityComparer<ExecAllowlistRuleKey>
37+
{
38+
public bool Equals(ExecAllowlistRuleKey left, ExecAllowlistRuleKey right) =>
39+
string.Equals(left.Pattern, right.Pattern, StringComparison.OrdinalIgnoreCase)
40+
&& string.Equals(left.ArgPattern, right.ArgPattern, StringComparison.Ordinal)
41+
&& (!includeSource
42+
|| string.Equals(left.Source, right.Source, StringComparison.Ordinal));
43+
44+
public int GetHashCode(ExecAllowlistRuleKey key)
45+
{
46+
var hash = new HashCode();
47+
hash.Add(key.Pattern, StringComparer.OrdinalIgnoreCase);
48+
hash.Add(key.ArgPattern, StringComparer.Ordinal);
49+
if (includeSource)
50+
hash.Add(key.Source, StringComparer.Ordinal);
51+
return hash.ToHashCode();
52+
}
53+
}
54+
}

‎src/OpenClaw.Shared/ExecApprovals/ExecApprovalEvaluation.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public sealed class ExecApprovalEvaluation
2121
public ExecCommandResolution? Resolution { get; }
2222

2323
public IReadOnlyList<ExecCommandResolution> AllowlistResolutions { get; }
24-
public IReadOnlyList<string> AllowAlwaysPatterns { get; }
24+
public IReadOnlyList<ExecAllowAlwaysPattern> AllowAlwaysPatterns { get; }
2525
public IReadOnlyList<ExecAllowlistEntry> AllowlistMatches { get; }
2626

2727
public bool AllAllowlistResolutionsMatched { get; }
@@ -45,7 +45,7 @@ public ExecApprovalEvaluation(
4545
ExecAsk ask,
4646
IReadOnlyDictionary<string, string>? env,
4747
IReadOnlyList<ExecCommandResolution> allowlistResolutions,
48-
IReadOnlyList<string> allowAlwaysPatterns,
48+
IReadOnlyList<ExecAllowAlwaysPattern> allowAlwaysPatterns,
4949
IReadOnlyList<ExecAllowlistEntry> allowlistMatches,
5050
bool skillAllow = false)
5151
{

‎src/OpenClaw.Shared/ExecApprovals/ExecApprovalsContracts.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,12 @@ public enum ExecApprovalDecision
3434

3535
public sealed class ExecAllowlistEntry
3636
{
37+
public const string AllowAlwaysSource = "allow-always";
38+
3739
public Guid? Id { get; set; }
3840
public string? Pattern { get; set; }
41+
public string? Source { get; set; }
42+
public string? ArgPattern { get; set; }
3943
public double? LastUsedAt { get; set; }
4044
public string? LastResolvedPath { get; set; }
4145
}

‎src/OpenClaw.Shared/ExecApprovals/ExecApprovalsCoordinator.cs‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -393,11 +393,26 @@ private static bool IsIndirectCommandHost(CanonicalCommandIdentity identity)
393393
// Caller guarantees Security == Allowlist (guard is in HandleAsync step 8).
394394
private async Task PersistAllowlistEntriesAsync(ExecApprovalEvaluation context)
395395
{
396-
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
397-
foreach (var pattern in context.AllowAlwaysPatterns)
396+
var seen = new HashSet<ExecAllowlistRuleKey>(
397+
ExecAllowlistRuleIdentity.MatchComparer);
398+
foreach (var candidate in context.AllowAlwaysPatterns)
398399
{
399-
if (string.IsNullOrWhiteSpace(pattern) || !seen.Add(pattern)) continue;
400-
await _store.AddAllowlistEntryAsync(context.AgentId, pattern).ConfigureAwait(false);
400+
if (string.IsNullOrWhiteSpace(candidate.Pattern))
401+
continue;
402+
var entry = new ExecAllowlistEntry
403+
{
404+
Pattern = candidate.Pattern,
405+
ArgPattern = candidate.ArgPattern,
406+
Source = ExecAllowlistEntry.AllowAlwaysSource,
407+
};
408+
if (!seen.Add(ExecAllowlistRuleIdentity.From(entry)))
409+
continue;
410+
await _store.AddAllowlistEntryAsync(
411+
context.AgentId,
412+
candidate.Pattern,
413+
candidate.ArgPattern,
414+
ExecAllowlistEntry.AllowAlwaysSource)
415+
.ConfigureAwait(false);
401416
}
402417
}
403418

@@ -406,16 +421,21 @@ private async Task PersistAllowlistEntriesAsync(ExecApprovalEvaluation context)
406421
private async Task RecordAllowlistUsageAsync(ExecApprovalEvaluation context)
407422
{
408423
if (context.Security != ExecSecurity.Allowlist || !context.AllowlistSatisfied) return;
409-
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
424+
var seen = new HashSet<ExecAllowlistRuleKey>(
425+
ExecAllowlistRuleIdentity.AuthorityComparer);
410426
for (var i = 0; i < context.AllowlistMatches.Count; i++)
411427
{
412-
var pattern = context.AllowlistMatches[i].Pattern;
413-
if (string.IsNullOrEmpty(pattern) || !seen.Add(pattern)) continue;
428+
var matchedEntry = context.AllowlistMatches[i];
429+
if (string.IsNullOrEmpty(matchedEntry.Pattern)
430+
|| !seen.Add(ExecAllowlistRuleIdentity.From(matchedEntry)))
431+
continue;
414432
var resolvedPath = i < context.AllowlistResolutions.Count
415433
? context.AllowlistResolutions[i].ResolvedPath
416434
: null;
417435
await _store.RecordAllowlistUseAsync(
418-
context.AgentId, pattern, resolvedPath)
436+
context.AgentId,
437+
matchedEntry,
438+
resolvedPath)
419439
.ConfigureAwait(false);
420440
}
421441
}

0 commit comments

Comments
 (0)