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
15 changes: 15 additions & 0 deletions .changeset/access-service-token-support.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
"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
CLOUDFLARE_ACCESS_CLIENT_ID="<your-client-id>.access" 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
207 changes: 194 additions & 13 deletions packages/wrangler/src/__tests__/access.test.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,212 @@
import { UserError } from "@cloudflare/workers-utils";
import { beforeEach, describe, it } from "vitest";
import { domainUsesAccess, getAccessToken } from "../user/access";
import ci from "ci-info";
import { http, HttpResponse } from "msw";
import { beforeEach, describe, it, vi } from "vitest";
import {
clearAccessCaches,
domainUsesAccess,
getAccessToken,
} 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("getAccessToken", () => {
it("should return undefined 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 getAccessToken("not-access-protected.com")).toBeFalsy();
});

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

// Handler that returns the Access 302 redirect for domainUsesAccess,
// or authenticates via service token headers.
msw.use(
http.get("https://access-protected.com/", ({ request }) => {
const clientId = request.headers.get("CF-Access-Client-Id");

// No service token headers = this is the domainUsesAccess check
if (!clientId) {
return HttpResponse.json(null, {
status: 302,
headers: {
location: "access-protected-com.cloudflareaccess.com",
},
});
}

const clientSecret = request.headers.get("CF-Access-Client-Secret");

if (
clientId === "test-client-id.access" &&
clientSecret === "test-client-secret"
) {
return new HttpResponse("OK", {
status: 200,
headers: {
"Set-Cookie":
"CF_Authorization=mock-jwt-token; Path=/; HttpOnly; Secure",
},
});
}

return HttpResponse.json(
{ error: "unauthorized" },
{ status: 403 }
);
})
);

const token = await getAccessToken("access-protected.com");
expect(token).toBe("mock-jwt-token");
});

it("should throw a clear error when service token authentication fails", async ({
expect,
}) => {
vi.stubEnv("CLOUDFLARE_ACCESS_CLIENT_ID", "bad-client-id.access");
vi.stubEnv("CLOUDFLARE_ACCESS_CLIENT_SECRET", "bad-secret");

// Handler that returns 302 for domainUsesAccess, but rejects
// service token auth (no CF_Authorization cookie).
msw.use(
http.get("https://access-protected.com/", ({ request }) => {
if (!request.headers.get("CF-Access-Client-Id")) {
return HttpResponse.json(null, {
status: 302,
headers: {
location: "access-protected-com.cloudflareaccess.com",
},
});
}

return HttpResponse.json(
{ error: "unauthorized" },
{ status: 403 }
);
})
);

await expect(
getAccessToken("access-protected.com")
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: Failed to authenticate with Cloudflare Access using Service Token for domain "access-protected.com". The service token may be expired or invalid, or the Access application may not have a Service Auth policy. Verify your CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET are correct.
See https://developers.cloudflare.com/cloudflare-one/access-controls/service-credentials/service-tokens/]`
);
});

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

// Non-interactive so it will throw after the warning
setIsTTY(false);

await expect(
getAccessToken("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).toMatchInlineSnapshot(`
"▲ [WARNING] Both CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET must be set to use Access Service Token authentication. Only CLOUDFLARE_ACCESS_CLIENT_ID was found.

"
`);
});

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

// Non-interactive so it will throw after the warning
setIsTTY(false);

await expect(
getAccessToken("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).toMatchInlineSnapshot(`
"▲ [WARNING] Both CLOUDFLARE_ACCESS_CLIENT_ID and CLOUDFLARE_ACCESS_CLIENT_SECRET must be set to use Access Service Token authentication. 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(
getAccessToken("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,
}) => {
// Even with TTY, CI detection should trigger the error
setIsTTY(true);
vi.mocked(ci).isCI = true;

await expect(
getAccessToken("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/]`
);
});
});

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

await expect(
getAccessToken("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]`
);
});
});
});
});
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 });
}),
];
Loading
Loading