mattermost

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: AGPL-3.0 Imports: 32 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mattermost is the REST client of Mattermost Connections (C-13.FR-1): the calls of the Mattermost REST API v4 with the bot token as a bearer token, through internal/outbound with the Connection's proxy, in the client class of the caller (ADR-0015); the dry probe of a check without a token (C-13.FR-2); and the Destination check of a Mattermost Destination (C-13.FR-10). Muster uses only the REST API with the bot account. The adapter of S-061 builds on this client.

Index

Constants

View Source
const (
	StepToken        = "token"
	StepBotInChannel = "bot_in_channel"

	MessageTokenInvalid = "The bot token is not valid." //nolint:gosec // G101: a message, not a credential
	MessageNotMember    = "The bot is not a member of this channel."
	MessageOtherTeam    = "The channel is not in this team."
	MessageArchived     = "The channel is archived."
)

The steps of the Destination check of a Mattermost Destination and their messages (C-13.FR-10).

View Source
const (
	CodeTokenInvalid = "token_invalid"
	CodeNotMember    = "bot_not_in_channel"
	CodeOtherTeam    = "channel_in_other_team"
	CodeArchived     = "channel_archived"
)

The codes of the steps that failed (ConnectionCheckStep.code, DestinationCheckItem.code), one per message above; any other failure has the code of delivery.FailureCode.

View Source
const (
	StepDryProbe = "dry_probe"

	MessageWrongPrefix  = "Wrong path prefix: the server answered 404."
	MessageProxyRefused = delivery.MessageProxyRefused
)

The step of the dry probe of a Mattermost Connection (C-13.FR-2) and the messages of what answered it.

View Source
const (
	CodeNotMattermost    = "not_mattermost"
	CodeWrongPrefix      = "wrong_path_prefix"
	CodeUnexpectedStatus = "unexpected_status"
)

The codes of the dry probe that reached no Mattermost server (ConnectionCheckStep.code); a probe without an answer has the code of delivery.FailureCode.

View Source
const (
	ViaDirect = "direct"
	ViaProxy  = "proxy"
)

The paths of a Connection's routes for the way its requests travel (ConnectionPath).

View Source
const (
	ChannelOpen    = "O"
	ChannelPrivate = "P"
	ChannelDirect  = "D"
	ChannelGroup   = "G"
)

The types of Mattermost channels.

View Source
const (
	StepMessage = "message"
	StepPress   = "press"
)

The names of the steps of a test and of the items of a preview.

View Source
const CallbackPath = "/api/v1/callbacks/mattermost/"

CallbackPath is where Mattermost calls Muster for the button presses of a Connection, under MUSTER_INGEST_URL, with the Connection's public_id after it (C-13.FR-4).

View Source
const CallbackPattern = CallbackPath + "{connection_id}"

CallbackPattern is the pattern of the callback of button presses on the callback mux of the ingest listener.

View Source
const DryProbePath = "/api/v4/system/ping"

DryProbePath is the path of the dry probe: the system ping, which a Mattermost server answers without a token (F-069).

View Source
const HintPressAnswersInThread = "the bot may not make ephemeral messages (create_post_ephemeral), so answers to " +
	"button presses show in the Thread of the Root message; give it that permission, for example the system admin " +
	"role, to show them in the channel"

HintPressAnswersInThread is the hint of a Connection whose bot lacks PermissionEphemeralPosts (D284).

View Source
const LengthLimit = 16_383

LengthLimit is the longest post message, and the longest attachment text, in characters: the server's MaxPostSize (F-057).

View Source
const PermissionEphemeralPosts = "create_post_ephemeral"

PermissionEphemeralPosts is the permission of POST /api/v4/posts/ephemeral, which only the system admin role holds by default (F-063).

View Source
const TestPressChannel = "muster_test_press"

TestPressChannel is the LISTEN/NOTIFY channel on which the callback of any replica reports the bot's own press of a test message, with the nonce of its test as the payload.

Variables

View Source
var ErrNoConnection = errors.New("no such mattermost connection")

ErrNoConnection is a callback for a Connection that is unknown, deleted or not a Mattermost one.

View Source
var ErrNoTarget = errors.New("the destination has no mattermost connection")

ErrNoTarget is a Destination that has no Mattermost Connection to post through: it, or its Connection, no longer exists, or it is not a Mattermost Destination.

Functions

func NewCallback

func NewCallback(cfg CallbackConfig) http.Handler

NewCallback is the callback of the button presses of Mattermost Connections, mattermostAction (C-13.FR-4): it verifies the signed action id, binds the press to the Root message or the Reminder it was issued for, maps the Mattermost user to a User through its Account link, and runs the Command as that User with the Transport mattermost. Every request is answered 200 with a JSON object, never with update. Whatever the person who pressed must read goes first as an ephemeral post through the interactive path, which shows in the channel view (F-026) — or, for a press on a Reminder, in the Thread of the Root message it replies to (F-025) — and the answer is empty; when that post is not made — refused with 403 to a bot without the create_post_ephemeral permission (F-063), or failed any other way — the text is the answer's ephemeral_text, which needs no permission and shows in the Thread (F-025, F-062), so that it is never lost (D284). A press on a Reminder whose key left the Keyring is answered that the button has expired (C-17.FR-6). Every request for a known Connection, refused ones included, is in its Request log through the annotation of requestlog.Inbound, with the Destination and the Alert Group once the press is matched (C-23.FR-1).

Types

type Adapter

type Adapter struct {
	Targets   Targets
	PublicURL string
	IngestURL string
	Version   string
}

Adapter is the delivery adapter of Mattermost Destinations (C-11.FR-7, C-13): Publish, Update and Reply, called by the delivery worker and the interactive path only, in the client class of their Call, and Check, the Destination check of C-13.FR-10 for the Broken probe. PublicURL and IngestURL are MUSTER_PUBLIC_URL and MUSTER_INGEST_URL, and Version the version that the attachment's footer names.

func (*Adapter) Check

func (a *Adapter) Check(ctx context.Context, c delivery.Call) delivery.Outcome

Check runs the Destination check of C-13.FR-10 at once, in the client class of c: the Broken probe calls it in the delivery class, the interactive path in the interactive class.

func (*Adapter) LengthLimit

func (a *Adapter) LengthLimit() int

LengthLimit is the server's post length limit (F-057), which a Root message is shortened to.

func (*Adapter) Markup

func (a *Adapter) Markup() messages.Markup

Markup is the markup of Mattermost posts.

func (*Adapter) Publish

Publish creates the Root message m, with the Mentions of a Loud call, its targets' and those of the template tokens of m, in its message.

func (*Adapter) Reply

Reply posts m into the Thread of root, with the Mentions of a Loud call first; a Reminder carries the buttons "Still on it" and "Unack" (C-13.FR-4), which are never edited: a reply is posted once, and a key rotation re-signs Root messages only.

func (*Adapter) Update

func (a *Adapter) Update(ctx context.Context, c delivery.Call, messageID string, m delivery.Message) delivery.Outcome

Update edits the Root message messageID to m: its summary line without Mentions and its attachment.

type Bindings

type Bindings interface {
	PressBinding(ctx context.Context, connectionID int64, groupPublicID, postID string) (delivery.Binding, error)
	ReplyBinding(ctx context.Context, connectionID int64, groupPublicID, postID string) (delivery.Binding, error)
	PostDestination(ctx context.Context, connectionID int64, postID, channelID string) (delivery.Destination, bool,
		error)
	TestDestination(ctx context.Context, connectionID int64, publicID, channelID string) (delivery.Destination, bool,
		error)
}

Bindings are delivery's reads of what a press is bound to; *delivery.Service implements it.

type CallbackConfig

type CallbackConfig struct {
	Connections Connections
	Bindings    Bindings
	Links       Links
	Commands    Commands
	// Roles are the Permissions of each Role, which the linked User presses with.
	Roles auth.Roles
	// Keys verify the signed action ids: the Keyring.
	Keys buttons.Keys
	// Path is the interactive path the ephemeral posts of the answers go through.
	Path Path
	// Budget bounds the ephemeral post of an answer, its limiter tokens included: delivery.interactive_budget; zero
	// takes delivery.InteractiveBudget.
	Budget time.Duration
	// Business is the business clock, from which a Snooze lasts its duration.
	Business clock.Clock
	// PublicURL is MUSTER_PUBLIC_URL, the base of the profile link.
	PublicURL string
	// BodyLimit is ingest.body_limit; zero takes ingest.BodyLimit.
	BodyLimit int64
	// TestPresses tell the Destination test waiting on any replica that the bot's own press of its test message
	// arrived (C-16.FR-3); nil tells nobody.
	TestPresses TestPresses
	Log         *logging.Logger
}

CallbackConfig is what the callback of button presses needs.

type Channel

type Channel struct {
	ID          string `json:"id"`
	TeamID      string `json:"team_id"`
	Name        string `json:"name"`
	DisplayName string `json:"display_name"`
	Type        string `json:"type"`
	DeleteAt    int64  `json:"delete_at"`
}

Channel is a Mattermost channel; a DeleteAt other than 0 is an archived one.

type Check

type Check struct {
	Steps       []Step
	TeamName    string
	ChannelName string
	// Bot is the bot the token belongs to, once the step token passed: the callback of button presses tells the bot's
	// own press of a test message by its user id (C-16.FR-3).
	Bot     User
	Outcome delivery.Outcome
}

Check is the result of a Destination check: the steps that ran, the names of the team and the channel when every step passed, and the outcome of the whole — ok, or the outcome of the step that failed — for the Broken probe.

func CheckDestination

func CheckDestination(ctx context.Context, c *Client, run Runner, teamID, channelID string) (Check, error)

CheckDestination runs the Destination check of the channel channelID in the team teamID without sending a message: GET /api/v4/users/me for the token, then GET /api/v4/channels/{channel_id}/members/me for the bot's membership, then, once both passed, the channel and its team for their names. A step that fails ends the check; the token fails with MessageTokenInvalid on 401, the membership with MessageNotMember on 403 or 404, with MessageOtherTeam for a channel of another team and MessageArchived for an archived one, each with its code, and any other failure with the masked text of the answer and the code of Result.FailureCode.

func (Check) OK

func (c Check) OK() bool

OK reports whether every step passed.

type Client

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

Client calls the REST API of one Mattermost Connection, in the interactive and the delivery client classes and, for muster doctor, the background class; the outbound client of a class is built on its first call.

func NewClient

func NewClient(n Network, s Settings) (*Client, error)

NewClient builds the client of the Connection s, checking its settings with the interactive class. Its requests go to the server URL, or to what s.Route answers for it and the bot token when it answers. The bot token and the proxy password are registered for redaction.

func (*Client) Channel

func (c *Client) Channel(ctx context.Context, class outbound.Class, channelID string) (Channel, Result)

Channel reads the channel channelID.

func (*Client) Channels

func (c *Client) Channels(ctx context.Context, class outbound.Class, teamID string) ([]Channel, Result)

Channels reads the channels of the team teamID that the bot is a member of.

func (*Client) DryProbe

func (c *Client) DryProbe(ctx context.Context, class outbound.Class) (Result, string)

DryProbe is `GET <server>/api/v4/system/ping` without the token (C-13.FR-2), which a Mattermost server answers to anyone. The Result is the raw answer with its body, which the check names, with the media type of the answer, empty without one; a 429 is Transient, never a RetryAfter.

func (*Client) Grants

func (c *Client) Grants(ctx context.Context, class outbound.Class, u User, permission string) (bool, Result)

Grants reports whether the system roles of u grant permission, as the server decides it for u's requests (F-064): one read of the roles, POST /api/v4/roles/names, of which any role that is not deleted holds permission. A user without roles is granted nothing and needs no read.

func (*Client) Me

func (c *Client) Me(ctx context.Context, class outbound.Class) (User, Result)

Me reads the bot's own user: the check of its token.

func (*Client) Member

func (c *Client) Member(ctx context.Context, class outbound.Class, channelID string) Result

Member reads the bot's membership of the channel channelID; a channel without the bot answers 404 or 403.

func (*Client) Team

func (c *Client) Team(ctx context.Context, class outbound.Class, teamID string) (Team, Result)

Team reads the team teamID.

func (*Client) Teams

func (c *Client) Teams(ctx context.Context, class outbound.Class) ([]Team, Result)

Teams reads the teams the bot belongs to.

func (*Client) UserByUsername

func (c *Client) UserByUsername(ctx context.Context, class outbound.Class, username string) (User, Result)

UserByUsername reads the user username, which Mattermost matches without case; an unknown one answers 404.

func (*Client) Via

func (c *Client) Via() string

Via is how the requests of the client travel: ViaDirect or ViaProxy.

type Commands

type Commands interface {
	Acknowledge(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
	Unacknowledge(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
	Resolve(ctx context.Context, c groups.Caller, publicID string, note *string) (groups.Result, error)
	Snooze(ctx context.Context, c groups.Caller, publicID string, end groups.SnoozeEnd) (groups.Result, error)
	Unsnooze(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
	AnswerReminder(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
}

Commands are the Commands a button runs; *groups.Service implements it.

type Connection

type Connection struct {
	ID        int64
	PublicID  string
	BotUserID string
	Client    *Client
}

Connection is a Mattermost Connection as the callback of its button presses needs it: BotUserID is the user id of its bot, which a Connection check learns, empty before one did.

type Connections

type Connections interface {
	Connection(ctx context.Context, publicID string) (Connection, error)
}

Connections find the Connection of a callback; *connections.Service implements it.

type LinkBots

type LinkBots struct {
	Conns Connections
	Path  Path
}

LinkBots run the calls of an Account link through the bot of a Mattermost Connection (C-18.FR-3, FR-11): the lookup of the account by its username and the bot's direct messages, on the interactive path, never as a delivery. They implement accountlinks.MattermostBots.

func (LinkBots) Session

func (l LinkBots) Session(ctx context.Context, publicID string,
	f func(ctx context.Context, b accountlinks.MattermostBot) error) error

Session takes one limiter token of the Connection publicID on the interactive path and runs f with its bot; a 429 that a call of f gets holds the Connection. A Connection that is unknown, deleted or not a Mattermost one is accountlinks.ErrNoConnection; no token within the budget is a *delivery.LimitedError and runs nothing.

type Links interface {
	Lookup(ctx context.Context, identitySpace, externalID string) (accountlinks.User, error)
}

Links map a Mattermost account to its User; *accountlinks.Service implements it.

type Network

type Network struct {
	Policy   outbound.PolicySource
	Log      *logging.Logger
	Real     clock.Clock
	Resolver outbound.Resolver
	Recorder outbound.Recorder
}

Network is what a Client needs besides its Connection: the outbound address policy, the logger, the real clock of the outbound metrics, a resolver (nil: the system resolver) and the Request log, nil for none (C-23.FR-1).

type Path

type Path interface {
	Do(ctx context.Context, s delivery.Subject, op delivery.Op) (delivery.Outcome, error)
}

Path is the interactive path, declared by its consumer; *delivery.Interactive implements it.

type PressWaits

type PressWaits struct {
	// Notify sends payload on a LISTEN/NOTIFY channel: pg_notify through the main pool.
	Notify func(ctx context.Context, channel, payload string) error
	// contains filtered or unexported fields
}

PressWaits connect the bot's press of a test message, which reaches the callback of any replica, with the test that waits for it: the callback sends the test's nonce on TestPressChannel through Notify, and every replica's listener hands it to Arrived, which ends the wait of that nonce on the replica running the test.

func (*PressWaits) Arrived

func (w *PressWaits) Arrived(payload string)

Arrived ends the wait of the nonce payload, if this replica runs its test.

func (*PressWaits) Pressed

func (w *PressWaits) Pressed(ctx context.Context, nonce string) error

Pressed reports the bot's press of the test message of nonce to every replica.

type Probe

type Probe struct {
	OK      bool
	Latency time.Duration
	Message string
	Code    string
}

Probe is the result of a dry probe: whether it passed, its latency on the real clock, and when it failed what answered, in English, with its code, which clients translate.

func RunDryProbe

func RunDryProbe(ctx context.Context, c *Client, run Runner, realClock clock.Clock) (Probe, error)

RunDryProbe makes the dry probe of c through run (C-13.FR-2): `GET <server>/api/v4/system/ping` without the token, timed on the real clock, on a client that may have none. It passes on a 200 JSON answer whose status is OK and otherwise names what answered, a server it could not reach as delivery.FailureMessage does, without the server's name through a proxy, whose own name is the one that did not resolve. Its error is the runner's own.

type Result

type Result struct {
	Outcome delivery.Outcome
	Status  int
	ErrorID string
	Body    []byte
	Network string
	Blocked bool
}

Result is how a call ended: its outcome for delivery, which classifies the answer as C-13.FR-5 says, the status of the answer, 0 without one, the error id Mattermost answered with, such as api.context.permissions.app_error, and the body of the answer as received, which only a Destination test shows, masked (C-16.FR-2); when the call got no answer, what failed (outbound.Network*), and whether the outbound address policy refused the address.

func (Result) FailureCode

func (r Result) FailureCode() string

FailureCode is the check code of a call that failed for a reason its check does not name (delivery.FailureCode).

func (Result) OK

func (r Result) OK() bool

OK reports whether the call succeeded.

type Role

type Role struct {
	Name        string   `json:"name"`
	Permissions []string `json:"permissions"`
	DeleteAt    int64    `json:"delete_at"`
}

Role is a Mattermost role with its permissions; a DeleteAt other than 0 grants nothing.

type Route

type Route func(serverURL string, token logging.Secret) string

Route names the address a Connection's requests go to instead of its server URL, by that URL and the bot token: under `muster dev` the first fake Mattermost server for https://chat.example.org with one of its published tokens; an empty answer is the Connection's own server URL.

type Runner

type Runner func(ctx context.Context, f func(ctx context.Context, c delivery.Call) delivery.Outcome) (delivery.Outcome,
	error)

Runner makes one request of a check with the Call it is made in: on the interactive path when a person waits for it, directly in the delivery client class for the Broken probe. Its error is the runner's own — no limiter token within the budget, a failed limiter — and ends the check unfinished.

func Direct

func Direct(c delivery.Call) Runner

Direct is the Runner that calls at once with c: the Broken probe and muster doctor, which wait for no token.

func Interactive

func Interactive(in Path, s delivery.Subject) Runner

Interactive is the Runner of a check a person waits for: each request through the interactive path, limited by s.

type Settings

type Settings struct {
	ServerURL string
	Token     logging.Secret
	Proxy     *outbound.Proxy
	Owner     outbound.Owner
	Route     Route
}

Settings are a Connection as its client needs it: the server URL, the bot token and the proxy, nil for none; the Connection whose Request log keeps its requests, none for a client that records nothing; and the Route of `muster dev`, nil outside it.

type Step

type Step struct {
	Name    string
	OK      bool
	Message string
	Code    string
	Outcome delivery.Outcome
}

Step is one step of a check: its name, whether it passed, and when it failed the message for the person, in English, its code, which clients translate, and the outcome for delivery.

type Target

type Target struct {
	Client             *Client
	ConnectionID       int64
	ConnectionPublicID string
	TeamID             string
	TeamName           string
	ChannelID          string
	// BotUserID is the user id of the Connection's bot once a check learned it, empty before.
	BotUserID string
}

Target is where a Mattermost Destination posts: the client of its Connection, the Connection's id and public_id, and the team and channel of the Destination.

type Targets

type Targets interface {
	Target(ctx context.Context, destinationID int64) (Target, error)
}

Targets find the Target of a Destination by its id, declared by their consumer; *connections.Service implements them. A Destination without one is ErrNoTarget.

type Team

type Team struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	DisplayName string `json:"display_name"`
}

Team is a Mattermost team: Name is its URL name, the team_domain of a press.

type TestPresses

type TestPresses interface {
	Pressed(ctx context.Context, nonce string) error
}

TestPresses tell the waiting Destination test that the bot pressed its test message, declared by their consumer, the callback; *PressWaits implements them.

type TestRenderer

type TestRenderer interface {
	TestRoot(src *messages.Source, markup messages.Markup, destination string) messages.Rendered
}

TestRenderer renders the Root message of a test or a preview, declared by its consumer; *messages.Renderer implements it.

type Tester

type Tester struct {
	Adapter  *Adapter
	Path     Path
	Renderer TestRenderer
	Waits    *PressWaits
	Budget   time.Duration
	Real     clock.Clock
}

Tester is the Destination test and the preview of Mattermost Destinations, on the interactive path Path, each step within Budget (delivery.interactive_budget; zero is delivery.InteractiveBudget), timed on the real clock Real.

func (*Tester) Preview

func (t *Tester) Preview(ctx context.Context, in delivery.TestInput) ([]delivery.PreviewItem, error)

Preview renders, without sending anything, the Root message of the source of in as the Mattermost Destination would receive it (C-16.FR-4): the item message in Markdown, its text the post's message and its request the post, with the attachment, as it would be created, with the buttons a test message would carry, whose presses change nothing.

func (*Tester) Test

Test runs the test of the Mattermost Destination of in (C-16.FR-1, FR-3): the step message and, once it was posted with a button, the step press, which fails without pressing while the bot of the Connection is not known. A Destination whose Connection cannot be read fails the step message.

type User

type User struct {
	ID       string `json:"id"`
	Username string `json:"username"`
	IsBot    bool   `json:"is_bot"`
	// Roles are the user's system roles, separated by spaces, such as "system_user".
	Roles    string `json:"roles"`
	DeleteAt int64  `json:"delete_at"`
}

User is a Mattermost user as the API answers it; a DeleteAt other than 0 is a deactivated account.

Jump to

Keyboard shortcuts

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