diff --git a/build/generate-cli-docs/generate.go b/build/generate-cli-docs/generate.go index b58b8de01b..1612adcab7 100644 --- a/build/generate-cli-docs/generate.go +++ b/build/generate-cli-docs/generate.go @@ -1,125 +1,98 @@ package main import ( - "bufio" - "fmt" + "encoding/json" "log" "os" - "path/filepath" - "regexp" "strings" - "github.com/spf13/cobra/doc" + "github.com/spf13/cobra" + "github.com/spf13/pflag" "github.com/open-policy-agent/opa/cmd" ) -const fileHeader = `--- -title: CLI -kind: documentation -weight: 90 -restrictedtoc: true ---- - -The OPA executable provides the following commands. Note that command line arguments may either be provided as -traditional flags, or as environment variables. The expected format of environment variables used for this purpose -follows the pattern OPA__ where COMMAND is the command name in uppercase (like EVAL) and FLAG is the -flag name in uppercase (like STRICT), i.e. OPA_EVAL_STRICT would be equivalent to passing the --strict flag to the -eval command. - -` - func main() { - if len(os.Args) != 2 { - log.Fatal("Required argument: cli docs output directory") - } - out := os.Args[1] - command := cmd.RootCommand command.Use = "opa [command]" command.DisableAutoGenTag = true - dir, err := os.MkdirTemp("", "opa") - if err != nil { - log.Fatal(err) - } - defer os.RemoveAll(dir) + cmdData := make([]map[string]any, 0) - err = doc.GenMarkdownTree(command, dir) - if err != nil { - log.Fatal(err) //nolint: gocritic - } - - files, err := os.ReadDir(dir) - if err != nil { - log.Fatal(err) - } - - builder := strings.Builder{} - - last := len(files) - 1 - for i, file := range files { - // Skip the first "opa" document as it's rather pointless to include (only shows the --help flag) - if i == 0 { + for _, c := range command.Commands() { + if !showCommand(c) { continue } - path := filepath.Join(dir, file.Name()) - document, err := fixupSection(path) - if err != nil { - log.Fatal(err) - } - builder.WriteString(document) - if i != last { - builder.WriteString("____\n\n") - } + + cmdData = append(cmdData, cmdToData(c)) } - heading := regexp.MustCompile(`^[\\-]+$`) - lines := strings.Split(builder.String(), "\n") - document := make([]string, 0, len(lines)) - removed := 0 - - // The document may contain "----" for headings, which will be converted to h1 - // elements in markdown. This is undesirable, so let's remove them and prepend - // the line before that with ### to instead create a h3 - for line, str := range lines { - if heading.MatchString(str) { - document[line-1-removed] = fmt.Sprintf("### %s\n", document[line-1-removed]) - removed++ - continue - } - document = append(document, str+"\n") - } - - withHeader := fmt.Sprintf("%s%s", fileHeader, strings.Join(document, "")) - err = os.WriteFile(filepath.Join(out, "cli.md"), []byte(withHeader), 0755) + err := json.NewEncoder(os.Stdout).Encode(cmdData) if err != nil { log.Fatal(err) } } -func fixupSection(path string) (string, error) { - f, err := os.Open(path) - if err != nil { - return "", err - } - defer f.Close() - - scanner := bufio.NewScanner(f) - builder := strings.Builder{} - - for scanner.Scan() { - line := scanner.Text() - // Remove "See also" section - if strings.Contains(line, "### SEE ALSO") { - break - } - if home := os.Getenv("HOME"); home != "" { - line = strings.ReplaceAll(line, home, "$HOME") - } - builder.WriteString(line) - builder.WriteString("\n") +func showCommand(c *cobra.Command) bool { + if !c.IsAvailableCommand() || + c.IsAdditionalHelpTopicCommand() || + c.Hidden { + return false } - return builder.String(), scanner.Err() + return true +} + +func cmdToID(c *cobra.Command) string { + parts := strings.Split(c.Use, " ") + + if len(parts) == 0 { + return "" + } + + return parts[0] +} + +func extractFlags(flagSet *pflag.FlagSet) []map[string]any { + var result []map[string]any + + flagSet.VisitAll(func(f *pflag.Flag) { + flagInfo := map[string]any{ + "name": "--" + f.Name, + "shorthand": "", + "type": f.Value.Type(), + "default": f.DefValue, + "description": f.Usage, + } + + if f.Shorthand != "" { + flagInfo["shorthand"] = "-" + f.Shorthand + } + + result = append(result, flagInfo) + }) + + return result +} + +func cmdToData(c *cobra.Command) map[string]any { + childData := make([]map[string]any, 0) + for _, childCmd := range c.Commands() { + if !showCommand(childCmd) { + continue + } + childData = append(childData, cmdToData(childCmd)) + } + + return map[string]any{ + "id": cmdToID(c), + "use": c.Use, + "useline": c.UseLine(), + "short": c.Short, + "long": c.Long, + "example": c.Example, + "flags": extractFlags(c.NonInheritedFlags()), + "parent_flags": extractFlags(c.InheritedFlags()), + "children": childData, + } } diff --git a/cmd/check.go b/cmd/check.go index 13bf7225b0..e4492d89d8 100644 --- a/cmd/check.go +++ b/cmd/check.go @@ -169,9 +169,9 @@ func init() { Short: "Check Rego source files", Long: `Check Rego source files for parse and compilation errors. - If the 'check' command succeeds in parsing and compiling the source file(s), no output - is produced. If the parsing or compiling fails, 'check' will output the errors - and exit with a non-zero exit code.`, +If the 'check' command succeeds in parsing and compiling the source file(s), no output +is produced. If the parsing or compiling fails, 'check' will output the errors +and exit with a non-zero exit code.`, PreRunE: func(cmd *cobra.Command, args []string) error { if len(args) == 0 { diff --git a/cmd/deps.go b/cmd/deps.go index dba62cdeec..e82db8dc85 100644 --- a/cmd/deps.go +++ b/cmd/deps.go @@ -57,7 +57,6 @@ func newDepsCommandParams() depsCommandParams { } func init() { - params := newDepsCommandParams() depsCommand := &cobra.Command{ @@ -67,9 +66,9 @@ func init() { Dependencies are categorized as either base documents, which is any data loaded from the outside world, or virtual documents, i.e values that are computed from rules. +`, -Example -------- + Example: ` Given a policy like this: package policy @@ -117,7 +116,6 @@ data.policy.is_admin. } func deps(args []string, params depsCommandParams, w io.Writer) error { - query, err := ast.ParseBody(args[0]) if err != nil { return err diff --git a/cmd/eval.go b/cmd/eval.go index 4d5d4c9164..550bcf0084 100644 --- a/cmd/eval.go +++ b/cmd/eval.go @@ -35,9 +35,7 @@ import ( "github.com/open-policy-agent/opa/v1/util" ) -var ( - errIllegalUnknownsArg = errors.New("illegal argument with --unknowns, specify string with one or more --unknowns") -) +var errIllegalUnknownsArg = errors.New("illegal argument with --unknowns, specify string with one or more --unknowns") type evalCommandParams struct { capabilities *capabilitiesFlag @@ -114,7 +112,6 @@ func newEvalCommandParams() evalCommandParams { } func validateEvalParams(p *evalCommandParams, cmdArgs []string) error { - if len(cmdArgs) > 0 && p.stdin { return errors.New("specify query argument or --stdin but not both") } else if len(cmdArgs) == 0 && !p.stdin { @@ -193,16 +190,13 @@ func (regoError) Error() string { } func init() { - params := newEvalCommandParams() evalCommand := &cobra.Command{ Use: "eval ", Short: "Evaluate a Rego query", - Long: `Evaluate a Rego query and print the result. - -Examples --------- + Long: `Evaluate a Rego query and print the result.`, + Example: ` To evaluate a simple query: @@ -310,7 +304,6 @@ access. return env.CmdFlags.CheckEnvironmentVariables(cmd) }, Run: func(_ *cobra.Command, args []string) { - defined, err := eval(args, params, os.Stdout) if err != nil { if _, ok := err.(regoError); !ok { @@ -373,7 +366,6 @@ access. } func eval(args []string, params evalCommandParams, w io.Writer) (bool, error) { - ctx := context.Background() if params.timeout != 0 { var cancel func() @@ -523,7 +515,7 @@ func evalOnce(ctx context.Context, ectx *evalContext) pr.Output { } if ectx.params.profile { - var sortOrder = pr.DefaultProfileSortOrder + sortOrder := pr.DefaultProfileSortOrder if len(ectx.params.profileCriteria.v) != 0 { sortOrder = getProfileSortOrder(strings.Split(ectx.params.profileCriteria.String(), ",")) @@ -745,7 +737,6 @@ func (r *resettableProfiler) TraceEvent(ev topdown.Event) { r.p.TraceEvent(ev) } func (r *resettableProfiler) Config() topdown.TraceConfig { return r.p.Config() } func getProfileSortOrder(sortOrder []string) []string { - // convert the sort order slice to a map for faster lookups sortOrderMap := make(map[string]bool) for _, cr := range sortOrder { diff --git a/cmd/flags.go b/cmd/flags.go index 3998d706aa..7bc1af5f4f 100644 --- a/cmd/flags.go +++ b/cmd/flags.go @@ -102,7 +102,7 @@ func addSigningKeyFlag(fs *pflag.FlagSet, key *string) { } func addSigningPluginFlag(fs *pflag.FlagSet, plugin *string) { - fs.StringVarP(plugin, "signing-plugin", "", "", "name of the plugin to use for signing/verification (see https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-plugin") + fs.StringVarP(plugin, "signing-plugin", "", "", "name of the plugin to use for signing/verification (see https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-plugin)") } func addVerificationKeyFlag(fs *pflag.FlagSet, key *string) { @@ -228,7 +228,6 @@ func (f *capabilitiesFlag) Set(s string) error { return fmt.Errorf("no such file or capabilities version found: %v", s) } return nil - } type stringptrFlag struct { diff --git a/docs/Makefile b/docs/Makefile index 2b4c0d33e1..56610d2079 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -20,4 +20,4 @@ clean: .PHONY: generate-cli-docs generate-cli-docs: - $(CURDIR)/../build/gen-cli-docs.sh "$(CURDIR)/content" + $(CURDIR)/../build/gen-cli-docs.sh > $(CURDIR)/src/data/cli.json diff --git a/docs/content/cli.md b/docs/content/cli.md deleted file mode 100755 index 9fcc9ad871..0000000000 --- a/docs/content/cli.md +++ /dev/null @@ -1,1190 +0,0 @@ ---- -title: CLI -kind: documentation -weight: 90 -restrictedtoc: true ---- - -The OPA executable provides the following commands. Note that command line arguments may either be provided as -traditional flags, or as environment variables. The expected format of environment variables used for this purpose -follows the pattern OPA__ where COMMAND is the command name in uppercase (like EVAL) and FLAG is the -flag name in uppercase (like STRICT), i.e. OPA_EVAL_STRICT would be equivalent to passing the --strict flag to the -eval command. - -## opa bench - -Benchmark a Rego query - -### Synopsis - -Benchmark a Rego query and print the results. - -The benchmark command works very similar to 'eval' and will evaluate the query in the same fashion. The -evaluation will be repeated a number of times and performance results will be returned. - -Example with bundle and input data: - - opa bench -b ./policy-bundle -i input.json 'data.authz.allow' - -To run benchmarks against a running OPA server to evaluate server overhead use the --e2e flag. - -The optional "gobench" output format conforms to the Go Benchmark Data Format. - - -``` -opa bench [flags] -``` - -### Options - -``` - --benchmem report memory allocations with benchmark results (default true) - -b, --bundle string set bundle file(s) or directory path(s). This flag can be repeated. - -c, --config-file string set path of configuration file - --count int number of times to repeat each benchmark (default 1) - -d, --data string set policy or data file(s). This flag can be repeated. - --e2e run benchmarks against a running OPA server - --fail exits with non-zero exit code on undefined/empty result and errors (default true) - -f, --format {json,pretty,gobench} set output format (default pretty) - -h, --help help for bench - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) - --import string set query import(s). This flag can be repeated. - -i, --input string set input file path - --metrics report query performance metrics (default true) - --optimize-store-for-read-speed optimize default in-memory store for read speed. Has possible negative impact on memory footprint and write speed. See https://www.openpolicyagent.org/docs/latest/policy-performance/#storage-optimization for more details. - --package string set query package - -p, --partial perform partial evaluation - -s, --schema string set schema file path or directory path - --shutdown-grace-period int set the time (in seconds) that the server will wait to gracefully shut down. This flag is valid in 'e2e' mode only. (default 10) - --shutdown-wait-period int set the time (in seconds) that the server will wait before initiating shutdown. This flag is valid in 'e2e' mode only. - --stdin read query from stdin - -I, --stdin-input read input document from stdin - -t, --target {rego,wasm} set the runtime to exercise (default rego) - -u, --unknowns stringArray set paths to treat as unknown during partial evaluation (default [input]) - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release -``` - -____ - -## opa build - -Build an OPA bundle - -### Synopsis - -Build an OPA bundle. - -The 'build' command packages OPA policy and data files into bundles. Bundles are -gzipped tarballs containing policies and data. Paths referring to directories are -loaded recursively. - - $ ls - example.rego - - $ opa build -b . - -You can load bundles into OPA on the command-line: - - $ ls - bundle.tar.gz example.rego - - $ opa run bundle.tar.gz - -You can also configure OPA to download bundles from remote HTTP endpoints: - - $ opa run --server \ - --set bundles.example.resource=bundle.tar.gz \ - --set services.example.url=http://localhost:8080 - -Inside another terminal in the same directory, serve the bundle via HTTP: - - $ python3 -m http.server --bind localhost 8080 - -For more information on bundles see https://www.openpolicyagent.org/docs/latest/management-bundles/. - -### Common Flags - - -When -b is specified the 'build' command assumes paths refer to existing bundle files -or directories following the bundle structure. If multiple bundles are provided, their -contents are merged. If there are any merge conflicts (e.g., due to conflicting bundle -roots), the command fails. When loading an existing bundle file, the .manifest from -the input bundle will be included in the output bundle. Flags that set .manifest fields -(such as --revision) override input bundle .manifest fields. - -The -O flag controls the optimization level. By default, optimization is disabled (-O=0). -When optimization is enabled the 'build' command generates a bundle that is semantically -equivalent to the input files however the structure of the files in the bundle may have -been changed by rewriting, inlining, pruning, etc. Higher optimization levels may result -in longer build times. The --partial-namespace flag can used in conjunction with the -O flag -to specify the namespace for the partially evaluated files in the optimized bundle. - -The 'build' command supports targets (specified by -t): - - rego The default target emits a bundle containing a set of policy and data files - that are semantically equivalent to the input files. If optimizations are - disabled the output may simply contain a copy of the input policy and data - files. If optimization is enabled at least one entrypoint must be supplied, - either via the -e option, or via entrypoint metadata annotations. - - wasm The wasm target emits a bundle containing a WebAssembly module compiled from - the input files for each specified entrypoint. The bundle may contain the - original policy or data files. - - plan The plan target emits a bundle containing a plan, i.e., an intermediate - representation compiled from the input files for each specified entrypoint. - This is for further processing, OPA cannot evaluate a "plan bundle" like it - can evaluate a wasm or rego bundle. - -The -e flag tells the 'build' command which documents (entrypoints) will be queried by -the software asking for policy decisions, so that it can focus optimization efforts and -ensure that document is not eliminated by the optimizer. -Note: Unless the --prune-unused flag is used, any rule transitively referring to a -package or rule declared as an entrypoint will also be enumerated as an entrypoint. - -### Signing - - -The 'build' command can be used to verify the signature of a signed bundle and -also to generate a signature for the output bundle the command creates. - -If the directory path(s) provided to the 'build' command contain a ".signatures.json" file, -it will attempt to verify the signatures included in that file. The bundle files -or directory path(s) to verify must be specified using --bundle. - -For more information on the bundle signing and verification, see -https://www.openpolicyagent.org/docs/latest/management-bundles/#signing. - -Example: - - $ opa build --verification-key /path/to/public_key.pem --signing-key /path/to/private_key.pem --bundle foo - -Where foo has the following structure: - - foo/ - | - +-- bar/ - | | - | +-- data.json - | - +-- policy.rego - | - +-- .manifest - | - +-- .signatures.json - - -The 'build' command will verify the signatures using the public key provided by the --verification-key flag. -The default signing algorithm is RS256 and the --signing-alg flag can be used to specify -a different one. The --verification-key-id and --scope flags can be used to specify the name for the key -provided using the --verification-key flag and scope to use for bundle signature verification respectively. - -If the verification succeeds, the 'build' command will write out an updated ".signatures.json" file -to the output bundle. It will use the key specified by the --signing-key flag to sign -the token in the ".signatures.json" file. - -To include additional claims in the payload use the --claims-file flag to provide a JSON file -containing optional claims. - -For more information on the format of the ".signatures.json" file -see https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format. - -### Capabilities - - -The 'build' command can validate policies against a configurable set of OPA capabilities. -The capabilities define the built-in functions and other language features that policies -may depend on. For example, the following capabilities file only permits the policy to -depend on the "plus" built-in function ('+'): - - { - "builtins": [ - { - "name": "plus", - "infix": "+", - "decl": { - "type": "function", - "args": [ - { - "type": "number" - }, - { - "type": "number" - } - ], - "result": { - "type": "number" - } - } - } - ] - } - -Capabilities can be used to validate policies against a specific version of OPA. -The OPA repository contains a set of capabilities files for each OPA release. For example, -the following command builds a directory of policies ('./policies') and validates them -against OPA v0.22.0: - - opa build ./policies --capabilities v0.22.0 - - -``` -opa build [ [...]] [flags] -``` - -### Options - -``` - -b, --bundle load paths as bundle files or root directories - --capabilities string set capabilities version or capabilities.json file path - --claims-file string set path of JSON file containing optional claims (see: https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format) - --debug enable debug output - -e, --entrypoint string set slash separated entrypoint path - --exclude-files-verify strings set file names to exclude during bundle verification - --follow-symlinks follow symlinks in the input set of paths when building the bundle - -h, --help help for build - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) - -O, --optimize int set optimization level - -o, --output string set the output filename (default "bundle.tar.gz") - --partial-namespace string set the namespace to use for partially evaluated files in an optimized bundle (default "partial") - --prune-unused exclude dependents of entrypoints - -r, --revision string set output bundle revision - --scope string scope to use for bundle signature verification - --signing-alg string name of the signing algorithm (default "RS256") - --signing-key string set the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA) - --signing-plugin string name of the plugin to use for signing/verification (see https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-plugin - -t, --target {rego,wasm,plan} set the output bundle target type (default rego) - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --verification-key string set the secret (HMAC) or path of the PEM file containing the public key (RSA and ECDSA) - --verification-key-id string name assigned to the verification key used for bundle verification (default "default") - --wasm-include-print enable print statements inside of WebAssembly modules compiled by the compiler -``` - -____ - -## opa capabilities - -Print the capabilities of OPA - -### Synopsis - -Show capabilities for OPA. - -The 'capabilities' command prints the OPA capabilities, prior to and including the version of OPA used. - -Print a list of all existing capabilities version names - - $ opa capabilities - v0.17.0 - v0.17.1 - ... - v0.37.1 - v0.37.2 - v0.38.0 - ... - -Print the capabilities of the current version - - $ opa capabilities --current - { - "builtins": [...], - "future_keywords": [...], - "wasm_abi_versions": [...] - } - -Print the capabilities of a specific version - - $ opa capabilities --version v0.32.1 - { - "builtins": [...], - "future_keywords": null, - "wasm_abi_versions": [...] - } - -Print the capabilities of a capabilities file - - $ opa capabilities --file ./capabilities/v0.32.1.json - { - "builtins": [...], - "future_keywords": null, - "wasm_abi_versions": [...] - } - - - -``` -opa capabilities [flags] -``` - -### Options - -``` - --current print current capabilities - --file string print capabilities defined by a file - -h, --help help for capabilities - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --version string print capabilities of a specific version -``` - -____ - -## opa check - -Check Rego source files - -### Synopsis - -Check Rego source files for parse and compilation errors. - - If the 'check' command succeeds in parsing and compiling the source file(s), no output - is produced. If the parsing or compiling fails, 'check' will output the errors - and exit with a non-zero exit code. - -``` -opa check [path [...]] [flags] -``` - -### Options - -``` - -b, --bundle load paths as bundle files or root directories - --capabilities string set capabilities version or capabilities.json file path - -f, --format {pretty,json} set output format (default pretty) - -h, --help help for check - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) - -m, --max-errors int set the number of errors to allow before compilation fails early (default 10) - -s, --schema string set schema file path or directory path - -S, --strict enable compiler strict mode - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --v0-v1 check for Rego v0 and v1 compatibility (policies must be compatible with both Rego versions) -``` - -____ - -## opa deps - -Analyze Rego query dependencies - -### Synopsis - -Print dependencies of provided query. - -Dependencies are categorized as either base documents, which is any data loaded -from the outside world, or virtual documents, i.e values that are computed from rules. - -### Example - -Given a policy like this: - - package policy - - allow if is_admin - - is_admin if "admin" in input.user.roles - -To evaluate the dependencies of a simple query (e.g. data.policy.allow), -we'd run opa deps like demonstrated below: - - $ opa deps --data policy.rego data.policy.allow - +------------------+----------------------+ - | BASE DOCUMENTS | VIRTUAL DOCUMENTS | - +------------------+----------------------+ - | input.user.roles | data.policy.allow | - | | data.policy.is_admin | - +------------------+----------------------+ - -From the output we're able to determine that the allow rule depends on -the input.user.roles base document, as well as the virtual document (rule) -data.policy.is_admin. - - -``` -opa deps [flags] -``` - -### Options - -``` - -b, --bundle string set bundle file(s) or directory path(s). This flag can be repeated. - -d, --data string set policy or data file(s). This flag can be repeated. - -f, --format {pretty,json} set output format (default pretty) - -h, --help help for deps - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) -``` - -____ - -## opa eval - -Evaluate a Rego query - -### Synopsis - -Evaluate a Rego query and print the result. - -### Examples - - -To evaluate a simple query: - - $ opa eval 'x := 1; y := 2; x < y' - -To evaluate a query against JSON data: - - $ opa eval --data data.json 'name := data.names[_]' - -To evaluate a query against JSON data supplied with a file:// URL: - - $ opa eval --data file:///path/to/file.json 'data' - - -### File & Bundle Loading - - -The --bundle flag will load data files and Rego files contained -in the bundle specified by the path. It can be either a -compressed tar archive bundle file or a directory tree. - - $ opa eval --bundle /some/path 'data' - -Where /some/path contains: - - foo/ - | - +-- bar/ - | | - | +-- data.json - | - +-- baz.rego - | - +-- manifest.yaml - -The JSON file 'foo/bar/data.json' would be loaded and rooted under -'data.foo.bar' and the 'foo/baz.rego' would be loaded and rooted under the -package path contained inside the file. Only data files named data.json or -data.yaml will be loaded. In the example above the manifest.yaml would be -ignored. - -See https://www.openpolicyagent.org/docs/latest/management-bundles/ for more details -on bundle directory structures. - -The --data flag can be used to recursively load ALL *.rego, *.json, and -*.yaml files under the specified directory. - -The -O flag controls the optimization level. By default, optimization is disabled (-O=0). -When optimization is enabled the 'eval' command generates a bundle from the files provided -with either the --bundle or --data flag. This bundle is semantically equivalent to the input -files however the structure of the files in the bundle may have been changed by rewriting, inlining, -pruning, etc. This resulting optimized bundle is used to evaluate the query. If optimization is -enabled at least one entrypoint must be supplied, either via the -e option, or via entrypoint -metadata annotations. - -### Output Formats - - -Set the output format with the --format flag. - - --format=json : output raw query results as JSON - --format=values : output line separated JSON arrays containing expression values - --format=bindings : output line separated JSON objects containing variable bindings - --format=pretty : output query results in a human-readable format - --format=source : output partial evaluation results in a source format - --format=raw : output the values from query results in a scripting friendly format - --format=discard : output the result field as "discarded" when non-nil - -### Schema - - -The -s/--schema flag provides one or more JSON Schemas used to validate references to the input or data documents. -Loads a single JSON file, applying it to the input document; or all the schema files under the specified directory. - - $ opa eval --data policy.rego --input input.json --schema schema.json - $ opa eval --data policy.rego --input input.json --schema schemas/ - -### Capabilities - - -When passing a capabilities definition file via --capabilities, one can restrict which -hosts remote schema definitions can be retrieved from. For example, a capabilities.json -containing - - { - "builtins": [ ... ], - "allow_net": [ "kubernetesjsonschema.dev" ] - } - -would disallow fetching remote schemas from any host but "kubernetesjsonschema.dev". -Setting allow_net to an empty array would prohibit fetching any remote schemas. - -Not providing a capabilities file, or providing a file without an allow_net key, will -permit fetching remote schemas from any host. - -Note that the metaschemas http://json-schema.org/draft-04/schema, http://json-schema.org/draft-06/schema, -and http://json-schema.org/draft-07/schema, are always available, even without network -access. - - -``` -opa eval [flags] -``` - -### Options - -``` - -b, --bundle string set bundle file(s) or directory path(s). This flag can be repeated. - --capabilities string set capabilities version or capabilities.json file path - --count int number of times to repeat each benchmark (default 1) - --coverage report coverage - -d, --data string set policy or data file(s). This flag can be repeated. - --disable-early-exit disable 'early exit' optimizations - --disable-indexing disable indexing optimizations - --disable-inlining stringArray set paths of documents to exclude from inlining - -e, --entrypoint string set slash separated entrypoint path - --explain {off,full,notes,fails,debug} enable query explanations (default off) - --fail exits with non-zero exit code on undefined/empty result and errors - --fail-defined exits with non-zero exit code on defined/non-empty result and errors - -f, --format {json,values,bindings,pretty,source,raw,discard} set output format (default json) - -h, --help help for eval - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) - --import string set query import(s). This flag can be repeated. - -i, --input string set input file path - --instrument enable query instrumentation metrics (implies --metrics) - --metrics report query performance metrics - --nondeterminstic-builtins evaluate nondeterministic builtins (if all arguments are known) during partial eval - -O, --optimize int set optimization level - --optimize-store-for-read-speed optimize default in-memory store for read speed. Has possible negative impact on memory footprint and write speed. See https://www.openpolicyagent.org/docs/latest/policy-performance/#storage-optimization for more details. - --package string set query package - -p, --partial perform partial evaluation - --pretty-limit int set limit after which pretty output gets truncated (default 80) - --profile perform expression profiling - --profile-limit int set number of profiling results to show (default 10) - --profile-sort string set sort order of expression profiler results. Accepts: total_time_ns, num_eval, num_redo, num_gen_expr, file, line. This flag can be repeated. - -s, --schema string set schema file path or directory path - --shallow-inlining disable inlining of rules that depend on unknowns - --show-builtin-errors collect and return all encountered built-in errors, built in errors are not fatal - --stdin read query from stdin - -I, --stdin-input read input document from stdin - -S, --strict enable compiler strict mode - --strict-builtin-errors treat the first built-in function error encountered as fatal - -t, --target {rego,wasm} set the runtime to exercise (default rego) - --timeout duration set eval timeout (default unlimited) - -u, --unknowns stringArray set paths to treat as unknown during partial evaluation (default [input]) - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --var-values show local variable values in pretty trace output -``` - -____ - -## opa exec - -Execute against input files - -### Synopsis - -Execute against input files. - -The 'exec' command executes OPA against one or more input files. If the paths -refer to directories, OPA will execute against files contained inside those -directories, recursively. - -The 'exec' command accepts a --config-file/-c or series of --set options as -arguments. These options behave the same as way as 'opa run'. Since the 'exec' -command is intended to execute OPA in one-shot, the 'exec' command will -manually trigger plugins before and after policy execution: - -Before: Discovery -> Bundle -> Status -After: Decision Logs - -By default, the 'exec' command executes the "default decision" (specified in -the OPA configuration) against each input file. This can be overridden by -specifying the --decision argument and pointing at a specific policy decision, -e.g., opa exec --decision /foo/bar/baz ... - - -``` -opa exec [ [...]] [flags] -``` - -### Examples - -``` - Loading input from stdin: - generate exec [ [...]] --stdin-input [flags] - -``` - -### Options - -``` - -b, --bundle string set bundle file(s) or directory path(s). This flag can be repeated. - -c, --config-file string set path of configuration file - --decision string set decision to evaluate - --fail exits with non-zero exit code on undefined result and errors - --fail-defined exits with non-zero exit code on defined result and errors - --fail-non-empty exits with non-zero exit code on non-empty result and errors - -f, --format {json} set output format (default json) - -h, --help help for exec - --log-format {text,json,json-pretty} set log format (default json) - -l, --log-level {debug,info,error} set log level (default error) - --log-timestamp-format string set log timestamp format (OPA_LOG_TIMESTAMP_FORMAT environment variable) - --set stringArray override config values on the command line (use commas to specify multiple values) - --set-file stringArray override config values with files on the command line (use commas to specify multiple values) - -I, --stdin-input read input document from stdin rather than a static file - --timeout duration set exec timeout with a Go-style duration, such as '5m 30s'. (default unlimited) - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release -``` - -____ - -## opa fmt - -Format Rego source files - -### Synopsis - -Format Rego source files. - -The 'fmt' command takes a Rego source file and outputs a reformatted version. If no file path -is provided - this tool will use stdin. -The format of the output is not defined specifically; whatever this tool outputs -is considered correct format (with the exception of bugs). - -If the '-w' option is supplied, the 'fmt' command will overwrite the source file -instead of printing to stdout. - -If the '-d' option is supplied, the 'fmt' command will output a diff between the -original and formatted source. - -If the '-l' option is supplied, the 'fmt' command will output the names of files -that would change if formatted. The '-l' option will suppress any other output -to stdout from the 'fmt' command. - -If the '--fail' option is supplied, the 'fmt' command will return a non zero exit -code if a file would be reformatted. - -The 'fmt' command can be run in several compatibility modes for consuming and outputting -different Rego versions: - -* `opa fmt`: - * v1 Rego is formatted to v1 - * `rego.v1`/`future.keywords` imports are NOT removed - * `rego.v1`/`future.keywords` imports are NOT added if missing - * v0 rego is rejected -* `opa fmt --v0-compatible`: - * v0 Rego is formatted to v0 - * v1 Rego is rejected -* `opa fmt --v0-v1`: - * v0 Rego is formatted to be compatible with v0 AND v1 - * v1 Rego is rejected -* `opa fmt --v0-v1 --v1-compatible`: - * v1 Rego is formatted to be compatible with v0 AND v1 - * v0 Rego is rejected - - -``` -opa fmt [path [...]] [flags] -``` - -### Options - -``` - --check-result assert that the formatted code is valid and can be successfully parsed (default true) - -d, --diff only display a diff of the changes - --drop-v0-imports drop v0 imports from the formatted code, such as 'rego.v1' and 'future.keywords' - --fail non zero exit code on reformat - -h, --help help for fmt - -l, --list list all files who would change when formatted - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --v0-v1 format module(s) to be compatible with both Rego v0 and v1 - -w, --write overwrite the original source file -``` - -____ - -## opa inspect - -Inspect OPA bundle(s) or Rego files. - -### Synopsis - -Inspect OPA bundle(s) or Rego files. - -The 'inspect' command provides a summary of the contents in OPA bundle(s) or a single Rego file. Bundles are -gzipped tarballs containing policies and data. The 'inspect' command reads bundle(s) and lists -the following: - -* packages that are contributed by .rego files -* data locations defined by the data.json and data.yaml files -* manifest data -* signature data -* information about the Wasm module files -* package- and rule annotations - -Example: - - $ ls - bundle.tar.gz - $ opa inspect bundle.tar.gz - -You can provide exactly one OPA bundle, path to a bundle directory, or direct path to a Rego file to the 'inspect' command -on the command-line. If you provide a path referring to a directory, the 'inspect' command will load that path as a bundle -and summarize its structure and contents. If you provide a path referring to a Rego file, the 'inspect' command will load -that file and summarize its structure and contents. - - -``` -opa inspect [ [...]] [flags] -``` - -### Options - -``` - -a, --annotations list annotations - -f, --format {json,pretty} set output format (default pretty) - -h, --help help for inspect - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release -``` - -____ - -## opa parse - -Parse Rego source file - -### Synopsis - -Parse Rego source file and print AST. - -``` -opa parse [flags] -``` - -### Options - -``` - -f, --format {pretty,json} set output format (default pretty) - -h, --help help for parse - --json-include string include or exclude optional elements. By default comments are included. Current options: locations, comments. E.g. --json-include locations,-comments will include locations and exclude comments. -``` - -____ - -## opa run - -Start OPA in interactive or server mode - -### Synopsis - -Start an instance of the Open Policy Agent (OPA). - -To run the interactive shell: - - $ opa run - -To run the server: - - $ opa run -s - -The 'run' command starts an instance of the OPA runtime. The OPA runtime can be -started as an interactive shell or a server. - -When the runtime is started as a shell, users can define rules and evaluate -expressions interactively. When the runtime is started as a server, OPA exposes -an HTTP API for managing policies, reading and writing data, and executing -queries. - -The runtime can be initialized with one or more files that contain policies or -data. If the '--bundle' option is specified the paths will be treated as policy -bundles and loaded following standard bundle conventions. The path can be a -compressed archive file or a directory which will be treated as a bundle. -Without the '--bundle' flag OPA will recursively load ALL rego, JSON, and YAML -files. - -When loading from directories, only files with known extensions are considered. -The current set of file extensions that OPA will consider are: - - .json # JSON data - .yaml or .yml # YAML data - .rego # Rego file - -Non-bundle data file and directory paths can be prefixed with the desired -destination in the data document with the following syntax: - - : - -To set a data file as the input document in the interactive shell use the -"repl.input" path prefix with the input file: - - repl.input: - -Example: - - $ opa run repl.input:input.json - -Which will load the "input.json" file at path "data.repl.input". - -Use the "help input" command in the interactive shell to see more options. - - -File paths can be specified as URLs to resolve ambiguity in paths containing colons: - - $ opa run file:///c:/path/to/data.json - -URL paths to remote public bundles (http or https) will be parsed as shorthand -configuration equivalent of using repeated --set flags to accomplish the same: - - $ opa run -s https://example.com/bundles/bundle.tar.gz - -The above shorthand command is identical to: - - $ opa run -s --set "services.cli1.url=https://example.com" \ - --set "bundles.cli1.service=cli1" \ - --set "bundles.cli1.resource=/bundles/bundle.tar.gz" \ - --set "bundles.cli1.persist=true" - -The 'run' command can also verify the signature of a signed bundle. -A signed bundle is a normal OPA bundle that includes a file -named ".signatures.json". For more information on signed bundles -see https://www.openpolicyagent.org/docs/latest/management-bundles/#signing. - -The key to verify the signature of signed bundle can be provided -using the --verification-key flag. For example, for RSA family of algorithms, -the command expects a PEM file containing the public key. -For HMAC family of algorithms (eg. HS256), the secret can be provided -using the --verification-key flag. - -The --verification-key-id flag can be used to optionally specify a name for the -key provided using the --verification-key flag. - -The --signing-alg flag can be used to specify the signing algorithm. -The 'run' command uses RS256 (by default) as the signing algorithm. - -The --scope flag can be used to specify the scope to use for -bundle signature verification. - -Example: - - $ opa run --verification-key secret --signing-alg HS256 --bundle bundle.tar.gz - -The 'run' command will read the bundle "bundle.tar.gz", check the -".signatures.json" file and perform verification using the provided key. -An error will be generated if "bundle.tar.gz" does not contain a ".signatures.json" file. -For more information on the bundle verification process see -https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-verification. - -The 'run' command can ONLY be used with the --bundle flag to verify signatures -for existing bundle files or directories following the bundle structure. - -To skip bundle verification, use the --skip-verify flag. - -The --watch flag can be used to monitor policy and data file-system changes. When a change is detected, the updated policy -and data is reloaded into OPA. Watching individual files (rather than directories) is generally not recommended as some -updates might cause them to be dropped by OPA. - -OPA will automatically perform type checking based on a schema inferred from known input documents and report any errors -resulting from the schema check. Currently this check is performed on OPA's Authorization Policy Input document and will -be expanded in the future. To disable this, use the --skip-known-schema-check flag. - -The --v0-compatible flag can be used to opt-in to OPA features and behaviors that were the default in OPA v0.x. -Behaviors enabled by this flag include: -- setting OPA's listening address to ":8181" by default, corresponding to listening on every network interface. -- expecting v0 Rego syntax in policy modules instead of the default v1 Rego syntax. - -The --tls-cipher-suites flag can be used to specify the list of enabled TLS 1.0–1.2 cipher suites. Note that TLS 1.3 -cipher suites are not configurable. Following are the supported TLS 1.0 - 1.2 cipher suites (IANA): -TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, -TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, -TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, -TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, -TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, -TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 - -See https://godoc.org/crypto/tls#pkg-constants for more information. - - -``` -opa run [flags] -``` - -### Options - -``` - -a, --addr strings set listening address of the server (e.g., [ip]: for TCP, unix:// for UNIX domain socket) (default [localhost:8181]) - --authentication {token,tls,off} set authentication scheme (default off) - --authorization {basic,off} set authorization scheme (default off) - -b, --bundle load paths as bundle files or root directories - -c, --config-file string set path of configuration file - --diagnostic-addr strings set read-only diagnostic listening address of the server for /health and /metric APIs (e.g., [ip]: for TCP, unix:// for UNIX domain socket) - --disable-telemetry disables anonymous information reporting (see: https://www.openpolicyagent.org/docs/latest/privacy) - --exclude-files-verify strings set file names to exclude during bundle verification - -f, --format string set shell output format, i.e, pretty, json (default "pretty") - --h2c enable H2C for HTTP listeners - -h, --help help for run - -H, --history string set path of history file (default "$HOME/.opa_history") - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) - --log-format {text,json,json-pretty} set log format (default json) - -l, --log-level {debug,info,error} set log level (default info) - --log-timestamp-format string set log timestamp format (OPA_LOG_TIMESTAMP_FORMAT environment variable) - -m, --max-errors int set the number of errors to allow before compilation fails early (default 10) - --min-tls-version {1.0,1.1,1.2,1.3} set minimum TLS version to be used by OPA's server (default 1.2) - --optimize-store-for-read-speed optimize default in-memory store for read speed. Has possible negative impact on memory footprint and write speed. See https://www.openpolicyagent.org/docs/latest/policy-performance/#storage-optimization for more details. - --pprof enables pprof endpoints - --ready-timeout int wait (in seconds) for configured plugins before starting server (value <= 0 disables ready check) - --scope string scope to use for bundle signature verification - -s, --server start the runtime in server mode - --set stringArray override config values on the command line (use commas to specify multiple values) - --set-file stringArray override config values with files on the command line (use commas to specify multiple values) - --shutdown-grace-period int set the time (in seconds) that the server will wait to gracefully shut down (default 10) - --shutdown-wait-period int set the time (in seconds) that the server will wait before initiating shutdown - --signing-alg string name of the signing algorithm (default "RS256") - --skip-known-schema-check disables type checking on known input schemas - --skip-verify disables bundle signature verification - --tls-ca-cert-file string set path of TLS CA cert file - --tls-cert-file string set path of TLS certificate file - --tls-cert-refresh-period duration set certificate refresh period - --tls-cipher-suites strings set list of enabled TLS 1.0–1.2 cipher suites (IANA) - --tls-private-key-file string set path of TLS private key file - --unix-socket-perm string specify the permissions for the Unix domain socket if used to listen for incoming connections (default "755") - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --verification-key string set the secret (HMAC) or path of the PEM file containing the public key (RSA and ECDSA) - --verification-key-id string name assigned to the verification key used for bundle verification (default "default") - -w, --watch watch command line files for changes -``` - -____ - -## opa sign - -Generate an OPA bundle signature - -### Synopsis - -Generate an OPA bundle signature. - -The 'sign' command generates a digital signature for policy bundles. It generates a -".signatures.json" file that dictates which files should be included in the bundle, -what their SHA hashes are, and is cryptographically secure. - -The signatures file is a JSON file with an array containing a single JSON Web Token (JWT) -that encapsulates the signature for the bundle. - -The --signing-alg flag can be used to specify the algorithm to sign the token. The 'sign' -command uses RS256 (by default) as the signing algorithm. -See https://www.openpolicyagent.org/docs/latest/configuration/#keys -for a list of supported signing algorithms. - -The key to be used for signing the JWT MUST be provided using the --signing-key flag. -For example, for RSA family of algorithms, the command expects a PEM file containing -the private key. -For HMAC family of algorithms (eg. HS256), the secret can be provided using -the --signing-key flag. - -OPA 'sign' can ONLY be used with the --bundle flag to load paths that refer to -existing bundle files or directories following the bundle structure. - - $ opa sign --signing-key /path/to/private_key.pem --bundle foo - -Where foo has the following structure: - - foo/ - | - +-- bar/ - | | - | +-- data.json - | - +-- policy.rego - | - +-- .manifest - -This will create a ".signatures.json" file in the current directory. -The --output-file-path flag can be used to specify a different location for -the ".signatures.json" file. - -The content of the ".signatures.json" file is shown below: - - { - "signatures": [ - "eyJhbGciOiJSUzI1NiJ9.eyJmaWxlcyI6W3sibmFtZSI6Ii5tYW5pZmVzdCIsImhhc2giOiIxODc0NWRlNzJjMDFlODBjZDlmNTIwZjQxOGMwMDlhYzRkMmMzZDAyYjE3YTUwZTJkMDQyMTU4YmMzNTJhMzJkIiwiYWxnb3JpdGhtIjoiU0hBLTI1NiJ9LHsibmFtZSI6ImJhci9kYXRhLmpzb24iLCJoYXNoIjoiOTNhMjM5NzFhOTE0ZTVlYWNiZjBhOGQyNTE1NGNkYTMwOWMzYzFjNzJmYmI5OTE0ZDQ3YzYwZjNjYjY4MTU4OCIsImFsZ29yaXRobSI6IlNIQS0yNTYifSx7Im5hbWUiOiJwb2xpY3kucmVnbyIsImhhc2giOiJkMGYyNDJhYWUzNGRiNTRlZjU2NmJlYTRkNDVmY2YxOTcwMGM1ZDhmODdhOWRiOTMyZGZhZDZkMWYwZjI5MWFjIiwiYWxnb3JpdGhtIjoiU0hBLTI1NiJ9XX0.lNsmRqrmT1JI4Z_zpY6IzHRZQAU306PyOjZ6osquixPuTtdSBxgbsdKDcp7Civw3B77BgygVsvx4k3fYr8XCDKChm0uYKScrpFr9_yS6g5mVTQws3KZncZXCQHdupRFoqMS8vXAVgJr52C83AinYWABwH2RYq_B0ZPf_GDzaMgzpep9RlDNecGs57_4zlyxmP2ESU8kjfX8jAA6rYFKeGXJHMD-j4SassoYIzYRv9YkHx8F8Y2ae5Kd5M24Ql0kkvqc_4eO_T9s4nbQ4q5qGHGE-91ND1KVn2avcUyVVPc0-XCR7EH8HnHgCl0v1c7gX1RL7ET7NJbPzfmzQAzk0ZW0dEHI4KZnXSpqy8m-3zAc8kIARm2QwoNEWpy3MWiooPeZVSa9d5iw1aLrbyumfjBP0vCQEPes-Aa6PrARwd5jR9SacO5By0-4emzskvJYRZqbfJ9tXSXDMcAFOAm6kqRPJaj8AO4CyajTC_Lt32_0OLeXqYgNpt3HDqLqGjrb-8fVeQc-hKh0aES8XehQqXj4jMwfsTyj5alsXZm08LwzcFlfQZ7s1kUtmr0_BBNJYcdZUdlu6Qio3LFSRYXNuu6edAO1VH5GKqZISvE1uvDZb2E0Z-rtH-oPp1iSpfvsX47jKJ42LVpI6OahEBri44dzHOIwwm3CIuV8gFzOwR0k" - ] - } - -And the decoded JWT payload has the following form: - - { - "files": [ - { - "name": ".manifest", - "hash": "18745de72c01e80cd9f520f418c009ac4d2c3d02b17a50e2d042158bc352a32d", - "algorithm": "SHA-256" - }, - { - "name": "policy.rego", - "hash": "d0f242aae34db54ef566bea4d45fcf19700c5d8f87a9db932dfad6d1f0f291ac", - "algorithm": "SHA-256" - }, - { - "name": "bar/data.json", - "hash": "93a23971a914e5eacbf0a8d25154cda309c3c1c72fbb9914d47c60f3cb681588", - "algorithm": "SHA-256" - } - ] - } - -The "files" field is generated from the files under the directory path(s) -provided to the 'sign' command. During bundle signature verification, OPA will check -each file name (ex. "foo/bar/data.json") in the "files" field -exists in the actual bundle. The file content is hashed using SHA256. - -To include additional claims in the payload use the --claims-file flag to provide -a JSON file containing optional claims. - -For more information on the format of the ".signatures.json" file see -https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format. - - -``` -opa sign [ [...]] [flags] -``` - -### Options - -``` - -b, --bundle load paths as bundle files or root directories - --claims-file string set path of JSON file containing optional claims (see: https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format) - -h, --help help for sign - -o, --output-file-path string set the location for the .signatures.json file (default ".") - --signing-alg string name of the signing algorithm (default "RS256") - --signing-key string set the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA) - --signing-plugin string name of the plugin to use for signing/verification (see https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-plugin -``` - -____ - -## opa test - -Execute Rego test cases - -### Synopsis - -Execute Rego test cases. - -The 'test' command takes a file or directory path as input and executes all -test cases discovered in matching files. Test cases are rules whose names have the prefix "test_". - -If the '--bundle' option is specified the paths will be treated as policy bundles -and loaded following standard bundle conventions. The path can be a compressed archive -file or a directory which will be treated as a bundle. Without the '--bundle' flag OPA -will recursively load ALL *.rego, *.json, and *.yaml files for evaluating the test cases. - -Test cases under development may be prefixed "todo_" in order to skip their execution, -while still getting marked as skipped in the test results. - -Example policy (example/authz.rego): - - package authz - - allow if { - input.path == ["users"] - input.method == "POST" - } - - allow if { - input.path == ["users", input.user_id] - input.method == "GET" - } - -Example test (example/authz_test.rego): - - package authz_test - - import data.authz.allow - - test_post_allowed if { - allow with input as {"path": ["users"], "method": "POST"} - } - - test_get_denied if { - not allow with input as {"path": ["users"], "method": "GET"} - } - - test_get_user_allowed if { - allow with input as {"path": ["users", "bob"], "method": "GET", "user_id": "bob"} - } - - test_get_another_user_denied if { - not allow with input as {"path": ["users", "bob"], "method": "GET", "user_id": "alice"} - } - - todo_test_user_allowed_http_client_data if { - false # Remember to test this later! - } - -Example test run: - - $ opa test ./example/ - -If used with the '--bench' option then tests will be benchmarked. - -Example benchmark run: - - $ opa test --bench ./example/ - -The optional "gobench" output format conforms to the Go Benchmark Data Format. - -The --watch flag can be used to monitor policy and data file-system changes. When a change is detected, OPA reloads -the policy and data and then re-runs the tests. Watching individual files (rather than directories) is generally not -recommended as some updates might cause them to be dropped by OPA. - - -``` -opa test [path [...]] [flags] -``` - -### Options - -``` - --bench benchmark the unit tests - --benchmem report memory allocations with benchmark results (default true) - -b, --bundle load paths as bundle files or root directories - --capabilities string set capabilities version or capabilities.json file path - --count int number of times to repeat each test (default 1) - -c, --coverage report coverage (overrides debug tracing) - -z, --exit-zero-on-skipped skipped tests return status 0 - --explain {fails,full,notes,debug} enable query explanations (default fails) - -f, --format {pretty,json,gobench} set output format (default pretty) - -h, --help help for test - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) - -m, --max-errors int set the number of errors to allow before compilation fails early (default 10) - -r, --run string run only test cases matching the regular expression. - -s, --schema string set schema file path or directory path - -t, --target {rego,wasm} set the runtime to exercise (default rego) - --threshold float set coverage threshold and exit with non-zero status if coverage is less than threshold % - --timeout duration set test timeout (default 5s, 30s when benchmarking) - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --var-values show local variable values in test output - -v, --verbose set verbose reporting mode - -w, --watch watch command line files for changes -``` - -____ - -## opa version - -Print the version of OPA - -### Synopsis - -Show version and build information for OPA. - -``` -opa version [flags] -``` - -### Options - -``` - -c, --check check for latest OPA release - -h, --help help for version -``` - - diff --git a/docs/docs/cli.md b/docs/docs/cli.md old mode 100755 new mode 100644 index 730fb3755c..426f57b776 --- a/docs/docs/cli.md +++ b/docs/docs/cli.md @@ -1,1193 +1,20 @@ --- title: CLI -sidebar_position: 11 --- -The OPA executable provides the following commands. Note that command line arguments may either be provided as -traditional flags, or as environment variables. The expected format of environment variables used for this purpose -follows the pattern `OPA__` where COMMAND is the command name in uppercase (like EVAL) and FLAG is the -flag name in uppercase (like STRICT), i.e. OPA_EVAL_STRICT would be equivalent to passing the --strict flag to the -eval command. - -## opa bench - -Benchmark a Rego query - -### Synopsis - -Benchmark a Rego query and print the results. - -The benchmark command works very similar to 'eval' and will evaluate the query in the same fashion. The -evaluation will be repeated a number of times and performance results will be returned. - -Example with bundle and input data: - - opa bench -b ./policy-bundle -i input.json 'data.authz.allow' - -To run benchmarks against a running OPA server to evaluate server overhead use the --e2e flag. - -The optional "gobench" output format conforms to the Go Benchmark Data Format. - -``` -opa bench [flags] -``` - -### Options - -``` - --benchmem report memory allocations with benchmark results (default true) --b, --bundle string set bundle file(s) or directory path(s). This flag can be repeated. --c, --config-file string set path of configuration file - --count int number of times to repeat each benchmark (default 1) --d, --data string set policy or data file(s). This flag can be repeated. - --e2e run benchmarks against a running OPA server - --fail exits with non-zero exit code on undefined/empty result and errors (default true) --f, --format {json,pretty,gobench} set output format (default pretty) --h, --help help for bench - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) - --import string set query import(s). This flag can be repeated. --i, --input string set input file path - --metrics report query performance metrics (default true) - --optimize-store-for-read-speed optimize default in-memory store for read speed. Has possible negative impact on memory footprint and write speed. See https://www.openpolicyagent.org/docs/latest/policy-performance/#storage-optimization for more details. - --package string set query package --p, --partial perform partial evaluation --s, --schema string set schema file path or directory path - --shutdown-grace-period int set the time (in seconds) that the server will wait to gracefully shut down. This flag is valid in 'e2e' mode only. (default 10) - --shutdown-wait-period int set the time (in seconds) that the server will wait before initiating shutdown. This flag is valid in 'e2e' mode only. - --stdin read query from stdin --I, --stdin-input read input document from stdin --t, --target {rego,wasm} set the runtime to exercise (default rego) --u, --unknowns stringArray set paths to treat as unknown during partial evaluation (default [input]) - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release -``` - ---- - -## opa build - -Build an OPA bundle - -### Synopsis - -Build an OPA bundle. - -The 'build' command packages OPA policy and data files into bundles. Bundles are -gzipped tarballs containing policies and data. Paths referring to directories are -loaded recursively. - - $ ls - example.rego - - $ opa build -b . - -You can load bundles into OPA on the command-line: - - $ ls - bundle.tar.gz example.rego - - $ opa run bundle.tar.gz - -You can also configure OPA to download bundles from remote HTTP endpoints: - - $ opa run --server \ - --set bundles.example.resource=bundle.tar.gz \ - --set services.example.url=http://localhost:8080 - -Inside another terminal in the same directory, serve the bundle via HTTP: - - $ python3 -m http.server --bind localhost 8080 - -For more information on bundles see https://www.openpolicyagent.org/docs/latest/management-bundles/. - -### Common Flags - -When -b is specified the 'build' command assumes paths refer to existing bundle files -or directories following the bundle structure. If multiple bundles are provided, their -contents are merged. If there are any merge conflicts (e.g., due to conflicting bundle -roots), the command fails. When loading an existing bundle file, the .manifest from -the input bundle will be included in the output bundle. Flags that set .manifest fields -(such as --revision) override input bundle .manifest fields. - -The -O flag controls the optimization level. By default, optimization is disabled (-O=0). -When optimization is enabled the 'build' command generates a bundle that is semantically -equivalent to the input files however the structure of the files in the bundle may have -been changed by rewriting, inlining, pruning, etc. Higher optimization levels may result -in longer build times. The --partial-namespace flag can used in conjunction with the -O flag -to specify the namespace for the partially evaluated files in the optimized bundle. - -The 'build' command supports targets (specified by -t): - - rego The default target emits a bundle containing a set of policy and data files - that are semantically equivalent to the input files. If optimizations are - disabled the output may simply contain a copy of the input policy and data - files. If optimization is enabled at least one entrypoint must be supplied, - either via the -e option, or via entrypoint metadata annotations. - - wasm The wasm target emits a bundle containing a WebAssembly module compiled from - the input files for each specified entrypoint. The bundle may contain the - original policy or data files. - - plan The plan target emits a bundle containing a plan, i.e., an intermediate - representation compiled from the input files for each specified entrypoint. - This is for further processing, OPA cannot evaluate a "plan bundle" like it - can evaluate a wasm or rego bundle. - -The -e flag tells the 'build' command which documents (entrypoints) will be queried by -the software asking for policy decisions, so that it can focus optimization efforts and -ensure that document is not eliminated by the optimizer. -Note: Unless the --prune-unused flag is used, any rule transitively referring to a -package or rule declared as an entrypoint will also be enumerated as an entrypoint. - -### Signing - -The 'build' command can be used to verify the signature of a signed bundle and -also to generate a signature for the output bundle the command creates. - -If the directory path(s) provided to the 'build' command contain a ".signatures.json" file, -it will attempt to verify the signatures included in that file. The bundle files -or directory path(s) to verify must be specified using --bundle. - -For more information on the bundle signing and verification, see -https://www.openpolicyagent.org/docs/latest/management-bundles/#signing. - -Example: - - $ opa build --verification-key /path/to/public_key.pem --signing-key /path/to/private_key.pem --bundle foo - -Where foo has the following structure: - - foo/ - | - +-- bar/ - | | - | +-- data.json - | - +-- policy.rego - | - +-- .manifest - | - +-- .signatures.json - -The 'build' command will verify the signatures using the public key provided by the --verification-key flag. -The default signing algorithm is RS256 and the --signing-alg flag can be used to specify -a different one. The --verification-key-id and --scope flags can be used to specify the name for the key -provided using the --verification-key flag and scope to use for bundle signature verification respectively. - -If the verification succeeds, the 'build' command will write out an updated ".signatures.json" file -to the output bundle. It will use the key specified by the --signing-key flag to sign -the token in the ".signatures.json" file. - -To include additional claims in the payload use the --claims-file flag to provide a JSON file -containing optional claims. - -For more information on the format of the ".signatures.json" file -see https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format. - -### Capabilities - -The 'build' command can validate policies against a configurable set of OPA capabilities. -The capabilities define the built-in functions and other language features that policies -may depend on. For example, the following capabilities file only permits the policy to -depend on the "plus" built-in function ('+'): - -``` -{ - "builtins": [ - { - "name": "plus", - "infix": "+", - "decl": { - "type": "function", - "args": [ - { - "type": "number" - }, - { - "type": "number" - } - ], - "result": { - "type": "number" - } - } - } - ] -} -``` - -Capabilities can be used to validate policies against a specific version of OPA. -The OPA repository contains a set of capabilities files for each OPA release. For example, -the following command builds a directory of policies ('./policies') and validates them -against OPA v0.22.0: - - opa build ./policies --capabilities v0.22.0 - -``` -opa build [ [...]] [flags] -``` - -### Options - -``` --b, --bundle load paths as bundle files or root directories - --capabilities string set capabilities version or capabilities.json file path - --claims-file string set path of JSON file containing optional claims (see: https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format) - --debug enable debug output --e, --entrypoint string set slash separated entrypoint path - --exclude-files-verify strings set file names to exclude during bundle verification - --follow-symlinks follow symlinks in the input set of paths when building the bundle --h, --help help for build - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) --O, --optimize int set optimization level --o, --output string set the output filename (default "bundle.tar.gz") - --partial-namespace string set the namespace to use for partially evaluated files in an optimized bundle (default "partial") - --prune-unused exclude dependents of entrypoints --r, --revision string set output bundle revision - --scope string scope to use for bundle signature verification - --signing-alg string name of the signing algorithm (default "RS256") - --signing-key string set the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA) - --signing-plugin string name of the plugin to use for signing/verification (see https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-plugin --t, --target {rego,wasm,plan} set the output bundle target type (default rego) - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --verification-key string set the secret (HMAC) or path of the PEM file containing the public key (RSA and ECDSA) - --verification-key-id string name assigned to the verification key used for bundle verification (default "default") - --wasm-include-print enable print statements inside of WebAssembly modules compiled by the compiler -``` - ---- - -## opa capabilities - -Print the capabilities of OPA - -### Synopsis - -Show capabilities for OPA. - -The 'capabilities' command prints the OPA capabilities, prior to and including the version of OPA used. - -Print a list of all existing capabilities version names - - $ opa capabilities - v0.17.0 - v0.17.1 - ... - v0.37.1 - v0.37.2 - v0.38.0 - ... - -Print the capabilities of the current version - -``` -$ opa capabilities --current -{ - "builtins": [...], - "future_keywords": [...], - "wasm_abi_versions": [...] -} -``` - -Print the capabilities of a specific version - -``` -$ opa capabilities --version v0.32.1 -{ - "builtins": [...], - "future_keywords": null, - "wasm_abi_versions": [...] -} -``` - -Print the capabilities of a capabilities file - -``` -$ opa capabilities --file ./capabilities/v0.32.1.json -{ - "builtins": [...], - "future_keywords": null, - "wasm_abi_versions": [...] -} -``` - -``` -opa capabilities [flags] -``` - -### Options - -``` - --current print current capabilities - --file string print capabilities defined by a file --h, --help help for capabilities - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --version string print capabilities of a specific version -``` - ---- - -## opa check - -Check Rego source files - -### Synopsis - -Check Rego source files for parse and compilation errors. - - If the 'check' command succeeds in parsing and compiling the source file(s), no output - is produced. If the parsing or compiling fails, 'check' will output the errors - and exit with a non-zero exit code. - -``` -opa check [path [...]] [flags] -``` - -### Options - -``` --b, --bundle load paths as bundle files or root directories - --capabilities string set capabilities version or capabilities.json file path --f, --format {pretty,json} set output format (default pretty) --h, --help help for check - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) --m, --max-errors int set the number of errors to allow before compilation fails early (default 10) --s, --schema string set schema file path or directory path --S, --strict enable compiler strict mode - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --v0-v1 check for Rego v0 and v1 compatibility (policies must be compatible with both Rego versions) -``` - ---- - -## opa deps - -Analyze Rego query dependencies - -### Synopsis - -Print dependencies of provided query. - -Dependencies are categorized as either base documents, which is any data loaded -from the outside world, or virtual documents, i.e values that are computed from rules. - -### Example - -Given a policy like this: - - package policy - - allow if is_admin - - is_admin if "admin" in input.user.roles - -To evaluate the dependencies of a simple query (e.g. data.policy.allow), -we'd run opa deps like demonstrated below: - - $ opa deps --data policy.rego data.policy.allow - +------------------+----------------------+ - | BASE DOCUMENTS | VIRTUAL DOCUMENTS | - +------------------+----------------------+ - | input.user.roles | data.policy.allow | - | | data.policy.is_admin | - +------------------+----------------------+ - -From the output we're able to determine that the allow rule depends on -the input.user.roles base document, as well as the virtual document (rule) -data.policy.is_admin. - -``` -opa deps [flags] -``` - -### Options - -``` --b, --bundle string set bundle file(s) or directory path(s). This flag can be repeated. --d, --data string set policy or data file(s). This flag can be repeated. --f, --format {pretty,json} set output format (default pretty) --h, --help help for deps - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) -``` - ---- - -## opa eval - -Evaluate a Rego query - -### Synopsis - -Evaluate a Rego query and print the result. - -### Examples - -To evaluate a simple query: - - $ opa eval 'x := 1; y := 2; x < y' - -To evaluate a query against JSON data: - - $ opa eval --data data.json 'name := data.names[_]' - -To evaluate a query against JSON data supplied with a file:// URL: - - $ opa eval --data file:///path/to/file.json 'data' - -### File & Bundle Loading - -The --bundle flag will load data files and Rego files contained -in the bundle specified by the path. It can be either a -compressed tar archive bundle file or a directory tree. - - $ opa eval --bundle /some/path 'data' - -Where /some/path contains: - - foo/ - | - +-- bar/ - | | - | +-- data.json - | - +-- baz.rego - | - +-- manifest.yaml - -The JSON file 'foo/bar/data.json' would be loaded and rooted under -'data.foo.bar' and the 'foo/baz.rego' would be loaded and rooted under the -package path contained inside the file. Only data files named data.json or -data.yaml will be loaded. In the example above the manifest.yaml would be -ignored. - -See https://www.openpolicyagent.org/docs/latest/management-bundles/ for more details -on bundle directory structures. - -The --data flag can be used to recursively load ALL *.rego, *.json, and -*.yaml files under the specified directory. - -The -O flag controls the optimization level. By default, optimization is disabled (-O=0). -When optimization is enabled the 'eval' command generates a bundle from the files provided -with either the --bundle or --data flag. This bundle is semantically equivalent to the input -files however the structure of the files in the bundle may have been changed by rewriting, inlining, -pruning, etc. This resulting optimized bundle is used to evaluate the query. If optimization is -enabled at least one entrypoint must be supplied, either via the -e option, or via entrypoint -metadata annotations. - -### Output Formats - -Set the output format with the --format flag. - - --format=json : output raw query results as JSON - --format=values : output line separated JSON arrays containing expression values - --format=bindings : output line separated JSON objects containing variable bindings - --format=pretty : output query results in a human-readable format - --format=source : output partial evaluation results in a source format - --format=raw : output the values from query results in a scripting friendly format - --format=discard : output the result field as "discarded" when non-nil - -### Schema - -The -s/--schema flag provides one or more JSON Schemas used to validate references to the input or data documents. -Loads a single JSON file, applying it to the input document; or all the schema files under the specified directory. - - $ opa eval --data policy.rego --input input.json --schema schema.json - $ opa eval --data policy.rego --input input.json --schema schemas/ - -### Capabilities - -When passing a capabilities definition file via --capabilities, one can restrict which -hosts remote schema definitions can be retrieved from. For example, a capabilities.json -containing - -``` -{ - "builtins": [ ... ], - "allow_net": [ "kubernetesjsonschema.dev" ] -} -``` - -would disallow fetching remote schemas from any host but "kubernetesjsonschema.dev". -Setting allow_net to an empty array would prohibit fetching any remote schemas. - -Not providing a capabilities file, or providing a file without an allow_net key, will -permit fetching remote schemas from any host. - -Note that the metaschemas http://json-schema.org/draft-04/schema, http://json-schema.org/draft-06/schema, -and http://json-schema.org/draft-07/schema, are always available, even without network -access. - -``` -opa eval [flags] -``` - -### Options - -``` --b, --bundle string set bundle file(s) or directory path(s). This flag can be repeated. - --capabilities string set capabilities version or capabilities.json file path - --count int number of times to repeat each benchmark (default 1) - --coverage report coverage --d, --data string set policy or data file(s). This flag can be repeated. - --disable-early-exit disable 'early exit' optimizations - --disable-indexing disable indexing optimizations - --disable-inlining stringArray set paths of documents to exclude from inlining --e, --entrypoint string set slash separated entrypoint path - --explain {off,full,notes,fails,debug} enable query explanations (default off) - --fail exits with non-zero exit code on undefined/empty result and errors - --fail-defined exits with non-zero exit code on defined/non-empty result and errors --f, --format {json,values,bindings,pretty,source,raw,discard} set output format (default json) --h, --help help for eval - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) - --import string set query import(s). This flag can be repeated. --i, --input string set input file path - --instrument enable query instrumentation metrics (implies --metrics) - --metrics report query performance metrics - --nondeterminstic-builtins evaluate nondeterministic builtins (if all arguments are known) during partial eval --O, --optimize int set optimization level - --optimize-store-for-read-speed optimize default in-memory store for read speed. Has possible negative impact on memory footprint and write speed. See https://www.openpolicyagent.org/docs/latest/policy-performance/#storage-optimization for more details. - --package string set query package --p, --partial perform partial evaluation - --pretty-limit int set limit after which pretty output gets truncated (default 80) - --profile perform expression profiling - --profile-limit int set number of profiling results to show (default 10) - --profile-sort string set sort order of expression profiler results. Accepts: total_time_ns, num_eval, num_redo, num_gen_expr, file, line. This flag can be repeated. --s, --schema string set schema file path or directory path - --shallow-inlining disable inlining of rules that depend on unknowns - --show-builtin-errors collect and return all encountered built-in errors, built in errors are not fatal - --stdin read query from stdin --I, --stdin-input read input document from stdin --S, --strict enable compiler strict mode - --strict-builtin-errors treat the first built-in function error encountered as fatal --t, --target {rego,wasm} set the runtime to exercise (default rego) - --timeout duration set eval timeout (default unlimited) --u, --unknowns stringArray set paths to treat as unknown during partial evaluation (default [input]) - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --var-values show local variable values in pretty trace output -``` - ---- - -## opa exec - -Execute against input files - -### Synopsis - -Execute against input files. - -The 'exec' command executes OPA against one or more input files. If the paths -refer to directories, OPA will execute against files contained inside those -directories, recursively. - -The 'exec' command accepts a --config-file/-c or series of --set options as -arguments. These options behave the same as way as 'opa run'. Since the 'exec' -command is intended to execute OPA in one-shot, the 'exec' command will -manually trigger plugins before and after policy execution: - -Before: Discovery -> Bundle -> Status -After: Decision Logs - -By default, the 'exec' command executes the "default decision" (specified in -the OPA configuration) against each input file. This can be overridden by -specifying the --decision argument and pointing at a specific policy decision, -e.g., opa exec --decision /foo/bar/baz ... - -``` -opa exec [ [...]] [flags] -``` - -### Examples - -``` -Loading input from stdin: - generate exec [ [...]] --stdin-input [flags] -``` - -### Options - -``` --b, --bundle string set bundle file(s) or directory path(s). This flag can be repeated. --c, --config-file string set path of configuration file - --decision string set decision to evaluate - --fail exits with non-zero exit code on undefined result and errors - --fail-defined exits with non-zero exit code on defined result and errors - --fail-non-empty exits with non-zero exit code on non-empty result and errors --f, --format {json} set output format (default json) --h, --help help for exec - --log-format {text,json,json-pretty} set log format (default json) --l, --log-level {debug,info,error} set log level (default error) - --log-timestamp-format string set log timestamp format (OPA_LOG_TIMESTAMP_FORMAT environment variable) - --set stringArray override config values on the command line (use commas to specify multiple values) - --set-file stringArray override config values with files on the command line (use commas to specify multiple values) --I, --stdin-input read input document from stdin rather than a static file - --timeout duration set exec timeout with a Go-style duration, such as '5m 30s'. (default unlimited) - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release -``` - ---- - -## opa fmt - -Format Rego source files - -### Synopsis - -Format Rego source files. - -The 'fmt' command takes a Rego source file and outputs a reformatted version. If no file path -is provided - this tool will use stdin. -The format of the output is not defined specifically; whatever this tool outputs -is considered correct format (with the exception of bugs). - -If the '-w' option is supplied, the 'fmt' command will overwrite the source file -instead of printing to stdout. - -If the '-d' option is supplied, the 'fmt' command will output a diff between the -original and formatted source. - -If the '-l' option is supplied, the 'fmt' command will output the names of files -that would change if formatted. The '-l' option will suppress any other output -to stdout from the 'fmt' command. - -If the '--fail' option is supplied, the 'fmt' command will return a non zero exit -code if a file would be reformatted. - -The 'fmt' command can be run in several compatibility modes for consuming and outputting -different Rego versions: - -- `opa fmt`: - - v1 Rego is formatted to v1 - - `rego.v1`/`future.keywords` imports are NOT removed - - `rego.v1`/`future.keywords` imports are NOT added if missing - - v0 rego is rejected -- `opa fmt --v0-compatible`: - - v0 Rego is formatted to v0 - - v1 Rego is rejected -- `opa fmt --v0-v1`: - - v0 Rego is formatted to be compatible with v0 AND v1 - - v1 Rego is rejected -- `opa fmt --v0-v1 --v1-compatible`: - - v1 Rego is formatted to be compatible with v0 AND v1 - - v0 Rego is rejected - -``` -opa fmt [path [...]] [flags] -``` - -### Options - -``` - --check-result assert that the formatted code is valid and can be successfully parsed (default true) --d, --diff only display a diff of the changes - --drop-v0-imports drop v0 imports from the formatted code, such as 'rego.v1' and 'future.keywords' - --fail non zero exit code on reformat --h, --help help for fmt --l, --list list all files who would change when formatted - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --v0-v1 format module(s) to be compatible with both Rego v0 and v1 --w, --write overwrite the original source file -``` - ---- - -## opa inspect - -Inspect OPA bundle(s) or Rego files. - -### Synopsis - -Inspect OPA bundle(s) or Rego files. - -The 'inspect' command provides a summary of the contents in OPA bundle(s) or a single Rego file. Bundles are -gzipped tarballs containing policies and data. The 'inspect' command reads bundle(s) and lists -the following: - -- packages that are contributed by .rego files -- data locations defined by the data.json and data.yaml files -- manifest data -- signature data -- information about the Wasm module files -- package- and rule annotations - -Example: - - $ ls - bundle.tar.gz - $ opa inspect bundle.tar.gz - -You can provide exactly one OPA bundle, path to a bundle directory, or direct path to a Rego file to the 'inspect' command -on the command-line. If you provide a path referring to a directory, the 'inspect' command will load that path as a bundle -and summarize its structure and contents. If you provide a path referring to a Rego file, the 'inspect' command will load -that file and summarize its structure and contents. - -``` -opa inspect [ [...]] [flags] -``` - -### Options - -``` --a, --annotations list annotations --f, --format {json,pretty} set output format (default pretty) --h, --help help for inspect - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release -``` - ---- - -## opa parse - -Parse Rego source file - -### Synopsis - -Parse Rego source file and print AST. - -``` -opa parse [flags] -``` - -### Options - -``` --f, --format {pretty,json} set output format (default pretty) --h, --help help for parse - --json-include string include or exclude optional elements. By default comments are included. Current options: locations, comments. E.g. --json-include locations,-comments will include locations and exclude comments. -``` - ---- - -## opa run - -Start OPA in interactive or server mode - -### Synopsis - -Start an instance of the Open Policy Agent (OPA). - -To run the interactive shell: - - $ opa run - -To run the server: - - $ opa run -s - -The 'run' command starts an instance of the OPA runtime. The OPA runtime can be -started as an interactive shell or a server. - -When the runtime is started as a shell, users can define rules and evaluate -expressions interactively. When the runtime is started as a server, OPA exposes -an HTTP API for managing policies, reading and writing data, and executing -queries. - -The runtime can be initialized with one or more files that contain policies or -data. If the '--bundle' option is specified the paths will be treated as policy -bundles and loaded following standard bundle conventions. The path can be a -compressed archive file or a directory which will be treated as a bundle. -Without the '--bundle' flag OPA will recursively load ALL rego, JSON, and YAML -files. - -When loading from directories, only files with known extensions are considered. -The current set of file extensions that OPA will consider are: - - .json # JSON data - .yaml or .yml # YAML data - .rego # Rego file - -Non-bundle data file and directory paths can be prefixed with the desired -destination in the data document with the following syntax: - -``` -: -``` - -To set a data file as the input document in the interactive shell use the -"repl.input" path prefix with the input file: - -```` -repl.input: -``` - -Example: - -``` -$ opa run repl.input:input.json -``` - -Which will load the "input.json" file at path "data.repl.input". - -Use the "help input" command in the interactive shell to see more options. - -File paths can be specified as URLs to resolve ambiguity in paths containing colons: - - $ opa run file:///c:/path/to/data.json - -URL paths to remote public bundles (http or https) will be parsed as shorthand -configuration equivalent of using repeated --set flags to accomplish the same: - - $ opa run -s https://example.com/bundles/bundle.tar.gz - -The above shorthand command is identical to: - - $ opa run -s --set "services.cli1.url=https://example.com" \ - --set "bundles.cli1.service=cli1" \ - --set "bundles.cli1.resource=/bundles/bundle.tar.gz" \ - --set "bundles.cli1.persist=true" - -The 'run' command can also verify the signature of a signed bundle. -A signed bundle is a normal OPA bundle that includes a file -named ".signatures.json". For more information on signed bundles -see https://www.openpolicyagent.org/docs/latest/management-bundles/#signing. - -The key to verify the signature of signed bundle can be provided -using the --verification-key flag. For example, for RSA family of algorithms, -the command expects a PEM file containing the public key. -For HMAC family of algorithms (eg. HS256), the secret can be provided -using the --verification-key flag. - -The --verification-key-id flag can be used to optionally specify a name for the -key provided using the --verification-key flag. - -The --signing-alg flag can be used to specify the signing algorithm. -The 'run' command uses RS256 (by default) as the signing algorithm. - -The --scope flag can be used to specify the scope to use for -bundle signature verification. - -Example: - - $ opa run --verification-key secret --signing-alg HS256 --bundle bundle.tar.gz - -The 'run' command will read the bundle "bundle.tar.gz", check the -".signatures.json" file and perform verification using the provided key. -An error will be generated if "bundle.tar.gz" does not contain a ".signatures.json" file. -For more information on the bundle verification process see -https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-verification. - -The 'run' command can ONLY be used with the --bundle flag to verify signatures -for existing bundle files or directories following the bundle structure. - -To skip bundle verification, use the --skip-verify flag. - -The --watch flag can be used to monitor policy and data file-system changes. When a change is detected, the updated policy -and data is reloaded into OPA. Watching individual files (rather than directories) is generally not recommended as some -updates might cause them to be dropped by OPA. - -OPA will automatically perform type checking based on a schema inferred from known input documents and report any errors -resulting from the schema check. Currently this check is performed on OPA's Authorization Policy Input document and will -be expanded in the future. To disable this, use the --skip-known-schema-check flag. - -The --v0-compatible flag can be used to opt-in to OPA features and behaviors that were the default in OPA v0.x. -Behaviors enabled by this flag include: - -- setting OPA's listening address to ":8181" by default, corresponding to listening on every network interface. -- expecting v0 Rego syntax in policy modules instead of the default v1 Rego syntax. - -The --tls-cipher-suites flag can be used to specify the list of enabled TLS 1.0–1.2 cipher suites. Note that TLS 1.3 -cipher suites are not configurable. Following are the supported TLS 1.0 - 1.2 cipher suites (IANA): -TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, -TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, -TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, -TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, -TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, -TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 - -See https://godoc.org/crypto/tls#pkg-constants for more information. -```` - -opa run [flags] - -``` -### Options -``` - --a, --addr strings set listening address of the server (e.g., `[ip]:` for TCP, `unix://` for UNIX domain socket) (default [localhost:8181]) ---authentication `{token,tls,off}` set authentication scheme (default off) ---authorization `{basic,off}` set authorization scheme (default off) --b, --bundle load paths as bundle files or root directories --c, --config-file string set path of configuration file ---diagnostic-addr strings set read-only diagnostic listening address of the server for /health and /metric APIs (e.g., `[ip]:` for TCP, `unix://` for UNIX domain socket) ---disable-telemetry disables anonymous information reporting (see: https://www.openpolicyagent.org/docs/latest/privacy) ---exclude-files-verify strings set file names to exclude during bundle verification --f, --format string set shell output format, i.e, pretty, json (default "pretty") ---h2c enable H2C for HTTP listeners --h, --help help for run --H, --history string set path of history file (default "$HOME/.opa_history") ---ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) ---log-format `{text,json,json-pretty}` set log format (default json) --l, --log-level `{debug,info,error}` set log level (default info) ---log-timestamp-format string set log timestamp format (OPA_LOG_TIMESTAMP_FORMAT environment variable) --m, --max-errors int set the number of errors to allow before compilation fails early (default 10) ---min-tls-version {1.0,1.1,1.2,1.3} set minimum TLS version to be used by OPA's server (default 1.2) ---optimize-store-for-read-speed optimize default in-memory store for read speed. Has possible negative impact on memory footprint and write speed. See https://www.openpolicyagent.org/docs/latest/policy-performance/#storage-optimization for more details. ---pprof enables pprof endpoints ---ready-timeout int wait (in seconds) for configured plugins before starting server (value `<=` 0 disables ready check) ---scope string scope to use for bundle signature verification --s, --server start the runtime in server mode ---set stringArray override config values on the command line (use commas to specify multiple values) ---set-file stringArray override config values with files on the command line (use commas to specify multiple values) ---shutdown-grace-period int set the time (in seconds) that the server will wait to gracefully shut down (default 10) ---shutdown-wait-period int set the time (in seconds) that the server will wait before initiating shutdown ---signing-alg string name of the signing algorithm (default "RS256") ---skip-known-schema-check disables type checking on known input schemas ---skip-verify disables bundle signature verification ---tls-ca-cert-file string set path of TLS CA cert file ---tls-cert-file string set path of TLS certificate file ---tls-cert-refresh-period duration set certificate refresh period ---tls-cipher-suites strings set list of enabled TLS 1.0–1.2 cipher suites (IANA) ---tls-private-key-file string set path of TLS private key file ---unix-socket-perm string specify the permissions for the Unix domain socket if used to listen for incoming connections (default "755") ---v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release ---verification-key string set the secret (HMAC) or path of the PEM file containing the public key (RSA and ECDSA) ---verification-key-id string name assigned to the verification key used for bundle verification (default "default") --w, --watch watch command line files for changes - -``` ---- - -## opa sign - -Generate an OPA bundle signature - -### Synopsis - -Generate an OPA bundle signature. - -The 'sign' command generates a digital signature for policy bundles. It generates a -".signatures.json" file that dictates which files should be included in the bundle, -what their SHA hashes are, and is cryptographically secure. - -The signatures file is a JSON file with an array containing a single JSON Web Token (JWT) -that encapsulates the signature for the bundle. - -The --signing-alg flag can be used to specify the algorithm to sign the token. The 'sign' -command uses RS256 (by default) as the signing algorithm. -See https://www.openpolicyagent.org/docs/latest/configuration/#keys -for a list of supported signing algorithms. - -The key to be used for signing the JWT MUST be provided using the --signing-key flag. -For example, for RSA family of algorithms, the command expects a PEM file containing -the private key. -For HMAC family of algorithms (eg. HS256), the secret can be provided using -the --signing-key flag. - -OPA 'sign' can ONLY be used with the --bundle flag to load paths that refer to -existing bundle files or directories following the bundle structure. - - $ opa sign --signing-key /path/to/private_key.pem --bundle foo - -Where foo has the following structure: - - foo/ - | - +-- bar/ - | | - | +-- data.json - | - +-- policy.rego - | - +-- .manifest - -This will create a ".signatures.json" file in the current directory. -The --output-file-path flag can be used to specify a different location for -the ".signatures.json" file. - -The content of the ".signatures.json" file is shown below: -``` - -```json -{ - "signatures": [ - "eyJhbGciOiJSUzI1NiJ9.eyJmaWxlcyI6W3sibmFtZSI6Ii5tYW5pZmVzdCIsImhhc2giOiIxODc0NWRlNzJjMDFlODBjZDlmNTIwZjQxOGMwMDlhYzRkMmMzZDAyYjE3YTUwZTJkMDQyMTU4YmMzNTJhMzJkIiwiYWxnb3JpdGhtIjoiU0hBLTI1NiJ9LHsibmFtZSI6ImJhci9kYXRhLmpzb24iLCJoYXNoIjoiOTNhMjM5NzFhOTE0ZTVlYWNiZjBhOGQyNTE1NGNkYTMwOWMzYzFjNzJmYmI5OTE0ZDQ3YzYwZjNjYjY4MTU4OCIsImFsZ29yaXRobSI6IlNIQS0yNTYifSx7Im5hbWUiOiJwb2xpY3kucmVnbyIsImhhc2giOiJkMGYyNDJhYWUzNGRiNTRlZjU2NmJlYTRkNDVmY2YxOTcwMGM1ZDhmODdhOWRiOTMyZGZhZDZkMWYwZjI5MWFjIiwiYWxnb3JpdGhtIjoiU0hBLTI1NiJ9XX0.lNsmRqrmT1JI4Z_zpY6IzHRZQAU306PyOjZ6osquixPuTtdSBxgbsdKDcp7Civw3B77BgygVsvx4k3fYr8XCDKChm0uYKScrpFr9_yS6g5mVTQws3KZncZXCQHdupRFoqMS8vXAVgJr52C83AinYWABwH2RYq_B0ZPf_GDzaMgzpep9RlDNecGs57_4zlyxmP2ESU8kjfX8jAA6rYFKeGXJHMD-j4SassoYIzYRv9YkHx8F8Y2ae5Kd5M24Ql0kkvqc_4eO_T9s4nbQ4q5qGHGE-91ND1KVn2avcUyVVPc0-XCR7EH8HnHgCl0v1c7gX1RL7ET7NJbPzfmzQAzk0ZW0dEHI4KZnXSpqy8m-3zAc8kIARm2QwoNEWpy3MWiooPeZVSa9d5iw1aLrbyumfjBP0vCQEPes-Aa6PrARwd5jR9SacO5By0-4emzskvJYRZqbfJ9tXSXDMcAFOAm6kqRPJaj8AO4CyajTC_Lt32_0OLeXqYgNpt3HDqLqGjrb-8fVeQc-hKh0aES8XehQqXj4jMwfsTyj5alsXZm08LwzcFlfQZ7s1kUtmr0_BBNJYcdZUdlu6Qio3LFSRYXNuu6edAO1VH5GKqZISvE1uvDZb2E0Z-rtH-oPp1iSpfvsX47jKJ42LVpI6OahEBri44dzHOIwwm3CIuV8gFzOwR0k" - ] -} -``` - -``` -And the decoded JWT payload has the following form: -``` - -```json -{ - "files": [ - { - "name": ".manifest", - "hash": "18745de72c01e80cd9f520f418c009ac4d2c3d02b17a50e2d042158bc352a32d", - "algorithm": "SHA-256" - }, - { - "name": "policy.rego", - "hash": "d0f242aae34db54ef566bea4d45fcf19700c5d8f87a9db932dfad6d1f0f291ac", - "algorithm": "SHA-256" - }, - { - "name": "bar/data.json", - "hash": "93a23971a914e5eacbf0a8d25154cda309c3c1c72fbb9914d47c60f3cb681588", - "algorithm": "SHA-256" - } - ] -} -``` - -``` -The "files" field is generated from the files under the directory path(s) -provided to the 'sign' command. During bundle signature verification, OPA will check -each file name (ex. "foo/bar/data.json") in the "files" field -exists in the actual bundle. The file content is hashed using SHA256. - -To include additional claims in the payload use the --claims-file flag to provide -a JSON file containing optional claims. - -For more information on the format of the ".signatures.json" file see -https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format. -``` - -``` -opa sign [ [...]] [flags] -``` - -``` -### Options -``` - --b, --bundle load paths as bundle files or root directories ---claims-file string set path of JSON file containing optional claims (see: https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format) --h, --help help for sign --o, --output-file-path string set the location for the .signatures.json file (default ".") ---signing-alg string name of the signing algorithm (default "RS256") ---signing-key string set the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA) ---signing-plugin string name of the plugin to use for signing/verification (see https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-plugin - -```` ---- - -## opa test - -Execute Rego test cases - -### Synopsis - -Execute Rego test cases. - -The 'test' command takes a file or directory path as input and executes all -test cases discovered in matching files. Test cases are rules whose names have the prefix "test_". - -If the '--bundle' option is specified the paths will be treated as policy bundles -and loaded following standard bundle conventions. The path can be a compressed archive -file or a directory which will be treated as a bundle. Without the '--bundle' flag OPA -will recursively load ALL *.rego, *.json, and *.yaml files for evaluating the test cases. - -Test cases under development may be prefixed "todo_" in order to skip their execution, -while still getting marked as skipped in the test results. - -Example policy (example/authz.rego): - -```rego - package authz - - allow if { - input.path == ["users"] - input.method == "POST" - } - - allow if { - input.path == ["users", input.user_id] - input.method == "GET" - } -```` - -Example test (example/authz_test.rego): - -```rego - package authz_test - - import data.authz.allow - - test_post_allowed if { - allow with input as {"path": ["users"], "method": "POST"} - } - - test_get_denied if { - not allow with input as {"path": ["users"], "method": "GET"} - } - - test_get_user_allowed if { - allow with input as {"path": ["users", "bob"], "method": "GET", "user_id": "bob"} - } - - test_get_another_user_denied if { - not allow with input as {"path": ["users", "bob"], "method": "GET", "user_id": "alice"} - } - - todo_test_user_allowed_http_client_data if { - false # Remember to test this later! - } -``` - -Example test run: - - $ opa test ./example/ - -If used with the '--bench' option then tests will be benchmarked. - -Example benchmark run: - - $ opa test --bench ./example/ - -The optional "gobench" output format conforms to the Go Benchmark Data Format. - -The --watch flag can be used to monitor policy and data file-system changes. When a change is detected, OPA reloads -the policy and data and then re-runs the tests. Watching individual files (rather than directories) is generally not -recommended as some updates might cause them to be dropped by OPA. - -``` -opa test [path [...]] [flags] -``` - -### Options - -``` - --bench benchmark the unit tests - --benchmem report memory allocations with benchmark results (default true) --b, --bundle load paths as bundle files or root directories - --capabilities string set capabilities version or capabilities.json file path - --count int number of times to repeat each test (default 1) --c, --coverage report coverage (overrides debug tracing) --z, --exit-zero-on-skipped skipped tests return status 0 - --explain {fails,full,notes,debug} enable query explanations (default fails) --f, --format {pretty,json,gobench} set output format (default pretty) --h, --help help for test - --ignore strings set file and directory names to ignore during loading (e.g., '.*' excludes hidden files) --m, --max-errors int set the number of errors to allow before compilation fails early (default 10) --r, --run string run only test cases matching the regular expression. --s, --schema string set schema file path or directory path --t, --target {rego,wasm} set the runtime to exercise (default rego) - --threshold float set coverage threshold and exit with non-zero status if coverage is less than threshold % - --timeout duration set test timeout (default 5s, 30s when benchmarking) - --v0-compatible opt-in to OPA features and behaviors prior to the OPA v1.0 release - --var-values show local variable values in test output --v, --verbose set verbose reporting mode --w, --watch watch command line files for changes -``` - ---- - -## opa version - -Print the version of OPA - -### Synopsis - -Show version and build information for OPA. - -``` -opa version [flags] -``` - -### Options - -``` --c, --check check for latest OPA release --h, --help help for version -``` +The commands exposed in the `opa` executable are listed here in alphabetical +order. + +:::tip +Note that command line arguments may either be provided as traditional flags, or +as environment variables. The expected format of environment variables used for +this purpose follows the pattern `OPA__` where COMMAND is the +command name in uppercase (like EVAL) and FLAG is the flag name in uppercase +(like STRICT), i.e. `OPA_EVAL_STRICT` would be equivalent to passing the +--strict flag to the eval command. +::: + +import commands from "@generated/cli-data/default/cli.json"; +import CommandList from "@site/src/components/CommandList"; + + diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index c8b2407269..697b489f96 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -408,6 +408,26 @@ The Linux Foundation has registered trademarks and uses trademarks. For a list o }; }, + async function cliData(context, options) { + return { + name: "cli-data", + + async loadContent() { + const filePath = path.join(context.siteDir, "src/data/cli.json"); + const cliJson = await fs.readFile(filePath, "utf-8"); + const parsedData = JSON.parse(cliJson); + + return parsedData; + }, + + async contentLoaded({ content, actions }) { + const { createData } = actions; + + await createData("cli.json", JSON.stringify(content, null, 2)); + }, + }; + }, + async function versionsPageGen(context, options) { return { name: "version-page-gen", diff --git a/docs/src/components/CommandDoc.js b/docs/src/components/CommandDoc.js new file mode 100644 index 0000000000..fbbfd0ab84 --- /dev/null +++ b/docs/src/components/CommandDoc.js @@ -0,0 +1,128 @@ +import { useThemeConfig } from "@docusaurus/theme-common"; +import React from "react"; +import { useEffect } from "react"; +import ReactMarkdown from "react-markdown"; +import { useLocation } from "react-router-dom"; + +const capitalize = (str) => { + return str.charAt(0).toUpperCase() + str.slice(1); +}; + +const convertUrlsToMarkdownLinks = (text) => { + if (typeof text !== "string") { + text = String(text); + } + + text = text.replace(/<\/?[^>]+(>|$)/g, ""); + + const urlRegex = /https?:\/\/(?:www\.)?[^\s<>"'()]+[^\s<>"'.),!?]/g; + + return text.replace(urlRegex, (rawUrl) => { + const trailingMatch = rawUrl.match(/[.)]+$/); + const trailing = trailingMatch ? trailingMatch[0] : ""; + const url = trailing ? rawUrl.slice(0, -trailing.length) : rawUrl; + + const displayText = url + .replace(/^https?:\/\//, "") + .replace(/^www\./, "") + .replace(/\/$/, ""); + + return `[${displayText}](${url})${trailing}`; + }); +}; + +const htmlSafe = (str) => { + return String(str) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +}; + +const CommandDoc = ({ command }) => { + const { navbar } = useThemeConfig(); + const location = useLocation(); + + const { + id, + use, + useline, + long, + example, + flags, + } = command; + + return ( +
+
+

+ {id} + + # + +

+
+ + {useline && ( +
+          {useline}
+        
+ )} + + {long && {convertUrlsToMarkdownLinks(long)}} + + {flags.length > 0 && ( + <> +

Flags

+ + + + + + + + + + {flags.map((f, idx) => ( + + + + + + ))} + +
ShortFlagDescription
+ {f.shorthand && {f.shorthand}} + + {f.name} + + {f.description !== "" && ( + + {convertUrlsToMarkdownLinks(capitalize(htmlSafe(f.description)))} + + )} + + {f.type && f.type.startsWith("{") && ( +
+ Accepts:{" "} + + {f.type.replace(/,/g, ",\u200b")} + +
+ )} +
+ + )} + + {example && example.trim() !== "" && ( + <> +

Example

+ {example} + + )} +
+ ); +}; + +export default CommandDoc; diff --git a/docs/src/components/CommandList.js b/docs/src/components/CommandList.js new file mode 100644 index 0000000000..21784c12bb --- /dev/null +++ b/docs/src/components/CommandList.js @@ -0,0 +1,71 @@ +import React, { useState } from "react"; +import CommandDoc from "./CommandDoc"; + +function filterCommandById(command, query) { + const lowerQuery = query.toLowerCase(); + + const matches = (text) => text && text.toLowerCase().includes(lowerQuery); + + const isMatch = matches(command.id); + + // (charlieegan3) we don't have child commands for now and it might need to adjusted when + // we do, but I didn't want to ignore the fact they might exist in future. + let matchedChildren = []; + if (Array.isArray(command.children)) { + matchedChildren = command.children + .map(child => filterCommandById(child, query)) + .filter(Boolean); + } + + if (isMatch || matchedChildren.length > 0) { + return { + ...command, + children: matchedChildren.length > 0 ? matchedChildren : command.children, + }; + } + + return null; +} + +const CommandList = ({ commands }) => { + const [search, setSearch] = useState(""); + + const filtered = commands + .map(cmd => filterCommandById(cmd, search)) + .filter(Boolean); + + const totalCommands = commands.length; + const filteredCommands = filtered.length; + + return ( +
+ setSearch(e.target.value)} + style={{ + width: "100%", + padding: "0.5rem", + marginBottom: "1rem", + fontSize: "1rem", + border: "1px solid #ccc", + borderRadius: "4px", + }} + /> + + {filteredCommands !== totalCommands && filteredCommands > 0 && ( +

+ Showing {filteredCommands}/{totalCommands} commands + {filtered.length > 1 && "(" + filtered.map(cmd => cmd.id).join(", ") + ")"} +

+ )} + + {filteredCommands === 0 ?

No matching commands found.

: ( + filtered.map((cmd, idx) => ) + )} +
+ ); +}; + +export default CommandList; diff --git a/docs/src/data/cli.json b/docs/src/data/cli.json new file mode 100644 index 0000000000..7b645f64cb --- /dev/null +++ b/docs/src/data/cli.json @@ -0,0 +1 @@ +[{"children":null,"example":"","flags":[{"default":"true","description":"report memory allocations with benchmark results","name":"--benchmem","shorthand":"","type":"bool"},{"default":"","description":"set bundle file(s) or directory path(s). This flag can be repeated.","name":"--bundle","shorthand":"-b","type":"string"},{"default":"","description":"set path of configuration file","name":"--config-file","shorthand":"-c","type":"string"},{"default":"1","description":"number of times to repeat each benchmark","name":"--count","shorthand":"","type":"int"},{"default":"","description":"set policy or data file(s). This flag can be repeated.","name":"--data","shorthand":"-d","type":"string"},{"default":"false","description":"run benchmarks against a running OPA server","name":"--e2e","shorthand":"","type":"bool"},{"default":"true","description":"exits with non-zero exit code on undefined/empty result and errors","name":"--fail","shorthand":"","type":"bool"},{"default":"pretty","description":"set output format","name":"--format","shorthand":"-f","type":"{json,pretty,gobench}"},{"default":"[]","description":"set file and directory names to ignore during loading (e.g., '.*' excludes hidden files)","name":"--ignore","shorthand":"","type":"stringSlice"},{"default":"","description":"set query import(s). This flag can be repeated.","name":"--import","shorthand":"","type":"string"},{"default":"","description":"set input file path","name":"--input","shorthand":"-i","type":"string"},{"default":"true","description":"report query performance metrics","name":"--metrics","shorthand":"","type":"bool"},{"default":"false","description":"optimize default in-memory store for read speed. Has possible negative impact on memory footprint and write speed. See https://www.openpolicyagent.org/docs/latest/policy-performance/#storage-optimization for more details.","name":"--optimize-store-for-read-speed","shorthand":"","type":"bool"},{"default":"","description":"set query package","name":"--package","shorthand":"","type":"string"},{"default":"false","description":"perform partial evaluation","name":"--partial","shorthand":"-p","type":"bool"},{"default":"","description":"set schema file path or directory path","name":"--schema","shorthand":"-s","type":"string"},{"default":"10","description":"set the time (in seconds) that the server will wait to gracefully shut down. This flag is valid in 'e2e' mode only.","name":"--shutdown-grace-period","shorthand":"","type":"int"},{"default":"0","description":"set the time (in seconds) that the server will wait before initiating shutdown. This flag is valid in 'e2e' mode only.","name":"--shutdown-wait-period","shorthand":"","type":"int"},{"default":"false","description":"read query from stdin","name":"--stdin","shorthand":"","type":"bool"},{"default":"false","description":"read input document from stdin","name":"--stdin-input","shorthand":"-I","type":"bool"},{"default":"rego","description":"set the runtime to exercise","name":"--target","shorthand":"-t","type":"{rego,wasm}"},{"default":"[input]","description":"set paths to treat as unknown during partial evaluation","name":"--unknowns","shorthand":"-u","type":"stringArray"},{"default":"false","description":"opt-in to OPA features and behaviors prior to the OPA v1.0 release","name":"--v0-compatible","shorthand":"","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"}],"id":"bench","long":"Benchmark a Rego query and print the results.\n\nThe benchmark command works very similar to 'eval' and will evaluate the query in the same fashion. The\nevaluation will be repeated a number of times and performance results will be returned.\n\nExample with bundle and input data:\n\n\topa bench -b ./policy-bundle -i input.json 'data.authz.allow'\n\nTo run benchmarks against a running OPA server to evaluate server overhead use the --e2e flag.\n\nThe optional \"gobench\" output format conforms to the Go Benchmark Data Format.\n","parent_flags":null,"short":"Benchmark a Rego query","use":"bench \u003cquery\u003e","useline":"opa bench \u003cquery\u003e [flags]"},{"children":null,"example":"","flags":[{"default":"false","description":"load paths as bundle files or root directories","name":"--bundle","shorthand":"-b","type":"bool"},{"default":"","description":"set capabilities version or capabilities.json file path","name":"--capabilities","shorthand":"","type":"string"},{"default":"","description":"set path of JSON file containing optional claims (see: https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format)","name":"--claims-file","shorthand":"","type":"string"},{"default":"false","description":"enable debug output","name":"--debug","shorthand":"","type":"bool"},{"default":"","description":"set slash separated entrypoint path","name":"--entrypoint","shorthand":"-e","type":"string"},{"default":"[]","description":"set file names to exclude during bundle verification","name":"--exclude-files-verify","shorthand":"","type":"stringSlice"},{"default":"false","description":"follow symlinks in the input set of paths when building the bundle","name":"--follow-symlinks","shorthand":"","type":"bool"},{"default":"[]","description":"set file and directory names to ignore during loading (e.g., '.*' excludes hidden files)","name":"--ignore","shorthand":"","type":"stringSlice"},{"default":"0","description":"set optimization level","name":"--optimize","shorthand":"-O","type":"int"},{"default":"bundle.tar.gz","description":"set the output filename","name":"--output","shorthand":"-o","type":"string"},{"default":"partial","description":"set the namespace to use for partially evaluated files in an optimized bundle","name":"--partial-namespace","shorthand":"","type":"string"},{"default":"false","description":"exclude dependents of entrypoints","name":"--prune-unused","shorthand":"","type":"bool"},{"default":"","description":"set output bundle revision","name":"--revision","shorthand":"-r","type":"string"},{"default":"","description":"scope to use for bundle signature verification","name":"--scope","shorthand":"","type":"string"},{"default":"RS256","description":"name of the signing algorithm","name":"--signing-alg","shorthand":"","type":"string"},{"default":"","description":"set the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA)","name":"--signing-key","shorthand":"","type":"string"},{"default":"","description":"name of the plugin to use for signing/verification (see https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-plugin)","name":"--signing-plugin","shorthand":"","type":"string"},{"default":"rego","description":"set the output bundle target type","name":"--target","shorthand":"-t","type":"{rego,wasm,plan}"},{"default":"false","description":"opt-in to OPA features and behaviors prior to the OPA v1.0 release","name":"--v0-compatible","shorthand":"","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"},{"default":"","description":"set the secret (HMAC) or path of the PEM file containing the public key (RSA and ECDSA)","name":"--verification-key","shorthand":"","type":"string"},{"default":"default","description":"name assigned to the verification key used for bundle verification","name":"--verification-key-id","shorthand":"","type":"string"},{"default":"false","description":"enable print statements inside of WebAssembly modules compiled by the compiler","name":"--wasm-include-print","shorthand":"","type":"bool"}],"id":"build","long":"Build an OPA bundle.\n\nThe 'build' command packages OPA policy and data files into bundles. Bundles are\ngzipped tarballs containing policies and data. Paths referring to directories are\nloaded recursively.\n\n $ ls\n example.rego\n\n $ opa build -b .\n\nYou can load bundles into OPA on the command-line:\n\n $ ls\n bundle.tar.gz example.rego\n\n $ opa run bundle.tar.gz\n\nYou can also configure OPA to download bundles from remote HTTP endpoints:\n\n $ opa run --server \\\n --set bundles.example.resource=bundle.tar.gz \\\n --set services.example.url=http://localhost:8080\n\nInside another terminal in the same directory, serve the bundle via HTTP:\n\n $ python3 -m http.server --bind localhost 8080\n\nFor more information on bundles see https://www.openpolicyagent.org/docs/latest/management-bundles/.\n\nCommon Flags\n------------\n\nWhen -b is specified the 'build' command assumes paths refer to existing bundle files\nor directories following the bundle structure. If multiple bundles are provided, their\ncontents are merged. If there are any merge conflicts (e.g., due to conflicting bundle\nroots), the command fails. When loading an existing bundle file, the .manifest from\nthe input bundle will be included in the output bundle. Flags that set .manifest fields\n(such as --revision) override input bundle .manifest fields.\n\nThe -O flag controls the optimization level. By default, optimization is disabled (-O=0).\nWhen optimization is enabled the 'build' command generates a bundle that is semantically\nequivalent to the input files however the structure of the files in the bundle may have\nbeen changed by rewriting, inlining, pruning, etc. Higher optimization levels may result\nin longer build times. The --partial-namespace flag can used in conjunction with the -O flag\nto specify the namespace for the partially evaluated files in the optimized bundle.\n\nThe 'build' command supports targets (specified by -t):\n\n rego The default target emits a bundle containing a set of policy and data files\n that are semantically equivalent to the input files. If optimizations are\n disabled the output may simply contain a copy of the input policy and data\n files. If optimization is enabled at least one entrypoint must be supplied,\n either via the -e option, or via entrypoint metadata annotations.\n\n wasm The wasm target emits a bundle containing a WebAssembly module compiled from\n the input files for each specified entrypoint. The bundle may contain the\n original policy or data files.\n\n plan The plan target emits a bundle containing a plan, i.e., an intermediate\n representation compiled from the input files for each specified entrypoint.\n This is for further processing, OPA cannot evaluate a \"plan bundle\" like it\n can evaluate a wasm or rego bundle.\n\nThe -e flag tells the 'build' command which documents (entrypoints) will be queried by \nthe software asking for policy decisions, so that it can focus optimization efforts and \nensure that document is not eliminated by the optimizer.\nNote: Unless the --prune-unused flag is used, any rule transitively referring to a \npackage or rule declared as an entrypoint will also be enumerated as an entrypoint.\n\nSigning\n-------\n\nThe 'build' command can be used to verify the signature of a signed bundle and\nalso to generate a signature for the output bundle the command creates.\n\nIf the directory path(s) provided to the 'build' command contain a \".signatures.json\" file,\nit will attempt to verify the signatures included in that file. The bundle files\nor directory path(s) to verify must be specified using --bundle.\n\nFor more information on the bundle signing and verification, see\nhttps://www.openpolicyagent.org/docs/latest/management-bundles/#signing.\n\nExample:\n\n $ opa build --verification-key /path/to/public_key.pem --signing-key /path/to/private_key.pem --bundle foo\n\nWhere foo has the following structure:\n\n foo/\n |\n +-- bar/\n | |\n | +-- data.json\n |\n +-- policy.rego\n |\n +-- .manifest\n |\n +-- .signatures.json\n\n\nThe 'build' command will verify the signatures using the public key provided by the --verification-key flag.\nThe default signing algorithm is RS256 and the --signing-alg flag can be used to specify\na different one. The --verification-key-id and --scope flags can be used to specify the name for the key\nprovided using the --verification-key flag and scope to use for bundle signature verification respectively.\n\nIf the verification succeeds, the 'build' command will write out an updated \".signatures.json\" file\nto the output bundle. It will use the key specified by the --signing-key flag to sign\nthe token in the \".signatures.json\" file.\n\nTo include additional claims in the payload use the --claims-file flag to provide a JSON file\ncontaining optional claims.\n\nFor more information on the format of the \".signatures.json\" file\nsee https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format.\n\nCapabilities\n------------\n\nThe 'build' command can validate policies against a configurable set of OPA capabilities.\nThe capabilities define the built-in functions and other language features that policies\nmay depend on. For example, the following capabilities file only permits the policy to\ndepend on the \"plus\" built-in function ('+'):\n\n {\n \"builtins\": [\n {\n \"name\": \"plus\",\n \"infix\": \"+\",\n \"decl\": {\n \"type\": \"function\",\n \"args\": [\n {\n \"type\": \"number\"\n },\n {\n \"type\": \"number\"\n }\n ],\n \"result\": {\n \"type\": \"number\"\n }\n }\n }\n ]\n }\n\nCapabilities can be used to validate policies against a specific version of OPA.\nThe OPA repository contains a set of capabilities files for each OPA release. For example,\nthe following command builds a directory of policies ('./policies') and validates them\nagainst OPA v0.22.0:\n\n opa build ./policies --capabilities v0.22.0\n","parent_flags":null,"short":"Build an OPA bundle","use":"build \u003cpath\u003e [\u003cpath\u003e [...]]","useline":"opa build \u003cpath\u003e [\u003cpath\u003e [...]] [flags]"},{"children":null,"example":"","flags":[{"default":"false","description":"print current capabilities","name":"--current","shorthand":"","type":"bool"},{"default":"","description":"print capabilities defined by a file","name":"--file","shorthand":"","type":"string"},{"default":"false","description":"opt-in to OPA features and behaviors prior to the OPA v1.0 release","name":"--v0-compatible","shorthand":"","type":"bool"},{"default":"","description":"print capabilities of a specific version","name":"--version","shorthand":"","type":"string"}],"id":"capabilities","long":"Show capabilities for OPA.\n\nThe 'capabilities' command prints the OPA capabilities, prior to and including the version of OPA used.\n\nPrint a list of all existing capabilities version names\n\n $ opa capabilities\n v0.17.0\n v0.17.1\n ...\n v0.37.1\n v0.37.2\n v0.38.0\n ...\n\nPrint the capabilities of the current version\n\n $ opa capabilities --current\n {\n \"builtins\": [...],\n \"future_keywords\": [...],\n \"wasm_abi_versions\": [...]\n }\n\nPrint the capabilities of a specific version\n\n $ opa capabilities --version v0.32.1\n {\n \"builtins\": [...],\n \"future_keywords\": null,\n \"wasm_abi_versions\": [...]\n }\n\nPrint the capabilities of a capabilities file\n\n $ opa capabilities --file ./capabilities/v0.32.1.json\n {\n \"builtins\": [...],\n \"future_keywords\": null,\n \"wasm_abi_versions\": [...]\n }\n\n","parent_flags":null,"short":"Print the capabilities of OPA","use":"capabilities","useline":"opa capabilities [flags]"},{"children":null,"example":"","flags":[{"default":"false","description":"load paths as bundle files or root directories","name":"--bundle","shorthand":"-b","type":"bool"},{"default":"","description":"set capabilities version or capabilities.json file path","name":"--capabilities","shorthand":"","type":"string"},{"default":"pretty","description":"set output format","name":"--format","shorthand":"-f","type":"{pretty,json}"},{"default":"[]","description":"set file and directory names to ignore during loading (e.g., '.*' excludes hidden files)","name":"--ignore","shorthand":"","type":"stringSlice"},{"default":"10","description":"set the number of errors to allow before compilation fails early","name":"--max-errors","shorthand":"-m","type":"int"},{"default":"false","description":"check for Rego v0 and v1 compatibility (policies must be compatible with both Rego versions)","name":"--rego-v1","shorthand":"","type":"bool"},{"default":"","description":"set schema file path or directory path","name":"--schema","shorthand":"-s","type":"string"},{"default":"false","description":"enable compiler strict mode","name":"--strict","shorthand":"-S","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors prior to the OPA v1.0 release","name":"--v0-compatible","shorthand":"","type":"bool"},{"default":"false","description":"check for Rego v0 and v1 compatibility (policies must be compatible with both Rego versions)","name":"--v0-v1","shorthand":"","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"}],"id":"check","long":"Check Rego source files for parse and compilation errors.\n\t\nIf the 'check' command succeeds in parsing and compiling the source file(s), no output\nis produced. If the parsing or compiling fails, 'check' will output the errors\nand exit with a non-zero exit code.","parent_flags":null,"short":"Check Rego source files","use":"check \u003cpath\u003e [path [...]]","useline":"opa check \u003cpath\u003e [path [...]] [flags]"},{"children":null,"example":"\nGiven a policy like this:\n\n\tpackage policy\n\n\tallow if is_admin\n\n\tis_admin if \"admin\" in input.user.roles\n\nTo evaluate the dependencies of a simple query (e.g. data.policy.allow),\nwe'd run opa deps like demonstrated below:\n\n\t$ opa deps --data policy.rego data.policy.allow\n\t+------------------+----------------------+\n\t| BASE DOCUMENTS | VIRTUAL DOCUMENTS |\n\t+------------------+----------------------+\n\t| input.user.roles | data.policy.allow |\n\t| | data.policy.is_admin |\n\t+------------------+----------------------+\n\nFrom the output we're able to determine that the allow rule depends on\nthe input.user.roles base document, as well as the virtual document (rule)\ndata.policy.is_admin.\n","flags":[{"default":"","description":"set bundle file(s) or directory path(s). This flag can be repeated.","name":"--bundle","shorthand":"-b","type":"string"},{"default":"","description":"set policy or data file(s). This flag can be repeated.","name":"--data","shorthand":"-d","type":"string"},{"default":"pretty","description":"set output format","name":"--format","shorthand":"-f","type":"{pretty,json}"},{"default":"[]","description":"set file and directory names to ignore during loading (e.g., '.*' excludes hidden files)","name":"--ignore","shorthand":"","type":"stringSlice"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"}],"id":"deps","long":"Print dependencies of provided query.\n\nDependencies are categorized as either base documents, which is any data loaded\nfrom the outside world, or virtual documents, i.e values that are computed from rules.\n","parent_flags":null,"short":"Analyze Rego query dependencies","use":"deps \u003cquery\u003e","useline":"opa deps \u003cquery\u003e [flags]"},{"children":null,"example":"\n\nTo evaluate a simple query:\n\n $ opa eval 'x := 1; y := 2; x \u003c y'\n\nTo evaluate a query against JSON data:\n\n $ opa eval --data data.json 'name := data.names[_]'\n\nTo evaluate a query against JSON data supplied with a file:// URL:\n\n $ opa eval --data file:///path/to/file.json 'data'\n\n\nFile \u0026 Bundle Loading\n---------------------\n\nThe --bundle flag will load data files and Rego files contained\nin the bundle specified by the path. It can be either a\ncompressed tar archive bundle file or a directory tree.\n\n $ opa eval --bundle /some/path 'data'\n\nWhere /some/path contains:\n\n foo/\n |\n +-- bar/\n | |\n | +-- data.json\n |\n +-- baz.rego\n |\n +-- manifest.yaml\n\nThe JSON file 'foo/bar/data.json' would be loaded and rooted under\n'data.foo.bar' and the 'foo/baz.rego' would be loaded and rooted under the\npackage path contained inside the file. Only data files named data.json or\ndata.yaml will be loaded. In the example above the manifest.yaml would be\nignored.\n\nSee https://www.openpolicyagent.org/docs/latest/management-bundles/ for more details\non bundle directory structures.\n\nThe --data flag can be used to recursively load ALL *.rego, *.json, and\n*.yaml files under the specified directory.\n\nThe -O flag controls the optimization level. By default, optimization is disabled (-O=0).\nWhen optimization is enabled the 'eval' command generates a bundle from the files provided\nwith either the --bundle or --data flag. This bundle is semantically equivalent to the input\nfiles however the structure of the files in the bundle may have been changed by rewriting, inlining,\npruning, etc. This resulting optimized bundle is used to evaluate the query. If optimization is\nenabled at least one entrypoint must be supplied, either via the -e option, or via entrypoint\nmetadata annotations.\n\nOutput Formats\n--------------\n\nSet the output format with the --format flag.\n\n --format=json : output raw query results as JSON\n --format=values : output line separated JSON arrays containing expression values\n --format=bindings : output line separated JSON objects containing variable bindings\n --format=pretty : output query results in a human-readable format\n --format=source : output partial evaluation results in a source format\n --format=raw : output the values from query results in a scripting friendly format\n --format=discard : output the result field as \"discarded\" when non-nil\n\nSchema\n------\n\nThe -s/--schema flag provides one or more JSON Schemas used to validate references to the input or data documents.\nLoads a single JSON file, applying it to the input document; or all the schema files under the specified directory.\n\n $ opa eval --data policy.rego --input input.json --schema schema.json\n $ opa eval --data policy.rego --input input.json --schema schemas/\n\nCapabilities\n------------\n\nWhen passing a capabilities definition file via --capabilities, one can restrict which\nhosts remote schema definitions can be retrieved from. For example, a capabilities.json\ncontaining\n\n {\n \"builtins\": [ ... ],\n \"allow_net\": [ \"kubernetesjsonschema.dev\" ]\n }\n\nwould disallow fetching remote schemas from any host but \"kubernetesjsonschema.dev\".\nSetting allow_net to an empty array would prohibit fetching any remote schemas.\n\nNot providing a capabilities file, or providing a file without an allow_net key, will\npermit fetching remote schemas from any host.\n\nNote that the metaschemas http://json-schema.org/draft-04/schema, http://json-schema.org/draft-06/schema,\nand http://json-schema.org/draft-07/schema, are always available, even without network\naccess.\n","flags":[{"default":"","description":"set bundle file(s) or directory path(s). This flag can be repeated.","name":"--bundle","shorthand":"-b","type":"string"},{"default":"","description":"set capabilities version or capabilities.json file path","name":"--capabilities","shorthand":"","type":"string"},{"default":"1","description":"number of times to repeat each benchmark","name":"--count","shorthand":"","type":"int"},{"default":"false","description":"report coverage","name":"--coverage","shorthand":"","type":"bool"},{"default":"","description":"set policy or data file(s). This flag can be repeated.","name":"--data","shorthand":"-d","type":"string"},{"default":"false","description":"disable 'early exit' optimizations","name":"--disable-early-exit","shorthand":"","type":"bool"},{"default":"false","description":"disable indexing optimizations","name":"--disable-indexing","shorthand":"","type":"bool"},{"default":"[]","description":"set paths of documents to exclude from inlining","name":"--disable-inlining","shorthand":"","type":"stringArray"},{"default":"","description":"set slash separated entrypoint path","name":"--entrypoint","shorthand":"-e","type":"string"},{"default":"off","description":"enable query explanations","name":"--explain","shorthand":"","type":"{off,full,notes,fails,debug}"},{"default":"false","description":"exits with non-zero exit code on undefined/empty result and errors","name":"--fail","shorthand":"","type":"bool"},{"default":"false","description":"exits with non-zero exit code on defined/non-empty result and errors","name":"--fail-defined","shorthand":"","type":"bool"},{"default":"json","description":"set output format","name":"--format","shorthand":"-f","type":"{json,values,bindings,pretty,source,raw,discard}"},{"default":"[]","description":"set file and directory names to ignore during loading (e.g., '.*' excludes hidden files)","name":"--ignore","shorthand":"","type":"stringSlice"},{"default":"","description":"set query import(s). This flag can be repeated.","name":"--import","shorthand":"","type":"string"},{"default":"","description":"set input file path","name":"--input","shorthand":"-i","type":"string"},{"default":"false","description":"enable query instrumentation metrics (implies --metrics)","name":"--instrument","shorthand":"","type":"bool"},{"default":"false","description":"report query performance metrics","name":"--metrics","shorthand":"","type":"bool"},{"default":"false","description":"evaluate nondeterministic builtins (if all arguments are known) during partial eval","name":"--nondeterminstic-builtins","shorthand":"","type":"bool"},{"default":"0","description":"set optimization level","name":"--optimize","shorthand":"-O","type":"int"},{"default":"false","description":"optimize default in-memory store for read speed. Has possible negative impact on memory footprint and write speed. See https://www.openpolicyagent.org/docs/latest/policy-performance/#storage-optimization for more details.","name":"--optimize-store-for-read-speed","shorthand":"","type":"bool"},{"default":"","description":"set query package","name":"--package","shorthand":"","type":"string"},{"default":"false","description":"perform partial evaluation","name":"--partial","shorthand":"-p","type":"bool"},{"default":"80","description":"set limit after which pretty output gets truncated","name":"--pretty-limit","shorthand":"","type":"int"},{"default":"false","description":"perform expression profiling","name":"--profile","shorthand":"","type":"bool"},{"default":"10","description":"set number of profiling results to show","name":"--profile-limit","shorthand":"","type":"int"},{"default":"","description":"set sort order of expression profiler results. Accepts: total_time_ns, num_eval, num_redo, num_gen_expr, file, line. This flag can be repeated.","name":"--profile-sort","shorthand":"","type":"string"},{"default":"","description":"set schema file path or directory path","name":"--schema","shorthand":"-s","type":"string"},{"default":"false","description":"disable inlining of rules that depend on unknowns","name":"--shallow-inlining","shorthand":"","type":"bool"},{"default":"false","description":"collect and return all encountered built-in errors, built in errors are not fatal","name":"--show-builtin-errors","shorthand":"","type":"bool"},{"default":"false","description":"read query from stdin","name":"--stdin","shorthand":"","type":"bool"},{"default":"false","description":"read input document from stdin","name":"--stdin-input","shorthand":"-I","type":"bool"},{"default":"false","description":"enable compiler strict mode","name":"--strict","shorthand":"-S","type":"bool"},{"default":"false","description":"treat the first built-in function error encountered as fatal","name":"--strict-builtin-errors","shorthand":"","type":"bool"},{"default":"rego","description":"set the runtime to exercise","name":"--target","shorthand":"-t","type":"{rego,wasm}"},{"default":"0s","description":"set eval timeout (default unlimited)","name":"--timeout","shorthand":"","type":"duration"},{"default":"[input]","description":"set paths to treat as unknown during partial evaluation","name":"--unknowns","shorthand":"-u","type":"stringArray"},{"default":"false","description":"opt-in to OPA features and behaviors prior to the OPA v1.0 release","name":"--v0-compatible","shorthand":"","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"},{"default":"false","description":"show local variable values in pretty trace output","name":"--var-values","shorthand":"","type":"bool"}],"id":"eval","long":"Evaluate a Rego query and print the result.","parent_flags":null,"short":"Evaluate a Rego query","use":"eval \u003cquery\u003e","useline":"opa eval \u003cquery\u003e [flags]"},{"children":null,"example":" Loading input from stdin:\n generate exec [\u003cpath\u003e [...]] --stdin-input [flags]\n","flags":[{"default":"","description":"set bundle file(s) or directory path(s). This flag can be repeated.","name":"--bundle","shorthand":"-b","type":"string"},{"default":"","description":"set path of configuration file","name":"--config-file","shorthand":"-c","type":"string"},{"default":"","description":"set decision to evaluate","name":"--decision","shorthand":"","type":"string"},{"default":"false","description":"exits with non-zero exit code on undefined result and errors","name":"--fail","shorthand":"","type":"bool"},{"default":"false","description":"exits with non-zero exit code on defined result and errors","name":"--fail-defined","shorthand":"","type":"bool"},{"default":"false","description":"exits with non-zero exit code on non-empty result and errors","name":"--fail-non-empty","shorthand":"","type":"bool"},{"default":"json","description":"set output format","name":"--format","shorthand":"-f","type":"{json}"},{"default":"json","description":"set log format","name":"--log-format","shorthand":"","type":"{text,json,json-pretty}"},{"default":"error","description":"set log level","name":"--log-level","shorthand":"-l","type":"{debug,info,error}"},{"default":"","description":"set log timestamp format (OPA_LOG_TIMESTAMP_FORMAT environment variable)","name":"--log-timestamp-format","shorthand":"","type":"string"},{"default":"[]","description":"override config values on the command line (use commas to specify multiple values)","name":"--set","shorthand":"","type":"stringArray"},{"default":"[]","description":"override config values with files on the command line (use commas to specify multiple values)","name":"--set-file","shorthand":"","type":"stringArray"},{"default":"false","description":"read input document from stdin rather than a static file","name":"--stdin-input","shorthand":"-I","type":"bool"},{"default":"0s","description":"set exec timeout with a Go-style duration, such as '5m 30s'. (default unlimited)","name":"--timeout","shorthand":"","type":"duration"},{"default":"false","description":"opt-in to OPA features and behaviors prior to the OPA v1.0 release","name":"--v0-compatible","shorthand":"","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"}],"id":"exec","long":"Execute against input files.\n\nThe 'exec' command executes OPA against one or more input files. If the paths\nrefer to directories, OPA will execute against files contained inside those\ndirectories, recursively.\n\nThe 'exec' command accepts a --config-file/-c or series of --set options as\narguments. These options behave the same as way as 'opa run'. Since the 'exec'\ncommand is intended to execute OPA in one-shot, the 'exec' command will\nmanually trigger plugins before and after policy execution:\n\nBefore: Discovery -\u003e Bundle -\u003e Status\nAfter: Decision Logs\n\nBy default, the 'exec' command executes the \"default decision\" (specified in\nthe OPA configuration) against each input file. This can be overridden by\nspecifying the --decision argument and pointing at a specific policy decision,\ne.g., opa exec --decision /foo/bar/baz ...\n","parent_flags":null,"short":"Execute against input files","use":"exec \u003cpath\u003e [\u003cpath\u003e [...]]","useline":"opa exec \u003cpath\u003e [\u003cpath\u003e [...]] [flags]"},{"children":null,"example":"","flags":[{"default":"true","description":"assert that the formatted code is valid and can be successfully parsed","name":"--check-result","shorthand":"","type":"bool"},{"default":"false","description":"only display a diff of the changes","name":"--diff","shorthand":"-d","type":"bool"},{"default":"false","description":"drop v0 imports from the formatted code, such as 'rego.v1' and 'future.keywords'","name":"--drop-v0-imports","shorthand":"","type":"bool"},{"default":"false","description":"non zero exit code on reformat","name":"--fail","shorthand":"","type":"bool"},{"default":"false","description":"list all files who would change when formatted","name":"--list","shorthand":"-l","type":"bool"},{"default":"false","description":"format module(s) to be compatible with both Rego v0 and v1","name":"--rego-v1","shorthand":"","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors prior to the OPA v1.0 release","name":"--v0-compatible","shorthand":"","type":"bool"},{"default":"false","description":"format module(s) to be compatible with both Rego v0 and v1","name":"--v0-v1","shorthand":"","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"},{"default":"false","description":"overwrite the original source file","name":"--write","shorthand":"-w","type":"bool"}],"id":"fmt","long":"Format Rego source files.\n\nThe 'fmt' command takes a Rego source file and outputs a reformatted version. If no file path\nis provided - this tool will use stdin.\nThe format of the output is not defined specifically; whatever this tool outputs\nis considered correct format (with the exception of bugs).\n\nIf the '-w' option is supplied, the 'fmt' command will overwrite the source file\ninstead of printing to stdout.\n\nIf the '-d' option is supplied, the 'fmt' command will output a diff between the\noriginal and formatted source.\n\nIf the '-l' option is supplied, the 'fmt' command will output the names of files\nthat would change if formatted. The '-l' option will suppress any other output\nto stdout from the 'fmt' command.\n\nIf the '--fail' option is supplied, the 'fmt' command will return a non zero exit\ncode if a file would be reformatted.\n\nThe 'fmt' command can be run in several compatibility modes for consuming and outputting\ndifferent Rego versions:\n\n* `opa fmt`:\n * v1 Rego is formatted to v1\n * `rego.v1`/`future.keywords` imports are NOT removed\n * `rego.v1`/`future.keywords` imports are NOT added if missing\n * v0 rego is rejected\n* `opa fmt --v0-compatible`:\n * v0 Rego is formatted to v0\n * v1 Rego is rejected\n* `opa fmt --v0-v1`:\n * v0 Rego is formatted to be compatible with v0 AND v1\n * v1 Rego is rejected\n* `opa fmt --v0-v1 --v1-compatible`:\n * v1 Rego is formatted to be compatible with v0 AND v1\n * v0 Rego is rejected\n","parent_flags":null,"short":"Format Rego source files","use":"fmt [path [...]]","useline":"opa fmt [path [...]] [flags]"},{"children":null,"example":"","flags":[{"default":"false","description":"list annotations","name":"--annotations","shorthand":"-a","type":"bool"},{"default":"pretty","description":"set output format","name":"--format","shorthand":"-f","type":"{json,pretty}"},{"default":"false","description":"opt-in to OPA features and behaviors prior to the OPA v1.0 release","name":"--v0-compatible","shorthand":"","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"}],"id":"inspect","long":"Inspect OPA bundle(s) or Rego files.\n\nThe 'inspect' command provides a summary of the contents in OPA bundle(s) or a single Rego file. Bundles are\ngzipped tarballs containing policies and data. The 'inspect' command reads bundle(s) and lists\nthe following:\n\n* packages that are contributed by .rego files\n* data locations defined by the data.json and data.yaml files\n* manifest data\n* signature data\n* information about the Wasm module files\n* package- and rule annotations\n\nExample:\n\n $ ls\n bundle.tar.gz\n $ opa inspect bundle.tar.gz\n\nYou can provide exactly one OPA bundle, path to a bundle directory, or direct path to a Rego file to the 'inspect' command\non the command-line. If you provide a path referring to a directory, the 'inspect' command will load that path as a bundle\nand summarize its structure and contents. If you provide a path referring to a Rego file, the 'inspect' command will load\nthat file and summarize its structure and contents.\n","parent_flags":null,"short":"Inspect OPA bundle(s) or Rego files.","use":"inspect \u003cpath\u003e [\u003cpath\u003e [...]]","useline":"opa inspect \u003cpath\u003e [\u003cpath\u003e [...]] [flags]"},{"children":null,"example":"","flags":[{"default":"pretty","description":"set output format","name":"--format","shorthand":"-f","type":"{pretty,json}"},{"default":"","description":"include or exclude optional elements. By default comments are included. Current options: locations, comments. E.g. --json-include locations,-comments will include locations and exclude comments.","name":"--json-include","shorthand":"","type":"string"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"}],"id":"parse","long":"Parse Rego source file and print AST.","parent_flags":null,"short":"Parse Rego source file","use":"parse \u003cpath\u003e","useline":"opa parse \u003cpath\u003e [flags]"},{"children":null,"example":"","flags":[{"default":"[localhost:8181]","description":"set listening address of the server (e.g., [ip]:\u003cport\u003e for TCP, unix://\u003cpath\u003e for UNIX domain socket)","name":"--addr","shorthand":"-a","type":"stringSlice"},{"default":"off","description":"set authentication scheme","name":"--authentication","shorthand":"","type":"{token,tls,off}"},{"default":"off","description":"set authorization scheme","name":"--authorization","shorthand":"","type":"{basic,off}"},{"default":"false","description":"load paths as bundle files or root directories","name":"--bundle","shorthand":"-b","type":"bool"},{"default":"","description":"set path of configuration file","name":"--config-file","shorthand":"-c","type":"string"},{"default":"[]","description":"set read-only diagnostic listening address of the server for /health and /metric APIs (e.g., [ip]:\u003cport\u003e for TCP, unix://\u003cpath\u003e for UNIX domain socket)","name":"--diagnostic-addr","shorthand":"","type":"stringSlice"},{"default":"false","description":"disables anonymous information reporting (see: https://www.openpolicyagent.org/docs/latest/privacy)","name":"--disable-telemetry","shorthand":"","type":"bool"},{"default":"[]","description":"set file names to exclude during bundle verification","name":"--exclude-files-verify","shorthand":"","type":"stringSlice"},{"default":"pretty","description":"set shell output format, i.e, pretty, json","name":"--format","shorthand":"-f","type":"string"},{"default":"false","description":"enable H2C for HTTP listeners","name":"--h2c","shorthand":"","type":"bool"},{"default":"/Users/charlieegan3/.opa_history","description":"set path of history file","name":"--history","shorthand":"-H","type":"string"},{"default":"[]","description":"set file and directory names to ignore during loading (e.g., '.*' excludes hidden files)","name":"--ignore","shorthand":"","type":"stringSlice"},{"default":"json","description":"set log format","name":"--log-format","shorthand":"","type":"{text,json,json-pretty}"},{"default":"info","description":"set log level","name":"--log-level","shorthand":"-l","type":"{debug,info,error}"},{"default":"","description":"set log timestamp format (OPA_LOG_TIMESTAMP_FORMAT environment variable)","name":"--log-timestamp-format","shorthand":"","type":"string"},{"default":"10","description":"set the number of errors to allow before compilation fails early","name":"--max-errors","shorthand":"-m","type":"int"},{"default":"1.2","description":"set minimum TLS version to be used by OPA's server","name":"--min-tls-version","shorthand":"","type":"{1.0,1.1,1.2,1.3}"},{"default":"false","description":"optimize default in-memory store for read speed. Has possible negative impact on memory footprint and write speed. See https://www.openpolicyagent.org/docs/latest/policy-performance/#storage-optimization for more details.","name":"--optimize-store-for-read-speed","shorthand":"","type":"bool"},{"default":"false","description":"enables pprof endpoints","name":"--pprof","shorthand":"","type":"bool"},{"default":"0","description":"wait (in seconds) for configured plugins before starting server (value \u003c= 0 disables ready check)","name":"--ready-timeout","shorthand":"","type":"int"},{"default":"","description":"scope to use for bundle signature verification","name":"--scope","shorthand":"","type":"string"},{"default":"false","description":"start the runtime in server mode","name":"--server","shorthand":"-s","type":"bool"},{"default":"[]","description":"override config values on the command line (use commas to specify multiple values)","name":"--set","shorthand":"","type":"stringArray"},{"default":"[]","description":"override config values with files on the command line (use commas to specify multiple values)","name":"--set-file","shorthand":"","type":"stringArray"},{"default":"10","description":"set the time (in seconds) that the server will wait to gracefully shut down","name":"--shutdown-grace-period","shorthand":"","type":"int"},{"default":"0","description":"set the time (in seconds) that the server will wait before initiating shutdown","name":"--shutdown-wait-period","shorthand":"","type":"int"},{"default":"RS256","description":"name of the signing algorithm","name":"--signing-alg","shorthand":"","type":"string"},{"default":"false","description":"disables type checking on known input schemas","name":"--skip-known-schema-check","shorthand":"","type":"bool"},{"default":"false","description":"disables bundle signature verification","name":"--skip-verify","shorthand":"","type":"bool"},{"default":"false","description":"disables anonymous version reporting (see: https://www.openpolicyagent.org/docs/latest/privacy)","name":"--skip-version-check","shorthand":"","type":"bool"},{"default":"","description":"set path of TLS CA cert file","name":"--tls-ca-cert-file","shorthand":"","type":"string"},{"default":"","description":"set path of TLS certificate file","name":"--tls-cert-file","shorthand":"","type":"string"},{"default":"0s","description":"set certificate refresh period","name":"--tls-cert-refresh-period","shorthand":"","type":"duration"},{"default":"[]","description":"set list of enabled TLS 1.0–1.2 cipher suites (IANA)","name":"--tls-cipher-suites","shorthand":"","type":"stringSlice"},{"default":"","description":"set path of TLS private key file","name":"--tls-private-key-file","shorthand":"","type":"string"},{"default":"755","description":"specify the permissions for the Unix domain socket if used to listen for incoming connections","name":"--unix-socket-perm","shorthand":"","type":"string"},{"default":"false","description":"opt-in to OPA features and behaviors prior to the OPA v1.0 release","name":"--v0-compatible","shorthand":"","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"},{"default":"","description":"set the secret (HMAC) or path of the PEM file containing the public key (RSA and ECDSA)","name":"--verification-key","shorthand":"","type":"string"},{"default":"default","description":"name assigned to the verification key used for bundle verification","name":"--verification-key-id","shorthand":"","type":"string"},{"default":"false","description":"watch command line files for changes","name":"--watch","shorthand":"-w","type":"bool"}],"id":"run","long":"Start an instance of the Open Policy Agent (OPA).\n\nTo run the interactive shell:\n\n $ opa run\n\nTo run the server:\n\n $ opa run -s\n\nThe 'run' command starts an instance of the OPA runtime. The OPA runtime can be\nstarted as an interactive shell or a server.\n\nWhen the runtime is started as a shell, users can define rules and evaluate\nexpressions interactively. When the runtime is started as a server, OPA exposes\nan HTTP API for managing policies, reading and writing data, and executing\nqueries.\n\nThe runtime can be initialized with one or more files that contain policies or\ndata. If the '--bundle' option is specified the paths will be treated as policy\nbundles and loaded following standard bundle conventions. The path can be a\ncompressed archive file or a directory which will be treated as a bundle.\nWithout the '--bundle' flag OPA will recursively load ALL rego, JSON, and YAML\nfiles.\n\nWhen loading from directories, only files with known extensions are considered.\nThe current set of file extensions that OPA will consider are:\n\n .json # JSON data\n .yaml or .yml # YAML data\n .rego # Rego file\n\nNon-bundle data file and directory paths can be prefixed with the desired\ndestination in the data document with the following syntax:\n\n \u003cdotted-path\u003e:\u003cfile-path\u003e\n\nTo set a data file as the input document in the interactive shell use the\n\"repl.input\" path prefix with the input file:\n\n repl.input:\u003cfile-path\u003e\n\nExample:\n\n $ opa run repl.input:input.json\n\nWhich will load the \"input.json\" file at path \"data.repl.input\".\n\nUse the \"help input\" command in the interactive shell to see more options.\n\n\nFile paths can be specified as URLs to resolve ambiguity in paths containing colons:\n\n $ opa run file:///c:/path/to/data.json\n\nURL paths to remote public bundles (http or https) will be parsed as shorthand\nconfiguration equivalent of using repeated --set flags to accomplish the same:\n\n\t$ opa run -s https://example.com/bundles/bundle.tar.gz\n\nThe above shorthand command is identical to:\n\n $ opa run -s --set \"services.cli1.url=https://example.com\" \\\n --set \"bundles.cli1.service=cli1\" \\\n --set \"bundles.cli1.resource=/bundles/bundle.tar.gz\" \\\n --set \"bundles.cli1.persist=true\"\n\nThe 'run' command can also verify the signature of a signed bundle.\nA signed bundle is a normal OPA bundle that includes a file\nnamed \".signatures.json\". For more information on signed bundles\nsee https://www.openpolicyagent.org/docs/latest/management-bundles/#signing.\n\nThe key to verify the signature of signed bundle can be provided\nusing the --verification-key flag. For example, for RSA family of algorithms,\nthe command expects a PEM file containing the public key.\nFor HMAC family of algorithms (eg. HS256), the secret can be provided\nusing the --verification-key flag.\n\nThe --verification-key-id flag can be used to optionally specify a name for the\nkey provided using the --verification-key flag.\n\nThe --signing-alg flag can be used to specify the signing algorithm.\nThe 'run' command uses RS256 (by default) as the signing algorithm.\n\nThe --scope flag can be used to specify the scope to use for\nbundle signature verification.\n\nExample:\n\n $ opa run --verification-key secret --signing-alg HS256 --bundle bundle.tar.gz\n\nThe 'run' command will read the bundle \"bundle.tar.gz\", check the\n\".signatures.json\" file and perform verification using the provided key.\nAn error will be generated if \"bundle.tar.gz\" does not contain a \".signatures.json\" file.\nFor more information on the bundle verification process see\nhttps://www.openpolicyagent.org/docs/latest/management-bundles/#signature-verification.\n\nThe 'run' command can ONLY be used with the --bundle flag to verify signatures\nfor existing bundle files or directories following the bundle structure.\n\nTo skip bundle verification, use the --skip-verify flag.\n\nThe --watch flag can be used to monitor policy and data file-system changes. When a change is detected, the updated policy\nand data is reloaded into OPA. Watching individual files (rather than directories) is generally not recommended as some\nupdates might cause them to be dropped by OPA.\n\nOPA will automatically perform type checking based on a schema inferred from known input documents and report any errors\nresulting from the schema check. Currently this check is performed on OPA's Authorization Policy Input document and will\nbe expanded in the future. To disable this, use the --skip-known-schema-check flag.\n\nThe --v0-compatible flag can be used to opt-in to OPA features and behaviors that were the default in OPA v0.x.\nBehaviors enabled by this flag include:\n- setting OPA's listening address to \":8181\" by default, corresponding to listening on every network interface.\n- expecting v0 Rego syntax in policy modules instead of the default v1 Rego syntax.\n\nThe --tls-cipher-suites flag can be used to specify the list of enabled TLS 1.0–1.2 cipher suites. Note that TLS 1.3\ncipher suites are not configurable. Following are the supported TLS 1.0 - 1.2 cipher suites (IANA):\nTLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA,\nTLS_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,\nTLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,\nTLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,\nTLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\nTLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256\n\nSee https://godoc.org/crypto/tls#pkg-constants for more information.\n","parent_flags":null,"short":"Start OPA in interactive or server mode","use":"run","useline":"opa run [flags]"},{"children":null,"example":"","flags":[{"default":"false","description":"load paths as bundle files or root directories","name":"--bundle","shorthand":"-b","type":"bool"},{"default":"","description":"set path of JSON file containing optional claims (see: https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format)","name":"--claims-file","shorthand":"","type":"string"},{"default":".","description":"set the location for the .signatures.json file","name":"--output-file-path","shorthand":"-o","type":"string"},{"default":"RS256","description":"name of the signing algorithm","name":"--signing-alg","shorthand":"","type":"string"},{"default":"","description":"set the secret (HMAC) or path of the PEM file containing the private key (RSA and ECDSA)","name":"--signing-key","shorthand":"","type":"string"},{"default":"","description":"name of the plugin to use for signing/verification (see https://www.openpolicyagent.org/docs/latest/management-bundles/#signature-plugin)","name":"--signing-plugin","shorthand":"","type":"string"}],"id":"sign","long":"Generate an OPA bundle signature.\n\nThe 'sign' command generates a digital signature for policy bundles. It generates a\n\".signatures.json\" file that dictates which files should be included in the bundle,\nwhat their SHA hashes are, and is cryptographically secure.\n\nThe signatures file is a JSON file with an array containing a single JSON Web Token (JWT)\nthat encapsulates the signature for the bundle.\n\nThe --signing-alg flag can be used to specify the algorithm to sign the token. The 'sign'\ncommand uses RS256 (by default) as the signing algorithm.\nSee https://www.openpolicyagent.org/docs/latest/configuration/#keys\nfor a list of supported signing algorithms.\n\nThe key to be used for signing the JWT MUST be provided using the --signing-key flag.\nFor example, for RSA family of algorithms, the command expects a PEM file containing\nthe private key.\nFor HMAC family of algorithms (eg. HS256), the secret can be provided using\nthe --signing-key flag.\n\nOPA 'sign' can ONLY be used with the --bundle flag to load paths that refer to\nexisting bundle files or directories following the bundle structure.\n\n\t$ opa sign --signing-key /path/to/private_key.pem --bundle foo\n\nWhere foo has the following structure:\n\n\tfoo/\n\t |\n\t +-- bar/\n\t | |\n\t | +-- data.json\n\t |\n\t +-- policy.rego\n\t |\n\t +-- .manifest\n\nThis will create a \".signatures.json\" file in the current directory.\nThe --output-file-path flag can be used to specify a different location for\nthe \".signatures.json\" file.\n\nThe content of the \".signatures.json\" file is shown below:\n\n\t{\n\t \"signatures\": [\n\t\t\"eyJhbGciOiJSUzI1NiJ9.eyJmaWxlcyI6W3sibmFtZSI6Ii5tYW5pZmVzdCIsImhhc2giOiIxODc0NWRlNzJjMDFlODBjZDlmNTIwZjQxOGMwMDlhYzRkMmMzZDAyYjE3YTUwZTJkMDQyMTU4YmMzNTJhMzJkIiwiYWxnb3JpdGhtIjoiU0hBLTI1NiJ9LHsibmFtZSI6ImJhci9kYXRhLmpzb24iLCJoYXNoIjoiOTNhMjM5NzFhOTE0ZTVlYWNiZjBhOGQyNTE1NGNkYTMwOWMzYzFjNzJmYmI5OTE0ZDQ3YzYwZjNjYjY4MTU4OCIsImFsZ29yaXRobSI6IlNIQS0yNTYifSx7Im5hbWUiOiJwb2xpY3kucmVnbyIsImhhc2giOiJkMGYyNDJhYWUzNGRiNTRlZjU2NmJlYTRkNDVmY2YxOTcwMGM1ZDhmODdhOWRiOTMyZGZhZDZkMWYwZjI5MWFjIiwiYWxnb3JpdGhtIjoiU0hBLTI1NiJ9XX0.lNsmRqrmT1JI4Z_zpY6IzHRZQAU306PyOjZ6osquixPuTtdSBxgbsdKDcp7Civw3B77BgygVsvx4k3fYr8XCDKChm0uYKScrpFr9_yS6g5mVTQws3KZncZXCQHdupRFoqMS8vXAVgJr52C83AinYWABwH2RYq_B0ZPf_GDzaMgzpep9RlDNecGs57_4zlyxmP2ESU8kjfX8jAA6rYFKeGXJHMD-j4SassoYIzYRv9YkHx8F8Y2ae5Kd5M24Ql0kkvqc_4eO_T9s4nbQ4q5qGHGE-91ND1KVn2avcUyVVPc0-XCR7EH8HnHgCl0v1c7gX1RL7ET7NJbPzfmzQAzk0ZW0dEHI4KZnXSpqy8m-3zAc8kIARm2QwoNEWpy3MWiooPeZVSa9d5iw1aLrbyumfjBP0vCQEPes-Aa6PrARwd5jR9SacO5By0-4emzskvJYRZqbfJ9tXSXDMcAFOAm6kqRPJaj8AO4CyajTC_Lt32_0OLeXqYgNpt3HDqLqGjrb-8fVeQc-hKh0aES8XehQqXj4jMwfsTyj5alsXZm08LwzcFlfQZ7s1kUtmr0_BBNJYcdZUdlu6Qio3LFSRYXNuu6edAO1VH5GKqZISvE1uvDZb2E0Z-rtH-oPp1iSpfvsX47jKJ42LVpI6OahEBri44dzHOIwwm3CIuV8gFzOwR0k\"\n\t ]\n\t}\n\nAnd the decoded JWT payload has the following form:\n\n\t{\n\t \"files\": [\n\t\t{\n\t\t \"name\": \".manifest\",\n\t\t \"hash\": \"18745de72c01e80cd9f520f418c009ac4d2c3d02b17a50e2d042158bc352a32d\",\n\t\t \"algorithm\": \"SHA-256\"\n\t\t},\n\t\t{\n\t\t \"name\": \"policy.rego\",\n\t\t \"hash\": \"d0f242aae34db54ef566bea4d45fcf19700c5d8f87a9db932dfad6d1f0f291ac\",\n\t\t \"algorithm\": \"SHA-256\"\n\t\t},\n\t\t{\n\t\t \"name\": \"bar/data.json\",\n\t\t \"hash\": \"93a23971a914e5eacbf0a8d25154cda309c3c1c72fbb9914d47c60f3cb681588\",\n\t\t \"algorithm\": \"SHA-256\"\n\t\t}\n\t ]\n\t}\n\nThe \"files\" field is generated from the files under the directory path(s)\nprovided to the 'sign' command. During bundle signature verification, OPA will check\neach file name (ex. \"foo/bar/data.json\") in the \"files\" field\nexists in the actual bundle. The file content is hashed using SHA256.\n\nTo include additional claims in the payload use the --claims-file flag to provide\na JSON file containing optional claims.\n\nFor more information on the format of the \".signatures.json\" file see\nhttps://www.openpolicyagent.org/docs/latest/management-bundles/#signature-format.\n","parent_flags":null,"short":"Generate an OPA bundle signature","use":"sign \u003cpath\u003e [\u003cpath\u003e [...]]","useline":"opa sign \u003cpath\u003e [\u003cpath\u003e [...]] [flags]"},{"children":null,"example":"","flags":[{"default":"false","description":"benchmark the unit tests","name":"--bench","shorthand":"","type":"bool"},{"default":"true","description":"report memory allocations with benchmark results","name":"--benchmem","shorthand":"","type":"bool"},{"default":"false","description":"load paths as bundle files or root directories","name":"--bundle","shorthand":"-b","type":"bool"},{"default":"","description":"set capabilities version or capabilities.json file path","name":"--capabilities","shorthand":"","type":"string"},{"default":"1","description":"number of times to repeat each test","name":"--count","shorthand":"","type":"int"},{"default":"false","description":"report coverage (overrides debug tracing)","name":"--coverage","shorthand":"-c","type":"bool"},{"default":"false","description":"skipped tests return status 0","name":"--exit-zero-on-skipped","shorthand":"-z","type":"bool"},{"default":"fails","description":"enable query explanations","name":"--explain","shorthand":"","type":"{fails,full,notes,debug}"},{"default":"pretty","description":"set output format","name":"--format","shorthand":"-f","type":"{pretty,json,gobench}"},{"default":"[]","description":"set file and directory names to ignore during loading (e.g., '.*' excludes hidden files)","name":"--ignore","shorthand":"","type":"stringSlice"},{"default":"10","description":"set the number of errors to allow before compilation fails early","name":"--max-errors","shorthand":"-m","type":"int"},{"default":"","description":"run only test cases matching the regular expression.","name":"--run","shorthand":"-r","type":"string"},{"default":"","description":"set schema file path or directory path","name":"--schema","shorthand":"-s","type":"string"},{"default":"rego","description":"set the runtime to exercise","name":"--target","shorthand":"-t","type":"{rego,wasm}"},{"default":"0","description":"set coverage threshold and exit with non-zero status if coverage is less than threshold %","name":"--threshold","shorthand":"","type":"float64"},{"default":"0s","description":"set test timeout (default 5s, 30s when benchmarking)","name":"--timeout","shorthand":"","type":"duration"},{"default":"false","description":"opt-in to OPA features and behaviors prior to the OPA v1.0 release","name":"--v0-compatible","shorthand":"","type":"bool"},{"default":"false","description":"opt-in to OPA features and behaviors that are enabled by default in OPA v1.0","name":"--v1-compatible","shorthand":"","type":"bool"},{"default":"false","description":"show local variable values in test output","name":"--var-values","shorthand":"","type":"bool"},{"default":"false","description":"set verbose reporting mode","name":"--verbose","shorthand":"-v","type":"bool"},{"default":"false","description":"watch command line files for changes","name":"--watch","shorthand":"-w","type":"bool"}],"id":"test","long":"Execute Rego test cases.\n\nThe 'test' command takes a file or directory path as input and executes all\ntest cases discovered in matching files. Test cases are rules whose names have the prefix \"test_\".\n\nIf the '--bundle' option is specified the paths will be treated as policy bundles\nand loaded following standard bundle conventions. The path can be a compressed archive\nfile or a directory which will be treated as a bundle. Without the '--bundle' flag OPA\nwill recursively load ALL *.rego, *.json, and *.yaml files for evaluating the test cases.\n\nTest cases under development may be prefixed \"todo_\" in order to skip their execution,\nwhile still getting marked as skipped in the test results.\n\nExample policy (example/authz.rego):\n\n\tpackage authz\n\n\tallow if {\n\t\tinput.path == [\"users\"]\n\t\tinput.method == \"POST\"\n\t}\n\n\tallow if {\n\t\tinput.path == [\"users\", input.user_id]\n\t\tinput.method == \"GET\"\n\t}\n\nExample test (example/authz_test.rego):\n\n\tpackage authz_test\n\n\timport data.authz.allow\n\n\ttest_post_allowed if {\n\t\tallow with input as {\"path\": [\"users\"], \"method\": \"POST\"}\n\t}\n\n\ttest_get_denied if {\n\t\tnot allow with input as {\"path\": [\"users\"], \"method\": \"GET\"}\n\t}\n\n\ttest_get_user_allowed if {\n\t\tallow with input as {\"path\": [\"users\", \"bob\"], \"method\": \"GET\", \"user_id\": \"bob\"}\n\t}\n\n\ttest_get_another_user_denied if {\n\t\tnot allow with input as {\"path\": [\"users\", \"bob\"], \"method\": \"GET\", \"user_id\": \"alice\"}\n\t}\n\n\ttodo_test_user_allowed_http_client_data if {\n\t\tfalse # Remember to test this later!\n\t}\n\nExample test run:\n\n\t$ opa test ./example/\n\nIf used with the '--bench' option then tests will be benchmarked.\n\nExample benchmark run:\n\n\t$ opa test --bench ./example/\n\nThe optional \"gobench\" output format conforms to the Go Benchmark Data Format.\n\nThe --watch flag can be used to monitor policy and data file-system changes. When a change is detected, OPA reloads\nthe policy and data and then re-runs the tests. Watching individual files (rather than directories) is generally not\nrecommended as some updates might cause them to be dropped by OPA.\n","parent_flags":null,"short":"Execute Rego test cases","use":"test \u003cpath\u003e [path [...]]","useline":"opa test \u003cpath\u003e [path [...]] [flags]"},{"children":null,"example":"","flags":[{"default":"false","description":"check for latest OPA release","name":"--check","shorthand":"-c","type":"bool"}],"id":"version","long":"Show version and build information for OPA.","parent_flags":null,"short":"Print the version of OPA","use":"version","useline":"opa version [flags]"}]