Commit Graph

61 Commits

Author SHA1 Message Date
Anders Eknert e43ef0a979 Use any in place of interface{} (#7566)
Earlier this evening I tried to run the Go
[modernize](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/modernize)
analyzer on OPA. That didn't go as planned:

- https://github.com/golang/go/issues/73661
- https://github.com/golang/go/issues/73663

While we wait for that to be fixed, I figured an old-fashioned
search-and-replace across the repo may work for at least the
`interface{}` to `any` conversion. That should help make it easier
to see the other fixes as applied by the modernize tool once it has
had those issues resolved.

Signed-off-by: Anders Eknert <anders@styra.com>
2025-05-12 13:57:48 +02:00
Johan Fylling a179a24c48 v1 API
All packages, except for `cmd` and `internal`, have been moved into a new `v1` root package.

Old packages are kept for backwards-compatibility reasons. All contained code is replaced with simple type aliases and proxy functions to `v1` implementations.

Old packages default to the Rego v0 syntax, new `v1` packages default to the Rego v1 syntax.

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-12-12 15:27:34 +01:00
Johan Fylling 7bb6dbe36b Preparing for v1 API
Moving (most) source to v1 root package to prepare for v0/v1 API separation.

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-12-12 15:09:03 +01:00
Stephan Renatus 20885fe4a9 golangci: bump version, addess all new findings
The previous version has been failing without any good reason for me,
so let's try this.

About the version pick: It's not the latest version (v1.62.0 at the
moment), because that would introduce a new revive rule,
redeclares-builtin-id, and that flags every variable called `min` or
`max` in the code base. I had started addressing these, but they were
just too many.

The new issues related to this version are mostly that it complains
whenever it finds a non-static string that makes its way into a printf-
like function. However, that's a common pattern in some place here, so
I've sprinkled some nolint:govet on it.

Signed-off-by: Stephan Renatus <stephan@styra.com>
2024-11-14 20:36:50 +01:00
Philip Conrad f32ad09458 util+plugins: Fix potential memory leaks with explicit timer cancellation. (#7089)
This commit adds a utility for explicitly creating cancelable timers, to avoid
possible memory leaks caused by some `<-time.After` timer receives in select
statements never being GC'd properly. This issue is fixed in Go 1.23, but
since we're still on Go 1.21, this will resolve the possibility of leaks in
the mean time.

Signed-off-by: Philip Conrad <philip@chariot-chaser.net>
2024-10-02 15:56:56 -04:00
Anders Eknert efef7d238e Strip BOM from input JSON when found
Fixes #6988

Signed-off-by: Anders Eknert <anders@eknert.com>
2024-09-04 14:42:48 -07:00
Johan Fylling 3ac5104087 debug: Adding debugger SDK (#6877)
This is an experimental feature, subject to change.

Fixes: #6876

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-08-28 20:26:52 +02:00
Philip Conrad ee9ab0bf75 util+server: Fix bug around chunked request handling. (#6906)
This commit fixes a request handling bug introduced in #6868, which
caused OPA to treat all incoming chunked requests as if they had
zero-length request bodies.

The fix detects cases where the request body size is unknown in the
DecodingLimits handler, and propagates a request context key down to
the `util.ReadMaybeCompressedBody` function, allowing it to correctly
select between using the original `io.ReadAll` style for chunked
requests, or the newer preallocated buffers approach (for requests of
known size).

This change has a small, but barely visible performance impact for large
requests (<5% increase in GC pauses for a 1GB request JSON blob), and
minimal, if any, effect on RPS under load.

Fixes: #6904

Signed-off-by: Philip Conrad <philip@chariot-chaser.net>
2024-08-01 15:22:51 -04:00
Philip Conrad c5706eef7c server+util: Limit max request sizes, prealloc request buffers (#6868)
This commit introduces a few major changes:
 - (Breaking change) Limits now exist for maximum request body sizes.
 - Buffers are preallocated for reading request bodies.
 - Buffers are preallocated for decompressing request bodies.
 - Gzip decoder instances are reused in a `sync.Pool` across requests.

The effect on garbage collection is dramatically fewer GC pauses, giving
a roughly 9% RPS improvement in load tests with gzipped request bodies.
For larger request sizes, the number of GC pauses is dramatically
reduced, although the peak pause time may increase by a few percent.

Implementation notes:
 - The DecodingLimits handler enforces the max request body size both
   through a Content-Length check, and a MaxBytesReader wrapper around
   the payload.
 - The DecodingLimits handler passes the gzip payload size limit down
   using a context key.

Signed-off-by: Philip Conrad <philipaconrad@gmail.com>
2024-07-22 13:15:08 -04:00
Tyler Schade 5226cf3137 add ability for opa inspect to inspect a single file outside of any bundle (#6873)
add ability for opa inspect to inspect a single file outside of any bundle

Signed-off-by: Tyler Schade <tyler.schade@solo.io>
2024-07-21 20:22:52 +02:00
Philip Conrad 4e01537fe7 server/authorizer: Fix gzip payload handling. (#6825)
This PR fixes an issue where an OPA running authorization policies would
be unable to handle gzipped request bodies.

Example OPA CLI setup:

    opa run -s --authorization=basic

Example request:

    echo -n '{}' | gzip | curl -H "Content-Encoding: gzip" --data-binary @- http://127.0.0.1:8181/v1/data

This would result in unhelpful error messages, like:

```json
{
  "code": "invalid_parameter",
  "message": "invalid character '\\x1f' looking for beginning of value"
}
```

The cause was that the request body handling system in the
`server/authorizer` package did not take gzipped payloads into
account. The fix was to borrow the gzip request body handling function
from `server/server.go`, to transparently decompress the body when
needed.

Fixes: #6804

Signed-off-by: Philip Conrad <philipaconrad@gmail.com>
2024-06-27 09:55:19 +02:00
occupyhabit d6c8c1b51b chore: remove repetitive words
Signed-off-by: occupyhabit <wangmengjiao@outlook.com>
2024-03-25 11:28:12 -07:00
Johan Fylling b36151d992 Adding --v1-compatible flag to all previously unsupported command line commands (#6521)
In addition to those commands already supported:

* build
* check
* eval
* fmt
* test

support has been added to the following commands:

* `bench`
* `deps`
* `exec`
* `inspect`
* `parse`
* `run` (command `server` and `REPL`)

Fixes: #6520

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-01-24 15:42:32 +01:00
Manuel Rüger 9cab6c95cf chore: Replace ghodss/yaml with sigs.k8s.io/yaml (#6195)
This is a fork that is maintained by the kubernetes community.

https://github.com/kubernetes-sigs/yaml

Signed-off-by: Manuel Rüger <manuel@rueg.eu>
2023-08-30 15:08:36 +02:00
Johan Fylling 304be03e98 cmd: Making test watch-mode tests more robust (#6019)
* Waiting for output buffer to contain expected data rather than making exact matches on the entire content.
* Not aborting watcher on encountered errors

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2023-06-19 10:51:28 +02:00
Stephan Renatus cca81970d1 loader: change extension handler type (#6015)
This

1. changes the extension.Handler type to make it more flexible
2. simplifies the extension usage -- it used to be called in many places,
   but it could all be handled through util.Unmarshal and util.UnmarshalJSON
   instead

We've previously marked it as "EXPERIMENTAL", so we should have enough
leeway to change this now.

NOTE: As a consequence of (2.), we're no longer accepting trailing data for
json files loaded with OPA. I believe it wasn't intentional to ignore bad data
before -- now, it'll be an error.

Signed-off-by: Stephan Renatus <stephan@styra.com>
2023-06-16 09:37:33 +02:00
Stephan Renatus 34d5da43a5 loader: allow extensions (experimental) (#5940)
This extension to the loader package allows experimenting with data formats that are not JSON, but pretend to be.

Signed-off-by: Stephan Renatus <stephan@styra.com>
Co-authored-by: kevinstyra <83973046+kevinstyra@users.noreply.github.com>
2023-05-24 08:45:06 +02:00
Kieran Othen b65c68e340 Add ability to load bundles from an arbitrary filesystem
Support OPA Client SDK programs loading bundles from an arbitraty filesystem, such as an in-memory filesystem, which unlocks additional uses that include compiling a bundle to an intermediate representation from a client program rather than the OPA command line.

Fixes #5833

bundle: Add filesystem support
Soften constraint in `Equal` method to support bundle comparison for rootless filesystems, eg treat "/file" and "file" as equal for both URLs and Paths
Add `WithPathFormat` for `DirectoryLoader` builders to centralise logic for how paths are returned during file traversal, ie in `NextFile`
Add support for specifiying the root directory for `dirLoaderFS`

compile: Add filesystem support
Add `WithFS` builder helper to pass into `initload.LoadPaths` to load bundles from a filesystem

internal/runtime/init: Add filesystem support
Pass newly supplied `fsys fs.FS` parameter in `LoadPaths` into file loader builder

loader: Add filesystem support
Add new `GetBundleDirectLoaderFS` which can load bundles from the supplied filesystem

runtime: Add filesystem support
Pass-through nil parameter as `fsys fs.FS` parameter into `initLoad.LoadPaths` (OPA servers/repls are not in scope for loading from filesystem)

util/test: Add in-memory filesystem support
Add new `WithTestFS` helper to allow tests that currently use `WithTempFS` to choose between a disk-based or memory-based filesystem - now used throughout `compile_test`

Signed-off-by: Kieran Othen <kieran.othen@mac.com>
2023-04-26 12:28:17 -07:00
Stephan Renatus c9ec05d3fe bump: go 1.19.5 -> 1.20.1
This PR bumps go to 1.20.1 (https://go.dev/doc/go1.20) which
addresses the following vulnerabilities:
https://pkg.go.dev/vuln/GO-2023-1571
https://pkg.go.dev/vuln/GO-2023-1570
https://pkg.go.dev/vuln/GO-2023-1568

As part of the migration, general Golang
stdlib deprecations and test failures were addressed as well.
Some of those changes are:

* Bump golangci-lint for support with go1.20
* Migrate rand.Seed() calls to the newer rand.New(rand.NewSource(seed))

Co-authored-by: Stephan Renatus <stephan@styra.com>
Co-authored-by: Philip Conrad <philipaconrad@gmail.com>

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2023-02-21 13:51:23 -08:00
Edward Paget 4e66158fb7 topdown: cache undefined rule evaluations (#5523)
With this change, `undefined` outcomes of complete rule evaluations
are now also cached. Previously, only defined results had been cached,
and empty partial sets/objects.

In the case of partial rules with string keys, the introduction of ref heads
changed how they had been evaluated: Before, they had been evaluated
as partial sets, and thus got cached when empty. After, they had been
evaluated as complete rules (with ref heads), and if they were undefined,
they had _not_ been cached. This caused a performance regression.

Fixes #593.

Signed-off-by: Edward Paget <edward.paget@chime.com>
2023-01-06 11:13:10 +01:00
Anders Eknert 50d4e31d6b chore: Use t.Setenv in tests (#5321)
And enable the `tenv` linter for the future.

Also, bump version of golangci-lint and fix some new
warnings that came from that.

Signed-off-by: Anders Eknert <anders@eknert.com>
2022-10-27 17:44:56 +02:00
Anders Eknert 9a597feb2e chore: don't use the deprecated ioutil functions (#5319)
Another annoyance removed :P

Signed-off-by: Anders Eknert <anders@eknert.com>
2022-10-27 14:30:26 +02:00
Stephan Renatus a8b6395faa util/backoff: seed math/rand source (#5124)
It has a negligible impact, but since security scanners like gosec will pick
this up, let's do it in a way that'll pass inspection.

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2022-09-12 18:01:15 +02:00
Stephan Renatus 927f631472 ci: skip flakey darwin tests on PR runs (#4749)
Some care has been taken that these tests still run on development
machines. They'll only be skipped if the following is true:

1. the os is darwin
2. the GITHUB_ACTIONS env var is set to something

This approach, adding the skip calls manually on a case-by-case basis,
should allow us some fine-grained control. If we had used build tags,
we'd only be able to skip all the tests in one file together.

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2022-06-07 14:38:30 +02:00
Stephan Renatus 61b8c1463d util/Unmarshal: if it's JSON, skip YAMLtoJSON (#4681)
This helper accepts JSON or YAML, and used to do this:

1. For YAML input, yaml.YAMLToJSON would parse it as yaml, marshal it to
   JSON, and pass that back out to be passed to UnmarshalJSON
2. For JSON input, yaml.YAMLToJSON would also parse it as yaml, marshal it
   to JSON, and pass that back out to UnmarshalJSON

Issue #4673 has shown that the theoretical "superset" propery of YAML doesn't
seem to hold in all cases.

So now, we'll do this:

1. For YAML input, yaml.YAMLToJSON would parse it as yaml, marshal it to
   JSON, and pass that back out to be passed to UnmarshalJSON
2. For JSON input, json.Valid will determine that it's JSON, and we'll
   feed it into UnmarshalJSON as-is.

The YAML path (1.) still seems suboptimal, but I also suspect that JSON is
more common. Also, this change shouldn't make the YAML path much worse:
determining that yaml string isn't valid JSON should be quick.

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2022-05-12 20:30:10 +02:00
Johan Fylling 987148a02b ast: Adding generic annotations (rich metadata) (#4332)
Relates to: #4331
Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2022-02-17 12:19:31 +01:00
Will Beason 3be1d08b87 Change check-lint to use golangci-lint (#3465)
golint is deprecated. The author of the code no longer supports the
codebase. golangci-lint is faster than golint, and is in use by other
opa repositories (e.g. Gatekeeper).

This commit changes tools.go to reference golangci (so it ends up in
vendor) and modifies check-lint to use golangci instead.

Breaking API Changes:

- plugins/rest/rest.go: Fix typo "AllowInsureTLS" -> "AllowInsecureTLS"
- storage/errors.go: Removed unused IndexingNotSupportedErr

Signed-off-by: Will Beason <willbeason@google.com>
2021-05-19 07:52:02 +02:00
Stephan Renatus 58be4ee36b cleanup: remove test.Subtest (#3144)
Go 1.7 was so long ago. New code doesn't use this anymore, either,
so let's get rid of it.

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2021-02-11 19:59:54 +01:00
Stephan Renatus 01d2554f80 wasm/sdk: add benchmarks (#3103)
This is porting some of the existing topdown tests --
but run with the Wasm SDK. I've factored out the data
generation bits into the util package; using it in both places.

I've come to believe that whatever memory usage data we're
collecting there is probably bogus: too many of my runs yield

    1597 B/op	      41 allocs/op

regardless of the input size. I'd think that the problem lies in
the boundary crossing to cgo-land, but I have yet to find a
source for that.

That aside, disabling the allocation reporting, and gathering
benchmark data for the run times is probably already useful,
so let's go with that.

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2021-02-03 14:02:50 +01:00
Olivier Lemasle c9e1d024e1 tests: fix tests failing on 32-bit arch
E.g. GOARCH=386 go test ./...

- Some tests were failing because of Int overflow;
- Test ExampleRego_custom_function_caching was failing
  because it was dependent of rand default seed on 64bits arch.

Signed-off-by: Olivier Lemasle <o.lemasle@gmail.com>
2020-10-28 12:14:40 -04:00
Torin Sandall 9cc0c705c2 util: Fix flakey wait function unit tests
The delays were too aggressive. Bumping them to be orders of magnitude
in difference.

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2020-08-11 09:35:55 -04:00
mikaelcabot 47ecd762d7 feat: server wait for plugins
A new flag introduced `ready-timeout`.
This flag controls if and for how long OPA server will wait for
configured bundles and plugins to be activated/ready before listening for traffic.
A value of 0 or less means no wait is exercised.

Signed-off-by: mikaelcabot <mikaelcabot@gmail.com>
2020-08-06 14:34:27 -07:00
Torin Sandall 2975ed6d70 topdown: Mark test run/assert functions as helpers
Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2020-06-23 09:20:32 -04:00
katsew 65a2b187c4 util: Fix UnmarshalJSON parses invalid json in some cases
Fixes: #2331

Signed-off-by: katsew <y.katsew@gmail.com>
2020-04-30 19:54:53 -07:00
Patrick East 2d22309715 cmd/test: --explain now turns on verbose output
Rather than requiring both `--explain` and `--verbose`/`-v` a user
just needs to pass in `--explain` and verbose output will be enabled.

Fixes: #2069
Signed-off-by: Patrick East <east.patrick@gmail.com>
2020-04-06 09:56:24 -07:00
Patrick East b48c534722 Run make fmt with new goimports cmd
Signed-off-by: Patrick East <east.patrick@gmail.com>
2019-09-27 09:55:11 -04:00
Patrick East e46b0cab4e util: Change tempfs file prefix to opa_test
It was `loader_test` but we are using this helper in many more places
than just the loader tests. It makes for somewhat confusing results
when there are orphaned test files with `loader_test` when they
didn't actually come from the loader.

Signed-off-by: Patrick East <east.patrick@gmail.com>
2019-09-04 13:39:52 -06:00
Guangming Wang 952437ebe3 cleanup: fix some typos in code comment
Signed-off-by: Guangming Wang <guangming.wang@daocloud.io>
2019-08-21 09:24:37 -04:00
Patrick East 346aa964e8 Add support for multiple bundles
This change brings in support for multiple bundles to be downloaded
and activated OPA.

This is enabled by using the new config option `bundles` to define
the bundles, and deprecates the older `bundle` option.

The new `bundles` keyword and structure is propagated through to the
decision logs, status API, provenance, stored manifests, etc. Check
out the doc changes for all the updated structures.

That being said any existing configuration using `bundle` will *not*
see the new structure, everything is intended to be backwards
compatible (almost to a fault).

Fixes: #721

Signed-off-by: Patrick East <east.patrick@gmail.com>
2019-07-31 03:43:38 -04:00
Patrick East c2d2d1b7fa Remove extra character in util/close.go
Signed-off-by: Patrick East <east.patrick@gmail.com>
2019-07-31 03:43:38 -04:00
Varun Mathur 8885997264 Added ability to dynamically load .so objects and the respective required testing.
Signed-off-by: Varun Mathur <varun.mathur@live.com>
2018-08-16 13:11:49 -07:00
Stephan Renatus 38dd5a8110 json_test: add util.Reference test
Left this as an extra commit for now, as I'm not sure if you'd think it's of
much value... will squash or drop accordingly.

Signed-off-by: Stephan Renatus <srenatus@chef.io>
2018-05-15 08:57:12 -07:00
Stephan Renatus 004e6a80e7 storage/inmem: support pointers to structs
This should fix #722. It's a slight variation of the code snippet provided
there:

I wasn't sure what the reflect.Interface part was for, so this is using
only reflect.Ptr. Also, there existing tests would fail without the added
check for reflect.Invalid.

Adds a test case for inmem -- in a new method, as I couldn't quite fit it
into the schema of TestInMemoryWrite.

Also, util.Reference() ensures that the returned value is a pointer to
something -- and not a pointer to a pointer to something. While this wasn't
part of the issue #722, it felt weird not to solve the general problem, but
only the edge case. :)

Signed-off-by: Stephan Renatus <srenatus@chef.io>
2018-05-15 08:57:12 -07:00
Teemu Koponen 59976cf20a Fix error formatting in test.
Signed-off-by: Teemu Koponen <koponen@styra.com>
2018-04-28 10:58:00 -07:00
Torin Sandall f131cfcff3 Add support for bundle downloading
Previously, policies and data had to be pushed into OPA via the REST API
or loaded via command line arguments at startup.

With these changes, OPA can now be configured to pull down bundles of
policy and data from remote HTTP servers. When a bundle is downloaded
successfully, the policies and data are loaded out of the bundle file
and inserted into storage.
2018-03-16 08:51:37 -07:00
Stephan Renatus bb05fb8067 util.RoundTrip(): use neighbouring UnmarshalJSON function
The test failures this had introduced before, from index_tests.go's
TestIndicesBuild, suggested that this is probably what we want.

Signed-off-by: Stephan Renatus <srenatus@chef.io>
2018-03-13 09:35:14 -07:00
Stephan Renatus 5b07711891 ast: allow passing in []string, not only []interface{}
With this, where before we've gotten

    ast: illegal value: []string

and had worked around it by converting all our []string inputs to
[]interface{}, it now would work to pass in the []string values as-is.

This adds a roundtrip through the JSON encoding to both the rego.Input,
and the inmem store's Write.

Signed-off-by: Stephan Renatus <srenatus@chef.io>
2018-03-13 09:35:14 -07:00
Torin Sandall c612260af4 Refactor file loading for OPA
The file loading logic implemented in the runtime package is generally
useful within OPA. These changes factor the file loading into a separate
package that can be reused without taking a dependency on the runtime.
2017-09-07 11:40:22 -07:00
Torin Sandall 18b2e363bd Refactor rule graph 2017-04-26 15:04:48 -07:00
Torin Sandall cf56ae2c23 Add BFS traversal and refactor DFS 2017-04-26 15:04:48 -07:00