| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | package guard |
| 7 | |
| 8 | import ( |
| 9 | "bufio" |
| 10 | "context" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "io/fs" |
| 14 | "os" |
| 15 | "path" |
| 16 | "runtime" |
| 17 | "strings" |
| 18 | "sync" |
| 19 | "time" |
| 20 | "unicode" |
| 21 | |
| 22 | "github.com/lima-vm/sshocker/pkg/reversesshfs" |
| 23 | "github.com/sylvinus/agent-vm/internal/desktop" |
| 24 | ) |
| 25 | |
| 26 | |
| 27 | |
| 28 | const FileName = "guarded" |
| 29 | |
| 30 | |
| 31 | |
| 32 | var Defaults = map[string]string{ |
| 33 | ".envrc": "direnv runs it when you enter the folder.", |
| 34 | |
| 35 | ".vscode/tasks.json": "VS Code can run its tasks when the folder opens.", |
| 36 | ".vscode/settings.json": "VS Code reads commands from it (terminal profiles, tools to run).", |
| 37 | ".vscode/launch.json": "VS Code runs it when you debug.", |
| 38 | ".vscode/mcp.json": "VS Code starts the MCP servers it lists.", |
| 39 | |
| 40 | ".devcontainer/devcontainer.json": "VS Code runs its initializeCommand on your machine when you reopen the folder in a container.", |
| 41 | ".devcontainer.json": "VS Code runs its initializeCommand on your machine when you reopen the folder in a container.", |
| 42 | |
| 43 | ".idea/runConfigurations": "JetBrains IDEs run these configurations on your machine.", |
| 44 | ".idea/watchers.xml": "JetBrains IDEs run its file watchers on your machine each time you save.", |
| 45 | ".zed/settings.json": "Zed starts the language servers it names.", |
| 46 | ".zed/tasks.json": "Zed runs its tasks.", |
| 47 | ".dir-locals.el": "Emacs applies its settings, which can evaluate code, when you open a file.", |
| 48 | |
| 49 | ".claude/settings.json": "Claude Code runs the hooks it lists on your machine.", |
| 50 | ".claude/settings.local.json": "Claude Code runs the hooks it lists on your machine.", |
| 51 | ".mcp.json": "Claude Code starts the MCP servers it lists.", |
| 52 | ".cursor/mcp.json": "Cursor starts the MCP servers it lists.", |
| 53 | ".cursor/hooks.json": "Cursor runs the hooks it lists on your machine.", |
| 54 | ".codex/config.toml": "Codex starts the MCP servers and programs it lists.", |
| 55 | ".gemini/settings.json": "Gemini CLI starts the MCP servers and hooks it lists.", |
| 56 | |
| 57 | ".pre-commit-config.yaml": "pre-commit runs its hooks on your commits.", |
| 58 | "lefthook.yml": "lefthook runs its hooks on your commits.", |
| 59 | ".lefthook.yml": "lefthook runs its hooks on your commits.", |
| 60 | "lefthook.yaml": "lefthook runs its hooks on your commits.", |
| 61 | ".lefthook.yaml": "lefthook runs its hooks on your commits.", |
| 62 | "lefthook-local.yml": "lefthook runs its hooks on your commits.", |
| 63 | ".lefthook-local.yml": "lefthook runs its hooks on your commits.", |
| 64 | ".husky": "Git runs these hooks on your commits.", |
| 65 | ".githooks": "Git runs these hooks on your commits when core.hooksPath points here.", |
| 66 | |
| 67 | "mise.toml": "mise runs its hooks and tasks when you enter the folder.", |
| 68 | ".mise.toml": "mise runs its hooks and tasks when you enter the folder.", |
| 69 | "mise.local.toml": "mise runs its hooks and tasks when you enter the folder.", |
| 70 | ".mise.local.toml": "mise runs its hooks and tasks when you enter the folder.", |
| 71 | ".mise": "mise runs its config and tasks when you enter the folder.", |
| 72 | ".config/mise.toml": "mise runs its hooks and tasks when you enter the folder.", |
| 73 | ".config/mise": "mise runs its config and tasks when you enter the folder.", |
| 74 | ".yarnrc.yml": "yarn runs the program its yarnPath and plugins name.", |
| 75 | ".yarn/releases": "yarn runs these files.", |
| 76 | ".yarn/plugins": "yarn runs these files.", |
| 77 | ".pnpmfile.cjs": "pnpm runs it when you install.", |
| 78 | ".npmrc": "npm can run the program its script-shell or git settings name.", |
| 79 | ".cargo/config.toml": "cargo can run the program its runner and wrapper settings name.", |
| 80 | ".cargo/config": "cargo can run the program its runner and wrapper settings name.", |
| 81 | ".lfsconfig": "git-lfs sends your files and credentials to the server it names.", |
| 82 | } |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | var WindowsDefaults = map[string]string{ |
| 90 | "*.library-ms": "Explorer contacts the server it names when it shows it, and sends your NTLM hash.", |
| 91 | "*.searchConnector-ms": "Explorer contacts the server it names when it shows it, and sends your NTLM hash.", |
| 92 | "*.lnk": "Explorer can contact the server its icon names when it shows it, and send your NTLM hash.", |
| 93 | "*.url": "Explorer can contact the server its icon names when it shows it, and send your NTLM hash.", |
| 94 | "*.scf": "Explorer contacts the server its icon names when it shows it, and sends your NTLM hash.", |
| 95 | "desktop.ini": "Explorer contacts the server it names when it shows the folder, and sends your NTLM hash.", |
| 96 | } |
| 97 | |
| 98 | |
| 99 | |
| 100 | const deniedFor = time.Minute |
| 101 | |
| 102 | |
| 103 | const answerWithin = 2 * time.Minute |
| 104 | |
| 105 | |
| 106 | |
| 107 | const ( |
| 108 | maxRefusals = 3 |
| 109 | refusalWindow = 5 * time.Minute |
| 110 | coolDown = 5 * time.Minute |
| 111 | ) |
| 112 | |
| 113 | |
| 114 | const maxShown = 100 |
| 115 | |
| 116 | |
| 117 | |
| 118 | var maxScan = 20000 |
| 119 | |
| 120 | |
| 121 | type Guard struct { |
| 122 | |
| 123 | VM string |
| 124 | |
| 125 | |
| 126 | |
| 127 | Paths map[string]string |
| 128 | |
| 129 | |
| 130 | Ask func(ctx context.Context, title, msg string) (allow, ok bool) |
| 131 | |
| 132 | Tell func(title, msg string) |
| 133 | |
| 134 | rulesOnce sync.Once |
| 135 | rules []rule |
| 136 | |
| 137 | askMu sync.Mutex |
| 138 | mu sync.Mutex |
| 139 | allowed map[string]bool |
| 140 | denied map[string]time.Time |
| 141 | refusals []time.Time |
| 142 | coolUntil time.Time |
| 143 | now func() time.Time |
| 144 | } |
| 145 | |
| 146 | |
| 147 | |
| 148 | type rule struct { |
| 149 | path string |
| 150 | comps []string |
| 151 | ext string |
| 152 | } |
| 153 | |
| 154 | |
| 155 | func Load(stateDir, vm string) (*Guard, error) { |
| 156 | g := &Guard{VM: vm, Paths: map[string]string{}, Ask: desktop.Ask, Tell: desktop.Notify} |
| 157 | |
| 158 | if os.Getenv("AGENT_VM_GUARDED_WRITES") == "deny" { |
| 159 | g.Ask = func(context.Context, string, string) (bool, bool) { return false, true } |
| 160 | } |
| 161 | for p, why := range Defaults { |
| 162 | g.Paths[p] = why |
| 163 | } |
| 164 | if windowsHost { |
| 165 | for p, why := range WindowsDefaults { |
| 166 | g.Paths[p] = why |
| 167 | } |
| 168 | } |
| 169 | f, err := os.Open(stateDir + "/" + FileName) |
| 170 | if errors.Is(err, os.ErrNotExist) { |
| 171 | return g, nil |
| 172 | } |
| 173 | if err != nil { |
| 174 | return nil, err |
| 175 | } |
| 176 | defer f.Close() |
| 177 | sc := bufio.NewScanner(f) |
| 178 | for sc.Scan() { |
| 179 | line, _, _ := strings.Cut(sc.Text(), "#") |
| 180 | line = strings.TrimSpace(line) |
| 181 | if line == "" { |
| 182 | continue |
| 183 | } |
| 184 | if p, ok := strings.CutPrefix(line, "!"); ok { |
| 185 | for k := range g.Paths { |
| 186 | if strings.EqualFold(k, clean(p)) { |
| 187 | delete(g.Paths, k) |
| 188 | } |
| 189 | } |
| 190 | continue |
| 191 | } |
| 192 | if _, ok := g.Paths[clean(line)]; !ok { |
| 193 | g.Paths[clean(line)] = "" |
| 194 | } |
| 195 | } |
| 196 | return g, sc.Err() |
| 197 | } |
| 198 | |
| 199 | func clean(p string) string { return strings.Trim(path.Clean("/"+strings.TrimSpace(p)), "/") } |
| 200 | |
| 201 | |
| 202 | |
| 203 | var windowsHost = runtime.GOOS == "windows" |
| 204 | |
| 205 | func foldAll(p string) []string { |
| 206 | comps := strings.Split(p, "/") |
| 207 | for i, c := range comps { |
| 208 | if windowsHost { |
| 209 | c, _, _ = strings.Cut(c, ":") |
| 210 | c = strings.TrimRight(c, ". ") |
| 211 | } |
| 212 | comps[i] = reversesshfs.FoldName(c) |
| 213 | } |
| 214 | return comps |
| 215 | } |
| 216 | |
| 217 | func (g *Guard) loadRules() []rule { |
| 218 | g.rulesOnce.Do(func() { |
| 219 | for p := range g.Paths { |
| 220 | if ext, ok := strings.CutPrefix(p, "*."); ok && !strings.Contains(ext, "/") { |
| 221 | g.rules = append(g.rules, rule{path: p, ext: foldAll("." + ext)[0]}) |
| 222 | continue |
| 223 | } |
| 224 | g.rules = append(g.rules, rule{path: p, comps: foldAll(p)}) |
| 225 | } |
| 226 | }) |
| 227 | return g.rules |
| 228 | } |
| 229 | |
| 230 | |
| 231 | type hit struct { |
| 232 | rule string |
| 233 | kind kind |
| 234 | key string |
| 235 | } |
| 236 | |
| 237 | type kind int |
| 238 | |
| 239 | const ( |
| 240 | |
| 241 | kindPath kind = iota |
| 242 | |
| 243 | kindParent |
| 244 | |
| 245 | kindInside |
| 246 | |
| 247 | kindTooBig |
| 248 | ) |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | func (g *Guard) match(rel string, entry bool) (hit, bool) { |
| 254 | comps := foldAll(rel) |
| 255 | for _, r := range g.loadRules() { |
| 256 | if r.ext != "" { |
| 257 | if strings.HasSuffix(comps[len(comps)-1], r.ext) { |
| 258 | return hit{r.path, kindPath, "p:" + strings.Join(comps, "/")}, true |
| 259 | } |
| 260 | continue |
| 261 | } |
| 262 | n := len(r.comps) |
| 263 | for i := 0; i+n <= len(comps); i++ { |
| 264 | if equal(comps[i:i+n], r.comps) { |
| 265 | return hit{r.path, kindPath, "p:" + strings.Join(comps[:i+n], "/")}, true |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 | if !entry { |
| 270 | return hit{}, false |
| 271 | } |
| 272 | for _, r := range g.loadRules() { |
| 273 | if r.ext != "" { |
| 274 | continue |
| 275 | } |
| 276 | for k := min(len(r.comps)-1, len(comps)); k >= 1; k-- { |
| 277 | if equal(comps[len(comps)-k:], r.comps[:k]) { |
| 278 | return hit{r.path, kindParent, "d:" + strings.Join(comps, "/")}, true |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | return hit{}, false |
| 283 | } |
| 284 | |
| 285 | func equal(a, b []string) bool { |
| 286 | for i := range a { |
| 287 | if a[i] != b[i] { |
| 288 | return false |
| 289 | } |
| 290 | } |
| 291 | return len(a) == len(b) |
| 292 | } |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | func (g *Guard) holds(root, rel string) (hit, bool) { |
| 298 | r, err := os.OpenRoot(root) |
| 299 | if err != nil { |
| 300 | return hit{}, false |
| 301 | } |
| 302 | defer r.Close() |
| 303 | if fi, err := r.Lstat(rel); err != nil || !fi.IsDir() { |
| 304 | return hit{}, false |
| 305 | } |
| 306 | var found hit |
| 307 | seen := 0 |
| 308 | _ = fs.WalkDir(r.FS(), rel, func(p string, d fs.DirEntry, err error) error { |
| 309 | if err != nil || p == rel { |
| 310 | return nil |
| 311 | } |
| 312 | if seen++; seen > maxScan { |
| 313 | found = hit{fmt.Sprintf("a folder with more than %d entries", maxScan), kindTooBig, "b:" + strings.Join(foldAll(rel), "/")} |
| 314 | return fs.SkipAll |
| 315 | } |
| 316 | if m, ok := g.match(p, false); ok { |
| 317 | found = hit{m.rule, kindInside, "i:" + strings.Join(foldAll(rel), "/")} |
| 318 | return fs.SkipAll |
| 319 | } |
| 320 | return nil |
| 321 | }) |
| 322 | return found, found.rule != "" |
| 323 | } |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | func (g *Guard) Allow(root, rel string, entry bool) bool { |
| 330 | h, ok := g.match(rel, entry) |
| 331 | if !ok && entry { |
| 332 | h, ok = g.holds(root, rel) |
| 333 | } |
| 334 | if !ok { |
| 335 | return true |
| 336 | } |
| 337 | key := root + "/" + h.key |
| 338 | if allow, decided := g.decided(key); decided { |
| 339 | return allow |
| 340 | } |
| 341 | g.askMu.Lock() |
| 342 | defer g.askMu.Unlock() |
| 343 | |
| 344 | if allow, decided := g.decided(key); decided { |
| 345 | return allow |
| 346 | } |
| 347 | |
| 348 | why := g.Paths[h.rule] |
| 349 | if h.kind == kindTooBig { |
| 350 | why = "It may hold a file agent-vm guards." |
| 351 | } else if why == "" { |
| 352 | why = "You asked agent-vm to guard it (~/.agent-vm/" + FileName + ")." |
| 353 | } |
| 354 | title := "agent-vm: " + g.VM |
| 355 | msg := question(root, rel, h, why) |
| 356 | ctx, cancel := context.WithTimeout(context.Background(), answerWithin) |
| 357 | defer cancel() |
| 358 | allow, asked := g.Ask(ctx, title, msg) |
| 359 | if !asked && g.Tell != nil { |
| 360 | g.Tell(title, fmt.Sprintf("Refused: the VM wanted to change %s in %s, and no dialog could ask you.", h.rule, root)) |
| 361 | } |
| 362 | |
| 363 | g.mu.Lock() |
| 364 | defer g.mu.Unlock() |
| 365 | if allow { |
| 366 | if g.allowed == nil { |
| 367 | g.allowed = map[string]bool{} |
| 368 | } |
| 369 | g.allowed[key] = true |
| 370 | return true |
| 371 | } |
| 372 | now := g.time() |
| 373 | if g.denied == nil { |
| 374 | g.denied = map[string]time.Time{} |
| 375 | } |
| 376 | g.denied[key] = now.Add(deniedFor) |
| 377 | for len(g.refusals) > 0 && now.Sub(g.refusals[0]) > refusalWindow { |
| 378 | g.refusals = g.refusals[1:] |
| 379 | } |
| 380 | g.refusals = append(g.refusals, now) |
| 381 | if len(g.refusals) >= maxRefusals { |
| 382 | g.coolUntil = now.Add(coolDown) |
| 383 | g.refusals = nil |
| 384 | if g.Tell != nil { |
| 385 | g.Tell(title, fmt.Sprintf("The VM asked to change guarded files %d times and was refused: it is refused without asking for %d minutes.", maxRefusals, int(coolDown/time.Minute))) |
| 386 | } |
| 387 | } |
| 388 | return false |
| 389 | } |
| 390 | |
| 391 | func (g *Guard) time() time.Time { |
| 392 | if g.now != nil { |
| 393 | return g.now() |
| 394 | } |
| 395 | return time.Now() |
| 396 | } |
| 397 | |
| 398 | |
| 399 | |
| 400 | func (g *Guard) decided(key string) (allow, ok bool) { |
| 401 | g.mu.Lock() |
| 402 | defer g.mu.Unlock() |
| 403 | now := g.time() |
| 404 | if g.allowed[key] { |
| 405 | return true, true |
| 406 | } |
| 407 | if until, ok := g.denied[key]; ok && now.Before(until) { |
| 408 | return false, true |
| 409 | } |
| 410 | if now.Before(g.coolUntil) { |
| 411 | return false, true |
| 412 | } |
| 413 | return false, false |
| 414 | } |
| 415 | |
| 416 | |
| 417 | |
| 418 | func question(root, rel string, h hit, why string) string { |
| 419 | var what string |
| 420 | switch h.kind { |
| 421 | case kindPath: |
| 422 | what = "change " + h.rule |
| 423 | case kindParent: |
| 424 | what = "create, move or remove a folder that holds " + h.rule |
| 425 | case kindInside: |
| 426 | what = "move or remove a folder that holds " + h.rule |
| 427 | case kindTooBig: |
| 428 | what = "move or remove " + h.rule + " (too many to check for guarded files)" |
| 429 | } |
| 430 | return fmt.Sprintf("The VM wants to %s in %s.\n\nPath: %s\n\n%s\n\nAllow it? (Until the VM stops.)", what, root, shown(rel), why) |
| 431 | } |
| 432 | |
| 433 | |
| 434 | |
| 435 | func shown(rel string) string { |
| 436 | var b []rune |
| 437 | for _, r := range rel { |
| 438 | switch { |
| 439 | case r == '<' || r == '>' || r == '&': |
| 440 | b = append(b, '?') |
| 441 | case unicode.IsControl(r) || unicode.In(r, unicode.Cf, unicode.Zl, unicode.Zp, unicode.Variation_Selector, unicode.Other_Default_Ignorable_Code_Point): |
| 442 | |
| 443 | default: |
| 444 | b = append(b, r) |
| 445 | } |
| 446 | } |
| 447 | if len(b) > maxShown { |
| 448 | return "..." + string(b[len(b)-maxShown:]) |
| 449 | } |
| 450 | return string(b) |
| 451 | } |