-
Notifications
You must be signed in to change notification settings - Fork 3
/
metadata.go
254 lines (222 loc) · 7.04 KB
/
metadata.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
Copyright 2020 The Flux 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 chart
import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strings"
helmchart "helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chartutil"
"sigs.k8s.io/yaml"
"github.com/doodlescheduling/flux-build/internal/helm"
)
var drivePathPattern = regexp.MustCompile(`^[a-zA-Z]:/`)
// OverwriteChartDefaultValues overwrites the chart default values file with the given data.
func OverwriteChartDefaultValues(chart *helmchart.Chart, vals chartutil.Values) (bool, error) {
if vals == nil {
return false, nil
}
var bVals bytes.Buffer
if len(vals) > 0 {
if err := vals.Encode(&bVals); err != nil {
return false, err
}
}
// Replace current values file in Raw field
for _, f := range chart.Raw {
if f.Name == chartutil.ValuesfileName {
// Do nothing if contents are equal
if reflect.DeepEqual(f.Data, bVals.Bytes()) {
return false, nil
}
// Replace in Files field
for _, f := range chart.Files {
if f.Name == chartutil.ValuesfileName {
f.Data = bVals.Bytes()
}
}
f.Data = bVals.Bytes()
chart.Values = vals.AsMap()
return true, nil
}
}
// This should never happen, helm charts must have a values.yaml file to be valid
return false, fmt.Errorf("failed to locate values file: %s", chartutil.ValuesfileName)
}
// LoadChartMetadata attempts to load the chart.Metadata from the "Chart.yaml" file in the directory or archive at the
// given chartPath. It takes "requirements.yaml" files into account, and is therefore compatible with the
// chart.APIVersionV1 format.
func LoadChartMetadata(chartPath string) (meta *helmchart.Metadata, err error) {
i, err := os.Stat(chartPath)
if err != nil {
return nil, err
}
if i.IsDir() {
meta, err = LoadChartMetadataFromDir(chartPath)
return
}
meta, err = LoadChartMetadataFromArchive(chartPath)
return
}
// LoadChartMetadataFromDir loads the chart.Metadata from the "Chart.yaml" file in the directory at the given path.
// It takes "requirements.yaml" files into account, and is therefore compatible with the chart.APIVersionV1 format.
func LoadChartMetadataFromDir(dir string) (*helmchart.Metadata, error) {
m := new(helmchart.Metadata)
b, err := os.ReadFile(filepath.Join(dir, chartutil.ChartfileName))
if err != nil {
return nil, err
}
err = yaml.Unmarshal(b, m)
if err != nil {
return nil, fmt.Errorf("cannot load '%s': %w", chartutil.ChartfileName, err)
}
if m.APIVersion == "" {
m.APIVersion = helmchart.APIVersionV1
}
fp := filepath.Join(dir, "requirements.yaml")
stat, err := os.Stat(fp)
if (err != nil && !errors.Is(err, os.ErrNotExist)) || stat != nil {
if err != nil {
return nil, err
}
if stat.IsDir() {
return nil, fmt.Errorf("'%s' is a directory", stat.Name())
}
if stat.Size() > helm.MaxChartFileSize {
return nil, fmt.Errorf("size of '%s' exceeds '%d' bytes limit", stat.Name(), helm.MaxChartFileSize)
}
}
b, err = os.ReadFile(fp)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
if len(b) > 0 {
if err = yaml.Unmarshal(b, m); err != nil {
return nil, fmt.Errorf("cannot load 'requirements.yaml': %w", err)
}
}
return m, nil
}
// LoadChartMetadataFromArchive loads the chart.Metadata from the "Chart.yaml" file in the archive at the given path.
// It takes "requirements.yaml" files into account, and is therefore compatible with the chart.APIVersionV1 format.
func LoadChartMetadataFromArchive(archive string) (*helmchart.Metadata, error) {
stat, err := os.Stat(archive)
if err != nil || stat.IsDir() {
if err == nil {
err = fmt.Errorf("'%s' is a directory", stat.Name())
}
return nil, err
}
if stat.Size() > helm.MaxChartSize {
return nil, fmt.Errorf("size of chart '%s' exceeds '%d' bytes limit", stat.Name(), helm.MaxChartSize)
}
f, err := os.Open(archive)
if err != nil {
return nil, err
}
defer f.Close()
r := bufio.NewReader(f)
zr, err := gzip.NewReader(r)
if err != nil {
return nil, err
}
tr := tar.NewReader(zr)
// The following logic is on par with how Helm validates the package while
// unpackaging it, except that we only read the Metadata related files.
// Ref: https://github.com/helm/helm/blob/a499b4b179307c267bdf3ec49b880e3dbd2a5591/pkg/chart/loader/archive.go#L104
var m *helmchart.Metadata
for {
hd, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if hd.FileInfo().IsDir() {
// Use this instead of hd.Typeflag because we don't have to do any
// inference chasing.
continue
}
switch hd.Typeflag {
// We don't want to process these extension header files.
case tar.TypeXGlobalHeader, tar.TypeXHeader:
continue
}
// Archive could contain \ if generated on Windows
delimiter := "/"
if strings.ContainsRune(hd.Name, '\\') {
delimiter = "\\"
}
parts := strings.Split(hd.Name, delimiter)
n := strings.Join(parts[1:], delimiter)
// Normalize the path to the / delimiter
n = strings.ReplaceAll(n, delimiter, "/")
if path.IsAbs(n) {
return nil, errors.New("chart illegally contains absolute paths")
}
n = path.Clean(n)
if n == "." {
// In this case, the original path was relative when it should have been absolute.
return nil, fmt.Errorf("chart illegally contains content outside the base directory: %s", hd.Name)
}
if strings.HasPrefix(n, "..") {
return nil, fmt.Errorf("chart illegally references parent directory")
}
// In some particularly arcane acts of path creativity, it is possible to intermix
// UNIX and Windows style paths in such a way that you produce a result of the form
// c:/foo even after all the built-in absolute path checks. So we explicitly check
// for this condition.
if drivePathPattern.MatchString(n) {
return nil, errors.New("chart contains illegally named files")
}
// We are only interested in files in the base directory from here on
if len(parts) != 2 {
continue
}
switch parts[1] {
case chartutil.ChartfileName, "requirements.yaml":
if hd.Size > helm.MaxChartFileSize {
return nil, fmt.Errorf("size of '%s' exceeds '%d' bytes limit", hd.Name, helm.MaxChartFileSize)
}
b, err := io.ReadAll(tr)
if err != nil {
return nil, err
}
if m == nil {
m = new(helmchart.Metadata)
}
err = yaml.Unmarshal(b, m)
if err != nil {
return nil, fmt.Errorf("cannot load '%s': %w", parts[1], err)
}
if m.APIVersion == "" {
m.APIVersion = helmchart.APIVersionV1
}
}
}
if m == nil {
return nil, fmt.Errorf("no '%s' found", chartutil.ChartfileName)
}
return m, nil
}