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
17 changes: 17 additions & 0 deletions .changeset/access-service-token-support.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
"wrangler": minor
---

Add support for Cloudflare Access Service Token authentication via environment variables

When running `wrangler dev` with remote bindings behind a Cloudflare Access-protected domain, Wrangler previously required `cloudflared access login` which opens a browser for interactive authentication. This does not work in CI/CD environments.

You can now set the `CLOUDFLARE_ACCESS_CLIENT_ID` and `CLOUDFLARE_ACCESS_CLIENT_SECRET` environment variables to authenticate using an Access Service Token instead:

```sh
export CLOUDFLARE_ACCESS_CLIENT_ID="<your-client-id>.access"
export CLOUDFLARE_ACCESS_CLIENT_SECRET="<your-client-secret>"
wrangler dev
```

Additionally, when running in a non-interactive environment (CI) without these credentials, Wrangler now throws a clear, actionable error instead of hanging on `cloudflared access login`.
7 changes: 7 additions & 0 deletions packages/workers-utils/src/environment-variables/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,13 @@ type VariableNames =
/** Direct authorization token for API requests. */
| "WRANGLER_CF_AUTHORIZATION_TOKEN"

// ## Cloudflare Access Service Token (for CI/non-interactive environments)

/** Cloudflare Access Service Token Client ID. Used to authenticate with Access-protected domains in non-interactive environments (e.g. CI). */
| "CLOUDFLARE_ACCESS_CLIENT_ID"
/** Cloudflare Access Service Token Client Secret. Used with CLOUDFLARE_ACCESS_CLIENT_ID. */
| "CLOUDFLARE_ACCESS_CLIENT_SECRET"

// ## Experimental Feature Flags

/** Enable the local explorer UI at /cdn-cgi/explorer (experimental, default: false). */
Expand Down
137 changes: 124 additions & 13 deletions packages/wrangler/src/__tests__/access.test.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,142 @@
import { UserError } from "@cloudflare/workers-utils";
import { beforeEach, describe, it } from "vitest";
import { domainUsesAccess, getAccessToken } from "../user/access";
import ci from "ci-info";
import { beforeEach, describe, it, vi } from "vitest";
import {
clearAccessCaches,
domainUsesAccess,
getAccessHeaders,
} from "../user/access";
import { mockConsoleMethods } from "./helpers/mock-console";
import { useMockIsTTY } from "./helpers/mock-istty";
import { msw, mswAccessHandlers } from "./helpers/msw";

describe("access", () => {
const { setIsTTY } = useMockIsTTY();
const std = mockConsoleMethods();

beforeEach(() => {
clearAccessCaches();
msw.use(...mswAccessHandlers);
});

describe("basic", () => {
describe("domainUsesAccess", () => {
it("should correctly detect an access protected domain", async ({
expect,
}) => {
expect(await domainUsesAccess("access-protected.com")).toBeTruthy();
expect(await domainUsesAccess("not-access-protected.com")).toBeFalsy();
});
it("should not fail without cloudflared installed", async ({ expect }) => {
expect(await getAccessToken("not-access-protected.com")).toBeFalsy();
});
it("should error without cloudflared installed on an access protected domain", async ({
});

describe("getAccessHeaders", () => {
it("should return empty headers for non-access-protected domains", async ({
expect,
}) => {
await expect(getAccessToken("access-protected.com")).rejects.toEqual(
new UserError(
"To use Wrangler with Cloudflare Access, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
)
);
expect(await getAccessHeaders("not-access-protected.com")).toEqual({});
});

describe("service token authentication", () => {
it("should return service token headers when both env vars are set", async ({
expect,
}) => {
vi.stubEnv("CLOUDFLARE_ACCESS_CLIENT_ID", "test-client-id.access");
vi.stubEnv("CLOUDFLARE_ACCESS_CLIENT_SECRET", "test-client-secret");

const headers = await getAccessHeaders("access-protected.com");
expect(headers).toEqual({
"CF-Access-Client-Id": "test-client-id.access",
"CF-Access-Client-Secret": "test-client-secret",
});
// No warning is presented since both env variables are set
expect(std.warn).toMatchInlineSnapshot(`""`);
});

it("should warn when only CLOUDFLARE_ACCESS_CLIENT_ID is set", async ({
expect,
}) => {
vi.stubEnv("CLOUDFLARE_ACCESS_CLIENT_ID", "test-client-id.access");
setIsTTY(false);

await expect(
getAccessHeaders("access-protected.com")
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: The domain "access-protected.com" is behind Cloudflare Access, but no Access Service Token credentials were found and the current environment is non-interactive.
Set the CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET environment variables to authenticate with an Access Service Token.
See https://developers.cloudflare.com/cloudflare-one/access-controls/service-credentials/service-tokens/]`
);
expect(std.warn).toContain(
"Both CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET must be set"
);
expect(std.warn).toContain(
"Only CLOUDFLARE_ACCESS_CLIENT_ID was found"
);
});

it("should warn when only CLOUDFLARE_ACCESS_CLIENT_SECRET is set", async ({
expect,
}) => {
vi.stubEnv("CLOUDFLARE_ACCESS_CLIENT_SECRET", "test-client-secret");
setIsTTY(false);

await expect(
getAccessHeaders("access-protected.com")
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: The domain "access-protected.com" is behind Cloudflare Access, but no Access Service Token credentials were found and the current environment is non-interactive.
Set the CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET environment variables to authenticate with an Access Service Token.
See https://developers.cloudflare.com/cloudflare-one/access-controls/service-credentials/service-tokens/]`
);
expect(std.warn).toContain(
"Both CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET must be set"
);
expect(std.warn).toContain(
"Only CLOUDFLARE_ACCESS_CLIENT_SECRET was found"
);
});
});

describe("non-interactive environment", () => {
it("should throw actionable error when non-interactive and no service token", async ({
expect,
}) => {
setIsTTY(false);

await expect(
getAccessHeaders("access-protected.com")
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: The domain "access-protected.com" is behind Cloudflare Access, but no Access Service Token credentials were found and the current environment is non-interactive.
Set the CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET environment variables to authenticate with an Access Service Token.
See https://developers.cloudflare.com/cloudflare-one/access-controls/service-credentials/service-tokens/]`
);
});

it("should throw actionable error when in CI and no service token", async ({
expect,
}) => {
setIsTTY(true);
vi.mocked(ci).isCI = true;

await expect(
getAccessHeaders("access-protected.com")
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: The domain "access-protected.com" is behind Cloudflare Access, but no Access Service Token credentials were found and the current environment is non-interactive.
Set the CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET environment variables to authenticate with an Access Service Token.
Comment thread
dario-piotrowicz marked this conversation as resolved.
See https://developers.cloudflare.com/cloudflare-one/access-controls/service-credentials/service-tokens/]`
);
});
});

describe("interactive environment (cloudflared fallback)", () => {
it("should error without cloudflared installed on an access protected domain", async ({
expect,
}) => {
setIsTTY(true);
vi.mocked(ci).isCI = false;

await expect(
getAccessHeaders("access-protected.com")
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: To use Wrangler with Cloudflare Access, please install \`cloudflared\` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation]`
);
});
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
createRemoteWorkerInit,
getWorkerAccountAndContext,
} from "../../../dev/remote";
import { getAccessToken } from "../../../user/access";
import { getAccessHeaders } from "../../../user/access";
import { FakeBus } from "../../helpers/fake-bus";
import { mockConsoleMethods } from "../../helpers/mock-console";
import { useTeardown } from "../../helpers/teardown";
Expand All @@ -35,7 +35,7 @@ vi.mock("../../../dev/remote", () => ({
}));

vi.mock("../../../user/access", () => ({
getAccessToken: vi.fn(),
getAccessHeaders: vi.fn(),
domainUsesAccess: vi.fn(),
}));

Expand Down Expand Up @@ -163,7 +163,7 @@ describe("RemoteRuntimeController", () => {
tailUrl: "wss://test.workers.dev/tail",
});

vi.mocked(getAccessToken).mockResolvedValue(undefined);
vi.mocked(getAccessHeaders).mockResolvedValue({});
});

describe("preview token refresh", () => {
Expand Down
26 changes: 9 additions & 17 deletions packages/wrangler/src/__tests__/helpers/msw/handlers/access.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@
import { http, HttpResponse } from "msw";

export default [
http.get(
"*access-protected.com*",
() => {
return HttpResponse.json(null, {
status: 302,
headers: { location: "access-protected-com.cloudflareaccess.com" },
});
},
{ once: true }
),
http.get(
"*not-access-protected.com*",
() => {
return HttpResponse.json("OK", { status: 200 });
},
{ once: true }
),
http.get("https://access-protected.com/", () => {
return HttpResponse.json(null, {
status: 302,
headers: { location: "access-protected-com.cloudflareaccess.com" },
});
}),
http.get("https://not-access-protected.com/", () => {
return HttpResponse.json("OK", { status: 200 });
}),
];
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import { logger } from "../../logger";
import { TRACE_VERSION } from "../../tail/createTail";
import { realishPrintLogs } from "../../tail/printing";
import { getAccessToken } from "../../user/access";
import { getAccessHeaders } from "../../user/access";
import { retryOnAPIFailure } from "../../utils/retry";
import { RuntimeController } from "./BaseController";
import { castErrorCause } from "./events";
Expand Down Expand Up @@ -310,7 +310,7 @@ export class RemoteRuntimeController extends RuntimeController {
return;
}

const accessToken = await getAccessToken(token.host);
const accessHeaders = await getAccessHeaders(token.host);

this.emitReloadCompleteEvent({
type: "reloadComplete",
Expand All @@ -324,7 +324,7 @@ export class RemoteRuntimeController extends RuntimeController {
},
headers: {
"cf-workers-preview-token": token.value,
...(accessToken ? { Cookie: `CF_Authorization=${accessToken}` } : {}),
...accessHeaders,
"cf-connecting-ip": "",
},
liveReload: config.dev.liveReload,
Expand Down
10 changes: 3 additions & 7 deletions packages/wrangler/src/dev/create-worker-preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { fetchResult } from "../cfetch";
import { createWorkerUploadForm } from "../deployment-bundle/create-worker-upload-form";
import { logger } from "../logger";
import { getWorkersDevSubdomain } from "../routes";
import { getAccessToken } from "../user/access";
import { getAccessHeaders } from "../user/access";
import type { ApiCredentials } from "../user";
import type { CfWorkerInitWithName } from "./remote";
import type {
Expand Down Expand Up @@ -138,12 +138,8 @@ async function tryExpandToken(
try {
const switchedExchangeUrl = switchHost(exchangeUrl, ctx.host, !!ctx.zone);

const headers: HeadersInit = {};
const accessToken = await getAccessToken(switchedExchangeUrl.hostname);

if (accessToken) {
headers.cookie = `CF_Authorization=${accessToken}`;
}
const accessHeaders = await getAccessHeaders(switchedExchangeUrl.hostname);
const headers: HeadersInit = { ...accessHeaders };

logger.debugWithSanitization(
"-- START EXCHANGE API REQUEST:",
Expand Down
Loading
Loading