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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# Changelog

## 0.3.1

An account without a build token no longer needs a manual step in the Cloudflare dashboard.

- `WorkersBuilds.Repository`: without `buildToken`, on an account without a build token, the
provider registers the stack's API token as a build token named `alchemy-<stack name>`. It reads
the token id from `GET /user/tokens/verify` and calls `POST /accounts/{account_id}/builds/tokens`.
Before, the deploy failed and told you to connect a Worker to Git once in the dashboard. The order
is `buildToken`, then the account's first build token, then the registration.
- Destroy keeps the registered build token: build tokens belong to the account, and other
configurations can use them.
- Workers Builds accepts only API tokens. With the OAuth login or a global API key, the provider
cannot register a build token, and the deploy fails with `WorkersBuildsError`, as before.
- Docs: Workers Builds deploys with the registered token, so the token needs the permissions of the
deploy: Workers Scripts: Edit, and R2, KV, and D1 edit when the Wrangler file binds them.
- Unit tests prove the requests and the order on payloads from Cloudflare's API schema. No live run
has registered a build token yet.

## 0.3.0

A run file can now leave out the Worker name and the repository, so it works unchanged in each fork
Expand Down
34 changes: 25 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@ Alchemy uses environment credentials only when both variables are set. They then
profile for the whole stack, so also give the token the permissions that the other resources in
the stack need.

When the account has no build token and `WorkersBuilds.Repository` has no `buildToken`, the
provider registers this token as the build token (see [Build token](#workersbuildsrepository)).
Workers Builds then deploys with it, so also give it the permissions of the deploy:

- Workers Scripts: Edit (in the list above)
- Workers R2 Storage: Edit, Workers KV Storage: Edit, and D1: Edit, when the Wrangler file binds
R2 buckets, KV namespaces, or D1 databases

To register the token, the provider needs no other permission. If you roll or delete the token,
the builds that deploy with it fail.

The Cloudflare Workers and Pages GitHub App must have access to the repository. Install it once from
**Workers & Pages** in the Cloudflare dashboard.

Expand Down Expand Up @@ -185,9 +196,9 @@ Outputs: `workerId` (the Worker tag), `name`, `url`
### `WorkersBuilds.Repository`

Calls `GET`, `POST`, `PATCH`, and `DELETE /accounts/{account_id}/builds/workers[/{script_tag}]`,
`POST .../builds/workers/{script_tag}/migrate_to_previews`, `GET .../builds/tokens`,
`GET .../builds/workers/{script_tag}/triggers`, `DELETE .../builds/triggers/{trigger_uuid}`, and
`GET https://api.github.com/repos/{owner}/{name}`.
`POST .../builds/workers/{script_tag}/migrate_to_previews`, `GET` and `POST .../builds/tokens`,
`GET /user/tokens/verify`, `GET .../builds/workers/{script_tag}/triggers`,
`DELETE .../builds/triggers/{trigger_uuid}`, and `GET https://api.github.com/repos/{owner}/{name}`.

| Prop | Default | Change |
| ------------------------------------- | ------------------------- | ----------------------------------------------- |
Expand Down Expand Up @@ -219,8 +230,13 @@ Outputs: `scriptTag`, `repoConnectionId`, `triggerIds`, `previewsEnabled`, `acco
update, not a replacement. Without the ids, another owner or name replaces the configuration.
- Build token: Workers Builds deploys with the API token behind a build token. Without
`buildToken`, a new configuration uses the account's first build token (by name, newest first),
and an existing configuration keeps its token. If the account has no build token, connect any
Worker to Git once in the dashboard. Cloudflare then creates one.
and an existing configuration keeps its token. If the account has no build token, the provider
registers the stack's API token (`CLOUDFLARE_API_TOKEN`) as a build token named
`alchemy-<stack name>`, with the token id from `GET /user/tokens/verify`. The token then needs
the permissions of the deploy, see [Credentials](#credentials). Destroy keeps the build token,
because build tokens belong to the account and other configurations can use them. Workers Builds
accepts only API tokens: with the OAuth login or a global API key, the provider cannot register
one, and the deploy fails with `WorkersBuildsError`.
- Previews: with `previews: true`, Cloudflare builds a preview deployment with its own URL for each
branch. Cloudflare can create legacy branch triggers even when the request enables previews. The
provider then calls `migrate_to_previews`.
Expand Down Expand Up @@ -262,8 +278,8 @@ Outputs: `workerName`, `name`, `accountId`.
## Limits

- GitHub only. Workers Builds also supports GitLab; this package does not.
- The package cannot create a build token. A build token wraps an account API token, and creating
one needs more permissions than the three above.
- The package never creates an API token. It registers only the stack's own API token as a build
token. No live run has registered a build token yet.
- Secret build variables and `WorkersBuilds.Secret` values are part of Alchemy state. Alchemy's
Cloudflare state store encrypts state at rest; the local file store does not.
- Turning `previews` from `true` to `false` sends `previews_enabled: false`. The live tests do not
Expand All @@ -281,8 +297,8 @@ pnpm run test:live # real API calls, see below
```

Unit tests run against recorded Cloudflare and GitHub payloads in `test/fixtures/`, and against
secret payloads that follow Cloudflare's API schema until a live run records them. They make no
network calls.
secret and build token payloads that follow Cloudflare's API schema until a live run records them.
They make no network calls.

Live tests run only with `ALCHEMY_WORKERS_BUILDS_LIVE=1`:

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@samebase/alchemy-cloudflare-workers",
"version": "0.3.0",
"version": "0.3.1",
"description": "Alchemy v2 resources for Cloudflare Workers Builds: a Worker whose code Workers Builds deploys, the repository connection, the triggers, the build variables, and the Worker secrets.",
"keywords": [
"alchemy",
Expand Down
59 changes: 52 additions & 7 deletions src/Repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
// then runs the deploy command on each push to the production branch and the
// preview deploy command on every other branch. This resource never deletes
// the Worker.
import { Credentials } from "@distilled.cloud/cloudflare/Credentials";
import * as user from "@distilled.cloud/cloudflare/user";
import * as workersBuilds from "@distilled.cloud/cloudflare/workers_builds";
import { Resource } from "alchemy";
import { Unowned } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import { GitHubEnv } from "alchemy/GitHub";
import * as Provider from "alchemy/Provider";
import { StackName } from "alchemy/Stack";
import * as Config from "effect/Config";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
Expand Down Expand Up @@ -94,7 +97,9 @@ export interface RepositoryProps {
/**
* Build token uuid. Builds deploys with the API token behind it. Without
* it, a new configuration uses the account's first build token (by name,
* newest first), and an existing configuration keeps its token.
* newest first), and an existing configuration keeps its token. When the
* account has no build token, the provider registers the stack's API token
* as a build token named `alchemy-<stack name>`.
*/
readonly buildToken?: string;
/**
Expand Down Expand Up @@ -399,7 +404,7 @@ export const RepositoryProvider = () =>
let builds = yield* getBuilds(accountId, scriptTag);

if (builds === undefined) {
const buildToken = news.buildToken ?? (yield* firstBuildToken(accountId));
const buildToken = yield* resolveBuildToken(accountId, news.buildToken);
builds = yield* cloudflareRequest({
operation: "create Workers Builds configuration",
method: "POST",
Expand Down Expand Up @@ -502,6 +507,17 @@ const attributesOf = (accountId: string, builds: WorkerBuilds) =>
})),
);

/**
* The build token of a new configuration, in this order: `buildToken`, the
* account's first build token, else the stack's API token, which the
* provider registers as a build token.
*/
export const resolveBuildToken = (accountId: string, buildToken: string | undefined) =>
Effect.gen(function* () {
if (buildToken !== undefined) return buildToken;
return (yield* firstBuildToken(accountId)) ?? (yield* registerBuildToken(accountId));
});

const firstBuildToken = (accountId: string) =>
Effect.gen(function* () {
const tokens: workersBuilds.ListTokensResultItem[] = [];
Expand All @@ -512,14 +528,43 @@ const firstBuildToken = (accountId: string) =>
tokens.push(...batch);
if (batch.length < BUILD_TOKEN_PAGE_SIZE) break;
}
const uuid = selectBuildToken(tokens);
if (uuid === undefined) {
return selectBuildToken(tokens);
});

/**
* Registers the stack's API token as the build token `alchemy-<stack name>`,
* with the token id from GET /user/tokens/verify. Workers Builds accepts
* only API tokens, so an OAuth login or a global API key fails with
* {@link WorkersBuildsError}. Destroy keeps the build token: it belongs to
* the account, and other configurations can use it.
*/
const registerBuildToken = (accountId: string) =>
Effect.gen(function* () {
const operation = "register build token";
const credentials = yield* yield* Credentials;
if (credentials.type !== "apiToken") {
return yield* new WorkersBuildsError({
operation: "select build token",
message: `Account ${accountId} has no Workers Builds token. Connect any Worker to Git once in the Cloudflare dashboard, which creates one, or pass buildToken.`,
operation,
message: `Account ${accountId} has no Workers Builds token, and the stack's Cloudflare credentials are not an API token, so the provider cannot register one. Set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID, pass buildToken, or connect any Worker to Git once in the Cloudflare dashboard, which creates one.`,
});
}
const { id } = yield* user.verifyToken({}).pipe(refused("verify API token"));
// The request holds the token secret; never log it.
const registered = yield* workersBuilds
.createToken({
accountId,
buildTokenName: `alchemy-${yield* StackName}`,
buildTokenSecret: Redacted.value(credentials.apiToken),
cloudflareTokenId: id,
})
.pipe(refused(operation));
if (!registered.buildTokenUuid) {
return yield* new WorkersBuildsError({
operation,
message: `${operation}: the result has no build_token_uuid`,
});
}
return uuid;
return registered.buildTokenUuid;
});

const gitHubToken = Config.Redacted("GITHUB_TOKEN").pipe(
Expand Down
123 changes: 123 additions & 0 deletions test/Repository.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { readFileSync } from "node:fs";
import {
Credentials,
fromApiToken,
oauthCredentials,
} from "@distilled.cloud/cloudflare/Credentials";
import { Stack } from "alchemy/Stack";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
Expand All @@ -20,6 +27,7 @@ import {
GitHubRepositoryResponse,
type RepositoryAttributes,
type RepositoryProps,
resolveBuildToken,
resolveRepository,
selectBuildToken,
triggerAttributes,
Expand Down Expand Up @@ -490,3 +498,118 @@ describe("currentRepository", () => {
expect(github.requests).toHaveLength(0);
});
});

describe("resolveBuildToken", () => {
const api = "https://api.cloudflare.com/client/v4";
const tokensUrl = `${api}/accounts/${accountId}/builds/tokens`;
const listUrl = `${tokensUrl}?page=1&per_page=100`;
const verifyUrl = `${api}/user/tokens/verify`;
const success = (result: unknown) =>
Response.json({ success: true, errors: [], messages: [], result });
const Strings = Schema.Record(Schema.String, Schema.String);
/** The spec-derived create result, which has the same fields as a list item. */
const registered = () =>
Schema.decodeUnknownSync(Strings)(fixture("cloudflare/builds_tokens_create.json"));

/**
* Cloudflare with `tokens` as the account's build tokens, the spec-derived
* verify response, and `created` as the create result. Records the requests.
*/
const cloudflare = (tokens: readonly unknown[], created: unknown = registered()) =>
serve((request) =>
request.method === "GET" && request.url === listUrl
? success(tokens)
: request.method === "GET" && request.url === verifyUrl
? success(fixture("cloudflare/user_tokens_verify.json"))
: request.method === "POST" && request.url === tokensUrl
? success(created)
: new Response(null, { status: 404 }),
);
const calls = (server: ReturnType<typeof serve>) =>
server.requests.map((request) => `${request.method} ${request.url}`);

const resolve = (
server: ReturnType<typeof serve>,
buildToken: string | undefined,
credentials: Layer.Layer<Credentials> = fromApiToken({ apiToken: "test-token" }),
) =>
resolveBuildToken(accountId, buildToken).pipe(
Effect.provideService(HttpClient.HttpClient, server.client),
Effect.provide(credentials),
Effect.provideService(Stack, {
name: "MyApp",
stage: "dev",
resources: {},
bindings: {},
actions: {},
}),
);

it("takes buildToken first and calls nothing", async () => {
const server = cloudflare([]);
const uuid = await Effect.runPromise(
resolve(server, legacy.production_settings.build_token_uuid),
);
expect(uuid).toBe("bf34959e-03df-446a-af6d-b55bff91ab8b");
expect(server.requests).toHaveLength(0);
});

it("takes the account's first build token next, such as one that an earlier deploy registered", async () => {
const server = cloudflare([registered()]);
expect(await Effect.runPromise(resolve(server, undefined))).toBe(
"182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
);
expect(calls(server)).toEqual([`GET ${listUrl}`]);
});

it("registers the stack's API token under its verified id when the account has no build token", async () => {
const server = cloudflare([]);
expect(await Effect.runPromise(resolve(server, undefined))).toBe(
"182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
);
expect(calls(server)).toEqual([`GET ${listUrl}`, `GET ${verifyUrl}`, `POST ${tokensUrl}`]);
const [, verify, create] = server.requests;
expect(verify?.headers["authorization"]).toBe("Bearer test-token");
const body = Schema.decodeUnknownSync(Strings)(
create?.body._tag === "Uint8Array"
? JSON.parse(new TextDecoder().decode(create.body.body))
: undefined,
);
expect(Object.keys(body).sort()).toEqual([
"build_token_name",
"build_token_secret",
"cloudflare_token_id",
]);
const { build_token_secret: secret, ...named } = body;
expect(named).toEqual({
build_token_name: "alchemy-MyApp",
cloudflare_token_id: "ed17574386854bf78a67040be0a770b0",
});
// Presence only, so a failure never prints the secret.
expect(secret !== undefined && secret.length > 0).toBe(true);
});

it("fails with a WorkersBuildsError for OAuth credentials and registers nothing", async () => {
const server = cloudflare([]);
const oauth = Layer.succeed(
Credentials,
Effect.succeed(oauthCredentials({ accessToken: "test-oauth-token" })),
);
const error = await Effect.runPromise(Effect.flip(resolve(server, undefined, oauth)));
expect(error).toBeInstanceOf(WorkersBuildsError);
expect(error).toMatchObject({ operation: "register build token" });
expect(error.message).toContain("not an API token");
expect(error.message).toContain("pass buildToken");
expect(error.message).not.toContain("test-oauth-token");
expect(calls(server)).toEqual([`GET ${listUrl}`]);
});

it("fails when the create result has no build_token_uuid", async () => {
const { build_token_uuid: _, ...withoutUuid } = registered();
const error = await Effect.runPromise(
Effect.flip(resolve(cloudflare([], withoutUuid), undefined)),
);
expect(error).toBeInstanceOf(WorkersBuildsError);
expect(error.message).toContain("no build_token_uuid");
});
});
7 changes: 7 additions & 0 deletions test/fixtures/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ it with 400 and with 404. Replace each file with a recording when the secret liv
| `workers_scripts_secrets_list.json` | GET /accounts/{account_id}/workers/scripts/{script_name}/secrets | OpenAPI `worker-list-script-secrets` |
| `workers_scripts_secrets_put.json` | PUT /accounts/{account_id}/workers/scripts/{script_name}/secrets | OpenAPI `worker-put-script-secret` |
| `workers_scripts_not_found_error.json` | /accounts/{account_id}/workers/scripts/{script_name}/..., Worker does not exist | code 10007, Samebase test message |
| `user_tokens_verify.json` | GET /user/tokens/verify | OpenAPI `user-api-tokens-verify-token` |
| `builds_tokens_create.json` | POST /accounts/{account_id}/builds/tokens | OpenAPI `createBuildToken` |

The verify file is the example of the schema. The create file has the uuid of the documentation
example, the token id of the verify file, and the name that the provider sends for the stack
`MyApp`. A list item of GET /accounts/{account_id}/builds/tokens has the same fields, so the tests
also send it as the list. The create result never holds the token secret.

## GitHub

Expand Down
6 changes: 6 additions & 0 deletions test/fixtures/cloudflare/builds_tokens_create.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"build_token_name": "alchemy-MyApp",
"build_token_uuid": "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e",
"cloudflare_token_id": "ed17574386854bf78a67040be0a770b0",
"owner_type": "user"
}
6 changes: 6 additions & 0 deletions test/fixtures/cloudflare/user_tokens_verify.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"id": "ed17574386854bf78a67040be0a770b0",
"status": "active",
"expires_on": "2020-01-01T00:00:00Z",
"not_before": "2018-07-01T05:20:00Z"
}
Loading