native

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 30 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.

README

oidc/native

An opt-in broker that lets native public clients (mobile, desktop, CLI) log in through a gosso oidc.RP, following OAuth 2.0 for native apps:

  • RFC 6749 authorization code flow with RFC 7636 PKCE (S256 only)
  • RFC 8252 redirect URIs (custom schemes, claimed HTTPS, loopback)
  • RFC 7009 token revocation

The app never talks to the IdP. It opens the broker's authorize endpoint in a browser tab, the broker runs the RP's normal login, and on the callback redirects back to the app with a one-time code. The app redeems the code with its PKCE verifier for an access token minted by your code and a rotating refresh token. Every refresh also redeems the IdP refresh token kept on the session, so the IdP still decides whether the session lives on.

Stateful, unlike the rest of gosso

The broker owns one-time codes and refresh sessions. Everything about persisting them lives in repository:

Path Contents
repository/interfaces.go repository.Code and repository.Session, the interfaces the broker uses
repository/code.go, session.go BaseCode and BaseSession: MongoDB implementations on keel's persistor
repository/store the entities: Code, Session, Subject, Attributes, EncryptedToken

Refresh secrets and codes are stored hashed; the IdP refresh token is stored encrypted with AES-256-GCM. Tests run against MongoDB in a testcontainer, so they need Docker.

Endpoints

Handler Method Purpose
Handlers().Authorize GET starts a native login, redirects to the IdP
Handlers().Token POST authorization_code and refresh_token grants
Handlers().Revoke POST ends a refresh session (RFC 7009)

Wiring

The RP needs the broker's wrapped hooks and the broker needs the RP, so build the broker first and attach the RP last:

codes, err := repository.NewDefaultCode(persistor)
sessions, err := repository.NewDefaultSession(persistor)

b, err := native.New(codes, sessions, native.Hooks{
	Authenticate: authenticate, // map the subject to your user, return attributes
	Mint:         mint,         // mint the access token the app receives
}, []native.Client{
	{ID: "app-ios", RedirectURIs: []string{"com.example.app:/oauth2redirect"}},
}, encryptionKey) // exactly 32 bytes

rp, err := oidc.New(ctx, issuer, clientID, clientSecret, callbackURL, transitKey,
	b.OnAuthenticated(webOnAuth),
	oidc.WithOnRedirect(b.OnRedirect(webOnRedirect)),
	oidc.WithOnLoginError(b.OnLoginError(nil)),
)

err = b.Attach(rp)

h := b.Handlers()
mux.Handle("/oidc/app/authorize", h.Authorize)
mux.Handle("/oidc/app/token", h.Token)
mux.Handle("/oidc/app/revoke", h.Revoke)

Attach fails unless all three wrappers were taken from the broker. It cannot see whether they reached oidc.New, so make sure they do.

A login that outlives the RP's transit cookie (the user takes longer at the IdP than its lifetime) ends with a plain 400 at the callback, never with a redirect to the app: without the cookie there is no trusted redirect URI. Raise oidc.WithTransitTTL (default 5 min) if your users need longer, and let apps time out their own wait.

Further reading

Documentation

Overview

Package native is an opt-in broker that lets native (mobile, desktop, CLI) public clients log in through an oidc.RP using OAuth 2.0 for native apps: RFC 6749 authorization code + RFC 7636 PKCE (S256 only), RFC 8252 redirect URIs and RFC 7009 revocation.

The app never talks to the IdP. It opens the broker's authorize endpoint in a browser tab; the broker runs the RP's normal login and, on the callback, redirects back to the app with a one-time code. The app redeems that code (with its PKCE verifier) at the token endpoint for an access token minted by the consumer and a rotating refresh token. Each refresh redeems the IdP refresh token kept on the session, so the IdP still decides whether the session lives on.

Unlike the rest of gosso this package is stateful: codes and refresh sessions are persisted through the repository.Code and repository.Session interfaces, implemented on MongoDB (keel's persistor) by the repository package. Refresh secrets and codes are stored hashed; the IdP refresh token is stored encrypted with AES-256-GCM.

Wiring order: the RP needs the broker's wrapped hooks, and the broker needs the RP, so build the broker first and attach the RP last:

b, err := native.New(codes, sessions, hooks, clients, key)
rp, err := oidc.New(ctx, issuer, id, secret, callbackURL, transitKey,
	b.OnAuthenticated(webOnAuth),
	oidc.WithOnRedirect(b.OnRedirect(webOnRedirect)),
	oidc.WithOnLoginError(b.OnLoginError(nil)))
err = b.Attach(rp)

Then mount Handlers().Authorize, Token and Revoke next to the RP's own.

Index

Constants

This section is empty.

Variables

View Source
var ErrRejected = errors.New("native: subject rejected")

ErrRejected is wrapped by a Hooks.Authenticate error when no retry can succeed: the subject must not get or keep a session, e.g. because it has no account or lacks a required claim. A login then fails with error=access_denied; a refresh deletes the session and answers invalid_grant, so the app logs in again instead of retrying.

Functions

This section is empty.

Types

type Broker

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

Broker serves the native-app endpoints on top of an oidc.RP. Build it with New, pass its wrapped hooks to oidc.New, then Attach the RP.

func New

func New(codes repository.Code, sessions repository.Session, hooks Hooks, clients []Client, encryptionKey []byte, opts ...Option) (*Broker, error)

New builds a Broker. codes and sessions persist one-time codes and refresh sessions; clients are the registered native apps; encryptionKey (exactly 32 bytes) encrypts the stored IdP refresh tokens.

func (*Broker) Attach

func (b *Broker) Attach(rp *oidc.RP) error

Attach hands the broker the RP it logs in and refreshes through. It fails unless OnAuthenticated, OnRedirect and OnLoginError were all taken from this broker: a missing wrapper would silently send native logins down the web path. It only sees that the wrappers were created, not that they reached rp: pass them to oidc.New. Until Attach succeeds the handlers answer 500.

func (*Broker) Handlers

func (b *Broker) Handlers() Handlers

Handlers returns the broker's HTTP handlers. They answer 500 server_error until Attach succeeded.

func (*Broker) OnAuthenticated

func (b *Broker) OnAuthenticated(web sso.OnAuthenticated[oidc.Payload]) sso.OnAuthenticated[oidc.Payload]

OnAuthenticated wraps the web OnAuthenticated hook. Native logins skip it, so they set no web session; all others are delegated to web, or fail when web is nil.

func (*Broker) OnLoginError

func (b *Broker) OnLoginError(web oidc.OnLoginError) oidc.OnLoginError

OnLoginError wraps the web OnLoginError hook. A failed native login redirects to the app with error and state: the IdP's own error for a user-facing outcome (access_denied, login_required, ...), access_denied for a Hooks.Authenticate error wrapping ErrRejected, server_error for everything else. Other logins are delegated to web (nil keeps the default error response).

func (*Broker) OnRedirect

func (b *Broker) OnRedirect(web oidc.OnRedirect) oidc.OnRedirect

OnRedirect wraps the web OnRedirect hook. For a native login it runs Hooks.Authenticate, stores a one-time code and redirects to the app's redirect URI with code and state; an error there reaches OnLoginError, which redirects the app with error=server_error. Other logins are delegated to web (nil keeps the default target).

type Client

type Client struct {
	// ID is the client_id the app sends, e.g. "app-ios".
	ID string
	// RedirectURIs are the app's redirect URIs, matched exactly.
	RedirectURIs []string
}

Client is a registered native app: a public client without a secret.

type Handlers

type Handlers struct {
	// Authorize starts a native login (GET).
	Authorize http.Handler
	// Token redeems codes and refresh tokens (POST).
	Token http.Handler
	// Revoke ends a refresh session (POST, RFC 7009).
	Revoke http.Handler
}

Handlers groups the broker's HTTP handlers.

type Hooks

type Hooks struct {
	// Authenticate runs after a native login and after each successful
	// refresh. It returns attributes stored on the session. An error fails
	// the login (redirect with error=server_error) or the refresh (503,
	// session kept); an error wrapping ErrRejected fails the login with
	// error=access_denied and ends the session on refresh (400
	// invalid_grant). On refresh, ctx and r.Context() are detached from the
	// app's request, so they outlive a hang-up; honour their deadline.
	Authenticate func(ctx context.Context, r *http.Request, sub sso.Subject[oidc.Payload]) (store.Attributes, error)
	// Mint issues the consumer's access token for a session. It decides
	// the token format.
	Mint func(ctx context.Context, s store.Session) (Tokens, error)
}

Hooks are the consumer's part of the broker.

type Option

type Option = options.OptionE[*Broker]

Option configures a Broker.

func WithClock

func WithClock(now func() time.Time) Option

WithClock replaces time.Now, for tests.

func WithCodeTTL

func WithCodeTTL(d time.Duration) Option

WithCodeTTL sets how long a one-time code can be redeemed. Default 60s.

func WithDeprecatedEncryptionKeys

func WithDeprecatedEncryptionKeys(keys ...[]byte) Option

WithDeprecatedEncryptionKeys adds previous encryption keys that still open stored IdP refresh tokens, for key rotation. Each must be exactly 32 bytes; empty entries are skipped.

func WithErrorLogger

func WithErrorLogger(fn sso.ErrorLogger) Option

WithErrorLogger routes runtime errors to fn. Responses stay generic.

func WithLoginScopes

func WithLoginScopes(scopes ...string) Option

WithLoginScopes replaces the scopes a native login requests on top of the RP's own. Default offline_access, which most IdPs need to issue the refresh token the broker requires; web logins through the same RP do not request it, so they open no offline session at the IdP. Without arguments a native login requests the RP's scopes only.

func WithRotationGrace

func WithRotationGrace(d time.Duration) Option

WithRotationGrace sets how long the previous refresh tokens keep working after a rotation is stored, so concurrent or retried refreshes from one app all succeed. Default 10s.

0 disables the grace window: rotation is strict, and a second refresh with the same token counts as reuse and ends the session, even one sent concurrently with the first. Use it only when the app serialises its refreshes and never retries one whose response it lost.

func WithSessionTTL

func WithSessionTTL(d time.Duration) Option

WithSessionTTL sets the absolute lifetime of a refresh session, counted from login. Default 90 days.

type Tokens

type Tokens struct {
	// AccessToken is returned as access_token with token_type "Bearer".
	AccessToken string
	// ExpiresIn is returned as expires_in, in whole seconds.
	ExpiresIn time.Duration
}

Tokens are the consumer's tokens for a session, minted by Hooks.Mint.

Directories

Path Synopsis
Package repository persists the native broker's one-time codes and refresh sessions.
Package repository persists the native broker's one-time codes and refresh sessions.
store
Package store holds the entities the native broker persists through its repositories: one-time codes and refresh sessions.
Package store holds the entities the native broker persists through its repositories: one-time codes and refresh sessions.

Jump to

Keyboard shortcuts

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