config

package
v0.18.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 26 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 config loads locksql profiles from the project and user config files, applies defaults, refuses anything that looks like a secret, and computes the security-relevant policy of a profile.

Index

Constants

View Source
const (
	PresetFullAuto = "full-auto"
	PresetDefault  = "default"
)

PresetFullAuto sets every action to auto; PresetDefault is the defaults (DefaultAutoRules).

View Source
const (
	WriteFunctionsDenylist  = "denylist"
	WriteFunctionsAllowlist = "allowlist"
)

Values of write_functions. The default, denylist, is stored as "" so that policies approved before the setting existed keep their fingerprint.

View Source
const (
	EngineMariaDB  = "mariadb"
	EngineMySQL    = "mysql"
	EnginePostgres = "postgres"
	EngineSQLite   = "sqlite"
)

Supported engines.

View Source
const (
	MinIdleTimeout = time.Minute
	MaxMaxSession  = 24 * time.Hour
)

Bounds of the session limits: MinIdleTimeout <= idle_timeout <= max_session <= MaxMaxSession.

View Source
const (
	DefaultGrantMaxDuration   = time.Hour
	DefaultGrantMaxStatements = 200
	DefaultGrantMaxRows       = 10_000
	DefaultGrantMaxBytes      = 1 << 20 // 1 MiB
	// MaxGrantDuration bounds limits.grant_max_duration: a grant never
	// outlives the longest session anyway.
	MaxGrantDuration = MaxMaxSession
)

Grant limits: the most a grant may ask for (#171). A grant is one human decision covering a bounded read scope: a database, tables, a duration and a read budget. The limits are profile limits; a request above them is clamped to them, never refused.

View Source
const (
	TLSDisable    = kconfig.TLSDisable
	TLSPrefer     = kconfig.TLSPrefer
	TLSRequire    = kconfig.TLSRequire
	TLSVerifyCA   = kconfig.TLSVerifyCA
	TLSVerifyFull = kconfig.TLSVerifyFull
)

TLS modes of a network profile, as libpq's sslmode, in increasing strength.

View Source
const (
	CredentialsAsk      = kconfig.CredentialsAsk
	CredentialsKeychain = kconfig.CredentialsKeychain
	CredentialsVault    = kconfig.CredentialsVault
)

Credentials modes. CredentialsVault reads the user and password from HashiCorp Vault with the vault CLI at every connection (Profile.VaultPath).

View Source
const (
	SSHAuthKey      = kconfig.SSHAuthKey
	SSHAuthAgent    = kconfig.SSHAuthAgent
	SSHAuthPassword = kconfig.SSHAuthPassword
)

SSH authentication methods.

View Source
const DefaultMaskMode = "redact"

DefaultMaskMode is the mode of a mask rule that sets none.

View Source
const DefaultSSHPort = kconfig.DefaultSSHPort

DefaultSSHPort is the port of an ssh table that leaves port unset.

View Source
const ManagedTool = "locksql"

ManagedTool is locksql's section of the company's managed file ([locksql.bounds], [locksql.defaults], [locksql.profiles.<name>]).

View Source
const ShareFormat = 1

ShareFormat is the version of the shared configuration file this release reads and writes. A newer file is refused; an older one is migrated in DecodeShare.

Variables

AutoActions lists the actions in the order they are shown.

View Source
var DefaultAutoRules = AutoRules{Connect: AutoAsk, Read: AutoAuto, Write: AutoAsk, DDL: AutoAsk, Unmask: AutoAsk}

DefaultAutoRules is the auto mode of a profile that sets none: connect asked once per session, reads auto, writes, schema changes and unmasked results asked every time.

View Source
var ErrNotShareable = errors.New("not shareable")

ErrNotShareable marks a profile that cannot be shared: a SQLite file or a Unix socket is a path of one machine.

View Source
var FullAutoRules = AutoRules{Connect: AutoAuto, Read: AutoAuto, Write: AutoAuto, DDL: AutoAuto, Unmask: AutoAuto}

FullAutoRules is the full-auto preset: every action auto.

View Source
var HandLocalKeys = []string{"proxy_command"}

HandLocalKeys are local keys that only the importer's own config file may set: proxy_command is a command line, which neither a shared file nor --local may bring. An import keeps the local value, or skips the profile.

View Source
var LocalKeys = []string{"tls_ca", "tls_cert", "tls_key", "ssh.key"}

LocalKeys are the keys that name files of one machine: never exported, listed in needs_local, given on import with --local NAME.KEY=VALUE.

Functions

func ApprovedKey

func ApprovedKey(root, profile string) string

ApprovedKey names the approved-policy file of a profile: <ProjectHash(root)>-<profile>, or user-<profile> for a profile that comes from the user config only (root == "").

func AutoRuleOf added in v0.17.0

func AutoRuleOf(r AutoRules, class Tier, unmask bool) (AutoAction, AutoValue)

AutoRuleOf is the action of a statement class (read, write, ddl, admin), unmasked or not. An unmasked statement of any class (a read, or a write or schema change whose RETURNING rows come back in clear) is decided by the stricter of its class's action and unmask (unmask when they are equal), so that a looser write or ddl rule never lets cleartext results through an unmask rule that asks or denies.

func CheckFiles added in v0.17.2

func CheckFiles(p Profile, home string) error

CheckFiles opens every file key of p, resolved in home, so that a missing or unreadable file stops the console before any question that needs the network or a secret. Errors name the key and the path, never the content.

func DefaultDetectors

func DefaultDetectors() []string

DefaultDetectors is the detector set used when a profile does not set detectors. National id detectors are opt-in.

func DefaultPort added in v0.5.0

func DefaultPort(engine string) int

DefaultPort is the port of engine when a profile leaves port unset, 0 for an engine without one (sqlite).

func EncodeShare added in v0.9.0

func EncodeShare(w io.Writer, s Share) error

EncodeShare writes s as indented JSON, keys sorted.

func ExpandHome added in v0.17.2

func ExpandHome(path, home string) string

ExpandHome resolves a leading "~/" (or a lone "~") of a file key's path to home, the console account's home, as ssh.key always did; any other path is returned as is.

func FindProjectRoot

func FindProjectRoot(cwd string) (string, bool)

FindProjectRoot walks up from cwd to the first directory holding .locksql/config.toml.

func Fingerprint

func Fingerprint(p Policy) string

Fingerprint returns the hex sha256 of the policy's canonical JSON. List order does not change the fingerprint. Only an out-of-range Tier can fail to encode; lockkit then fingerprints its raw form so that it still differs from every valid policy.

func HomePath added in v0.17.2

func HomePath(path string) string

HomePath is ExpandHome with this account's home; path as is when the home is unknown.

func IsLocalKey added in v0.9.0

func IsLocalKey(key string) bool

IsLocalKey reports whether key is one of LocalKeys.

func IsLoopback added in v0.4.0

func IsLoopback(host string) bool

IsLoopback reports "localhost" or a loopback IP literal.

func PIIPatternsOverlap added in v0.18.0

func PIIPatternsOverlap(a, b string) bool

PIIPatternsOverlap reports whether some column db.table.column could match both patterns a and b (valid patterns): segment by segment, the way package pii folds names. It errs toward true: an allow rule that overlaps a managed mask is refused.

func ParsePIIPattern added in v0.18.0

func ParsePIIPattern(p string) (string, error)

ParsePIIPattern validates a PII rule pattern "db.table.column": three non-empty segments, each '*' or a name without '.', quotes, blanks, control characters or format characters (bidi controls, zero-width marks), with at most one leading and one trailing '*'. Patterns are shown to the human in review diffs, where such characters could hide text. Errors never quote the pattern, which may be a secret pasted in the wrong place. Package pii validates its rules with it; the managed bounds' pii_mask too.

func ParseProfiles added in v0.1.2

func ParseProfiles(data []byte, name, baseDir string) (map[string]Profile, error)

ParseProfiles decodes and validates config data. name labels errors. Relative sqlite paths are resolved against baseDir. Errors never quote config values that could be secrets.

func ProjectHash

func ProjectHash(root string) string

ProjectHash returns the first 8 hex digits of sha256 of the absolute, cleaned project root.

func ProjectKey

func ProjectKey(cwd string) string

ProjectKey names the project of cwd in socket paths: ProjectHash of the project root, or "user" when cwd is outside any project (profiles from the user config only). The console and its clients must agree on it.

func ProxyString added in v0.9.0

func ProxyString(argv []string) string

ProxyString renders a proxy_command argv for the approval screens, each argument quoted so that one holding a space cannot read as two.

func RuleSetOf added in v0.9.0

func RuleSetOf(p Profile) string

RuleSetOf is the PII rule set of p from its config: pii_rules, or the profile name in lower case. Sharing a set is opt-in.

func SSHString added in v0.4.0

func SSHString(s *SSHProfile) string

SSHString shows a bastion in a policy change.

func SaveApproved

func SaveApproved(stateDir, key string, p Policy) error

SaveApproved atomically writes the policy to <stateDir>/locksql/approved/<key>.json with mode 0600.

func SaveApprovedManaged added in v0.18.0

func SaveApprovedManaged(stateDir, key string, p Policy, managedFP string) error

SaveApprovedManaged is SaveApproved recording the fingerprint of the company's managed file in force (managed_sha256; "" for none).

func SaveConfirmed added in v0.16.1

func SaveConfirmed(stateDir, key string, p Policy) error

SaveConfirmed records p as the production policy whose profile name the human typed under key.

func StateDir

func StateDir() (string, error)

StateDir returns the user state directory (without the locksql suffix): $XDG_STATE_HOME or ~/.local/state on Linux and other Unix systems, and os.UserConfigDir() on macOS.

func TLSRank added in v0.4.0

func TLSRank(mode string) int

TLSRank orders TLS modes by strength ("" is prefer, unknown is -1).

func UserConfigPath added in v0.1.2

func UserConfigPath() (string, error)

UserConfigPath returns <user config dir>/locksql/config.toml.

func ValidRuleSet added in v0.9.0

func ValidRuleSet(s string) bool

ValidRuleSet reports whether s may name a PII rule set.

Types

type AutoAction added in v0.17.0

type AutoAction string

AutoAction is what a rule applies to.

const (
	// ActionConnect opens the profile's connection.
	ActionConnect AutoAction = "connect"
	// ActionRead runs a read (SELECT, a grant's scope).
	ActionRead AutoAction = "read"
	// ActionWrite runs a write: INSERT, UPDATE, UPSERT, DELETE, MERGE.
	ActionWrite AutoAction = "write"
	// ActionDDL runs a schema change, or an admin statement.
	ActionDDL AutoAction = "ddl"
	// ActionUnmask runs a statement whose results come back in clear: a
	// read, or a write or schema change with RETURNING rows.
	ActionUnmask AutoAction = "unmask"
)

The actions of an auto rule.

type AutoRules added in v0.17.0

type AutoRules struct {
	Connect AutoValue `json:"connect,omitempty"`
	Read    AutoValue `json:"read,omitempty"`
	Write   AutoValue `json:"write,omitempty"`
	DDL     AutoValue `json:"ddl,omitempty"`
	Unmask  AutoValue `json:"unmask,omitempty"`
}

AutoRules is the auto mode of a profile, one value per action. The zero value of a field is its default (DefaultAutoRules): a profile stores only what differs from it, so that a policy approved before auto rules existed keeps its fingerprint.

func (AutoRules) Effective added in v0.17.0

func (r AutoRules) Effective() AutoRules

Effective is r with every action set (defaults filled in).

func (AutoRules) Get added in v0.17.0

func (r AutoRules) Get(a AutoAction) AutoValue

Get is the value of action a, its default when r does not set it.

func (AutoRules) Preset added in v0.17.0

func (r AutoRules) Preset() string

Preset names the preset r is, "" for none.

func (AutoRules) String added in v0.17.0

func (r AutoRules) String() string

String is r in one line: "connect ask · read auto · write ask · ddl ask · unmask ask", with the preset it is when it is one.

type AutoValue added in v0.17.0

type AutoValue string

AutoValue is what auto mode does with one action.

const (
	// AutoDeny refuses the action, even when a human would approve it.
	AutoDeny AutoValue = "deny"
	// AutoAsk asks the human: once per lox run session for connect, every
	// time for the other actions.
	AutoAsk AutoValue = "ask"
	// AutoAuto approves the action without a question.
	AutoAuto AutoValue = "auto"
)

The values of an action, from the strictest.

func ParseAutoValue added in v0.17.0

func ParseAutoValue(s string) (AutoValue, error)

ParseAutoValue parses "auto", "ask" or "deny".

type Bounds added in v0.18.0

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

Bounds are [locksql.bounds] and the [family] rules locksql enforces: the loosest policy the company allows. A nil *Bounds bounds nothing.

func (*Bounds) ApplyPII added in v0.18.0

func (b *Bounds) ApplyPII(mask, allow []string, modes map[string]string) ([]string, []string, map[string]string, error)

ApplyPII adds the managed mask rules to the PII rules of a profile (its mask and allow patterns, and the modes of its masks), whatever its rule set: a user mask of a managed pattern takes the managed mode. A user allow rule that could clear what a managed rule masks is refused: a user can add rules, never remove or weaken a managed one.

func (*Bounds) Ceiling added in v0.18.0

func (b *Bounds) Ceiling(pol Policy) (*Policy, map[string]string, error)

Ceiling returns pol at its ceiling under b: pol with every bounded field set to its bound, which Diff then compares pol with, and the bound keys of the Diff fields whose names differ. A value outside an allowlist Diff cannot express (credentials, engine, hosts, family.vault.required) is a *BoundsError naming the managed key. A nil b bounds nothing: nil.

func (*Bounds) Describe added in v0.18.0

func (b *Bounds) Describe() []string

Describe is the bounds as lines for `locksql managed show`.

func (*Bounds) Masks added in v0.18.0

func (b *Bounds) Masks() []MaskRule

Masks are the managed mask rules, nil for a nil b.

func (*Bounds) Require added in v0.18.0

func (b *Bounds) Require(ps map[string]Profile)

Require adds the detectors the bounds require to every profile of ps.

func (*Bounds) Violations added in v0.18.0

func (b *Bounds) Violations(pol Policy) ([]string, error)

Violations are the lines that refuse pol, each "blocked by company policy: …". An error is a bounds section that cannot be applied.

type BoundsError added in v0.18.0

type BoundsError struct {
	Violations []managed.Violation
}

BoundsError is a policy outside an allowlist bound: credentials, engine, hosts, family.vault.required. The console refuses it as a violation.

func (*BoundsError) Error added in v0.18.0

func (e *BoundsError) Error() string

Error cites each violation as managed.Violation does, without its "blocked by company policy: " lead, which the console adds.

type Change

type Change = kconfig.Change

Change is one difference between two policies.

func Diff

func Diff(approved, current Policy) []Change

Diff lists the changes from approved to current and marks each loosening (spec section 4): a higher tier, production true→false, a larger limit (0 means unlimited), a longer idle_timeout or max_session, a removed PII rule or detector, an added allow rule, any change of engine, host, port, path, database or user, a weaker tls mode, another tls_ca or tls_server_name, a credentials mode other than ask, any change of the ssh table or of proxy_command, any change of the PII rule set, write_functions from allowlist to denylist, and an auto rule moved toward auto (deny → ask → auto).

type Config

type Config struct {
	// ProjectRoot is the directory holding .locksql/config.toml, or "" when
	// no project config was found.
	ProjectRoot string
	Profiles    map[string]Profile
	// Managed is locksql's part of the company's managed file (nil: none):
	// its profiles are in Profiles, its defaults applied, its required
	// detectors added.
	Managed *Managed
}

Config is the merged set of profiles visible from a working directory.

func Load

func Load(cwd string) (*Config, error)

Load reads the project config (found by walking up from cwd), the user config (<user config dir>/locksql/config.toml) and the company's managed file. On a profile name present in both config files, the project profile wins as a whole; a managed profile wins over both, and either file redefining it is an error.

func LoadFrom

func LoadFrom(cwd, userConfigPath string) (*Config, error)

LoadFrom is Load with an explicit user config path ("" for none). A missing user config file is not an error.

func LoadWith added in v0.18.0

func LoadWith(cwd, userConfigPath string, m *Managed) (*Config, error)

LoadWith is LoadFrom with the managed part already read (nil: none).

type ConfigFile added in v0.9.0

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

ConfigFile is a config file as written, for editing: profiles the edit does not touch are written back with the keys they had.

func ParseConfigFile added in v0.9.0

func ParseConfigFile(data []byte, name, baseDir string) (*ConfigFile, error)

ParseConfigFile decodes config data for editing. It is checked like ParseProfiles; name labels errors and baseDir resolves sqlite paths.

func (*ConfigFile) Import added in v0.9.0

func (f *ConfigFile) Import(s *Share, o ImportOptions) ([]Skipped, error)

Import merges the profiles of s into f. An imported profile replaces the profile of the same name, but keeps its user (unless the share sets one) and its local keys (unless --local sets them). A profile whose needs_local keys are neither given nor kept is skipped. --local values for a key that is not local, or for a profile not imported, are refused.

func (*ConfigFile) Names added in v0.9.0

func (f *ConfigFile) Names() []string

Names lists the profiles of f, sorted.

func (*ConfigFile) TOML added in v0.9.0

func (f *ConfigFile) TOML(header string) []byte

TOML writes f as a config file: header, then one table per profile, sorted, with only the keys a profile sets. Every string is quoted and escaped; values were checked for control characters on the way in, and the result is parsed again by the caller before it is written.

type FileKey added in v0.17.2

type FileKey struct {
	Key  string
	Path string
}

FileKey is a profile key that names a file the console reads: Path as written in the config, "~/" included.

type GrantLimits added in v0.16.0

type GrantLimits struct {
	Duration   time.Duration
	Statements int64
	Rows       int64
	Bytes      int64
}

GrantLimits are the effective grant limits of a profile.

type ImportOptions added in v0.9.0

type ImportOptions struct {
	// Only, when not empty, limits the import to these profiles.
	Only []string
	// Replace drops the profiles of the file that the import does not
	// hold; by default they are kept.
	Replace bool
	// Local are the --local values: profile -> key -> value.
	Local map[string]map[string]string
}

ImportOptions steer ConfigFile.Import.

type Limits

type Limits struct {
	StatementTimeout  time.Duration `toml:"statement_timeout" json:"statement_timeout"`
	ExplainRowsWarn   int64         `toml:"explain_rows_warn" json:"explain_rows_warn"`
	ExplainRowsRefuse int64         `toml:"explain_rows_refuse" json:"explain_rows_refuse"`
	MaxRows           int           `toml:"max_rows" json:"max_rows"`
	MaxCellChars      int           `toml:"max_cell_chars" json:"max_cell_chars"`
	MaxOutputBytes    int           `toml:"max_output_bytes" json:"max_output_bytes"`
	// ExplainCostRefuse refuses a plan whose total cost, in the engine's
	// own units, is above it; 0 disables the check. Engines without a cost
	// (SQLite) are not checked.
	ExplainCostRefuse float64 `toml:"explain_cost_refuse" json:"explain_cost_refuse,omitempty"`
	// KAnonymity is the smallest number of rows a PII filter, a grouping
	// on a PII column or an aggregate of one may cover without a warning
	// on the approval screen.
	KAnonymity int `toml:"k_anonymity" json:"k_anonymity,omitempty"`
	// ReferenceProbe has no effect since cell references are not
	// supported; it is still read, so that existing configs load, and
	// raising it is still a loosening.
	ReferenceProbe int `toml:"reference_probe" json:"reference_probe,omitempty"`
	// IdleTimeout ends the console session after that long without
	// activity, MaxSession after that long in all; raising either is a
	// loosening. Bounds: 1m <= IdleTimeout <= MaxSession <= 24h.
	IdleTimeout time.Duration `toml:"idle_timeout" json:"idle_timeout,omitempty"`
	MaxSession  time.Duration `toml:"max_session" json:"max_session,omitempty"`
	// The grant limits (Grants): the longest grant and its largest read
	// budget. Zero is the default; GrantsOff (grant_max_duration = 0 in
	// the file) disables grants. Raising any of them is a loosening.
	GrantMaxDuration   time.Duration `toml:"grant_max_duration" json:"grant_max_duration,omitempty"`
	GrantMaxStatements int64         `toml:"grant_max_statements" json:"grant_max_statements,omitempty"`
	GrantMaxRows       int64         `toml:"grant_max_rows" json:"grant_max_rows,omitempty"`
	GrantMaxBytes      int64         `toml:"grant_max_bytes" json:"grant_max_bytes,omitempty"`
	GrantsOff          bool          `toml:"-" json:"grants_off,omitempty"`
	// The hub client's ticket limits (TicketLimits): at most
	// TicketsPerWindow tickets a human decides per TicketWindow, and
	// MaxPending tickets pending. Zero keeps lockkit's default (30 per 5m,
	// 30 pending). Raising either count or shortening the window is a
	// loosening.
	TicketsPerWindow int           `toml:"tickets_per_window" json:"tickets_per_window,omitempty"`
	TicketWindow     time.Duration `toml:"ticket_window" json:"ticket_window,omitempty"`
	MaxPending       int           `toml:"max_pending" json:"max_pending,omitempty"`
}

Limits bound the cost and size of one statement.

func DefaultLimits

func DefaultLimits(production bool) Limits

DefaultLimits returns the limits applied to unset (zero) limit fields.

func (Limits) Grants added in v0.16.0

func (l Limits) Grants() (GrantLimits, bool)

Grants returns the effective grant limits of l (an unset limit is its default) and whether grants are enabled: limits.grant_max_duration = 0 disables them.

func (Limits) TicketLimits added in v0.18.0

func (l Limits) TicketLimits() hubclient.Limits

TicketLimits are the hub client's limits of l, lockkit's defaults applied where l sets none: what the console passes to hubclient.Client.SetLimits once the policy is in force.

type Managed added in v0.18.0

type Managed struct {
	File *managed.File
	// Defaults is [locksql.defaults] as the file holds it (nil: none): the
	// keys a profile leaves unset take it.
	Defaults map[string]any
	// Profiles are [locksql.profiles.<name>], built with the defaults.
	Profiles map[string]Profile
	// Bounds are [locksql.bounds] and the [family] rules locksql enforces
	// (nil: none).
	Bounds *Bounds
}

Managed is locksql's part of the company's managed file (lockkit managed): its defaults, its profiles and its bounds. A nil *Managed is no managed file.

func LoadManaged added in v0.18.0

func LoadManaged() (*Managed, error)

LoadManaged reads the machine's managed file: nil and no error when there is none. A file lockkit refuses (badly owned, invalid, badly signed) or a locksql section that is invalid or beyond its own bounds is an error: the caller refuses to start.

func ParseManaged added in v0.18.0

func ParseManaged(f *managed.File) (*Managed, error)

ParseManaged reads locksql's part of f (nil: none). A managed default or a managed profile beyond the bounds is an error.

func (*Managed) BoundsOf added in v0.18.0

func (m *Managed) BoundsOf() *Bounds

BoundsOf is m's bounds, nil for a nil m.

func (*Managed) DescribeDefaults added in v0.18.0

func (m *Managed) DescribeDefaults() []string

DescribeDefaults is [locksql.defaults] as lines for `locksql managed show` ("locksql.defaults.limits.max_rows = 100").

type MaskRule added in v0.18.0

type MaskRule struct {
	Column, Mode string
}

MaskRule is one [[locksql.bounds.pii_mask]]: a column pattern (db.table.column, as [[mask]] in a PII rule set) and its mode.

type Policy

type Policy struct {
	Profile  Profile  `json:"profile"`
	PIIMask  []string `json:"pii_mask"`  // sorted column patterns
	PIIAllow []string `json:"pii_allow"` // sorted column patterns
	// PIIModes maps a mask pattern to its mode when it is not the default
	// (redact): partial or email.
	PIIModes map[string]string `json:"pii_modes,omitempty"`
}

Policy is the security-relevant view of one profile plus its PII rules. The console compares the current policy with the last approved one and asks the human before applying any loosening.

func Canonical added in v0.11.0

func Canonical(p Policy) Policy

Canonical is p in its canonical form: sorted lists, defaults applied. Its JSON is what is saved as the approved policy and fingerprinted.

func LoadApproved

func LoadApproved(stateDir, key string) (*Policy, error)

LoadApproved reads <stateDir>/locksql/approved/<key>.json. When no policy was approved yet, the error wraps fs.ErrNotExist.

func LoadConfirmed added in v0.16.1

func LoadConfirmed(stateDir, key string) (*Policy, error)

LoadConfirmed reads the production policy confirmed by its typed profile name under key. When none was confirmed yet, the error wraps fs.ErrNotExist.

func NewPolicy

func NewPolicy(p Profile, mask, allow []string) Policy

NewPolicy builds a policy with sorted, de-duplicated PII lists.

func (Policy) WithModes

func (p Policy) WithModes(m map[string]string) Policy

WithModes returns p with the mask modes m (pattern -> mode).

type Profile

type Profile struct {
	Name        string `json:"name"`
	Engine      string `json:"engine"`
	Host        string `json:"host"`
	Path        string `json:"path"`
	User        string `json:"user"`
	Database    string `json:"database"`
	Credentials string `json:"credentials"`
	// TLS is the transport mode (TLSDisable ... TLSVerifyFull), passed to
	// the driver with libpq's sslmode semantics, and TLSCA an optional PEM
	// bundle that replaces the system roots. locksql enforces none of them.
	TLS   string `json:"tls,omitempty"`
	TLSCA string `json:"tls_ca,omitempty"`
	// TLSCert and TLSKey are the PEM files of a client certificate and its
	// private key, presented when the server asks for one. TLSServerName
	// replaces host as the name verify-full checks in the certificate.
	TLSCert       string `json:"tls_cert,omitempty"`
	TLSKey        string `json:"tls_key,omitempty"`
	TLSServerName string `json:"tls_server_name,omitempty"`
	// SSH, when set, is the bastion the profile is reached through.
	SSH *SSHProfile `json:"ssh,omitempty"`
	// ProxyCommand, when set, is the argv of a command whose stdin and
	// stdout carry each connection to the database, as OpenSSH's
	// ProxyCommand: docker exec, kubectl exec, ssh to a socket and so on.
	// It runs without a shell, as the console account.
	ProxyCommand []string `json:"proxy_command,omitempty"`
	Port         int      `json:"port"`
	Tier         Tier     `json:"tier"`
	Production   bool     `json:"production"`
	Detectors    []string `json:"detectors"`
	Limits       Limits   `json:"limits"`
	// CredentialsTTL makes the console ask for the secret again (and
	// reconnect) once the connection is that old; 0 keeps it for the
	// session. It suits short-lived secrets from a vault.
	CredentialsTTL time.Duration `json:"credentials_ttl,omitempty"`
	// VaultPath is the Vault path read for the login when Credentials is
	// "vault", such as "database/creds/app-readonly".
	VaultPath string `json:"vault_path,omitempty"`
	// PIIRules names the PII rule set of the profile: the file
	// pii/<set>.toml next to the config. The config holds the pii_rules
	// key, "" when it is not set; the console stores the set it resolved
	// (RuleSetOf, or the migrated default set) in the policy it approves.
	PIIRules string `json:"pii_rules,omitempty"`
	// WriteFunctions is "" (the denylist of every class) or
	// WriteFunctionsAllowlist: writes may call allowlisted functions only.
	WriteFunctions string `json:"write_functions,omitempty"`
	// Auto is the profile's auto mode (auto.go): only the actions that
	// differ from DefaultAutoRules, nil when none does. Read it with
	// AutoRules.
	Auto *AutoRules `json:"auto,omitempty"`
}

Profile is one named database target with its policy. It never holds a secret.

func (Profile) AutoRules added in v0.17.0

func (p Profile) AutoRules() AutoRules

AutoRules is the effective auto mode of p.

func (Profile) FileKeys added in v0.17.2

func (p Profile) FileKeys() []FileKey

FileKeys are the file keys p sets: tls_ca, tls_cert, tls_key and, with ssh auth = "key", ssh.key.

type SSHProfile added in v0.4.0

type SSHProfile = kconfig.SSHProfile

SSHProfile is the bastion a network profile is reached through.

type Share added in v0.9.0

type Share struct {
	Format   int                      `json:"locksql_config_format"`
	Version  string                   `json:"locksql_version,omitempty"`
	Profiles map[string]SharedProfile `json:"profiles"`
	PII      map[string]SharedRules   `json:"pii,omitempty"`
}

Share is a shareable locksql configuration (locksql config export): the shared keys of some profiles and the PII rule sets they use, keyed by set name. It never holds a secret nor a machine-specific value.

func DecodeShare added in v0.9.0

func DecodeShare(data []byte) (*Share, error)

DecodeShare reads a shared configuration strictly: an unknown field at any depth, a format newer than ShareFormat, a profile or set name that is not valid, a secret-like or unsafe value, a needs_local key that is not local, or trailing data are refused. Errors never quote a value.

type SharedLimits added in v0.9.0

type SharedLimits struct {
	StatementTimeout  string  `json:"statement_timeout,omitempty"`
	ExplainRowsWarn   int64   `json:"explain_rows_warn,omitempty"`
	ExplainRowsRefuse int64   `json:"explain_rows_refuse,omitempty"`
	MaxRows           int     `json:"max_rows,omitempty"`
	MaxCellChars      int     `json:"max_cell_chars,omitempty"`
	MaxOutputBytes    int     `json:"max_output_bytes,omitempty"`
	ExplainCostRefuse float64 `json:"explain_cost_refuse,omitempty"`
	KAnonymity        int     `json:"k_anonymity,omitempty"`
	ReferenceProbe    int     `json:"reference_probe,omitempty"`
	IdleTimeout       string  `json:"idle_timeout,omitempty"`
	MaxSession        string  `json:"max_session,omitempty"`
	// GrantMaxDuration is "0s" when grants are off.
	GrantMaxDuration   string `json:"grant_max_duration,omitempty"`
	GrantMaxStatements int64  `json:"grant_max_statements,omitempty"`
	GrantMaxRows       int64  `json:"grant_max_rows,omitempty"`
	GrantMaxBytes      int64  `json:"grant_max_bytes,omitempty"`
	TicketsPerWindow   int    `json:"tickets_per_window,omitempty"`
	TicketWindow       string `json:"ticket_window,omitempty"`
	MaxPending         int    `json:"max_pending,omitempty"`
}

SharedLimits are the limits of a SharedProfile; durations as Go duration strings.

type SharedProfile added in v0.9.0

type SharedProfile struct {
	Engine         string   `json:"engine"`
	Host           string   `json:"host,omitempty"`
	Port           int      `json:"port,omitempty"`
	User           string   `json:"user,omitempty"`
	Database       string   `json:"database,omitempty"`
	Credentials    string   `json:"credentials,omitempty"`
	VaultPath      string   `json:"vault_path,omitempty"`
	CredentialsTTL string   `json:"credentials_ttl,omitempty"`
	TLS            string   `json:"tls,omitempty"`
	TLSServerName  string   `json:"tls_server_name,omitempty"`
	Tier           string   `json:"tier,omitempty"`
	Production     bool     `json:"production,omitempty"`
	Detectors      []string `json:"detectors"`
	PIIRules       string   `json:"pii_rules,omitempty"`
	WriteFunctions string   `json:"write_functions,omitempty"`
	// Auto is the profile's auto mode, the actions that differ from the
	// defaults (nil: the defaults).
	Auto       *AutoRules    `json:"auto,omitempty"`
	Limits     *SharedLimits `json:"limits,omitempty"`
	SSH        *SharedSSH    `json:"ssh,omitempty"`
	NeedsLocal []string      `json:"needs_local,omitempty"`
}

SharedProfile holds the keys of a profile that a team shares. The keys of one machine (LocalKeys) are never in it: NeedsLocal names those the source profile had, which the importer supplies with --local. User is exported only on request: it is the employee's own login.

func ExportProfile added in v0.9.0

func ExportProfile(p Profile, set string, includeUser bool) (SharedProfile, error)

ExportProfile is the shared form of the resolved profile p, whose PII rule set is set. It fails with ErrNotShareable for a SQLite or Unix socket profile, and refuses a value that looks like a secret.

type SharedRule added in v0.9.0

type SharedRule struct {
	Column string `json:"column"`
	Mode   string `json:"mode,omitempty"`
}

SharedRule is one PII rule: a column pattern and, for a mask rule, its mode when it is not redact.

type SharedRules added in v0.9.0

type SharedRules struct {
	Mask  []SharedRule `json:"mask"`
	Allow []SharedRule `json:"allow"`
}

SharedRules is one PII rule set in a Share.

type SharedSSH added in v0.9.0

type SharedSSH struct {
	Host        string `json:"host"`
	Port        int    `json:"port,omitempty"`
	User        string `json:"user"`
	Auth        string `json:"auth"`
	Credentials string `json:"credentials,omitempty"`
}

SharedSSH is the bastion of a SharedProfile, without its key file.

type Skipped added in v0.9.0

type Skipped struct{ Profile, Reason string }

Skipped is a profile of the share that was not imported, and why.

type Tier

type Tier int

Tier is the highest statement class a profile may run. The order is TierRead < TierWrite < TierDDL < TierAdmin.

const (
	TierRead Tier = iota
	TierWrite
	TierDDL
	TierAdmin
)

Tiers, in increasing order of privilege.

func ParseTier

func ParseTier(s string) (Tier, error)

ParseTier parses "read", "write", "ddl" or "admin".

func (Tier) MarshalText

func (t Tier) MarshalText() ([]byte, error)

MarshalText encodes the tier by name.

func (Tier) String

func (t Tier) String() string

func (*Tier) UnmarshalText

func (t *Tier) UnmarshalText(b []byte) error

UnmarshalText decodes a tier name.

Jump to

Keyboard shortcuts

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