| 1 |
/* |
| 2 |
Copyright 2016 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
// Package generators has the generators for the import-boss utility. |
| 18 |
package generators |
| 19 |
|
| 20 |
import ( |
| 21 |
"encoding/json" |
| 22 |
"errors" |
| 23 |
"fmt" |
| 24 |
"io" |
| 25 |
"io/ioutil" |
| 26 |
"os" |
| 27 |
"path/filepath" |
| 28 |
"regexp" |
| 29 |
"sort" |
| 30 |
"strings" |
| 31 |
|
| 32 |
"k8s.io/gengo/args" |
| 33 |
"k8s.io/gengo/generator" |
| 34 |
"k8s.io/gengo/namer" |
| 35 |
"k8s.io/gengo/types" |
| 36 |
"sigs.k8s.io/yaml" |
| 37 |
|
| 38 |
"k8s.io/klog/v2" |
| 39 |
) |
| 40 |
|
| 41 |
const ( |
| 42 |
goModFile = "go.mod" |
| 43 |
importBossFileType = "import-boss" |
| 44 |
) |
| 45 |
|
| 46 |
// NameSystems returns the name system used by the generators in this package. |
| 47 |
func NameSystems() namer.NameSystems { |
| 48 |
return namer.NameSystems{ |
| 49 |
"raw": namer.NewRawNamer("", nil), |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
// DefaultNameSystem returns the default name system for ordering the types to be |
| 54 |
// processed by the generators in this package. |
| 55 |
func DefaultNameSystem() string { |
| 56 |
return "raw" |
| 57 |
} |
| 58 |
|
| 59 |
// Packages makes the import-boss package definition. |
| 60 |
func Packages(c *generator.Context, arguments *args.GeneratorArgs) generator.Packages { |
| 61 |
pkgs := generator.Packages{} |
| 62 |
c.FileTypes = map[string]generator.FileType{ |
| 63 |
importBossFileType: importRuleFile{c}, |
| 64 |
} |
| 65 |
|
| 66 |
for _, p := range c.Universe { |
| 67 |
if !inputIncludes(arguments.InputDirs, p) { |
| 68 |
// Don't run on e.g. third party dependencies. |
| 69 |
continue |
| 70 |
} |
| 71 |
savedPackage := p |
| 72 |
pkgs = append(pkgs, &generator.DefaultPackage{ |
| 73 |
PackageName: p.Name, |
| 74 |
PackagePath: p.Path, |
| 75 |
Source: p.SourcePath, |
| 76 |
// GeneratorFunc returns a list of generators. Each generator makes a |
| 77 |
// single file. |
| 78 |
GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) { |
| 79 |
return []generator.Generator{&importRules{ |
| 80 |
myPackage: savedPackage, |
| 81 |
}} |
| 82 |
}, |
| 83 |
FilterFunc: func(c *generator.Context, t *types.Type) bool { |
| 84 |
return false |
| 85 |
}, |
| 86 |
}) |
| 87 |
} |
| 88 |
|
| 89 |
return pkgs |
| 90 |
} |
| 91 |
|
| 92 |
// inputIncludes returns true if the given package is a (sub) package of one of |
| 93 |
// the InputDirs. |
| 94 |
func inputIncludes(inputs []string, p *types.Package) bool { |
| 95 |
// TODO: This does not handle conversion of local paths (./foo) into |
| 96 |
// canonical packages (github.com/example/project/foo). |
| 97 |
for _, input := range inputs { |
| 98 |
// Normalize paths |
| 99 |
input := strings.TrimSuffix(input, "/") |
| 100 |
input = strings.TrimPrefix(input, "./vendor/") |
| 101 |
seek := strings.TrimSuffix(p.Path, "/") |
| 102 |
|
| 103 |
if input == seek { |
| 104 |
return true |
| 105 |
} |
| 106 |
if strings.HasSuffix(input, "...") { |
| 107 |
input = strings.TrimSuffix(input, "...") |
| 108 |
if strings.HasPrefix(seek+"/", input) { |
| 109 |
return true |
| 110 |
} |
| 111 |
} |
| 112 |
} |
| 113 |
return false |
| 114 |
} |
| 115 |
|
| 116 |
// A single import restriction rule. |
| 117 |
type Rule struct { |
| 118 |
// All import paths that match this regexp... |
| 119 |
SelectorRegexp string |
| 120 |
// ... must have one of these prefixes ... |
| 121 |
AllowedPrefixes []string |
| 122 |
// ... and must not have one of these prefixes. |
| 123 |
ForbiddenPrefixes []string |
| 124 |
} |
| 125 |
|
| 126 |
type InverseRule struct { |
| 127 |
Rule |
| 128 |
// True if the rule is to be applied to transitive imports. |
| 129 |
Transitive bool |
| 130 |
} |
| 131 |
|
| 132 |
type fileFormat struct { |
| 133 |
CurrentImports []string |
| 134 |
|
| 135 |
Rules []Rule |
| 136 |
InverseRules []InverseRule |
| 137 |
|
| 138 |
path string |
| 139 |
} |
| 140 |
|
| 141 |
func readFile(path string) (*fileFormat, error) { |
| 142 |
currentBytes, err := ioutil.ReadFile(path) |
| 143 |
if err != nil { |
| 144 |
return nil, fmt.Errorf("couldn't read %v: %v", path, err) |
| 145 |
} |
| 146 |
|
| 147 |
var current fileFormat |
| 148 |
err = yaml.Unmarshal(currentBytes, ¤t) |
| 149 |
if err != nil { |
| 150 |
return nil, fmt.Errorf("couldn't unmarshal %v: %v", path, err) |
| 151 |
} |
| 152 |
current.path = path |
| 153 |
return ¤t, nil |
| 154 |
} |
| 155 |
|
| 156 |
func writeFile(path string, ff *fileFormat) error { |
| 157 |
raw, err := json.MarshalIndent(ff, "", "\t") |
| 158 |
if err != nil { |
| 159 |
return fmt.Errorf("couldn't format data for file %v.\n%#v", path, ff) |
| 160 |
} |
| 161 |
f, err := os.Create(path) |
| 162 |
if err != nil { |
| 163 |
return fmt.Errorf("couldn't open %v for writing: %v", path, err) |
| 164 |
} |
| 165 |
defer f.Close() |
| 166 |
_, err = f.Write(raw) |
| 167 |
return err |
| 168 |
} |
| 169 |
|
| 170 |
// This does the actual checking, since it knows the literal destination file. |
| 171 |
type importRuleFile struct { |
| 172 |
context *generator.Context |
| 173 |
} |
| 174 |
|
| 175 |
func (irf importRuleFile) AssembleFile(f *generator.File, path string) error { |
| 176 |
return irf.VerifyFile(f, path) |
| 177 |
} |
| 178 |
|
| 179 |
// TODO: make a flag to enable this, or expose this information in some other way. |
| 180 |
func (importRuleFile) listEntireImportTree(f *generator.File, path string) error { |
| 181 |
// If the file exists, populate its current imports. This is mostly to help |
| 182 |
// humans figure out what they need to fix. |
| 183 |
if _, err := os.Stat(path); err != nil { |
| 184 |
// Ignore packages which haven't opted in by adding an .import-restrictions file. |
| 185 |
return nil |
| 186 |
} |
| 187 |
|
| 188 |
current, err := readFile(path) |
| 189 |
if err != nil { |
| 190 |
return err |
| 191 |
} |
| 192 |
|
| 193 |
current.CurrentImports = []string{} |
| 194 |
for v := range f.Imports { |
| 195 |
current.CurrentImports = append(current.CurrentImports, v) |
| 196 |
} |
| 197 |
sort.Strings(current.CurrentImports) |
| 198 |
|
| 199 |
return writeFile(path, current) |
| 200 |
} |
| 201 |
|
| 202 |
// removeLastDir removes the last directory, but leaves the file name |
| 203 |
// unchanged. It returns the new path and the removed directory. So: |
| 204 |
// "a/b/c/file" -> ("a/b/file", "c") |
| 205 |
func removeLastDir(path string) (newPath, removedDir string) { |
| 206 |
dir, file := filepath.Split(path) |
| 207 |
dir = strings.TrimSuffix(dir, string(filepath.Separator)) |
| 208 |
return filepath.Join(filepath.Dir(dir), file), filepath.Base(dir) |
| 209 |
} |
| 210 |
|
| 211 |
// isGoModRoot checks if a directory is the root directory for a package |
| 212 |
// by checking for the existence of a 'go.mod' file in that directory. |
| 213 |
func isGoModRoot(path string) bool { |
| 214 |
_, err := os.Stat(filepath.Join(filepath.Dir(path), goModFile)) |
| 215 |
return err == nil |
| 216 |
} |
| 217 |
|
| 218 |
// recursiveRead collects all '.import-restriction' files, between the current directory, |
| 219 |
// and the package root when Go modules are enabled, or $GOPATH/src when they are not. |
| 220 |
func recursiveRead(path string) ([]*fileFormat, error) { |
| 221 |
restrictionFiles := make([]*fileFormat, 0) |
| 222 |
|
| 223 |
for { |
| 224 |
if _, err := os.Stat(path); err == nil { |
| 225 |
rules, err := readFile(path) |
| 226 |
if err != nil { |
| 227 |
return nil, err |
| 228 |
} |
| 229 |
|
| 230 |
restrictionFiles = append(restrictionFiles, rules) |
| 231 |
} |
| 232 |
|
| 233 |
nextPath, removedDir := removeLastDir(path) |
| 234 |
if nextPath == path || isGoModRoot(path) || removedDir == "src" { |
| 235 |
break |
| 236 |
} |
| 237 |
|
| 238 |
path = nextPath |
| 239 |
} |
| 240 |
|
| 241 |
return restrictionFiles, nil |
| 242 |
} |
| 243 |
|
| 244 |
func (irf importRuleFile) VerifyFile(f *generator.File, path string) error { |
| 245 |
restrictionFiles, err := recursiveRead(filepath.Join(f.PackageSourcePath, f.Name)) |
| 246 |
if err != nil { |
| 247 |
return fmt.Errorf("error finding rules file: %v", err) |
| 248 |
} |
| 249 |
|
| 250 |
if err := irf.verifyRules(restrictionFiles, f); err != nil { |
| 251 |
return err |
| 252 |
} |
| 253 |
|
| 254 |
return irf.verifyInverseRules(restrictionFiles, f) |
| 255 |
} |
| 256 |
|
| 257 |
func (irf importRuleFile) verifyRules(restrictionFiles []*fileFormat, f *generator.File) error { |
| 258 |
selectors := make([][]*regexp.Regexp, len(restrictionFiles)) |
| 259 |
for i, restrictionFile := range restrictionFiles { |
| 260 |
for _, r := range restrictionFile.Rules { |
| 261 |
re, err := regexp.Compile(r.SelectorRegexp) |
| 262 |
if err != nil { |
| 263 |
return fmt.Errorf("regexp `%s` in file %q doesn't compile: %v", r.SelectorRegexp, restrictionFile.path, err) |
| 264 |
} |
| 265 |
|
| 266 |
selectors[i] = append(selectors[i], re) |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
forbiddenImports := map[string]string{} |
| 271 |
allowedMismatchedImports := []string{} |
| 272 |
|
| 273 |
for v := range f.Imports { |
| 274 |
explicitlyAllowed := false |
| 275 |
|
| 276 |
NextRestrictionFiles: |
| 277 |
for i, rules := range restrictionFiles { |
| 278 |
for j, r := range rules.Rules { |
| 279 |
matching := selectors[i][j].MatchString(v) |
| 280 |
klog.V(5).Infof("Checking %v matches %v: %v\n", r.SelectorRegexp, v, matching) |
| 281 |
if !matching { |
| 282 |
continue |
| 283 |
} |
| 284 |
for _, forbidden := range r.ForbiddenPrefixes { |
| 285 |
klog.V(4).Infof("Checking %v against %v\n", v, forbidden) |
| 286 |
if strings.HasPrefix(v, forbidden) { |
| 287 |
forbiddenImports[v] = forbidden |
| 288 |
} |
| 289 |
} |
| 290 |
for _, allowed := range r.AllowedPrefixes { |
| 291 |
klog.V(4).Infof("Checking %v against %v\n", v, allowed) |
| 292 |
if strings.HasPrefix(v, allowed) { |
| 293 |
explicitlyAllowed = true |
| 294 |
break |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
if !explicitlyAllowed { |
| 299 |
allowedMismatchedImports = append(allowedMismatchedImports, v) |
| 300 |
} else { |
| 301 |
klog.V(2).Infof("%v importing %v allowed by %v\n", f.PackagePath, v, restrictionFiles[i].path) |
| 302 |
break NextRestrictionFiles |
| 303 |
} |
| 304 |
} |
| 305 |
} |
| 306 |
} |
| 307 |
|
| 308 |
if len(forbiddenImports) > 0 || len(allowedMismatchedImports) > 0 { |
| 309 |
var errorBuilder strings.Builder |
| 310 |
for i, f := range forbiddenImports { |
| 311 |
fmt.Fprintf(&errorBuilder, "import %v has forbidden prefix %v\n", i, f) |
| 312 |
} |
| 313 |
if len(allowedMismatchedImports) > 0 { |
| 314 |
sort.Strings(allowedMismatchedImports) |
| 315 |
fmt.Fprintf(&errorBuilder, "the following imports did not match any allowed prefix:\n") |
| 316 |
for _, i := range allowedMismatchedImports { |
| 317 |
fmt.Fprintf(&errorBuilder, " %v\n", i) |
| 318 |
} |
| 319 |
} |
| 320 |
return errors.New(errorBuilder.String()) |
| 321 |
} |
| 322 |
|
| 323 |
return nil |
| 324 |
} |
| 325 |
|
| 326 |
// verifyInverseRules checks that all packages that import a package are allowed to import it. |
| 327 |
func (irf importRuleFile) verifyInverseRules(restrictionFiles []*fileFormat, f *generator.File) error { |
| 328 |
// compile all Selector regex in all restriction files |
| 329 |
selectors := make([][]*regexp.Regexp, len(restrictionFiles)) |
| 330 |
for i, restrictionFile := range restrictionFiles { |
| 331 |
for _, r := range restrictionFile.InverseRules { |
| 332 |
re, err := regexp.Compile(r.SelectorRegexp) |
| 333 |
if err != nil { |
| 334 |
return fmt.Errorf("regexp `%s` in file %q doesn't compile: %v", r.SelectorRegexp, restrictionFile.path, err) |
| 335 |
} |
| 336 |
|
| 337 |
selectors[i] = append(selectors[i], re) |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
directImport := map[string]bool{} |
| 342 |
for _, imp := range irf.context.IncomingImports()[f.PackagePath] { |
| 343 |
directImport[imp] = true |
| 344 |
} |
| 345 |
|
| 346 |
forbiddenImports := map[string]string{} |
| 347 |
allowedMismatchedImports := []string{} |
| 348 |
|
| 349 |
for _, v := range irf.context.TransitiveIncomingImports()[f.PackagePath] { |
| 350 |
explicitlyAllowed := false |
| 351 |
|
| 352 |
NextRestrictionFiles: |
| 353 |
for i, rules := range restrictionFiles { |
| 354 |
for j, r := range rules.InverseRules { |
| 355 |
if !r.Transitive && !directImport[v] { |
| 356 |
continue |
| 357 |
} |
| 358 |
|
| 359 |
re := selectors[i][j] |
| 360 |
matching := re.MatchString(v) |
| 361 |
klog.V(4).Infof("Checking %v matches %v (importing %v: %v\n", r.SelectorRegexp, v, f.PackagePath, matching) |
| 362 |
if !matching { |
| 363 |
continue |
| 364 |
} |
| 365 |
for _, forbidden := range r.ForbiddenPrefixes { |
| 366 |
klog.V(4).Infof("Checking %v against %v\n", v, forbidden) |
| 367 |
if strings.HasPrefix(v, forbidden) { |
| 368 |
forbiddenImports[v] = forbidden |
| 369 |
} |
| 370 |
} |
| 371 |
for _, allowed := range r.AllowedPrefixes { |
| 372 |
klog.V(4).Infof("Checking %v against %v\n", v, allowed) |
| 373 |
if strings.HasPrefix(v, allowed) { |
| 374 |
explicitlyAllowed = true |
| 375 |
break |
| 376 |
} |
| 377 |
} |
| 378 |
if !explicitlyAllowed { |
| 379 |
allowedMismatchedImports = append(allowedMismatchedImports, v) |
| 380 |
} else { |
| 381 |
klog.V(2).Infof("%v importing %v allowed by %v\n", v, f.PackagePath, restrictionFiles[i].path) |
| 382 |
break NextRestrictionFiles |
| 383 |
} |
| 384 |
} |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
if len(forbiddenImports) > 0 || len(allowedMismatchedImports) > 0 { |
| 389 |
var errorBuilder strings.Builder |
| 390 |
for i, f := range forbiddenImports { |
| 391 |
fmt.Fprintf(&errorBuilder, "(inverse): import %v has forbidden prefix %v\n", i, f) |
| 392 |
} |
| 393 |
if len(allowedMismatchedImports) > 0 { |
| 394 |
sort.Strings(allowedMismatchedImports) |
| 395 |
fmt.Fprintf(&errorBuilder, "(inverse): the following imports did not match any allowed prefix:\n") |
| 396 |
for _, i := range allowedMismatchedImports { |
| 397 |
fmt.Fprintf(&errorBuilder, " %v\n", i) |
| 398 |
} |
| 399 |
} |
| 400 |
return errors.New(errorBuilder.String()) |
| 401 |
} |
| 402 |
|
| 403 |
return nil |
| 404 |
} |
| 405 |
|
| 406 |
// importRules produces a file with a set for a single type. |
| 407 |
type importRules struct { |
| 408 |
myPackage *types.Package |
| 409 |
imports namer.ImportTracker |
| 410 |
} |
| 411 |
|
| 412 |
var ( |
| 413 |
_ = generator.Generator(&importRules{}) |
| 414 |
_ = generator.FileType(importRuleFile{}) |
| 415 |
) |
| 416 |
|
| 417 |
func (r *importRules) Name() string { return "import rules" } |
| 418 |
func (r *importRules) Filter(*generator.Context, *types.Type) bool { return false } |
| 419 |
func (r *importRules) Namers(*generator.Context) namer.NameSystems { return nil } |
| 420 |
func (r *importRules) PackageVars(*generator.Context) []string { return []string{} } |
| 421 |
func (r *importRules) PackageConsts(*generator.Context) []string { return []string{} } |
| 422 |
func (r *importRules) GenerateType(*generator.Context, *types.Type, io.Writer) error { return nil } |
| 423 |
func (r *importRules) Filename() string { return ".import-restrictions" } |
| 424 |
func (r *importRules) FileType() string { return importBossFileType } |
| 425 |
func (r *importRules) Init(c *generator.Context, w io.Writer) error { return nil } |
| 426 |
func (r *importRules) Finalize(*generator.Context, io.Writer) error { return nil } |
| 427 |
|
| 428 |
func dfsImports(dest *[]string, seen map[string]bool, p *types.Package) { |
| 429 |
for _, p2 := range p.Imports { |
| 430 |
if seen[p2.Path] { |
| 431 |
continue |
| 432 |
} |
| 433 |
seen[p2.Path] = true |
| 434 |
dfsImports(dest, seen, p2) |
| 435 |
*dest = append(*dest, p2.Path) |
| 436 |
} |
| 437 |
} |
| 438 |
|
| 439 |
func (r *importRules) Imports(*generator.Context) []string { |
| 440 |
all := []string{} |
| 441 |
dfsImports(&all, map[string]bool{}, r.myPackage) |
| 442 |
return all |
| 443 |
} |