github.com/google/osv-scalibr@v0.4.1/artifact/image/symlink/symlink_test.go (about)

     1  // Copyright 2025 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package symlink_test
    16  
    17  import (
    18  	"runtime"
    19  	"testing"
    20  
    21  	"github.com/google/osv-scalibr/artifact/image/symlink"
    22  )
    23  
    24  func TestTargetOutsideRoot(t *testing.T) {
    25  	tests := []struct {
    26  		name   string
    27  		path   string
    28  		target string
    29  		want   bool
    30  	}{{
    31  		name:   "absolute target",
    32  		path:   "/a/f.txt",
    33  		target: "/a/f.txt",
    34  		want:   false,
    35  	}, {
    36  		name:   "absolute path and relative target within root",
    37  		path:   "/a/f.txt",
    38  		target: "../t.txt",
    39  		want:   false,
    40  	}, {
    41  		name:   "relative target within root",
    42  		path:   "a/f.txt",
    43  		target: "../t.txt",
    44  		want:   false,
    45  	}, {
    46  		name:   "absolute path and relative target outside root",
    47  		path:   "/a/f.txt",
    48  		target: "../../t.txt",
    49  		want:   true,
    50  	}, {
    51  		name:   "relative target outside root",
    52  		path:   "a/f.txt",
    53  		target: "../../t.txt",
    54  		want:   true,
    55  	}, {
    56  		name: "absolute_target_outside_root",
    57  		path: "a/f.txt",
    58  		target: func() string {
    59  			if runtime.GOOS == "windows" {
    60  				return "\\\\..\\t.txt"
    61  			}
    62  			return "/../t.txt"
    63  		}(),
    64  		want: true,
    65  	}, {
    66  		name:   "absolute target inside root",
    67  		path:   "a/b/f.txt",
    68  		target: "/a/../c/t.txt",
    69  		want:   false,
    70  	}}
    71  
    72  	for _, tc := range tests {
    73  		t.Run(tc.name, func(t *testing.T) {
    74  			got := symlink.TargetOutsideRoot(tc.path, tc.target)
    75  			if got != tc.want {
    76  				t.Errorf("targetOutsideRoot(%v, %v) = %v, want %v", tc.path, tc.target, got, tc.want)
    77  			}
    78  		})
    79  	}
    80  }