-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfs.go
More file actions
652 lines (601 loc) · 16.4 KB
/
fs.go
File metadata and controls
652 lines (601 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
// Sandboxed local filesystem I/O for the Core framework.
package core
import (
"io/fs"
)
// Fs is a sandboxed local filesystem backend.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.EnsureDir("logs")
// if !r.OK { return r }
type Fs struct {
root string
}
// FS is a generic filesystem accepted by Mount and Extract.
//
// fsys := core.DirFS("templates")
// r := core.Mount(fsys, ".")
type FS = fs.FS
// FsFile is a file opened from an FS.
//
// r := emb.Open("README.md")
// if r.OK { file := r.Value.(core.FsFile); _ = file }
type FsFile = fs.File
// FsFileInfo describes a file returned by Stat and PathWalk.
//
// info := stat.Value.(core.FsFileInfo)
// _ = info
type FsFileInfo = fs.FileInfo
// FsDirEntry is a directory entry returned by filesystem walkers.
//
// r := emb.ReadDir(".")
// if r.OK { entries := r.Value.([]core.FsDirEntry); _ = entries }
type FsDirEntry = fs.DirEntry
// WalkDirFunc visits one path during a filesystem walk.
//
// fn := func(path string, d core.FsDirEntry, err error) error { return err }
// _ = fn
type WalkDirFunc = fs.WalkDirFunc
// New initialises an Fs with the given root directory.
// Root "/" means unrestricted access. Empty root defaults to "/".
//
// fs := (&core.Fs{}).New("/")
func (m *Fs) New(root string) *Fs {
if root == "" {
root = "/"
}
m.root = root
return m
}
// NewUnrestricted returns a new Fs with root "/", granting full filesystem access.
// Use this instead of unsafe.Pointer to bypass the sandbox.
//
// fs := c.Fs().NewUnrestricted()
// fs.Read("/etc/hostname") // works — no sandbox
func (m *Fs) NewUnrestricted() *Fs {
return (&Fs{}).New("/")
}
// Root returns the sandbox root path.
//
// root := c.Fs().Root() // e.g. "/home/agent/.core"
func (m *Fs) Root() string {
if m.root == "" {
return "/"
}
return m.root
}
// path sanitises and returns the full path.
// Absolute paths are sandboxed under root (unless root is "/").
// Empty root defaults to "/" — the zero value of Fs is usable.
func (m *Fs) path(p string) string {
root := m.root
if root == "" {
root = "/"
}
if p == "" {
return root
}
// If the path is relative and the medium is rooted at "/",
// treat it as relative to the current working directory.
// This makes io.Local behave more like the standard 'os' package.
if root == "/" && !PathIsAbs(p) {
cwd := ""
if r := Getwd(); r.OK {
cwd = r.Value.(string)
}
return PathJoin(cwd, p)
}
// Use a leading slash to resolve all .. and . internally
// before joining with the root. This is a standard way to sandbox paths.
clean := CleanPath("/"+p, string(PathSeparator))
// If root is "/", allow absolute paths through
if root == "/" {
return clean
}
// Strip leading "/" so Join works correctly with root
return PathJoin(root, clean[1:])
}
// validatePath ensures the path is within the sandbox, following symlinks if they exist.
func (m *Fs) validatePath(p string) Result {
root := m.root
if root == "" {
root = "/"
}
if root == "/" {
return Result{m.path(p), true}
}
// Split the cleaned path into components
parts := Split(CleanPath("/"+p, string(PathSeparator)), string(PathSeparator))
current := root
for _, part := range parts {
if part == "" {
continue
}
next := PathJoin(current, part)
realNextResult := PathEvalSymlinks(next)
if !realNextResult.OK {
err, _ := realNextResult.Value.(error)
if IsNotExist(err) {
// Part doesn't exist, we can't follow symlinks anymore.
// Since the path is already Cleaned and current is safe,
// appending a component to current will not escape.
current = next
continue
}
return Result{err, false}
}
realNext := realNextResult.Value.(string)
// Verify the resolved part is still within the root
relResult := PathRel(root, realNext)
rel := ""
if relResult.OK {
rel = relResult.Value.(string)
}
if !relResult.OK || HasPrefix(rel, "..") {
// Security event: sandbox escape attempt
username := "unknown"
if r := UserCurrent(); r.OK {
username = r.Value.(*User).Username
}
Print(Stderr(), "[%s] SECURITY sandbox escape detected root=%s path=%s attempted=%s user=%s",
Now().Format(TimeRFC3339), root, p, realNext, username)
err, _ := relResult.Value.(error)
if err == nil {
err = E("fs.validatePath", Concat("sandbox escape: ", p, " resolves outside ", m.root), nil)
}
return Result{err, false}
}
current = realNext
}
return Result{current, true}
}
// Read returns file contents as string.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.Read("config/agent.json")
// if r.OK { core.Println(r.Value.(string)) }
func (m *Fs) Read(p string) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
r := ReadFile(vp.Value.(string))
if !r.OK {
return r
}
return Result{string(r.Value.([]byte)), true}
}
// Write saves content to file, creating parent directories as needed.
// Files are created with mode 0644. For sensitive files (keys, secrets),
// use WriteMode with 0600.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.Write("config/agent.json", `{"host":"homelab.lthn.sh"}`)
// if !r.OK { return r }
func (m *Fs) Write(p, content string) Result {
return m.WriteMode(p, content, 0644)
}
// WriteMode saves content to file with explicit permissions.
// Use 0600 for sensitive files (encryption output, private keys, auth hashes).
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.WriteMode("secrets/token", "lethean-token", 0o600)
// if !r.OK { return r }
func (m *Fs) WriteMode(p, content string, mode FileMode) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
full := vp.Value.(string)
if r := MkdirAll(PathDir(full), 0755); !r.OK {
return r
}
if r := WriteFile(full, []byte(content), mode); !r.OK {
return r
}
return Result{OK: true}
}
// TempDir creates a temporary directory and returns its path.
// The caller is responsible for cleanup via fs.DeleteAll().
//
// dir := fs.TempDir("agent-workspace")
// defer fs.DeleteAll(dir)
func (m *Fs) TempDir(prefix string) string {
r := MkdirTemp("", prefix)
if !r.OK {
return ""
}
return r.Value.(string)
}
// ReadDir reads a directory from fsys.
//
// r := core.ReadDir(core.DirFS("templates"), ".")
func ReadDir(fsys FS, name string) Result {
return Result{}.New(fs.ReadDir(fsys, name))
}
// ReadFSFile reads a file from fsys.
//
// r := core.ReadFSFile(core.DirFS("templates"), "README.md")
func ReadFSFile(fsys FS, name string) Result {
data, err := fs.ReadFile(fsys, name)
if err != nil {
return Result{err, false}
}
return Result{data, true}
}
// Sub returns an FS rooted at dir inside fsys.
//
// r := core.Sub(core.DirFS("templates"), "agent")
func Sub(fsys FS, dir string) Result {
sub, err := fs.Sub(fsys, dir)
if err != nil {
return Result{err, false}
}
return Result{sub, true}
}
// WalkDir walks fsys from root, calling fn for each file or directory.
//
// err := core.WalkDir(core.DirFS("templates"), ".", fn)
func WalkDir(fsys FS, root string, fn WalkDirFunc) error {
return fs.WalkDir(fsys, root, fn)
}
// WriteAtomic writes content by writing to a temp file then renaming.
// Rename is atomic on POSIX — concurrent readers never see a partial file.
// Use this for status files, config, or any file read from multiple goroutines.
//
// r := fs.WriteAtomic("/status.json", jsonData)
func (m *Fs) WriteAtomic(p, content string) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
full := vp.Value.(string)
if r := MkdirAll(PathDir(full), 0755); !r.OK {
return r
}
tmp := full + ".tmp." + shortRand()
if r := WriteFile(tmp, []byte(content), 0644); !r.OK {
return r
}
if r := Rename(tmp, full); !r.OK {
Remove(tmp)
return r
}
return Result{OK: true}
}
// EnsureDir creates directory if it doesn't exist.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.EnsureDir("logs/agent")
// if !r.OK { return r }
func (m *Fs) EnsureDir(p string) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
if r := MkdirAll(vp.Value.(string), 0755); !r.OK {
return r
}
return Result{OK: true}
}
// IsDir returns true if path is a directory.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// if fsys.IsDir("logs") { core.Println("logs ready") }
func (m *Fs) IsDir(p string) bool {
if p == "" {
return false
}
vp := m.validatePath(p)
if !vp.OK {
return false
}
r := Stat(vp.Value.(string))
if !r.OK {
return false
}
info := r.Value.(interface{ IsDir() bool })
return info.IsDir()
}
// IsFile returns true if path is a regular file.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// if fsys.IsFile("config/agent.json") { core.Println("config ready") }
func (m *Fs) IsFile(p string) bool {
if p == "" {
return false
}
vp := m.validatePath(p)
if !vp.OK {
return false
}
r := Stat(vp.Value.(string))
if !r.OK {
return false
}
info := r.Value.(interface{ Mode() FileMode })
return info.Mode().IsRegular()
}
// Exists returns true if path exists.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// if fsys.Exists("config/agent.json") { core.Println("config present") }
func (m *Fs) Exists(p string) bool {
vp := m.validatePath(p)
if !vp.OK {
return false
}
return Stat(vp.Value.(string)).OK
}
// List returns directory entries.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.List("config")
// if !r.OK { return r }
func (m *Fs) List(p string) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
return ReadDir(DirFS(vp.Value.(string)), ".")
}
// Stat returns file info.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.Stat("config/agent.json")
// if !r.OK { return r }
func (m *Fs) Stat(p string) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
return Stat(vp.Value.(string))
}
// Open opens the named file for reading.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.ReadStream("config/agent.json")
// if !r.OK { return r }
// defer r.Value.(core.ReadCloser).Close()
func (m *Fs) Open(p string) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
return Open(vp.Value.(string))
}
// Create creates or truncates the named file.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.WriteStream("logs/agent.log")
// if !r.OK { return r }
// defer r.Value.(core.WriteCloser).Close()
func (m *Fs) Create(p string) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
full := vp.Value.(string)
if r := MkdirAll(PathDir(full), 0755); !r.OK {
return r
}
return Create(full)
}
// Append opens the named file for appending, creating it if it doesn't exist.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.Append("logs/agent.log")
// if !r.OK { return r }
// defer r.Value.(core.WriteCloser).Close()
func (m *Fs) Append(p string) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
full := vp.Value.(string)
if r := MkdirAll(PathDir(full), 0755); !r.OK {
return r
}
return OpenFile(full, O_APPEND|O_CREATE|O_WRONLY, 0644)
}
// ReadStream returns a reader for the file content.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.ReadStream("config/agent.json")
// if !r.OK { return r }
// defer r.Value.(core.ReadCloser).Close()
func (m *Fs) ReadStream(path string) Result {
return m.Open(path)
}
// WriteStream returns a writer for the file content.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.WriteStream("logs/agent.log")
// if !r.OK { return r }
// defer r.Value.(core.WriteCloser).Close()
func (m *Fs) WriteStream(path string) Result {
return m.Create(path)
}
// WriteAll writes content to a writer and closes it if it implements Closer.
//
// r := fs.WriteStream(path)
// core.WriteAll(r.Value, "content")
func WriteAll(writer any, content string) Result {
wc, ok := writer.(Writer)
if !ok {
return Result{E("core.WriteAll", "not a writer", nil), false}
}
_, err := wc.Write([]byte(content))
if closer, ok := writer.(Closer); ok {
closer.Close()
}
if err != nil {
return Result{err, false}
}
return Result{OK: true}
}
// CloseStream closes any value that implements Closer.
//
// core.CloseStream(r.Value)
func CloseStream(v any) {
if closer, ok := v.(Closer); ok {
closer.Close()
}
}
// Delete removes a file or empty directory.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.Delete("logs/old-agent.log")
// if !r.OK { return r }
func (m *Fs) Delete(p string) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
full := vp.Value.(string)
if full == "/" || full == Getenv("HOME") {
return Result{E("fs.Delete", Concat("refusing to delete protected path: ", full), nil), false}
}
if r := Remove(full); !r.OK {
return r
}
return Result{OK: true}
}
// DeleteAll removes a file or directory recursively.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.DeleteAll("tmp/session-42")
// if !r.OK { return r }
func (m *Fs) DeleteAll(p string) Result {
vp := m.validatePath(p)
if !vp.OK {
return vp
}
full := vp.Value.(string)
if full == "/" || full == Getenv("HOME") {
return Result{E("fs.DeleteAll", Concat("refusing to delete protected path: ", full), nil), false}
}
if r := RemoveAll(full); !r.OK {
return r
}
return Result{OK: true}
}
// Rename moves a file or directory.
//
// fsys := (&core.Fs{}).New("/tmp/agent-workspace")
// r := fsys.Rename("config/agent.tmp", "config/agent.json")
// if !r.OK { return r }
func (m *Fs) Rename(oldPath, newPath string) Result {
oldVp := m.validatePath(oldPath)
if !oldVp.OK {
return oldVp
}
newVp := m.validatePath(newPath)
if !newVp.OK {
return newVp
}
return Rename(oldVp.Value.(string), newVp.Value.(string))
}
// FsEntry is a directory entry yielded by WalkSeq and WalkSeqSkip.
// Path is relative to the walk root.
//
// entry := core.FsEntry{Path: "config/agent.json", Name: "agent.json", IsDir: false, Mode: 0o644}
// core.Println(entry.Path)
type FsEntry struct {
Path string // relative to walk root, OS-native separator
Name string // basename
IsDir bool
Mode fs.FileMode
}
// WalkSeq walks the directory tree rooted at root within the Fs sandbox,
// yielding every entry depth-first. Iteration stops on caller break.
//
// Symlinks are not followed: validatePath rejects any symlink that resolves
// outside the sandbox before descent, and the underlying walker uses
// PathWalkDir which does not traverse into symlinked directories.
//
// for entry, err := range c.Fs().WalkSeq("./") {
// if err != nil { break }
// if !entry.IsDir { /* file */ }
// }
func (m *Fs) WalkSeq(root string) Seq2[FsEntry, error] {
return m.walkSeq(root, nil)
}
// WalkSeqSkip walks like WalkSeq but skips any directory whose basename
// appears in skipNames (e.g. "vendor", "node_modules", ".git"). Skipped
// directories are not descended into; their contents are never yielded.
// The walk root itself is never skipped, even if its basename matches.
//
// for entry, err := range c.Fs().WalkSeqSkip("./", "vendor", "node_modules", ".git") {
// if err != nil { break }
// if !entry.IsDir { /* file */ }
// }
func (m *Fs) WalkSeqSkip(root string, skipNames ...string) Seq2[FsEntry, error] {
skip := make(map[string]struct{}, len(skipNames))
for _, name := range skipNames {
if name != "" {
skip[name] = struct{}{}
}
}
return m.walkSeq(root, skip)
}
// walkSeq is the shared implementation behind WalkSeq and WalkSeqSkip.
func (m *Fs) walkSeq(root string, skip map[string]struct{}) Seq2[FsEntry, error] {
return func(yield func(FsEntry, error) bool) {
vp := m.validatePath(root)
if !vp.OK {
err, _ := vp.Value.(error)
if err == nil {
err = E("fs.WalkSeq", "invalid walk root", nil)
}
yield(FsEntry{}, err)
return
}
fullRoot, _ := vp.Value.(string)
if fullRoot == "" {
yield(FsEntry{}, E("fs.WalkSeq", "validatePath returned empty root", nil))
return
}
stop := false
_ = PathWalkDir(fullRoot, func(path string, d FsDirEntry, walkErr error) error {
if stop {
return PathSkipAll
}
if walkErr != nil {
if !yield(FsEntry{}, walkErr) {
stop = true
return PathSkipAll
}
return nil
}
if d.IsDir() && skip != nil && path != fullRoot {
if _, ok := skip[d.Name()]; ok {
return PathSkipDir
}
}
relResult := PathRel(fullRoot, path)
rel := ""
if !relResult.OK {
rel = path
} else {
rel = relResult.Value.(string)
}
info, _ := d.Info()
mode := fs.FileMode(0)
if info != nil {
mode = info.Mode()
}
entry := FsEntry{
Path: rel,
Name: d.Name(),
IsDir: d.IsDir(),
Mode: mode,
}
if !yield(entry, nil) {
stop = true
return PathSkipAll
}
return nil
})
}
}