api

package
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: May 13, 2024 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ScopeUser  = "b3scale"
	ScopeAdmin = "b3scale:admin"
	ScopeNode  = "b3scale:node"
)

Scopes

View Source
const (
	RPCStatusOK    = "ok"
	RPCStatusError = "error"
)

RPC status

View Source
const (
	ActionMeetingStateReset     = "meeting_state_reset"
	ActionMeetingSetRunning     = "meeting_set_running"
	ActionMeetingAddAttendee    = "meeting_add_attendee"
	ActionMeetingRemoveAttendee = "meeting_remove_attendee"
)

Actions

View Source
const (
	// PrefixInternalID indicates that the ID is an 'internal' ID.
	PrefixInternalID = "internal:"
)

Variables

View Source
var (
	ErrInvalidAction  = errors.New("the requsted RPC action is unknown")
	ErrInvalidBackend = errors.New("backend not associated with meeting")
)

Errors

View Source
var ErrCommandNotAllowed = store.ValidationError{
	"action": []string{"this action is not allowed"},
}

ErrCommandNotAllowed is a validation error

View Source
var (
	// ErrMissingJWTSecret will be returned if a JWT secret
	// could not be found in the environment.
	ErrMissingJWTSecret = errors.New("missing JWT secret")
)

Errors

View Source
var ErrNotFound = errors.New("the resource could not be found (404)")

ErrNotFound is the error when a response is a 404

View Source
var (
	ErrRequestBodyRequired = echo.NewHTTPError(
		http.StatusBadRequest,
		"the request must contain content of a metadata.xml")
)

Errors

View Source
var ResourceAgentBackend = &Resource{
	List: RequireScope(
		ScopeNode,
	)(apiAgentBackendShow),
}

ResourceAgentBackend is the resource for retrieving the currently with the agent associated backend

View Source
var ResourceAgentHeartbeat = &Resource{
	Create: RequireScope(
		ScopeNode,
	)(apiAgentHeartbeatCreate),
}

ResourceAgentHeartbeat is the resource for receiving an agent heartbeat

View Source
var ResourceAgentRPC = &Resource{

	Create: RequireScope(
		ScopeNode,
	)(func(ctx context.Context, api *API) error {

		rpc := &RPCRequest{}
		if err := api.Bind(rpc); err != nil {
			return api.JSON(http.StatusBadRequest, RPCError(err))
		}

		tx, err := api.Conn.Begin(ctx)
		if err != nil {
			return err
		}
		defer tx.Rollback(ctx)

		backend, err := BackendFromAgentRef(ctx, api, tx)
		if err != nil {
			return err
		}
		if backend == nil {
			return echo.ErrForbidden
		}
		tx.Rollback(ctx)

		res := rpc.Dispatch(ctx, &RPCHandler{
			AgentRef: api.Ref,
			Backend:  backend,
			Conn:     api.Conn,
		})

		return api.JSON(http.StatusOK, res)
	}),
}

ResourceAgentRPC is the API resource for creating RPC requests

View Source
var ResourceBackends = &Resource{
	List: RequireScope(
		ScopeAdmin,
	)(apiBackendsList),

	Create: RequireScope(
		ScopeAdmin,
		ScopeNode,
	)(apiBackendCreate),

	Show: RequireScope(
		ScopeAdmin,
		ScopeNode,
	)(apiBackendShow),

	Update: RequireScope(
		ScopeAdmin,
		ScopeNode,
	)(apiBackendUpdate),

	Destroy: RequireScope(
		ScopeAdmin,
	)(apiBackendDestroy),
}

ResourceBackends is a restful group for backend endpoints

View Source
var ResourceCommands = &Resource{
	List: RequireScope(
		ScopeAdmin,
	)(apiCommandList),

	Show: RequireScope(
		ScopeAdmin,
	)(apiCommandShow),

	Create: RequireScope(
		ScopeAdmin,
	)(apiCommandCreate),
}

ResourceCommands bundles read and create operations for manipulating the command queue.

View Source
var ResourceCtlMigrate = &Resource{
	Create: RequireScope(
		ScopeAdmin,
	)(apiCtlMigrate),
}

ResourceCtlMigrate is a restful group for applying migrations

View Source
var ResourceFrontends = &Resource{
	List: RequireScope(
		ScopeAdmin,
		ScopeUser,
	)(apiFrontendsList),

	Create: RequireScope(
		ScopeAdmin,
	)(apiFrontendCreate),

	Show: RequireScope(
		ScopeAdmin,
		ScopeUser,
	)(apiFrontendShow),

	Update: RequireScope(
		ScopeAdmin,
		ScopeUser,
	)(apiFrontendUpdate),

	Destroy: RequireScope(
		ScopeAdmin,
	)(apiFrontendDestroy),
}

ResourceFrontends is a restful group for frontend endpoints

View Source
var ResourceMeetings = &Resource{
	List: RequireScope(
		ScopeAdmin,
	)(apiMeetingsList),

	Show: RequireScope(
		ScopeAdmin,
		ScopeNode,
	)(apiMeetingShow),

	Update: RequireScope(
		ScopeAdmin,
		ScopeNode,
	)(apiMeetingUpdate),

	Destroy: RequireScope(
		ScopeAdmin,
		ScopeNode,
	)(apiMeetingDestroy),
}

ResourceMeetings is a restful group for meetings

View Source
var ResourceRecordingsImport = &Resource{
	Create: RequireScope(
		ScopeAdmin,
		ScopeNode,
	)(apiRecordingsImport),
}

ResourceRecordingsImport is the recordings import api resource

Functions

func BackendFromAgentRef

func BackendFromAgentRef(
	ctx context.Context,
	api *API,
	tx pgx.Tx,
) (*store.BackendState, error)

BackendFromAgentRef resolves the backend attached to the current node agent.

func BackendFromQuery

func BackendFromQuery(
	ctx context.Context,
	api *API,
	tx pgx.Tx,
) (*store.BackendState, error)

BackendFromQuery resolves the backend, either identified by ID or by hostname. The hostname must be an exact match.

func ContextMiddleware

func ContextMiddleware(next echo.HandlerFunc) echo.HandlerFunc

ContextMiddleware initializes the context with auth information and a database connection.

func Endpoint

func Endpoint(handler ResourceHandler) echo.HandlerFunc

Endpoint wrapps a handler function and provides the request context and sets the correct APIContext type.

func ErrScopeRequired

func ErrScopeRequired(scopes ...string) *echo.HTTPError

ErrScopeRequired will be returned when a scope is missing from the response.

func ErrorHandler

func ErrorHandler(next echo.HandlerFunc) echo.HandlerFunc

ErrorHandler intercepts well known errors and renders a response.

func ErrorInvalidCredentials

func ErrorInvalidCredentials(c echo.Context) error

ErrorInvalidCredentials will create an API response for an unauthorized request

func ErrorValidationFailed

func ErrorValidationFailed(c echo.Context, err store.ValidationError) error

ErrorValidationFailed creates an API response when validating a resource failed.

func GenerateNonce

func GenerateNonce(n int) string

GenerateNonce will create a random string of length n

func GenerateRef

func GenerateRef(n int) string

GenerateRef will create a most likely unique combination of words.

func Init

func Init(e *echo.Echo) error

Init sets up a group with authentication for a restful management interface.

func InternalMeetingID

func InternalMeetingID(id string) string

InternalMeetingID returns the internal id for accessing via the API.

func MeetingFromRequest

func MeetingFromRequest(
	ctx context.Context,
	api *API,
	tx pgx.Tx,
) (*store.MeetingState, error)

MeetingFromRequest resolves the current meeting

func NewAPIEndpointsSchema

func NewAPIEndpointsSchema() map[string]oa.Path

NewAPIEndpointsSchema combines all the endpoints schemas

func NewAPIJWTConfig

func NewAPIJWTConfig() (middleware.JWTConfig, error)

NewAPIJWTConfig creates a new JWT middleware config. Parameters like shared secrets, public keys, etc.. are retrieved from the environment.

func NewAPIResponses

func NewAPIResponses() map[string]oa.Response

NewAPIResponses creates all default (error) responses

func NewAPISchemas

func NewAPISchemas() map[string]oa.Schema

NewAPISchemas creates the schemas we use in the API

func NewAPISecuritySchemes

func NewAPISecuritySchemes() map[string]oa.SecurityScheme

NewAPISecuritySchemes creates the default security schemes

func NewAPISpec

func NewAPISpec() *oa.Spec

NewAPISpec makes the api specs for b3scale

func NewAgentAPISchema

func NewAgentAPISchema() map[string]oa.Path

NewAgentAPISchema creates the API schema for the node agent

func NewBackendsAPISchema

func NewBackendsAPISchema() map[string]oa.Path

NewBackendsAPISchema generates the schema for backend related endpoint.

func NewCommandsAPISchema

func NewCommandsAPISchema() map[string]oa.Path

NewCommandsAPISchema create the endpoint schema for commands

func NewCtrlEndpointsSchema

func NewCtrlEndpointsSchema() map[string]oa.Path

NewCtrlEndpointsSchema creates the api ctrl endpoints

func NewErrorSchema

func NewErrorSchema() oa.Schema

NewErrorSchema creates the error schema

func NewFrontendsAPISchema

func NewFrontendsAPISchema() map[string]oa.Path

NewFrontendsAPISchema generates the endpoints for the frontend

func NewMeetingsAPISchema

func NewMeetingsAPISchema() map[string]oa.Path

NewMeetingsAPISchema create the endpoint schema for meetings

func NewMetaEndpointsSchema

func NewMetaEndpointsSchema() map[string]oa.Path

NewMetaEndpointsSchema creates the api meta endpoints

func NewNotFoundErrorSchema

func NewNotFoundErrorSchema() oa.Schema

NewNotFoundErrorSchema creates a not found error object schema

func NewRPCRequestSchema

func NewRPCRequestSchema() oa.Schema

NewRPCRequestSchema creates the RPCRequest schema

func NewRPCResponseSchema

func NewRPCResponseSchema() oa.Schema

NewRPCResponseSchema creates the RPC response schema

func NewRecordingsImportAPISchema

func NewRecordingsImportAPISchema() map[string]oa.Path

NewRecordingsImportAPISchema creates the api schema for accepting a BBB recodrings metadata document

func NewServerErrorSchema

func NewServerErrorSchema() oa.Schema

NewServerErrorSchema creates a fallback error schema with only contains the error message.

func NewValidationErrorSchema

func NewValidationErrorSchema() oa.Schema

NewValidationErrorSchema creates the validation error schema

func SignAccessToken

func SignAccessToken(sub string, scope string, secret []byte) (string, error)

SignAccessToken creates an authorized JWT

func SignAdminAccessToken

func SignAdminAccessToken(sub string, secret []byte) (string, error)

SignAdminAccessToken creates a new authorized JWT with an admin scope.

Types

type API

type API struct {
	// Authorization
	Scopes []string
	Ref    string
	// Database
	Conn *pgxpool.Conn

	echo.Context
}

API extends the context and provides methods for handling the current user.

func (*API) Ctx

func (api *API) Ctx() context.Context

Ctx is a shortcut to access the request context

func (*API) HasScope

func (api *API) HasScope(s string) (found bool)

HasScope checks if the authentication scope claim contains a scope by name. The scope claim is a space separated list of scopes according to RFC8693, Section 4.2, (OAuth 2).

func (*API) ParamID

func (api *API) ParamID() (string, bool)

ParamID is a shortcut to access the ID parameter. If the parameter is prefixed with `internal:`, the prefix will be stripped and the ID will be returned.

type AgentResourceClient

type AgentResourceClient interface {
	AgentHeartbeatCreate(
		ctx context.Context,
	) (*store.AgentHeartbeat, error)
	AgentBackendRetrieve(
		ctx context.Context,
	) (*store.BackendState, error)
	AgentRPC(
		ctx context.Context,
		req *RPCRequest,
	) (RPCResult, error)
}

AgentResourceClient defines node agent specific methods.

type AuthClaims

type AuthClaims struct {
	Scope string `json:"scope"`
	jwt.StandardClaims
}

AuthClaims extends the JWT standard claims with a well-known `scope` claim.

type BackendResourceClient

type BackendResourceClient interface {
	BackendsList(
		ctx context.Context, query ...url.Values,
	) ([]*store.BackendState, error)
	BackendRetrieve(
		ctx context.Context, id string,
	) (*store.BackendState, error)
	BackendCreate(
		ctx context.Context, backend *store.BackendState,
	) (*store.BackendState, error)
	BackendUpdate(
		ctx context.Context, backend *store.BackendState,
	) (*store.BackendState, error)
	BackendUpdateRaw(
		ctx context.Context, id string, payload []byte,
	) (*store.BackendState, error)
	BackendDelete(
		ctx context.Context,
		backend *store.BackendState,
		opts ...url.Values,
	) (*store.BackendState, error)
}

BackendResourceClient defines methods for using the backends api resource

type Client

Client is an interface to the api API.

type CommandResourceClient

type CommandResourceClient interface {
	BackendMeetingsEnd(
		ctx context.Context,
		backendID string,
	) (*store.Command, error)

	CommandCreate(
		ctx context.Context,
		cmd *store.Command,
	) (*store.Command, error)
	CommandRetrieve(
		ctx context.Context,
		id string,
	) (*store.Command, error)

	// Control commands
	CtrlMigrate(
		ctx context.Context,
	) (*schema.Status, error)
}

CommandResourceClient defines methods for creating and polling commands

type FrontendResourceClient

type FrontendResourceClient interface {
	FrontendsList(
		ctx context.Context, query ...url.Values,
	) ([]*store.FrontendState, error)
	FrontendRetrieve(
		ctx context.Context, id string,
	) (*store.FrontendState, error)
	FrontendCreate(
		ctx context.Context, frontend *store.FrontendState,
	) (*store.FrontendState, error)
	FrontendUpdate(
		ctx context.Context, frontend *store.FrontendState,
	) (*store.FrontendState, error)
	FrontendUpdateRaw(
		ctx context.Context, id string, payload []byte,
	) (*store.FrontendState, error)
	FrontendDelete(
		ctx context.Context, frontend *store.FrontendState,
	) (*store.FrontendState, error)
}

FrontendResourceClient defines methods for using the frontends resource of the api

type MeetingAddAttendeeRequest

type MeetingAddAttendeeRequest struct {
	InternalMeetingID string        `json:"internal_meeting_id"`
	Attendee          *bbb.Attendee `json:"attendee"`
}

MeetingAddAttendeeRequest will add an attedee to the attendees list of a meeting

type MeetingRemoveAttendeeRequest

type MeetingRemoveAttendeeRequest struct {
	InternalMeetingID string `json:"internal_meeting_id"`
	InternalUserID    string `json:"internal_user_id"`
}

MeetingRemoveAttendeeRequest will remove an attendee from a meeting identified by the internal user id

type MeetingResourceClient

type MeetingResourceClient interface {
	BackendMeetingsList(
		ctx context.Context,
		backendID string,
		query ...url.Values,
	) ([]*store.MeetingState, error)

	MeetingsList(
		ctx context.Context,
		query ...url.Values,
	) ([]*store.MeetingState, error)
	MeetingRetrieve(
		ctx context.Context,
		id string,
	) (*store.MeetingState, error)
	MeetingUpdateRaw(
		ctx context.Context,
		id string,
		payload []byte,
	) (*store.MeetingState, error)
	MeetingUpdate(
		ctx context.Context,
		meeting *store.MeetingState,
	) (*store.MeetingState, error)
	MeetingDelete(
		ctx context.Context,
		id string,
	) (*store.MeetingState, error)
}

MeetingResourceClient defines methods for accessing the meetings api resource

type MeetingSetRunningRequest

type MeetingSetRunningRequest struct {
	InternalMeetingID string `json:"internal_meeting_id"`
	Running           bool   `json:"running"`
}

MeetingSetRunningRequest contains a meetingID

type MeetingStateResetRequest

type MeetingStateResetRequest struct {
	InternalMeetingID string `json:"internal_meeting_id"`
}

MeetingStateResetRequest contains a meetingID

type RPCHandler

type RPCHandler struct {
	AgentRef string
	Backend  *store.BackendState
	Conn     *pgxpool.Conn
}

RPCHandler contains a database connection

func (*RPCHandler) MeetingAddAttendee

func (rpc *RPCHandler) MeetingAddAttendee(
	ctx context.Context,
	req *MeetingAddAttendeeRequest,
) (RPCResult, error)

MeetingAddAttendee insers an attendee into the list

func (*RPCHandler) MeetingRemoveAttendee

func (rpc *RPCHandler) MeetingRemoveAttendee(
	ctx context.Context,
	req *MeetingRemoveAttendeeRequest,
) (RPCResult, error)

MeetingRemoveAttendee removes an attendee from the list

func (*RPCHandler) MeetingSetRunning

func (rpc *RPCHandler) MeetingSetRunning(
	ctx context.Context,
	req *MeetingSetRunningRequest,
) (RPCResult, error)

MeetingSetRunning sets the meeting is running flag for a meeting. The meeting will be awaited.

func (*RPCHandler) MeetingStateReset

func (rpc *RPCHandler) MeetingStateReset(
	ctx context.Context,
	req *MeetingStateResetRequest,
) (RPCResult, error)

MeetingStateReset clears the attendees list and sets the running flag to false

type RPCPayload

type RPCPayload json.RawMessage

RPCPayload is a json raw message which then can be decoded into the actual request

type RPCRequest

type RPCRequest struct {
	Action  string     `json:"action"`
	Payload RPCPayload `json:"payload"`
}

RPCRequest is an incomming request with an action and a payload.

func NewRPCRequest

func NewRPCRequest(
	action string,
	params interface{},
) *RPCRequest

NewRPCRequest creates a new RPC request

func RPCMeetingAddAttendee

func RPCMeetingAddAttendee(params *MeetingAddAttendeeRequest) *RPCRequest

RPCMeetingAddAttendee creates a new add attendee request

func RPCMeetingRemoveAttendee

func RPCMeetingRemoveAttendee(params *MeetingRemoveAttendeeRequest) *RPCRequest

RPCMeetingRemoveAttendee creates a remove attendee request

func RPCMeetingSetRunning

func RPCMeetingSetRunning(params *MeetingSetRunningRequest) *RPCRequest

RPCMeetingSetRunning creates a set running request

func RPCMeetingStateReset

func RPCMeetingStateReset(params *MeetingStateResetRequest) *RPCRequest

RPCMeetingStateReset creates an meeting state reset request

func (*RPCRequest) Dispatch

func (rpc *RPCRequest) Dispatch(
	ctx context.Context,
	handler *RPCHandler,
) *RPCResponse

Dispatch will invoke the RPC handlers with the decoded request payload.

type RPCResponse

type RPCResponse struct {
	Status string    `json:"status"`
	Result RPCResult `json:"result"`
}

RPCResponse is the result of an RPC request

func RPCError

func RPCError(err error) *RPCResponse

RPCError is an RPC error response

func RPCSuccess

func RPCSuccess(result RPCResult) *RPCResponse

RPCSuccess is a successful RPC response

type RPCResult

type RPCResult interface{}

RPCResult is anything the handle responds with

type Resource

type Resource struct {
	List    ResourceHandler
	Show    ResourceHandler
	Create  ResourceHandler
	Update  ResourceHandler
	Destroy ResourceHandler
}

Resource is a restful handler group

func (*Resource) Mount

func (r *Resource) Mount(
	root *echo.Group,
	prefix string,
	middlewares ...echo.MiddlewareFunc,
)

Mount registers the endpoints in the group

type ResourceHandler

type ResourceHandler func(context.Context, *API) error

ResourceHandler is a handler function for API endpoints

type ResourceMiddleware

type ResourceMiddleware func(next ResourceHandler) ResourceHandler

ResourceMiddleware is a function returning a HandlerFunction

func RequireScope

func RequireScope(scopes ...string) ResourceMiddleware

RequireScope creates a middleware to ensure the presence of at least one required scope.

type Scopes

type Scopes []string

Scopes is a list of scopes

type ServerError

type ServerError map[string]interface{}

ServerError will contain the decoded json body when the response status was not OK or Accepted

func (ServerError) Error

func (err ServerError) Error() string

Error implements the error interface

type StatusResponse

type StatusResponse struct {
	Version    string         `json:"version" doc:"The current b3scale server version."`
	Build      string         `json:"build" doc:"Build identifier of the server."`
	API        string         `json:"api" doc:"The API version." example:"v1"`
	AccountRef string         `json:"account_ref" doc:"The currently authenticated subject."`
	IsAdmin    bool           `json:"is_admin" doc:"True if the subject has admin privileges."`
	Database   *schema.Status `json:"database" doc:"Status of the database" api:"SchemaStatus"`
}

StatusResponse returns information about the API implementation and the current user.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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