Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wip change schema version to tuple #415

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ describe("AWS Lambda SaleorSyncWebhook", () => {
baseUrl: "example.com",
event: "CHECKOUT_CALCULATE_TAXES",
payload: { data: "test_payload" },
schemaVersion: 3.19,
schemaVersion: [3, 19],
authData: {
token: webhookConfig.apl.mockToken,
jwks: webhookConfig.apl.mockJwks,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ describe("Web API SaleorAsyncWebhook", () => {
baseUrl: "example.com",
event: "product_updated",
payload: { data: "test_payload" },
schemaVersion: 3.2,
schemaVersion: [3, 20],
authData: {
saleorApiUrl: mockAPL.workingSaleorApiUrl,
token: mockAPL.mockToken,
Expand Down Expand Up @@ -62,7 +62,7 @@ describe("Web API SaleorAsyncWebhook", () => {
authData: expect.objectContaining({
saleorApiUrl: mockAPL.workingSaleorApiUrl,
}),
})
}),
);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ describe("Web API SaleorSyncWebhook", () => {
baseUrl: "example.com",
event: "checkout_calculate_taxes",
payload: { data: "test_payload" },
schemaVersion: 3.19,
schemaVersion: [3, 19],
authData: {
token: webhookConfiguration.apl.mockToken,
jwks: webhookConfiguration.apl.mockJwks,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ export type WebhookConfig<Event = AsyncWebhookEventType | SyncWebhookEventType>
GenericWebhookConfig<WebApiHandlerInput, Event>;

/** Function type provided by consumer in `SaleorWebApiWebhook.createHandler` */
export type WebApiWebhookHandler<TPayload = unknown, TExtras = {}> = (
export type WebApiWebhookHandler<TPayload = unknown> = (
req: Request,
ctx: WebhookContext<TPayload> & TExtras
ctx: WebhookContext<TPayload>,
) => Response | Promise<Response>;

export abstract class SaleorWebApiWebhook<
TPayload = unknown,
TExtras extends Record<string, unknown> = {}
> extends GenericSaleorWebhook<WebApiHandlerInput, TPayload, TExtras> {
createHandler(handlerFn: WebApiWebhookHandler<TPayload, TExtras>): WebApiHandler {
export abstract class SaleorWebApiWebhook<TPayload = unknown> extends GenericSaleorWebhook<
WebApiHandlerInput,
TPayload
> {
createHandler(handlerFn: WebApiWebhookHandler<TPayload>): WebApiHandler {
return async (req) => {
const adapter = new WebApiAdapter(req);
const prepareRequestResult = await super.prepareRequest<WebApiAdapter>(adapter);
Expand All @@ -34,7 +34,6 @@ export abstract class SaleorWebApiWebhook<

debug("Incoming request validated. Call handlerFn");
return handlerFn(req, {
...(this.extraContext ?? ({} as TExtras)),
...prepareRequestResult.context,
});
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ describe("Next.js SaleorAsyncWebhook", () => {
expect(saleorAsyncWebhook.getWebhookManifest(baseUrl)).toEqual(
expect.objectContaining({
targetUrl: `${baseUrl}/${webhookPath}`,
})
}),
);
});

Expand All @@ -56,7 +56,7 @@ describe("Next.js SaleorAsyncWebhook", () => {
baseUrl: "example.com",
event: "product_updated",
payload: { data: "test_payload" },
schemaVersion: 3.2,
schemaVersion: [3, 20],
authData: {
saleorApiUrl: mockAPL.workingSaleorApiUrl,
token: mockAPL.mockToken,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe("Next.js SaleorSyncWebhook", () => {
baseUrl: "example.com",
event: "checkout_calculate_taxes",
payload: { data: "test_payload" },
schemaVersion: 3.19,
schemaVersion: [3, 19],
authData: {
token: validSyncWebhookConfiguration.apl.mockToken,
jwks: validSyncWebhookConfiguration.apl.mockJwks,
Expand Down
3 changes: 1 addition & 2 deletions src/handlers/shared/saleor-webhook-validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,7 @@
});
});

// TODO: This should be required
it("Fallbacks to null if version is missing in payload", async () => {
it("Throws if version header is missing", async () => {
vi.spyOn(adapter, "getRawBody").mockResolvedValue(JSON.stringify({}));
vi.spyOn(requestProcessor, "getSaleorHeaders").mockReturnValue(validHeaders);

Expand All @@ -249,7 +248,7 @@
requestProcessor,
});

expect(result).toMatchObject({

Check failure on line 251 in src/handlers/shared/saleor-webhook-validator.test.ts

View workflow job for this annotation

GitHub Actions / test

src/handlers/shared/saleor-webhook-validator.test.ts > SaleorWebhookValidator > Throws if version header is missing

AssertionError: expected { result: 'ok', context: { …(5) } } to match object { result: 'ok', …(1) } (9 matching properties omitted from actual) - Expected + Received { - "context": ObjectContaining { - "schemaVersion": null, + "context": { + "authData": { + "appId": "mock-app-id", + "jwks": "{}", + "saleorApiUrl": "https://example.com/graphql/", + "token": "mock-token", + }, + "baseUrl": "https://example-app.com/api", + "event": "product_updated", + "payload": {}, + "schemaVersion": [ + 3, + 20, + ], }, "result": "ok", } ❯ src/handlers/shared/saleor-webhook-validator.test.ts:251:20
result: "ok",
context: expect.objectContaining({
schemaVersion: null,
Expand All @@ -267,7 +266,7 @@
requestProcessor,
});

expect(result).toMatchObject({

Check failure on line 269 in src/handlers/shared/saleor-webhook-validator.test.ts

View workflow job for this annotation

GitHub Actions / test

src/handlers/shared/saleor-webhook-validator.test.ts > SaleorWebhookValidator > Returns success on valid request with signature passing validation against jwks in auth data

AssertionError: expected { result: 'ok', context: { …(5) } } to match object { result: 'ok', …(1) } (9 matching properties omitted from actual) - Expected + Received { - "context": ObjectContaining { + "context": { + "authData": { + "appId": "mock-app-id", + "jwks": "{}", + "saleorApiUrl": "https://example.com/graphql/", + "token": "mock-token", + }, "baseUrl": "https://example-app.com/api", "event": "product_updated", "payload": {}, - "schemaVersion": null, + "schemaVersion": [ + 3, + 20, + ], }, "result": "ok", } ❯ src/handlers/shared/saleor-webhook-validator.test.ts:269:20
result: "ok",
context: expect.objectContaining({
baseUrl: "https://example-app.com/api",
Expand Down
26 changes: 11 additions & 15 deletions src/handlers/shared/saleor-webhook-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { createDebug } from "@/debug";
import { fetchRemoteJwks } from "@/fetch-remote-jwks";
import { getOtelTracer } from "@/open-telemetry";
import { SaleorSchemaVersion } from "@/types";

Check failure on line 7 in src/handlers/shared/saleor-webhook-validator.ts

View workflow job for this annotation

GitHub Actions / lint

'SaleorSchemaVersion' is defined but never used
import { parseSchemaVersion } from "@/util";
import { verifySignatureWithJwks } from "@/verify-signature";

Expand Down Expand Up @@ -69,7 +70,8 @@
throw new WebhookError("Wrong request method, only POST allowed", "WRONG_METHOD");
}

const { event, signature, saleorApiUrl } = requestProcessor.getSaleorHeaders();
const { event, signature, saleorApiUrl, schemaVersion } =
requestProcessor.getSaleorHeaders();
const baseUrl = adapter.getBaseUrl();

if (!baseUrl) {
Expand All @@ -94,7 +96,7 @@

throw new WebhookError(
`Wrong incoming request event: ${event}. Expected: ${expected}`,
"WRONG_EVENT"
"WRONG_EVENT",
);
}

Expand All @@ -111,7 +113,7 @@
throw new WebhookError("Missing request body", "MISSING_REQUEST_BODY");
}

let parsedBody: unknown & { version?: string | null };
let parsedBody: unknown;

try {
parsedBody = JSON.parse(rawBody);
Expand All @@ -121,13 +123,7 @@
throw new WebhookError("Request body can't be parsed", "CANT_BE_PARSED");
}

let parsedSchemaVersion: number | null = null;

try {
parsedSchemaVersion = parseSchemaVersion(parsedBody.version);
} catch {
this.debug("Schema version cannot be parsed");
}
const parsedSchemaVersion = parseSchemaVersion(schemaVersion);

/**
* Verify if the app is properly installed for given Saleor API URL
Expand All @@ -139,7 +135,7 @@

throw new WebhookError(
`Can't find auth data for ${saleorApiUrl}. Please register the application`,
"NOT_REGISTERED"
"NOT_REGISTERED",
);
}

Expand All @@ -162,15 +158,15 @@

throw new WebhookError(
"Fetching remote JWKS failed",
"SIGNATURE_VERIFICATION_FAILED"
"SIGNATURE_VERIFICATION_FAILED",
);
});

this.debug("Fetched refreshed JWKS");

try {
this.debug(
"Second attempt to validate the signature JWKS, using fresh tokens from the API"
"Second attempt to validate the signature JWKS, using fresh tokens from the API",
);

await verifySignatureWithJwks(newJwks, signature, rawBody);
Expand All @@ -183,7 +179,7 @@

throw new WebhookError(
"Request signature check failed",
"SIGNATURE_VERIFICATION_FAILED"
"SIGNATURE_VERIFICATION_FAILED",
);
}
}
Expand Down Expand Up @@ -211,7 +207,7 @@
} finally {
span.end();
}
}
},
);
}
}
6 changes: 3 additions & 3 deletions src/handlers/shared/saleor-webhook.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { SaleorSchemaVersion } from "@/types";

import { AuthData } from "../../APL";

export const WebhookErrorCodeMap: Record<SaleorWebhookError, number> = {
Expand Down Expand Up @@ -50,9 +52,7 @@ export type WebhookContext<TPayload> = {
event: string;
payload: TPayload;
authData: AuthData;
// TODO: Make this required
/** Added in Saleor 3.15 */
schemaVersion: number | null;
schemaVersion: SaleorSchemaVersion;
};

export type FormatWebhookErrorResult = {
Expand Down
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,3 +320,8 @@ export interface AppManifest {
};
};
}

/**
* Tuple representing public schema version. Patch is omitted - it doesn't change the schema.
*/
export type SaleorSchemaVersion = [major: number, minor: number];
28 changes: 18 additions & 10 deletions src/util/schema-version.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
export const parseSchemaVersion = (rawVersion: string | undefined | null): number | null => {
if (!rawVersion) {
return null;
}
import { SaleorSchemaVersion } from "@/types";

const cantParseError = new Error("Cant parse Saleor schema version");

Check failure on line 3 in src/util/schema-version.ts

View workflow job for this annotation

GitHub Actions / test

src/util/schema-version.test.ts > parseSchemaVersion > Parses version string from: '3' to: null

Error: Cant parse Saleor schema version ❯ src/util/schema-version.ts:3:24 ❯ src/util/schema-version.test.ts:3:1

Check failure on line 3 in src/util/schema-version.ts

View workflow job for this annotation

GitHub Actions / test

src/util/schema-version.test.ts > parseSchemaVersion > Parses version string from: 'malformed' to: null

Error: Cant parse Saleor schema version ❯ src/util/schema-version.ts:3:24 ❯ src/util/schema-version.test.ts:3:1

Check failure on line 3 in src/util/schema-version.ts

View workflow job for this annotation

GitHub Actions / test

src/util/schema-version.test.ts > parseSchemaVersion > Parses version string from: 'malformed.raw' to: null

Error: Cant parse Saleor schema version ❯ src/util/schema-version.ts:3:24 ❯ src/util/schema-version.test.ts:3:1

Check failure on line 3 in src/util/schema-version.ts

View workflow job for this annotation

GitHub Actions / test

src/util/schema-version.test.ts > parseSchemaVersion > Parses version string from: 'malformed.raw.version' to: null

Error: Cant parse Saleor schema version ❯ src/util/schema-version.ts:3:24 ❯ src/util/schema-version.test.ts:3:1

Check failure on line 3 in src/util/schema-version.ts

View workflow job for this annotation

GitHub Actions / test

src/util/schema-version.test.ts > parseSchemaVersion > Parses version string from: null to: null

Error: Cant parse Saleor schema version ❯ src/util/schema-version.ts:3:24 ❯ src/util/schema-version.test.ts:3:1

Check failure on line 3 in src/util/schema-version.ts

View workflow job for this annotation

GitHub Actions / test

src/util/schema-version.test.ts > parseSchemaVersion > Parses version string from: undefined to: null

Error: Cant parse Saleor schema version ❯ src/util/schema-version.ts:3:24 ❯ src/util/schema-version.test.ts:3:1

export const parseSchemaVersion = (rawVersion: string | undefined | null): SaleorSchemaVersion => {
try {
if (!rawVersion) {
throw cantParseError;
}

const [majorString, minorString] = rawVersion.split(".");
const major = parseInt(majorString, 10);
const minor = parseInt(minorString, 10);
const [majorString, minorString] = rawVersion.split(".");
const major = parseInt(majorString, 10);
const minor = parseInt(minorString, 10);

if (major && minor) {
return parseFloat(`${major}.${minor}`);
if (major && minor) {
return [major, minor];
}
} catch (e) {
throw cantParseError;
}

return null;
throw cantParseError;
};
Loading