Let WriteFiles write includes that leave the folder when asked

AllowParentPaths is off by default, so WriteFiles still refuses a path
with .. in it. Absolute paths are refused either way.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 23:12:34 +00:00
co-authored by Claude Sonnet 5.5
parent 8134660721
commit 37d2866fe9
3 changed files with 47 additions and 4 deletions
+2 -2
View File
@@ -50,7 +50,7 @@ The model is read with each setting that a controller moves taken at the control
## Writing and building ## Writing and building
- `Document.Write` writes one file, and `WriteFiles` writes the main file and each file it includes, through a `FileWriter`. They take `WriteOptions`: `InlineIncludes` puts included files into the main file, `ExpandVariables` replaces variables with their values, and `LineEnding` sets the line break. The zero value writes each file as it was read. - `Document.Write` writes one file, and `WriteFiles` writes the main file and each file it includes, through a `FileWriter`. They take `WriteOptions`: `InlineIncludes` puts included files into the main file, `ExpandVariables` replaces variables with their values, and `LineEnding` sets the line break. The zero value writes each file as it was read.
- `Write` and `WriteTo` return an error for a document with includes unless `InlineIncludes` is set, as the files they hold would be lost. `WriteFiles` also returns an error for an include whose path is absolute or leaves the folder, and for a file included more than once that would be written differently each time. - `Write` and `WriteTo` return an error for a document with includes unless `InlineIncludes` is set, as the files they hold would be lost. `WriteFiles` also returns an error for an include whose path is absolute or leaves the folder (`AllowParentPaths` opts in to `..` paths, not absolute ones), and for a file included more than once that would be written differently each time.
- `Build` makes a new document from an `Instrument`, with `BuildOptions`: `SplitFiles` puts regions in included files, `Variables` hoists repeated values into `#define`s and the samples' folder into `default_path`, and `Indent` sets the indent. Reading the result gives the instrument back, except for the opcodes and headers the typed model doesn't hold. It returns an error for a value that can't be written, such as a sample path with a line break in it. - `Build` makes a new document from an `Instrument`, with `BuildOptions`: `SplitFiles` puts regions in included files, `Variables` hoists repeated values into `#define`s and the samples' folder into `default_path`, and `Indent` sets the indent. Reading the result gives the instrument back, except for the opcodes and headers the typed model doesn't hold. It returns an error for a value that can't be written, such as a sample path with a line break in it.
## Includes ## Includes
@@ -91,7 +91,7 @@ Errors wrap one of these, for `errors.Is`:
An instrument's text decides what the library does, so a file from elsewhere can't be trusted to be small or to stay in its folder. An instrument's text decides what the library does, so a file from elsewhere can't be trusted to be small or to stay in its folder.
- **Limits.** `Parse` stops at the limits in `Limits`: includes nest at most 16 deep, and the files and what their variables expand to may hold 16 MB. `WithLimits` changes both. It reads no more than the limit from a reader. - **Limits.** `Parse` stops at the limits in `Limits`: includes nest at most 16 deep, and the files and what their variables expand to may hold 16 MB. `WithLimits` changes both. It reads no more than the limit from a reader.
- **Paths.** The paths in `#include` and `sample` come from the text and can be absolute or hold `..`. A `Resolver` that reads from a disk, and a `FileWriter` that writes to one, need to keep to the instrument's folder. `ParseFile` does, through `fs.FS`, and `WriteFiles` refuses a path that leaves the folder. `Region.Sample` is as the text gives it, and the host resolves it. - **Paths.** The paths in `#include` and `sample` come from the text and can be absolute or hold `..`. A `Resolver` that reads from a disk, and a `FileWriter` that writes to one, need to keep to the instrument's folder. `ParseFile` does, through `fs.FS`, and `WriteFiles` refuses a path that leaves the folder unless `AllowParentPaths` is set. `Region.Sample` is as the text gives it, and the host resolves it.
## Concurrency ## Concurrency
+22
View File
@@ -143,6 +143,28 @@ func TestWriteFilesStaysInFolder(t *testing.T) {
} }
} }
// TestWriteFilesAllowParentPaths checks that AllowParentPaths lets WriteFiles
// write an include that leaves the folder with ".." (also spelled with a
// backslash, which the resolver reads as a slash), and still refuses
// absolute paths.
func TestWriteFilesAllowParentPaths(t *testing.T) {
anyFile := func(string) ([]byte, error) { return []byte("<region> sample=a.wav\n"), nil }
for include, ok := range map[string]bool{"../Data/a.sfz": true, "../../a.sfz": true, "/evil.sfz": false, "..\\evil.sfz": true} {
doc, err := Parse(strings.NewReader(fmt.Sprintf("#include %q\n", include)), WithResolver(anyFile))
if err != nil {
t.Fatal(err)
}
var written []string
err = doc.WriteFiles("out/main.sfz", func(p string, _ []byte) error { written = append(written, p); return nil }, WriteOptions{AllowParentPaths: true})
if ok && (err != nil || len(written) != 2) {
t.Errorf("%s: err %v, wrote %q", include, err, written)
}
if !ok && (!errors.Is(err, ErrInvalid) || len(written) != 0) {
t.Errorf("%s: err %v, wrote %q", include, err, written)
}
}
}
// TestValidateOutsideFolder checks that Validate reports includes and samples // TestValidateOutsideFolder checks that Validate reports includes and samples
// that leave the folder. // that leave the folder.
func TestValidateOutsideFolder(t *testing.T) { func TestValidateOutsideFolder(t *testing.T) {
+23 -2
View File
@@ -34,6 +34,12 @@ type WriteOptions struct {
// as a file of its own, as it would need to be written differently each // as a file of its own, as it would need to be written differently each
// time, and [Document.WriteFiles] returns an error for it. // time, and [Document.WriteFiles] returns an error for it.
ExpandVariables bool ExpandVariables bool
// AllowParentPaths lets [Document.WriteFiles] write an included file whose
// path leaves the folder of the main file with "..", as the DrumGizmo kits'
// "../Data" layout does. Absolute paths are refused either way. The writer
// is then trusted with files outside the folder, so set it only for
// documents whose includes are known to be safe.
AllowParentPaths bool
// LineEnding is the line break of the text written. The zero value is // LineEnding is the line break of the text written. The zero value is
// [KeepLineEndings]. // [KeepLineEndings].
LineEnding LineEnding LineEnding LineEnding
@@ -71,7 +77,8 @@ func (d *Document) hasIncludes() bool {
// WriteFiles writes the main file with the path root, and each file it includes // WriteFiles writes the main file with the path root, and each file it includes
// at its own path in the folder of root, using fw. It writes nothing, and // at its own path in the folder of root, using fw. It writes nothing, and
// returns an error wrapping [ErrInvalid], for an include whose path is absolute // returns an error wrapping [ErrInvalid], for an include whose path is absolute
// or leaves the folder, and for a file that is included more than once and // or leaves the folder (unless AllowParentPaths is set, which permits leaving
// it with ".."), and for a file that is included more than once and
// would be written differently each time. // would be written differently each time.
func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) error { func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) error {
r := &renderer{opts: opts, defines: defines{}, outputs: map[string]string{}, collect: true} r := &renderer{opts: opts, defines: defines{}, outputs: map[string]string{}, collect: true}
@@ -83,7 +90,7 @@ func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) err
for p := range r.outputs { for p := range r.outputs {
// An include path comes from the text, so it can't be trusted to stay in // An include path comes from the text, so it can't be trusted to stay in
// the folder. // the folder.
if !fs.ValidPath(p) { if !fs.ValidPath(p) && !(opts.AllowParentPaths && isParentPath(p)) {
return fmt.Errorf("%w: the include %q is outside the folder of the main file", ErrInvalid, p) return fmt.Errorf("%w: the include %q is outside the folder of the main file", ErrInvalid, p)
} }
paths = append(paths, p) paths = append(paths, p)
@@ -101,6 +108,20 @@ func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) err
return nil return nil
} }
// isParentPath reports whether p is a relative, clean path that leaves its
// folder with "..", and otherwise has no empty, "." or ".." elements after the
// leading ones.
func isParentPath(p string) bool {
if p == "" || strings.Contains(p, "\\") || path.Clean(p) != p || path.IsAbs(p) {
return false
}
rest := p
for strings.HasPrefix(rest, "../") {
rest = rest[3:]
}
return rest == ".." || fs.ValidPath(rest)
}
// renderer writes the files of a document as the options say. // renderer writes the files of a document as the options say.
type renderer struct { type renderer struct {
opts WriteOptions opts WriteOptions