Documentation
¶
Overview ¶
Package apps is the integration domain: app accounts (a bot user plus the app row), their scoped bearer tokens, the bearer authenticator, per-token rate limits and the pairing flow that hands a new app its first token.
Like the other domain services, every mutation runs in one store transaction together with its audit entry and events; the Tx variants join the caller's transaction.
Index ¶
- Constants
- Variables
- func HasScope(scopes []string, scope string) bool
- func NormalizeFingerprint(fp string) string
- func NormalizeScopes(field string, scopes []string) ([]string, error)
- func ValidScope(s string) bool
- type CreateAppInput
- type Endpoint
- type IssueTokenInput
- type IssuedToken
- type Options
- type PendingLimitError
- type Realtime
- type Service
- func (s *Service) ApprovePairing(ctx context.Context, admin chat.Actor, aud audit.Actor, id string, ...) (protocol.PairingApproval, error)
- func (s *Service) Authenticator() auth.Authenticator
- func (s *Service) CreateApp(ctx context.Context, actor audit.Actor, in CreateAppInput) (protocol.App, error)
- func (s *Service) CreateAppTx(tx *store.Tx, actor audit.Actor, in CreateAppInput) (protocol.App, error)
- func (s *Service) CreatePairing(ctx context.Context, ip string, in protocol.PairingRequestInput) (protocol.PairingCreated, error)
- func (s *Service) DenyPairing(ctx context.Context, aud audit.Actor, id string) error
- func (s *Service) GetApp(ctx context.Context, id string) (protocol.App, error)
- func (s *Service) Invoke(ctx context.Context, actor chat.Actor, req protocol.InvokeCommandRequest) (protocol.InvokedCommand, error)
- func (s *Service) IssueToken(ctx context.Context, actor audit.Actor, appID string, in IssueTokenInput) (IssuedToken, error)
- func (s *Service) IssueTokenTx(tx *store.Tx, actor audit.Actor, appID string, in IssueTokenInput) (IssuedToken, error)
- func (s *Service) Limiter() *auth.BucketLimiter
- func (s *Service) ListApps(ctx context.Context) ([]protocol.App, error)
- func (s *Service) ListCommands(ctx context.Context) ([]protocol.Command, error)
- func (s *Service) ListPending(ctx context.Context, caFingerprint string) ([]protocol.PendingPairing, error)
- func (s *Service) PollPairing(ctx context.Context, ip, id, secret string) (protocol.PairingStatus, error)
- func (s *Service) Respond(ctx context.Context, g *auth.TokenGrant, id string, ...) (protocol.RespondedCommand, error)
- func (s *Service) RevokeToken(ctx context.Context, actor audit.Actor, appID, tokenID string) error
- func (s *Service) Self(ctx context.Context, appID, tokenID string) (protocol.AppSelf, error)
- func (s *Service) SetCommands(ctx context.Context, g *auth.TokenGrant, in []protocol.CommandInput) ([]protocol.Command, error)
- func (s *Service) SetRealtime(rt Realtime)
- func (s *Service) UpdateApp(ctx context.Context, actor audit.Actor, id string, in UpdateAppInput) (protocol.App, error)
- type UpdateAppInput
Constants ¶
const ( ActionAppCreate = "app.create" ActionAppUpdate = "app.update" ActionAppDisable = "app.disable" ActionAppEnable = "app.enable" ActionTokenCreate = "token.create" ActionTokenRevoke = "token.revoke" ActionPairingApprove = "pairing.approve" ActionPairingDeny = "pairing.deny" )
Audit actions written by this package. Detail never carries a token, a poll secret or a pairing ciphertext.
const ( MaxNameChars = 64 MaxDescriptionChars = 500 )
Limits of app fields.
const ( MaxPendingPerApp = 100 MaxPendingPerInvoker = 20 )
Pending invocation caps: an app may have MaxPendingPerApp invocations awaiting an answer, and one invoker MaxPendingPerInvoker across all apps.
const ( // PairingTTL is how long a request waits for the admin. PairingTTL = 10 * time.Minute // ClaimWindow is how long an approved request stays claimable. It starts // at the approval, so an approval in the last seconds of the TTL is not // lost to the app's polling interval. ClaimWindow = 5 * time.Minute // MaxPendingPairings caps the open requests; more are answered 429. MaxPendingPairings = 20 // PairingCreatesPerMinute limits POST /pairing/requests per source IP. PairingCreatesPerMinute = 5 // PairingPollsPerSecond (burst PairingPollBurst) limits polling per IP. PairingPollsPerSecond = 2 PairingPollBurst = 20 )
Pairing limits (plan pipeline step 14).
const ( ScopeMessagesRead = protocol.ScopeMessagesRead ScopeMessagesWrite = protocol.ScopeMessagesWrite ScopeAlertsWrite = protocol.ScopeAlertsWrite ScopeFilesWrite = protocol.ScopeFilesWrite ScopeChannelsRead = protocol.ScopeChannelsRead ScopeEventsRead = protocol.ScopeEventsRead ScopeCommands = protocol.ScopeCommands ScopeDMWrite = protocol.ScopeDMWrite ScopeMCP = protocol.ScopeMCP )
The scopes an app token can carry (see protocol.AppScopes).
const ( // PrefixLen is the number of leading token characters stored (and shown) // to identify a token: "bub_" and four characters of the secret. PrefixLen = 8 // LastUsedInterval throttles last_used_at writes per token. LastUsedInterval = time.Minute )
const ( TokenRatePerSecond = 10 TokenBurst = 30 )
Per-token request limit.
const InvocationTTL = 15 * time.Minute
InvocationTTL is how long an app may answer an invocation.
Variables ¶
var ErrAppOffline = errors.New("app is offline")
ErrAppOffline is returned by Invoke when the command's app has no live connection; the REST layer answers 503 unavailable.
Functions ¶
func NormalizeFingerprint ¶
NormalizeFingerprint returns fp as lower-case hex without separators.
func NormalizeScopes ¶
NormalizeScopes validates scopes and returns them without duplicates in the canonical order of protocol.AppScopes. Unknown scopes are a validation error on field.
Types ¶
type CreateAppInput ¶
type CreateAppInput struct {
Name string
Description string
// Username is the bot's username; empty derives one from Name.
Username string
// OwnerID is the admin who created the app.
OwnerID string
}
CreateAppInput are the inputs of CreateApp.
type Endpoint ¶
type Endpoint struct {
// Host is the address clients should use (the first LAN address).
Host string
// Port is the HTTPS port.
Port int
// Fingerprint is the SHA-256 fingerprint of the CA certificate in any
// common notation (hex, optionally with spaces or colons).
Fingerprint string
}
Endpoint says how clients reach this server; it fills the connection string of a new token.
func (Endpoint) ConnectionString ¶
ConnectionString returns bubbles://<host>:<port>/?token=...&fp=sha256:<hex>. An endpoint without a fingerprint leaves fp out.
type IssueTokenInput ¶
type IssueTokenInput struct {
Scopes []string
// ChannelIDs restricts the token to these channels; nil leaves it
// unrestricted (the channels the bot is a member of).
ChannelIDs []string
// ExpiresAt is optional; it must lie in the future.
ExpiresAt *time.Time
}
IssueTokenInput are the inputs of IssueToken.
type IssuedToken ¶
IssuedToken is a new token: Secret is shown once and never stored.
type Options ¶
type Options struct {
DB *store.DB
Chat *chat.Service
// Now is the clock of the limiters, token expiry and pairing; nil means
// time.Now. It should be the clock the store uses.
Now func() time.Time
Logger *slog.Logger
// Realtime delivers the ephemeral command events and reports which apps are
// connected; it is the events hub. nil disables command invocation.
Realtime Realtime
}
Options configure a Service.
type PendingLimitError ¶
PendingLimitError reports that the app or the invoker already has the maximum of invocations awaiting an answer. The REST layer answers 429 with Retry-After set from RetryAfter.
func (*PendingLimitError) Error ¶
func (e *PendingLimitError) Error() string
type Realtime ¶
Realtime is the part of the events hub the command service needs: it publishes ephemeral events (seq 0, never stored) and knows which accounts have a live connection.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the apps domain service.
func (*Service) ApprovePairing ¶
func (s *Service) ApprovePairing(ctx context.Context, admin chat.Actor, aud audit.Actor, id string, in protocol.ApprovePairingRequest) (protocol.PairingApproval, error)
ApprovePairing creates the app, its bot and its first token for a pending request, adds the bot to the chosen channels (and to a new public "<app>-alerts" channel when asked), and records the approved scopes on the request. No token is created here: the app's first poll after the approval mints it (see PollPairing). admin must be an admin; audit actor is the admin too.
func (*Service) Authenticator ¶
func (s *Service) Authenticator() auth.Authenticator
Authenticator returns the auth.Authenticator for `Authorization: Bearer bub_...` headers. It resolves the token by the SHA-256 of the secret and answers (nil, nil), which the REST layer turns into a generic 401, for anything that is not a live token: unknown, revoked, expired, an app that is disabled or a bot account that is deactivated. Only a database failure is an error.
func (*Service) CreateApp ¶
func (s *Service) CreateApp(ctx context.Context, actor audit.Actor, in CreateAppInput) (protocol.App, error)
CreateApp creates an app and its bot account (kind app, role member, no password, so it can never sign in with a cookie).
func (*Service) CreateAppTx ¶
func (s *Service) CreateAppTx(tx *store.Tx, actor audit.Actor, in CreateAppInput) (protocol.App, error)
CreateAppTx is CreateApp inside the caller's transaction.
func (*Service) CreatePairing ¶
func (s *Service) CreatePairing(ctx context.Context, ip string, in protocol.PairingRequestInput) (protocol.PairingCreated, error)
CreatePairing opens a pairing request from the app at ip. The poll secret is returned here only; the database keeps its SHA-256.
func (*Service) DenyPairing ¶
DenyPairing rejects a pending request.
func (*Service) Invoke ¶
func (s *Service) Invoke(ctx context.Context, actor chat.Actor, req protocol.InvokeCommandRequest) (protocol.InvokedCommand, error)
Invoke runs a slash command typed by a person in a channel. Built-ins run here and their private notice, if any, goes to the invoker. For an app command it tells the app's connections and returns the invocation id; an app with no live connection is ErrAppOffline, with an ephemeral notice to the invoker.
func (*Service) IssueToken ¶
func (s *Service) IssueToken(ctx context.Context, actor audit.Actor, appID string, in IssueTokenInput) (IssuedToken, error)
IssueToken creates a token for the app. Only the SHA-256 of the secret and its 8-character prefix are stored.
func (*Service) IssueTokenTx ¶
func (s *Service) IssueTokenTx(tx *store.Tx, actor audit.Actor, appID string, in IssueTokenInput) (IssuedToken, error)
IssueTokenTx is IssueToken inside the caller's transaction.
func (*Service) Limiter ¶
func (s *Service) Limiter() *auth.BucketLimiter
Limiter is the per-token request limit (10 per second, burst 30), keyed by auth.TokenGrant.ID. The REST layer applies it to every bearer request.
func (*Service) ListCommands ¶
ListCommands returns the built-ins followed by the commands of every enabled app, by name.
func (*Service) ListPending ¶
func (s *Service) ListPending(ctx context.Context, caFingerprint string) ([]protocol.PendingPairing, error)
ListPending returns the open pairing requests, oldest first, each marked with caFingerprint (the one the app shows, for the admin to compare).
func (*Service) PollPairing ¶
func (s *Service) PollPairing(ctx context.Context, ip, id, secret string) (protocol.PairingStatus, error)
PollPairing answers the app's poll. The poll secret must match, else the request is ErrNotFound (a wrong secret reveals nothing, not even that the id exists). No token exists before the first poll after the approval: that poll mints it in the same transaction that moves the request to claimed, so the token is returned once and never stored in any recoverable form.
func (*Service) Respond ¶
func (s *Service) Respond(ctx context.Context, g *auth.TokenGrant, id string, req protocol.RespondCommandRequest) (protocol.RespondedCommand, error)
Respond answers an invocation as the app. An ephemeral answer reaches only the invoker's connections and is not stored; any other is a normal message of the app's bot in the channel (and thread) the command ran in, with mentions disabled.
func (*Service) RevokeToken ¶
RevokeToken revokes one token of the app. Revoking a revoked token does nothing; a token of another app is ErrNotFound. The token's live connections are closed when the change commits.
func (*Service) Self ¶
Self returns the app and token behind a bearer principal. The app's token list is left empty.
func (*Service) SetCommands ¶
func (s *Service) SetCommands(ctx context.Context, g *auth.TokenGrant, in []protocol.CommandInput) ([]protocol.Command, error)
SetCommands replaces the command set of the token's app atomically. Names are unique across all apps and must not shadow a built-in; a clash is a conflict that names the owner.
func (*Service) SetRealtime ¶
SetRealtime installs the realtime hub after construction (the composition root and tests build the services first). Call it before serving requests.
func (*Service) UpdateApp ¶
func (s *Service) UpdateApp(ctx context.Context, actor audit.Actor, id string, in UpdateAppInput) (protocol.App, error)
UpdateApp renames an app, edits its description, or disables and enables it. A disabled app's tokens are rejected on their next request and its live connections are closed; nothing is revoked, so enabling the app restores them.
type UpdateAppInput ¶
UpdateAppInput are the optional changes of UpdateApp.