api

package
v0.23.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2023 License: AGPL-3.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PathVersion  = "/version"
	PathStatus   = "/v1/status"
	PathReady    = "/v1/ready"
	PathMetrics  = "/v1/metrics"
	PathListAPIs = "/v1/api"

	PathKeyCreate   = "/v1/key/create/"
	PathKeyImport   = "/v1/key/import/"
	PathKeyDescribe = "/v1/key/describe/"
	PathKeyDelete   = "/v1/key/delete/"
	PathKeyList     = "/v1/key/list/"
	PathKeyGenerate = "/v1/key/generate/"
	PathKeyEncrypt  = "/v1/key/encrypt/"
	PathKeyDecrypt  = "/v1/key/decrypt/"

	PathPolicyDescribe = "/v1/policy/describe/"
	PathPolicyRead     = "/v1/policy/read/"
	PathPolicyList     = "/v1/policy/list/"

	PathIdentityDescribe     = "/v1/identity/describe/"
	PathIdentityList         = "/v1/identity/list/"
	PathIdentitySelfDescribe = "/v1/identity/self/describe"

	PathLogError = "/v1/log/error"
	PathLogAudit = "/v1/log/audit"
)

API paths exposed by KES servers.

Variables

This section is empty.

Functions

func Fail

func Fail(r *Response, code int, msg string) error

Fail responds to the client with the given status code and error message. The message encoding format is selected automatically based on the response content type. Handlers should return after calling Fail.

func Failf

func Failf(r *Response, code int, format string, a ...any) error

Failf responds to the client with the given status code and formatted error message. The message encoding format is selected automatically based on the response content type. Handlers should return after calling Failf.

func Failr

func Failr(r *Response, err Error) error

Failr responds to the client with err. The response status code is set to err.Status. The error encoding format is selected automatically based on the response content type. Handlers should return after calling Failr.

func ReadBody

func ReadBody(r *Request, v any) error

ReadBody reads the request body into v using the request content encoding.

ReadBody assumes that the request body is limited to a reasonable size. It may return an error if it cannot determine the request content length before decoding.

func Reply

func Reply(r *Response, code int)

Reply sends just an HTTP status code to the client. The response body is empty.

func ReplyWith

func ReplyWith(r *Response, code int, data any) error

ReplyWith sends an HTTP status code and the data as response body to the client. The data format is selected automatically based on the response content encoding.

Types

type AuditLogEvent

type AuditLogEvent struct {
	Time     time.Time        `json:"time"`
	Request  AuditLogRequest  `json:"request"`
	Response AuditLogResponse `json:"response"`
}

AuditLogEvent is sent to clients (as stream of events) when they subscribe to the AuditLog API.

type AuditLogRequest

type AuditLogRequest struct {
	IP       string `json:"ip,omitempty"`
	APIPath  string `json:"path"`
	Identity string `json:"identity,omitempty"`
}

AuditLogRequest describes a client request in an AuditLogEvent.

type AuditLogResponse

type AuditLogResponse struct {
	StatusCode int   `json:"code"`
	Time       int64 `json:"time"` // In microseconds
}

AuditLogResponse describes a server response in an AuditLogEvent.

type Authenticator

type Authenticator interface {
	Authenticate(*http.Request) (*Request, Error)
}

An Authenticator authenticates HTTP requests.

Authenticate should verify an incoming HTTP request and return either an authenticated API request or an API error.

var InsecureSkipVerify Authenticator = insecureSkipVerify{}

InsecureSkipVerify is an Authenticator that does not verify incoming HTTP requests in any way. It should only be used for routes that do neither wish to authenticate requests nor care about the client identity.

type DecryptKeyRequest

type DecryptKeyRequest struct {
	Ciphertext []byte `json:"ciphertext"`
	Context    []byte `json:"context"` // optional
}

DecryptKeyRequest is the request sent by clients when calling the DecryptKey API.

type DecryptKeyResponse

type DecryptKeyResponse struct {
	Plaintext []byte `json:"plaintext"`
}

DecryptKeyResponse is the response sent to clients by the DecryptKey API.

type DescribeIdentityResponse

type DescribeIdentityResponse struct {
	IsAdmin   bool      `json:"admin,omitempty"`
	Policy    string    `json:"policy,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	CreatedBy string    `json:"created_by,omitempty"`
}

DescribeIdentityResponse is the response sent to clients by the DescribeIdentity API.

type DescribeKeyResponse

type DescribeKeyResponse struct {
	Name      string    `json:"name"`
	Algorithm string    `json:"algorithm,omitempty"`
	CreatedAt time.Time `json:"created_at,omitempty"`
	CreatedBy string    `json:"created_by,omitempty"`
}

DescribeKeyResponse is the response sent to clients by the DescribeKey API.

type DescribePolicyResponse

type DescribePolicyResponse struct {
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	CreatedBy string    `json:"created_by"`
}

DescribePolicyResponse is the response sent to clients by the DescribePolicy API.

type DescribeRouteResponse

type DescribeRouteResponse struct {
	Method  string `json:"method"`
	Path    string `json:"path"`
	MaxBody int64  `json:"max_body"`
	Timeout int64  `json:"timeout"` // in seconds
}

DescribeRouteResponse describes a single API route. It is part of a List API response.

type EncryptKeyRequest

type EncryptKeyRequest struct {
	Plaintext []byte `json:"plaintext"`
	Context   []byte `json:"context"` // optional
}

EncryptKeyRequest is the request sent by clients when calling the EncryptKey API.

type EncryptKeyResponse

type EncryptKeyResponse struct {
	Ciphertext []byte `json:"ciphertext"`
}

EncryptKeyResponse is the response sent to clients by the EncryptKey API.

type Error

type Error interface {
	error

	// Status returns the Error's HTTP status code.
	Status() int
}

Error is an API error.

Status codes should be within 400 (inclusive) and 600 (exclusive). HTTP clients treat status codes between 400 and 499 as client errors and status codes between 500 and 599 as server errors.

Refer to the net/http package for a list of HTTP status codes.

func IsError

func IsError(err error) (Error, bool)

IsError reports whether any error in err's tree is an Error. It returns the first error that implements Error, if any.

The tree consists of err itself, followed by the errors obtained by repeatedly unwrapping the error. When err wraps multiple errors, IsError examines err followed by a depth-first traversal of its children.

func NewError

func NewError(code int, msg string) Error

NewError returns a new Error from the given status code and error message.

func ReadError

func ReadError(resp *http.Response) Error

ReadError reads the response body into an Error using the response content encoding. It limits the response body to a reasonable size for typical error messages.

type ErrorLogEvent

type ErrorLogEvent struct {
	Message string `json:"message"`
}

ErrorLogEvent is sent to clients (as stream of events) when they subscribe to the ErrorLog API.

type GenerateKeyRequest

type GenerateKeyRequest struct {
	Context []byte `json:"context"` // optional
}

GenerateKeyRequest is the request sent by clients when calling the GenerateKey API.

type GenerateKeyResponse

type GenerateKeyResponse struct {
	Plaintext  []byte `json:"plaintext"`
	Ciphertext []byte `json:"ciphertext"`
}

GenerateKeyResponse is the response sent to clients by the GenerateKey API.

type Handler

type Handler interface {
	ServeAPI(*Response, *Request)
}

A Handler responds to an API request.

ServeAPI should either reply to the client or fail the request and then return. The Response type provides methods to do so. Returning signals that the request is finished; it is not valid to send a Response or read from the Request.Body after or concurrently with the completion of the ServeAPI call.

If ServeAPI panics, the HTTP server assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM, depending on the HTTP protocol. To abort a handler so the client sees an interrupted response but the server doesn't log an error, panic with the value http.ErrAbortHandler.

type HandlerFunc

type HandlerFunc func(*Response, *Request)

The HandlerFunc type is an adapter to allow the use of ordinary functions as API handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

func (HandlerFunc) ServeAPI

func (f HandlerFunc) ServeAPI(resp *Response, req *Request)

ServeAPI calls f with the given request and response.

type ImportKeyRequest

type ImportKeyRequest struct {
	Bytes  []byte `json:"key"`
	Cipher string `json:"cipher"`
}

ImportKeyRequest is the request sent by clients when calling the ImportKey API.

type ListAPIsResponse

type ListAPIsResponse []DescribeRouteResponse

ListAPIsResponse is the response sent to clients by the List APIs API.

type ListIdentitiesResponse

type ListIdentitiesResponse struct {
	Identities []string `json:"identities"`
	ContinueAt string   `json:"continue_at"`
}

ListIdentitiesResponse is the response sent to clients by the ListIdentities API.

type ListKeysResponse

type ListKeysResponse struct {
	Names      []string `json:"names"`
	ContinueAt string   `json:"continue_at,omitempty"`
}

ListKeysResponse is the response sent to clients by the ListKeys API.

type ListPoliciesResponse

type ListPoliciesResponse struct {
	Names      []string `json:"names"`
	ContinueAt string   `json:"continue_at"`
}

ListPoliciesResponse is the response sent to clients by the ListPolicies API.

type LogWriter

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

LogWriter wraps an io.Writer and encodes each write operation as ErrorLogEvent.

It's intended to be used as adapter to send API error logs to an http.ResponseWriter.

func NewLogWriter

func NewLogWriter(w io.Writer) *LogWriter

NewLogWriter returns a new LogWriter wrapping w.

func (*LogWriter) Write

func (w *LogWriter) Write(p []byte) (int, error)

Write encodes p as ErrorLogEvent and writes it to the underlying io.Writer.

type Multicast

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

Multicast is a one-to-many io.Writer. It is similar to io.MultiWriter but writers can be added and removed dynamically. A Multicast may be modified by multiple go routines concurrently.

Its zero value is an empty group of io.Writers and ready for use.

func (*Multicast) Add

func (m *Multicast) Add(w io.Writer)

Add adds w to m. Future writes to m will also reach w. If w is already part of m, Add does nothing.

func (*Multicast) Num

func (m *Multicast) Num() int

Num returns how many connections are part of this Multicast.

func (*Multicast) Remove

func (m *Multicast) Remove(w io.Writer)

Remove removes w from m. Future writes to m will no longer reach w.

func (*Multicast) Write

func (m *Multicast) Write(p []byte) (n int, err error)

Write writes p to all io.Writers that are currently part of m. It returns the first error encountered, if any, but writes to all io.Writers before returning.

type ReadPolicyResponse

type ReadPolicyResponse struct {
	Name      string              `json:"name"`
	Allow     map[string]struct{} `json:"allow,omitempty"`
	Deny      map[string]struct{} `json:"deny,omitempty"`
	CreatedAt time.Time           `json:"created_at"`
	CreatedBy string              `json:"created_by"`
}

ReadPolicyResponse is the response sent to clients by the ReadPolicy API.

type Request

type Request struct {
	*http.Request

	Identity kes.Identity

	Resource string

	Received time.Time
}

Request is an authenticated HTTP request.

func (*Request) LogValue

func (r *Request) LogValue() slog.Value

LogValue returns the requests logging representation.

type Response

type Response struct {
	http.ResponseWriter
}

Response is an API response.

func (*Response) Fail

func (r *Response) Fail(code int, msg string) error

Fail is a shorthand for api.Fail. It responds to the client with the given status code and error message.

func (*Response) Failf

func (r *Response) Failf(code int, format string, v ...any) error

Failf is a shorthand for api.Failf. Failf responds to the client with the given status code and formatted error message.

func (*Response) Failr

func (r *Response) Failr(err Error) error

Failr is a shorthand for api.Failr. Failr responds to the client with err.

func (*Response) Reply

func (r *Response) Reply(code int)

Reply is a shorthand for api.Reply. It sends just an HTTP status code to the client. The response body is empty.

type Route

type Route struct {
	Method  string        // The HTTP method (GET, PUT, DELETE, ...)
	Path    string        // The API Path
	MaxBody mem.Size      // The max. size of a request body
	Timeout time.Duration // Timeout after which the request gets aborted
	Auth    Authenticator // The authentication method for this API route
	Handler Handler       // The API handler implementing the server-side logic
}

Route represents an API route handling a client request.

func (Route) ServeHTTP

func (ro Route) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler for Route and handles an incoming client request as following:

  • Verify that the request method matches Route.Method.
  • Verify that the request got routed correctly, i.e. Route.Path is a prefix of the request path.
  • Limit the request body to Route.MaxBody.
  • Apply Route.Timeout and timeout the request if generating a response takes longer.
  • Authenticate the request. If Route.Auth.Authenticate returns an error the error is sent to the client and the route handler is not invoked.
  • Handle the request. The Route.Handler.ServeAPI is invoked with the authenticated request.

type SelfDescribeIdentityResponse

type SelfDescribeIdentityResponse struct {
	Identity  string    `json:"identity"`
	IsAdmin   bool      `json:"admin,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	CreatedBy string    `json:"created_by,omitempty"`

	Policy *ReadPolicyResponse `json:"policy,omitempty"`
}

SelfDescribeIdentityResponse is the response sent to clients by the SelfDescribeIdentity API.

type StatusResponse

type StatusResponse struct {
	Version    string `json:"version"`
	OS         string `json:"os"`
	Arch       string `json:"arch"`
	UpTime     uint64 `json:"uptime"` // in seconds
	CPUs       int    `json:"num_cpu"`
	UsableCPUs int    `json:"num_cpu_used"`
	HeapAlloc  uint64 `json:"mem_heap_used"`
	StackAlloc uint64 `json:"mem_stack_used"`

	KeyStoreLatency     int64 `json:"keystore_latency,omitempty"` // In microseconds
	KeyStoreUnreachable bool  `json:"keystore_unreachable,omitempty"`
}

StatusResponse is the response sent to clients by the Status API.

type VersionResponse

type VersionResponse struct {
	Version string `json:"version"`
	Commit  string `json:"commit"`
}

VersionResponse is the response sent to clients by the Version API.

Jump to

Keyboard shortcuts

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