host

package
v1.18.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package host is the plugin-side client of wick's Host API (wick.host.v1): the calls a plugin makes back into wick (users, sessions, tickets, connector instances, ...). One Host interface sits over two transports:

  • gRPC over the go-plugin GRPCBroker connection (connector/tool/job), see FromConn;
  • HTTP to /x/-/api/* with WICK_PLUGIN_TOKEN (every kind, service plugins included), see FromEnv.

Default picks whichever is available. Nothing here panics on a wick that predates the Host API: with no broker connection and no plugin token every constructor returns ErrHostAPIUnavailable. A service plugin on such a wick does hold a token, so the constructors succeed and each RPC then returns ErrHostAPIUnavailable; Whoami alone succeeds over HTTP with HostApiVersion 0 (the callback door's original whoami). Probe Whoami and treat version 0 as "no Host API" when that matters.

The package deliberately imports nothing from pkg/plugin so the SDK there can depend on it.

Index

Constants

View Source
const (
	// HeaderCallID carries the id on a proxied HTTP request and on HTTP door
	// calls.
	HeaderCallID = "X-Wick-Call-Id"
	// MetadataCallID carries the id as gRPC metadata (Execute, and broker
	// calls back into wick).
	MetadataCallID = "wick-call-id"
)

Call ids tie a Host API call to the wick request it serves. wick issues one per request it sends a plugin (a connector Execute, a proxied tool or service request) and remembers who that request runs for; the plugin echoes the id on its Host API calls and wick maps it back to the person. The id is only a lookup key: wick drops it when the request ends and ignores an id another plugin was given, so it cannot be used to borrow an identity.

View Source
const (
	DefaultCallTimeout = 30 * time.Second
	ExecuteCallTimeout = 3 * time.Minute // connector ops may be slow

)

Per-call deadlines applied when the caller's ctx has none, the same on both transports.

View Source
const (
	HeaderHostAPI      = "X-Wick-Host-Api"
	HeaderHostAPIError = "X-Wick-Host-Api-Error"
)

HTTP door wire format. Every response the Host API serves carries HeaderHostAPI (its version); a response without it came from a wick that does not serve the Host API. A failed call additionally carries HeaderHostAPIError (the gRPC code name) and an ErrorBody JSON body.

View Source
const (
	EnvHostAPIURL  = "WICK_HOST_API_URL"
	EnvBaseURL     = "WICK_BASE_URL"
	EnvPluginToken = "WICK_PLUGIN_TOKEN"
)

Env the host sets on a plugin process for the HTTP door. EnvBaseURL and EnvPluginToken match pkg/plugin.EnvBaseURL / EnvPluginToken (kept in sync by a test).

EnvHostAPIURL is the private (loopback) address of the Host API door. It wins over EnvBaseURL, which is wick's public URL; EnvBaseURL is only the fallback for a wick that sets no EnvHostAPIURL.

View Source
const APIVersion = 1

APIVersion is the Host API version this client speaks (wick.host.v1).

View Source
const CallbackPrefix = "/x/-"

CallbackPrefix is the /x/{key} mount of the callback API ("-" is never a plugin key); Route.Pattern is relative to it.

View Source
const RestPrefix = "/api/rest"

RestPrefix is where the Rest RPC lives on the HTTP door: the wick REST path follows it verbatim (ANY /x/-/api/rest/api/tickets/42).

Variables

View Source
var ErrHostAPIUnavailable = errors.New("wick host API unavailable")

ErrHostAPIUnavailable means this wick does not serve the Host API (it predates it, no broker connection was offered, or no plugin token is set) or does not serve the requested RPC yet.

View Source
var ErrPermissionDenied = errors.New("wick host API: permission denied")

ErrPermissionDenied matches every *PermissionDeniedError via errors.Is.

View Source
var Routes = []Route{

	{"Whoami", http.MethodGet, "/api/whoami"},
	{"ListMethods", http.MethodGet, "/api/methods"},

	{"ListUsers", http.MethodGet, "/api/users"},
	{"GetUser", http.MethodGet, "/api/users/{id}"},
	{"GetUserByEmail", http.MethodGet, "/api/users/by-email/{email}"},

	{"ConnectedAccounts", http.MethodGet, "/api/accounts"},

	{"ListSessions", http.MethodGet, "/api/sessions"},
	{"GetSessionMeta", http.MethodGet, "/api/sessions/{id}"},
	{"SendToSession", http.MethodPost, "/api/sessions/{session_id}/send"},

	{"GetTicket", http.MethodGet, "/api/tickets/{id}"},
	{"ListTickets", http.MethodGet, "/api/tickets"},
	{"CreateTicket", http.MethodPost, "/api/tickets"},
	{"UpdateTicket", http.MethodPatch, "/api/tickets/{id}"},
	{"AttachSession", http.MethodPost, "/api/tickets/{ticket_id}/sessions"},

	{"GetConfig", http.MethodGet, "/api/config"},

	{"ListConnectorInstances", http.MethodGet, "/api/connectors"},
	{"ExecuteConnector", http.MethodPost, "/api/connectors/execute"},

	{"Invoke", http.MethodPost, "/api/invoke"},
	{"Query", http.MethodPost, "/api/query"},
}

Routes is the HTTP door table, shared by this client and wick's server so both sides agree on paths. Rest is not listed: it is ANY RestPrefix + path, a raw passthrough (request and response bodies/headers as-is).

Whoami compatibility: GET /api/whoami already answers service plugins with {"plugin","scopes"}. The server MUST keep sending those two keys next to the WhoamiResponse fields in the same body (a superset), so old plugins keep working; this client reads either shape.

Functions

func CallIDFrom

func CallIDFrom(ctx context.Context) string

CallIDFrom returns the call id on ctx: the one set by WithCallID, else the one wick sent as incoming gRPC metadata (a connector Execute context).

func CallIDHandler

func CallIDHandler(next http.Handler) http.Handler

CallIDHandler puts the call id wick sent on a proxied request (HeaderCallID) on the request context, so Host API calls made with r.Context() run for the person behind the request. The plugin SDKs wrap their handlers with it.

func CodeForHTTPStatus

func CodeForHTTPStatus(s int) codes.Code

CodeForHTTPStatus is the inverse of HTTPStatus, used when a failed response carries no ErrorBody code.

func ConnGeneration

func ConnGeneration() uint64

ConnGeneration changes every time SetConn / SetConnFunc records a new connection, so a cached probe of the old one can be dropped.

func HTTPStatus

func HTTPStatus(c codes.Code) int

HTTPStatus maps a gRPC code to the HTTP status of the HTTP door, so both doors answer the same failure the same way.

func MarshalHTTP

func MarshalHTTP(m proto.Message) ([]byte, error)

MarshalHTTP encodes m as an HTTP door body.

func SetConn

func SetConn(c grpc.ClientConnInterface)

SetConn records the broker connection for Default. The plugin SDK calls it once the host announces a Host API broker id; plugins do not.

func SetConnFunc

func SetConnFunc(f func() (grpc.ClientConnInterface, error))

SetConnFunc records a broker connection that is still being dialled: Default waits for f (called once, its result kept) and falls back to the HTTP env when it fails. The plugin SDK sets it while it dials the broker; plugins do not.

func UnmarshalHTTP

func UnmarshalHTTP(b []byte, m proto.Message) error

UnmarshalHTTP decodes an HTTP door body into m (reset first).

func WithCallID

func WithCallID(ctx context.Context, id string) context.Context

WithCallID returns ctx carrying the call id of the wick request it serves. The plugin SDK sets it on every request context; plugins only need it when they start their own context (pass the request's id along).

func WriteHTTPError

func WriteHTTPError(w http.ResponseWriter, err error)

WriteHTTPError writes err as a Host API HTTP door failure: status from HTTPStatus, both headers, and an ErrorBody. A *PermissionDeniedError keeps its scope/item/plugin; ErrHostAPIUnavailable answers Unimplemented.

Types

type ErrorBody

type ErrorBody struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Scope   string `json:"scope,omitempty"`
	Item    string `json:"item,omitempty"`
	Plugin  string `json:"plugin,omitempty"`
}

ErrorBody is the JSON body of a failed HTTP door call. Code is the gRPC code name (codes.Code.String(), e.g. "PermissionDenied").

type Host

type Host interface {
	// meta (scope: whoami, always allowed)
	Whoami(ctx context.Context) (*hostpb.WhoamiResponse, error)
	ListMethods(ctx context.Context) (*hostpb.ListMethodsResponse, error)

	// users.read
	ListUsers(ctx context.Context, in *hostpb.ListUsersRequest) (*hostpb.ListUsersResponse, error)
	GetUser(ctx context.Context, in *hostpb.GetUserRequest) (*hostpb.User, error)
	GetUserByEmail(ctx context.Context, in *hostpb.GetUserByEmailRequest) (*hostpb.User, error)

	// accounts.read
	ConnectedAccounts(ctx context.Context, in *hostpb.ConnectedAccountsRequest) (*hostpb.ConnectedAccountsResponse, error)

	// sessions.read / sessions.notify
	ListSessions(ctx context.Context, in *hostpb.ListSessionsRequest) (*hostpb.ListSessionsResponse, error)
	GetSessionMeta(ctx context.Context, in *hostpb.GetSessionMetaRequest) (*hostpb.SessionMeta, error)
	SendToSession(ctx context.Context, in *hostpb.SendToSessionRequest) (*hostpb.SendToSessionResponse, error)

	// tickets.read / tickets.write
	GetTicket(ctx context.Context, in *hostpb.GetTicketRequest) (*hostpb.Ticket, error)
	ListTickets(ctx context.Context, in *hostpb.ListTicketsRequest) (*hostpb.ListTicketsResponse, error)
	CreateTicket(ctx context.Context, in *hostpb.CreateTicketRequest) (*hostpb.Ticket, error)
	UpdateTicket(ctx context.Context, in *hostpb.UpdateTicketRequest) (*hostpb.Ticket, error)
	AttachSession(ctx context.Context, in *hostpb.AttachSessionRequest) error

	// config.read_other
	GetConfig(ctx context.Context, in *hostpb.GetConfigRequest) (*hostpb.GetConfigResponse, error)

	// connectors.read / connectors.execute
	ListConnectorInstances(ctx context.Context, in *hostpb.ListConnectorInstancesRequest) (*hostpb.ListConnectorInstancesResponse, error)
	ExecuteConnector(ctx context.Context, in *hostpb.ExecuteConnectorRequest) (*hostpb.ExecuteConnectorResponse, error)

	// generic layer
	Invoke(ctx context.Context, in *hostpb.InvokeRequest) (*hostpb.InvokeResponse, error)
	Rest(ctx context.Context, in *hostpb.RestRequest) (*hostpb.RestResponse, error)
	Query(ctx context.Context, in *hostpb.QueryRequest) (*hostpb.QueryResponse, error)
}

Host is wick's Host API as seen from a plugin. Every method takes the request message of its RPC (nil = empty request) so adding a field to the proto never changes a signature.

func Default

func Default() (Host, error)

Default picks a transport by itself: the broker connection when the SDK registered one, otherwise the HTTP env. Neither available (an older wick, or a process not started by wick) yields ErrHostAPIUnavailable.

func FromConn

func FromConn(conn grpc.ClientConnInterface) (Host, error)

FromConn returns a Host speaking gRPC over conn, the connection the GRPCBroker hands the plugin. A nil conn (no broker id in the handshake, i.e. an older wick) yields ErrHostAPIUnavailable.

func FromEnv

func FromEnv() (Host, error)

FromEnv returns a Host speaking HTTP to WICK_HOST_API_URL (else WICK_BASE_URL) with WICK_PLUGIN_TOKEN. No URL or no token yields ErrHostAPIUnavailable.

func FromHTTP

func FromHTTP(baseURL, token string, hc *http.Client) (Host, error)

FromHTTP is FromEnv with explicit values. hc nil uses a client that never follows redirects (a 3xx from Rest reaches the caller as its status); the per-call deadline comes from the context (see DefaultCallTimeout).

type PermissionDeniedError

type PermissionDeniedError struct {
	Scope   string
	Item    string
	Plugin  string
	Message string
}

PermissionDeniedError is a call the plugin is not allowed to make: its scope is not granted, or Item (a table, a REST path, a connector op) is blocked or not declared.

func (*PermissionDeniedError) Error

func (e *PermissionDeniedError) Error() string

func (*PermissionDeniedError) GRPCStatus

func (e *PermissionDeniedError) GRPCStatus() *status.Status

GRPCStatus lets status.Code / status.FromError see PermissionDenied, and is what a server returns to put {scope, item, plugin} on the wire.

func (*PermissionDeniedError) Is

func (e *PermissionDeniedError) Is(target error) bool

Is makes errors.Is(err, ErrPermissionDenied) true.

type Route

type Route struct {
	RPC     string
	Method  string
	Pattern string
}

Route maps one Host RPC onto the HTTP door. {name} segments are filled from the request field of that proto name. GET requests send their remaining populated fields as query parameters (proto names); POST/PATCH send the request as an HTTP door body (MarshalHTTP: plain JSON, *_json fields inline). Success bodies are the response in the same codec.

Jump to

Keyboard shortcuts

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