http_server

package
v0.0.0-...-8bc3ba8 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2023 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	UUIDKey                = "uuid"
	VerifyPath             = "/verify"
	OfflinePath            = "/offline"
	HashEndpoint           = "/hash"
	RegisterEndpoint       = "/register"
	CSREndpoint            = "/csr"
	ActiveUpdateEndpoint   = "/device/updateActive"
	MetricsEndpoint        = "/metrics"
	LivenessCheckEndpoint  = "/healthz"
	ReadinessCheckEndpoint = "/readyz"

	BinType  = "application/octet-stream"
	TextType = "text/plain"
	JSONType = "application/json"

	XUPPHeader   = "X-Ubirch-UPP"
	XAuthHeader  = "X-Auth-Token"
	XErrorHeader = "X-Err"

	HexEncoding = "hex"

	HashLen = 32
)
View Source
const (
	GatewayTimeout  = 20 * time.Second // time after which a 504 response will be sent if no timely response could be produced
	ShutdownTimeout = 10 * time.Second // time after which the server will be shut down forcefully if graceful shutdown did not happen before
	ReadTimeout     = 1 * time.Second  // maximum duration for reading the entire request -> low since we only expect requests with small content
	WriteTimeout    = 60 * time.Second // time after which the connection will be closed if response was not written -> this should never happen
	IdleTimeout     = 60 * time.Second // time to wait for the next request when keep-alives are enabled
)

Variables

View Source
var (
	UUIDPath = fmt.Sprintf("/{%s}", UUIDKey)

	ErrUnknown            = errors.New("identity unknown")
	ErrAlreadyInitialized = errors.New("identity already registered")
	ErrAlreadyDeactivated = errors.New("key already deactivated")
	ErrAlreadyActivated   = errors.New("key already activated")
)

Functions

func AuthToken

func AuthToken(header http.Header) string

helper function to get "X-Auth-Token" from request header

func ClientError

func ClientError(uid uuid.UUID, r *http.Request, w http.ResponseWriter, errMsg string, code int)

ClientError is a wrapper for http.Error that additionally logs uuid, request URL path, error message and status with logging level "warning"

func ContentEncoding

func ContentEncoding(header http.Header) string

helper function to get "Content-Transfer-Encoding" from request header

func ContentType

func ContentType(header http.Header) string

helper function to get "Content-Type" from request header

func FetchCSR

func FetchCSR(auth string, get GetCSR) http.HandlerFunc

func GetSortedCompactJSON

func GetSortedCompactJSON(data []byte) ([]byte, error)

func GetUUID

func GetUUID(r *http.Request) (uuid.UUID, error)

GetUUID returns the UUID parameter from the request URL

func HandleOptions

func HandleOptions(http.ResponseWriter, *http.Request)

func Health

func Health(server string) http.HandlerFunc

Health is a liveness probe.

func HttpFailed

func HttpFailed(StatusCode int) bool

func HttpSuccess

func HttpSuccess(StatusCode int) bool

func NewRouter

func NewRouter() *chi.Mux

func ReadBody

func ReadBody(r *http.Request) ([]byte, error)

func Ready

func Ready(server string, readinessChecks []func() error) http.HandlerFunc

Ready is a readiness probe.

func Register

func Register(auth string, initialize InitializeIdentity) http.HandlerFunc

func SendResponse

func SendResponse(w http.ResponseWriter, resp HTTPResponse)

SendResponse forwards a response to the client

func ServerError

func ServerError(uid uuid.UUID, r *http.Request, w http.ResponseWriter, errMsg string, code int)

ServerError is a wrapper for http.Error that additionally logs uuid, request URL path, error message and status with logging level "error". The error message is not sent to the client.

func UpdateActive

func UpdateActive(auth string,
	deactivate UpdateActivateStatus,
	reactivate UpdateActivateStatus) http.HandlerFunc

Types

type ActiveUpdatePayload

type ActiveUpdatePayload struct {
	Uid    uuid.UUID `json:"id"`
	Active bool      `json:"active"`
}

func GetActiveUpdatePayload

func GetActiveUpdatePayload(r *http.Request) (*ActiveUpdatePayload, error)

type CheckAuth

type CheckAuth func(ctx context.Context, uid uuid.UUID, auth string) (ok, found bool, err error)

type GetCSR

type GetCSR func(uid uuid.UUID) (csr []byte, err error)

type HTTPRequest

type HTTPRequest struct {
	Ctx       context.Context
	ID        uuid.UUID
	Auth      string
	Hash      Sha256Sum
	Operation Operation
	Offline   bool
}

type HTTPResponse

type HTTPResponse struct {
	StatusCode int         `json:"statusCode"`
	Header     http.Header `json:"header"`
	Content    []byte      `json:"content"`
}

type HTTPServer

type HTTPServer struct {
	Router   *chi.Mux
	Addr     string
	TLS      bool
	CertFile string
	KeyFile  string
}

func InitHTTPServer

func InitHTTPServer(conf *config.Config,
	initialize InitializeIdentity, getCSR GetCSR,
	checkAuth CheckAuth, sign Sign,
	verify Verify, verifyOffline VerifyOffline,
	deactivate UpdateActivateStatus, reactivate UpdateActivateStatus,
	serverID string, readinessChecks []func() error) *HTTPServer

func (*HTTPServer) AddServiceEndpoint

func (srv *HTTPServer) AddServiceEndpoint(endpointPath string, handle func(offline, isHash bool) http.HandlerFunc, supportOffline bool)

func (*HTTPServer) Serve

func (srv *HTTPServer) Serve() error

func (*HTTPServer) SetUpCORS

func (srv *HTTPServer) SetUpCORS(allowedOrigins []string, debug bool)

type InitializeIdentity

type InitializeIdentity func(uid uuid.UUID, auth string) (csr []byte, err error)

type Operation

type Operation string
const (
	AnchorHash  Operation = "anchor"
	ChainHash   Operation = "chain"
	DisableHash Operation = "disable"
	EnableHash  Operation = "enable"
	DeleteHash  Operation = "delete"
)

type RegistrationPayload

type RegistrationPayload struct {
	Uid uuid.UUID `json:"uuid"`
	Pwd string    `json:"password"`
}

type Sha256Sum

type Sha256Sum [HashLen]byte

func GetHash

func GetHash(r *http.Request, isHashRequest bool) (Sha256Sum, error)

GetHash returns the hash from the request body

type Sign

type Sign func(msg HTTPRequest) (resp HTTPResponse)

type SigningService

type SigningService struct {
	CheckAuth
	Sign
}

func (*SigningService) HandleSigningRequest

func (s *SigningService) HandleSigningRequest(op Operation) func(bool, bool) http.HandlerFunc

HandleSigningRequest unpacks an incoming HTTP request and calls the Sign function with the according parameters. The function expects an Operation as parameter. Supported operations are anchoring, chaining, deleting etc.

There are online and offline signing endpoints for several operations, as well as endpoints for direct hash injection and JSON data packages for all operations. For that reason, the function is nested in a way that it can be passed to the AddServiceEndpoint function with the following signature: func (srv *HTTPServer) AddServiceEndpoint(endpointPath string, handle func(offline bool, isHash bool) http.HandlerFunc, supportOffline bool) That way we can call AddServiceEndpoint once for each operation in order to initialize the above endpoints.

type UpdateActivateStatus

type UpdateActivateStatus func(uid uuid.UUID) error

type VerificationService

type VerificationService struct {
	Verify
	VerifyOffline
}

func (*VerificationService) HandleVerificationRequest

func (s *VerificationService) HandleVerificationRequest(offline, isHashRequest bool) http.HandlerFunc

HandleVerificationRequest unpacks an incoming HTTP request and calls either Verify or VerifyOffline depending on the endpoint the request was received at.

There are online and offline verification endpoints, as well as endpoints for direct hash injection and JSON data packages. For that reason, the function is nested in a way that it can be passed to the AddServiceEndpoint function with the following signature: func (srv *HTTPServer) AddServiceEndpoint(endpointPath string, handle func(offline bool, isHash bool) http.HandlerFunc, supportOffline bool)

type Verify

type Verify func(ctx context.Context, hash []byte) HTTPResponse

type VerifyOffline

type VerifyOffline func(upp []byte, hash []byte) HTTPResponse

Jump to

Keyboard shortcuts

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