server

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0 Imports: 71 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

server

The tensile-auth server: the library packaged as one binary, so apps in any language can use it over HTTP. The app proxies /auth/ to the server, so sessions stay in __Host- cookies on the app's own origin. The design is in docs/design/server.md. To install, configure, back up, upgrade, and monitor it, read the operator guide.

Run it

To try it on your computer with nothing to set up, run:

go run ./cmd/tensile-auth-server dev

dev keeps everything in memory, serves the API on localhost:8080 and the health checks /livez and /readyz on localhost:9090 (see Monitor), writes email to standard error, and serves the browser client's developer panel under /auth/dev/. It refuses any origin other than localhost.

To run it on one node with SQLite, set TENSILE_AUTH_DATABASE_URL=sqlite:///var/lib/tensile-auth/auth.db. For several replicas, use a postgres:// URL.

To check a configuration without serving, run tensile-auth-server check. It runs every startup check and exits with 0 or 1. To apply migrations as a job before a rollout, run tensile-auth-server migrate and set migrate to check on the servers.

Configure it

Settings come from, in order of precedence: flags, then TENSILE_AUTH_ environment variables, then a TOML file, then defaults. Each key maps to one variable and one flag:

Key Variable Flag
origins TENSILE_AUTH_ORIGINS --origins
passwords.mailer_url TENSILE_AUTH_PASSWORDS__MAILER_URL or TENSILE_AUTH_PASSWORDS__MAILER_URL_FILE --passwords.mailer-url-file

A secret, such as master_key, database_url, or passwords.mailer_url, can be read from a file with the _FILE suffix, and has only a -file flag, so it never appears in a process list. An unknown key in the file, or a TENSILE_AUTH_ variable that matches no key, stops the server.

Contents

Name What it holds
server.go Main, the commands, and the serve loop with its shutdown order
config.go The configuration and how it loads
checks.go The startup refusals
app.go Builds the service and mounts the routes
ops.go /livez and /readyz on the ops listener
db.go Postgres and SQLite connections, and both sets of migrations
deps.go Opens the stores, the cache and its watcher, and the rate-limit backend
keys.go Keys sealed under the master key: the key-check value, rotation, and rewrapping
keyscmd.go keys status, keys rotate, and keys rewrap
appkeys.go App keys, app-key create, revoke, and list, and the leakscan revoker for leaked keys
export.go export and import, including import --from auth0, clerk, and supabase, and the count of bcrypt hashes that check reports
v1.go The app API: /v1/check, /v1/meta, and the document
v1.openapi.json, auth.openapi.json, openapi.json The /v1 OpenAPI document, the server's own /auth/ routes, and the merged document for the SDK
openapi.go Merges the documents; go generate rewrites openapi.json
oauthroutes.go The JSON behind the app's OAuth consent and device pages, under /auth/oauth/ and /auth/device/
events.go /v1/events/stream, which tells the SDK when to clear its cache
hooks.go The sign-up and session scopes hooks, signed both ways, which fail closed
webhooks.go Delivers events from the sealed audit log to webhooks.url, at least once
admin.go The admin API under /admin/, the administrators table, invitations, and admin grant, revoke, list, and invite
oauthprovider.go Builds the OAuth provider from [oauth] and mounts its endpoints
mailer.go Sends the password package's mail over SMTP or a signed webhook
totpkeys.go Counts and reseals TOTP secrets after a rotation
migrations/ The server's own tables

Documentation

Overview

Package server is the tensile-auth server: the library packaged as one binary, so apps in any language can use it over HTTP. The app proxies /auth/ to it, so sessions stay in __Host- cookies on the app's own origin.

The binary in cmd/tensile-auth-server calls Main. Tests and Go apps can call Main too, to start a server in-process. The design is in docs/design/server.md.

Index

Constants

View Source
const AdminPrefix = "/admin/"

AdminPrefix is where the admin API is mounted. Every request under it needs a human with AssuranceMulti, whichever route serves it.

View Source
const AppKeyHeader = "Tensile-App-Key"

AppKeyHeader carries the app key on every /v1 call.

View Source
const ClientIPHeader = "Tensile-Client-IP"

ClientIPHeader carries the end user's address on a request that the SDK's proxy forwards. The server trusts it only on a request that also carries a live app key in AppKeyHeader.

View Source
const DefaultConfigFile = "/etc/tensile-auth/config.toml"

DefaultConfigFile is where the server looks for its file when neither --config nor TENSILE_AUTH_CONFIG names one. A missing default file is not an error; a missing named file is.

View Source
const EnvPrefix = "TENSILE_AUTH_"

EnvPrefix starts every environment variable the server reads.

View Source
const SubjectHeader = "Tensile-Subject"

SubjectHeader carries the subject on GET routes that act for a person: base64url JSON in the shape of a check's credential.

Variables

View Source
var Version = "dev"

Version is the server's version, stamped at build time with -ldflags.

Functions

func Main

func Main(ctx context.Context, e Env) int

Main runs the command in e.Args until ctx ends, and returns the exit code. Cancel ctx on SIGTERM to shut the server down in order.

Types

type AdminConfig

type AdminConfig struct {
	// AllowedNetworks are CIDRs whose clients may reach /admin/. Empty
	// means any.
	AllowedNetworks []string `toml:"allowed_networks"`
}

AdminConfig is the [admin] table.

type CacheConfig

type CacheConfig struct {
	// Enabled wraps the store in cachestore, kept fresh by pgstore.Watch.
	Enabled bool `toml:"enabled"`
}

CacheConfig is the [cache] table.

type Config

type Config struct {
	// DatabaseURL is a postgres:// URL, or sqlite:///path for a single
	// node.
	DatabaseURL string `toml:"database_url" secret:"true"`
	// Origins are the app's public origins.
	Origins []string `toml:"origins"`
	// RPID is the passkey relying party ID. Default: the host of the
	// first origin.
	RPID string `toml:"rp_id"`
	// RPName is the name some authenticators show. Default: RPID.
	RPName string `toml:"rp_name"`
	// MasterKey is 32 random bytes in standard base64. It wraps every key
	// the server stores.
	MasterKey string `toml:"master_key" secret:"true"`
	// Listen is the API listener.
	Listen string `toml:"listen"`
	// OpsListen is the health and metrics listener. Never proxy it.
	OpsListen string `toml:"ops_listen"`
	// TrustedProxies are CIDRs whose X-Forwarded-For the server trusts.
	TrustedProxies []string `toml:"trusted_proxies"`
	// Preset is the preset the service, passwords, and routes are built
	// from.
	Preset string `toml:"preset"`
	// Migrate is auto, check, or off.
	Migrate         string   `toml:"migrate"`
	ShutdownTimeout Duration `toml:"shutdown_timeout"`

	Passwords  PasswordsConfig  `toml:"passwords"`
	Cache      CacheConfig      `toml:"cache"`
	RateLimits RateLimitsConfig `toml:"rate_limits"`
	Sessions   SessionsConfig   `toml:"sessions"`
	Hooks      HooksConfig      `toml:"hooks"`
	Webhooks   WebhooksConfig   `toml:"webhooks"`
	Admin      AdminConfig      `toml:"admin"`
	OAuth      OAuthConfig      `toml:"oauth"`
	Log        LogConfig        `toml:"log"`
}

Config is the server's configuration. Each field is one key of the TOML file; a nested struct is a TOML table. A field tagged secret:"true" can also be read from a file with the _FILE suffix, and has no plain flag, so the secret never appears in a process list.

type Duration

type Duration struct{ time.Duration }

Duration is a time.Duration written as a Go duration string, for example "8s", in the file, a variable, or a flag.

func (Duration) MarshalText

func (d Duration) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*Duration) UnmarshalText

func (d *Duration) UnmarshalText(b []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Env

type Env struct {
	// Args are the arguments after the program name.
	Args []string
	// Environ is the environment, as KEY=value strings.
	Environ []string
	Stdout  io.Writer
	Stderr  io.Writer
	// ReadFile reads the configuration file and _FILE secrets.
	ReadFile func(name string) ([]byte, error)
	// Getuid returns the process's user ID.
	Getuid func() int
	// Stdin is standard input. StdinTerminal and StdoutTerminal report
	// whether standard input and output are terminals; nil means not.
	Stdin          io.Reader
	StdinTerminal  func() bool
	StdoutTerminal func() bool
	// ReadPassword reads a line from the terminal without echoing it.
	ReadPassword func() ([]byte, error)
	// Listening, when set, is called with the API and ops addresses once
	// the server accepts connections.
	Listening func(api, ops string)
	// contains filtered or unexported fields
}

Env is what Main reads and writes, so a test can run it without the process's own arguments, environment, files, or user.

func OSEnv

func OSEnv() Env

OSEnv returns the process's own Env.

type HooksConfig

type HooksConfig struct {
	// URL is the app's endpoint for synchronous hooks: sign-up and
	// session scopes. Each answer must be signed.
	URL string `toml:"url"`
}

HooksConfig is the [hooks] table.

type LogConfig

type LogConfig struct {
	// Format is json or text.
	Format string `toml:"format"`
}

LogConfig is the log table.

type OAuthClient

type OAuthClient struct {
	ID   string `toml:"id"`
	Name string `toml:"name"`
	// SecretSHA256 holds the hex SHA-256 of each valid client secret, so
	// the file holds no secret. A client without one is public.
	SecretSHA256 []string `toml:"secret_sha256"`
	RedirectURIs []string `toml:"redirect_uris"`
	Native       bool     `toml:"native"`
	// Grants are authorization_code, refresh_token, device_code, or
	// token_exchange.
	Grants     []string `toml:"grants"`
	Scopes     []string `toml:"scopes"`
	AccessTTL  Duration `toml:"access_ttl"`
	Refresh    bool     `toml:"refresh"`
	FirstParty bool     `toml:"first_party"`
}

OAuthClient is one [[oauth.clients]] table.

type OAuthConfig

type OAuthConfig struct {
	// Enabled mounts the OAuth and OpenID Connect provider.
	Enabled bool `toml:"enabled"`
	// Issuer is the provider's URL. Default: the first origin.
	Issuer string `toml:"issuer"`
	// Interaction is the app's consent page. Default: the first origin
	// followed by /oauth/consent.
	Interaction string `toml:"interaction"`
	// DevicePage is the path of the app's device page. Default:
	// /login/device.
	DevicePage string          `toml:"device_page"`
	Clients    []OAuthClient   `toml:"clients"`
	Resources  []OAuthResource `toml:"resources"`
}

OAuthConfig is the oauth table. Clients and resources are arrays of tables, [[oauth.clients]] and [[oauth.resources]], so they come only from the file.

type OAuthResource

type OAuthResource struct {
	URI    string   `toml:"uri"`
	Name   string   `toml:"name"`
	Scopes []string `toml:"scopes"`
}

OAuthResource is one [[oauth.resources]] table: a protected resource, such as an MCP server.

type PasswordsConfig

type PasswordsConfig struct {
	// Enabled false serves passkeys only.
	Enabled bool `toml:"enabled"`
	// MailerURL is an smtp:// or smtps:// URL, or an https:// webhook.
	MailerURL string `toml:"mailer_url" secret:"true"`
	// AcceptBcrypt verifies bcrypt hashes imported from other products,
	// and replaces each with Argon2id on its first correct sign-in.
	AcceptBcrypt bool `toml:"accept_bcrypt"`
}

PasswordsConfig is the [passwords] table.

type RateLimitsConfig

type RateLimitsConfig struct {
	// Backend is "postgres", "memory" for a single node, or a redis://
	// or rediss:// URL. Default: postgres on Postgres, and memory on
	// SQLite and in dev.
	Backend string `toml:"backend" secret:"true"`
}

RateLimitsConfig is the [rate_limits] table.

type SessionsConfig

type SessionsConfig struct {
	// DefaultScopes are the scopes of every session.
	DefaultScopes []string `toml:"default_scopes"`
}

SessionsConfig is the [sessions] table.

type WebhooksConfig

type WebhooksConfig struct {
	// URL is the app's endpoint for events, delivered after they commit.
	URL string `toml:"url"`
}

WebhooksConfig is the [webhooks] table.

Jump to

Keyboard shortcuts

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