tenant

package
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 25 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 tenant is the control plane for a hosted, multi-user context-guru: who the users are, which token identifies them, and what configuration their traffic runs under.

Two properties shape every decision here.

First, this data is NOT derived. dash's request store is a view — it renames itself aside and starts fresh on a schema change, because losing observability history beats refusing to boot. Accounts cannot work that way, so tenants live in their own database with real forward migrations (PRAGMA user_version), never in the dashboard file, and the retention janitor never touches them.

Second, we hold no user's provider credential. A user authenticates with a token WE mint and forwards their OWN provider key to the upstream; that key belongs to the caller, is read from the request, and is never stored. So the secrets in this database are only ever DERIVED: the sha256 of a token, the sha256 of a session cookie, the sha256 of an agent's provider key (for agents that cannot set a custom header), an argon2id hash of a dashboard password (see password.go), and the sha256 of a 5-minute email code. None of the five can be replayed as the thing it was derived from, and the only value ever displayed is a token's 8-character prefix. There is no code path that can print a token, a provider key, or a password: after Register/MintToken/RegisterAccount return the process no longer holds one, and BindAgentKey hashes its argument before anything else.

Index

Constants

View Source
const (
	CampaignSourceLive   = "suggest-live"
	CampaignSourceUpload = "upload"

	CampaignStatusActive   = "active"
	CampaignStatusArchived = "archived"
)
View Source
const (
	MinFeedbackChars = 50
	// MaxFeedbackChars bounds what goes into a row and into an email body. Generous
	// for a paragraph, small enough that a submission cannot be a payload.
	MaxFeedbackChars = 4000
)

Text limits. 50 is the owner's rule, and it is enforced on the SERVER: the form counts characters too, but a form is a courtesy and a POST is the boundary.

View Source
const (
	TargetAll  = "all"
	TargetList = "list"
)
View Source
const (
	ChangeAccount  = "account"
	ChangeStrategy = "strategy"
)

ChangeAccount and ChangeStrategy are the kinds passed to the listener.

View Source
const CodeTTL = 5 * time.Minute

CodeTTL is how long an emailed code stays valid. The owner asked for 5 minutes; the API returns the absolute expiry so the UI can count down against it rather than assuming this constant.

View Source
const DefaultCacheTTL = 30 * time.Second

DefaultCacheTTL is deliberately short: it exists to keep a token lookup off the writer's path under agent-rate traffic, not to be a session store.

View Source
const DefaultConfigYAML = `` /* 153-byte string literal not displayed */

DefaultConfigYAML is the pipeline every new tenant starts on: the config named `house`, which is codesmart's structural offloaders in an operator-chosen order with the LLM extractor removed and no blind collapse. Deterministic all the way through, which on a SHARED box is the property that matters — it makes no cheap-model calls, so it adds no upstream spend, contends on no shared LLM budget, and costs near-zero added latency on someone else's agent. A tenant can opt into extract_llm on their settings page and see the tradeoff there.

Kept as a literal document even though `house` is now a registered preset name, for two reasons that have nothing to do with taste: supersededDefaults compares stored configs against it BYTE for byte, and this package must not import the pipeline. The two cannot drift — defaultconfig_test.go asserts this literal and `preset: house` resolve to the same pipeline and the same component blocks. failed_run is deliberately absent. Measured on this service and on Terminal-Bench it acted ZERO times while spending real wall clock scanning every request for superseded failures (843 ms across 251 requests on one account, 28.8 s on the Terminal-Bench arm). A component that has never once fired on agentic traffic is latency with a name.

textclean is here because it is the cheapest thing in the catalogue that actually fires. It is a Reformat, so it is LOSSLESS — no marker, no stash, no floor, a pure function of the content and therefore byte-stable across turns and restarts, which is the same cache posture as `format`. It handles the shape `format` and `toon` never see: 1,724 of 1,748 distinct tool outputs measured on this box are not JSON. Measured −17,219 tokens = 1.73% of the capture corpus, at no upstream spend and no cache churn, which is why it is safe to turn on for everyone rather than offer as an opt-in. The order is the operator's: dedup and cmdfilter run ahead of searchfold and textclean, so the lossless trio does NOT lead here as it does in config.presets["general"]. The consequence is confined to attribution — two offloaders have already edited the messages by the time the folds count theirs, so the per-component split in /stats is less honest than `general`'s. Totals are unaffected. toolfilter is last and carries an empty removal list, so it is a no-op until an account names something; it is in the default so that naming one is a settings change rather than a pipeline change.

View Source
const DefaultStrategyTZ = "Asia/Jerusalem"

DefaultStrategyTZ is what an unset Window.TZ resolves to.

View Source
const DefaultWebSessionTTL = 30 * 24 * time.Hour

DefaultWebSessionTTL is how long a dashboard login lasts.

View Source
const MaxCodeAttempts = 5

MaxCodeAttempts is how many wrong guesses a single code tolerates before it is destroyed. Low on purpose: a human reading a code out of their mail does not need five tries, and every extra try is 1-in-200,000 handed to someone who is not them.

View Source
const MinAgentKeyLen = 20

MinAgentKeyLen is the shortest string accepted as a provider key. Every real one is far longer (sk-..., 40+ chars); this only rules out claiming "test" or "changeme", which are digests anyone can compute and whose real owner would then be unable to bind their own key.

View Source
const (

	// MinPasswordLen is the only password rule. Length is the property that
	// actually buys entropy; composition rules ("one symbol!") push users to
	// Password1! and buy nothing, so there are none.
	//
	// 8 is the operator's chosen floor. It is lower than this file would pick on its
	// own, and the reason it is defensible here is that the password is not the only
	// thing standing between an attacker and an account: every sign-in also needs a
	// 6-digit code mailed to the address, each verify is capped at 5 attempts before
	// the code is destroyed, sign-in attempts are rate-limited per email AND per
	// client address, and each guess costs a 64 MiB argon2id hash. Online guessing is
	// bounded by those, not by this number. Offline guessing against a stolen hash is
	// where a short password actually loses — that is the trade being made.
	MinPasswordLen = 8
)

argon2id parameters.

64 MiB / 3 passes / 2 lanes. Chosen against the RFC 9106 "second recommended" profile (64 MiB, t=3, p=4) and trimmed to 2 lanes because this runs on a shared box next to a proxy on the hot path, and lanes buy parallel speed for the DEFENDER only — the attacker parallelises across guesses regardless. Measured cost is roughly 40-60 ms and 64 MiB per verify on this hardware, which is why the code and password endpoints are rate-limited: without a limit, 64 MiB per attempt is itself a memory-exhaustion lever.

These live in the encoded hash (PHC string format), so raising them later does not invalidate a single existing password — VerifyPassword reads the parameters the hash was made with. Re-hashing on next sign-in is deliberately NOT implemented; add it when the parameters actually change.

View Source
const TokenPrefix = "cg_live_"

TokenPrefix is how a context-guru token is recognised on sight. Exported because the proxy now accepts the caller's OWN provider key in the Authorization slot, so it has to be able to tell our token apart from a credential it must forward.

Variables

View Source
var (
	ErrBadCode      = errors.New("tenant: wrong verification code")
	ErrCodeExpired  = errors.New("tenant: verification code expired")
	ErrCodeAttempts = errors.New("tenant: too many wrong codes; that code is now void")
	ErrNoCode       = errors.New("tenant: no verification code pending")
)

Errors callers branch on. ErrBadCode and ErrCodeExpired are deliberately different so the UI can say "that code has expired, here is a new one" instead of "wrong" — this is not an oracle worth protecting: the attacker already knows the clock.

View Source
var (
	ErrFeedbackText  = fmt.Errorf("tenant: the comment must be at least %d characters of real text", MinFeedbackChars)
	ErrFeedbackLong  = fmt.Errorf("tenant: that text is longer than %d characters", MaxFeedbackChars)
	ErrFeedbackScore = errors.New("tenant: every rating must be a whole number of stars from 1 to 5")
	ErrFeedbackDim   = errors.New("tenant: unknown rating")
	ErrFeedbackAgent = errors.New("tenant: say which agent this is about")
)
View Source
var (
	ErrBadPassword = errors.New("tenant: password must be at least 8 characters")
	ErrNoPassword  = errors.New("tenant: account has no password set")
	ErrWrongPass   = errors.New("tenant: wrong email or password")
	ErrNotVerified = errors.New("tenant: email not verified")
	ErrBadPassHash = errors.New("tenant: unreadable password hash")
)

Errors callers branch on.

View Source
var (
	ErrUnknownToken = errors.New("tenant: unknown or revoked token")
	ErrDisabled     = errors.New("tenant: account disabled")
	ErrNotFound     = errors.New("tenant: no such tenant")
	ErrEmailTaken   = errors.New("tenant: email already registered")
	ErrEmailDomain  = errors.New("tenant: email domain not allowed")
	ErrBadEmail     = errors.New("tenant: malformed email")
	ErrBadLabel     = errors.New("tenant: label must be 1-64 printable characters")
	ErrForbidden    = errors.New("tenant: not permitted")
	ErrBadVariant   = errors.New(
		"tenant: variant must be 1-32 characters of letters, digits, '.', '_' or '-'")
	ErrBadReason = errors.New("tenant: reason must be at most 200 printable characters")
	// ErrLastManager guards the only route back into administration. Demoting or disabling
	// the last manager locks every account out of the manager pages, and the manager pages
	// are the only way to make another manager — so the database would be the only way back.
	ErrLastManager = errors.New("tenant: this is the last manager; promote another one first")
)

Errors callers are expected to branch on. Authentication fails CLOSED (an unknown token is never treated as a new tenant); configuration fails open elsewhere, in the resolver that reads it.

View Source
var ErrBadAgentKey = errors.New("tenant: provider key is too short to bind")

ErrBadAgentKey rejects a key too short to be one. A digest is only evidence of holding a key if the key could not have been guessed.

View Source
var ErrNoAgentKey = errors.New("tenant: provider key is not bound to any account")

ErrNoAgentKey is returned when a provider key's digest is bound to no tenant.

View Source
var ErrNoCampaign = errors.New("tenant: no such strategy campaign")

ErrNoCampaign names no strategy campaign.

View Source
var ErrNoSession = errors.New("tenant: no such dashboard session")

ErrNoSession is returned when a cookie does not identify a live login.

View Source
var ErrNoStrategy = errors.New("tenant: no such keep-alive strategy")

ErrNoStrategy names no keep-alive strategy.

View Source
var FeedbackAgents = []Labelled{
	{"claude-code", "Claude Code"},
	{"bob", "Bob"},
}

FeedbackAgents is what the selector offers. Two values, closed: the answer is a grouping key in every aggregate and a line in an email, so a third one is refused rather than stored as a group nobody asked about.

View Source
var FeedbackQuestions = []Labelled{
	{"overall", "Overall experience"},
	{"performance", "How has Context Guru affected your agent's performance?"},
	{"compaction", "How well does compaction preserve useful information?"},
	{"latency", "In terms of latency — was it not noticeable?"},
	{"dashboard", "How useful is the dashboard?"},
	{"ease", "How easy was setup and day-to-day use?"},
	{"recommend", "How likely are you to recommend Context Guru to a colleague?"},
}

FeedbackQuestions is the fixed set of star questions, in the order the form and the manager's view both present them. It is the ONE list: the handler validates against it, Summarize orders by it, and a key that is not in it is refused rather than silently stored and never read.

All seven are mandatory and all seven are asked about ONE agent, named by the selector — the same questions either way, so two agents' answers are comparable.

Functions

func AgentLabel

func AgentLabel(key string) string

AgentLabel is the words for a stored agent value.

func HashPassword

func HashPassword(pw string) (string, error)

HashPassword returns a PHC-encoded argon2id hash with a fresh random salt.

func LooksLikeToken

func LooksLikeToken(s string) bool

LooksLikeToken reports whether s is shaped like one of our tokens. It says nothing about whether the token exists — only that it is ours rather than a provider credential, which is the distinction the proxy needs before deciding what to forward.

func QuestionLabel

func QuestionLabel(key string) string

QuestionLabel is the words for one star question, for anything rendering a stored row.

func SID

func SID(cookie string) string

SID returns the public handle for a cookie, so a handler can mark which row in the list is the browser it is answering — without a query, and without the cookie leaving the request.

func VerifyPassword

func VerifyPassword(encoded, pw string) bool

VerifyPassword reports whether pw produced encoded.

Returns false — never an error — for a malformed or empty stored hash, so a corrupt row is a failed sign-in rather than a way to distinguish accounts.

Types

type AuditEntry

type AuditEntry struct {
	At            time.Time
	Actor, Target string
	Field         string
	Before, After string
}

AuditEntry is one recorded configuration change.

type Campaign

type Campaign struct {
	ID          string
	Name        string
	Source      string // CampaignSourceLive | CampaignSourceUpload
	Baseline    string
	MinRequests int
	Weekdays    []string
	Status      string // CampaignStatusActive | CampaignStatusArchived
	CreatedBy   string
	CreatedAt   time.Time
	// ActivatedAt is the floor every real-saving read is bounded by (see
	// dash.DB.CampaignRealSavings) — never backfilled, for the same reason a keep-alive
	// strategy's own pings are not: there is no way to know what a strategy that did
	// not exist yet would have done with older traffic.
	ActivatedAt time.Time
}

Campaign is one bundle: the suggest run it came from (frozen parameters, so a reader of a cell's predicted numbers knows what population they were backtested against), when it went live, and whether it is still in force.

type CampaignCell

type CampaignCell struct {
	CampaignID string
	TenantID   string
	HourUTC    int
	// Requests is the suggest cell's own Requests: how many Sunday-Thursday requests in
	// this hour the backtest that produced PredictedUSD was actually computed from.
	Requests int64
	// Arm is the suggest cell's best_strategy, verbatim.
	Arm          string
	PredictedUSD float64
	BaselineUSD  float64
	// OptimalSavingUSD is the suggest cell's own exact-ceiling saving over Baseline (see
	// dash.KVCacheSuggestion.OptimalSavingUSD), frozen the same way PredictedUSD is — so a
	// campaign's own "how much did we actually capture" figure always has a fixed "how much
	// was there to capture" figure beside it, from the exact same backtest population.
	OptimalSavingUSD float64
	InsufficientData bool
	// Activatable is false for a simulation-only arm, or a 1h-tier arm on a tenant
	// whose model does not honor it — see proxy/campaign.go's arm-mapping table. A
	// non-activatable cell is still recorded, with SkipReason saying why, never hidden.
	Activatable bool
	SkipReason  string
	// StrategyID is which keepalive_strategies row now serves this cell, "" when
	// Activatable is false. Multiple cells commonly share one StrategyID — see the
	// coalescing rule in proxy/campaign.go.
	StrategyID string
}

CampaignCell is one (tenant, hour-of-day) suggest cell, frozen at campaign-creation time. This IS the "historical/predicted saving" half of the drill-down; there is no corresponding "real" field on this type on purpose — see the file doc comment.

type CampaignCellOwner

type CampaignCellOwner struct {
	TenantID     string
	HourUTC      int
	CampaignID   string
	CampaignName string
}

CampaignCellOwner names which ACTIVE campaign already enforces one (tenant, hour) — the input the create flow needs to refuse enforcing it a second time.

type Code

type Code struct {
	Plain     string
	ExpiresAt time.Time
}

Code is a freshly issued challenge. The Plain field is the ONLY place the digits exist outside the user's mailbox: it is not stored (only its hash is), and the caller's single job is to hand it to the mailer and drop it.

type CodePurpose

type CodePurpose string

CodePurpose separates the two flows so a registration code cannot be spent as a login second factor (or the reverse) — same tenant, same table, different meaning.

const (
	PurposeRegister CodePurpose = "register"
	PurposeLogin    CodePurpose = "login"
	// PurposeReset is a password reset. A third purpose rather than a reuse of the login
	// code, and the separation is the security property: the purpose is mixed into the
	// hash, so a login code cannot be spent at the reset endpoint and a reset code cannot
	// be spent as a second factor. Which purpose is in play is decided by the ROUTE that
	// spends it, never by a field the client sends.
	PurposeReset CodePurpose = "reset"
)

type DayPoint

type DayPoint struct {
	Day  int64   `json:"day"` // epoch ms, midnight UTC
	N    int     `json:"n"`
	Mean float64 `json:"mean"` // mean of "overall" that day
}

DayPoint is one UTC day of the trend. UTC so two people reading the same chart see the same buckets.

type DimStat

type DimStat struct {
	Dimension string  `json:"dimension"`
	N         int     `json:"n"`
	Mean      float64 `json:"mean"`
	// Dist counts stars: Dist[0] is how many 1-star answers, Dist[4] how many 5-star.
	Dist [5]int `json:"dist"`
}

DimStat is one question's arithmetic: how many people answered it, their mean, and the shape of the answers. The distribution is reported alongside the mean because a 3.0 made of 3s and a 3.0 made of 1s and 5s are different situations.

type DisabledError

type DisabledError struct{ Reason string }

DisabledError is ErrDisabled carrying the manager's REASON, so the refusal an agent receives can say why. It unwraps to ErrDisabled, so every existing errors.Is(err, ErrDisabled) branch keeps working unchanged — the reason is additive.

The reason is written by a manager and read by the account's owner. It is bounded and printable on write (validReason) precisely because it ends up in an HTTP body.

func (*DisabledError) Error

func (e *DisabledError) Error() string

func (*DisabledError) Unwrap

func (e *DisabledError) Unwrap() error

type Feedback

type Feedback struct {
	ID       int64
	TenantID string
	// Email and Label are copied in at write time rather than joined at read time, so
	// the manager's list still says who wrote something after an account is renamed.
	Email     string
	Label     string
	CreatedAt time.Time
	// Agent is which agent the answers are about, one of FeedbackAgents. Stored with the
	// submission so the manager's aggregate can be read per agent.
	Agent string
	// Scores maps a dimension to 1..5 stars.
	Scores map[string]int
	// Comment is the mandatory prose.
	Comment string
	// MailedAt is when the manager's copy was accepted by the relay; zero means it was
	// never delivered. The row is the source of truth either way.
	MailedAt time.Time
}

Feedback is one submission.

type FeedbackSummary

type FeedbackSummary struct {
	N          int        `json:"n"`
	Dimensions []DimStat  `json:"dimensions"`
	NPS        NPSSplit   `json:"nps"`
	Trend      []DayPoint `json:"trend"`
	// Unmailed counts submissions whose notification never got out, so a broken relay
	// is visible in the UI instead of only in the log.
	Unmailed int `json:"unmailed"`
	// ByAgent is this same arithmetic over the submissions about one agent, keyed by
	// FeedbackAgents key. The same shape rather than a narrower one because the question
	// a manager asks of the whole set — mean, spread, NPS — is the question they ask of
	// Claude Code alone. Empty in the nested values: one level is the breakdown.
	ByAgent map[string]*FeedbackSummary `json:"by_agent,omitempty"`
}

FeedbackSummary is everything the manager's view needs that is not a raw answer.

func Summarize

func Summarize(fs []*Feedback) FeedbackSummary

Summarize computes the aggregate from the submissions themselves, plus the same arithmetic per agent — which is the point of asking which agent it was about.

In Go rather than in SQL or in the browser: it is arithmetic somebody will act on, so it belongs somewhere a test can seed five rows and assert the mean.

type Labelled

type Labelled struct {
	Key   string `json:"key"`
	Label string `json:"label"`
}

Labelled is a key plus the words a human reads for it. The label lives HERE, with the key, because the form, the manager's table and the manager's email all need it: a copy in the browser and another in the mail body is three chances to ask one question three different ways.

type NPSSplit

type NPSSplit struct {
	Promoters  int     `json:"promoters"`
	Passives   int     `json:"passives"`
	Detractors int     `json:"detractors"`
	N          int     `json:"n"`
	Score      float64 `json:"score"`
}

NPSSplit is the recommend question read the way an NPS is read. The 1-5 mapping is stated here because there is no standard one: 5 promotes, 4 is passive, 1-3 detract. Score is promoters% − detractors%, so it runs -100..100.

type Options

type Options struct {
	// DefaultConfig is what a tenant's traffic runs under until they store a
	// configuration of their own — read live on every resolve, never copied into a
	// tenant's row, so changing it changes what every tracking tenant runs.
	// Empty = DefaultConfigYAML.
	DefaultConfig string
	// ManagerEmail, when it matches a registering email (case-insensitively), makes
	// that tenant a manager. This is how the first manager exists at all; an
	// interactive bootstrap step is a thing to forget and then work around.
	ManagerEmail string
	// EmailDomains restricts who may self-register (e.g. ["ibm.com"]). Empty means
	// anyone who can reach the port, which is only right on loopback.
	EmailDomains []string
	// DefaultUpstreams are the allow-list names a new tenant starts with.
	DefaultUpAnthropic string
	DefaultUpOpenAI    string
	DefaultUpBob       string
	// CacheTTL bounds how long a resolved token is trusted from memory. Mutations
	// through this registry clear the cache immediately, so the TTL only bounds
	// staleness from an EXTERNAL edit of the database. 0 = DefaultCacheTTL.
	CacheTTL time.Duration
	// Validate checks a configuration document before it is stored. nil skips
	// validation, which is right for tests and wrong for a server.
	Validate func([]byte) error
}

Options configures the registry.

type Patch

type Patch struct {
	Label          *string
	Role           *Role
	ConfigYAML     *string
	UpAnthropic    *string
	UpOpenAI       *string
	UpBob          *string
	CaptureContent *bool
	MaxRows        *int64
	Disabled       *bool
	// Variant and DisabledReason are manager-only, like Role/MaxRows/Disabled: one is
	// how an A/B group is assigned and the other is a note the account's owner reads,
	// and neither is a thing a user should be able to write about themselves.
	Variant        *string
	DisabledReason *string
}

Patch is a sparse update: a nil field is left alone. One method with pointers beats eight single-field setters, and it lets the audit trail record exactly the fields that changed.

type Registry

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

Registry is the control-plane store. Safe for concurrent use.

func Open

func Open(path string, o Options) (*Registry, error)

Open opens (creating if needed) the control database and runs migrations. An empty path opens a private in-memory database, for tests.

func (*Registry) ActiveCampaignCellOwners

func (r *Registry) ActiveCampaignCellOwners() ([]CampaignCellOwner, error)

ActiveCampaignCellOwners returns every (tenant, hour) that an active campaign already has a real strategy for.

The campaign_cells primary key already stops one campaign from naming a (tenant, hour) twice, but says nothing across campaigns — so two campaigns created from overlapping suggest runs each got their own live strategy for the same tenant in the same hour. Nothing crashed: the resolution chain simply picks the highest-priority match and the loser never fires. But both campaigns then reported that hour as theirs, one of them claiming a prediction for a strategy that never actually ran, and a manager reading either one had no way to tell which. Refusing the second enforcement (see proxy/campaign.go's overlap gate) is what makes "this campaign's cells" and "the strategies actually running" the same set.

ARCHIVED campaigns are excluded on purpose. Archiving does not delete the strategies a campaign created (see ArchiveCampaign), so an archived campaign's hours may well still be served — but archiving is exactly how a manager says "stop managing this as a group", and treating it as a permanent claim on those hours would leave no way to ever re-issue them short of deleting each strategy by hand. The narrower risk of an overlap with a deliberately archived campaign is the better trade than an un-releasable lock.

func (*Registry) AddFeedback

func (r *Registry) AddFeedback(t *Tenant, agent string, scores map[string]int, comment string) (*Feedback, error)

AddFeedback validates and stores one submission.

The tenant comes from the authenticated principal, never from the request body: this is the only writer, so there is no path by which a submission can be attributed to somebody else.

func (*Registry) AgentKeyCount

func (r *Registry) AgentKeyCount(tenantID string) (int, error)

AgentKeyCount reports how many keys a tenant has bound, for the settings page.

func (*Registry) ArchiveCampaign

func (r *Registry) ArchiveCampaign(id string) error

func (*Registry) Audit

func (r *Registry) Audit(targetID string, limit int) ([]AuditEntry, error)

Audit returns the most recent changes to a tenant, newest first. A shared service needs "which config change broke my agent, and who made it" to be answerable.

func (*Registry) AuditWrite

func (r *Registry) AuditWrite(actorID, targetID, field, before, after string) error

AuditWrite records an action that is not a field diff — a manager-initiated password reset, a storage purge, a password change — so the trail answers "who did this to my account" for those too, and not only for configuration edits.

Exported because the actions are performed at the HTTP layer over several packages' worth of state (the metrics database, the mailer), so there is no single registry method they could be recorded inside. It writes to the same table Update does, which is what makes /api/me/audit one list rather than three.

func (*Registry) BindAgentKey

func (r *Registry) BindAgentKey(tenantID, key string) error

BindAgentKey records that a provider key belongs to a tenant, by digest, so an agent that can only send that key is still identified. Idempotent for the tenant that already holds the binding.

What this actually establishes is only that the caller can type the string, NOT that they hold a key of their own — the digest is computed here, from whatever arrived, and nothing about it is verified against a provider. So a digest another tenant has bound is refused (ErrForbidden), never moved: a transfer has to be an unbind by the real owner followed by a fresh bind. Silently reassigning it would route the victim's traffic — and, with capture_content on, their transcripts — to whoever guessed it.

func (*Registry) ByEmail

func (r *Registry) ByEmail(email string) (*Tenant, error)

ByEmail reads one tenant by email (lowercased).

func (*Registry) CampaignByID

func (r *Registry) CampaignByID(id string) (Campaign, error)

CampaignByID reads one campaign.

func (*Registry) CampaignCells

func (r *Registry) CampaignCells(campaignID string) ([]CampaignCell, error)

CampaignCells returns every frozen cell for one campaign, ordered by tenant then hour — the same order the suggest payload it came from already used.

func (*Registry) ChangePassword

func (r *Registry) ChangePassword(tenantID, currentCookie, old, next string) error

ChangePassword replaces a signed-in user's password, checking the OLD one first.

The old password is required even though the caller already holds a session cookie, and that is not ceremony: a stolen cookie is the exact thing a password change would otherwise convert into permanent ownership of the account, locking the real owner out of a credential they still know.

It ends every OTHER browser session on success and leaves the caller's own alone. A password change is the moment a user acts on "someone else may be in here", so the other sessions have to go; signing the person out of the tab they just used to do it would make the feature feel broken.

func (*Registry) Close

func (r *Registry) Close() error

Close releases the database.

func (*Registry) Config

func (r *Registry) Config(t *Tenant) string

Config returns the configuration document to run this tenant's traffic under, falling back to the server default when the tenant has none. Resolution fails OPEN: a user's agent must not break because their configuration row is empty.

func (*Registry) CreateCampaign

func (r *Registry) CreateCampaign(actorID string, c Campaign, cells []CampaignCell) (Campaign, error)

CreateCampaign and ArchiveCampaign commit and then tell the registry's listener (see SetOnChange).

func (*Registry) CreateStrategy

func (r *Registry) CreateStrategy(actorID string, s Strategy) (Strategy, error)

The three writers below commit through the unexported versions above and then tell the registry's listener, so a cached dashboard read that includes strategies is dropped the moment one changes.

func (*Registry) DefaultConfig added in v0.5.2

func (r *Registry) DefaultConfig() string

DefaultConfig is the document a tenant with no stored configuration runs under.

func (*Registry) Delete

func (r *Registry) Delete(actor *Tenant, targetID string) error

Delete removes an account and every control-plane row that hangs off it: its tokens, its browser sessions, its bound agent keys and any pending email code, all by ON DELETE CASCADE.

It does NOT touch the metrics database. That is a SEPARATE file (dash's request store), so no foreign key reaches it and deleting this row would otherwise leave a tenant's requests, component rows, captured transcripts and archived objects behind, owned by an id no account answers to. The caller purges those first — see proxy's ctlDeleteTenant, which runs dash.Recorder.PurgeTenant before this and once more after it.

Manager only, and never the actor's own account. Self-deletion is refused because the manager routes are the only way to make another manager: a deployment whose last manager deleted themselves has no way back except editing the database by hand.

The audit row is written in the SAME transaction, before the delete. tenant_config_audit deliberately has no foreign key on target_tenant, so the trail outlives the account it describes — which is the whole point of auditing a deletion.

func (*Registry) DeleteStrategy

func (r *Registry) DeleteStrategy(id string) error

func (*Registry) EndAllWebSessions

func (r *Registry) EndAllWebSessions(tenantID string) error

EndAllWebSessions signs a tenant out everywhere. Used when an account is disabled: leaving a live dashboard login behind would mean a disabled user could still read their history until the cookie lapsed.

func (*Registry) EndOtherWebSessions

func (r *Registry) EndOtherWebSessions(tenantID, keep string) error

EndOtherWebSessions signs a tenant out everywhere EXCEPT the browser making the request — the "sign out my other machines" half of a password change.

keep is the caller's own cookie value, hashed here rather than passed in as a digest, so no caller has to know how a session id is derived. An empty keep ends all of them, which is the same thing EndAllWebSessions does.

func (*Registry) EndWebSession

func (r *Registry) EndWebSession(cookie string) error

EndWebSession signs one browser out. Idempotent: signing out twice, or with a cookie that was already expired, is a success — the caller's intent is satisfied either way.

func (*Registry) EndWebSessionBySID

func (r *Registry) EndWebSessionBySID(tenantID, sid string) error

EndWebSessionBySID revokes ONE of a tenant's logins by its public handle.

Scoped by tenant_id inside the WHERE clause rather than checked after the fact, so "revoke session X" cannot reach another account's row even if a handle is guessed.

ponytail: matches on substr(hex(id)) so the handle needs no stored column, at the cost of a scan over this tenant's own sessions. A user has a handful; add an indexed sid column if that ever stops being true.

func (*Registry) FeedbackList

func (r *Registry) FeedbackList(tenantID string, limit int) ([]*Feedback, error)

FeedbackList returns submissions newest first. An empty tenantID means every account's — which is a MANAGER view, gated at the handler, never here.

func (*Registry) FirstManagerEmail

func (r *Registry) FirstManagerEmail() (string, error)

FirstManagerEmail returns a registered manager's address, for when --manager-email was not set but somebody holds the role anyway.

func (*Registry) Get

func (r *Registry) Get(id string) (*Tenant, error)

Get reads one tenant by id.

func (*Registry) IssueCode

func (r *Registry) IssueCode(tenantID string, p CodePurpose) (Code, error)

IssueCode mints a code for a tenant and purpose, replacing any pending one.

func (*Registry) List

func (r *Registry) List() ([]*Tenant, error)

List returns every tenant, newest first. Manager-only at the API layer.

func (*Registry) ListCampaigns

func (r *Registry) ListCampaigns() ([]Campaign, error)

ListCampaigns returns every campaign, newest first — no cells; call CampaignCells for one campaign's own, the same list/detail split ListStrategies/StrategyByID uses.

func (*Registry) ListStrategies

func (r *Registry) ListStrategies() ([]Strategy, error)

ListStrategies returns every strategy, newest first. Loaded into the keeper's memory at process start and refreshed on every write — see proxy/keepalivestrategy.go.

func (*Registry) ManagerEmail

func (r *Registry) ManagerEmail() string

ManagerEmail is the address configured with --manager-email, for the notification path. Exported as an accessor rather than a field so nothing can rewrite it after the registry is open.

func (*Registry) MarkFeedbackMailed

func (r *Registry) MarkFeedbackMailed(id int64, at time.Time) error

MarkFeedbackMailed records that the manager's copy was delivered.

func (*Registry) MintToken

func (r *Registry) MintToken(tenantID, label string) (string, error)

MintToken issues an additional token for a tenant, so a machine can be added or a credential rotated without downtime. The plaintext is returned once.

func (*Registry) NewWebSession

func (r *Registry) NewWebSession(token string, ttl time.Duration) (*Tenant, string, error)

NewWebSession authenticates a plaintext PROXY token and, if it is valid, opens a dashboard login for its tenant. Returning the cookie value once, like a token.

Going through the proxy token means the browser never becomes a second place a long-lived credential has to be stored, and it means "can you prove you hold the token" is the only question the login flow has to answer.

func (*Registry) OpenWebSession

func (r *Registry) OpenWebSession(tenantID string, m SessionMeta, ttl time.Duration) (string, error)

OpenWebSession signs a tenant in on one machine WITHOUT checking a credential — the caller has already done that (password plus emailed code, or a proxy token). Returns the cookie value once.

Sessions ACCUMULATE rather than replace: signing in on a desktop must not sign the laptop out. Several concurrent logins per account are the expected state, which is what the per-row metadata is for — a list of hashes is not something a user can revoke from.

func (*Registry) Register

func (r *Registry) Register(label, email string) (*Tenant, string, error)

Register creates a tenant and its first token. The returned string is the ONLY time the plaintext token exists outside the caller's machine: it is not stored, logged, or recoverable. Show it once.

func (*Registry) RegisterAccount

func (r *Registry) RegisterAccount(label, email, password string) (*Tenant, error)

RegisterAccount creates an unverified account with a password and no token. The caller is expected to follow immediately with IssueCode + a mail send.

Re-registering an existing address is refused unless the account behind it has NEVER been usable: no password set and not one token row, live or revoked. "Unverified" alone is not that test and must never be used as one — migration v3 added email_verified_at with DEFAULT 0, so every account created before email auth is unverified while being in daily use. Gating on unverified would make this endpoint a password reset for those accounts: type a colleague's address, get their row back with your own password installed, and the owner is locked out of both doors at once (loginWithToken refuses an account that has a password; they do not know it).

The cost of the strict test is that an abandoned half-registration reserves the address until an operator clears it. That is the right way round: a squatted address is a support ticket, a claimable live account is a takeover.

func (*Registry) ResetPassword

func (r *Registry) ResetPassword(tenantID, code, next string) error

ResetPassword completes the emailed-code recovery flow: it spends a PurposeReset code and installs the new password.

One function rather than VerifyCode + SetPassword at the HTTP layer, for the same reason VerifyRegistration is one function: a handler that spent the code and then failed to write the password would burn the user's only code and leave them exactly where they started, and its retry would need a fresh one.

Every session goes, including the caller's — there is no session at this point anyway (this flow is reached by someone who cannot sign in), and whoever else was in the account is precisely who a recovery is meant to evict.

func (*Registry) Resolve

func (r *Registry) Resolve(token string) (*Tenant, error)

Resolve maps a plaintext token to its tenant. This is on the proxy's hot path, so a hit is served from memory; a miss reads the database and stamps last_used_at, which bounds that write to once per CacheTTL per token rather than once per request.

There is no secret-dependent comparison to make constant-time: the sha256 IS the lookup key, and computing it requires already holding the token.

func (*Registry) ResolveAgentKey

func (r *Registry) ResolveAgentKey(key string) (*Tenant, error)

ResolveAgentKey maps a caller's own provider key to the tenant that bound it. Same caching and last-used bookkeeping as Resolve, and the same closed failure: an unbound key is not a new tenant.

func (*Registry) RevokeToken

func (r *Registry) RevokeToken(tenantID, prefix string) error

RevokeToken revokes one of a tenant's tokens by its public prefix. Revocation is a timestamp, not a delete, so a leaked credential stays visible in the audit trail instead of quietly disappearing.

func (*Registry) Sessions

func (r *Registry) Sessions(tenantID, currentCookie string) ([]Session, error)

Sessions lists a tenant's live logins, most recently active first. Expired rows are filtered in the QUERY, for the same reason WebSession filters there: the sweeper is a disk job, never the access control.

func (*Registry) SetOnChange added in v0.5.3

func (r *Registry) SetOnChange(fn func(kind string))

SetOnChange registers fn to run after every committed write to an account (its configuration, its removal list, its upstreams, its label) and to the keep-alive strategy and campaign ledgers. The dashboard uses it to drop cached reads that include that state; without it a cached body would show the old state for as long as the cache may serve it. Set once at start-up.

func (*Registry) SetPassword

func (r *Registry) SetPassword(tenantID, password string) error

SetPassword replaces an account's password. Both callers are in this file: ChangePassword (the signed-in user, old password required) and ResetPassword (the emailed-code recovery flow). It is deliberately NOT exported behaviour a manager can reach — see ResetPassword.

func (*Registry) StrategyByID

func (r *Registry) StrategyByID(id string) (Strategy, error)

StrategyByID reads one strategy.

func (*Registry) SweepCodes

func (r *Registry) SweepCodes() (int64, error)

SweepCodes deletes lapsed codes. Disk reclaim only — VerifyCode refuses an expired row on its own, so a sweep that never runs costs space, never access. Same contract as SweepWebSessions, and called from the same place.

func (*Registry) SweepWebSessions

func (r *Registry) SweepWebSessions() (int64, error)

SweepWebSessions deletes expired logins. Purely a disk-reclaim job — WebSession already refuses an expired row, so skipping this costs space, not safety.

func (*Registry) Tokens

func (r *Registry) Tokens(tenantID string) ([]Token, error)

Tokens lists a tenant's tokens, including revoked ones.

func (*Registry) UnbindAgentKeys

func (r *Registry) UnbindAgentKeys(tenantID string) error

UnbindAgentKeys drops every agent key bound to a tenant. There is no per-key variant: the digests are not displayable, so "which one" is not a question the user can answer.

func (*Registry) Update

func (r *Registry) Update(actor *Tenant, targetID string, p Patch) error

Update applies a patch to a tenant, recording each changed field in the audit log. actor must be the target tenant or a manager; only a manager may change role, row quota, or disabled state — the fields a user would otherwise raise on themselves.

func (*Registry) UpdateStrategy

func (r *Registry) UpdateStrategy(actorID, id string, p StrategyPatch) (Strategy, error)

func (*Registry) VerifyCode

func (r *Registry) VerifyCode(tenantID string, p CodePurpose, code string) error

VerifyCode consumes a code. Success DELETES the row, which is what makes a code one-time: replaying it a second later finds nothing and fails.

Runs in a transaction because the attempt counter is the security control, and an increment that races with a concurrent guess is an increment an attacker gets for free.

func (*Registry) VerifyLogin

func (r *Registry) VerifyLogin(email, password string) (*Tenant, error)

VerifyLogin is the FIRST factor: it checks an email and password and nothing else. It opens no session — the caller must still put a mailed code in front of one.

Every failure returns ErrWrongPass, whether the address is unknown, the password is wrong, or no password has been set. One error for all three, so this endpoint cannot be used to learn which addresses have accounts. ErrDisabled and ErrNotVerified are the two exceptions, because a user who cannot sign in needs to be told which of the two things to do about it, and both require having got the password right first.

The argon2 verify runs even for an unknown address, against a throwaway hash. Not doing so makes "unknown email" answer in microseconds and "wrong password" in ~50 ms, which turns the deliberately vague error message into a precise account enumeration oracle.

func (*Registry) VerifyRegistration

func (r *Registry) VerifyRegistration(tenantID, code string) (*Tenant, string, error)

VerifyRegistration completes a registration: it consumes the mailed code, marks the address verified, and mints the account's FIRST proxy token, returned once.

One function rather than three calls at the HTTP layer, because "verified" and "has a usable token" must not be able to disagree — a handler that verified and then failed to mint would leave an account that can sign in but cannot send traffic, and its retry would mint a second token. Idempotent-ish on the token: an already verified account gets no new one.

func (*Registry) WebSession

func (r *Registry) WebSession(cookie string) (*Tenant, error)

WebSession resolves a cookie value to its tenant, refusing an expired one.

Expiry is enforced HERE, in the query, rather than relying on a sweeper. A sweep that fails or falls behind would otherwise silently extend every login, and a missed cleanup should cost disk, never access.

type Role

type Role string

Role decides what a token may see beyond its own rows. Exactly two, because a permission matrix nobody asked for is the classic thing to regret.

const (
	RoleUser    Role = "user"
	RoleManager Role = "manager"
)

type Session

type Session struct {
	// SID is the public handle: the first 16 hex characters of sha256(cookie). It is
	// DERIVED rather than stored, so there is no second column to keep in step with
	// the key, and it is safe to show because it is a truncation of a hash of the
	// only thing that authenticates — holding the SID proves nothing and unlocks
	// nothing.
	SID        string
	Label      string
	UserAgent  string
	IP         string
	CreatedAt  time.Time
	LastSeenAt time.Time
	ExpiresAt  time.Time
	// Current marks the session making the request, so the UI can label it and warn
	// before it signs itself out.
	Current bool
}

Session is one signed-in machine, as its owner sees it.

type SessionMeta

type SessionMeta struct {
	// Label is a short human name for the machine ("laptop"). Falls back to
	// "browser" when empty or unprintable.
	Label string
	// UserAgent is truncated on write: a real browser string is bounded, an
	// attacker's is not.
	UserAgent string
	IP        string
}

SessionMeta is what a new login records about the machine it came from, so the owner can tell their sessions apart well enough to revoke the right one. All of it is UNTRUSTED — client-supplied text (User-Agent) or a network fact (IP). It is display material for the account's owner, never an authorisation input.

type Strategy

type Strategy struct {
	ID              string
	Name            string
	IdleSeconds     int
	MaxPings        int
	MinPrefixTokens int
	MaxUSDPerPing   float64
	Windows         []Window
	Target          Target
	Active          bool
	// PredictorID optionally names a registered kvcache.Predictor that must also clear
	// PredictorThreshold before a ping fires, on top of the window/target match above.
	// "" (the default) means no predictor gate at all — a strategy with an empty
	// PredictorID behaves exactly as every strategy did before this field existed.
	// Resolving the id to an actual Predictor implementation, and refusing an unknown
	// one, is proxy's job (this package only stores the reference); see
	// proxy/keepalivestrategy.go.
	PredictorID string
	// PredictorThreshold is the minimum probability PredictorID must return for a ping
	// to fire. Ignored while PredictorID is "".
	PredictorThreshold float64
	// HeadTTL1h asks for the one-hour tier on the head breakpoints, the same knob a
	// tenant's own account config exposes (config.CacheConfig.HeadTTL1h) — see
	// apply/headttl.go. False (the default) leaves the account's own setting in force;
	// a strategy can only turn this ON, never off, matching how it only ever turns
	// KeepAlive on (proxy/keepalivestrategy.go's applyStrategy).
	HeadTTL1h bool
	// HeadTTLMinTokens gates HeadTTL1h on request size. Ignored while HeadTTL1h is false.
	HeadTTLMinTokens int
	CreatedBy        string
	CreatedAt        time.Time
	UpdatedBy        string
	UpdatedAt        time.Time
}

Strategy is a manager-authored keep-alive rule — see the design doc's "Model".

func (Strategy) InWindow

func (s Strategy) InWindow(now time.Time) bool

InWindow reports whether this strategy's schedule covers `now`, ignoring Target and Active — the "would this fire right now, for whoever it targets" flag the strategies list shows at a glance.

func (Strategy) Matches

func (s Strategy) Matches(now time.Time, tenantID string) bool

Matches reports whether this strategy applies to tenantID right now: Active, the target covers tenantID, and now falls inside one of its windows — see the design doc's "Model" for the precise rule.

func (Strategy) ValidatePredictor

func (s Strategy) ValidatePredictor() error

ValidatePredictor checks only this strategy's own shape: a threshold in [0,1], and only when a predictor is actually named — an unset PredictorID with a nonzero, unused threshold left over from a previous edit is not an error, since it is ignored either way. Whether PredictorID actually NAMES a registered kvcache.Predictor is not knowable here (this package has no registry of them) — that check belongs to the caller that does, exactly as an unknown strategy name is refused by kvcache.NewStrategy rather than silently defaulted. See proxy/keepalivestrategy.go.

type StrategyPatch

type StrategyPatch struct {
	Name               *string
	IdleSeconds        *int
	MaxPings           *int
	MinPrefixTokens    *int
	MaxUSDPerPing      *float64
	Windows            *[]Window
	Target             *Target
	Active             *bool
	PredictorID        *string
	PredictorThreshold *float64
	HeadTTL1h          *bool
	HeadTTLMinTokens   *int
}

StrategyPatch is a sparse update, matching Patch's own pointer convention: a nil field is left alone.

type Target

type Target struct {
	Mode      string   `json:"mode"` // TargetAll | TargetList
	TenantIDs []string `json:"tenant_ids,omitempty"`
}

Target selects which tenants a strategy applies to.

func (Target) Covers added in v0.5.2

func (t Target) Covers(tenantID string) bool

Covers reports whether the target includes tenantID, ignoring Active and the windows.

func (Target) Validate

func (t Target) Validate() error

Validate checks the target's own shape: a known mode, and at least one tenant id for a list-target strategy (an empty list matches nothing, which is never what was meant).

type Tenant

type Tenant struct {
	ID    string
	Label string
	Email string
	Role  Role
	// ConfigYAML is the tenant's context-guru configuration, validated on write by
	// the same strict loader the proxy uses. Empty means "use the server default".
	ConfigYAML string
	// Upstream selections, by name into the server's allow-list — never a URL. A
	// user-supplied upstream URL would make this proxy an SSRF hop out of the
	// network, which is not a tradeoff, just a hole.
	UpAnthropic string
	UpOpenAI    string
	UpBob       string
	// CaptureContent opts this tenant into storing before/after transcript text.
	// Per-tenant by design: the redactor is a best-effort denylist, so this is consent,
	// not a switch. A new account starts with it ON (see Register for why); the column's
	// DEFAULT 0 applies only to rows inserted without the field.
	CaptureContent bool
	// MaxRows caps this tenant's retained request rows so one heavy user cannot
	// evict everyone else's history. 0 = the server default
	// (--dashboard-max-rows-per-tenant). Enforced by the dashboard janitor, which reads
	// it through dash.Recorder.SetTenantQuota — wired in cmd/context-guru-proxy.
	MaxRows int64
	// Variant is the A/B group a manager put this account in, or "" for none. It is a
	// LABEL and nothing else: it selects no configuration and changes no behaviour, so
	// assigning it can never break someone's agent. What it buys is the ability to group
	// the metrics that already exist by the group a manager assigned — see the /api/variants
	// rollup, which is honest about the fact that a manager's assignment is not a
	// randomised trial.
	Variant string
	// DisabledReason is the manager's note on why this account is off, shown to its
	// owner in the 403 their agent receives and in the refusal at sign-in. Without it
	// "disabled" is undiagnosable from the outside: the person whose agent stopped has
	// no way to learn whether it was deliberate.
	DisabledReason string
	Disabled       bool
	CreatedAt      time.Time
	LastSeenAt     time.Time
	// VerifiedAt is when this account proved it owns its email address, by entering
	// a code we mailed there. Zero means unverified: the account exists but holds no
	// token and cannot sign in.
	VerifiedAt time.Time
	// HasPassword reports whether a dashboard password is set. The HASH itself is
	// deliberately NOT a field on this struct — it is loaded only inside
	// VerifyLogin, so there is no path by which a caller that renders a Tenant can
	// render a password hash.
	HasPassword bool
}

Tenant is one user of the service.

func (*Tenant) IsManager

func (t *Tenant) IsManager() bool

IsManager reports whether this tenant may read and write other tenants.

func (*Tenant) TracksDefault

func (t *Tenant) TracksDefault() bool

TracksDefault reports whether this tenant follows the server default rather than a configuration of their own. It is the ONE test for that, used by Config to resolve the document and by the API to tell the UI which state to draw — two copies of the same predicate is how a settings page ends up disagreeing with the proxy.

func (*Tenant) Verified

func (t *Tenant) Verified() bool

Verified reports whether this account's email address has been confirmed.

type Token

type Token struct {
	Prefix     string // first 8 chars of the random part, for display
	Label      string
	TenantID   string
	CreatedAt  time.Time
	LastUsedAt time.Time
	RevokedAt  time.Time
}

Token is the public view of a credential: enough to recognise and revoke one, never enough to use it.

func (Token) Revoked

func (t Token) Revoked() bool

Revoked reports whether this token has been revoked.

type Window

type Window struct {
	Days  []time.Weekday `json:"days,omitempty"`
	Start string         `json:"start"`
	End   string         `json:"end"`
	// TZ is an IANA zone name. Empty resolves to DefaultStrategyTZ.
	TZ string `json:"tz,omitempty"`
}

Window is one recurring span a strategy is active in, evaluated in its own timezone. Days empty means every day. Start/End are "HH:MM" (24-hour), and End must be strictly after Start: an overnight window is out of scope (see the design doc's "Out of scope").

func (Window) Validate

func (w Window) Validate() error

Validate checks this window's own shape: parseable HH:MM bounds, End strictly after Start (an overnight window is out of scope), a loadable IANA timezone, and weekdays in range. It does not know the keep-alive's own spend-authorization bounds (Idle/MaxPings/…) — that check lives in proxy, alongside validOverride's bounds.

func (Window) Zone added in v0.5.2

func (w Window) Zone() string

Zone is the IANA zone the window is evaluated in: TZ, or DefaultStrategyTZ when it is empty.

Jump to

Keyboard shortcuts

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