connectors

package
v0.258.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 35 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 connectors is muster's secure connector store: named credentials for external platforms that agents USE without ever HOLDING.

🔴 THE SECRET NEVER ENTERS AN AGENT POD. An agent reaches a platform through muster's proxy — /connect/{connector}/{host}/{path} — and muster injects the credential (a bearer token, a custom header, or HTTP basic) on the way out (proxy.go). The secret is stored only as AES-256-GCM ciphertext (seal.go) and no API, page or log line ever returns it after it was entered: the Connector type has no field that could carry it.

⚠ A RESPONSE IS NOT A GUARANTEED-CLEAN CHANNEL. An upstream that reflects the request (an echo endpoint, an error quoting a header) could hand the credential back; the proxy redacts the forms it knows and refuses the response shapes that would bypass that (proxy.go, secretForms). That is defence in depth, not a proof — the guarantee is that the secret is never in the pod, and only an approved agent reaches only the connector's own hosts.

🔴 ACCESS IS RECORDED PER AGENT, BUT AN APPROVAL IS SHARED BY THE OWNER'S AGENTS. Any agent may ASK for any connector by name (an officer instance only for `github` and the connectors its officer declares: internal/api officerConnectorRefusal); the first ask files a pending Grant. When the owner approves one, a StandingGrant is recorded for the owner, keyed on the connector, its credential source and — for the GitHub App's one-repository token — the agent's repository: a later request from ANY of the owner's agents with the same key is approved at request time (decided_via 'standing', naming the standing grant), and requests already waiting with that key are approved in the same step (never for a worker-pool member or an officer instance: internal/api excludedFromSharing). Only when no standing grant matches is the owner prompted. An approved agent keeps access until it is destroyed (the grant row cascades with the agent), the grant or its standing grant is revoked, the connector is deleted (its grants and standing grants go with it), or its grant is re-opened because the connector's credential source (0033) or the agent's repository (0061) changed (ReconcileGrant). There is no time-based expiry. A denial is final for that request, and is never shared.

⚠ HTTP, PLUS ONE DATABASE KIND THAT NEVER LEAVES muster-server. HTTPS APIs and git's smart-HTTP protocol go through the proxy. A SchemePostgres connector is not proxied at all: muster-server itself connects to the database and runs one read-only statement per call (PostgresExecutor, postgres.go), and the agent gets rows back — never the password, never a socket. The HTTP proxy refuses a postgres connector. Other non-HTTP platforms (SSH) remain out of scope: a "handout" scheme would hand the secret to the pod and would need its own opt-in, warning and audit shape — nothing accepts one.

Index

Constants

View Source
const (
	StatusPending  = "pending"
	StatusApproved = "approved"
	StatusDenied   = "denied"
	StatusRevoked  = "revoked"
)

Grant statuses (mirrors the connector_grants.status CHECK constraint).

View Source
const (
	SourceStored = "stored"
	SourceApp    = "app"
)

Grant sources: which credential an approval was about.

View Source
const (
	InternalHTTPDefaultPrefix = "/v1/"
	// InternalHTTPDefaultMaxResponseBytes fits a full-page PNG screenshot.
	InternalHTTPDefaultMaxResponseBytes = 8 << 20
	InternalHTTPMinMaxResponseBytes     = 1 << 10
	InternalHTTPMaxMaxResponseBytes     = 32 << 20
	InternalHTTPDefaultTimeout          = 30 * time.Second
	InternalHTTPMaxTimeout              = 300 * time.Second
	// InternalHTTPMaxRequestBytes caps a POST body.
	InternalHTTPMaxRequestBytes = 1 << 20
	InternalHTTPMaxPathBytes    = 2048
	InternalHTTPMaxQueryParams  = 32
	InternalHTTPMaxQueryValue   = 1024
)

The internal_http connector's limits and defaults.

View Source
const (
	PGDefaultPort             = 5432
	PGDefaultStatementTimeout = 5 * time.Second
	PGMinStatementTimeout     = 100 * time.Millisecond
	PGMaxStatementTimeout     = 30 * time.Second
	// PGLockTimeout is lock_timeout, or the statement timeout when that is
	// shorter.
	PGLockTimeout     = 2 * time.Second
	PGDefaultMaxRows  = 200
	PGMaxRowsCap      = 1000
	PGDefaultMaxBytes = 256 << 10
	PGMinMaxBytes     = 1 << 10
	PGMaxBytesCap     = 1 << 20
	// PGPoolMaxConns is the per-connector connection pool's size.
	PGPoolMaxConns  = 2
	PGMaxSQLBytes   = 16 << 10
	PGMaxParams     = 64
	PGMaxParamBytes = 8 << 10
	// PGDefaultRatePerMinute and PGDefaultBurst are the per-agent token
	// bucket: a sustained rate and how many calls may arrive at once.
	PGDefaultRatePerMinute = 30
	PGDefaultBurst         = 10
)

The postgres connector's hard limits and defaults. A connector may lower a cap (PostgresSettings); nothing raises one past these.

View Source
const (
	// GitHubGitHost and GitHubAPIHost are the hosts a standing public read is
	// served on unless the Proxy names others (Proxy.GitHubGitHost).
	GitHubGitHost = "github.com"
	GitHubAPIHost = "api.github.com"
)
View Source
const DecidedByStanding = "standing-grant"

DecidedByStanding is decided_by on a grant approved by a standing grant. It is deliberately not "operator": the owner did not decide this request.

View Source
const DecidedViaMCP = "mcp"

DecidedViaMCP is decided_via for a decision made through connector_request_decide, from one of the operator's own mirrored Claude Code sessions (migration 0035).

View Source
const DecidedViaStanding = "standing"

DecidedViaStanding is decided_via for a grant approved automatically by a StandingGrant (migration 0043): no human decided THIS request — the owner approved an earlier one with the same key. decided_by is DecidedByStanding.

View Source
const InternalHTTPTokenEnvPrefix = "MUSTER_INTERNAL_HTTP_TOKEN_"

InternalHTTPTokenEnvPrefix is where each connector's bearer token is read from: MUSTER_INTERNAL_HTTP_TOKEN_<NAME>, NAME upper-cased with every non-alphanumeric byte written as '_' (app-driver → APP_DRIVER).

View Source
const InternalHTTPTool = "internal_http_request"

InternalHTTPTool is the one tool that uses an internal_http connector.

View Source
const KeySize = 32

KeySize is the encryption key's length: AES-256.

View Source
const KubeReadName = "kube-read"

KubeReadName is the kube-read connector's name (officers.KubeConnector names the same connector for the officer configuration).

View Source
const KubeReadTool = "officer_kube_read"

KubeReadTool is the one tool that uses the connector, named in the proxy's refusal.

View Source
const MaxAfterForwardBody = 1 << 20

MaxAfterForwardBody bounds ForwardResult.Body.

View Source
const MaxAuditDetailBytes = 500

MaxAuditDetailBytes is how much of an audit entry's Detail is stored.

View Source
const MaxPendingGrantsPerAgent = 5

MaxPendingGrantsPerAgent is how many requests one agent may have waiting on the operator at once.

🔴 EVERY NEW REQUEST PUSHES A NOTIFICATION. Without a cap, an agent looping over invented connector names (or a client retrying across names) files a row and buzzes the operator's phone per name. Past the cap a request is refused with ErrTooManyPending: nothing is filed and nothing is pushed. A request for a connector the agent ALREADY has a live grant for is answered with that grant and does not count.

View Source
const MinSecretLen = 8

MinSecretLen is the shortest secret accepted. It is a floor on what the proxy can REDACT: a response that reflects the credential has the forms the redactor knows replaced (proxy.go, secretForms), and replacing a two-character string would mangle bodies while protecting nothing.

View Source
const RedactedMarker = "[REDACTED-BY-MUSTER]"

RedactedMarker replaces every occurrence of the credential in a response.

View Source
const ReopenedDestinationChanged = "re-opened: the connector's configured service (base URL or path prefix) changed"

ReopenedDestinationChanged is ReconcileGrant's reason for an internal_http grant approved for another destination. It names neither: an address is never in an agent-visible line.

View Source
const ReopenedSourceChanged = "re-opened: the connector's credential source changed"

ReopenedSourceChanged is ReconcileGrant's reason for a changed credential source.

Variables

View Source
var ErrDecrypt = errors.New("connectors: the stored secret could not be decrypted with the configured key")

ErrDecrypt is returned when a stored secret does not open under the configured key — the wrong key, a ciphertext that was moved to another row, or a row whose bound fields (binding) were changed after the secret was sealed.

🔴 IT FAILS CLOSED: no fallback key, no plaintext column, no "try without additional data". The proxy answers 502 and forwards nothing.

View Source
var ErrForbiddenAddress = safedial.ErrForbiddenAddress

ErrForbiddenAddress is the dial refusal for a non-public destination (internal/safedial's, so errors.Is matches whichever dialer refused).

View Source
var ErrGateConflict = fmt.Errorf("%w: the change conflicts with it", ErrGateRefused)

ErrGateConflict is a Gate's refusal of a write whose CONTENT conflicts with the policy (a forbidden path, a secret shape): answered 409, not 403. It wraps ErrGateRefused, so every check for a refusal still sees one.

View Source
var ErrGateQueued = errors.New("connectors: accepted and queued by this agent's write policy")

ErrGateQueued is a Gate's answer to a write it did NOT forward but recorded, to be made later by muster itself (a draft officer's pull request held back by its open cap: internal/officership's queue). It is answered 202 Accepted with a QueuedBody whose message is the error's text, so the agent reads "accepted, later" rather than a refusal to escalate. It does not wrap ErrGateRefused: nothing was refused.

View Source
var ErrGateRefused = errors.New("connectors: refused by this agent's write policy")

ErrGateRefused is a Gate's refusal of one request.

View Source
var ErrInvalid = errors.New("connectors: invalid")

ErrInvalid wraps every validation refusal, so a handler can answer 400.

View Source
var ErrManaged = fmt.Errorf("%w: this connector is provided by the server's configuration", ErrInvalid)

ErrManaged refuses an operator write to a virtual connector's name.

View Source
var ErrNotFound = errors.New("connectors: not found")

ErrNotFound is returned when a connector or grant does not exist.

View Source
var ErrNotPending = errors.New("connectors: the request is no longer pending")

ErrNotPending is returned when a decision targets a grant that was already decided (or revoked).

View Source
var ErrNotPostgres = fmt.Errorf("%w: that connector is not a postgres connector", ErrInvalid)

ErrNotPostgres is a postgres query naming a connector of another scheme.

View Source
var ErrRateLimited = errors.New("connectors: too many queries from this agent; wait a few seconds and try again")

ErrRateLimited is a postgres query refused by the per-agent rate limit.

View Source
var ErrRoleUncertain = errors.New("connectors: the agent's owner's role could not be read; retry shortly")

ErrRoleUncertain refuses access decided on a fallback role (the caller's owner's role could not be read). Retryable.

View Source
var ErrTargetRefused = errors.New("connectors: refused for this agent")

ErrTargetRefused is a virtual connector's refusal of one request's target.

View Source
var ErrTooManyPending = fmt.Errorf("connectors: this agent already has %d requests waiting for the operator; "+
	"wait for them to be decided (or ask the operator) before requesting another connector", MaxPendingGrantsPerAgent)

ErrTooManyPending is the refusal past MaxPendingGrantsPerAgent.

View Source
var GitHubPreset = Preset{
	Key:         "github",
	Label:       "GitHub",
	Hosts:       []string{"api.github.com", "github.com"},
	Scheme:      SchemeBasic,
	Username:    "x-access-token",
	SecretLabel: "Personal access token",
	Help: "A fine-grained personal access token scoped to the repositories the agents should reach " +
		"(Contents read/write, Pull requests read/write, Metadata read). It is used for the REST API " +
		"and for git over HTTPS.",
}

GitHubPreset covers the REST API and git's smart-HTTP protocol.

🔴 BASIC WITH USERNAME `x-access-token`, NOT BEARER, BECAUSE ONE CONNECTOR SERVES BOTH HOSTS. git over HTTPS to github.com authenticates with basic auth (token as the password); api.github.com accepts the same basic pair as well as a bearer header. Basic is the one shape both accept.

View Source
var InternalHTTPMethods = []string{http.MethodGet, http.MethodPost, http.MethodDelete}

InternalHTTPMethods are the methods a call may use.

View Source
var PGSSLModes = []string{"disable", "prefer", "require", "verify-ca", "verify-full"}

PGSSLModes are the sslmode values a postgres connector may use. allow is left out (it tries plaintext first); verify-ca and verify-full verify against the system roots — muster-server holds no client certificate or root file.

View Source
var PostgresPreset = Preset{
	Key:         "postgres",
	Label:       "PostgreSQL (read-only SQL)",
	Scheme:      SchemePostgres,
	SecretLabel: "Database password",
	Help: "muster-server connects to the database itself and runs each agent query as ONE statement inside " +
		"BEGIN READ ONLY, with a statement timeout and row and byte caps; the agent gets rows, never the password. " +
		"Use a dedicated login role with no table grants (docs/connectors.md has the recipe). Admins only.",
}

PostgresPreset is the database connector (postgres.go). It has no fixed hosts: the form asks for the host, port, database, user and TLS settings.

View Source
var VirtualCreatedAt = time.Now()

VirtualCreatedAt is a stable "created" time for a virtual connector's description: when this process started.

Functions

func AfterForwardOf added in v0.156.0

func AfterForwardOf(r *http.Request) func(ctx context.Context, res ForwardResult)

AfterForwardOf is the function WithAfterForward attached to r, nil when none.

func AuditWithID added in v0.153.0

func AuditWithID(ctx context.Context, s Store, e AuditEntry) (int64, error)

AuditWithID appends e to s and returns its row id when s (or the store a virtual connector wraps) can say it, else 0 after a plain Audit. Kept off the Store interface on purpose: only officer_kube_read needs the id.

func GitHubGrantLookup

func GitHubGrantLookup(s Store) func(ctx context.Context, agentID int64) (string, error)

GitHubGrantLookup answers, for one agent, the connector of an APPROVED grant it holds that reaches GitHub (ReachesGitHub), or "" when it holds none.

A nil store is a deployment with no connector store: no grant can exist, so the answer is always "". That is stated here rather than left to a nil check at the caller, so the caller can treat a MISSING lookup as unknown.

func GitHubTargetRepo added in v0.221.0

func GitHubTargetRepo(gitHost, apiHost, host, rest string) (repo string, scoped bool, err error)

GitHubTargetRepo is the repository a request for host/rest (rest escaped, no leading slash) targets on GitHub, gitHost and apiHost being the platform's git and API hosts. scoped is false for an API path that names no repository (/graphql, /rate_limit, /user …).

The path is FULLY percent-decoded first and compared without case, as GitHub routes it:

  • gitHost: every path is <owner>/<repo>[.git]/… (git's smart-HTTP protocol, and the web URLs). A path with fewer segments is refused.
  • apiHost: /repos/<owner>/<repo>/… (any case) names a repository; /repositories/<id>/… is REFUSED (an id muster cannot match without another API call); any other path is not repository-scoped.

Refused outright, because the upstream may resolve them to another repository after this check: a `.` or `..` segment, a leading empty segment (`%2Frepos/…` decodes to one), a `%` left after decoding (double encoding), a backslash, and an escape that does not decode.

🔴 ONE RULE, ONE PLACE: the GitHub App (githubapp.App.targetRepo) and the standing public read both decide a request's repository here.

func GrantScope added in v0.229.0

func GrantScope(ctx context.Context, s Store, connector, repo string) string

GrantScope is what an approval of connector, for an agent whose effective repository scope is repo (RepoScope), is recorded as being FOR (Grant.Repo, DecideGrantFrom's repo): the connector's Destination for an internal_http connector, whose reach is the server's configuration, and repo for every other. 🔴 ONE PLACE: the approval writes it and ReconcileGrant compares against it (sameDestination).

func Hosts

func Hosts(ctx context.Context, s Store) (map[string][]string, error)

Hosts is every connector's hosts, by name.

func InternalHTTPTokenEnv added in v0.229.0

func InternalHTTPTokenEnv(name string) string

InternalHTTPTokenEnv is the environment variable connector name's token is read from.

func IsInternalHTTP added in v0.229.0

func IsInternalHTTP(v Virtual) bool

IsInternalHTTP reports whether v is an internal_http connector.

func IsKubeRead added in v0.153.0

func IsKubeRead(v Virtual) bool

IsKubeRead reports whether v is the kube-read connector. The callers that describe a virtual connector as the GitHub App branch on it first.

func NormalizeHost

func NormalizeHost(h string) (string, error)

NormalizeHost validates one allowlist entry and returns it lowercased.

An entry is a DNS hostname with at least one dot, optionally followed by ":port". IP literals are refused: an allowlist that names an address cannot be checked against the private-range rule by name, and every real platform has a hostname. Wildcards are refused: the allowlist is exact by design.

func NormalizeInternalPath added in v0.229.0

func NormalizeInternalPath(prefix, p string) (string, error)

NormalizeInternalPath validates a call's path against prefix and returns it. It refuses rather than repairs: a path that would need cleaning is not one a well-behaved caller sends.

🔴 EACH REFUSAL IS ONE WAY OUT OF THE PREFIX OR OFF THE HOST: an absolute URL (`http://…`: ':' is refused), a network-path reference (`//host/…`), a `.` or `..` segment, any percent-escape (`%2e%2e`, `%2f`, `%5c`: '%' is refused, so nothing is decoded later), a backslash, a query or fragment (`?`, `#`: query values go in Query, where they are encoded), and a path not under the prefix.

The STRUCTURAL guards are the character set (pathCharsRE), the empty- and dot-segment checks and the prefix. The backslash, '%' and leading-'//' cases come first only to give the caller a precise message: each is also refused by the character set or the empty-segment check, so removing one alone changes the message, not the outcome (mutation-checked both ways).

func ReachesGitHub

func ReachesGitHub(name string, hosts map[string][]string) bool

ReachesGitHub reports whether a grant on connector name could put a GitHub credential in the agent's pod: the `github` connector, a connector with a github.com host, or — failing closed — one whose hosts are unknown.

ONE PREDICATE, THREE DOORS: a pool worker holding an approved grant it matches is not eligible for a job, an approval of one for a pool worker is refused (internal/api jobs_grants.go), and a worker-pool agent holding one is never started with job-lane permission bypass (internal/agentprovision).

func RedactPG added in v0.118.0

func RedactPG(s string, secrets ...string) string

RedactPG is redactPG for callers outside the package (the API's last-resort error text).

func RepoScope added in v0.137.0

func RepoScope(repo string, readRepos []string) string

RepoScope is the repository SET a grant is approved for (Grant.Repo, and ReconcileGrant's repo): the caller's own repository and its further read-only ones (Caller.ReadRepos, an officer's `read_repos`), as ONE canonical string.

  • With no read repositories it is repo itself, trimmed — byte-for-byte what every approval before read_repos recorded, so adding this changed no existing grant's key and re-opened nothing.
  • Otherwise it is "<repo> (+ read: <a>, <b>)", the read repositories trimmed, lowercased, deduplicated and SORTED: declaring the same set in another order or case is the same scope and does not re-open a grant, while adding, removing or changing any entry — or changing repo — does.

🔴 ONE CANONICAL FORM, ONE PLACE. The approval records it (api.decideConnectorGrant) and every reconcile compares against it (the proxy's CheckAccess, the agent routes); a door that built it differently would re-open every officer grant on its first use.

func ResponseRewriteOf added in v0.170.0

func ResponseRewriteOf(r *http.Request) func(ctx context.Context, resp *http.Response) error

ResponseRewriteOf is the function WithResponseRewrite attached to r, nil when none.

func SameRepo added in v0.108.0

func SameRepo(a, b string) bool

SameRepo reports whether two repository names are the same repository: equal without case or surrounding space ("" is no repository).

func SourceFor

func SourceFor(ctx context.Context, s Store, name string) string

SourceFor is the credential source connector name has for ctx's principal: SourceApp when a virtual connector presents it, SourceStored otherwise.

func StandingRepo

func StandingRepo(source, repo string) (string, bool)

StandingRepo is the repository part of a standing grant's key for an agent dispatched with repo, under credential source: the repository trimmed and lowercased (GitHub names are case-insensitive, and the App compares them so: githubapp.App.Credential) for SourceApp, and "" for a stored credential, which is keyed on the connector alone. ok is false when there is no key: a SourceApp approval for an agent with no repository grants nothing usable, so it is never shared.

func ValidateName

func ValidateName(name string) error

ValidateName refuses a connector name that is not lowercase [a-z0-9-], starting and ending alphanumeric, at most 63 characters.

func ValidateSecret

func ValidateSecret(s string) error

ValidateSecret refuses a too-short secret or one that cannot travel in a header.

func WithAfterForward added in v0.156.0

func WithAfterForward(r *http.Request, f func(ctx context.Context, res ForwardResult)) *http.Request

WithAfterForward returns r carrying f: a Gate's Admit returns it so that the proxy calls f ONCE with what it saw of the upstream's answer.

🔴 f RUNS WHATEVER THE CLIENT DOES. Serve defers it as soon as Admit has admitted the request, so it runs on every path out of Serve: a forwarded request, a proxy refusal after Admit (Forwarded false), and a client that went away mid-relay (ReverseProxy's panic(http.ErrAbortHandler) unwinds through deferred calls only). Its ctx is detached from the request's (context.WithoutCancel): a client that drops its connection cannot cancel it. f runs in the handler; it must bound its own work. The push gate's re-check of a push and of a new pull request is the user (internal/officership's afterPush and afterCreate).

func WithCaller added in v0.156.0

func WithCaller(ctx context.Context, c Caller) context.Context

WithCaller returns ctx carrying c for CallerOf.

func WithResponseRewrite added in v0.170.0

func WithResponseRewrite(r *http.Request, f func(ctx context.Context, resp *http.Response) error) *http.Request

WithResponseRewrite returns r carrying f: a Gate's Admit returns it so that the proxy calls f with the upstream's answer BEFORE any of it is relayed to the client. f may read resp.Body and replace it (and resp.Header); the proxy's own handling (redaction, the Location rewrite, the after-forward tee, which sees the upstream's bytes) still applies around it. An error from f is answered 502 and nothing of the upstream's answer is relayed.

It is for a gate that must act on the upstream's answer before the client learns it: the shepherd's push lands a commit only after it is verified, and tells the client what landed (internal/officership shepherd.go).

Types

type Access

type Access struct {
	Grant  Grant
	Usable bool
	// Filed is true when THIS check filed a new pending request.
	Filed bool
}

Access is the outcome of checking a caller's grant.

type AuditEntry

type AuditEntry struct {
	ID        int64     `json:"id"`
	At        time.Time `json:"at"`
	Kind      string    `json:"kind"` // "proxy" | "grant"
	AgentID   int64     `json:"agentId,omitempty"`
	AgentName string    `json:"agentName"`
	Connector string    `json:"connector"`
	Method    string    `json:"method,omitempty"`
	Host      string    `json:"host,omitempty"`
	Path      string    `json:"path,omitempty"`
	Status    int       `json:"status,omitempty"`
	Detail    string    `json:"detail,omitempty"`
}

AuditEntry is one line of the audit trail. It carries no body and no header.

type AuditIDer added in v0.153.0

type AuditIDer interface {
	AuditID(ctx context.Context, e AuditEntry) (int64, error)
}

AuditIDer is a store that returns an appended audit row's id (PGStore).

type Caller

type Caller struct {
	AgentID   int64
	AgentName string
	// Repo is the agent's own repository (owner/name), "" when it was dispatched
	// without one. A virtual connector that scopes its credential to the agent's
	// repository (the GitHub App) reads it; a stored connector ignores it.
	Repo string
	// ReadRepos are further repositories (owner/name) the caller may READ
	// through a virtual connector that scopes its credential per repository
	// (the GitHub App): a request that targets one of them gets a READ-ONLY
	// credential for that one repository, whatever ReadOnly and the
	// connector's own mode say. Set for an officer instance from its
	// officer's `read_repos` (api.Server.agentReadRepos); nil for every other
	// caller. A stored connector ignores it. The grant is approved for
	// RepoScope(Repo, ReadRepos).
	ReadRepos []string
	// PublicReadRepos are PUBLIC repositories (owner/name) the caller may READ
	// through the `github` connector with NO grant: the standing public read
	// (public_read.go) — anonymous, reads only, each verified public with
	// GitHub. Set for an instance of a builtin officer that declares
	// read_grant "standing" (api.Server.agentPublicReadRepos); nil for every
	// other caller. They are never part of the grant's RepoScope.
	PublicReadRepos []string
	// ReadOnly asks a virtual connector that mints a credential (the GitHub
	// App) for a READ-ONLY one for this caller, whatever its own mode. Set for
	// an officer instance (api.Server.callerOf). A stored connector ignores
	// it: its secret is whatever the operator stored.
	ReadOnly bool
	// Gate, when set, REPLACES the connector's own credential for this caller
	// and decides every request before a credential exists (see [Gate]). Set
	// for an officer instance that ships code (api.Server.callerOf); nil for
	// every other caller.
	Gate Gate
}

Caller is the authenticated agent a proxied request is made for.

func CallerOf added in v0.156.0

func CallerOf(ctx context.Context) (Caller, bool)

CallerOf is the caller Serve resolved for a gated request, as Admit sees it in the request's context (ok false outside Serve: a test calling Admit directly sets it with WithCaller).

type Connector

type Connector struct {
	ID         int64    `json:"id"`
	Name       string   `json:"name"`
	Platform   string   `json:"platform"`
	Hosts      []string `json:"hosts"`
	Scheme     Scheme   `json:"scheme"`
	HeaderName string   `json:"headerName,omitempty"`
	Username   string   `json:"username,omitempty"`
	// Postgres is a SchemePostgres connector's non-secret settings (database,
	// sslmode, the TLS requirement and the per-query caps); nil for every other
	// scheme. Hosts holds its one host:port and Username its database user.
	Postgres   *PostgresSettings `json:"postgres,omitempty"`
	CreatedAt  time.Time         `json:"createdAt"`
	UpdatedAt  time.Time         `json:"updatedAt"`
	RotatedAt  *time.Time        `json:"rotatedAt,omitempty"`
	LastUsedAt *time.Time        `json:"lastUsedAt,omitempty"`
}

Connector is one stored credential's PUBLIC description.

🔴 THERE IS NO SECRET FIELD, AND THAT ABSENCE IS THE GUARANTEE that no list, page or JSON projection can leak one: the secret exists in plaintext only on the stack of the proxy call that injects it (Store.Credential).

func (Connector) AllowsHost

func (c Connector) AllowsHost(host string) bool

AllowsHost reports whether host (as it appears in a proxy path) is one of the connector's declared hosts. Comparison is case-insensitive and exact: no suffix, wildcard or subdomain matching.

type DecisionSource

type DecisionSource struct {
	Via     string
	Host    string
	Session string
}

DecisionSource is where the operator decided a request when it was NOT the Connectors tab: Via (DecidedViaMCP) and the mirrored session it came from (Host, the session's mirror host — proven by the host's token; Session, the Claude session id the caller named — a claim). The zero value is the tab.

func (DecisionSource) String

func (src DecisionSource) String() string

String is "<host>/<session>", "" for the tab.

func (DecisionSource) ViaSession

func (src DecisionSource) ViaSession() bool

ViaSession reports whether src names a mirrored session (an MCP decision).

type ForwardResult added in v0.156.0

type ForwardResult struct {
	// Forwarded: the request was handed to the upstream (false: the proxy
	// answered it itself after Admit, e.g. no credential could be minted).
	Forwarded bool
	// Status is the upstream's status, 0 when no answer head arrived.
	Status int
	// Body is the start of the upstream's response body as the proxy read it
	// (before redaction, at most MaxAfterForwardBody bytes), and Complete
	// whether it was read to its end within that bound. A client that went
	// away stops the relay, and with it the read: Complete is then false.
	Body     []byte
	Complete bool
}

ForwardResult is what the proxy saw of the upstream's answer to an admitted request, handed to its after-forward hook.

type Gate added in v0.110.0

type Gate interface {
	// Connector is the connector name the gate serves. A gated caller's
	// request for any other connector is refused.
	Connector() string
	// Describe is the connector's description as the gate serves it: its
	// hosts (the allowlist) and auth shape.
	Describe() Connector
	// Admit decides one request (host on Describe().Hosts; rest escaped, no
	// leading slash). It may return a request whose body was re-wrapped after
	// inspection. A refusal must wrap [ErrGateRefused]; its text is shown to
	// the agent and must carry no secret. Any other error is a 502.
	Admit(r *http.Request, host, rest string) (*http.Request, error)
	// Credential is the secret for an admitted request (anonymous=true: send
	// none), as [Virtual.Credential].
	Credential(ctx context.Context, caller Caller, host, rest string) (secret string, anonymous bool, err error)
	// Rejected is told the upstream answered 401 to a request that carried
	// Credential's secret.
	Rejected(caller Caller)
}

Gate is a per-caller WRITE POLICY with its own credential: an officer instance whose writes muster must filter, because the platform it writes to enforces nothing itself (a private repository with no branch protection).

🔴 THE GATE RUNS IN muster-server, BEFORE ANY CREDENTIAL IS MINTED, AND IT IS THE ONLY WAY A GATED CALLER'S REQUEST GETS ONE. Serve asks Admit first; a refusal is a 403 and the upstream never sees a byte. Only an admitted request is handed a credential, and it comes from Gate.Credential — never from the connector's stored secret or the deployment's App — so a gated caller cannot reach an ungated credential by any path through this proxy.

type Grant

type Grant struct {
	ID          int64      `json:"id"`
	AgentID     int64      `json:"agentId"`
	AgentName   string     `json:"agentName"`
	Connector   string     `json:"connector"`
	Status      string     `json:"status"`
	Reason      string     `json:"reason,omitempty"`
	RequestedAt time.Time  `json:"requestedAt"`
	DecidedAt   *time.Time `json:"decidedAt,omitempty"`
	DecidedBy   string     `json:"decidedBy,omitempty"`
	LastUsedAt  *time.Time `json:"lastUsedAt,omitempty"`
	// Source is the credential the approval was about: SourceStored or
	// SourceApp (migration 0033). See ReconcileGrant.
	Source string `json:"source,omitempty"`
	// DecidedVia is where the operator decided it when that was NOT the
	// Connectors tab (migration 0035): the zero value for the tab, for a grant
	// not yet decided, a revoked one, and every decision recorded before 0035.
	// DecidedViaStanding for an automatic approval (migration 0043).
	DecidedVia DecisionSource `json:"-"`
	// StandingGrantID is the standing grant that approved this grant
	// automatically (migration 0043); 0 for every other grant.
	StandingGrantID int64 `json:"standingGrantId,omitempty"`
	// Repo is the repository the decision was made for (migration 0061): the
	// agent's effective repository when the owner decided it, or — when none
	// was recorded (a decision before 0061, an approval from a standing grant,
	// a grant not yet decided) — the agent row's own repository. "" for none.
	// For an internal_http connector it is instead the destination the
	// approval was made for (InternalHTTP.Destination, written by GrantScope),
	// a fingerprint never shown to an agent. See ReconcileGrant.
	Repo string `json:"-"`
}

Grant is one agent's request for, and the operator's decision on, one connector.

func ReconcileGrant

func ReconcileGrant(ctx context.Context, s Store, g Grant, repo string) (Grant, string, error)

ReconcileGrant puts an approved grant back to pending when the approval no longer describes what the grant would now serve, and says why:

  • its connector's credential source (for ctx's principal, the grant's owner) is no longer the one the approval was about — the GitHub App configured over a stored token, or removed from under one (0033);
  • the agent's effective repository (repo: connectors.Caller.Repo, the officer's configured `repo` for an officer instance) is not the one the approval was made for (Grant.Repo, 0061) — compared without case or surrounding space, as GitHub names are. An officer approved for one repository and then pointed at another, or approved with none and then given one, asks its owner again. For an officer with `read_repos`, repo is the whole set as RepoScope writes it, so a change to either `repo` or `read_repos` re-opens the grant and a reordering does not. NOT for kube-read (KubeReadVirtual) or an internal_http connector (InternalHTTP): what they reach is the server's configuration, never a repository, so a repository change leaves their grant as it is (its credential source is still compared);
  • for an internal_http connector, the destination the approval was made for (Grant.Repo holds InternalHTTP.Destination there: GrantScope) is not the connector's destination now — its base URL or path prefix was changed and the server restarted. A grant recorded with none (or a repository) is re-opened too: it fails closed.

reason is "" when the grant is returned unchanged, else the audit line's why. The caller prompts the owner.

🔴 THIS IS THE ONE PLACE THE RULE LIVES; every reader that turns a grant into "may this agent use the connector" calls it first (Proxy.CheckAccess, the agent's connector status and request routes).

func (Grant) Usable

func (g Grant) Usable() bool

Usable reports whether the grant currently authorises use: it is approved.

type InternalHTTP added in v0.229.0

type InternalHTTP struct {

	// Logger receives one line per call; nil logs nothing.
	Logger *log.Logger
	// contains filtered or unexported fields
}

InternalHTTP is one configured internal_http connector. It is a Virtual (presented by WithVirtual) and it performs the calls (InternalHTTP.Do).

func InternalHTTPOf added in v0.229.0

func InternalHTTPOf(ctx context.Context, s Store, name string) (*InternalHTTP, bool)

InternalHTTPOf returns the internal_http connector s presents under name to ctx's principal (an admin), or false.

func NewInternalHTTP added in v0.229.0

func NewInternalHTTP(d InternalHTTPSettings, token string) (*InternalHTTP, error)

NewInternalHTTP validates one connector's settings and token.

func ParseInternalHTTP added in v0.229.0

func ParseInternalHTTP(raw string, getenv func(string) string) ([]*InternalHTTP, error)

ParseInternalHTTP reads MUSTER_INTERNAL_HTTP_CONNECTORS (raw: a JSON array of InternalHTTPSettings; "" is none) and each connector's token from getenv. Every refusal names the connector and what to fix; no refusal carries a token.

func (*InternalHTTP) BaseURL added in v0.229.0

func (ih *InternalHTTP) BaseURL() string

BaseURL is the configured base URL. Operator-facing only: the Connectors tab (a human's page) and the boot log. No tool answer carries it — not an agent's view, and not the owner's mirrored session's either (connector_requests_list / connector_request_decide describe the grant without it: api.internalHTTPGrantsDescription).

func (*InternalHTTP) Credential added in v0.229.0

func (ih *InternalHTTP) Credential(context.Context, Caller, string, string) (string, bool, error)

Credential refuses: the token is spent only by Do.

func (*InternalHTTP) Describe added in v0.229.0

func (ih *InternalHTTP) Describe() Connector

Describe names no host: no model's view of the connector (an agent's, or the owner's mirrored session's) carries the base URL, and the proxy has nothing to allowlist.

func (*InternalHTTP) Destination added in v0.229.0

func (ih *InternalHTTP) Destination() string

Destination is the fingerprint of where the connector's calls go: its base URL and its path prefix. An approval records it (GrantScope) and ReconcileGrant re-opens one recorded for another. It is a hash, so the grant row and any line quoting it never carry the address itself. The token is deliberately not in it: rotating the token changes no destination.

func (*InternalHTTP) Do added in v0.229.0

Do performs one call for caller and audits it to audit (the connector store). The caller must already hold an approved grant: Do decides HOW the call is made, the grant check (the api package, through Proxy.CheckAccess) decides WHETHER.

func (*InternalHTTP) MaxResponseBytes added in v0.229.0

func (ih *InternalHTTP) MaxResponseBytes() int

MaxResponseBytes is the response cap.

func (*InternalHTTP) Name added in v0.229.0

func (ih *InternalHTTP) Name() string

Name is the connector's name.

func (*InternalHTTP) PathPrefix added in v0.229.0

func (ih *InternalHTTP) PathPrefix() string

PathPrefix is the configured path prefix.

func (*InternalHTTP) Problem added in v0.229.0

func (ih *InternalHTTP) Problem(int64) string

func (*InternalHTTP) Rejected added in v0.229.0

func (ih *InternalHTTP) Rejected(Caller)

func (*InternalHTTP) Timeout added in v0.229.0

func (ih *InternalHTTP) Timeout() time.Duration

Timeout is the per-call timeout.

type InternalHTTPError added in v0.229.0

type InternalHTTPError struct {
	Class   string `json:"class"`
	Message string `json:"error"`
}

InternalHTTPError is a refusal or a failed call, with its audit class. Its message never carries the token.

func (*InternalHTTPError) Error added in v0.229.0

func (e *InternalHTTPError) Error() string

type InternalHTTPImage added in v0.229.0

type InternalHTTPImage struct {
	MIMEType string
	Data     []byte
}

InternalHTTPImage is one image a response carried (SplitImages).

type InternalHTTPRequest added in v0.229.0

type InternalHTTPRequest struct {
	Method string
	Path   string
	Query  map[string]string
	// Body is a POST's JSON body (sent as application/json); empty for none.
	Body json.RawMessage
}

InternalHTTPRequest is one call, as the tool receives it. There is no field for a URL, a host or a header: the destination and every header are the connector's.

type InternalHTTPResult added in v0.229.0

type InternalHTTPResult struct {
	Status      int    `json:"status"`
	ContentType string `json:"content_type,omitempty"`
	Body        string `json:"body,omitempty"`
	BodyBase64  string `json:"body_base64,omitempty"`
	Bytes       int    `json:"bytes"`
	MaxBytes    int    `json:"max_bytes"`
	DurationMS  int64  `json:"duration_ms"`
	// Images is how many images SplitImages took out of the response, each
	// returned beside this result as an image (an MCP image content block).
	Images int `json:"images,omitempty"`
}

InternalHTTPResult is one call's answer. Body is set for a text response (text/*, JSON, XML, valid UTF-8), BodyBase64 for any other (an image).

func (InternalHTTPResult) SplitImages added in v0.229.0

SplitImages takes the images out of r, for a caller that can show them (the MCP door: api.toolInternalHTTP), and returns r without them. A JSON text of several megabytes of base64 is unreadable to a model and overruns its client's output limit, while an image block is what it can SEE.

  • A binary body (BodyBase64) whose bytes are an image: the image, and BodyBase64 is emptied.
  • A JSON body whose TOP-LEVEL object has a string field named `*_base64` (a screenshot service's `png_base64`) that decodes, as standard base64, to an image: that image, and the field's value becomes a placeholder naming the image's position, type and size. Every other field is kept (the object is re-encoded, its keys sorted).

Anything else is returned unchanged with no image: another body, a field that does not decode or decodes to something not an image, a nested field. Images is set to the count. The bytes are the already-redacted body's.

type InternalHTTPSettings added in v0.229.0

type InternalHTTPSettings struct {
	Name             string `json:"name"`
	BaseURL          string `json:"base_url"`
	PathPrefix       string `json:"path_prefix,omitempty"`
	MaxResponseBytes int    `json:"max_response_bytes,omitempty"`
	TimeoutSeconds   int    `json:"timeout_seconds,omitempty"`
}

InternalHTTPSettings is one connector's configuration, as declared in MUSTER_INTERNAL_HTTP_CONNECTORS. There is deliberately no token field: a declaration that carries one is refused (unknown key).

type NewConnector

type NewConnector struct {
	Name       string
	Platform   string
	Hosts      []string
	Scheme     Scheme
	HeaderName string
	Username   string
	Secret     string
	// Postgres is required for SchemePostgres and must be nil otherwise.
	Postgres *PostgresSettings
}

NewConnector is what an operator submits to create a connector.

func (NewConnector) Validate

func (nc NewConnector) Validate() (NewConnector, error)

Validate refuses a NewConnector that could not be safely used, and returns it normalised (hosts lowercased, deduplicated and sorted).

type PGColumn added in v0.118.0

type PGColumn struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

PGColumn is one result column: its name and its Postgres type name.

type PGError added in v0.118.0

type PGError struct {
	Class    string `json:"class"`
	SQLState string `json:"sqlstate,omitempty"`
	Message  string `json:"error"`
}

PGError is a refusal or a database error, carrying its class for the audit. Its message has been through redactPG.

func (*PGError) Error added in v0.118.0

func (e *PGError) Error() string

type PGQuery added in v0.118.0

type PGQuery struct {
	SQL    string
	Params []json.RawMessage
}

PGQuery is one agent query: a single SQL statement and its positional parameters ($1, $2, …) as JSON values.

type PGResult added in v0.118.0

type PGResult struct {
	Columns  []PGColumn  `json:"columns"`
	Rows     [][]*string `json:"rows"`
	RowCount int         `json:"row_count"`
	// Truncated is true when the row or byte cap cut the result; TruncatedBy
	// says which ("rows" or "bytes").
	Truncated   bool   `json:"truncated"`
	TruncatedBy string `json:"truncated_by,omitempty"`
	MaxRows     int    `json:"max_rows"`
	MaxBytes    int    `json:"max_bytes"`
	Command     string `json:"command,omitempty"`
	DurationMS  int64  `json:"duration_ms"`
}

PGResult is one query's answer. Every value is Postgres's TEXT representation (null is JSON null).

type PGStore

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

PGStore is the Postgres-backed Store. Secrets are sealed with the key given to NewPG before they reach a query, and opened only by PGStore.Credential.

func NewPG

func NewPG(pool *pgxpool.Pool, key []byte) (*PGStore, error)

NewPG builds a PGStore. key must be KeySize bytes.

func (*PGStore) ApproveFromStanding

func (s *PGStore) ApproveFromStanding(ctx context.Context, id, sg int64) (Grant, error)

ApproveFromStanding approves pending grant id from live standing grant sg.

🔴 THE STANDING GRANT'S ROW IS LOCKED (FOR SHARE) FOR THE APPROVAL, so it serialises with RevokeStandingGrant (which updates that row first): either the revoke commits first and this finds it revoked (ErrNotPending), or this commits first and the revoke's cascade — a later statement — sees the grant and revokes it. An approval can never land after its standing grant's revoke has swept.

func (*PGStore) Audit

func (s *PGStore) Audit(ctx context.Context, e AuditEntry) error

Audit appends one entry.

func (*PGStore) AuditID added in v0.153.0

func (s *PGStore) AuditID(ctx context.Context, e AuditEntry) (int64, error)

AuditID appends one entry and returns its id (connector_audit.id, a BIGINT identity): what officer_kube_read hands the instance to cite.

func (*PGStore) CreateConnector

func (s *PGStore) CreateConnector(ctx context.Context, nc NewConnector) (Connector, error)

CreateConnector validates, seals and inserts a connector. A duplicate name is ErrInvalid.

func (*PGStore) CreateStandingGrant

func (s *PGStore) CreateStandingGrant(ctx context.Context, connector, source, repo string, origin int64) (StandingGrant, bool, error)

CreateStandingGrant records the standing grant for (connector, source, repo), owned by the owner of grant origin (the approval it comes from), or returns the live one that already holds the key.

func (*PGStore) Credential

func (s *PGStore) Credential(ctx context.Context, name string) (Connector, string, error)

Credential returns the connector with its decrypted secret. A secret that does not open under the configured key is ErrDecrypt.

The secret opens only under the row's CURRENT name, hosts, scheme, header and username (seal.go), so the connector returned is exactly the one the secret was sealed for: a row edited outside muster is ErrDecrypt, not a credential sent somewhere new.

func (*PGStore) DecideGrant

func (s *PGStore) DecideGrant(ctx context.Context, id int64, approve bool, by, source string) (Grant, error)

DecideGrant approves or denies a pending grant, recording the credential source the decision was about (SourceStored / SourceApp). It is a decision on the Connectors tab: no provenance (DecideGrantFrom with the zero source).

func (*PGStore) DecideGrantFrom

func (s *PGStore) DecideGrantFrom(ctx context.Context, id int64, approve bool, by, source, repo string, via DecisionSource) (Grant, error)

DecideGrantFrom is DecideGrant recording where the operator made the decision (migration 0035). The zero via writes NULLs — the tab.

🔴 ONE CONDITIONAL UPDATE FOR BOTH DOORS, so a decision from a mirrored session and one from the tab cannot drift apart, and two of them racing on one request cannot both land: the loser is ErrNotPending. 0035's CHECK refuses a half-written provenance or one on an undecided row.

repo is the repository the decision is for (migration 0061), stored trimmed; "" stores NULL, which reads back as the agent row's own repository.

func (*PGStore) DeleteConnector

func (s *PGStore) DeleteConnector(ctx context.Context, name string) error

DeleteConnector removes a connector AND every grant and standing grant naming it, in one transaction, so a connector later re-created under the same name starts with no approvals — shared or not.

func (*PGStore) GetConnector

func (s *PGStore) GetConnector(ctx context.Context, name string) (Connector, error)

GetConnector returns one connector's public description.

func (*PGStore) GetGrant

func (s *PGStore) GetGrant(ctx context.Context, id int64) (Grant, error)

GetGrant returns one grant.

func (*PGStore) LatestGrant

func (s *PGStore) LatestGrant(ctx context.Context, agentID int64, connector string) (Grant, error)

LatestGrant returns the newest grant row for the pair.

func (*PGStore) ListAudit

func (s *PGStore) ListAudit(ctx context.Context, limit int) ([]AuditEntry, error)

ListAudit returns the newest entries first.

func (*PGStore) ListConnectors

func (s *PGStore) ListConnectors(ctx context.Context) ([]Connector, error)

ListConnectors returns every connector, by name.

func (*PGStore) ListGrants

func (s *PGStore) ListGrants(ctx context.Context) ([]Grant, error)

ListGrants returns every live (pending or approved) grant.

func (*PGStore) ListPendingGrants

func (s *PGStore) ListPendingGrants(ctx context.Context) ([]Grant, error)

ListPendingGrants returns the requests awaiting the operator, oldest first.

func (*PGStore) ListStandingGrants

func (s *PGStore) ListStandingGrants(ctx context.Context) ([]StandingGrant, error)

ListStandingGrants returns the live standing grants, by connector.

func (*PGStore) MatchStandingGrant

func (s *PGStore) MatchStandingGrant(ctx context.Context, agentID int64, connector, source, repo string) (StandingGrant, error)

MatchStandingGrant is the live standing grant for the key that may approve agentID's request.

🔴 OWNER: THE AGENT'S, STATED IN THE QUERY. Row-level security already hides another owner's standing grants from a user principal; the explicit `owner_id = <the agent's owner>` is what keeps a scope-all (System) caller from approving one owner's agent with another owner's approval (TestAStandingGrantNeverCrossesOwners).

🔴 A PER-AGENT "NO" OUTLIVES THE SHARED "YES": a grant on this connector that the owner revoked or denied for THIS agent after the standing grant was made keeps the standing grant from approving the agent again — revoking one agent on the Connectors tab is not undone by the agent simply asking again.

func (*PGStore) PruneAudit

func (s *PGStore) PruneAudit(ctx context.Context, before time.Time) (int64, error)

PruneAudit deletes entries older than before.

func (*PGStore) ReopenGrant

func (s *PGStore) ReopenGrant(ctx context.Context, id int64) (Grant, bool, error)

ReopenGrant puts an APPROVED grant back to pending (see ReconcileGrant). It is conditional on the row still being approved: false, nil when it was not. An undecided row carries no decision, so its provenance is cleared too.

func (*PGStore) RequestGrant

func (s *PGStore) RequestGrant(ctx context.Context, agentID int64, connector, reason string) (Grant, bool, error)

RequestGrant returns the live grant for (agent, connector) or files a pending one.

func (*PGStore) RevokeGrant

func (s *PGStore) RevokeGrant(ctx context.Context, id int64, by string) (Grant, error)

RevokeGrant ends a pending or approved grant. A revocation is made on the Connectors tab, so it clears an MCP decision's provenance with the rest of the decision it replaces (decided_by/decided_at describe the revocation); the audit trail keeps where the approval came from.

func (*PGStore) RevokeStandingGrant

func (s *PGStore) RevokeStandingGrant(ctx context.Context, id int64, by string) (StandingGrant, []Grant, error)

RevokeStandingGrant revokes standing grant id and, in the same transaction, every APPROVED grant it gave: those it approved automatically, and the approval it was created from. A revoke is an off-switch for the shared approval, not only for the ones still to come.

func (*PGStore) RotateSecret

func (s *PGStore) RotateSecret(ctx context.Context, name, secret string) error

RotateSecret replaces a connector's secret. Grants are kept: rotation changes what is sent, not who may send it.

🔴 THE OLD SECRET MUST OPEN UNDER THE ROW AS IT STANDS, OR NOTHING IS WRITTEN (ErrDecrypt). The new ciphertext is bound to the row's current hosts and auth shape; re-sealing a row someone edited out of band would bind the secret to THEIR hosts and launder the edit. The UPDATE also matches the ciphertext it verified, so a concurrent change to the row is not overwritten. A connector whose secret no longer opens (wrong key, altered row) is deleted and created again.

func (*PGStore) TouchConnector

func (s *PGStore) TouchConnector(ctx context.Context, name string) error

TouchConnector stamps last_used_at.

func (*PGStore) TouchGrant

func (s *PGStore) TouchGrant(ctx context.Context, id int64) error

TouchGrant stamps last_used_at.

type Policy

type Policy struct {
	// AllowLoopback admits loopback destinations (127.0.0.0/8, ::1). Every other
	// non-public range stays refused.
	AllowLoopback bool
	// InsecureHTTP speaks plain HTTP to the upstream instead of HTTPS.
	InsecureHTTP bool
	// Resolve replaces the system resolver. nil means net.DefaultResolver.
	Resolve func(ctx context.Context, host string) ([]netip.Addr, error)
}

Policy is the proxy's network policy for upstream connections.

🔴 THE ZERO VALUE IS PRODUCTION, AND IT IS THE STRICT ONE: HTTPS only, the system resolver, and no non-public destination. Each field below LOOSENS it and exists for tests (a fake upstream on loopback); cmd/muster-server never sets one outside a binary built with the e2e tag.

func (Policy) Transport

func (p Policy) Transport() *http.Transport

Transport builds the upstream transport for this policy.

🔴 Proxy IS nil, DELIBERATELY: an HTTPS_PROXY in muster's environment would otherwise carry every injected credential through a third party, and the address checks above would be checking the proxy rather than the platform.

type PostgresExecutor added in v0.118.0

type PostgresExecutor struct {
	Store  Store
	Logger *log.Logger
	// RatePerMinute and Burst set the per-agent token bucket (0: the
	// defaults).
	RatePerMinute, Burst int
	// Now is the limiter's clock (tests); nil is time.Now.
	Now func() time.Time
	// Dial, when set, is the ONLY way a connection to the database is made:
	// every connection attempt resolves the connector's host and dials it
	// through this guard, so a host that is (or resolves to) a loopback,
	// private, link-local, CGNAT, unspecified or multicast address is refused
	// at connect time (MUSTER_DIAL_DENY_PRIVATE=1). nil, the default, dials
	// whatever host the connector names — an admin's own LAN database included.
	Dial *safedial.Guard
	// contains filtered or unexported fields
}

PostgresExecutor runs agent queries against postgres connectors.

func (*PostgresExecutor) Close added in v0.118.0

func (e *PostgresExecutor) Close()

Close closes every pool.

func (*PostgresExecutor) Query added in v0.118.0

func (e *PostgresExecutor) Query(ctx context.Context, caller Caller, connector string, q PGQuery) (PGResult, error)

Query runs q against connector for caller. The caller must already hold an approved grant: the executor decides HOW a query runs, the grant check (the api package, through Proxy.CheckAccess) decides WHETHER.

An error is a *PGError (its Message safe to show the agent), ErrInvalid (a bad request), ErrRateLimited, ErrNotFound or ErrDecrypt.

type PostgresSettings added in v0.118.0

type PostgresSettings struct {
	Database string `json:"database"`
	SSLMode  string `json:"sslmode"`
	// RequireTLS refuses a connection that is not TLS, whatever the sslmode
	// negotiated (checked on the live connection after it is made).
	RequireTLS bool `json:"require_tls"`
	// StatementTimeoutMS is statement_timeout in milliseconds; 0 is
	// PGDefaultStatementTimeout. Validated within
	// [PGMinStatementTimeout, PGMaxStatementTimeout].
	StatementTimeoutMS int `json:"statement_timeout_ms,omitempty"`
	// MaxRows and MaxBytes cap one result; 0 is the default.
	MaxRows  int `json:"max_rows,omitempty"`
	MaxBytes int `json:"max_bytes,omitempty"`
}

PostgresSettings is a postgres connector's non-secret configuration.

func (PostgresSettings) ByteCap added in v0.118.0

func (p PostgresSettings) ByteCap() int

ByteCap is the effective byte cap.

func (PostgresSettings) LockTimeout added in v0.118.0

func (p PostgresSettings) LockTimeout() time.Duration

LockTimeout is the effective lock_timeout.

func (PostgresSettings) RowCap added in v0.118.0

func (p PostgresSettings) RowCap() int

RowCap is the effective row cap.

func (PostgresSettings) StatementTimeout added in v0.118.0

func (p PostgresSettings) StatementTimeout() time.Duration

StatementTimeout is the effective statement_timeout, clamped to the caps.

type Preset

type Preset struct {
	Key         string
	Label       string
	Hosts       []string
	Scheme      Scheme
	HeaderName  string
	Username    string
	SecretLabel string
	Help        string
}

Preset is a ready-made connector shape for a known platform.

func PresetFor

func PresetFor(key string) (Preset, bool)

PresetFor returns the preset with key, or false.

func Presets

func Presets() []Preset

Presets is every built-in preset, in display order.

type Proxy

type Proxy struct {
	Store  Store
	Policy Policy
	Logger *log.Logger
	// OnGrantRequested is called (synchronously; keep it cheap) when a proxied
	// request files a NEW pending grant, so the operator can be prompted.
	OnGrantRequested func(context.Context, Grant)
	// AutoApprove, when set, is offered every request a check FILES, BEFORE
	// OnGrantRequested: it returns the grant approved and true when an owner's
	// standing grant covers it (the api package's approveFromStanding, the one
	// rule every door shares), and the owner is then not prompted. false leaves
	// the grant as it was. A grant RE-OPENED because its connector's credential
	// source changed is not offered: that change asks the owner again (0033),
	// and their approval is then shared as any other.
	AutoApprove func(context.Context, Grant) (Grant, bool)
	// OnPendingRefusal is called (synchronously) when CheckAccess answers a
	// caller whose grant is PENDING — every door (the proxy, the query and
	// internal_http tools, the kube read) refuses on that answer — so the api
	// package can record which officer item the refusal blocked and re-run it
	// once THAT grant is approved (officer_connector_rerun.go). A denied or
	// revoked grant is not reported: no approval of it will follow.
	OnPendingRefusal func(context.Context, Caller, Grant)
	// StreamsEnd is the server's shutdown signal for streams: once it is done, a
	// proxied GET EVENT STREAM in flight ends, and one that starts later ends at
	// once (endsAtShutdown says which exchanges, and why only GET).
	// Every other proxied request is left alone. nil means never (a Proxy built
	// directly, as tests do). The api package hands it the same signal
	// api.Server.EndStreams cancels, so ending its own streams and the ones relayed
	// here is ONE event, fired by the one EndStreams call at the top of
	// cmd/muster-server's shutdown, before either listener drains. See
	// endOnShutdown.
	StreamsEnd context.Context
	// Now is the clock the standing public read's verdict cache reads; nil is
	// time.Now (tests set it).
	Now func() time.Time
	// GitHubGitHost and GitHubAPIHost are the hosts a standing public read is
	// served on; "" is GitHubGitHost / GitHubAPIHost. The api package sets
	// them from a configured GitHub App's own hosts.
	GitHubGitHost, GitHubAPIHost string
	// contains filtered or unexported fields
}

Proxy forwards an agent's request to a connector's upstream with the credential injected.

func (*Proxy) CheckAccess

func (p *Proxy) CheckAccess(ctx context.Context, caller Caller, connector, reason string) (Access, error)

CheckAccess resolves whether the caller may use the connector now, filing a pending request when the caller has never asked.

🔴 A DENIAL OR A REVOCATION IS NOT RE-FILED HERE. A retrying client would otherwise turn one "no" into a prompt per retry. The agent must ask again explicitly (the request route / the connector_request tool), which is a deliberate act the operator then sees as a new request.

func (*Proxy) Serve

func (p *Proxy) Serve(w http.ResponseWriter, r *http.Request, caller Caller, connector, host, rest string)

Serve proxies one request. connector and host are the path's first two segments after /connect/, and rest is everything after the host segment, still escaped (no leading slash).

func (*Proxy) SetTransport

func (p *Proxy) SetTransport(rt http.RoundTripper)

SetTransport overrides the upstream transport (tests). Call it before the first Serve: the transport is fixed from then on.

type QueuedBody added in v0.257.0

type QueuedBody struct {
	Queued    bool   `json:"queued"`
	Message   string `json:"message"`
	Connector string `json:"connector,omitempty"`
}

QueuedBody is the JSON answer to a write a gate queued (202).

type RefusalBody

type RefusalBody struct {
	Error     string `json:"error"`
	Connector string `json:"connector,omitempty"`
	// Grant is the caller's grant status for the connector, when the refusal is
	// about access: "pending", "denied", "revoked".
	Grant   string `json:"grant,omitempty"`
	GrantID int64  `json:"grantId,omitempty"`
}

RefusalBody is the JSON every refusal from the proxy carries.

type Scheme

type Scheme string

Scheme is how a connector's secret is presented to its upstream.

const (
	// SchemeBearer sends `Authorization: Bearer <secret>`.
	SchemeBearer Scheme = "bearer"
	// SchemeHeader sends `<HeaderName>: <secret>` (e.g. an API-key header).
	SchemeHeader Scheme = "header"
	// SchemeBasic sends `Authorization: Basic base64(<Username>:<secret>)`.
	SchemeBasic Scheme = "basic"
	// SchemePostgres is a database connector: the secret is the password of
	// Username on the connector's one host, used by muster-server's own
	// connection (postgres.go). It is never sent over HTTP.
	SchemePostgres Scheme = "postgres"
)
const SchemeInternalHTTP Scheme = "internal_http"

SchemeInternalHTTP is the internal_http connector's scheme. Like SchemeKubeRead it is never served by the HTTP proxy.

const SchemeKubeRead Scheme = "kube-read"

SchemeKubeRead is the kube-read connector's scheme: a read of a Kubernetes API server that muster-server performs ITSELF (internal/kuberead, through the officer_kube_read tool). Like SchemePostgres it is never sent over HTTP by the proxy: the proxy refuses it.

type StandingGrant

type StandingGrant struct {
	ID        int64  `json:"id"`
	Connector string `json:"connector"`
	Source    string `json:"source"`
	Repo      string `json:"repo,omitempty"`
	// OriginGrantID is the per-agent grant whose approval created it.
	OriginGrantID int64      `json:"originGrantId,omitempty"`
	CreatedAt     time.Time  `json:"createdAt"`
	RevokedAt     *time.Time `json:"revokedAt,omitempty"`
}

StandingGrant is one owner-wide approval (migration 0043): while it is live (RevokedAt nil), a request from any of the owner's agents for Connector whose credential source is Source — and, for the GitHub App (SourceApp), whose agent's repository is Repo — is approved automatically.

type Store

type Store interface {
	ListConnectors(ctx context.Context) ([]Connector, error)
	GetConnector(ctx context.Context, name string) (Connector, error)
	CreateConnector(ctx context.Context, nc NewConnector) (Connector, error)
	RotateSecret(ctx context.Context, name, secret string) error
	DeleteConnector(ctx context.Context, name string) error
	// Credential returns the connector and its DECRYPTED secret. The proxy is
	// its only production caller.
	Credential(ctx context.Context, name string) (Connector, string, error)
	TouchConnector(ctx context.Context, name string) error

	// RequestGrant returns the live (pending or approved) grant for the pair,
	// creating a pending one when there is none. created reports which.
	RequestGrant(ctx context.Context, agentID int64, connector, reason string) (g Grant, created bool, err error)
	// LatestGrant returns the most recent grant row for the pair, live or not.
	LatestGrant(ctx context.Context, agentID int64, connector string) (Grant, error)
	GetGrant(ctx context.Context, id int64) (Grant, error)
	// DecideGrant approves or denies a PENDING grant; ErrNotPending otherwise.
	DecideGrant(ctx context.Context, id int64, approve bool, by, source string) (Grant, error)
	// DecideGrantFrom is DecideGrant recording where the decision was made
	// (via; the zero value is the Connectors tab, exactly DecideGrant) and the
	// repository it was made for (repo, Grant.Repo; "" records none, which
	// reads back as the agent row's own repository).
	DecideGrantFrom(ctx context.Context, id int64, approve bool, by, source, repo string, via DecisionSource) (Grant, error)
	// ReopenGrant puts an approved grant back to pending; reopened is false when
	// it was no longer approved.
	ReopenGrant(ctx context.Context, id int64) (g Grant, reopened bool, err error)
	RevokeGrant(ctx context.Context, id int64, by string) (Grant, error)
	ListPendingGrants(ctx context.Context) ([]Grant, error)
	// ListGrants returns every pending and approved grant (the live set).
	ListGrants(ctx context.Context) ([]Grant, error)
	TouchGrant(ctx context.Context, id int64) error

	// CreateStandingGrant records the owner's standing grant for the key
	// (connector, source, repo — see StandingRepo), from the approval of grant
	// origin; when a live one already exists it is returned and created is false.
	// It retires the connector's live standing grants under the OTHER source.
	CreateStandingGrant(ctx context.Context, connector, source, repo string, origin int64) (sg StandingGrant, created bool, err error)
	// MatchStandingGrant returns the owner's live standing grant for the key that
	// may approve agentID's request, or ErrNotFound. A standing grant does not
	// apply to an agent whose grant on the connector the owner revoked or denied
	// after the standing grant was created: that agent's own decision stands.
	MatchStandingGrant(ctx context.Context, agentID int64, connector, source, repo string) (StandingGrant, error)
	// ApproveFromStanding approves PENDING grant id from live standing grant sg
	// (recording the standing grant's credential source); ErrNotPending when the
	// grant is no longer pending or the standing grant is no longer live.
	ApproveFromStanding(ctx context.Context, id, sg int64) (Grant, error)
	// RevokeStandingGrant revokes a live standing grant AND every approved grant
	// it gave (the ones it approved automatically, and the approval it was
	// created from), returning the grants it revoked. ErrNotPending when it was
	// already revoked.
	RevokeStandingGrant(ctx context.Context, id int64, by string) (StandingGrant, []Grant, error)
	// ListStandingGrants returns the owner's live standing grants.
	ListStandingGrants(ctx context.Context) ([]StandingGrant, error)

	Audit(ctx context.Context, e AuditEntry) error
	ListAudit(ctx context.Context, limit int) ([]AuditEntry, error)
	PruneAudit(ctx context.Context, before time.Time) (int64, error)
}

Store persists connectors, grants and the audit trail.

func WithVirtual

func WithVirtual(s Store, v Virtual, allow func(context.Context) bool) Store

WithVirtual returns s with v presented as a connector named v.Describe().Name to the principals allow admits (see the file comment). A nil v returns s unchanged; a nil allow admits nobody.

type Virtual

type Virtual interface {
	// Describe is the connector's public description. Its Name is the name it
	// answers to; its Hosts are the allowlist the proxy enforces BEFORE asking for
	// a credential.
	Describe() Connector
	// Credential returns the secret to inject for caller's request to host/rest
	// (rest as the proxy received it: escaped, no leading slash). host is already
	// on Describe().Hosts. anonymous=true means forward the request with NO
	// credential at all (secret is then ""). A request the connector refuses for
	// this caller is [ErrTargetRefused]; any other error means no credential
	// could be produced, and its text is shown to the agent and the operator, so
	// it must never carry a secret.
	Credential(ctx context.Context, caller Caller, host, rest string) (secret string, anonymous bool, err error)
	// Rejected tells the connector the upstream answered 401 to a request that
	// carried the secret Credential returned for caller, so a cached credential
	// can be dropped.
	Rejected(caller Caller)
	// Problem is the operator-facing reason this connector cannot currently serve
	// agentID (0: any agent), or "" when nothing is known to be wrong.
	Problem(agentID int64) string
}

Virtual is a connector whose credential is minted per request.

func KubeReadVirtual added in v0.153.0

func KubeReadVirtual() Virtual

KubeReadVirtual is the kube-read connector, presented through the store by WithVirtual so an officer instance's request for it is filed, shown on a request card and approved BY HAND like every other officer connector grant.

🔴 IT HOLDS NO CREDENTIAL AND HAS NO HTTP FACE. Each cluster's endpoint, CA and minter token are the server's sealed environment (the officer `kube` block, internal/officers), read only by officer_kube_read inside muster-server. Describe names no host, and the proxy refuses the scheme before any host check, so /connect/kube-read/… reaches nothing.

func VirtualOf

func VirtualOf(ctx context.Context, s Store, name string) (Virtual, bool)

VirtualOf returns the virtual connector s presents under name to ctx's principal, if any. The proxy uses it to take the credential from the connector rather than from the sealed-secret table; the UI uses it to mark the connector as managed.

Wrappers nest (the GitHub App's, then kube-read's: KubeReadVirtual), so it looks through each in turn: the outer one answering for its own name only, as every virtualStore method does.

Jump to

Keyboard shortcuts

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