oidc

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0, MIT Imports: 31 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.

README

Signing in (oidc)

Package oidc signs people in through an organization's OpenID Connect provider. It serves the routes to sign in and out, keeps each session in an encrypted cookie, and tells the server whose each request is (it is a server.Authenticator). A person is the one in the organization's data with the mail address the provider has verified. The package depends on the standard library and the package server alone. Japanese: README.ja.md.

To Read
sign people in to a server that ritsu ringi init made Connect the sign-in. It uses this package through the -oidc-… flags, and you write no Go
sign people in to a server you put together in Go what to register at the provider, then Use, below
test a server that signs people in A provider for tests, below
know how it works, and why the design

Use

keys, err := oidc.ParseKeys(os.Getenv("RINGI_SESSION_KEYS"))
var srv *server.Server
people := oidc.ByEmail(func(ctx context.Context) ([]server.OrgPerson, error) {
	return oidc.PeopleOf(ctx, srv) // the people of the organization's data in effect today
})
signin, err := oidc.New(ctx, oidc.Config{
	Issuer:       os.Getenv("RINGI_OIDC_ISSUER"),
	ClientID:     os.Getenv("RINGI_OIDC_CLIENT_ID"),
	ClientSecret: os.Getenv("RINGI_OIDC_CLIENT_SECRET"),
	RedirectURL:  "https://requests.example.test/login/callback",
	Keys:         keys,
	Map:          oidc.Roles(people, "roles"), // the roles the claim "roles" lists, for the gate
	Revocations:  store,                       // the PostgreSQL store: a sign-out holds in every process
})
srv, err = server.New(server.Config{…, Store: store, Authenticator: signin})
h, err := web.New(srv, web.Config{
	Require:  signin.Require,  // a page opened with no session goes to sign in, and comes back
	LoginURL: signin.LoginURL, // the link of the page that says no one is signed in
	SignOut:  "/logout",       // the button at the top of each page
})
signin.Mount(h) // GET /login, GET /login/callback, POST /logout, behind the handler's guards
  • New reads the provider's discovery document and its keys. A wrong issuer, or a provider that cannot be reached, stops the server when it starts, and not at someone's first sign-in.
  • Write the issuer exactly as the discovery document (<issuer>/.well-known/openid-configuration) has it. With one / more or less at its end it is another issuer, and New refuses it.
  • A person's roles are those in the ID token of their last sign-in. A claim that is not in it gives no role. The package reads the ID token only, not the userinfo endpoint.
  • Without Revocations, signing out takes the cookie from the browser, and a copy of the cookie works until the session's limit.
  • For a server without package web, Mount takes an *http.ServeMux (the design, section 10).
  • The API answers a request with no session 401.

The other settings, with their defaults, are the fields of oidc.Config: how long a session lasts, the scopes, the paths, how the client proves itself. ProviderLogout signs a person out of the provider too, and PostLogoutRedirectURL is where the provider then sends them, which is registered there.

The keys of the cookies

A key is 32 random bytes, in base64:

head -c 32 /dev/urandom | base64

oidc.ParseKeys reads one key, or several with commas between them. The first encrypts, and every one of them decrypts. To change the key, put the new one first and keep the old one after it. Take the old one out once the longest session has passed, which is 12 hours when SessionLimit is not set.

New refuses a key that is not random, such as a passphrase in base64 or 32 zero bytes. Anyone who guesses the key can make a session of anyone.

A provider for tests

oidc/oidctest is an OpenID Connect provider for tests. It serves over https on a local address, and signs in at once the person a test says. It checks the client, the redirect URL, PKCE, and that a code is used once, as a provider does.

p := oidctest.New(t, clock)
p.SignInAs(map[string]any{"sub": "u-1201", "email": "e1201@example.com", "email_verified": true})
signin, err := oidc.New(ctx, p.Config("https://"+app.Listener.Addr().String()+"/login/callback", keys, m))

examples/signin_test.go signs in with it, and makes a request on the pages.

The tests of the package

go test ./oidc/...
ok  	github.com/i2y/ringi-server/oidc	0.841s
?   	github.com/i2y/ringi-server/oidc/oidctest	[no test files]

They run a provider of their own over TLS (httptest), and send nothing anywhere else. With RINGI_TEST_DATABASE, the ended sessions are kept in PostgreSQL too, by two stores on the same tables. The design, section 12, lists what they run.

Documentation

Overview

Package oidc signs people in through the organization's OpenID Connect provider. It keeps who they are in a session, and tells the framework who sends each request: it has an Authenticator of the framework (server.Authenticator), the routes of signing in and out, and a wrapper for the pages that need a person.

Package serve uses it. https://i2y.github.io/ringi-server/sign-in/ says how to connect a provider, and DESIGN.md how it works.

Index

Constants

View Source
const (
	DefaultSkew         = time.Minute
	DefaultSessionLimit = 12 * time.Hour
	DefaultIdleLimit    = 2 * time.Hour
)

The defaults of Config.

View Source
const (
	SessionCookie = "__Host-ringi-session"
	SignInCookie  = "__Host-ringi-signin-"
)

The names of the cookies: the session, and a sign-in under way (followed by the first 16 characters of its state).

Variables

View Source
var (
	ErrNoVerifiedEmail = &Refusal{Reason: "no_verified_email", Words: map[string]string{
		"en": "Your organization's account has no confirmed email address, so this server cannot tell who you are. Ask the people who manage the accounts.",
		"ja": "組織のアカウントに確認済みのメールアドレスが無いため、このサーバーではあなたが誰かを確かめられません。アカウントの管理者に相談してください。",
	}}
	ErrNotInOrganization = &Refusal{Reason: "not_in_organization", Words: map[string]string{
		"en": "No one in the organization's data has your email address, so you cannot use this server yet. Ask the people who keep the organization's data to add you.",
		"ja": "組織のデータに、あなたのメールアドレスの人がいません。そのため、まだこのサーバーを使えません。組織のデータを管理している人に、登録を頼んでください。",
	}}
	ErrAmbiguousEmail = &Refusal{Reason: "ambiguous_email", Words: map[string]string{
		"en": "More than one person in the organization's data has your email address, so this server cannot tell which one you are. Ask the people who keep the organization's data to correct it.",
		"ja": "組織のデータに、あなたのメールアドレスの人が二人以上います。そのため、どの人かを決められません。組織のデータを管理している人に、直すよう頼んでください。",
	}}
)

The refusals of ByEmail.

Functions

func ParseKeys

func ParseKeys(text string) ([][]byte, error)

ParseKeys reads the keys of the cookies from text: base64 (standard or URL, with or without padding) of 32 bytes each, apart with commas or spaces, the newest first.

func PeopleOf

func PeopleOf(ctx context.Context, srv *server.Server) ([]server.OrgPerson, error)

PeopleOf answers the people of the version of the organization the server has in effect today, with their addresses (Server.People).

Types

type Claims

type Claims struct {
	Issuer  string
	Subject string
	// Email is the token's email, and EmailVerified whether the token says the provider verified
	// it (the JSON boolean true).
	Email         string
	EmailVerified bool
	Name          string
	// All are every claim of the token, as it writes them.
	All map[string]json.RawMessage
}

Claims are the claims of an ID token that passed every check.

func (Claims) Strings

func (c Claims) Strings(name string) []string

Strings answers a claim that is a text or a list of texts (groups, roles); nil when the token has no such claim, or it is something else.

type Config

type Config struct {
	// Issuer is the provider's issuer URL, exactly as its discovery document writes it.
	Issuer string
	// ClientID and ClientSecret are the client's, as the provider registered it.
	ClientID     string
	ClientSecret string
	// ClientAuth is how the client proves itself at the token endpoint: "client_secret_basic"
	// (when "") or "client_secret_post".
	ClientAuth string
	// RedirectURL is the callback's URL, as registered at the provider. The callback is served at
	// its path.
	RedirectURL string
	// Scopes are the scopes asked for: "openid email profile" when nil ("openid" is added when
	// missing).
	Scopes []string
	// Params are more parameters of the authorization request (prompt, login_hint…).
	Params url.Values
	// Algorithms are the algorithms an ID token may be signed with: RS256, PS256 and ES256 when
	// nil.
	Algorithms []string
	// Audiences are the audiences an ID token may name besides the client ID.
	Audiences []string
	// Skew is how far the provider's clock may be from the server's: 1 minute when 0, none when
	// negative.
	Skew time.Duration
	// Keys are the keys of the cookies, 32 random bytes each: the first seals, every one opens. New
	// refuses a key that is text or repeats its bytes, and a key given twice.
	Keys [][]byte
	// SessionLimit is the longest a session lasts from the sign-in: 12 hours when 0.
	SessionLimit time.Duration
	// IdleLimit is the longest a session lasts unused: 2 hours when 0, none when negative.
	IdleLimit time.Duration
	// Revocations, when given, keeps the sessions ended before their limits.
	Revocations Revocations
	// Map makes the framework's person from the claims of an ID token that passed every check.
	Map Map
	// LoginPath and LogoutPath are the paths of signing in and out: /login and /logout when "".
	LoginPath, LogoutPath string
	// AfterLogout is where signing out sends a browser: / when "".
	AfterLogout string
	// ProviderLogout sends a person who signs out on to the provider's end_session_endpoint;
	// PostLogoutRedirectURL is where the provider sends them back (registered there; none when "").
	ProviderLogout        bool
	PostLogoutRedirectURL string
	// HTTPClient makes the calls to the provider: a client with a 10-second timeout when nil.
	HTTPClient *http.Client
	// Clock tells the time: the system's when nil.
	Clock server.Clock
	// Logger is slog.Default() when nil.
	Logger *slog.Logger
}

Config is what New is made with (DESIGN.md, section 9).

func (Config) Check

func (c Config) Check() error

Check reports what New would refuse in the configuration, without reaching the provider, so that a server can say what is wrong before it reaches anything (New checks it again).

type Map

type Map func(ctx context.Context, c Claims) (server.Person, error)

Map makes the framework's person from the claims of an ID token that passed every check. A *Refusal keeps the person from signing in, with the words they are shown; any other error is a failure (500).

func ByEmail

func ByEmail(people People) Map

ByEmail answers a Map that finds the person whose address in the organization's data is the token's email, when the provider verified it. Addresses are compared without regard to case, after trimming spaces.

func Roles

func Roles(m Map, claim string) Map

Roles answers a Map that makes the person m makes, with the roles the claim lists (a text or a list of texts) added.

type MemoryRevocations

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

MemoryRevocations keeps the ended sessions in memory: for a server of one process, and for tests.

func NewMemoryRevocations

func NewMemoryRevocations() *MemoryRevocations

NewMemoryRevocations makes an empty MemoryRevocations.

func (*MemoryRevocations) Revoke

func (m *MemoryRevocations) Revoke(_ context.Context, session string, until time.Time) error

Revoke records the session, and drops the records whose sessions would have ended by now.

func (*MemoryRevocations) Revoked

func (m *MemoryRevocations) Revoked(_ context.Context, session string) (bool, error)

Revoked reports whether the session was recorded.

type Mux

type Mux interface {
	Handle(pattern string, handler http.Handler)
}

Mux is what Mount adds the routes to: an *http.ServeMux, or the screens' handler (web.Handler), which puts them behind its guards.

type People

type People func(ctx context.Context) ([]server.OrgPerson, error)

People answers the people of the version of the organization in effect today.

type Refusal

type Refusal struct {
	Reason string
	// Words are the words shown, by language: "en", and "ja" when there are Japanese ones.
	Words map[string]string
}

Refusal is what a Map answers to keep a person from signing in: the person is shown Words in their language (English when there are none of theirs), with 403, and Reason is logged.

func (*Refusal) Error

func (r *Refusal) Error() string

type Revocations

type Revocations interface {
	// Revoke records that the session has ended; until is when it would have ended anyway, after
	// which the record may be dropped.
	Revoke(ctx context.Context, session string, until time.Time) error
	// Revoked reports whether the session was recorded as ended.
	Revoked(ctx context.Context, session string) (bool, error)
}

Revocations keeps the sessions ended before their limits (DESIGN.md, 6.4).

type SignIn

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

SignIn signs people in through one provider and finds them in their sessions. It is safe for use by many goroutines at once.

func New

func New(ctx context.Context, cfg Config) (*SignIn, error)

New makes a SignIn: it checks the configuration, then reads the provider's discovery document and its keys.

func (*SignIn) Authenticate

func (s *SignIn) Authenticate(r *http.Request) (server.Person, error)

Authenticate answers the person of the request's session: server.ErrNoPerson when there is none, it does not open, or it has ended. It is the framework's Authenticator.

func (*SignIn) LoginURL

func (s *SignIn) LoginURL(returnTo string) string

LoginURL answers the address of signing in that comes back to returnTo, a path of this server (/ when it is not one).

func (*SignIn) Mount

func (s *SignIn) Mount(mux Mux)

Mount adds the routes of signing in and out: GET Config.LoginPath, GET the redirect URL's path (the callback), and POST Config.LogoutPath.

func (*SignIn) Require

func (s *SignIn) Require(h http.Handler) http.Handler

Require serves h to a person. With no session, a page a browser opens is sent to sign in and come back; a form a browser sends is answered 401 with a page; any other request is answered 401 as the API answers it. It renews the session it finds (DESIGN.md, 6.3).

Directories

Path Synopsis
Package oidctest is an OpenID Connect provider for the tests of a server that signs people in with package oidc: its discovery document, a JWK Set, an authorization endpoint that signs in at once the person a test chooses, and a token endpoint that checks the client, the redirect URL, PKCE and that a code is used once, and signs ID tokens with an RSA key (RS256).
Package oidctest is an OpenID Connect provider for the tests of a server that signs people in with package oidc: its discovery document, a JWK Set, an authorization endpoint that signs in at once the person a test chooses, and a token endpoint that checks the client, the redirect URL, PKCE and that a code is used once, and signs ID tokens with an RSA key (RS256).

Jump to

Keyboard shortcuts

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