httpz

package module
v0.0.0-...-4e8e723 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2024 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package httpz provides authorization middleware for HTTP servers built on top of the standard net/http.

The middleware intercepts incoming requests and calls the Aserto authorizer service to determine if access should be allowed or denied.

Example
package main

import (
	"log"
	"net/http"
	"time"

	"github.com/aserto-dev/go-aserto"
	"github.com/aserto-dev/go-aserto/az"
	"github.com/aserto-dev/go-aserto/middleware/httpz"
)

func Hello(w http.ResponseWriter, _ *http.Request) {
	if _, err := w.Write([]byte(`"hello"`)); err != nil {
		log.Println("Failed to write HTTP response:", err)
	}
}

func main() {
	// Create azClient client.
	azClient, err := az.New(
		aserto.WithAPIKeyAuth("<Aserto authorizer API Key>"),
		aserto.WithTenantID("<Aserto tenant ID>"),
	)
	if err != nil {
		log.Fatal("Failed to create authorizer client:", err)
	}
	defer azClient.Close()

	// Create HTTP middleware.
	middleware := httpz.New(
		azClient,
		&httpz.Policy{
			Name:     "<Aserto policy Name>",
			Decision: "<authorization decision (e.g. 'allowed')",
		},
	)

	// Define HTTP route.
	http.Handle(
		"/",
		middleware.Handler(http.HandlerFunc(Hello)), // Attach middleware to route.
	)

	// Start server.
	server := &http.Server{
		Addr:              ":8080",
		ReadHeaderTimeout: 2 * time.Second,
	}
	if err := server.ListenAndServe(); err != nil {
		log.Println("Failed to start server:", err)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthorizerClient

type AuthorizerClient = authz.AuthorizerClient

type Check

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

func (*Check) Handler

func (c *Check) Handler(next http.Handler) http.Handler

Handler returns a middleware handler that checks incoming requests.

func (*Check) HandlerFunc

func (c *Check) HandlerFunc(next http.HandlerFunc) http.HandlerFunc

HandlerFunc returns a middleware handler that wraps the given http.HandlerFunc and checks incoming requests.

type CheckOption

type CheckOption func(*CheckOptions)

CheckOption is used to configure the check middleware.

func WithIdentityMapper

func WithIdentityMapper(mapper IdentityMapper) CheckOption

WithIdentityMapper takes an identity mapper function that is used to determine the subject id for the check call.

func WithObjectID

func WithObjectID(id string) CheckOption

WithObjectID set the id of the object to check.

func WithObjectIDMapper

func WithObjectIDMapper(mapper StringMapper) CheckOption

WithObjectIDMapper takes a function that is used to determine the object id to check from the incoming request.

func WithObjectMapper

func WithObjectMapper(mapper ObjectMapper) CheckOption

WithObjectMapper takes a function that is used to determine the object type and id to check from the incoming request.

func WithObjectType

func WithObjectType(objType string) CheckOption

WithObjectType sets the object type to check.

func WithPolicyPath

func WithPolicyPath(path string) CheckOption

WithPolicyPath sets the path of the policy module to use for the check call.

func WithRelation

func WithRelation(name string) CheckOption

WithRelation sets the relation/permission to check.

func WithRelationMapper

func WithRelationMapper(mapper StringMapper) CheckOption

WithRelation takes a function that is used to determine the relation/permission to check from the incoming request.

type CheckOptions

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

CheckOptions is used to configure the check middleware.

type IdentityBuilder

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

IdentityBuilder is used to configure what information about caller identity is sent in authorization calls.

func (*IdentityBuilder) Build

Build constructs an IdentityContext that can be used in authorization requests.

func (*IdentityBuilder) FromContextValue

func (b *IdentityBuilder) FromContextValue(key interface{}) *IdentityBuilder

FromContextValue extracts caller identity from a value in the incoming request context.

If the value is not present, not a string, or an empty string then the request is considered anonymous.

func (*IdentityBuilder) FromHeader

func (b *IdentityBuilder) FromHeader(header ...string) *IdentityBuilder

FromHeader retrieves caller identity from request headers.

Headers are attempted in order. The first non-empty header is used. If none of the specified headers have a value, the request is considered anonymous.

func (*IdentityBuilder) FromHostname

func (b *IdentityBuilder) FromHostname(segment int) *IdentityBuilder

FromHostname extracts caller identity from the incoming request's host name.

The function returns the specified hostname segment. Indexing is zero-based and starts from the left. Negative indices start from the right.

For Example, if the hostname is "service.user.company.com" then both FromHostname(1) and FromHostname(-3) return the value "user".

func (*IdentityBuilder) ID

func (b *IdentityBuilder) ID(identity string) *IdentityBuilder

Call ID(...) to set the user's identity. If neither JWT() or Subject() are called too, IdentityMapper tries to infer whether the specified identity is a JWT or not. Passing an empty string is the same as calling .None() and results in an authorization check for anonymous access.

func (*IdentityBuilder) JWT

func (b *IdentityBuilder) JWT() *IdentityBuilder

Call JWT() to indicate that the user's identity is expressed as a string-encoded JWT.

JWT() is always called in conjunction with another method that provides the user ID itself. For example:

idBuilder.JWT().FromHeader("Authorization")

func (*IdentityBuilder) Manual

func (b *IdentityBuilder) Manual() *IdentityBuilder

Call Manual() to indicate that the user's identity is set manually and isn't resolved to a user by the authorizer.

Manually set identities are available in the authorizer's policy language through the "input.identity" variable.

func (*IdentityBuilder) Mapper

func (b *IdentityBuilder) Mapper(mapper IdentityMapper) *IdentityBuilder

Mapper takes a custom IdentityMapper to be used for extracting identity information from incoming requests.

func (*IdentityBuilder) None

func (b *IdentityBuilder) None() *IdentityBuilder

Call None() to indicate that requests are unauthenticated.

func (*IdentityBuilder) Subject

func (b *IdentityBuilder) Subject() *IdentityBuilder

Subject() is always used in conjunction with another method that provides the user ID itself. For example:

idBuilder.Subject().FromContextValue("username")

type IdentityMapper

type IdentityMapper func(*http.Request, middleware.Identity)

IdentityMapper is the type of callback functions that can inspect incoming HTTP requests and set the caller's identity.

type Middleware

type Middleware struct {
	// Identity determines the caller identity used in authorization calls.
	Identity *IdentityBuilder
	// contains filtered or unexported fields
}

Middleware implements an http.Handler that can be added to routes in net/http servers.

To authorize incoming requests, the middleware needs information about:

1. The user making the request.

2. The Aserto authorization policy to evaluate.

3. Optional, additional input data to the authorization policy.

The values for these parameters can be set globally or extracted dynamically from incoming messages.

func New

func New(client AuthorizerClient, policy *Policy) *Middleware

New creates middleware for the specified policy.

The new middleware is created with default identity and policy path mapper. Those can be overridden using `Middleware.Identity` to specify the caller's identity, or using the middleware's ".With...()" functions to set policy path and resource mappers.

func (*Middleware) Check

func (m *Middleware) Check(options ...CheckOption) *Check

Check returns a new Check middleware object that can be used to make ReBAC authorization decisions for individual routes. A check call returns true if a given relation exists between an object and a subject.

func (*Middleware) Handler

func (m *Middleware) Handler(next http.Handler) http.Handler

Handler returns a middlleware handler that authorizes incoming requests.

func (*Middleware) HandlerFunc

func (m *Middleware) HandlerFunc(next http.HandlerFunc) http.Handler

HandlerFunc returns a middleware handler that wraps the given http.HandlerFunc and authorizes incoming requests.

func (*Middleware) WithNoResourceContext

func (m *Middleware) WithNoResourceContext() *Middleware

WithNoResourceContext causes the middleware to include no resource context in authorization request instead of the default behavior that sends all URL path parameters.

func (*Middleware) WithPolicyFromURL

func (m *Middleware) WithPolicyFromURL(prefix string) *Middleware

WithPolicyFromURL instructs the middleware to construct the policy path from the path segment of the incoming request's URL.

Path separators ('/') are replaced with dots ('.'). An optional prefix can be specified to be included in all paths.

Example

Using 'WithPolicyFromURL("myapp")', the route

POST /api/products/

becomes the policy path

"myapp.POST.api.products"

func (*Middleware) WithPolicyPathMapper

func (m *Middleware) WithPolicyPathMapper(mapper StringMapper) *Middleware

WithPolicyPathMapper sets a custom policy mapper, a function that takes an incoming request and returns the path within the policy of the package to query.

func (*Middleware) WithResourceMapper

func (m *Middleware) WithResourceMapper(mapper ResourceMapper) *Middleware

WithResourceMapper sets a custom resource mapper, a function that takes an incoming request and returns the resource object to include with the authorization request as a `structpb.Struct`.

type ObjectMapper

type ObjectMapper func(r *http.Request) (objType string, id string)

ObjectMapper takes an incoming request and returns the object type and id to check.

type Policy

type Policy = middleware.Policy

type ResourceMapper

type ResourceMapper func(*http.Request, map[string]interface{})

ResourceMapper functions are used to extract structured data from incoming requests.

type StringMapper

type StringMapper func(*http.Request) string

StringMapper functions are used to extract string values from incoming requests. They are used to define policy mappers.

Jump to

Keyboard shortcuts

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