# Service and routes

> Create the service, declare a rule for every route, and mount every sign-in route in one call.

From `docs/guide.md` in tensile-tools/tensile-auth at commit `e66760d` (v0.4.1-7-ge66760d). The HTML page is https://auth.tensile.tools/docs/guides/service-and-routes.

Throughout the guides, `ctx` is a request context, and errors go to the client with `authhttp.Error(w, r, err)`, which writes the RFC 9457 problem from `auth.Describe`. Every code is in the [error catalog](/docs/reference/errors).

## Create the service

```go
db, _ := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err := pgstore.Migrate(ctx, db); err != nil {
	log.Fatal(err)
}
store := pgstore.New(db)

limiter, _ := ratelimit.New(pgstore.NewRateLimits(db), ratelimit.DefaultRules())
svc, err := auth.New(store, auth.WithLimiter(limiter), auth.WithLogger(slog.Default()))
if err != nil {
	log.Fatal(err) // a setup error: its message names the field and the fix
}
go svc.Run(ctx) // ctx lives as long as the server
```

For tests, use `memstore.New()` and `ratelimit.NewMemory()`. For a small install, `sqlitestore.Open(ctx, "auth.db")` keeps everything in one SQLite file. It uses the `ncruces/go-sqlite3` driver, registered as `sqlite3`. An application that also uses `modernc.org/sqlite`, registered as `sqlite`, works, but must use `sqlitestore.DSN` only for the store's own database, opened with the `sqlite3` driver.

- **Run `svc.Run`.** Start it once per server, in its own goroutine, for as long as the service runs. Once a minute, it seals new audit events into the hash chain, writes failure summaries, and deletes unclaimed agents past their deadline. Until an event is sealed, a change to it, or its deletion, is undetectable: `svc.VerifyAudit` covers only sealed events. `svc.UnsealedAudit` counts the events that aren't sealed, and the admin API's chain status reports it as `unsealed`.
- **Log.** `auth.WithLogger` sets the logger for the service and, unless you pass `authhttp.WithLogger`, for `authhttp`: every 500 that `authhttp.Error` writes logs its error there. Without a logger, those errors are discarded.
- **Setup errors.** Errors from `auth.New`, `passkey.New`, `password.New`, and `mux.Check` name the field and the fix. Log them as they are and stop. Never pass them to `auth.Describe`, which is for request errors and turns most of them into a bare `internal` problem.

## Declare every route

Use `authhttp.Mux`. Every route declares `authhttp.Public` or a need, and `Check` refuses to start when something would weaken security: a route without a rule, an admin route below a multi-factor human, no client key, no limiter, an `http://` origin, or dev tools outside localhost.

```go
mux := authhttp.NewMux(svc,
	authhttp.WithClientIP(netip.MustParsePrefix("10.0.0.0/8")), // your load balancers
	authhttp.WithOrigins("https://tensile.example"),
	authhttp.WithAdminPrefix("/admin/"),
	authhttp.WithRotation(15*time.Minute),
	authhttp.WithFreshHeader(10*time.Minute),
	authhttp.WithStepUpURL("/auth/passkey/step-up/begin"),
)
mux.HandleFunc("GET /{$}", authhttp.Public, home)
mux.HandleFunc("GET /repos/{id}", authhttp.Need(auth.Need{Scopes: []string{"repo:read"}}), showRepo)
mux.HandleFunc("DELETE /repos/{id}", authhttp.Need(auth.Need{Assurance: auth.AssuranceMulti, Within: 10 * time.Minute, Human: true}), deleteRepo)
if err := mux.Check(); err != nil {
	log.Fatal(err) // names every problem and its fix
}
```

In CI, `authtest.Routes(t, mux)` calls every route as an anonymous caller, a recovery-mode session, a stale session, and an agent without scopes, and fails on any 2xx the route's need excludes. It checks that each route enforces the need it declares, not that the need is right: it can't catch a need that is too loose, it skips `Public` routes, and it can't see what a handler checks itself. Your own route tests catch those: call each sensitive route as the principal it must refuse, such as an agent or another user. To review `Public` routes, compare `authtest.PublicRoutes(mux)` with the list you expect.

## The one-call setup

To get every sign-in route the browser client calls, mount them all at once, then skip to [the browser client](/docs/guides/browser-client):

```go
authroutes.Mount(mux, authroutes.Config{Passkeys: pk, Passwords: pw, TOTP: twoFactor, Recovery: codes})
```

Email and password sign-in is on unless you turn it off: `Mount` panics unless exactly one of `Config.Passwords` and `Config.PasskeyOnly` is set. To serve passkeys only, set `PasskeyOnly: true`. `Config.NewUser` creates the account row for a passkey sign-up and returns its ID; store that ID in your user row, for example as its primary key, because every session's `Principal.User` is that ID. `Config.Scopes` gives new sessions their scopes. The sections below show what the routes do, for apps that write their own.
