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 api/v1beta1/clusterreport_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ import (
libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1"
)

const (
ClusterReportKind = "ClusterReport"
)

// HelmAction represents the type of action on a give resource or helm release
type HelmAction string

Expand Down
32 changes: 30 additions & 2 deletions controllers/clustersummary_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,9 @@ func (r *ClusterSummaryReconciler) blockOnInvalidTenantIdentity(clusterSummary *
return true
}

// checkClusterHealth checks if the cluster is ready and the agent is healthy.
// Returns (proceed, result, error)
// checkClusterHealth checks the preconditions reconcileNormal needs: the cluster is ready, the
// agent is healthy, and - for a ClusterSummary owned by a Profile - its content is exactly what
// the Profile reconciler would have produced. Returns (proceed, error).
func (r *ClusterSummaryReconciler) checkClusterHealth(ctx context.Context,
clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) (bool, error) {

Expand Down Expand Up @@ -323,9 +324,36 @@ func (r *ClusterSummaryReconciler) checkClusterHealth(ctx context.Context,
return false, nil
}

// 3. Check the ClusterSummary content itself is trustworthy
if !r.rejectInvalidProfileClusterSummary(ctx, clusterSummaryScope, logger) {
return false, nil
}

return true, nil
}

// rejectInvalidProfileClusterSummary reports whether clusterSummaryScope's ClusterSummary may
// proceed to reconcileNormal. A ClusterSummary owned by a Profile (not a ClusterProfile, which
// is admin-level) must be exactly what the Profile reconciler would have produced for it; one
// that is not - for instance a forged ClusterSummary whose templateResourceRefs/policyRefs/etc
// point at another tenant's namespace - is refused rather than deployed with the controller's
// own rights. See isProfileClusterSummaryValid.
func (r *ClusterSummaryReconciler) rejectInvalidProfileClusterSummary(ctx context.Context,
clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) bool {

if clusterSummaryScope.Profile.GetObjectKind().GroupVersionKind().Kind != configv1beta1.ProfileKind {
return true
}
if isProfileClusterSummaryValid(clusterSummaryScope.ClusterSummary) {
return true
}

msg := "ClusterSummary does not match what its owning Profile would produce. Not deploying it."
logger.V(logs.LogInfo).Info(msg)
r.handleClusterNotUsable(ctx, clusterSummaryScope, msg, logger)
return false
}

// Helper to avoid repeating the "Not Ready/Not Healthy" boilerplate
func (r *ClusterSummaryReconciler) handleClusterNotUsable(ctx context.Context,
clusterSummaryScope *scope.ClusterSummaryScope, msg string, logger logr.Logger) {
Expand Down
53 changes: 29 additions & 24 deletions controllers/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,27 +44,31 @@ const (
)

var (
ReconcileDeleteCommon = reconcileDeleteCommon
ClusterProfileReconcileDelete = (*ClusterProfileReconciler).reconcileDelete
ProfileReconcileDelete = (*ProfileReconciler).reconcileDelete
UpdateClusterSummaries = updateClusterSummaries
CreateClusterSummary = createClusterSummary
UpdateClusterSummary = updateClusterSummary
UpdateClusterConfigurations = updateClusterConfigurations
UpdateClusterConfigurationWithProfile = updateClusterConfigurationWithProfile
CleanClusterConfiguration = cleanClusterConfiguration
CleanClusterConfigurations = cleanClusterConfigurations
CleanClusterReports = cleanClusterReports
CleanClusterSummaries = cleanClusterSummaries
UpdateClusterSummarySyncMode = updateClusterSummarySyncMode
UpdateClusterReports = updateClusterReports
GetMatchingClusters = getMatchingClusters
IsProfilePaused = isProfilePaused
GetMaxUpdate = getMaxUpdate
ReviseUpdatedAndUpdatingClusters = reviseUpdatedAndUpdatingClusters
GetUpdatedAndUpdatingClusters = getUpdatedAndUpdatingClusters
ReviseUpdatingClusterList = reviseUpdatingClusterList
GrantsPullModeEligibility = grantsPullModeEligibility
ReconcileDeleteCommon = reconcileDeleteCommon
ClusterProfileReconcileDelete = (*ClusterProfileReconciler).reconcileDelete
ProfileReconcileDelete = (*ProfileReconciler).reconcileDelete
UpdateClusterSummaries = updateClusterSummaries
CreateClusterSummary = createClusterSummary
UpdateClusterSummary = updateClusterSummary
UpdateClusterConfigurations = updateClusterConfigurations
UpdateClusterConfigurationWithProfile = updateClusterConfigurationWithProfile
CleanClusterConfiguration = cleanClusterConfiguration
CleanClusterConfigurations = cleanClusterConfigurations
CleanClusterReports = cleanClusterReports
CleanClusterSummaries = cleanClusterSummaries
UpdateClusterSummarySyncMode = updateClusterSummarySyncMode
UpdateClusterReports = updateClusterReports
GetMatchingClusters = getMatchingClusters
IsProfilePaused = isProfilePaused
GetMaxUpdate = getMaxUpdate
ReviseUpdatedAndUpdatingClusters = reviseUpdatedAndUpdatingClusters
GetUpdatedAndUpdatingClusters = getUpdatedAndUpdatingClusters
ReviseUpdatingClusterList = reviseUpdatingClusterList
GrantsPullModeEligibility = grantsPullModeEligibility
IsResourceKindAllowedForLocalProfileDeploy = isResourceKindAllowedForLocalProfileDeploy
BuildKustomization = buildKustomization
NewConfinedKustomizeFileSystem = newConfinedKustomizeFileSystem
RejectSymlinksUnder = rejectSymlinksUnder
)

var (
Expand All @@ -73,9 +77,10 @@ var (
)

var (
RequeueProfileForCluster = (*ProfileReconciler).requeueProfileForCluster
LimitReferencesToNamespace = (*ProfileReconciler).limitReferencesToNamespace
GetClustersFromSets = (*ProfileReconciler).getClustersFromSets
RequeueProfileForCluster = (*ProfileReconciler).requeueProfileForCluster
LimitReferencesToNamespace = (*ProfileReconciler).limitReferencesToNamespace
GetClustersFromSets = (*ProfileReconciler).getClustersFromSets
IsProfileClusterSummaryValid = isProfileClusterSummaryValid
)

var (
Expand Down
12 changes: 10 additions & 2 deletions controllers/handlers_kustomize.go
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,16 @@ func deployKustomizeRef(ctx context.Context, c client.Client, remoteRestConfig *

defer os.RemoveAll(tmpDir)

// tmpDir must be canonicalized before dirPath (below) is derived from it, or a
// legitimate path kustomize derives internally from its own root would stop having
// this root as a prefix and would be wrongly rejected as escaping it. See
// secureKustomizeContentDir.
var fs filesys.FileSystem
tmpDir, fs, err = secureKustomizeContentDir(tmpDir)
if err != nil {
return nil, nil, err
}

// Path can be expressed as a template and instantiate using Cluster fields and
// TemplateResourceRefs-collected resources.
instantiatedPath, err := instantiateTemplateValues(ctx, getManagementClusterConfig(), getManagementClusterClient(),
Expand Down Expand Up @@ -845,8 +855,6 @@ func deployKustomizeRef(ctx context.Context, c client.Client, remoteRestConfig *
return nil, nil, fmt.Errorf("failed to write modified kustomization.yaml: %w", err)
}

fs := filesys.MakeFsOnDisk()

var resMap resmap.ResMap
resMap, err = buildKustomization(fs, dirPath)
if err != nil {
Expand Down
233 changes: 233 additions & 0 deletions controllers/handlers_kustomize_confined_fs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
/*
Copyright 2026. projectsveltos.io. All rights reserved.

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 controllers

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

"sigs.k8s.io/kustomize/kyaml/filesys"
)

// secureKustomizeContentDir prepares tmpDir - the directory a kustomization's content was
// extracted into - to be built safely: it canonicalizes tmpDir, refuses any symlink found under
// it, and returns both the canonical path (deployKustomizeRef must use this, not the original
// tmpDir, for every path it derives from it afterwards) and a filesystem confined to it, ready
// to pass to buildKustomization alongside LoadRestrictionsNone.
func secureKustomizeContentDir(tmpDir string) (canonicalDir string, fs filesys.FileSystem, err error) {
canonicalDir, err = filepath.EvalSymlinks(tmpDir)
if err != nil {
return "", nil, fmt.Errorf("failed to resolve kustomization content directory: %w", err)
}

if err := rejectSymlinksUnder(canonicalDir); err != nil {
return "", nil, fmt.Errorf("refusing to build kustomization: %w", err)
}

fs, err = newConfinedKustomizeFileSystem(canonicalDir)
if err != nil {
return "", nil, err
}

return canonicalDir, fs, nil
}

// newConfinedKustomizeFileSystem returns a filesys.FileSystem backed by the real on-disk
// filesystem, but confined to root: every path it is asked to touch, however it is spelled
// (absolute, or relative with a chain of ".."), is resolved and then refused unless it falls
// under root.
//
// kustomize is built with LoadRestrictionsNone (see buildKustomization), because a kustomization
// legitimately referencing a sibling overlay such as "../../base" needs it. Without this
// confinement, that same setting lets a tenant-controlled kustomization.yaml read (or write, via
// a generator) any path on the addon-controller container's filesystem, e.g.
// /var/run/secrets/kubernetes.io/serviceaccount/token, by spelling it as an absolute path or a
// long enough "../" chain in a resources/patches/generator file reference.
//
// This only closes the path-string route. A path that is textually under root but is actually a
// symlink to somewhere else would still let the real OS-level Open/ReadFile follow it outside of
// root: rejectSymlinksUnder must be run against root before this filesystem is used, so that by
// the time it is in use, every regular path under root genuinely stays under root.
func newConfinedKustomizeFileSystem(root string) (filesys.FileSystem, error) {
absRoot, err := filepath.Abs(root)
if err != nil {
return nil, fmt.Errorf("failed to resolve kustomization root %q: %w", root, err)
}

// fsOnDisk.CleanedAbs, which kustomize calls to establish its own notion of the
// kustomization root, evaluates symlinks (e.g. macOS resolves /var to /private/var).
// The confined root has to go through the same canonicalization, or every path
// kustomize later derives from its own root would stop having this root as a prefix
// and would be wrongly rejected as an escape. rejectSymlinksUnder must have already
// guaranteed nothing under root itself is a symlink, so this only ever resolves
// symlinks that sit above root, never ones a tenant controls.
canonicalRoot, err := filepath.EvalSymlinks(absRoot)
if err != nil {
return nil, fmt.Errorf("failed to resolve kustomization root %q: %w", root, err)
}

return &confinedFileSystem{disk: filesys.MakeFsOnDisk(), root: filepath.Clean(canonicalRoot)}, nil
}

// rejectSymlinksUnder fails if root (or anything under it) is a symlink. It must be called
// before newConfinedKustomizeFileSystem is used to build a kustomization rooted at root: see
// that function's comment for why.
//
// None of addon-controller's own kustomize content sources (the ConfigMap/Secret tar.gz
// extraction in extractTarGz, and the flux-sourced/RemoteURL fetches which go through
// fluxcd/pkg/tar) currently materialize symlinks when extracting tenant-supplied content, so
// this is defense in depth against a future content source, or a bug in one of those, doing so.
func rejectSymlinksUnder(root string) error {
return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("%q is a symlink, which is not allowed in kustomization content", path)
}
return nil
})
}

// confinedFileSystem implements filesys.FileSystem by forwarding every call to the real on-disk
// filesystem, after confining the path argument to root. See newConfinedKustomizeFileSystem.
type confinedFileSystem struct {
disk filesys.FileSystem
root string
}

// confine resolves path against fs.root (joining it if relative) and fails if the cleaned
// result does not fall under fs.root.
func (fs *confinedFileSystem) confine(path string) (string, error) {
resolved := path
if !filepath.IsAbs(resolved) {
resolved = filepath.Join(fs.root, resolved)
}
resolved = filepath.Clean(resolved)

if resolved != fs.root && !strings.HasPrefix(resolved, fs.root+string(filepath.Separator)) {
return "", fmt.Errorf("path %q resolves outside of the kustomization content", path)
}

return resolved, nil
}

func (fs *confinedFileSystem) Create(path string) (filesys.File, error) {
p, err := fs.confine(path)
if err != nil {
return nil, err
}
return fs.disk.Create(p)
}

func (fs *confinedFileSystem) Mkdir(path string) error {
p, err := fs.confine(path)
if err != nil {
return err
}
return fs.disk.Mkdir(p)
}

func (fs *confinedFileSystem) MkdirAll(path string) error {
p, err := fs.confine(path)
if err != nil {
return err
}
return fs.disk.MkdirAll(p)
}

func (fs *confinedFileSystem) RemoveAll(path string) error {
p, err := fs.confine(path)
if err != nil {
return err
}
return fs.disk.RemoveAll(p)
}

func (fs *confinedFileSystem) Open(path string) (filesys.File, error) {
p, err := fs.confine(path)
if err != nil {
return nil, err
}
return fs.disk.Open(p)
}

func (fs *confinedFileSystem) IsDir(path string) bool {
p, err := fs.confine(path)
if err != nil {
return false
}
return fs.disk.IsDir(p)
}

func (fs *confinedFileSystem) ReadDir(path string) ([]string, error) {
p, err := fs.confine(path)
if err != nil {
return nil, err
}
return fs.disk.ReadDir(p)
}

func (fs *confinedFileSystem) CleanedAbs(path string) (filesys.ConfirmedDir, string, error) {
p, err := fs.confine(path)
if err != nil {
return "", "", err
}
return fs.disk.CleanedAbs(p)
}

func (fs *confinedFileSystem) Exists(path string) bool {
p, err := fs.confine(path)
if err != nil {
return false
}
return fs.disk.Exists(p)
}

func (fs *confinedFileSystem) Glob(pattern string) ([]string, error) {
p, err := fs.confine(pattern)
if err != nil {
return nil, err
}
return fs.disk.Glob(p)
}

func (fs *confinedFileSystem) ReadFile(path string) ([]byte, error) {
p, err := fs.confine(path)
if err != nil {
return nil, err
}
return fs.disk.ReadFile(p)
}

func (fs *confinedFileSystem) WriteFile(path string, data []byte) error {
p, err := fs.confine(path)
if err != nil {
return err
}
return fs.disk.WriteFile(p, data)
}

func (fs *confinedFileSystem) Walk(path string, walkFn filepath.WalkFunc) error {
p, err := fs.confine(path)
if err != nil {
return err
}
return fs.disk.Walk(p, walkFn)
}
Loading