Skip to content
Open
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
3 changes: 2 additions & 1 deletion packages/http-message-sig/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Signatures for TypeScript.
| Ordinary field components | Yes |
| Structured Field dictionary member (`key`) | Yes, strict RFC 8941 parsing |
| Derived components | `@method`, `@target-uri`, `@authority`, `@scheme`, `@request-target`, `@path`, `@query`, `@status` |
| Query parameters (`@query-param`) | Yes, rejecting repeated names |
| Multiple signatures | Yes |
| Async signing and verification | Yes |
| Synchronous signing | Yes |
Expand Down Expand Up @@ -67,7 +68,7 @@ only after successful cryptographic verification.

## Limitations

- `sf`, `bs`, `tr`, `@query-param`, and unknown derived components are rejected
- `sf`, `bs`, `tr`, and unknown derived components are rejected
with `UnsupportedFeature`.
- RFC 9651 dates and display strings are rejected in signature fields. Signature
metadata is limited to RFC 8941 bare items.
Expand Down
58 changes: 46 additions & 12 deletions packages/http-message-sig/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const derivedComponents = new Set([
"@request-target",
"@path",
"@query",
"@query-param",
"@status",
]);
const unsupportedParameters = new Set(["sf", "bs", "tr"]);
Expand Down Expand Up @@ -195,12 +196,6 @@ function copyComponentParameters(
function normalizeComponentName(name: string): string {
const normalized = name.toLowerCase();
if (normalized.startsWith("@")) {
if (normalized === "@query-param") {
return fail(
SignatureErrorCode.UnsupportedFeature,
"@query-param is not supported"
);
}
if (!derivedComponents.has(normalized)) {
return fail(
SignatureErrorCode.UnsupportedFeature,
Expand Down Expand Up @@ -228,7 +223,7 @@ function validateComponent(value: ComponentDescriptor): void {
if (unsupportedParameters.has(name)) {
fail(SignatureErrorCode.UnsupportedFeature, `${name} is not supported`);
}
if (name !== "req" && name !== "key") {
if (name !== "req" && name !== "key" && name !== "name") {
fail(
SignatureErrorCode.UnsupportedFeature,
`Component parameter ${name} is not supported`
Expand All @@ -240,13 +235,25 @@ function validateComponent(value: ComponentDescriptor): void {
if (name === "key" && typeof parameterValue !== "string") {
fail(SignatureErrorCode.InvalidComponent, "key must be a string");
}
if (name === "name" && typeof parameterValue !== "string") {
fail(SignatureErrorCode.InvalidComponent, "name must be a string");
}
}
if (value.name.startsWith("@") && value.parameters.key !== undefined) {
fail(
SignatureErrorCode.InvalidComponent,
`key is invalid on derived component ${value.name}`
);
}
if (value.name === "@query-param" && value.parameters.name === undefined) {
fail(SignatureErrorCode.InvalidComponent, "@query-param requires name");
}
if (value.name !== "@query-param" && value.parameters.name !== undefined) {
fail(
SignatureErrorCode.InvalidComponent,
`name is invalid on component ${value.name}`
);
}
}

function componentMap(value: ComponentDescriptor): Parameters {
Expand Down Expand Up @@ -494,10 +501,38 @@ function requestTarget(
});
}

// URLSearchParams writes spaces as "+", not %20 (RFC 9421, Section 2.2.8).
function encodeQueryParam(value: string): string {
return new URLSearchParams([["", value]])
.toString()
.slice(1)
.replace(/\+/g, "%20");
}

function extractQueryParam(query: string, name: string | undefined): string {
const values = [...new URLSearchParams(query)]
.filter(([key]) => encodeQueryParam(key) === name)
.map(([, value]) => encodeQueryParam(value));
if (values.length === 0) {
return fail(
SignatureErrorCode.MissingField,
`Missing query parameter ${name}`
);
}
if (values.length > 1) {
return fail(
SignatureErrorCode.InvalidComponent,
`Query parameter ${name} occurs more than once`
);
}
return values[0];
}

function extractDerived(
snapshot: RequestSnapshot | ResponseSnapshot,
name: string
value: ComponentDescriptor
): string {
const { name } = value;
if (name === "@status") {
if (snapshot.kind !== "response") {
return fail(
Expand Down Expand Up @@ -534,6 +569,8 @@ function extractDerived(
return target.path;
case "@query":
return target.query;
case "@query-param":
return extractQueryParam(target.query, value.parameters.name);
default:
return fail(
SignatureErrorCode.UnsupportedFeature,
Expand All @@ -547,13 +584,10 @@ function extractComponentValue(
value: ComponentDescriptor
): string {
const selected = requestForComponent(snapshot, value);
if (value.name.startsWith("@")) return extractDerived(selected, value.name);
if (value.name.startsWith("@")) return extractDerived(selected, value);
const fieldValue = extractField(selected, value.name, false);
const key = value.parameters.key;
if (key === undefined) return fieldValue;
if (typeof key !== "string") {
return fail(SignatureErrorCode.InvalidComponent, "key must be a string");
}
const dictionary = parseRfc8941Dictionary(fieldValue, `field ${value.name}`);
const member = dictionary.get(key);
if (member === undefined) {
Expand Down
10 changes: 7 additions & 3 deletions packages/http-message-sig/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,13 @@ export type SignatureParameters = Readonly<
} & { readonly [name: string]: Rfc8941BareItem | undefined }
>;

export type ComponentParameters = Readonly<{
readonly [name: string]: Rfc8941BareItem | undefined;
}>;
export type ComponentParameters = Readonly<
{
readonly req?: true;
readonly key?: string;
readonly name?: string;
} & { readonly [name: string]: Rfc8941BareItem | undefined }
>;

export interface ComponentDescriptor {
readonly name: string;
Expand Down
45 changes: 40 additions & 5 deletions packages/http-message-sig/test/core.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
verifySignature,
webcrypto,
type RequestDescriptor,
type SignatureComponent,
type SignatureFields,
type SignatureMessage,
type Verifier,
Expand Down Expand Up @@ -76,7 +77,12 @@ function replacingFields(

async function signed(
message: SignatureMessage = request,
components = ["@method", "@authority", "@path", "content-type"]
components: readonly SignatureComponent[] = [
"@method",
"@authority",
"@path",
"content-type",
]
): Promise<{
readonly fields: SignatureFields;
readonly base: Uint8Array;
Expand Down Expand Up @@ -323,6 +329,30 @@ describe("createSignature", () => {
);
});

it("derives a re-encoded @query-param value", async () => {
const { base } = await signed(
{ ...request, targetUri: "https://example.com/path?a=1&b+c=x+y%21" },
[component("@query-param", { name: "b%20c" })]
);
expect(new TextDecoder().decode(base)).toContain(
'"@query-param";name="b%20c": x%20y%21\n'
);
});

it.each([
["?b=1", SignatureErrorCode.MissingField],
["?a=1&%61=2", SignatureErrorCode.InvalidComponent],
])(
"rejects a missing or repeated @query-param in %s",
async (query, code) => {
await expect(
signed({ ...request, targetUri: `https://example.com/path${query}` }, [
component("@query-param", { name: "a" }),
])
).rejects.toMatchObject({ code });
}
);

it("rejects a bare fragment in a descriptor target URI", async () => {
await expect(
signed({ ...request, targetUri: "https://example.com/path#" }, ["@path"])
Expand Down Expand Up @@ -512,14 +542,19 @@ describe("component identities", () => {
});

it("rejects component confusion and unsupported features", () => {
expect(() => component("@authority", { key: "host" })).toThrowError(
expect.objectContaining({ code: SignatureErrorCode.InvalidComponent })
);
for (const value of [
() => component("@authority", { key: "host" }),
() => component("@query-param"),
() => component("@path", { name: "a" }),
]) {
expect(value).toThrowError(
expect.objectContaining({ code: SignatureErrorCode.InvalidComponent })
);
}
for (const value of [
() => component("x", { sf: true }),
() => component("x", { bs: true }),
() => component("x", { tr: true }),
() => component("@query-param", { name: "a" }),
() => component("@unknown"),
]) {
expect(value).toThrowError(
Expand Down