server

package
v0.0.0-...-236a0cd Latest Latest
Warning

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

Go to latest
Published: May 8, 2026 License: Apache-2.0 Imports: 28 Imported by: 14

Documentation

Overview

Package server provides a RESTful HTTPS server implementation for the Layer 8 framework. It supports TLS, bearer token authentication, and seamless integration with Layer 8's Virtual Network Interface (VNic) for distributed service communication.

The server registers web services dynamically and routes HTTP requests through the Layer 8 network overlay, enabling proximity-based routing and service discovery.

Index

Constants

View Source
const (
	WsNotifyServiceName = "websock"
	WsNotifyServiceArea = byte(0)
)
View Source
const (
	// ServiceTypeName is the identifier used when registering the WebService
	// with the Layer 8 service manager.
	ServiceTypeName = "WebService"
)

Variables

View Source
var BearerCookieName = "bToken"

BearerCookieName is the name of the HTTP-only cookie used to store bearer tokens for browser-based authentication.

View Source
var Method = ifs.M_Leader

Method specifies the routing method for requests: M_Leader (leader-based), M_Local (local service), or M_Proximity (proximity-based routing).

View Source
var Target = ""

Target specifies a specific service instance UUID to route requests to. If empty, requests are routed based on the Method setting.

View Source
var Timeout = 30

Timeout specifies the default request timeout in seconds for VNic operations.

Functions

func NewRestServer

func NewRestServer(config *RestServerConfig) (ifs.IWebServer, error)

NewRestServer creates a new HTTPS REST server with the provided configuration. It initializes the HTTP multiplexer and loads any web UI files. CertDomain and CertPrivate are required — the server only supports HTTPS.

func NewRestServerNoIndex

func NewRestServerNoIndex(config *RestServerConfig) (ifs.IWebServer, error)

NewRestServerNoIndex creates a REST server in proxy mode, which disables the default index.html serving. This is used when the server operates behind a reverse proxy that handles static file serving.

func UpdateLoginJsonPrefix

func UpdateLoginJsonPrefix(prefix string) error

UpdateLoginJsonPrefix reads the web/login.json file, updates the apiPrefix field under the "app" section with the given prefix, and writes it back.

Types

type RestServer

type RestServer struct {
	RestServerConfig // Embedded configuration
	// contains filtered or unexported fields
}

RestServer implements the ifs.IWebServer interface and provides HTTPS server functionality with Layer 8 integration. It manages web service registration, TLS configuration, and request routing.

func (*RestServer) Deadline

func (this *RestServer) Deadline() (deadline time.Time, ok bool)

Deadline implements context.Context interface for shutdown coordination. Returns the current time as the deadline.

func (*RestServer) Done

func (this *RestServer) Done() <-chan struct{}

Done implements context.Context interface for shutdown coordination. Returns nil as this context doesn't support cancellation signaling.

func (*RestServer) Err

func (this *RestServer) Err() error

Err implements context.Context interface for shutdown coordination. Returns nil as this context doesn't track cancellation errors.

func (*RestServer) LoadWebUI

func (this *RestServer) LoadWebUI()

LoadWebUI scans the web directory and registers HTTP handlers for all files. It clears the file map (for hot-reload) but preserves handler registrations since Go's ServeMux doesn't support handler removal. In proxy mode, the root handler is not registered to avoid conflicts with the reverse proxy.

func (*RestServer) RegisterHandler

func (this *RestServer) RegisterHandler(path string, handler http.Handler)

RegisterHandler registers a custom HTTP handler at the given path, prefixed with the server's URL prefix. Use this for webhook endpoints and other custom handlers that don't follow the service area/name pattern.

func (*RestServer) RegisterWebService

func (this *RestServer) RegisterWebService(ws ifs.IWebService, vnic ifs.IVNic)

RegisterWebService registers a web service with the server, creating an HTTP handler that routes requests through the Layer 8 VNic. Each service is assigned a unique URL pattern based on its service area and name. Duplicate registrations are ignored.

func (*RestServer) Start

func (this *RestServer) Start() error

Start begins listening for HTTPS requests. This method blocks until the server is stopped.

func (*RestServer) Stop

func (this *RestServer) Stop()

Stop gracefully shuts down the server and cleans up registered endpoints. It uses the RestServer itself as the context for shutdown coordination.

func (*RestServer) Value

func (this *RestServer) Value(key interface{}) interface{}

Value implements context.Context interface for shutdown coordination. Returns nil as this context doesn't store any values.

type RestServerConfig

type RestServerConfig struct {
	Host           string // Host address to bind to (e.g., "localhost", "0.0.0.0")
	Port           int    // Port number to listen on
	Authentication bool   // Enable bearer token authentication for endpoints
	Prefix         string // URL prefix for all registered endpoints (e.g., "/api/v1/")
	CertDomain     string // TLS certificate PEM (required)
	CertPrivate    string // TLS private key PEM (required)
}

RestServerConfig contains the configuration options for creating a REST server.

type ServiceAction

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

ServiceAction encapsulates request and response Protocol Buffer messages for a service operation.

type ServiceHandler

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

ServiceHandler handles HTTP requests for a specific web service, routing them through the Layer 8 VNic to the appropriate service implementation. It manages authentication validation, request parsing, and response serialization.

func (*ServiceHandler) ServiceArea

func (this *ServiceHandler) ServiceArea() byte

ServiceArea returns the service area identifier used for request routing.

func (*ServiceHandler) ServiceName

func (this *ServiceHandler) ServiceName() string

ServiceName returns the name of the service this handler manages.

type WebService

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

WebService implements the Layer 8 service handler interface for web service management. It handles service activation, HTTP endpoint registration, and cross-VNet authentication token mapping.

func (*WebService) Activate

func (this *WebService) Activate(sla *ifs.ServiceLevelAgreement, vnic ifs.IVNic) error

Activate initializes the WebService and registers all HTTP endpoints. It sets up authentication, TFA, CAPTCHA, and registration handlers. If additional VNic instances are provided in the SLA args, they are registered as adjacent networks for cross-VNet authentication.

func (*WebService) Auth

func (this *WebService) Auth(w http.ResponseWriter, r *http.Request)

Auth handles user authentication requests at the /auth endpoint. It expects a POST request with JSON body containing user and pass fields. On successful authentication, it returns a bearer token and sets an HTTP-only cookie for browser-based clients. Also handles TFA status (needTfa, setupTfa). For cross-VNet setups, it also authenticates with adjacent networks and maps tokens.

func (*WebService) Captcha

func (this *WebService) Captcha(w http.ResponseWriter, r *http.Request)

Captcha handles the /captcha endpoint for generating CAPTCHA challenges. It returns a CAPTCHA string that must be included in registration requests to prevent automated bot registrations. The CAPTCHA is typically displayed as an image challenge that users must solve.

func (*WebService) DeActivate

func (this *WebService) DeActivate() error

DeActivate performs cleanup when the service is being shut down. Currently a no-op as cleanup is handled elsewhere.

func (*WebService) Delete

func (this *WebService) Delete(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

Delete handles DELETE requests for the WebService. Not implemented.

func (*WebService) Failed

func (this *WebService) Failed(pb ifs.IElements, vnic ifs.IVNic, msg *ifs.Message) ifs.IElements

Failed handles failed requests for the WebService. Not implemented.

func (*WebService) Get

func (this *WebService) Get(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

Get handles GET requests for the WebService. Returns an empty response.

func (*WebService) GetCopy

func (this *WebService) GetCopy(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

GetCopy handles copy GET requests for the WebService. Not implemented.

func (*WebService) Patch

func (this *WebService) Patch(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

Patch handles PATCH requests for the WebService. Not implemented.

func (*WebService) Permissions

func (this *WebService) Permissions(w http.ResponseWriter, r *http.Request)

Permissions handles requests to the /permissions endpoint, returning the per-type allowed actions for the authenticated user as JSON. Response format: { "TypeName": [1,2,5], ... } where 1=POST,2=PUT,3=PATCH,4=DELETE,5=GET

func (*WebService) Post

func (this *WebService) Post(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

Post handles incoming web service registration requests via Layer 8 messaging. When a new web service is discovered in the network, this method deserializes the service definition, loads any associated plugins, and registers the service with the local REST server.

func (*WebService) Put

func (this *WebService) Put(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

Put handles PUT requests for the WebService. Not implemented.

func (*WebService) Register

func (this *WebService) Register(w http.ResponseWriter, r *http.Request)

Register handles the /register endpoint for new user registration. It expects a POST request with username, password, and a valid CAPTCHA response. The CAPTCHA must match one previously obtained from the /captcha endpoint. Returns HTTP 200 on success or HTTP 401 if registration fails (invalid CAPTCHA, duplicate user, etc.).

func (*WebService) Registry

func (this *WebService) Registry(w http.ResponseWriter, r *http.Request)

Registry handles requests to the /registry endpoint, returning the type registry as JSON. Requires authentication if globally enabled.

func (*WebService) TFASetup

func (this *WebService) TFASetup(w http.ResponseWriter, r *http.Request)

TFASetup handles the /tfaSetup endpoint for Two-Factor Authentication setup. It expects a POST request with a user ID and returns a secret key and QR code URL that can be scanned by authenticator apps (Google Authenticator, Authy, etc.). The QR code encodes a TOTP URI that authenticator apps can use to generate codes.

func (*WebService) TFAVerify

func (this *WebService) TFAVerify(w http.ResponseWriter, r *http.Request)

TFAVerify handles the /tfaVerify and /tfaSetupVerify endpoints for TOTP code verification. It expects a POST request with user ID, the 6-digit TOTP code, and optionally a bearer token. On success, it returns ok=true. This is used both for initial TFA setup verification and for validating TFA codes during login.

func (*WebService) TransactionConfig

func (this *WebService) TransactionConfig() ifs.ITransactionConfig

TransactionConfig returns the transaction configuration for this service. Returns nil as WebService doesn't use transactions.

func (*WebService) ValidateBearerToken

func (this *WebService) ValidateBearerToken(r *http.Request) error

ValidateBearerToken validates the bearer token from an HTTP request. It first checks the Authorization header, then falls back to extractToken (which checks cookies and query parameters). Returns an error if the token is missing or invalid. This method is used by the reverse proxy for protected endpoint validation.

func (*WebService) WebService

func (this *WebService) WebService() ifs.IWebService

WebService returns the web service interface. Returns nil as this is the manager.

type WebSocketManager

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

WebSocketManager manages WebSocket connections keyed by AAAId (authenticated user identity).

func NewWebSocketManager

func NewWebSocketManager(vnic ifs.IVNic) *WebSocketManager

func (*WebSocketManager) ConnectionCount

func (this *WebSocketManager) ConnectionCount() int

ConnectionCount returns the number of active WebSocket connections.

func (*WebSocketManager) HandleUpgrade

func (this *WebSocketManager) HandleUpgrade(w http.ResponseWriter, r *http.Request)

HandleUpgrade validates the bearer token, resolves the AAAId, and upgrades to a WebSocket connection.

func (*WebSocketManager) OnNotification

func (this *WebSocketManager) OnNotification(notification *l8notify.L8NotificationSet)

OnNotification serializes a notification and sends to subscribed clients.

func (*WebSocketManager) Remove

func (this *WebSocketManager) Remove(aaaId string)

Remove closes and removes the connection for the given AAAId.

type WsNotifyService

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

WsNotifyService is a stateless service that receives client-facing change notifications via L8Bus multicast and forwards them to WebSocket clients.

func NewWsNotifyService

func NewWsNotifyService(wsManager *WebSocketManager) *WsNotifyService

func (*WsNotifyService) Activate

func (this *WsNotifyService) Activate(sla *ifs.ServiceLevelAgreement, vnic ifs.IVNic) error

func (*WsNotifyService) DeActivate

func (this *WsNotifyService) DeActivate() error

func (*WsNotifyService) Delete

func (this *WsNotifyService) Delete(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

func (*WsNotifyService) Failed

func (this *WsNotifyService) Failed(pb ifs.IElements, vnic ifs.IVNic, msg *ifs.Message) ifs.IElements

func (*WsNotifyService) Get

func (this *WsNotifyService) Get(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

func (*WsNotifyService) Patch

func (this *WsNotifyService) Patch(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

func (*WsNotifyService) Post

func (this *WsNotifyService) Post(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

func (*WsNotifyService) Put

func (this *WsNotifyService) Put(pb ifs.IElements, vnic ifs.IVNic) ifs.IElements

func (*WsNotifyService) TransactionConfig

func (this *WsNotifyService) TransactionConfig() ifs.ITransactionConfig

func (*WsNotifyService) WebService

func (this *WsNotifyService) WebService() ifs.IWebService

Jump to

Keyboard shortcuts

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