This is an automated email from the ASF dual-hosted git repository.

squakez pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel-k.git


The following commit(s) were added to refs/heads/main by this push:
     new 840e6d10a chore: path sanitization
840e6d10a is described below

commit 840e6d10aae64dd4590e92c4230c053a867cf42e
Author: Pasquale Congiusti <[email protected]>
AuthorDate: Fri Dec 4 08:19:09 2026 +0100

    chore: path sanitization
---
 pkg/builder/git.go             |  7 ++-
 pkg/builder/git_test.go        | 19 +++++++++
 pkg/builder/quarkus.go         |  6 ++-
 pkg/builder/quarkus_test.go    | 17 ++++++++
 pkg/trait/gitops.go            | 11 ++++-
 pkg/trait/gitops_test.go       | 29 +++++++++++++
 pkg/util/gitops/gitops.go      |  5 ++-
 pkg/util/gitops/gitops_test.go | 14 ++++++
 pkg/util/io/io.go              | 22 ++++++++++
 pkg/util/io/io_test.go         | 96 ++++++++++++++++++++++++++++++++++++++++++
 10 files changed, 220 insertions(+), 6 deletions(-)

diff --git a/pkg/builder/git.go b/pkg/builder/git.go
index d4156a822..acf3c23c5 100644
--- a/pkg/builder/git.go
+++ b/pkg/builder/git.go
@@ -83,8 +83,11 @@ func cloneProject(ctx *builderContext) error {
                return err
        }
        if ctx.Build.Git.Path != "" {
-               selectedPath := filepath.Join(gitClonePath, ctx.Build.Git.Path)
-               _, err := os.Stat(selectedPath)
+               selectedPath, err := io.SanitizePath(gitClonePath, 
ctx.Build.Git.Path)
+               if err != nil {
+                       return err
+               }
+               _, err = os.Stat(selectedPath)
                if err != nil {
                        return err
                }
diff --git a/pkg/builder/git_test.go b/pkg/builder/git_test.go
index 636cab8b0..bbc91fd7f 100644
--- a/pkg/builder/git_test.go
+++ b/pkg/builder/git_test.go
@@ -201,6 +201,25 @@ func TestGitPublicRepoWithPath(t *testing.T) {
        assert.Contains(t, f.Name(), "test.yaml")
 }
 
+func TestGitPublicRepoWithPathTraversal(t *testing.T) {
+       tmpGitDir := t.TempDir()
+
+       ctx := &builderContext{
+               C:    context.TODO(),
+               Path: tmpGitDir,
+               Build: v1.BuilderTask{
+                       Git: &v1.GitConfigSpec{
+                               URL:  "https://github.com/squakez/sample.git";,
+                               Path: "../../etc",
+                       },
+               },
+       }
+
+       err := cloneProject(ctx)
+       require.Error(t, err)
+       assert.Contains(t, err.Error(), "escapes base directory")
+}
+
 // gitBasicAuthRecorder is a fake Git HTTP server which records the basic auth 
credentials it receives
 // and rejects every request.
 type gitBasicAuthRecorder struct {
diff --git a/pkg/builder/quarkus.go b/pkg/builder/quarkus.go
index 69a747f7d..57150cf59 100644
--- a/pkg/builder/quarkus.go
+++ b/pkg/builder/quarkus.go
@@ -83,8 +83,12 @@ func prepareProjectWithSources(ctx *builderContext) error {
                        sourceList += ","
                }
                sourceList += "classpath:routes/" + source.Name
+               sourcePath, err := io.SanitizePath(sourcesPath, source.Name)
+               if err != nil {
+                       return fmt.Errorf("failure while securing source path 
%s: %w", source.Name, err)
+               }
                if err := os.WriteFile(
-                       filepath.Join(sourcesPath, source.Name),
+                       sourcePath,
                        []byte(source.Content),
                        projectModePerm,
                ); err != nil {
diff --git a/pkg/builder/quarkus_test.go b/pkg/builder/quarkus_test.go
index 51de9f22a..3bdf53341 100644
--- a/pkg/builder/quarkus_test.go
+++ b/pkg/builder/quarkus_test.go
@@ -224,6 +224,23 @@ func TestGenerateQuarkusProjectWithNativeSources(t 
*testing.T) {
        require.NoError(t, err)
 }
 
+func TestPrepareProjectWithSourcesPathTraversal(t *testing.T) {
+       tmpDir := t.TempDir()
+       builderContext := builderContext{
+               C:    context.TODO(),
+               Path: tmpDir,
+               Build: v1.BuilderTask{
+                       Sources: []v1.SourceSpec{
+                               v1.NewSourceSpec("../../evil.java", "bogus", 
v1.LanguageJavaSource),
+                       },
+               },
+       }
+
+       err := prepareProjectWithSources(&builderContext)
+       require.Error(t, err)
+       assert.Contains(t, err.Error(), "escapes base directory")
+}
+
 func TestBuildQuarkusRunner(t *testing.T) {
        tmpDir := t.TempDir()
        defaultCatalog, err := camel.DefaultCatalog()
diff --git a/pkg/trait/gitops.go b/pkg/trait/gitops.go
index d5eab2b93..2a4cc461a 100644
--- a/pkg/trait/gitops.go
+++ b/pkg/trait/gitops.go
@@ -147,7 +147,10 @@ func (t *gitOpsTrait) pushGitOpsItInGitRepo(ctx 
context.Context, it *v1.Integrat
        }
 
        // Generate Kustomize content (it may override upstream content)
-       ciCdDir := filepath.Join(dir, t.getIntegrationsDirectory())
+       ciCdDir, err := io.SanitizePath(dir, t.getIntegrationsDirectory())
+       if err != nil {
+               return err
+       }
        err = os.MkdirAll(ciCdDir, io.FilePerm755)
        if err != nil {
                return err
@@ -177,7 +180,11 @@ func (t *gitOpsTrait) pushGitOpsItInGitRepo(ctx 
context.Context, it *v1.Integrat
        }
 
        // Commit and push new content
-       _, err = w.Add(t.getIntegrationsDirectory())
+       relCiCdDir, err := filepath.Rel(dir, ciCdDir)
+       if err != nil {
+               return err
+       }
+       _, err = w.Add(relCiCdDir)
        if err != nil {
                return err
        }
diff --git a/pkg/trait/gitops_test.go b/pkg/trait/gitops_test.go
index 5f33a9649..412249fdf 100644
--- a/pkg/trait/gitops_test.go
+++ b/pkg/trait/gitops_test.go
@@ -110,6 +110,35 @@ func TestGitOpsPushRepoDefault(t *testing.T) {
        assert.True(t, gitopsDir.IsDir())
 }
 
+func TestGitOpsPushRepoPathTraversal(t *testing.T) {
+       trait, _ := newGitOpsTrait().(*gitOpsTrait)
+       trait.Overlays = []string{"dev"}
+       trait.IntegrationDirectory = "../../integrations"
+
+       srcGitDir := t.TempDir()
+       tmpGitDir := t.TempDir()
+       err := initFakeGitRepo(srcGitDir)
+       require.NoError(t, err)
+       it := v1.NewIntegration("default", "test")
+       conf := &v1.GitConfigSpec{
+               URL: srcGitDir,
+       }
+       it.Spec = v1.IntegrationSpec{
+               Git:     conf,
+               Sources: []v1.SourceSpec{v1.NewSourceSpec("Test.java", "bogus", 
v1.LanguageJavaSource)},
+       }
+       now := metav1.Now().Rfc3339Copy()
+       it.Status = v1.IntegrationStatus{
+               Image:               "my-img",
+               BuildTimestamp:      &now,
+               DeploymentTimestamp: &now,
+       }
+
+       err = trait.pushGitOpsItInGitRepo(context.TODO(), &it, tmpGitDir, 
"fake")
+       require.Error(t, err)
+       assert.Contains(t, err.Error(), "escapes base directory")
+}
+
 // initFakeGitInmemoryRepo has the goal to create a fake a git repository into 
a given directory.
 // We can use this to simulate pull and push activities.
 func initFakeGitRepo(dirPath string) error {
diff --git a/pkg/util/gitops/gitops.go b/pkg/util/gitops/gitops.go
index 1120f02b1..a5690fcab 100644
--- a/pkg/util/gitops/gitops.go
+++ b/pkg/util/gitops/gitops.go
@@ -226,7 +226,10 @@ func AppendKustomizeIntegration(dstIt *v1.Integration, 
destinationDir string, ov
                return err
        }
        for _, src := range baseIt.OriginalSourcesOnly() {
-               srcName := filepath.Join(newpath, src.Name)
+               srcName, err := io.SanitizePath(newpath, src.Name)
+               if err != nil {
+                       return err
+               }
                cnt := []byte(src.Content)
                if err := os.WriteFile(srcName, cnt, io.FilePerm755); err != 
nil {
                        return err
diff --git a/pkg/util/gitops/gitops_test.go b/pkg/util/gitops/gitops_test.go
index 032247b1a..43a8d773b 100644
--- a/pkg/util/gitops/gitops_test.go
+++ b/pkg/util/gitops/gitops_test.go
@@ -91,3 +91,17 @@ func TestCloneGitProjectWithoutToken(t *testing.T) {
        })
        assert.False(t, recorder.ok)
 }
+
+func TestAppendKustomizeIntegrationSourcePathTraversal(t *testing.T) {
+       tmpDir := t.TempDir()
+       it := v1.NewIntegration("default", "test")
+       it.Spec = v1.IntegrationSpec{
+               Sources: []v1.SourceSpec{
+                       v1.NewSourceSpec("../../evil.java", "bogus", 
v1.LanguageJavaSource),
+               },
+       }
+
+       err := AppendKustomizeIntegration(&it, tmpDir, true)
+       require.Error(t, err)
+       assert.Contains(t, err.Error(), "escapes base directory")
+}
diff --git a/pkg/util/io/io.go b/pkg/util/io/io.go
index 931c7c009..cf203ebb8 100644
--- a/pkg/util/io/io.go
+++ b/pkg/util/io/io.go
@@ -18,9 +18,11 @@ limitations under the License.
 package io
 
 import (
+       "fmt"
        "io"
        "os"
        "path/filepath"
+       "strings"
 )
 
 const (
@@ -31,6 +33,26 @@ const (
        FilePerm400 os.FileMode = 0o400 // For read only files
 )
 
+// SanitizePath joins baseDir and subPath ensuring that the resulting path is 
within baseDir.
+// It returns an error if subPath attempts to escape baseDir (e.g. through 
directory traversal).
+func SanitizePath(baseDir, subPath string) (string, error) {
+       cleanBase := filepath.Clean(baseDir)
+       cleanSub := filepath.Clean(subPath)
+       if filepath.IsAbs(cleanSub) {
+               cleanSub = strings.TrimPrefix(cleanSub, 
string(filepath.Separator))
+       }
+       target := filepath.Join(cleanBase, cleanSub)
+       rel, err := filepath.Rel(cleanBase, target)
+       if err != nil {
+               return "", fmt.Errorf("invalid path %q: %w", subPath, err)
+       }
+       if rel == ".." || strings.HasPrefix(rel, 
".."+string(filepath.Separator)) {
+               return "", fmt.Errorf("path %q escapes base directory", subPath)
+       }
+
+       return target, nil
+}
+
 // CopyDir programmatically "cp -r src dst".
 func CopyDir(src, dst string) error {
        return filepath.WalkDir(src, func(path string, d os.DirEntry, err 
error) error {
diff --git a/pkg/util/io/io_test.go b/pkg/util/io/io_test.go
new file mode 100644
index 000000000..22db73608
--- /dev/null
+++ b/pkg/util/io/io_test.go
@@ -0,0 +1,96 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements.  See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License.  You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package io
+
+import (
+       "path/filepath"
+       "testing"
+
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+func TestSanitizePath(t *testing.T) {
+       baseDir := filepath.Join("tmp", "project")
+
+       tests := []struct {
+               name        string
+               subPath     string
+               expected    string
+               expectError bool
+       }{
+               {
+                       name:        "simple relative path",
+                       subPath:     "foo.java",
+                       expected:    filepath.Join(baseDir, "foo.java"),
+                       expectError: false,
+               },
+               {
+                       name:        "nested relative path",
+                       subPath:     filepath.Join("sub", "dir", "Route.java"),
+                       expected:    filepath.Join(baseDir, "sub", "dir", 
"Route.java"),
+                       expectError: false,
+               },
+               {
+                       name:        "relative path with inner dots",
+                       subPath:     filepath.Join("sub", "..", "Route.java"),
+                       expected:    filepath.Join(baseDir, "Route.java"),
+                       expectError: false,
+               },
+               {
+                       name:        "absolute-like path treated as relative",
+                       subPath:     "/etc/passwd",
+                       expected:    filepath.Join(baseDir, "etc", "passwd"),
+                       expectError: false,
+               },
+               {
+                       name:        "path traversal escaping base dir",
+                       subPath:     "../escape.txt",
+                       expectError: true,
+               },
+               {
+                       name:        "deep path traversal escaping base dir",
+                       subPath:     filepath.Join("..", "..", "etc", "passwd"),
+                       expectError: true,
+               },
+               {
+                       name:        "current dir dot",
+                       subPath:     ".",
+                       expected:    baseDir,
+                       expectError: false,
+               },
+               {
+                       name:        "empty string",
+                       subPath:     "",
+                       expected:    baseDir,
+                       expectError: false,
+               },
+       }
+
+       for _, tc := range tests {
+               t.Run(tc.name, func(t *testing.T) {
+                       result, err := SanitizePath(baseDir, tc.subPath)
+                       if tc.expectError {
+                               require.Error(t, err)
+                       } else {
+                               require.NoError(t, err)
+                               assert.Equal(t, tc.expected, result)
+                       }
+               })
+       }
+}

Reply via email to