opaclient

package module
v0.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2026 License: Apache-2.0 Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Nuclio OPA Client

A Go client library for Open Policy Agent (OPA) with support for HTTP-based policy queries.

Features

  • 🚀 Multiple Client Types: HTTP, Mock, and No-op clients
  • 🔄 Retry Logic: Built-in retry mechanism for HTTP requests
  • 📊 Batch Queries: Query permissions for multiple resources at once
  • 🛡️ Override Support: Bypass policy checks with override headers
  • 🔧 Configurable: Flexible configuration options
  • 🧪 Well Tested: Comprehensive test coverage
  • 📝 Structured Logging: Integration with nuclio logger

Installation

go get github.com/nuclio/opa-client

Quick Start

package main

import (
    "context"
    "time"
    
    "github.com/nuclio/logger"
    "github.com/nuclio/opa-client"
)

func main() {
    // Create configuration
    config := &opa.Config{
        ClientKind:               opa.ClientKindHTTP,
        Address:                  "http://localhost:8181",
        PermissionQueryPath:      "/v1/data/authz/allow",
        PermissionFilterPath:     "/v1/data/authz/filter_allowed",
        AllowedProjectsQueryPath: "/v1/data/authz/allowed_projects",
        RequestTimeout:           10,
        Verbose:                  false,
    }
    
    // Create client
    logger := // your logger instance
    client := opa.CreateOpaClient(logger, config)
    
    // Query single permission
    allowed, err := client.QueryPermissions(
        "resource1",
        opa.ActionRead,
        &opa.PermissionOptions{
            MemberIds: []string{"user123"},
        },
    )
    
    // Query multiple permissions
    permissions, err := client.QueryPermissionsMultiResources(
        context.Background(),
        []string{"resource1", "resource2"},
        opa.ActionRead,
        &opa.PermissionOptions{
            MemberIds: []string{"user123"},
        },
    )

    // Query allowed projects
    projects, err := client.QueryAllowedProjects(
        context.Background(),
        &opa.PermissionOptions{
            MemberIds: []string{"user123", "group456"},
        },
    )
    // projects may be ["*"] (all projects) or a list of concrete project names
}

Configuration

Field Type Description Default
ClientKind ClientKind Type of client (http, nop, mock) nop
Address string OPA server URL -
PermissionQueryPath string Single permission query endpoint -
PermissionFilterPath string Multi-resource query endpoint -
AllowedProjectsQueryPath string Allowed-projects query endpoint -
RequestTimeout int HTTP timeout in seconds 10
Verbose bool Enable verbose logging false
OverrideHeaderValue string Value for bypass functionality -

Client Types

HTTP Client

Production client that communicates with OPA over HTTP.

No-op Client

Always returns true for all permission checks. Useful for development/testing.

Mock Client

Test client using testify/mock for unit testing.

Actions

Supported actions: read, create, update, delete

Contributing

Prerequisites
  • Go 1.23+
  • Make
Format Code
make fmt
Testing
make test
make test-coverage
Linting
make lint

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Documentation

Overview

package opaclient provides a Go client library for Open Policy Agent (OPA) with support for HTTP-based policy queries.

The package supports multiple client types:

  • HTTPClient: Production client for communicating with OPA over HTTP
  • NopClient: Always returns true, useful for development/testing
  • MockClient: Test client using testify/mock for unit testing

Example usage:

config := &opa.Config{
	ClientKind:           opa.ClientKindHTTP,
	Address:             "http://localhost:8181",
	PermissionQueryPath: "/v1/data/authz/allow",
	RequestTimeout:      10,
}

client := opa.CreateOpaClient(logger, config)
allowed, err := client.QueryPermissions("resource1", opa.ActionRead, &opa.PermissionOptions{
	MemberIds: []string{"user123"},
})

Index

Constants

View Source
const (
	// Version is the current version of the OPA client library
	Version = "0.0.1"

	// UserAgent is used in HTTP requests to identify the client
	UserAgent = "nuclio-opa-client/" + Version
)

Version information

Variables

This section is empty.

Functions

This section is empty.

Types

type Action

type Action string
const (
	ActionRead   Action = "read"
	ActionList   Action = "list"
	ActionCreate Action = "create"
	ActionUpdate Action = "update"
	ActionDelete Action = "delete"
)

type AllowedProjectsRequest added in v0.0.4

type AllowedProjectsRequest struct {
	Input AllowedProjectsRequestInput `json:"input,omitempty"`
}

type AllowedProjectsRequestInput added in v0.0.4

type AllowedProjectsRequestInput struct {
	Ids []string `json:"ids,omitempty"`
}

type AllowedProjectsResponse added in v0.0.4

type AllowedProjectsResponse struct {
	Result []string `json:"result,omitempty"`
}

type Client

type Client interface {
	// QueryPermissions queries permission for a single resource.
	QueryPermissions(context.Context, string, Action, *PermissionOptions) (bool, error)

	// QueryPermissionsMultiResources queries permissions for multiple resources at once.
	// Returns a slice of booleans where each index corresponds to the resource at the same index.
	QueryPermissionsMultiResources(context.Context, []string, Action, *PermissionOptions) ([]bool, error)

	// QueryAllowedProjects returns the set of project names the caller (identified by
	// PermissionOptions.MemberIds) is allowed to read or list. A returned slice
	// containing "*" signals that all projects are accessible — callers are responsible
	// for treating "*" as a wildcard; no concrete names are returned alongside it.
	QueryAllowedProjects(context.Context, *PermissionOptions) ([]string, error)
}

Client represents an OPA client that can query permissions.

func CreateOpaClient

func CreateOpaClient(parentLogger logger.Logger, opaConfiguration *Config) Client

CreateOpaClient creates an OPA client by a given configuration

type ClientKind

type ClientKind string
const (
	ClientKindHTTP ClientKind = "http"
	ClientKindNop  ClientKind = "nop"
	ClientKindMock ClientKind = "mock"

	DefaultClientKind     = ClientKindNop
	DefaultRequestTimeOut = 10 * time.Second
)

type Config

type Config struct {

	// OPA server address
	Address string `json:"address,omitempty"`

	// client kind to use (nop | http | mock)
	ClientKind ClientKind `json:"clientKind,omitempty"`

	// timeout period when querying opa server
	RequestTimeout int `json:"requestTimeout,omitempty"`

	// the path used when querying single resource against opa server (e.g.: /v1/data/somewhere/authz/allow)
	PermissionQueryPath string `json:"permissionQueryPath,omitempty"`

	// the path used when querying multiple resources against opa server (e.g.: /v1/data/somewhere/authz/filter_allowed)
	PermissionFilterPath string `json:"permissionFilterPath,omitempty"`

	// the path used when querying allowed projects against opa server (e.g.: /v1/data/platform/authz/allowed_projects)
	AllowedProjectsQueryPath string `json:"allowedProjectsQueryPath,omitempty"`

	// for extra verbosity
	Verbose bool `json:"verbose,omitempty"`

	// the header value for bypassing OPA if needed
	OverrideHeaderValue string `json:"overrideHeaderValue,omitempty"`

	// SkipTLSVerify indicates whether to skip TLS verification for the OPA server
	SkipTLSVerify bool `json:"skipTLSVerify,omitempty"`
}

type HTTPClient

type HTTPClient struct {
	// contains filtered or unexported fields
}

func NewHTTPClient

func NewHTTPClient(parentLogger logger.Logger,
	address string,
	permissionQueryPath string,
	permissionFilterPath string,
	allowedProjectsQueryPath string,
	requestTimeout time.Duration,
	verbose bool,
	overrideHeaderValue string,
	skipTLSVerify bool,
) *HTTPClient

func (*HTTPClient) QueryAllowedProjects added in v0.0.4

func (c *HTTPClient) QueryAllowedProjects(ctx context.Context,
	permissionOptions *PermissionOptions) ([]string, error)

QueryAllowedProjects returns the set of project names the caller (identified by permissionOptions.MemberIds) is allowed to read or list. A returned slice containing "*" signals that all projects are accessible.

func (*HTTPClient) QueryPermissions

func (c *HTTPClient) QueryPermissions(ctx context.Context,
	resource string,
	action Action,
	permissionOptions *PermissionOptions) (bool, error)

func (*HTTPClient) QueryPermissionsMultiResources

func (c *HTTPClient) QueryPermissionsMultiResources(ctx context.Context,
	resources []string,
	action Action,
	permissionOptions *PermissionOptions) ([]bool, error)

QueryPermissionsMultiResources query permissions for multiple resources at once. The response is a list of booleans indicating for each resource if the action against such resource is allowed or not. Therefore, it is guaranteed that len(resources) and len(results) are equal and resources[i] query permission is at results[i]

type MockClient

type MockClient struct {
	mock.Mock
}

func (*MockClient) QueryAllowedProjects added in v0.0.4

func (mc *MockClient) QueryAllowedProjects(ctx context.Context,
	permissionOptions *PermissionOptions) ([]string, error)

func (*MockClient) QueryPermissions

func (mc *MockClient) QueryPermissions(ctx context.Context,
	resource string,
	action Action,
	permissionOptions *PermissionOptions) (bool, error)

func (*MockClient) QueryPermissionsMultiResources

func (mc *MockClient) QueryPermissionsMultiResources(ctx context.Context,
	resources []string,
	action Action,
	permissionOptions *PermissionOptions) ([]bool, error)

type NopClient

type NopClient struct {
	// contains filtered or unexported fields
}

func NewNopClient

func NewNopClient(parentLogger logger.Logger, verbose bool) *NopClient

func (*NopClient) QueryAllowedProjects added in v0.0.4

func (c *NopClient) QueryAllowedProjects(ctx context.Context, permissionOptions *PermissionOptions) ([]string, error)

func (*NopClient) QueryPermissions

func (c *NopClient) QueryPermissions(ctx context.Context, resource string, action Action, permissionOptions *PermissionOptions) (bool, error)

func (*NopClient) QueryPermissionsMultiResources

func (c *NopClient) QueryPermissionsMultiResources(ctx context.Context,
	resources []string, action Action, permissionOptions *PermissionOptions) ([]bool, error)

type PermissionFilterRequest

type PermissionFilterRequest struct {
	Input PermissionFilterRequestInput `json:"input,omitempty"`
}

type PermissionFilterRequestInput

type PermissionFilterRequestInput struct {
	Resources []string `json:"resources,omitempty"`
	Action    string   `json:"action,omitempty"`
	Ids       []string `json:"ids,omitempty"`
}

type PermissionFilterResponse

type PermissionFilterResponse struct {
	Result []string `json:"result,omitempty"`
}

type PermissionOptions

type PermissionOptions struct {
	MemberIds            []string
	RaiseForbidden       bool
	OverrideHeaderValue  string
	SkipLoggingForbidden bool
}

type PermissionQueryRequest

type PermissionQueryRequest struct {
	Input PermissionQueryRequestInput `json:"input,omitempty"`
}

type PermissionQueryRequestInput

type PermissionQueryRequestInput struct {
	Resource string   `json:"resource,omitempty"`
	Action   string   `json:"action,omitempty"`
	Ids      []string `json:"ids,omitempty"`
}

type PermissionQueryResponse

type PermissionQueryResponse struct {
	Result bool `json:"result,omitempty"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL