Skip to content

Commit

Permalink
Use zone_name for deployment of custom hostnames (#4232)
Browse files Browse the repository at this point in the history
* Use `zone_name` for deployment of custom hostnames

* Simplify getting zone id from `zone_name` based on PR comments

* Add some more tests

* Add mock auth to tests

---------

Co-authored-by: Samuel Macleod <[email protected]>
  • Loading branch information
romeupalos and penalosa authored Oct 25, 2023
1 parent 109b159 commit 69b4303
Show file tree
Hide file tree
Showing 5 changed files with 239 additions and 24 deletions.
11 changes: 11 additions & 0 deletions .changeset/rich-schools-fry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"wrangler": minor
---

fix: use `zone_name` to determine a zone when the pattern is a custom hostname

In Cloudflare for SaaS, custom hostnames of third party domain owners can be used in Cloudflare.
Workers are allowed to intercept these requests based on the routes configuration.
Before this change, the same logic used by `wrangler dev` was used in `wrangler deploy`, which caused wrangler to fail with:

[ERROR] Could not find zone for [partner-saas-domain.com]
114 changes: 114 additions & 0 deletions packages/wrangler/src/__tests__/deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,84 @@ describe("deploy", () => {
`);
});

it("should deploy to a route with a SaaS domain", async () => {
writeWranglerToml({
workers_dev: false,
routes: [
{
pattern: "partner.com/*",
zone_name: "owned-zone.com",
},
],
});
writeWorkerSource();
mockUpdateWorkerRequest({ enabled: false });
mockUploadWorkerRequest({ available_on_subdomain: false });
mockGetZones("owned-zone.com", [{ id: "owned-zone-id-1" }]);
mockGetWorkerRoutes("owned-zone-id-1");
mockPublishRoutesRequest({
routes: [
{
pattern: "partner.com/*",
zone_name: "owned-zone.com",
},
],
});
await runWrangler("deploy ./index");
expect(std).toMatchInlineSnapshot(`
Object {
"debug": "",
"err": "",
"info": "",
"out": "Total Upload: xx KiB / gzip: xx KiB
Uploaded test-name (TIMINGS)
Published test-name (TIMINGS)
partner.com/* (zone name: owned-zone.com)
Current Deployment ID: Galaxy-Class",
"warn": "",
}
`);
});

it("should deploy to a route with a SaaS subdomain", async () => {
writeWranglerToml({
workers_dev: false,
routes: [
{
pattern: "subdomain.partner.com/*",
zone_name: "owned-zone.com",
},
],
});
writeWorkerSource();
mockUpdateWorkerRequest({ enabled: false });
mockUploadWorkerRequest({ available_on_subdomain: false });
mockGetZones("owned-zone.com", [{ id: "owned-zone-id-1" }]);
mockGetWorkerRoutes("owned-zone-id-1");
mockPublishRoutesRequest({
routes: [
{
pattern: "subdomain.partner.com/*",
zone_name: "owned-zone.com",
},
],
});
await runWrangler("deploy ./index");
expect(std).toMatchInlineSnapshot(`
Object {
"debug": "",
"err": "",
"info": "",
"out": "Total Upload: xx KiB / gzip: xx KiB
Uploaded test-name (TIMINGS)
Published test-name (TIMINGS)
subdomain.partner.com/* (zone name: owned-zone.com)
Current Deployment ID: Galaxy-Class",
"warn": "",
}
`);
});

it("should deploy to a route with a pattern/{zone_id|zone_name} combo (service environments)", async () => {
writeWranglerToml({
env: {
Expand Down Expand Up @@ -8911,6 +8989,42 @@ function mockUnauthorizedPublishRoutesRequest({
);
}

function mockGetZones(domain: string, zones: { id: string }[] = []) {
msw.use(
rest.get("*/zones", (req, res, ctx) => {
expect([...req.url.searchParams.entries()]).toEqual([["name", domain]]);

return res(
ctx.status(200),
ctx.json({
success: true,
errors: [],
messages: [],
result: zones,
})
);
})
);
}

function mockGetWorkerRoutes(zoneId: string) {
msw.use(
rest.get("*/zones/:zoneId/workers/routes", (req, res, ctx) => {
expect(req.params.zoneId).toEqual(zoneId);

return res(
ctx.status(200),
ctx.json({
success: true,
errors: [],
messages: [],
result: [],
})
);
})
);
}

function mockPublishRoutesFallbackRequest(route: {
pattern: string;
script: string;
Expand Down
16 changes: 0 additions & 16 deletions packages/wrangler/src/__tests__/dev.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -377,22 +377,6 @@ describe("wrangler dev", () => {
expect(std.err).toMatchInlineSnapshot(`""`);
});

it("should fail for non-existing zones", async () => {
writeWranglerToml({
main: "index.js",
routes: [
{
pattern: "https://subdomain.does-not-exist.com/*",
zone_name: "exists.com",
},
],
});
await fs.promises.writeFile("index.js", `export default {};`);
await expect(runWrangler("dev --remote")).rejects.toEqual(
new Error("Could not find zone for subdomain.does-not-exist.com")
);
});

it("should fail for non-existing zones, when falling back from */*", async () => {
writeWranglerToml({
main: "index.js",
Expand Down
104 changes: 103 additions & 1 deletion packages/wrangler/src/__tests__/zones.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,28 @@
import { getHostFromUrl } from "../zones";
import { rest } from "msw";
import { getHostFromUrl, getZoneForRoute } from "../zones";
import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
import { msw } from "./helpers/msw";
function mockGetZones(domain: string, zones: { id: string }[] = []) {
msw.use(
rest.get("*/zones", (req, res, ctx) => {
expect([...req.url.searchParams.entries()]).toEqual([["name", domain]]);

return res.once(
ctx.status(200),
ctx.json({
success: true,
errors: [],
messages: [],
result: zones,
})
);
})
);
}

describe("Zones", () => {
mockAccountId();
mockApiToken();
describe("getHostFromUrl", () => {
test.each`
pattern | host
Expand Down Expand Up @@ -35,4 +57,84 @@ describe("Zones", () => {
expect(getHostFromUrl(pattern)).toBe(host);
});
});
describe("getZoneForRoute", () => {
test("string route", async () => {
mockGetZones("example.com", [{ id: "example-id" }]);
expect(await getZoneForRoute("example.com/*")).toEqual({
host: "example.com",
id: "example-id",
});
});

test("string route (not a zone)", async () => {
mockGetZones("wrong.com", []);
await expect(
getZoneForRoute("wrong.com/*")
).rejects.toMatchInlineSnapshot(
`[Error: Could not find zone for wrong.com]`
);
});
test("zone_id route", async () => {
// example-id and other-id intentionally different to show that the API is not called
// when a zone_id is provided in the route
mockGetZones("example.com", [{ id: "example-id" }]);
expect(
await getZoneForRoute({ pattern: "example.com/*", zone_id: "other-id" })
).toEqual({
host: "example.com",
id: "other-id",
});
});
test("zone_id route (custom hostname)", async () => {
// example-id and other-id intentionally different to show that the API is not called
// when a zone_id is provided in the route
mockGetZones("example.com", [{ id: "example-id" }]);
expect(
await getZoneForRoute({
pattern: "some.third-party.com/*",
zone_id: "other-id",
})
).toEqual({
host: "some.third-party.com",
id: "other-id",
});
});

test("zone_name route (apex)", async () => {
mockGetZones("example.com", [{ id: "example-id" }]);
expect(
await getZoneForRoute({
pattern: "example.com/*",
zone_name: "example.com",
})
).toEqual({
host: "example.com",
id: "example-id",
});
});
test("zone_name route (subdomain)", async () => {
mockGetZones("example.com", [{ id: "example-id" }]);
expect(
await getZoneForRoute({
pattern: "subdomain.example.com/*",
zone_name: "example.com",
})
).toEqual({
host: "subdomain.example.com",
id: "example-id",
});
});
test("zone_name route (custom hostname)", async () => {
mockGetZones("example.com", [{ id: "example-id" }]);
expect(
await getZoneForRoute({
pattern: "some.third-party.com/*",
zone_name: "example.com",
})
).toEqual({
host: "some.third-party.com",
id: "example-id",
});
});
});
});
18 changes: 11 additions & 7 deletions packages/wrangler/src/zones.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,24 @@ export function getHostFromRoute(route: Route): string | undefined {
}

/**
* Try to compute the a zone ID and host name for one or more routes.
* Try to compute the a zone ID and host name for a route.
*
* When we're given a route, we do 2 things:
* - We try to extract a host from it
* - We try to get a zone id from the host
*/
export async function getZoneForRoute(route: Route): Promise<Zone | undefined> {
const host = getHostFromRoute(route);
const id =
typeof route === "object" && "zone_id" in route
? route.zone_id
: host
? await getZoneIdFromHost(host)
: undefined;
let id: string | undefined;

if (typeof route === "object" && "zone_id" in route) {
id = route.zone_id;
} else if (typeof route === "object" && "zone_name" in route) {
id = await getZoneIdFromHost(route.zone_name);
} else if (host) {
id = await getZoneIdFromHost(host);
}

return id && host ? { id, host } : undefined;
}

Expand Down

0 comments on commit 69b4303

Please sign in to comment.