Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow CLI to work with arbitrary Cloud API servers #722

Merged
merged 8 commits into from
Jan 31, 2024
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
5 changes: 0 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,6 @@ node build/cli.js ...

### Environment variables

`SALEOR_CLI_ENV`

Set to `staging` to use the CLI with staging Saleor Cloud
Comment on lines -153 to -155
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why its removed? I see its used in the source code?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.



`RUN_FUNCTIONAL_TESTS`

Set to `true` to enable functional tests
Expand Down
20 changes: 0 additions & 20 deletions src/aws-exports-prod.ts

This file was deleted.

20 changes: 0 additions & 20 deletions src/aws-exports-staging.ts

This file was deleted.

16 changes: 15 additions & 1 deletion src/cli/configure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import Enquirer from 'enquirer';
import type { Arguments, CommandBuilder } from 'yargs';

import { Config } from '../lib/config.js';
import { API, GET } from '../lib/index.js';
import {
API,
GET,
defaultCloudApiAuthDomain,
defaultCloudApiUrl,
} from '../lib/index.js';
import {
formatConfirm,
obfuscateArgv,
Expand Down Expand Up @@ -123,5 +128,14 @@ export const configure = async (providedToken: string | undefined) => {
Config.reset();
const header = `Token ${token}`;
await Config.set('token', header);
await Config.set('saleor_env', process.env.SALEOR_CLI_ENV || 'production');
await Config.set(
'cloud_api_url',
process.env.SALEOR_CLI_ENV_URL || defaultCloudApiUrl,
);
await Config.set(
'cloud_api_auth_domain',
process.env.SALEOR_CLI_ENV_AUTH_DOMAIN || defaultCloudApiAuthDomain,
);
return header;
};
43 changes: 29 additions & 14 deletions src/cli/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@ import { Arguments, CommandBuilder } from 'yargs';

import { Config, ConfigField, SaleorCLIPort } from '../lib/config.js';
import { checkPort } from '../lib/detectPort.js';
import { API, getAmplifyConfig, getEnvironment, POST } from '../lib/index.js';
import {
API,
getEnvironment,
POST,
getCloudApiAuthDomain,
defaultCloudApiUrl,
defaultCloudApiAuthDomain,
} from '../lib/index.js';
import {
CannotOpenURLError,
delay,
Expand Down Expand Up @@ -69,19 +76,16 @@ export const doLogin = async () => {
debug('check if port for the temporary HTTP server is free');
await checkPort(SaleorCLIPort);

debug('get AWS Amplify Configuration');
const amplifyConfig = await getAmplifyConfig();

const { code_challenge: codeChallenge, code_verifier: codeVerifier } =
await pkceChallenge();

const generatedState = nanoid();

const BaseParams = {
response_type: 'code',
client_id: amplifyConfig.aws_user_pools_web_client_id,
client_id: 'saleor-cli',
redirect_uri: RedirectURI,
scope: amplifyConfig.oauth.scope.join(' '),
scope: 'email openid profile',
state: generatedState,
};

Expand All @@ -100,13 +104,16 @@ export const doLogin = async () => {
`prepare the Base OAuth params: ${JSON.stringify(BaseParams, null, 2)}`,
);

const url = `https://${
amplifyConfig.oauth.domain
}/realms/saleor-cloud/protocol/openid-connect/auth?${new URLSearchParams({
...KeycloakParams,
})}`;
const cloudApiAuthDomain = await getCloudApiAuthDomain();

const url = `https://${cloudApiAuthDomain}/realms/saleor-cloud/protocol/openid-connect/auth?${new URLSearchParams(
{
...KeycloakParams,
},
)}`;

try {
debug(`opening browser with URL: ${url}`);
await openURL(url);
} catch (error) {
invariant(error instanceof Error, 'Must be an error');
Expand All @@ -133,12 +140,12 @@ export const doLogin = async () => {
grant_type: 'authorization_code',
code,
code_verifier: codeVerifier,
client_id: amplifyConfig.aws_user_pools_web_client_id,
client_id: 'saleor-cli',
redirect_uri: RedirectURI,
};

try {
const tokenURL = `https://${amplifyConfig.oauth.domain}/realms/saleor-cloud/protocol/openid-connect/token`;
const tokenURL = `https://${cloudApiAuthDomain}/realms/saleor-cloud/protocol/openid-connect/token`;

const response: any = await got
.post(tokenURL, {
Expand Down Expand Up @@ -252,7 +259,15 @@ const createConfig = async (

await Config.reset();
await Config.set('token', `Token ${token}`);
await Config.set('saleor_env', environment);
await Config.set('saleor_env', process.env.SALEOR_CLI_ENV || 'production');
await Config.set(
'cloud_api_url',
process.env.SALEOR_CLI_ENV_URL || defaultCloudApiUrl,
);
await Config.set(
'cloud_api_auth_domain',
process.env.SALEOR_CLI_ENV_AUTH_DOMAIN || defaultCloudApiAuthDomain,
);
await Config.set('user_session', userSession);
for (const [name, value] of Object.entries(secrets)) {
await Config.set(name as ConfigField, value);
Expand Down
2 changes: 2 additions & 0 deletions src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export type ConfigField =
| 'vercel_team_id'
| 'telemetry'
| 'saleor_env'
| 'cloud_api_url'
| 'cloud_api_auth_domain'
Comment on lines +22 to +23
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we add these env variables (SALEOR_CLI_ENV_URL and SALEOR_CLI_ENV_AUTH_DOMAIN) to readme?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

| 'TunnelServerSecret'
| 'VercelClientID'
| 'VercelClientSecret'
Expand Down
7 changes: 1 addition & 6 deletions src/lib/environment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { Arguments } from 'yargs';

import { Options } from '../types.js';
import { getEnvironment } from './environment.js';
import { configs } from './index.js';

const environment = {
name: 'Test environment',
Expand All @@ -28,11 +27,7 @@ const handlers = [
res(ctx.status(200), ctx.json(environment)),
),
rest.get(
`${configs.production.cloudApiUrl}/organizations/${argv.organization}/environments/${argv.environment}`,
(req, res, ctx) => res(ctx.status(200), ctx.json(environment)),
),
rest.get(
`${configs.staging.cloudApiUrl}/organizations/${argv.organization}/environments/${argv.environment}`,
`https://cloud.saleor.io/platform/api/organizations/${argv.organization}/environments/${argv.environment}`,
(req, res, ctx) => res(ctx.status(200), ctx.json(environment)),
),
];
Expand Down
52 changes: 31 additions & 21 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,44 @@ import type { CancelableRequest, OptionsOfTextResponseBody } from 'got';
import got from 'got';
import { Argv, CommandBuilder } from 'yargs';

import amplifyProdConfig from '../aws-exports-prod.js';
import amplifyStagingConfig from '../aws-exports-staging.js'; // esl
import { ConfigMap, Options } from '../types.js';
import { Options } from '../types.js';
import { Config } from './config.js';

const debug = Debug('saleor-cli:lib:index');

export const configs: ConfigMap = {
staging: {
cloudApiUrl: 'https://staging-cloud.saleor.io/platform/api',
amplifyConfig: amplifyStagingConfig,
},
production: {
cloudApiUrl: 'https://cloud.saleor.io/platform/api',
amplifyConfig: amplifyProdConfig,
},
export const defaultCloudApiUrl = 'https://cloud.saleor.io/platform/api';
export const defaultCloudApiAuthDomain = 'auth.saleor.io';

export const getCloudApiUrl = async () => {
if (await isLoggedIn()) {
const { cloud_api_url: cloudApiUrl } = await Config.get();
return cloudApiUrl || defaultCloudApiUrl;
}

return process.env.SALEOR_CLI_ENV_URL || defaultCloudApiUrl;
};

export const getEnvironment = async () => {
const { saleor_env: saleorEnv } = await Config.get();
return process.env.SALEOR_CLI_ENV || saleorEnv || 'production';
export const getCloudApiAuthDomain = async () => {
if (await isLoggedIn()) {
const { cloud_api_auth_domain: cloudApiAuthDomain } = await Config.get();
return cloudApiAuthDomain || defaultCloudApiAuthDomain;
}

return process.env.SALEOR_CLI_ENV_AUTH_DOMAIN || defaultCloudApiAuthDomain;
};

export const getAmplifyConfig = async () => {
const environment = await getEnvironment();
const { amplifyConfig } = configs[environment];
return amplifyConfig;
export const isLoggedIn = async () => {
const { token } = await Config.get();
return !!token;
};

export const getEnvironment = async () => {
const { saleor_env: saleorEnv, token } = await Config.get();
if (token) {
return saleorEnv;
}

return process.env.SALEOR_CLI_ENV || 'production';
};

type DefaultURLPath = (_: Options) => string;
Expand All @@ -47,8 +58,7 @@ const handleAuthAndConfig =
options: OptionsOfTextResponseBody = {},
) => {
const path = pathFunc(argv);
const environment = await getEnvironment();
const { cloudApiUrl } = configs[environment];
const cloudApiUrl = await getCloudApiUrl();

debug(path);
debug('cli options', argv);
Expand Down
10 changes: 0 additions & 10 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,16 +122,6 @@ export interface Task {
task_id: string;
}

export type Config = {
cloudApiUrl: string;
amplifyConfig: any;
captchaKey?: string | null;
};

export type ConfigMap = {
[key: string]: Config;
};

export interface Tasks {
count: number;
next: string | null;
Expand Down