Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pkg/engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,10 @@ func (cad *cadEngine) UpdatePackageResourcesWithoutRender(ctx context.Context, r
return nil, fmt.Errorf("cannot update a package revision with lifecycle value %q; package must be Draft", lifecycle)
}

if err := util.ValidateResourcePaths(newRes.Spec.Resources); err != nil {
return nil, err
}

repo, err := cad.cache.OpenRepository(ctx, repositoryObj)
if err != nil {
return nil, err
Expand Down
37 changes: 27 additions & 10 deletions pkg/engine/engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -894,13 +894,15 @@ func TestUpdatePackageResourcesRenderFailure(t *testing.T) {

func TestUpdatePackageResourcesWithoutRender(t *testing.T) {
tests := []struct {
name string
lifecycle porchapi.PackageRevisionLifecycle
oldRV string
newRV string
closeErr error
expectError bool
errorContains string
name string
lifecycle porchapi.PackageRevisionLifecycle
oldRV string
newRV string
resources map[string]string
closeErr error
skipWriteClose bool
expectError bool
errorContains string
}{
{
name: "success - draft lifecycle",
Expand Down Expand Up @@ -941,6 +943,16 @@ func TestUpdatePackageResourcesWithoutRender(t *testing.T) {
expectError: true,
errorContains: "git push failed",
},
{
name: "failure - path traversal rejected",
lifecycle: porchapi.PackageRevisionLifecycleDraft,
oldRV: "1",
newRV: "1",
resources: map[string]string{"../../etc/config": "content"},
skipWriteClose: true,
expectError: true,
errorContains: "invalid resource path",
},
}

for _, tt := range tests {
Expand All @@ -963,21 +975,26 @@ func TestUpdatePackageResourcesWithoutRender(t *testing.T) {
ResourceVersion: tt.oldRV,
},
}
resources := tt.resources
if resources == nil {
resources = map[string]string{"Kptfile": "test"}
}
newRes := &porchapi.PackageRevisionResources{
ObjectMeta: metav1.ObjectMeta{
Name: "test-pkg",
ResourceVersion: tt.newRV,
},
Spec: porchapi.PackageRevisionResourcesSpec{
Resources: map[string]string{"Kptfile": "test"},
Resources: resources,
},
}

mockPkgRev.On("Lifecycle", mock.Anything).Return(tt.lifecycle).Maybe()
mockPkgRev.On("Key").Return(repository.PackageRevisionKey{}).Maybe()

// Only expect repo open + draft flow when we pass validation
needsDraft := tt.newRV != "" && tt.oldRV == tt.newRV && tt.lifecycle == porchapi.PackageRevisionLifecycleDraft
// Only expect repo open + draft flow when we pass all pre-draft validation
needsDraft := !tt.skipWriteClose && tt.newRV != "" && tt.oldRV == tt.newRV &&
tt.lifecycle == porchapi.PackageRevisionLifecycleDraft
if needsDraft {
mockCache.On("OpenRepository", mock.Anything, repositoryObj).Return(mockRepo, nil)
mockRepo.On("UpdatePackageRevision", mock.Anything, mockPkgRev).Return(mockDraft, nil)
Expand Down
37 changes: 0 additions & 37 deletions pkg/engine/safejoin.go

This file was deleted.

16 changes: 10 additions & 6 deletions pkg/repository/update.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2022-2025 The kpt Authors
// Copyright 2022-2026 The kpt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -23,6 +23,7 @@ import (

"github.com/kptdev/kpt/pkg/lib/update"
updatetypes "github.com/kptdev/kpt/pkg/lib/update/updatetypes"
"github.com/kptdev/porch/pkg/util"
)

const LocalUpdateDir = "kpt-pkg-update-*"
Expand Down Expand Up @@ -99,13 +100,16 @@ func (m *DefaultPackageUpdater) do(_ context.Context, localPkgDir, originalPkgDi

func writeResourcesToDirectory(dir string, resources PackageResources) error {
for k, v := range resources.Contents {
p := filepath.Join(dir, k)
dir := filepath.Dir(p)
if err := os.MkdirAll(dir, 0750); err != nil {
return fmt.Errorf("failed to create directory %q: %w", dir, err)
p, err := util.FilepathSafeJoin(dir, k)
if err != nil {
return fmt.Errorf("invalid resource path %q: %w", k, err)
}
d := filepath.Dir(p)
if err := os.MkdirAll(d, 0750); err != nil {
return fmt.Errorf("failed to create directory %q: %w", d, err)
}
if err := os.WriteFile(p, []byte(v), 0600); err != nil {
return fmt.Errorf("failed to write file %q: %w", dir, err)
return fmt.Errorf("failed to write file %q: %w", p, err)
}
}
return nil
Expand Down
28 changes: 27 additions & 1 deletion pkg/repository/update_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2022, 2024 The kpt Authors
// Copyright 2022, 2024, 2026 The kpt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -149,3 +149,29 @@ func TestDefaultPackageUpdaterdo(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, "upstream content", updatedResources.Contents["file1.txt"])
}

func TestWriteResourcesToDirectoryRejectsInvalidPaths(t *testing.T) {
dir := t.TempDir()

tests := []struct {
name string
key string
}{
{"relative path escapes base", "../escape.txt"},
{"nested relative path escapes base", "a/../../escape.txt"},
{"absolute path", "/etc/file"},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resources := PackageResources{
Contents: map[string]string{
tt.key: "content",
},
}
err := writeResourcesToDirectory(dir, resources)
assert.Error(t, err)
assert.Contains(t, err.Error(), "invalid resource path")
})
}
}
35 changes: 34 additions & 1 deletion pkg/task/replace_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2022, 2024 The kpt Authors
// Copyright 2022, 2024, 2026 The kpt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -91,3 +91,36 @@ func removeCommentsFromFile(t *testing.T, name, contents string) string {

return nocomment.String()
}

func TestReplaceResourcesRejectsInvalidPaths(t *testing.T) {
ctx := context.Background()

replace := &replaceResourcesMutation{
newResources: &porchapi.PackageRevisionResources{
Spec: porchapi.PackageRevisionResourcesSpec{
Resources: map[string]string{
"../../../etc/config": "content",
},
},
},
oldResources: &porchapi.PackageRevisionResources{
Spec: porchapi.PackageRevisionResourcesSpec{
Resources: map[string]string{
"Kptfile": "existing",
},
},
},
}

input := repository.PackageResources{
Contents: map[string]string{"Kptfile": "existing"},
}

_, _, err := replace.apply(ctx, input)
if err == nil {
t.Fatal("expected error for invalid path, got nil")
}
if !bytes.Contains([]byte(err.Error()), []byte("invalid resource path")) {
t.Errorf("unexpected error message: %v", err)
}
}
7 changes: 6 additions & 1 deletion pkg/task/replaceresources.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2024 The kpt Authors
// Copyright 2024, 2026 The kpt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -20,6 +20,7 @@ import (

porchapi "github.com/kptdev/porch/api/porch/v1alpha1"
"github.com/kptdev/porch/pkg/repository"
"github.com/kptdev/porch/pkg/util"
"go.opentelemetry.io/otel/trace"
)

Expand All @@ -34,6 +35,10 @@ func (m *replaceResourcesMutation) apply(ctx context.Context, resources reposito
_, span := tracer.Start(ctx, "mutationReplaceResources::apply", trace.WithAttributes())
defer span.End()

if err := util.ValidateResourcePaths(m.newResources.Spec.Resources); err != nil {
return repository.PackageResources{}, nil, err
}

old := resources.Contents
newRes, err := healConfig(old, m.newResources.Spec.Resources)
if err != nil {
Expand Down
55 changes: 55 additions & 0 deletions pkg/util/safejoin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2022, 2026 The kpt Authors
//
// Licensed 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 util

import (
"fmt"
"path/filepath"
"strings"
)

// Relevant: https://github.com/golang/go/issues/20126

// FilepathSafeJoin joins dir and relative, returning an error if relative is
// not a clean, canonical relative path within dir. It rejects path traversal
// (.. sequences), absolute paths, the bare "." and ".." entries, and any path
// that would be altered by filepath.Clean (e.g. leading "./", redundant
// separators, or internal "a/../b" segments).
func FilepathSafeJoin(dir, relative string) (string, error) {
p := filepath.Join(dir, relative)
p = filepath.Clean(p)

rel, err := filepath.Rel(dir, p)
if err != nil {
return "", fmt.Errorf("invalid relative path %q", relative)
}
if rel == "." || rel == ".." || rel != relative || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || strings.HasPrefix(rel, "."+string(filepath.Separator)) {
return "", fmt.Errorf("invalid relative path %q", relative)
}
return p, nil
}

// ValidateResourcePaths checks that all keys in a resource map are valid
// relative file paths within a package. It rejects path traversal sequences,
// absolute paths, and non-canonical paths (e.g. leading "./", bare "." or "..").
// Returns an error on the first invalid key.
func ValidateResourcePaths(resources map[string]string) error {
for k := range resources {
if _, err := FilepathSafeJoin(".", k); err != nil {
return fmt.Errorf("invalid resource path %q: %w", k, err)
}
}
return nil
}
Loading
Loading