mirror of
https://github.com/open-policy-agent/opa.git
synced 2026-08-12 19:32:48 -06:00
Add gocritic linter, fix a bunch of stuff (#7377)
Brace yourselves! For there are many touched files here. No changes in semantics however. Spent a long time trying out the various optional rules gocritic provides, and settled for a few of them. There are more I really like, but that would take many hours to address across the codebase. Perhaps others find gocritic too pedantic? If so, we can merge the fixes without enabling the rule. Signed-off-by: Anders Eknert <anders@styra.com>
This commit is contained in:
+1
-1
@@ -1 +1 @@
|
|||||||
1.23.6
|
1.24.0
|
||||||
|
|||||||
@@ -3,6 +3,10 @@ run:
|
|||||||
|
|
||||||
issues:
|
issues:
|
||||||
max-same-issues: 0 # don't hide issues in CI runs because they are the same type
|
max-same-issues: 0 # don't hide issues in CI runs because they are the same type
|
||||||
|
exclude-dirs:
|
||||||
|
- internal/gojsonschema
|
||||||
|
- internal/gqlparser
|
||||||
|
- internal/jwx
|
||||||
exclude-rules:
|
exclude-rules:
|
||||||
- path: ast/
|
- path: ast/
|
||||||
linters:
|
linters:
|
||||||
@@ -140,6 +144,37 @@ issues:
|
|||||||
linters-settings:
|
linters-settings:
|
||||||
lll:
|
lll:
|
||||||
line-length: 200
|
line-length: 200
|
||||||
|
gocritic:
|
||||||
|
disabled-checks:
|
||||||
|
- appendAssign
|
||||||
|
# NOTE(ae): this one should be enabled, but there were too
|
||||||
|
# many violations to fix in one go... revisit later
|
||||||
|
- singleCaseSwitch
|
||||||
|
# Reasonable rule, but not sure what to replace with in
|
||||||
|
# many locations, so disabling for now
|
||||||
|
- exitAfterDefer
|
||||||
|
# The following 3 rules are disabled from the perfomance tag
|
||||||
|
# enabled further down. The first two are reasonable, but not
|
||||||
|
# super important. appendCombine is really nice though! And
|
||||||
|
# should be enabled. Just many places to fix..
|
||||||
|
- hugeParam
|
||||||
|
- preferFprint
|
||||||
|
- appendCombine
|
||||||
|
enabled-checks:
|
||||||
|
# NOTE that these are rules enabled in addition to the default set
|
||||||
|
- filepathJoin
|
||||||
|
- dupImport
|
||||||
|
- redundantSprint
|
||||||
|
- stringConcatSimplify
|
||||||
|
enabled-tags:
|
||||||
|
- performance
|
||||||
|
settings:
|
||||||
|
ifElseChain:
|
||||||
|
# ridiculous value set for now, but this should be
|
||||||
|
# lowered to something more reasonable, as the rule
|
||||||
|
# is reasonable (replace long if-else chains with
|
||||||
|
# switch)... just too many violations right now
|
||||||
|
minThreshold: 10
|
||||||
govet:
|
govet:
|
||||||
enable:
|
enable:
|
||||||
- deepequalerrors
|
- deepequalerrors
|
||||||
@@ -175,4 +210,5 @@ linters:
|
|||||||
- unconvert
|
- unconvert
|
||||||
- copyloopvar
|
- copyloopvar
|
||||||
- perfsprint
|
- perfsprint
|
||||||
|
- gocritic
|
||||||
# - gosec # too many false positives
|
# - gosec # too many false positives
|
||||||
|
|||||||
+2
-4
@@ -66,10 +66,8 @@ func TestCompile_DefaultRegoVersion(t *testing.T) {
|
|||||||
|
|
||||||
if len(tc.expErrs) > 0 {
|
if len(tc.expErrs) > 0 {
|
||||||
assertErrors(t, compiler.Errors, tc.expErrs)
|
assertErrors(t, compiler.Errors, tc.expErrs)
|
||||||
} else {
|
} else if len(compiler.Errors) > 0 {
|
||||||
if len(compiler.Errors) > 0 {
|
t.Fatalf("Unexpected errors: %v", compiler.Errors)
|
||||||
t.Fatalf("Unexpected errors: %v", compiler.Errors)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -108,10 +108,8 @@ func TestCompileModules_DefaultRegoVersion(t *testing.T) {
|
|||||||
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
t.Fatalf("Unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -216,10 +214,8 @@ func TestCompileModulesWithOpt_DefaultRegoVersion(t *testing.T) {
|
|||||||
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
t.Fatalf("Unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -21,7 +21,7 @@ func TestParser_DefaultRegoVersion(t *testing.T) {
|
|||||||
p[x] {
|
p[x] {
|
||||||
c = ["a", "b", "c"][i]
|
c = ["a", "b", "c"][i]
|
||||||
}`,
|
}`,
|
||||||
expStmtCount: 2, //package, p
|
expStmtCount: 2, // package, p
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
note: "v1",
|
note: "v1",
|
||||||
@@ -30,7 +30,7 @@ p contains x if {
|
|||||||
c = ["a", "b", "c"][i]
|
c = ["a", "b", "c"][i]
|
||||||
}`,
|
}`,
|
||||||
// v1 Keywords are not recognized, and interpreted as individual statements
|
// v1 Keywords are not recognized, and interpreted as individual statements
|
||||||
expStmtCount: 5, //package, p, contains, x, if
|
expStmtCount: 5, // package, p, contains, x, if
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ func main() {
|
|||||||
|
|
||||||
err = doc.GenMarkdownTree(command, dir)
|
err = doc.GenMarkdownTree(command, dir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err) //nolint: gocritic
|
||||||
}
|
}
|
||||||
|
|
||||||
files, err := os.ReadDir(dir)
|
files, err := os.ReadDir(dir)
|
||||||
|
|||||||
@@ -86,18 +86,6 @@ func TestHasRootsOverlap(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//err := hasRootsOverlap(ctx, mockStore, txn, bundles)
|
|
||||||
//if !tc.overlaps && err != nil {
|
|
||||||
// t.Fatalf("unepected error: %s", err)
|
|
||||||
//} else if tc.overlaps && (err == nil || !strings.Contains(err.Error(), "detected overlapping roots in bundle manifest")) {
|
|
||||||
// t.Fatalf("expected overlapping roots error, got: %s", err)
|
|
||||||
//}
|
|
||||||
|
|
||||||
//err = mockStore.Commit(ctx, txn)
|
|
||||||
//if err != nil {
|
|
||||||
// t.Fatalf("unexpected error: %s", err)
|
|
||||||
//}
|
|
||||||
|
|
||||||
mockStore.AssertValid(t)
|
mockStore.AssertValid(t)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -175,7 +175,7 @@ func TestRunBenchmarkE2EWithOPAConfigFile(t *testing.T) {
|
|||||||
|
|
||||||
params := testBenchParams()
|
params := testBenchParams()
|
||||||
params.e2e = true
|
params.e2e = true
|
||||||
params.configFile = filepath.Join(testDirRoot, "/config.yaml")
|
params.configFile = filepath.Join(testDirRoot, "config.yaml")
|
||||||
|
|
||||||
args := []string{"1 + 1"}
|
args := []string{"1 + 1"}
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
@@ -580,7 +580,7 @@ func TestBenchMainInvalidInputFile(t *testing.T) {
|
|||||||
}
|
}
|
||||||
args := []string{"1+1"}
|
args := []string{"1+1"}
|
||||||
test.WithTempFS(files, func(path string) {
|
test.WithTempFS(files, func(path string) {
|
||||||
params.inputPath = filepath.Join(path, "definitely/not/input.yaml")
|
params.inputPath = filepath.Join(path, "definitely", "not", "input.yaml")
|
||||||
|
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
|
|
||||||
@@ -662,7 +662,7 @@ func TestBenchMainInvalidInputFileE2E(t *testing.T) {
|
|||||||
}
|
}
|
||||||
args := []string{"1+1"}
|
args := []string{"1+1"}
|
||||||
test.WithTempFS(files, func(path string) {
|
test.WithTempFS(files, func(path string) {
|
||||||
params.inputPath = filepath.Join(path, "definitely/not/input.yaml")
|
params.inputPath = filepath.Join(path, "definitely", "not", "input.yaml")
|
||||||
|
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -190,7 +190,7 @@ import rego.v1`,
|
|||||||
for i := range tests {
|
for i := range tests {
|
||||||
tc := tests[i]
|
tc := tests[i]
|
||||||
tc.bundleMode = true
|
tc.bundleMode = true
|
||||||
tc.note = tc.note + " (as bundle)"
|
tc.note += " (as bundle)"
|
||||||
tests = append(tests, tc)
|
tests = append(tests, tc)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -149,7 +149,7 @@ import rego.v1`,
|
|||||||
for i := range tests {
|
for i := range tests {
|
||||||
tc := tests[i]
|
tc := tests[i]
|
||||||
tc.bundleMode = true
|
tc.bundleMode = true
|
||||||
tc.note = tc.note + " (as bundle)"
|
tc.note += " (as bundle)"
|
||||||
tests = append(tests, tc)
|
tests = append(tests, tc)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+6
-12
@@ -70,10 +70,8 @@ a contains x if {
|
|||||||
t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error())
|
t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
t.Fatalf("Unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -249,10 +247,8 @@ p contains 3 if {
|
|||||||
t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error())
|
t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
t.Fatalf("Unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -566,10 +562,8 @@ p contains 4 if {
|
|||||||
t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error())
|
t.Fatalf("Expected error:\n\n%s\n\ngot:\n\n%s", expErr, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
t.Fatalf("Unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
+2
-4
@@ -680,10 +680,8 @@ p contains v if {
|
|||||||
t.Fatalf("Expected error:\n\n%v\n\nbut got:\n\n%v", expErr, err.Error())
|
t.Fatalf("Expected error:\n\n%v\n\nbut got:\n\n%v", expErr, err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
Vendored
+1
-1
@@ -33,7 +33,7 @@ func (cf cmdFlagsImpl) CheckEnvironmentVariables(command *cobra.Command) error {
|
|||||||
}
|
}
|
||||||
command.Flags().VisitAll(func(f *pflag.Flag) {
|
command.Flags().VisitAll(func(f *pflag.Flag) {
|
||||||
configName := f.Name
|
configName := f.Name
|
||||||
configName = strings.Replace(configName, "-", "_", -1)
|
configName = strings.ReplaceAll(configName, "-", "_")
|
||||||
if !f.Changed && v.IsSet(configName) {
|
if !f.Changed && v.IsSet(configName) {
|
||||||
val := v.Get(configName)
|
val := v.Get(configName)
|
||||||
err := command.Flags().Set(f.Name, fmt.Sprintf("%v", val))
|
err := command.Flags().Set(f.Name, fmt.Sprintf("%v", val))
|
||||||
|
|||||||
@@ -237,7 +237,7 @@ func TestExec(t *testing.T) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
err := Exec(ctx, opa, params)
|
err := Exec(ctx, opa, params)
|
||||||
output := strings.Replace(buf.String(), dir, "%ROOT%", -1)
|
output := strings.ReplaceAll(buf.String(), dir, "%ROOT%")
|
||||||
tt.assertion(t, output, err)
|
tt.assertion(t, output, err)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
+10
-14
@@ -144,7 +144,7 @@ p = 1
|
|||||||
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedOutput := strings.Replace(`{
|
expectedOutput := strings.ReplaceAll(`{
|
||||||
"package": {
|
"package": {
|
||||||
"location": {
|
"location": {
|
||||||
"file": "TEMPDIR/x.rego",
|
"file": "TEMPDIR/x.rego",
|
||||||
@@ -238,7 +238,7 @@ p = 1
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
`, "TEMPDIR", tempDirPath, -1)
|
`, "TEMPDIR", tempDirPath)
|
||||||
|
|
||||||
gotLines := strings.Split(string(stdout), "\n")
|
gotLines := strings.Split(string(stdout), "\n")
|
||||||
wantLines := strings.Split(expectedOutput, "\n")
|
wantLines := strings.Split(expectedOutput, "\n")
|
||||||
@@ -350,7 +350,7 @@ a.b.c := true
|
|||||||
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedOutput := strings.Replace(`{
|
expectedOutput := strings.ReplaceAll(`{
|
||||||
"package": {
|
"package": {
|
||||||
"location": {
|
"location": {
|
||||||
"file": "TEMPDIR/x.rego",
|
"file": "TEMPDIR/x.rego",
|
||||||
@@ -464,7 +464,7 @@ a.b.c := true
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
`, "TEMPDIR", tempDirPath, -1)
|
`, "TEMPDIR", tempDirPath)
|
||||||
|
|
||||||
gotLines := strings.Split(string(stdout), "\n")
|
gotLines := strings.Split(string(stdout), "\n")
|
||||||
wantLines := strings.Split(expectedOutput, "\n")
|
wantLines := strings.Split(expectedOutput, "\n")
|
||||||
@@ -508,7 +508,7 @@ allow = true if {
|
|||||||
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
||||||
}
|
}
|
||||||
|
|
||||||
expectedOutput := strings.Replace(`{
|
expectedOutput := strings.ReplaceAll(`{
|
||||||
"package": {
|
"package": {
|
||||||
"location": {
|
"location": {
|
||||||
"file": "TEMPDIR/x.rego",
|
"file": "TEMPDIR/x.rego",
|
||||||
@@ -925,7 +925,7 @@ allow = true if {
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
`, "TEMPDIR", tempDirPath, -1)
|
`, "TEMPDIR", tempDirPath)
|
||||||
|
|
||||||
gotLines := strings.Split(string(stdout), "\n")
|
gotLines := strings.Split(string(stdout), "\n")
|
||||||
wantLines := strings.Split(expectedOutput, "\n")
|
wantLines := strings.Split(expectedOutput, "\n")
|
||||||
@@ -1015,10 +1015,8 @@ a contains x if {
|
|||||||
t.Fatalf("Expected error:\n\n%q\n\ngot:\n\n%s", expErr, errs)
|
t.Fatalf("Expected error:\n\n%q\n\ngot:\n\n%s", expErr, errs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if len(stderr) > 0 {
|
||||||
if len(stderr) > 0 {
|
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
||||||
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1172,10 +1170,8 @@ p contains v if {
|
|||||||
t.Fatalf("Expected error:\n\n%q\n\ngot:\n\n%s", expErr, errs)
|
t.Fatalf("Expected error:\n\n%q\n\ngot:\n\n%s", expErr, errs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if len(stderr) > 0 {
|
||||||
if len(stderr) > 0 {
|
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
||||||
t.Fatalf("Expected no stderr output, got:\n%s\n", string(stderr))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-4
@@ -176,10 +176,8 @@ func TestValidateSignParams(t *testing.T) {
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -386,10 +386,8 @@ p contains "B" if {
|
|||||||
t.Fatalf("expected error to contain:\n\n%s\n\ngot:\n\n%v", expErr, err)
|
t.Fatalf("expected error to contain:\n\n%s\n\ngot:\n\n%v", expErr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatal(err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -54,8 +54,8 @@ func TestGenerateBundleInfoWithFileDir(t *testing.T) {
|
|||||||
expectedNamespaces := map[string][]string{
|
expectedNamespaces := map[string][]string{
|
||||||
"data": {filepath.Join(rootDir, "data.json")},
|
"data": {filepath.Join(rootDir, "data.json")},
|
||||||
"data.bar": {filepath.Join(rootDir, "base.rego")},
|
"data.bar": {filepath.Join(rootDir, "base.rego")},
|
||||||
"data.foo": {filepath.Join(rootDir, "baz/authz.rego"), filepath.Join(rootDir, "foo/policy.rego")},
|
"data.foo": {filepath.Join(rootDir, "baz", "authz.rego"), filepath.Join(rootDir, "foo", "policy.rego")},
|
||||||
"data.fuz": {filepath.Join(rootDir, "fuz/fuz.rego"), filepath.Join(rootDir, "fuz/data.json")},
|
"data.fuz": {filepath.Join(rootDir, "fuz", "fuz.rego"), filepath.Join(rootDir, "fuz", "data.json")},
|
||||||
}
|
}
|
||||||
|
|
||||||
if !reflect.DeepEqual(info.Namespaces, expectedNamespaces) {
|
if !reflect.DeepEqual(info.Namespaces, expectedNamespaces) {
|
||||||
@@ -253,7 +253,7 @@ func TestGenerateBundleInfoWithBundleTarGz(t *testing.T) {
|
|||||||
expectedWasmModules := []map[string]interface{}{}
|
expectedWasmModules := []map[string]interface{}{}
|
||||||
expectedWasmModule1 := map[string]interface{}{
|
expectedWasmModule1 := map[string]interface{}{
|
||||||
"path": "/example/policy.wasm",
|
"path": "/example/policy.wasm",
|
||||||
"url": filepath.Join(bundleFile, "/example/policy.wasm"),
|
"url": filepath.Join(bundleFile, "example", "policy.wasm"),
|
||||||
"entrypoints": []string{"data.http.example.foo.allow"},
|
"entrypoints": []string{"data.http.example.foo.allow"},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -98,7 +98,7 @@ func LoadBundleFromDiskForRegoVersion(regoVersion ast.RegoVersion, path, name st
|
|||||||
|
|
||||||
_, err := os.Stat(bundlePath)
|
_, err := os.Stat(bundlePath)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
f, err := os.Open(filepath.Join(bundlePath))
|
f, err := os.Open(bundlePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ func GetAddressRange(ipNet net.IPNet) (net.IP, net.IP) {
|
|||||||
copy(lastIPMask, ipNet.Mask)
|
copy(lastIPMask, ipNet.Mask)
|
||||||
for i := range lastIPMask {
|
for i := range lastIPMask {
|
||||||
lastIPMask[len(lastIPMask)-i-1] = ^lastIPMask[len(lastIPMask)-i-1]
|
lastIPMask[len(lastIPMask)-i-1] = ^lastIPMask[len(lastIPMask)-i-1]
|
||||||
lastIP[net.IPv6len-i-1] = lastIP[net.IPv6len-i-1] | lastIPMask[len(lastIPMask)-i-1]
|
lastIP[net.IPv6len-i-1] |= lastIPMask[len(lastIPMask)-i-1]
|
||||||
}
|
}
|
||||||
|
|
||||||
return firstIP, lastIP
|
return firstIP, lastIP
|
||||||
|
|||||||
@@ -127,10 +127,8 @@ func TestVerifyAuthorizationPolicySchema(t *testing.T) {
|
|||||||
t.Errorf("Expected error %v not found", e)
|
t.Errorf("Expected error %v not found", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -340,7 +340,7 @@ func (c *Compiler) initModule() error {
|
|||||||
// two times. But let's deal with that when it happens.
|
// two times. But let's deal with that when it happens.
|
||||||
if _, ok := c.funcs[name]; ok { // already seen
|
if _, ok := c.funcs[name]; ok { // already seen
|
||||||
c.debug.Printf("function name duplicate: %s (%d)", name, fn.Index)
|
c.debug.Printf("function name duplicate: %s (%d)", name, fn.Index)
|
||||||
name = name + ".1"
|
name += ".1"
|
||||||
}
|
}
|
||||||
c.funcs[name] = fn.Index
|
c.funcs[name] = fn.Index
|
||||||
}
|
}
|
||||||
@@ -348,7 +348,7 @@ func (c *Compiler) initModule() error {
|
|||||||
for _, fn := range c.policy.Funcs.Funcs {
|
for _, fn := range c.policy.Funcs.Funcs {
|
||||||
|
|
||||||
params := make([]types.ValueType, len(fn.Params))
|
params := make([]types.ValueType, len(fn.Params))
|
||||||
for i := 0; i < len(params); i++ {
|
for i := range params {
|
||||||
params[i] = types.I32
|
params[i] = types.I32
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -996,12 +996,16 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err
|
|||||||
for _, stmt := range block.Stmts {
|
for _, stmt := range block.Stmts {
|
||||||
switch stmt := stmt.(type) {
|
switch stmt := stmt.(type) {
|
||||||
case *ir.ResultSetAddStmt:
|
case *ir.ResultSetAddStmt:
|
||||||
instrs = append(instrs, instruction.GetLocal{Index: c.lrs})
|
instrs = append(instrs,
|
||||||
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Value)})
|
instruction.GetLocal{Index: c.lrs},
|
||||||
instrs = append(instrs, instruction.Call{Index: c.function(opaSetAdd)})
|
instruction.GetLocal{Index: c.local(stmt.Value)},
|
||||||
|
instruction.Call{Index: c.function(opaSetAdd)},
|
||||||
|
)
|
||||||
case *ir.ReturnLocalStmt:
|
case *ir.ReturnLocalStmt:
|
||||||
instrs = append(instrs, instruction.GetLocal{Index: c.local(stmt.Source)})
|
instrs = append(instrs,
|
||||||
instrs = append(instrs, instruction.Return{})
|
instruction.GetLocal{Index: c.local(stmt.Source)},
|
||||||
|
instruction.Return{},
|
||||||
|
)
|
||||||
case *ir.BlockStmt:
|
case *ir.BlockStmt:
|
||||||
for i := range stmt.Blocks {
|
for i := range stmt.Blocks {
|
||||||
block, err := c.compileBlock(stmt.Blocks[i])
|
block, err := c.compileBlock(stmt.Blocks[i])
|
||||||
@@ -1029,8 +1033,10 @@ func (c *Compiler) compileBlock(block *ir.Block) ([]instruction.Instruction, err
|
|||||||
return instrs, err
|
return instrs, err
|
||||||
}
|
}
|
||||||
case *ir.AssignVarStmt:
|
case *ir.AssignVarStmt:
|
||||||
instrs = append(instrs, c.instrRead(stmt.Source))
|
instrs = append(instrs,
|
||||||
instrs = append(instrs, instruction.SetLocal{Index: c.local(stmt.Target)})
|
c.instrRead(stmt.Source),
|
||||||
|
instruction.SetLocal{Index: c.local(stmt.Target)},
|
||||||
|
)
|
||||||
case *ir.AssignVarOnceStmt:
|
case *ir.AssignVarOnceStmt:
|
||||||
instrs = append(instrs, instruction.Block{
|
instrs = append(instrs, instruction.Block{
|
||||||
Instrs: []instruction.Instruction{
|
Instrs: []instruction.Instruction{
|
||||||
@@ -1535,8 +1541,7 @@ func (c *Compiler) compileExternalCall(stmt *ir.CallStmt, ef externalFunc, resul
|
|||||||
}
|
}
|
||||||
|
|
||||||
instrs := *result
|
instrs := *result
|
||||||
instrs = append(instrs, instruction.I32Const{Value: ef.ID})
|
instrs = append(instrs, instruction.I32Const{Value: ef.ID}, instruction.I32Const{Value: 0}) // unused context parameter
|
||||||
instrs = append(instrs, instruction.I32Const{Value: 0}) // unused context parameter
|
|
||||||
|
|
||||||
for _, arg := range stmt.Args {
|
for _, arg := range stmt.Args {
|
||||||
instrs = append(instrs, c.instrRead(arg))
|
instrs = append(instrs, c.instrRead(arg))
|
||||||
@@ -1545,9 +1550,11 @@ func (c *Compiler) compileExternalCall(stmt *ir.CallStmt, ef externalFunc, resul
|
|||||||
instrs = append(instrs, instruction.Call{Index: c.function(builtinDispatchers[len(stmt.Args)])})
|
instrs = append(instrs, instruction.Call{Index: c.function(builtinDispatchers[len(stmt.Args)])})
|
||||||
|
|
||||||
if ef.Decl.Result() != nil {
|
if ef.Decl.Result() != nil {
|
||||||
instrs = append(instrs, instruction.TeeLocal{Index: c.local(stmt.Result)})
|
instrs = append(instrs,
|
||||||
instrs = append(instrs, instruction.I32Eqz{})
|
instruction.TeeLocal{Index: c.local(stmt.Result)},
|
||||||
instrs = append(instrs, instruction.BrIf{Index: 0})
|
instruction.I32Eqz{},
|
||||||
|
instruction.BrIf{Index: 0},
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
instrs = append(instrs, instruction.Drop{})
|
instrs = append(instrs, instruction.Drop{})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -306,7 +306,7 @@ discovery:
|
|||||||
`}
|
`}
|
||||||
|
|
||||||
test.WithTempFS(fs, func(rootDir string) {
|
test.WithTempFS(fs, func(rootDir string) {
|
||||||
configFile := filepath.Join(rootDir, "/some/config.yaml")
|
configFile := filepath.Join(rootDir, "some", "config.yaml")
|
||||||
configOverrides := []string{"services.acmecorp.credentials.bearer.token=bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm"}
|
configOverrides := []string{"services.acmecorp.credentials.bearer.token=bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm"}
|
||||||
|
|
||||||
configBytes, err := Load(configFile, configOverrides, nil)
|
configBytes, err := Load(configFile, configOverrides, nil)
|
||||||
@@ -361,8 +361,8 @@ discovery:
|
|||||||
}
|
}
|
||||||
|
|
||||||
test.WithTempFS(fs, func(rootDir string) {
|
test.WithTempFS(fs, func(rootDir string) {
|
||||||
configFile := filepath.Join(rootDir, "/some/config.yaml")
|
configFile := filepath.Join(rootDir, "some", "config.yaml")
|
||||||
secretFile := filepath.Join(rootDir, "/some/secret.txt")
|
secretFile := filepath.Join(rootDir, "some", "secret.txt")
|
||||||
overrideFiles := []string{"services.acmecorp.credentials.bearer.token=" + secretFile}
|
overrideFiles := []string{"services.acmecorp.credentials.bearer.token=" + secretFile}
|
||||||
|
|
||||||
configBytes, err := Load(configFile, nil, overrideFiles)
|
configBytes, err := Load(configFile, nil, overrideFiles)
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ func Init(ctx context.Context, raw []byte, id string) (*otlptrace.Exporter, *tra
|
|||||||
return nil, nil, nil, err
|
return nil, nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.ToLower(distributedTracingConfig.Type) != "grpc" {
|
if !strings.EqualFold(distributedTracingConfig.Type, "grpc") {
|
||||||
return nil, nil, nil, nil
|
return nil, nil, nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ func (vector *BitVector) Length() int {
|
|||||||
// position of the last byte in the slice.
|
// position of the last byte in the slice.
|
||||||
// This returns the bit that was shifted off of the last byte.
|
// This returns the bit that was shifted off of the last byte.
|
||||||
func shiftLower(bit byte, b []byte) byte {
|
func shiftLower(bit byte, b []byte) byte {
|
||||||
bit = bit << 7
|
bit <<= 7
|
||||||
for i := len(b) - 1; i >= 0; i-- {
|
for i := len(b) - 1; i >= 0; i-- {
|
||||||
newByte := b[i] >> 1
|
newByte := b[i] >> 1
|
||||||
newByte |= bit
|
newByte |= bit
|
||||||
|
|||||||
@@ -1180,5 +1180,5 @@ func (e *EditTree) Filter(paths []ast.Ref) *ast.Term {
|
|||||||
type termSlice []*ast.Term
|
type termSlice []*ast.Term
|
||||||
|
|
||||||
func (s termSlice) Less(i, j int) bool { return ast.Compare(s[i].Value, s[j].Value) < 0 }
|
func (s termSlice) Less(i, j int) bool { return ast.Compare(s[i].Value, s[j].Value) < 0 }
|
||||||
func (s termSlice) Swap(i, j int) { x := s[i]; s[i] = s[j]; s[j] = x }
|
func (s termSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||||
func (s termSlice) Len() int { return len(s) }
|
func (s termSlice) Len() int { return len(s) }
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ func Test(t *testing.T, filename string, f func(t *testing.T, input string) Spec
|
|||||||
for i, tok := range result.Tokens {
|
for i, tok := range result.Tokens {
|
||||||
expected := spec.Tokens[i]
|
expected := spec.Tokens[i]
|
||||||
|
|
||||||
if !strings.EqualFold(strings.Replace(expected.Kind, "_", "", -1), tok.Kind) {
|
if !strings.EqualFold(strings.ReplaceAll(expected.Kind, "_", ""), tok.Kind) {
|
||||||
t.Errorf("token[%d].kind should be %s, was %s", i, expected.Kind, tok.Kind)
|
t.Errorf("token[%d].kind should be %s, was %s", i, expected.Kind, tok.Kind)
|
||||||
}
|
}
|
||||||
if expected.Value != "undefined" && expected.Value != tok.Value {
|
if expected.Value != "undefined" && expected.Value != tok.Value {
|
||||||
|
|||||||
@@ -159,8 +159,6 @@ func unexpectedTypeMessageOnly(v *ast.Value) ErrorOption {
|
|||||||
return Message(`Float cannot represent non numeric value: %s`, v.String())
|
return Message(`Float cannot represent non numeric value: %s`, v.String())
|
||||||
case "ID", "ID!":
|
case "ID", "ID!":
|
||||||
return Message(`ID cannot represent a non-string and non-integer value: %s`, v.String())
|
return Message(`ID cannot represent a non-string and non-integer value: %s`, v.String())
|
||||||
//case "Enum":
|
|
||||||
// return Message(`Enum "%s" cannot represent non-enum value: %s`, v.ExpectedType.String(), v.String())
|
|
||||||
default:
|
default:
|
||||||
if v.Definition.Kind == ast.Enum {
|
if v.Definition.Kind == ast.Enum {
|
||||||
return Message(`Enum "%s" cannot represent non-enum value: %s.`, v.ExpectedType.String(), v.String())
|
return Message(`Enum "%s" cannot represent non-enum value: %s.`, v.ExpectedType.String(), v.String())
|
||||||
|
|||||||
@@ -223,7 +223,7 @@ func (v *varValidator) validateVarType(typ *ast.Type, val reflect.Value) (reflec
|
|||||||
if fieldDef.Type.NonNull && field.IsNil() {
|
if fieldDef.Type.NonNull && field.IsNil() {
|
||||||
return val, gqlerror.ErrorPathf(v.path, "cannot be null")
|
return val, gqlerror.ErrorPathf(v.path, "cannot be null")
|
||||||
}
|
}
|
||||||
//allow null object field and skip it
|
// allow null object field and skip it
|
||||||
if !fieldDef.Type.NonNull && field.IsNil() {
|
if !fieldDef.Type.NonNull && field.IsNil() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ func ParsePatchPathEscaped(str string) (path storage.Path, ok bool) {
|
|||||||
// the substitutions in this order, an implementation avoids the error of
|
// the substitutions in this order, an implementation avoids the error of
|
||||||
// turning '~01' first into '~1' and then into '/', which would be
|
// turning '~01' first into '~1' and then into '/', which would be
|
||||||
// incorrect (the string '~01' correctly becomes '~1' after transformation)."
|
// incorrect (the string '~01' correctly becomes '~1' after transformation)."
|
||||||
path[i] = strings.Replace(path[i], "~1", "/", -1)
|
path[i] = strings.ReplaceAll(path[i], "~1", "/")
|
||||||
path[i] = strings.Replace(path[i], "~0", "~", -1)
|
path[i] = strings.ReplaceAll(path[i], "~0", "~")
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ func parse(jwkSrc string) (*Set, error) {
|
|||||||
|
|
||||||
// ParseBytes parses JWK from the incoming byte buffer.
|
// ParseBytes parses JWK from the incoming byte buffer.
|
||||||
func ParseBytes(buf []byte) (*Set, error) {
|
func ParseBytes(buf []byte) (*Set, error) {
|
||||||
return parse(string(buf[:]))
|
return parse(string(buf))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseString parses JWK from the incoming string.
|
// ParseString parses JWK from the incoming string.
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ func Verify(buf []byte, alg jwa.SignatureAlgorithm, key interface{}) (ret []byte
|
|||||||
return nil, errors.New(`attempt to verify empty buffer`)
|
return nil, errors.New(`attempt to verify empty buffer`)
|
||||||
}
|
}
|
||||||
|
|
||||||
parts, err := SplitCompact(string(buf[:]))
|
parts, err := SplitCompact(string(buf))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed extract from compact serialization format: %w", err)
|
return nil, fmt.Errorf("failed extract from compact serialization format: %w", err)
|
||||||
}
|
}
|
||||||
@@ -164,7 +164,7 @@ func VerifyWithJWKSet(buf []byte, keyset *jwk.Set) (payload []byte, err error) {
|
|||||||
|
|
||||||
// ParseByte parses a JWS value serialized via compact serialization and provided as []byte.
|
// ParseByte parses a JWS value serialized via compact serialization and provided as []byte.
|
||||||
func ParseByte(jwsCompact []byte) (m *Message, err error) {
|
func ParseByte(jwsCompact []byte) (m *Message, err error) {
|
||||||
return parseCompact(string(jwsCompact[:]))
|
return parseCompact(string(jwsCompact))
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseString parses a JWS value serialized via compact serialization and provided as string.
|
// ParseString parses a JWS value serialized via compact serialization and provided as string.
|
||||||
|
|||||||
@@ -336,7 +336,7 @@ func TestEncode(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Verify with standard ecdsa library
|
// Verify with standard ecdsa library
|
||||||
parts, err := jws.SplitCompact(string(jwsCompact[:]))
|
parts, err := jws.SplitCompact(string(jwsCompact))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal("Failed to split compact JWT")
|
t.Fatal("Failed to split compact JWT")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -497,7 +497,6 @@ func (p *Planner) planDotOr(obj ir.Local, key ir.Operand, or stmtFactory, iter p
|
|||||||
|
|
||||||
func (p *Planner) planNestedObjects(obj ir.Local, ref ast.Ref, iter planLocalIter) error {
|
func (p *Planner) planNestedObjects(obj ir.Local, ref ast.Ref, iter planLocalIter) error {
|
||||||
if len(ref) == 0 {
|
if len(ref) == 0 {
|
||||||
//return fmt.Errorf("nested object construction didn't create object")
|
|
||||||
return iter(obj)
|
return iter(obj)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -991,8 +990,7 @@ func (p *Planner) planExprCall(e *ast.Expr, iter planiter) error {
|
|||||||
op := e.Operator()
|
op := e.Operator()
|
||||||
|
|
||||||
if replacement := p.mocks.Lookup(operator); replacement != nil {
|
if replacement := p.mocks.Lookup(operator); replacement != nil {
|
||||||
switch r := replacement.Value.(type) {
|
if r, ok := replacement.Value.(ast.Ref); ok {
|
||||||
case ast.Ref:
|
|
||||||
if !r.HasPrefix(ast.DefaultRootRef) && !r.HasPrefix(ast.InputRootRef) {
|
if !r.HasPrefix(ast.DefaultRootRef) && !r.HasPrefix(ast.InputRootRef) {
|
||||||
// replacement is builtin
|
// replacement is builtin
|
||||||
operator = r.String()
|
operator = r.String()
|
||||||
|
|||||||
@@ -492,7 +492,7 @@ func prettyASTNode(x interface{}, regoVersion ast.RegoVersion) (string, int, err
|
|||||||
return "", 0, fmt.Errorf("format error: %w", err)
|
return "", 0, fmt.Errorf("format error: %w", err)
|
||||||
}
|
}
|
||||||
var maxLineWidth int
|
var maxLineWidth int
|
||||||
s := strings.Trim(strings.Replace(string(bs), "\t", " ", -1), "\n")
|
s := strings.Trim(strings.ReplaceAll(string(bs), "\t", " "), "\n")
|
||||||
for _, line := range strings.Split(s, "\n") {
|
for _, line := range strings.Split(s, "\n") {
|
||||||
width := tablewriter.DisplayWidth(line)
|
width := tablewriter.DisplayWidth(line)
|
||||||
if width > maxLineWidth {
|
if width > maxLineWidth {
|
||||||
|
|||||||
@@ -216,7 +216,7 @@ func (s *httpSigner) Build() (signedRequest, error) {
|
|||||||
|
|
||||||
signedHeaders, signedHeadersStr, canonicalHeaderStr := s.buildCanonicalHeaders(host, v4Internal.IgnoredHeaders, unsignedHeaders, s.Request.ContentLength)
|
signedHeaders, signedHeadersStr, canonicalHeaderStr := s.buildCanonicalHeaders(host, v4Internal.IgnoredHeaders, unsignedHeaders, s.Request.ContentLength)
|
||||||
|
|
||||||
rawQuery := strings.Replace(query.Encode(), "+", "%20", -1)
|
rawQuery := strings.ReplaceAll(query.Encode(), "+", "%20")
|
||||||
|
|
||||||
canonicalURI := v4Internal.GetURIPath(req.URL)
|
canonicalURI := v4Internal.GetURIPath(req.URL)
|
||||||
|
|
||||||
|
|||||||
@@ -434,8 +434,7 @@ func TestWalkPaths(t *testing.T) {
|
|||||||
test.WithTempFS(files, func(rootDir string) {
|
test.WithTempFS(files, func(rootDir string) {
|
||||||
|
|
||||||
paths := []string{}
|
paths := []string{}
|
||||||
paths = append(paths, filepath.Join(rootDir, "bundle1"))
|
paths = append(paths, filepath.Join(rootDir, "bundle1"), filepath.Join(rootDir, "bundle2"))
|
||||||
paths = append(paths, filepath.Join(rootDir, "bundle2"))
|
|
||||||
|
|
||||||
// bundle mode
|
// bundle mode
|
||||||
loaded, err := WalkPaths(paths, nil, true)
|
loaded, err := WalkPaths(paths, nil, true)
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ func TruncateFilePaths(maxIdealWidth, maxWidth int, path ...string) (map[string]
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Drop the overall length down to match our substitution
|
// Drop the overall length down to match our substitution
|
||||||
longestLocation = longestLocation - (len(lcs) - 3)
|
longestLocation -= (len(lcs) - 3)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, longestLocation
|
return result, longestLocation
|
||||||
|
|||||||
@@ -148,8 +148,6 @@ func (t *parser) key(data map[string]interface{}) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return fmt.Errorf("key %q has no value", string(k))
|
return fmt.Errorf("key %q has no value", string(k))
|
||||||
//set(data, string(k), "")
|
|
||||||
//return err
|
|
||||||
case last == '[':
|
case last == '[':
|
||||||
// We are in a list index context, so we need to set an index.
|
// We are in a list index context, so we need to set an index.
|
||||||
i, err := t.keyIndex()
|
i, err := t.keyIndex()
|
||||||
@@ -168,7 +166,7 @@ func (t *parser) key(data map[string]interface{}) error {
|
|||||||
set(data, kk, list)
|
set(data, kk, list)
|
||||||
return err
|
return err
|
||||||
case last == '=':
|
case last == '=':
|
||||||
//End of key. Consume =, Get value.
|
// End of key. Consume =, Get value.
|
||||||
// FIXME: Get value list first
|
// FIXME: Get value list first
|
||||||
vl, e := t.valList()
|
vl, e := t.valList()
|
||||||
switch e {
|
switch e {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ limitations under the License.
|
|||||||
package strvals
|
package strvals
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"sigs.k8s.io/yaml"
|
"sigs.k8s.io/yaml"
|
||||||
@@ -382,7 +383,7 @@ func TestParseSet(t *testing.T) {
|
|||||||
t.Fatalf("Error serializing parsed value: %s", err)
|
t.Fatalf("Error serializing parsed value: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if string(y1) != string(y2) {
|
if !bytes.Equal(y1, y2) {
|
||||||
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
|
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -407,7 +408,7 @@ func TestParseSet(t *testing.T) {
|
|||||||
t.Fatalf("Error serializing parsed value: %s", err)
|
t.Fatalf("Error serializing parsed value: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if string(y1) != string(y2) {
|
if !bytes.Equal(y1, y2) {
|
||||||
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
|
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -443,7 +444,7 @@ func TestParseInto(t *testing.T) {
|
|||||||
t.Fatalf("Error serializing parsed value: %s", err)
|
t.Fatalf("Error serializing parsed value: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if string(y1) != string(y2) {
|
if !bytes.Equal(y1, y2) {
|
||||||
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
|
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -476,7 +477,7 @@ func TestParseIntoString(t *testing.T) {
|
|||||||
t.Fatalf("Error serializing parsed value: %s", err)
|
t.Fatalf("Error serializing parsed value: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if string(y1) != string(y2) {
|
if !bytes.Equal(y1, y2) {
|
||||||
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
|
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -509,7 +510,7 @@ func TestParseIntoFile(t *testing.T) {
|
|||||||
t.Fatalf("Error serializing parsed value: %s", err)
|
t.Fatalf("Error serializing parsed value: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if string(y1) != string(y2) {
|
if !bytes.Equal(y1, y2) {
|
||||||
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
|
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -330,8 +330,7 @@ func scopeCompare(s1, s2 string) int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func scopeOrder(s string) int {
|
func scopeOrder(s string) int {
|
||||||
switch s {
|
if s == annotationScopeRule {
|
||||||
case annotationScopeRule:
|
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
+1
-1
@@ -3401,7 +3401,7 @@ func (b *Builtin) IsTargetPos(i int) bool {
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
BuiltinMap = map[string]*Builtin{}
|
BuiltinMap = map[string]*Builtin{}
|
||||||
for _, b := range DefaultBuiltins {
|
for _, b := range &DefaultBuiltins {
|
||||||
RegisterBuiltin(b)
|
RegisterBuiltin(b)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-7
@@ -306,10 +306,8 @@ func (tc *typeChecker) checkRule(env *TypeEnv, as *AnnotationSet, rule *Rule) {
|
|||||||
tc.err([]*Error{NewError(TypeErr, rule.Head.Location, err.Error())}) //nolint:govet
|
tc.err([]*Error{NewError(TypeErr, rule.Head.Location, err.Error())}) //nolint:govet
|
||||||
tpe = nil
|
tpe = nil
|
||||||
}
|
}
|
||||||
} else {
|
} else if typeV != nil {
|
||||||
if typeV != nil {
|
tpe = typeV
|
||||||
tpe = typeV
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
case MultiValue:
|
case MultiValue:
|
||||||
typeK := cpy.GetByValue(rule.Head.Key.Value)
|
typeK := cpy.GetByValue(rule.Head.Key.Value)
|
||||||
@@ -732,8 +730,8 @@ func (rc *refChecker) Visit(x interface{}) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (rc *refChecker) checkApply(curr *TypeEnv, ref Ref) *Error {
|
func (rc *refChecker) checkApply(curr *TypeEnv, ref Ref) *Error {
|
||||||
switch tpe := curr.GetByRef(ref).(type) {
|
if tpe, ok := curr.GetByRef(ref).(*types.Function); ok {
|
||||||
case *types.Function: // NOTE(sr): We don't support first-class functions, except for `with`.
|
// NOTE(sr): We don't support first-class functions, except for `with`.
|
||||||
return newRefErrUnsupported(ref[0].Location, rc.varRewriter(ref), len(ref)-1, tpe)
|
return newRefErrUnsupported(ref[0].Location, rc.varRewriter(ref), len(ref)-1, tpe)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1003,7 +1001,7 @@ type ArgErrDetail struct {
|
|||||||
func (d *ArgErrDetail) Lines() []string {
|
func (d *ArgErrDetail) Lines() []string {
|
||||||
lines := make([]string, 2)
|
lines := make([]string, 2)
|
||||||
lines[0] = "have: " + formatArgs(d.Have)
|
lines[0] = "have: " + formatArgs(d.Have)
|
||||||
lines[1] = "want: " + fmt.Sprint(d.Want)
|
lines[1] = "want: " + d.Want.String()
|
||||||
return lines
|
return lines
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1529,9 +1529,7 @@ func TestCheckErrorOrdering(t *testing.T) {
|
|||||||
inputReversed[i] = mod.Rules[i]
|
inputReversed[i] = mod.Rules[i]
|
||||||
}
|
}
|
||||||
|
|
||||||
tmp := inputReversed[1]
|
inputReversed[1], inputReversed[2] = inputReversed[2], inputReversed[1]
|
||||||
inputReversed[1] = inputReversed[2]
|
|
||||||
inputReversed[2] = tmp
|
|
||||||
|
|
||||||
_, errs1 := newTypeChecker().CheckTypes(nil, input, nil)
|
_, errs1 := newTypeChecker().CheckTypes(nil, input, nil)
|
||||||
_, errs2 := newTypeChecker().CheckTypes(nil, inputReversed, nil)
|
_, errs2 := newTypeChecker().CheckTypes(nil, inputReversed, nil)
|
||||||
|
|||||||
+1
-1
@@ -236,7 +236,7 @@ func Compare(a, b interface{}) int {
|
|||||||
type termSlice []*Term
|
type termSlice []*Term
|
||||||
|
|
||||||
func (s termSlice) Less(i, j int) bool { return Compare(s[i].Value, s[j].Value) < 0 }
|
func (s termSlice) Less(i, j int) bool { return Compare(s[i].Value, s[j].Value) < 0 }
|
||||||
func (s termSlice) Swap(i, j int) { x := s[i]; s[i] = s[j]; s[j] = x }
|
func (s termSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||||
func (s termSlice) Len() int { return len(s) }
|
func (s termSlice) Len() int { return len(s) }
|
||||||
|
|
||||||
func sortOrder(x interface{}) int {
|
func sortOrder(x interface{}) int {
|
||||||
|
|||||||
+2
-4
@@ -3545,10 +3545,8 @@ func (n *TreeNode) add(path Ref, rule *Rule) {
|
|||||||
}
|
}
|
||||||
node.Children[sub.Key] = sub
|
node.Children[sub.Key] = sub
|
||||||
node.Sorted = append(node.Sorted, sub.Key)
|
node.Sorted = append(node.Sorted, sub.Key)
|
||||||
} else {
|
} else if rule != nil {
|
||||||
if rule != nil {
|
node.Values = append(node.Values, rule)
|
||||||
node.Values = append(node.Values, rule)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10164,10 +10164,8 @@ func runStrictnessQueryTestCase(t *testing.T, cases []strictnessQueryTestCase) {
|
|||||||
if !strings.Contains(err.Error(), tc.expectedErrors.Error()) {
|
if !strings.Contains(err.Error(), tc.expectedErrors.Error()) {
|
||||||
t.Fatalf("Expected error %v but got: %v", tc.expectedErrors, err)
|
t.Fatalf("Expected error %v but got: %v", tc.expectedErrors, err)
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error from %v: %v", tc.query, err)
|
||||||
t.Fatalf("Unexpected error from %v: %v", tc.query, err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11493,10 +11491,8 @@ func TestCompile_DefaultRegoVersion(t *testing.T) {
|
|||||||
|
|
||||||
if len(tc.expErrs) > 0 {
|
if len(tc.expErrs) > 0 {
|
||||||
assertErrors(t, compiler.Errors, tc.expErrs, false)
|
assertErrors(t, compiler.Errors, tc.expErrs, false)
|
||||||
} else {
|
} else if len(compiler.Errors) > 0 {
|
||||||
if len(compiler.Errors) > 0 {
|
t.Fatalf("Unexpected errors: %v", compiler.Errors)
|
||||||
t.Fatalf("Unexpected errors: %v", compiler.Errors)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,10 +113,8 @@ func TestCompileModules_DefaultRegoVersion(t *testing.T) {
|
|||||||
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
t.Fatalf("Unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -226,10 +224,8 @@ func TestCompileModulesWithOpt_DefaultRegoVersion(t *testing.T) {
|
|||||||
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
t.Fatalf("Expected error to contain:\n\n%s\n\nbut got:\n\n%s", expErr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
t.Fatalf("Unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -101,8 +101,8 @@ func (s *Scanner) Keyword(lit string) tokens.Token {
|
|||||||
func (s *Scanner) AddKeyword(kw string, tok tokens.Token) {
|
func (s *Scanner) AddKeyword(kw string, tok tokens.Token) {
|
||||||
s.keywords[kw] = tok
|
s.keywords[kw] = tok
|
||||||
|
|
||||||
switch tok {
|
if tok == tokens.Every {
|
||||||
case tokens.Every: // importing 'every' means also importing 'in'
|
// importing 'every' means also importing 'in'
|
||||||
s.keywords["in"] = tokens.In
|
s.keywords["in"] = tokens.In
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -398,7 +398,7 @@ func (s *Scanner) scanComment() string {
|
|||||||
end := s.offset - 1
|
end := s.offset - 1
|
||||||
// Trim carriage returns that precede the newline
|
// Trim carriage returns that precede the newline
|
||||||
if s.offset > 1 && s.bs[s.offset-2] == '\r' {
|
if s.offset > 1 && s.bs[s.offset-2] == '\r' {
|
||||||
end = end - 1
|
end -= 1
|
||||||
}
|
}
|
||||||
|
|
||||||
return util.ByteSliceToString(s.bs[start:end])
|
return util.ByteSliceToString(s.bs[start:end])
|
||||||
|
|||||||
+3
-3
@@ -134,7 +134,7 @@ func (c parsedTermCache) String() string {
|
|||||||
s.WriteRune('{')
|
s.WriteRune('{')
|
||||||
var e *parsedTermCacheItem
|
var e *parsedTermCacheItem
|
||||||
for e = c.m; e != nil; e = e.next {
|
for e = c.m; e != nil; e = e.next {
|
||||||
s.WriteString(fmt.Sprintf("%v", e))
|
s.WriteString(e.String())
|
||||||
}
|
}
|
||||||
s.WriteRune('}')
|
s.WriteRune('}')
|
||||||
return s.String()
|
return s.String()
|
||||||
@@ -2063,7 +2063,7 @@ func (p *Parser) parseTermPairList(end tokens.Token, r [][2]*Term) [][2]*Term {
|
|||||||
func (p *Parser) parseTermOp(values ...tokens.Token) *Term {
|
func (p *Parser) parseTermOp(values ...tokens.Token) *Term {
|
||||||
for i := range values {
|
for i := range values {
|
||||||
if p.s.tok == values[i] {
|
if p.s.tok == values[i] {
|
||||||
r := RefTerm(VarTerm(fmt.Sprint(p.s.tok)).SetLocation(p.s.Loc())).SetLocation(p.s.Loc())
|
r := RefTerm(VarTerm(p.s.tok.String()).SetLocation(p.s.Loc())).SetLocation(p.s.Loc())
|
||||||
p.scan()
|
p.scan()
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
@@ -2612,7 +2612,7 @@ func parseAuthorString(s string) (*AuthorAnnotation, error) {
|
|||||||
strings.HasSuffix(trailing, emailSuffix) {
|
strings.HasSuffix(trailing, emailSuffix) {
|
||||||
email = trailing[len(emailPrefix):]
|
email = trailing[len(emailPrefix):]
|
||||||
email = email[0 : len(email)-len(emailSuffix)]
|
email = email[0 : len(email)-len(emailSuffix)]
|
||||||
namePartCount = namePartCount - 1
|
namePartCount -= 1
|
||||||
}
|
}
|
||||||
|
|
||||||
name := strings.Join(parts[0:namePartCount], " ")
|
name := strings.Join(parts[0:namePartCount], " ")
|
||||||
|
|||||||
+16
-16
@@ -140,7 +140,7 @@ func TestSetTypesWithPodSchema(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestAllOfSchemas(t *testing.T) {
|
func TestAllOfSchemas(t *testing.T) {
|
||||||
//Test 1: object schema
|
// Test 1: object schema
|
||||||
objectSchemaStaticProps := []*types.StaticProperty{}
|
objectSchemaStaticProps := []*types.StaticProperty{}
|
||||||
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "AddressLine1", Value: types.S})
|
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "AddressLine1", Value: types.S})
|
||||||
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "AddressLine2", Value: types.S})
|
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "AddressLine2", Value: types.S})
|
||||||
@@ -151,10 +151,10 @@ func TestAllOfSchemas(t *testing.T) {
|
|||||||
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S})
|
objectSchemaStaticProps = append(objectSchemaStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S})
|
||||||
objectSchemaExpectedType := types.NewObject(objectSchemaStaticProps, nil)
|
objectSchemaExpectedType := types.NewObject(objectSchemaStaticProps, nil)
|
||||||
|
|
||||||
//Test 2: array schema
|
// Test 2: array schema
|
||||||
arrayExpectedType := types.NewArray(nil, types.N)
|
arrayExpectedType := types.NewArray(nil, types.N)
|
||||||
|
|
||||||
//Test 3: parent variation
|
// Test 3: parent variation
|
||||||
parentVariationStaticProps := []*types.StaticProperty{}
|
parentVariationStaticProps := []*types.StaticProperty{}
|
||||||
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "State", Value: types.S})
|
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "State", Value: types.S})
|
||||||
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S})
|
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S})
|
||||||
@@ -162,13 +162,13 @@ func TestAllOfSchemas(t *testing.T) {
|
|||||||
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S})
|
parentVariationStaticProps = append(parentVariationStaticProps, &types.StaticProperty{Key: "PostCode", Value: types.S})
|
||||||
parentVariationExpectedType := types.NewObject(parentVariationStaticProps, nil)
|
parentVariationExpectedType := types.NewObject(parentVariationStaticProps, nil)
|
||||||
|
|
||||||
//Test 4: empty schema with allOf
|
// Test 4: empty schema with allOf
|
||||||
emptyExpectedType := types.A
|
emptyExpectedType := types.A
|
||||||
|
|
||||||
//Tests 5 & 6: schema with array of arrays, object and array as siblings
|
// Tests 5 & 6: schema with array of arrays, object and array as siblings
|
||||||
expectedError := errors.New("unable to merge these schemas")
|
expectedError := errors.New("unable to merge these schemas")
|
||||||
|
|
||||||
//Test 7: array of objects
|
// Test 7: array of objects
|
||||||
arrayOfObjectsStaticProps := []*types.StaticProperty{}
|
arrayOfObjectsStaticProps := []*types.StaticProperty{}
|
||||||
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "State", Value: types.S})
|
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "State", Value: types.S})
|
||||||
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S})
|
arrayOfObjectsStaticProps = append(arrayOfObjectsStaticProps, &types.StaticProperty{Key: "ZipCode", Value: types.S})
|
||||||
@@ -179,7 +179,7 @@ func TestAllOfSchemas(t *testing.T) {
|
|||||||
innerType := types.NewObject(arrayOfObjectsStaticProps, nil)
|
innerType := types.NewObject(arrayOfObjectsStaticProps, nil)
|
||||||
arrayOfObjectsExpectedType := types.NewArray(nil, innerType)
|
arrayOfObjectsExpectedType := types.NewArray(nil, innerType)
|
||||||
|
|
||||||
//Tests 8 & 9: allOf schema with type not specified
|
// Tests 8 & 9: allOf schema with type not specified
|
||||||
objectMissingStaticProps := []*types.StaticProperty{}
|
objectMissingStaticProps := []*types.StaticProperty{}
|
||||||
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "AddressLine", Value: types.S})
|
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "AddressLine", Value: types.S})
|
||||||
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "State", Value: types.S})
|
objectMissingStaticProps = append(objectMissingStaticProps, &types.StaticProperty{Key: "State", Value: types.S})
|
||||||
@@ -189,10 +189,10 @@ func TestAllOfSchemas(t *testing.T) {
|
|||||||
objectMissingExpectedType := types.NewObject(objectMissingStaticProps, nil)
|
objectMissingExpectedType := types.NewObject(objectMissingStaticProps, nil)
|
||||||
arrayMissingExpectedType := types.NewArray([]types.Type{types.N, types.N}, nil)
|
arrayMissingExpectedType := types.NewArray([]types.Type{types.N, types.N}, nil)
|
||||||
|
|
||||||
//Tests 10 & 11: allOf schema with array that contains different types (with and without error)
|
// Tests 10 & 11: allOf schema with array that contains different types (with and without error)
|
||||||
arrayDifTypesExpectedType := types.NewArray([]types.Type{types.S, types.N}, nil)
|
arrayDifTypesExpectedType := types.NewArray([]types.Type{types.S, types.N}, nil)
|
||||||
|
|
||||||
//Test 12: array inside of object
|
// Test 12: array inside of object
|
||||||
arrayInObjectstaticProps := []*types.StaticProperty{}
|
arrayInObjectstaticProps := []*types.StaticProperty{}
|
||||||
arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "age", Value: types.N})
|
arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "age", Value: types.N})
|
||||||
arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "name", Value: types.S})
|
arrayInObjectstaticProps = append(arrayInObjectstaticProps, &types.StaticProperty{Key: "name", Value: types.S})
|
||||||
@@ -203,7 +203,7 @@ func TestAllOfSchemas(t *testing.T) {
|
|||||||
arrayInObjectExpectedType := types.NewObject([]*types.StaticProperty{
|
arrayInObjectExpectedType := types.NewObject([]*types.StaticProperty{
|
||||||
types.NewStaticProperty("familyMembers", arrayInObjectInnerType)}, nil)
|
types.NewStaticProperty("familyMembers", arrayInObjectInnerType)}, nil)
|
||||||
|
|
||||||
//Test 13: allOf inside core schema
|
// Test 13: allOf inside core schema
|
||||||
coreStaticProps := []*types.StaticProperty{}
|
coreStaticProps := []*types.StaticProperty{}
|
||||||
coreStaticProps = append(coreStaticProps, &types.StaticProperty{Key: "accessMe", Value: types.S})
|
coreStaticProps = append(coreStaticProps, &types.StaticProperty{Key: "accessMe", Value: types.S})
|
||||||
coreStaticProps = append(coreStaticProps, &types.StaticProperty{Key: "accessYou", Value: types.S})
|
coreStaticProps = append(coreStaticProps, &types.StaticProperty{Key: "accessYou", Value: types.S})
|
||||||
@@ -213,12 +213,12 @@ func TestAllOfSchemas(t *testing.T) {
|
|||||||
outerType = append(outerType, &types.StaticProperty{Key: "AddressLine", Value: types.S})
|
outerType = append(outerType, &types.StaticProperty{Key: "AddressLine", Value: types.S})
|
||||||
coreSchemaExpectedType := types.NewObject(outerType, nil)
|
coreSchemaExpectedType := types.NewObject(outerType, nil)
|
||||||
|
|
||||||
//Tests 14-17: other types besides array and object
|
// Tests 14-17: other types besides array and object
|
||||||
expectedStringType := types.NewString()
|
expectedStringType := types.NewString()
|
||||||
expectedIntegerType := types.NewNumber()
|
expectedIntegerType := types.NewNumber()
|
||||||
expectedBooleanType := types.NewBoolean()
|
expectedBooleanType := types.NewBoolean()
|
||||||
|
|
||||||
//Test 18: array with uneven numbers of items children to merge
|
// Test 18: array with uneven numbers of items children to merge
|
||||||
expectedUnevenArrayType := types.NewArray([]types.Type{types.N, types.N, types.S}, nil)
|
expectedUnevenArrayType := types.NewArray([]types.Type{types.N, types.N, types.S}, nil)
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
@@ -357,7 +357,7 @@ func TestAllOfSchemas(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestParseSchemaUntypedField(t *testing.T) {
|
func TestParseSchemaUntypedField(t *testing.T) {
|
||||||
//Expected type is: object<foo: any>
|
// Expected type is: object<foo: any>
|
||||||
staticProps := []*types.StaticProperty{}
|
staticProps := []*types.StaticProperty{}
|
||||||
staticProps = append(staticProps, &types.StaticProperty{Key: "foo", Value: types.A})
|
staticProps = append(staticProps, &types.StaticProperty{Key: "foo", Value: types.A})
|
||||||
expectedType := types.NewObject(staticProps, nil)
|
expectedType := types.NewObject(staticProps, nil)
|
||||||
@@ -365,13 +365,13 @@ func TestParseSchemaUntypedField(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestParseSchemaNoChildren(t *testing.T) {
|
func TestParseSchemaNoChildren(t *testing.T) {
|
||||||
//Expected type is: object[any: any]
|
// Expected type is: object[any: any]
|
||||||
expectedType := types.NewObject(nil, &types.DynamicProperty{Key: types.A, Value: types.A})
|
expectedType := types.NewObject(nil, &types.DynamicProperty{Key: types.A, Value: types.A})
|
||||||
testParseSchema(t, noChildrenObjectSchema, expectedType, nil)
|
testParseSchema(t, noChildrenObjectSchema, expectedType, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseSchemaArrayNoItems(t *testing.T) {
|
func TestParseSchemaArrayNoItems(t *testing.T) {
|
||||||
//Expected type is: object<b: array[any]>
|
// Expected type is: object<b: array[any]>
|
||||||
staticProps := []*types.StaticProperty{}
|
staticProps := []*types.StaticProperty{}
|
||||||
staticProps = append(staticProps, &types.StaticProperty{Key: "b", Value: types.NewArray(nil, types.A)})
|
staticProps = append(staticProps, &types.StaticProperty{Key: "b", Value: types.NewArray(nil, types.A)})
|
||||||
expectedType := types.NewObject(staticProps, nil)
|
expectedType := types.NewObject(staticProps, nil)
|
||||||
@@ -379,7 +379,7 @@ func TestParseSchemaArrayNoItems(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestParseSchemaBooleanField(t *testing.T) {
|
func TestParseSchemaBooleanField(t *testing.T) {
|
||||||
//Expected type is: object<a: boolean>
|
// Expected type is: object<a: boolean>
|
||||||
staticProps := []*types.StaticProperty{}
|
staticProps := []*types.StaticProperty{}
|
||||||
staticProps = append(staticProps, &types.StaticProperty{Key: "a", Value: types.B})
|
staticProps = append(staticProps, &types.StaticProperty{Key: "a", Value: types.B})
|
||||||
expectedType := types.NewObject(staticProps, nil)
|
expectedType := types.NewObject(staticProps, nil)
|
||||||
|
|||||||
+7
-7
@@ -1391,14 +1391,14 @@ func (arr *Array) String() string {
|
|||||||
|
|
||||||
defer sbPool.Put(sb)
|
defer sbPool.Put(sb)
|
||||||
|
|
||||||
sb.WriteRune('[')
|
sb.WriteByte('[')
|
||||||
for i, e := range arr.elems {
|
for i, e := range arr.elems {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
sb.WriteString(", ")
|
sb.WriteString(", ")
|
||||||
}
|
}
|
||||||
sb.WriteString(e.String())
|
sb.WriteString(e.String())
|
||||||
}
|
}
|
||||||
sb.WriteRune(']')
|
sb.WriteByte(']')
|
||||||
|
|
||||||
return sb.String()
|
return sb.String()
|
||||||
}
|
}
|
||||||
@@ -1589,14 +1589,14 @@ func (s *set) String() string {
|
|||||||
|
|
||||||
defer sbPool.Put(sb)
|
defer sbPool.Put(sb)
|
||||||
|
|
||||||
sb.WriteRune('{')
|
sb.WriteByte('{')
|
||||||
for i := range s.sortedKeys() {
|
for i := range s.sortedKeys() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
sb.WriteString(", ")
|
sb.WriteString(", ")
|
||||||
}
|
}
|
||||||
sb.WriteString(s.keys[i].Value.String())
|
sb.WriteString(s.keys[i].Value.String())
|
||||||
}
|
}
|
||||||
sb.WriteRune('}')
|
sb.WriteByte('}')
|
||||||
|
|
||||||
return sb.String()
|
return sb.String()
|
||||||
}
|
}
|
||||||
@@ -2217,7 +2217,7 @@ type objectElem struct {
|
|||||||
type objectElemSlice []*objectElem
|
type objectElemSlice []*objectElem
|
||||||
|
|
||||||
func (s objectElemSlice) Less(i, j int) bool { return Compare(s[i].key.Value, s[j].key.Value) < 0 }
|
func (s objectElemSlice) Less(i, j int) bool { return Compare(s[i].key.Value, s[j].key.Value) < 0 }
|
||||||
func (s objectElemSlice) Swap(i, j int) { x := s[i]; s[i] = s[j]; s[j] = x }
|
func (s objectElemSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||||
func (s objectElemSlice) Len() int { return len(s) }
|
func (s objectElemSlice) Len() int { return len(s) }
|
||||||
|
|
||||||
// Item is a helper for constructing an tuple containing two Terms
|
// Item is a helper for constructing an tuple containing two Terms
|
||||||
@@ -2502,7 +2502,7 @@ func (obj *object) String() string {
|
|||||||
|
|
||||||
defer sbPool.Put(sb)
|
defer sbPool.Put(sb)
|
||||||
|
|
||||||
sb.WriteRune('{')
|
sb.WriteByte('{')
|
||||||
|
|
||||||
for i, elem := range obj.sortedKeys() {
|
for i, elem := range obj.sortedKeys() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
@@ -2512,7 +2512,7 @@ func (obj *object) String() string {
|
|||||||
sb.WriteString(": ")
|
sb.WriteString(": ")
|
||||||
sb.WriteString(elem.value.String())
|
sb.WriteString(elem.value.String())
|
||||||
}
|
}
|
||||||
sb.WriteRune('}')
|
sb.WriteByte('}')
|
||||||
|
|
||||||
return sb.String()
|
return sb.String()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -324,8 +324,8 @@ func BenchmarkObjectConstruction(b *testing.B) {
|
|||||||
for i := range n {
|
for i := range n {
|
||||||
es = append(es, struct{ k, v int }{i, i})
|
es = append(es, struct{ k, v int }{i, i})
|
||||||
}
|
}
|
||||||
rand.New(rand.NewSource(seed)) // Seed the PRNG.
|
r := rand.New(rand.NewSource(seed)) // Seed the PRNG.
|
||||||
rand.Shuffle(len(es), func(i, j int) { es[i], es[j] = es[j], es[i] })
|
r.Shuffle(len(es), func(i, j int) { es[i], es[j] = es[j], es[i] })
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
for range b.N {
|
for range b.N {
|
||||||
obj := NewObject()
|
obj := NewObject()
|
||||||
|
|||||||
+2
-3
@@ -867,7 +867,6 @@ func TestSetConcurrentReads(t *testing.T) {
|
|||||||
numbers[i] = IntNumberTerm(i)
|
numbers[i] = IntNumberTerm(i)
|
||||||
}
|
}
|
||||||
// Shuffle numbers array for random insertion order.
|
// Shuffle numbers array for random insertion order.
|
||||||
rand.New(rand.NewSource(10000)) // Seed the PRNG.
|
|
||||||
rand.Shuffle(len(numbers), func(i, j int) {
|
rand.Shuffle(len(numbers), func(i, j int) {
|
||||||
numbers[i], numbers[j] = numbers[j], numbers[i]
|
numbers[i], numbers[j] = numbers[j], numbers[i]
|
||||||
})
|
})
|
||||||
@@ -909,8 +908,8 @@ func TestObjectConcurrentReads(t *testing.T) {
|
|||||||
numbers[i] = IntNumberTerm(i)
|
numbers[i] = IntNumberTerm(i)
|
||||||
}
|
}
|
||||||
// Shuffle numbers array for random insertion order.
|
// Shuffle numbers array for random insertion order.
|
||||||
rand.New(rand.NewSource(10000)) // Seed the PRNG.
|
r := rand.New(rand.NewSource(10000)) // Seed the PRNG.
|
||||||
rand.Shuffle(len(numbers), func(i, j int) {
|
r.Shuffle(len(numbers), func(i, j int) {
|
||||||
numbers[i], numbers[j] = numbers[j], numbers[i]
|
numbers[i], numbers[j] = numbers[j], numbers[i]
|
||||||
})
|
})
|
||||||
// Build an object with numbers in unsorted order.
|
// Build an object with numbers in unsorted order.
|
||||||
|
|||||||
@@ -599,10 +599,8 @@ func TestReadWithSignatures(t *testing.T) {
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,10 +52,8 @@ func TestValidateAndInjectDefaultsVerificationConfig(t *testing.T) {
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if !reflect.DeepEqual(tc.vc.PublicKeys, tc.publicKeys) {
|
if !reflect.DeepEqual(tc.vc.PublicKeys, tc.publicKeys) {
|
||||||
@@ -99,10 +97,8 @@ func TestGetPublicKey(t *testing.T) {
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if !reflect.DeepEqual(kc, tc.kc) {
|
if !reflect.DeepEqual(kc, tc.kc) {
|
||||||
@@ -328,7 +324,7 @@ func TestGetClaimsErrors(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
test.WithTempFS(files, func(rootDir string) {
|
test.WithTempFS(files, func(rootDir string) {
|
||||||
//json unmarshal error
|
// json unmarshal error
|
||||||
sc := NewSigningConfig("secret", "HS256", filepath.Join(rootDir, "claims.json"))
|
sc := NewSigningConfig("secret", "HS256", filepath.Join(rootDir, "claims.json"))
|
||||||
_, err := sc.GetClaims()
|
_, err := sc.GetClaims()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
|||||||
+3
-5
@@ -101,11 +101,9 @@ func generatePayload(files []FileInfo, sc *SigningConfig, keyID string) ([]byte,
|
|||||||
for claim, value := range claims {
|
for claim, value := range claims {
|
||||||
payload[claim] = value
|
payload[claim] = value
|
||||||
}
|
}
|
||||||
} else {
|
} else if keyID != "" {
|
||||||
if keyID != "" {
|
// keyid claim is deprecated but include it for backwards compatibility.
|
||||||
// keyid claim is deprecated but include it for backwards compatibility.
|
payload["keyid"] = keyID
|
||||||
payload["keyid"] = keyID
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return json.Marshal(payload)
|
return json.Marshal(payload)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6621,10 +6621,8 @@ func TestDoDFS(t *testing.T) {
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,10 +63,8 @@ func TestVerifyBundleSignature(t *testing.T) {
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -210,10 +208,8 @@ yQjtQ8mbDOsiLLvh7wIDAQAB==
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -277,10 +273,8 @@ func TestVerifyBundleFile(t *testing.T) {
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ func BenchmarkCompileDynamicPolicy(b *testing.B) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateDynamicPolicyBenchmarkData(N int) map[string]string {
|
func generateDynamicPolicyBenchmarkData(n int) map[string]string {
|
||||||
files := map[string]string{
|
files := map[string]string{
|
||||||
"main.rego": `
|
"main.rego": `
|
||||||
package main
|
package main
|
||||||
@@ -56,19 +56,19 @@ func generateDynamicPolicyBenchmarkData(N int) map[string]string {
|
|||||||
}`,
|
}`,
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := range N {
|
for i := range n {
|
||||||
files[fmt.Sprintf("policy%d.rego", i)] = generateDynamicMockPolicy(i)
|
files[fmt.Sprintf("policy%d.rego", i)] = generateDynamicMockPolicy(i)
|
||||||
}
|
}
|
||||||
|
|
||||||
return files
|
return files
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateDynamicMockPolicy(N int) string {
|
func generateDynamicMockPolicy(n int) string {
|
||||||
return fmt.Sprintf(`package policies["%d"]["%d"].policy%d
|
return fmt.Sprintf(`package policies["%d"]["%d"].policy%d
|
||||||
denies contains x if {
|
denies contains x if {
|
||||||
input.attribute == "%d"
|
input.attribute == "%d"
|
||||||
x := "policy%d"
|
x := "policy%d"
|
||||||
}`, N, N, N, N, N)
|
}`, n, n, n, n, n)
|
||||||
}
|
}
|
||||||
|
|
||||||
func BenchmarkLargePartialRulePolicy(b *testing.B) {
|
func BenchmarkLargePartialRulePolicy(b *testing.B) {
|
||||||
@@ -95,13 +95,13 @@ func BenchmarkLargePartialRulePolicy(b *testing.B) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateLargePartialRuleBenchmarkData(N int) map[string]string {
|
func generateLargePartialRuleBenchmarkData(n int) map[string]string {
|
||||||
var policy strings.Builder
|
var policy strings.Builder
|
||||||
policy.Grow((140 * N) + 100) // Each rule takes around 130 characters.
|
policy.Grow((140 * n) + 100) // Each rule takes around 130 characters.
|
||||||
|
|
||||||
policy.WriteString(`package example.large.partial.rules.policy["dynamic_part"].main`)
|
policy.WriteString(`package example.large.partial.rules.policy["dynamic_part"].main`)
|
||||||
policy.WriteString("\n\n")
|
policy.WriteString("\n\n")
|
||||||
for i := range N {
|
for i := range n {
|
||||||
policy.WriteString(generateLargePartialRuleMockRule(i))
|
policy.WriteString(generateLargePartialRuleMockRule(i))
|
||||||
policy.WriteString("\n\n")
|
policy.WriteString("\n\n")
|
||||||
}
|
}
|
||||||
@@ -115,11 +115,11 @@ func generateLargePartialRuleBenchmarkData(N int) map[string]string {
|
|||||||
return files
|
return files
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateLargePartialRuleMockRule(N int) string {
|
func generateLargePartialRuleMockRule(n int) string {
|
||||||
return fmt.Sprintf(`deny contains [resource, errormsg] if {
|
return fmt.Sprintf(`deny contains [resource, errormsg] if {
|
||||||
resource := "example.%d"
|
resource := "example.%d"
|
||||||
i := %d
|
i := %d
|
||||||
i %% 2 != 0
|
i %% 2 != 0
|
||||||
errormsg := "denied because %d is an odd number."
|
errormsg := "denied because %d is an odd number."
|
||||||
}`, N, N, N)
|
}`, n, n, n)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -481,10 +481,8 @@ p contains "B" if {
|
|||||||
t.Fatalf("expected error to contain:\n\n%s\n\ngot:\n\n%v", expErr, err)
|
t.Fatalf("expected error to contain:\n\n%s\n\ngot:\n\n%v", expErr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatal(err)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -1246,10 +1244,8 @@ func TestCompilerOptimizationL2(t *testing.T) {
|
|||||||
if !compiler.bundle.Modules[1].Parsed.Equal(prunedExp) {
|
if !compiler.bundle.Modules[1].Parsed.Equal(prunedExp) {
|
||||||
t.Fatalf("expected pruned module to be:\n\n%v\n\ngot:\n\n%v", prunedExp, compiler.bundle.Modules[1])
|
t.Fatalf("expected pruned module to be:\n\n%v\n\ngot:\n\n%v", prunedExp, compiler.bundle.Modules[1])
|
||||||
}
|
}
|
||||||
} else {
|
} else if !compiler.bundle.Modules[1].Parsed.Equal(optimizedExp) {
|
||||||
if !compiler.bundle.Modules[1].Parsed.Equal(optimizedExp) {
|
t.Fatalf("expected optimized module to be:\n\n%v\n\ngot:\n\n%v", optimizedExp, compiler.bundle.Modules[1])
|
||||||
t.Fatalf("expected optimized module to be:\n\n%v\n\ngot:\n\n%v", optimizedExp, compiler.bundle.Modules[1])
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -99,7 +99,7 @@ func (c Config) PluginNames() (result []string) {
|
|||||||
|
|
||||||
// PluginsEnabled returns true if one or more plugin features are enabled.
|
// PluginsEnabled returns true if one or more plugin features are enabled.
|
||||||
//
|
//
|
||||||
// Deprecated. Use PluginNames instead.
|
// Deprecated: Use PluginNames instead.
|
||||||
func (c Config) PluginsEnabled() bool {
|
func (c Config) PluginsEnabled() bool {
|
||||||
return c.Bundle != nil || c.Bundles != nil || c.DecisionLogs != nil || c.Status != nil || len(c.Plugins) > 0
|
return c.Bundle != nil || c.Bundles != nil || c.DecisionLogs != nil || c.Status != nil || len(c.Plugins) > 0
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-7
@@ -299,12 +299,7 @@ func hasFileLocation(loc *ast.Location) bool {
|
|||||||
|
|
||||||
// Check the expression and return true if it should be included in the coverage report
|
// Check the expression and return true if it should be included in the coverage report
|
||||||
func includeExprInCoverage(x *ast.Expr) bool {
|
func includeExprInCoverage(x *ast.Expr) bool {
|
||||||
includeExprType := true
|
_, excludeExprType := x.Terms.(*ast.SomeDecl)
|
||||||
|
|
||||||
switch x.Terms.(type) {
|
return !excludeExprType && hasFileLocation(x.Location)
|
||||||
case *ast.SomeDecl:
|
|
||||||
includeExprType = false
|
|
||||||
}
|
|
||||||
|
|
||||||
return includeExprType && hasFileLocation(x.Location)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -850,7 +850,7 @@ func (s *session) AddBreakpoint(loc location.Location) (Breakpoint, error) {
|
|||||||
return s.breakpoints.add(loc), nil
|
return s.breakpoints.add(loc), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *session) RemoveBreakpoint(ID BreakpointID) (Breakpoint, error) {
|
func (s *session) RemoveBreakpoint(id BreakpointID) (Breakpoint, error) {
|
||||||
if s == nil {
|
if s == nil {
|
||||||
return nil, errors.New("no active debug session")
|
return nil, errors.New("no active debug session")
|
||||||
}
|
}
|
||||||
@@ -858,9 +858,9 @@ func (s *session) RemoveBreakpoint(ID BreakpointID) (Breakpoint, error) {
|
|||||||
s.mtx.Lock()
|
s.mtx.Lock()
|
||||||
defer s.mtx.Unlock()
|
defer s.mtx.Unlock()
|
||||||
|
|
||||||
bp := s.breakpoints.remove(ID)
|
bp := s.breakpoints.remove(id)
|
||||||
if bp == nil {
|
if bp == nil {
|
||||||
return nil, fmt.Errorf("breakpoint %d not found", ID)
|
return nil, fmt.Errorf("breakpoint %d not found", id)
|
||||||
}
|
}
|
||||||
|
|
||||||
return bp, nil
|
return bp, nil
|
||||||
|
|||||||
@@ -2096,10 +2096,8 @@ func assertVariables(t *testing.T, s Session, variables []Variable, exp map[stri
|
|||||||
t.Fatalf("Unexpected error: %v", err)
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
}
|
}
|
||||||
assertVariables(t, s, vars, expVar.children)
|
assertVariables(t, s, vars, expVar.children)
|
||||||
} else {
|
} else if v.VariablesReference() != 0 {
|
||||||
if v.VariablesReference() != 0 {
|
t.Errorf("Expected zero variables reference")
|
||||||
t.Errorf("Expected zero variables reference")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -232,16 +232,14 @@ func (d *Downloader) loop(ctx context.Context) {
|
|||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
delay = util.DefaultBackoff(float64(minRetryDelay), float64(*d.config.Polling.MaxDelaySeconds), retry)
|
delay = util.DefaultBackoff(float64(minRetryDelay), float64(*d.config.Polling.MaxDelaySeconds), retry)
|
||||||
} else {
|
} else if !d.longPollingEnabled || d.config.Polling.LongPollingTimeoutSeconds == nil {
|
||||||
if !d.longPollingEnabled || d.config.Polling.LongPollingTimeoutSeconds == nil {
|
// revert the response header timeout value on the http client's transport
|
||||||
// revert the response header timeout value on the http client's transport
|
if *d.client.Config().ResponseHeaderTimeoutSeconds == 0 {
|
||||||
if *d.client.Config().ResponseHeaderTimeoutSeconds == 0 {
|
d.client = d.client.SetResponseHeaderTimeout(&d.respHdrTimeoutSec)
|
||||||
d.client = d.client.SetResponseHeaderTimeout(&d.respHdrTimeoutSec)
|
|
||||||
}
|
|
||||||
min := float64(*d.config.Polling.MinDelaySeconds)
|
|
||||||
max := float64(*d.config.Polling.MaxDelaySeconds)
|
|
||||||
delay = time.Duration(((max - min) * rand.Float64()) + min)
|
|
||||||
}
|
}
|
||||||
|
min := float64(*d.config.Polling.MinDelaySeconds)
|
||||||
|
max := float64(*d.config.Polling.MaxDelaySeconds)
|
||||||
|
delay = time.Duration(((max - min) * rand.Float64()) + min)
|
||||||
}
|
}
|
||||||
|
|
||||||
d.logger.Debug("Waiting %v before next download/retry.", delay)
|
d.logger.Debug("Waiting %v before next download/retry.", delay)
|
||||||
|
|||||||
+4
-6
@@ -63,12 +63,10 @@ func SourceWithOpts(filename string, src []byte, opts Opts) ([]byte, error) {
|
|||||||
var parserOpts ast.ParserOptions
|
var parserOpts ast.ParserOptions
|
||||||
if opts.ParserOptions != nil {
|
if opts.ParserOptions != nil {
|
||||||
parserOpts = *opts.ParserOptions
|
parserOpts = *opts.ParserOptions
|
||||||
} else {
|
} else if regoVersion == ast.RegoV1 {
|
||||||
if regoVersion == ast.RegoV1 {
|
// If the rego version is V1, we need to parse it as such, to allow for future keywords not being imported.
|
||||||
// If the rego version is V1, we need to parse it as such, to allow for future keywords not being imported.
|
// Otherwise, we'll default to the default rego-version.
|
||||||
// Otherwise, we'll default to the default rego-version.
|
parserOpts.RegoVersion = ast.RegoV1
|
||||||
parserOpts.RegoVersion = ast.RegoV1
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if parserOpts.RegoVersion == ast.RegoUndefined {
|
if parserOpts.RegoVersion == ast.RegoUndefined {
|
||||||
|
|||||||
@@ -72,10 +72,8 @@ func TestParseKeysConfig(t *testing.T) {
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if !reflect.DeepEqual(kc, tc.result) {
|
if !reflect.DeepEqual(kc, tc.result) {
|
||||||
|
|||||||
@@ -504,8 +504,8 @@ func TestLoadDirRecursive(t *testing.T) {
|
|||||||
}
|
}
|
||||||
mod1 := ast.MustParseModule(files["/a/e.rego"])
|
mod1 := ast.MustParseModule(files["/a/e.rego"])
|
||||||
mod2 := ast.MustParseModule(files["/b/d/e.rego"])
|
mod2 := ast.MustParseModule(files["/b/d/e.rego"])
|
||||||
expectedMod1 := loaded.Modules[CleanPath(filepath.Join(rootDir, "/a/e.rego"))].Parsed
|
expectedMod1 := loaded.Modules[CleanPath(filepath.Join(rootDir, "a", "e.rego"))].Parsed
|
||||||
expectedMod2 := loaded.Modules[CleanPath(filepath.Join(rootDir, "/b/d/e.rego"))].Parsed
|
expectedMod2 := loaded.Modules[CleanPath(filepath.Join(rootDir, "b", "d", "e.rego"))].Parsed
|
||||||
if !mod1.Equal(expectedMod1) {
|
if !mod1.Equal(expectedMod1) {
|
||||||
t.Fatalf("Expected:\n%v\n\nGot:\n%v", expectedMod1, mod1)
|
t.Fatalf("Expected:\n%v\n\nGot:\n%v", expectedMod1, mod1)
|
||||||
}
|
}
|
||||||
@@ -807,8 +807,8 @@ func TestAsBundleWithDir(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
expectedModulePaths := map[string]struct{}{
|
expectedModulePaths := map[string]struct{}{
|
||||||
filepath.Join(rootDir, "foo/policy.rego"): {},
|
filepath.Join(rootDir, "foo", "policy.rego"): {},
|
||||||
filepath.Join(rootDir, "base.rego"): {},
|
filepath.Join(rootDir, "base.rego"): {},
|
||||||
}
|
}
|
||||||
for _, mf := range b.Modules {
|
for _, mf := range b.Modules {
|
||||||
if _, found := expectedModulePaths[mf.Path]; !found {
|
if _, found := expectedModulePaths[mf.Path]; !found {
|
||||||
@@ -849,7 +849,7 @@ func TestAsBundleWithFileURLDir(t *testing.T) {
|
|||||||
t.Fatalf("expected 1 modules, got %d", len(b.Modules))
|
t.Fatalf("expected 1 modules, got %d", len(b.Modules))
|
||||||
}
|
}
|
||||||
expectedModulePaths := map[string]struct{}{
|
expectedModulePaths := map[string]struct{}{
|
||||||
filepath.Join(rootDir, "/foo/policy.rego"): {},
|
filepath.Join(rootDir, "foo", "policy.rego"): {},
|
||||||
}
|
}
|
||||||
for _, mf := range b.Modules {
|
for _, mf := range b.Modules {
|
||||||
if _, found := expectedModulePaths[mf.Path]; !found {
|
if _, found := expectedModulePaths[mf.Path]; !found {
|
||||||
@@ -977,10 +977,8 @@ func TestCheckForUNCPath(t *testing.T) {
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -175,10 +175,8 @@ func (c *Config) validateAndInjectDefaults(services []string, keys map[string]*k
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("invalid configuration for bundle %q: %s", name, err.Error())
|
return fmt.Errorf("invalid configuration for bundle %q: %s", name, err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if len(keys) > 0 {
|
||||||
if len(keys) > 0 {
|
source.Signing = bundle.NewVerificationConfig(keys, "", "", nil)
|
||||||
source.Signing = bundle.NewVerificationConfig(keys, "", "", nil)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.HasPrefix(source.Resource, "file://") {
|
if strings.HasPrefix(source.Resource, "file://") {
|
||||||
|
|||||||
@@ -434,17 +434,14 @@ func (p *Plugin) loadAndActivateBundlesFromDisk(ctx context.Context) {
|
|||||||
|
|
||||||
func (p *Plugin) newDownloader(name string, source *Source, bundles map[string]*Source) Loader {
|
func (p *Plugin) newDownloader(name string, source *Source, bundles map[string]*Source) Loader {
|
||||||
|
|
||||||
if u, err := url.Parse(source.Resource); err == nil {
|
if u, err := url.Parse(source.Resource); err == nil && u.Scheme == "file" {
|
||||||
switch u.Scheme {
|
return &fileLoader{
|
||||||
case "file":
|
name: name,
|
||||||
return &fileLoader{
|
path: u.Path,
|
||||||
name: name,
|
bvc: source.Signing,
|
||||||
path: u.Path,
|
sizeLimitBytes: source.SizeLimitBytes,
|
||||||
bvc: source.Signing,
|
f: p.oneShot,
|
||||||
sizeLimitBytes: source.SizeLimitBytes,
|
bundleParserOpts: p.manager.ParserOptions(),
|
||||||
f: p.oneShot,
|
|
||||||
bundleParserOpts: p.manager.ParserOptions(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -921,10 +921,8 @@ func TestPluginStartLazyLoadInMem(t *testing.T) {
|
|||||||
if ast.Compare(result, expected) != 0 {
|
if ast.Compare(result, expected) != 0 {
|
||||||
t.Fatalf("expected data to be %v but got %v", expected, result)
|
t.Fatalf("expected data to be %v but got %v", expected, result)
|
||||||
}
|
}
|
||||||
} else {
|
} else if !reflect.DeepEqual(result, mockBundle1.Data["p"]) {
|
||||||
if !reflect.DeepEqual(result, mockBundle1.Data["p"]) {
|
t.Fatalf("expected data to be %v but got %v", mockBundle1.Data, result)
|
||||||
t.Fatalf("expected data to be %v but got %v", mockBundle1.Data, result)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err = storage.ReadOne(ctx, manager.Store, storage.Path{"q"})
|
result, err = storage.ReadOne(ctx, manager.Store, storage.Path{"q"})
|
||||||
@@ -937,10 +935,8 @@ func TestPluginStartLazyLoadInMem(t *testing.T) {
|
|||||||
if ast.Compare(result, expected) != 0 {
|
if ast.Compare(result, expected) != 0 {
|
||||||
t.Fatalf("expected data to be %v but got %v", expected, result)
|
t.Fatalf("expected data to be %v but got %v", expected, result)
|
||||||
}
|
}
|
||||||
} else {
|
} else if !reflect.DeepEqual(result, mockBundle2.Data["q"]) {
|
||||||
if !reflect.DeepEqual(result, mockBundle2.Data["q"]) {
|
t.Fatalf("expected data to be %v but got %v", mockBundle2.Data, result)
|
||||||
t.Fatalf("expected data to be %v but got %v", mockBundle2.Data, result)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
txn := storage.NewTransactionOrDie(ctx, manager.Store)
|
txn := storage.NewTransactionOrDie(ctx, manager.Store)
|
||||||
@@ -1348,7 +1344,7 @@ func TestStop(t *testing.T) {
|
|||||||
|
|
||||||
serviceName := "test-svc"
|
serviceName := "test-svc"
|
||||||
err := manager.Reconfigure(&config.Config{
|
err := manager.Reconfigure(&config.Config{
|
||||||
Services: []byte(fmt.Sprintf("{\"%s\":{ \"url\": \"%s\"}}", serviceName, ts.URL+tsURLBase)),
|
Services: []byte(fmt.Sprintf("{%q:{ \"url\": %q}}", serviceName, ts.URL+tsURLBase)),
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Error configuring plugin manager: %s", err)
|
t.Fatalf("Error configuring plugin manager: %s", err)
|
||||||
@@ -3008,7 +3004,7 @@ p contains x`),
|
|||||||
|
|
||||||
txn := storage.NewTransactionOrDie(ctx, manager.Store)
|
txn := storage.NewTransactionOrDie(ctx, manager.Store)
|
||||||
|
|
||||||
_, err := manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "/example.rego"))
|
_, err := manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "example.rego"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Unexpected error: %v", err)
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
}
|
}
|
||||||
@@ -3037,7 +3033,7 @@ p contains x`),
|
|||||||
|
|
||||||
txn = storage.NewTransactionOrDie(ctx, manager.Store)
|
txn = storage.NewTransactionOrDie(ctx, manager.Store)
|
||||||
|
|
||||||
_, err = manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "/example.rego"))
|
_, err = manager.Store.GetPolicy(ctx, txn, filepath.Join(bundleName, "example.rego"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Unexpected error: %v", err)
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
}
|
}
|
||||||
@@ -3149,7 +3145,7 @@ func TestPluginOneShotActivationRemovesOld(t *testing.T) {
|
|||||||
ids, err := manager.Store.ListPolicies(ctx, txn)
|
ids, err := manager.Store.ListPolicies(ctx, txn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else if !slices.Equal([]string{filepath.Join(bundleName, "/example2.rego")}, ids) {
|
} else if !slices.Equal([]string{filepath.Join(bundleName, "example2.rego")}, ids) {
|
||||||
return errors.New("expected updated policy ids")
|
return errors.New("expected updated policy ids")
|
||||||
}
|
}
|
||||||
data, err := manager.Store.Read(ctx, txn, storage.Path{})
|
data, err := manager.Store.Read(ctx, txn, storage.Path{})
|
||||||
@@ -3813,7 +3809,7 @@ func TestPluginActivateScopedBundle(t *testing.T) {
|
|||||||
} else {
|
} else {
|
||||||
expData = util.MustUnmarshalJSON([]byte(exp))
|
expData = util.MustUnmarshalJSON([]byte(exp))
|
||||||
}
|
}
|
||||||
expIDs := []string{filepath.Join(bundleName, "bundle/id1"), "some/id2", "some/id3"}
|
expIDs := []string{filepath.Join(bundleName, "bundle", "id1"), "some/id2", "some/id3"}
|
||||||
validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux", nil)
|
validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux", nil)
|
||||||
|
|
||||||
// Activate a bundle that is scoped to a/a3 ad a/a6. Include a function
|
// Activate a bundle that is scoped to a/a3 ad a/a6. Include a function
|
||||||
@@ -3853,7 +3849,7 @@ func TestPluginActivateScopedBundle(t *testing.T) {
|
|||||||
} else {
|
} else {
|
||||||
expData = util.MustUnmarshalJSON([]byte(exp))
|
expData = util.MustUnmarshalJSON([]byte(exp))
|
||||||
}
|
}
|
||||||
expIDs = []string{filepath.Join(bundleName, "bundle/id2"), "some/id3"}
|
expIDs = []string{filepath.Join(bundleName, "bundle", "id2"), "some/id3"}
|
||||||
validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2",
|
validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2",
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"a": map[string]interface{}{"a1": "deadbeef"},
|
"a": map[string]interface{}{"a1": "deadbeef"},
|
||||||
@@ -3877,7 +3873,7 @@ func TestPluginActivateScopedBundle(t *testing.T) {
|
|||||||
|
|
||||||
// Ensure bundle activation failed by checking that previous revision is
|
// Ensure bundle activation failed by checking that previous revision is
|
||||||
// still active.
|
// still active.
|
||||||
expIDs = []string{filepath.Join(bundleName, "bundle/id2"), "not_scoped", "some/id3"}
|
expIDs = []string{filepath.Join(bundleName, "bundle", "id2"), "not_scoped", "some/id3"}
|
||||||
validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2",
|
validateStoreState(ctx, t, manager.Store, "/a", expData, expIDs, bundleName, "quickbrownfaux-2",
|
||||||
map[string]interface{}{
|
map[string]interface{}{
|
||||||
"a": map[string]interface{}{"a1": "deadbeef"},
|
"a": map[string]interface{}{"a1": "deadbeef"},
|
||||||
@@ -3943,7 +3939,7 @@ func TestPluginSetCompilerOnContext(t *testing.T) {
|
|||||||
t.Fatalf("Expected 2 events but got: %+v", events)
|
t.Fatalf("Expected 2 events but got: %+v", events)
|
||||||
} else if compiler := plugins.GetCompilerOnContext(events[1].Context); compiler == nil {
|
} else if compiler := plugins.GetCompilerOnContext(events[1].Context); compiler == nil {
|
||||||
t.Fatalf("Expected compiler on 2nd event but got: %+v", events)
|
t.Fatalf("Expected compiler on 2nd event but got: %+v", events)
|
||||||
} else if !compiler.Modules[filepath.Join(bundleName, "/test.rego")].Equal(exp) {
|
} else if !compiler.Modules[filepath.Join(bundleName, "test.rego")].Equal(exp) {
|
||||||
t.Fatalf("Expected module on compiler but got: %v", compiler.Modules)
|
t.Fatalf("Expected module on compiler but got: %v", compiler.Modules)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5420,10 +5416,8 @@ p contains 7 if {
|
|||||||
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if s.LastSuccessfulActivation.IsZero() {
|
||||||
if s.LastSuccessfulActivation.IsZero() {
|
t.Fatal("expected successful activation")
|
||||||
t.Fatal("expected successful activation")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -5737,10 +5731,8 @@ p contains 7 if {
|
|||||||
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if s.LastSuccessfulActivation.IsZero() {
|
||||||
if s.LastSuccessfulActivation.IsZero() {
|
t.Fatal("expected successful activation")
|
||||||
t.Fatal("expected successful activation")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -5942,10 +5934,8 @@ p contains 7 if {
|
|||||||
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if s.LastSuccessfulActivation.IsZero() {
|
||||||
if s.LastSuccessfulActivation.IsZero() {
|
t.Fatal("expected successful activation")
|
||||||
t.Fatal("expected successful activation")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -6236,10 +6226,8 @@ p contains 7 if {
|
|||||||
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
t.Fatalf("expected error:\n\n%s\n\nbut got:\n\n%v", expErr, s.Errors)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if s.LastSuccessfulActivation.IsZero() {
|
||||||
if s.LastSuccessfulActivation.IsZero() {
|
t.Fatal("expected successful activation")
|
||||||
t.Fatal("expected successful activation")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -101,10 +101,8 @@ func (c *Config) validateAndInjectDefaults(services []string, confKeys map[strin
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("invalid configuration for discovery service: %s", err.Error())
|
return fmt.Errorf("invalid configuration for discovery service: %s", err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if len(confKeys) > 0 {
|
||||||
if len(confKeys) > 0 {
|
c.Signing = bundle.NewVerificationConfig(cpy, "", "", nil)
|
||||||
c.Signing = bundle.NewVerificationConfig(cpy, "", "", nil)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.Resource != nil {
|
if c.Resource != nil {
|
||||||
@@ -126,9 +124,9 @@ func (c *Config) validateAndInjectDefaults(services []string, confKeys map[strin
|
|||||||
c.service = service
|
c.service = service
|
||||||
|
|
||||||
if c.Decision != nil {
|
if c.Decision != nil {
|
||||||
c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.Replace(strings.Trim(*c.Decision, "/"), "/", ".", -1))
|
c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.ReplaceAll(strings.Trim(*c.Decision, "/"), "/", "."))
|
||||||
} else if c.Name != nil {
|
} else if c.Name != nil {
|
||||||
c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.Replace(strings.Trim(*c.Name, "/"), "/", ".", -1))
|
c.query = fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.ReplaceAll(strings.Trim(*c.Name, "/"), "/", "."))
|
||||||
} else {
|
} else {
|
||||||
c.query = ast.DefaultRootDocument.String()
|
c.query = ast.DefaultRootDocument.String()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,6 @@ import (
|
|||||||
"github.com/open-policy-agent/opa/v1/logging/test"
|
"github.com/open-policy-agent/opa/v1/logging/test"
|
||||||
"github.com/open-policy-agent/opa/v1/metrics"
|
"github.com/open-policy-agent/opa/v1/metrics"
|
||||||
"github.com/open-policy-agent/opa/v1/plugins"
|
"github.com/open-policy-agent/opa/v1/plugins"
|
||||||
"github.com/open-policy-agent/opa/v1/plugins/bundle"
|
|
||||||
bundlePlugin "github.com/open-policy-agent/opa/v1/plugins/bundle"
|
bundlePlugin "github.com/open-policy-agent/opa/v1/plugins/bundle"
|
||||||
"github.com/open-policy-agent/opa/v1/plugins/logs"
|
"github.com/open-policy-agent/opa/v1/plugins/logs"
|
||||||
"github.com/open-policy-agent/opa/v1/plugins/status"
|
"github.com/open-policy-agent/opa/v1/plugins/status"
|
||||||
@@ -3339,10 +3338,8 @@ bundles:
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -3406,10 +3403,8 @@ decision_logs:
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -3479,10 +3474,8 @@ status:
|
|||||||
if tc.err != nil && tc.err.Error() != err.Error() {
|
if tc.err != nil && tc.err.Error() != err.Error() {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.err.Error(), err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -3832,8 +3825,8 @@ func TestListeners(t *testing.T) {
|
|||||||
|
|
||||||
ensurePluginState(t, disco, plugins.StateNotReady)
|
ensurePluginState(t, disco, plugins.StateNotReady)
|
||||||
|
|
||||||
var status *bundle.Status
|
var status *bundlePlugin.Status
|
||||||
disco.RegisterListener("testlistener", func(s bundle.Status) {
|
disco.RegisterListener("testlistener", func(s bundlePlugin.Status) {
|
||||||
status = &s
|
status = &s
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -3954,7 +3947,7 @@ func (t *testFixture) runQuery(ctx context.Context, query string, m metrics.Metr
|
|||||||
rego.Metrics(m),
|
rego.Metrics(m),
|
||||||
)
|
)
|
||||||
|
|
||||||
//Run evaluation.
|
// Run evaluation.
|
||||||
rs, err := r.Eval(ctx)
|
rs, err := r.Eval(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -183,8 +183,8 @@ func (enc *chunkEncoder) reset() ([][]byte, error) {
|
|||||||
enc.initialize()
|
enc.initialize()
|
||||||
|
|
||||||
var result [][]byte
|
var result [][]byte
|
||||||
for _, event := range events {
|
for i := range events {
|
||||||
chunk, err := enc.Write(event)
|
chunk, err := enc.Write(events[i])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -893,8 +893,8 @@ func (p *Plugin) oneShot(ctx context.Context) (ok bool, err error) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, event := range events {
|
for i := range events {
|
||||||
p.encodeAndBufferEvent(event)
|
p.encodeAndBufferEvent(events[i])
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// requeue the chunk
|
// requeue the chunk
|
||||||
|
|||||||
@@ -803,7 +803,7 @@ func (m *Manager) Reconfigure(config *config.Config) error {
|
|||||||
|
|
||||||
m.Config = config
|
m.Config = config
|
||||||
m.interQueryBuiltinCacheConfig = interQueryBuiltinCacheConfig
|
m.interQueryBuiltinCacheConfig = interQueryBuiltinCacheConfig
|
||||||
for name, client := range services {
|
for name, client := range services { //nolint:gocritic
|
||||||
m.services[name] = client
|
m.services[name] = client
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -206,7 +206,7 @@ func convertSignatureToBase64(alg string, der []byte) (string, error) {
|
|||||||
return signatureData, nil
|
return signatureData, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func pointsFromDER(der []byte) (R, S *big.Int, err error) {
|
func pointsFromDER(der []byte) (R, S *big.Int, err error) { //nolint:gocritic
|
||||||
R, S = &big.Int{}, &big.Int{}
|
R, S = &big.Int{}, &big.Int{}
|
||||||
data := asn1.RawValue{}
|
data := asn1.RawValue{}
|
||||||
if _, err := asn1.Unmarshal(der, &data); err != nil {
|
if _, err := asn1.Unmarshal(der, &data); err != nil {
|
||||||
@@ -394,12 +394,7 @@ func (ap *oauth2ClientCredentialsAuthPlugin) SignWithKMS(ctx context.Context, pa
|
|||||||
|
|
||||||
encodedHdr := base64.RawURLEncoding.EncodeToString(hdrBuf)
|
encodedHdr := base64.RawURLEncoding.EncodeToString(hdrBuf)
|
||||||
encodedPayload := base64.RawURLEncoding.EncodeToString(payload)
|
encodedPayload := base64.RawURLEncoding.EncodeToString(payload)
|
||||||
input := strings.Join(
|
input := encodedHdr + "." + encodedPayload
|
||||||
[]string{
|
|
||||||
encodedHdr,
|
|
||||||
encodedPayload,
|
|
||||||
}, ".",
|
|
||||||
)
|
|
||||||
digest, err := messageDigest([]byte(input), ap.AWSKmsKey.Algorithm)
|
digest, err := messageDigest([]byte(input), ap.AWSKmsKey.Algorithm)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -628,7 +623,7 @@ func (ap *oauth2ClientCredentialsAuthPlugin) requestToken(ctx context.Context) (
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.ToLower(tokenResponse.TokenType) != "bearer" {
|
if !strings.EqualFold(tokenResponse.TokenType, "bearer") {
|
||||||
return nil, errors.New("unknown token type returned from token endpoint")
|
return nil, errors.New("unknown token type returned from token endpoint")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -341,7 +341,7 @@ func (c Client) Do(ctx context.Context, method, path string) (*http.Response, er
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(string(dump)) < defaultResponseSizeLimitBytes {
|
if len(dump) < defaultResponseSizeLimitBytes {
|
||||||
c.loggerFields["response"] = string(dump)
|
c.loggerFields["response"] = string(dump)
|
||||||
} else {
|
} else {
|
||||||
c.loggerFields["response"] = fmt.Sprintf("%v...", string(dump[:defaultResponseSizeLimitBytes]))
|
c.loggerFields["response"] = fmt.Sprintf("%v...", string(dump[:defaultResponseSizeLimitBytes]))
|
||||||
|
|||||||
@@ -939,10 +939,8 @@ func TestDoWithResponseHeaderTimeout(t *testing.T) {
|
|||||||
if !strings.Contains(err.Error(), tc.errMsg) {
|
if !strings.Contains(err.Error(), tc.errMsg) {
|
||||||
t.Fatalf("Expected error %v but got %v", tc.errMsg, err.Error())
|
t.Fatalf("Expected error %v but got %v", tc.errMsg, err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error %v", err)
|
||||||
t.Fatalf("Unexpected error %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -2013,10 +2011,8 @@ func TestAWSCredentialServiceChain(t *testing.T) {
|
|||||||
if !strings.Contains(err.Error(), tc.errMsg) {
|
if !strings.Contains(err.Error(), tc.errMsg) {
|
||||||
t.Fatalf("Expected error message %v but got %v", tc.errMsg, err.Error())
|
t.Fatalf("Expected error message %v but got %v", tc.errMsg, err.Error())
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil {
|
||||||
if err != nil {
|
t.Fatalf("Unexpected error: %v", err)
|
||||||
t.Fatalf("Unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2149,7 +2149,7 @@ func TestRegoEvalWithBundle(t *testing.T) {
|
|||||||
t.Fatalf("expected %d modules, found %d", exp, act)
|
t.Fatalf("expected %d modules, found %d", exp, act)
|
||||||
}
|
}
|
||||||
for act := range mods {
|
for act := range mods {
|
||||||
if exp := filepath.Join(path, "x/x.rego"); exp != act {
|
if exp := filepath.Join(path, "x", "x.rego"); exp != act {
|
||||||
t.Errorf("expected module name %q, got %q", exp, act)
|
t.Errorf("expected module name %q, got %q", exp, act)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2176,7 +2176,7 @@ func TestRegoEvalWithBundleURL(t *testing.T) {
|
|||||||
t.Fatalf("expected %d modules, found %d", exp, act)
|
t.Fatalf("expected %d modules, found %d", exp, act)
|
||||||
}
|
}
|
||||||
for act := range mods {
|
for act := range mods {
|
||||||
if exp := filepath.Join(path, "x/x.rego"); exp != act {
|
if exp := filepath.Join(path, "x", "x.rego"); exp != act {
|
||||||
t.Errorf("expected module name %q, got %q", exp, act)
|
t.Errorf("expected module name %q, got %q", exp, act)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-5
@@ -513,7 +513,7 @@ func (r *REPL) cmdShow(args []string) error {
|
|||||||
}
|
}
|
||||||
fmt.Fprint(r.output, string(bs))
|
fmt.Fprint(r.output, string(bs))
|
||||||
return nil
|
return nil
|
||||||
} else if strings.Compare(args[0], "debug") == 0 {
|
} else if args[0] == "debug" {
|
||||||
debug := replDebugState{
|
debug := replDebugState{
|
||||||
Explain: r.explain,
|
Explain: r.explain,
|
||||||
Metrics: r.metricsEnabled(),
|
Metrics: r.metricsEnabled(),
|
||||||
@@ -707,7 +707,7 @@ func (r *REPL) unsetRule(ctx context.Context, name ast.Var) (bool, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *REPL) unsetPackage(_ context.Context, pkg *ast.Package) (bool, error) {
|
func (r *REPL) unsetPackage(_ context.Context, pkg *ast.Package) (bool, error) {
|
||||||
path := fmt.Sprintf("%v", pkg.Path)
|
path := pkg.Path.String()
|
||||||
_, ok := r.modules[path]
|
_, ok := r.modules[path]
|
||||||
if ok {
|
if ok {
|
||||||
delete(r.modules, path)
|
delete(r.modules, path)
|
||||||
@@ -1418,10 +1418,10 @@ func newCommand(line string) *command {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
inputCommand := strings.ToLower(p[0])
|
inputCommand := strings.ToLower(p[0])
|
||||||
for _, c := range builtin {
|
for i := range builtin {
|
||||||
if c.name == inputCommand {
|
if builtin[i].name == inputCommand {
|
||||||
return &command{
|
return &command{
|
||||||
op: c.name,
|
op: builtin[i].name,
|
||||||
args: p[1:],
|
args: p[1:],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ func TestRegisterPlugin(t *testing.T) {
|
|||||||
|
|
||||||
RegisterPlugin("test", Factory{})
|
RegisterPlugin("test", Factory{})
|
||||||
|
|
||||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||||
|
|
||||||
rt, err := NewRuntime(context.Background(), params)
|
rt, err := NewRuntime(context.Background(), params)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -98,7 +98,7 @@ func TestRegisterPluginNotStartedWithoutConfig(t *testing.T) {
|
|||||||
|
|
||||||
RegisterPlugin("test", Factory{})
|
RegisterPlugin("test", Factory{})
|
||||||
|
|
||||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||||
|
|
||||||
rt, err := NewRuntime(context.Background(), params)
|
rt, err := NewRuntime(context.Background(), params)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -130,7 +130,7 @@ func TestRegisterPluginBadBootConfig(t *testing.T) {
|
|||||||
|
|
||||||
RegisterPlugin("test", Factory{})
|
RegisterPlugin("test", Factory{})
|
||||||
|
|
||||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||||
|
|
||||||
_, err := NewRuntime(context.Background(), params)
|
_, err := NewRuntime(context.Background(), params)
|
||||||
if err == nil || !strings.Contains(err.Error(), "config error: test") {
|
if err == nil || !strings.Contains(err.Error(), "config error: test") {
|
||||||
@@ -151,7 +151,7 @@ func TestWaitPluginsReady(t *testing.T) {
|
|||||||
RegisterPlugin("test", Factory{})
|
RegisterPlugin("test", Factory{})
|
||||||
|
|
||||||
params := NewParams()
|
params := NewParams()
|
||||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||||
|
|
||||||
rt, err := NewRuntime(context.Background(), params)
|
rt, err := NewRuntime(context.Background(), params)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -697,7 +697,7 @@ func (rt *Runtime) Serve(ctx context.Context) error {
|
|||||||
return rt.gracefulServerShutdown(rt.server)
|
return rt.gracefulServerShutdown(rt.server)
|
||||||
case err := <-errc:
|
case err := <-errc:
|
||||||
rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Listener failed.")
|
rt.logger.WithFields(map[string]interface{}{"err": err}).Error("Listener failed.")
|
||||||
os.Exit(1)
|
os.Exit(1) //nolint:gocritic
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -744,7 +744,7 @@ func (rt *Runtime) StartREPL(ctx context.Context) {
|
|||||||
if rt.Params.Watch {
|
if rt.Params.Watch {
|
||||||
if err := rt.startWatcher(ctx, rt.Params.Paths, onReloadPrinter(rt.Params.Output)); err != nil {
|
if err := rt.startWatcher(ctx, rt.Params.Paths, onReloadPrinter(rt.Params.Output)); err != nil {
|
||||||
fmt.Fprintln(rt.Params.Output, "error opening watch:", err)
|
fmt.Fprintln(rt.Params.Output, "error opening watch:", err)
|
||||||
os.Exit(1)
|
os.Exit(1) //nolint:gocritic
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -140,10 +140,8 @@ func testRuntimeProcessWatchEvents(t *testing.T, asBundle bool, readAst bool) {
|
|||||||
if ast.Compare(val, exp) == 0 {
|
if ast.Compare(val, exp) == 0 {
|
||||||
return // success
|
return // success
|
||||||
}
|
}
|
||||||
} else {
|
} else if reflect.DeepEqual(val, expected) {
|
||||||
if reflect.DeepEqual(val, expected) {
|
return // success
|
||||||
return // success
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1402,7 +1400,7 @@ func TestGracefulTracerShutdown(t *testing.T) {
|
|||||||
logger := testLog.New()
|
logger := testLog.New()
|
||||||
|
|
||||||
params := NewParams()
|
params := NewParams()
|
||||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||||
params.Addrs = &[]string{"localhost:0"}
|
params.Addrs = &[]string{"localhost:0"}
|
||||||
params.GracefulShutdownPeriod = 1
|
params.GracefulShutdownPeriod = 1
|
||||||
params.Logger = logger
|
params.Logger = logger
|
||||||
@@ -1603,7 +1601,7 @@ func TestRuntimeWithExplicitMetricConfiguration(t *testing.T) {
|
|||||||
|
|
||||||
test.WithTempFS(fs, func(testDirRoot string) {
|
test.WithTempFS(fs, func(testDirRoot string) {
|
||||||
params := NewParams()
|
params := NewParams()
|
||||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||||
|
|
||||||
_, err := NewRuntime(context.Background(), params)
|
_, err := NewRuntime(context.Background(), params)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1619,7 +1617,7 @@ func TestRuntimeWithExplicitBadMetricConfiguration(t *testing.T) {
|
|||||||
|
|
||||||
test.WithTempFS(fs, func(testDirRoot string) {
|
test.WithTempFS(fs, func(testDirRoot string) {
|
||||||
params := NewParams()
|
params := NewParams()
|
||||||
params.ConfigFile = filepath.Join(testDirRoot, "/config.yaml")
|
params.ConfigFile = filepath.Join(testDirRoot, "config.yaml")
|
||||||
|
|
||||||
_, err := NewRuntime(context.Background(), params)
|
_, err := NewRuntime(context.Background(), params)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
|
|||||||
+1
-1
@@ -276,7 +276,7 @@ func (s *Server) handleOCIBundles(w http.ResponseWriter, r *http.Request) {
|
|||||||
tag := "" // image tag used in request path verification
|
tag := "" // image tag used in request path verification
|
||||||
repo := "" // image repo used in request path verification
|
repo := "" // image repo used in request path verification
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
//get first key that matches request url pattern
|
// get first key that matches request url pattern
|
||||||
for key := range s.bundles {
|
for key := range s.bundles {
|
||||||
// extract tag
|
// extract tag
|
||||||
parsedRef := strings.Split(key, ":")
|
parsedRef := strings.Split(key, ":")
|
||||||
|
|||||||
@@ -268,13 +268,9 @@ func TestBasicEscapeError(t *testing.T) {
|
|||||||
|
|
||||||
req.URL.Path = `/invalid/path/foo%LALALA`
|
req.URL.Path = `/invalid/path/foo%LALALA`
|
||||||
|
|
||||||
compiler := func() *ast.Compiler {
|
|
||||||
return ast.NewCompiler()
|
|
||||||
}
|
|
||||||
|
|
||||||
store := inmem.New()
|
store := inmem.New()
|
||||||
|
|
||||||
NewBasic(&mockHandler{}, compiler, store).ServeHTTP(recorder, req)
|
NewBasic(&mockHandler{}, ast.NewCompiler, store).ServeHTTP(recorder, req)
|
||||||
|
|
||||||
if recorder.Code != http.StatusBadRequest {
|
if recorder.Code != http.StatusBadRequest {
|
||||||
t.Fatalf("Expected bad request but got: %v", recorder)
|
t.Fatalf("Expected bad request but got: %v", recorder)
|
||||||
|
|||||||
@@ -131,7 +131,7 @@ func (w *compressResponseWriter) doCompressedResponse() error {
|
|||||||
w.Header().Del(contentLengthHeader)
|
w.Header().Del(contentLengthHeader)
|
||||||
w.writeHeader()
|
w.writeHeader()
|
||||||
// there's nothing to write
|
// there's nothing to write
|
||||||
if len(w.buffer) <= 0 {
|
if len(w.buffer) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
gzipWriter := gzipPool.Get().(*gzip.Writer)
|
gzipWriter := gzipPool.Get().(*gzip.Writer)
|
||||||
|
|||||||
+3
-3
@@ -581,9 +581,9 @@ func (b *baseHTTPListener) Type() httpListenerType {
|
|||||||
return b.t
|
return b.t
|
||||||
}
|
}
|
||||||
|
|
||||||
func isMinTLSVersionSupported(TLSVersion uint16) bool {
|
func isMinTLSVersionSupported(tlsVersion uint16) bool {
|
||||||
for _, version := range supportedTLSVersions {
|
for _, version := range supportedTLSVersions {
|
||||||
if TLSVersion == version {
|
if tlsVersion == version {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2722,7 +2722,7 @@ func getBoolParam(url *url.URL, name string, ifEmpty bool) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, x := range p {
|
for _, x := range p {
|
||||||
if strings.ToLower(x) == "true" {
|
if strings.EqualFold(x, "true") {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -207,7 +207,7 @@ func (t TraceV1) MarshalJSON() ([]byte, error) {
|
|||||||
|
|
||||||
// UnmarshalJSON unmarshals the TraceV1 from a JSON representation.
|
// UnmarshalJSON unmarshals the TraceV1 from a JSON representation.
|
||||||
func (t *TraceV1) UnmarshalJSON(b []byte) error {
|
func (t *TraceV1) UnmarshalJSON(b []byte) error {
|
||||||
*t = TraceV1(b[:])
|
*t = TraceV1(b)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -56,8 +56,7 @@ func (err *Error) Error() string {
|
|||||||
|
|
||||||
// IsNotFound returns true if this error is a NotFoundErr.
|
// IsNotFound returns true if this error is a NotFoundErr.
|
||||||
func IsNotFound(err error) bool {
|
func IsNotFound(err error) bool {
|
||||||
switch err := err.(type) {
|
if err, ok := err.(*Error); ok {
|
||||||
case *Error:
|
|
||||||
return err.Code == NotFoundErr
|
return err.Code == NotFoundErr
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -1109,10 +1109,8 @@ func TestInMemoryTriggers(t *testing.T) {
|
|||||||
if err != nil || ast.Compare(expAstValue, result) != 0 {
|
if err != nil || ast.Compare(expAstValue, result) != 0 {
|
||||||
t.Fatalf("Expected result to be %v for trigger read but got: %v (err: %v)", expectedValue, result, err)
|
t.Fatalf("Expected result to be %v for trigger read but got: %v (err: %v)", expectedValue, result, err)
|
||||||
}
|
}
|
||||||
} else {
|
} else if err != nil || !reflect.DeepEqual(result, expectedValue) {
|
||||||
if err != nil || !reflect.DeepEqual(result, expectedValue) {
|
t.Fatalf("Expected result to be %v for trigger read but got: %v (err: %v)", expectedValue, result, err)
|
||||||
t.Fatalf("Expected result to be %v for trigger read but got: %v (err: %v)", expectedValue, result, err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
event = evt
|
event = evt
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ func copyEntry(sourceRoot string, sourceRegoVersion ast.RegoVersion, e os.DirEnt
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Format test modules
|
// Format test modules
|
||||||
for _, testCase := range testCases.Cases {
|
for _, testCase := range testCases.Cases { //nolint:gocritic
|
||||||
for i, module := range testCase.Modules {
|
for i, module := range testCase.Modules {
|
||||||
bs, err := format.SourceWithOpts(fmt.Sprintf("mod%d.rego", i), []byte(module),
|
bs, err := format.SourceWithOpts(fmt.Sprintf("mod%d.rego", i), []byte(module),
|
||||||
format.Opts{
|
format.Opts{
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ func runAuthzBenchmark(b *testing.B, mode testAuthz.InputMode, numPaths int) {
|
|||||||
b.Fatal(err)
|
b.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
queryPath := strings.Replace(testAuthz.AllowQuery, ".", "/", -1)
|
queryPath := strings.ReplaceAll(testAuthz.AllowQuery, ".", "/")
|
||||||
url := testRuntime.URL() + "/v1/" + queryPath
|
url := testRuntime.URL() + "/v1/" + queryPath
|
||||||
|
|
||||||
input, expected := testAuthz.GenerateInput(profile, mode)
|
input, expected := testAuthz.GenerateInput(profile, mode)
|
||||||
|
|||||||
@@ -55,7 +55,6 @@ func TestH2CHTTPListeners(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("failed to GET %s: %s", u, err)
|
t.Fatalf("failed to GET %s: %s", u, err)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if expected, actual := http.StatusOK, resp.StatusCode; expected != actual {
|
if expected, actual := http.StatusOK, resp.StatusCode; expected != actual {
|
||||||
t.Errorf("resp status: expected %d, got %d", expected, actual)
|
t.Errorf("resp status: expected %d, got %d", expected, actual)
|
||||||
@@ -63,5 +62,7 @@ func TestH2CHTTPListeners(t *testing.T) {
|
|||||||
if expected, actual := 2, resp.ProtoMajor; expected != actual {
|
if expected, actual := 2, resp.ProtoMajor; expected != actual {
|
||||||
t.Errorf("resp.ProtoMajor: expected %d, got %d", expected, actual)
|
t.Errorf("resp.ProtoMajor: expected %d, got %d", expected, actual)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
resp.Body.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -353,19 +352,19 @@ func (t *TestRuntime) UploadData(data io.Reader) error {
|
|||||||
func (t *TestRuntime) UploadDataToPath(path string, data io.Reader) error {
|
func (t *TestRuntime) UploadDataToPath(path string, data io.Reader) error {
|
||||||
client := &http.Client{}
|
client := &http.Client{}
|
||||||
|
|
||||||
urlPath := strings.TrimSuffix(filepath.Join("/v1/data"+path), "/")
|
urlPath := strings.TrimSuffix("/v1/data"+path, "/")
|
||||||
|
|
||||||
req, err := http.NewRequest("PUT", t.URL()+urlPath, data)
|
req, err := http.NewRequest("PUT", t.URL()+urlPath, data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("Unexpected error creating request: %s", err)
|
return fmt.Errorf("unexpected error creating request: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("Failed to PUT data: %s", err)
|
return fmt.Errorf("failed to PUT data: %s", err)
|
||||||
}
|
}
|
||||||
if resp.StatusCode != http.StatusNoContent {
|
if resp.StatusCode != http.StatusNoContent {
|
||||||
return fmt.Errorf("Unexpected response: %d %s", resp.StatusCode, resp.Status)
|
return fmt.Errorf("unexpected response: %d %s", resp.StatusCode, resp.Status)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ type compiledTestCase struct {
|
|||||||
|
|
||||||
func compileTestCases(ctx context.Context, tests cases.Set) (*compiledTestCaseSet, error) {
|
func compileTestCases(ctx context.Context, tests cases.Set) (*compiledTestCaseSet, error) {
|
||||||
result := make([]compiledTestCase, 0, len(tests.Cases))
|
result := make([]compiledTestCase, 0, len(tests.Cases))
|
||||||
for _, tc := range tests.Cases {
|
for _, tc := range tests.Cases { //nolint:gocritic
|
||||||
|
|
||||||
var numExpects int
|
var numExpects int
|
||||||
|
|
||||||
@@ -171,7 +171,7 @@ func run(params params) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
dst := strings.Replace(files[i].Name(), ".yaml", ".json", -1)
|
dst := strings.ReplaceAll(files[i].Name(), ".yaml", ".json")
|
||||||
return writeFile(tw, dst, bs)
|
return writeFile(tw, dst, bs)
|
||||||
}()
|
}()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -219,7 +219,7 @@ func (r PrettyReporter) fmtBenchmark(tr *Result) string {
|
|||||||
// This converts the test case name like data.foo.bar.test_auth to be more
|
// This converts the test case name like data.foo.bar.test_auth to be more
|
||||||
// like BenchmarkDataFooBarTestAuth.
|
// like BenchmarkDataFooBarTestAuth.
|
||||||
camelCaseName := ""
|
camelCaseName := ""
|
||||||
for _, part := range strings.Split(strings.Replace(name, "_", ".", -1), ".") {
|
for _, part := range strings.Split(strings.ReplaceAll(name, "_", "."), ".") {
|
||||||
camelCaseName += strings.Title(part) //nolint:staticcheck // SA1019, no unicode here
|
camelCaseName += strings.Title(part) //nolint:staticcheck // SA1019, no unicode here
|
||||||
}
|
}
|
||||||
name = "Benchmark" + camelCaseName
|
name = "Benchmark" + camelCaseName
|
||||||
|
|||||||
@@ -314,12 +314,12 @@ func (b *bindingsArrayHashmap) Put(key *ast.Term, value value) {
|
|||||||
if b.a == nil {
|
if b.a == nil {
|
||||||
b.a = new([maxLinearScan]bindingArrayKeyValue)
|
b.a = new([maxLinearScan]bindingArrayKeyValue)
|
||||||
} else if i := b.find(key); i >= 0 {
|
} else if i := b.find(key); i >= 0 {
|
||||||
(*b.a)[i].value = value
|
b.a[i].value = value
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if b.n < maxLinearScan {
|
if b.n < maxLinearScan {
|
||||||
(*b.a)[b.n] = bindingArrayKeyValue{key, value}
|
b.a[b.n] = bindingArrayKeyValue{key, value}
|
||||||
b.n++
|
b.n++
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -342,7 +342,7 @@ func (b *bindingsArrayHashmap) Put(key *ast.Term, value value) {
|
|||||||
func (b *bindingsArrayHashmap) Get(key *ast.Term) (value, bool) {
|
func (b *bindingsArrayHashmap) Get(key *ast.Term) (value, bool) {
|
||||||
if b.m == nil {
|
if b.m == nil {
|
||||||
if i := b.find(key); i >= 0 {
|
if i := b.find(key); i >= 0 {
|
||||||
return (*b.a)[i].value, true
|
return b.a[i].value, true
|
||||||
}
|
}
|
||||||
|
|
||||||
return value{}, false
|
return value{}, false
|
||||||
@@ -361,7 +361,7 @@ func (b *bindingsArrayHashmap) Delete(key *ast.Term) {
|
|||||||
if i := b.find(key); i >= 0 {
|
if i := b.find(key); i >= 0 {
|
||||||
n := b.n - 1
|
n := b.n - 1
|
||||||
if i < n {
|
if i < n {
|
||||||
(*b.a)[i] = (*b.a)[n]
|
b.a[i] = b.a[n]
|
||||||
}
|
}
|
||||||
|
|
||||||
b.n = n
|
b.n = n
|
||||||
@@ -375,7 +375,7 @@ func (b *bindingsArrayHashmap) Delete(key *ast.Term) {
|
|||||||
func (b *bindingsArrayHashmap) Iter(f func(k *ast.Term, v value) bool) {
|
func (b *bindingsArrayHashmap) Iter(f func(k *ast.Term, v value) bool) {
|
||||||
if b.m == nil {
|
if b.m == nil {
|
||||||
for i := range b.n {
|
for i := range b.n {
|
||||||
if f((*b.a)[i].key, (*b.a)[i].value) {
|
if f(b.a[i].key, b.a[i].value) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -392,7 +392,7 @@ func (b *bindingsArrayHashmap) Iter(f func(k *ast.Term, v value) bool) {
|
|||||||
func (b *bindingsArrayHashmap) find(key *ast.Term) int {
|
func (b *bindingsArrayHashmap) find(key *ast.Term) int {
|
||||||
v := key.Value.(ast.Var)
|
v := key.Value.(ast.Var)
|
||||||
for i := range b.n {
|
for i := range b.n {
|
||||||
if (*b.a)[i].key.Value.(ast.Var) == v {
|
if b.a[i].key.Value.(ast.Var) == v {
|
||||||
return i
|
return i
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-6
@@ -46,7 +46,7 @@ func builtinToNumber(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term
|
|||||||
return builtins.NewOperandTypeErr(1, operands[0].Value, "null", "boolean", "number", "string")
|
return builtins.NewOperandTypeErr(1, operands[0].Value, "null", "boolean", "number", "string")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated in v0.13.0.
|
// Deprecated: deprecated in v0.13.0.
|
||||||
func builtinToArray(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
func builtinToArray(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||||
switch val := operands[0].Value.(type) {
|
switch val := operands[0].Value.(type) {
|
||||||
case *ast.Array:
|
case *ast.Array:
|
||||||
@@ -64,7 +64,7 @@ func builtinToArray(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated in v0.13.0.
|
// Deprecated: deprecated in v0.13.0.
|
||||||
func builtinToSet(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
func builtinToSet(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||||
switch val := operands[0].Value.(type) {
|
switch val := operands[0].Value.(type) {
|
||||||
case *ast.Array:
|
case *ast.Array:
|
||||||
@@ -80,7 +80,7 @@ func builtinToSet(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) e
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated in v0.13.0.
|
// Deprecated: deprecated in v0.13.0.
|
||||||
func builtinToString(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
func builtinToString(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||||
switch val := operands[0].Value.(type) {
|
switch val := operands[0].Value.(type) {
|
||||||
case ast.String:
|
case ast.String:
|
||||||
@@ -90,7 +90,7 @@ func builtinToString(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated in v0.13.0.
|
// Deprecated: deprecated in v0.13.0.
|
||||||
func builtinToBoolean(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
func builtinToBoolean(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||||
switch val := operands[0].Value.(type) {
|
switch val := operands[0].Value.(type) {
|
||||||
case ast.Boolean:
|
case ast.Boolean:
|
||||||
@@ -100,7 +100,7 @@ func builtinToBoolean(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Ter
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated in v0.13.0.
|
// Deprecated: deprecated in v0.13.0.
|
||||||
func builtinToNull(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
func builtinToNull(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||||
switch val := operands[0].Value.(type) {
|
switch val := operands[0].Value.(type) {
|
||||||
case ast.Null:
|
case ast.Null:
|
||||||
@@ -110,7 +110,7 @@ func builtinToNull(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated in v0.13.0.
|
// Deprecated: deprecated in v0.13.0.
|
||||||
func builtinToObject(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
func builtinToObject(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
|
||||||
switch val := operands[0].Value.(type) {
|
switch val := operands[0].Value.(type) {
|
||||||
case ast.Object:
|
case ast.Object:
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user