How Behemoth fits together

This page gives you the big picture of Behemoth: the parts it is made of, how an application starts, and what happens when a request arrives. Read it after the Quick Start and before the pages on individual parts.

The parts #

Behemoth is a library that you add to your Go application. It connects to your database and your router, and it does not run as a separate service. The following table lists its parts and where you meet each one:

PartWhat it doesWhere you meet it
PluginsAdd an authentication method or a behavior. A plugin declares the tables, routes, hooks, and rate limits it needs.The plugin list you pass to Prepare
Database and migrationsStore users, sessions, and tokens in your database. Behemoth generates migrations from the tables that plugins and your application declare.A database adapter and the behemoth command
Sessions and tokensCreate a session at sign-in, deliver its token by cookie or header, and issue single-use tokens for flows such as password reset.SessionConfig and RouterConfig.Carrier
HooksRun your code before or after an operation, or when it fails.BootConfig.Hooks
Routes and routersServe the plugins' routes on your framework, with rate limits and consistent error responses.A router adapter in BootConfig.HTTP
Mail and SMSHand messages to the sender you provide, so you keep your own delivery service and templates.BootConfig.Mail and BootConfig.SMS
TelemetryRecord logs, audit events, metrics, and traces.BootConfig.Telemetry

Two phases: Prepare and Boot #

Behemoth starts in two phases. The split exists so that tools such as the migration command can read your declarations without a database connection.

1. Prepare

Needs no database or router

  • Orders the plugins by their dependencies
  • Collects tables, hook points, token kinds, and rate-limit rules
  • Adds your application's own tables
  • Fixes the declarations

2. Boot

Needs a database, optionally a router

  • Checks that the database is set up correctly
  • Registers hook handlers and starts the plugins
  • Builds the session, token, and mail services
  • Mounts the routes on your router

AuthContext

What you keep

  • Holds the services Behemoth built
  • Gives your code the session manager, the store, and telemetry
  • Is what plugins receive when they start

The following example shows both phases. The Quick Start explains each line in detail.

go
// Phase 1: collect the declarations. No database is needed.
app, err := engine.Prepare(
    []core.Plugin{emailpassword.New(emailpassword.Options{})},
    engine.PrepareConfig{},
)
if err != nil {
    log.Fatal(err)
}

// Phase 2: connect to the database and the router.
db := postgres.NewPostgresAdapter(sqlDB, app.Resolver)
router := gin.New()

secrets := crypto.StaticSecretSource{
    Secrets: map[int]string{1: os.Getenv("BEHEMOTH_SECRET")},
    Current: 1,
}

ac, err := engine.Boot(
    ctx,
    app,
    db,
    engine.BootConfig{
        Crypto: crypto.Config{
            Secrets: secrets,
        },
        HTTP: ginadapter.New(router),
    },
)
if err != nil {
    log.Fatal(err)
}

In this example, sqlDB is your open *sql.DB connection and ctx is a context that lives as long as the application. Pass app.Resolver to the database adapter so that your queries and your migrations agree on table and column names.

What Boot checks #

Boot reports a setup problem at startup, not on the first sign-up. It returns an error in these cases:

  • The database does not support transactions, as on a standalone MongoDB server.
  • The database does not enforce foreign keys, as on a SQLite connection opened without them. Set BootConfig.AllowUnenforcedForeignKeys to start anyway with a logged warning.
  • A plugin needs a mail or SMS sender and you did not configure one.
  • The router or session configuration is invalid, for example a cookie domain that does not cover your base URL.

What a plugin contributes #

Everything Behemoth does for a user comes from a plugin. A plugin takes part in both phases:

PhaseWhat the plugin does
PrepareDeclares its tables, hook points, token kinds, permissions, and rate-limit rules.
BootRegisters its hook handlers, receives the services it works with, and supplies its routes.

A plugin lists the plugins it depends on. Prepare orders them so that each plugin comes after its dependencies. It returns an error if a required plugin is missing or if the dependencies form a cycle. For example, username builds on emailpassword, so it can only be used with it.

Your application takes part in the same way as a plugin, under the name app unless you set PrepareConfig.AppName:

  • PrepareConfig.Schema declares your tables after every plugin has declared, so it can also add a column to a plugin's table such as users.
  • BootConfig.Hooks registers your hook handlers after every plugin's handlers.

The AuthContext #

Boot returns an *core.AuthContext. It is one value that holds the services Behemoth built from your configuration. Behemoth passes it to every plugin when the plugin starts, and you receive the same value as ac.

Most of its fields are for plugins. The following table lists the ones you are most likely to use in your own code:

FieldWhat it gives youUse it to
StoreBehemoth's data layer for its own tablesLook up a user, for example with ac.Store.FindUserByEmail, or query audit events
SessionManagerCreate, validate, and look up sessionsPass it to httpapi.RequireFreshSession, or manage sessions in a route of your own
PublicThe columns of a row that are safe to send to a clientAnswer a request with ac.Public.Of(user) instead of the model
DBThe root database adapterRead and write your own tables
Mailer and SMSThe senders behind BootConfig.Mail and BootConfig.SMSWait for queued messages at shutdown
TelemetryThe logger, audit recorder, and metricsLog from your own code with the same setup as Behemoth
HTTPClientThe client Behemoth uses for calls to other servicesMake outbound calls with the same timeout and tracing. See Outbound calls.

The other fields hold services that plugins build on, such as the token manager, the rate limiter, and the cryptography services. The generated reference lists all of them.

Write Behemoth's tables through the store

Use ac.Store for Behemoth's tables, not ac.DB. The database adapter skips the hooks, ids, timestamps, normalization, and token sealing that the store adds. Use ac.DB for tables that your application or a plugin declared itself.

Shut down cleanly #

Behemoth sends mail and text messages in the background. When your application stops, call Close on both senders so that messages still in the queue are sent first:

go
shutdownCtx, cancel := context.WithTimeout(
    context.Background(),
    10*time.Second,
)
defer cancel()

err := errors.Join(
    ac.Mailer.Close(shutdownCtx),
    ac.SMS.Close(shutdownCtx),
)
if err != nil {
    log.Println("shutdown:", err)
}

Use a context that is not already cancelled, because the context of a stopping server usually is.

The life of a request #

The following steps describe a request to a route that Behemoth mounted, such as a sign-in:

  1. Your framework receives the request and passes it to the route through the router adapter.
  2. If the session token travels in a cookie, Behemoth checks the Origin of the request and refuses form content types. A bearer token needs neither check, because a browser never sends it on its own.
  3. The route's rate limit runs first, so a refused request costs no session lookup.
  4. Behemoth resolves the session token, if there is one, to a session.
  5. The plugin's flow runs. Before hooks run first and can change the data or stop the operation. After hooks run when the operation succeeds, and failed hooks run when it does not.
  6. Writes go through the store. The store seals sensitive values before they reach the database, and it runs data hooks in the same transaction as the write.
  7. A sign-in creates a session and returns its token by cookie or header.

Telemetry records logs and audit events along the way. A failed request returns a JSON body with an error message and, for most errors, a code that your client can match on.

Where your code fits #

The following table maps common tasks to the place where you do them:

If You want toUse
Add a sign-in method or a reusable behaviorA plugin that you pass to Prepare
Store your own data next to Behemoth's tablesPrepareConfig.Schema, then behemoth generate for the migration
Run code around sign-up, sign-in, or a data writeBootConfig.Hooks
Send email or text messagesBootConfig.Mail and BootConfig.SMS
Use a framework other than the supported onesYour own implementation of FrameworkDriver
Require a signed-in user on your own routesThe httpapi.RequireSession middleware. See Protect your own routes.
Call a flow such as sign-in from your own codeThe plugin's own methods, such as plugin.SignIn, which work without a router

Run without a router #

Leave BootConfig.HTTP unset to boot Behemoth without serving any routes. Behemoth still builds and checks the route table, so a misconfiguration surfaces the same way in every process. Use this in a worker or a command-line tool, and call the flows from code.

A complete application

The examples/init directory in the repository shows these parts together: PostgreSQL, Gin, migrations, a custom plugin, hooks, and telemetry.

Next steps #

To go deeper into a part, read the following pages:

  • Quick Start: Build your first authentication flow.
  • Hooks: Run your code at fixed points.
  • Sessions: Configure how the session token is delivered.
  • Routers: Mount the routes on your framework.
  • Core tables: See the tables Behemoth creates.
  • Migration CLI: Generate migrations from your declarations.