Skip to content
Merged
22 changes: 19 additions & 3 deletions doc/bin/relay/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,9 +223,25 @@ everything. Put application data somewhere other than the token.
Tokens and key scopes from the older `moq-token` format still work: each `put`
and `get` prefix `p` reads as the subtree `p/**`.

Roles are pattern arrays. Object roles, including bitrate caps such as
`{"path":["alice/**"],"rate":8000000}`, are refused in full by token and
auth-server grant parsing. No transport currently enforces bitrate caps.
### Bitrate caps

A role may cap its bitrate, in bits per second, by naming its patterns as
`{"path":["alice/**"],"rate":8000000}` in a token or an auth-server grant. A
`publish` cap bounds what the session sends the relay, and a `subscribe` cap
what the relay sends it, QUIC overhead and retransmissions included. Each
averages over a second, with one second of the rate as a burst. Older relays
refuse a capped role rather than drop the cap.

Only QUIC and WebTransport on the tokio or io\_uring listener enforce caps.
WebSocket, iroh, and HTTP `/fetch` and `/announced` refuse a capped grant,
whether it arrives at connect, in band, or at revalidation. When in-band tokens
add grants to one session, each direction takes the highest cap among them, and
a grant giving that direction paths without a cap lifts it. A cap changed at
revalidation applies to the live session.

Every QUIC session starts with only the flow-control credit its SETUP needs, so
a client cannot bank the full `[quic] receive_window` before its cap applies;
the relay opens the window once it admits the session.

### Path matching

Expand Down
8 changes: 5 additions & 3 deletions doc/lib/js/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ checks a connection path against a token's claims exactly as `moq auth serve`
does. A grant can label its session's stats independently of its authorization
root. Tokens are interchangeable with the Rust side. Grants and claims are
[`Pattern`](https://www.npmjs.com/package/@moq/pattern) unions: `foo` is one
broadcast, `foo/**` is a subtree, `**` is everything. Parsed claim and grant roles are
pattern string arrays; `authorize` returns reduced `Patterns` for each role.
Object roles, including bitrate caps, are refused during parsing.
broadcast, `foo/**` is a subtree, `**` is everything. A claim or grant role may
also carry a bitrate cap, parsed into `publish_rate` or `subscribe_rate` beside
the pattern arrays; key scopes bound paths only, and `authorize` checks paths
only. Answer a capped grant with `encodeGrant`, which writes the cap where the
relay reads it.

```bash
bun add @moq/auth
Expand Down
4 changes: 2 additions & 2 deletions doc/lib/rs/moq-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ Everything a party needs to ask for or answer an authorization on
answers the relay, in a service that mints tokens for clients, or in your own
accept loop that decides in process.

- **Request and grant.** `Request` is the JSON a relay POSTs on each session event (`connect`, `revalidate`, `end`), carrying everything it knows about the session. `Grant` is the answer: publish and subscribe [`Pattern`](https://docs.rs/moq-pattern) unions, an expiry, a revalidation cadence, optional stats tier and label, and whether the session is a cluster peer or an [upstream link](/bin/relay/cluster#upstream-links). `Grant::validate` checks the grant contract; the accept loop must enforce its caps or refuse it. Expiry is exact, with no allowance for clock skew.
- **Request and grant.** `Request` is the JSON a relay POSTs on each session event (`connect`, `revalidate`, `end`), carrying everything it knows about the session. `Grant` is the answer: publish and subscribe [`Pattern`](https://docs.rs/moq-pattern) unions with optional [bitrate caps](/bin/relay/auth#bitrate-caps) (`publish_rate`, `subscribe_rate`), an expiry, a revalidation cadence, optional stats tier and label, and whether the session is a cluster peer or an [upstream link](/bin/relay/cluster#upstream-links). `Grant::validate` checks the grant contract; the accept loop must enforce its caps or refuse it. Expiry is exact, with no allowance for clock skew.
- **Lease.** `lease::Producer` and `lease::Consumer` are the handle a session holds for its grant: read it, wait for a change, revoke it, and learn why it ended. Whoever runs the accept loop builds the producer, so an embedder can decide in process with no HTTP.
- **Refusals.** `Refusal` carries a `refusal::Reason` (`Refused`, `Forbidden`, or `Expired`) and optional `root` and `tier`. An auth server returns it as JSON with HTTP 403; `Client` returns `Error::Refused(refusal)`. Legacy plain-text 401/403 bodies and unknown reason strings read as `Refused`. Set `root` only from a verified credential, never the dialed path. Embedded relay deciders pass the same shape in `auth::Error::Refused`.
- **Client.** `Client` drives a lease against an auth server over `https://`, `unix://`, or loopback `http://`. It revalidates on cadence and retries through an outage until the grant expires, revokes on a 401, 403, or invalid grant, and reports `end` with the session's byte totals.
- **Server** (feature `serve`). `serve::Server` is the reference auth server behind `moq auth serve`: JWTs from the query or the moq-transport SETUP token, certificate grants, anonymous rules, tiers, and session caps. `Server::router` mounts it in your own axum service.
- **Mesh enrollment.** `mesh` holds the [enrollment contract](/bin/relay/auth#mesh-enrollment): a device proves its Ed25519 endpoint key against a fresh challenge and receives relay URLs and a scoped token. `mesh::Client` (feature `client`) enrolls with an enrollment key and renews before expiry; `mesh::Coordinator` (feature `serve`) answers it.
- **Keys and claims.** Generate HMAC, RSA, ECDSA, or EdDSA keys as JWKs, sign `Claims` (`root`, `publish`, `subscribe`, `exp`), and verify them. `Claims::authorize(path)` scopes verified claims to the path a client dialed, exactly as `moq auth serve` does. Roles hold path pattern unions directly.
- **Keys and claims.** Generate HMAC, RSA, ECDSA, or EdDSA keys as JWKs, sign `Claims` (`root`, `publish`, `subscribe`, their optional `Rate` caps, `exp`), and verify them. `Claims::authorize(path)` scopes verified claims to the path a client dialed, exactly as `moq auth serve` does. Roles hold path pattern unions directly.

```bash
cargo add moq-auth
Expand Down
12 changes: 8 additions & 4 deletions js/auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ contract, the relay flags, and worked examples, see the
[Authentication Documentation](../../doc/bin/relay/auth.md).

Grants and claims name paths with patterns from `@moq/pattern`: `foo` is one
broadcast, `foo/**` is a subtree, `**` is everything.
broadcast, `foo/**` is a subtree, `**` is everything. A role may also carry a
bitrate cap, written `{"path": [...], "rate": bps}` and parsed into
`publish_rate` or `subscribe_rate` beside the patterns.

## Installation

Expand Down Expand Up @@ -105,13 +107,15 @@ moq-auth verify --key root.jwk --in alice.jwt

### Answering a relay

A server implementing the contract validates what the relay sends and answers a grant:
A server implementing the contract validates what the relay sends and answers a grant.
`encodeGrant` writes a cap into its role, where the relay reads it:

```typescript
import { type Grant, GrantSchema, RequestSchema } from "@moq/auth";
import { encodeGrant, type Grant, RequestSchema } from "@moq/auth";

const request = RequestSchema.parse(await body.json());
const grant: Grant = GrantSchema.parse({ subscribe: ["**"], expires: 4102444800, revalidate: 60 });
const grant: Grant = { subscribe: ["**"], subscribe_rate: 8_000_000, expires: 4102444800, revalidate: 60 };
return Response.json(encodeGrant(grant));
```

### Working example
Expand Down
179 changes: 127 additions & 52 deletions js/auth/api/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,51 +61,116 @@ export const ClaimsSchema: ZodMiniPipe<ZodMiniObject<{
iss: ZodMiniOptional<ZodMiniUnknown>;
jti: ZodMiniOptional<ZodMiniUnknown>;
nbf: ZodMiniOptional<ZodMiniInt>;
publish: ZodMiniOptional<ZodMiniArray<ZodMiniString<string>>>;
publish: ZodMiniOptional<ZodMiniUnion<readonly [ZodMiniArray<ZodMiniString<string>>, ZodMiniObject<{
path: ZodMiniArray<ZodMiniString<string>>;
rate: ZodMiniNumber<number>;
}, $strict>]>>;
put: ZodMiniOptional<ZodMiniUnion<readonly [ZodMiniString<string>, ZodMiniArray<ZodMiniString<string>>]>>;
root: ZodMiniDefault<ZodMiniString<string>>;
sub: ZodMiniOptional<ZodMiniUnknown>;
subscribe: ZodMiniOptional<ZodMiniArray<ZodMiniString<string>>>;
}, $strict>, ZodMiniTransform<Omit<{
subscribe: ZodMiniOptional<ZodMiniUnion<readonly [ZodMiniArray<ZodMiniString<string>>, ZodMiniObject<{
path: ZodMiniArray<ZodMiniString<string>>;
rate: ZodMiniNumber<number>;
}, $strict>]>>;
}, $strict>, ZodMiniTransform<Omit<Omit<{
exp?: number | undefined;
get?: string | string[] | undefined;
iat?: number | undefined;
nbf?: number | undefined;
publish?: string[] | undefined;
publish?: string[] | {
path: string[];
rate: number;
} | undefined;
put?: string | string[] | undefined;
root: string;
subscribe?: string[] | undefined;
}, "get" | "put"> & {
subscribe?: string[] | {
path: string[];
rate: number;
} | undefined;
}, "get" | "put">, "publish" | "subscribe"> & {
publish?: string[];
publish_rate?: number;
subscribe?: string[];
subscribe_rate?: number;
}, {
exp?: number | undefined;
get?: string | string[] | undefined;
iat?: number | undefined;
iss?: unknown;
jti?: unknown;
nbf?: number | undefined;
publish?: string[] | undefined;
publish?: string[] | {
path: string[];
rate: number;
} | undefined;
put?: string | string[] | undefined;
root: string;
sub?: unknown;
subscribe?: string[] | undefined;
subscribe?: string[] | {
path: string[];
rate: number;
} | undefined;
}>>;

export type Grant = infer<typeof GrantSchema>;

export const GrantSchema: ZodMiniObject<{
export const GrantSchema: ZodMiniPipe<ZodMiniObject<{
expires: ZodMiniOptional<ZodMiniInt>;
label: ZodMiniOptional<ZodMiniString<string>>;
mounts: ZodMiniOptional<ZodMiniRecord<ZodMiniString<string>, ZodMiniString<string>>>;
peer: ZodMiniOptional<ZodMiniBoolean<boolean>>;
publish: ZodMiniOptional<ZodMiniArray<ZodMiniString<string>>>;
publish: ZodMiniOptional<ZodMiniUnion<readonly [ZodMiniArray<ZodMiniString<string>>, ZodMiniObject<{
path: ZodMiniArray<ZodMiniString<string>>;
rate: ZodMiniNumber<number>;
}, $strict>]>>;
revalidate: ZodMiniOptional<ZodMiniInt>;
root: ZodMiniOptional<ZodMiniString<string>>;
subscribe: ZodMiniOptional<ZodMiniArray<ZodMiniString<string>>>;
subscribe: ZodMiniOptional<ZodMiniUnion<readonly [ZodMiniArray<ZodMiniString<string>>, ZodMiniObject<{
path: ZodMiniArray<ZodMiniString<string>>;
rate: ZodMiniNumber<number>;
}, $strict>]>>;
tier: ZodMiniOptional<ZodMiniString<string>>;
upstream: ZodMiniOptional<ZodMiniBoolean<boolean>>;
}, $strip>;
}, $strip>, ZodMiniTransform<Omit<{
expires?: number | undefined;
label?: string | undefined;
mounts?: Record<string, string> | undefined;
peer?: boolean | undefined;
publish?: string[] | {
path: string[];
rate: number;
} | undefined;
revalidate?: number | undefined;
root?: string | undefined;
subscribe?: string[] | {
path: string[];
rate: number;
} | undefined;
tier?: string | undefined;
upstream?: boolean | undefined;
}, "publish" | "subscribe"> & {
publish?: string[];
publish_rate?: number;
subscribe?: string[];
subscribe_rate?: number;
}, {
expires?: number | undefined;
label?: string | undefined;
mounts?: Record<string, string> | undefined;
peer?: boolean | undefined;
publish?: string[] | {
path: string[];
rate: number;
} | undefined;
revalidate?: number | undefined;
root?: string | undefined;
subscribe?: string[] | {
path: string[];
rate: number;
} | undefined;
tier?: string | undefined;
upstream?: boolean | undefined;
}>>;

export { InvalidPattern } from "@moq/pattern";

Expand All @@ -120,11 +185,20 @@ export const Key: {
iss?: unknown;
jti?: unknown;
nbf?: number;
publish?: string[];
publish?: string[] | {
path: string[];
rate: number;
};
put?: string | string[];
root?: string;
sub?: unknown;
subscribe?: string[];
subscribe?: string[] | {
path: string[];
rate: number;
};
} & {
publish_rate?: number;
subscribe_rate?: number;
}) => Promise<string>;
verify: (key: PublicKey | SymmetricKey, token: string) => Promise<Claims>;
};
Expand Down Expand Up @@ -171,10 +245,7 @@ export const KeySchema: ZodMiniDiscriminatedUnion<[ZodMiniObject<{
put?: string[] | undefined;
root: string;
subscribe?: string[] | undefined;
}, "get" | "put"> & {
publish?: string[];
subscribe?: string[];
}, {
}, "get" | "put">, {
get?: string[] | undefined;
publish?: string[] | undefined;
put?: string[] | undefined;
Expand Down Expand Up @@ -225,10 +296,7 @@ export const KeySchema: ZodMiniDiscriminatedUnion<[ZodMiniObject<{
put?: string[] | undefined;
root: string;
subscribe?: string[] | undefined;
}, "get" | "put"> & {
publish?: string[];
subscribe?: string[];
}, {
}, "get" | "put">, {
get?: string[] | undefined;
publish?: string[] | undefined;
put?: string[] | undefined;
Expand Down Expand Up @@ -275,10 +343,7 @@ export const KeySchema: ZodMiniDiscriminatedUnion<[ZodMiniObject<{
put?: string[] | undefined;
root: string;
subscribe?: string[] | undefined;
}, "get" | "put"> & {
publish?: string[];
subscribe?: string[];
}, {
}, "get" | "put">, {
get?: string[] | undefined;
publish?: string[] | undefined;
put?: string[] | undefined;
Expand Down Expand Up @@ -324,10 +389,7 @@ export const KeySchema: ZodMiniDiscriminatedUnion<[ZodMiniObject<{
put?: string[] | undefined;
root: string;
subscribe?: string[] | undefined;
}, "get" | "put"> & {
publish?: string[];
subscribe?: string[];
}, {
}, "get" | "put">, {
get?: string[] | undefined;
publish?: string[] | undefined;
put?: string[] | undefined;
Expand All @@ -348,11 +410,20 @@ export const KeySet: {
iss?: unknown;
jti?: unknown;
nbf?: number;
publish?: string[];
publish?: string[] | {
path: string[];
rate: number;
};
put?: string | string[];
root?: string;
sub?: unknown;
subscribe?: string[];
subscribe?: string[] | {
path: string[];
rate: number;
};
} & {
publish_rate?: number;
subscribe_rate?: number;
}) => Promise<string>;
verify: (set: KeySet, token: string) => Promise<Claims>;
};
Expand Down Expand Up @@ -396,10 +467,7 @@ export const KeySetSchema: ZodMiniObject<{
put?: string[] | undefined;
root: string;
subscribe?: string[] | undefined;
}, "get" | "put"> & {
publish?: string[];
subscribe?: string[];
}, {
}, "get" | "put">, {
get?: string[] | undefined;
publish?: string[] | undefined;
put?: string[] | undefined;
Expand Down Expand Up @@ -450,10 +518,7 @@ export const KeySetSchema: ZodMiniObject<{
put?: string[] | undefined;
root: string;
subscribe?: string[] | undefined;
}, "get" | "put"> & {
publish?: string[];
subscribe?: string[];
}, {
}, "get" | "put">, {
get?: string[] | undefined;
publish?: string[] | undefined;
put?: string[] | undefined;
Expand Down Expand Up @@ -500,10 +565,7 @@ export const KeySetSchema: ZodMiniObject<{
put?: string[] | undefined;
root: string;
subscribe?: string[] | undefined;
}, "get" | "put"> & {
publish?: string[];
subscribe?: string[];
}, {
}, "get" | "put">, {
get?: string[] | undefined;
publish?: string[] | undefined;
put?: string[] | undefined;
Expand Down Expand Up @@ -549,10 +611,7 @@ export const KeySetSchema: ZodMiniObject<{
put?: string[] | undefined;
root: string;
subscribe?: string[] | undefined;
}, "get" | "put"> & {
publish?: string[];
subscribe?: string[];
}, {
}, "get" | "put">, {
get?: string[] | undefined;
publish?: string[] | undefined;
put?: string[] | undefined;
Expand Down Expand Up @@ -756,10 +815,7 @@ export const ScopeSchema: ZodMiniPipe<ZodMiniObject<{
put?: string[] | undefined;
root: string;
subscribe?: string[] | undefined;
}, "get" | "put"> & {
publish?: string[];
subscribe?: string[];
}, {
}, "get" | "put">, {
get?: string[] | undefined;
publish?: string[] | undefined;
put?: string[] | undefined;
Expand Down Expand Up @@ -802,6 +858,25 @@ export function authorize(claims: Claims, path: string): Permissions;

export { compareSpecificity } from "@moq/pattern";

export function encodeGrant(grant: Grant): {
expires?: number;
label?: string;
mounts?: Record<string, string>;
peer?: boolean;
publish?: string[] | {
path: string[];
rate: number;
};
revalidate?: number;
root?: string;
subscribe?: string[] | {
path: string[];
rate: number;
};
tier?: string;
upstream?: boolean;
};

export function patterns(texts: readonly string[] | undefined): Patterns;

export function scopeAllows(scope: Scope, claims: Claims): boolean;
Expand Down
Loading