config

package
v0.267.0 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package config loads and persists ofga configuration: a set of named connection profiles (contexts) plus the name of the active one. Values are stored as TOML in the platform config directory and can be overridden by OPENFGA_* environment variables and command-line flags.

Index

Constants

View Source
const (
	AuthNone              = "none"
	AuthAPIToken          = "api_token"
	AuthClientCredentials = "client_credentials"
	AuthPrivateKeyJWT     = "private_key_jwt"
)

Auth method names for Auth.Method.

View Source
const (

	// DefaultAPIURL is the address of a stock local OpenFGA server.
	DefaultAPIURL = "http://localhost:8080"
)
View Source
const SchemaVersion = 1

Config is the on-disk configuration document. SchemaVersion is the current on-disk config format version, written on Save and available to gate future migrations.

Variables

View Source
var ErrNoProfile = errors.New("profile not found")

ErrNoProfile is returned when a requested profile does not exist.

Functions

func DefaultPath

func DefaultPath() string

DefaultPath returns the resolved config file path, or "" if it can't be determined. Useful before a Config is loaded (e.g. to point at a broken file).

func PurgeAllSecrets

func PurgeAllSecrets() error

PurgeAllSecrets deletes every secret this CLI stored in the OS keyring. It is the only way to reclaim entries orphaned by a hand-deleted config: go-keyring can't enumerate accounts, so per-profile reconciliation can't find them once the config naming them is gone. This is all-or-nothing across every profile and config on this machine.

func SaveWasCommitted

func SaveWasCommitted(err error) bool

SaveWasCommitted reports whether Save replaced the config before a post-rename durability sync failed. Callers must retain their in-memory changes in this case rather than rolling back over the replaced file.

Types

type Auth

type Auth struct {
	Method string `toml:"method,omitempty" json:"method,omitempty"` // none | api_token | client_credentials | private_key_jwt

	Token string `toml:"token,omitempty" json:"-"` // secret; never serialized to JSON output

	// client_credentials and private_key_jwt share the OAuth2 grant shape.
	ClientID     string   `toml:"client_id,omitempty" json:"client_id,omitempty"`
	ClientSecret string   `toml:"client_secret,omitempty" json:"-"` // secret; never serialized to JSON output
	TokenURL     string   `toml:"token_url,omitempty" json:"token_url,omitempty"`
	Audience     string   `toml:"audience,omitempty" json:"audience,omitempty"`
	Scopes       []string `toml:"scopes,omitempty" json:"scopes,omitempty"`

	// private_key_jwt.
	APIAudience   string `toml:"api_audience,omitempty" json:"api_audience,omitempty"` // audience requested in the grant
	KeyFile       string `toml:"key_file,omitempty" json:"key_file,omitempty"`         // path to the PEM signing key
	SigningMethod string `toml:"signing_method,omitempty" json:"signing_method,omitempty"`
	KeyID         string `toml:"key_id,omitempty" json:"key_id,omitempty"`

	// private_key holds the PEM signing key contents for private_key_jwt when
	// stored in the OS keyring (config carries the sentinel). key_file remains
	// the on-disk-path alternative.
	PrivateKey string `toml:"private_key,omitempty" json:"-"` // secret; never serialized to JSON output
}

Auth holds a profile's authentication configuration. Which fields apply depends on Method; unused ones stay empty.

func (Auth) ConfiguredSecretFields

func (a Auth) ConfiguredSecretFields() []string

ConfiguredSecretFields lists keyring-managed fields present on the profile.

func (Auth) Validate

func (a Auth) Validate() error

Validate reports incomplete authentication settings before the SDK turns them into a remote token-exchange failure or silently sends no credential.

type Config

type Config struct {
	Version                   int                 `toml:"version"`
	Active                    string              `toml:"active_profile"`
	Theme                     string              `toml:"theme,omitempty"`
	Icons                     string              `toml:"icons,omitempty"`
	PendingCredentialCleanups []CredentialCleanup `toml:"pending_credential_cleanup,omitempty" json:"-"`
	Profiles                  map[string]Profile  `toml:"profiles"`
	// contains filtered or unexported fields
}

func Load

func Load() (*Config, error)

Load reads the config from its default location (honoring OPENFGA_CONFIG).

func LoadFrom

func LoadFrom(path string) (*Config, error)

LoadFrom reads the config from path, or the resolved default when path is empty. If the file does not exist, a fresh default config is returned (not yet written to disk). A parse failure or an unsupported schema version is not returned as an error but recorded on the Config (see Resolve), so read-only inspection like `ofga config path` still works against a broken file.

func New

func New() *Config

New returns an empty Config seeded with a sensible default profile.

func (*Config) ActiveName

func (c *Config) ActiveName(o Overrides) string

ActiveName returns the profile name selected by the standard precedence: the --profile override, else OPENFGA_PROFILE/FGA_PROFILE, else the active profile on disk. It does not check that the profile exists. Callers that need the label of the connection Resolve() actually made must use this so the two never drift.

func (*Config) ClearLoadErr

func (c *Config) ClearLoadErr()

ClearLoadErr discards a recorded load error so a subsequent Save is allowed. Only the intentional recovery path (`ofga init`) uses this: it deliberately replaces an unparseable or unsupported file, whereas ordinary mutations keep the Save guard that refuses to clobber a file that failed to load.

func (*Config) Existed

func (c *Config) Existed() bool

Existed reports whether the config was read from an existing file on disk, as opposed to a freshly-minted in-memory default. Callers use this to write out a starter config on first run.

func (*Config) Get

func (c *Config) Get(name string) (Profile, bool)

Get returns a profile by name.

func (*Config) IconsMode

func (c *Config) IconsMode() string

IconsMode returns the configured glyph capability rung, giving precedence to the OPENFGA_ICONS environment variable over the on-disk value.

func (*Config) LoadErr

func (c *Config) LoadErr() error

LoadErr returns the deferred parse/version error recorded at load time, or nil when the file loaded cleanly. Read-only inspection commands surface it as a warning while still operating on the in-memory defaults.

func (*Config) Path

func (c *Config) Path() string

Path returns the resolved configuration file path.

func (*Config) ProfileNames

func (c *Config) ProfileNames() []string

ProfileNames returns the profile names sorted alphabetically.

func (*Config) Remove

func (c *Config) Remove(name string) error

Remove deletes a profile. The active profile cannot be removed.

func (*Config) Resolve

func (c *Config) Resolve(o Overrides) (Resolved, error)

Resolve merges, in increasing order of precedence: profile values, OPENFGA_* (or FGA_*) environment variables, then flag overrides.

func (*Config) RetryCredentialCleanup

func (c *Config) RetryCredentialCleanup() (int, error)

RetryCredentialCleanup retries all durable cleanup requests while holding the same cross-process lock used for config writes.

func (*Config) Save

func (c *Config) Save() error

Save writes the config to disk, creating parent directories as needed. The file holds API tokens and client secrets, so it is written with 0600 permissions (dir 0700) via a temp file + atomic rename, ensuring the secrets are never world-readable even briefly and never left truncated on error.

func (*Config) SaveWithSecretCleanup

func (c *Config) SaveWithSecretCleanup(profile string, all bool, expected ...string) (saved bool, err error)

SaveWithSecretCleanup saves the config and removes the named profile's credentials before releasing the same cross-process lock. saved reports whether the config was durably replaced when cleanup itself fails.

func (*Config) Set

func (c *Config) Set(name string, p Profile)

Set creates or replaces a profile.

func (*Config) Use

func (c *Config) Use(name string) error

Use sets the active profile.

type CredentialCleanup

type CredentialCleanup struct {
	Profile string   `toml:"profile"`
	Fields  []string `toml:"fields"`
}

CredentialCleanup is a durable, config-scoped request to remove obsolete keyring fields. It makes a failed post-save cleanup explicitly retryable.

type Overrides

type Overrides struct {
	Profile      string
	APIURL       string
	StoreID      string
	ModelID      string
	APIToken     string
	ClientSecret string
	PrivateKey   string
	Headers      []string
}

Overrides carries flag-supplied values that take precedence over everything. An empty string means "not set".

type Profile

type Profile struct {
	APIURL  string `toml:"api_url" json:"api_url"`
	StoreID string `toml:"store_id,omitempty" json:"store_id,omitempty"`
	ModelID string `toml:"model_id,omitempty" json:"model_id,omitempty"`
	Auth    Auth   `toml:"auth,omitempty" json:"auth"`
	// Headers are extra HTTP headers sent with every API request, as
	// "Name: value" strings. They exist for deployments that put OpenFGA behind
	// a gateway with its own header-based authentication (openfga/cli#669).
	Headers []string `toml:"headers,omitempty" json:"headers,omitempty"`
}

Profile is a single named connection context.

func (Profile) ResolvedAuth

func (p Profile) ResolvedAuth() Auth

ResolvedAuth returns the profile's effective auth.

type Resolved

type Resolved struct {
	Profile string
	APIURL  string
	StoreID string
	// StoreIDSource names the layer StoreID came from ("--store-id", an
	// environment variable, or a profile), so an error about a bad value can
	// point at the place that needs fixing rather than leaving the user to
	// guess which layer won.
	StoreIDSource string
	ModelID       string
	Auth          Auth
	// Headers are the profile's extra request headers with any --header flags
	// appended, so a flag can add to (or replace, by repeating the name) what
	// the profile configures.
	Headers []string

	// Notices holds non-fatal advisories gathered during resolution (e.g. an
	// environment token ignored under an OAuth profile, or an incomplete env
	// grant). The caller surfaces them on stderr; they never change the auth.
	Notices []string
}

Resolved is the fully merged, ready-to-use connection configuration after applying profile values, environment variables and flag overrides.

func (Resolved) APIToken

func (r Resolved) APIToken() string

APIToken returns the pre-shared token when the resolved auth uses one, for callers that only care about the legacy token (e.g. masked display).

Jump to

Keyboard shortcuts

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