hostkey

package
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 15 Imported by: 1 module, 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 hostkey is the domain layer for the HostKey entity — a credential the relay uses to authenticate to a Host (a serving endpoint). A HostKey is owned by the actor that created it (Meta.Owner.Kind=user, or =system for YAML-seeded keys) and *targets* a Host via Spec.HostID.

Value modes:

  • ValueKindEnv: Spec.ValueFrom.Env names an environment variable the relay reads at boot. No cleartext touches storage.
  • ValueKindStored: cleartext is supplied on the write boundary (Spec.Value), encrypted by the storage layer with RELAY_MASTER_KEY, and persisted as opaque bytes.
  • ValueKindOAuth: Spec.Value carries an OAuth token blob (access + refresh + expiry). Stored encrypted exactly like ValueKindStored; the resolver returns the access token and refreshes it on expiry via the oauth:<Provider> settings section. Spec.ValueFrom.Provider selects it.

Spec.Value is intentionally tagged `json:"-"` so cleartext never appears in JSONB or in API responses. Loading from YAML is the only path that carries a literal value through this struct.

Index

Constants

View Source
const (
	StrategyAPI = "api" // per-token metered spend
	StrategySub = "sub" // flat-rate subscription; reference cost only
)

Pricing strategies — see Spec.PricingStrategy.

View Source
const AnonIDPrefix = "anon:"

AnonIDPrefix prefixes the synthetic anonymous key's id, KeyHash, and name so it never collides with a real key (real KeyHash is 12 hex chars).

Variables

View Source
var ErrNoAccount = errors.New("a host key needs a provider account; create one at this host first")

ErrNoAccount refuses a key that names no provider account.

View Source
var ErrReservedEnv = errors.New("valueFrom.env names a variable reserved for relay's own configuration (RELAY_*, WYOLET_*)")

ErrReservedEnv refuses an env ref under a reserved name. It leaves the variable name out: the reason is shown to anyone who can read the key.

Functions

func SecretScope added in v0.11.6

func SecretScope(o meta.Owner) string

SecretScope is the scope a key's stored value is sealed under: its owner.

Types

type CredentialState added in v0.9.10

type CredentialState string

CredentialState classifies an OAuth credential's refresh health.

const (
	// CredentialOK: last renewal succeeded; ExpiresAt is the new expiry.
	CredentialOK CredentialState = "ok"
	// CredentialRevoked: the provider rejected the grant itself — renewal
	// stops until the operator re-authorizes (uploading a new value clears
	// the status).
	CredentialRevoked CredentialState = "revoked"
)

type CredentialStatus added in v0.9.10

type CredentialStatus struct {
	State     CredentialState `` /* 167-byte string literal not displayed */
	ExpiresAt time.Time       `json:"expiresAt,omitempty" yaml:"-" doc:"When the current access token expires."`
	RenewedAt time.Time       `json:"renewedAt,omitempty" yaml:"-" doc:"When the token was last renewed."`
	LastError string          `json:"lastError,omitempty" yaml:"-" doc:"The last renewal error, when it failed."`
	At        time.Time       `json:"at"                  yaml:"-" doc:"When this observation was recorded."`
}

CredentialStatus is one observation of the credential's refresh health.

type HostKey

type HostKey struct {
	Meta meta.Metadata `json:"metadata" yaml:"metadata"`

	// Status is observed state (see Status type) — API-visible, never
	// round-tripped through YAML manifests.
	Status Status `json:"status,omitzero" yaml:"-" readOnly:"true" doc:"Observed state of the credential. Ignored on write."`
	Spec   Spec   `json:"spec"     yaml:"spec"`

	// Resolved is the cleartext value reconstructed at load time (read from
	// the env var or decrypted from PG). Runtime-only; never serialized.
	Resolved string `json:"-" yaml:"-"`
	// KeyHash is sha256 hex (first 6 bytes) of Resolved, for telemetry.
	KeyHash string `json:"-" yaml:"-"`

	// Derived: populated by the control-API enrich step from the stores; not
	// stored and not loaded from YAML. Lists every Policy whose pools reach
	// this HostKey, so the admin UI can show where a key is in use.
	Policies []PolicyRef `` /* 184-byte string literal not displayed */
}

HostKey is a credential bound to a Host.

func Anonymous added in v0.2.0

func Anonymous(hostID, hostName string) *HostKey

Anonymous returns the synthetic, never-persisted HostKey routing injects for a host marked Spec.NoAuth — a keyless upstream (e.g. self-hosted Ollama). Resolved is empty so the adapter attaches no Authorization header. KeyHash is host-scoped (not derived from the empty value) so every no-auth host gets its own circuit breaker rather than sharing one. It has no account, so no tier caps it.

func (*HostKey) Hint added in v0.20.0

func (k *HostKey) Hint() string

Hint is what anyone but the key's owners sees of the secret: the key format's fixed prefix, when it starts with a known one, and the last 4 characters; "" while it is unresolved or too short to show any of it.

func (*HostKey) IsEnabled

func (k *HostKey) IsEnabled() bool

IsEnabled returns true when Enabled is unset or explicitly true.

func (*HostKey) Prefix added in v0.20.0

func (k *HostKey) Prefix() string

Prefix is the secret's first characters, for the key's owners to recognise it; "" while it is unresolved or too short to show any of it.

func (*HostKey) Validate

func (k *HostKey) Validate() error

Validate runs intra-row rules via the shared meta.Validator and enforces:

  • Owner.Kind must be user, organization, system, team or project, a team owner with its id; keys are not owned by the Host they authenticate to.
  • Spec.HostID is required; it points at the Host this key targets.
  • ValueKindEnv requires Spec.ValueFrom.Env outside the reserved RELAY_*/WYOLET_* names; cleartext Value must be empty.
  • ValueKindStored requires non-empty cleartext Spec.Value at write time; ValueFrom.Env must be empty.

Cross-entity checks (HostID resolves to a Host; AccountID names an account at THAT host) live in app/refcheck.

type PolicyRef

type PolicyRef struct {
	ID   string `json:"id"   doc:"Policy id."`
	Name string `json:"name" doc:"Policy slug."`
}

PolicyRef is the lightweight {id, name} pair used in derived reverse-ref lists exposed by the control API.

type Spec

type Spec struct {
	// HostID is the id of the Host this key authenticates to. Required.
	// Replaces the pre-refactor Meta.Owner pointing at a Host.
	HostID string `json:"hostId" yaml:"hostId" validate:"required" doc:"Id of the host this key authenticates to."`

	// AccountID is the provider account (organization) the key belongs to; keys of one account share its upstream limits, and the account's bound tier policy caps them. Required: nothing makes an account for a key. The account must be at HostID, a cross-row check in app/refcheck.
	AccountID string `` /* 423-byte string literal not displayed */

	ValueFrom   ValueFrom `json:"valueFrom"             yaml:"valueFrom"             validate:"required" doc:"Where the secret comes from."`
	DefaultTier string    ``                                                                                                                              /* 213-byte string literal not displayed */
	Enabled     *bool     `json:"enabled,omitempty"     yaml:"enabled,omitempty"     doc:"False stops routing requests to this key. Omitted means true."` // nil = true

	// PricingStrategy selects how this credential's spend is accounted.
	// "api": per-token metered — the cost is real spend and counts toward
	// future budget enforcement. "sub": flat-rate subscription — the cost
	// computed from the binding's pricing is a reference/"would-have-cost"
	// figure only, never enforced. Empty defaults to "api". The value must
	// be one of the credential's Host.Spec.PricingStrategies (the host's
	// menu of offered billing modes); that membership is a composition-layer
	// invariant.
	PricingStrategy string `` /* 348-byte string literal not displayed */

	// Value is cleartext on the write path for ValueKindStored. Accepted
	// from JSON and YAML inputs; never returned on reads — Store.Get
	// never repopulates it, and marshalSpec strips it before any JSONB
	// persistence. The `omitempty` tag combined with that read-side
	// invariant keeps cleartext out of GET responses.
	Value string `` /* 289-byte string literal not displayed */
}

Spec carries non-secret config and the value-mode discriminator. Cleartext (Value) is write-only via YAML; storage encrypts and discards it.

func (Spec) EffectivePricingStrategy added in v0.3.0

func (s Spec) EffectivePricingStrategy() string

EffectivePricingStrategy returns the credential's strategy, defaulting an empty value to StrategyAPI.

type Status added in v0.9.10

type Status struct {
	// Credential reports the OAuth credential's refresh lifecycle. Nil for
	// api-key hostkeys and for oauth keys with no observation yet.
	Credential *CredentialStatus `` /* 134-byte string literal not displayed */

	// Unresolved is set at load time when the key's secret could not be
	// read (an env-ref whose variable is unset, a stored value the master
	// key cannot decrypt). The row still lists and edits so an operator can
	// repair it; the snapshot drops it so no request picks a valueless key.
	// Load-time only — never written to the status column.
	Unresolved *UnresolvedStatus `` /* 127-byte string literal not displayed */

	// LastUsedAt is read from its own column, never written to the status column.
	LastUsedAt *time.Time `` /* 165-byte string literal not displayed */
}

Status is the entity's observed state — written by relay components (never by the operator, never seeded from YAML), returned on the same hostkey the UI already reads. Spec stays desired-state.

type Store

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

Store is the HostKey data-access type. resolver resolves env + stored refs to plaintext; stored writes stored-mode values (nil for env-only deployments — stored-mode operations then error loudly).

func NewStore

func NewStore(db storage.DB, resolver *secret.Registry, backend *stored.Backend) *Store

NewStore constructs a Store over db. Pass the shared secret Registry + the stored backend (see app/secret.Wire); backend may be nil to run env-only.

func (*Store) ChangeOwner added in v0.30.0

func (s *Store) ChangeOwner(ctx context.Context, k *HostKey, owner meta.Owner) error

ChangeOwner moves k, as read at its version, to owner: a stored or oauth value stays as stored, sealed again under the new owner's scope in the same transaction and decrypted before it commits; k's resolved value is not needed. A row changed since k was read, or a value that does not open, leaves the key as it was.

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, id string) error

Delete removes a HostKey by id, plus its stored secret value (best-effort — orphaned ciphertext is harmless but we clean it up).

func (*Store) Get

func (s *Store) Get(ctx context.Context, id string) (*HostKey, error)

Get returns the HostKey with the given id, or (nil, nil) if not found.

func (*Store) List

func (s *Store) List(ctx context.Context) ([]*HostKey, error)

List returns every HostKey row with Resolved + KeyHash populated.

func (*Store) SetCredentialStatus added in v0.9.10

func (s *Store) SetCredentialStatus(ctx context.Context, id string, cs CredentialStatus) error

SetCredentialStatus persists the observed credential state on the hostkey row (the refresher's renewed/revoked reports). A later value update (operator re-auth) clears it — see UpdateSecretStored.

func (*Store) Upsert

func (s *Store) Upsert(ctx context.Context, k *HostKey) error

Upsert writes k. env rows store the var name; stored rows encrypt the cleartext into secret_values (via the stored resolver) and persist a ciphertext-free secrets row. Cleartext Spec.Value never reaches the secrets table and is cleared after a successful stored write. A key that names no account is refused with ErrNoAccount.

type UnresolvedStatus added in v0.10.0

type UnresolvedStatus struct {
	Reason string `json:"reason" doc:"Why the secret could not be read, such as an unset environment variable."`
}

UnresolvedStatus explains why a key's value could not be resolved.

type ValueFrom

type ValueFrom struct {
	Kind ValueKind `` /* 275-byte string literal not displayed */
	Env  string    `` /* 142-byte string literal not displayed */
	// Provider selects the oauth:<provider> settings section (refresh
	// endpoints + client). Required for ValueKindOAuth, empty otherwise.
	Provider string `` /* 132-byte string literal not displayed */
}

ValueFrom is the value-mode discriminator. For ValueKindEnv, Env names the environment variable. For ValueKindStored, Env is empty. For ValueKindOAuth, Provider names the oauth:<provider> settings section used to refresh the token, and Spec.Value (on write) carries the initial token blob.

type ValueKind

type ValueKind string

ValueKind enumerates the supported value-storage modes.

const (
	ValueKindEnv    ValueKind = "env"
	ValueKindStored ValueKind = "stored"
	// ValueKindOAuth stores an OAuth token blob (access + refresh + expiry),
	// encrypted like ValueKindStored. The resolver returns the access token and
	// refreshes it on expiry via the oauth:<Provider> config. Same at-rest
	// storage as stored (rotated + decrypted by the same machinery); the
	// distinction is semantic and lives in this Spec, not the value_kind column.
	ValueKindOAuth ValueKind = "oauth"
)

Jump to

Keyboard shortcuts

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