### Install Oso Cloud SDK for Node.js Source: https://osohq.com/docs/quickstart Instructions to install the Oso Cloud Software Development Kit (SDK) for Node.js using npm, enabling easy integration of Oso authorization into applications. ```Node npm install oso-cloud ``` -------------------------------- ### Install Oso Cloud Go Client Package Source: https://osohq.com/docs/app-integration/client-apis/go/v1 Instructions to install the `go-oso-cloud` package using `go get`. ```Go go get github.com/osohq/go-oso-cloud ``` -------------------------------- ### Examples of `get` with `FactPattern` in Oso Cloud Java Source: https://osohq.com/docs/app-integration/client-apis/java/migrating-to-v1 These examples demonstrate various uses of the v1 `get(FactPattern)` method in Oso Cloud Java, including retrieving specific facts, listing all roles for a user on any resource, and listing all roles on a specific repository for any user. ```Java import com.osohq.oso_cloud.Oso; import com.osohq.oso_cloud.Value; import com.osohq.oso_cloud.Fact; import com.osohq.oso_cloud.FactPattern; import com.osohq.oso_cloud.ValuePattern; ... Oso oso = new Oso(YOUR_API_KEY); Value user = new Value("User", "1"); Value repo = new Value("Repository", "anvils"); // Get specific fact Fact[] specificRole = oso.get(new FactPattern("has_role", user, new Value("admin"), repo)); // List all roles for User:1 on any resource Fact[] userRoles = oso.get(new FactPattern("has_role", user, ValuePattern.ANY, ValuePattern.ANY)); // List all roles on the 'anvils' repo for any user Fact[] repoRoles = oso.get(new FactPattern( "has_role", new ValuePattern.ValueOfType("User"), // Or ValuePattern.ANY for any type ValuePattern.ANY, repo )); ``` -------------------------------- ### Initialize Oso Dev Server with Policy Files Source: https://osohq.com/docs/development/oso-dev-server This command line example shows how to start the Oso Dev Server and load multiple policy files upon startup. This is useful for initializing the server's environment with predefined policies. ```Shell ./standalone main.polar tests.polar ``` -------------------------------- ### Install Oso Cloud Clients Source: https://osohq.com/docs/oso-in-depth/end-to-end-example Install the Oso Cloud client libraries for Python and Node.js using their respective package managers (pip and yarn) to enable communication with the Oso Cloud service. ```Shell # In the Python project pip install oso-cloud # In the Node.js project yarn add oso-cloud ``` -------------------------------- ### Install Oso Cloud Go Client Package Source: https://osohq.com/docs/app-integration/client-apis/go Installs the latest version of the `go-oso-cloud` package using `go get` to enable interaction with the Oso Cloud API. ```Go go get github.com/osohq/go-oso-cloud/v2@latest ``` -------------------------------- ### Authorize User Bob to Edit Item in Node.js Source: https://osohq.com/docs/quickstart Shows how to modify the previous authorization example to check if user "Bob" can "edit" the same "Item". This demonstrates a scenario where authorization might fail, as Bob is expected to be a "viewer". ```Node import { Oso } from 'oso-cloud' const apiKey = process.env.OSO_CLOUD_API_KEY; const oso = new Oso("https://cloud.osohq.com", apiKey); const authorized = await oso.authorize( {type: "User", id: "Bob"}, "edit", {type: "Item", id: "foo"} ); console.log("Authorization result was " + authorized); ``` -------------------------------- ### Migrate Get API for Zero-Valued Instance Wildcard Source: https://osohq.com/docs/app-integration/client-apis/go/migrating-to-v2 Migration guide for replacing the zero-valued `oso.Instance` wildcard with `nil` when fetching facts with `oso.Get`. This applies when you want to match any resource. ```Go // Fetch all has_role facts for Users with an admin role on any resource - oso.Get( - "has_role", - oso.Instance{Type: "User"}, - oso.String("admin"), - oso.Instance{}, - ) + oso.Get(oso.NewFactPattern( + "has_role", + oso.NewValueOfType("User"), + oso.String("admin"), + nil, + )) ``` -------------------------------- ### Install Oso Cloud CLI Source: https://osohq.com/docs/app-integration/client-apis/cli Provides the command to download and install the Oso Cloud CLI package, followed by a command to verify the installation. ```bash curl -L https://cloud.osohq.com/install.sh | bash ``` ```bash which oso-cloud ``` -------------------------------- ### Configure Oso LSP in JetBrains IDEs Source: https://osohq.com/docs/development/set-up-your-environment Steps to install and configure the Oso Language Server Protocol (LSP) in JetBrains IDEs using the LSP4IJ plugin. This setup enables features like syntax validation, shorthand expansion, and unit test integration for Polar policy files. ```IDE Configuration * Install the LSP4IJ plugin * Go to Language & Frameworks > Language Servers * Create a new one with: Server > Command: `oso-cloud lsp`, Mappings > File name patterns: `*.polar` , language ID: `polar` ``` -------------------------------- ### Start Oso Dev Server in Test Mode Source: https://osohq.com/docs/development/workflow-walkthrough Command to start the `standalone` Oso Dev Server executable. It shows the output indicating the server is in test mode and provides the API token required for interaction. ```Bash ❯ ~/.local/bin/standalone Server is in test mode, use token 'e_0123456789_12345_osotesttoken01xiIn' ``` -------------------------------- ### Example: Initializing a Query with `oso.buildQuery` Source: https://osohq.com/docs/app-integration/client-apis/node Illustrates how to initialize a query using `oso.buildQuery` with concrete and typed variable arguments. Note that `evaluate` must be called to run the query. ```javascript const actor = { type: "User", id: "bob" }; const repository = typedVar("Repository"); // Query for all the repositories bob can read oso.buildQuery(["allow", actor, "read", repository]); // => QueryBuilder { ... } ``` -------------------------------- ### Oso Migrate: Client Library Installation Source: https://osohq.com/docs/app-integration/client-apis/node This command installs the Oso Cloud client library that includes Oso Migrate, a suite of developer tools for migrating legacy authorization systems. Ensure you install version 2.5.2 or later. ```NPM npm install oso-cloud@latest ``` -------------------------------- ### Migrate Get API for Specific Facts Source: https://osohq.com/docs/app-integration/client-apis/go/migrating-to-v2 Migration guide for updating `oso.Get` calls. This involves replacing `oso.Instance` with `oso.NewValue` and wrapping them in a call to `oso.NewFactPattern`. ```Go - oso.Get( - "has_role", - oso.Instance{Type: "User", ID: "bob"}, - oso.String("admin"), - oso.Instance{Type: "Repository", ID: "anvils"}, - ) + oso.Get(oso.NewFactPattern( + "has_role", + oso.NewValue("User", "bob"), + oso.String("admin"), + oso.NewValue("Repository", "anvils"), + )) ``` -------------------------------- ### Oso Cloud Client Setup and Initialization Source: https://osohq.com/docs/app-integration/client-apis/python/v1 This section outlines the initial steps for setting up and configuring the Oso Cloud client, including instantiation, specifying a fallback host, and passing application entities. ```APIDOC Instantiating an Oso Cloud client Specifying an Oso Fallback host Passing application entities into the client ``` -------------------------------- ### Install Oso Migrate Client Library Source: https://osohq.com/docs/app-integration/client-apis/ruby Instructions to install the Oso Cloud client library that includes Oso Migrate features. This enables developers to use the migration tooling suite for incrementally transitioning legacy authorization systems to Oso. ```Shell # install latest version gem install oso-cloud ``` -------------------------------- ### Initialize Koala Analytics SDK Source: https://www.osohq.com/company/security Initializes the Koala analytics SDK by setting the host and defining `ko` functions for tracking and identification. It dynamically loads the SDK script into the document. ```JavaScript window.koalaSettings = { host: 'https://koala-proxy.analytics.osohq.com' } !function (t) { if (window.ko) return; window.ko = [], ["identify", "track", "removeListeners", "open", "on", "off", "qualify", "ready"].forEach(function (t) { ko[t] = function () { var n = [].slice.call(arguments); return n.unshift(t), ko.push(n), ko } }); var n = document.createElement("script"); n.async = !0, n.setAttribute("src", "https://koala-cdn.analytics.osohq.com/v1/oso/sdk.js"), (document.body || document.head).appendChild(n) }(); ``` -------------------------------- ### Install Oso Migrate client library (CLI) Source: https://osohq.com/docs/app-integration/client-apis/dotnet Instructions to install the Oso Cloud client library version 1.9.0 or higher, which includes Oso Migrate tools, using the .NET CLI command `dotnet add package`. ```Shell # install latest version: dotnet add package OsoCloud --version 1.9.0 ``` -------------------------------- ### Initialize QueryBuilder: osoClient.BuildQuery example in Go Source: https://osohq.com/docs/app-integration/client-apis/go Demonstrates how to initialize a query using `osoClient.BuildQuery()` with concrete values and type-constrained variables. This returns a `QueryBuilder` object for further chaining. ```Go actor := oso.NewValue("User", "bob") repository := oso.TypedVar("Repository") // Query for all the repositories bob can read osoClient.BuildQuery(oso.NewQueryFact("allow", actor, oso.String("read"), repository)) // => QueryBuilder { ... } ``` -------------------------------- ### Install Oso Cloud Ruby Gem Source: https://osohq.com/docs/app-integration/client-apis/ruby Instructions for installing the `oso-cloud` gem from RubyGems via the command line or by adding it to your `Gemfile`. This gem provides the necessary client for interacting with Oso Cloud. ```Ruby gem install oso-cloud -v 1.10.0 ``` ```Ruby gem 'oso-cloud', '~> 1.10', '>= 1.10.0' ``` -------------------------------- ### Installing Oso Cloud Client Library for Migrate Source: https://osohq.com/docs/app-integration/client-apis/python Provides the pip command to install the Oso Cloud client library, specifically mentioning the version required for Oso Migrate features. ```Shell pip install oso-cloud==2.5.0 ``` -------------------------------- ### Add Fact to Oso Cloud (Go) Source: https://osohq.com/docs/app-integration/client-apis/go Illustrates how to add a new fact to Oso Cloud using the `osoClient.Insert()` method. This example provides a complete Go program setup, including client initialization and inserting a `has_role` fact. ```Go package main import ( "os" "fmt" oso "github.com/osohq/go-oso-cloud/v2" ) func main { apiKey := os.Getenv("OSO_CLOUD_API_KEY") osoClient := oso.NewClient("https://cloud.osohq.com", apiKey) osoClient.Insert(oso.NewFact( "has_role", oso.NewValue("User", "bob"), oso.String("owner"), oso.NewValue("Organization", "acme") )) } ``` -------------------------------- ### Install Oso Cloud Node.js Package Source: https://osohq.com/docs/app-integration/client-apis/node This command installs the `oso-cloud` package from NPM, which is the official Node.js client library for Oso Cloud. It specifies version 2.5.2. ```bash npm install oso-cloud@2.5.2 ``` -------------------------------- ### Install Oso Cloud Python Client Source: https://osohq.com/docs/app-integration/client-apis/python Instructions for installing the `oso-cloud` package using pip. This is the first step to integrate Oso Cloud into a Python application. ```Python pip install oso-cloud==2.5.0 ``` -------------------------------- ### Verify Oso Cloud CLI Installation Source: https://osohq.com/docs/app-integration/client-apis/cli/windows After installing the Oso Cloud CLI, run this command from your PowerShell prompt to verify the installation. It displays the CLI's help information, confirming it's correctly set up. ```PowerShell C:\\oso_cli --help ``` -------------------------------- ### Install Oso Cloud .NET Client Package Source: https://osohq.com/docs/app-integration/client-apis/dotnet Instructions to install the OsoCloud NuGet package using the .NET CLI. This package provides the necessary client libraries to interact with the Oso Cloud service. ```.NET dotnet add package OsoCloud --version 1.9.0 ``` -------------------------------- ### Start Oso Cloud LSP Server Source: https://osohq.com/docs/app-integration/client-apis/ide-support This command starts the Language Server Protocol (LSP) server for Oso Cloud, allowing any LSP-compatible editor to integrate with Oso's policy diagnostics and features. Users should consult their editor's documentation for specific LSP configuration instructions. ```Shell oso-cloud lsp ``` -------------------------------- ### Instantiate Oso Cloud Client in Go Source: https://osohq.com/docs/app-integration/client-apis/go/v1 Demonstrates how to import the Oso Cloud Go client and instantiate it with your Oso Cloud URL and API key. Includes examples of `Tell` and `Authorize` calls. ```Go import ( ... oso "github.com/osohq/go-oso-cloud" ) osoClient := oso.NewClient("https://cloud.osohq.com", YOUR_API_KEY) // Later: e := osoClient.Tell("has_role", user, role, resource) if e != nil { // Handle error. } // Wherever authorization needs to be performed: allowed, e := osoClient.Authorize(user, action, resource) if e != nil { // Handle error. } if allowed { // Action is allowed. } ``` -------------------------------- ### GitHub Actions Workflow for Isolated Oso Dev Server Environment Source: https://osohq.com/docs/development/ci-cd This GitHub Actions workflow demonstrates how to set up and use an isolated Oso Dev Server environment for policy testing. It includes steps to install the Oso Cloud CLI and Dev Server, start the server, create a new test environment using the `test_environment` endpoint, and push a policy to it. This ensures that each test run operates in a clean, dedicated environment. ```YAML create-new-environment-on-oso-dev-server: runs-on: ubuntu-latest env: ARCHIVE_URL: "https://oso-local-development-binary.s3.amazonaws.com/latest/oso-local-development-binary-linux-x86_64.tar.gz" OUTPUT_FILENAME: "oso-dev-server.tar.gz" OSO_URL: "http://localhost:8080" steps: - name: Check out repository code uses: actions/checkout@v4 - name: Install Oso Cloud CLI run: | curl -L https://cloud.osohq.com/install.sh | bash - name: Install Oso Dev Server run: | curl ${ARCHIVE_URL} --output ${OUTPUT_FILENAME} tar -xzf ${OUTPUT_FILENAME} rm ${OUTPUT_FILENAME} chmod 0700 standalone - name: Start Oso Dev Server in the background run: | ./standalone & - name: Create new environment and store API key in environment run: | echo "OSO_AUTH=$(curl -s -X POST http://localhost:8080/test_environment\?copy\=false | jq -r '.token')" >> "$GITHUB_ENV" - name: Push the policy to the new environment run: | oso-cloud policy policy/policy.polar ``` -------------------------------- ### Example: Chaining Conditions with `QueryBuilder.and` Source: https://osohq.com/docs/app-integration/client-apis/node Demonstrates how to chain multiple conditions using `QueryBuilder.and()` to refine a query. This example adds a requirement for repositories to belong to a specific folder. Note that `evaluate` must be called to run the query. ```javascript const actor = { type: "User", id: "bob" }; const repository = typedVar("Repository"); const folder = { type: "Folder", id: "folder-1" }; // Query for all the repositories this user can read... oso .buildQuery(["allow", actor, "read", repository]) //... and require the repositories to belong to the given folder. .and(["has_relation", repository, "folder", folder]); // => QueryBuilder { ... } ``` -------------------------------- ### Load Wisepops Marketing Script Source: https://www.osohq.com/company/security Integrates the Wisepops marketing script by defining a global function `wisepops` and dynamically inserting the loader script into the document. This script is used for displaying popups and other marketing elements. ```JavaScript (function(w,i,s,e){window[w]=window[w]||function(){(window[w].q=window[w].q||[]).push(arguments)};window[w].l=Date.now();s=document.createElement('script');e=document.getElementsByTagName('script')[0];s.defer=1;s.src=i;e.parentNode.insertBefore(s, e)})('wisepops', 'https://wisepops.net/loader.js?v=3&h=NgwtMc5Uzd'); ``` -------------------------------- ### Initialize Oso Cloud Client in Python Source: https://osohq.com/docs/oso-in-depth/end-to-end-example Initialize a global Oso Cloud client instance in the Python service. The client is stateless and uses an API key retrieved from environment variables for authentication. ```Python from oso_cloud import Oso oso = Oso(api_key=getenv("OSO_AUTH")) ``` -------------------------------- ### Authorize User Alice to Edit Item in Node.js Source: https://osohq.com/docs/quickstart Demonstrates how to import the Oso SDK, instantiate an Oso client with an API key, and authorize a user named "Alice" to perform the "edit" action on an "Item" named "foo". The result of the authorization check is logged. ```Node import { Oso } from 'oso-cloud' const apiKey = process.env.OSO_CLOUD_API_KEY; const oso = new Oso("https://cloud.osohq.com", apiKey); const authorized = await oso.authorize( {type: "User", id: "Alice"}, "edit", {type: "Item", id: "foo"} ); console.log("Authorization result was " + authorized); ``` -------------------------------- ### Policy Debugger Query Visualization Example Source: https://osohq.com/docs/development/oso-migrate This snippet shows how a query is initially presented in the Oso Policy Debugger. It illustrates the query `allow(User{"alice"}, "view", Content{"foo"})` with indicators for expansion/collapse, success/failure, and multiple possible resolution paths. ```text ▶ allow(User{\"alice\"}, \"view\", Content{\"foo\"}) ← ● ○ → ``` -------------------------------- ### Authorize User with Node.js Oso Cloud SDK Source: https://osohq.com/docs/quickstart Demonstrates how to use the Node.js Oso Cloud SDK to authorize a user's action on a resource. This involves initializing the Oso client with an API key and calling the `authorize` method with user, action, and resource details. The result indicates whether the action is authorized. ```Node.js import { Oso } from 'oso-cloud' const apiKey = process.env.OSO_CLOUD_API_KEY; const oso = new Oso("https://cloud.osohq.com", apiKey); const authorized = await oso.authorize( {type: "User", id: "Alice"}, "view", {type: "Item", id: "foo"} ); console.log("Authorization result was " + authorized); ``` -------------------------------- ### Define and Use Oso Policy Test Fixtures Source: https://osohq.com/docs/modeling-in-polar/reference/tests This snippet demonstrates how to define a `test fixture` block in Oso Policy to reuse common setup data across multiple tests. It includes examples of asserting permissions with and without additional setup, showing how fixtures simplify test setup. ```Polar test fixture acme { has_role(User{"alice"}, "admin", Organization{"acme"}); has_role(User{"bob"}, "member", Organization{"acme"}); has_relation(Repository{"foo"}, "organization", Organization{"acme"}); is_private(Repository{"foo"}); } test "by default, members cannot read private repositories" { setup { fixture acme; } assert allow(User{"alice"}, "read", Repository{"foo"}); assert_not allow(User{"bob"}, "read", Repository{"foo"}); } test "members can read private repositories if they have direct access" { setup { fixture acme; has_role(User{"bob"}, "reader", Repository{"foo"}); } assert allow(User{"bob"}, "read", Repository{"foo"}); } ``` -------------------------------- ### Define Initial Polar Policy Test Source: https://osohq.com/docs/development/workflow-walkthrough An example of a basic Polar test block (`test "example test"`) demonstrating how to set up conditions (`setup`) and assert authorization outcomes (`assert allow`). This test validates organization role logic. ```Polar test "example test" { setup { has_role(User{"alice"}, "member", Organization{"org1"}); } assert allow(User{"alice"}, "view", Organization{"org1"}); } ``` -------------------------------- ### Initialize Theme Switching Logic for Oso Docs Source: https://osohq.com/docs/development/oso-migrate This JavaScript snippet handles the initial theme (light/dark) setup for the Oso documentation site. It checks local storage for a saved theme preference or defaults to the system's color scheme preference, applying the appropriate CSS class and color-scheme property to the document element. ```JavaScript !function(){try{var d=document.documentElement,c=d.classList;c.remove('light','dark');var e=localStorage.getItem('theme');if('system'===e||(!e&&true)){var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);if(m.media!==t||m.matches){d.style.colorScheme = 'dark';c.add('dark')}else{d.style.colorScheme = 'light';c.add('light')}}else if(e){c.add(e|| '')}if(e==='light'||e==='dark')d.style.colorScheme=e}catch(e){}}() ``` -------------------------------- ### Retrieve variable values with EvaluateArgs.values() (Java) Source: https://osohq.com/docs/app-integration/client-apis/java Returns a `List` of values for a specified variable. This example shows how to get all actions an actor can perform on a given resource. ```Java import com.osohq.oso_cloud.Oso; import com.osohq.oso_cloud.Value; import com.osohq.oso_cloud.TypedVar; import com.osohq.oso_cloud.QueryBuilder.EvaluateArgs; import java.util.List; // ... Oso oso = new Oso(YOUR_API_KEY); Value actor = new Value("User", "bob"); Value resource = new Value("Repository", "acme"); TypedVar actionVar = new TypedVar("String"); List actions = oso .buildQuery("allow", actor, actionVar, resource) .evaluate(EvaluateArgs.values(actionVar)); // => all the actions the actor can perform on the given resource- eg. ["read", "write"] ``` -------------------------------- ### GitHub Actions Job to Test Oso Policies Against Dev Server Source: https://osohq.com/docs/development/ci-cd This GitHub Actions job configures a CI environment to run Oso policy tests against a locally installed Oso Dev Server. It checks out the code, installs both the Oso Cloud CLI and the Dev Server, starts the Dev Server in the background, and then executes tests against a specified policy file. ```yaml test-policy-with-oso-dev-server: runs-on: ubuntu-latest env: ARCHIVE_URL: "https://oso-local-development-binary.s3.amazonaws.com/latest/oso-local-development-binary-linux-x86_64.tar.gz" OUTPUT_FILENAME: "oso-dev-server.tar.gz" OSO_URL: "http://localhost:8080" OSO_AUTH: "e_0123456789_12345_osotesttoken01xiIn" steps: - name: Check out repository code uses: actions/checkout@v4 - name: Install Oso Cloud CLI run: | curl -L https://cloud.osohq.com/install.sh | bash - name: Install Oso Dev Server run: | curl ${ARCHIVE_URL} --output ${OUTPUT_FILENAME} tar -xzf ${OUTPUT_FILENAME} rm ${OUTPUT_FILENAME} chmod 0700 standalone - name: Start Oso Dev Server in the background run: | ./standalone & - name: Run policy tests against the Oso Dev Server run: | oso-cloud test policy/policy.polar ``` -------------------------------- ### Initialize Oso Node.js Client Source: https://osohq.com/docs/development/set-up-your-environment This snippet demonstrates how to instantiate the Oso Node.js client. It requires a local URL for the Oso Dev Server and an API token for authentication. This setup is crucial for connecting your application to the Oso policy engine. ```Node.js const { Oso } = require("oso-cloud"); const oso = new Oso( "http://localhost:8080", "e_0123456789_12345_osotesttoken01xiIn" ); ``` -------------------------------- ### Define and Use Test Fixtures in Oso Polar Source: https://osohq.com/docs/changelog/oso-dev-server This example demonstrates how to define and utilize test fixtures in Oso's Polar policy language. Fixtures allow sharing setup facts across multiple tests, reducing redundancy. It shows a `test fixture` definition and its inclusion in `test` blocks using `setup { fixture bar; }`. ```Polar foo(x: Integer, y: Boolean, z: String) if bar(x, y, z); test fixture bar { bar(1, false, "hi"); } test "foo 1" { assert_not foo(1, false, "hi"); } test "foo 2" { setup { fixture bar; } assert foo(1, false, "hi"); } test "foo 3" { setup { fixture bar; } assert foo(1, false, "hi"); } ``` -------------------------------- ### Dockerfile for Oso Dev Server Deployment Source: https://osohq.com/docs/development/ci-cd This Dockerfile sets up a minimal Debian image, installs base dependencies, creates a dedicated runtime environment for the application, and fetches the Oso Dev Server binary. It configures environment variables for the server's data directory and port, setting the entrypoint to run the standalone server. ```Dockerfile FROM debian:bookworm-slim # install base dependencies RUN apt-get update && apt-get install -y curl ca-certificates && rm -rf /var/lib/apt/lists/* # create the runtime environment for the app RUN useradd -ms /bin/bash app RUN mkdir -p /app && chown app:app /app # create data directory RUN mkdir -p /data && chown app:app /data USER app WORKDIR /app # fetch the Oso Dev Server RUN curl https://oso-local-development-binary.s3.amazonaws.com/latest/oso-local-development-binary-linux-x86_64.tar.gz --output oso-dev-server.tar.gz && tar -xzf oso-dev-server.tar.gz && rm oso-dev-server.tar.gz RUN chmod +x ./standalone ENV OSO_DIRECTORY=/data ENV OSO_PORT=8080 ENTRYPOINT ["/app/standalone"] ``` -------------------------------- ### Migrate Get API for Type-Based Wildcard Source: https://osohq.com/docs/app-integration/client-apis/go/migrating-to-v2 Migration guide for fetching facts with arguments of a particular type (but no specific ID). This involves using `oso.NewValueOfType` instead of `oso.Instance` with only a `Type`. ```Go // Fetch all has_role facts for Users with an admin role on Repository anvils - oso.Get( - "has_role", - oso.Instance{Type: "User"}, - oso.String("admin"), - oso.Instance{Type: "Repository", ID: "anvils"}, - ) + oso.Get(oso.NewFactPattern( + "has_role", + oso.NewValueOfType("User"), + oso.String("admin"), + oso.NewValue("Repository", "anvils"), + )) ``` -------------------------------- ### Testing Authorization Policies with Example Data in Oso Polar Source: https://osohq.com/docs/modeling-in-polar This snippet demonstrates how to write policy tests in Oso Polar using a `setup` block to define example data and `assert` statements to verify authorization outcomes. It sets up a user 'alice' as an admin of 'project-1' and two tasks belonging to different projects, then asserts that 'alice' can read 'task-1' but not 'task-2', validating the defined 'read' permission logic. ```Polar resource Organization { # ... } resource Project { roles = ["admin"]; relations = { organization: Organization, }; # ... } resource Task { permissions = ["read"]; relations = { project: Project, }; "read" if "admin" on "project"; # ... } test "project admins can read tasks" { setup { has_role(User{"alice"}, "admin", Project{"project-1"}); has_relation(Task{"task-1"}, "project", Project{"project-1"}); has_relation(Task{"task-2"}, "project", Project{"project-2"}); } assert allow(User{"alice"}, "read", Task{"task-1"}); assert_not allow(User{"alice"}, "read", Task{"task-2"}); } ``` -------------------------------- ### Initialize Oso Migrate with Standalone Binary Source: https://osohq.com/docs/development/oso-migrate For MacOS and Linux users, this command initializes Oso Migrate by running the Oso Dev Server standalone binary. It requires version 1.14.0 or higher of the Oso Dev Server and takes the `migrate-ui` argument followed by the path to your policy file(s). ```Shell ./standalone migrate-ui path/to/policy.polar ``` -------------------------------- ### Get policy metadata with `oso.GetPolicyMetadata` (C#) Source: https://osohq.com/docs/app-integration/client-apis/dotnet Demonstrates how to retrieve metadata about the currently active policy using `oso.GetPolicyMetadata`. The example prints the keys of available resources and roles within the 'Organization' resource, providing insights into the policy's structure. ```C# metadata = await oso.GetPolicyMetadata() Console.WriteLine(string.Join(", ", metadata.Resources.Keys)); # prints Organization, Repository, User, global Console.WriteLine(string.Join(", ", metadata.Resources["Organization"].Roles)); # prints admin, member ``` -------------------------------- ### Example Oso Polar Policy with Embedded Test Suite Source: https://osohq.com/docs/development/workflow-walkthrough This Polar policy defines roles and permissions for `User`, `Organization`, and `Project` resources, including role inheritance. It also contains an embedded `test` block with setup and assertions to validate access control logic. ```Polar == Policy: policy.polar == actor User {} resource Organization { roles = ["member"]; permissions = ["view"]; "view" if "member"; } resource Project { roles = ["member"]; permissions = ["view"]; relations = { organization: Organization }; "member" if "member" on "organization"; "view" if "member"; } test "example test" { setup { # Project "project1" belongs to Organization "org1" has_relation(Project{"project1"}, "organization", Organization{"org1"}); # User "alice" has the "member" role on Organization "org1" has_role(User{"alice"}, "member", Organization{"org1"}); # User "bob" has the "member" role on Project "project1" has_role(User{"bob"}, "member", Project{"project1"}); } # Alice can view the "org1" Organization assert allow(User{"alice"}, "view", Organization{"org1"}); # Alice can view the "project1" Project via inheritance from the "org1" Organization assert allow(User{"alice"}, "view", Project{"project1"}); # Bob can not view the "org1" Organization assert_not allow(User{"bob"}, "view", Organization{"org1"}); # Bob can view the "project1" Project via direct assignment assert allow(User{"bob"}, "view", Project{"project1"}); # Charlie can view neither the "org1" Organization nor the "project1" Project assert_not allow(User{"charlie"}, "view", Organization{"org1"}); assert_not allow(User{"charlie"}, "view", Project{"project1"}); } ``` -------------------------------- ### Instantiate Oso Cloud Client in Go Source: https://osohq.com/docs/app-integration/client-apis/go Demonstrates how to create a new Oso Cloud client instance using `oso.NewClient` with the Oso Cloud URL and API key. Includes examples of inserting facts and performing authorization checks. ```Go import ( ... oso "github.com/osohq/go-oso-cloud/v2" ) osoClient := oso.NewClient("https://cloud.osohq.com", YOUR_API_KEY) // Later: e := osoClient.Insert(oso.NewFact("has_role", user, role, resource)) if e != nil { // Handle error. } // Wherever authorization needs to be performed: allowed, e := osoClient.Authorize(user, action, resource) if e != nil { // Handle error. } if allowed { // Action is allowed. } ``` -------------------------------- ### Exporting Authorization Facts using Oso Cloud CLI Source: https://osohq.com/docs/authorization-data/centralized/manage-centralized-authz-data/export-data This snippet demonstrates how to export facts from Oso Cloud using the `oso-cloud get` command. It shows examples for exporting `has_role` facts and `has_relation` facts, illustrating the command syntax and the expected output format for retrieved data. ```CLI # Export all `has_role` facts $ oso-cloud get has_role _ _ _ Retrieving has_role(_, _, _) from Oso at https://cloud.osohq.com/ has_role(User:Alice, String:admin, Repository:Anvils) ... # Export all `has_relation` facts $ oso-cloud get has_relation _ _ _ Retrieving has_relation(_, _, _) from Oso at https://cloud.osohq.com/ has_relation(Repository:Anvils, String:organization, Organization:ACME) ... ``` -------------------------------- ### Fetch facts by type using Oso Cloud `get` with `ValueOfType` Source: https://osohq.com/docs/app-integration/client-apis/python/migrating-to-v2 This example shows how to replace dictionary-based type fetching in `oso.get` with `oso_cloud.ValueOfType`. It allows querying for facts where an argument matches a specific type rather than a specific ID, providing more flexible querying capabilities. ```Python -user = { "type": "User", "id": "1" } -roles = oso.get("has_role", user, None, { "type": "Repo" }) +from oso_cloud import ValueOfType +user = Value("User", "1") +roles = oso.get(("has_role", user, None, ValueOfType("Repo"))) ``` -------------------------------- ### Configure Oso Migrate for Local Authorization Data Snapshotting Source: https://osohq.com/docs/development/oso-migrate This command initializes Oso Migrate UI to snapshot authorization data from a local database. It requires a path to the local authorization configuration file and a database connection URI. Currently, only Postgres is supported for this feature. ```shell ./standalone migrate-ui --local_authorization_config [path_to_local_authz_config] --connection-string [db_connection_string] ``` -------------------------------- ### Integrate Winston as Custom Logger for Oso Cloud Debugging Source: https://osohq.com/docs/app-integration/client-apis/node An example demonstrating how to configure the Oso Cloud client to use a Winston logger for routing debug timings. It shows the setup of a Winston logger instance and its integration into the Oso constructor's debug options. ```JavaScript const { Oso } = require("oso-cloud"); const winston = require("winston"); const logger = winston.createLogger({ level: "debug", format: winston.format.json(), transports: [new winston.transports.Console()], }); const oso = new Oso(url, apiKey, { debug: { logger: function (level, message, metadata) { logger.log(level, message, metadata); }, }, }); ``` -------------------------------- ### Go: Checking Global Permissions with Oso and GORM Source: https://osohq.com/docs/app-integration/client-apis/go This example illustrates how to use Oso Cloud to check if a user possesses a global permission. It generates a SQL `EXISTS` query using `EvaluateLocalSelect` to determine if the permission is granted, which is then executed via GORM to get a boolean result. ```Go actor := oso.NewValue("User", "alice") sqlQuery, err := osoClient.BuildQuery( oso.NewQueryFact("has_permission", actor, oso.String("create_repository")), ).EvaluateLocalSelect(map[string]oso.Variable{}) // => "SELECT EXISTS (... /* alice has the create_repository permission */) AS result" var results []bool db.Raw(sqlQuery).Pluck("result", &results) hasPermission := results[0] // => true ``` -------------------------------- ### Python: Get Oso Cloud Policy Metadata Source: https://osohq.com/docs/app-integration/client-apis/python/v1 Illustrates how to retrieve metadata about the currently active policy in Oso Cloud using `oso.get_policy_metadata()`. The example shows how to access resource keys and specific roles from the returned metadata object, providing insights into the policy's structure. ```Python metadata = oso.get_policy_metadata() print(metadata.resources.keys()) # returns ["Organization", "User", "global"] print(metadata.resources["Organization"].roles) # returns ["admin", "member"] ``` -------------------------------- ### Import Oso Fallback Data Snapshot Source: https://osohq.com/docs/app-integration/productionizing/fallback/setup This command initializes a new Oso Fallback node from a previously exported snapshot using the `--import` flag. It allows the node to start even if Oso Cloud is unavailable, by seeding its data directory from the local snapshot. A volume mount is necessary to access the snapshot file. ```bash docker run \ --env-file=.env \ -p 127.0.0.1:8080:8080 \ --volume "${PWD}:/import" \ public.ecr.aws/osohq/fallback:latest \ --import /import/oso-data.snapshot ``` -------------------------------- ### Initialize Oso Client and Run Jest Tests with Dev Server Source: https://osohq.com/docs/development/oso-dev-server Provides a Node.js example using Jest to set up and interact with the Oso Dev Server. It includes a function to initialize the Oso client by creating a new test environment and demonstrates basic authorization tests. ```javascript const { Oso } = require("oso-cloud"); const OSO_SERVER_URL = "http://localhost:8080"; async function initializeOsoClient(devServerURL, opts) { const response = await fetch(devServerURL + "/test_environment", { method: "POST", }); const data = await response.json(); return new Oso(devServerURL, data.token, opts); } describe("oso tests", () => { let oso; beforeEach(async () => { oso = await initializeOsoClient(OSO_SERVER_URL); }); test("denied", async () => { const authorize = await oso.authorize(...); expect(authorize).toEqual(false); }); test("policy 1", async () => { const authorize = await oso.authorize(...); expect(authorize).toEqual(true); }); }); ``` -------------------------------- ### Using ParityHandle with Oso Local Authorization in Java Source: https://osohq.com/docs/app-integration/client-apis/java This example demonstrates how `ParityHandle` can be used with Oso's local authorization feature. It shows recording the expected legacy result before or after calling `oso.authorizeLocal()`, and then executing the generated SQL query to get Oso's result, which appears in the Dev Server's Logs tab. ```Java import com.osohq.oso_cloud.*; import java.util.List; import java.util.Arrays; import java.io.IOException; /** * Checks authorization in both Oso and the legacy authorization system in parallel. * Compares results using ParityHandle. */ public boolean authorizeLocalWithParityCheck( String userId, String action, Value resource ) throws Exception { ParityHandle parityHandle = oso.createParityHandle(); Value user = new Value("User", userId); boolean legacyResult = legacyAuthorize(userId, action, resource); // You can call expect before or after oso.authorize() and oso.authorizeLocal() try { parityHandle.expect(legacyResult); } catch (IOException e) { System.err.println("Failed to record expected result: " + e.getMessage()); } Value alice = new Value("User", "alice"); Value environment2 = new Value("Environment", "env2"); List contextFacts = Arrays.asList( new Fact("has_permission", alice, new Value("create_repository"), environment2) ); String sqlQuery = oso.authorizeLocal(user, action, resource, contextFacts, parityHandle); // Execute the SQL query in your database to get the Oso result. // This result will show up in the "Actual" column in the Logs tab. boolean osoResult = executeQuery(sqlQuery); // Enforce the legacy result until you're confident things are consistent. return legacyResult; } ``` -------------------------------- ### Oso Policy: Full RBAC Example with Organization, Account, and Tests Source: https://osohq.com/docs/modeling-in-polar/field-level-authorization/fields-in-permissions A comprehensive Oso policy demonstrating RBAC for 'User', 'Organization', and 'Account' resources. It includes role definitions, hierarchical role implication, resource and field-level permissions, and relations. The policy also features a `test` block with setup and assertions to validate various access scenarios for different user roles. ```Polar actor User {} resource Organization { roles = ["visitor", "member", "community_admin", "admin"]; permissions = ["read", "update"]; # Role implication # visitor < member < community_admin < admin "visitor" if "member"; "member" if "community_admin"; "community_admin" if "admin"; # RBAC "update" if "admin"; "read" if "visitor"; } resource Account { permissions = [ # resource-level permissions "read", "update", # field-level permissions "username.read", "username.update", "email.read", "email.update", ]; relations = { parent: Organization, owner: User }; # RBAC # Resource-level permissions # # relation | read | update # --------------------------|------|-------- # owner | x | x # admin on parent | x | x # community_admin on parent | x | x # member on parent | x | - # visitor on parent | x | - "update" if "owner"; "update" if "admin" on "parent"; # "update" is a higher-level permission than "username.update", so apply it # to community_admin. "update" if "community_admin" on "parent"; "read" if "update"; "read" if "visitor" on "parent"; # Field-level permissions # # relation | username | email # --------------------------|--------------|---------------- # owner | read, update | read, update # admin on parent | read, update | read, update # community_admin on parent | read, update | read # member on parent | read | read # visitor on parent | - | - # username ## username.update "username.update" if "owner"; "username.update" if "admin" on "parent"; "username.update" if "community_admin" on "parent"; ## username.read "username.read" if "username.update"; "username.read" if "member" on "parent"; # email ## email.update "email.update" if "owner"; "email.update" if "admin" on "parent"; ## username.read "email.read" if "email.update"; "email.read" if "community_admin" on "parent"; "email.read" if "member" on "parent"; } test "Fields in permissions" { setup { # admin has_role(User{"alice"}, "admin", Organization{"example"}); has_relation(Account{"alice"}, "owner", User{"alice"}); has_relation(Account{"alice"}, "parent", Organization{"example"}); # community_admin has_role(User{"bob"}, "community_admin", Organization{"example"}); has_relation(Account{"bob"}, "owner", User{"bob"}); has_relation(Account{"bob"}, "parent", Organization{"example"}); # member has_role(User{"charlie"}, "member", Organization{"example"}); has_relation(Account{"charlie"}, "owner", User{"charlie"}); has_relation(Account{"charlie"}, "parent", Organization{"example"}); # visitor has_role(User{"dana"}, "visitor", Organization{"example"}); has_relation(Account{"dana"}, "owner", User{"dana"}); has_relation(Account{"dana"}, "parent", Organization{"example"}); } # anyone can update any field of their own account assert allow(User{"charlie"}, "update", Account{"charlie"}); assert allow(User{"charlie"}, "username.update", Account{"charlie"}); assert allow(User{"dana"}, "update", Account{"dana"}); assert allow(User{"dana"}, "username.update", Account{"dana"}); # admins can update all fields in all accounts assert allow(User{"alice"}, "username.update", Account{"bob"}); assert allow(User{"alice"}, "email.update", Account{"bob"}); assert allow(User{"alice"}, "username.update", Account{"charlie"}); # community admins have resource-level update permissions assert allow(User{"bob"}, "update", Account{"alice"}); assert allow(User{"bob"}, "update", Account{"dana"}); # community admins can only update usernames, but can read all fields assert allow(User{"bob"}, "username.update", Account{"alice"}); assert allow(User{"bob"}, "username.update", Account{"charlie"}); assert_not allow(User{"bob"}, "email.update", Account{"alice"}); assert_not allow(User{"bob"}, "email.update", Account{"dana"}); assert allow(User{"bob"}, "email.read", Account{"alice"}); # members have read access to all fields assert allow(User{"charlie"}, "username.read", Account{"alice"}); assert allow(User{"charlie"}, "email.read", Account{"dana"}); assert_not allow(User{"charlie"}, "email.update", Account{"dana"}); # visitors only have read access to others' accounts assert allow(User{"dana"}, "read", Account{"alice"}); assert allow(User{"dana"}, "read", Account{"charlie"}); assert_not allow(User{"dana"}, "read", Account{"charlie"} ``` -------------------------------- ### Install Oso Cloud CLI with Specific Version Source: https://osohq.com/docs/development/ci-cd This command installs the Oso Cloud CLI, allowing you to pin the tool to a specific version by replacing 'x.y.z' with the desired version number. It uses curl to download and execute the installation script. ```bash curl -L https://cloud.osohq.com/install.sh | OSO_CLI_VERSION="x.y.z" bash ```