Skip to content

Commit 3483232

Browse files
committed
Remove Cloudchamber/Containers auth customisation
1 parent d4f7f8b commit 3483232

File tree

7 files changed

+48
-126
lines changed

7 files changed

+48
-126
lines changed

packages/wrangler/src/cfetch/internal.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ function cloneHeaders(
142142
: { ...headers };
143143
}
144144

145-
async function requireLoggedIn(
145+
export async function requireLoggedIn(
146146
complianceConfig: ComplianceConfig
147147
): Promise<void> {
148148
const loggedIn = await loginOrRefreshIfRequired(complianceConfig);
@@ -151,7 +151,7 @@ async function requireLoggedIn(
151151
}
152152
}
153153

154-
function addAuthorizationHeaderIfUnspecified(
154+
export function addAuthorizationHeaderIfUnspecified(
155155
headers: Record<string, string>,
156156
auth: ApiCredentials
157157
): void {
@@ -165,7 +165,7 @@ function addAuthorizationHeaderIfUnspecified(
165165
}
166166
}
167167

168-
function addUserAgent(headers: Record<string, string>): void {
168+
export function addUserAgent(headers: Record<string, string>): void {
169169
headers["User-Agent"] = `wrangler/${wranglerVersion}`;
170170
}
171171

packages/wrangler/src/cloudchamber/common.ts

Lines changed: 23 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,27 @@
1-
import { mkdir } from "fs/promises";
2-
import { logRaw, space, status, updateStatus } from "@cloudflare/cli";
1+
import { space, updateStatus } from "@cloudflare/cli";
32
import { brandColor, dim } from "@cloudflare/cli/colors";
43
import { inputPrompt, spinner } from "@cloudflare/cli/interactive";
54
import {
65
ApiError,
76
DeploymentMutationError,
87
OpenAPI,
98
} from "@cloudflare/containers-shared";
10-
import { version as wranglerVersion } from "../../package.json";
9+
import {
10+
addAuthorizationHeaderIfUnspecified,
11+
addUserAgent,
12+
} from "../cfetch/internal";
1113
import { readConfig } from "../config";
12-
import { getConfigCache, purgeConfigCaches } from "../config-cache";
13-
import { containersScope } from "../containers";
1414
import { getCloudflareApiBaseUrl } from "../environment-variables/misc-variables";
1515
import { UserError } from "../errors";
1616
import { isNonInteractiveOrCI } from "../is-interactive";
1717
import { logger } from "../logger";
18-
import {
19-
DefaultScopeKeys,
20-
getAccountFromCache,
21-
getAccountId,
22-
getAPIToken,
23-
getAuthFromEnv,
24-
getScopes,
25-
logout,
26-
reinitialiseAuthTokens,
27-
requireAuth,
28-
setLoginScopeKeys,
29-
} from "../user";
18+
import { requireApiToken, requireAuth } from "../user";
3019
import { parseByteSize } from "./../parse";
3120
import { wrap } from "./helpers/wrap";
3221
import { idToLocationName, loadAccount } from "./locations";
3322
import type { Config } from "../config";
3423
import type { CloudchamberConfig, ContainerApp } from "../config/environment";
35-
import type { Scope } from "../user";
24+
import type { containersScope } from "../containers";
3625
import type {
3726
CommonYargsOptions,
3827
StrictYargsOptionsToInterfaceJSON,
@@ -45,7 +34,7 @@ import type {
4534
NetworkParameters,
4635
} from "@cloudflare/containers-shared";
4736

48-
export const cloudchamberScope: Scope = "cloudchamber:write";
37+
export const cloudchamberScope = "cloudchamber:write" as const;
4938

5039
export type CommonCloudchamberConfiguration = { json: boolean };
5140

@@ -107,7 +96,7 @@ export function handleFailure<
10796
: never,
10897
>(
10998
cb: (args: CommandArgumentsObject, config: Config) => Promise<void>,
110-
scope: Scope
99+
scope: typeof cloudchamberScope | typeof containersScope
111100
): (
112101
args: CommonYargsOptions &
113102
CommandArgumentsObject &
@@ -146,21 +135,15 @@ export async function loadAccountSpinner({ json }: { json?: boolean }) {
146135
* Gets the API URL depending if the user is using old/admin based authentication.
147136
*
148137
*/
149-
async function getAPIUrl(config: Config, scope: Scope) {
138+
async function getAPIUrl(
139+
config: Config,
140+
accountId: string,
141+
scope: typeof cloudchamberScope | typeof containersScope
142+
) {
150143
const api = getCloudflareApiBaseUrl(config);
151-
// This one will probably be cache'd already so it won't ask for the accountId again
152-
const accountId = config.account_id || (await getAccountId(config));
153-
const endpoint =
154-
scope === cloudchamberScope
155-
? "cloudchamber"
156-
: scope === containersScope
157-
? "containers"
158-
: null;
159-
if (endpoint === null) {
160-
throw new UserError(
161-
"unexpected scope for command: " + JSON.stringify(scope)
162-
);
163-
}
144+
145+
const endpoint = scope === cloudchamberScope ? "cloudchamber" : "containers";
146+
164147
return `${api}/accounts/${accountId}/${endpoint}`;
165148
}
166149

@@ -190,83 +173,19 @@ export async function promiseSpinner<T>(
190173
export async function fillOpenAPIConfiguration(
191174
config: Config,
192175
json: boolean,
193-
scope: Scope
176+
scope: typeof containersScope | typeof cloudchamberScope
194177
) {
195178
const headers: Record<string, string> =
196179
OpenAPI.HEADERS !== undefined ? { ...OpenAPI.HEADERS } : {};
197180

198-
// if the config cache folder doesn't exist, it means that there is not a node_modules folder in the tree
199-
if (Object.keys(getConfigCache("wrangler-account.json")).length === 0) {
200-
await wrap(mkdir("node_modules", {}));
201-
purgeConfigCaches();
202-
}
203-
204-
const scopes = getScopes();
205-
const needsToken = !scopes?.some((s) => s === scope);
206-
const neededScopes: Scope[] = [scope];
207-
const scopesToSet: Scope[] =
208-
scopes == undefined
209-
? neededScopes.concat(DefaultScopeKeys)
210-
: neededScopes.concat(scopes);
211-
212-
if (getAuthFromEnv() && needsToken) {
213-
setLoginScopeKeys(scopesToSet);
214-
// Wrangler will try to retrieve the oauth token and refresh it
215-
// for its internal fetch call even if we have AuthFromEnv.
216-
// Let's mock it
217-
reinitialiseAuthTokens({
218-
expiration_time: "2300-01-01:00:00:00+00:00",
219-
oauth_token: "_",
220-
});
221-
} else {
222-
if (needsToken && scopes) {
223-
logRaw(
224-
status.warning +
225-
" We need to re-authenticate to add a required token..."
226-
);
227-
// cache account id
228-
await getAccountId(config);
229-
const account = getAccountFromCache();
230-
config.account_id = account?.id ?? config.account_id;
231-
await promiseSpinner(logout(), { json, message: "Revoking token" });
232-
purgeConfigCaches();
233-
reinitialiseAuthTokens({});
234-
}
235-
236-
setLoginScopeKeys(scopesToSet);
237-
238-
// Require either login, or environment variables being set to authenticate
239-
//
240-
// This will prompt the user for an accountId being chosen if they haven't configured the account id yet
241-
const [, err] = await wrap(requireAuth(config));
242-
if (err) {
243-
throw new UserError(
244-
`authenticating with the Cloudflare API: ${err.message}`
245-
);
246-
}
247-
}
248-
249-
// Get the loaded API token
250-
const token = getAPIToken();
251-
if (!token) {
252-
throw new UserError("unexpected apiToken not existing in credentials");
253-
}
254-
255-
const val = "apiToken" in token ? token.apiToken : null;
256-
// Don't try to support this method of authentication
257-
if (!val) {
258-
throw new UserError(
259-
"we don't allow for authKey/email credentials, use `wrangler login` or CLOUDFLARE_API_TOKEN env variable to authenticate"
260-
);
261-
}
181+
const accountId = await requireAuth(config);
182+
const auth = requireApiToken();
183+
addAuthorizationHeaderIfUnspecified(headers, auth);
184+
addUserAgent(headers);
262185

263-
headers["Authorization"] = `Bearer ${val}`;
264-
// These are being set by the internal fetch of wrangler, but we are not using it
265-
// due to our OpenAPI codegenerated client.
266-
headers["User-Agent"] = `wrangler/${wranglerVersion}`;
267186
OpenAPI.CREDENTIALS = "omit";
268187
if (OpenAPI.BASE.length === 0) {
269-
const [base, errApiURL] = await wrap(getAPIUrl(config, scope));
188+
const [base, errApiURL] = await wrap(getAPIUrl(config, accountId, scope));
270189
if (errApiURL) {
271190
throw new UserError("getting the API url: " + errApiURL.message);
272191
}

packages/wrangler/src/cloudchamber/images/images.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,13 @@ import {
2222
} from "../common";
2323
import { wrap } from "../helpers/wrap";
2424
import type { Config } from "../../config";
25-
import type { Scope } from "../../user";
25+
import type { containersScope } from "../../containers";
2626
import type {
2727
CommonYargsArgvJSON,
2828
CommonYargsArgvSanitizedJSON,
2929
StrictYargsOptionsToInterfaceJSON,
3030
} from "../../yargs-types";
31+
import type { cloudchamberScope } from "../common";
3132
import type { ImageRegistryPermissions } from "@cloudflare/containers-shared";
3233

3334
function configureImageRegistryOptionalYargs(yargs: CommonYargsArgvJSON) {
@@ -61,7 +62,10 @@ function credentialsImageRegistryYargs(yargs: CommonYargsArgvJSON) {
6162
});
6263
}
6364

64-
export const registriesCommand = (yargs: CommonYargsArgvJSON, scope: Scope) => {
65+
export const registriesCommand = (
66+
yargs: CommonYargsArgvJSON,
67+
scope: typeof containersScope | typeof cloudchamberScope
68+
) => {
6569
return yargs
6670
.command(
6771
"configure",

packages/wrangler/src/cloudchamber/images/list.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ import {
55
import { logger } from "../../logger";
66
import { handleFailure, promiseSpinner } from "../common";
77
import type { Config } from "../../config";
8-
import type { Scope } from "../../user";
8+
import type { containersScope } from "../../containers";
99
import type {
1010
CommonYargsArgvJSON,
1111
CommonYargsArgvSanitizedJSON,
1212
StrictYargsOptionsToInterfaceJSON,
1313
} from "../../yargs-types";
14+
import type { cloudchamberScope } from "../common";
1415
import type { ImageRegistryPermissions } from "@cloudflare/containers-shared";
1516

1617
interface CatalogResponse {
@@ -22,7 +23,10 @@ interface TagsResponse {
2223
tags: string[];
2324
}
2425

25-
export const imagesCommand = (yargs: CommonYargsArgvJSON, scope: Scope) => {
26+
export const imagesCommand = (
27+
yargs: CommonYargsArgvJSON,
28+
scope: typeof containersScope | typeof cloudchamberScope
29+
) => {
2630
return yargs
2731
.command(
2832
"list",

packages/wrangler/src/cloudchamber/ssh/ssh.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,13 @@ import {
2424
import { wrap } from "../helpers/wrap";
2525
import { validatePublicSSHKeyCLI, validateSSHKey } from "./validate";
2626
import type { Config } from "../../config";
27-
import type { Scope } from "../../user";
27+
import type { containersScope } from "../../containers";
2828
import type {
2929
CommonYargsArgvJSON,
3030
CommonYargsArgvSanitizedJSON,
3131
StrictYargsOptionsToInterfaceJSON,
3232
} from "../../yargs-types";
33+
import type { cloudchamberScope } from "../common";
3334
import type {
3435
ListSSHPublicKeys,
3536
SSHPublicKeyID,
@@ -107,7 +108,10 @@ export async function sshPrompts(
107108
return key || undefined;
108109
}
109110

110-
export const sshCommand = (yargs: CommonYargsArgvJSON, scope: Scope) => {
111+
export const sshCommand = (
112+
yargs: CommonYargsArgvJSON,
113+
scope: typeof cloudchamberScope | typeof containersScope
114+
) => {
111115
return yargs
112116
.command(
113117
"list",

packages/wrangler/src/containers/index.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,10 @@ import {
1414
listCommand,
1515
listYargs,
1616
} from "./containers";
17-
import type { Scope } from "../user";
1817
import type { CommonYargsArgvJSON, CommonYargsOptions } from "../yargs-types";
1918
import type { CommandModule } from "yargs";
2019

21-
export const containersScope: Scope = "containers:write";
20+
export const containersScope = "containers:write" as const;
2221

2322
export const containers = (
2423
yargs: CommonYargsArgvJSON,

packages/wrangler/src/user/user.ts

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -361,24 +361,16 @@ const DefaultScopes = {
361361
"See and change Cloudflare Pipelines configurations and data",
362362
"secrets_store:write":
363363
"See and change secrets + stores within the Secrets Store",
364-
} as const;
365-
366-
const OptionalScopes = {
367-
"cloudchamber:write": "Manage Cloudchamber",
368364
"containers:write": "Manage Workers Containers",
365+
"cloudchamber:write": "Manage Cloudchamber",
369366
} as const;
370367

371-
const AllScopes = {
372-
...DefaultScopes,
373-
...OptionalScopes,
374-
};
375-
376368
/**
377369
* The possible keys for a Scope.
378370
*
379371
* "offline_access" is automatically included.
380372
*/
381-
export type Scope = keyof typeof AllScopes;
373+
export type Scope = keyof typeof DefaultScopes;
382374

383375
export let DefaultScopeKeys = Object.keys(DefaultScopes) as Scope[];
384376

@@ -1216,7 +1208,7 @@ export function listScopes(message = "💁 Available scopes:"): void {
12161208
logger.log(message);
12171209
const data = DefaultScopeKeys.map((scope: Scope) => ({
12181210
Scope: scope,
1219-
Description: AllScopes[scope],
1211+
Description: DefaultScopes[scope],
12201212
}));
12211213
logger.table(data);
12221214
// TODO: maybe a good idea to show usage here

0 commit comments

Comments
 (0)