api

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 56 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// RoleUser is an ordinary account: it reaches its own runs and machines.
	RoleUser = "user"
	// RoleOperator additionally reaches the dispatcher-wide administration
	// operations listed in docs/api.md. No HTTP route grants this role; it is
	// held by the account the local development mode bootstraps.
	RoleOperator = "operator"
)

Account roles. A role is a property of the account, never of the request.

View Source
const (
	// CodeInvalidRequest is a malformed or incomplete request.
	CodeInvalidRequest = "invalid_request"
	// CodeInvalidPolicy is a request whose debuglet policy cannot be priced,
	// scheduled or served: a timeout outside 1..maxTimeoutMS milliseconds, a
	// negative floor, a ceiling below the floor, a repeated order_id, an order
	// or a batch whose price overflows, or a policy the chosen executor cannot
	// serve (ICMP required, a listener without a public host).
	CodeInvalidPolicy = "invalid_policy"
	// CodeUnknownExecutor names an executor that is not registered, or no
	// longer available when the batch is admitted.
	CodeUnknownExecutor = "unknown_executor"
	// CodeIntentMismatch is a submission whose debuglets differ from the ones
	// the payment intent was created for.
	CodeIntentMismatch = "intent_mismatch"
	// CodePaymentIncomplete is a submission for a transaction that is not paid.
	CodePaymentIncomplete = "payment_incomplete"
	// CodeUnsupportedPaymentMethod is a payment method this API does not admit.
	CodeUnsupportedPaymentMethod = "unsupported_payment_method"
	// CodePaymentsDisabled is a chain payment method while blockchain payments
	// are disabled.
	CodePaymentsDisabled = "payments_disabled"
	// CodeUnsupportedAPIVersion is a required contract version this dispatcher
	// does not serve.
	CodeUnsupportedAPIVersion = "unsupported_api_version"
	// CodeUnauthorized is a missing, malformed, unknown, expired or revoked
	// credential, or an auth key that does not match the transaction. It says
	// that the request was not authenticated, never which of those it was.
	CodeUnauthorized = "unauthorized"
	// CodeForbidden is an authenticated request whose account may not perform
	// the operation: an operator operation asked for by an ordinary account, or
	// a cookie-authenticated state change without its CSRF token. Access to
	// another account's object is not reported with this code; it answers
	// not_found, so the response is no existence oracle.
	CodeForbidden = "forbidden"
	// CodeNotFound is a debuglet, user or executor that does not exist.
	CodeNotFound = "not_found"
	// CodeIdentityConflict refuses a sign-in change that would split ownership or remove the last usable method.
	CodeIdentityConflict = "identity_conflict"
	// CodeCapacityExhausted is a batch the scheduler cannot admit within the
	// executor's remaining capacity, or a destination limit below the floors
	// already admitted on that destination.
	CodeCapacityExhausted = "capacity_exhausted"
	// CodeCancelRefused is a cancellation the dispatcher did not accept.
	CodeCancelRefused = "cancel_refused"
	// CodeMethodNotAllowed is a method the route does not serve.
	CodeMethodNotAllowed = "method_not_allowed"
	// CodeUnsupportedMediaType is a body representation the route does not read.
	CodeUnsupportedMediaType = "unsupported_media_type"
	// CodePayloadTooLarge is a body beyond the accepted size.
	CodePayloadTooLarge = "payload_too_large"
	// CodeInternal is a failure inside the dispatcher. Its details are logged,
	// never returned.
	CodeInternal = "internal_error"
	// CodeUnavailable is a temporarily unavailable capability.
	CodeUnavailable = "service_unavailable"
	// CodeRateLimited is a client address that sent more requests to a
	// rate-limited route than it admits; retry after the Retry-After delay.
	CodeRateLimited = "rate_limited"
)

Documented failure codes. New codes may appear within a contract major version, so a client must treat an unknown code as a plain failure of the status it arrived with.

View Source
const (
	CodePayloadDeleted      = "payload_deleted"
	CodePayloadNotDeletable = "payload_not_deletable"
)
View Source
const (
	// CodeAllowanceExceeded is a TEST intent whose price the account's
	// remaining usage allowance does not cover.
	CodeAllowanceExceeded = "allowance_exceeded"
	// CodeConflict is a request whose idempotency key already names a
	// different request.
	CodeConflict = "conflict"
	// CodeAllowanceOutOfRange is an account whose allowance history cannot be
	// represented: a total of its grants or orders, or what remains, overflows
	// a signed 64-bit integer.
	CodeAllowanceOutOfRange = "allowance_out_of_range"
)
View Source
const CodeAccountQuota = "account_quota_exceeded"
View Source
const PricingRule = "bw-s-ceil-ms-v1"

PricingRule names the rule priceOrder implements. A response that carries a price names it, so a client can tell when the rule changed between a quote and an intent; a different rule is a new name.

View Source
const (
	// SessionLifetime is how long an issued session stays valid. It is not
	// extended by use: a client logs in again, which issues a new session.
	SessionLifetime = 12 * time.Hour
)
View Source
const VersionHeader = apispec.VersionHeader

VersionHeader carries the contract version a client requires on requests and the version this dispatcher implements on responses. It is re-exported so that a server assembling middleware can name it without importing the contract package.

Variables

This section is empty.

Functions

func APIToSpec

func APIToSpec(r DebugletRequest) (models.DebugletSpec, error)

func APIVersionMiddleware

func APIVersionMiddleware() echo.MiddlewareFunc

APIVersionMiddleware announces the implemented contract version on every response and answers a client that requires an incompatible one with an explicit error instead of a best-effort response. A request without the header is served unchanged, which keeps every client written before the contract was versioned working.

func AuthMiddleware

func AuthMiddleware(db *sql.DB, localDevelopment bool, audience ...string) echo.MiddlewareFunc

AuthMiddleware verifies the credential a request presents and records the caller it establishes. Unlike the identity cookie it replaces, it never accepts a user identifier as a credential and never lets a rejected credential continue as an anonymous request on a protected route.

localDevelopment admits a request that presents no credential at all as the local operator, which is the documented development bypass. It is off unless the deployment explicitly asked for it.

func NewRecoveryCredential added in v0.3.0

func NewRecoveryCredential() (token, selector string, digest []byte, err error)

NewRecoveryCredential creates the same recovery-code format used by account registration. Host administration stores its digest with a bounded lifetime.

func RequestLog added in v0.3.0

func RequestLog(logger *zap.Logger) echo.MiddlewareFunc

RequestLog logs the matched route, never a raw URL, query, credential or body. Caller-supplied request IDs are not trusted as correlation identifiers.

Types

type AccountResponse

type AccountResponse struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	Role         string `json:"role"`
	AccountKey   string `json:"account_key"`
	RecoveryCode string `json:"recovery_code"`
}

AccountResponse is an account together with the credentials just issued for it. The two credentials are returned exactly once, by the operation that minted them; the dispatcher keeps only their digests and cannot show them again.

type AttributionCandidatesResponse added in v0.3.0

type AttributionCandidatesResponse = wire.AttributionCandidates

type AttributionKeysResponse added in v0.3.0

type AttributionKeysResponse = wire.AttributionKeys

type AttributionReceiptKeys added in v0.3.0

type AttributionReceiptKeys = wire.AttributionReceiptKeys

type AttributionVerifyRequest added in v0.3.0

type AttributionVerifyRequest = wire.AttributionVerifyRequest

type AttributionVerifyResponse added in v0.3.0

type AttributionVerifyResponse = wire.AttributionVerifyResponse

type BalanceResponse

type BalanceResponse struct {
	Balance int64 `json:"balance"`
}

type CILogonConfig added in v0.3.0

type CILogonConfig struct {
	Enabled                                                 bool
	Issuer, ClientID, ClientSecret, CallbackURL, SuccessURL string
}

type CreateUserRequest

type CreateUserRequest struct {
	Name string `json:"name"`
}

type CredentialInfo added in v0.3.0

type CredentialInfo struct {
	ID        string   `json:"id"`
	Kind      string   `json:"kind"`
	Audience  string   `json:"audience"`
	Scopes    []string `json:"scopes"`
	Label     string   `json:"label"`
	CreatedAt int64    `json:"created_at"`
	ExpiresAt int64    `json:"expires_at"`
	Current   bool     `json:"current"`
}

type CredentialRequest added in v0.3.0

type CredentialRequest struct {
	Audience string   `json:"audience"`
	Scopes   []string `json:"scopes"`
	Label    string   `json:"label"`
}

CredentialRequest grants only the selected existing account operations.

type DebugletDeleteRequest

type DebugletDeleteRequest struct {
	DebugletID uuid.UUID `json:"debuglet_id"`
	ExecutorID string    `json:"executor_id"`
}

type DebugletLogEntry

type DebugletLogEntry = wire.LogEntry[string]

type DebugletLogsResponse

type DebugletLogsResponse wire.LogPage[string]

func (DebugletLogsResponse) MarshalJSON added in v0.3.0

func (p DebugletLogsResponse) MarshalJSON() ([]byte, error)

MarshalJSON preserves the response's optional workload error.

type DebugletPolicyRequest

type DebugletPolicyRequest = wire.Policy

type DebugletRequest

type DebugletRequest = wire.Request[string]

type DebugletResponse

type DebugletResponse struct {
	ID         uuid.UUID `json:"id"`
	StartTime  int64     `json:"start_time"`
	EndTime    int64     `json:"end_time"`
	Usage      int64     `json:"usage"`
	ExecutorID string    `json:"executor_id"`
	Addresses  []string  `json:"addresses"`
	State      string    `json:"state"`
}

type DebugletStateResponse

type DebugletStateResponse = wire.State

type DestinationLimitRequest

type DestinationLimitRequest struct {
	Destination string `json:"destination"`
	Limit       int64  `json:"limit"`
	Denied      bool   `json:"denied,omitempty"`
	// Reason is required to deny a destination or to lower its limit.
	Reason string `json:"reason,omitempty"`
	// ExpiresAt, in RFC 3339, is when the default returns; empty never.
	ExpiresAt string `json:"expires_at,omitempty"`
}

DestinationLimitRequest is the complete policy an operator sets for a destination: its limit, or a deny, which admits nothing and records no limit.

type DestinationPoliciesResponse added in v0.3.0

type DestinationPoliciesResponse struct {
	Destinations []DestinationPolicyResponse `json:"destinations"`
}

type DestinationPolicyResponse added in v0.3.0

type DestinationPolicyResponse struct {
	Destination string `json:"destination"`
	// Kind is limit, deny, or allow for a return to the default.
	Kind   string `json:"kind"`
	Denied bool   `json:"denied"`
	// Limit is null when the destination has the default capacity.
	Limit     *int64     `json:"limit"`
	Reason    string     `json:"reason"`
	Actor     string     `json:"actor"`
	SetAt     time.Time  `json:"set_at"`
	ExpiresAt *time.Time `json:"expires_at"`
	Revision  int64      `json:"revision"`
	// Delivery is confirmed when every executor holding an allocation on
	// the destination acknowledged the policy, and unconfirmed otherwise.
	Delivery    string `json:"delivery"`
	Recipients  int    `json:"recipients"`
	Unconfirmed int    `json:"unconfirmed"`
}

DestinationPolicyResponse is the current recorded policy of a destination.

type DeviceApprovalRequest added in v0.3.0

type DeviceApprovalRequest struct {
	UserCode string `json:"user_code"`
	Audience string `json:"audience"`
	Confirm  bool   `json:"confirm"`
}

type DeviceLoginInfo added in v0.3.0

type DeviceLoginInfo struct {
	UserCode  string   `json:"user_code"`
	Audience  string   `json:"audience"`
	Scopes    []string `json:"scopes"`
	Label     string   `json:"label"`
	ExpiresAt int64    `json:"expires_at"`
	State     string   `json:"state"`
}

type DeviceLoginPoll added in v0.3.0

type DeviceLoginPoll struct {
	State      string            `json:"state"`
	Interval   int64             `json:"interval,omitempty"`
	Credential *IssuedCredential `json:"credential,omitempty"`
}

type DeviceLoginRequest added in v0.3.0

type DeviceLoginRequest struct {
	DeviceCode string `json:"device_code"`
	Audience   string `json:"audience"`
}

type DeviceLoginStart added in v0.3.0

type DeviceLoginStart struct {
	DeviceCode      string   `json:"device_code"`
	UserCode        string   `json:"user_code"`
	VerificationURI string   `json:"verification_uri"`
	Audience        string   `json:"audience"`
	Scopes          []string `json:"scopes"`
	ExpiresAt       int64    `json:"expires_at"`
	Interval        int64    `json:"interval"`
}

type DummyIntent

type DummyIntent struct {
	TransactionID string `json:"transaction_id"`
	AuthKey       string `json:"auth_key"`
}

type ErrorResponse

type ErrorResponse struct {
	Code        string            `json:"code"`
	Message     string            `json:"message"`
	FieldErrors []wire.FieldError `json:"field_errors,omitempty"`
	// AdmittedIDs appears only when submission failed after durable admission.
	// IDs are in request order; inspect their state instead of replaying work.
	AdmittedIDs []string `json:"admitted_ids,omitempty"`
}

ErrorResponse is the documented error envelope of the HTTP API. Every failure answers with this object: Code is a stable identifier a client branches on, Message is a bounded human-readable diagnostic it must not parse. Internal diagnostics are never part of it; they stay in the dispatcher's log. api/openapi.yaml lists the codes.

type ExecutorByIPResponse

type ExecutorByIPResponse struct {
	ExecutorID  string      `json:"executor_id"`
	DebugletIDs []uuid.UUID `json:"debuglet_ids"` // newest first, up to ?n= (default 10)
}

ExecutorByIPResponse is returned by GET /executors/by-ip?ip=<ip>. It identifies which executor corresponds to a given source IP and lists the most recent debuglet IDs that were dispatched to it.

type ExecutorCounts

type ExecutorCounts struct {
	// Eligible counts executors whose control session lease is valid now.
	Eligible int `json:"eligible"`
	// Registered counts the entries of the executor registry.
	Registered int `json:"registered"`
}

ExecutorCounts reports the executor registry and its eligible subset.

type ExecutorResponse

type ExecutorResponse = wire.Executor

type ExecutorSetupResponse added in v0.3.0

type ExecutorSetupResponse struct {
	Executor      OwnedExecutorResponse `json:"executor"`
	Token         string                `json:"token"`
	ExpiresAt     int64                 `json:"expires_at"`
	DispatcherURL string                `json:"dispatcher_url"`
}

type ExecutorTeslaResponse

type ExecutorTeslaResponse struct {
	ExecutorID        string `json:"executor_id"`
	AnchorKey         string `json:"anchor_key"`          // base64-encoded k_0
	AnchorTimestampNs int64  `json:"anchor_timestamp_ns"` // Unix nanoseconds of epoch 0
	DelaySec          int64  `json:"delay_sec"`           // deprecated name of epoch_seconds
	EpochSeconds      int64  `json:"epoch_seconds"`       // epoch length I in seconds
	// DisclosureDelayEpochs is d; 0 for an executor that predates it, which
	// disclosed after one epoch and whose tags a verifier must not accept.
	DisclosureDelayEpochs  int64  `json:"disclosure_delay_epochs"`
	DisclosureDelaySeconds int64  `json:"disclosure_delay_seconds"` // d * epoch_seconds
	DisclosedEpoch         int64  `json:"disclosed_epoch"`          // index of latest disclosed key
	DisclosedKey           string `json:"disclosed_key"`            // base64-encoded k_τ, empty if none yet
	// NextDisclosureEpoch is disclosed_epoch+1, and NextDisclosureAtNs the
	// earliest Unix nanoseconds its key may be disclosed.
	NextDisclosureEpoch int64 `json:"next_disclosure_epoch"`
	NextDisclosureAtNs  int64 `json:"next_disclosure_at_ns"`
}

ExecutorTeslaResponse is returned by GET /executors/:id/tesla. It provides all parameters needed by an external verifier to reconstruct chain keys and validate packet authentication tags.

The key of epoch t is disclosed no earlier than anchor_timestamp_ns + (t + disclosure_delay_epochs) * epoch_seconds. A verifier accepts a packet captured at time c with the key of its epoch t or t-1 only while that key was still secret at c.

type GitHubOAuthConfig

type GitHubOAuthConfig struct {
	Enabled                 bool
	ClientID, ClientSecret  string
	CallbackURL, SuccessURL string
}

type Handler

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

func NewHandler

func NewHandler(d *dispatcher.Dispatcher, db *sql.DB, l *zap.Logger, options ...Option) *Handler

func (*Handler) ApproveDeviceLogin added in v0.3.0

func (h *Handler) ApproveDeviceLogin(c echo.Context) error

func (*Handler) CancelDeviceLogin added in v0.3.0

func (h *Handler) CancelDeviceLogin(c echo.Context) error
func (h *Handler) ConfirmIdentityLink(c echo.Context) error

func (*Handler) CreateCredential added in v0.3.0

func (h *Handler) CreateCredential(c echo.Context) error

func (*Handler) CreateMeasurementProfile added in v0.3.0

func (h *Handler) CreateMeasurementProfile(c echo.Context) error

func (*Handler) CreateUser

func (h *Handler) CreateUser(c echo.Context) error

PUT /user CreateUser registers an account and issues its first credentials. The account key and the recovery code are returned exactly once; only their digests are stored. The role of a self-registered account is always the ordinary one.

func (*Handler) DeleteDebuglet

func (h *Handler) DeleteDebuglet(c echo.Context) error

DELETE /debuglet

func (*Handler) DeleteDebugletPayload added in v0.3.0

func (h *Handler) DeleteDebugletPayload(c echo.Context) error

DeleteDebugletPayload is deliberately distinct from DELETE /debuglet, which requests cancellation. Operator read privileges do not grant deletion of another account's payload. The explicit local profile owns ownerless runs.

func (*Handler) DeleteIdentity added in v0.3.0

func (h *Handler) DeleteIdentity(c echo.Context) error

func (*Handler) DeleteMeasurementProfile added in v0.3.0

func (h *Handler) DeleteMeasurementProfile(c echo.Context) error

func (*Handler) DenyDeviceLogin added in v0.3.0

func (h *Handler) DenyDeviceLogin(c echo.Context) error

func (*Handler) GetAttributionCandidates added in v0.3.0

func (h *Handler) GetAttributionCandidates(c echo.Context) error

GET /attribution/candidates?ip=<ip>&at=<RFC 3339 time>

The runs that were active from ip within one epoch of at, each with its executor's chain schedule and the latest disclosed epoch of that chain.

func (*Handler) GetAttributionKeys added in v0.3.0

func (h *Handler) GetAttributionKeys(c echo.Context) error

GET /attribution/keys?executor_id=<id>&chain_id=<chain>[&from_epoch=<n>][&to_epoch=<n>]

One page of the disclosed keys of a chain, from from_epoch (default 1) towards to_epoch (default unbounded), spanning at most maxAttributionKeyPage epochs.

func (*Handler) GetAttributionReceiptKeys added in v0.3.0

func (h *Handler) GetAttributionReceiptKeys(c echo.Context) error

GET /attribution/receipt-keys

Every key that verifies this dispatcher's receipts, with its validity.

func (*Handler) GetAuthProviders added in v0.3.0

func (h *Handler) GetAuthProviders(c echo.Context) error

func (*Handler) GetCILogonCallback added in v0.3.0

func (h *Handler) GetCILogonCallback(c echo.Context) error

func (*Handler) GetCILogonLogin added in v0.3.0

func (h *Handler) GetCILogonLogin(c echo.Context) error

func (*Handler) GetCredentialStatus added in v0.3.0

func (h *Handler) GetCredentialStatus(c echo.Context) error

func (*Handler) GetDebugletCancellation added in v0.3.0

func (h *Handler) GetDebugletCancellation(c echo.Context) error

GetDebugletCancellation inspects an existing request without sending an Abort.

func (*Handler) GetDebugletLogs

func (h *Handler) GetDebugletLogs(c echo.Context) error

GET /debuglet/:id/logs

func (*Handler) GetDebugletRecovery added in v0.3.0

func (h *Handler) GetDebugletRecovery(c echo.Context) error

GetDebugletRecovery returns an observation without changing the stored run.

func (*Handler) GetDebugletResult added in v0.3.0

func (h *Handler) GetDebugletResult(c echo.Context) error

GetDebugletResult exports the retained record without contacting an executor or substituting current node observations for admission facts.

func (*Handler) GetDebugletState

func (h *Handler) GetDebugletState(c echo.Context) error

GET /debuglet/:id/state

func (*Handler) GetDestinationPolicies added in v0.3.0

func (h *Handler) GetDestinationPolicies(c echo.Context) error

GET /destinations

GetDestinationPolicies lists the current recorded policy of every destination that has one, with who set it, why, and whether every executor holding an allocation there acknowledged it.

func (*Handler) GetExecutorByIP

func (h *Handler) GetExecutorByIP(c echo.Context) error

GET /executors/by-ip?ip=<ip>[&n=<count>]

Returns the executor ID of the executor whose source IP matches the query parameter, and the recent runs of the requesting account that were dispatched to it. Which executor serves an address is attribution data a measurement peer may need; which runs it carried is private, so the returned identifiers are the caller's own, never the run identifiers of another account. n defaults to 10 and can be raised by the caller up to maxRecentDebugletIDs, though the executor's ring retains at most 20 recent identifiers, so that is the real bound on the answer.

func (*Handler) GetExecutorEarnings added in v0.3.0

func (h *Handler) GetExecutorEarnings(c echo.Context) error

GET /operator/executors/:id/earnings

GetExecutorEarnings reports what an executor the caller owns has earned and the outbound chain transfers that name it. It reads records only; no payout is started here. Another account's executor answers like a missing one.

func (*Handler) GetExecutorTesla

func (h *Handler) GetExecutorTesla(c echo.Context) error

GET /executors/:id/tesla

Returns the TESLA key schedule parameters for the given executor, including the public anchor key k_0 and the latest disclosed key k_τ. External verifiers use these to reconstruct chain keys and validate packet tags.

func (*Handler) GetExecutors

func (h *Handler) GetExecutors(c echo.Context) error

GET /executors[?status=connected,disconnected,abandoned,never_connected]

func (*Handler) GetGitHubCallback

func (h *Handler) GetGitHubCallback(c echo.Context) error

func (*Handler) GetGitHubLogin

func (h *Handler) GetGitHubLogin(c echo.Context) error

func (*Handler) GetHealth

func (h *Handler) GetHealth(c echo.Context) error

GetHealth answers GET /health. It always answers 200: the report is the answer, and a probe that could not read it would learn nothing.

func (*Handler) GetIdentities added in v0.3.0

func (h *Handler) GetIdentities(c echo.Context) error

func (*Handler) GetLiveness

func (h *Handler) GetLiveness(c echo.Context) error

GetLiveness answers GET /healthz. Reaching it is the whole check.

func (*Handler) GetMe

func (h *Handler) GetMe(c echo.Context) error

GET /me GetMe returns the authenticated account. It requires a credential even in local development, because the local development bypass names no account.

func (*Handler) GetMeasurement added in v0.3.0

func (h *Handler) GetMeasurement(c echo.Context) error

func (*Handler) GetMeasurementProfile added in v0.3.0

func (h *Handler) GetMeasurementProfile(c echo.Context) error

func (*Handler) GetMeasurementTemplates added in v0.3.0

func (h *Handler) GetMeasurementTemplates(c echo.Context) error

GetMeasurementTemplates publishes immutable versioned starter definitions. The program is shipped by the pinned companion dashboard, not fetched from an arbitrary URL. Its digest is checked again on profile creation.

func (*Handler) GetMetrics added in v0.3.0

func (h *Handler) GetMetrics(c echo.Context) error

GetMetrics exports aggregate observations only to an established operator. The one-second memo bounds the cost of repeated scrapes. Its lock owns only this report: collection takes no runtime ownership guard across storage I/O.

func (*Handler) GetMyAllowance added in v0.3.0

func (h *Handler) GetMyAllowance(c echo.Context) error

GET /me/allowance

GetMyAllowance reports the caller's usage allowance. The route exists only while allowances are enabled.

func (*Handler) GetMyOrders added in v0.3.0

func (h *Handler) GetMyOrders(c echo.Context) error

GET /me/orders?limit=&before=

GetMyOrders pages the caller's own payment intents with their orders, newest expiry first. There is no creation time on an intent; its expiry is creation plus a fixed period, so the order is the order of creation. before is the next cursor of the previous page.

func (*Handler) GetOpenAPI

func (h *Handler) GetOpenAPI(c echo.Context) error

GetOpenAPI answers GET /openapi.yaml with the contract this build implements.

func (*Handler) GetOwnedExecutors added in v0.3.0

func (h *Handler) GetOwnedExecutors(c echo.Context) error

func (*Handler) GetPaymentStatus

func (h *Handler) GetPaymentStatus(c echo.Context) error

GET /payment/:transaction_id/status

GetPaymentStatus reports whether one payment order is paid. The order is private to the account that created it: another account's order and an unknown one answer alike.

func (*Handler) GetReadiness

func (h *Handler) GetReadiness(c echo.Context) error

GetReadiness answers GET /readyz: 200 while this dispatcher would admit new work, 503 naming the failed checks otherwise.

func (*Handler) GetRunDetail added in v0.3.0

func (h *Handler) GetRunDetail(c echo.Context) error

GetRunDetail reads configuration without loading output. Result exports and paginated logs remain separate, so a large output never hides configuration.

func (*Handler) GetVersion

func (h *Handler) GetVersion(c echo.Context) error

VersionResponse identities. GetVersion answers GET /version.

func (*Handler) InspectDeviceLogin added in v0.3.0

func (h *Handler) InspectDeviceLogin(c echo.Context) error

func (*Handler) ListCredentials added in v0.3.0

func (h *Handler) ListCredentials(c echo.Context) error

func (*Handler) ListMeasurementProfiles added in v0.3.0

func (h *Handler) ListMeasurementProfiles(c echo.Context) error

func (*Handler) ListMeasurements added in v0.3.0

func (h *Handler) ListMeasurements(c echo.Context) error

func (*Handler) ListUserDebuglets

func (h *Handler) ListUserDebuglets(c echo.Context) error

GET /list-debuglets

func (*Handler) ListUserIDs

func (h *Handler) ListUserIDs(c echo.Context) error

GET /user-ids ListUserIDs enumerates the accounts of this dispatcher. Enumeration is an operator operation: an ordinary account has no reason to learn which other accounts exist, and an identifier it learned was once enough to impersonate one.

func (*Handler) LockPrice

func (h *Handler) LockPrice(request PaymentIntentRequest, transactionId string, refundAddress string, ctx context.Context) (int64, error)

LockPrice prices an intent and creates its Outstanding debuglet_order rows, returning the total price. The rows reference the intent's transaction, so that transaction must already exist; PutPaymentIntent therefore prices, creates the transaction and only then stores the orders. Every failure it reports is already a documented API error, so a caller can return it unchanged.

func (*Handler) PatchDestinationLimit

func (h *Handler) PatchDestinationLimit(c echo.Context) error

PATCH /destination

PatchDestinationLimit changes a dispatcher-wide destination policy, which affects every account's admission decisions. It is therefore an operator operation rather than something a submitter may do to its own runs.

func (*Handler) PatchOwnedExecutor added in v0.3.0

func (h *Handler) PatchOwnedExecutor(c echo.Context) error

PatchOwnedExecutor changes only the caller's public presentation labels. Ownership is checked in the UPDATE, and omitted fields are preserved there.

func (*Handler) PollDeviceLogin added in v0.3.0

func (h *Handler) PollDeviceLogin(c echo.Context) error

func (*Handler) PostAccountAllowance added in v0.3.0

func (h *Handler) PostAccountAllowance(c echo.Context) error

POST /operator/accounts/:id/allowance

PostAccountAllowance records a grant to an account, issued by the calling operator account. A grant is never changed or removed, and a repeated request with the same idempotency key issues it once.

func (*Handler) PostAttributionVerify added in v0.3.0

func (h *Handler) PostAttributionVerify(c echo.Context) error

POST /attribution/verify

Verdicts for up to 256 packets in at most 16 groups, with a signed receipt.

func (*Handler) PostExecutorEnrollment added in v0.3.0

func (h *Handler) PostExecutorEnrollment(c echo.Context) error

PostExecutorEnrollment exchanges a one-use machine token for a certificate. The token authenticates this operation; an account session grants no right to issue a certificate. The private key remains on the joining machine.

func (h *Handler) PostIdentityLink(c echo.Context) error

func (*Handler) PostLogin

func (h *Handler) PostLogin(c echo.Context) error

POST /auth/login

PostLogin verifies an account key and issues a session for the account it names. It is the only route that turns a long-lived credential into one, and it never accepts a user identifier, a run identifier or a payment auth key.

func (*Handler) PostLogout

func (h *Handler) PostLogout(c echo.Context) error

POST /auth/logout

PostLogout revokes the session the request authenticated with and clears the browser cookies. The revoked token is refused from then on, before its expiry.

func (*Handler) PostOwnedExecutor added in v0.3.0

func (h *Handler) PostOwnedExecutor(c echo.Context) error

func (*Handler) PostOwnedExecutorToken added in v0.3.0

func (h *Handler) PostOwnedExecutorToken(c echo.Context) error

func (*Handler) PostPaymentQuote added in v0.3.0

func (h *Handler) PostPaymentQuote(c echo.Context) error

POST /payment/quote

PostPaymentQuote prices a batch as PUT /payment/intent would, and stops there: it writes nothing, creates no transaction and issues no auth key. A batch the intent would refuse is still quoted, with the refusals in its errors; only a request the intent could not even read keeps the intent's status. The intent prices again when it is created.

func (*Handler) PostRecover

func (h *Handler) PostRecover(c echo.Context) error

POST /auth/recover

PostRecover consumes a recovery code and returns a new account key and a new recovery code for the one account that code belongs to. Every session of that account is revoked first, so a recovered account is not still reachable with a credential the previous holder kept. A recovery code names its own account and nothing else: it can never be redirected at another one.

func (*Handler) PutDebuglets

func (h *Handler) PutDebuglets(c echo.Context) error

PUT /debuglet

func (*Handler) PutPaymentIntent

func (h *Handler) PutPaymentIntent(c echo.Context) error

PUT /payment/intent

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(e *echo.Echo)

func (*Handler) RevokeAllCredentials added in v0.3.0

func (h *Handler) RevokeAllCredentials(c echo.Context) error

func (*Handler) RevokeCredential added in v0.3.0

func (h *Handler) RevokeCredential(c echo.Context) error

func (*Handler) StartDeviceLogin added in v0.3.0

func (h *Handler) StartDeviceLogin(c echo.Context) error

func (*Handler) UpdateMeasurementProfile added in v0.3.0

func (h *Handler) UpdateMeasurementProfile(c echo.Context) error

func (*Handler) VersionIdentities

func (h *Handler) VersionIdentities() VersionResponse

VersionIdentities reports the three independent identities of a running dispatcher: the HTTP API contract it serves, the binary it was built from and the executor control protocol it speaks. They are versioned separately and only the API contract is a promise to HTTP clients.

type HealthResponse

type HealthResponse struct {
	Live      bool           `json:"live"`
	Ready     bool           `json:"ready"`
	Reasons   []string       `json:"reasons"`
	Storage   string         `json:"storage"`
	Control   string         `json:"control"`
	Executors ExecutorCounts `json:"executors"`
}

HealthResponse is the aggregate report. It is a fixed set of small fields: no operator note, no identifier, no path, because the route is public.

type IntentResponse

type IntentResponse struct {
	Retry  *wire.RetryReceipt `json:"retry,omitempty"`
	Method string             `json:"method"`
	Intent any                `json:"intent"`
	// Quote states the prices the intent stored. It is absent when a retry
	// recovers an intent created earlier.
	Quote *wire.Quote `json:"quote,omitempty"`
}

type IssuedCredential added in v0.3.0

type IssuedCredential struct {
	Token        string   `json:"token"`
	CredentialID string   `json:"credential_id"`
	Audience     string   `json:"audience"`
	Scopes       []string `json:"scopes"`
	ExpiresAt    int64    `json:"expires_at"`
	ID           string   `json:"id"`
	Name         string   `json:"name"`
	Role         string   `json:"role"`
}

IssuedCredential contains the secret once, at creation. Subsequent listings expose metadata only.

type LoginRequest

type LoginRequest struct {
	AccountKey string `json:"account_key"`
}

LoginRequest exchanges an account key for a session. An empty account key is the local development bootstrap and is refused by every other deployment.

type Option

type Option func(*Handler)

Option configures a Handler. Every option is explicit: the zero configuration is the profile a deployment gets, and nothing about it is inferred from the request.

func AttributionTrustedProxies added in v0.3.0

func AttributionTrustedProxies(prefixes []netip.Prefix) Option

AttributionTrustedProxies names the reverse proxies whose X-Forwarded-For header the attribution rate limit trusts (attribution.trusted_proxies). With none, the limit counts the TCP peer of every request.

func Authentication added in v0.3.0

func Authentication(publicURL, verificationURL string) Option

func CILogon added in v0.3.0

func CILogon(cfg CILogonConfig) Option

func CookieSecure

func CookieSecure(secure bool) Option

CookieSecure marks the session and CSRF cookies Secure, so a browser sends them over TLS only. It is an explicit statement by the deployment because a request cannot describe its own scheme: X-Forwarded-Proto, X-Url-Scheme and X-Forwarded-Ssl are set by whoever sent the request, and trusting them would let a plaintext caller decide that its own cookies need no TLS. cmd/dispatcher sets it when the daemon terminates TLS itself or when the configuration says a TLS terminator stands in front of it.

func ExecutorOnboarding added in v0.3.0

func ExecutorOnboarding(cfg config.ExecutorOnboardingConfig, issuer *enrollment.Signer) Option

ExecutorOnboarding enables account-owned machines using an explicitly configured certificate authority. A nil issuer leaves enrollment disabled.

func GitHubOAuth

func GitHubOAuth(cfg GitHubOAuthConfig) Option

func LocalDevelopment

func LocalDevelopment(enabled bool) Option

LocalDevelopment enables the local development profile of this API. In it, a request that presents no credential at all is served as the dispatcher's own local operator, and its runs are recorded without an owner, which is what keeps the explicit wallet-free local flow usable without a browser. A request that does present a credential is authenticated and authorized normally even here.

It is off by default and must never be enabled for a deployment that is reachable by anyone but its operator. cmd/dispatcher enables it exactly where it already recognises a local environment: blockchain payments disabled, the TLS listener disabled and both listeners on loopback, which is the configuration the local role commands generate and the deployment examples do not.

func MetricsStateDirectory added in v0.3.0

func MetricsStateDirectory(path string) Option

MetricsStateDirectory selects the local filesystem whose available bytes are observed. It must be the directory holding this dispatcher's database.

type OwnedExecutorResponse added in v0.3.0

type OwnedExecutorResponse struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Status    string `json:"status"`
	Ready     bool   `json:"ready"`
	Admission string `json:"admission"`
	// DrainStatus is unknown: the control protocol does not report whether
	// the executor's host service manager completed a joined shutdown.
	DrainStatus  string                 `json:"drain_status"`
	LastSeen     int64                  `json:"last_seen,omitempty"`
	Version      string                 `json:"version,omitempty"`
	OwnerDisplay config.ExecutorDisplay `json:"owner_display"`
	Display      wire.ExecutorDisplay   `json:"display"`
}

type OwnedExecutorsResponse added in v0.3.0

type OwnedExecutorsResponse struct {
	Enabled       bool                    `json:"enabled"`
	Executors     []OwnedExecutorResponse `json:"executors"`
	DispatcherURL string                  `json:"dispatcher_url,omitempty"`
}

type PaymentIntentRequest

type PaymentIntentRequest struct {
	Retry         *wire.RetryLink   `json:"retry,omitempty"`
	Debuglets     []DebugletRequest `json:"debuglets"`
	PaymentMethod string            `json:"payment_method"`
	RefundAddress string            `json:"refund_address"`
}

type ProbeResponse

type ProbeResponse struct {
	Status  string   `json:"status"`
	Reasons []string `json:"reasons,omitempty"`
}

ProbeResponse is the body of the liveness and readiness probes. Reasons is present only on a refusal.

type RecoverRequest

type RecoverRequest struct {
	RecoveryCode string `json:"recovery_code"`
}

RecoverRequest exchanges a recovery code for fresh account credentials.

type SessionResponse

type SessionResponse struct {
	Token     string `json:"token"`
	CSRFToken string `json:"csrf_token"`
	ExpiresAt int64  `json:"expires_at"`
	ID        string `json:"id"`
	Name      string `json:"name"`
	Role      string `json:"role"`
}

SessionResponse is an issued session. token is the bearer credential a native client repeats on every request; csrf_token is the value a browser client, which received the session in a cookie, repeats in the X-Debuglet-CSRF header of every state-changing request.

type SubmitDebugletsRequest

type SubmitDebugletsRequest struct {
	Retry         *wire.RetryLink   `json:"retry,omitempty"`
	Debuglets     []DebugletRequest `json:"debuglets"`
	TransactionId string            `json:"transaction_id"`
	AuthKey       string            `json:"auth_key"`
}

type SuiIntent

type SuiIntent struct {
	TransactionId   string `json:"transaction_id"`
	AuthKey         string `json:"auth_key"`
	Price           int64  `json:"price"`
	CoinType        string `json:"coin_type"`
	ExpiresAtS      int64  `json:"expires_at_s"`
	RegistryAddress string `json:"registry_address"`
	ReceiverAddress string `json:"receiver_address"`
}

type UserResponse

type UserResponse = wire.User

type VersionResponse

type VersionResponse wire.Version

VersionResponse reports the dispatcher's independent version identities.

func (VersionResponse) MarshalJSON added in v0.3.0

func (v VersionResponse) MarshalJSON() ([]byte, error)

MarshalJSON preserves the response's optional build revision.

Jump to

Keyboard shortcuts

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