Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

The ecosystem · packages/guard

Rate limits, feature flags and guards, as middleware

Guard protects an app's routes: 5 login tries a minute from each address, a new checkout for staff first and then a quarter of everyone, security headers on every answer, and maintenance mode for the whole site. Each guard is middleware that decides in plain Roc, so the tables on this page are the package's own answers, worked out when the site was built.

Installing it#

Name the package in your app's header (main.roc): guard: "../packages/guard/main.roc". Its middleware needs the server platform; the browser's half sees only the modules that need no platform (the logic, and the <Flagged> component).

A first guard#

A guard goes in the middleware of the directory it guards: routes/+middleware.roc runs around every request, a directory's +middleware.roc around the routes in and below it. Here every answer gets security headers, a body over a megabyte is refused, the site can go into maintenance, /api is limited per user, and the login route per address:

packages/guard/example/Middlewares.roc
import pf.Middleware
import pf.Server
import guard.RateLimit
import guard.Security
import guard.Guard
import Features

Middlewares := [].{

	Context : { facts : Str, user : Str }

	## Every request (routes/+middleware.roc): who is signed in, then the guards.
	default : Middleware({ facts : Str }, Context)
	default =
		signed_in
			.then(Guard.security_headers(Security.defaults))
			.then(Guard.body_limit(1_000_000))
			.then(Guard.maintenance({ flag: Features.maintenance, message: "Back soon.", retry_after_s: 600, except: ["/admin"] }))

	## 5 a minute from each client, behind one proxy.
	login_limit : Middleware(Context, Context)
	login_limit = Guard.rate_limit("login", RateLimit.per_minute(5), Guard.ip(Hops(1)))

	## 100 a minute for each user, or each address when signed out (routes/api/+middleware.roc).
	api_limit : Middleware(Context, Context)
	api_limit = Guard.rate_limit("api", RateLimit.per_minute(100), Guard.user(|context| context.user, Hops(1)))

	## Only for those with the new checkout on.
	beta : Middleware(Context, Context)
	beta = Guard.feature(Features.new_checkout, |context| { user: context.user, groups: [] })

	## Only for the app's admins (ada): anyone else is answered 403.
	admins : Middleware(Context, Context)
	admins = Middleware.make(|request, context, next!| if (context.user == "ada") next!(request, context) else Server.refused(403, "Admins only."))
}

## Who is signed in: the `user` cookie, handed on as `context.user`. A stand-in for the app's own
## sign-in: the cookie isn't signed, so anyone can claim any name. A real app reads its session.
signed_in : Middleware({ facts : Str }, Middlewares.Context)
signed_in = Middleware.make(|request, context, next!| next!(request, { facts: context.facts, user: Server.cookie(request, "user") ?? "" }))
packages/guard/example/routes/api/+middleware.roc
import ../../Middlewares

## The API: 100 requests a minute for each user.
middleware = Middlewares.api_limit
packages/guard/example/routes/login/+middleware.roc
import ../../Middlewares

## 5 tries a minute from each client.
middleware = Middlewares.login_limit

The sixth try in a minute gets 429 Too Many Requests, with Retry-After and the RateLimit-* headers. Every guard hands on its context unchanged, so guards go anywhere in a chain. The code is from packages/guard/example/, a whole app its tests ask over HTTP.

Rate limits#

A limit says how many requests a client may send, in how long. RateLimit.per_minute(5) is a token bucket: 5 at once, then one every 12 seconds. .sliding() counts a sliding window instead: never more than 5 in any minute. Both are plain functions: a client's state and the time go in; whether the request may go on, and the client's next state, come out.

site/Demos/GuardLimits.rocx
## A login form's limit: 5 at once, then one every 12 seconds.
login : RateLimit
login = RateLimit.per_minute(5)

## The same 5 a minute, never more in any minute.
strict : RateLimit
strict = RateLimit.per_minute(5).sliding()

## What each request is answered, each checked as the one before it left the limit.
answers : RateLimit, List(U64) -> List(Str)
answers = |policy, seconds| {
	var $state = policy.fresh(0)
	var $said = []
	for second in seconds {
		{ decision, state } = policy.check($state, second * 1000)
		$state = state
		$said = $said.append(answer(policy, decision))
	}
	$said
}

The same eleven requests under each limit, as RateLimit.check answered them when this page was built (the clock is a list of seconds, as in the package's tests):

SecondToken bucketSliding window
0 200, 4 left 200, 4 left
1 200, 3 left 200, 3 left
2 200, 2 left 200, 2 left
3 200, 1 left 200, 1 left
4 200, 0 left 200, 0 left
5 429, Retry-After: 7 429, Retry-After: 67
12 200, 0 left 429, Retry-After: 60
13 429, Retry-After: 11 429, Retry-After: 59
24 200, 0 left 429, Retry-After: 48
60 200, 2 left 429, Retry-After: 12
72 200, 2 left 200, 0 left

In the bucket, a refused request costs nothing, so hammering doesn't delay the next allowed one. The sliding window refuses everything after the fifth until the five weigh less: its count is this minute's requests plus last minute's, weighted by how much of last minute the window still covers. So it keeps two numbers per client, however high the limit.

Try a limit#

The same RateLimit.check, in your browser, with a clock you move by hand. Nothing is sent: each line is what the middleware would answer.

Second 0 · 5 a minute

The demo: site/Demos/GuardPlayground.rocx
site/Demos/GuardPlayground.rocx
import pf.Html
import pf.Solid exposing [create_signal!]
import guard.RateLimit

## A login form's limit, 5 a minute, run in the browser by the package's own `RateLimit.check`, with
## a clock moved by hand: send requests, wait, and see what the server's middleware would answer.
## Nothing is sent anywhere. Switching between a token bucket and a sliding window starts again.
GuardPlayground := [].{

	Answer : { id : U64, second : U64, allowed : Bool, text : Str }

	view! : {} => Html
	view! = |{}| {
		(sliding!, set_sliding!) = create_signal!(Bool.False)
		(now!, set_now!) = create_signal!(0)
		(kept!, set_kept!) = create_signal!(nothing)
		(said!, set_said!) = create_signal!(none)
		send! = || {
			limit = policy(sliding!())
			at = now!()
			{ decision, state } = limit.check(kept!() ?? limit.fresh(at), at)
			set_kept!(Ok(state))
			id =
				match said!().first() {
					Ok(last) => last.id + 1
					Err(_) => 0
				}
			set_said!([{ id, second: at // 1000, allowed: decision.allowed, text: answer(limit, decision) }].concat(said!()).take_first(6))
		}
		wait! = |seconds| set_now!(now!() + seconds * 1000)
		start! = |sliding| {
			set_sliding!(sliding)
			set_now!(0)
			set_kept!(nothing)
			set_said!(none)
		}
		<div class="playground">
			<div class="kinds" role="group" aria-label="How the limit counts">
				<button type="button" aria-pressed={if (sliding!()) "false" else "true"} on:click={|| start!(Bool.False)}>Token bucket</button>
				<button type="button" aria-pressed={if (sliding!()) "true" else "false"} on:click={|| start!(Bool.True)}>Sliding window</button>
			</div>
			<div class="actions">
				<button type="button" class="send" on:click={send!}>Send a request</button>
				<button type="button" on:click={|| wait!(1)}>Wait 1 s</button>
				<button type="button" on:click={|| wait!(12)}>Wait 12 s</button>
				<button type="button" on:click={|| wait!(60)}>Wait a minute</button>
			</div>
			<p class="clock">Second <output>{(now!() // 1000).to_str()}</output> · 5 a minute</p>
			<ol class="answers" aria-live="polite">
				{...said!().map(|each|
					<li key={each.id} class:refused={!each.allowed}>
						<span class="at">{"Second ${each.second.to_str()}"}</span>
						<span>{each.text}</span>
					</li>
				)}
			</ol>
		</div>
	}

	<style>
		.playground {
			display: grid;
			gap: var(--space-3);
		}

		.kinds,
		.actions {
			display: flex;
			flex-wrap: wrap;
			gap: var(--space-2);
		}

		button {
			padding: var(--space-1) var(--space-3);
			font-size: var(--size-sm);
		}

		.kinds button[aria-pressed="true"],
		.send {
			background: var(--accent-soft);
			color: var(--accent);
		}

		.clock {
			margin: 0;
			color: var(--text-muted);
			font-size: var(--size-sm);
		}

		.answers {
			display: grid;
			gap: var(--space-1);
			min-height: 9.5rem;
			margin: 0;
			padding: 0;
			list-style: none;
			font-family: var(--mono);
			font-size: var(--size-sm);
		}

		.answers:not(:has(li))::before {
			content: "No requests yet.";
			color: var(--text-muted);
		}

		li {
			display: flex;
			flex-wrap: wrap;
			gap: var(--space-3);
			padding: var(--space-1) var(--space-2);
			border-radius: var(--radius-sm);
			background: var(--good-soft);
		}

		li.refused {
			background: var(--bad-soft);
		}

		.at {
			color: var(--text-muted);
		}
	</style>
}

## The limit: 5 a minute, as a token bucket or a sliding window.
policy : Bool -> RateLimit
policy = |sliding| if (sliding) RateLimit.per_minute(5).sliding() else RateLimit.per_minute(5)

## What the server's middleware answers: its status, and the header a client reads.
answer : RateLimit, RateLimit.Decision -> Str
answer = |limit, decision| {
	headers = RateLimit.headers(limit, decision)
	header = |name|
		match headers.find_first(|each| each.name == name) {
			Ok(found) => found.value
			Err(_) => "?"
		}
	if decision.allowed {
		"200 OK, RateLimit-Remaining: ${header("ratelimit-remaining")}"
	} else {
		"429 Too Many Requests, Retry-After: ${header("retry-after")}"
	}
}

## No state yet: the next request is the first.
nothing : Try(RateLimit.State, [Fresh])
nothing = Err(Fresh)

none : List(GuardPlayground.Answer)
none = []

Who is counted

Guard.rate_limit(name, limit, key) counts each key separately. The name keeps one limit's counts apart from another's ("login", "api"). The key says who a request counts as:

KeyCounts
Guard.ip(trust)each address, found as trust says; an IPv6 address by its first 64 bits, the block one household is given. Clients whose address can't be told (an X-Forwarded-For that isn't an address, where it is trusted) all count as one, unknown, so a made-up header doesn't make a client unlimited
Guard.user(|context| context.user, trust)each signed-in user, as the context names them; each address when signed out
Guard.routeeach method and path
Guard.both(key, key)each pair: Guard.both(Guard.ip(trust), Guard.route) is each address on each route
|request, context| …whatever your function says. A request whose key is "" isn't limited

What a client is told

An allowed answer carries RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset (seconds until the whole limit is back) and RateLimit-Policy (5;w=60: 5 in 60 seconds). A refusal is a 429 with those headers, Retry-After (seconds until one more is allowed) and a line of text. A form posted without the runtime goes back to its page with what was typed and a flash of the 429, shown where the form shows any refusal.

Memory stays bounded

Each limit keeps at most 10,000 clients (Guard.rate_limit_with takes another number). Clients whose limit is whole again are forgotten first, which changes nothing; past that, the client seen longest ago is forgotten and starts again. Each limit's clients are split into 64 tallies, so a request reads and writes about 150 of them at most.

The counts live in the server's memory (Kv), never in the database. A request reads its tally and swaps the next one in, reading again if another request changed it first, so no hit is lost. If a tally can't be changed after many tries, the request goes on and the log says why: a failing limiter shouldn't take the site down. A restart resets every limit.

Behind a proxy#

Most apps sit behind a proxy, which adds the address it saw to X-Forwarded-For. A client can write anything in that header too, so it is read only as far as the app says its own proxies wrote it. Take a request from 10.0.0.2, the app's proxy, whose X-Forwarded-For is 6.6.6.6, 198.51.100.4: the client wrote the first address, the proxy added the second. Who the client is, by each way to trust, as ClientIp.of worked it out when this page was built:

TrustThe client is
Direct 10.0.0.2
Header("x-real-ip") 198.51.100.4
Hops(1) 198.51.100.4
Hops(2) 6.6.6.6
Proxies(Ip.private) 198.51.100.4

Proxies(Ip.private) is right both with no proxy in front and behind one in the server's own network, so the app rocx new makes uses it. Hops(1) with no proxy in front believes the client, who could name a new address each time and never be limited.

Feature flags#

A flag is defined in code: its name, what it's for, and who has it on. A rule is on or off for everyone (off is a kill switch), plus the users and groups it lists, plus a share of everyone else signed in. A hash of the flag's name and the user's puts each user in or out of a rollout the same way every time, so raising the share only adds people. An environment can have its own rule.

site/Demos/GuardFlags.rocx
import guard.Flag
import guard.Flags

## On for ada, for anyone in staff, and for a quarter of everyone else who is signed in. In
## development, on for everyone.
new_checkout : Flag
new_checkout = Flag.define("new_checkout", "The one-page checkout", { ..Flags.rollout(25), users: ["ada"], groups: ["staff"] })
	.in_env("dev", Flags.on)

Who has it on, as Flags.is_on answered when this page was built. A user's bucket, 0 to 99, is that hash (Flags.bucket): a rollout of 25 takes those below 25.

WhoBucketIn productionIn development
ada, listed 88 on on
bea, in staff 84 on on
cy 35 off on
dee 27 off on
jo 8 on on
kai 87 off on
max 0 on on
signed out none off on

ada is listed and bea is in staff, so they have it whatever their bucket. A signed-out visitor has no id to hash, so a rollout reaches them only at 100. The environment is APP_ENV if set, else dev under --dev, else production.

Changed while the server runs

The code's rule is the default; an admin page can override it until it is reset. Overrides live in the server's memory (Kv), so a restart brings back the code's rules. To keep them across restarts and deploys, an app with a database lists FlagStore.plugin({}): each override is also a row of its table (guard_flags, for Postgres, SQLite and Turso), read back as the server starts. Only admins may set a rule: in the example, Middlewares.admins answers anyone else 403.

packages/guard/example/routes/admin/flags/+server.roc
import pf.Server
import pf.Endpoint
import guard.Flags
import guard.FlagStore
import ../../../Middlewares

## POST /admin/flags: a flag `on` or `off` for everyone, in place of the code's rule, or `reset`
## to the code's rule again. For admins only.
post! : { request : Server.Request, params : {}, context : Middlewares.Context, body : { name : Str, state : Str } } => Try(Str, Endpoint.Refusal)
post! = |{ body, .. }| {
	done =
		match body.state {
			"on" => FlagStore.set!(body.name, Flags.on)
			"off" => FlagStore.set!(body.name, Flags.off)
			_ => FlagStore.reset!(body.name)
		}
	match done {
		Ok({}) => Ok(body.state)
		Err(FlagErr(why)) => Err(Failed(why))
	}
}

On the server, FlagStore.is_on!(flag, { user, groups }) answers in an endpoint, and Guard.feature(flag, who) answers 404 to anyone without the flag, as if the route weren't there.

In a page

The server decides the visitor's flags once, in a GET endpoint the layout reads; a <Flagged> shows its children only when its flag is on. The flags travel in the rendered page, so the browser hydrates with the same values without asking again.

packages/guard/example/Visitor.rocx
import guard.Flags
import Generated/Api

## Who is visiting, as the server knows them.
Visitor := [].{

	## The app's flags, decided on the server for whoever is signed in: `GET /flags`
	## (`routes/flags/+server.roc`), which the server answers as it renders the page, and the page
	## carries, so the browser's first run reads the same values instead of asking again.
	flags! : {} => Flags.Values
	flags! = |{}| Api.get_flags({}).read!()
}
packages/guard/example/routes/+layout.rocx
import pf.Html
import pf.Context
import guard.Flagged
import ../Visitor

view! = |{ children, .. }|
	<html lang="en">
		<head>
			<meta charset="utf-8" />
			<title>guard</title>
		</head>
		<body>
			<FlagsContext value={Visitor.flags!({})}>
				<main>{...children}</main>
			</FlagsContext>
		</body>
	</html>
packages/guard/example/routes/+page.rocx
import pf.Html
import guard.Flagged

view! = |_|
	<section>
		<Flagged name="new_checkout" fallback={<p id="old">The old checkout</p>}>
			<p id="new">The new checkout</p>
		</Flagged>
	</section>

This site has no server, so below the flags are decided as the site is built. ada is listed for the new checkout; cy isn't, nor in the rollout's quarter:

The new checkout, for ada

The old checkout, for cy

site/Demos/GuardCheckout.rocx
import pf.Html
import pf.Context
import guard.Flags
import guard.Flagged
import GuardFlags

## The page a visitor gets, with the new checkout or the old: the flags decided for them, in the
## context `<Flagged>` reads. An app decides them on the server, in a GET endpoint the page reads
## (`FlagStore.values!`); here they are decided where the page is rendered, when the site is built.
GuardCheckout := [].{

	view! : { who : Flags.Who } => Html
	view! = |{ who }| {
		flags = Flags.values([GuardFlags.new_checkout], { env: "production", overrides: [] }, who)
		<FlagsContext value={flags}>
			<Flagged name="new_checkout" fallback={<p>The old checkout, for {who.user}</p>}>
				<p>The new checkout, for {who.user}</p>
			</Flagged>
		</FlagsContext>
	}
}
<Flagged> propIs
name : Strthe flag's name
fallback : Htmlwhat shows when the flag is off: nothing, unless given
childrenwhat shows when the flag is on

<FlagsContext value={…}> is a context that provides the flags to every <Flagged> under it (its file needs import pf.Context). Without one, every flag is off. Flags.enabled(values, name) reads one flag, where an if reads better.

Other guards#

GuardDoes
Guard.security_headers(Security.defaults)adds the headers below to every answer, but not those it sets itself
Guard.body_limit(bytes)refuses a larger body, 413
Guard.methods(["GET", "POST"])refuses any other method, 405, with Allow
Guard.hosts(["example.com", "*.example.com"])refuses any other Host, 400
Guard.ips({ allow, deny, trust })refuses an address in deny, or not in allow when it lists any, 403
Guard.maintenance({ flag, message, retry_after_s, except })while the flag is on, answers 503 with Retry-After and a small page, except under the paths in except (/admin, so you can turn it off again)
Guard.feature(flag, who)answers 404 to anyone who doesn't have the flag on
Guard.under("/api", guard)runs guard for paths under /api only

Security.defaults adds these headers to every answer, as Security.headers wrote them when this page was built:

Security.headers(Security.defaults, { dev: Bool.False })
content-security-policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'
strict-transport-security: max-age=31536000
x-content-type-options: nosniff
referrer-policy: strict-origin-when-cross-origin
x-frame-options: SAMEORIGIN
cross-origin-opener-policy: same-origin

The Content-Security-Policy fits a Roc Solid app: scripts and WebAssembly from the site's own origin (a page needs 'wasm-unsafe-eval' to start its wasm under a CSP), inline styles (components write style="…"), and calls to the site's own server. Security.directive changes one directive (to allow images from another host, say). Under --dev there is no Strict-Transport-Security, and the CSP only reports: a violation shows in the console instead of breaking the page. The dev server's reload script is the site's own file (/__reload.js), so it is no violation.

The modules#

The logic is plain Roc, on no platform, so the server, the browser and a test decide alike. roc test packages/guard/main.roc runs its expects.

ModuleWhat it does
RateLimita limit: per_second, per_minute, per_hour, per(n, window_ms), .sliding(); fresh, check(state, now), idle, headers, explain
Tallymany clients' states by key, bounded: Tally.hit(tally, limit, key, now, room); to_str, from_str, shard
ClientIpClientIp.of(trust, peer, headers), by Direct, Header(name), Hops(n) or Proxies(cidrs)
IpIPv4 and IPv6 addresses and ranges: parse, to_str, cidr, cidrs, within, within_any, key, private
Flaga flag in code: Flag.define(name, about, rule), .in_env(env, rule)
Flagsrules (on, off, rollout(percent), only(users, groups)), is_on, values, enabled, set and reset for overrides, describe for an admin page
Securitysecurity headers: defaults, directives, directive, csp, headers
Hasha small, stable hash of text, the same on every machine: of, and bucket, which puts a user in or out of a rollout and a client in a tally
Checkschecks on a request: methods, hosts, body_size, ips, maintenance

The server half: Guard holds the guards, FlagStore the flags while the server runs, and Kept the rate limits' tallies. Only the server compiles these three.

packages/guard/Guard.roc
Key(c) : Server.Request, c -> Str
rate_limit : Str, RateLimit, Key(c) -> Middleware(c, c)
rate_limit_with : { name : Str, policy : RateLimit, key : Key(c), max_keys : U64 } -> Middleware(c, c)
ip : ClientIp.Trust -> Key(c)
user : (c -> Str), ClientIp.Trust -> Key(c)
route : Key(c)
both : Key(c), Key(c) -> Key(c)
under : Str, Middleware(c, c) -> Middleware(c, c)
security_headers : Security.Config -> Middleware(c, c)
body_limit : U64 -> Middleware(c, c)
methods : List(Str) -> Middleware(c, c)
hosts : List(Str) -> Middleware(c, c)
ips : { allow : List(Ip.Cidr), deny : List(Ip.Cidr), trust : ClientIp.Trust } -> Middleware(c, c)
maintenance : { flag : Flag, message : Str, retry_after_s : U64, except : List(Str) } -> Middleware(c, c)
feature : Flag, (c -> Flags.Who) -> Middleware(c, c)
packages/guard/FlagStore.roc
env! : {} => Str
overrides! : {} => List(Flags.Override)
settings! : {} => Flags.Settings
is_on! : Flag, Flags.Who => Bool
values! : List(Flag), Flags.Who => Flags.Values
describe! : List(Flag) => List({ name : Str, about : Str, rule : Flag.Rule, code : Flag.Rule, overridden : Bool })
set! : Str, Flag.Rule => Try({}, [FlagErr(Str)])
reset! : Str => Try({}, [FlagErr(Str)])

The package's README has the whole API in one place.

Tested, and limits#

Every module is tested by its expects, and the middleware in packages/guard/example/, asked over HTTP. Its login limit answers 429 on the sixth try with the headers above, also to clients whose X-Forwarded-For isn't an address (they share one count). Its admin endpoint answers 403 to anyone but an admin. Flag overrides turn its feature route and maintenance mode on and off while it runs, and outlive a restart in its SQLite file.

The server reads a request's body, up to 16 MiB (or its --max-body), before any middleware runs, so Guard.body_limit refuses a large body after it has arrived, not before.