99package fsroot
1010
1111import (
12+ "crypto/rand"
1213 "encoding/json"
1314 "errors"
1415 "fmt"
1516 "io/fs"
1617 "os"
1718 "path/filepath"
19+ "strings"
1820 "time"
1921
2022 "gopkg.in/yaml.v3"
3537// depending on this package.
3638var errReadOnly = fmt .Errorf ("write operation not available in read-only mode: %w" , errors .ErrUnsupported )
3739
40+ // errTempPatternSeparator is returned when a temporary-name pattern contains a path separator, which would let a
41+ // caller redirect the created object through the name instead of the directory argument. It wraps
42+ // [fs.ErrInvalid] so callers can test for it without depending on this package.
43+ var errTempPatternSeparator = fmt .Errorf ("temporary name pattern contains a path separator: %w" , fs .ErrInvalid )
44+
45+ // maxTempAttempts bounds the collision retries in [createTempIn] and [mkdirTempIn], matching [os.CreateTemp].
46+ const maxTempAttempts = 10000
47+
3848// Root provides scoped filesystem operations. All path arguments are [Path] values created through [Root.NewPath].
3949//
4050// Three concrete implementations provide different access modes:
@@ -49,18 +59,25 @@ var errReadOnly = fmt.Errorf("write operation not available in read-only mode: %
4959// The method set mirrors [*os.Root] in full, so code that knows the standard library's root knows
5060// this one. Every filesystem mutation in the repository is expected to flow through this interface;
5161// a direct os.* call must carry a `// Confinement:` comment stating why the root cannot serve it.
62+ //
63+ // [Root.CreateTemp] and [Root.MkdirTemp] go beyond the mirror: [*os.Root] has no equivalent, and
64+ // [os.CreateTemp] cannot be confined to a root. Choosing between a scratch root and this one is the
65+ // whole of the decision — use the session's scratch unless the bytes must end up in this tree
66+ // atomically, since a rename out of scratch can cross a device boundary and degrade to a copy.
5267type Root interface {
5368 Chmod (p Path , mode os.FileMode ) error
5469 Chown (p Path , uid , gid int ) error
5570 Chtimes (p Path , atime , mtime time.Time ) error
5671 Close () error
5772 Create (p Path ) (* os.File , error )
73+ CreateTemp (dir Path , pattern string ) (* os.File , Path , error )
5874 FS () fs.FS
5975 Lchown (p Path , uid , gid int ) error
6076 Link (oldPath , newPath Path ) error
6177 Lstat (p Path ) (fs.FileInfo , error )
6278 Mkdir (p Path , perm os.FileMode ) error
6379 MkdirAll (p Path , perm os.FileMode ) error
80+ MkdirTemp (dir Path , pattern string ) (Path , error )
6481 Name () string
6582 NewPath (path string ) Path
6683 Open (p Path ) (* os.File , error )
@@ -406,6 +423,33 @@ func (r *confinedRoot) Mkdir(p Path, perm os.FileMode) error {
406423 return applyMode (p .abs , perm , true )
407424}
408425
426+ // CreateTemp creates a uniquely named file under `dir`, confined to the root.
427+ //
428+ // Parameters:
429+ // - `dir`: the directory within the root to create the file under; use `NewPath(".")` for the root itself.
430+ // - `pattern`: the name pattern; the random string replaces the last `*`, or is appended when there is none.
431+ //
432+ // Returns:
433+ // - `*os.File`: the open file, owned by the caller.
434+ // - `Path`: the created file's path.
435+ // - `error`: any error from [createTempIn].
436+ func (r * confinedRoot ) CreateTemp (dir Path , pattern string ) (* os.File , Path , error ) {
437+ return createTempIn (r , dir , pattern )
438+ }
439+
440+ // MkdirTemp creates a uniquely named directory under `dir`, confined to the root.
441+ //
442+ // Parameters:
443+ // - `dir`: the directory within the root to create the directory under; use `NewPath(".")` for the root itself.
444+ // - `pattern`: the name pattern; the random string replaces the last `*`, or is appended when there is none.
445+ //
446+ // Returns:
447+ // - `Path`: the created directory's path.
448+ // - `error`: any error from [mkdirTempIn].
449+ func (r * confinedRoot ) MkdirTemp (dir Path , pattern string ) (Path , error ) {
450+ return mkdirTempIn (r , dir , pattern )
451+ }
452+
409453// MkdirAll creates the directory at the path along with any necessary parents, confined to the root.
410454//
411455// Parameters:
@@ -634,6 +678,16 @@ func (r *unconfinedRootReader) Chtimes(Path, time.Time, time.Time) error { retur
634678// - `error`: always [errReadOnly].
635679func (r * unconfinedRootReader ) Create (Path ) (* os.File , error ) { return nil , errReadOnly }
636680
681+ // CreateTemp is unavailable in read-only mode.
682+ //
683+ // Returns:
684+ // - `*os.File`: always nil.
685+ // - `Path`: always the zero Path.
686+ // - `error`: always [errReadOnly].
687+ func (r * unconfinedRootReader ) CreateTemp (Path , string ) (* os.File , Path , error ) {
688+ return nil , Path {}, errReadOnly
689+ }
690+
637691// Lchown is unavailable in read-only mode.
638692//
639693// Returns:
@@ -668,6 +722,13 @@ func (r *unconfinedRootReader) Mkdir(Path, os.FileMode) error { return errReadOn
668722// - `error`: always [errReadOnly].
669723func (r * unconfinedRootReader ) MkdirAll (Path , os.FileMode ) error { return errReadOnly }
670724
725+ // MkdirTemp is unavailable in read-only mode.
726+ //
727+ // Returns:
728+ // - `Path`: always the zero Path.
729+ // - `error`: always [errReadOnly].
730+ func (r * unconfinedRootReader ) MkdirTemp (Path , string ) (Path , error ) { return Path {}, errReadOnly }
731+
671732// Open opens the path for reading.
672733//
673734// Parameters:
@@ -899,6 +960,33 @@ func (r *unconfinedRootReaderWriter) Mkdir(p Path, perm os.FileMode) error {
899960 return applyMode (p .abs , perm , true )
900961}
901962
963+ // CreateTemp creates a uniquely named file under `dir`.
964+ //
965+ // Parameters:
966+ // - `dir`: the directory to create the file under; use `NewPath(".")` for the root directory itself.
967+ // - `pattern`: the name pattern; the random string replaces the last `*`, or is appended when there is none.
968+ //
969+ // Returns:
970+ // - `*os.File`: the open file, owned by the caller.
971+ // - `Path`: the created file's path.
972+ // - `error`: any error from [createTempIn].
973+ func (r * unconfinedRootReaderWriter ) CreateTemp (dir Path , pattern string ) (* os.File , Path , error ) {
974+ return createTempIn (r , dir , pattern )
975+ }
976+
977+ // MkdirTemp creates a uniquely named directory under `dir`.
978+ //
979+ // Parameters:
980+ // - `dir`: the directory to create the directory under; use `NewPath(".")` for the root directory itself.
981+ // - `pattern`: the name pattern; the random string replaces the last `*`, or is appended when there is none.
982+ //
983+ // Returns:
984+ // - `Path`: the created directory's path.
985+ // - `error`: any error from [mkdirTempIn].
986+ func (r * unconfinedRootReaderWriter ) MkdirTemp (dir Path , pattern string ) (Path , error ) {
987+ return mkdirTempIn (r , dir , pattern )
988+ }
989+
902990// MkdirAll creates the directory at the path along with any necessary parents.
903991//
904992// Parameters:
@@ -1243,4 +1331,114 @@ func makePath(rootName, path string) Path {
12431331 }
12441332}
12451333
1334+ // createTempIn creates a uniquely named file under `dir`, mirroring [os.CreateTemp] inside a root.
1335+ //
1336+ // The file is created through `r`'s own [Root.OpenFile] with `O_CREATE|O_EXCL`, so confinement and the Windows
1337+ // enforcement pass both apply exactly as they do to any other create. Mode 0600 matches [os.CreateTemp] and is
1338+ // private, which means a temporary file receives a protected DACL on Windows without the caller asking.
1339+ //
1340+ // Parameters:
1341+ // - `r`: the root the file is created in.
1342+ // - `dir`: the directory within `r` to create the file under; use `r.NewPath(".")` for the root itself.
1343+ // - `pattern`: the name pattern; the random string replaces the last `*`, or is appended when there is none.
1344+ //
1345+ // Returns:
1346+ // - `*os.File`: the open file, positioned at offset zero and owned by the caller.
1347+ // - `Path`: the created file's path, for the rename or removal the caller owes it.
1348+ // - `error`: [errTempPatternSeparator] when the pattern contains a path separator, [fs.ErrExist] when a unique
1349+ // name could not be found, or any error from [Root.OpenFile].
1350+ func createTempIn (r Root , dir Path , pattern string ) (* os.File , Path , error ) {
1351+
1352+ prefix , suffix , err := tempNameParts (pattern )
1353+ if err != nil {
1354+ return nil , Path {}, err
1355+ }
1356+
1357+ for range maxTempAttempts {
1358+
1359+ candidate := r .NewPath (filepath .Join (dir .Rel (), prefix + nextTempName ()+ suffix ))
1360+
1361+ file , openErr := r .OpenFile (candidate , os .O_RDWR | os .O_CREATE | os .O_EXCL , 0o600 )
1362+ if openErr == nil {
1363+ return file , candidate , nil
1364+ }
1365+ if ! errors .Is (openErr , fs .ErrExist ) {
1366+ return nil , Path {}, openErr
1367+ }
1368+ }
1369+
1370+ return nil , Path {}, fmt .Errorf ("fsroot.CreateTemp %s: %w" , filepath .Join (dir .Rel (), prefix + "*" + suffix ), fs .ErrExist )
1371+ }
1372+
1373+ // mkdirTempIn creates a uniquely named directory under `dir`, mirroring [os.MkdirTemp] inside a root.
1374+ //
1375+ // The directory is created through `r`'s own [Root.Mkdir], so confinement and the Windows enforcement pass apply.
1376+ // Mode 0700 matches [os.MkdirTemp] and is private, so the directory is DACL-protected on Windows.
1377+ //
1378+ // Parameters:
1379+ // - `r`: the root the directory is created in.
1380+ // - `dir`: the directory within `r` to create the new directory under; use `r.NewPath(".")` for the root itself.
1381+ // - `pattern`: the name pattern; the random string replaces the last `*`, or is appended when there is none.
1382+ //
1383+ // Returns:
1384+ // - `Path`: the created directory's path, for the removal the caller owes it.
1385+ // - `error`: [errTempPatternSeparator] when the pattern contains a path separator, [fs.ErrExist] when a unique
1386+ // name could not be found, or any error from [Root.Mkdir].
1387+ func mkdirTempIn (r Root , dir Path , pattern string ) (Path , error ) {
1388+
1389+ prefix , suffix , err := tempNameParts (pattern )
1390+ if err != nil {
1391+ return Path {}, err
1392+ }
1393+
1394+ for range maxTempAttempts {
1395+
1396+ candidate := r .NewPath (filepath .Join (dir .Rel (), prefix + nextTempName ()+ suffix ))
1397+
1398+ mkdirErr := r .Mkdir (candidate , 0o700 )
1399+ if mkdirErr == nil {
1400+ return candidate , nil
1401+ }
1402+ if ! errors .Is (mkdirErr , fs .ErrExist ) {
1403+ return Path {}, mkdirErr
1404+ }
1405+ }
1406+
1407+ return Path {}, fmt .Errorf ("fsroot.MkdirTemp %s: %w" , filepath .Join (dir .Rel (), prefix + "*" + suffix ), fs .ErrExist )
1408+ }
1409+
1410+ // nextTempName returns a random component for a temporary name.
1411+ //
1412+ // Uniqueness is not this function's job: both callers create with O_EXCL and retry on collision, exactly as
1413+ // [os.CreateTemp] does, so a repeat costs an attempt rather than a wrong result. The source is [rand.Text] rather
1414+ // than a pseudo-random generator because a predictable temporary name in a directory an attacker can also write
1415+ // to invites a symlink race, and the cost of the strong source here is nothing.
1416+ //
1417+ // Returns:
1418+ // - `string`: the random component.
1419+ func nextTempName () string { return rand .Text () }
1420+
1421+ // tempNameParts splits a temporary-name pattern around its last `*`.
1422+ //
1423+ // Parameters:
1424+ // - `pattern`: the name pattern.
1425+ //
1426+ // Returns:
1427+ // - `string`: the part before the `*`, or the whole pattern when it has none.
1428+ // - `string`: the part after the `*`, or empty.
1429+ // - `error`: [errTempPatternSeparator] when the pattern contains a path separator, which would let a caller
1430+ // escape `dir` through the name rather than the path.
1431+ func tempNameParts (pattern string ) (prefix , suffix string , err error ) {
1432+
1433+ if strings .ContainsAny (pattern , `/\` ) {
1434+ return "" , "" , fmt .Errorf ("fsroot: pattern %q: %w" , pattern , errTempPatternSeparator )
1435+ }
1436+
1437+ if position := strings .LastIndex (pattern , "*" ); position >= 0 {
1438+ return pattern [:position ], pattern [position + 1 :], nil
1439+ }
1440+
1441+ return pattern , "" , nil
1442+ }
1443+
12461444// endregion
0 commit comments