|
| 1 | +using System.Text.Json; |
| 2 | +using Microsoft.Extensions.Logging; |
| 3 | +using OpenClaw.Core.Abstractions; |
| 4 | +using OpenClaw.Core.Models; |
| 5 | +using OpenClaw.Agent.Tools; |
| 6 | + |
| 7 | +namespace OpenClaw.Agent; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Enforces contract-scoped tool restrictions at tool-call time. |
| 11 | +/// Checks path-scoped capabilities and tool call count limits. |
| 12 | +/// </summary> |
| 13 | +public sealed class ContractScopeHook : IToolHookWithContext |
| 14 | +{ |
| 15 | + private readonly Func<string, ContractPolicy?> _contractResolver; |
| 16 | + private readonly Func<string, int> _toolCallCounter; |
| 17 | + private readonly ILogger _logger; |
| 18 | + |
| 19 | + public string Name => "ContractScope"; |
| 20 | + |
| 21 | + /// <param name="contractResolver">Resolves a session ID to its contract policy (or null).</param> |
| 22 | + /// <param name="toolCallCounter">Returns the current tool call count for a session ID.</param> |
| 23 | + /// <param name="logger">Logger instance.</param> |
| 24 | + public ContractScopeHook( |
| 25 | + Func<string, ContractPolicy?> contractResolver, |
| 26 | + Func<string, int> toolCallCounter, |
| 27 | + ILogger logger) |
| 28 | + { |
| 29 | + _contractResolver = contractResolver; |
| 30 | + _toolCallCounter = toolCallCounter; |
| 31 | + _logger = logger; |
| 32 | + } |
| 33 | + |
| 34 | + public ValueTask<bool> BeforeExecuteAsync(string toolName, string arguments, CancellationToken ct) |
| 35 | + => ValueTask.FromResult(true); // No-op for non-context path; context variant handles enforcement. |
| 36 | + |
| 37 | + public ValueTask<bool> BeforeExecuteAsync(ToolHookContext context, CancellationToken ct) |
| 38 | + { |
| 39 | + var policy = _contractResolver(context.SessionId); |
| 40 | + if (policy is null) |
| 41 | + return ValueTask.FromResult(true); |
| 42 | + |
| 43 | + // Check MaxToolCalls |
| 44 | + if (policy.MaxToolCalls > 0) |
| 45 | + { |
| 46 | + var count = _toolCallCounter(context.SessionId); |
| 47 | + if (count >= policy.MaxToolCalls) |
| 48 | + { |
| 49 | + _logger.LogInformation( |
| 50 | + "ContractScope: denied tool {Tool} for session {Session} — MaxToolCalls ({Max}) reached", |
| 51 | + context.ToolName, context.SessionId, policy.MaxToolCalls); |
| 52 | + return ValueTask.FromResult(false); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + // Check scoped capabilities (path restrictions) |
| 57 | + var scope = FindScope(policy, context.ToolName); |
| 58 | + if (scope is not null && scope.AllowedPaths.Length > 0) |
| 59 | + { |
| 60 | + if (TryExtractPathArgument(context.ToolName, context.ArgumentsJson, out var path) && |
| 61 | + !string.IsNullOrWhiteSpace(path)) |
| 62 | + { |
| 63 | + if (!IsPathAllowed(path!, scope.AllowedPaths)) |
| 64 | + { |
| 65 | + _logger.LogInformation( |
| 66 | + "ContractScope: denied tool {Tool} path {Path} for session {Session} — outside scoped paths", |
| 67 | + context.ToolName, path, context.SessionId); |
| 68 | + return ValueTask.FromResult(false); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return ValueTask.FromResult(true); |
| 74 | + } |
| 75 | + |
| 76 | + public ValueTask AfterExecuteAsync(string toolName, string arguments, string result, TimeSpan duration, bool failed, CancellationToken ct) |
| 77 | + => ValueTask.CompletedTask; |
| 78 | + |
| 79 | + public ValueTask AfterExecuteAsync(ToolHookContext context, string result, TimeSpan duration, bool failed, CancellationToken ct) |
| 80 | + => ValueTask.CompletedTask; |
| 81 | + |
| 82 | + private static ScopedCapability? FindScope(ContractPolicy policy, string toolName) |
| 83 | + { |
| 84 | + foreach (var scope in policy.ScopedCapabilities) |
| 85 | + { |
| 86 | + if (string.Equals(scope.ToolName, toolName, StringComparison.Ordinal)) |
| 87 | + return scope; |
| 88 | + } |
| 89 | + return null; |
| 90 | + } |
| 91 | + |
| 92 | + private static bool IsPathAllowed(string path, string[] allowedPaths) |
| 93 | + { |
| 94 | + var expanded = ExpandTilde(path); |
| 95 | + var full = ToolPathPolicy.ResolveRealPath(expanded); |
| 96 | + |
| 97 | + var comparison = OperatingSystem.IsWindows() |
| 98 | + ? StringComparison.OrdinalIgnoreCase |
| 99 | + : StringComparison.Ordinal; |
| 100 | + |
| 101 | + foreach (var allowed in allowedPaths) |
| 102 | + { |
| 103 | + var allowedExpanded = ExpandTilde(allowed.Trim()); |
| 104 | + var allowedFull = Path.GetFullPath(allowedExpanded); |
| 105 | + |
| 106 | + if (string.Equals(full, allowedFull, comparison)) |
| 107 | + return true; |
| 108 | + |
| 109 | + var root = allowedFull.EndsWith(Path.DirectorySeparatorChar) |
| 110 | + ? allowedFull |
| 111 | + : allowedFull + Path.DirectorySeparatorChar; |
| 112 | + |
| 113 | + if (full.StartsWith(root, comparison)) |
| 114 | + return true; |
| 115 | + } |
| 116 | + |
| 117 | + return false; |
| 118 | + } |
| 119 | + |
| 120 | + private static bool TryExtractPathArgument(string toolName, string arguments, out string? path) |
| 121 | + { |
| 122 | + path = null; |
| 123 | + var prop = toolName switch |
| 124 | + { |
| 125 | + "git" => "cwd", |
| 126 | + _ => "path" |
| 127 | + }; |
| 128 | + |
| 129 | + try |
| 130 | + { |
| 131 | + using var doc = JsonDocument.Parse(arguments); |
| 132 | + if (doc.RootElement.TryGetProperty(prop, out var p) && p.ValueKind == JsonValueKind.String) |
| 133 | + { |
| 134 | + path = p.GetString(); |
| 135 | + return !string.IsNullOrWhiteSpace(path); |
| 136 | + } |
| 137 | + } |
| 138 | + catch { } |
| 139 | + |
| 140 | + return false; |
| 141 | + } |
| 142 | + |
| 143 | + private static string ExpandTilde(string path) |
| 144 | + { |
| 145 | + if (path.StartsWith("~/", StringComparison.Ordinal) || path == "~") |
| 146 | + { |
| 147 | + var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| 148 | + return path.Length == 1 ? home : Path.Combine(home, path[2..]); |
| 149 | + } |
| 150 | + return path; |
| 151 | + } |
| 152 | +} |
0 commit comments