appidentity

package
v1.171.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 32 Imported by: 0 modules, 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 appidentity is an application environment's own identity provider (#2878): an OpenID Connect provider the application names, which the platform signs people in through on the application's own addresses and hands to the application's handlers. The people it signs in never become platform users: nothing here writes the known-users directory, resolves a persona or issues a platform credential.

What it keeps, and where each secret goes:

  • the client secret is a stored secret named by reference, read only at the token exchange through the reserved use SecretUse;
  • a sign-in begun is a row holding the state's digest, the nonce and the PKCE verifier, used once and expired after minutes, bound to the host and to a cookie set in the browser that began it;
  • a session is a row holding the digest of its cookie's value and the claims the environment maps; no token is ever stored, logged or handed to a handler.

Index

Constants

View Source
const (
	PathStart    = "/_auth/app/start"
	PathCallback = "/_auth/app/callback"
	PathSignOut  = "/_auth/app/signout"
)

The paths a sign-in answers on every address of an application.

View Source
const (
	StatusSaved            = "saved"
	StatusAwaitingApproval = "awaiting_approval"
)

The statuses a set answers with.

View Source
const (
	DefaultSessionSeconds = 8 * 60 * 60
	DefaultIdleSeconds    = 60 * 60
)

Defaults an environment that sets none takes.

View Source
const SecretUse = "application_identity"

SecretUse is the reserved name a stored secret's allow_connections must list for an application environment to use it as its client secret.

Variables

View Source
var (
	ErrNotFound  = errors.New("appidentity: the environment names no identity provider")
	ErrNoSession = errors.New("appidentity: nobody is signed in")
)

Errors read by identity.

View Source
var DefaultScopes = []string{"openid", "email", "profile"}

DefaultScopes are the scopes asked for when an environment names none.

View Source
var ErrNotAllowed = errors.New("appidentity: only the application's owner or an administrator sets its identity provider")

ErrNotAllowed is an actor who does not edit the application.

Functions

func Handles

func Handles(path string) bool

Handles reports whether path is one of the sign-in's own paths.

func LocalPath

func LocalPath(v string) bool

LocalPath reports whether v is a path on the host it is followed on: it starts with one slash and names no other host.

func SameOrigin

func SameOrigin(r *http.Request) bool

SameOrigin reports whether the browser says the request came from the address it is sent to.

func SecretName

func SecretName(v string) string

SecretName is the stored secret a client_secret value names: a {{secret:<name>}} placeholder or the bare name.

func StartURL

func StartURL(returnTo string) string

StartURL is where a browser with no session is sent to sign in, coming back to returnTo.

func ViewerJSON

func ViewerJSON(p *Person) map[string]any

ViewerJSON is what /_viewer answers for a person an application's provider signed in: never a token.

Types

type Applications

type Applications interface {
	Find(ctx context.Context, ref string) (*application.Application, error)
}

Applications finds an application by name or id.

type Approvals

type Approvals interface {
	ApplicationIdentityApproved(ctx context.Context, appID, env, stamp string) bool
	SubmitApplicationIdentity(ctx context.Context, actor approval.Actor, in approval.SubmitApplicationIdentity) (*approval.Request, error)
}

Approvals is the queue a provider on an environment people use waits on.

type EndpointIdentity

type EndpointIdentity struct {
	Service *Service
	// AppName names an application by id for the caller's id; nil uses the id.
	AppName func(ctx context.Context, id string) string
}

EndpointIdentity answers ephttp.AppIdentity: the person an application endpoint runs as, from the environment's session or a bearer token.

func (EndpointIdentity) Caller

func (e EndpointIdentity) Caller(r *http.Request, appID, env string, audiences []string) (*eprun.Caller, error)

Caller is who r is signed in as through appID's environment env: a bearer token first, then the session cookie. A request that changes something on the session must come from the address it is sent to: every site under the pages domain is one site to a browser, so SameSite alone would let a sibling's page act as this one's person.

func (EndpointIdentity) SignInURL

func (EndpointIdentity) SignInURL(path string) string

SignInURL is where a browser with no session is sent.

type Manager

type Manager struct {
	Apps      Applications
	Service   *Service
	Approvals Approvals
	// PersonaOf is the persona roles resolve to, which a stored secret's
	// allow_personas is checked against; nil is none.
	PersonaOf func(roles []string) string
}

Manager sets, removes and reads application environments' providers and their sessions, for someone who edits the application.

func (*Manager) EndSession

func (m *Manager) EndSession(ctx context.Context, actor application.Actor, ref, env, id string) (int, error)

EndSession ends one session of env by its id; "" ends every one. It reports how many ended; each takes effect on its next request.

func (*Manager) Providers

func (m *Manager) Providers(ctx context.Context, actor application.Actor, ref string) ([]Provider, error)

Providers lists an application's providers.

func (*Manager) Remove

func (m *Manager) Remove(ctx context.Context, actor application.Actor, ref, env string) error

Remove removes env's provider and ends its sessions. Removing reduces who gets in, so it waits on no one.

func (*Manager) SessionCounts

func (m *Manager) SessionCounts(ctx context.Context, actor application.Actor, ref string) (map[string]int, error)

SessionCounts is how many live sessions each environment of an application has, for the environments list.

func (*Manager) Sessions

func (m *Manager) Sessions(ctx context.Context, actor application.Actor, ref, env string) ([]Session, error)

Sessions lists env's live sessions.

func (*Manager) Set

func (m *Manager) Set(ctx context.Context, actor application.Actor, ref string, p Provider, reason string) (*SetResult, error)

Set names or changes env's provider. It checks that the provider answers and that the actor may use the stored secret; a change of who signs people in (issuer, client, secret, scopes) on an environment that requires approval, or by an agent outside dev, waits on Approvals until a person decides it.

type Person

type Person struct {
	Issuer        string
	Subject       string
	Email         string
	EmailVerified bool
	Name          string
	Claims        map[string]any
}

Person is who a session or a bearer token names, as the environment maps the provider's claims.

type PostgresStore

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

PostgresStore is the Store over the platform's database.

func NewPostgresStore

func NewPostgresStore(db *sql.DB) *PostgresStore

NewPostgresStore returns the store over db.

func (*PostgresStore) DeleteProvider

func (s *PostgresStore) DeleteProvider(ctx context.Context, appID, env string) error

DeleteProvider removes an environment's provider and ends its sessions.

func (*PostgresStore) EndSession

func (s *PostgresStore) EndSession(ctx context.Context, appID, env, id string, now time.Time) (bool, error)

EndSession ends one of an environment's sessions by its public id.

func (*PostgresStore) EndSessions

func (s *PostgresStore) EndSessions(ctx context.Context, appID, env string, now time.Time) (int, error)

EndSessions ends every live session of an environment.

func (*PostgresStore) Provider

func (s *PostgresStore) Provider(ctx context.Context, appID, env string) (*Provider, error)

Provider reads one environment's provider, ErrNotFound for none.

func (*PostgresStore) Providers

func (s *PostgresStore) Providers(ctx context.Context, appID string) ([]Provider, error)

Providers lists an application's providers, one per environment naming one.

func (*PostgresStore) PutProvider

func (s *PostgresStore) PutProvider(ctx context.Context, p *Provider) error

PutProvider stores an environment's provider, replacing the one it had.

func (*PostgresStore) Sessions

func (s *PostgresStore) Sessions(ctx context.Context, appID, env string, now time.Time) ([]Session, error)

Sessions lists an environment's live sessions, newest first.

type Provider

type Provider struct {
	ApplicationID string `json:"-"`
	Environment   string `json:"environment" example:"prod"`
	Issuer        string `json:"issuer" example:"https://auth.example.com/realms/staff"`
	ClientID      string `json:"client_id" example:"partner-portal"`
	// ClientSecret is the name of the stored secret holding the client
	// secret, never its value.
	ClientSecret string   `json:"client_secret" example:"partner-portal-oidc"`
	Scopes       []string `json:"scopes" example:"openid,email,profile"`
	// The claim each value is read from; Roles is a dotted path, "" for none.
	ClaimSubject string `json:"claim_subject" example:"sub"`
	ClaimEmail   string `json:"claim_email" example:"email"`
	ClaimName    string `json:"claim_name" example:"name"`
	ClaimRoles   string `json:"claim_roles,omitempty" example:"realm_access.roles"`
	// RequireVerifiedEmail refuses a person whose provider has not verified
	// their email.
	RequireVerifiedEmail bool `json:"require_verified_email"`
	// SessionSeconds is how long a sign-in lasts and IdleSeconds how long it
	// lasts with no request.
	SessionSeconds int `json:"session_seconds" example:"28800"`
	IdleSeconds    int `json:"idle_seconds" example:"3600"`
	// SignedOutRedirect is the path a person is sent to after signing out,
	// "" for the platform's signed-out page.
	SignedOutRedirect string    `json:"signed_out_redirect,omitempty" example:"/"`
	UpdatedBy         string    `json:"updated_by,omitempty"`
	UpdatedAt         time.Time `json:"updated_at"`
}

Provider is one application environment's identity provider.

func (*Provider) Normalize

func (p *Provider) Normalize()

Normalize fills the defaults and trims what a paste brings.

func (*Provider) Stamp

func (p *Provider) Stamp() string

Stamp is what an approval of the provider holds for: who signs people in and as which client. A change of either is approved again; the session lifetimes are not part of it.

func (*Provider) Validate

func (p *Provider) Validate() error

Validate refuses a provider that cannot sign anyone in or that would send a person somewhere other than the application's own address. It checks the shape only; whether the issuer answers and the secret may be used is the service's.

type RefusedError

type RefusedError struct{ Msg string }

RefusedError is a setting refused for a reason the caller can act on.

func (*RefusedError) Error

func (e *RefusedError) Error() string

type Secrets

type Secrets interface {
	UseValue(ctx context.Context, name, use, persona string, admin bool) (string, error)
}

Secrets reads a stored secret for a reserved use (secretstore.UseValue).

type Service

type Service struct {
	Store   Store
	Secrets Secrets
	// Client reaches providers through the egress guard, which admits a
	// private address only when an operator listed its range.
	Client *http.Client
	// Secure says the application addresses answer over https: cookies are
	// then __Host- and Secure.
	Secure bool
	// Port is the port the application addresses answer on, "" for the
	// scheme's own; the callback address the provider is sent carries it.
	Port string
	Now  func() time.Time
	// contains filtered or unexported fields
}

Service runs sign-in, sessions and bearer tokens for every application environment that names a provider.

func New

func New(store Store, secrets Secrets, client *http.Client, secure bool) *Service

New returns the service.

func (*Service) Bearer

func (s *Service) Bearer(r *http.Request, appID, env string, audiences []string) (*Person, error)

Bearer is who a bearer access token on r names, for an endpoint admitting audiences: signed by the environment's provider, issued by it, for one of audiences and unexpired. ErrNoSession when r carries no bearer token; a refused token's error says why and never repeats it.

func (*Service) Serve

func (s *Service) Serve(w http.ResponseWriter, r *http.Request, t Target)

Serve answers one of the sign-in's paths for t.

func (*Service) Session

func (s *Service) Session(r *http.Request, appID, env string) (*Person, error)

Session is who is signed in on r for the application environment, ErrNoSession for nobody. A session of another environment, ended, expired or idle past its bound is nobody.

type Session

type Session struct {
	// ID is the session's public id, shown in the portal and used to end it;
	// it opens nothing.
	ID            string         `json:"id" example:"as_3f9c0d2a7b1e"`
	ApplicationID string         `json:"-"`
	Environment   string         `json:"environment" example:"prod"`
	Issuer        string         `json:"issuer"`
	Subject       string         `json:"subject"`
	Email         string         `json:"email"`
	EmailVerified bool           `json:"email_verified"`
	Name          string         `json:"name"`
	Claims        map[string]any `json:"claims"`
	CreatedAt     time.Time      `json:"created_at"`
	LastSeenAt    time.Time      `json:"last_seen_at"`
	ExpiresAt     time.Time      `json:"expires_at"`
	IdleSeconds   int            `json:"idle_seconds"`
}

Session is a person signed in through an application environment's provider. It holds the claims the environment maps and never a token.

func (*Session) EndsAt

func (s *Session) EndsAt() time.Time

EndsAt is the earlier of its expiry and its idle end.

func (*Session) IdleEndsAt

func (s *Session) IdleEndsAt() time.Time

IdleEndsAt is when the session ends with no further request.

type SetResult

type SetResult struct {
	Provider *Provider         `json:"provider"`
	Status   string            `json:"status" example:"saved"`
	Approval *approval.Request `json:"approval,omitempty"`
}

SetResult is what a set did: stored, or waiting on Approvals.

type Store

type Store interface {
	Provider(ctx context.Context, appID, env string) (*Provider, error)
	Providers(ctx context.Context, appID string) ([]Provider, error)
	PutProvider(ctx context.Context, p *Provider) error
	DeleteProvider(ctx context.Context, appID, env string) error

	Sessions(ctx context.Context, appID, env string, now time.Time) ([]Session, error)
	EndSession(ctx context.Context, appID, env, id string, now time.Time) (bool, error)
	EndSessions(ctx context.Context, appID, env string, now time.Time) (int, error)
	// contains filtered or unexported methods
}

Store keeps providers, sign-ins begun and sessions.

type Target

type Target struct {
	ApplicationID string
	Application   string
	Environment   string
	Host          string
}

Target is the application environment and address a request is for.

Jump to

Keyboard shortcuts

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