75 lines
2.3 KiB
Go
75 lines
2.3 KiB
Go
package cli
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"gitea.maximumdirect.net/eric/notarius/internal/core/fileio"
|
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
|
)
|
|
|
|
func writeOutputFiles(runOutputDir string, files []contracts.OutputFile) error {
|
|
for _, file := range files {
|
|
if _, err := outputFilePath(runOutputDir, file.Name); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
outputParent := filepath.Dir(runOutputDir)
|
|
if err := os.MkdirAll(outputParent, 0o755); err != nil {
|
|
return fmt.Errorf("create output parent %q: %w", outputParent, err)
|
|
}
|
|
if err := os.Mkdir(runOutputDir, 0o755); err != nil {
|
|
if os.IsExist(err) {
|
|
return fmt.Errorf("output run directory %q already exists", runOutputDir)
|
|
}
|
|
return fmt.Errorf("create output run directory %q: %w", runOutputDir, err)
|
|
}
|
|
for _, file := range files {
|
|
if err := fileio.WriteBytes(runOutputDir, file.Name, file.Bytes, 0o755, 0o644); err != nil {
|
|
return fmt.Errorf("write output file %q: %w", file.Name, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func outputFilePath(runOutputDir, logicalName string) (string, error) {
|
|
name := strings.TrimSpace(logicalName)
|
|
if name == "" {
|
|
return "", fmt.Errorf("output file name must not be empty")
|
|
}
|
|
if strings.Contains(name, `\`) {
|
|
return "", fmt.Errorf("output file name %q must use slash-separated relative paths", name)
|
|
}
|
|
if path.IsAbs(name) || filepath.IsAbs(name) {
|
|
return "", fmt.Errorf("output file name %q must be relative", name)
|
|
}
|
|
if strings.Contains(name, "..") {
|
|
return "", fmt.Errorf("output file name %q must not contain ..", name)
|
|
}
|
|
cleaned := path.Clean(name)
|
|
if cleaned == "." || cleaned != name {
|
|
return "", fmt.Errorf("output file name %q must be clean", name)
|
|
}
|
|
|
|
root, err := filepath.Abs(runOutputDir)
|
|
if err != nil {
|
|
return "", fmt.Errorf("resolve output directory %q: %w", runOutputDir, err)
|
|
}
|
|
target, err := filepath.Abs(filepath.Join(root, filepath.FromSlash(cleaned)))
|
|
if err != nil {
|
|
return "", fmt.Errorf("resolve output file %q: %w", name, err)
|
|
}
|
|
rel, err := filepath.Rel(root, target)
|
|
if err != nil {
|
|
return "", fmt.Errorf("resolve output file %q: %w", name, err)
|
|
}
|
|
if rel == "." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || rel == ".." {
|
|
return "", fmt.Errorf("output file name %q resolves outside output directory", name)
|
|
}
|
|
return target, nil
|
|
}
|