Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/bin/relay/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ evaluated or refused: nothing is ignored, and no two are combined.
| a JWT and a certificate | never requested | refused |

A JWT is verified against `--key FILE`, `--key-dir DIR`, or `--key-set FILE`
(by `kid`, read per request so rotation needs no restart) and authorized at the
(by `kid`, re-read when the file changes so rotation needs no restart) and authorized at the
dialed path, as in [Path matching](#path-matching). A bad token is refused; it
never falls through to the anonymous rules. A JWT presented with a certificate
is refused too, because neither can safely win, so a peer presents
Expand Down
7 changes: 7 additions & 0 deletions js/auth/MIGRATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ How to update your code for each breaking change, newest first.

## Unreleased

### Times and key sets parse strictly, as `moq-auth` does

`ClaimsSchema` refuses an `exp`, `iat`, or `nbf`, and `GrantSchema` an `expires`, below 0
or above 18446744073. `KeySet.parse` refuses two keys sharing a `kid`, and `ScopeSchema`
a root `Key.sign` would refuse, such as `/demo`; give each key its own `kid` and spell
scope roots without boundary slashes.

### Multi-prime RSA JWKs are refused (#6898)

`Key.parse` rejects an RSA JWK containing `oth` instead of discarding it.
Expand Down
17 changes: 12 additions & 5 deletions js/auth/src/claims.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { Pattern, Patterns } from "@moq/pattern";
import * as z from "zod/mini";
import * as Path from "./path.ts";
import { decodeGrants, decodeRoles, PatternListSchema, WireRoleSchema } from "./wire.ts";
import { decodeGrants, decodeRoles, PatternListSchema, UnixSecondsSchema, WireRoleSchema } from "./wire.ts";

export { PatternListSchema } from "./wire.ts";

Expand All @@ -32,7 +32,7 @@ const ScopeFields = {
* `root` is optional on the wire to match the Rust `moq-auth` crate, which omits it
* when the scope sits at the top level. A legacy `put`/`get` prefix scope reads as the
* subtree patterns it meant. A scope bounds paths, never bitrate, so a capped role is
* refused. Any other field is refused.
* refused, as is a root `Key.sign` would refuse. Any other field is refused.
*/
export const ScopeSchema = z
.pipe(
Expand All @@ -47,6 +47,13 @@ export const ScopeSchema = z
z.refine((data) => (data.publish?.length ?? 0) > 0 || (data.subscribe?.length ?? 0) > 0, {
message: "Either publish or subscribe must contain at least one pattern",
}),
z.superRefine((data, ctx) => {
try {
Path.validate(data.root);
} catch (error) {
ctx.addIssue({ code: "custom", message: error instanceof Error ? error.message : String(error) });
}
}),
);

/** A value parsed by {@link ScopeSchema}. */
Expand All @@ -59,11 +66,11 @@ const ClaimsFields = {
/** Patterns the holder may subscribe to, relative to `root`, optionally with a bitrate cap. */
subscribe: z.optional(WireRoleSchema),
/** Expiration time, as a whole unix timestamp in seconds. */
exp: z.optional(z.int()),
exp: z.optional(UnixSecondsSchema),
/** Issued-at time, as a whole unix timestamp in seconds. */
iat: z.optional(z.int()),
iat: z.optional(UnixSecondsSchema),
/** Not-before time, as a whole unix timestamp in seconds. Enforced by verification. */
nbf: z.optional(z.int()),
nbf: z.optional(UnixSecondsSchema),
};

// Registered claims that narrow nothing: an issuer's bookkeeping, read and dropped.
Expand Down
3 changes: 0 additions & 3 deletions js/auth/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { base64url } from "jose";
import type { Algorithm } from "./algorithm.ts";
import { authorize, ClaimsSchema, type Scope, ScopeSchema } from "./claims.ts";
import { Key } from "./key.ts";
import * as Path from "./path.ts";
import { encodeGrants } from "./wire.ts";

const program = new Command();
Expand Down Expand Up @@ -36,8 +35,6 @@ program
...(options.publish && { publish: options.publish }),
...(options.subscribe && { subscribe: options.subscribe }),
});
// A scope root `Key.sign` would refuse could never sign anything beneath it.
Path.validate(scope.root);
key = { ...key, scope };
}

Expand Down
4 changes: 2 additions & 2 deletions js/auth/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import { Pattern } from "@moq/pattern";
import * as z from "zod/mini";
import { decodeRoles, encodeRoles, WireRoleSchema } from "./wire.ts";
import { decodeRoles, encodeRoles, UnixSecondsSchema, WireRoleSchema } from "./wire.ts";

const PathSchema = z.string().check(
z.refine(
Expand Down Expand Up @@ -195,7 +195,7 @@ export const GrantSchema = z
/** Subtrees read from elsewhere: each path, relative to the root, resolves at the absolute path it maps to. Read-only. */
mounts: z.optional(z.record(z.string(), z.string())),
/** When the session closes, as whole unix seconds. */
expires: z.optional(z.int()),
expires: z.optional(UnixSecondsSchema),
/** How long until the relay asks again, in whole seconds. Zero would be a tight loop. */
revalidate: z.optional(z.int().check(z.positive())),
/** The stats tier this session's traffic is bucketed under: `/`-joined segments of ASCII letters, digits, `.`, `_`, and `-`. */
Expand Down
72 changes: 72 additions & 0 deletions js/auth/src/corpus.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Replays rs/moq-auth/tests/corpus.json, which the Rust crate replays too, so the two
// parsers cannot disagree on a token, key, key set, or grant without both failing.
import { describe, expect, test } from "bun:test";
import * as jose from "jose";
import { type Claims, patterns } from "./claims.ts";
import { GrantSchema } from "./contract.ts";
import { Key } from "./key.ts";
import { KeySet } from "./set.ts";

type Case = { name: string; jwk?: unknown; jwks?: unknown; grant?: unknown; valid: boolean };

const corpus = (await Bun.file(new URL("../../../rs/moq-auth/tests/corpus.json", import.meta.url)).json()) as {
keys: Record<string, unknown>;
tokens: { name: string; key: string; token?: string; payload?: jose.JWTPayload; claims: unknown }[];
jwk: Case[];
sets: Case[];
grants: Case[];
};

// The claims as the corpus writes them: patterns reduced, absent roles empty, and rates
// and times only when present.
function canonical(claims: Claims): unknown {
return {
root: claims.root,
publish: patterns(claims.publish).toJSON(),
subscribe: patterns(claims.subscribe).toJSON(),
...(claims.publish_rate !== undefined && { publish_rate: claims.publish_rate }),
...(claims.subscribe_rate !== undefined && { subscribe_rate: claims.subscribe_rate }),
...(claims.exp !== undefined && { exp: claims.exp }),
...(claims.iat !== undefined && { iat: claims.iat }),
...(claims.nbf !== undefined && { nbf: claims.nbf }),
};
}

describe("tokens", () => {
for (const c of corpus.tokens) {
test(c.name, async () => {
const key = Key.parse(JSON.stringify(corpus.keys[c.key]));
if ((c.token === undefined) === (c.payload === undefined))
throw new Error("give exactly one of token or payload");
// Sign the raw payload, bypassing `Key.sign`'s own checks, so verification sees it as written.
const token =
c.token ??
(await new jose.SignJWT(c.payload)
.setProtectedHeader({ alg: key.alg, ...(key.kid && { kid: key.kid }) })
.sign(await jose.importJWK(key as jose.JWK, key.alg)));
const verified = Key.verify(key as Parameters<typeof Key.verify>[0], token);
if (c.claims === null) {
await expect(verified).rejects.toThrow();
} else {
expect(canonical(await verified)).toEqual(c.claims);
}
});
}
});

const sections: [string, Case[], (input: unknown) => unknown][] = [
["jwk", corpus.jwk, (jwk) => Key.parse(JSON.stringify(jwk))],
["sets", corpus.sets, (jwks) => KeySet.parse(JSON.stringify(jwks))],
["grants", corpus.grants, (grant) => GrantSchema.parse(grant)],
];
for (const [section, cases, parse] of sections) {
describe(section, () => {
for (const c of cases) {
test(c.name, () => {
const run = () => parse(c.jwk ?? c.jwks ?? c.grant);
if (c.valid) run();
else expect(run).toThrow();
});
}
});
}
Loading
Loading