Documentation
¶
Overview ¶
Package outbound is the only code that makes outbound HTTP requests (ADR-0015, C-02.FR-20 to FR-22): clients are built per client class with a connect timeout and an overall timeout, never follow redirects, name Muster and its version in the User-Agent of every request and every CONNECT to a proxy, classify every answer into an outcome, retry by the policy of their class, redact registered secrets from everything they log and return, count their requests in the muster_client_* metrics, and connect only to addresses that pass the Organization's outbound address policy, directly or through their own proxy. No other package creates an http.Client or an http.Transport (architecture lint 4).
Index ¶
- Constants
- Variables
- func AlwaysBlocked() []string
- func CloseIdleConnections()
- func MaskHeaders(h http.Header, redact func(string) string) http.Header
- func StartCheck(ctx context.Context, kind string, destination int64) (context.Context, string)
- func WithLinks(ctx context.Context, l Links) context.Context
- func WithSecrets(ctx context.Context, secrets ...logging.Secret) context.Context
- type BlockedError
- type BodyClassifier
- type BodyError
- type Class
- type Client
- type Config
- type Entry
- type Error
- type Links
- type Mapping
- type Mode
- type Outcome
- type Owner
- type Policy
- type PolicySource
- type Proxy
- type ProxyType
- type Record
- type Recorder
- type Request
- type Resolver
- type Result
- type Untrusted
- type WebSocket
Constants ¶
const ( NetworkDNS = "dns" NetworkTLS = "tls" NetworkTimeout = "timeout" // NetworkProxyAuth is a proxy that refused the client's credentials: 407 to an HTTP CONNECT, or a SOCKS5 proxy // that refused the username and password. NetworkProxyAuth = "proxy_auth" // NetworkConnect is any other failure to connect or to read the answer, such as a refused connection. NetworkConnect = "connect" )
What failed when a request got no answer (Error.Network).
const ( CheckConnection = "connection_check" CheckDraft = "draft_check" CheckDestination = "destination_check" CheckTest = "test" CheckProbe = "probe" )
The kinds of checks and tests whose requests a record marks (C-23.FR-2).
const ( ViaDirect = "direct" ViaProxy = "proxy" )
The paths of a request (ConnectionPath): direct, or through the client's proxy.
const DefaultMaxBodyBytes = 8 << 20
DefaultMaxBodyBytes is how much of an answer a client reads unless its configuration says otherwise.
Variables ¶
var Classes = []Class{ClassDelivery, ClassInteractive, ClassBackground, ClassHeartbeat}
Classes are the client classes, the closed set of the metric label client.
var MaskedHeaders = []string{"Authorization", "Proxy-Authorization", "Cookie", "Set-Cookie",
"X-Telegram-Bot-Api-Secret-Token", "Webhook-Signature", "X-Slack-Signature"}
MaskedHeaders are the headers whose values every record shows as [redacted], whatever they hold (C-23.FR-3): the credentials of the request and of the proxy, cookies, Telegram's webhook secret token, the signature of an outgoing webhook or a Bridge push, and Slack's signature of a press (C-24.FR-14).
var Outcomes = []Outcome{OutcomeOK, OutcomeRetryAfter, OutcomeTransient, OutcomeFatal, OutcomeUnknown, OutcomeBlocked, OutcomeRedirect}
Outcomes is the closed set of outcomes.
Functions ¶
func AlwaysBlocked ¶
func AlwaysBlocked() []string
AlwaysBlocked lists the rules that always apply, each with its networks, for the policy as the API shows it.
func CloseIdleConnections ¶
func CloseIdleConnections()
CloseIdleConnections makes every client use a new transport from its next request on, so that the request dials again and its address is checked against the policy in force: the policy is checked when a connection is dialled, and a pooled connection opened under an older policy, idle or still serving another request, would otherwise carry a request past a stricter one. Each client compares the generation this moves with the one its transport was built for; when it moved, the client builds a fresh transport and closes the idle connections of the old one. Requests in flight finish on the old transport, which no new request reaches, and its remaining connections close when idle. Nothing keeps the clients, so a client its owner dropped is not kept alive.
func MaskHeaders ¶
MaskHeaders is a copy of h with the values of MaskedHeaders replaced by [redacted] and every other name and value passed through redact; nil stays nil.
func StartCheck ¶
StartCheck is ctx under a new check run of kind, about the Destination destination, 0 for none, and the run: the public_id with the prefix CR that the records of every request made under ctx share (C-23.FR-2, FR-5).
func WithLinks ¶
WithLinks is ctx with the links of the requests made under it. Links that name no check keep the check and run of ctx, so that the requests of a check or a test keep them under the links a delivery attempt within it sets.
func WithSecrets ¶
WithSecrets is ctx with secrets added to those of the requests made under it, which their records mask besides the client's own: an Account link code in a direct message, the secret token of setWebhook.
Types ¶
type BlockedError ¶
type BlockedError struct {
Rule string
}
BlockedError is a request refused by the outbound address policy; Rule names the rule that refused it.
func (*BlockedError) Error ¶
func (e *BlockedError) Error() string
type BodyClassifier ¶
BodyClassifier finds an error in the body of an answer; ok is false when the body reports none. It runs inside the attempt on every answer, so an error inside a successful answer is classified like a status code.
type BodyError ¶
type BodyError struct {
// Code is the status code the body reports; the mapping classifies it like the status of the answer.
Code int
// RetryAfter is the delay the body asks for, used exactly when positive.
RetryAfter time.Duration
// Text is the provider's error text.
Text string
}
BodyError is an error the provider reports in the body of its answer, such as Telegram's ok: false with its error_code, description and parameters.retry_after.
type Class ¶
type Class string
Class is a client class (ADR-0015): it follows who waits for the result and sets the retry policy.
const ( // ClassDelivery makes one attempt; the classified outcome goes back to the caller's delivery row. ClassDelivery Class = "delivery" // ClassInteractive makes one attempt within the budget the caller's context gives. ClassInteractive Class = "interactive" // ClassBackground retries with exponential backoff, jitter and a cap until its context ends. ClassBackground Class = "background" // ClassHeartbeat makes one attempt with a short timeout; the next tick is the retry. ClassHeartbeat Class = "heartbeat" )
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client makes the requests of one client configuration.
type Config ¶
type Config struct {
Class Class
// ConnectTimeout bounds name resolution, the connection and the TLS handshake, to the proxy when there is one.
ConnectTimeout time.Duration
// Timeout bounds each attempt, from the dial to the end of the answer's body.
Timeout time.Duration
// Proxy is the client's own proxy; nil connects directly.
Proxy *Proxy
// Secrets are replaced with [redacted] in every log line and every returned error; the proxy's password is added.
Secrets []logging.Secret
// BaseURL, when set, is the only address the client sends to: request URLs are paths below it, its own path
// prefix included.
BaseURL string
// Policy gives the outbound address policy in force.
Policy PolicySource
Logger *logging.Logger
// Clock is the real clock: Retry-After dates and the duration of requests.
Clock clock.Clock
// Resolver resolves host names; nil is the system resolver.
Resolver Resolver
// MaxBodyBytes is the largest answer read; 0 is DefaultMaxBodyBytes.
MaxBodyBytes int64
// Recorder, with an Owner that names a Connection, an outgoing webhook Destination or a draft, gets the record of
// each attempt (C-23.FR-1); without either the client records nothing.
Recorder Recorder
Owner Owner
}
Config is the configuration of one client.
type Entry ¶
type Entry struct {
// contains filtered or unexported fields
}
Entry is one entry of the allowed or denied list: a network in CIDR form (a bare address is a network of one), a host name such as chat.example.org, matched exactly, or a domain written *.example.org, which matches every name below example.org but not example.org itself.
func ParseEntry ¶
ParseEntry parses an entry of the allowed or denied list.
type Error ¶
type Error struct {
Outcome Outcome
RetryAfter time.Duration
// Rule names the rule of the outbound address policy that blocked the request.
Rule string
// Status is the status code of the answer, 0 without one.
Status int
ProviderError Untrusted
// Network is what failed when the request got no answer, one of the Network constants, empty otherwise; Detail is
// the redacted text of that failure without the request, such as the TLS error.
Network string
Detail string
// contains filtered or unexported fields
}
Error is a request that did not end with ok. Its text is redacted; it wraps only the context's error, when the context ended.
type Links ¶
Links are what a request concerns besides its owner: the Destination and the Alert Group of a delivery, 0 for none, and for a request of a check or a test its kind and its check run, the public_id its requests share.
type Mapping ¶
Mapping classifies a status code; retryAfter is the delay the answer asked for, valid when hasRetryAfter. Callers replace DefaultMapping with their own (C-13, C-14, C-15). A mapping that classifies 409 Conflict as transient makes the background class only back off.
type Outcome ¶
type Outcome string
Outcome is the classified result of a request (C-02.FR-20), the closed set of the metric label outcome.
const ( OutcomeOK Outcome = "ok" OutcomeRetryAfter Outcome = "retry_after" OutcomeTransient Outcome = "transient" OutcomeFatal Outcome = "fatal" // OutcomeUnknown is an answer the mapping does not know; it is never retried. OutcomeUnknown Outcome = "unknown" // OutcomeBlocked is a request the outbound address policy refused. OutcomeBlocked Outcome = "blocked" // OutcomeRedirect is a 3xx answer, never followed. OutcomeRedirect Outcome = "redirect" )
func DefaultMapping ¶
DefaultMapping is the mapping of C-02.FR-20: 2xx is ok; 429 or 503 with Retry-After is retry_after; 408, 500, 502, 503 without Retry-After and 504 are transient; 400, 401, 403 and 404 are fatal; anything else is unknown.
type Owner ¶
Owner is whose Request log a client's requests go to, by internal id: a Connection or an outgoing webhook Destination; or, with Draft, nobody: the client of a check before saving of a new Connection, whose records are read by their check run and bounded per Organization (C-23.FR-4, FR-5). PublicID names it in the log line of a record that could not be written.
type PolicySource ¶
PolicySource gives the policy in force; the Organization's cached policy implements it.
func StaticPolicy ¶
func StaticPolicy(p Policy) PolicySource
StaticPolicy is a source that always gives p.
type Proxy ¶
type Proxy struct {
Type ProxyType
// Address is host:port.
Address string
Username string
Password logging.Secret
}
Proxy is a client's own proxy (C-02.FR-22). The password is a Secret decrypted with the Keyring only to build the client. Proxies from the environment (HTTP_PROXY, HTTPS_PROXY, NO_PROXY) are never consulted.
type Record ¶
type Record struct {
Owner Owner
Links Links
Operation string
Method string
URL string
RequestHeader http.Header
RequestBody []byte
Status int
ResponseHeader http.Header
ResponseBody []byte
// Latency is measured on the client's real clock.
Latency time.Duration
Via string
Attempt int
Outcome Outcome
Network string
Error string
}
Record is one attempt of a request, as the Recorder gets it: its URL as errors show it, its headers as sent and its bodies, all masked of the client's and the request's Secrets, of a base URL's path prefix of at least minSecretPrefix bytes and of MaskedHeaders, with Location and Content-Location shown as the URL is. Status is 0, and the answer's header and body nil, when the attempt got no answer; Outcome is ok for an attempt that succeeded, and Network and Error say what failed otherwise.
type Recorder ¶
Recorder keeps the record of each attempt of a client that has one and an owner (C-23.FR-1): the Request log. It gets the record after the attempt has its outcome and fails nothing: a record it cannot keep is its own concern.
type Request ¶
type Request struct {
Method string
URL string
Header http.Header
Body []byte
// Mapping replaces DefaultMapping.
Mapping Mapping
// ClassifyBody finds errors the provider reports in the body; nil reads none.
ClassifyBody BodyClassifier
// Operation names the request in the Request log as its protocol names it, such as createPost or getUpdates.
Operation string
// SkipRecord, when set, says of an attempt that succeeded, by its status and body, that the Request log leaves it
// out, as it does a long poll that ended without events; a failed attempt is always recorded.
SkipRecord func(status int, body []byte) bool
}
Request is one request. URL is absolute, or a path below the base URL when the client has one.
type Resolver ¶
type Resolver interface {
LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
}
Resolver resolves host names; *net.Resolver implements it.
type Result ¶
type Result struct {
Outcome Outcome
Status int
Header http.Header
Body []byte
// RetryAfter is the exact delay asked for when Outcome is retry_after.
RetryAfter time.Duration
// ProviderError is the provider's error text, untrusted and redacted.
ProviderError Untrusted
Attempts int
}
Result is what a request ended with. Body and Header are those of the last answer, if there was one.
type Untrusted ¶
type Untrusted string
Untrusted is text that comes from the provider: escape it wherever it is shown, and never act on it.
type WebSocket ¶
WebSocket is an open WebSocket connection with the TCP connection it was dialled on, which Cut closes at once. Only DialWebSocket builds one that Cut can close; Cut on any other does nothing.
func DialWebSocket ¶
func DialWebSocket(ctx context.Context, c *Client, rawURL string, header http.Header) (*WebSocket, error)
DialWebSocket opens a WebSocket connection to rawURL, ws or wss, for the client c (ADR-0015, C-02.FR-20): through c's dialer, which checks the outbound address policy after name resolution, and c's proxy — an HTTP or HTTPS proxy by CONNECT whatever the target's scheme, so that no request in absolute form carries the upgrade, a SOCKS5 proxy as for every request — with c's connect timeout for the connection, a TLS handshake and the CONNECT, c's overall timeout for the handshake, Muster's User-Agent unless header names one, and no redirect. The handshake is one request in muster_client_requests_total and muster_client_request_duration_seconds under c's class; it is not recorded in the Request log. Every failure is an *Error whose text shows the address with its query as [redacted], with c's secrets and the query's values replaced. ctx bounds only the handshake: reading, writing, pinging and closing the connection, and its read limit, are the caller's.
func (*WebSocket) Cut ¶
func (w *WebSocket) Cut()
Cut closes the TCP connection at once, without a word to the peer, not even TLS's close_notify. Unlike Conn.CloseNow, which waits for a Close already under way, it also ends a Close whose peer does not answer, which otherwise waits for the answer up to the library's own five seconds. It frees nothing else: the caller still calls Close or CloseNow.