Skip to content

Commit

Permalink
Validate usage of knative.dev/hack/shell
Browse files Browse the repository at this point in the history
This is follow up to knative.dev/hack#30 intended to disallow using this
shell out package without control.

If new place is required to use this package, first a allow PR should be
made to this repo.
  • Loading branch information
cardil committed Nov 26, 2020
1 parent c46a649 commit e957121
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
15 changes: 15 additions & 0 deletions foo/caller_not_allowed_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package foo

import (
"errors"
"testing"

"knative.dev/hack/shell"
)

func TestCallerNotAllowed(t *testing.T) {
_, err := shell.NewProjectLocation("..")
if !errors.Is(err, shell.ErrCallerNotAllowed) {
t.Error("usage should be blocked")
}
}
31 changes: 29 additions & 2 deletions shell/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,21 @@ package shell

import (
"errors"
"fmt"
"path"
"regexp"
"runtime"
)

// ErrCantGetCaller is raised when we can't calculate a caller of NewProjectLocation.
var ErrCantGetCaller = errors.New("can't get caller")
var (
// ErrCantGetCaller is raised when we can't calculate a caller of NewProjectLocation.
ErrCantGetCaller = errors.New("can't get caller")

// ErrCallerNotAllowed is raised when user tries to use this shell-out package
// outside of allowed places. This package is deprecated from start and was
// introduced to allow rewriting of shell code to Golang in small chunks.
ErrCallerNotAllowed = errors.New("don't try use knative.dev/hack/shell package outside of allowed places")
)

// NewProjectLocation creates a ProjectLocation that is used to calculate
// relative paths within the project.
Expand All @@ -32,6 +41,10 @@ func NewProjectLocation(pathToRoot string) (ProjectLocation, error) {
if !ok {
return nil, ErrCantGetCaller
}
err := ensureIsValid(filename)
if err != nil {
return nil, err
}
return &callerLocation{
caller: filename,
pathToRoot: pathToRoot,
Expand All @@ -50,3 +63,17 @@ type callerLocation struct {
caller string
pathToRoot string
}

func ensureIsValid(filename string) error {
validPaths := []string{
"knative.+/test/upgrade/",
"knative[/-]hack/shell/",
}
for _, validPath := range validPaths {
r := regexp.MustCompile(validPath)
if loc := r.FindStringIndex(filename); loc != nil {
return nil
}
}
return fmt.Errorf("%w: %s", ErrCallerNotAllowed, filename)
}

0 comments on commit e957121

Please sign in to comment.