api

package
v0.17.5 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2023 License: GPL-3.0 Imports: 42 Imported by: 9

Documentation

Overview

Package api provides an API for integration with other components of the same software package and also third party components.

It provides direct database access as well as a simpler way to register API endpoints. You can of course also register raw `http.Handler`s directly.

Optional authentication guards registered handlers. This is achieved by attaching functions to the `http.Handler`s that are registered, which allow them to specify the required permissions for the handler.

The permissions are divided into the roles and assume a single user per host. The Roles are User, Admin and Self. User roles are expected to have mostly read access and react to notifications or system events, like a system tray program. The Admin role is meant for advanced components that also change settings, but are restricted so they cannot break the software. Self is reserved for internal use with full access.

Index

Constants

View Source
const (
	CfgDefaultListenAddressKey = "core/listenAddress"
	CfgAPIKeys                 = "core/apiKeys"
)

Config Keys.

View Source
const (
	MimeTypeJSON string = "application/json"
	MimeTypeText string = "text/plain"
)

MIME Types.

Variables

View Source
var (

	// ErrInvalidEndpoint is returned when an invalid endpoint is registered.
	ErrInvalidEndpoint = errors.New("endpoint is invalid")

	// ErrAlreadyRegistered is returned when there already is an endpoint with
	// the same path registered.
	ErrAlreadyRegistered = errors.New("an endpoint for this path is already registered")
)
View Source
var (
	ErrAuthenticationAlreadySet = errors.New("the authentication function has already been set")
	ErrAuthenticationImmutable  = errors.New("the authentication function can only be set before the api has started")
)

API Errors.

View Source
var EnableServer = true

EnableServer defines if the HTTP server should be started.

View Source
var (

	// ErrAPIAccessDeniedMessage should be wrapped by errors returned by
	// AuthenticatorFunc in order to signify a blocked request, including a error
	// message for the user. This is an empty message on purpose, as to allow the
	// function to define the full text of the error shown to the user.
	ErrAPIAccessDeniedMessage = errors.New("")
)
View Source
var RequestContextKey = apiRequestContextKey{}

RequestContextKey is the key used to add the API request to the context.

Functions

func ErrorWithStatus added in v0.13.0

func ErrorWithStatus(err error, code int) error

ErrorWithStatus adds the HTTP status code to the error.

func MarshalRecord added in v0.16.5

func MarshalRecord(r record.Record, withDSDIdentifier bool) ([]byte, error)

MarshalRecord locks and marshals the given record, additionally adding metadata and returning it as json.

func RegisterEndpoint added in v0.9.4

func RegisterEndpoint(e Endpoint) error

RegisterEndpoint registers a new endpoint. An error will be returned if it does not pass the sanity checks.

func RegisterHandleFunc

func RegisterHandleFunc(path string, handleFunc func(http.ResponseWriter, *http.Request)) *mux.Route

RegisterHandleFunc registers a handle function with the API endpoint.

func RegisterHandler added in v0.3.0

func RegisterHandler(path string, handler http.Handler) *mux.Route

RegisterHandler registers a handler with the API endpoint.

func RequestLogger

func RequestLogger(next http.Handler) http.Handler

RequestLogger is a logging middleware.

func SetAuthenticator added in v0.3.0

func SetAuthenticator(fn AuthenticatorFunc) error

SetAuthenticator sets an authenticator function for the API endpoint. If none is set, all requests will be permitted.

func SetDefaultAPIListenAddress

func SetDefaultAPIListenAddress(address string)

SetDefaultAPIListenAddress sets the default listen address for the API.

func TextResponse added in v0.9.4

func TextResponse(w http.ResponseWriter, r *http.Request, text string)

TextResponse writes a text response.

func WrapInAuthHandler added in v0.9.4

func WrapInAuthHandler(fn http.HandlerFunc, read, write Permission) http.Handler

WrapInAuthHandler wraps a simple http.HandlerFunc into a handler that exposes the required API permissions for this handler.

Types

type ActionFunc added in v0.9.4

type ActionFunc func(ar *Request) (msg string, err error)

ActionFunc is for simple actions with a return message for the user.

type AuthToken added in v0.9.4

type AuthToken struct {
	Read       Permission
	Write      Permission
	ValidUntil *time.Time
}

AuthToken represents either a set of required or granted permissions. All attributes must be set when the struct is built and must not be changed later. Functions may be called at any time. The Write permission implicitly also includes reading.

type AuthenticatedHandler added in v0.9.4

type AuthenticatedHandler interface {
	ReadPermission(*http.Request) Permission
	WritePermission(*http.Request) Permission
}

AuthenticatedHandler defines the handler interface to specify custom permission for an API handler. The returned permission is the required permission for the request to proceed.

type AuthenticatorFunc added in v0.9.4

type AuthenticatorFunc func(r *http.Request, s *http.Server) (*AuthToken, error)

AuthenticatorFunc is a function that can be set as the authenticator for the API endpoint. If none is set, all requests will have full access. The returned AuthToken represents the permissions that the request has.

type DataFunc added in v0.9.4

type DataFunc func(ar *Request) (data []byte, err error)

DataFunc is for returning raw data that the caller for further processing.

type DatabaseAPI

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

DatabaseAPI is a generic database API interface.

func CreateDatabaseAPI added in v0.17.0

func CreateDatabaseAPI(sendFunction func(data []byte)) DatabaseAPI

CreateDatabaseAPI creates a new database interface.

func (*DatabaseAPI) Handle added in v0.17.0

func (api *DatabaseAPI) Handle(msg []byte)

Handle handles a message for the database API.

type DatabaseWebsocketAPI added in v0.17.0

type DatabaseWebsocketAPI struct {
	DatabaseAPI
	// contains filtered or unexported fields
}

DatabaseWebsocketAPI is a database websocket API interface.

type Endpoint added in v0.9.4

type Endpoint struct {
	// Name is the human reabable name of the endpoint.
	Name string
	// Description is the human readable description and documentation of the endpoint.
	Description string
	// Parameters is the parameter documentation.
	Parameters []Parameter `json:",omitempty"`

	// Path describes the URL path of the endpoint.
	Path string

	// MimeType defines the content type of the returned data.
	MimeType string

	// Read defines the required read permission.
	Read Permission `json:",omitempty"`

	// ReadMethod sets the required read method for the endpoint.
	// Available methods are:
	// GET: Returns data only, no action is taken, nothing is changed.
	// If omitted, defaults to GET.
	//
	// This field is currently being introduced and will only warn and not deny
	// access if the write method does not match.
	ReadMethod string `json:",omitempty"`

	// Write defines the required write permission.
	Write Permission `json:",omitempty"`

	// WriteMethod sets the required write method for the endpoint.
	// Available methods are:
	// POST: Create a new resource; Change a status; Execute a function
	// PUT: Update an existing resource
	// DELETE: Remove an existing resource
	// If omitted, defaults to POST.
	//
	// This field is currently being introduced and will only warn and not deny
	// access if the write method does not match.
	WriteMethod string `json:",omitempty"`

	// BelongsTo defines which module this endpoint belongs to.
	// The endpoint will not be accessible if the module is not online.
	BelongsTo *modules.Module `json:"-"`

	// ActionFunc is for simple actions with a return message for the user.
	ActionFunc ActionFunc `json:"-"`

	// DataFunc is for returning raw data that the caller for further processing.
	DataFunc DataFunc `json:"-"`

	// StructFunc is for returning any kind of struct.
	StructFunc StructFunc `json:"-"`

	// RecordFunc is for returning a database record. It will be properly locked
	// and marshalled including metadata.
	RecordFunc RecordFunc `json:"-"`

	// HandlerFunc is the raw http handler.
	HandlerFunc http.HandlerFunc `json:"-"`
}

Endpoint describes an API Endpoint. Path and at least one permission are required. As is exactly one function.

func ExportEndpoints added in v0.9.4

func ExportEndpoints() []*Endpoint

ExportEndpoints exports the registered endpoints. The returned data must be treated as immutable.

func GetEndpointByPath added in v0.17.0

func GetEndpointByPath(path string) (*Endpoint, error)

GetEndpointByPath returns the endpoint registered with the given path.

func (*Endpoint) ServeHTTP added in v0.10.0

func (e *Endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles the http request.

type EndpointBridgeRequest added in v0.10.0

type EndpointBridgeRequest struct {
	record.Base
	sync.Mutex

	Method   string
	Path     string
	Query    map[string]string
	Data     []byte
	MimeType string
}

EndpointBridgeRequest holds a bridged request API request.

type EndpointBridgeResponse added in v0.10.0

type EndpointBridgeResponse struct {
	record.Base
	sync.Mutex

	MimeType string
	Body     string
}

EndpointBridgeResponse holds a bridged request API response.

type HTTPStatusError added in v0.13.0

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

HTTPStatusError represents an error with an HTTP status code.

func (*HTTPStatusError) Error added in v0.13.0

func (e *HTTPStatusError) Error() string

Error returns the error message.

func (*HTTPStatusError) HTTPStatus added in v0.13.0

func (e *HTTPStatusError) HTTPStatus() int

HTTPStatus returns the HTTP status code this error.

func (*HTTPStatusError) Unwrap added in v0.13.0

func (e *HTTPStatusError) Unwrap() error

Unwrap return the wrapped error.

type HTTPStatusProvider added in v0.13.0

type HTTPStatusProvider interface {
	HTTPStatus() int
}

HTTPStatusProvider is an interface for errors to provide a custom HTTP status code.

type LoggingResponseWriter added in v0.3.0

type LoggingResponseWriter struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	Status         int
}

LoggingResponseWriter is a wrapper for http.ResponseWriter for better request logging.

func NewLoggingResponseWriter added in v0.3.0

func NewLoggingResponseWriter(w http.ResponseWriter, r *http.Request) *LoggingResponseWriter

NewLoggingResponseWriter wraps a http.ResponseWriter.

func (*LoggingResponseWriter) Header added in v0.3.0

func (lrw *LoggingResponseWriter) Header() http.Header

Header wraps the original Header method.

func (*LoggingResponseWriter) Hijack added in v0.3.0

func (lrw *LoggingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack wraps the original Hijack method, if available.

func (*LoggingResponseWriter) Write added in v0.3.0

func (lrw *LoggingResponseWriter) Write(b []byte) (int, error)

Write wraps the original Write method.

func (*LoggingResponseWriter) WriteHeader added in v0.3.0

func (lrw *LoggingResponseWriter) WriteHeader(code int)

WriteHeader wraps the original WriteHeader method to extract information.

type ModuleHandler added in v0.10.2

type ModuleHandler interface {
	BelongsTo() *modules.Module
}

ModuleHandler specifies the interface for API endpoints that are bound to a module.

type Parameter added in v0.9.4

type Parameter struct {
	Method      string
	Field       string
	Value       string
	Description string
}

Parameter describes a parameterized variation of an endpoint.

type Permission added in v0.9.4

type Permission int8

Permission defines an API requests permission.

const (
	// NotFound declares that the operation does not exist.
	NotFound Permission = -2

	// Dynamic declares that the operation requires permission to be processed,
	// but anyone can execute the operation, as it reacts to permissions itself.
	Dynamic Permission = -1

	// NotSupported declares that the operation is not supported.
	NotSupported Permission = 0

	// PermitAnyone declares that anyone can execute the operation without any
	// authentication.
	PermitAnyone Permission = 1

	// PermitUser declares that the operation may be executed by authenticated
	// third party applications that are categorized as representing a simple
	// user and is limited in access.
	PermitUser Permission = 2

	// PermitAdmin declares that the operation may be executed by authenticated
	// third party applications that are categorized as representing an
	// administrator and has broad in access.
	PermitAdmin Permission = 3

	// PermitSelf declares that the operation may only be executed by the
	// software itself and its own (first party) components.
	PermitSelf Permission = 4
)

func (Permission) Role added in v0.9.4

func (p Permission) Role() string

Role returns a string representation of the permission role.

func (Permission) String added in v0.9.4

func (p Permission) String() string

type RecordFunc added in v0.9.4

type RecordFunc func(ar *Request) (r record.Record, err error)

RecordFunc is for returning a database record. It will be properly locked and marshalled including metadata.

type Request added in v0.9.4

type Request struct {
	// Request is the http request.
	*http.Request

	// InputData contains the request body for write operations.
	InputData []byte

	// Route of this request.
	Route *mux.Route

	// URLVars contains the URL variables extracted by the gorilla mux.
	URLVars map[string]string

	// AuthToken is the request-side authentication token assigned.
	AuthToken *AuthToken

	// ResponseHeader holds the response header.
	ResponseHeader http.Header

	// HandlerCache can be used by handlers to cache data between handlers within a request.
	HandlerCache interface{}
}

Request is a support struct to pool more request related information.

func GetAPIRequest added in v0.9.4

func GetAPIRequest(r *http.Request) *Request

GetAPIRequest returns the API Request of the given http request.

type StructFunc added in v0.9.4

type StructFunc func(ar *Request) (i interface{}, err error)

StructFunc is for returning any kind of struct.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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