integrations

package
v0.0.0-...-7a309a5 Latest Latest
Warning

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

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

Documentation

Overview

Package integrations provides HTTP handlers for integration management (Slack, Discord, webhook, email, etc.). The legacy `integration_connections` table backs this domain — see spec 2026-05-07-03 for the rename rationale.

Index

Constants

View Source
const (
	// IdentityStatusMatched means the member has an identity on this integration.
	IdentityStatusMatched = "matched"
	// IdentityStatusNotFound means the member's email resolved to nobody in the
	// workspace (or was never synced).
	IdentityStatusNotFound = "notFound"
	// IdentityStatusAmbiguous means the auto-match resolved to a workspace user
	// that another member already owns. Never guessed — surfaced for an admin
	// to settle with a manual override.
	IdentityStatusAmbiguous = "ambiguous"
)

Identity mapping statuses reported per member.

View Source
const TestResultCodeMisconfigured = "INTEGRATION_MISCONFIGURED"

TestResultCodeMisconfigured is IntegrationTestResult.Code when the sender sent nothing because a required setting is missing (spec 2026-10-08-03). The endpoint still answers 200: it is a result, not an HTTP error.

Variables

View Source
var (
	// ErrIdentitiesUnsupportedType is returned when identity mapping is asked
	// of an integration type that has no identity concept. Slack and bot-mode
	// Discord are supported; Teams is explicitly out of scope
	// (spec 2026-08-12-03).
	ErrIdentitiesUnsupportedType = errors.New(
		"identity mapping is only available for Slack and Discord bot integrations")
	// ErrSlackNotConnected is returned when the Slack integration carries no
	// bot token, so no workspace lookup is possible.
	ErrSlackNotConnected = errors.New("slack integration is not connected — install the Slack app")
	// ErrIdentityExternalIDRequired is returned when a manual override omits
	// the provider-side identifier.
	ErrIdentityExternalIDRequired = errors.New("externalId is required")
	// ErrIdentityMemberNotFound is returned when the target user is not a
	// member of the integration's organization.
	ErrIdentityMemberNotFound = errors.New("user is not a member of this organization")
	// ErrIdentityAlreadyClaimed is returned when the requested external id is
	// already mapped to a different member on this integration. Mapping one
	// Slack account to two people would make mentions lie about who is on call.
	ErrIdentityAlreadyClaimed = errors.New("that workspace user is already mapped to another member")
)

Identity-mapping errors.

View Source
var (
	// ErrOrganizationNotFound is returned when an organization is not found.
	ErrOrganizationNotFound = errors.New("organization not found")
	// ErrConnectionNotFound is returned when a connection is not found.
	ErrConnectionNotFound = errors.New("connection not found")
	// ErrInvalidConnectionType is returned when an invalid connection type is provided.
	ErrInvalidConnectionType = errors.New("invalid connection type")
	// ErrFreeboxPairingFailed is returned when the Freebox pairing flow
	// fails (transport error, denial, timeout). The wrapped error keeps
	// the underlying cause so the handler can surface a useful message.
	ErrFreeboxPairingFailed = errors.New("freebox pairing failed")
	// ErrFreeboxNotPairing is returned when a status-poll is requested
	// against a channel that isn't currently in the pairing state.
	ErrFreeboxNotPairing = errors.New("freebox channel is not in pairing state")
	// ErrFreeboxTypeMismatch is returned when a pairing endpoint targets
	// a non-Freebox channel.
	ErrFreeboxTypeMismatch = errors.New("channel is not a freebox connection")
	// ErrSlackManualCreate is returned when a Slack channel is created via the
	// manual create endpoint. Slack channels can only originate from the OAuth
	// install flow (which writes the bot token); a manually-created stub has no
	// token and is permanently broken.
	ErrSlackManualCreate = errors.New("slack channels are added by installing the Slack app")
	// ErrMSTeamsBotManualCreate is returned when a msteams-bot channel is
	// created through the generic API. Like Slack, this type carries a
	// provider-side identity that must be PROVEN, not asserted: its tenant_id
	// decides whose Teams conversations the connection receives, so allowing
	// a caller to supply one would let any org claim any Microsoft 365
	// tenant. Creation goes through
	// POST /orgs/:org/integrations/msteams/link-code, which issues a
	// one-time code that must be redeemed from inside the tenant itself.
	ErrMSTeamsBotManualCreate = errors.New(
		"microsoft teams bot channels are added with a link code, not created directly")
	// ErrMSTeamsBotUnknownDestination is returned when a destination
	// selection names a conversation the bot was never added to. The
	// conversation id is not proof of access — see
	// models.MSTeamsBotSettings.HasDestination.
	ErrMSTeamsBotUnknownDestination = errors.New(
		"the selected Microsoft Teams channel is not one this bot has been added to")
	// ErrNotWebhookChannel is returned when a webhook-only operation
	// (rotate-secret) targets a channel of a different type.
	ErrNotWebhookChannel = errors.New("channel is not a webhook connection")
	// ErrIntegrationNotNotifiable is returned when a test-notification is
	// requested for an integration whose type cannot send notifications
	// (e.g. a data source like Freebox).
	ErrIntegrationNotNotifiable = errors.New("integration type cannot send notifications")
	// ErrInvalidSettings is returned when a connection's type-specific settings
	// fail validation (e.g. a malformed Twilio account SID or phone number).
	ErrInvalidSettings = errors.New("invalid connection settings")
)
View Source
var ErrFreeboxNotGranted = errors.New("freebox channel is not paired yet")

ErrFreeboxNotGranted is returned when the channels handler tries to run a Freebox-authenticated call against a channel that hasn't completed the LCD-pairing flow yet. The handler maps this to a 409 (Conflict) so the dashboard can prompt the user to finish pairing.

Functions

This section is empty.

Types

type A2ACardRequest

type A2ACardRequest struct {
	// Settings are the form's current values. An empty secret means "keep
	// the stored one" when IntegrationUID is set, as on PATCH.
	Settings map[string]any `json:"settings"`
	// IntegrationUID names a saved A2A integration whose stored secrets fill
	// in the ones the form does not echo back. Optional.
	IntegrationUID string `json:"integrationUid,omitempty"`
}

A2ACardRequest asks the server to resolve an AI agent's Agent Card before the integration is saved (spec 2026-10-18-02, the dashboard's Test button).

type A2ACardResult

type A2ACardResult struct {
	Success bool                        `json:"success"`
	Agent   *notifications.A2AAgentInfo `json:"agent,omitempty"`
	Error   string                      `json:"error,omitempty"`
}

A2ACardResult is the outcome of a card resolution. Always HTTP 200: the caller reads Success, like IntegrationTestResult.

type CreateIntegrationRequest

type CreateIntegrationRequest struct {
	Type      string         `json:"type"`
	Name      string         `json:"name"`
	Enabled   *bool          `json:"enabled,omitempty"`
	IsDefault *bool          `json:"isDefault,omitempty"`
	Settings  map[string]any `json:"settings,omitempty"`
}

CreateIntegrationRequest represents the request to create a connection.

type FreeboxPairingResponse

type FreeboxPairingResponse struct {
	ConnectionUID string `json:"connectionUid"`
	TrackID       int    `json:"trackId"`
	Status        string `json:"status"`
}

FreeboxPairingResponse is the body returned by the start-pairing endpoint.

type FreeboxPairingStatusResponse

type FreeboxPairingStatusResponse struct {
	Status string `json:"status"`
}

FreeboxPairingStatusResponse is the body returned by the poll-status endpoint.

type Handler

type Handler struct {
	base.HandlerBase
	// contains filtered or unexported fields
}

Handler provides HTTP handlers for connection management endpoints.

func NewHandler

func NewHandler(service *Service, cfg *config.Config) *Handler

NewHandler creates a new connections handler.

func (*Handler) CreateIntegration

func (h *Handler) CreateIntegration(writer http.ResponseWriter, req *http.Request) error

CreateIntegration handles creating a new connection.

func (*Handler) DeleteIdentity

func (h *Handler) DeleteIdentity(writer http.ResponseWriter, req *http.Request) error

DeleteIdentity clears a member's mapping on an integration.

Route: DELETE /api/v1/orgs/:org/integrations/:uid/identities/:userUid.

func (*Handler) DeleteIntegration

func (h *Handler) DeleteIntegration(writer http.ResponseWriter, req *http.Request) error

DeleteIntegration handles deleting a connection.

func (*Handler) GetFreeboxPairingStatus

func (h *Handler) GetFreeboxPairingStatus(writer http.ResponseWriter, req *http.Request) error

GetFreeboxPairingStatus returns the current Freebox pairing status for a channel. The dashboard polls this every ~2 s until the response is `granted`, `denied`, or `timeout`.

func (*Handler) GetIntegration

func (h *Handler) GetIntegration(writer http.ResponseWriter, req *http.Request) error

GetIntegration handles getting a specific connection by UID.

func (*Handler) LanHostsHandler

func (h *Handler) LanHostsHandler(writer http.ResponseWriter, req *http.Request) error

LanHostsHandler handles `GET /api/v1/orgs/:org/integrations/freebox/:uid/lan-hosts`. It resolves the org + channel, asserts the channel is a granted Freebox connection, and proxies the LAN-browser query through to the underlying Freebox.

func (*Handler) ListIdentities

func (h *Handler) ListIdentities(writer http.ResponseWriter, req *http.Request) error

ListIdentities returns every org member's mapping status on an integration.

Route: GET /api/v1/orgs/:org/integrations/:uid/identities.

func (*Handler) ListIntegrations

func (h *Handler) ListIntegrations(writer http.ResponseWriter, req *http.Request) error

ListIntegrations handles listing all connections of an organization.

func (*Handler) ResolveA2ACard

func (h *Handler) ResolveA2ACard(writer http.ResponseWriter, req *http.Request) error

ResolveA2ACard handles POST /orgs/:org/integrations/a2a/resolve-card.

func (*Handler) RotateWebhookSecret

func (h *Handler) RotateWebhookSecret(writer http.ResponseWriter, req *http.Request) error

RotateWebhookSecret rotates the signing secret of a webhook channel. The current secret becomes the previous one (valid for a 24 h grace window) and a fresh secret is generated. Returns the updated channel.

func (*Handler) SetIdentity

func (h *Handler) SetIdentity(writer http.ResponseWriter, req *http.Request) error

SetIdentity records an admin's manual mapping for one member.

Route: PUT /api/v1/orgs/:org/integrations/:uid/identities/:userUid.

func (*Handler) StartFreeboxPairing

func (h *Handler) StartFreeboxPairing(writer http.ResponseWriter, req *http.Request) error

StartFreeboxPairing kicks off the Freebox LCD-pairing flow. On success, returns the new connectionUid + trackId; the dashboard then polls GetFreeboxPairingStatus every 2 s until the user approves the prompt on the Freebox.

func (*Handler) SyncIdentities

func (h *Handler) SyncIdentities(writer http.ResponseWriter, req *http.Request) error

SyncIdentities re-runs the email auto-match against the workspace.

Route: POST /api/v1/orgs/:org/integrations/:uid/identities/sync.

func (*Handler) TestIntegration

func (h *Handler) TestIntegration(writer http.ResponseWriter, req *http.Request) error

TestIntegration sends a sample notification through the integration and reports the outcome. Always returns HTTP 200 for a notifiable integration — the caller inspects the `success` field to know whether delivery worked.

func (*Handler) UpdateIntegration

func (h *Handler) UpdateIntegration(writer http.ResponseWriter, req *http.Request) error

UpdateIntegration handles updating a connection.

type IntegrationResponse

type IntegrationResponse struct {
	UID       string         `json:"uid"`
	Type      string         `json:"type"`
	Name      string         `json:"name"`
	Enabled   bool           `json:"enabled"`
	IsDefault bool           `json:"isDefault"`
	Settings  map[string]any `json:"settings,omitempty"`
	// SettingsPrivateKeys lists which top-level Settings keys are stored
	// encrypted (and therefore stripped from the Settings map in the
	// response). Lets the dashboard render placeholder pills like
	// "•••• access_token" without echoing the secret value.
	SettingsPrivateKeys []string  `json:"settingsPrivateKeys,omitempty"`
	CreatedAt           time.Time `json:"createdAt"`
	UpdatedAt           time.Time `json:"updatedAt"`
}

IntegrationResponse represents a connection in API responses.

type IntegrationTestResult

type IntegrationTestResult struct {
	Success    bool   `json:"success"`
	StatusCode int    `json:"statusCode"`
	DurationMs int64  `json:"durationMs"`
	Error      string `json:"error,omitempty"`
	// Detail carries an optional human-readable success note (e.g. the
	// Kubernetes cluster's reported server version). Empty for notification
	// tests, which have nothing extra to report on success.
	Detail string `json:"detail,omitempty"`
	// Code is INTEGRATION_MISCONFIGURED when the sender refused to send
	// because a required setting is missing: a configuration error, not a
	// delivery failure. Empty otherwise.
	Code string `json:"code,omitempty"`
	// MissingSetting names what is missing ("API token") when Code is
	// INTEGRATION_MISCONFIGURED.
	MissingSetting string `json:"missingSetting,omitempty"`
}

IntegrationTestResult is returned by TestIntegration. Success reports whether the integration delivered the sample notification. StatusCode carries the HTTP status for HTTP-based integrations (e.g. webhooks); it is 0 for senders with no such concept. The handler always returns HTTP 200; the caller inspects Success.

type ListConnectionsResponse

type ListConnectionsResponse struct {
	Data []*IntegrationResponse `json:"data"`
}

ListConnectionsResponse represents the response for listing connections.

type ListIdentitiesResponse

type ListIdentitiesResponse struct {
	Data []*MemberIdentityResponse `json:"data"`
}

ListIdentitiesResponse wraps the per-member mapping list.

type ListLanHostsResponse

type ListLanHostsResponse struct {
	Data []freebox.LanHost `json:"data"`
}

ListLanHostsResponse is the body returned by the lan-hosts endpoint. Sticks to the dashboard convention: list endpoints wrap the slice in a `data` object so we have room to add pagination later.

type MemberIdentityResponse

type MemberIdentityResponse struct {
	UserUID     string `json:"userUid"`
	Email       string `json:"email"`
	Name        string `json:"name,omitempty"`
	Status      string `json:"status"`
	ExternalID  string `json:"externalId,omitempty"`
	DisplayName string `json:"displayName,omitempty"`
	Source      string `json:"source,omitempty"`
}

MemberIdentityResponse is the per-member mapping status returned by the identity endpoints. Only identity data travels — never a contact value.

type Service

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

Service provides business logic for connection management.

func NewService

func NewService(
	dbService db.Service,
	creds credentials.Service,
	registry *services.Registry,
	cfg *config.Config,
) *Service

NewService creates a new connections service. registry and cfg may be nil when test-notification dispatch is not required (e.g. unit tests).

func (*Service) AllowFreeboxTestBaseURL

func (s *Service) AllowFreeboxTestBaseURL(rawURL string)

AllowFreeboxTestBaseURL registers rawURL as an EXACT baseUrl value this Service accepts without going through freebox.ValidateBaseURL's private-IP/port contract. It is a Go-level construction seam, never reachable from an HTTP request body — the same shape as importers.Handler.WithBetterStackBaseURL — that exists only so a test can stand up a fresh httptest.Server (a loopback host on a random port, which is never where a real Freebox lives and the real contract correctly rejects) and let pairing reach it. Every OTHER value — including any other loopback or special-range address — is still held to the full contract, so this seam cannot be used to smuggle a general bypass. It mutates s in place (unlike the Service's other With* constructors) because tests must register the URL only after starting the fake server, by which point the fixture has already wired this *Service into a Handler/router by pointer.

func (*Service) CheckFreeboxPairingStatus

func (s *Service) CheckFreeboxPairingStatus(
	ctx context.Context, orgSlug, connectionUID string,
) (*FreeboxPairingStatusResponse, error)

CheckFreeboxPairingStatus polls the Freebox once for the current pairing status and reconciles the IntegrationConnection record:

  • granted → clears TrackID, sets Status = granted
  • denied / timeout → sets Status accordingly, leaves the row in place so the operator can see the failure (and re-pair from the UI)
  • pending / unknown → unchanged

func (*Service) CreateIntegration

func (s *Service) CreateIntegration(
	ctx context.Context, orgSlug string, req CreateIntegrationRequest,
) (*IntegrationResponse, error)

CreateIntegration creates a new connection.

func (*Service) DeleteIdentity

func (s *Service) DeleteIdentity(ctx context.Context, orgSlug, integrationUID, userUID string) error

DeleteIdentity clears a member's mapping on an integration. Idempotent.

func (*Service) DeleteIntegration

func (s *Service) DeleteIntegration(ctx context.Context, orgSlug, connectionUID string) error

DeleteIntegration deletes a connection.

func (*Service) GetIntegration

func (s *Service) GetIntegration(
	ctx context.Context, orgSlug, connectionUID string,
) (*IntegrationResponse, error)

GetIntegration returns a connection by UID.

func (*Service) ListFreeboxLanHosts

func (s *Service) ListFreeboxLanHosts(
	ctx context.Context, orgSlug, connectionUID string,
) ([]freebox.LanHost, error)

ListFreeboxLanHosts resolves the org + channel, validates it is a Freebox connection (preserving the precise 404 / 400 domain errors the HTTP layer relies on), then delegates the granted-check → decrypt-token → build-client → list chain to the shared freebox.ListLanHostsForChannel resolver. The freebox package's not-granted sentinel is mapped back to this handler's ErrFreeboxNotGranted so the endpoint keeps returning 409.

func (*Service) ListIdentities

func (s *Service) ListIdentities(
	ctx context.Context, orgSlug, integrationUID string,
) (*ListIdentitiesResponse, error)

ListIdentities returns the mapping status of every org member on one integration. Purely a read — it never calls out to Slack, so the dashboard can render the panel without spending an API call or a workspace round-trip.

func (*Service) ListIntegrations

func (s *Service) ListIntegrations(
	ctx context.Context, orgSlug string, connType *string,
) (*ListConnectionsResponse, error)

ListIntegrations returns all connections for an organization.

func (*Service) ResolveA2ACard

func (s *Service) ResolveA2ACard(ctx context.Context, orgSlug string, req *A2ACardRequest) (*A2ACardResult, error)

ResolveA2ACard resolves the Agent Card for possibly unsaved settings.

func (*Service) RotateWebhookSecret

func (s *Service) RotateWebhookSecret(
	ctx context.Context, orgSlug, connectionUID string,
) (*IntegrationResponse, error)

RotateWebhookSecret cycles a webhook channel's signing secret: the current secret becomes the previous one (valid for a 24 h grace window) and a fresh secret is generated. Receivers can verify against either during the window.

func (*Service) SetIdentity

func (s *Service) SetIdentity(
	ctx context.Context, orgSlug, integrationUID, userUID string, req SetIdentityRequest,
) (*MemberIdentityResponse, error)

SetIdentity records an admin's manual mapping of a member to a workspace user. The external id may be claimed by at most one member per integration.

func (*Service) SetSlackIdentityClient

func (s *Service) SetSlackIdentityClient(factory SlackIdentityClientFactory)

SetSlackIdentityClient overrides the Slack lookup factory for this service instance. Per-instance rather than package-level so parallel tests can never race on a shared seam.

func (*Service) StartFreeboxPairing

func (s *Service) StartFreeboxPairing(
	ctx context.Context, orgSlug string, req StartFreeboxPairingRequest,
) (*FreeboxPairingResponse, error)

StartFreeboxPairing kicks off a Freebox pairing flow and persists the resulting permanent app_token (encrypted) onto a new IntegrationConnection row. The connection starts in `Status = "pairing"` until the operator approves the prompt on the Freebox LCD.

func (*Service) SyncIdentities

func (s *Service) SyncIdentities(
	ctx context.Context, orgSlug, integrationUID string,
) (*SyncIdentitiesResponse, error)

SyncIdentities re-runs the email auto-match against the Slack workspace.

Rules, in order:

  • A `manual` row is never touched — an admin's explicit choice outranks anything an email match can infer.
  • A workspace hit whose user id is already owned by ANOTHER member is reported ambiguous and written nowhere. Guessing here would make an alert ping the wrong human.
  • A member whose email resolves to nobody keeps whatever identity they already had (a transient Slack answer must not wipe a working mapping) and is only reported "not found" when they had none.

func (*Service) TestIntegration

func (s *Service) TestIntegration(
	ctx context.Context, orgSlug, connectionUID string,
) (*IntegrationTestResult, error)

TestIntegration sends a sample notification through the integration's real sender — the same delivery path a live incident takes — and reports the outcome. Works for every notification type; data-source-only types (e.g. Freebox) are rejected with ErrIntegrationNotNotifiable.

func (*Service) UpdateIntegration

func (s *Service) UpdateIntegration(
	ctx context.Context, orgSlug, connectionUID string, req UpdateIntegrationRequest,
) (*IntegrationResponse, error)

UpdateIntegration updates a connection.

type SetIdentityRequest

type SetIdentityRequest struct {
	ExternalID  string `json:"externalId"`
	DisplayName string `json:"displayName,omitempty"`
}

SetIdentityRequest is the body of the manual-override PUT.

type SlackIdentityClientFactory

type SlackIdentityClientFactory func(token string) SlackIdentityLookup

SlackIdentityClientFactory builds a lookup client from a bot token.

type SlackIdentityLookup

type SlackIdentityLookup interface {
	LookupUserByEmail(ctx context.Context, email string) (*slack.SlackUser, bool, error)
}

SlackIdentityLookup is the slice of the Slack API the identity auto-match needs. Narrow on purpose so tests can supply a fake without a Slack server.

type StartFreeboxPairingRequest

type StartFreeboxPairingRequest struct {
	// Name is used for the IntegrationConnection row and for the
	// device_name shown on the Freebox LCD prompt. Optional — defaults
	// to "SolidPing" if absent.
	Name string `json:"name,omitempty"`
	// BaseURL of the Freebox API. Defaults to
	// "http://mafreebox.freebox.fr" when empty.
	BaseURL string `json:"baseUrl,omitempty"`
}

StartFreeboxPairingRequest is the body for the start-pairing endpoint.

type SyncIdentitiesResponse

type SyncIdentitiesResponse struct {
	Data           []*MemberIdentityResponse `json:"data"`
	MatchedCount   int                       `json:"matchedCount"`
	NotFoundCount  int                       `json:"notFoundCount"`
	AmbiguousCount int                       `json:"ambiguousCount"`
}

SyncIdentitiesResponse reports the post-sync state plus the bucket counts the dashboard summarizes ("12 matched, 3 not found").

type UpdateIntegrationRequest

type UpdateIntegrationRequest struct {
	Name      *string        `json:"name,omitempty"`
	Enabled   *bool          `json:"enabled,omitempty"`
	IsDefault *bool          `json:"isDefault,omitempty"`
	Settings  map[string]any `json:"settings,omitempty"`
}

UpdateIntegrationRequest represents the request to update a connection.

Jump to

Keyboard shortcuts

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