diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index a6d56048491..cbb26ea7615 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -168,15 +168,6 @@ rules: - patch - update - watch -- apiGroups: - - templates.gatekeeper.sh - resources: - - constrainttemplates/finalizers - verbs: - - delete - - get - - patch - - update - apiGroups: - templates.gatekeeper.sh resources: diff --git a/go.mod b/go.mod index f59c91c7650..4f4b668b28b 100644 --- a/go.mod +++ b/go.mod @@ -161,4 +161,4 @@ require ( ) // TODO: testing purposes only - remove this before merging -replace github.com/open-policy-agent/frameworks/constraint => github.com/sozercan/frameworks/constraint v0.0.0-20250123183526-62279e78b9a5 +replace github.com/open-policy-agent/frameworks/constraint => github.com/sozercan/frameworks/constraint v0.0.0-20250123191509-ea09dbab7e9d diff --git a/go.sum b/go.sum index fb5a3e4d385..c43b6c74ac6 100644 --- a/go.sum +++ b/go.sum @@ -333,8 +333,8 @@ github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/sozercan/frameworks/constraint v0.0.0-20250123183526-62279e78b9a5 h1:8UVNDBOQm/oBSxVc2Gbn6Nn5iu6RB9MtNVjO7Yp9yD0= -github.com/sozercan/frameworks/constraint v0.0.0-20250123183526-62279e78b9a5/go.mod h1:gkrOtCNNVFs/yw0aEJT3cRGMjfQYDIfSJV5Xx/vIJZI= +github.com/sozercan/frameworks/constraint v0.0.0-20250123191509-ea09dbab7e9d h1:NdFfLtJr7qLZ/OHdhN3du2TJGEnNW/13UN+7QeTP9oM= +github.com/sozercan/frameworks/constraint v0.0.0-20250123191509-ea09dbab7e9d/go.mod h1:gkrOtCNNVFs/yw0aEJT3cRGMjfQYDIfSJV5Xx/vIJZI= github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= diff --git a/main.go b/main.go index add56d97c49..00964c9acdc 100644 --- a/main.go +++ b/main.go @@ -284,10 +284,6 @@ func innerMain() int { close(setupFinished) } - // ControllerSwitch will be used to disable controllers during our teardown process, - // avoiding conflicts in finalizer cleanup. - sw := watch.NewSwitch() - // Setup tracker and register readiness probe. tracker, err := readiness.SetupTracker(mgr, mutation.Enabled(), *externaldata.ExternalDataEnabled, *expansion.ExpansionEnabled) if err != nil { @@ -316,7 +312,7 @@ func innerMain() int { setupErr := make(chan error) ctx := ctrl.SetupSignalHandler() go func() { - setupErr <- setupControllers(ctx, mgr, sw, tracker, setupFinished) + setupErr <- setupControllers(ctx, mgr, tracker, setupFinished) }() setupLog.Info("starting manager") @@ -348,12 +344,7 @@ blockingLoop: break blockingLoop } } - - // Manager stops controllers asynchronously. - // Instead, we use ControllerSwitch to synchronously prevent them from doing more work. - // This can be removed when finalizer and status teardown is removed. setupLog.Info("disabling controllers...") - sw.Stop() if hadError { return 1 @@ -361,7 +352,7 @@ blockingLoop: return 0 } -func setupControllers(ctx context.Context, mgr ctrl.Manager, sw *watch.ControllerSwitch, tracker *readiness.Tracker, setupFinished chan struct{}) error { +func setupControllers(ctx context.Context, mgr ctrl.Manager, tracker *readiness.Tracker, setupFinished chan struct{}) error { // Block until the setup (certificate generation) finishes. <-setupFinished @@ -508,17 +499,16 @@ func setupControllers(ctx context.Context, mgr ctrl.Manager, sw *watch.Controlle } opts := controller.Dependencies{ - CFClient: client, - WatchManger: wm, - SyncEventsCh: events, - CacheMgr: cm, - ControllerSwitch: sw, - Tracker: tracker, - ProcessExcluder: processExcluder, - MutationSystem: mutationSystem, - ExpansionSystem: expansionSystem, - ProviderCache: providerCache, - PubsubSystem: pubsubSystem, + CFClient: client, + WatchManger: wm, + SyncEventsCh: events, + CacheMgr: cm, + Tracker: tracker, + ProcessExcluder: processExcluder, + MutationSystem: mutationSystem, + ExpansionSystem: expansionSystem, + ProviderCache: providerCache, + PubsubSystem: pubsubSystem, } if err := controller.AddToManager(mgr, &opts); err != nil { diff --git a/manifest_staging/charts/gatekeeper/templates/gatekeeper-manager-role-clusterrole.yaml b/manifest_staging/charts/gatekeeper/templates/gatekeeper-manager-role-clusterrole.yaml index 591d36dc566..8221431f9b4 100644 --- a/manifest_staging/charts/gatekeeper/templates/gatekeeper-manager-role-clusterrole.yaml +++ b/manifest_staging/charts/gatekeeper/templates/gatekeeper-manager-role-clusterrole.yaml @@ -177,15 +177,6 @@ rules: - patch - update - watch -- apiGroups: - - templates.gatekeeper.sh - resources: - - constrainttemplates/finalizers - verbs: - - delete - - get - - patch - - update - apiGroups: - templates.gatekeeper.sh resources: diff --git a/manifest_staging/deploy/gatekeeper.yaml b/manifest_staging/deploy/gatekeeper.yaml index 0e2da7d3598..15dce06ba85 100644 --- a/manifest_staging/deploy/gatekeeper.yaml +++ b/manifest_staging/deploy/gatekeeper.yaml @@ -4967,15 +4967,6 @@ rules: - patch - update - watch -- apiGroups: - - templates.gatekeeper.sh - resources: - - constrainttemplates/finalizers - verbs: - - delete - - get - - patch - - update - apiGroups: - templates.gatekeeper.sh resources: diff --git a/pkg/controller/config/config_controller.go b/pkg/controller/config/config_controller.go index b3f4ec96e43..63cf6928f44 100644 --- a/pkg/controller/config/config_controller.go +++ b/pkg/controller/config/config_controller.go @@ -28,7 +28,6 @@ import ( "github.com/open-policy-agent/gatekeeper/v3/pkg/keys" "github.com/open-policy-agent/gatekeeper/v3/pkg/readiness" "github.com/open-policy-agent/gatekeeper/v3/pkg/util" - "github.com/open-policy-agent/gatekeeper/v3/pkg/watch" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" @@ -53,9 +52,8 @@ var ( ) type Adder struct { - ControllerSwitch *watch.ControllerSwitch - Tracker *readiness.Tracker - CacheManager *cm.CacheManager + Tracker *readiness.Tracker + CacheManager *cm.CacheManager // GetPod returns an instance of the currently running Gatekeeper pod GetPod func(context.Context) (*corev1.Pod, error) } @@ -63,7 +61,7 @@ type Adder struct { // Add creates a new ConfigController and adds it to the Manager with default RBAC. The Manager will set fields on the Controller // and Start it when the Manager is Started. func (a *Adder) Add(mgr manager.Manager) error { - r, err := newReconciler(mgr, a.CacheManager, a.ControllerSwitch, a.Tracker, a.GetPod) + r, err := newReconciler(mgr, a.CacheManager, a.Tracker, a.GetPod) if err != nil { return err } @@ -71,10 +69,6 @@ func (a *Adder) Add(mgr manager.Manager) error { return add(mgr, r) } -func (a *Adder) InjectControllerSwitch(cs *watch.ControllerSwitch) { - a.ControllerSwitch = cs -} - func (a *Adder) InjectTracker(t *readiness.Tracker) { a.Tracker = t } @@ -88,7 +82,7 @@ func (a *Adder) InjectGetPod(getPod func(ctx context.Context) (*corev1.Pod, erro } // newReconciler returns a new reconcile.Reconciler. -func newReconciler(mgr manager.Manager, cm *cm.CacheManager, cs *watch.ControllerSwitch, tracker *readiness.Tracker, getPod func(context.Context) (*corev1.Pod, error)) (*ReconcileConfig, error) { +func newReconciler(mgr manager.Manager, cm *cm.CacheManager, tracker *readiness.Tracker, getPod func(context.Context) (*corev1.Pod, error)) (*ReconcileConfig, error) { if cm == nil { return nil, fmt.Errorf("cacheManager must be non-nil") } @@ -98,7 +92,6 @@ func newReconciler(mgr manager.Manager, cm *cm.CacheManager, cs *watch.Controlle writer: mgr.GetClient(), statusClient: mgr.GetClient(), scheme: mgr.GetScheme(), - cs: cs, cacheManager: cm, tracker: tracker, getPod: getPod, @@ -138,7 +131,6 @@ type ReconcileConfig struct { scheme *runtime.Scheme cacheManager *cm.CacheManager - cs *watch.ControllerSwitch tracker *readiness.Tracker @@ -155,15 +147,6 @@ type ReconcileConfig struct { // and what is in the Config.Spec // Automatically generate RBAC rules to allow the Controller to read all things (for sync). func (r *ReconcileConfig) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { - // Short-circuit if shutting down. - if r.cs != nil { - running := r.cs.Enter() - defer r.cs.Exit() - if !running { - return reconcile.Result{}, nil - } - } - // Fetch the Config instance if request.NamespacedName != keys.Config { log.Info("Ignoring unsupported config name", "namespace", request.NamespacedName.Namespace, "name", request.NamespacedName.Name) diff --git a/pkg/controller/config/config_controller_test.go b/pkg/controller/config/config_controller_test.go index 817e34e10b0..1697d93ee19 100644 --- a/pkg/controller/config/config_controller_test.go +++ b/pkg/controller/config/config_controller_test.go @@ -125,7 +125,6 @@ func TestReconcile(t *testing.T) { dataClient := &fakes.FakeCfClient{} - cs := watch.NewSwitch() tracker, err := readiness.SetupTracker(mgr, false, false, false) if err != nil { t.Fatal(err) @@ -158,7 +157,7 @@ func TestReconcile(t *testing.T) { fakes.WithName("no-pod"), ) - rec, err := newReconciler(mgr, cacheManager, cs, tracker, func(context.Context) (*v1.Pod, error) { return pod, nil }) + rec, err := newReconciler(mgr, cacheManager, tracker, func(context.Context) (*v1.Pod, error) { return pod, nil }) require.NoError(t, err) // Wrap the Controller Reconcile function so it writes each request to a map when it is finished reconciling. @@ -290,8 +289,6 @@ func TestReconcile(t *testing.T) { // fooPod should be namespace excluded, hence not added to the cache require.False(t, dataClient.Contains(map[fakes.CfDataKey]interface{}{{Gvk: fooPod.GroupVersionKind(), Key: "default"}: struct{}{}})) - - cs.Stop() } // tests that expectations for sync only resource gets canceled when it gets deleted. @@ -424,7 +421,6 @@ func setupController(ctx context.Context, mgr manager.Manager, wm *watch.Manager } } - cs := watch.NewSwitch() processExcluder := process.Get() syncMetricsCache := syncutil.NewMetricsCache() reg, err := wm.NewRegistrar( @@ -453,7 +449,7 @@ func setupController(ctx context.Context, mgr manager.Manager, wm *watch.Manager fakes.WithName("no-pod"), ) - rec, err := newReconciler(mgr, cacheManager, cs, tracker, func(context.Context) (*v1.Pod, error) { return pod, nil }) + rec, err := newReconciler(mgr, cacheManager, tracker, func(context.Context) (*v1.Pod, error) { return pod, nil }) if err != nil { return nil, fmt.Errorf("creating reconciler: %w", err) } @@ -600,7 +596,6 @@ func TestConfig_Retries(t *testing.T) { c := testclient.NewRetryClient(mgr.GetClient()) dataClient := &fakes.FakeCfClient{} - cs := watch.NewSwitch() tracker, err := readiness.SetupTracker(mgr, false, false, false) if err != nil { t.Fatal(err) @@ -632,7 +627,7 @@ func TestConfig_Retries(t *testing.T) { fakes.WithName("no-pod"), ) - rec, _ := newReconciler(mgr, cacheManager, cs, tracker, func(context.Context) (*v1.Pod, error) { return pod, nil }) + rec, _ := newReconciler(mgr, cacheManager, tracker, func(context.Context) (*v1.Pod, error) { return pod, nil }) err = add(mgr, rec) if err != nil { t.Fatal(err) diff --git a/pkg/controller/configstatus/configstatus_controller.go b/pkg/controller/configstatus/configstatus_controller.go index b0bae57e02a..c63c0b69fc5 100644 --- a/pkg/controller/configstatus/configstatus_controller.go +++ b/pkg/controller/configstatus/configstatus_controller.go @@ -46,8 +46,6 @@ type Adder struct { WatchManager *watch.Manager } -func (a *Adder) InjectControllerSwitch(_ *watch.ControllerSwitch) {} - func (a *Adder) InjectTracker(_ *readiness.Tracker) {} // Add creates a new config Status Controller and adds it to the Manager. The Manager will set fields on the Controller diff --git a/pkg/controller/constraint/constraint_controller.go b/pkg/controller/constraint/constraint_controller.go index 1df04f6d3b4..8792f187041 100644 --- a/pkg/controller/constraint/constraint_controller.go +++ b/pkg/controller/constraint/constraint_controller.go @@ -87,7 +87,6 @@ type Adder struct { CFClient *constraintclient.Client ConstraintsCache *ConstraintsCache WatchManager *watch.Manager - ControllerSwitch *watch.ControllerSwitch Events <-chan event.GenericEvent Tracker *readiness.Tracker GetPod func(context.Context) (*corev1.Pod, error) @@ -107,10 +106,6 @@ func (a *Adder) InjectWatchManager(w *watch.Manager) { a.WatchManager = w } -func (a *Adder) InjectControllerSwitch(cs *watch.ControllerSwitch) { - a.ControllerSwitch = cs -} - func (a *Adder) InjectTracker(t *readiness.Tracker) { a.Tracker = t } @@ -127,7 +122,7 @@ func (a *Adder) Add(mgr manager.Manager) error { return err } - r := newReconciler(mgr, a.CFClient, a.ControllerSwitch, reporter, a.ConstraintsCache, a.Tracker) + r := newReconciler(mgr, a.CFClient, reporter, a.ConstraintsCache, a.Tracker) if a.GetPod != nil { r.getPod = a.GetPod } @@ -151,7 +146,6 @@ type tags struct { func newReconciler( mgr manager.Manager, cfClient *constraintclient.Client, - cs *watch.ControllerSwitch, reporter StatsReporter, constraintsCache *ConstraintsCache, tracker *readiness.Tracker, @@ -162,7 +156,6 @@ func newReconciler( statusClient: mgr.GetClient(), reader: mgr.GetCache(), - cs: cs, scheme: mgr.GetScheme(), cfClient: cfClient, log: log, @@ -209,7 +202,6 @@ type ReconcileConstraint struct { writer client.Writer statusClient client.StatusClient - cs *watch.ControllerSwitch scheme *runtime.Scheme cfClient *constraintclient.Client log logr.Logger @@ -229,15 +221,6 @@ type ReconcileConstraint struct { // Reconcile reads that state of the cluster for a constraint object and makes changes based on the state read // and what is in the constraint.Spec. func (r *ReconcileConstraint) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { - // Short-circuit if shutting down. - if r.cs != nil { - running := r.cs.Enter() - defer r.cs.Exit() - if !running { - return reconcile.Result{}, nil - } - } - gvk, unpackedRequest, err := util.UnpackRequest(request) if err != nil { // Unrecoverable, do not retry. diff --git a/pkg/controller/constraintstatus/constraintstatus_controller.go b/pkg/controller/constraintstatus/constraintstatus_controller.go index 7f6714c85f2..ca9d915656d 100644 --- a/pkg/controller/constraintstatus/constraintstatus_controller.go +++ b/pkg/controller/constraintstatus/constraintstatus_controller.go @@ -45,11 +45,10 @@ import ( var log = logf.Log.WithName("controller").WithValues(logging.Process, "constraint_status_controller") type Adder struct { - CFClient *constraintclient.Client - WatchManager *watch.Manager - ControllerSwitch *watch.ControllerSwitch - Events <-chan event.GenericEvent - IfWatching func(schema.GroupVersionKind, func() error) (bool, error) + CFClient *constraintclient.Client + WatchManager *watch.Manager + Events <-chan event.GenericEvent + IfWatching func(schema.GroupVersionKind, func() error) (bool, error) } // Add creates a new Constraint Status Controller and adds it to the Manager. The Manager will set fields on the Controller @@ -58,7 +57,7 @@ func (a *Adder) Add(mgr manager.Manager) error { if !operations.IsAssigned(operations.Status) { return nil } - r := newReconciler(mgr, a.ControllerSwitch) + r := newReconciler(mgr) if a.IfWatching != nil { r.ifWatching = a.IfWatching } @@ -68,7 +67,6 @@ func (a *Adder) Add(mgr manager.Manager) error { // newReconciler returns a new reconcile.Reconciler. func newReconciler( mgr manager.Manager, - cs *watch.ControllerSwitch, ) *ReconcileConstraintStatus { return &ReconcileConstraintStatus{ // Separate reader and writer because manager's default client bypasses the cache for unstructured resources. @@ -76,7 +74,6 @@ func newReconciler( statusClient: mgr.GetClient(), reader: mgr.GetCache(), - cs: cs, scheme: mgr.GetScheme(), log: log, ifWatching: func(_ schema.GroupVersionKind, fn func() error) (bool, error) { return true, fn() }, @@ -145,7 +142,6 @@ type ReconcileConstraintStatus struct { writer client.Writer statusClient client.StatusClient - cs *watch.ControllerSwitch scheme *runtime.Scheme log logr.Logger ifWatching func(schema.GroupVersionKind, func() error) (bool, error) @@ -157,15 +153,6 @@ type ReconcileConstraintStatus struct { // Reconcile reads that state of the cluster for a constraint object and makes changes based on the state read // and what is in the constraint.Spec. func (r *ReconcileConstraintStatus) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { - // Short-circuit if shutting down. - if r.cs != nil { - running := r.cs.Enter() - defer r.cs.Exit() - if !running { - return reconcile.Result{}, nil - } - } - gvk, unpackedRequest, err := util.UnpackRequest(request) if err != nil { // Unrecoverable, do not retry. diff --git a/pkg/controller/constrainttemplate/constrainttemplate_controller.go b/pkg/controller/constrainttemplate/constrainttemplate_controller.go index 03ff303361d..2871e135dd9 100644 --- a/pkg/controller/constrainttemplate/constrainttemplate_controller.go +++ b/pkg/controller/constrainttemplate/constrainttemplate_controller.go @@ -77,11 +77,10 @@ var gvkConstraintTemplate = schema.GroupVersionKind{ } type Adder struct { - CFClient *constraintclient.Client - WatchManager *watch.Manager - ControllerSwitch *watch.ControllerSwitch - Tracker *readiness.Tracker - GetPod func(context.Context) (*corev1.Pod, error) + CFClient *constraintclient.Client + WatchManager *watch.Manager + Tracker *readiness.Tracker + GetPod func(context.Context) (*corev1.Pod, error) } // Add creates a new ConstraintTemplate Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller @@ -92,7 +91,7 @@ func (a *Adder) Add(mgr manager.Manager) error { } // events will be used to receive events from dynamic watches registered events := make(chan event.GenericEvent, 1024) - r, err := newReconciler(mgr, a.CFClient, a.WatchManager, a.ControllerSwitch, a.Tracker, events, events, a.GetPod) + r, err := newReconciler(mgr, a.CFClient, a.WatchManager, a.Tracker, events, events, a.GetPod) if err != nil { return err } @@ -107,10 +106,6 @@ func (a *Adder) InjectWatchManager(wm *watch.Manager) { a.WatchManager = wm } -func (a *Adder) InjectControllerSwitch(cs *watch.ControllerSwitch) { - a.ControllerSwitch = cs -} - func (a *Adder) InjectTracker(t *readiness.Tracker) { a.Tracker = t } @@ -123,7 +118,7 @@ func (a *Adder) InjectGetPod(getPod func(context.Context) (*corev1.Pod, error)) // cstrEvents is the channel from which constraint controller will receive the events // regEvents is the channel registered by Registrar to put the events in // cstrEvents and regEvents point to same event channel except for testing. -func newReconciler(mgr manager.Manager, cfClient *constraintclient.Client, wm *watch.Manager, cs *watch.ControllerSwitch, tracker *readiness.Tracker, cstrEvents <-chan event.GenericEvent, regEvents chan<- event.GenericEvent, getPod func(context.Context) (*corev1.Pod, error)) (*ReconcileConstraintTemplate, error) { +func newReconciler(mgr manager.Manager, cfClient *constraintclient.Client, wm *watch.Manager, tracker *readiness.Tracker, cstrEvents <-chan event.GenericEvent, regEvents chan<- event.GenericEvent, getPod func(context.Context) (*corev1.Pod, error)) (*ReconcileConstraintTemplate, error) { // constraintsCache contains total number of constraints and shared mutex and vap label constraintsCache := constraint.NewConstraintsCache() @@ -142,7 +137,6 @@ func newReconciler(mgr manager.Manager, cfClient *constraintclient.Client, wm *w CFClient: cfClient, ConstraintsCache: constraintsCache, WatchManager: wm, - ControllerSwitch: cs, Events: cstrEvents, Tracker: tracker, GetPod: getPod, @@ -158,20 +152,18 @@ func newReconciler(mgr manager.Manager, cfClient *constraintclient.Client, wm *w // via the registrar below. statusEvents := make(chan event.GenericEvent, 1024) csAdder := constraintstatus.Adder{ - CFClient: cfClient, - WatchManager: wm, - ControllerSwitch: cs, - Events: statusEvents, - IfWatching: statusW.IfWatching, + CFClient: cfClient, + WatchManager: wm, + Events: statusEvents, + IfWatching: statusW.IfWatching, } if err := csAdder.Add(mgr); err != nil { return nil, err } ctsAdder := constrainttemplatestatus.Adder{ - CfClient: cfClient, - WatchManager: wm, - ControllerSwitch: cs, + CfClient: cfClient, + WatchManager: wm, } if err := ctsAdder.Add(mgr); err != nil { return nil, err @@ -185,7 +177,6 @@ func newReconciler(mgr manager.Manager, cfClient *constraintclient.Client, wm *w cfClient: cfClient, watcher: w, statusWatcher: statusW, - cs: cs, metrics: r, tracker: tracker, getPod: getPod, @@ -245,7 +236,6 @@ type ReconcileConstraintTemplate struct { watcher *watch.Registrar statusWatcher *watch.Registrar cfClient *constraintclient.Client - cs *watch.ControllerSwitch metrics *reporter tracker *readiness.Tracker getPod func(context.Context) (*corev1.Pod, error) @@ -255,8 +245,6 @@ type ReconcileConstraintTemplate struct { // +kubebuilder:rbac:groups=admissionregistration.k8s.io,resources=validatingadmissionpolicies;validatingadmissionpolicybindings,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=apiextensions.k8s.io,resources=customresourcedefinitions,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=templates.gatekeeper.sh,resources=constrainttemplates,verbs=get;list;watch;create;update;patch;delete -// TODO(acpana): remove in 3.16 as per https://github.com/open-policy-agent/gatekeeper/issues/3084 -// +kubebuilder:rbac:groups=templates.gatekeeper.sh,resources=constrainttemplates/finalizers,verbs=get;update;patch;delete // +kubebuilder:rbac:groups=templates.gatekeeper.sh,resources=constrainttemplates/status,verbs=get;update;patch // +kubebuilder:rbac:groups=externaldata.gatekeeper.sh,resources=providers,verbs=get;list;watch;create;update;patch;delete @@ -264,14 +252,6 @@ type ReconcileConstraintTemplate struct { // and what is in the ConstraintTemplate.Spec. func (r *ReconcileConstraintTemplate) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { logger := logger.WithValues("template_name", request.Name) - // Short-circuit if shutting down. - if r.cs != nil { - running := r.cs.Enter() - defer r.cs.Exit() - if !running { - return reconcile.Result{}, nil - } - } defer r.metrics.registry.report(ctx, r.metrics) diff --git a/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go b/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go index c0606e4b689..5ab10810734 100644 --- a/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go +++ b/pkg/controller/constrainttemplate/constrainttemplate_controller_test.go @@ -38,7 +38,6 @@ import ( "github.com/open-policy-agent/gatekeeper/v3/pkg/readiness" "github.com/open-policy-agent/gatekeeper/v3/pkg/target" "github.com/open-policy-agent/gatekeeper/v3/pkg/util" - "github.com/open-policy-agent/gatekeeper/v3/pkg/watch" testclient "github.com/open-policy-agent/gatekeeper/v3/test/clients" "github.com/open-policy-agent/gatekeeper/v3/test/testutils" "golang.org/x/net/context" @@ -246,7 +245,6 @@ func TestReconcile(t *testing.T) { testutils.Setenv(t, "POD_NAME", "no-pod") - cs := watch.NewSwitch() tracker, err := readiness.SetupTracker(mgr, false, false, false) if err != nil { t.Fatal(err) @@ -259,7 +257,7 @@ func TestReconcile(t *testing.T) { // events will be used to receive events from dynamic watches registered events := make(chan event.GenericEvent, 1024) - rec, err := newReconciler(mgr, cfClient, wm, cs, tracker, events, events, func(context.Context) (*corev1.Pod, error) { return pod, nil }) + rec, err := newReconciler(mgr, cfClient, wm, tracker, events, events, func(context.Context) (*corev1.Pod, error) { return pod, nil }) if err != nil { t.Fatal(err) } @@ -1498,7 +1496,6 @@ violation[{"msg": "denied!"}] { testutils.Setenv(t, "POD_NAME", "no-pod") - cs := watch.NewSwitch() pod := fakes.Pod( fakes.WithNamespace("gatekeeper-system"), fakes.WithName("no-pod"), @@ -1506,7 +1503,7 @@ violation[{"msg": "denied!"}] { // events will be used to receive events from dynamic watches registered events := make(chan event.GenericEvent, 1024) - rec, err := newReconciler(mgr, cfClient, wm, cs, tracker, events, nil, func(context.Context) (*corev1.Pod, error) { return pod, nil }) + rec, err := newReconciler(mgr, cfClient, wm, tracker, events, nil, func(context.Context) (*corev1.Pod, error) { return pod, nil }) if err != nil { t.Fatal(err) } diff --git a/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller.go b/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller.go index 6947a2c3ad8..5b1b75b547c 100644 --- a/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller.go +++ b/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller.go @@ -45,9 +45,8 @@ import ( var log = logf.Log.WithName("controller").WithValues(logging.Process, "constraint_template_status_controller") type Adder struct { - CfClient *constraintclient.Client - WatchManager *watch.Manager - ControllerSwitch *watch.ControllerSwitch + CfClient *constraintclient.Client + WatchManager *watch.Manager } // Add creates a new Constraint Status Controller and adds it to the Manager. The Manager will set fields on the Controller @@ -56,24 +55,21 @@ func (a *Adder) Add(mgr manager.Manager) error { if !operations.IsAssigned(operations.Status) { return nil } - r := newReconciler(mgr, a.ControllerSwitch) + r := newReconciler(mgr) return add(mgr, r) } // newReconciler returns a new reconcile.Reconciler. func newReconciler( mgr manager.Manager, - cs *watch.ControllerSwitch, ) reconcile.Reconciler { return &ReconcileConstraintStatus{ // Separate reader and writer because manager's default client bypasses the cache for unstructured resources. writer: mgr.GetClient(), statusClient: mgr.GetClient(), reader: mgr.GetCache(), - - cs: cs, - scheme: mgr.GetScheme(), - log: log, + scheme: mgr.GetScheme(), + log: log, } } @@ -132,10 +128,8 @@ type ReconcileConstraintStatus struct { reader client.Reader writer client.Writer statusClient client.StatusClient - - cs *watch.ControllerSwitch - scheme *runtime.Scheme - log logr.Logger + scheme *runtime.Scheme + log logr.Logger } // +kubebuilder:rbac:groups=constraints.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete @@ -144,14 +138,6 @@ type ReconcileConstraintStatus struct { // Reconcile reads that state of the cluster for a constraint object and makes changes based on the state read // and what is in the constraint.Spec. func (r *ReconcileConstraintStatus) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { - // Short-circuit if shutting down. - if r.cs != nil { - running := r.cs.Enter() - defer r.cs.Exit() - if !running { - return reconcile.Result{}, nil - } - } template := &unstructured.Unstructured{} gv := constrainttemplatev1beta1.SchemeGroupVersion template.SetGroupVersionKind(gv.WithKind("ConstraintTemplate")) diff --git a/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_test.go b/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_test.go index 4a43271cbd1..0663cc79dee 100644 --- a/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_test.go +++ b/pkg/controller/constrainttemplatestatus/constrainttemplatestatus_controller_test.go @@ -122,7 +122,6 @@ violation[{"msg": "denied!"}] { testutils.Setenv(t, "POD_NAME", "no-pod") - cs := watch.NewSwitch() tracker, err := readiness.SetupTracker(mgr, false, false, false) if err != nil { t.Fatal(err) @@ -133,11 +132,10 @@ violation[{"msg": "denied!"}] { ) adder := constrainttemplate.Adder{ - CFClient: cfClient, - WatchManager: wm, - ControllerSwitch: cs, - Tracker: tracker, - GetPod: func(context.Context) (*corev1.Pod, error) { return pod, nil }, + CFClient: cfClient, + WatchManager: wm, + Tracker: tracker, + GetPod: func(context.Context) (*corev1.Pod, error) { return pod, nil }, } err = adder.Add(mgr) if err != nil { diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index d129dc03e02..97b6044a523 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -47,7 +47,6 @@ import ( var debugUseFakePod = flag.Bool("debug-use-fake-pod", false, "Use a fake pod name so the Gatekeeper executable can be run outside of Kubernetes") type Injector interface { - InjectControllerSwitch(*watch.ControllerSwitch) InjectTracker(tracker *readiness.Tracker) Add(mgr manager.Manager) error @@ -94,18 +93,17 @@ var AddToManagerFuncs []func(manager.Manager) error // Dependencies are dependencies that can be injected into controllers. type Dependencies struct { - CFClient *constraintclient.Client - WatchManger *watch.Manager - ControllerSwitch *watch.ControllerSwitch - Tracker *readiness.Tracker - GetPod func(context.Context) (*corev1.Pod, error) - ProcessExcluder *process.Excluder - MutationSystem *mutation.System - ExpansionSystem *expansion.System - ProviderCache *externaldata.ProviderCache - PubsubSystem *pubsub.System - SyncEventsCh chan event.GenericEvent - CacheMgr *cm.CacheManager + CFClient *constraintclient.Client + WatchManger *watch.Manager + Tracker *readiness.Tracker + GetPod func(context.Context) (*corev1.Pod, error) + ProcessExcluder *process.Excluder + MutationSystem *mutation.System + ExpansionSystem *expansion.System + ProviderCache *externaldata.ProviderCache + PubsubSystem *pubsub.System + SyncEventsCh chan event.GenericEvent + CacheMgr *cm.CacheManager } type defaultPodGetter struct { @@ -194,7 +192,6 @@ func AddToManager(m manager.Manager, deps *Dependencies) error { } for _, a := range Injectors { - a.InjectControllerSwitch(deps.ControllerSwitch) a.InjectTracker(deps.Tracker) if a2, ok := a.(DataClientInjector); ok { diff --git a/pkg/controller/expansion/expansion_controller.go b/pkg/controller/expansion/expansion_controller.go index 3539508adf0..7e73aaf3b5a 100644 --- a/pkg/controller/expansion/expansion_controller.go +++ b/pkg/controller/expansion/expansion_controller.go @@ -50,8 +50,6 @@ func (a *Adder) Add(mgr manager.Manager) error { return add(mgr, r) } -func (a *Adder) InjectControllerSwitch(_ *watch.ControllerSwitch) {} - func (a *Adder) InjectTracker(tracker *readiness.Tracker) { a.Tracker = tracker } diff --git a/pkg/controller/expansionstatus/expansionstatus_controller.go b/pkg/controller/expansionstatus/expansionstatus_controller.go index e512860f856..baf24537c8f 100644 --- a/pkg/controller/expansionstatus/expansionstatus_controller.go +++ b/pkg/controller/expansionstatus/expansionstatus_controller.go @@ -49,8 +49,6 @@ type Adder struct { WatchManager *watch.Manager } -func (a *Adder) InjectControllerSwitch(_ *watch.ControllerSwitch) {} - func (a *Adder) InjectTracker(_ *readiness.Tracker) {} // Add creates a new Constraint Status Controller and adds it to the Manager. The Manager will set fields on the Controller diff --git a/pkg/controller/externaldata/externaldata_controller.go b/pkg/controller/externaldata/externaldata_controller.go index 2f650b34abb..79822a24405 100644 --- a/pkg/controller/externaldata/externaldata_controller.go +++ b/pkg/controller/externaldata/externaldata_controller.go @@ -10,7 +10,6 @@ import ( "github.com/open-policy-agent/gatekeeper/v3/pkg/externaldata" "github.com/open-policy-agent/gatekeeper/v3/pkg/logging" "github.com/open-policy-agent/gatekeeper/v3/pkg/readiness" - "github.com/open-policy-agent/gatekeeper/v3/pkg/watch" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -45,8 +44,6 @@ func (a *Adder) InjectCFClient(c *constraintclient.Client) { a.CFClient = c } -func (a *Adder) InjectControllerSwitch(_ *watch.ControllerSwitch) {} - func (a *Adder) InjectTracker(t *readiness.Tracker) { a.Tracker = t } diff --git a/pkg/controller/externaldata/externaldata_controller_test.go b/pkg/controller/externaldata/externaldata_controller_test.go index b695db24dc0..caa17fba714 100644 --- a/pkg/controller/externaldata/externaldata_controller_test.go +++ b/pkg/controller/externaldata/externaldata_controller_test.go @@ -17,7 +17,6 @@ import ( "github.com/open-policy-agent/gatekeeper/v3/pkg/readiness" "github.com/open-policy-agent/gatekeeper/v3/pkg/target" "github.com/open-policy-agent/gatekeeper/v3/pkg/util" - "github.com/open-policy-agent/gatekeeper/v3/pkg/watch" testclient "github.com/open-policy-agent/gatekeeper/v3/test/clients" "github.com/open-policy-agent/gatekeeper/v3/test/testutils" "github.com/prometheus/client_golang/prometheus" @@ -93,7 +92,6 @@ func TestReconcile(t *testing.T) { t.Fatalf("unable to set up constraint framework client: %s", err) } - cs := watch.NewSwitch() tracker, err := readiness.SetupTracker(mgr, false, true, false) if err != nil { t.Fatal(err) @@ -182,5 +180,4 @@ func TestReconcile(t *testing.T) { }) testMgrStopped() - cs.Stop() } diff --git a/pkg/controller/mutators/instances/mutator_controllers.go b/pkg/controller/mutators/instances/mutator_controllers.go index da74eb9d1a5..13f78a1c1bc 100644 --- a/pkg/controller/mutators/instances/mutator_controllers.go +++ b/pkg/controller/mutators/instances/mutator_controllers.go @@ -11,7 +11,6 @@ import ( "github.com/open-policy-agent/gatekeeper/v3/pkg/mutation/mutators" "github.com/open-policy-agent/gatekeeper/v3/pkg/mutation/types" "github.com/open-policy-agent/gatekeeper/v3/pkg/readiness" - "github.com/open-policy-agent/gatekeeper/v3/pkg/watch" corev1 "k8s.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/event" @@ -124,8 +123,6 @@ func (a *Adder) Add(mgr manager.Manager) error { return assignMetadata.Add(mgr) } -func (a *Adder) InjectControllerSwitch(_ *watch.ControllerSwitch) {} - func (a *Adder) InjectTracker(t *readiness.Tracker) { a.Tracker = t } diff --git a/pkg/controller/mutatorstatus/mutatorstatus_controller.go b/pkg/controller/mutatorstatus/mutatorstatus_controller.go index bc63c784fe7..e9dc77d4e74 100644 --- a/pkg/controller/mutatorstatus/mutatorstatus_controller.go +++ b/pkg/controller/mutatorstatus/mutatorstatus_controller.go @@ -46,12 +46,9 @@ import ( var log = logf.Log.WithName("controller").WithValues(logging.Process, "mutator_status_controller") type Adder struct { - WatchManager *watch.Manager - ControllerSwitch *watch.ControllerSwitch + WatchManager *watch.Manager } -func (a *Adder) InjectControllerSwitch(_ *watch.ControllerSwitch) {} - func (a *Adder) InjectTracker(_ *readiness.Tracker) {} // Add creates a new Mutator Status Controller and adds it to the Manager. The Manager will set fields on the Controller @@ -60,24 +57,21 @@ func (a *Adder) Add(mgr manager.Manager) error { if !operations.IsAssigned(operations.MutationStatus) { return nil } - r := newReconciler(mgr, a.ControllerSwitch) + r := newReconciler(mgr) return add(mgr, r) } // newReconciler returns a new reconcile.Reconciler. func newReconciler( mgr manager.Manager, - cs *watch.ControllerSwitch, ) reconcile.Reconciler { return &ReconcileMutatorStatus{ // Separate reader and writer because manager's default client bypasses the cache for unstructured resources. writer: mgr.GetClient(), statusClient: mgr.GetClient(), reader: mgr.GetCache(), - - cs: cs, - scheme: mgr.GetScheme(), - log: log, + scheme: mgr.GetScheme(), + log: log, } } @@ -217,10 +211,8 @@ type ReconcileMutatorStatus struct { reader client.Reader writer client.Writer statusClient client.StatusClient - - cs *watch.ControllerSwitch - scheme *runtime.Scheme - log logr.Logger + scheme *runtime.Scheme + log logr.Logger } // +kubebuilder:rbac:groups=mutations.gatekeeper.sh,resources=*,verbs=get;list;watch;create;update;patch;delete @@ -229,15 +221,6 @@ type ReconcileMutatorStatus struct { // Reconcile reads that state of the cluster for a mutator object and makes changes based on the state read // and what is in the mutator.Spec. func (r *ReconcileMutatorStatus) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { - // Short-circuit if shutting down. - if r.cs != nil { - running := r.cs.Enter() - defer r.cs.Exit() - if !running { - return reconcile.Result{}, nil - } - } - gvk, unpackedRequest, err := util.UnpackRequest(request) if err != nil { // Unrecoverable, do not retry. diff --git a/pkg/controller/pubsub/pubsub_config_controller.go b/pkg/controller/pubsub/pubsub_config_controller.go index c7957d2617c..e807df760b6 100644 --- a/pkg/controller/pubsub/pubsub_config_controller.go +++ b/pkg/controller/pubsub/pubsub_config_controller.go @@ -10,7 +10,6 @@ import ( "github.com/open-policy-agent/gatekeeper/v3/pkg/pubsub" "github.com/open-policy-agent/gatekeeper/v3/pkg/readiness" "github.com/open-policy-agent/gatekeeper/v3/pkg/util" - "github.com/open-policy-agent/gatekeeper/v3/pkg/watch" corev1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" @@ -43,8 +42,6 @@ func (a *Adder) Add(mgr manager.Manager) error { return add(mgr, r) } -func (a *Adder) InjectControllerSwitch(_ *watch.ControllerSwitch) {} - func (a *Adder) InjectTracker(_ *readiness.Tracker) {} func (a *Adder) InjectPubsubSystem(pubsubSystem *pubsub.System) { diff --git a/pkg/controller/syncset/syncset_controller.go b/pkg/controller/syncset/syncset_controller.go index 597824985de..b104b8b1d96 100644 --- a/pkg/controller/syncset/syncset_controller.go +++ b/pkg/controller/syncset/syncset_controller.go @@ -10,7 +10,6 @@ import ( "github.com/open-policy-agent/gatekeeper/v3/pkg/logging" "github.com/open-policy-agent/gatekeeper/v3/pkg/operations" "github.com/open-policy-agent/gatekeeper/v3/pkg/readiness" - "github.com/open-policy-agent/gatekeeper/v3/pkg/watch" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -56,9 +55,6 @@ func (a *Adder) InjectCacheManager(o *cm.CacheManager) { a.CacheManager = o } -func (a *Adder) InjectControllerSwitch(_ *watch.ControllerSwitch) { -} - func (a *Adder) InjectTracker(t *readiness.Tracker) { a.Tracker = t } diff --git a/pkg/drivers/k8scel/driver.go b/pkg/drivers/k8scel/driver.go index 483b86b78f2..81abb53f05e 100644 --- a/pkg/drivers/k8scel/driver.go +++ b/pkg/drivers/k8scel/driver.go @@ -15,7 +15,7 @@ import ( "github.com/open-policy-agent/frameworks/constraint/pkg/types" pSchema "github.com/open-policy-agent/gatekeeper/v3/pkg/drivers/k8scel/schema" "github.com/open-policy-agent/gatekeeper/v3/pkg/drivers/k8scel/transform" - "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/storage" admissionv1 "k8s.io/api/admission/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" diff --git a/pkg/readiness/pruner/pruner_test.go b/pkg/readiness/pruner/pruner_test.go index eaa8daba831..36991bb2f49 100644 --- a/pkg/readiness/pruner/pruner_test.go +++ b/pkg/readiness/pruner/pruner_test.go @@ -15,7 +15,6 @@ import ( "github.com/open-policy-agent/gatekeeper/v3/pkg/mutation" "github.com/open-policy-agent/gatekeeper/v3/pkg/readiness" "github.com/open-policy-agent/gatekeeper/v3/pkg/syncutil" - "github.com/open-policy-agent/gatekeeper/v3/pkg/watch" testclient "github.com/open-policy-agent/gatekeeper/v3/test/clients" "github.com/open-policy-agent/gatekeeper/v3/test/testutils" "github.com/stretchr/testify/require" @@ -81,20 +80,18 @@ func setupTest(_ context.Context, t *testing.T, readyTrackerClient readiness.Lis cm, err := cachemanager.NewCacheManager(config) require.NoError(t, err, "creating cachemanager") - sw := watch.NewSwitch() mutationSystem := mutation.NewSystem(mutation.SystemOpts{}) frameworksexternaldata.NewCache() opts := controller.Dependencies{ - CFClient: testutils.SetupDataClient(t), - WatchManger: wm, - ControllerSwitch: sw, - Tracker: tracker, - ProcessExcluder: process.Get(), - MutationSystem: mutationSystem, - ExpansionSystem: expansion.NewSystem(mutationSystem), - ProviderCache: frameworksexternaldata.NewCache(), - CacheMgr: cm, - SyncEventsCh: events, + CFClient: testutils.SetupDataClient(t), + WatchManger: wm, + Tracker: tracker, + ProcessExcluder: process.Get(), + MutationSystem: mutationSystem, + ExpansionSystem: expansion.NewSystem(mutationSystem), + ProviderCache: frameworksexternaldata.NewCache(), + CacheMgr: cm, + SyncEventsCh: events, } require.NoError(t, controller.AddToManager(mgr, &opts), "registering controllers") diff --git a/pkg/readiness/ready_tracker_test.go b/pkg/readiness/ready_tracker_test.go index 147e5f184f1..8dc893ad0c1 100644 --- a/pkg/readiness/ready_tracker_test.go +++ b/pkg/readiness/ready_tracker_test.go @@ -128,8 +128,6 @@ func setupController( return fmt.Errorf("setting up tracker: %w", err) } - sw := watch.NewSwitch() - pod := fakes.Pod( fakes.WithNamespace("gatekeeper-system"), fakes.WithName("no-pod"), @@ -159,17 +157,16 @@ func setupController( // Setup all Controllers opts := controller.Dependencies{ - CFClient: cfClient, - WatchManger: wm, - ControllerSwitch: sw, - Tracker: tracker, - GetPod: func(_ context.Context) (*corev1.Pod, error) { return pod, nil }, - ProcessExcluder: processExcluder, - MutationSystem: mutationSystem, - ExpansionSystem: expansionSystem, - ProviderCache: providerCache, - CacheMgr: cacheManager, - SyncEventsCh: events, + CFClient: cfClient, + WatchManger: wm, + Tracker: tracker, + GetPod: func(_ context.Context) (*corev1.Pod, error) { return pod, nil }, + ProcessExcluder: processExcluder, + MutationSystem: mutationSystem, + ExpansionSystem: expansionSystem, + ProviderCache: providerCache, + CacheMgr: cacheManager, + SyncEventsCh: events, } if err := controller.AddToManager(mgr, &opts); err != nil { return fmt.Errorf("registering controllers: %w", err) diff --git a/pkg/watch/controller_switch.go b/pkg/watch/controller_switch.go deleted file mode 100644 index e6f27db4d8b..00000000000 --- a/pkg/watch/controller_switch.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package watch - -import ( - "sync" -) - -type ControllerSwitch struct { - running bool - runningLock sync.RWMutex -} - -func NewSwitch() *ControllerSwitch { - return &ControllerSwitch{running: true} -} - -func (c *ControllerSwitch) Stop() { - c.runningLock.Lock() - defer c.runningLock.Unlock() - c.running = false -} - -func (c *ControllerSwitch) Enter() bool { - c.runningLock.RLock() - return c.running -} - -func (c *ControllerSwitch) Exit() { - c.runningLock.RUnlock() -} diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/interface.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/interface.go index 036b23e4bfa..651e6e080ca 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/interface.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/interface.go @@ -5,7 +5,7 @@ import ( "github.com/open-policy-agent/frameworks/constraint/pkg/client/reviews" "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" - "github.com/open-policy-agent/opa/v1/storage" + "github.com/open-policy-agent/opa/storage" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/args.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/args.go index 4f68a7501e0..9a7ab8a3e37 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/args.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/args.go @@ -5,10 +5,10 @@ import ( "github.com/open-policy-agent/frameworks/constraint/pkg/client/errors" "github.com/open-policy-agent/frameworks/constraint/pkg/externaldata" - "github.com/open-policy-agent/opa/v1/ast" - "github.com/open-policy-agent/opa/v1/storage" - "github.com/open-policy-agent/opa/v1/topdown/print" - opatypes "github.com/open-policy-agent/opa/v1/types" + "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/storage" + "github.com/open-policy-agent/opa/topdown/print" + opatypes "github.com/open-policy-agent/opa/types" "sigs.k8s.io/controller-runtime/pkg/certwatcher" ) diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/builtin.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/builtin.go index 83a00a00d6d..7ea46eb6f3e 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/builtin.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/builtin.go @@ -5,8 +5,8 @@ import ( "time" "github.com/open-policy-agent/frameworks/constraint/pkg/externaldata" - "github.com/open-policy-agent/opa/v1/ast" - "github.com/open-policy-agent/opa/v1/rego" + "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/rego" ) const ( diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/compilers.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/compilers.go index 1524bd9c0e3..0fc072deae8 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/compilers.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/compilers.go @@ -9,7 +9,7 @@ import ( clienterrors "github.com/open-policy-agent/frameworks/constraint/pkg/client/errors" "github.com/open-policy-agent/frameworks/constraint/pkg/core/templates" "github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter" - "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/ast" ) var ErrNoRego = errors.New("Could not extract Rego from the constraint template") diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/driver.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/driver.go index c9041b889c2..921567179e2 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/driver.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/driver.go @@ -20,11 +20,11 @@ import ( "github.com/open-policy-agent/frameworks/constraint/pkg/externaldata" "github.com/open-policy-agent/frameworks/constraint/pkg/instrumentation" "github.com/open-policy-agent/frameworks/constraint/pkg/types" - "github.com/open-policy-agent/opa/v1/ast" - "github.com/open-policy-agent/opa/v1/rego" - "github.com/open-policy-agent/opa/v1/storage" - "github.com/open-policy-agent/opa/v1/topdown" - "github.com/open-policy-agent/opa/v1/topdown/print" + "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/rego" + "github.com/open-policy-agent/opa/storage" + "github.com/open-policy-agent/opa/topdown" + "github.com/open-policy-agent/opa/topdown/print" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/certwatcher" diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/new.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/new.go index eb0660eecf3..de433764b93 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/new.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/new.go @@ -1,8 +1,8 @@ package rego import ( - "github.com/open-policy-agent/opa/v1/rego" - opatypes "github.com/open-policy-agent/opa/v1/types" + "github.com/open-policy-agent/opa/rego" + opatypes "github.com/open-policy-agent/opa/types" ) // New constructs a new Driver and registers the built-in external_data function diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/rego.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/rego.go index 19c9bd01e31..2037bc028fe 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/rego.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/rego.go @@ -1,6 +1,6 @@ package rego -import "github.com/open-policy-agent/opa/v1/ast" +import "github.com/open-policy-agent/opa/ast" const ( // templatePath is the path the Template's Rego code is stored. diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/storages.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/storages.go index 8ff32e2ae8c..26361a1bbb8 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/storages.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/rego/storages.go @@ -6,8 +6,8 @@ import ( "sync" clienterrors "github.com/open-policy-agent/frameworks/constraint/pkg/client/errors" - "github.com/open-policy-agent/opa/v1/storage" - "github.com/open-policy-agent/opa/v1/storage/inmem" + "github.com/open-policy-agent/opa/storage" + "github.com/open-policy-agent/opa/storage/inmem" ) type storages struct { diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/to_result.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/to_result.go index 96cf7780058..72e8af9c690 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/to_result.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/client/drivers/to_result.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/open-policy-agent/frameworks/constraint/pkg/types" - "github.com/open-policy-agent/opa/v1/rego" + "github.com/open-policy-agent/opa/rego" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/externaldata/response.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/externaldata/response.go index 050ab98efa0..80164e86ed5 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/externaldata/response.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/externaldata/response.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/json" - "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/ast" ) // RegoResponse is the response inside rego. diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/ast_helpers.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/ast_helpers.go index 422b13b0091..ffc3e01e2aa 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/ast_helpers.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/ast_helpers.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/golang/glog" - "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/ast" ) var ( diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/module.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/module.go index dc75ec0108b..38906a1f44f 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/module.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/module.go @@ -4,8 +4,8 @@ import ( "os" "strings" - "github.com/open-policy-agent/opa/v1/ast" - "github.com/open-policy-agent/opa/v1/format" + "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/format" ) // Module represents a rego module. diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/packagetransformer.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/packagetransformer.go index 6d4601c350a..c2cead10df5 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/packagetransformer.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/packagetransformer.go @@ -3,7 +3,7 @@ package regorewriter import ( "strings" - "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/ast" ) // PackageTransformer takes a package path and transforms it to the new package path it will be diff --git a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/regorewriter.go b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/regorewriter.go index 0f90076db1a..815ae6642f0 100644 --- a/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/regorewriter.go +++ b/vendor/github.com/open-policy-agent/frameworks/constraint/pkg/regorewriter/regorewriter.go @@ -8,8 +8,8 @@ import ( "strings" "github.com/golang/glog" - "github.com/open-policy-agent/opa/v1/ast" - "github.com/open-policy-agent/opa/v1/format" + "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/format" ) const ( diff --git a/vendor/github.com/open-policy-agent/opa/ast/annotations.go b/vendor/github.com/open-policy-agent/opa/ast/annotations.go new file mode 100644 index 00000000000..533290d3233 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/annotations.go @@ -0,0 +1,33 @@ +// Copyright 2022 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +type ( + // Annotations represents metadata attached to other AST nodes such as rules. + Annotations = v1.Annotations + + // SchemaAnnotation contains a schema declaration for the document identified by the path. + SchemaAnnotation = v1.SchemaAnnotation + + AuthorAnnotation = v1.AuthorAnnotation + + RelatedResourceAnnotation = v1.RelatedResourceAnnotation + + AnnotationSet = v1.AnnotationSet + + AnnotationsRef = v1.AnnotationsRef + + AnnotationsRefSet = v1.AnnotationsRefSet + + FlatAnnotationsRefSet = v1.FlatAnnotationsRefSet +) + +func NewAnnotationsRef(a *Annotations) *AnnotationsRef { + return v1.NewAnnotationsRef(a) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/builtins.go b/vendor/github.com/open-policy-agent/opa/ast/builtins.go new file mode 100644 index 00000000000..d0ab69a1630 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/builtins.go @@ -0,0 +1,634 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// Builtins is the registry of built-in functions supported by OPA. +// Call RegisterBuiltin to add a new built-in. +var Builtins = v1.Builtins + +// RegisterBuiltin adds a new built-in function to the registry. +func RegisterBuiltin(b *Builtin) { + v1.RegisterBuiltin(b) +} + +// DefaultBuiltins is the registry of built-in functions supported in OPA +// by default. When adding a new built-in function to OPA, update this +// list. +var DefaultBuiltins = v1.DefaultBuiltins + +// BuiltinMap provides a convenient mapping of built-in names to +// built-in definitions. +var BuiltinMap = v1.BuiltinMap + +// Deprecated: Builtins can now be directly annotated with the +// Nondeterministic property, and when set to true, will be ignored +// for partial evaluation. +var IgnoreDuringPartialEval = v1.IgnoreDuringPartialEval + +/** + * Unification + */ + +// Equality represents the "=" operator. +var Equality = v1.Equality + +/** + * Assignment + */ + +// Assign represents the assignment (":=") operator. +var Assign = v1.Assign + +// Member represents the `in` (infix) operator. +var Member = v1.Member + +// MemberWithKey represents the `in` (infix) operator when used +// with two terms on the lhs, i.e., `k, v in obj`. +var MemberWithKey = v1.MemberWithKey + +var GreaterThan = v1.GreaterThan + +var GreaterThanEq = v1.GreaterThanEq + +// LessThan represents the "<" comparison operator. +var LessThan = v1.LessThan + +var LessThanEq = v1.LessThanEq + +var NotEqual = v1.NotEqual + +// Equal represents the "==" comparison operator. +var Equal = v1.Equal + +var Plus = v1.Plus + +var Minus = v1.Minus + +var Multiply = v1.Multiply + +var Divide = v1.Divide + +var Round = v1.Round + +var Ceil = v1.Ceil + +var Floor = v1.Floor + +var Abs = v1.Abs + +var Rem = v1.Rem + +/** + * Bitwise + */ + +var BitsOr = v1.BitsOr + +var BitsAnd = v1.BitsAnd + +var BitsNegate = v1.BitsNegate + +var BitsXOr = v1.BitsXOr + +var BitsShiftLeft = v1.BitsShiftLeft + +var BitsShiftRight = v1.BitsShiftRight + +/** + * Sets + */ + +var And = v1.And + +// Or performs a union operation on sets. +var Or = v1.Or + +var Intersection = v1.Intersection + +var Union = v1.Union + +/** + * Aggregates + */ + +var Count = v1.Count + +var Sum = v1.Sum + +var Product = v1.Product + +var Max = v1.Max + +var Min = v1.Min + +/** + * Sorting + */ + +var Sort = v1.Sort + +/** + * Arrays + */ + +var ArrayConcat = v1.ArrayConcat + +var ArraySlice = v1.ArraySlice + +var ArrayReverse = v1.ArrayReverse + +/** + * Conversions + */ + +var ToNumber = v1.ToNumber + +/** + * Regular Expressions + */ + +var RegexMatch = v1.RegexMatch + +var RegexIsValid = v1.RegexIsValid + +var RegexFindAllStringSubmatch = v1.RegexFindAllStringSubmatch + +var RegexTemplateMatch = v1.RegexTemplateMatch + +var RegexSplit = v1.RegexSplit + +// RegexFind takes two strings and a number, the pattern, the value and number of match values to +// return, -1 means all match values. +var RegexFind = v1.RegexFind + +// GlobsMatch takes two strings regexp-style strings and evaluates to true if their +// intersection matches a non-empty set of non-empty strings. +// Examples: +// - "a.a." and ".b.b" -> true. +// - "[a-z]*" and [0-9]+" -> not true. +var GlobsMatch = v1.GlobsMatch + +/** + * Strings + */ + +var AnyPrefixMatch = v1.AnyPrefixMatch + +var AnySuffixMatch = v1.AnySuffixMatch + +var Concat = v1.Concat + +var FormatInt = v1.FormatInt + +var IndexOf = v1.IndexOf + +var IndexOfN = v1.IndexOfN + +var Substring = v1.Substring + +var Contains = v1.Contains + +var StringCount = v1.StringCount + +var StartsWith = v1.StartsWith + +var EndsWith = v1.EndsWith + +var Lower = v1.Lower + +var Upper = v1.Upper + +var Split = v1.Split + +var Replace = v1.Replace + +var ReplaceN = v1.ReplaceN + +var RegexReplace = v1.RegexReplace + +var Trim = v1.Trim + +var TrimLeft = v1.TrimLeft + +var TrimPrefix = v1.TrimPrefix + +var TrimRight = v1.TrimRight + +var TrimSuffix = v1.TrimSuffix + +var TrimSpace = v1.TrimSpace + +var Sprintf = v1.Sprintf + +var StringReverse = v1.StringReverse + +var RenderTemplate = v1.RenderTemplate + +/** + * Numbers + */ + +// RandIntn returns a random number 0 - n +// Marked non-deterministic because it relies on RNG internally. +var RandIntn = v1.RandIntn + +var NumbersRange = v1.NumbersRange + +var NumbersRangeStep = v1.NumbersRangeStep + +/** + * Units + */ + +var UnitsParse = v1.UnitsParse + +var UnitsParseBytes = v1.UnitsParseBytes + +// +/** + * Type + */ + +// UUIDRFC4122 returns a version 4 UUID string. +// Marked non-deterministic because it relies on RNG internally. +var UUIDRFC4122 = v1.UUIDRFC4122 + +var UUIDParse = v1.UUIDParse + +/** + * JSON + */ + +var JSONFilter = v1.JSONFilter + +var JSONRemove = v1.JSONRemove + +var JSONPatch = v1.JSONPatch + +var ObjectSubset = v1.ObjectSubset + +var ObjectUnion = v1.ObjectUnion + +var ObjectUnionN = v1.ObjectUnionN + +var ObjectRemove = v1.ObjectRemove + +var ObjectFilter = v1.ObjectFilter + +var ObjectGet = v1.ObjectGet + +var ObjectKeys = v1.ObjectKeys + +/* + * Encoding + */ + +var JSONMarshal = v1.JSONMarshal + +var JSONMarshalWithOptions = v1.JSONMarshalWithOptions + +var JSONUnmarshal = v1.JSONUnmarshal + +var JSONIsValid = v1.JSONIsValid + +var Base64Encode = v1.Base64Encode + +var Base64Decode = v1.Base64Decode + +var Base64IsValid = v1.Base64IsValid + +var Base64UrlEncode = v1.Base64UrlEncode + +var Base64UrlEncodeNoPad = v1.Base64UrlEncodeNoPad + +var Base64UrlDecode = v1.Base64UrlDecode + +var URLQueryDecode = v1.URLQueryDecode + +var URLQueryEncode = v1.URLQueryEncode + +var URLQueryEncodeObject = v1.URLQueryEncodeObject + +var URLQueryDecodeObject = v1.URLQueryDecodeObject + +var YAMLMarshal = v1.YAMLMarshal + +var YAMLUnmarshal = v1.YAMLUnmarshal + +// YAMLIsValid verifies the input string is a valid YAML document. +var YAMLIsValid = v1.YAMLIsValid + +var HexEncode = v1.HexEncode + +var HexDecode = v1.HexDecode + +/** + * Tokens + */ + +var JWTDecode = v1.JWTDecode + +var JWTVerifyRS256 = v1.JWTVerifyRS256 + +var JWTVerifyRS384 = v1.JWTVerifyRS384 + +var JWTVerifyRS512 = v1.JWTVerifyRS512 + +var JWTVerifyPS256 = v1.JWTVerifyPS256 + +var JWTVerifyPS384 = v1.JWTVerifyPS384 + +var JWTVerifyPS512 = v1.JWTVerifyPS512 + +var JWTVerifyES256 = v1.JWTVerifyES256 + +var JWTVerifyES384 = v1.JWTVerifyES384 + +var JWTVerifyES512 = v1.JWTVerifyES512 + +var JWTVerifyHS256 = v1.JWTVerifyHS256 + +var JWTVerifyHS384 = v1.JWTVerifyHS384 + +var JWTVerifyHS512 = v1.JWTVerifyHS512 + +// Marked non-deterministic because it relies on time internally. +var JWTDecodeVerify = v1.JWTDecodeVerify + +// Marked non-deterministic because it relies on RNG internally. +var JWTEncodeSignRaw = v1.JWTEncodeSignRaw + +// Marked non-deterministic because it relies on RNG internally. +var JWTEncodeSign = v1.JWTEncodeSign + +/** + * Time + */ + +// Marked non-deterministic because it relies on time directly. +var NowNanos = v1.NowNanos + +var ParseNanos = v1.ParseNanos + +var ParseRFC3339Nanos = v1.ParseRFC3339Nanos + +var ParseDurationNanos = v1.ParseDurationNanos + +var Format = v1.Format + +var Date = v1.Date + +var Clock = v1.Clock + +var Weekday = v1.Weekday + +var AddDate = v1.AddDate + +var Diff = v1.Diff + +/** + * Crypto. + */ + +var CryptoX509ParseCertificates = v1.CryptoX509ParseCertificates + +var CryptoX509ParseAndVerifyCertificates = v1.CryptoX509ParseAndVerifyCertificates + +var CryptoX509ParseAndVerifyCertificatesWithOptions = v1.CryptoX509ParseAndVerifyCertificatesWithOptions + +var CryptoX509ParseCertificateRequest = v1.CryptoX509ParseCertificateRequest + +var CryptoX509ParseKeyPair = v1.CryptoX509ParseKeyPair +var CryptoX509ParseRSAPrivateKey = v1.CryptoX509ParseRSAPrivateKey + +var CryptoParsePrivateKeys = v1.CryptoParsePrivateKeys + +var CryptoMd5 = v1.CryptoMd5 + +var CryptoSha1 = v1.CryptoSha1 + +var CryptoSha256 = v1.CryptoSha256 + +var CryptoHmacMd5 = v1.CryptoHmacMd5 + +var CryptoHmacSha1 = v1.CryptoHmacSha1 + +var CryptoHmacSha256 = v1.CryptoHmacSha256 + +var CryptoHmacSha512 = v1.CryptoHmacSha512 + +var CryptoHmacEqual = v1.CryptoHmacEqual + +/** + * Graphs. + */ + +var WalkBuiltin = v1.WalkBuiltin + +var ReachableBuiltin = v1.ReachableBuiltin + +var ReachablePathsBuiltin = v1.ReachablePathsBuiltin + +/** + * Type + */ + +var IsNumber = v1.IsNumber + +var IsString = v1.IsString + +var IsBoolean = v1.IsBoolean + +var IsArray = v1.IsArray + +var IsSet = v1.IsSet + +var IsObject = v1.IsObject + +var IsNull = v1.IsNull + +/** + * Type Name + */ + +// TypeNameBuiltin returns the type of the input. +var TypeNameBuiltin = v1.TypeNameBuiltin + +/** + * HTTP Request + */ + +// Marked non-deterministic because HTTP request results can be non-deterministic. +var HTTPSend = v1.HTTPSend + +/** + * GraphQL + */ + +// GraphQLParse returns a pair of AST objects from parsing/validation. +var GraphQLParse = v1.GraphQLParse + +// GraphQLParseAndVerify returns a boolean and a pair of AST object from parsing/validation. +var GraphQLParseAndVerify = v1.GraphQLParseAndVerify + +// GraphQLParseQuery parses the input GraphQL query and returns a JSON +// representation of its AST. +var GraphQLParseQuery = v1.GraphQLParseQuery + +// GraphQLParseSchema parses the input GraphQL schema and returns a JSON +// representation of its AST. +var GraphQLParseSchema = v1.GraphQLParseSchema + +// GraphQLIsValid returns true if a GraphQL query is valid with a given +// schema, and returns false for all other inputs. +var GraphQLIsValid = v1.GraphQLIsValid + +// GraphQLSchemaIsValid returns true if the input is valid GraphQL schema, +// and returns false for all other inputs. +var GraphQLSchemaIsValid = v1.GraphQLSchemaIsValid + +/** + * JSON Schema + */ + +// JSONSchemaVerify returns empty string if the input is valid JSON schema +// and returns error string for all other inputs. +var JSONSchemaVerify = v1.JSONSchemaVerify + +// JSONMatchSchema returns empty array if the document matches the JSON schema, +// and returns non-empty array with error objects otherwise. +var JSONMatchSchema = v1.JSONMatchSchema + +/** + * Cloud Provider Helper Functions + */ + +var ProvidersAWSSignReqObj = v1.ProvidersAWSSignReqObj + +/** + * Rego + */ + +var RegoParseModule = v1.RegoParseModule + +var RegoMetadataChain = v1.RegoMetadataChain + +// RegoMetadataRule returns the metadata for the active rule +var RegoMetadataRule = v1.RegoMetadataRule + +/** + * OPA + */ + +// Marked non-deterministic because of unpredictable config/environment-dependent results. +var OPARuntime = v1.OPARuntime + +/** + * Trace + */ + +var Trace = v1.Trace + +/** + * Glob + */ + +var GlobMatch = v1.GlobMatch + +var GlobQuoteMeta = v1.GlobQuoteMeta + +/** + * Networking + */ + +var NetCIDRIntersects = v1.NetCIDRIntersects + +var NetCIDRExpand = v1.NetCIDRExpand + +var NetCIDRContains = v1.NetCIDRContains + +var NetCIDRContainsMatches = v1.NetCIDRContainsMatches + +var NetCIDRMerge = v1.NetCIDRMerge + +var NetCIDRIsValid = v1.NetCIDRIsValid + +// Marked non-deterministic because DNS resolution results can be non-deterministic. +var NetLookupIPAddr = v1.NetLookupIPAddr + +/** + * Semantic Versions + */ + +var SemVerIsValid = v1.SemVerIsValid + +var SemVerCompare = v1.SemVerCompare + +/** + * Printing + */ + +// Print is a special built-in function that writes zero or more operands +// to a message buffer. The caller controls how the buffer is displayed. The +// operands may be of any type. Furthermore, unlike other built-in functions, +// undefined operands DO NOT cause the print() function to fail during +// evaluation. +var Print = v1.Print + +// InternalPrint represents the internal implementation of the print() function. +// The compiler rewrites print() calls to refer to the internal implementation. +var InternalPrint = v1.InternalPrint + +/** + * Deprecated built-ins. + */ + +// SetDiff has been replaced by the minus built-in. +var SetDiff = v1.SetDiff + +// NetCIDROverlap has been replaced by the `net.cidr_contains` built-in. +var NetCIDROverlap = v1.NetCIDROverlap + +// CastArray checks the underlying type of the input. If it is array or set, an array +// containing the values is returned. If it is not an array, an error is thrown. +var CastArray = v1.CastArray + +// CastSet checks the underlying type of the input. +// If it is a set, the set is returned. +// If it is an array, the array is returned in set form (all duplicates removed) +// If neither, an error is thrown +var CastSet = v1.CastSet + +// CastString returns input if it is a string; if not returns error. +// For formatting variables, see sprintf +var CastString = v1.CastString + +// CastBoolean returns input if it is a boolean; if not returns error. +var CastBoolean = v1.CastBoolean + +// CastNull returns null if input is null; if not returns error. +var CastNull = v1.CastNull + +// CastObject returns the given object if it is null; throws an error otherwise +var CastObject = v1.CastObject + +// RegexMatchDeprecated declares `re_match` which has been deprecated. Use `regex.match` instead. +var RegexMatchDeprecated = v1.RegexMatchDeprecated + +// All takes a list and returns true if all of the items +// are true. A collection of length 0 returns true. +var All = v1.All + +// Any takes a collection and returns true if any of the items +// is true. A collection of length 0 returns false. +var Any = v1.Any + +// Builtin represents a built-in function supported by OPA. Every built-in +// function is uniquely identified by a name. +type Builtin = v1.Builtin diff --git a/vendor/github.com/open-policy-agent/opa/ast/capabilities.go b/vendor/github.com/open-policy-agent/opa/ast/capabilities.go new file mode 100644 index 00000000000..bc7278a885a --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/capabilities.go @@ -0,0 +1,58 @@ +// Copyright 2020 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + "io" + + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// VersonIndex contains an index from built-in function name, language feature, +// and future rego keyword to version number. During the build, this is used to +// create an index of the minimum version required for the built-in/feature/kw. +type VersionIndex = v1.VersionIndex + +// In the compiler, we used this to check that we're OK working with ref heads. +// If this isn't present, we'll fail. This is to ensure that older versions of +// OPA can work with policies that we're compiling -- if they don't know ref +// heads, they wouldn't be able to parse them. +const FeatureRefHeadStringPrefixes = v1.FeatureRefHeadStringPrefixes +const FeatureRefHeads = v1.FeatureRefHeads +const FeatureRegoV1 = v1.FeatureRegoV1 +const FeatureRegoV1Import = v1.FeatureRegoV1Import + +// Capabilities defines a structure containing data that describes the capabilities +// or features supported by a particular version of OPA. +type Capabilities = v1.Capabilities + +// WasmABIVersion captures the Wasm ABI version. Its `Minor` version is indicating +// backwards-compatible changes. +type WasmABIVersion = v1.WasmABIVersion + +// CapabilitiesForThisVersion returns the capabilities of this version of OPA. +func CapabilitiesForThisVersion() *Capabilities { + return v1.CapabilitiesForThisVersion(v1.CapabilitiesRegoVersion(DefaultRegoVersion)) +} + +// LoadCapabilitiesJSON loads a JSON serialized capabilities structure from the reader r. +func LoadCapabilitiesJSON(r io.Reader) (*Capabilities, error) { + return v1.LoadCapabilitiesJSON(r) +} + +// LoadCapabilitiesVersion loads a JSON serialized capabilities structure from the specific version. +func LoadCapabilitiesVersion(version string) (*Capabilities, error) { + return v1.LoadCapabilitiesVersion(version) +} + +// LoadCapabilitiesFile loads a JSON serialized capabilities structure from a file. +func LoadCapabilitiesFile(file string) (*Capabilities, error) { + return v1.LoadCapabilitiesFile(file) +} + +// LoadCapabilitiesVersions loads all capabilities versions +func LoadCapabilitiesVersions() ([]string, error) { + return v1.LoadCapabilitiesVersions() +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/check.go b/vendor/github.com/open-policy-agent/opa/ast/check.go new file mode 100644 index 00000000000..4cf00436df1 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/check.go @@ -0,0 +1,22 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// UnificationErrDetail describes a type mismatch error when two values are +// unified (e.g., x = [1,2,y]). +type UnificationErrDetail = v1.UnificationErrDetail + +// RefErrUnsupportedDetail describes an undefined reference error where the +// referenced value does not support dereferencing (e.g., scalars). +type RefErrUnsupportedDetail = v1.RefErrUnsupportedDetail + +// RefErrInvalidDetail describes an undefined reference error where the referenced +// value does not support the reference operand (e.g., missing object key, +// invalid key type, etc.) +type RefErrInvalidDetail = v1.RefErrInvalidDetail diff --git a/vendor/github.com/open-policy-agent/opa/ast/compare.go b/vendor/github.com/open-policy-agent/opa/ast/compare.go new file mode 100644 index 00000000000..d36078e3384 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/compare.go @@ -0,0 +1,39 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// Compare returns an integer indicating whether two AST values are less than, +// equal to, or greater than each other. +// +// If a is less than b, the return value is negative. If a is greater than b, +// the return value is positive. If a is equal to b, the return value is zero. +// +// Different types are never equal to each other. For comparison purposes, types +// are sorted as follows: +// +// nil < Null < Boolean < Number < String < Var < Ref < Array < Object < Set < +// ArrayComprehension < ObjectComprehension < SetComprehension < Expr < SomeDecl +// < With < Body < Rule < Import < Package < Module. +// +// Arrays and Refs are equal if and only if both a and b have the same length +// and all corresponding elements are equal. If one element is not equal, the +// return value is the same as for the first differing element. If all elements +// are equal but a and b have different lengths, the shorter is considered less +// than the other. +// +// Objects are considered equal if and only if both a and b have the same sorted +// (key, value) pairs and are of the same length. Other comparisons are +// consistent but not defined. +// +// Sets are considered equal if and only if the symmetric difference of a and b +// is empty. +// Other comparisons are consistent but not defined. +func Compare(a, b interface{}) int { + return v1.Compare(a, b) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/compile.go b/vendor/github.com/open-policy-agent/opa/ast/compile.go new file mode 100644 index 00000000000..5a3daa910a7 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/compile.go @@ -0,0 +1,127 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// CompileErrorLimitDefault is the default number errors a compiler will allow before +// exiting. +const CompileErrorLimitDefault = 10 + +// Compiler contains the state of a compilation process. +type Compiler = v1.Compiler + +// CompilerStage defines the interface for stages in the compiler. +type CompilerStage = v1.CompilerStage + +// CompilerEvalMode allows toggling certain stages that are only +// needed for certain modes, Concretely, only "topdown" mode will +// have the compiler build comprehension and rule indices. +type CompilerEvalMode = v1.CompilerEvalMode + +const ( + // EvalModeTopdown (default) instructs the compiler to build rule + // and comprehension indices used by topdown evaluation. + EvalModeTopdown = v1.EvalModeTopdown + + // EvalModeIR makes the compiler skip the stages for comprehension + // and rule indices. + EvalModeIR = v1.EvalModeIR +) + +// CompilerStageDefinition defines a compiler stage +type CompilerStageDefinition = v1.CompilerStageDefinition + +// RulesOptions defines the options for retrieving rules by Ref from the +// compiler. +type RulesOptions = v1.RulesOptions + +// QueryContext contains contextual information for running an ad-hoc query. +// +// Ad-hoc queries can be run in the context of a package and imports may be +// included to provide concise access to data. +type QueryContext = v1.QueryContext + +// NewQueryContext returns a new QueryContext object. +func NewQueryContext() *QueryContext { + return v1.NewQueryContext() +} + +// QueryCompiler defines the interface for compiling ad-hoc queries. +type QueryCompiler = v1.QueryCompiler + +// QueryCompilerStage defines the interface for stages in the query compiler. +type QueryCompilerStage = v1.QueryCompilerStage + +// QueryCompilerStageDefinition defines a QueryCompiler stage +type QueryCompilerStageDefinition = v1.QueryCompilerStageDefinition + +// NewCompiler returns a new empty compiler. +func NewCompiler() *Compiler { + return v1.NewCompiler().WithDefaultRegoVersion(DefaultRegoVersion) +} + +// ModuleLoader defines the interface that callers can implement to enable lazy +// loading of modules during compilation. +type ModuleLoader = v1.ModuleLoader + +// SafetyCheckVisitorParams defines the AST visitor parameters to use for collecting +// variables during the safety check. This has to be exported because it's relied on +// by the copy propagation implementation in topdown. +var SafetyCheckVisitorParams = v1.SafetyCheckVisitorParams + +// ComprehensionIndex specifies how the comprehension term can be indexed. The keys +// tell the evaluator what variables to use for indexing. In the future, the index +// could be expanded with more information that would allow the evaluator to index +// a larger fragment of comprehensions (e.g., by closing over variables in the outer +// query.) +type ComprehensionIndex = v1.ComprehensionIndex + +// ModuleTreeNode represents a node in the module tree. The module +// tree is keyed by the package path. +type ModuleTreeNode = v1.ModuleTreeNode + +// TreeNode represents a node in the rule tree. The rule tree is keyed by +// rule path. +type TreeNode = v1.TreeNode + +// NewRuleTree returns a new TreeNode that represents the root +// of the rule tree populated with the given rules. +func NewRuleTree(mtree *ModuleTreeNode) *TreeNode { + return v1.NewRuleTree(mtree) +} + +// Graph represents the graph of dependencies between rules. +type Graph = v1.Graph + +// NewGraph returns a new Graph based on modules. The list function must return +// the rules referred to directly by the ref. +func NewGraph(modules map[string]*Module, list func(Ref) []*Rule) *Graph { + return v1.NewGraph(modules, list) +} + +// GraphTraversal is a Traversal that understands the dependency graph +type GraphTraversal = v1.GraphTraversal + +// NewGraphTraversal returns a Traversal for the dependency graph +func NewGraphTraversal(graph *Graph) *GraphTraversal { + return v1.NewGraphTraversal(graph) +} + +// OutputVarsFromBody returns all variables which are the "output" for +// the given body. For safety checks this means that they would be +// made safe by the body. +func OutputVarsFromBody(c *Compiler, body Body, safe VarSet) VarSet { + return v1.OutputVarsFromBody(c, body, safe) +} + +// OutputVarsFromExpr returns all variables which are the "output" for +// the given expression. For safety checks this means that they would be +// made safe by the expr. +func OutputVarsFromExpr(c *Compiler, expr *Expr, safe VarSet) VarSet { + return v1.OutputVarsFromExpr(c, expr, safe) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/compilehelper.go b/vendor/github.com/open-policy-agent/opa/ast/compilehelper.go new file mode 100644 index 00000000000..37ede329ea4 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/compilehelper.go @@ -0,0 +1,48 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import v1 "github.com/open-policy-agent/opa/v1/ast" + +// CompileModules takes a set of Rego modules represented as strings and +// compiles them for evaluation. The keys of the map are used as filenames. +func CompileModules(modules map[string]string) (*Compiler, error) { + return CompileModulesWithOpt(modules, CompileOpts{ + ParserOptions: ParserOptions{ + RegoVersion: DefaultRegoVersion, + }, + }) +} + +// CompileOpts defines a set of options for the compiler. +type CompileOpts = v1.CompileOpts + +// CompileModulesWithOpt takes a set of Rego modules represented as strings and +// compiles them for evaluation. The keys of the map are used as filenames. +func CompileModulesWithOpt(modules map[string]string, opts CompileOpts) (*Compiler, error) { + if opts.ParserOptions.RegoVersion == RegoUndefined { + opts.ParserOptions.RegoVersion = DefaultRegoVersion + } + + return v1.CompileModulesWithOpt(modules, opts) +} + +// MustCompileModules compiles a set of Rego modules represented as strings. If +// the compilation process fails, this function panics. +func MustCompileModules(modules map[string]string) *Compiler { + return MustCompileModulesWithOpts(modules, CompileOpts{}) +} + +// MustCompileModulesWithOpts compiles a set of Rego modules represented as strings. If +// the compilation process fails, this function panics. +func MustCompileModulesWithOpts(modules map[string]string, opts CompileOpts) *Compiler { + + compiler, err := CompileModulesWithOpt(modules, opts) + if err != nil { + panic(err) + } + + return compiler +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/conflicts.go b/vendor/github.com/open-policy-agent/opa/ast/conflicts.go new file mode 100644 index 00000000000..10edce382c3 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/conflicts.go @@ -0,0 +1,15 @@ +// Copyright 2019 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// CheckPathConflicts returns a set of errors indicating paths that +// are in conflict with the result of the provided callable. +func CheckPathConflicts(c *Compiler, exists func([]string) (bool, error)) Errors { + return v1.CheckPathConflicts(c, exists) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/doc.go b/vendor/github.com/open-policy-agent/opa/ast/doc.go new file mode 100644 index 00000000000..ba974e5ba60 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/doc.go @@ -0,0 +1,8 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package ast diff --git a/vendor/github.com/open-policy-agent/opa/ast/env.go b/vendor/github.com/open-policy-agent/opa/ast/env.go new file mode 100644 index 00000000000..ef0ccf89ce8 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/env.go @@ -0,0 +1,12 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// TypeEnv contains type info for static analysis such as type checking. +type TypeEnv = v1.TypeEnv diff --git a/vendor/github.com/open-policy-agent/opa/ast/errors.go b/vendor/github.com/open-policy-agent/opa/ast/errors.go new file mode 100644 index 00000000000..0cb8ee28f70 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/errors.go @@ -0,0 +1,46 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// Errors represents a series of errors encountered during parsing, compiling, +// etc. +type Errors = v1.Errors + +const ( + // ParseErr indicates an unclassified parse error occurred. + ParseErr = v1.ParseErr + + // CompileErr indicates an unclassified compile error occurred. + CompileErr = v1.CompileErr + + // TypeErr indicates a type error was caught. + TypeErr = v1.TypeErr + + // UnsafeVarErr indicates an unsafe variable was found during compilation. + UnsafeVarErr = v1.UnsafeVarErr + + // RecursionErr indicates recursion was found during compilation. + RecursionErr = v1.RecursionErr +) + +// IsError returns true if err is an AST error with code. +func IsError(code string, err error) bool { + return v1.IsError(code, err) +} + +// ErrorDetails defines the interface for detailed error messages. +type ErrorDetails = v1.ErrorDetails + +// Error represents a single error caught during parsing, compiling, etc. +type Error = v1.Error + +// NewError returns a new Error object. +func NewError(code string, loc *Location, f string, a ...interface{}) *Error { + return v1.NewError(code, loc, f, a...) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/index.go b/vendor/github.com/open-policy-agent/opa/ast/index.go new file mode 100644 index 00000000000..7e80bb7716c --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/index.go @@ -0,0 +1,20 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// RuleIndex defines the interface for rule indices. +type RuleIndex v1.RuleIndex + +// IndexResult contains the result of an index lookup. +type IndexResult = v1.IndexResult + +// NewIndexResult returns a new IndexResult object. +func NewIndexResult(kind RuleKind) *IndexResult { + return v1.NewIndexResult(kind) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/interning.go b/vendor/github.com/open-policy-agent/opa/ast/interning.go new file mode 100644 index 00000000000..239293664be --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/interning.go @@ -0,0 +1,24 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +func InternedBooleanTerm(b bool) *Term { + return v1.InternedBooleanTerm(b) +} + +// InternedIntNumberTerm returns a term with the given integer value. The term is +// cached between -1 to 512, and for values outside of that range, this function +// is equivalent to ast.IntNumberTerm. +func InternedIntNumberTerm(i int) *Term { + return v1.InternedIntNumberTerm(i) +} + +func HasInternedIntNumberTerm(i int) bool { + return v1.HasInternedIntNumberTerm(i) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/json/doc.go b/vendor/github.com/open-policy-agent/opa/ast/json/doc.go new file mode 100644 index 00000000000..26aee9b9940 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/json/doc.go @@ -0,0 +1,8 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package json diff --git a/vendor/github.com/open-policy-agent/opa/ast/json/json.go b/vendor/github.com/open-policy-agent/opa/ast/json/json.go new file mode 100644 index 00000000000..8a3a36bb9b1 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/json/json.go @@ -0,0 +1,15 @@ +package json + +import v1 "github.com/open-policy-agent/opa/v1/ast/json" + +// Options defines the options for JSON operations, +// currently only marshaling can be configured +type Options = v1.Options + +// MarshalOptions defines the options for JSON marshaling, +// currently only toggling the marshaling of location information is supported +type MarshalOptions = v1.MarshalOptions + +// NodeToggle is a generic struct to allow the toggling of +// settings for different ast node types +type NodeToggle = v1.NodeToggle diff --git a/vendor/github.com/open-policy-agent/opa/ast/map.go b/vendor/github.com/open-policy-agent/opa/ast/map.go new file mode 100644 index 00000000000..070ad3e5ded --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/map.go @@ -0,0 +1,18 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// ValueMap represents a key/value map between AST term values. Any type of term +// can be used as a key in the map. +type ValueMap = v1.ValueMap + +// NewValueMap returns a new ValueMap. +func NewValueMap() *ValueMap { + return v1.NewValueMap() +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/parser.go b/vendor/github.com/open-policy-agent/opa/ast/parser.go new file mode 100644 index 00000000000..45cd4da06ef --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/parser.go @@ -0,0 +1,49 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +var RegoV1CompatibleRef = v1.RegoV1CompatibleRef + +// RegoVersion defines the Rego syntax requirements for a module. +type RegoVersion = v1.RegoVersion + +const DefaultRegoVersion = RegoV0 + +const ( + RegoUndefined = v1.RegoUndefined + // RegoV0 is the default, original Rego syntax. + RegoV0 = v1.RegoV0 + // RegoV0CompatV1 requires modules to comply with both the RegoV0 and RegoV1 syntax (as when 'rego.v1' is imported in a module). + // Shortly, RegoV1 compatibility is required, but 'rego.v1' or 'future.keywords' must also be imported. + RegoV0CompatV1 = v1.RegoV0CompatV1 + // RegoV1 is the Rego syntax enforced by OPA 1.0; e.g.: + // future.keywords part of default keyword set, and don't require imports; + // 'if' and 'contains' required in rule heads; + // (some) strict checks on by default. + RegoV1 = v1.RegoV1 +) + +func RegoVersionFromInt(i int) RegoVersion { + return v1.RegoVersionFromInt(i) +} + +// Parser is used to parse Rego statements. +type Parser = v1.Parser + +// ParserOptions defines the options for parsing Rego statements. +type ParserOptions = v1.ParserOptions + +// NewParser creates and initializes a Parser. +func NewParser() *Parser { + return v1.NewParser().WithRegoVersion(DefaultRegoVersion) +} + +func IsFutureKeyword(s string) bool { + return v1.IsFutureKeywordForRegoVersion(s, RegoV0) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/parser_ext.go b/vendor/github.com/open-policy-agent/opa/ast/parser_ext.go new file mode 100644 index 00000000000..3b8b4068252 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/parser_ext.go @@ -0,0 +1,310 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + "fmt" + + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// MustParseBody returns a parsed body. +// If an error occurs during parsing, panic. +func MustParseBody(input string) Body { + return MustParseBodyWithOpts(input, ParserOptions{}) +} + +// MustParseBodyWithOpts returns a parsed body. +// If an error occurs during parsing, panic. +func MustParseBodyWithOpts(input string, opts ParserOptions) Body { + return v1.MustParseBodyWithOpts(input, setDefaultRegoVersion(opts)) +} + +// MustParseExpr returns a parsed expression. +// If an error occurs during parsing, panic. +func MustParseExpr(input string) *Expr { + parsed, err := ParseExpr(input) + if err != nil { + panic(err) + } + return parsed +} + +// MustParseImports returns a slice of imports. +// If an error occurs during parsing, panic. +func MustParseImports(input string) []*Import { + parsed, err := ParseImports(input) + if err != nil { + panic(err) + } + return parsed +} + +// MustParseModule returns a parsed module. +// If an error occurs during parsing, panic. +func MustParseModule(input string) *Module { + return MustParseModuleWithOpts(input, ParserOptions{}) +} + +// MustParseModuleWithOpts returns a parsed module. +// If an error occurs during parsing, panic. +func MustParseModuleWithOpts(input string, opts ParserOptions) *Module { + return v1.MustParseModuleWithOpts(input, setDefaultRegoVersion(opts)) +} + +// MustParsePackage returns a Package. +// If an error occurs during parsing, panic. +func MustParsePackage(input string) *Package { + parsed, err := ParsePackage(input) + if err != nil { + panic(err) + } + return parsed +} + +// MustParseStatements returns a slice of parsed statements. +// If an error occurs during parsing, panic. +func MustParseStatements(input string) []Statement { + parsed, _, err := ParseStatements("", input) + if err != nil { + panic(err) + } + return parsed +} + +// MustParseStatement returns exactly one statement. +// If an error occurs during parsing, panic. +func MustParseStatement(input string) Statement { + parsed, err := ParseStatement(input) + if err != nil { + panic(err) + } + return parsed +} + +func MustParseStatementWithOpts(input string, popts ParserOptions) Statement { + return v1.MustParseStatementWithOpts(input, setDefaultRegoVersion(popts)) +} + +// MustParseRef returns a parsed reference. +// If an error occurs during parsing, panic. +func MustParseRef(input string) Ref { + parsed, err := ParseRef(input) + if err != nil { + panic(err) + } + return parsed +} + +// MustParseRule returns a parsed rule. +// If an error occurs during parsing, panic. +func MustParseRule(input string) *Rule { + parsed, err := ParseRule(input) + if err != nil { + panic(err) + } + return parsed +} + +// MustParseRuleWithOpts returns a parsed rule. +// If an error occurs during parsing, panic. +func MustParseRuleWithOpts(input string, opts ParserOptions) *Rule { + return v1.MustParseRuleWithOpts(input, setDefaultRegoVersion(opts)) +} + +// MustParseTerm returns a parsed term. +// If an error occurs during parsing, panic. +func MustParseTerm(input string) *Term { + parsed, err := ParseTerm(input) + if err != nil { + panic(err) + } + return parsed +} + +// ParseRuleFromBody returns a rule if the body can be interpreted as a rule +// definition. Otherwise, an error is returned. +func ParseRuleFromBody(module *Module, body Body) (*Rule, error) { + return v1.ParseRuleFromBody(module, body) +} + +// ParseRuleFromExpr returns a rule if the expression can be interpreted as a +// rule definition. +func ParseRuleFromExpr(module *Module, expr *Expr) (*Rule, error) { + return v1.ParseRuleFromExpr(module, expr) +} + +// ParseCompleteDocRuleFromAssignmentExpr returns a rule if the expression can +// be interpreted as a complete document definition declared with the assignment +// operator. +func ParseCompleteDocRuleFromAssignmentExpr(module *Module, lhs, rhs *Term) (*Rule, error) { + return v1.ParseCompleteDocRuleFromAssignmentExpr(module, lhs, rhs) +} + +// ParseCompleteDocRuleFromEqExpr returns a rule if the expression can be +// interpreted as a complete document definition. +func ParseCompleteDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, error) { + return v1.ParseCompleteDocRuleFromEqExpr(module, lhs, rhs) +} + +func ParseCompleteDocRuleWithDotsFromTerm(module *Module, term *Term) (*Rule, error) { + return v1.ParseCompleteDocRuleWithDotsFromTerm(module, term) +} + +// ParsePartialObjectDocRuleFromEqExpr returns a rule if the expression can be +// interpreted as a partial object document definition. +func ParsePartialObjectDocRuleFromEqExpr(module *Module, lhs, rhs *Term) (*Rule, error) { + return v1.ParsePartialObjectDocRuleFromEqExpr(module, lhs, rhs) +} + +// ParsePartialSetDocRuleFromTerm returns a rule if the term can be interpreted +// as a partial set document definition. +func ParsePartialSetDocRuleFromTerm(module *Module, term *Term) (*Rule, error) { + return v1.ParsePartialSetDocRuleFromTerm(module, term) +} + +// ParseRuleFromCallEqExpr returns a rule if the term can be interpreted as a +// function definition (e.g., f(x) = y => f(x) = y { true }). +func ParseRuleFromCallEqExpr(module *Module, lhs, rhs *Term) (*Rule, error) { + return v1.ParseRuleFromCallEqExpr(module, lhs, rhs) +} + +// ParseRuleFromCallExpr returns a rule if the terms can be interpreted as a +// function returning true or some value (e.g., f(x) => f(x) = true { true }). +func ParseRuleFromCallExpr(module *Module, terms []*Term) (*Rule, error) { + return v1.ParseRuleFromCallExpr(module, terms) +} + +// ParseImports returns a slice of Import objects. +func ParseImports(input string) ([]*Import, error) { + return v1.ParseImports(input) +} + +// ParseModule returns a parsed Module object. +// For details on Module objects and their fields, see policy.go. +// Empty input will return nil, nil. +func ParseModule(filename, input string) (*Module, error) { + return ParseModuleWithOpts(filename, input, ParserOptions{}) +} + +// ParseModuleWithOpts returns a parsed Module object, and has an additional input ParserOptions +// For details on Module objects and their fields, see policy.go. +// Empty input will return nil, nil. +func ParseModuleWithOpts(filename, input string, popts ParserOptions) (*Module, error) { + return v1.ParseModuleWithOpts(filename, input, setDefaultRegoVersion(popts)) +} + +// ParseBody returns exactly one body. +// If multiple bodies are parsed, an error is returned. +func ParseBody(input string) (Body, error) { + return ParseBodyWithOpts(input, ParserOptions{SkipRules: true}) +} + +// ParseBodyWithOpts returns exactly one body. It does _not_ set SkipRules: true on its own, +// but respects whatever ParserOptions it's been given. +func ParseBodyWithOpts(input string, popts ParserOptions) (Body, error) { + return v1.ParseBodyWithOpts(input, setDefaultRegoVersion(popts)) +} + +// ParseExpr returns exactly one expression. +// If multiple expressions are parsed, an error is returned. +func ParseExpr(input string) (*Expr, error) { + body, err := ParseBody(input) + if err != nil { + return nil, fmt.Errorf("failed to parse expression: %w", err) + } + if len(body) != 1 { + return nil, fmt.Errorf("expected exactly one expression but got: %v", body) + } + return body[0], nil +} + +// ParsePackage returns exactly one Package. +// If multiple statements are parsed, an error is returned. +func ParsePackage(input string) (*Package, error) { + return v1.ParsePackage(input) +} + +// ParseTerm returns exactly one term. +// If multiple terms are parsed, an error is returned. +func ParseTerm(input string) (*Term, error) { + body, err := ParseBody(input) + if err != nil { + return nil, fmt.Errorf("failed to parse term: %w", err) + } + if len(body) != 1 { + return nil, fmt.Errorf("expected exactly one term but got: %v", body) + } + term, ok := body[0].Terms.(*Term) + if !ok { + return nil, fmt.Errorf("expected term but got %v", body[0].Terms) + } + return term, nil +} + +// ParseRef returns exactly one reference. +func ParseRef(input string) (Ref, error) { + term, err := ParseTerm(input) + if err != nil { + return nil, fmt.Errorf("failed to parse ref: %w", err) + } + ref, ok := term.Value.(Ref) + if !ok { + return nil, fmt.Errorf("expected ref but got %v", term) + } + return ref, nil +} + +// ParseRuleWithOpts returns exactly one rule. +// If multiple rules are parsed, an error is returned. +func ParseRuleWithOpts(input string, opts ParserOptions) (*Rule, error) { + return v1.ParseRuleWithOpts(input, setDefaultRegoVersion(opts)) +} + +// ParseRule returns exactly one rule. +// If multiple rules are parsed, an error is returned. +func ParseRule(input string) (*Rule, error) { + return ParseRuleWithOpts(input, ParserOptions{}) +} + +// ParseStatement returns exactly one statement. +// A statement might be a term, expression, rule, etc. Regardless, +// this function expects *exactly* one statement. If multiple +// statements are parsed, an error is returned. +func ParseStatement(input string) (Statement, error) { + stmts, _, err := ParseStatements("", input) + if err != nil { + return nil, err + } + if len(stmts) != 1 { + return nil, fmt.Errorf("expected exactly one statement") + } + return stmts[0], nil +} + +func ParseStatementWithOpts(input string, popts ParserOptions) (Statement, error) { + return v1.ParseStatementWithOpts(input, setDefaultRegoVersion(popts)) +} + +// ParseStatements is deprecated. Use ParseStatementWithOpts instead. +func ParseStatements(filename, input string) ([]Statement, []*Comment, error) { + return ParseStatementsWithOpts(filename, input, ParserOptions{}) +} + +// ParseStatementsWithOpts returns a slice of parsed statements. This is the +// default return value from the parser. +func ParseStatementsWithOpts(filename, input string, popts ParserOptions) ([]Statement, []*Comment, error) { + return v1.ParseStatementsWithOpts(filename, input, setDefaultRegoVersion(popts)) +} + +// ParserErrorDetail holds additional details for parser errors. +type ParserErrorDetail = v1.ParserErrorDetail + +func setDefaultRegoVersion(opts ParserOptions) ParserOptions { + if opts.RegoVersion == RegoUndefined { + opts.RegoVersion = DefaultRegoVersion + } + return opts +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/policy.go b/vendor/github.com/open-policy-agent/opa/ast/policy.go new file mode 100644 index 00000000000..a29f0dcc75b --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/policy.go @@ -0,0 +1,235 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + astJSON "github.com/open-policy-agent/opa/ast/json" + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// DefaultRootDocument is the default root document. +// +// All package directives inside source files are implicitly prefixed with the +// DefaultRootDocument value. +var DefaultRootDocument = v1.DefaultRootDocument + +// InputRootDocument names the document containing query arguments. +var InputRootDocument = v1.InputRootDocument + +// SchemaRootDocument names the document containing external data schemas. +var SchemaRootDocument = v1.SchemaRootDocument + +// FunctionArgRootDocument names the document containing function arguments. +// It's only for internal usage, for referencing function arguments between +// the index and topdown. +var FunctionArgRootDocument = v1.FunctionArgRootDocument + +// FutureRootDocument names the document containing new, to-become-default, +// features. +var FutureRootDocument = v1.FutureRootDocument + +// RegoRootDocument names the document containing new, to-become-default, +// features in a future versioned release. +var RegoRootDocument = v1.RegoRootDocument + +// RootDocumentNames contains the names of top-level documents that can be +// referred to in modules and queries. +// +// Note, the schema document is not currently implemented in the evaluator so it +// is not registered as a root document name (yet). +var RootDocumentNames = v1.RootDocumentNames + +// DefaultRootRef is a reference to the root of the default document. +// +// All refs to data in the policy engine's storage layer are prefixed with this ref. +var DefaultRootRef = v1.DefaultRootRef + +// InputRootRef is a reference to the root of the input document. +// +// All refs to query arguments are prefixed with this ref. +var InputRootRef = v1.InputRootRef + +// SchemaRootRef is a reference to the root of the schema document. +// +// All refs to schema documents are prefixed with this ref. Note, the schema +// document is not currently implemented in the evaluator so it is not +// registered as a root document ref (yet). +var SchemaRootRef = v1.SchemaRootRef + +// RootDocumentRefs contains the prefixes of top-level documents that all +// non-local references start with. +var RootDocumentRefs = v1.RootDocumentRefs + +// SystemDocumentKey is the name of the top-level key that identifies the system +// document. +const SystemDocumentKey = v1.SystemDocumentKey + +// ReservedVars is the set of names that refer to implicitly ground vars. +var ReservedVars = v1.ReservedVars + +// Wildcard represents the wildcard variable as defined in the language. +var Wildcard = v1.Wildcard + +// WildcardPrefix is the special character that all wildcard variables are +// prefixed with when the statement they are contained in is parsed. +const WildcardPrefix = v1.WildcardPrefix + +// Keywords contains strings that map to language keywords. +var Keywords = v1.Keywords + +var KeywordsV0 = v1.KeywordsV0 + +var KeywordsV1 = v1.KeywordsV1 + +func KeywordsForRegoVersion(v RegoVersion) []string { + return v1.KeywordsForRegoVersion(v) +} + +// IsKeyword returns true if s is a language keyword. +func IsKeyword(s string) bool { + return v1.IsKeyword(s) +} + +func IsInKeywords(s string, keywords []string) bool { + return v1.IsInKeywords(s, keywords) +} + +// IsKeywordInRegoVersion returns true if s is a language keyword. +func IsKeywordInRegoVersion(s string, regoVersion RegoVersion) bool { + return v1.IsKeywordInRegoVersion(s, regoVersion) +} + +type ( + // Node represents a node in an AST. Nodes may be statements in a policy module + // or elements of an ad-hoc query, expression, etc. + Node = v1.Node + + // Statement represents a single statement in a policy module. + Statement = v1.Statement +) + +type ( + + // Module represents a collection of policies (defined by rules) + // within a namespace (defined by the package) and optional + // dependencies on external documents (defined by imports). + Module = v1.Module + + // Comment contains the raw text from the comment in the definition. + Comment = v1.Comment + + // Package represents the namespace of the documents produced + // by rules inside the module. + Package = v1.Package + + // Import represents a dependency on a document outside of the policy + // namespace. Imports are optional. + Import = v1.Import + + // Rule represents a rule as defined in the language. Rules define the + // content of documents that represent policy decisions. + Rule = v1.Rule + + // Head represents the head of a rule. + Head = v1.Head + + // Args represents zero or more arguments to a rule. + Args = v1.Args + + // Body represents one or more expressions contained inside a rule or user + // function. + Body = v1.Body + + // Expr represents a single expression contained inside the body of a rule. + Expr = v1.Expr + + // SomeDecl represents a variable declaration statement. The symbols are variables. + SomeDecl = v1.SomeDecl + + Every = v1.Every + + // With represents a modifier on an expression. + With = v1.With +) + +// NewComment returns a new Comment object. +func NewComment(text []byte) *Comment { + return v1.NewComment(text) +} + +// IsValidImportPath returns an error indicating if the import path is invalid. +// If the import path is valid, err is nil. +func IsValidImportPath(v Value) (err error) { + return v1.IsValidImportPath(v) +} + +// NewHead returns a new Head object. If args are provided, the first will be +// used for the key and the second will be used for the value. +func NewHead(name Var, args ...*Term) *Head { + return v1.NewHead(name, args...) +} + +// VarHead creates a head object, initializes its Name, Location, and Options, +// and returns the new head. +func VarHead(name Var, location *Location, jsonOpts *astJSON.Options) *Head { + return v1.VarHead(name, location, jsonOpts) +} + +// RefHead returns a new Head object with the passed Ref. If args are provided, +// the first will be used for the value. +func RefHead(ref Ref, args ...*Term) *Head { + return v1.RefHead(ref, args...) +} + +// DocKind represents the collection of document types that can be produced by rules. +type DocKind int + +const ( + // CompleteDoc represents a document that is completely defined by the rule. + CompleteDoc = v1.CompleteDoc + + // PartialSetDoc represents a set document that is partially defined by the rule. + PartialSetDoc = v1.PartialSetDoc + + // PartialObjectDoc represents an object document that is partially defined by the rule. + PartialObjectDoc = v1.PartialObjectDoc +) + +type RuleKind = v1.RuleKind + +const ( + SingleValue = v1.SingleValue + MultiValue = v1.MultiValue +) + +// NewBody returns a new Body containing the given expressions. The indices of +// the immediate expressions will be reset. +func NewBody(exprs ...*Expr) Body { + return v1.NewBody(exprs...) +} + +// NewExpr returns a new Expr object. +func NewExpr(terms interface{}) *Expr { + return v1.NewExpr(terms) +} + +// NewBuiltinExpr creates a new Expr object with the supplied terms. +// The builtin operator must be the first term. +func NewBuiltinExpr(terms ...*Term) *Expr { + return v1.NewBuiltinExpr(terms...) +} + +// Copy returns a deep copy of the AST node x. If x is not an AST node, x is returned unmodified. +func Copy(x interface{}) interface{} { + return v1.Copy(x) +} + +// RuleSet represents a collection of rules that produce a virtual document. +type RuleSet = v1.RuleSet + +// NewRuleSet returns a new RuleSet containing the given rules. +func NewRuleSet(rules ...*Rule) RuleSet { + return v1.NewRuleSet(rules...) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/pretty.go b/vendor/github.com/open-policy-agent/opa/ast/pretty.go new file mode 100644 index 00000000000..f2b8104e0a7 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/pretty.go @@ -0,0 +1,18 @@ +// Copyright 2018 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + "io" + + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// Pretty writes a pretty representation of the AST rooted at x to w. +// +// This is function is intended for debug purposes when inspecting ASTs. +func Pretty(w io.Writer, x interface{}) { + v1.Pretty(w, x) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/schema.go b/vendor/github.com/open-policy-agent/opa/ast/schema.go new file mode 100644 index 00000000000..979958a3c00 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/schema.go @@ -0,0 +1,17 @@ +// Copyright 2021 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// SchemaSet holds a map from a path to a schema. +type SchemaSet = v1.SchemaSet + +// NewSchemaSet returns an empty SchemaSet. +func NewSchemaSet() *SchemaSet { + return v1.NewSchemaSet() +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/strings.go b/vendor/github.com/open-policy-agent/opa/ast/strings.go new file mode 100644 index 00000000000..ef9354bf78b --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/strings.go @@ -0,0 +1,14 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// TypeName returns a human readable name for the AST element type. +func TypeName(x interface{}) string { + return v1.TypeName(x) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/term.go b/vendor/github.com/open-policy-agent/opa/ast/term.go new file mode 100644 index 00000000000..a5d146ea27c --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/term.go @@ -0,0 +1,306 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + "encoding/json" + "io" + + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// Location records a position in source code. +type Location = v1.Location + +// NewLocation returns a new Location object. +func NewLocation(text []byte, file string, row int, col int) *Location { + return v1.NewLocation(text, file, row, col) +} + +// Value declares the common interface for all Term values. Every kind of Term value +// in the language is represented as a type that implements this interface: +// +// - Null, Boolean, Number, String +// - Object, Array, Set +// - Variables, References +// - Array, Set, and Object Comprehensions +// - Calls +type Value = v1.Value + +// InterfaceToValue converts a native Go value x to a Value. +func InterfaceToValue(x interface{}) (Value, error) { + return v1.InterfaceToValue(x) +} + +// ValueFromReader returns an AST value from a JSON serialized value in the reader. +func ValueFromReader(r io.Reader) (Value, error) { + return v1.ValueFromReader(r) +} + +// As converts v into a Go native type referred to by x. +func As(v Value, x interface{}) error { + return v1.As(v, x) +} + +// Resolver defines the interface for resolving references to native Go values. +type Resolver = v1.Resolver + +// ValueResolver defines the interface for resolving references to AST values. +type ValueResolver = v1.ValueResolver + +// UnknownValueErr indicates a ValueResolver was unable to resolve a reference +// because the reference refers to an unknown value. +type UnknownValueErr = v1.UnknownValueErr + +// IsUnknownValueErr returns true if the err is an UnknownValueErr. +func IsUnknownValueErr(err error) bool { + return v1.IsUnknownValueErr(err) +} + +// ValueToInterface returns the Go representation of an AST value. The AST +// value should not contain any values that require evaluation (e.g., vars, +// comprehensions, etc.) +func ValueToInterface(v Value, resolver Resolver) (interface{}, error) { + return v1.ValueToInterface(v, resolver) +} + +// JSON returns the JSON representation of v. The value must not contain any +// refs or terms that require evaluation (e.g., vars, comprehensions, etc.) +func JSON(v Value) (interface{}, error) { + return v1.JSON(v) +} + +// JSONOpt defines parameters for AST to JSON conversion. +type JSONOpt = v1.JSONOpt + +// JSONWithOpt returns the JSON representation of v. The value must not contain any +// refs or terms that require evaluation (e.g., vars, comprehensions, etc.) +func JSONWithOpt(v Value, opt JSONOpt) (interface{}, error) { + return v1.JSONWithOpt(v, opt) +} + +// MustJSON returns the JSON representation of v. The value must not contain any +// refs or terms that require evaluation (e.g., vars, comprehensions, etc.) If +// the conversion fails, this function will panic. This function is mostly for +// test purposes. +func MustJSON(v Value) interface{} { + return v1.MustJSON(v) +} + +// MustInterfaceToValue converts a native Go value x to a Value. If the +// conversion fails, this function will panic. This function is mostly for test +// purposes. +func MustInterfaceToValue(x interface{}) Value { + return v1.MustInterfaceToValue(x) +} + +// Term is an argument to a function. +type Term = v1.Term + +// NewTerm returns a new Term object. +func NewTerm(v Value) *Term { + return v1.NewTerm(v) +} + +// IsConstant returns true if the AST value is constant. +func IsConstant(v Value) bool { + return v1.IsConstant(v) +} + +// IsComprehension returns true if the supplied value is a comprehension. +func IsComprehension(x Value) bool { + return v1.IsComprehension(x) +} + +// ContainsRefs returns true if the Value v contains refs. +func ContainsRefs(v interface{}) bool { + return v1.ContainsRefs(v) +} + +// ContainsComprehensions returns true if the Value v contains comprehensions. +func ContainsComprehensions(v interface{}) bool { + return v1.ContainsComprehensions(v) +} + +// ContainsClosures returns true if the Value v contains closures. +func ContainsClosures(v interface{}) bool { + return v1.ContainsClosures(v) +} + +// IsScalar returns true if the AST value is a scalar. +func IsScalar(v Value) bool { + return v1.IsScalar(v) +} + +// Null represents the null value defined by JSON. +type Null = v1.Null + +// NullTerm creates a new Term with a Null value. +func NullTerm() *Term { + return v1.NullTerm() +} + +// Boolean represents a boolean value defined by JSON. +type Boolean = v1.Boolean + +// BooleanTerm creates a new Term with a Boolean value. +func BooleanTerm(b bool) *Term { + return v1.BooleanTerm(b) +} + +// Number represents a numeric value as defined by JSON. +type Number = v1.Number + +// NumberTerm creates a new Term with a Number value. +func NumberTerm(n json.Number) *Term { + return v1.NumberTerm(n) +} + +// IntNumberTerm creates a new Term with an integer Number value. +func IntNumberTerm(i int) *Term { + return v1.IntNumberTerm(i) +} + +// UIntNumberTerm creates a new Term with an unsigned integer Number value. +func UIntNumberTerm(u uint64) *Term { + return v1.UIntNumberTerm(u) +} + +// FloatNumberTerm creates a new Term with a floating point Number value. +func FloatNumberTerm(f float64) *Term { + return v1.FloatNumberTerm(f) +} + +// String represents a string value as defined by JSON. +type String = v1.String + +// StringTerm creates a new Term with a String value. +func StringTerm(s string) *Term { + return v1.StringTerm(s) +} + +// Var represents a variable as defined by the language. +type Var = v1.Var + +// VarTerm creates a new Term with a Variable value. +func VarTerm(v string) *Term { + return v1.VarTerm(v) +} + +// Ref represents a reference as defined by the language. +type Ref = v1.Ref + +// EmptyRef returns a new, empty reference. +func EmptyRef() Ref { + return v1.EmptyRef() +} + +// PtrRef returns a new reference against the head for the pointer +// s. Path components in the pointer are unescaped. +func PtrRef(head *Term, s string) (Ref, error) { + return v1.PtrRef(head, s) +} + +// RefTerm creates a new Term with a Ref value. +func RefTerm(r ...*Term) *Term { + return v1.RefTerm(r...) +} + +func IsVarCompatibleString(s string) bool { + return v1.IsVarCompatibleString(s) +} + +// QueryIterator defines the interface for querying AST documents with references. +type QueryIterator = v1.QueryIterator + +// ArrayTerm creates a new Term with an Array value. +func ArrayTerm(a ...*Term) *Term { + return v1.ArrayTerm(a...) +} + +// NewArray creates an Array with the terms provided. The array will +// use the provided term slice. +func NewArray(a ...*Term) *Array { + return v1.NewArray(a...) +} + +// Array represents an array as defined by the language. Arrays are similar to the +// same types as defined by JSON with the exception that they can contain Vars +// and References. +type Array = v1.Array + +// Set represents a set as defined by the language. +type Set = v1.Set + +// NewSet returns a new Set containing t. +func NewSet(t ...*Term) Set { + return v1.NewSet(t...) +} + +func SetTerm(t ...*Term) *Term { + return v1.SetTerm(t...) +} + +// Object represents an object as defined by the language. +type Object = v1.Object + +// NewObject creates a new Object with t. +func NewObject(t ...[2]*Term) Object { + return v1.NewObject(t...) +} + +// ObjectTerm creates a new Term with an Object value. +func ObjectTerm(o ...[2]*Term) *Term { + return v1.ObjectTerm(o...) +} + +func LazyObject(blob map[string]interface{}) Object { + return v1.LazyObject(blob) +} + +// Item is a helper for constructing an tuple containing two Terms +// representing a key/value pair in an Object. +func Item(key, value *Term) [2]*Term { + return v1.Item(key, value) +} + +// NOTE(philipc): The only way to get an ObjectKeyIterator should be +// from an Object. This ensures that the iterator can have implementation- +// specific details internally, with no contracts except to the very +// limited interface. +type ObjectKeysIterator = v1.ObjectKeysIterator + +// ArrayComprehension represents an array comprehension as defined in the language. +type ArrayComprehension = v1.ArrayComprehension + +// ArrayComprehensionTerm creates a new Term with an ArrayComprehension value. +func ArrayComprehensionTerm(term *Term, body Body) *Term { + return v1.ArrayComprehensionTerm(term, body) +} + +// ObjectComprehension represents an object comprehension as defined in the language. +type ObjectComprehension = v1.ObjectComprehension + +// ObjectComprehensionTerm creates a new Term with an ObjectComprehension value. +func ObjectComprehensionTerm(key, value *Term, body Body) *Term { + return v1.ObjectComprehensionTerm(key, value, body) +} + +// SetComprehension represents a set comprehension as defined in the language. +type SetComprehension = v1.SetComprehension + +// SetComprehensionTerm creates a new Term with an SetComprehension value. +func SetComprehensionTerm(term *Term, body Body) *Term { + return v1.SetComprehensionTerm(term, body) +} + +// Call represents as function call in the language. +type Call = v1.Call + +// CallTerm returns a new Term with a Call value defined by terms. The first +// term is the operator and the rest are operands. +func CallTerm(terms ...*Term) *Term { + return v1.CallTerm(terms...) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/transform.go b/vendor/github.com/open-policy-agent/opa/ast/transform.go new file mode 100644 index 00000000000..cfb137813f0 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/transform.go @@ -0,0 +1,46 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// Transformer defines the interface for transforming AST elements. If the +// transformer returns nil and does not indicate an error, the AST element will +// be set to nil and no transformations will be applied to children of the +// element. +type Transformer = v1.Transformer + +// Transform iterates the AST and calls the Transform function on the +// Transformer t for x before recursing. +func Transform(t Transformer, x interface{}) (interface{}, error) { + return v1.Transform(t, x) +} + +// TransformRefs calls the function f on all references under x. +func TransformRefs(x interface{}, f func(Ref) (Value, error)) (interface{}, error) { + return v1.TransformRefs(x, f) +} + +// TransformVars calls the function f on all vars under x. +func TransformVars(x interface{}, f func(Var) (Value, error)) (interface{}, error) { + return v1.TransformVars(x, f) +} + +// TransformComprehensions calls the functio nf on all comprehensions under x. +func TransformComprehensions(x interface{}, f func(interface{}) (Value, error)) (interface{}, error) { + return v1.TransformComprehensions(x, f) +} + +// GenericTransformer implements the Transformer interface to provide a utility +// to transform AST nodes using a closure. +type GenericTransformer = v1.GenericTransformer + +// NewGenericTransformer returns a new GenericTransformer that will transform +// AST nodes using the function f. +func NewGenericTransformer(f func(x interface{}) (interface{}, error)) *GenericTransformer { + return v1.NewGenericTransformer(f) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/unify.go b/vendor/github.com/open-policy-agent/opa/ast/unify.go new file mode 100644 index 00000000000..3cb260272aa --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/unify.go @@ -0,0 +1,14 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import v1 "github.com/open-policy-agent/opa/v1/ast" + +// Unify returns a set of variables that will be unified when the equality expression defined by +// terms a and b is evaluated. The unifier assumes that variables in the VarSet safe are already +// unified. +func Unify(safe VarSet, a *Term, b *Term) VarSet { + return v1.Unify(safe, a, b) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/varset.go b/vendor/github.com/open-policy-agent/opa/ast/varset.go new file mode 100644 index 00000000000..9e7db8efdad --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/varset.go @@ -0,0 +1,17 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import ( + v1 "github.com/open-policy-agent/opa/v1/ast" +) + +// VarSet represents a set of variables. +type VarSet = v1.VarSet + +// NewVarSet returns a new VarSet containing the specified variables. +func NewVarSet(vs ...Var) VarSet { + return v1.NewVarSet(vs...) +} diff --git a/vendor/github.com/open-policy-agent/opa/ast/visit.go b/vendor/github.com/open-policy-agent/opa/ast/visit.go new file mode 100644 index 00000000000..94823c6cc77 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/ast/visit.go @@ -0,0 +1,123 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package ast + +import v1 "github.com/open-policy-agent/opa/v1/ast" + +// Visitor defines the interface for iterating AST elements. The Visit function +// can return a Visitor w which will be used to visit the children of the AST +// element v. If the Visit function returns nil, the children will not be +// visited. +// Deprecated: use GenericVisitor or another visitor implementation +type Visitor = v1.Visitor + +// BeforeAndAfterVisitor wraps Visitor to provide hooks for being called before +// and after the AST has been visited. +// Deprecated: use GenericVisitor or another visitor implementation +type BeforeAndAfterVisitor = v1.BeforeAndAfterVisitor + +// Walk iterates the AST by calling the Visit function on the Visitor +// v for x before recursing. +// Deprecated: use GenericVisitor.Walk +func Walk(v Visitor, x interface{}) { + v1.Walk(v, x) +} + +// WalkBeforeAndAfter iterates the AST by calling the Visit function on the +// Visitor v for x before recursing. +// Deprecated: use GenericVisitor.Walk +func WalkBeforeAndAfter(v BeforeAndAfterVisitor, x interface{}) { + v1.WalkBeforeAndAfter(v, x) +} + +// WalkVars calls the function f on all vars under x. If the function f +// returns true, AST nodes under the last node will not be visited. +func WalkVars(x interface{}, f func(Var) bool) { + v1.WalkVars(x, f) +} + +// WalkClosures calls the function f on all closures under x. If the function f +// returns true, AST nodes under the last node will not be visited. +func WalkClosures(x interface{}, f func(interface{}) bool) { + v1.WalkClosures(x, f) +} + +// WalkRefs calls the function f on all references under x. If the function f +// returns true, AST nodes under the last node will not be visited. +func WalkRefs(x interface{}, f func(Ref) bool) { + v1.WalkRefs(x, f) +} + +// WalkTerms calls the function f on all terms under x. If the function f +// returns true, AST nodes under the last node will not be visited. +func WalkTerms(x interface{}, f func(*Term) bool) { + v1.WalkTerms(x, f) +} + +// WalkWiths calls the function f on all with modifiers under x. If the function f +// returns true, AST nodes under the last node will not be visited. +func WalkWiths(x interface{}, f func(*With) bool) { + v1.WalkWiths(x, f) +} + +// WalkExprs calls the function f on all expressions under x. If the function f +// returns true, AST nodes under the last node will not be visited. +func WalkExprs(x interface{}, f func(*Expr) bool) { + v1.WalkExprs(x, f) +} + +// WalkBodies calls the function f on all bodies under x. If the function f +// returns true, AST nodes under the last node will not be visited. +func WalkBodies(x interface{}, f func(Body) bool) { + v1.WalkBodies(x, f) +} + +// WalkRules calls the function f on all rules under x. If the function f +// returns true, AST nodes under the last node will not be visited. +func WalkRules(x interface{}, f func(*Rule) bool) { + v1.WalkRules(x, f) +} + +// WalkNodes calls the function f on all nodes under x. If the function f +// returns true, AST nodes under the last node will not be visited. +func WalkNodes(x interface{}, f func(Node) bool) { + v1.WalkNodes(x, f) +} + +// GenericVisitor provides a utility to walk over AST nodes using a +// closure. If the closure returns true, the visitor will not walk +// over AST nodes under x. +type GenericVisitor = v1.GenericVisitor + +// NewGenericVisitor returns a new GenericVisitor that will invoke the function +// f on AST nodes. +func NewGenericVisitor(f func(x interface{}) bool) *GenericVisitor { + return v1.NewGenericVisitor(f) +} + +// BeforeAfterVisitor provides a utility to walk over AST nodes using +// closures. If the before closure returns true, the visitor will not +// walk over AST nodes under x. The after closure is invoked always +// after visiting a node. +type BeforeAfterVisitor = v1.BeforeAfterVisitor + +// NewBeforeAfterVisitor returns a new BeforeAndAfterVisitor that +// will invoke the functions before and after AST nodes. +func NewBeforeAfterVisitor(before func(x interface{}) bool, after func(x interface{})) *BeforeAfterVisitor { + return v1.NewBeforeAfterVisitor(before, after) +} + +// VarVisitor walks AST nodes under a given node and collects all encountered +// variables. The collected variables can be controlled by specifying +// VarVisitorParams when creating the visitor. +type VarVisitor = v1.VarVisitor + +// VarVisitorParams contains settings for a VarVisitor. +type VarVisitorParams = v1.VarVisitorParams + +// NewVarVisitor returns a new VarVisitor object. +func NewVarVisitor() *VarVisitor { + return v1.NewVarVisitor() +} diff --git a/vendor/github.com/open-policy-agent/opa/bundle/bundle.go b/vendor/github.com/open-policy-agent/opa/bundle/bundle.go new file mode 100644 index 00000000000..50ad97349a0 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/bundle/bundle.go @@ -0,0 +1,134 @@ +// Copyright 2018 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package bundle implements bundle loading. +package bundle + +import ( + "io" + + "github.com/open-policy-agent/opa/ast" + v1 "github.com/open-policy-agent/opa/v1/bundle" +) + +// Common file extensions and file names. +const ( + RegoExt = v1.RegoExt + WasmFile = v1.WasmFile + PlanFile = v1.PlanFile + ManifestExt = v1.ManifestExt + SignaturesFile = v1.SignaturesFile + + DefaultSizeLimitBytes = v1.DefaultSizeLimitBytes + DeltaBundleType = v1.DeltaBundleType + SnapshotBundleType = v1.SnapshotBundleType +) + +// Bundle represents a loaded bundle. The bundle can contain data and policies. +type Bundle = v1.Bundle + +// Raw contains raw bytes representing the bundle's content +type Raw = v1.Raw + +// Patch contains an array of objects wherein each object represents the patch operation to be +// applied to the bundle data. +type Patch = v1.Patch + +// PatchOperation models a single patch operation against a document. +type PatchOperation = v1.PatchOperation + +// SignaturesConfig represents an array of JWTs that encapsulate the signatures for the bundle. +type SignaturesConfig = v1.SignaturesConfig + +// DecodedSignature represents the decoded JWT payload. +type DecodedSignature = v1.DecodedSignature + +// FileInfo contains the hashing algorithm used, resulting digest etc. +type FileInfo = v1.FileInfo + +// NewFile returns a new FileInfo. +func NewFile(name, hash, alg string) FileInfo { + return v1.NewFile(name, hash, alg) +} + +// Manifest represents the manifest from a bundle. The manifest may contain +// metadata such as the bundle revision. +type Manifest = v1.Manifest + +// WasmResolver maps a wasm module to an entrypoint ref. +type WasmResolver = v1.WasmResolver + +// ModuleFile represents a single module contained in a bundle. +type ModuleFile = v1.ModuleFile + +// WasmModuleFile represents a single wasm module contained in a bundle. +type WasmModuleFile = v1.WasmModuleFile + +// PlanModuleFile represents a single plan module contained in a bundle. +// +// NOTE(tsandall): currently the plans are just opaque binary blobs. In the +// future we could inject the entrypoints so that the plans could be executed +// inside of OPA proper like we do for Wasm modules. +type PlanModuleFile = v1.PlanModuleFile + +// Reader contains the reader to load the bundle from. +type Reader = v1.Reader + +// NewReader is deprecated. Use NewCustomReader instead. +func NewReader(r io.Reader) *Reader { + return v1.NewReader(r).WithRegoVersion(ast.DefaultRegoVersion) +} + +// NewCustomReader returns a new Reader configured to use the +// specified DirectoryLoader. +func NewCustomReader(loader DirectoryLoader) *Reader { + return v1.NewCustomReader(loader).WithRegoVersion(ast.DefaultRegoVersion) +} + +// Write is deprecated. Use NewWriter instead. +func Write(w io.Writer, bundle Bundle) error { + return v1.Write(w, bundle) +} + +// Writer implements bundle serialization. +type Writer = v1.Writer + +// NewWriter returns a bundle writer that writes to w. +func NewWriter(w io.Writer) *Writer { + return v1.NewWriter(w) +} + +// Merge accepts a set of bundles and merges them into a single result bundle. If there are +// any conflicts during the merge (e.g., with roots) an error is returned. The result bundle +// will have an empty revision except in the special case where a single bundle is provided +// (and in that case the bundle is just returned unmodified.) +func Merge(bundles []*Bundle) (*Bundle, error) { + return MergeWithRegoVersion(bundles, ast.DefaultRegoVersion, false) +} + +// MergeWithRegoVersion creates a merged bundle from the provided bundles, similar to Merge. +// If more than one bundle is provided, the rego version of the result bundle is set to the provided regoVersion. +// Any Rego files in a bundle of conflicting rego version will be marked in the result's manifest with the rego version +// of its original bundle. If the Rego file already had an overriding rego version, it will be preserved. +// If a single bundle is provided, it will retain any rego version information it already had. If it has none, the +// provided regoVersion will be applied to it. +// If usePath is true, per-file rego-versions will be calculated using the file's ModuleFile.Path; otherwise, the file's +// ModuleFile.URL will be used. +func MergeWithRegoVersion(bundles []*Bundle, regoVersion ast.RegoVersion, usePath bool) (*Bundle, error) { + if regoVersion == ast.RegoUndefined { + regoVersion = ast.DefaultRegoVersion + } + + return v1.MergeWithRegoVersion(bundles, regoVersion, usePath) +} + +// RootPathsOverlap takes in two bundle root paths and returns true if they overlap. +func RootPathsOverlap(pathA string, pathB string) bool { + return v1.RootPathsOverlap(pathA, pathB) +} + +// RootPathsContain takes a set of bundle root paths and returns true if the path is contained. +func RootPathsContain(roots []string, path string) bool { + return v1.RootPathsContain(roots, path) +} diff --git a/vendor/github.com/open-policy-agent/opa/bundle/doc.go b/vendor/github.com/open-policy-agent/opa/bundle/doc.go new file mode 100644 index 00000000000..7ec7c9b3328 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/bundle/doc.go @@ -0,0 +1,8 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package bundle diff --git a/vendor/github.com/open-policy-agent/opa/bundle/file.go b/vendor/github.com/open-policy-agent/opa/bundle/file.go new file mode 100644 index 00000000000..ccb7b235109 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/bundle/file.go @@ -0,0 +1,50 @@ +package bundle + +import ( + "io" + + "github.com/open-policy-agent/opa/storage" + v1 "github.com/open-policy-agent/opa/v1/bundle" +) + +// Descriptor contains information about a file and +// can be used to read the file contents. +type Descriptor = v1.Descriptor + +func NewDescriptor(url, path string, reader io.Reader) *Descriptor { + return v1.NewDescriptor(url, path, reader) +} + +type PathFormat = v1.PathFormat + +const ( + Chrooted = v1.Chrooted + SlashRooted = v1.SlashRooted + Passthrough = v1.Passthrough +) + +// DirectoryLoader defines an interface which can be used to load +// files from a directory by iterating over each one in the tree. +type DirectoryLoader = v1.DirectoryLoader + +// NewDirectoryLoader returns a basic DirectoryLoader implementation +// that will load files from a given root directory path. +func NewDirectoryLoader(root string) DirectoryLoader { + return v1.NewDirectoryLoader(root) +} + +// NewTarballLoader is deprecated. Use NewTarballLoaderWithBaseURL instead. +func NewTarballLoader(r io.Reader) DirectoryLoader { + return v1.NewTarballLoader(r) +} + +// NewTarballLoaderWithBaseURL returns a new DirectoryLoader that reads +// files out of a gzipped tar archive. The file URLs will be prefixed +// with the baseURL. +func NewTarballLoaderWithBaseURL(r io.Reader, baseURL string) DirectoryLoader { + return v1.NewTarballLoaderWithBaseURL(r, baseURL) +} + +func NewIterator(raw []Raw) storage.Iterator { + return v1.NewIterator(raw) +} diff --git a/vendor/github.com/open-policy-agent/opa/bundle/filefs.go b/vendor/github.com/open-policy-agent/opa/bundle/filefs.go new file mode 100644 index 00000000000..16e00928dad --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/bundle/filefs.go @@ -0,0 +1,22 @@ +//go:build go1.16 +// +build go1.16 + +package bundle + +import ( + "io/fs" + + v1 "github.com/open-policy-agent/opa/v1/bundle" +) + +// NewFSLoader returns a basic DirectoryLoader implementation +// that will load files from a fs.FS interface +func NewFSLoader(filesystem fs.FS) (DirectoryLoader, error) { + return v1.NewFSLoader(filesystem) +} + +// NewFSLoaderWithRoot returns a basic DirectoryLoader implementation +// that will load files from a fs.FS interface at the supplied root +func NewFSLoaderWithRoot(filesystem fs.FS, root string) DirectoryLoader { + return v1.NewFSLoaderWithRoot(filesystem, root) +} diff --git a/vendor/github.com/open-policy-agent/opa/bundle/hash.go b/vendor/github.com/open-policy-agent/opa/bundle/hash.go new file mode 100644 index 00000000000..d4cc601dead --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/bundle/hash.go @@ -0,0 +1,32 @@ +// Copyright 2020 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package bundle + +import ( + v1 "github.com/open-policy-agent/opa/v1/bundle" +) + +// HashingAlgorithm represents a subset of hashing algorithms implemented in Go +type HashingAlgorithm = v1.HashingAlgorithm + +// Supported values for HashingAlgorithm +const ( + MD5 = v1.MD5 + SHA1 = v1.SHA1 + SHA224 = v1.SHA224 + SHA256 = v1.SHA256 + SHA384 = v1.SHA384 + SHA512 = v1.SHA512 + SHA512224 = v1.SHA512224 + SHA512256 = v1.SHA512256 +) + +// SignatureHasher computes a signature digest for a file with (structured or unstructured) data and policy +type SignatureHasher = v1.SignatureHasher + +// NewSignatureHasher returns a signature hasher suitable for a particular hashing algorithm +func NewSignatureHasher(alg HashingAlgorithm) (SignatureHasher, error) { + return v1.NewSignatureHasher(alg) +} diff --git a/vendor/github.com/open-policy-agent/opa/bundle/keys.go b/vendor/github.com/open-policy-agent/opa/bundle/keys.go new file mode 100644 index 00000000000..99f9b0f165a --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/bundle/keys.go @@ -0,0 +1,30 @@ +// Copyright 2020 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package bundle provide helpers that assist in creating the verification and signing key configuration +package bundle + +import ( + v1 "github.com/open-policy-agent/opa/v1/bundle" +) + +// KeyConfig holds the keys used to sign or verify bundles and tokens +// Moved to own package, alias kept for backwards compatibility +type KeyConfig = v1.KeyConfig + +// VerificationConfig represents the key configuration used to verify a signed bundle +type VerificationConfig = v1.VerificationConfig + +// NewVerificationConfig return a new VerificationConfig +func NewVerificationConfig(keys map[string]*KeyConfig, id, scope string, exclude []string) *VerificationConfig { + return v1.NewVerificationConfig(keys, id, scope, exclude) +} + +// SigningConfig represents the key configuration used to generate a signed bundle +type SigningConfig = v1.SigningConfig + +// NewSigningConfig return a new SigningConfig +func NewSigningConfig(key, alg, claimsPath string) *SigningConfig { + return v1.NewSigningConfig(key, alg, claimsPath) +} diff --git a/vendor/github.com/open-policy-agent/opa/bundle/sign.go b/vendor/github.com/open-policy-agent/opa/bundle/sign.go new file mode 100644 index 00000000000..56e25eec9c1 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/bundle/sign.go @@ -0,0 +1,35 @@ +// Copyright 2020 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package bundle provide helpers that assist in the creating a signed bundle +package bundle + +import ( + v1 "github.com/open-policy-agent/opa/v1/bundle" +) + +// Signer is the interface expected for implementations that generate bundle signatures. +type Signer v1.Signer + +// GenerateSignedToken will retrieve the Signer implementation based on the Plugin specified +// in SigningConfig, and call its implementation of GenerateSignedToken. The signer generates +// a signed token given the list of files to be included in the payload and the bundle +// signing config. The keyID if non-empty, represents the value for the "keyid" claim in the token. +func GenerateSignedToken(files []FileInfo, sc *SigningConfig, keyID string) (string, error) { + return v1.GenerateSignedToken(files, sc, keyID) +} + +// DefaultSigner is the default bundle signing implementation. It signs bundles by generating +// a JWT and signing it using a locally-accessible private key. +type DefaultSigner v1.DefaultSigner + +// GetSigner returns the Signer registered under the given id +func GetSigner(id string) (Signer, error) { + return v1.GetSigner(id) +} + +// RegisterSigner registers a Signer under the given id +func RegisterSigner(id string, s Signer) error { + return v1.RegisterSigner(id, s) +} diff --git a/vendor/github.com/open-policy-agent/opa/bundle/store.go b/vendor/github.com/open-policy-agent/opa/bundle/store.go new file mode 100644 index 00000000000..d73cc774225 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/bundle/store.go @@ -0,0 +1,123 @@ +// Copyright 2019 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package bundle + +import ( + "context" + + "github.com/open-policy-agent/opa/storage" + v1 "github.com/open-policy-agent/opa/v1/bundle" +) + +// BundlesBasePath is the storage path used for storing bundle metadata +var BundlesBasePath = v1.BundlesBasePath + +// Note: As needed these helpers could be memoized. + +// ManifestStoragePath is the storage path used for the given named bundle manifest. +func ManifestStoragePath(name string) storage.Path { + return v1.ManifestStoragePath(name) +} + +// EtagStoragePath is the storage path used for the given named bundle etag. +func EtagStoragePath(name string) storage.Path { + return v1.EtagStoragePath(name) +} + +// ReadBundleNamesFromStore will return a list of bundle names which have had their metadata stored. +func ReadBundleNamesFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) ([]string, error) { + return v1.ReadBundleNamesFromStore(ctx, store, txn) +} + +// WriteManifestToStore will write the manifest into the storage. This function is called when +// the bundle is activated. +func WriteManifestToStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string, manifest Manifest) error { + return v1.WriteManifestToStore(ctx, store, txn, name, manifest) +} + +// WriteEtagToStore will write the bundle etag into the storage. This function is called when the bundle is activated. +func WriteEtagToStore(ctx context.Context, store storage.Store, txn storage.Transaction, name, etag string) error { + return v1.WriteEtagToStore(ctx, store, txn, name, etag) +} + +// EraseManifestFromStore will remove the manifest from storage. This function is called +// when the bundle is deactivated. +func EraseManifestFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) error { + return v1.EraseManifestFromStore(ctx, store, txn, name) +} + +// ReadWasmModulesFromStore will write Wasm module resolver metadata from the store. +func ReadWasmModulesFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) (map[string][]byte, error) { + return v1.ReadWasmModulesFromStore(ctx, store, txn, name) +} + +// ReadBundleRootsFromStore returns the roots in the specified bundle. +// If the bundle is not activated, this function will return +// storage NotFound error. +func ReadBundleRootsFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) ([]string, error) { + return v1.ReadBundleRootsFromStore(ctx, store, txn, name) +} + +// ReadBundleRevisionFromStore returns the revision in the specified bundle. +// If the bundle is not activated, this function will return +// storage NotFound error. +func ReadBundleRevisionFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) (string, error) { + return v1.ReadBundleRevisionFromStore(ctx, store, txn, name) +} + +// ReadBundleMetadataFromStore returns the metadata in the specified bundle. +// If the bundle is not activated, this function will return +// storage NotFound error. +func ReadBundleMetadataFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) (map[string]interface{}, error) { + return v1.ReadBundleMetadataFromStore(ctx, store, txn, name) +} + +// ReadBundleEtagFromStore returns the etag for the specified bundle. +// If the bundle is not activated, this function will return +// storage NotFound error. +func ReadBundleEtagFromStore(ctx context.Context, store storage.Store, txn storage.Transaction, name string) (string, error) { + return v1.ReadBundleEtagFromStore(ctx, store, txn, name) +} + +// ActivateOpts defines options for the Activate API call. +type ActivateOpts = v1.ActivateOpts + +// Activate the bundle(s) by loading into the given Store. This will load policies, data, and record +// the manifest in storage. The compiler provided will have had the polices compiled on it. +func Activate(opts *ActivateOpts) error { + return v1.Activate(opts) +} + +// DeactivateOpts defines options for the Deactivate API call +type DeactivateOpts = v1.DeactivateOpts + +// Deactivate the bundle(s). This will erase associated data, policies, and the manifest entry from the store. +func Deactivate(opts *DeactivateOpts) error { + return v1.Deactivate(opts) +} + +// LegacyWriteManifestToStore will write the bundle manifest to the older single (unnamed) bundle manifest location. +// Deprecated: Use WriteManifestToStore and named bundles instead. +func LegacyWriteManifestToStore(ctx context.Context, store storage.Store, txn storage.Transaction, manifest Manifest) error { + return v1.LegacyWriteManifestToStore(ctx, store, txn, manifest) +} + +// LegacyEraseManifestFromStore will erase the bundle manifest from the older single (unnamed) bundle manifest location. +// Deprecated: Use WriteManifestToStore and named bundles instead. +func LegacyEraseManifestFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) error { + return v1.LegacyEraseManifestFromStore(ctx, store, txn) +} + +// LegacyReadRevisionFromStore will read the bundle manifest revision from the older single (unnamed) bundle manifest location. +// Deprecated: Use ReadBundleRevisionFromStore and named bundles instead. +func LegacyReadRevisionFromStore(ctx context.Context, store storage.Store, txn storage.Transaction) (string, error) { + return v1.LegacyReadRevisionFromStore(ctx, store, txn) +} + +// ActivateLegacy calls Activate for the bundles but will also write their manifest to the older unnamed store location. +// Deprecated: Use Activate with named bundles instead. +func ActivateLegacy(opts *ActivateOpts) error { + return v1.ActivateLegacy(opts) +} diff --git a/vendor/github.com/open-policy-agent/opa/bundle/verify.go b/vendor/github.com/open-policy-agent/opa/bundle/verify.go new file mode 100644 index 00000000000..ef2e1e32db0 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/bundle/verify.go @@ -0,0 +1,36 @@ +// Copyright 2020 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package bundle provide helpers that assist in the bundle signature verification process +package bundle + +import ( + v1 "github.com/open-policy-agent/opa/v1/bundle" +) + +// Verifier is the interface expected for implementations that verify bundle signatures. +type Verifier v1.Verifier + +// VerifyBundleSignature will retrieve the Verifier implementation based +// on the Plugin specified in SignaturesConfig, and call its implementation +// of VerifyBundleSignature. VerifyBundleSignature verifies the bundle signature +// using the given public keys or secret. If a signature is verified, it keeps +// track of the files specified in the JWT payload +func VerifyBundleSignature(sc SignaturesConfig, bvc *VerificationConfig) (map[string]FileInfo, error) { + return v1.VerifyBundleSignature(sc, bvc) +} + +// DefaultVerifier is the default bundle verification implementation. It verifies bundles by checking +// the JWT signature using a locally-accessible public key. +type DefaultVerifier = v1.DefaultVerifier + +// GetVerifier returns the Verifier registered under the given id +func GetVerifier(id string) (Verifier, error) { + return v1.GetVerifier(id) +} + +// RegisterVerifier registers a Verifier under the given id +func RegisterVerifier(id string, v Verifier) error { + return v1.RegisterVerifier(id, v) +} diff --git a/vendor/github.com/open-policy-agent/opa/format/doc.go b/vendor/github.com/open-policy-agent/opa/format/doc.go new file mode 100644 index 00000000000..ba514fffb94 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/format/doc.go @@ -0,0 +1,8 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package format diff --git a/vendor/github.com/open-policy-agent/opa/format/format.go b/vendor/github.com/open-policy-agent/opa/format/format.go new file mode 100644 index 00000000000..ad09cea843f --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/format/format.go @@ -0,0 +1,86 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package format implements formatting of Rego source files. +package format + +import ( + "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/types" + v1 "github.com/open-policy-agent/opa/v1/format" +) + +// Opts lets you control the code formatting via `AstWithOpts()`. +type Opts = v1.Opts + +// Source formats a Rego source file. The bytes provided must describe a complete +// Rego module. If they don't, Source will return an error resulting from the attempt +// to parse the bytes. +func Source(filename string, src []byte) ([]byte, error) { + return SourceWithOpts(filename, src, Opts{ + RegoVersion: ast.DefaultRegoVersion, + ParserOptions: &ast.ParserOptions{ + RegoVersion: ast.DefaultRegoVersion, + }, + }) +} + +func SourceWithOpts(filename string, src []byte, opts Opts) ([]byte, error) { + if opts.RegoVersion == ast.RegoUndefined { + opts.RegoVersion = ast.DefaultRegoVersion + } + if opts.ParserOptions == nil { + opts.ParserOptions = &ast.ParserOptions{} + } + if opts.ParserOptions.RegoVersion == ast.RegoUndefined { + opts.ParserOptions.RegoVersion = ast.DefaultRegoVersion + } + + return v1.SourceWithOpts(filename, src, opts) +} + +// MustAst is a helper function to format a Rego AST element. If any errors +// occurs this function will panic. This is mostly used for test +func MustAst(x interface{}) []byte { + bs, err := Ast(x) + if err != nil { + panic(err) + } + return bs +} + +// MustAstWithOpts is a helper function to format a Rego AST element. If any errors +// occurs this function will panic. This is mostly used for test +func MustAstWithOpts(x interface{}, opts Opts) []byte { + bs, err := AstWithOpts(x, opts) + if err != nil { + panic(err) + } + return bs +} + +// Ast formats a Rego AST element. If the passed value is not a valid AST +// element, Ast returns nil and an error. If AST nodes are missing locations +// an arbitrary location will be used. +func Ast(x interface{}) ([]byte, error) { + return AstWithOpts(x, Opts{ + RegoVersion: ast.DefaultRegoVersion, + }) +} + +func AstWithOpts(x interface{}, opts Opts) ([]byte, error) { + if opts.RegoVersion == ast.RegoUndefined { + opts.RegoVersion = ast.DefaultRegoVersion + } + + return v1.AstWithOpts(x, opts) +} + +// ArgErrDetail but for `fmt` checks since compiler has not run yet. +type ArityFormatErrDetail = v1.ArityFormatErrDetail + +// arityMismatchError but for `fmt` checks since the compiler has not run yet. +func ArityFormatMismatchError(operands []*ast.Term, operator string, loc *ast.Location, f *types.Function) *ast.Error { + return v1.ArityFormatMismatchError(operands, operator, loc, f) +} diff --git a/vendor/github.com/open-policy-agent/opa/loader/doc.go b/vendor/github.com/open-policy-agent/opa/loader/doc.go new file mode 100644 index 00000000000..9f60920d955 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/loader/doc.go @@ -0,0 +1,8 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package loader diff --git a/vendor/github.com/open-policy-agent/opa/loader/errors.go b/vendor/github.com/open-policy-agent/opa/loader/errors.go new file mode 100644 index 00000000000..8dc70b86738 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/loader/errors.go @@ -0,0 +1,12 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package loader + +import ( + v1 "github.com/open-policy-agent/opa/v1/loader" +) + +// Errors is a wrapper for multiple loader errors. +type Errors = v1.Errors diff --git a/vendor/github.com/open-policy-agent/opa/loader/loader.go b/vendor/github.com/open-policy-agent/opa/loader/loader.go new file mode 100644 index 00000000000..9b2f91d4e9f --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/loader/loader.go @@ -0,0 +1,145 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package loader contains utilities for loading files into OPA. +package loader + +import ( + "io/fs" + "os" + "strings" + + "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/bundle" + v1 "github.com/open-policy-agent/opa/v1/loader" +) + +// Result represents the result of successfully loading zero or more files. +type Result = v1.Result + +// RegoFile represents the result of loading a single Rego source file. +type RegoFile = v1.RegoFile + +// Filter defines the interface for filtering files during loading. If the +// filter returns true, the file should be excluded from the result. +type Filter = v1.Filter + +// GlobExcludeName excludes files and directories whose names do not match the +// shell style pattern at minDepth or greater. +func GlobExcludeName(pattern string, minDepth int) Filter { + return v1.GlobExcludeName(pattern, minDepth) +} + +// FileLoader defines an interface for loading OPA data files +// and Rego policies. +type FileLoader = v1.FileLoader + +// NewFileLoader returns a new FileLoader instance. +func NewFileLoader() FileLoader { + return v1.NewFileLoader().WithRegoVersion(ast.DefaultRegoVersion) +} + +// GetBundleDirectoryLoader returns a bundle directory loader which can be used to load +// files in the directory +func GetBundleDirectoryLoader(path string) (bundle.DirectoryLoader, bool, error) { + return v1.GetBundleDirectoryLoader(path) +} + +// GetBundleDirectoryLoaderWithFilter returns a bundle directory loader which can be used to load +// files in the directory after applying the given filter. +func GetBundleDirectoryLoaderWithFilter(path string, filter Filter) (bundle.DirectoryLoader, bool, error) { + return v1.GetBundleDirectoryLoaderWithFilter(path, filter) +} + +// GetBundleDirectoryLoaderFS returns a bundle directory loader which can be used to load +// files in the directory. +func GetBundleDirectoryLoaderFS(fsys fs.FS, path string, filter Filter) (bundle.DirectoryLoader, bool, error) { + return v1.GetBundleDirectoryLoaderFS(fsys, path, filter) +} + +// FilteredPaths is the same as FilterPathsFS using the current diretory file +// system +func FilteredPaths(paths []string, filter Filter) ([]string, error) { + return v1.FilteredPaths(paths, filter) +} + +// FilteredPathsFS return a list of files from the specified +// paths while applying the given filters. If any filter returns true, the +// file/directory is excluded. +func FilteredPathsFS(fsys fs.FS, paths []string, filter Filter) ([]string, error) { + return v1.FilteredPathsFS(fsys, paths, filter) +} + +// Schemas loads a schema set from the specified file path. +func Schemas(schemaPath string) (*ast.SchemaSet, error) { + return v1.Schemas(schemaPath) +} + +// All returns a Result object loaded (recursively) from the specified paths. +// Deprecated: Use FileLoader.Filtered() instead. +func All(paths []string) (*Result, error) { + return NewFileLoader().Filtered(paths, nil) +} + +// Filtered returns a Result object loaded (recursively) from the specified +// paths while applying the given filters. If any filter returns true, the +// file/directory is excluded. +// Deprecated: Use FileLoader.Filtered() instead. +func Filtered(paths []string, filter Filter) (*Result, error) { + return NewFileLoader().Filtered(paths, filter) +} + +// AsBundle loads a path as a bundle. If it is a single file +// it will be treated as a normal tarball bundle. If a directory +// is supplied it will be loaded as an unzipped bundle tree. +// Deprecated: Use FileLoader.AsBundle() instead. +func AsBundle(path string) (*bundle.Bundle, error) { + return NewFileLoader().AsBundle(path) +} + +// AllRegos returns a Result object loaded (recursively) with all Rego source +// files from the specified paths. +func AllRegos(paths []string) (*Result, error) { + return NewFileLoader().Filtered(paths, func(_ string, info os.FileInfo, _ int) bool { + return !info.IsDir() && !strings.HasSuffix(info.Name(), bundle.RegoExt) + }) +} + +// Rego is deprecated. Use RegoWithOpts instead. +func Rego(path string) (*RegoFile, error) { + return RegoWithOpts(path, ast.ParserOptions{}) +} + +// RegoWithOpts returns a RegoFile object loaded from the given path. +func RegoWithOpts(path string, opts ast.ParserOptions) (*RegoFile, error) { + if opts.RegoVersion == ast.RegoUndefined { + opts.RegoVersion = ast.DefaultRegoVersion + } + + return v1.RegoWithOpts(path, opts) +} + +// CleanPath returns the normalized version of a path that can be used as an identifier. +func CleanPath(path string) string { + return v1.CleanPath(path) +} + +// Paths returns a sorted list of files contained at path. If recurse is true +// and path is a directory, then Paths will walk the directory structure +// recursively and list files at each level. +func Paths(path string, recurse bool) (paths []string, err error) { + return v1.Paths(path, recurse) +} + +// Dirs resolves filepaths to directories. It will return a list of unique +// directories. +func Dirs(paths []string) []string { + return v1.Dirs(paths) +} + +// SplitPrefix returns a tuple specifying the document prefix and the file +// path. +func SplitPrefix(path string) ([]string, string) { + return v1.SplitPrefix(path) +} diff --git a/vendor/github.com/open-policy-agent/opa/rego/doc.go b/vendor/github.com/open-policy-agent/opa/rego/doc.go new file mode 100644 index 00000000000..febe75696c5 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/rego/doc.go @@ -0,0 +1,8 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package rego diff --git a/vendor/github.com/open-policy-agent/opa/rego/errors.go b/vendor/github.com/open-policy-agent/opa/rego/errors.go new file mode 100644 index 00000000000..bcbd2efeddf --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/rego/errors.go @@ -0,0 +1,17 @@ +package rego + +import v1 "github.com/open-policy-agent/opa/v1/rego" + +// HaltError is an error type to return from a custom function implementation +// that will abort the evaluation process (analogous to topdown.Halt). +type HaltError = v1.HaltError + +// NewHaltError wraps an error such that the evaluation process will stop +// when it occurs. +func NewHaltError(err error) error { + return v1.NewHaltError(err) +} + +// ErrorDetails interface is satisfied by an error that provides further +// details. +type ErrorDetails = v1.ErrorDetails diff --git a/vendor/github.com/open-policy-agent/opa/rego/plugins.go b/vendor/github.com/open-policy-agent/opa/rego/plugins.go new file mode 100644 index 00000000000..38ef84416fb --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/rego/plugins.go @@ -0,0 +1,17 @@ +// Copyright 2023 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package rego + +import ( + v1 "github.com/open-policy-agent/opa/v1/rego" +) + +type TargetPlugin = v1.TargetPlugin + +type TargetPluginEval = v1.TargetPluginEval + +func RegisterPlugin(name string, p TargetPlugin) { + v1.RegisterPlugin(name, p) +} diff --git a/vendor/github.com/open-policy-agent/opa/rego/rego.go b/vendor/github.com/open-policy-agent/opa/rego/rego.go new file mode 100644 index 00000000000..e6af30c39c5 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/rego/rego.go @@ -0,0 +1,628 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package rego exposes high level APIs for evaluating Rego policies. +package rego + +import ( + "io" + "time" + + "github.com/open-policy-agent/opa/ast" + "github.com/open-policy-agent/opa/bundle" + "github.com/open-policy-agent/opa/loader" + "github.com/open-policy-agent/opa/storage" + "github.com/open-policy-agent/opa/v1/metrics" + v1 "github.com/open-policy-agent/opa/v1/rego" + "github.com/open-policy-agent/opa/v1/resolver" + "github.com/open-policy-agent/opa/v1/topdown" + "github.com/open-policy-agent/opa/v1/topdown/builtins" + "github.com/open-policy-agent/opa/v1/topdown/cache" + "github.com/open-policy-agent/opa/v1/topdown/print" + "github.com/open-policy-agent/opa/v1/tracing" +) + +// CompileResult represents the result of compiling a Rego query, zero or more +// Rego modules, and arbitrary contextual data into an executable. +type CompileResult = v1.CompileResult + +// PartialQueries contains the queries and support modules produced by partial +// evaluation. +type PartialQueries = v1.PartialQueries + +// PartialResult represents the result of partial evaluation. The result can be +// used to generate a new query that can be run when inputs are known. +type PartialResult = v1.PartialResult + +// EvalContext defines the set of options allowed to be set at evaluation +// time. Any other options will need to be set on a new Rego object. +type EvalContext = v1.EvalContext + +// EvalOption defines a function to set an option on an EvalConfig +type EvalOption = v1.EvalOption + +// EvalInput configures the input for a Prepared Query's evaluation +func EvalInput(input interface{}) EvalOption { + return v1.EvalInput(input) +} + +// EvalParsedInput configures the input for a Prepared Query's evaluation +func EvalParsedInput(input ast.Value) EvalOption { + return v1.EvalParsedInput(input) +} + +// EvalMetrics configures the metrics for a Prepared Query's evaluation +func EvalMetrics(metric metrics.Metrics) EvalOption { + return v1.EvalMetrics(metric) +} + +// EvalTransaction configures the Transaction for a Prepared Query's evaluation +func EvalTransaction(txn storage.Transaction) EvalOption { + return v1.EvalTransaction(txn) +} + +// EvalInstrument enables or disables instrumenting for a Prepared Query's evaluation +func EvalInstrument(instrument bool) EvalOption { + return v1.EvalInstrument(instrument) +} + +// EvalTracer configures a tracer for a Prepared Query's evaluation +// Deprecated: Use EvalQueryTracer instead. +func EvalTracer(tracer topdown.Tracer) EvalOption { + return v1.EvalTracer(tracer) +} + +// EvalQueryTracer configures a tracer for a Prepared Query's evaluation +func EvalQueryTracer(tracer topdown.QueryTracer) EvalOption { + return v1.EvalQueryTracer(tracer) +} + +// EvalPartialNamespace returns an argument that sets the namespace to use for +// partial evaluation results. The namespace must be a valid package path +// component. +func EvalPartialNamespace(ns string) EvalOption { + return v1.EvalPartialNamespace(ns) +} + +// EvalUnknowns returns an argument that sets the values to treat as +// unknown during partial evaluation. +func EvalUnknowns(unknowns []string) EvalOption { + return v1.EvalUnknowns(unknowns) +} + +// EvalDisableInlining returns an argument that adds a set of paths to exclude from +// partial evaluation inlining. +func EvalDisableInlining(paths []ast.Ref) EvalOption { + return v1.EvalDisableInlining(paths) +} + +// EvalParsedUnknowns returns an argument that sets the values to treat +// as unknown during partial evaluation. +func EvalParsedUnknowns(unknowns []*ast.Term) EvalOption { + return v1.EvalParsedUnknowns(unknowns) +} + +// EvalRuleIndexing will disable indexing optimizations for the +// evaluation. This should only be used when tracing in debug mode. +func EvalRuleIndexing(enabled bool) EvalOption { + return v1.EvalRuleIndexing(enabled) +} + +// EvalEarlyExit will disable 'early exit' optimizations for the +// evaluation. This should only be used when tracing in debug mode. +func EvalEarlyExit(enabled bool) EvalOption { + return v1.EvalEarlyExit(enabled) +} + +// EvalTime sets the wall clock time to use during policy evaluation. +// time.now_ns() calls will return this value. +func EvalTime(x time.Time) EvalOption { + return v1.EvalTime(x) +} + +// EvalSeed sets a reader that will seed randomization required by built-in functions. +// If a seed is not provided crypto/rand.Reader is used. +func EvalSeed(r io.Reader) EvalOption { + return v1.EvalSeed(r) +} + +// EvalInterQueryBuiltinCache sets the inter-query cache that built-in functions can utilize +// during evaluation. +func EvalInterQueryBuiltinCache(c cache.InterQueryCache) EvalOption { + return v1.EvalInterQueryBuiltinCache(c) +} + +// EvalInterQueryBuiltinValueCache sets the inter-query value cache that built-in functions can utilize +// during evaluation. +func EvalInterQueryBuiltinValueCache(c cache.InterQueryValueCache) EvalOption { + return v1.EvalInterQueryBuiltinValueCache(c) +} + +// EvalNDBuiltinCache sets the non-deterministic builtin cache that built-in functions can +// use during evaluation. +func EvalNDBuiltinCache(c builtins.NDBCache) EvalOption { + return v1.EvalNDBuiltinCache(c) +} + +// EvalResolver sets a Resolver for a specified ref path for this evaluation. +func EvalResolver(ref ast.Ref, r resolver.Resolver) EvalOption { + return v1.EvalResolver(ref, r) +} + +// EvalSortSets causes the evaluator to sort sets before returning them as JSON arrays. +func EvalSortSets(yes bool) EvalOption { + return v1.EvalSortSets(yes) +} + +// EvalCopyMaps causes the evaluator to copy `map[string]interface{}`s before returning them. +func EvalCopyMaps(yes bool) EvalOption { + return v1.EvalCopyMaps(yes) +} + +// EvalPrintHook sets the object to use for handling print statement outputs. +func EvalPrintHook(ph print.Hook) EvalOption { + return v1.EvalPrintHook(ph) +} + +// EvalVirtualCache sets the topdown.VirtualCache to use for evaluation. This is +// optional, and if not set, the default cache is used. +func EvalVirtualCache(vc topdown.VirtualCache) EvalOption { + return v1.EvalVirtualCache(vc) +} + +// PreparedEvalQuery holds the prepared Rego state that has been pre-processed +// for subsequent evaluations. +type PreparedEvalQuery = v1.PreparedEvalQuery + +// PreparedPartialQuery holds the prepared Rego state that has been pre-processed +// for partial evaluations. +type PreparedPartialQuery = v1.PreparedPartialQuery + +// Errors represents a collection of errors returned when evaluating Rego. +type Errors = v1.Errors + +// IsPartialEvaluationNotEffectiveErr returns true if err is an error returned by +// this package to indicate that partial evaluation was ineffective. +func IsPartialEvaluationNotEffectiveErr(err error) bool { + return v1.IsPartialEvaluationNotEffectiveErr(err) +} + +// Rego constructs a query and can be evaluated to obtain results. +type Rego = v1.Rego + +// Function represents a built-in function that is callable in Rego. +type Function = v1.Function + +// BuiltinContext contains additional attributes from the evaluator that +// built-in functions can use, e.g., the request context.Context, caches, etc. +type BuiltinContext = v1.BuiltinContext + +type ( + // Builtin1 defines a built-in function that accepts 1 argument. + Builtin1 = v1.Builtin1 + + // Builtin2 defines a built-in function that accepts 2 arguments. + Builtin2 = v1.Builtin2 + + // Builtin3 defines a built-in function that accepts 3 argument. + Builtin3 = v1.Builtin3 + + // Builtin4 defines a built-in function that accepts 4 argument. + Builtin4 = v1.Builtin4 + + // BuiltinDyn defines a built-in function that accepts a list of arguments. + BuiltinDyn = v1.BuiltinDyn +) + +// RegisterBuiltin1 adds a built-in function globally inside the OPA runtime. +func RegisterBuiltin1(decl *Function, impl Builtin1) { + v1.RegisterBuiltin1(decl, impl) +} + +// RegisterBuiltin2 adds a built-in function globally inside the OPA runtime. +func RegisterBuiltin2(decl *Function, impl Builtin2) { + v1.RegisterBuiltin2(decl, impl) +} + +// RegisterBuiltin3 adds a built-in function globally inside the OPA runtime. +func RegisterBuiltin3(decl *Function, impl Builtin3) { + v1.RegisterBuiltin3(decl, impl) +} + +// RegisterBuiltin4 adds a built-in function globally inside the OPA runtime. +func RegisterBuiltin4(decl *Function, impl Builtin4) { + v1.RegisterBuiltin4(decl, impl) +} + +// RegisterBuiltinDyn adds a built-in function globally inside the OPA runtime. +func RegisterBuiltinDyn(decl *Function, impl BuiltinDyn) { + v1.RegisterBuiltinDyn(decl, impl) +} + +// Function1 returns an option that adds a built-in function to the Rego object. +func Function1(decl *Function, f Builtin1) func(*Rego) { + return v1.Function1(decl, f) +} + +// Function2 returns an option that adds a built-in function to the Rego object. +func Function2(decl *Function, f Builtin2) func(*Rego) { + return v1.Function2(decl, f) +} + +// Function3 returns an option that adds a built-in function to the Rego object. +func Function3(decl *Function, f Builtin3) func(*Rego) { + return v1.Function3(decl, f) +} + +// Function4 returns an option that adds a built-in function to the Rego object. +func Function4(decl *Function, f Builtin4) func(*Rego) { + return v1.Function4(decl, f) +} + +// FunctionDyn returns an option that adds a built-in function to the Rego object. +func FunctionDyn(decl *Function, f BuiltinDyn) func(*Rego) { + return v1.FunctionDyn(decl, f) +} + +// FunctionDecl returns an option that adds a custom-built-in function +// __declaration__. NO implementation is provided. This is used for +// non-interpreter execution envs (e.g., Wasm). +func FunctionDecl(decl *Function) func(*Rego) { + return v1.FunctionDecl(decl) +} + +// Dump returns an argument that sets the writer to dump debugging information to. +func Dump(w io.Writer) func(r *Rego) { + return v1.Dump(w) +} + +// Query returns an argument that sets the Rego query. +func Query(q string) func(r *Rego) { + return v1.Query(q) +} + +// ParsedQuery returns an argument that sets the Rego query. +func ParsedQuery(q ast.Body) func(r *Rego) { + return v1.ParsedQuery(q) +} + +// Package returns an argument that sets the Rego package on the query's +// context. +func Package(p string) func(r *Rego) { + return v1.Package(p) +} + +// ParsedPackage returns an argument that sets the Rego package on the query's +// context. +func ParsedPackage(pkg *ast.Package) func(r *Rego) { + return v1.ParsedPackage(pkg) +} + +// Imports returns an argument that adds a Rego import to the query's context. +func Imports(p []string) func(r *Rego) { + return v1.Imports(p) +} + +// ParsedImports returns an argument that adds Rego imports to the query's +// context. +func ParsedImports(imp []*ast.Import) func(r *Rego) { + return v1.ParsedImports(imp) +} + +// Input returns an argument that sets the Rego input document. Input should be +// a native Go value representing the input document. +func Input(x interface{}) func(r *Rego) { + return v1.Input(x) +} + +// ParsedInput returns an argument that sets the Rego input document. +func ParsedInput(x ast.Value) func(r *Rego) { + return v1.ParsedInput(x) +} + +// Unknowns returns an argument that sets the values to treat as unknown during +// partial evaluation. +func Unknowns(unknowns []string) func(r *Rego) { + return v1.Unknowns(unknowns) +} + +// ParsedUnknowns returns an argument that sets the values to treat as unknown +// during partial evaluation. +func ParsedUnknowns(unknowns []*ast.Term) func(r *Rego) { + return v1.ParsedUnknowns(unknowns) +} + +// DisableInlining adds a set of paths to exclude from partial evaluation inlining. +func DisableInlining(paths []string) func(r *Rego) { + return v1.DisableInlining(paths) +} + +// ShallowInlining prevents rules that depend on unknown values from being inlined. +// Rules that only depend on known values are inlined. +func ShallowInlining(yes bool) func(r *Rego) { + return v1.ShallowInlining(yes) +} + +// SkipPartialNamespace disables namespacing of partial evalution results for support +// rules generated from policy. Synthetic support rules are still namespaced. +func SkipPartialNamespace(yes bool) func(r *Rego) { + return v1.SkipPartialNamespace(yes) +} + +// PartialNamespace returns an argument that sets the namespace to use for +// partial evaluation results. The namespace must be a valid package path +// component. +func PartialNamespace(ns string) func(r *Rego) { + return v1.PartialNamespace(ns) +} + +// Module returns an argument that adds a Rego module. +func Module(filename, input string) func(r *Rego) { + return v1.Module(filename, input) +} + +// ParsedModule returns an argument that adds a parsed Rego module. If a string +// module with the same filename name is added, it will override the parsed +// module. +func ParsedModule(module *ast.Module) func(*Rego) { + return v1.ParsedModule(module) +} + +// Load returns an argument that adds a filesystem path to load data +// and Rego modules from. Any file with a *.rego, *.yaml, or *.json +// extension will be loaded. The path can be either a directory or file, +// directories are loaded recursively. The optional ignore string patterns +// can be used to filter which files are used. +// The Load option can only be used once. +// Note: Loading files will require a write transaction on the store. +func Load(paths []string, filter loader.Filter) func(r *Rego) { + return v1.Load(paths, filter) +} + +// LoadBundle returns an argument that adds a filesystem path to load +// a bundle from. The path can be a compressed bundle file or a directory +// to be loaded as a bundle. +// Note: Loading bundles will require a write transaction on the store. +func LoadBundle(path string) func(r *Rego) { + return v1.LoadBundle(path) +} + +// ParsedBundle returns an argument that adds a bundle to be loaded. +func ParsedBundle(name string, b *bundle.Bundle) func(r *Rego) { + return v1.ParsedBundle(name, b) +} + +// Compiler returns an argument that sets the Rego compiler. +func Compiler(c *ast.Compiler) func(r *Rego) { + return v1.Compiler(c) +} + +// Store returns an argument that sets the policy engine's data storage layer. +// +// If using the Load, LoadBundle, or ParsedBundle options then a transaction +// must also be provided via the Transaction() option. After loading files +// or bundles the transaction should be aborted or committed. +func Store(s storage.Store) func(r *Rego) { + return v1.Store(s) +} + +// StoreReadAST returns an argument that sets whether the store should eagerly convert data to AST values. +// +// Only applicable when no store has been set on the Rego object through the Store option. +func StoreReadAST(enabled bool) func(r *Rego) { + return v1.StoreReadAST(enabled) +} + +// Transaction returns an argument that sets the transaction to use for storage +// layer operations. +// +// Requires the store associated with the transaction to be provided via the +// Store() option. If using Load(), LoadBundle(), or ParsedBundle() options +// the transaction will likely require write params. +func Transaction(txn storage.Transaction) func(r *Rego) { + return v1.Transaction(txn) +} + +// Metrics returns an argument that sets the metrics collection. +func Metrics(m metrics.Metrics) func(r *Rego) { + return v1.Metrics(m) +} + +// Instrument returns an argument that enables instrumentation for diagnosing +// performance issues. +func Instrument(yes bool) func(r *Rego) { + return v1.Instrument(yes) +} + +// Trace returns an argument that enables tracing on r. +func Trace(yes bool) func(r *Rego) { + return v1.Trace(yes) +} + +// Tracer returns an argument that adds a query tracer to r. +// Deprecated: Use QueryTracer instead. +func Tracer(t topdown.Tracer) func(r *Rego) { + return v1.Tracer(t) +} + +// QueryTracer returns an argument that adds a query tracer to r. +func QueryTracer(t topdown.QueryTracer) func(r *Rego) { + return v1.QueryTracer(t) +} + +// Runtime returns an argument that sets the runtime data to provide to the +// evaluation engine. +func Runtime(term *ast.Term) func(r *Rego) { + return v1.Runtime(term) +} + +// Time sets the wall clock time to use during policy evaluation. Prepared queries +// do not inherit this parameter. Use EvalTime to set the wall clock time when +// executing a prepared query. +func Time(x time.Time) func(r *Rego) { + return v1.Time(x) +} + +// Seed sets a reader that will seed randomization required by built-in functions. +// If a seed is not provided crypto/rand.Reader is used. +func Seed(r io.Reader) func(*Rego) { + return v1.Seed(r) +} + +// PrintTrace is a helper function to write a human-readable version of the +// trace to the writer w. +func PrintTrace(w io.Writer, r *Rego) { + v1.PrintTrace(w, r) +} + +// PrintTraceWithLocation is a helper function to write a human-readable version of the +// trace to the writer w. +func PrintTraceWithLocation(w io.Writer, r *Rego) { + v1.PrintTraceWithLocation(w, r) +} + +// UnsafeBuiltins sets the built-in functions to treat as unsafe and not allow. +// This option is ignored for module compilation if the caller supplies the +// compiler. This option is always honored for query compilation. Provide an +// empty (non-nil) map to disable checks on queries. +func UnsafeBuiltins(unsafeBuiltins map[string]struct{}) func(r *Rego) { + return v1.UnsafeBuiltins(unsafeBuiltins) +} + +// SkipBundleVerification skips verification of a signed bundle. +func SkipBundleVerification(yes bool) func(r *Rego) { + return v1.SkipBundleVerification(yes) +} + +// InterQueryBuiltinCache sets the inter-query cache that built-in functions can utilize +// during evaluation. +func InterQueryBuiltinCache(c cache.InterQueryCache) func(r *Rego) { + return v1.InterQueryBuiltinCache(c) +} + +// InterQueryBuiltinValueCache sets the inter-query value cache that built-in functions can utilize +// during evaluation. +func InterQueryBuiltinValueCache(c cache.InterQueryValueCache) func(r *Rego) { + return v1.InterQueryBuiltinValueCache(c) +} + +// NDBuiltinCache sets the non-deterministic builtins cache. +func NDBuiltinCache(c builtins.NDBCache) func(r *Rego) { + return v1.NDBuiltinCache(c) +} + +// StrictBuiltinErrors tells the evaluator to treat all built-in function errors as fatal errors. +func StrictBuiltinErrors(yes bool) func(r *Rego) { + return v1.StrictBuiltinErrors(yes) +} + +// BuiltinErrorList supplies an error slice to store built-in function errors. +func BuiltinErrorList(list *[]topdown.Error) func(r *Rego) { + return v1.BuiltinErrorList(list) +} + +// Resolver sets a Resolver for a specified ref path. +func Resolver(ref ast.Ref, r resolver.Resolver) func(r *Rego) { + return v1.Resolver(ref, r) +} + +// Schemas sets the schemaSet +func Schemas(x *ast.SchemaSet) func(r *Rego) { + return v1.Schemas(x) +} + +// Capabilities configures the underlying compiler's capabilities. +// This option is ignored for module compilation if the caller supplies the +// compiler. +func Capabilities(c *ast.Capabilities) func(r *Rego) { + return v1.Capabilities(c) +} + +// Target sets the runtime to exercise. +func Target(t string) func(r *Rego) { + return v1.Target(t) +} + +// GenerateJSON sets the AST to JSON converter for the results. +func GenerateJSON(f func(*ast.Term, *EvalContext) (interface{}, error)) func(r *Rego) { + return v1.GenerateJSON(f) +} + +// PrintHook sets the object to use for handling print statement outputs. +func PrintHook(h print.Hook) func(r *Rego) { + return v1.PrintHook(h) +} + +// DistributedTracingOpts sets the options to be used by distributed tracing. +func DistributedTracingOpts(tr tracing.Options) func(r *Rego) { + return v1.DistributedTracingOpts(tr) +} + +// EnablePrintStatements enables print() calls. If this option is not provided, +// print() calls will be erased from the policy. This option only applies to +// queries and policies that passed as raw strings, i.e., this function will not +// have any affect if the caller supplies the ast.Compiler instance. +func EnablePrintStatements(yes bool) func(r *Rego) { + return v1.EnablePrintStatements(yes) +} + +// Strict enables or disables strict-mode in the compiler +func Strict(yes bool) func(r *Rego) { + return v1.Strict(yes) +} + +func SetRegoVersion(version ast.RegoVersion) func(r *Rego) { + return v1.SetRegoVersion(version) +} + +// New returns a new Rego object. +func New(options ...func(r *Rego)) *Rego { + opts := make([]func(r *Rego), 0, len(options)+1) + opts = append(opts, options...) + opts = append(opts, func(r *Rego) { + if r.RegoVersion() == ast.RegoUndefined { + SetRegoVersion(ast.DefaultRegoVersion)(r) + } + }) + + return v1.New(opts...) +} + +// CompileOption defines a function to set options on Compile calls. +type CompileOption = v1.CompileOption + +// CompileContext contains options for Compile calls. +type CompileContext = v1.CompileContext + +// CompilePartial defines an option to control whether partial evaluation is run +// before the query is planned and compiled. +func CompilePartial(yes bool) CompileOption { + return v1.CompilePartial(yes) +} + +// PrepareOption defines a function to set an option to control +// the behavior of the Prepare call. +type PrepareOption = v1.PrepareOption + +// PrepareConfig holds settings to control the behavior of the +// Prepare call. +type PrepareConfig = v1.PrepareConfig + +// WithPartialEval configures an option for PrepareForEval +// which will have it perform partial evaluation while preparing +// the query (similar to rego.Rego#PartialResult) +func WithPartialEval() PrepareOption { + return v1.WithPartialEval() +} + +// WithNoInline adds a set of paths to exclude from partial evaluation inlining. +func WithNoInline(paths []string) PrepareOption { + return v1.WithNoInline(paths) +} + +// WithBuiltinFuncs carries the rego.Function{1,2,3} per-query function definitions +// to the target plugins. +func WithBuiltinFuncs(bis map[string]*topdown.Builtin) PrepareOption { + return v1.WithBuiltinFuncs(bis) +} diff --git a/vendor/github.com/open-policy-agent/opa/rego/resultset.go b/vendor/github.com/open-policy-agent/opa/rego/resultset.go new file mode 100644 index 00000000000..5c03360dfaa --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/rego/resultset.go @@ -0,0 +1,22 @@ +package rego + +import ( + v1 "github.com/open-policy-agent/opa/v1/rego" +) + +// ResultSet represents a collection of output from Rego evaluation. An empty +// result set represents an undefined query. +type ResultSet = v1.ResultSet + +// Vars represents a collection of variable bindings. The keys are the variable +// names and the values are the binding values. +type Vars = v1.Vars + +// Result defines the output of Rego evaluation. +type Result = v1.Result + +// Location defines a position in a Rego query or module. +type Location = v1.Location + +// ExpressionValue defines the value of an expression in a Rego query. +type ExpressionValue = v1.ExpressionValue diff --git a/vendor/github.com/open-policy-agent/opa/storage/doc.go b/vendor/github.com/open-policy-agent/opa/storage/doc.go new file mode 100644 index 00000000000..c33db689edb --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/storage/doc.go @@ -0,0 +1,10 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package storage exposes the policy engine's storage layer. +// +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package storage diff --git a/vendor/github.com/open-policy-agent/opa/storage/errors.go b/vendor/github.com/open-policy-agent/opa/storage/errors.go new file mode 100644 index 00000000000..1403b3a9887 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/storage/errors.go @@ -0,0 +1,73 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package storage + +import ( + v1 "github.com/open-policy-agent/opa/v1/storage" +) + +const ( + // InternalErr indicates an unknown, internal error has occurred. + InternalErr = v1.InternalErr + + // NotFoundErr indicates the path used in the storage operation does not + // locate a document. + NotFoundErr = v1.NotFoundErr + + // WriteConflictErr indicates a write on the path enocuntered a conflicting + // value inside the transaction. + WriteConflictErr = v1.WriteConflictErr + + // InvalidPatchErr indicates an invalid patch/write was issued. The patch + // was rejected. + InvalidPatchErr = v1.InvalidPatchErr + + // InvalidTransactionErr indicates an invalid operation was performed + // inside of the transaction. + InvalidTransactionErr = v1.InvalidTransactionErr + + // TriggersNotSupportedErr indicates the caller attempted to register a + // trigger against a store that does not support them. + TriggersNotSupportedErr = v1.TriggersNotSupportedErr + + // WritesNotSupportedErr indicate the caller attempted to perform a write + // against a store that does not support them. + WritesNotSupportedErr = v1.WritesNotSupportedErr + + // PolicyNotSupportedErr indicate the caller attempted to perform a policy + // management operation against a store that does not support them. + PolicyNotSupportedErr = v1.PolicyNotSupportedErr +) + +// Error is the error type returned by the storage layer. +type Error = v1.Error + +// IsNotFound returns true if this error is a NotFoundErr. +func IsNotFound(err error) bool { + return v1.IsNotFound(err) +} + +// IsWriteConflictError returns true if this error a WriteConflictErr. +func IsWriteConflictError(err error) bool { + return v1.IsWriteConflictError(err) +} + +// IsInvalidPatch returns true if this error is a InvalidPatchErr. +func IsInvalidPatch(err error) bool { + return v1.IsInvalidPatch(err) +} + +// IsInvalidTransaction returns true if this error is a InvalidTransactionErr. +func IsInvalidTransaction(err error) bool { + return v1.IsInvalidTransaction(err) +} + +// IsIndexingNotSupported is a stub for backwards-compatibility. +// +// Deprecated: We no longer return IndexingNotSupported errors, so it is +// unnecessary to check for them. +func IsIndexingNotSupported(err error) bool { + return v1.IsIndexingNotSupported(err) +} diff --git a/vendor/github.com/open-policy-agent/opa/storage/inmem/doc.go b/vendor/github.com/open-policy-agent/opa/storage/inmem/doc.go new file mode 100644 index 00000000000..5f536b66ddd --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/storage/inmem/doc.go @@ -0,0 +1,8 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package inmem diff --git a/vendor/github.com/open-policy-agent/opa/storage/inmem/inmem.go b/vendor/github.com/open-policy-agent/opa/storage/inmem/inmem.go new file mode 100644 index 00000000000..0a41b9d0da4 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/storage/inmem/inmem.go @@ -0,0 +1,56 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package inmem implements an in-memory version of the policy engine's storage +// layer. +// +// The in-memory store is used as the default storage layer implementation. The +// in-memory store supports multi-reader/single-writer concurrency with +// rollback. +// +// Callers should assume the in-memory store does not make copies of written +// data. Once data is written to the in-memory store, it should not be modified +// (outside of calling Store.Write). Furthermore, data read from the in-memory +// store should be treated as read-only. +package inmem + +import ( + "io" + + "github.com/open-policy-agent/opa/storage" + v1 "github.com/open-policy-agent/opa/v1/storage/inmem" +) + +// New returns an empty in-memory store. +func New() storage.Store { + return v1.New() +} + +// NewWithOpts returns an empty in-memory store, with extra options passed. +func NewWithOpts(opts ...Opt) storage.Store { + return v1.NewWithOpts(opts...) +} + +// NewFromObject returns a new in-memory store from the supplied data object. +func NewFromObject(data map[string]interface{}) storage.Store { + return v1.NewFromObject(data) +} + +// NewFromObjectWithOpts returns a new in-memory store from the supplied data object, with the +// options passed. +func NewFromObjectWithOpts(data map[string]interface{}, opts ...Opt) storage.Store { + return v1.NewFromObjectWithOpts(data, opts...) +} + +// NewFromReader returns a new in-memory store from a reader that produces a +// JSON serialized object. This function is for test purposes. +func NewFromReader(r io.Reader) storage.Store { + return v1.NewFromReader(r) +} + +// NewFromReader returns a new in-memory store from a reader that produces a +// JSON serialized object, with extra options. This function is for test purposes. +func NewFromReaderWithOpts(r io.Reader, opts ...Opt) storage.Store { + return v1.NewFromReaderWithOpts(r, opts...) +} diff --git a/vendor/github.com/open-policy-agent/opa/storage/inmem/opts.go b/vendor/github.com/open-policy-agent/opa/storage/inmem/opts.go new file mode 100644 index 00000000000..43f03ef27b9 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/storage/inmem/opts.go @@ -0,0 +1,35 @@ +package inmem + +import v1 "github.com/open-policy-agent/opa/v1/storage/inmem" + +// An Opt modifies store at instantiation. +type Opt = v1.Opt + +// OptRoundTripOnWrite sets whether incoming objects written to store are +// round-tripped through JSON to ensure they are serializable to JSON. +// +// Callers should disable this if they can guarantee all objects passed to +// Write() are serializable to JSON. Failing to do so may result in undefined +// behavior, including panics. +// +// Usually, when only storing objects in the inmem store that have been read +// via encoding/json, this is safe to disable, and comes with an improvement +// in performance and memory use. +// +// If setting to false, callers should deep-copy any objects passed to Write() +// unless they can guarantee the objects will not be mutated after being written, +// and that mutations happening to the objects after they have been passed into +// Write() don't affect their logic. +func OptRoundTripOnWrite(enabled bool) Opt { + return v1.OptRoundTripOnWrite(enabled) +} + +// OptReturnASTValuesOnRead sets whether data values added to the store should be +// eagerly converted to AST values, which are then returned on read. +// +// When enabled, this feature does not sanity check data before converting it to AST values, +// which may result in panics if the data is not valid. Callers should ensure that passed data +// can be serialized to AST values; otherwise, it's recommended to also enable OptRoundTripOnWrite. +func OptReturnASTValuesOnRead(enabled bool) Opt { + return v1.OptReturnASTValuesOnRead(enabled) +} diff --git a/vendor/github.com/open-policy-agent/opa/storage/interface.go b/vendor/github.com/open-policy-agent/opa/storage/interface.go new file mode 100644 index 00000000000..0192c459c83 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/storage/interface.go @@ -0,0 +1,86 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package storage + +import ( + v1 "github.com/open-policy-agent/opa/v1/storage" +) + +// Transaction defines the interface that identifies a consistent snapshot over +// the policy engine's storage layer. +type Transaction = v1.Transaction + +// Store defines the interface for the storage layer's backend. +type Store = v1.Store + +// MakeDirer defines the interface a Store could realize to override the +// generic MakeDir functionality in storage.MakeDir +type MakeDirer = v1.MakeDirer + +// TransactionParams describes a new transaction. +type TransactionParams = v1.TransactionParams + +// Context is a simple container for key/value pairs. +type Context = v1.Context + +// NewContext returns a new context object. +func NewContext() *Context { + return v1.NewContext() +} + +// WriteParams specifies the TransactionParams for a write transaction. +var WriteParams = v1.WriteParams + +// PatchOp is the enumeration of supposed modifications. +type PatchOp = v1.PatchOp + +// Patch supports add, remove, and replace operations. +const ( + AddOp = v1.AddOp + RemoveOp = v1.RemoveOp + ReplaceOp = v1.ReplaceOp +) + +// WritesNotSupported provides a default implementation of the write +// interface which may be used if the backend does not support writes. +type WritesNotSupported = v1.WritesNotSupported + +// Policy defines the interface for policy module storage. +type Policy = v1.Policy + +// PolicyNotSupported provides a default implementation of the policy interface +// which may be used if the backend does not support policy storage. +type PolicyNotSupported = v1.PolicyNotSupported + +// PolicyEvent describes a change to a policy. +type PolicyEvent = v1.PolicyEvent + +// DataEvent describes a change to a base data document. +type DataEvent = v1.DataEvent + +// TriggerEvent describes the changes that caused the trigger to be invoked. +type TriggerEvent = v1.TriggerEvent + +// TriggerConfig contains the trigger registration configuration. +type TriggerConfig = v1.TriggerConfig + +// Trigger defines the interface that stores implement to register for change +// notifications when the store is changed. +type Trigger = v1.Trigger + +// TriggersNotSupported provides default implementations of the Trigger +// interface which may be used if the backend does not support triggers. +type TriggersNotSupported = v1.TriggersNotSupported + +// TriggerHandle defines the interface that can be used to unregister triggers that have +// been registered on a Store. +type TriggerHandle = v1.TriggerHandle + +// Iterator defines the interface that can be used to read files from a directory starting with +// files at the base of the directory, then sub-directories etc. +type Iterator = v1.Iterator + +// Update contains information about a file +type Update = v1.Update diff --git a/vendor/github.com/open-policy-agent/opa/storage/path.go b/vendor/github.com/open-policy-agent/opa/storage/path.go new file mode 100644 index 00000000000..91d4f34f2bc --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/storage/path.go @@ -0,0 +1,34 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package storage + +import ( + "github.com/open-policy-agent/opa/ast" + v1 "github.com/open-policy-agent/opa/v1/storage" +) + +// Path refers to a document in storage. +type Path = v1.Path + +// ParsePath returns a new path for the given str. +func ParsePath(str string) (path Path, ok bool) { + return v1.ParsePath(str) +} + +// ParsePathEscaped returns a new path for the given escaped str. +func ParsePathEscaped(str string) (path Path, ok bool) { + return v1.ParsePathEscaped(str) +} + +// NewPathForRef returns a new path for the given ref. +func NewPathForRef(ref ast.Ref) (path Path, err error) { + return v1.NewPathForRef(ref) +} + +// MustParsePath returns a new Path for s. If s cannot be parsed, this function +// will panic. This is mostly for test purposes. +func MustParsePath(s string) Path { + return v1.MustParsePath(s) +} diff --git a/vendor/github.com/open-policy-agent/opa/storage/storage.go b/vendor/github.com/open-policy-agent/opa/storage/storage.go new file mode 100644 index 00000000000..c02773d9851 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/storage/storage.go @@ -0,0 +1,53 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package storage + +import ( + "context" + + v1 "github.com/open-policy-agent/opa/v1/storage" +) + +// NewTransactionOrDie is a helper function to create a new transaction. If the +// storage layer cannot create a new transaction, this function will panic. This +// function should only be used for tests. +func NewTransactionOrDie(ctx context.Context, store Store, params ...TransactionParams) Transaction { + return v1.NewTransactionOrDie(ctx, store, params...) +} + +// ReadOne is a convenience function to read a single value from the provided Store. It +// will create a new Transaction to perform the read with, and clean up after itself +// should an error occur. +func ReadOne(ctx context.Context, store Store, path Path) (interface{}, error) { + return v1.ReadOne(ctx, store, path) +} + +// WriteOne is a convenience function to write a single value to the provided Store. It +// will create a new Transaction to perform the write with, and clean up after itself +// should an error occur. +func WriteOne(ctx context.Context, store Store, op PatchOp, path Path, value interface{}) error { + return v1.WriteOne(ctx, store, op, path, value) +} + +// MakeDir inserts an empty object at path. If the parent path does not exist, +// MakeDir will create it recursively. +func MakeDir(ctx context.Context, store Store, txn Transaction, path Path) error { + return v1.MakeDir(ctx, store, txn, path) +} + +// Txn is a convenience function that executes f inside a new transaction +// opened on the store. If the function returns an error, the transaction is +// aborted and the error is returned. Otherwise, the transaction is committed +// and the result of the commit is returned. +func Txn(ctx context.Context, store Store, params TransactionParams, f func(Transaction) error) error { + return v1.Txn(ctx, store, params, f) +} + +// NonEmpty returns a function that tests if a path is non-empty. A +// path is non-empty if a Read on the path returns a value or a Read +// on any of the path prefixes returns a non-object value. +func NonEmpty(ctx context.Context, store Store, txn Transaction) func([]string) (bool, error) { + return v1.NonEmpty(ctx, store, txn) +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/builtins.go b/vendor/github.com/open-policy-agent/opa/topdown/builtins.go new file mode 100644 index 00000000000..f28c6c795d1 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/builtins.go @@ -0,0 +1,67 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package topdown + +import ( + v1 "github.com/open-policy-agent/opa/v1/topdown" +) + +type ( + // Deprecated: Functional-style builtins are deprecated. Use BuiltinFunc instead. + FunctionalBuiltin1 = v1.FunctionalBuiltin1 //nolint:staticcheck // SA1019: Intentional use of deprecated type. + + // Deprecated: Functional-style builtins are deprecated. Use BuiltinFunc instead. + FunctionalBuiltin2 = v1.FunctionalBuiltin2 //nolint:staticcheck // SA1019: Intentional use of deprecated type. + + // Deprecated: Functional-style builtins are deprecated. Use BuiltinFunc instead. + FunctionalBuiltin3 = v1.FunctionalBuiltin3 //nolint:staticcheck // SA1019: Intentional use of deprecated type. + + // Deprecated: Functional-style builtins are deprecated. Use BuiltinFunc instead. + FunctionalBuiltin4 = v1.FunctionalBuiltin4 //nolint:staticcheck // SA1019: Intentional use of deprecated type. + + // BuiltinContext contains context from the evaluator that may be used by + // built-in functions. + BuiltinContext = v1.BuiltinContext + + // BuiltinFunc defines an interface for implementing built-in functions. + // The built-in function is called with the plugged operands from the call + // (including the output operands.) The implementation should evaluate the + // operands and invoke the iterator for each successful/defined output + // value. + BuiltinFunc = v1.BuiltinFunc +) + +// RegisterBuiltinFunc adds a new built-in function to the evaluation engine. +func RegisterBuiltinFunc(name string, f BuiltinFunc) { + v1.RegisterBuiltinFunc(name, f) +} + +// Deprecated: Functional-style builtins are deprecated. Use RegisterBuiltinFunc instead. +func RegisterFunctionalBuiltin1(name string, fun FunctionalBuiltin1) { + v1.RegisterFunctionalBuiltin1(name, fun) +} + +// Deprecated: Functional-style builtins are deprecated. Use RegisterBuiltinFunc instead. +func RegisterFunctionalBuiltin2(name string, fun FunctionalBuiltin2) { + v1.RegisterFunctionalBuiltin2(name, fun) +} + +// Deprecated: Functional-style builtins are deprecated. Use RegisterBuiltinFunc instead. +func RegisterFunctionalBuiltin3(name string, fun FunctionalBuiltin3) { + v1.RegisterFunctionalBuiltin3(name, fun) +} + +// Deprecated: Functional-style builtins are deprecated. Use RegisterBuiltinFunc instead. +func RegisterFunctionalBuiltin4(name string, fun FunctionalBuiltin4) { + v1.RegisterFunctionalBuiltin4(name, fun) +} + +// GetBuiltin returns a built-in function implementation, nil if no built-in found. +func GetBuiltin(name string) BuiltinFunc { + return v1.GetBuiltin(name) +} + +// Deprecated: The BuiltinEmpty type is no longer needed. Use nil return values instead. +type BuiltinEmpty = v1.Builtin diff --git a/vendor/github.com/open-policy-agent/opa/topdown/cache.go b/vendor/github.com/open-policy-agent/opa/topdown/cache.go new file mode 100644 index 00000000000..bb39df03e0c --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/cache.go @@ -0,0 +1,19 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package topdown + +import ( + v1 "github.com/open-policy-agent/opa/v1/topdown" +) + +// VirtualCache defines the interface for a cache that stores the results of +// evaluated virtual documents (rules). +// The cache is a stack of frames, where each frame is a mapping from references +// to values. +type VirtualCache = v1.VirtualCache + +func NewVirtualCache() VirtualCache { + return v1.NewVirtualCache() +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/cancel.go b/vendor/github.com/open-policy-agent/opa/topdown/cancel.go new file mode 100644 index 00000000000..395a14a80d6 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/cancel.go @@ -0,0 +1,18 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package topdown + +import ( + v1 "github.com/open-policy-agent/opa/v1/topdown" +) + +// Cancel defines the interface for cancelling topdown queries. Cancel +// operations are thread-safe and idempotent. +type Cancel = v1.Cancel + +// NewCancel returns a new Cancel object. +func NewCancel() Cancel { + return v1.NewCancel() +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/doc.go b/vendor/github.com/open-policy-agent/opa/topdown/doc.go new file mode 100644 index 00000000000..a303ef7886e --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/doc.go @@ -0,0 +1,14 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package topdown provides low-level query evaluation support. +// +// The topdown implementation is a modified version of the standard top-down +// evaluation algorithm used in Datalog. References and comprehensions are +// evaluated eagerly while all other terms are evaluated lazily. +// +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package topdown diff --git a/vendor/github.com/open-policy-agent/opa/topdown/errors.go b/vendor/github.com/open-policy-agent/opa/topdown/errors.go new file mode 100644 index 00000000000..47853ec6d10 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/errors.go @@ -0,0 +1,54 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package topdown + +import ( + v1 "github.com/open-policy-agent/opa/v1/topdown" +) + +// Halt is a special error type that built-in function implementations return to indicate +// that policy evaluation should stop immediately. +type Halt = v1.Halt + +// Error is the error type returned by the Eval and Query functions when +// an evaluation error occurs. +type Error = v1.Error + +const ( + + // InternalErr represents an unknown evaluation error. + InternalErr = v1.InternalErr + + // CancelErr indicates the evaluation process was cancelled. + CancelErr = v1.CancelErr + + // ConflictErr indicates a conflict was encountered during evaluation. For + // instance, a conflict occurs if a rule produces multiple, differing values + // for the same key in an object. Conflict errors indicate the policy does + // not account for the data loaded into the policy engine. + ConflictErr = v1.ConflictErr + + // TypeErr indicates evaluation stopped because an expression was applied to + // a value of an inappropriate type. + TypeErr = v1.TypeErr + + // BuiltinErr indicates a built-in function received a semantically invalid + // input or encountered some kind of runtime error, e.g., connection + // timeout, connection refused, etc. + BuiltinErr = v1.BuiltinErr + + // WithMergeErr indicates that the real and replacement data could not be merged. + WithMergeErr = v1.WithMergeErr +) + +// IsError returns true if the err is an Error. +func IsError(err error) bool { + return v1.IsError(err) +} + +// IsCancel returns true if err was caused by cancellation. +func IsCancel(err error) bool { + return v1.IsCancel(err) +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/graphql.go b/vendor/github.com/open-policy-agent/opa/topdown/graphql.go new file mode 100644 index 00000000000..0d6ebda0a87 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/graphql.go @@ -0,0 +1,485 @@ +// Copyright 2022 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package topdown + +import ( + "encoding/json" + "fmt" + "strings" + + gqlast "github.com/open-policy-agent/opa/internal/gqlparser/ast" + gqlparser "github.com/open-policy-agent/opa/internal/gqlparser/parser" + gqlvalidator "github.com/open-policy-agent/opa/internal/gqlparser/validator" + + // Side-effecting import. Triggers GraphQL library's validation rule init() functions. + _ "github.com/open-policy-agent/opa/internal/gqlparser/validator/rules" + + "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/topdown/builtins" +) + +// Parses a GraphQL schema, and returns the GraphQL AST for the schema. +func parseSchema(schema string) (*gqlast.SchemaDocument, error) { + // NOTE(philipc): We don't include the "built-in schema defs" from the + // underlying graphql parsing library here, because those definitions + // generate enormous AST blobs. In the future, if there is demand for + // a "full-spec" version of schema ASTs, we may need to provide a + // version of this function that includes the built-in schema + // definitions. + schemaAST, err := gqlparser.ParseSchema(&gqlast.Source{Input: schema}) + if err != nil { + errorParts := strings.SplitN(err.Error(), ":", 4) + msg := strings.TrimLeft(errorParts[3], " ") + return nil, fmt.Errorf("%s in GraphQL string at location %s:%s", msg, errorParts[1], errorParts[2]) + } + return schemaAST, nil +} + +// Parses a GraphQL query, and returns the GraphQL AST for the query. +func parseQuery(query string) (*gqlast.QueryDocument, error) { + queryAST, err := gqlparser.ParseQuery(&gqlast.Source{Input: query}) + if err != nil { + errorParts := strings.SplitN(err.Error(), ":", 4) + msg := strings.TrimLeft(errorParts[3], " ") + return nil, fmt.Errorf("%s in GraphQL string at location %s:%s", msg, errorParts[1], errorParts[2]) + } + return queryAST, nil +} + +// Validates a GraphQL query against a schema, and returns an error. +// In this case, we get a wrappered error list type, and pluck out +// just the first error message in the list. +func validateQuery(schema *gqlast.Schema, query *gqlast.QueryDocument) error { + // Validate the query against the schema, erroring if there's an issue. + err := gqlvalidator.Validate(schema, query) + if err != nil { + // We use strings.TrimSuffix to remove the '.' characters that the library + // authors include on most of their validation errors. This should be safe, + // since variable names in their error messages are usually quoted, and + // this affects only the last character(s) in the string. + // NOTE(philipc): We know the error location will be in the query string, + // because schema validation always happens before this function is called. + errorParts := strings.SplitN(err.Error(), ":", 4) + msg := strings.TrimSuffix(strings.TrimLeft(errorParts[3], " "), ".\n") + return fmt.Errorf("%s in GraphQL query string at location %s:%s", msg, errorParts[1], errorParts[2]) + } + return nil +} + +func getBuiltinSchema() *gqlast.SchemaDocument { + schema, err := gqlparser.ParseSchema(gqlvalidator.Prelude) + if err != nil { + panic(fmt.Errorf("Error in gqlparser Prelude (should be impossible): %w", err)) + } + return schema +} + +// NOTE(philipc): This function expects *validated* schema documents, and will break +// if it is fed arbitrary structures. +func mergeSchemaDocuments(docA *gqlast.SchemaDocument, docB *gqlast.SchemaDocument) *gqlast.SchemaDocument { + ast := &gqlast.SchemaDocument{} + ast.Merge(docA) + ast.Merge(docB) + return ast +} + +// Converts a SchemaDocument into a gqlast.Schema object that can be used for validation. +// It merges in the builtin schema typedefs exactly as gqltop.LoadSchema did internally. +func convertSchema(schemaDoc *gqlast.SchemaDocument) (*gqlast.Schema, error) { + // Merge builtin schema + schema we were provided. + builtinsSchemaDoc := getBuiltinSchema() + mergedSchemaDoc := mergeSchemaDocuments(builtinsSchemaDoc, schemaDoc) + schema, err := gqlvalidator.ValidateSchemaDocument(mergedSchemaDoc) + if err != nil { + return nil, fmt.Errorf("Error in gqlparser SchemaDocument to Schema conversion: %w", err) + } + return schema, nil +} + +// Converts an ast.Object into a gqlast.QueryDocument object. +func objectToQueryDocument(value ast.Object) (*gqlast.QueryDocument, error) { + // Convert ast.Term to interface{} for JSON encoding below. + asJSON, err := ast.JSON(value) + if err != nil { + return nil, err + } + // Marshal to JSON. + bs, err := json.Marshal(asJSON) + if err != nil { + return nil, err + } + // Unmarshal from JSON -> gqlast.QueryDocument. + var result gqlast.QueryDocument + err = json.Unmarshal(bs, &result) + if err != nil { + return nil, err + } + return &result, nil +} + +// Converts an ast.Object into a gqlast.SchemaDocument object. +func objectToSchemaDocument(value ast.Object) (*gqlast.SchemaDocument, error) { + // Convert ast.Term to interface{} for JSON encoding below. + asJSON, err := ast.JSON(value) + if err != nil { + return nil, err + } + // Marshal to JSON. + bs, err := json.Marshal(asJSON) + if err != nil { + return nil, err + } + // Unmarshal from JSON -> gqlast.SchemaDocument. + var result gqlast.SchemaDocument + err = json.Unmarshal(bs, &result) + if err != nil { + return nil, err + } + return &result, nil +} + +// Recursively traverses an AST that has been run through InterfaceToValue, +// and prunes away the fields with null or empty values, and all `Position` +// structs. +// NOTE(philipc): We currently prune away null values to reduce the level +// of clutter in the returned AST objects. In the future, if there is demand +// for ASTs that have a more regular/fixed structure, we may need to provide +// a "raw" version of the AST, where we still prune away the `Position` +// structs, but leave in the null fields. +func pruneIrrelevantGraphQLASTNodes(value ast.Value) ast.Value { + // We iterate over the Value we've been provided, and recurse down + // in the case of complex types, such as Arrays/Objects. + // We are guaranteed to only have to deal with standard JSON types, + // so this is much less ugly than what we'd need for supporting every + // extant ast type! + switch x := value.(type) { + case *ast.Array: + result := ast.NewArray() + // Iterate over the array's elements, and do the following: + // - Drop any Nulls + // - Drop any any empty object/array value (after running the pruner) + for i := 0; i < x.Len(); i++ { + vTerm := x.Elem(i) + switch v := vTerm.Value.(type) { + case ast.Null: + continue + case *ast.Array: + // Safe, because we knew the type before going to prune it. + va := pruneIrrelevantGraphQLASTNodes(v).(*ast.Array) + if va.Len() > 0 { + result = result.Append(ast.NewTerm(va)) + } + case ast.Object: + // Safe, because we knew the type before going to prune it. + vo := pruneIrrelevantGraphQLASTNodes(v).(ast.Object) + if len(vo.Keys()) > 0 { + result = result.Append(ast.NewTerm(vo)) + } + default: + result = result.Append(vTerm) + } + } + return result + case ast.Object: + result := ast.NewObject() + // Iterate over our object's keys, and do the following: + // - Drop "Position". + // - Drop any key with a Null value. + // - Drop any key with an empty object/array value (after running the pruner) + keys := x.Keys() + for _, k := range keys { + // We drop the "Position" objects because we don't need the + // source-backref/location info they provide for policy rules. + // Note that keys are ast.Strings. + if ast.String("Position").Equal(k.Value) { + continue + } + vTerm := x.Get(k) + switch v := vTerm.Value.(type) { + case ast.Null: + continue + case *ast.Array: + // Safe, because we knew the type before going to prune it. + va := pruneIrrelevantGraphQLASTNodes(v).(*ast.Array) + if va.Len() > 0 { + result.Insert(k, ast.NewTerm(va)) + } + case ast.Object: + // Safe, because we knew the type before going to prune it. + vo := pruneIrrelevantGraphQLASTNodes(v).(ast.Object) + if len(vo.Keys()) > 0 { + result.Insert(k, ast.NewTerm(vo)) + } + default: + result.Insert(k, vTerm) + } + } + return result + default: + return x + } +} + +// Reports errors from parsing/validation. +func builtinGraphQLParse(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + var queryDoc *gqlast.QueryDocument + var schemaDoc *gqlast.SchemaDocument + var err error + + // Parse/translate query if it's a string/object. + switch x := operands[0].Value.(type) { + case ast.String: + queryDoc, err = parseQuery(string(x)) + case ast.Object: + queryDoc, err = objectToQueryDocument(x) + default: + // Error if wrong type. + return builtins.NewOperandTypeErr(0, x, "string", "object") + } + if err != nil { + return err + } + + // Parse/translate schema if it's a string/object. + switch x := operands[1].Value.(type) { + case ast.String: + schemaDoc, err = parseSchema(string(x)) + case ast.Object: + schemaDoc, err = objectToSchemaDocument(x) + default: + // Error if wrong type. + return builtins.NewOperandTypeErr(1, x, "string", "object") + } + if err != nil { + return err + } + + // Transform the ASTs into Objects. + queryASTValue, err := ast.InterfaceToValue(queryDoc) + if err != nil { + return err + } + schemaASTValue, err := ast.InterfaceToValue(schemaDoc) + if err != nil { + return err + } + + // Validate the query against the schema, erroring if there's an issue. + schema, err := convertSchema(schemaDoc) + if err != nil { + return err + } + if err := validateQuery(schema, queryDoc); err != nil { + return err + } + + // Recursively remove irrelevant AST structures. + queryResult := pruneIrrelevantGraphQLASTNodes(queryASTValue.(ast.Object)) + querySchema := pruneIrrelevantGraphQLASTNodes(schemaASTValue.(ast.Object)) + + // Construct return value. + verified := ast.ArrayTerm( + ast.NewTerm(queryResult), + ast.NewTerm(querySchema), + ) + + return iter(verified) +} + +// Returns default value when errors occur. +func builtinGraphQLParseAndVerify(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + var queryDoc *gqlast.QueryDocument + var schemaDoc *gqlast.SchemaDocument + var err error + + unverified := ast.ArrayTerm( + ast.InternedBooleanTerm(false), + ast.NewTerm(ast.NewObject()), + ast.NewTerm(ast.NewObject()), + ) + + // Parse/translate query if it's a string/object. + switch x := operands[0].Value.(type) { + case ast.String: + queryDoc, err = parseQuery(string(x)) + case ast.Object: + queryDoc, err = objectToQueryDocument(x) + default: + // Error if wrong type. + return iter(unverified) + } + if err != nil { + return iter(unverified) + } + + // Parse/translate schema if it's a string/object. + switch x := operands[1].Value.(type) { + case ast.String: + schemaDoc, err = parseSchema(string(x)) + case ast.Object: + schemaDoc, err = objectToSchemaDocument(x) + default: + // Error if wrong type. + return iter(unverified) + } + if err != nil { + return iter(unverified) + } + + // Transform the ASTs into Objects. + queryASTValue, err := ast.InterfaceToValue(queryDoc) + if err != nil { + return iter(unverified) + } + schemaASTValue, err := ast.InterfaceToValue(schemaDoc) + if err != nil { + return iter(unverified) + } + + // Validate the query against the schema, erroring if there's an issue. + schema, err := convertSchema(schemaDoc) + if err != nil { + return iter(unverified) + } + if err := validateQuery(schema, queryDoc); err != nil { + return iter(unverified) + } + + // Recursively remove irrelevant AST structures. + queryResult := pruneIrrelevantGraphQLASTNodes(queryASTValue.(ast.Object)) + querySchema := pruneIrrelevantGraphQLASTNodes(schemaASTValue.(ast.Object)) + + // Construct return value. + verified := ast.ArrayTerm( + ast.InternedBooleanTerm(true), + ast.NewTerm(queryResult), + ast.NewTerm(querySchema), + ) + + return iter(verified) +} + +func builtinGraphQLParseQuery(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + raw, err := builtins.StringOperand(operands[0].Value, 1) + if err != nil { + return err + } + + // Get the highly-nested AST struct, along with any errors generated. + query, err := parseQuery(string(raw)) + if err != nil { + return err + } + + // Transform the AST into an Object. + value, err := ast.InterfaceToValue(query) + if err != nil { + return err + } + + // Recursively remove irrelevant AST structures. + result := pruneIrrelevantGraphQLASTNodes(value.(ast.Object)) + + return iter(ast.NewTerm(result)) +} + +func builtinGraphQLParseSchema(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + raw, err := builtins.StringOperand(operands[0].Value, 1) + if err != nil { + return err + } + + // Get the highly-nested AST struct, along with any errors generated. + schema, err := parseSchema(string(raw)) + if err != nil { + return err + } + + // Transform the AST into an Object. + value, err := ast.InterfaceToValue(schema) + if err != nil { + return err + } + + // Recursively remove irrelevant AST structures. + result := pruneIrrelevantGraphQLASTNodes(value.(ast.Object)) + + return iter(ast.NewTerm(result)) +} + +func builtinGraphQLIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + var queryDoc *gqlast.QueryDocument + var schemaDoc *gqlast.SchemaDocument + var err error + + switch x := operands[0].Value.(type) { + case ast.String: + queryDoc, err = parseQuery(string(x)) + case ast.Object: + queryDoc, err = objectToQueryDocument(x) + default: + // Error if wrong type. + return iter(ast.InternedBooleanTerm(false)) + } + if err != nil { + return iter(ast.InternedBooleanTerm(false)) + } + + switch x := operands[1].Value.(type) { + case ast.String: + schemaDoc, err = parseSchema(string(x)) + case ast.Object: + schemaDoc, err = objectToSchemaDocument(x) + default: + // Error if wrong type. + return iter(ast.InternedBooleanTerm(false)) + } + if err != nil { + return iter(ast.InternedBooleanTerm(false)) + } + + // Validate the query against the schema, erroring if there's an issue. + schema, err := convertSchema(schemaDoc) + if err != nil { + return iter(ast.InternedBooleanTerm(false)) + } + if err := validateQuery(schema, queryDoc); err != nil { + return iter(ast.InternedBooleanTerm(false)) + } + + // If we got this far, the GraphQL query passed validation. + return iter(ast.InternedBooleanTerm(true)) +} + +func builtinGraphQLSchemaIsValid(_ BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error { + var schemaDoc *gqlast.SchemaDocument + var err error + + switch x := operands[0].Value.(type) { + case ast.String: + schemaDoc, err = parseSchema(string(x)) + case ast.Object: + schemaDoc, err = objectToSchemaDocument(x) + default: + // Error if wrong type. + return iter(ast.InternedBooleanTerm(false)) + } + if err != nil { + return iter(ast.InternedBooleanTerm(false)) + } + + // Validate the schema, this determines the result + _, err = convertSchema(schemaDoc) + return iter(ast.InternedBooleanTerm(err == nil)) +} + +func init() { + RegisterBuiltinFunc(ast.GraphQLParse.Name, builtinGraphQLParse) + RegisterBuiltinFunc(ast.GraphQLParseAndVerify.Name, builtinGraphQLParseAndVerify) + RegisterBuiltinFunc(ast.GraphQLParseQuery.Name, builtinGraphQLParseQuery) + RegisterBuiltinFunc(ast.GraphQLParseSchema.Name, builtinGraphQLParseSchema) + RegisterBuiltinFunc(ast.GraphQLIsValid.Name, builtinGraphQLIsValid) + RegisterBuiltinFunc(ast.GraphQLSchemaIsValid.Name, builtinGraphQLSchemaIsValid) +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/http.go b/vendor/github.com/open-policy-agent/opa/topdown/http.go new file mode 100644 index 00000000000..693ea4048c4 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/http.go @@ -0,0 +1,17 @@ +// Copyright 2018 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package topdown + +import ( + v1 "github.com/open-policy-agent/opa/v1/topdown" +) + +const ( + // HTTPSendInternalErr represents a runtime evaluation error. + HTTPSendInternalErr = v1.HTTPSendInternalErr + + // HTTPSendNetworkErr represents a network error. + HTTPSendNetworkErr = v1.HTTPSendNetworkErr +) diff --git a/vendor/github.com/open-policy-agent/opa/topdown/instrumentation.go b/vendor/github.com/open-policy-agent/opa/topdown/instrumentation.go new file mode 100644 index 00000000000..845f8da612d --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/instrumentation.go @@ -0,0 +1,21 @@ +// Copyright 2018 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package topdown + +import ( + "github.com/open-policy-agent/opa/v1/metrics" + v1 "github.com/open-policy-agent/opa/v1/topdown" +) + +// Instrumentation implements helper functions to instrument query evaluation +// to diagnose performance issues. Instrumentation may be expensive in some +// cases, so it is disabled by default. +type Instrumentation = v1.Instrumentation + +// NewInstrumentation returns a new Instrumentation object. Performance +// diagnostics recorded on this Instrumentation object will stored in m. +func NewInstrumentation(m metrics.Metrics) *Instrumentation { + return v1.NewInstrumentation(m) +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/print.go b/vendor/github.com/open-policy-agent/opa/topdown/print.go new file mode 100644 index 00000000000..5eacd180d99 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/print.go @@ -0,0 +1,16 @@ +// Copyright 2021 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package topdown + +import ( + "io" + + "github.com/open-policy-agent/opa/topdown/print" + v1 "github.com/open-policy-agent/opa/v1/topdown" +) + +func NewPrintHook(w io.Writer) print.Hook { + return v1.NewPrintHook(w) +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/print/doc.go b/vendor/github.com/open-policy-agent/opa/topdown/print/doc.go new file mode 100644 index 00000000000..c2ee0eca7fd --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/print/doc.go @@ -0,0 +1,8 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package print diff --git a/vendor/github.com/open-policy-agent/opa/topdown/print/print.go b/vendor/github.com/open-policy-agent/opa/topdown/print/print.go new file mode 100644 index 00000000000..66ffbb176f4 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/print/print.go @@ -0,0 +1,14 @@ +package print + +import ( + v1 "github.com/open-policy-agent/opa/v1/topdown/print" +) + +// Context provides the Hook implementation context about the print() call. +type Context = v1.Context + +// Hook defines the interface that callers can implement to receive print +// statement outputs. If the hook returns an error, it will be surfaced if +// strict builtin error checking is enabled (otherwise, it will not halt +// execution.) +type Hook = v1.Hook diff --git a/vendor/github.com/open-policy-agent/opa/topdown/query.go b/vendor/github.com/open-policy-agent/opa/topdown/query.go new file mode 100644 index 00000000000..d24060991f0 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/query.go @@ -0,0 +1,24 @@ +package topdown + +import ( + "github.com/open-policy-agent/opa/v1/ast" + v1 "github.com/open-policy-agent/opa/v1/topdown" +) + +// QueryResultSet represents a collection of results returned by a query. +type QueryResultSet = v1.QueryResultSet + +// QueryResult represents a single result returned by a query. The result +// contains bindings for all variables that appear in the query. +type QueryResult = v1.QueryResult + +// Query provides a configurable interface for performing query evaluation. +type Query = v1.Query + +// Builtin represents a built-in function that queries can call. +type Builtin = v1.Builtin + +// NewQuery returns a new Query object that can be run. +func NewQuery(query ast.Body) *Query { + return v1.NewQuery(query) +} diff --git a/vendor/github.com/open-policy-agent/opa/topdown/trace.go b/vendor/github.com/open-policy-agent/opa/topdown/trace.go new file mode 100644 index 00000000000..4d4cc295e26 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/topdown/trace.go @@ -0,0 +1,112 @@ +// Copyright 2016 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package topdown + +import ( + "io" + + v1 "github.com/open-policy-agent/opa/v1/topdown" +) + +// Op defines the types of tracing events. +type Op = v1.Op + +const ( + // EnterOp is emitted when a new query is about to be evaluated. + EnterOp = v1.EnterOp + + // ExitOp is emitted when a query has evaluated to true. + ExitOp = v1.ExitOp + + // EvalOp is emitted when an expression is about to be evaluated. + EvalOp = v1.EvalOp + + // RedoOp is emitted when an expression, rule, or query is being re-evaluated. + RedoOp = v1.RedoOp + + // SaveOp is emitted when an expression is saved instead of evaluated + // during partial evaluation. + SaveOp = v1.SaveOp + + // FailOp is emitted when an expression evaluates to false. + FailOp = v1.FailOp + + // DuplicateOp is emitted when a query has produced a duplicate value. The search + // will stop at the point where the duplicate was emitted and backtrack. + DuplicateOp = v1.DuplicateOp + + // NoteOp is emitted when an expression invokes a tracing built-in function. + NoteOp = v1.NoteOp + + // IndexOp is emitted during an expression evaluation to represent lookup + // matches. + IndexOp = v1.IndexOp + + // WasmOp is emitted when resolving a ref using an external + // Resolver. + WasmOp = v1.WasmOp + + // UnifyOp is emitted when two terms are unified. Node will be set to an + // equality expression with the two terms. This Node will not have location + // info. + UnifyOp = v1.UnifyOp + FailedAssertionOp = v1.FailedAssertionOp +) + +// VarMetadata provides some user facing information about +// a variable in some policy. +type VarMetadata = v1.VarMetadata + +// Event contains state associated with a tracing event. +type Event = v1.Event + +// Tracer defines the interface for tracing in the top-down evaluation engine. +// Deprecated: Use QueryTracer instead. +type Tracer = v1.Tracer + +// QueryTracer defines the interface for tracing in the top-down evaluation engine. +// The implementation can provide additional configuration to modify the tracing +// behavior for query evaluations. +type QueryTracer = v1.QueryTracer + +// TraceConfig defines some common configuration for Tracer implementations +type TraceConfig = v1.TraceConfig + +// WrapLegacyTracer will create a new QueryTracer which wraps an +// older Tracer instance. +func WrapLegacyTracer(tracer Tracer) QueryTracer { + return v1.WrapLegacyTracer(tracer) +} + +// BufferTracer implements the Tracer and QueryTracer interface by +// simply buffering all events received. +type BufferTracer = v1.BufferTracer + +// NewBufferTracer returns a new BufferTracer. +func NewBufferTracer() *BufferTracer { + return v1.NewBufferTracer() +} + +// PrettyTrace pretty prints the trace to the writer. +func PrettyTrace(w io.Writer, trace []*Event) { + v1.PrettyTrace(w, trace) +} + +// PrettyTraceWithLocation prints the trace to the writer and includes location information +func PrettyTraceWithLocation(w io.Writer, trace []*Event) { + v1.PrettyTraceWithLocation(w, trace) +} + +type PrettyTraceOptions = v1.PrettyTraceOptions + +func PrettyTraceWithOpts(w io.Writer, trace []*Event, opts PrettyTraceOptions) { + v1.PrettyTraceWithOpts(w, trace, opts) +} + +type PrettyEventOpts = v1.PrettyEventOpts + +func PrettyEvent(w io.Writer, e *Event, opts PrettyEventOpts) error { + return v1.PrettyEvent(w, e, opts) +} diff --git a/vendor/github.com/open-policy-agent/opa/types/decode.go b/vendor/github.com/open-policy-agent/opa/types/decode.go new file mode 100644 index 00000000000..ae04b38ff4e --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/types/decode.go @@ -0,0 +1,14 @@ +// Copyright 2020 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +package types + +import ( + v1 "github.com/open-policy-agent/opa/v1/types" +) + +// Unmarshal deserializes bs and returns the resulting type. +func Unmarshal(bs []byte) (result Type, err error) { + return v1.Unmarshal(bs) +} diff --git a/vendor/github.com/open-policy-agent/opa/types/doc.go b/vendor/github.com/open-policy-agent/opa/types/doc.go new file mode 100644 index 00000000000..bfa068e66b6 --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/types/doc.go @@ -0,0 +1,8 @@ +// Copyright 2024 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Deprecated: This package is intended for older projects transitioning from OPA v0.x and will remain for the lifetime of OPA v1.x, but its use is not recommended. +// For newer features and behaviours, such as defaulting to the Rego v1 syntax, use the corresponding components in the [github.com/open-policy-agent/opa/v1] package instead. +// See https://www.openpolicyagent.org/docs/latest/v0-compatibility/ for more information. +package types diff --git a/vendor/github.com/open-policy-agent/opa/types/types.go b/vendor/github.com/open-policy-agent/opa/types/types.go new file mode 100644 index 00000000000..b888b27b60e --- /dev/null +++ b/vendor/github.com/open-policy-agent/opa/types/types.go @@ -0,0 +1,200 @@ +// Copyright 2017 The OPA Authors. All rights reserved. +// Use of this source code is governed by an Apache2 +// license that can be found in the LICENSE file. + +// Package types declares data types for Rego values and helper functions to +// operate on these types. +package types + +import ( + v1 "github.com/open-policy-agent/opa/v1/types" +) + +// Sprint returns the string representation of the type. +func Sprint(x Type) string { + return v1.Sprint(x) +} + +// Type represents a type of a term in the language. +type Type = v1.Type + +// Null represents the null type. +type Null = v1.Null + +// NewNull returns a new Null type. +func NewNull() Null { + return v1.NewNull() +} + +// NamedType represents a type alias with an arbitrary name and description. +// This is useful for generating documentation for built-in functions. +type NamedType = v1.NamedType + +// Named returns the passed type as a named type. +// Named types are only valid at the top level of built-in functions. +// Note that nested named types cause panic. +func Named(name string, t Type) *NamedType { + return v1.Named(name, t) +} + +// Boolean represents the boolean type. +type Boolean = v1.Boolean + +// B represents an instance of the boolean type. +var B = NewBoolean() + +// NewBoolean returns a new Boolean type. +func NewBoolean() Boolean { + return v1.NewBoolean() +} + +// String represents the string type. +type String = v1.String + +// S represents an instance of the string type. +var S = NewString() + +// NewString returns a new String type. +func NewString() String { + return v1.NewString() +} + +// Number represents the number type. +type Number = v1.Number + +// N represents an instance of the number type. +var N = NewNumber() + +// NewNumber returns a new Number type. +func NewNumber() Number { + return v1.NewNumber() +} + +// Array represents the array type. +type Array = v1.Array + +// NewArray returns a new Array type. +func NewArray(static []Type, dynamic Type) *Array { + return v1.NewArray(static, dynamic) +} + +// Set represents the set type. +type Set = v1.Set + +// NewSet returns a new Set type. +func NewSet(of Type) *Set { + return v1.NewSet(of) +} + +// StaticProperty represents a static object property. +type StaticProperty = v1.StaticProperty + +// NewStaticProperty returns a new StaticProperty object. +func NewStaticProperty(key interface{}, value Type) *StaticProperty { + return v1.NewStaticProperty(key, value) +} + +// DynamicProperty represents a dynamic object property. +type DynamicProperty = v1.DynamicProperty + +// NewDynamicProperty returns a new DynamicProperty object. +func NewDynamicProperty(key, value Type) *DynamicProperty { + return v1.NewDynamicProperty(key, value) +} + +// Object represents the object type. +type Object = v1.Object + +// NewObject returns a new Object type. +func NewObject(static []*StaticProperty, dynamic *DynamicProperty) *Object { + return v1.NewObject(static, dynamic) +} + +// Any represents a dynamic type. +type Any = v1.Any + +// A represents the superset of all types. +var A = NewAny() + +// NewAny returns a new Any type. +func NewAny(of ...Type) Any { + return v1.NewAny(of...) +} + +// Function represents a function type. +type Function = v1.Function + +// Args returns an argument list. +func Args(x ...Type) []Type { + return v1.Args(x...) +} + +// Void returns true if the function has no return value. This function returns +// false if x is not a function. +func Void(x Type) bool { + return v1.Void(x) +} + +// Arity returns the number of arguments in the function signature or zero if x +// is not a function. If the type is unknown, this function returns -1. +func Arity(x Type) int { + return v1.Arity(x) +} + +// NewFunction returns a new Function object of the given argument and result types. +func NewFunction(args []Type, result Type) *Function { + return v1.NewFunction(args, result) +} + +// NewVariadicFunction returns a new Function object. This function sets the +// variadic bit on the signature. Non-void variadic functions are not currently +// supported. +func NewVariadicFunction(args []Type, varargs Type, result Type) *Function { + return v1.NewVariadicFunction(args, varargs, result) +} + +// FuncArgs represents the arguments that can be passed to a function. +type FuncArgs = v1.FuncArgs + +// Compare returns -1, 0, 1 based on comparison between a and b. +func Compare(a, b Type) int { + return v1.Compare(a, b) +} + +// Contains returns true if a is a superset or equal to b. +func Contains(a, b Type) bool { + return v1.Contains(a, b) +} + +// Or returns a type that represents the union of a and b. If one type is a +// superset of the other, the superset is returned unchanged. +func Or(a, b Type) Type { + return v1.Or(a, b) +} + +// Select returns a property or item of a. +func Select(a Type, x interface{}) Type { + return v1.Select(a, x) +} + +// Keys returns the type of keys that can be enumerated for a. For arrays, the +// keys are always number types, for objects the keys are always string types, +// and for sets the keys are always the type of the set element. +func Keys(a Type) Type { + return v1.Keys(a) +} + +// Values returns the type of values that can be enumerated for a. +func Values(a Type) Type { + return v1.Values(a) +} + +// Nil returns true if a's type is unknown. +func Nil(a Type) bool { + return v1.Nil(a) +} + +// TypeOf returns the type of the Golang native value. +func TypeOf(x interface{}) Type { + return v1.TypeOf(x) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 6b06a935ad7..34952332235 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -425,7 +425,7 @@ github.com/onsi/gomega/types # github.com/open-policy-agent/cert-controller v0.11.0 ## explicit; go 1.22.0 github.com/open-policy-agent/cert-controller/pkg/rotator -# github.com/open-policy-agent/frameworks/constraint v0.0.0-20250115145356-9e57a5775c15 => github.com/sozercan/frameworks/constraint v0.0.0-20250123183526-62279e78b9a5 +# github.com/open-policy-agent/frameworks/constraint v0.0.0-20250115145356-9e57a5775c15 => github.com/sozercan/frameworks/constraint v0.0.0-20250123191509-ea09dbab7e9d ## explicit; go 1.22.7 github.com/open-policy-agent/frameworks/constraint/deploy github.com/open-policy-agent/frameworks/constraint/pkg/apis @@ -453,7 +453,11 @@ github.com/open-policy-agent/frameworks/constraint/pkg/schema github.com/open-policy-agent/frameworks/constraint/pkg/types # github.com/open-policy-agent/opa v1.0.1 ## explicit; go 1.22.7 +github.com/open-policy-agent/opa/ast +github.com/open-policy-agent/opa/ast/json +github.com/open-policy-agent/opa/bundle github.com/open-policy-agent/opa/capabilities +github.com/open-policy-agent/opa/format github.com/open-policy-agent/opa/internal/bundle github.com/open-policy-agent/opa/internal/cidr/merge github.com/open-policy-agent/opa/internal/compiler @@ -505,6 +509,13 @@ github.com/open-policy-agent/opa/internal/wasm/opcode github.com/open-policy-agent/opa/internal/wasm/sdk/opa/capabilities github.com/open-policy-agent/opa/internal/wasm/types github.com/open-policy-agent/opa/internal/wasm/util +github.com/open-policy-agent/opa/loader +github.com/open-policy-agent/opa/rego +github.com/open-policy-agent/opa/storage +github.com/open-policy-agent/opa/storage/inmem +github.com/open-policy-agent/opa/topdown +github.com/open-policy-agent/opa/topdown/print +github.com/open-policy-agent/opa/types github.com/open-policy-agent/opa/v1/ast github.com/open-policy-agent/opa/v1/ast/internal/scanner github.com/open-policy-agent/opa/v1/ast/internal/tokens @@ -1633,4 +1644,4 @@ sigs.k8s.io/structured-merge-diff/v4/value ## explicit; go 1.12 sigs.k8s.io/yaml sigs.k8s.io/yaml/goyaml.v2 -# github.com/open-policy-agent/frameworks/constraint => github.com/sozercan/frameworks/constraint v0.0.0-20250123183526-62279e78b9a5 +# github.com/open-policy-agent/frameworks/constraint => github.com/sozercan/frameworks/constraint v0.0.0-20250123191509-ea09dbab7e9d