session

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: BSD-3-Clause Imports: 20 Imported by: ? 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 session is turnd's own login: an OpenID Connect login through go-authn/rp in a popup window, and a short-lived bearer token turnd signs itself, which the playground then presents to the credential and rendezvous endpoints.

The token is "t1.<payload>.<mac>" (both base64url): payload is the expiry (8 bytes, big endian Unix seconds), a 16-byte random nonce, then the subject; mac is HMAC-SHA256 over a domain-separation label and the payload, under a server key that never leaves turnd. It is compared in constant time and is refused when expired or altered.

Index

Constants

View Source
const (
	// MinKeyLen is the shortest session key accepted (the HMAC-SHA256 output size).
	MinKeyLen = 32
	// MaxSubjectLen bounds the subject of a token.
	MaxSubjectLen = 128
	// MaxTokenLen bounds a token Verify reads; anything longer is refused unread.
	MaxTokenLen = 512
)

Variables

View Source
var (
	// ErrInvalid is a token that is malformed, signed by no key of ours, or altered.
	ErrInvalid = errors.New("session: invalid token")
	// ErrExpired is a genuine token whose time is over.
	ErrExpired = errors.New("session: token expired")
)
View Source
var ErrEnded = errors.New("session: cannot be renewed, sign in again")

ErrEnded is the one refusal Renewer.Renew gives for a session that cannot be renewed, whatever the cause: the person must sign in again.

View Source
var ErrUnauthorized = errors.New("session: unauthorized")

ErrUnauthorized is the one refusal Subject gives, whatever the cause: a client that sent a bad token is not owed which check caught it.

View Source
var ErrUnavailable = errors.New("session: the identity provider did not answer, retry")

ErrUnavailable is a renewal that could not be tried or finished because the identity provider did not answer. The session is intact: retry.

Functions

func Bearer

func Bearer(r *http.Request) (string, bool)

Bearer extracts the token of an Authorization: Bearer header.

func Subject

func Subject(issuer, sub string) string

Subject is the opaque, stable identifier turnd uses for a person: a hash of issuer and "sub", never a name. It ends up in TURN usernames, which an eavesdropper sees (draft-uberti-behave-turn-rest-00 §6).

func ValidSubject

func ValidSubject(s string) bool

ValidSubject says whether s can be a token's subject: non-empty, UTF-8, at most MaxSubjectLen bytes, no control or space characters.

Types

type Auth

type Auth struct {
	Signer *Signer
	// AccessTokens, when non-nil, accepts issuer access tokens. Build it with
	// oidc.Config{Type: "at+jwt"} so an ID token is never taken for one.
	AccessTokens *oidc.Verifier
	Now          func() time.Time
	// Logf receives the real reason for a refusal (never sent to the client).
	Logf func(ctx context.Context, format string, args ...any)
	// Observe receives the reason of every refusal as one fixed word:
	// "session_token" or "access_token" (a token that failed verification),
	// "no_access_verifier" (an issuer token with no verifier configured),
	// "no_subject". Nil observes nothing.
	Observe func(ctx context.Context, reason string)
}

Auth authenticates an API request from its Authorization: Bearer header: a turnd session token, or (when AccessTokens is set) an access token of the configured issuer, verified by go-authn/oidc.

func (*Auth) Authenticate

func (a *Auth) Authenticate(ctx context.Context, tok string) (string, error)

Authenticate returns the opaque subject of a token: a turnd session token or an issuer access token. It is what a gRPC service calls with the token of its "authorization: Bearer" metadata.

func (*Auth) Subject

func (a *Auth) Subject(r *http.Request) (string, error)

Subject returns the opaque subject of the request's bearer token.

type Claims

type Claims struct {
	Subject string
	Expiry  time.Time
	Nonce   [nonceN]byte
	// Family is the renewal family; the zero value for a token that predates
	// renewal or was issued without one.
	Family Family
}

Claims is what a verified token says.

type Family added in v0.5.0

type Family [familyN]byte

Family names the renewal family of a session: a random identifier under which turnd keeps the identity provider's refresh token server side. It is not a secret of its own (it only means something inside a token turnd signed).

func (Family) IsZero added in v0.5.0

func (f Family) IsZero() bool

IsZero says whether f is the absent family of a token that cannot be renewed.

type Login

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

Login serves /login and /callback.

func NewLogin

func NewLogin(cfg LoginConfig) (*Login, error)

NewLogin validates cfg.

func (*Login) Mount

func (l *Login) Mount(mux *http.ServeMux)

Mount registers GET /login and GET /callback on mux.

type LoginConfig

type LoginConfig struct {
	Client *rp.Client
	Signer *Signer
	// Origins is the allowlist of origins ("https://go-tex.github.io") that may
	// open /login and receive the token by postMessage. Compared exactly; the
	// popup's return target comes from here and nowhere else.
	Origins []string
	// Secure marks the flow cookie Secure (set it when the public URL is https).
	Secure bool
	// FlowTTL is how long a login may take (default 10 minutes); MaxFlows bounds
	// the logins in progress (default 4096).
	FlowTTL  time.Duration
	MaxFlows int
	Now      func() time.Time
	// Renewer, when set, keeps the provider's refresh token of each login
	// server side and issues renewable session tokens. A login that comes back
	// without a refresh token still gets a session, one that cannot be renewed.
	Renewer *Renewer
	// Logf receives one line per callback outcome: the pseudonymous subject
	// on success, the reason on a refusal, never a code, token or cookie.
	// Without it the operator cannot tell a login that worked from one that
	// failed: the popup shows the same "You can close this window" for both
	// when it has no opener. Nil logs nothing.
	Logf func(ctx context.Context, format string, args ...any)
	// Observe receives the outcome of every callback and of every /login
	// start, as one fixed word: "issued", "unknown_flow", "no_cookie",
	// "cookie_mismatch", "provider_error", "issuer_check", "exchange_failed",
	// "issue_failed" (callback); "started", "origin_refused", "too_many_flows",
	// "internal_error" (login). ctx is the request's, so the span in it can be
	// annotated. Nil observes nothing.
	Observe func(ctx context.Context, outcome string)
}

LoginConfig configures NewLogin.

type Refresher added in v0.5.0

type Refresher interface {
	Refresh(ctx context.Context, refreshToken string, f rp.For) (*rp.Token, error)
}

Refresher is the part of go-authn/rp's *rp.Client a renewal needs.

type RenewConfig added in v0.5.0

type RenewConfig struct {
	Refresher Refresher
	Signer    *Signer
	// Lifetime is how long a family lives from the login: the identity
	// provider's refresh lifetime (bridge: the client's refresh_lifetime, fixed
	// at the login, not extended by rotation). Default 168 h.
	Lifetime time.Duration
	// Grace is how long after its expiry a session token can still be renewed
	// (default 5 minutes).
	Grace time.Duration
	// MaxFamilies bounds the store (default 10000). When it is full the family
	// closest to its end is dropped to make room: its person signs in again.
	MaxFamilies int
	Now         func() time.Time
	// Logf receives one line per outcome: the pseudonymous subject, never a
	// token or a family identifier.
	Logf func(format string, args ...any)
}

RenewConfig configures NewRenewer.

type Renewer added in v0.5.0

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

Renewer keeps refresh tokens server side, in memory, keyed by family, and renews session tokens with them. A restart empties it: everybody signs in again.

func NewRenewer added in v0.5.0

func NewRenewer(cfg RenewConfig) (*Renewer, error)

NewRenewer validates cfg.

func (*Renewer) Families added in v0.5.0

func (r *Renewer) Families() int

Families is the number of families held.

func (*Renewer) Open added in v0.5.0

func (r *Renewer) Open(subject, refreshToken string) (Family, error)

Open starts a family for a login that came with a refresh token and returns its identifier, to embed in the session token (Signer.IssueRenewable).

func (*Renewer) Renew added in v0.5.0

func (r *Renewer) Renew(ctx context.Context, token string) (string, time.Time, error)

Renew trades a session token, valid or expired for less than the grace, for a new one. Any refusal from the provider ends the family (ErrEnded); a failure to reach it leaves it (ErrUnavailable).

type Signer

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

Signer issues and verifies tokens. Issue signs with the first key; Verify accepts any of them, so a key can be rotated without logging everybody out.

func NewSigner

func NewSigner(ttl time.Duration, current []byte, previous ...[]byte) (*Signer, error)

NewSigner is a signer with the given lifetime for tokens it issues. A key shorter than MinKeyLen, a non-positive ttl or a duplicate key is refused.

func (*Signer) Issue

func (s *Signer) Issue(subject string, now time.Time) (token string, expiry time.Time, err error)

Issue signs a token for subject, valid for the signer's ttl from now.

func (*Signer) IssueRenewable added in v0.5.0

func (s *Signer) IssueRenewable(subject string, fam Family, now time.Time) (token string, expiry time.Time, err error)

IssueRenewable is Signer.Issue for a session that can be renewed: the token carries fam, which turnd's renewer maps to the stored refresh token.

func (*Signer) TTL

func (s *Signer) TTL() time.Duration

TTL is the lifetime of an issued token.

func (*Signer) Verify

func (s *Signer) Verify(token string, now time.Time) (Claims, error)

Verify checks a token. The signature is checked, against every key and in constant time, before anything in the payload is trusted; then the expiry.

func (*Signer) VerifyGrace added in v0.5.0

func (s *Signer) VerifyGrace(token string, now time.Time, grace time.Duration) (Claims, error)

VerifyGrace is Signer.Verify that also accepts a genuine token expired for less than grace. It is for renewal only: every other endpoint uses Verify.

Jump to

Keyboard shortcuts

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