Commit Graph

54 Commits

Author SHA1 Message Date
Ville Vesilehto f77322b3fb build: bump Go version requirement to 1.24 (#7839)
Go 1.23 is no longer supported as per Go release policy.

Changes:

- Use Go v1.24.6 as the project SDK requirement
- Apply lint fixes for Go 1.24
- Fix "non-constant format string in call" issues as seen in CI.

Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
2025-08-24 09:02:09 +02:00
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
Johan Fylling 5521453d87 cmd: Adding --v0-compatible flag (#7065)
To make OPA behave as v0.x post v1.0 release.
If used simultaneously with `--v1-compatible` flag, the `--v0-compatible` flag takes precedence.

Also, future-proofing `cmd` package tests for 1.0.

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-09-26 00:45:51 +02:00
Ashutosh Narkar 2c56293695 Add a new inter-query value cache to cache data across queries
This commit adds a new inter-query value cache that built-in
functions can use to cache information across queries.
For example, the `regex` and `glob` builtins can use this
to cache compiled regex and glob match patterns respectively.

The number of entries in the cache can be configured via the OPA
config. By default there is no limit.

Fixes: #6908

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2024-09-23 13:03:03 -07:00
Johan Fylling 2b1fba8a29 rego-v1: Future-proofing sdk pkg tests to be 1.0 compatible (#7027)
Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-09-19 18:15:03 +02:00
Johan Fylling 36dd26ac92 rego-v1: Future-proofing test pkg tests to be 1.0 compatible (#7030)
Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-09-18 14:18:00 +02:00
Johan Fylling b6eac1bd64 Adding documentation to the sdk.Options.V1Compatible option (#7023)
Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-09-16 16:00:27 +02:00
Ashutosh Narkar 44fa8ad64b Relax configuration check when Discovery is enabled
Previously if Discovery was enabled, other features like bundle downloading and status reporting could not be configured manually.
The reason for this was to prevent OPAs being deployed that could not be controlled through discovery. It's possible that
the system serving the discovered config is unaware of all options locally available in OPA. Hence, we relax the configuration
check when discovery is enabled so that the bootstrap configuration can contain plugin configurations. In case of conflicts,
the bootstrap configuration for plugins wins. These local configuration overrides from the bootstrap configuration are included
in the Status API messages so that management systems can get visibility into the local overrides.

**In general, the bootstrap configuration overrides the discovered configuration.** Previously this was not the case for all
configuration fields. For example, if the discovered configuration changes the `labels` section, only labels that are
additional compared to the bootstrap configuration are used, all other changes are ignored. This implies labels in the
bootstrap configuration override those in the discovered configuration. But for fields such as `default_decision`, `default_authorization_decision`,
`nd_builtin_cache`, the discovered configuration would override the bootstrap configuration. Now the behavior is more consistent
for the entire configuration and helps to avoid accidental configuration errors.

Fixes: #5722

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2024-04-23 15:32:37 -07:00
Francisco Edno 8f551d9baa sdk: fix bug while activating v1 bundle with the bundle plugin (#6689)
Fixing issue where active parser options aren't propagated to module reload during bundle activation.

Signed-off-by: Francisco Rodrigues <ednofco@gmail.com>
2024-04-11 13:13:31 +02:00
Francisco Rodrigues e0060ce6a1 sdk: expose manager options
This commit adds the possibility to configure the plugin manager with
custom options.

It will allow SDK users to override the options already provided by the
SDK and to futher customize it with configurations that were not
previously available. This is an advanced feature as it requires
some knowledge about the inner workings of OPA.

One use case for this is to provide a prometheus registerer and have the
status plugin metrics available for the client to use it in a
/metrics endpoint, for example.

resolves #6662

Signed-off-by: Francisco Rodrigues <ednofco@gmail.com>
2024-04-03 14:58:56 -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
Rudrakh Panigrahi f063c90275 Clean expired cache entries periodically
Regularly clean up of cache entries that have expired for a more efficient use of memory.
Introduce two new parameters to tune clean up frequency and threshold for forced FIFO eviction.

Fixes #5320

Signed-off-by: Rudrakh Panigrahi <rudrakh97@gmail.com>
2024-01-09 13:13:30 -08:00
robhafner 2ba393076d sdk_test: add environment variable tests (#6420)
Add two environment variable tests which illustrate how an environment variable can be used in OPA to verify a JWT.

Signed-off-by: Robert Hafner <robert.hafner@sas.com>
2023-11-17 15:46:39 +01:00
Anders Eknert a0ed11bbf2 SDK: Fix typo in test package error message (#6331)
Signed-off-by: Anders Eknert <anders@styra.com>
2023-10-20 08:51:19 +02:00
Brian Chhun 5cd774edf2 Add option for specifying decision ID to SDK
This allows clients to specify the decision ID for the decisions
returned by the `Decision` and `Partial` functions provided by the SDK
package. If not provided, a uniquely generated identifier will be
generated for the decision, just as before.

This option can be useful for clients that have already generated a
decision ID prior to calling OPA. It would then be convenient to pass
that decision ID through to OPA so decision logs use that same ID.

Signed-off-by: Brian Chhun <brian.chhun@chime.com>
2023-07-17 13:33:21 -07:00
Erik Paulson 4b627094e1 sdk: Fix decision log masking of input object
The sdk package allows you to pass arbitrary Go objects as the input
document. This is fine for evaluation (as long as the object can be
parsed to an AST), but is problematic for decision log masking, as the
masking logic expects the input on the event to be either a
map[string]interface{} or a []interface{}, and for inner types of the
object to also be similarly generic. Currently, the decision log masking
silently fails if the input object is not of the correct type.

This patch addresses this by rebuilding the input Go type for the
decision log from the parsed AST of the original input object. This
generates a Go type that does not break the masking logic, provided the
input is of a type that can be masked. The conversion from the AST only
happens if the decision logs plugin is actually registered with the
manager to avoid wasting cycles if decision logs are not enabled.

A test is added to cover the masking case for the SDK.

Signed-off-by: Erik Paulson <epaulson10@gmail.com>
2023-07-14 11:59:14 -07:00
Ashutosh Narkar 20612bb819 rego: Parse store modules iff modules set on the Rego object
Currently we parse store modules irrespective of whether
there are modules on the Rego object. This will result in
the compilation of those modules which triggers the bundle
activation flow. Now as part of the module compilation
we interact with the compiler's modules and run compilation
on the input modules. If let's say there are concurrent health
check requests (ie. /v1/health), this could result in a race
during the compilation process while working with the compiler's
modules.

This change avoids this situation by skipping parsing of the store
modules when none are set on the Rego object. The assumption this
change makes is that while using the rego package the compiler and
store are kept in-sync.

Fixes: #5868

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2023-07-07 01:44:53 -07:00
Benjamin Nørgaard f0b351d683 plugins/discovery: ensure discovery doesn't erase its own config
When the discovery plugin receives a a discovery bundle which omits the
discovery configuration, it deletes its own configuration from the
manager. In turn this means that `GET /v1/config` doesn't show the
configuration of the discovery plugin.

This change ensures that the plugin will never overwrite the discovery
configuration on the manager.

Signed-off-by: Benjamin Nørgaard <mail@blacksails.dev>
2023-07-06 10:34:00 -07:00
Stephan Renatus c9042db15f extensibility: add hooks (plugins, discovery, sdk)
This adds a lightweight extensibility mechanism to OPA: hooks. Loosely
modelled on what franz-go supports (see refs below).

We're starting with a configuration hook. It allows us to inspect or
alter the configuration of OPA after...

1. the config is read and parsed: OnConfig
2. a discovery bundle is processed: OnConfigDiscovery

References:
- franz-go: https://pkg.go.dev/github.com/twmb/franz-go/pkg/kgo#Hook

To follow:
- more hooks where they are useful
- runtime support for hooks, wiring them into the proper other places

Signed-off-by: Stephan Renatus <stephan@styra.com>
2023-06-29 10:18:41 +02:00
Stephan Renatus f8ed556da3 sdk: allow passing in a separate store implementation (#5962)
The store to use in the SDK is currently hard-coded to be inmem.
This change allows providing new implementations.

Signed-off-by: Stephan Renatus <stephan@styra.com>
2023-06-02 14:38:30 +02:00
Eng Zer Jun b3ae18d3a3 perf: avoid unnecessary byte/string conversion
We can use alternative functions/methods to avoid unnecessary
byte/string conversion calls.

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2023-05-23 10:00:59 -07:00
Anders Eknert f2c84747aa docs: mention ID property of sdk.Options and its benefits (#5876)
Fixes #5875

Signed-off-by: Anders Eknert <anders@styra.com>
2023-04-27 10:14:25 +02:00
Charlie Egan 8bb23ba156 [rego] Check store modules before skipping parsing (#5520)
* [rego] Check store modules before skipping parsing

Fixes https://github.com/open-policy-agent/opa/issues/5511

This change will cause the operation to be timed if the store
modules have already all been compiled and there are no
rawModules. This might be undesirable.

Signed-off-by: Charlie Egan <charlie@styra.com>
2023-01-05 10:47:48 +00:00
Charlie Egan 26ce80a5ac sdk: Return provenance information in Result types (#5460)
This will allow users of the SDK to see the version information of the
bundles used in decisions as well as the OPA SDK version.

Signed-off-by: Charlie Egan <charlieegan3@users.noreply.github.com>
2022-12-13 09:04:34 +00:00
Charlie Egan d1c61e332d sdk: Allow use of metrics, profilers, and instrumentation (#5459)
Signed-off-by: Charlie Egan <charlieegan3@users.noreply.github.com>
2022-12-12 10:04:38 +00:00
Charlie Egan 4669f9fab5 sdk: Allow use of a query tracer (#5447)
This PR exposes functionality to the callers of opa.Decision &
opa.Partial allowing a tracer implementing topdown.QueryTracer to be
passed.
2022-12-07 14:35:12 +00:00
Charlie Egan 8a0c08091b sdk: allow use of StrictBuiltinErrors (#5438)
This allows the struct builtin errors functionality to be used in the SDK by passing the value in DecisionOptions & PartialOptions.

Related to #5176

Signed-off-by: Charlie Egan <charlieegan3@users.noreply.github.com>
2022-12-06 10:38:53 +00: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
Philip Conrad ac20ef2bf5 server+sdk+plugins: Integrate NDBCache into decision logging. (#5147)
This commit integrates the non-deterministic builtins caching system
into decision logging, both in the server and sdk packages. Some
reworking of the NDBCache's serialization format were required to
accommodate this. The feature is disabled by default, and must be
opted into by user configuration.

The feature can be enabled via a top-level config key:

    nd_builtin_cache=true

The NDBCache is exposed to the masking system under the
`/nd_builtin_cache` path, which allows masking or dropping sensitive
values from decision logs selectively.

Note: If a decision log event exceeds the `upload_size_limit_bytes`
value for the OPA instance, OPA will reattempt uploading it, after
dropping the NDBCache from the event. This behavior will trigger a log
error, and will increment the `decision_logs_nd_builtin_cache_dropped`
metrics counter.

Fixes: #1514

Signed-off-by: Philip Conrad <philipaconrad@gmail.com>
2022-10-06 16:27:54 -04:00
Philip Conrad b2d92a33c1 Add prealloc linter check + linter fixes (#5139)
This commit adds the `prealloc` linter to the list of linters for OPA, and fixes up the miscellaneous locations in the code that the linter found where we could easily preallocate slices.

Signed-off-by: Philip Conrad <philipaconrad@gmail.com>
2022-09-15 15:09:54 -04:00
Rakshasa 2eee58c2c1 SDK: Allow configurable ID (#4736)
When calling the sdk the user can specify an opa id so that repeat calls to the sdk don't have a unique opa id

Signed-off-by: PrahathessRaghavan <prahathess@gmail.com>
2022-06-06 23:40:46 +02:00
carabasdaniel 2c650693ab OCI: skip reloading bundle if tarball SHA did not change (#4658)
Fixes #4637.

Signed-off-by: carabasdaniel <dani@aserto.com>
2022-05-13 10:41:01 +02:00
Stephan Renatus ac7bb1fa70 storage: code cosmetics
Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2022-03-30 10:25:45 +02:00
Stephan Renatus d48a5fc1fb sdk/opa_test: increase max delta (0.5s) (#4513)
When running on GHA, we've found this test to often fail on macos-latest:
It would not functionally be wrong, but it also wasn't able to finish in
the alloted time. Now, the maximum delta has been increased a lot (10ms to
500ms). It's much, but it's still good enough to ensure that the context
passed to Stop() is the one that matters for shutdown.

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2022-03-29 15:31:31 +02:00
Iceber Gu b7c67b9833 sdk: avoid using different state (#4505)
I noticed that when operating on opa.state, locking is usually done to avoid
a race, whereas here opa.state is used directly. By comparing the previous
changes, I found that #4240 changed the previous behaviour.

This change adjusts that: we ensure that we work on the state as read via
the mutex-protected `s := *opa.state`.

Signed-off-by: Iceber Gu <wei.cai-nat@daocloud.io>
2022-03-29 09:24:51 +02:00
Kurt Roekle f42b2db214 SDK: support partial eval (#4240)
Adding the ability to partially evaluate when using the the SDK as a go library.
This allows for utilizing the existing OPA configuration (e.g. bundle, decisions,
etc) when partially evaluating.

Signed-off-by: Kurt Roekle <kroekle@gmail.com>
2022-03-11 18:50:39 +01:00
Damien Burks 0c14834efc sdk: don't panic without config (#4314)
Fixes #4303.

Signed-off-by: Damien Burks <damien@damienjburks.com>
2022-02-02 18:31:27 +01:00
Stephan Renatus aa2e297a4e ci: address macos-latest test flakes (#4310)
* sdk/opa_test: increase max delta

6ms was arbitrary, and so is 10ms.

When GHA switched the macos-latest version, we've started seeing
test flakiness here.

30ms (20ms+10ms) are still waaaay below the 1s that the test_plugin
attempts need to shut down.

* test/e2e/certrefresh: double wait time for macos runner

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2022-02-01 10:16:31 +01:00
Torin Sandall 3cdbad64e2 sdk: send print output to logger
This commit updates the SDK to send print output to the logger if the
level is INFO or DEBUG and disables print statements entirely
otherwise. This way the SDK behaves teh same was as the server.

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2021-12-22 17:46:37 +01:00
Torin Sandall 7fad61ad40 sdk/test: error if mock bundle not prefixed correctly
The test server expects mock bundle files to be prefixed with
/bundles/ so return an error if they are not (otherwise the user has
to dig into the test server code to figure out why their test is not working.)

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2021-12-22 17:46:37 +01:00
Torin Sandall 7be1338c2f sdk: expose plugins on the sdk object
Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2021-12-22 17:46:37 +01:00
Stephan Renatus 883dc8817f plugins: support graceful shutdown through SDK (#4119)
With this change, the manager will respect the shutdown period if
it was supplied, otherwise it will use the passed context. This way,
SDK users can rely on the context (because the SDK doesn't set
the graceful shutdown period), but other callers are unaffected.

The added test is in the SDK, because that's where the problem had
manifested (#3980): when calling Stop(ctx) through the SDK, the
plugins.Manager's Stop function had set a smaller timeout (0, due
to the structs default value that hadn't been set to anything else),
and that would effectively leave the plugins zero time to cleanup.

Fixes #3980.

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2021-12-14 09:43:22 +01:00
Christian Schuetz d817166b36 sdk: forward SDK config to runtime config (#4121)
Updates runtime generation to include the opa config in `opa.runtime()`.

Signed-off-by: Christian Schuetz <christian.schuetz@chime.com>
2021-12-11 12:22:04 +01:00
orenzohar ab48bd789a add runtime() to Go SDK
Signed-off-by: orenzohar <oren.zohar@elastic.co>
2021-12-09 08:36:56 -08:00
Edward Paget f789a1eba0 sdk: Allow map of plugins to be passed to SDK
This adds a Plugins field to the SDK Options struct that accepts a
map[string]plugins.Factory similarly to the map created by
runtime.RegisterPlugin this map is passed to the discovery.Factories
plugin similarly, again, to how it works within the Runtime module. This
allows an OPA SDK instance to initialize plugins.

Fixes #3826

Signed-off-by: Edward Paget <edward.paget@chime.com>

Fixed changes requested by @tsandall (squash before merge)

Signed-off-by: Edward Paget <edward.paget@chime.com>
2021-10-01 10:25:24 -07:00
Torin Sandall 8b40acea0a logging: Fix console logger instantiation
This commit fixes the console loggers so that messages are emitted
regardless of the debug log level. The problem was that in 3fcc875 we
updated the plugins to use a console logger obtained from the plugin
manager as opposed to a global logger instantiated in the plugins
package--the console logger obtained from the plugin manager was
instantiated in the runtime package by calling
logging.NewStandardLogger. Unfortunately, logging.NewStandardLogger
does not create a new logger--it returns the global logrus
logger.

This commit fixes the issue by deprecating logging.NewStandardLogger
and introducing two new functions in the logging package:

* logging.Get() - this replaces the old logging.NewStandardLogger
  function--this function should be called to obtain the debug logger
  used throughout OPA.

* logging.New() - this actually returns a new logger that can be
  configured independently from the debug logger used throughout
  OPA.

The runtime and sdk packages have been updated to call logging.New()
to obtain console loggers and the rest of the codebase has been
updated to call logging.Get() in place of logging.NewStandardLogger().

Fixes #3654

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2021-07-27 09:39:01 -07: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
Torin Sandall f43a77141d sdk: Add readiness signal to the test server
This commit updates the test server so that callers can control when
the server becomes ready. This allows us to test the async option on
the SDK without worrying about race conditions. I.e., we can block
server readiness and assert that the SDK returns undefined until ready.

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2021-05-12 13:40:22 -04:00