plan

package
v0.30.1 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 42 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 plan folds the policy ladder into the structs the request path reads, and registers the engine controllers that keep them current. The ladder runs Host → Account → Credential on the upstream side and Team → Project → Principal on the caller side; each rung holds at most one policy, every rung only narrows, and a key holds none: it points at its principal's CallerPlan.

Write side: Register declares the input kinds with their sources and one controller per derived kind (catalog index, expanded policies, rung policies, account, credential and pool plans, owned credentials, shared accounts resolved to their real accounts, caller plans, key plans and their index). Read side: Holder.Load returns the Root; a request goes key hash → KeyPlan → CallerPlan → RouteTable.Get → Route → hops and slots, and hands a slot's counters to a limits.Limiter. Nothing on the read side calls into the engine.

Out of scope: counting (app/limits), picking a credential inside a hop and the breaker and cooldown transitions (app/keypool), the request pipeline, relay-minted tokens, model groups, and the save-time check that a policy links only what its author may use.

Index

Constants

View Source
const (
	// DroppedHeldForAnotherLane is a service account's share, which serves only that service account's lane.
	DroppedHeldForAnotherLane = "held_for_another_lane"
	// DroppedNarrowedByRung is a link another rung's pools leave out.
	DroppedNarrowedByRung = "narrowed_by_rung"
)

Codes of a dropped link, besides the issue codes ref_missing, link_out_of_scope, host_disabled, host_mismatch and pool_member_unusable.

View Source
const (
	CodePolicyDisabled      = "policy_disabled"
	CodeDuplicateBinding    = "duplicate_binding"
	CodeSubjectDisabled     = "subject_disabled"
	CodeModelNotFound       = "model_not_found"
	CodeModelDisabled       = "model_disabled"
	CodeNoBinding           = "no_binding"
	CodeModelNotAllowed     = "model_not_allowed"
	CodeNoCredentials       = "no_credentials"
	CodeUnpricedUnderBudget = "unpriced_under_budget"
	// CodeAccountClosed refuses a member account whose membership ended.
	CodeAccountClosed = "account_closed"
	// CodeAccountNotHeld refuses a lane the key's principal does not hold.
	CodeAccountNotHeld = "account_not_held"
	// CodePersonalAccountOff refuses a user's personal lane, or a provider account they own personally, while their personal account is turned off.
	CodePersonalAccountOff = "personal_account_off"
)

Refusal codes. A refusal on a rung names that rung; model and binding refusals name none.

View Source
const (
	CodeRateLimitExceeded = "rate_limit_exceeded"
	CodeBudgetExceeded    = "budget_exceeded"
	// CodeUpstreamLimited is every credential over an upstream limit or in its account's cooldown; answered as rate_limit_exceeded.
	CodeUpstreamLimited = "upstream_limited"
	// CodeNoHealthyKeys is every credential of the route out of rotation, its breaker open.
	CodeNoHealthyKeys = "no_healthy_keys"
	// CodeUpstreamUnreachable is a dial failure; it is a refusal only when no candidate host of the request accepted a connection.
	CodeUpstreamUnreachable = "upstream_unreachable"
)

Codes relay refuses with once a route is found: a caller limit, or no credential of the route with room.

View Source
const (
	IssueRefMissing            = "ref_missing"
	IssueSubjectOutOfScope     = "subject_out_of_scope"
	IssueLinkOutOfScope        = "link_out_of_scope"
	IssueModelRefInvalid       = "model_ref_invalid"
	IssueModelGroupUnsupported = "model_group_unsupported"
	IssueCredentialUnresolved  = "credential_unresolved"
	IssueHostMismatch          = "host_mismatch"
	IssueCredentialsIgnored    = "credentials_ignored"
	IssuePolicyNotBindable     = "policy_not_bindable"
	// IssueSharedAccountMissing is a shared account whose real account is gone, or no longer a provider account at its host: it serves nothing.
	IssueSharedAccountMissing = "shared_account_missing"
	// IssuePersonalAccountOff is a relay key whose lane, a personal or provider account whose owner, or a shared account whose real account's owner is a user with personal accounts turned off: it serves nothing until they are on again.
	IssuePersonalAccountOff = "personal_account_off"
	// IssueHostDisabled is a pool or credential at a disabled host: requests are not routed to it.
	IssueHostDisabled = "host_disabled"
	// IssueHostDisabledInUse is a disabled host that pools or enabled credentials still point at.
	IssueHostDisabledInUse = "host_disabled_in_use"
	// IssuePoolMemberUnusable is a credential or account a pool lists that contributes no usable key.
	IssuePoolMemberUnusable = "pool_member_unusable"
	// IssuePoolsServeNothing is a policy whose linked pools all serve nothing.
	IssuePoolsServeNothing = "pools_serve_nothing"
	// IssuePoolOutsideModels is a policy linking a pool whose host serves none of the policy's models.
	IssuePoolOutsideModels = "pool_outside_models"
	// IssueModelRefUnreachable is a policy model entry served at no host the policy's pools reach.
	IssueModelRefUnreachable = "model_ref_unreachable"
	// IssueModelRefDisabled is a policy model entry naming a disabled model.
	IssueModelRefDisabled = "model_ref_disabled"
	// IssueRateLimitDisabled is a policy linking a disabled rate limit, which does not apply.
	IssueRateLimitDisabled = "rate_limit_disabled"
	// IssueRateLimitScopeOutsideModels is a policy rate-limit link scoped only to models the policy does not allow, so it never counts.
	IssueRateLimitScopeOutsideModels = "rate_limit_scope_outside_models"
	// IssueModelRefBlocked is a policy model entry that a rung above the policy, or an upstream tier, keeps from accounts bound to it.
	IssueModelRefBlocked = "model_ref_blocked"
	// IssueModelUnservable is an enabled model with bindings, none of them enabled at an enabled host.
	IssueModelUnservable = "model_unservable"
)

Issue codes the controllers attach besides duplicate_binding and unpriced_under_budget, which they share with refusals.

View Source
const (
	KindProvider       engine.Kind = "provider"
	KindHost           engine.Kind = "host"
	KindModel          engine.Kind = "model"
	KindBinding        engine.Kind = "binding"
	KindPricing        engine.Kind = "pricing"
	KindOverlay        engine.Kind = "overlay"
	KindPolicy         engine.Kind = "policy"
	KindPolicyBinding  engine.Kind = "policybinding"
	KindRateLimit      engine.Kind = "ratelimit"
	KindBudget         engine.Kind = "budget"
	KindPool           engine.Kind = "pool"
	KindAccount        engine.Kind = "account"
	KindCredential     engine.Kind = "credential"
	KindTeam           engine.Kind = "team"
	KindProject        engine.Kind = "project"
	KindServiceAccount engine.Kind = "serviceaccount"
	KindUser           engine.Kind = "user"
	KindKey            engine.Kind = "key"
	KindRole           engine.Kind = "role"
	KindRoleBinding    engine.Kind = "rolebinding"
	KindGroup          engine.Kind = "group"
	// KindAccountsSetting is the accounts settings section, one row keyed by its section name.
	KindAccountsSetting engine.Kind = "accountssetting"
)

Input kinds, loaded from the stores.

View Source
const (
	KindCatalogIndex     engine.Kind = "catalogindex"
	KindManagedAccount   engine.Kind = "managedaccount"
	KindPendingAccounts  engine.Kind = "pendingaccounts"
	KindExpandedPolicy   engine.Kind = "expandedpolicy"
	KindRungPolicy       engine.Kind = "rungpolicy"
	KindAccountPlan      engine.Kind = "accountplan"
	KindKeySlot          engine.Kind = "keyslot"
	KindPoolPlan         engine.Kind = "poolplan"
	KindOwnedCredentials engine.Kind = "ownedcredentials"
	KindCallerPlan       engine.Kind = "callerplan"
	KindLaneIndex        engine.Kind = "laneindex"
	KindKeyPlan          engine.Kind = "keyplan"
	KindKeyPlanShard     engine.Kind = "keyplanshard"
	KindKeyPlanIndex     engine.Kind = "keyplanindex"
	KindUserPlan         engine.Kind = "userplan"
	KindUserIndex        engine.Kind = "userindex"
	KindPersonalAccount  engine.Kind = "personalaccount"

	// A shared account resolved to its real account.
	KindSharedAccount engine.Kind = "sharedaccount"

	// Checks that only attach issues, to a policy and to a host; no object of these kinds is built.
	KindPolicyCheck engine.Kind = "policycheck"
	KindHostCheck   engine.Kind = "hostcheck"
)

Derived kinds, built by the controllers.

Variables

This section is empty.

Functions

func AccountPolicy

func AccountPolicy(v *engine.View, accountID string) *policy.Policy

AccountPolicy returns the policy bound to the account with id accountID in v; nil when no binding names it, or when two do.

func KeyLane

func KeyLane(v *engine.View, k *key.Key) string

KeyLane returns the id of the account k's requests run in by default in v: its accountId, or its principal's own account when it names none; "" when that account is not made yet.

func KindSingular

func KindSingular(kind engine.Kind) string

KindSingular maps an engine kind to the control API's singular resource name used in authz decisions. Empty when the kind has no control API representation (derived kinds).

func LimitCode

func LimitCode(r *limits.Refused) string

LimitCode is the code a refused counter answers with: budget_exceeded for a spent budget, rate_limit_exceeded for any other.

func NameOf

func NameOf(v *engine.View, ref engine.Ref) string

NameOf returns the slug of the input object ref names in v: a user's username, every other input kind's metadata name. Empty when the object is absent, and for overlays and derived kinds, which have no slug.

func NotifyRef

func NotifyRef(kind, id string) (engine.Ref, bool)

NotifyRef maps a catalog notification to the engine row it names.

func OverlayID

func OverlayID(kind, resourceID string) string

OverlayID is an overlay's engine id: overlays are keyed by the kind and id of the row they patch.

func OwnerAccount

func OwnerAccount(v *engine.View, owner meta.Owner) (acc *account.Account, ok bool)

OwnerAccount returns the account a policy owned by owner is previewed in: a team's or project's own account, a user's personal account. ok is false when owner is another kind or its account is not made yet; the system and the organization answer nil, true, as they have no account.

func OwnerOf

func OwnerOf(v *engine.View, ref engine.Ref) meta.Owner

OwnerOf returns the owner of the input object ref names in v. Users are treated as the organization's for visibility purposes; overlays and derived kinds return system owner.

func ReasonOf

func ReasonOf(v *engine.View, r *Refusal) string

ReasonOf words a refusal for a reader: a model refused by a rung's policy names the rung and the policy by slug, any other refusal is its message.

func Register

func Register(e *engine.Engine, cells *cell.Registry, src Sources)

Register declares every input kind with its source, the derived kinds, and their controllers on e. cells must be the registry passed as e's Options.Cells, so the cells the controllers acquire are kept alive by the plans that link them. Call before e.Load.

func RetryAfterSeconds

func RetryAfterSeconds(d time.Duration) int64

RetryAfterSeconds rounds d up to whole seconds, at least 1: an SDK reads "0" as retry at once.

func SameOr

func SameOr[T any, P interface {
	*T
	builtFrom() inputs
}](prev, next P) P

SameOr returns prev when it was built from the same inputs as next, otherwise next. The engine compares outputs by pointer, so returning prev stops a rebuild from dirtying anything downstream.

func ScopeHolds

func ScopeHolds(v *engine.View, outer, inner meta.Owner) bool

ScopeHolds reports whether scope outer holds inner in v: the system holds everything, a scope itself, a team its projects.

Types

type AccountAction

type AccountAction uint8

AccountAction is what a ManagedAccount needs done to its row.

const (
	AccountUnchanged AccountAction = iota
	// AccountCreate makes the row Want describes.
	AccountCreate
	// AccountClose closes a member account whose last role grant went.
	AccountClose
	// AccountReopen opens a member account a role grants again, and marks it as following role bindings.
	AccountReopen
)

type AccountPlan

type AccountPlan struct {
	Account *account.Account
	// GroupedByRelay is the account's Spec.GroupedByRelay: its keys were grouped by owner and host, not declared one provider org, so an upstream 429 stays with the key.
	GroupedByRelay bool
	Cooldown       *keypool.CooldownCell
	// contains filtered or unexported fields
}

AccountPlan is one provider account and its cooldown cell, shared by every credential of the account.

type AccountsSettingSource

type AccountsSettingSource struct{ Store *settings.Store }

AccountsSettingSource reads the accounts settings section from the settings store as the one row of its kind; a section never written reads as its defaults.

func (AccountsSettingSource) Get

func (AccountsSettingSource) List

type AllowSet

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

AllowSet is the intersection of the caller rungs' model lists; a rung without one does not narrow.

type Answer

type Answer struct {
	Status     int
	Type, Code string
	Kind       RefusalKind
	Message    string
	// RetryAfter is the seconds the caller is told to wait; 0 sends no Retry-After.
	RetryAfter int64
}

Answer is how relay answers a refusal: the HTTP status, error type and code, the class, and the message the caller reads. A usage row records the same status and message.

func LimitAnswer

func LimitAnswer(r *limits.Refused) Answer

LimitAnswer answers a refused caller counter, naming the rung and policy whose limit refused, never the rule itself.

type BudgetCounter

type BudgetCounter struct {
	Link    *LinkedBudget
	Counter limits.Counter
	PerLane bool
}

BudgetCounter is one linked budget and its counter. PerLane is set, and Counter zero, as for RateLimitCounters.

type CallerPlan

type CallerPlan struct {
	Lane *account.Account
	// Holder is the principal acting in the lane ("user:<id>" or "serviceaccount:<id>"); empty for a provider account.
	Holder string
	Rungs  [3]Rung
	// Refused is set when a rung fails the lane closed: its policy is disabled, its binding ambiguous, its team, project or holder disabled, or the lane closed.
	Refused *Refusal
	Allow   AllowSet
	// Pools are the pools the lane reaches, in failover order: the innermost rung that links pools orders them and outer linking rungs narrow them; with no linking rung, the credentials the lane's scopes own, each a pool of one.
	Pools []*PoolPlan
	// Counters are the caller rungs' rules without a model scope and their budgets, outer rung first.
	Counters []limits.Counter
	Routes   *RouteTable
	// PayloadLogging is the nearest account on the ladder that sets it, lane first; empty leaves capture to the key.
	PayloadLogging account.PayloadLogging
	// contains filtered or unexported fields
}

CallerPlan is the caller half of the ladder folded for one lane: the account a request runs in and is charged to. A member or service account in project P of team T climbs T's account, then P's, then the lane; a member of team T climbs T's account, then the lane; a personal account is the lane alone. A provider account used as a lane climbs nothing: its own policy applies as the upstream rung of its keys, which are all it reaches. Every key whose default lane this is points at it, so a key write or rotation touches no allowance.

func LanePlan

func LanePlan(v *engine.View, accountID string) *CallerPlan

LanePlan returns the caller plan of the account with id accountID in v; nil for a team's or project's own account, which is never a lane, and for a lane whose holder or scope is gone.

func (*CallerPlan) CapturesPayload

func (p *CallerPlan) CapturesPayload(keyOptIn bool) bool

CapturesPayload reports whether a request in this lane has its bodies captured: the nearest account on the ladder that sets payloadLogging decides, else the key's own opt-in.

func (*CallerPlan) HeldBy

func (p *CallerPlan) HeldBy(principal string) bool

HeldBy reports whether principal ("user:<id>" or "serviceaccount:<id>") may run requests in this lane: it holds the account, or owns the provider account.

func (*CallerPlan) InnermostPolicy

func (p *CallerPlan) InnermostPolicy() *policy.Policy

InnermostPolicy returns the policy bound closest to the lane, nil when no caller rung has one. Usage rows record it.

func (*CallerPlan) LaneRung

func (p *CallerPlan) LaneRung() *Rung

LaneRung returns the lane's own rung.

func (*CallerPlan) Limits

func (cp *CallerPlan) Limits() []RungLimits

Limits returns the caller rungs the lane climbs that have an account, outermost first: a team's or project's account before the lane's own. A rung's links are listed whether or not its binding refuses; a provider account used as a lane climbs none.

func (*CallerPlan) Project

func (p *CallerPlan) Project() *Rung

func (*CallerPlan) ReachesHost

func (p *CallerPlan) ReachesHost(hostID string) bool

ReachesHost reports whether one of the caller's pools is at the host.

func (*CallerPlan) Team

func (p *CallerPlan) Team() *Rung

Team and Project return the lane's team and project rungs; their SubjectID is empty when the lane sits in no team or project.

type CatalogIndex

type CatalogIndex struct {
	Snap *appcatalog.Snapshot
	// contains filtered or unexported fields
}

CatalogIndex is the catalog a route fill resolves against: a snapshot of the catalog kinds alone, with each host's enabled bindings for expanding scoped upstream rules.

type DroppedLink struct {
	PoolID     string
	Pool       *pool.Pool
	Account    *account.Account
	Credential *hostkey.HostKey
	Code       string
	Reason     string
}

DroppedLink is a pool the policy links, or an account or key the pool lists, that brings the lane nothing. Pool is nil, and PoolID set, when the pool row is gone.

type ExpandedPolicy

type ExpandedPolicy struct {
	Policy *policy.Policy
	// Grant is nil when the policy names no models: its rung then does not narrow models.
	Grant      *Grant
	RateLimits []LinkedRateLimit
	Budgets    []LinkedBudget
	// contains filtered or unexported fields
}

ExpandedPolicy is one policy with its links read: model refs parsed into a Grant, rate limits and budgets resolved, and every missing link dropped with a ref_missing issue on the policy. Every rung binding the policy shares it.

type Forwarder

type Forwarder struct{ Engine *engine.Engine }

Forwarder feeds the catalog's NOTIFY stream to an engine the plans are registered on: each notification for a kind the plans read becomes an engine event, and every (re)attach of the listener a resync, since notifications sent while it was detached never arrive.

func (Forwarder) Attached

func (f Forwarder) Attached(ctx context.Context)

Attached resyncs the engine against its sources.

func (Forwarder) Event

func (f Forwarder) Event(kind, op, id string)

Event forwards one catalog notification; kinds the plans do not read are ignored.

type Grant

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

Grant is a policy's model list, parsed once. An entry that cannot match is dropped, so a list of only such entries grants nothing rather than everything.

func (*Grant) Allows

func (g *Grant) Allows(providerSlug string, m *model.Model, hostSlug string) bool

Allows reports whether the grant covers model m of provider providerSlug served at host hostSlug.

type Holder

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

Holder keeps the current Root behind one atomic pointer, swapped when the engine publishes.

func (*Holder) Await

func (h *Holder) Await(ctx context.Context, cond func(*Root) bool) bool

Await blocks until the published plans satisfy cond or ctx ends, and reports whether they did. It wakes on each publish rather than polling, so a write followed by Await returns as soon as this pod serves the result.

func (*Holder) AwaitKey

func (h *Holder) AwaitKey(ctx context.Context, keyHash string) bool

AwaitKey waits until the published plans hold the key plan for keyHash, refusing or not: the point the key authenticates on this pod.

func (*Holder) AwaitOpenLane

func (h *Holder) AwaitOpenLane(ctx context.Context, accountID string) bool

AwaitOpenLane waits until the published plans hold an open lane for accountID: the point a request in that account can be served on this pod.

func (*Holder) Load

func (h *Holder) Load() *Root

Load returns the current Root, nil before the first publish.

func (*Holder) OnPublish

func (h *Holder) OnPublish(v *engine.View, _ engine.PublishStats)

OnPublish is the engine's OnPublish hook: it stores the Root of the view just published.

type KeyPlan

type KeyPlan struct {
	Key       *key.Key
	Principal key.Principal
	// Caller is the key's default lane; a refusing plan when the principal cannot use it.
	Caller *CallerPlan
	// GraceEnds is when the pre-rotation hash stops authenticating; zero without a rotation.
	GraceEnds time.Time
	// contains filtered or unexported fields
}

KeyPlan is what authentication derives for one key: its principal and its default lane.

type KeyPlanIndex

type KeyPlanIndex struct{ Shards [256]*KeyPlanShard }

KeyPlanIndex finds a key plan by hash. 256 shards on the hash's first byte, so a key write copies one shard's map.

func (*KeyPlanIndex) Lookup

func (x *KeyPlanIndex) Lookup(h string, now time.Time) *KeyPlan

Lookup returns the plan of the key whose hash, or previous hash still in grace, is h, if that key is active at now; nil otherwise.

type KeyPlanShard

type KeyPlanShard struct {
	Index  int
	ByHash map[string]*KeyPlan
}

KeyPlanShard holds the key plans whose hash (or in-grace previous hash) starts with one byte.

type KeySlot

type KeySlot struct {
	Credential *hostkey.HostKey
	Host       *host.Host
	Account    *AccountPlan         // nil when the credential names no account
	Breaker    *keypool.BreakerCell // nil for a keyless host's anonymous slot
	Upstream   Rung                 // the provider account's
	// Via is the shared account the slot is reached through, whose policy narrows the real account's; SubjectID is empty on the real account's own slot.
	Via Rung
	// OnlyFor is the one lane holder ("serviceaccount:<id>") a service account's share serves; empty serves every lane reaching the slot.
	OnlyFor string
	// Refused is set when the account's policy is disabled or its binding ambiguous: the credential then serves nothing, rather than serving unmetered.
	Refused *Refusal
	// Whole holds the account's rules with no model scope and its budgets; ByModel the scoped rules, expanded per model id. A counter whose link is not shared counts per lane: the route fill renders it for the caller's lane.
	Whole   []slotCounter
	ByModel map[string][]slotCounter
	// Alone is the credential as a pool of one, for reach by ownership.
	Alone *PoolPlan
	// contains filtered or unexported fields
}

KeySlot is one credential with the upstream half of the ladder folded: its host and provider account, the policy bound to the account, the counters it imposes, and the breaker cell. One KeySlot is shared by every pool holding the credential.

func (*KeySlot) CountsOnAccount

func (s *KeySlot) CountsOnAccount(c *limits.Counter) bool

CountsOnAccount reports whether c counts on the real provider account of the slot, rather than on a shared account it is reached through.

type LaneIndex

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

LaneIndex finds a lane's plan by account id or name, and a user's member account in a team or project.

func (*LaneIndex) Lookup

func (x *LaneIndex) Lookup(ref string) *CallerPlan

Lookup returns the plan of the lane named by ref, an account id or name; nil when there is none.

func (*LaneIndex) Member

func (x *LaneIndex) Member(userID string, scope meta.Owner) *CallerPlan

Member returns the plan of userID's member account in scope, nil when the user has none there.

type LinkedBudget

type LinkedBudget struct {
	Budget *budget.Budget
	Shared bool
}

LinkedBudget is one budgets entry with its budget read.

type LinkedRateLimit

type LinkedRateLimit struct {
	RateLimit *ratelimit.RateLimit
	Scoped    bool
	Scope     []modelref.Ref
	// Models is the entry's model list as written, for reads that show it.
	Models []string
	Shared bool
}

LinkedRateLimit is one rateLimits entry with its rate limit read. A scoped entry applies only to models its Scope matches; one whose refs all failed to parse matches no model. Shared counts once for the bound account; otherwise once per lane under it.

type Listed

type Listed struct {
	Model    *model.Model
	Provider string
	Bindings []*binding.Binding
}

Listed is one reachable model and the bindings its route would use, one per hop.

type ManagedAccount

type ManagedAccount struct {
	Key string
	// Want is the account to create when Row is nil; nil when nothing calls for one (the source row is gone, or no role grants the membership).
	Want *account.Account
	Row  *account.Account
	// contains filtered or unexported fields
}

ManagedAccount is one caller account's place (account.Account.ManagedKey): the account its source row calls for, and the row holding the place, if any.

func Pending

func Pending(v *engine.View) []*ManagedAccount

Pending returns the account places that need work in view v.

func (*ManagedAccount) Action

func (m *ManagedAccount) Action() AccountAction

Action is what the place needs done.

type ModelReach

type ModelReach struct {
	Model    *model.Model
	Provider *provider.Provider
	// Accounts are, for a saved policy read in the accounts bound to it, the bound accounts that reach the model (or, excluded, that may not use it).
	Accounts []*account.Account
	// Hosts serve it for the lane, in failover order; for an excluded model, the reached hosts that bind it.
	Hosts []*host.Host
	// Via is what brings it, hop by hop: the pool (nil for a key reached by ownership) and the account each key draws on.
	Via      []ReachVia
	Upstream []UpstreamCheck
	Refused  *Refusal
}

ModelReach is one model and how the lane reaches it, or, with Refused set, why it does not.

type OverlaySource

type OverlaySource struct{ Store *overlay.Store }

OverlaySource adapts the overlay store, keyed by (kind, resource id), to the engine's single-string ids from OverlayID.

func (OverlaySource) Get

func (OverlaySource) List

func (s OverlaySource) List(ctx context.Context) ([]*overlay.Overlay, error)

type Override

type Override struct {
	AccountID string
	Policy    *policy.Policy
}

Override stands in for the policy bound to one account during a reach read. AccountID "" is the system scope, which no account holds: the policy then sits alone above a lane reaching only system-owned keys.

type OwnedCredentials

type OwnedCredentials struct {
	Pools []*PoolPlan
	// contains filtered or unexported fields
}

OwnedCredentials is the credentials one owner scope holds ("user:<id>", "project:<id>", "team:<id>", "organization:", "system:"), or one provider account holds ("account:<id>"), each as a pool of one in creation order: what a lane reaches when no caller rung links pools.

type PendingAccounts

type PendingAccounts struct {
	Items []*ManagedAccount
}

PendingAccounts is every account place whose row needs creating, closing or reopening, sorted by key: the work list of the writer off the engine.

type PersonalAccount

type PersonalAccount struct {
	UserID   string
	Username string
	On       bool
	Source   PersonalAccountSource
	// GroupID is the group that decided it, for Source group.
	GroupID string
	// contains filtered or unexported fields
}

PersonalAccount is a user's effective personal-account state.

func PersonalAccountOf

func PersonalAccountOf(v *engine.View, userID string) *PersonalAccount

PersonalAccountOf returns userID's personal-account state in view v; nil when the user is unknown.

type PersonalAccountSource

type PersonalAccountSource string

PersonalAccountSource names what decided a user's personal-account state.

const (
	PersonalAccountFromUser    PersonalAccountSource = "user"
	PersonalAccountFromGroup   PersonalAccountSource = "group"
	PersonalAccountFromSetting PersonalAccountSource = "setting"
)

func EffectivePersonalAccount

func EffectivePersonalAccount(userValue string, groups []*group.Group, setting *settings.Accounts) (on bool, source PersonalAccountSource, groupID string)

EffectivePersonalAccount is the first of: the user's own value; an enabled organization group's, off winning over on and the lowest id deciding among equals; the deployment's setting. A nil setting is on.

type PoolPlan

type PoolPlan struct {
	Pool      *pool.Pool
	Host      *host.Host
	Slots     []*KeySlot
	Selection keypool.KeySelection
	Rotation  *keypool.Rotation
	// contains filtered or unexported fields
}

PoolPlan is one pool: its host, its credentials in pool order, the selection algorithm and the rotation cell. A keyless host's pool holds one anonymous slot; a credential's pool of one has no Pool row and no rotation.

type RateLimitCounters

type RateLimitCounters struct {
	Link     *LinkedRateLimit
	Counters []limits.Counter
	PerLane  bool
}

RateLimitCounters is one linked rate limit and its counters, one per rule in rule order. PerLane is set, and Counters nil, when the link counts per lane and the rungs were read for no lane.

type Reach

type Reach struct {
	// Account is the account read; nil for the system scope.
	Account  *account.Account
	Refused  *Refusal
	Models   []ModelReach
	Excluded []ModelReach
	// Dropped are the links of the policy read that bring the lane nothing.
	Dropped []DroppedLink
}

Reach is what one lane may use: Refused when the whole ladder refuses, else the models it reaches and the models at its hosts it may not use.

func PolicyReach

func PolicyReach(v *engine.View, p *policy.Policy) *Reach

PolicyReach reads saved policy p where it applies. Bound, it is read in each account its enabled bindings name, once per distinct ladder, and merged: a model any of them reaches is reached, with the accounts that reach it; one none reaches is excluded, with one ladder's refusal and the accounts it holds for. Unbound, it is read in its owner's own account as a draft is. nil when neither can be read.

func ReachOf

func ReachOf(v *engine.View, accountID string, over *Override) *Reach

ReachOf reads what account accountID's lane may use in v, with over standing in for one rung's policy when set. A team's or project's own account is read as a lane directly under it. nil when the account is unknown or heads no ladder.

type ReachVia

type ReachVia struct {
	Pool    *pool.Pool
	Account *account.Account
}

ReachVia is one pool and account a model is reached through; either may be nil.

type Refusal

type Refusal struct {
	Code      string
	Rung      limits.Rung
	SubjectID string
	PolicyID  string
	Message   string
}

Refusal says why a lane, a credential or a route cannot serve: a stable code, and the rung, account and policy that decided it.

func (*Refusal) Error

func (r *Refusal) Error() string

func (*Refusal) Kind

func (r *Refusal) Kind() RefusalKind

Kind is r's class.

type RefusalKind

type RefusalKind string

RefusalKind is the class of a refusal a client acts on: use another model, reach another host, or wait.

const (
	RefusalModelNotAllowed  RefusalKind = "model_not_allowed"
	RefusalHostNotReachable RefusalKind = "host_not_reachable"
	RefusalNoCapacity       RefusalKind = "no_capacity"
)

func KindOf

func KindOf(code string) RefusalKind

KindOf is the class of a refusal code; "" for a code that is not a relay refusal, such as an upstream's own error.

type Root

type Root struct {
	Keys  *KeyPlanIndex
	Users *UserIndex
	Lanes *LaneIndex
	// Catalog resolves requests that name no caller (ResolveAtHost).
	Catalog *CatalogIndex
	Gen     uint64 // the generation it was published as, for caches keyed by it
}

Root is what the request path loads: the indexes of one published generation.

func (*Root) LaneFor

func (r *Root) LaneFor(kp *KeyPlan, ref string) (*CallerPlan, *Refusal)

LaneFor resolves the lane a key's request runs in: ref, an account id or name the key could be saved in (account.Account.TakesKeysOf), or the key's default lane when ref is empty or names it. Any other account refuses with account_not_held, the same answer for an account that does not exist. A closed account resolves and refuses through its plan, as a key's default lane does.

func (*Root) MemberLane

func (r *Root) MemberLane(userID, projectID string) (*CallerPlan, *Refusal)

MemberLane is the lane a user's request inside a project runs in, as a relay-minted token scoped to the project names: the user's member account there.

func (*Root) ResolveAtHost

func (r *Root) ResolveAtHost(h *host.Host, ref string) *Unkeyed

ResolveAtHost resolves the model ref at host h for a request that brings its own upstream key and names no caller, as anonymous proxy traffic does. No policy governs a host, so nothing is counted; the resolved model only prices and labels the request. A model the catalog does not serve at h leaves Model unset.

func (*Root) TokenLane

func (r *Root) TokenLane(userID, projectID, ref string) (*CallerPlan, *Refusal)

TokenLane resolves the lane a relay-minted token of userID runs in: the user's member account in projectID when ref is empty, else ref, an account id or name the user holds (a member account opened on first use among them). A token scoped to a project switches only into accounts inside it; one without a project into any the user holds.

type Route

type Route struct {
	Model    *model.Model
	Snapshot *model.Snapshot
	Provider string
	// UpstreamModel is the wire model name: the alias's override when one matched, else the snapshot's upstream name. ResolvedVia tags an alias match for usage rows.
	UpstreamModel string
	ResolvedVia   string
	Hops          []RouteHop
	Refused       *Refusal
}

Route is where one model ref goes for one caller: the model, and the hops (pool by pool, the failover order) with the slots that may serve it. Refused is set when no hop remains, naming what emptied the route.

type RouteHop

type RouteHop struct {
	Pool    *PoolPlan
	Binding *binding.Binding
	Host    *host.Host
	Pricing *pricing.Pricing
	Priced  bool
	Slots   []*KeySlot
	// Credentials is each slot's credential, in slot order, so a pick over the whole hop builds no slice.
	Credentials []*hostkey.HostKey
	Counters    [][]limits.Counter
	// CallerN is how many leading counters of each Counters[i] are the caller's; they are the same for every slot of the hop, so a failover inside it keeps the caller's hold.
	CallerN int
	// ParamRenames are the request-body renames the host applies to the binding's wire shape, resolved with the route so a request reads them without a lookup.
	ParamRenames []host.ParamRename
}

RouteHop is one pool's slots that may serve the route, with the binding and pricing at the pool's host. Counters[i] is everything slot i's request must fit: the caller rungs' counters, then the slot's upstream ones.

func (*RouteHop) CallerCounters

func (h *RouteHop) CallerCounters() []limits.Counter

CallerCounters returns the caller rungs' counters of this hop.

func (*RouteHop) UpstreamCounters

func (h *RouteHop) UpstreamCounters(i int) []limits.Counter

UpstreamCounters returns the upstream rungs' counters of slot i.

type RouteTable

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

RouteTable maps a caller's model ref to its Route, filling on first use from the catalog index and pools its CallerPlan holds. A table is never filled against newer inputs: any change replaces the CallerPlan and with it the table.

func (*RouteTable) Catalog

func (t *RouteTable) Catalog() *appcatalog.Snapshot

Catalog is the catalog snapshot this table resolves against, for projecting what it lists.

func (*RouteTable) Get

func (t *RouteTable) Get(ref string) *Route

Get returns the route for ref, filling it on first use; never nil. A hit is one read-locked map lookup.

func (*RouteTable) Listing

func (t *RouteTable) Listing() []Listed

Listing runs the route fill for every model, uncached, and keeps those with a hop; a snapshot name is reachable when one of its bindings serves it. The fill skips nothing a request for a named snapshot would not, so the list never advertises a refusal.

func (*RouteTable) Misses

func (t *RouteTable) Misses() uint64

Misses counts fills, for a gauge.

func (*RouteTable) Models

func (t *RouteTable) Models() []*model.Model

Models lists the models the caller can reach, by running the route fill per model: the listing cannot advertise what a request would be refused.

func (*RouteTable) ResolveUnkeyed

func (t *RouteTable) ResolveUnkeyed(ref string) *Unkeyed

ResolveUnkeyed resolves ref without credentials, uncached. No provider account's policy applies, as no relay credential serves. A keyless host counts only when one of the caller's pools is at it: the pool is the explicit grant a wildcard never gives.

type Rung

type Rung struct {
	Kind limits.Rung
	// SubjectID is the account, as "account:<id>"; empty for a rung the request does not climb.
	SubjectID string
	Account   *account.Account
	// ScopeID is the team or project id of a team or project rung, and of the lane's own scope; ID returns it.
	ScopeID string
	// Name is the slug of the team, project or service account the rung stands for, for usage rows; empty otherwise.
	Name   string
	Policy *ExpandedPolicy
}

Rung is one level of the ladder as a plan holds it: the account and the policy bound to it. A nil Policy does not constrain.

func (*Rung) ID

func (r *Rung) ID() string

ID returns the id of the team or project the rung stands for, "" for a rung the lane does not climb.

type RungLimits

type RungLimits struct {
	Rung       *Rung
	RateLimits []RateLimitCounters
	Budgets    []BudgetCounter
}

RungLimits is one caller rung a lane climbs, with what its policy links and the counters admission counts each link in.

func ScopeLimits

func ScopeLimits(v *engine.View, acc *account.Account) []RungLimits

ScopeLimits returns the rungs of a team's or project's own account in v, outermost first: the team's account, then the project's for a project account. No lane climbs them here, so links counted per lane carry no counters. nil for any other account.

type RungPolicy

type RungPolicy struct {
	Rung    Rung
	Binding *policybinding.PolicyBinding
	Refused *Refusal
	// contains filtered or unexported fields
}

RungPolicy is the policy bound to one account ("account:<id>"), or the refusal the account's rung imposes when its policy is disabled or its binding ambiguous.

type SharedAccount

type SharedAccount struct {
	Account *account.Account
	Source  *account.Account
	Slots   []*KeySlot
	// contains filtered or unexported fields
}

SharedAccount is a shared provider account resolved to its real account: the real account's slots, current and future, each narrowed by the shared account's own policy. Absent, with a shared_account_missing issue, while the real account is gone or cannot be shared, and with personal_account_off while its owner's personal accounts are off.

type Sources

type Sources struct {
	Providers       engine.Source[provider.Provider]
	Hosts           engine.Source[host.Host]
	Models          engine.Source[model.Model]
	Bindings        engine.Source[binding.Binding]
	Pricings        engine.Source[pricing.Pricing]
	Overlays        engine.Source[overlay.Overlay]
	Policies        engine.Source[policy.Policy]
	PolicyBindings  engine.Source[policybinding.PolicyBinding]
	RateLimits      engine.Source[ratelimit.RateLimit]
	Budgets         engine.Source[budget.Budget]
	Pools           engine.Source[pool.Pool]
	Accounts        engine.Source[account.Account]
	Credentials     engine.Source[hostkey.HostKey]
	Teams           engine.Source[team.Team]
	Projects        engine.Source[project.Project]
	ServiceAccounts engine.Source[serviceaccount.ServiceAccount]
	Users           engine.Source[user.User]
	Keys            engine.Source[key.Key]
	// RoleBindings decide the member accounts relay keeps; with Roles and Groups they also feed the RBAC re-check of personal policies bound by a team or project, for which Roles are read only when RBAC is set. Groups are read always: they turn their members' personal accounts on or off.
	Roles        engine.Source[role.Role]
	RoleBindings engine.Source[rolebinding.RoleBinding]
	Groups       engine.Source[group.Group]
	// AccountsSetting is the accounts settings section; nil reads personal accounts as on.
	AccountsSetting engine.Source[settings.Accounts]
	// RBAC is set under the role-based authorizer. Without it every user may manage every policy binding, so the plans do not re-check.
	RBAC bool
}

Sources are the stores each input kind loads from. A nil field loads nothing.

type Unkeyed

type Unkeyed struct {
	Model         *model.Model
	Provider      string
	Binding       *binding.Binding
	Host          *host.Host
	Pricing       *pricing.Pricing
	UpstreamModel string
	ResolvedVia   string
	// Counters are what the request must fit: the caller rungs' counters.
	Counters []limits.Counter
	Refused  *Refusal
}

Unkeyed is where a model ref goes when the caller brings its own upstream key: the first binding the caller's and the host's grants allow, whatever credentials it reaches. Refused is set when none does.

type UpstreamCheck

type UpstreamCheck struct {
	Account *account.Account
	// SharedAs is the shared account the keys are reached through; nil for the real account's own.
	SharedAs *account.Account
	Policy   *policy.Policy
	Refused  *Refusal
}

UpstreamCheck is one provider account whose keys could serve the model, with its tier policy and, when it refuses the model, why.

type UserIndex

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

UserIndex finds a user's plan by user id, for token authentication.

func (*UserIndex) Lookup

func (x *UserIndex) Lookup(id string) *UserPlan

Lookup returns the plan of user id, nil when the user has none.

type UserPlan

type UserPlan struct {
	UserID       string
	TokenVersion int
	// Disabled is read where no lane plan reads the user: a provider account used as a lane has no holder.
	Disabled bool
	// contains filtered or unexported fields
}

UserPlan is what a relay-minted token of one user authenticates against: the version every token of the user must carry.

Directories

Path Synopsis
Package plantest builds published plans from rows held in memory, for tests outside app/plan.
Package plantest builds published plans from rows held in memory, for tests outside app/plan.

Jump to

Keyboard shortcuts

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