api

package
v1.12.2 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TokenLifetime   = 15 * time.Minute
	SessionLifetime = 30 * 24 * time.Hour
)

Framework constants for token and session lifetimes. Not configurable.

View Source
const PublicConfigPrefix = "PUBLIC_"

PublicConfigPrefix marks environment variables as public frontend config. Every variable with this prefix is served by /api/config; nothing else is.

Variables

View Source
var (
	ErrBadRequest  = errors.New("bad request") // 400
	ErrForbidden   = errors.New("forbidden")   // 403
	ErrNotFound    = errors.New("not found")   // 404
	ErrConflict    = errors.New("conflict")    // 409
	ErrUnavailable = errors.New("unavailable") // 503
)

Sentinel errors that handlers can return (directly or wrapped with %w) to produce specific HTTP status codes.

Functions

func AuthOpenAPI added in v1.10.0

func AuthOpenAPI() (paths map[string]any, schemas map[string]any)

AuthOpenAPI returns the OpenAPI path items and component schemas of the framework's auth routes, as plain JSON-shaped maps. Both the codegen (static gen/openapi.json) and BuildOpenAPI merge them in, so the generated clients always have the auth routes. The auth0 login route is always included, independent of deployment config.

func BuildOpenAPI

func BuildOpenAPI(title, version string) openAPISchema

BuildOpenAPI constructs the OpenAPI spec from all registered routes. Exported so the codegen command can call it directly to write openapi.json.

func ConfigHandler added in v1.10.0

func ConfigHandler() http.Handler

ConfigHandler returns an http.Handler for GET /api/config: a flat JSON object of all PUBLIC_* environment variables. The environment is read once, when the handler is created (at server start). Always open (no auth). Not part of openapi.json; the frontend reads it via the generated config.gen.ts.

func HealthHandler

func HealthHandler() http.Handler

HealthHandler returns an http.Handler that reports the health of the service and database. GET /api/health → {"status":"ok","db":"ok"} or {"status":"error","db":"error: ..."}

func InitAuth

func InitAuth(key []byte)

InitAuth sets the HMAC-SHA256 signing key used for JWT verification. Called by the schemaf app after migrations run and the key is loaded from _schemaf_config.

func InitSessions added in v1.10.0

func InitSessions(store SessionStore)

InitSessions sets the session store. Called by the schemaf app after the database is initialized. Without it, StartSession and identity providers are unavailable and only stateless tokens work.

func IssueToken

func IssueToken(sub string, exp time.Time) (string, error)

IssueToken creates a signed stateless JWT for the given subject. exp=0 means no expiry. The token is not tied to a session: it is never renewed and only RevokeSubject ends it early. Use it for service-to-service tokens; use StartSession for users.

func NewMux

func NewMux() *http.ServeMux

NewMux builds and returns the http.ServeMux with all framework defaults and registered routes. Useful for testing with httptest.NewServer.

func OpenAPIHandler

func OpenAPIHandler() http.Handler

OpenAPIHandler returns an http.Handler that serves an OpenAPI 3.0 JSON document reflecting all registered routes.

func OpenAPISecurity added in v1.11.0

func OpenAPISecurity(level AuthLevel) []any

OpenAPISecurity returns the OpenAPI security requirement for an auth level: either scheme for AuthRequired, anonymous or either scheme for AuthOptional, and nil (no security) for AuthNone.

func OpenAPISecuritySchemes added in v1.11.0

func OpenAPISecuritySchemes(cookieName string) map[string]any

OpenAPISecuritySchemes returns the OpenAPI security schemes schemaf's auth accepts: bearerAuth (Authorization: Bearer <JWT>) and cookieAuth (the session cookie named cookieName). Both generators (runtime BuildOpenAPI and the static codegen spec) use it.

func Register

func Register(r Route)

Register adds a route to the global registry.

func RegisterHealth added in v1.5.0

func RegisterHealth(name string, fn HealthChecker)

RegisterHealth adds a named health check. If the checker returns an error, the overall health status is "error" and the response code is 503.

api.RegisterHealth("s3", func() error {
    return s3Client.Ping()
})

func RegisterStatus added in v1.4.0

func RegisterStatus(name string, fn StatusProvider)

RegisterStatus adds a named status provider. The returned value is included under the given key in the /api/status JSON response.

api.RegisterStatus("s3", func() any {
    return map[string]any{"bucket": "my-bucket", "connected": true}
})

func Reset

func Reset()

Reset clears all registered routes. Intended for use in tests only.

func RevokeSession added in v1.10.0

func RevokeSession(ctx context.Context, sessionID string) error

RevokeSession ends one session immediately.

func RevokeSubject added in v1.10.0

func RevokeSubject(ctx context.Context, subject string) error

RevokeSubject immediately ends every session of subject and every stateless token issued for it so far.

func Serve

func Serve(addr string) error

Serve starts the HTTP server on the given address using the registered routes. addr should be in the form ":8000".

func SessionCookieName added in v1.11.0

func SessionCookieName(projectName string) string

SessionCookieName is the session cookie name for a project: "<project name>_session".

func SessionID added in v1.10.0

func SessionID(ctx context.Context) (string, bool)

SessionID returns the session ID of the authenticated request. Returns ("", false) if the request was not authenticated or used a stateless token (see IssueToken).

func SetFrontend added in v0.7.0

func SetFrontend(fsys fs.FS)

SetFrontend registers the embedded frontend filesystem for production serving. In dev mode (SCHEMAF_ENV != "docker"), the server proxies to the frontend dev server instead.

func SetIdentityProviders added in v1.10.0

func SetIdentityProviders(ps []IdentityProvider)

SetIdentityProviders sets the active identity providers. Called by the schemaf app at server start, after validating names.

func SetOnLogin added in v1.10.0

func SetOnLogin(fn OnLoginFunc)

SetOnLogin sets the identity → subject mapping. nil means the provider's subject is used unchanged.

func StartSession added in v1.10.0

func StartSession(ctx context.Context, w http.ResponseWriter, subject string) (string, error)

StartSession starts a session for subject, sets the session cookie on w and returns the token for Bearer clients. Use it for logins the app handles itself (login codes, guests), from a raw endpoint. The session's provider column is empty.

func StatusHandler

func StatusHandler() http.Handler

StatusHandler returns an http.Handler for GET /api/status. Reports service uptime, last backup status, the names of the active identity providers, and any registered status providers. Always open (no auth required).

func Subject

func Subject(ctx context.Context) (string, bool)

Subject returns the authenticated subject (user ID) from the context. Returns ("", false) if the request was not authenticated.

func UserMeHandler

func UserMeHandler() http.Handler

UserMeHandler returns an http.Handler for GET /api/user/me (AuthRequired): the authenticated caller's subject.

Types

type AuthLevel added in v1.11.0

type AuthLevel int

AuthLevel declares how an endpoint authenticates its caller.

const (
	// AuthNone: credentials are never looked at; the handler runs anonymous.
	AuthNone AuthLevel = iota
	// AuthOptional: the subject if credentials are present, anonymous if
	// not. Present but invalid credentials are a 401.
	AuthOptional
	// AuthRequired: 401 without valid credentials.
	AuthRequired
)

func (AuthLevel) String added in v1.11.0

func (l AuthLevel) String() string

String returns the constant's name, e.g. "AuthRequired".

type Endpoint

type Endpoint[Req, Resp any] interface {
	Method() string  // HTTP method: "GET", "POST", "PUT", "DELETE", etc.
	Path() string    // Route path, e.g. "/api/todos/{id}"
	Auth() AuthLevel // AuthNone, AuthOptional or AuthRequired
	Handle(ctx context.Context, req Req) (Resp, error)
}

Endpoint is the interface that all schemaf API endpoints must implement. Req is the request type (decoded from JSON body or path/query params). Resp is the response type (encoded as JSON).

Document your endpoint with a Go doc comment on the struct:

// ListTodosEndpoint returns all todo items ordered by creation date.
// Returns an empty array if no todos exist.
type ListTodosEndpoint struct{}

The first line becomes the OpenAPI summary; subsequent lines the description. Both are extracted by codegen — no annotations required.

type HealthChecker added in v1.5.0

type HealthChecker func() error

HealthChecker returns nil if healthy, or an error describing the problem.

type Identity added in v1.10.0

type Identity struct {
	Provider string         // set by schemaf
	Subject  string         // the provider's subject (e.g. Auth0 sub)
	Claims   map[string]any // all further claims
}

Identity is what an identity provider proves.

type IdentityProvider added in v1.10.0

type IdentityProvider interface {
	Name() string // URL-safe, unique per app
	// Exchange verifies the provider's credential in the login request and
	// returns the identity it proves. ErrForbidden (or wrapped) → 403,
	// ErrBadRequest → 400, any other error → 500.
	Exchange(ctx context.Context, r *http.Request) (Identity, error)
}

IdentityProvider is a login plugin: it verifies a credential in the login request and returns the identity it proves. Providers are consulted only at login (POST /api/auth/{name}/login); after that only schemaf's own session matters.

type LoginResponse added in v1.10.0

type LoginResponse struct {
	Subject string `json:"subject"`
	Token   string `json:"token"`
}

LoginResponse is the body of POST /api/auth/{provider}/login.

type OnLoginFunc added in v1.10.0

type OnLoginFunc func(ctx context.Context, id Identity) (subject string, err error)

OnLoginFunc maps a proven identity to the app's subject. Returning ErrForbidden refuses the login (403).

type RawEndpoint added in v0.12.1

type RawEndpoint interface {
	Method() string
	Path() string
	Auth() AuthLevel
	HandleRaw(w http.ResponseWriter, r *http.Request) error
}

RawEndpoint is an alternative to Endpoint for handlers that need direct HTTP access — binary uploads, streaming downloads, SSE, etc.

Define HandleRaw instead of Handle on your endpoint struct. Exactly one of Handle or HandleRaw must be present; codegen will error if both exist.

The framework does not decode the request or encode the response — you have full control over http.ResponseWriter and *http.Request. If HandleRaw returns a non-nil error and no response has been written yet, the framework writes a JSON error response using the standard error mapping.

type RefreshResponse added in v1.10.0

type RefreshResponse struct {
	Token string `json:"token"`
}

RefreshResponse is the body of POST /api/auth/refresh.

type Route

type Route struct {
	Method      string    // "GET", "POST", "PUT", "DELETE", etc.
	Path        string    // e.g. "/api/todos", "/api/todos/{id}"
	Auth        AuthLevel // AuthNone, AuthOptional or AuthRequired
	Summary     string    // first line of endpoint struct doc comment
	Description string    // remaining lines of endpoint struct doc comment
	Handler     http.Handler
	ReqType     any // pointer to zero-value request type (for OpenAPI reflection)
	RespType    any // pointer to zero-value response type (for OpenAPI reflection)
}

Route describes a single HTTP route registered with the framework.

func NewRawRoute added in v0.12.1

func NewRawRoute(e RawEndpoint, summary, description string) Route

NewRawRoute creates a Route from a RawEndpoint. No JSON decode/encode is performed; the handler receives the raw http.ResponseWriter and *http.Request.

func NewRoute

func NewRoute[Req, Resp any](e Endpoint[Req, Resp], summary, description string) Route

NewRoute creates a Route from a typed Endpoint, wiring up JSON decode/encode and auth declaration. summary and description are extracted from the struct's doc comment by codegen and passed as string literals in the generated Provider().

func Routes

func Routes() []Route

Routes returns all registered routes.

type SessionStore added in v1.10.0

type SessionStore interface {
	CreateSession(ctx context.Context, s db.Session) error
	GetSession(ctx context.Context, id string) (db.Session, bool, error)
	RevokedBefore(ctx context.Context, subject string) (time.Time, error)
	RevokeSession(ctx context.Context, id string, at time.Time) error
	RevokeSubject(ctx context.Context, subject string, at time.Time) error
}

SessionStore persists sessions and per-subject revocations. The schemaf app injects the Postgres implementation (db.SessionStore).

type StatusProvider added in v1.4.0

type StatusProvider func() any

StatusProvider returns a value to include in the /api/status response.

Directories

Path Synopsis
Package oidc implements schemaf's built-in identity providers on top of a generic OIDC ID-token verifier (discovery + JWKS via coreos/go-oidc).
Package oidc implements schemaf's built-in identity providers on top of a generic OIDC ID-token verifier (discovery + JWKS via coreos/go-oidc).

Jump to

Keyboard shortcuts

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