postgres

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultSlug = "default"

DefaultSlug is the tenant every deployment has.

View Source
const MinimumReason = 10

MinimumReason is the shortest thing that counts as an explanation. It is enforced by the database as well, because a reason nobody can read is the same as no reason.

Variables

View Source
var (
	ErrNoDestination = errors.New("no destination with that name")
	ErrAlreadyRouted = errors.New("this provider already delivers to that url")
)
View Source
var (
	ErrNoReason       = errors.New("say why this is being delivered anyway, in a sentence")
	ErrNothingToForce = errors.New(
		"none of those events are waiting on a failed signature")
)
View Source
var (
	ErrNoUser     = errors.New("no user with that email")
	ErrNoEvent    = errors.New("no event with that identifier")
	ErrNoRoute    = errors.New("no route with that identifier")
	ErrNoProvider = errors.New("no verification configured")
)
View Source
var (
	ErrNoRole = errors.New("no role with that name")
	// A shipped role is what the panel falls back on, so removing one is
	// refused rather than silently ignored.
	ErrRoleKept = errors.New("that role is shipped with Charon and is not removed")
)
View Source
var ErrBadDestination = errors.New(
	"a destination needs an http or https address with a host")

ErrBadDestination is an address nothing could ever be delivered to.

View Source
var ErrBodyTooLarge = errors.New("body too large to record")
View Source
var ErrNoOperator = errors.New("no operator with that identifier in this tenant")
View Source
var ErrNoSigningSecret = fmt.Errorf("that destination does not sign with that secret")
View Source
var ErrNoTenant = errors.New("no tenant with that slug")
View Source
var ErrRetentionSpan = errors.New("retention is between 1 and 3650 days, or none to keep for ever")

Functions

func DeliverableURL

func DeliverableURL(raw string) (string, error)

DeliverableURL is what an address has to be before anything is routed to it. It lives here rather than in a form, because the panel and the command line are two ways to the same decision and only one of them was checking.

It says nothing about the path. A trailing slash is a real endpoint, and what belongs after the host is the receiver's business.

Types

type AReference

type AReference struct {
	ID        uuid.UUID
	Tenant    uuid.UUID
	Reference string
}

AReference is one signing secret as the process that delivers sees it: something to try to read, and somewhere to say what happened.

type Isolation

type Isolation struct {
	// Enforced is false when the connected role is a superuser or carries
	// BYPASSRLS. Postgres exempts both, and a policy that does not apply is
	// decoration.
	Enforced bool
	Tenants  int64
	Role     string
}

Isolation reports whether the database is enforcing the separation as well as Charon does. Charon keeps tenants apart on its own: every row carries the tenant it belongs to and every query is scoped to one. Row level security is the same rule again, one layer down, for a deployment that wants the database to refuse rather than trust the application. It applies only to a role that is neither a superuser nor carries BYPASSRLS.

type Kinds

type Kinds struct {
	Transports []string
	Verifiers  []string
	Methods    []string
}

Kinds is what a build knows how to do: the transports it can deliver over, the proofs it can check, and the ways it accepts a sign-in. Each is a registry a deployment extends by writing Go, so the rows a key points at are written by the process that has them rather than frozen in a migration.

type ProviderSettings

type ProviderSettings struct {
	Name          string
	SecretEnv     string
	SecretPresent bool
	provider.Settings
}

ProviderSettings is the configuration as stored, without secrets, for the panel and the command line to show.

type Retention

type Retention struct {
	Slug string
	Days int
}

Retention is how long one tenant's events are kept. Days is zero when they are kept for ever, which is what a tenant nobody has configured gets.

type SigningSecret

type SigningSecret struct {
	Destination string
	Reference   string
	Added       time.Time
}

SigningSecret is one secret a destination signs with, as an operator sees it: where the secret is kept, never what it is.

type Store

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

func Open

func Open(ctx context.Context, dsn string) (*Store, error)

func (*Store) AddRoute

func (s *Store) AddRoute(
	ctx context.Context, provider, destination, url, transport string,
) error

func (*Store) AddSigningSecret

func (s *Store) AddSigningSecret(ctx context.Context, destination, reference string) error

func (*Store) AllVerification

func (s *Store) AllVerification(
	ctx context.Context,
) (map[uuid.UUID]map[string]provider.Settings, error)

AllVerification reads the settings of every tenant, because one process checks requests for all of them. It reads them one tenant at a time rather than in a single query, so it returns the same thing whether or not the role it connects as is confined by row level security.

func (*Store) Claim

func (s *Store) Claim(
	ctx context.Context, batch int, lease time.Duration,
) ([]outbound.Delivery, error)

Claim takes a batch of due deliveries under a lease, so a worker that dies leaves its rows to be picked up again once the lease expires.

One tenant at a time, for the same reason planning is: this process works for all of them and the database answers for one. The batch is spread across them rather than granted to each.

func (*Store) ClearSystemAdmin

func (s *Store) ClearSystemAdmin(ctx context.Context, id uuid.UUID) error

ClearSystemAdmin puts the account back into a tenant, which it has to be given because it no longer has one.

func (*Store) ClearSystemAdminByEmail

func (s *Store) ClearSystemAdminByEmail(ctx context.Context, email string) error

func (*Store) Close

func (s *Store) Close()

func (*Store) CountEvents

func (s *Store) CountEvents(ctx context.Context) (int64, error)

func (*Store) CountSystemAdmins

func (s *Store) CountSystemAdmins(ctx context.Context) (int64, error)

func (*Store) CountUsers

func (s *Store) CountUsers(ctx context.Context) (int64, error)

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, digest []byte, userID uuid.UUID, expires time.Time) error

func (*Store) CreateTenant

func (s *Store) CreateTenant(ctx context.Context, slug, name string) (console.Tenant, error)

CreateTenant makes a tenant. The roles Charon ships belong to no tenant and are held in every one, so there is nothing to seed alongside it.

func (*Store) CreateUser

func (s *Store) CreateUser(
	ctx context.Context, email, passwordHash string, place console.Placement,
) error

CreateUser makes the person and puts them in a tenant in one go, because an account that belongs nowhere can reach nothing.

func (*Store) DeleteExpiredSessions

func (s *Store) DeleteExpiredSessions(ctx context.Context) error

func (*Store) DeleteOperator

func (s *Store) DeleteOperator(ctx context.Context, id uuid.UUID) error

func (*Store) DeleteProvider

func (s *Store) DeleteProvider(ctx context.Context, name string) error

func (*Store) DeleteRole

func (s *Store) DeleteRole(ctx context.Context, name string) error

DeleteRole leaves the shipped roles alone: they are what the panel falls back on, and a deployment that wants them gone can stop mapping anyone to them.

func (*Store) DeleteRoute

func (s *Store) DeleteRoute(ctx context.Context, routeID uuid.UUID) error

Removes the route so nothing new is planned for it. The destination and every delivery already recorded against it are left alone: dropping them would erase history an operator may still need.

func (*Store) DeleteSession

func (s *Store) DeleteSession(ctx context.Context, digest []byte) error

func (*Store) DeleteTenant

func (s *Store) DeleteTenant(ctx context.Context, slug string) error

func (*Store) DeliveryStates

func (s *Store) DeliveryStates(ctx context.Context) (map[string]int64, error)

func (*Store) DetailedRoutes

func (s *Store) DetailedRoutes(ctx context.Context) ([]console.RouteRow, error)

func (*Store) Event

func (s *Store) Event(ctx context.Context, id uuid.UUID) (db.InboundEvent, error)

func (*Store) EventDeliveries

func (s *Store) EventDeliveries(ctx context.Context, eventID uuid.UUID) ([]console.Delivery, error)

func (*Store) EventDetail

func (s *Store) EventDetail(ctx context.Context, id uuid.UUID) (console.EventDetail, error)

func (*Store) EventsAwaitingRoute

func (s *Store) EventsAwaitingRoute(ctx context.Context) (int64, error)

Events recorded for a provider that has no enabled route. They stay unplanned on purpose and are delivered as soon as a route appears.

func (*Store) EveryReference

func (s *Store) EveryReference(ctx context.Context) ([]AReference, error)

EveryReference reads them across all tenants, one tenant at a time, so it returns the same thing whether or not the role it connects as is confined by row level security.

func (*Store) Force

func (s *Store) Force(
	ctx context.Context, operator uuid.UUID, reason string, events []uuid.UUID,
) (int64, error)

Force delivers events whose signature failed, under one reason that covers all of them, and returns how many it applied to.

The verdict is not rewritten. An event delivered this way is still invalid or missing and says so for ever; what is added is who let it through. An event already overruled is left with the first decision, because that is the one that let it out.

func (*Store) ForgetTenants

func (s *Store) ForgetTenants()

ForgetTenants drops every held mapping, so the next request for any slug resolves it again.

func (*Store) Isolation

func (s *Store) Isolation(ctx context.Context) (Isolation, error)

func (*Store) Join

func (s *Store) Join(ctx context.Context, user uuid.UUID, place console.Placement) error

Join puts somebody who already exists into a tenant, or changes the role they hold there.

func (*Store) KnownProviders

func (s *Store) KnownProviders(ctx context.Context) ([]string, error)

KnownProviders names every provider this tenant has already established, by configuring verification for it, by routing it, or by having received a request under it. A name is never declared up front, so this is the only thing a new one can be weighed against.

func (*Store) LeaveTenant

func (s *Store) LeaveTenant(ctx context.Context, user, tenant uuid.UUID) error

LeaveTenant takes somebody out of a tenant. The account stays: it may belong to others, and belonging is a relationship rather than a property.

func (*Store) MarkDelivered

func (s *Store) MarkDelivered(ctx context.Context, tenant, id uuid.UUID, status int) error

func (*Store) MarkFailed

func (s *Store) MarkFailed(
	ctx context.Context,
	tenant, id uuid.UUID,
	nextAttempt time.Time,
	status int,
	reason string,
	maxAttempts int,
) error

func (*Store) Memberships

func (s *Store) Memberships(ctx context.Context, user uuid.UUID) ([]console.Membership, error)

Memberships is every tenant somebody belongs to, which is what the panel offers them to move between.

func (*Store) Migrate

func (s *Store) Migrate(ctx context.Context) (applied []string, err error)

func (*Store) NextWorkAt

func (s *Store) NextWorkAt(ctx context.Context) (time.Time, bool, error)

The earliest moment there is anything to do: an event still to plan, or a delivery whose retry window has come. Reports false when the queue is idle. NextWorkAt is the earliest moment any tenant has something due, so the loop sleeps until then instead of polling. Asked one tenant at a time, because a question that names none is answered for one of them, and sleeping on that answer leaves every other tenant waiting out the safety interval.

func (*Store) Notifications

func (s *Store) Notifications(ctx context.Context) <-chan struct{}

Wake-ups announced by Record when it commits. The channel is closed when ctx is done. A lost notification is not an error here: the dispatcher's safety interval catches whatever a notification failed to announce.

func (*Store) OldestPendingSeconds

func (s *Store) OldestPendingSeconds(ctx context.Context) (float64, error)

func (*Store) Operators

func (s *Store) Operators(ctx context.Context) ([]console.Operator, error)

func (*Store) PanelChanges

func (s *Store) PanelChanges(ctx context.Context) <-chan struct{}

Wake-ups for the panel: a recorded event, a delivery that changed state, a replay. Closed when ctx is done.

func (*Store) Pending

func (s *Store) Pending(ctx context.Context) ([]string, error)

Pending is what this build carries that the database has not applied. A process that only reads and writes — the one that delivers — has to know this before it starts, because running new code against an old schema fails on every round with an error about a missing column, which reads like a defect rather than like a rollout still in progress.

func (*Store) Permissions

func (s *Store) Permissions(ctx context.Context) (map[authz.Permission]string, error)

Permissions is the closed set as the database holds it, which is what a grant points at. It exists as rows so that granting something nothing enforces fails on a foreign key and not only on a check in Go.

func (*Store) Ping

func (s *Store) Ping(ctx context.Context) error

func (*Store) Placement

func (s *Store) Placement(
	ctx context.Context, method string, claims []string,
) ([]console.Placement, error)

Placement resolves where an identity belongs from the claims it presented. The first claim that is mapped wins, so the order the identity provider sends its groups in decides precedence. Placement is where the values an identity carries put it. A value is a path: its first part names a tenant, and a second part, when there is one, names the role held there. The name is the mapping, so a deployment whose groups are named after its tenants registers nothing. A value pointed at a tenant explicitly goes there instead, whatever its name would have said.

func (*Store) Plan

func (s *Store) Plan(ctx context.Context, batch int) (int, error)

Plan turns what arrived into deliveries, for every tenant.

One tenant at a time, because the process that plans works for all of them while row level security answers one at a time: a single sweep that names no tenant is answered for one of them and finds nothing for the rest, quietly. The batch is a budget spread across tenants rather than granted to each, so the work one round does stays bounded however many there are.

func (*Store) PointValueAt

func (s *Store) PointValueAt(
	ctx context.Context, method, value string, place console.Placement,
) error

PointValueAt is the exception to the convention: a value that names no tenant of ours is said to mean one. Pointing it again moves it, and a role left empty leaves whoever arrives at the least.

func (*Store) PointedHere

func (s *Store) PointedHere(ctx context.Context) ([]console.Mapping, error)

PointedHere is what this tenant claimed for itself, which is what its panel shows and edits.

func (*Store) ProviderChanges

func (s *Store) ProviderChanges(ctx context.Context) <-chan struct{}

func (*Store) ProviderSettings

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

func (*Store) Providers

func (s *Store) Providers(ctx context.Context) ([]string, error)

func (*Store) Purge

func (s *Store) Purge(ctx context.Context) (int64, error)

Purge discards what every tenant has said it no longer needs, and returns how much went. A tenant with no retention set keeps everything, so this does nothing at all until somebody asks for it.

It runs one tenant at a time, like everything that crosses them, so it discards the same rows whether or not the role it connects as is confined by row level security.

func (*Store) Purgeable

func (s *Store) Purgeable(ctx context.Context) (int64, error)

Purgeable is what Purge would discard, for saying so before doing it.

func (*Store) RawRequest

func (s *Store) RawRequest(ctx context.Context, eventID uuid.UUID) (db.InboundRequest, error)

func (*Store) Recheck

func (s *Store) Recheck(
	ctx context.Context, name string, batch int32,
) (recovered int, err error)

Recheck answers, for the requests of a provider that have no answer yet or were refused, the question the settings in force can now answer, and reopens planning for the ones that pass.

A request recorded before any verification existed is unchecked, which is not a verdict but the absence of one: nothing was configured, so nothing was asked. Configuring it later is what makes the question askable, which is why unchecked is reconsidered and not left as though it had been decided.

func (*Store) Reconsider

func (s *Store) Reconsider(ctx context.Context, batch int32) (int, error)

Reconsider does that for every provider of every tenant that has settings, which is what a change to any of them calls for: whoever configured one just answered a question that was open for everything already recorded under it.

Bounded per provider, because a deployment that configures verification a year in is asking about a year of requests, and the ones still waiting to be delivered are the ones the answer changes anything for.

func (*Store) Record

func (s *Store) Record(ctx context.Context, req inbound.Request) (uuid.UUID, error)

Returns the identifier the database gave the event, and only after the transaction has committed. Everything the caller tells the provider afterwards depends on that.

func (*Store) RecordAttempt

func (s *Store) RecordAttempt(
	ctx context.Context, tenant, deliveryID uuid.UUID, attempt, status int,
	signedWith []string, answer outbound.Answer, reason string, took time.Duration,
) error

func (*Store) RecordReading

func (s *Store) RecordReading(ctx context.Context, ref AReference, err error) error

RecordReading writes what the process that delivers found when it tried to read a secret, which is the only honest source for what the panel shows.

func (*Store) Register

func (s *Store) Register(ctx context.Context, known Kinds) error

func (*Store) RemoveSigningSecret

func (s *Store) RemoveSigningSecret(ctx context.Context, destination, reference string) error

func (*Store) ReplayDelivery

func (s *Store) ReplayDelivery(ctx context.Context, id uuid.UUID) (int64, error)

Replay resets a delivery to pending and announces the work. Attempt history survives in delivery_attempt, so an operator can still see what was tried.

func (*Store) ReplayDestination

func (s *Store) ReplayDestination(ctx context.Context, routeID uuid.UUID) (int64, error)

Replays everything already sent to one destination. Changing where a route points does not resend what was delivered to the old address; this is how an operator asks for that on purpose.

func (*Store) ReplayEvent

func (s *Store) ReplayEvent(ctx context.Context, eventID uuid.UUID) (int64, error)

Replays every delivery of an event, and unplans the event so a route added since is picked up as well.

func (*Store) Retentions

func (s *Store) Retentions(ctx context.Context) ([]Retention, error)

func (*Store) Role

func (s *Store) Role(ctx context.Context, name string) (authz.Role, error)

Role is one role with everything it grants, which is what deciding a request needs.

func (*Store) RoleIn

func (s *Store) RoleIn(ctx context.Context, user, tenant uuid.UUID) (string, bool, error)

RoleIn is the role somebody holds in one tenant. Belonging without a role stated is belonging as the least, so an empty name means exactly that.

func (*Store) Roles

func (s *Store) Roles(ctx context.Context) ([]authz.Role, error)

func (*Store) Routes

func (s *Store) Routes(ctx context.Context) ([]outbound.Route, error)

func (*Store) SaveRoute

func (s *Store) SaveRoute(ctx context.Context, routeID uuid.UUID, url string, enabled bool) error

func (*Store) SearchEvents

func (s *Store) SearchEvents(ctx context.Context, filter console.Filter) ([]console.EventSummary, error)

func (*Store) SendTest

func (s *Store) SendTest(ctx context.Context, routeID uuid.UUID) (uuid.UUID, error)

SendTest puts a synthetic event through the same path a real one takes, to one destination only.

It is not delivered from here: the process that serves the panel holds no signing secrets, so anything it sent would be unsigned and would prove the opposite of what was asked. Recording it and letting the dispatcher deliver it is what makes the test the real thing, signature and all.

func (*Store) SessionUser

func (s *Store) SessionUser(ctx context.Context, digest []byte) (console.User, error)

func (*Store) SetOperatorRole

func (s *Store) SetOperatorRole(ctx context.Context, id uuid.UUID, role string) error

func (*Store) SetProvider

func (s *Store) SetProvider(ctx context.Context, settings ProviderSettings) error

func (*Store) SetRetention

func (s *Store) SetRetention(ctx context.Context, slug string, days int) error

SetRetention says how long a tenant's events are kept. Days of zero puts it back to keeping them for ever.

func (*Store) SetRole

func (s *Store) SetRole(ctx context.Context, role authz.Role) error

SetRole writes a role and exactly the permissions given, so configuring one is one statement rather than a diff the caller has to work out.

func (*Store) SetSystemAdmin

func (s *Store) SetSystemAdmin(ctx context.Context, id uuid.UUID) error

SetSystemAdmin takes the account out of its tenant, because the standing is exactly not belonging to one.

func (*Store) SetSystemAdminByEmail

func (s *Store) SetSystemAdminByEmail(ctx context.Context, email string) error

func (*Store) Settle

func (s *Store) Settle(ctx context.Context, user uuid.UUID, named []console.Placement) error

Settle makes somebody belong to exactly what the identity provider named, and to nothing else. A value that names only a tenant leaves the role to whoever decides it here; one that names the role too makes the token the truth about that as well.

func (*Store) SignatureTotals

func (s *Store) SignatureTotals(ctx context.Context) (map[string]int64, error)

func (*Store) SigningChanges

func (s *Store) SigningChanges(ctx context.Context) <-chan struct{}

SigningChanges reports that a destination gained or lost a signing secret.

func (*Store) SigningFor

func (s *Store) SigningFor(ctx context.Context, destination uuid.UUID) ([]console.SigningSecret, error)

SigningFor is what a destination signs with, and what the process that delivers last found when it tried to read each one.

func (*Store) SigningSecrets

func (s *Store) SigningSecrets(ctx context.Context) ([]SigningSecret, error)

func (*Store) Snapshot

func (s *Store) Snapshot(ctx context.Context) (metrics.Snapshot, error)

Snapshot reads every number a scrape reports, one tenant at a time, so it reports the same whether or not the role it connects as is confined by row level security.

func (*Store) StopPointingValue

func (s *Store) StopPointingValue(ctx context.Context, method, value string) error

func (*Store) SystemAdmins

func (s *Store) SystemAdmins(ctx context.Context) ([]console.Operator, error)

SetSystemAdmin makes an account one that is not confined to a tenant, or takes that away. Who may call this is decided above: only somebody who already is one. SystemAdmins are the accounts that belong to no tenant, which is why they are listed apart from any tenant's operators.

func (*Store) Tenant

func (s *Store) Tenant(ctx context.Context, slug string) (uuid.UUID, bool, error)

Tenant resolves a slug to its id, holding the mapping to keep an address lookup off every inbound request.

What is held is only correct until somebody creates or removes a tenant, which is usually another process: the command line and the panel do not run where webhooks are received. A slug removed and made again is a different tenant wearing the same address, so ForgetTenants is what a change announced over the database is meant to call.

func (*Store) TenantBySlug

func (s *Store) TenantBySlug(ctx context.Context, slug string) (console.Tenant, error)

func (*Store) TenantChanges

func (s *Store) TenantChanges(ctx context.Context) <-chan struct{}

TenantChanges reports that a tenant was created or removed, anywhere.

func (*Store) Tenants

func (s *Store) Tenants(ctx context.Context) ([]console.Tenant, error)

func (*Store) UnroutedProviders

func (s *Store) UnroutedProviders(ctx context.Context) ([]console.UnroutedProvider, error)

func (*Store) Unsigned

func (s *Store) Unsigned(ctx context.Context) ([]console.UnsignedDestination, error)

Unsigned is every destination that is delivered to and signs with nothing.

func (*Store) UserByEmail

func (s *Store) UserByEmail(ctx context.Context, email string) (console.User, error)

func (*Store) UserBySubject

func (s *Store) UserBySubject(
	ctx context.Context, subject, email string, place console.Placement, provision bool,
) (console.User, error)

Finds the operator behind an identity token: by subject when the account was already linked, then by email so an existing local operator keeps one account. Provisioning a brand new operator is only done when the deployment asks for it.

func (*Store) Verification

func (s *Store) Verification(ctx context.Context) (map[string]provider.Settings, error)

Verification reads the settings, resolving each secret from the environment. The database never holds a secret, only the name of the variable that does.

func (*Store) Verifications

func (s *Store) Verifications(ctx context.Context) ([]console.Verification, error)

Verifications is what the panel shows: the settings plus how many requests each provider has refused, which is the number that matters when a secret is wrong.

func (*Store) VerifyPassword

func (s *Store) VerifyPassword(ctx context.Context, email, password string) (string, error)

VerifyPassword is the credentials port the local sign-in needs. It reports the stored address so that a case difference in what was typed does not end up on the session.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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