From 89fdc92655ba0917c825e88d39f32a4f47a49fe1 Mon Sep 17 00:00:00 2001 From: Artur Jankowski Date: Tue, 3 Nov 2026 12:16:06 +0100 Subject: [PATCH] feat: support OAuth 2.0 public client (PKCE) authentication Add `box login --public-client` (and menu option [3]) for OAuth apps registered as public clients, which have no client secret. Environments are stored as `authMethod: oauth20` with `publicClient: true`. Auth uses the generated SDK's `BoxPublicClientOAuth`. Legacy SDK commands get tokens through `PublicClientSessionAdapter`, which handles refresh, downscoping and revoke without a client secret. `logout` and `tokens:revoke` revoke without a secret as well. Requires a box-node-sdk release that exports `BoxPublicClientOAuth`. --- docs/authentication.md | 29 +- docs/login.md | 17 +- package-lock.json | 1 + package.json | 1 + src/box-command.js | 135 ++++++- src/commands/login.js | 271 ++++++++++--- src/commands/logout.js | 39 +- src/commands/tokens/revoke.js | 29 ++ src/public-client-session-adapter.js | 218 +++++++++++ src/public-client.js | 132 +++++++ src/token-cache.js | 23 +- test/commands/login.test.js | 380 ++++++++++++++++++- test/public-client-auth.test.js | 374 ++++++++++++++++++ test/public-client-session-adapter.test.js | 417 +++++++++++++++++++++ test/public-client.test.js | 48 +++ test/token-cache.test.js | 33 ++ 16 files changed, 2077 insertions(+), 70 deletions(-) create mode 100644 src/public-client-session-adapter.js create mode 100644 src/public-client.js create mode 100644 test/public-client-auth.test.js create mode 100644 test/public-client-session-adapter.test.js create mode 100644 test/public-client.test.js diff --git a/docs/authentication.md b/docs/authentication.md index 015e00e2..675d375e 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -11,6 +11,7 @@ overview of how the Box API handles authentication. - [OAuth 2.0 Login (`box login`)](#oauth-20-login-box-login) - [Option 1: Official Box CLI App](#option-1-official-box-cli-app) - [Option 2: Your Own Platform App](#option-2-your-own-platform-app) + - [Option 3: Your Own Public Client App (PKCE)](#option-3-your-own-public-client-app-pkce) - [Supported Ports](#supported-ports) - [Additional Flags](#additional-flags) - [Reauthorize OAuth2](#reauthorize-oauth2) @@ -127,7 +128,7 @@ box configure:environments:add /path/to/config.json --ccg-auth --ccg-user "USER_ The `box login` command authenticates you with Box using OAuth 2.0. It starts a local callback server, opens your browser for authorization, and stores the resulting tokens in a named environment. -When you run `box login`, the CLI presents three options: the **Official Box CLI App**, a **Platform App** you create yourself, or **quit** (`q`) to exit. You can either choose interactively or skip the selection entirely using the `--default-box-app` (`-d`) flag. You can also paste a Client ID directly at the prompt — any input between 16 and 99 characters is treated as a Client ID. +When you run `box login`, the CLI presents four options: the **Official Box CLI App**, a **Platform App** you create yourself, a **public client app** you create yourself, or **quit** (`q`) to exit. You can either choose interactively or skip the selection entirely using the `--default-box-app` (`-d`) flag. You can also paste a Client ID directly at the prompt — any input between 16 and 99 characters is treated as a Client ID. #### Option 1: Official Box CLI App @@ -137,7 +138,7 @@ This is the fastest way to get started with Box CLI. No app creation in the Box ```bash box login -# Choose [1] for Official Box CLI App, [2] for Platform App, or [q] to quit. +# Choose [1] for Official Box CLI App, [2] for Platform App, [3] for a public client app, or [q] to quit. ``` **Skip the prompt** — use the `--default-box-app` (or `-d`) flag to go directly to authorization: @@ -172,6 +173,27 @@ box login For a step-by-step walkthrough, see the [Quickstart Guide](https://developer.box.com/guides/tooling/cli/quick-start/). +#### Option 3: Your Own Public Client App (PKCE) + +A command line tool can't keep a client secret confidential, so you can register your OAuth app as a **public client** instead. A public client has no client secret. Every login is protected with [PKCE](https://oauth.net/2/pkce/): the CLI creates a random code verifier, sends a challenge derived from it in the authorize URL, and presents the verifier when it exchanges the authorization code for tokens. + +Before running the command, set up the app in the [Box Developer Console](https://cloud.app.box.com/developers/console): + +1. Create a Custom App with **User Authentication (OAuth 2.0)** and choose the **public client** option. The app type can't be changed later, so an existing app with a client secret can't be turned into a public client. +2. In the **Configuration** tab, set the **Redirect URI** to `http://localhost:3000/callback` (adjust the port if you use a different `--port` value). +3. Click **Save Changes**. + +Then log in and enter only the **Client ID**: + +```bash +box login --public-client +# Or run "box login" and choose [3]. +``` + +The environment is stored with `authMethod: oauth20` and `publicClient: true`, and no client secret. Access tokens are refreshed automatically with the refresh token, without a client secret. `box logout` and `box tokens:revoke` revoke tokens and `box tokens:exchange` downscopes them the same way. + +To reauthorize a public client environment, run `box login --reauthorize --name ` without `--public-client`. The stored Client ID is reused and the login is again protected with PKCE. `--public-client` can't be combined with `--reauthorize`. + #### Supported Ports The `box login` command starts a local callback server to receive the OAuth redirect. You can control the port with the `--port` (`-p`) flag. The default port is **3000**. @@ -194,6 +216,7 @@ When using your own Platform App, any port can be used — just make sure the ** |------|-------|--------------------------------------------------------------------------------------| | `--default-box-app` | `-d` | Use the Official Box CLI App and proceed directly to authorization. | | `--platform-app` | | Skip the prompt and go directly to Platform App setup (Client ID and Client Secret). | +| `--public-client` | | Skip the prompt and go directly to public client app setup (Client ID only, PKCE). Can't be combined with `--reauthorize`. | | `--port ` | `-p` | Set the port for the local callback server. Default: `3000`. | | `--name ` | `-n` | Set a name for the environment. Default: `oauth`. | | `--reauthorize` | `-r` | Reauthorize an existing environment (requires `--name`). | @@ -220,7 +243,7 @@ To reauthorize, run: box login --name "ENVIRONMENT_NAME" --reauthorize ``` -The `--reauthorize` flag retrieves the existing `clientID` and `clientSecret` from the stored environment, so you do not need to enter them again. After a successful login, the environment is updated and set as the default. +The `--reauthorize` flag retrieves the existing `clientID` and `clientSecret` (or, for a public client app, just the `clientID`) from the stored environment, so you do not need to enter them again. After a successful login, the environment is updated and set as the default. You can also combine `--reauthorize` with `--default-box-app` to switch an existing environment to the Official Box CLI App: diff --git a/docs/login.md b/docs/login.md index f06f72d7..9845765e 100644 --- a/docs/login.md +++ b/docs/login.md @@ -11,6 +11,9 @@ Login options: (2) Your own Platform OAuth App Enter your Client ID and Client Secret when prompted. Use --platform-app to skip the prompt. + (3) Your own Platform OAuth public client App + For apps registered as a public client, which have no client secret. Enter your Client ID when prompted; the login is protected with PKCE. Use --public-client to skip the prompt. + Quickstart: run "box login -d" to sign in immediately. A browser window will open for authorization. Once access is granted, the environment is created and set as default — you can start running commands right away. Headless environments: use --code (-c) if no browser is available. The CLI will display an authorize URL — visit it in an external browser, authorize and grant access to the app, then provide the state and authorization code back to the CLI when prompted. @@ -23,7 +26,8 @@ Sign in with OAuth 2.0 and create a new environment (or update an existing one w ``` USAGE - $ box login [--no-color] [-h] [-v] [-q] [-c] [-p ] [-d | --platform-app] [-r -n ] [-i] + $ box login [--no-color] [-h] [-v] [-q] [-c] [-p ] [-d | --platform-app | --public-client] [-r -n + ] [-i] FLAGS -c, --code @@ -65,6 +69,13 @@ FLAGS Skip the authentication method prompt and go directly to Platform App setup. You will be prompted for Client ID and Client Secret. + --public-client + Skip the authentication method prompt and go directly to public client app setup. + Use this for an OAuth 2.0 app registered in the Developer Console as a public client, which has no client secret. + Every login is protected with PKCE. You will be prompted for the Client ID only. + Cannot be combined with --reauthorize. To reauthorize a public client environment, run "box login --reauthorize + --name ". + DESCRIPTION Sign in with OAuth 2.0 and create a new environment (or update an existing one with --reauthorize). @@ -76,6 +87,10 @@ DESCRIPTION (2) Your own Platform OAuth App Enter your Client ID and Client Secret when prompted. Use --platform-app to skip the prompt. + (3) Your own Platform OAuth public client App + For apps registered as a public client, which have no client secret. Enter your Client ID when prompted; the login is + protected with PKCE. Use --public-client to skip the prompt. + Quickstart: run "box login -d" to sign in immediately. A browser window will open for authorization. Once access is granted, the environment is created and set as default — you can start running commands right away. diff --git a/package-lock.json b/package-lock.json index f5743d70..309bf074 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,6 +21,7 @@ "@oclif/table": "0.5.4", "@octokit/rest": "^22.0.0", "archiver": "^8.0.0", + "bluebird": "^3.7.2", "box-node-sdk": "^4.11.1", "chalk": "^2.4.1", "cli-progress": "^2.1.0", diff --git a/package.json b/package.json index fafe6b9d..ddff8fa5 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "@oclif/table": "0.5.4", "@octokit/rest": "^22.0.0", "archiver": "^8.0.0", + "bluebird": "^3.7.2", "box-node-sdk": "^4.11.1", "chalk": "^2.4.1", "cli-progress": "^2.1.0", diff --git a/src/box-command.js b/src/box-command.js index 0cd1e4e5..f8182d11 100644 --- a/src/box-command.js +++ b/src/box-command.js @@ -30,6 +30,13 @@ const BoxTSSDK = require('box-node-sdk/sdk-gen'); const BoxTsErrors = require('box-node-sdk/sdk-gen/box/errors'); const BoxCLIError = require('./cli-error'); const CLITokenCache = require('./token-cache'); +const PublicClientSessionAdapter = require('./public-client-session-adapter'); +const { + isPublicClientEnvironment, + createPublicClientTsClient, + createReauthorizeError, + isRefreshTokenRejectedError, +} = require('./public-client'); const PaginationUtilities = require('./pagination-utils'); const utils = require('./util'); const pkg = require('../package.json'); @@ -67,6 +74,7 @@ const KEY_MAPPINGS = { defaultAsUserId: 'Default As-User ID', useDefaultAsUser: 'Use Default As-User', cacheTokens: 'Cache Tokens', + publicClient: 'Public Client', ip: 'IP', operationParams: 'Operation Params', copyInstanceOnItemCopy: 'Copy Instance On Item Copy', @@ -115,6 +123,24 @@ function getDebugErrorDetails(error) { }; } +/** + * Build the CLI error message for a TS SDK API error response. + * OAuth2 token endpoint errors use `error` and `error_description` instead of the regular API error fields. + * + * @param {Object} responseInfo The response info of a BoxApiError + * @returns {string} The error message + */ +function formatApiErrorMessage(responseInfo) { + const body = responseInfo.body; + if (typeof body.error !== 'string') { + return `Unexpected API Response [${body.status} ${body.message} | ${body.request_id}] ${body.code} - ${body.message}`; + } + const message = `Unexpected API Response [${responseInfo.statusCode}] ${body.error}`; + return body.error_description + ? `${message} - ${body.error_description}` + : message; +} + /** * Parse a string value from CSV into the correct boolean value * @param {string|boolean} value The value to parse @@ -811,6 +837,11 @@ class BoxCommand extends Command { client = ccgUser ? sdk.getCCGClientForUser(ccgUser) : sdk.getAnonymousClient(); + } else if (isPublicClientEnvironment(environment)) { + client = await this._createPublicClientLegacyClient( + environmentsObj.default, + environment + ); } else if ( environmentsObj.default && environmentsObj.environments[environmentsObj.default].authMethod === @@ -994,6 +1025,11 @@ class BoxCommand extends Command { auth: ccgAuth, }); client = this._configureTsSdk(client, SDK_CONFIG); + } else if (isPublicClientEnvironment(environment)) { + client = this._getPublicClientTsClient( + environmentsObj.default, + environment + ); } else if ( environmentsObj.default && environmentsObj.environments[environmentsObj.default].authMethod === @@ -1097,6 +1133,88 @@ class BoxCommand extends Command { return client; } + /** + * Create the legacy SDK client for a public client (PKCE) environment. + * + * The legacy SDK only supports OAuth with a client secret, so the client's + * session is replaced with an adapter that gets tokens from the generated + * SDK auth. Token requests use the TS client's network session, so they + * honor the same proxy, base URL and header settings as the TS client. + * + * @param {string} environmentName Name of the current environment + * @param {Object} environment The current environment + * @returns {Promise} The legacy SDK client + * @private + */ + async _createPublicClientLegacyClient(environmentName, environment) { + DEBUG.init( + 'Using public client environment %s %O', + environmentName, + environment + ); + const tsClient = this._getPublicClientTsClient( + environmentName, + environment + ); + const cachedToken = await this._publicClientAuth.tokenStorage.get(); + if (!cachedToken?.accessToken) { + throw createReauthorizeError(environmentName); + } + const sdk = new BoxSDK({ + clientID: environment.clientId, + clientSecret: '', + ...SDK_CONFIG, + }); + this._configureSdk(sdk, { ...SDK_CONFIG }); + this.sdk = sdk; + + const client = sdk.getBasicClient(''); + client._session = new PublicClientSessionAdapter( + this._publicClientAuth, + { + environmentName, + expiryBufferMS: sdk.config.expiredBufferMS, + networkSession: tsClient.networkSession, + // Already read to check the environment is logged in, so the adapter does not read it again + initialToken: cachedToken, + } + ); + return client; + } + + /** + * Get the TS SDK client for a public client (PKCE) environment. + * Built once per command, so the legacy and TS clients share one auth and token cache. + * + * @param {string} environmentName Name of the current environment + * @param {Object} environment The current environment + * @returns {BoxTSSDK.BoxClient} The configured TS SDK client + * @private + */ + _getPublicClientTsClient(environmentName, environment) { + if (!this._publicClientTsClient) { + // Public client tokens are always cached: without the refresh token every command would need a new login. + this._publicClientEnvironmentName = environmentName; + const { auth, client } = createPublicClientTsClient(this, { + clientId: environment.clientId, + tokenStorage: new CLITokenCache(environmentName), + }); + this._publicClientAuth = auth; + this._publicClientTsClient = client; + } + return this._publicClientTsClient; + } + + /** + * Whether this command authenticates with the public client (PKCE) auth of the current environment. + * Only meaningful after client setup. + * + * @returns {boolean} True for public client environments not overridden by --token + */ + usesPublicClientAuth() { + return Boolean(this._publicClientAuth); + } + /** * Configures SDK by using values from settings.json file * @param {*} sdk to configure @@ -1684,13 +1802,26 @@ class BoxCommand extends Command { const AUTH_FAILED_HINT = 'Authentication failed: token is invalid or expired. OAuth: run "box login --reauthorize". JWT/CCG: tokens are refreshed automatically, so a 401 usually means app credentials or environment configuration must be fixed. You can also provide a fresh token with --token.'; if ( + this.usesPublicClientAuth() && + err instanceof BoxTsErrors.BoxApiError && + isRefreshTokenRejectedError(err) + ) { + // The TS SDK refreshes on 401 and surfaces the token endpoint error when the refresh token is no longer valid. + err = createReauthorizeError( + this._publicClientEnvironmentName, + err + ); + } else if ( err instanceof BoxTsErrors.BoxApiError && err.responseInfo && err.responseInfo.body ) { const responseInfo = err.responseInfo; - let errorMessage = `Unexpected API Response [${responseInfo.body.status} ${responseInfo.body.message} | ${responseInfo.body.request_id}] ${responseInfo.body.code} - ${responseInfo.body.message}`; - if (responseInfo.body.status === 401) { + let errorMessage = formatApiErrorMessage(responseInfo); + if ( + responseInfo.body.status === 401 || + responseInfo.statusCode === 401 + ) { errorMessage += `\n${AUTH_FAILED_HINT}`; } err = new BoxCLIError(errorMessage, err); diff --git a/src/commands/login.js b/src/commands/login.js index afee7066..d6814211 100644 --- a/src/commands/login.js +++ b/src/commands/login.js @@ -20,6 +20,11 @@ const { assertValidOAuthCode, getTokenInfoByAuthCode, } = require('../login-helper'); +const { + isPublicClientEnvironment, + createPublicClientTsClient, + getPublicClientAuthorizeUrl, +} = require('../public-client'); const GENERIC_OAUTH_CLIENT_ID = 'udz8zp4yue87uk9dzq4xk425kkwvqvh1'; const GENERIC_OAUTH_CLIENT_SECRET = 'iZ1MbvC3ZaF25nbJli7IsKdRHAxfu3fn'; @@ -73,6 +78,27 @@ async function promptForPlatformAppCredentials(inquirerModule, clientId) { }; } +async function promptForPublicClientCredentials(inquirerModule) { + let clientId = ''; + // An empty Client ID would open an authorize URL that Box rejects, and the login would wait until it times out. + while (!clientId) { + const answer = await inquirerModule.prompt([ + { + type: 'input', + name: 'clientId', + message: 'Enter the Client ID of the Public Client App:', + }, + ]); + clientId = (answer.clientId ?? '').trim(); + } + + return { + useDefaultBoxApp: false, + publicClient: true, + clientId, + }; +} + async function promptForAuthMethod(inquirerModule) { const CLIENT_ID_MIN_LENGTH = 16; const CLIENT_ID_MAX_LENGTH = 99; @@ -83,7 +109,7 @@ async function promptForAuthMethod(inquirerModule) { type: 'input', name: 'choice', message: - 'How would you like to authenticate?\n[1] Log-in as a Box user (OAuth)\n[2] Use a Box Platform App\n[q] Quit\n? Enter 1, 2, or q:', + 'How would you like to authenticate?\n[1] Log-in as a Box user (OAuth)\n[2] Use a Box Platform App\n[3] Use a Box Platform Public Client App (PKCE, no client secret)\n[q] Quit\n? Enter 1, 2, 3, or q:', }, ]); @@ -101,6 +127,10 @@ async function promptForAuthMethod(inquirerModule) { return promptForPlatformAppCredentials(inquirerModule); } + if (trimmedChoice === '3') { + return promptForPublicClientCredentials(inquirerModule); + } + if (trimmedChoice.toLowerCase() === 'q') { return null; } @@ -119,6 +149,102 @@ async function promptForAuthMethod(inquirerModule) { } } +/** + * Build the message for a failed login. Token exchange errors are wrapped in a BoxCLIError, + * so the API response is read from the wrapped cause: the legacy SDK puts it in `response`, + * the generated SDK in `responseInfo`. + * + * @param {Error} error The login error + * @returns {string} The message to show + */ +function getLoginErrorMessage(error) { + for (const source of [error, error?.cause]) { + const description = + source?.response?.body?.error_description || + source?.responseInfo?.body?.error_description; + if (description) { + return description; + } + } + for (const source of [error, error?.cause]) { + const statusCode = + source?.response?.statusCode ?? + source?.response?.status ?? + source?.responseInfo?.statusCode; + if (statusCode) { + return `Request failed with status ${statusCode}`; + } + } + // Not an API error, e.g. a network failure: the wrapper's message alone does not say what went wrong. + const causeMessage = error?.cause?.message; + if (error?.message && causeMessage && causeMessage !== error.message) { + return `${error.message} ${causeMessage}`; + } + return error?.message || causeMessage || 'Unknown error'; +} + +/** + * Exchange the auth code with a client secret and cache the tokens. + * + * @param {BoxSDK} sdk Legacy SDK configured with the app's client ID and secret + * @param {string} environmentName Name of the environment to cache the tokens for + * @param {string} code Authorization code from the callback + * @param {string} redirectUri Redirect URI used in the authorize URL + * @param {string} [codeVerifier] PKCE code verifier, if the authorize URL had a code challenge + * @returns {Promise} The logged in user + */ +async function getConfidentialClientUser( + sdk, + environmentName, + code, + redirectUri, + codeVerifier +) { + const tokenInfo = await getTokenInfoByAuthCode( + sdk, + code, + redirectUri, + codeVerifier + ); + const tokenCache = new CLITokenCache(environmentName); + await new Promise((resolve, reject) => { + tokenCache.write(tokenInfo, (error) => { + if (error) { + reject(error); + } else { + resolve(); + } + }); + }); + const client = sdk.getPersistentClient(tokenInfo, tokenCache); + return client.users.get('me'); +} + +/** + * Exchange the auth code with the PKCE code verifier stored for the state, without a client secret. + * The auth's token storage is the environment's token cache, so the tokens are cached by the exchange. + * + * @param {BoxTSSDK.BoxPublicClientOAuth} auth Public client auth that built the authorize URL + * @param {BoxTSSDK.BoxClient} client TS SDK client using the auth + * @param {Object} query Callback query with `code` and `state` + * @returns {Promise} The logged in user + */ +async function getPublicClientUser(auth, client, query) { + try { + await auth.getTokensAuthorizationCodeGrant( + query.code, + query.state, + client.networkSession + ); + } catch (error) { + throw new BoxCLIError( + 'Failed to exchange auth code for tokens.', + error + ); + } + return client.users.getUserMe(); +} + class OAuthLoginCommand extends BoxCommand { async run() { const openModule = await import('open'); @@ -128,6 +254,7 @@ class OAuthLoginCommand extends BoxCommand { const { flags } = await this.parse(OAuthLoginCommand); const forceDefaultBoxApp = flags['default-box-app']; const forcePlatformApp = flags['platform-app']; + const forcePublicClient = flags['public-client']; let useDefaultBoxApp = false; const environmentsObject = await this.getEnvironments(); const port = flags.port; @@ -168,6 +295,7 @@ class OAuthLoginCommand extends BoxCommand { useDefaultBoxApp = true; environment.clientId = GENERIC_OAUTH_CLIENT_ID; environment.clientSecret = GENERIC_OAUTH_CLIENT_SECRET; + delete environment.publicClient; } else { useDefaultBoxApp = environment.clientId === GENERIC_OAUTH_CLIENT_ID && @@ -200,6 +328,17 @@ class OAuthLoginCommand extends BoxCommand { cacheTokens: true, authMethod: 'oauth20', }; + } else if (forcePublicClient) { + const answers = await promptForPublicClientCredentials(inquirer); + useDefaultBoxApp = false; + + environment = { + clientId: answers.clientId, + name: this.flags.name, + cacheTokens: true, + authMethod: 'oauth20', + publicClient: true, + }; } else if (forcePlatformApp) { const answers = await promptForPlatformAppCredentials(inquirer); useDefaultBoxApp = false; @@ -218,13 +357,21 @@ class OAuthLoginCommand extends BoxCommand { } useDefaultBoxApp = answers.useDefaultBoxApp; - environment = { - clientId: answers.clientId, - clientSecret: answers.clientSecret, - name: this.flags.name, - cacheTokens: true, - authMethod: 'oauth20', - }; + environment = answers.publicClient + ? { + clientId: answers.clientId, + name: this.flags.name, + cacheTokens: true, + authMethod: 'oauth20', + publicClient: true, + } + : { + clientId: answers.clientId, + clientSecret: answers.clientSecret, + name: this.flags.name, + cacheTokens: true, + authMethod: 'oauth20', + }; } if (isUnsupportedDefaultAppPort()) { @@ -240,11 +387,24 @@ class OAuthLoginCommand extends BoxCommand { version: package_.version, }, }); - const sdk = new BoxSDK({ - clientID: environment.clientId, - clientSecret: environment.clientSecret, - }); - this._configureSdk(sdk, sdkConfig); + const isPublicClient = isPublicClientEnvironment(environment); + let sdk; + let publicClientAuth; + let publicClientTsClient; + if (isPublicClient) { + // The legacy SDK requires a client secret, so public clients log in with the generated SDK. + ({ auth: publicClientAuth, client: publicClientTsClient } = + createPublicClientTsClient(this, { + clientId: environment.clientId, + tokenStorage: new CLITokenCache(environmentName), + })); + } else { + sdk = new BoxSDK({ + clientID: environment.clientId, + clientSecret: environment.clientSecret, + }); + this._configureSdk(sdk, sdkConfig); + } const app = express(); let callbackHandled = false; @@ -337,24 +497,19 @@ class OAuthLoginCommand extends BoxCommand { ); } assertValidOAuthCode(request.query.code); - const tokenInfo = await getTokenInfoByAuthCode( - sdk, - request.query.code, - redirectUri, - pkce?.codeVerifier - ); - const tokenCache = new CLITokenCache(environmentName); - await new Promise((resolve, reject) => { - tokenCache.write(tokenInfo, (error) => { - if (error) { - reject(error); - } else { - resolve(); - } - }); - }); - const client = sdk.getPersistentClient(tokenInfo, tokenCache); - const user = await client.users.get('me'); + const user = isPublicClient + ? await getPublicClientUser( + publicClientAuth, + publicClientTsClient, + request.query + ) + : await getConfidentialClientUser( + sdk, + environmentName, + request.query.code, + redirectUri, + pkce?.codeVerifier + ); environmentsObject.environments[environmentName] = environment; environmentsObject.default = environmentName; @@ -385,15 +540,7 @@ class OAuthLoginCommand extends BoxCommand { ); } } catch (error) { - const statusCode = - error?.response?.statusCode ?? error?.response?.status; - const errorMessage = - error?.response?.body?.error_description || - (statusCode - ? `Request failed with status ${statusCode}` - : null) || - error?.message || - 'Unknown error'; + const errorMessage = getLoginErrorMessage(error); DEBUG.execute('Login error: %O', error); this.info(chalk`{red Login failed: ${errorMessage}}`); res.status(500).send( @@ -414,16 +561,22 @@ class OAuthLoginCommand extends BoxCommand { spinner.succeed(); // the URL to redirect the user to - const authorizeUrl = sdk.getAuthorizeURL({ - response_type: 'code', - state, - redirect_uri: redirectUri, - ...(useDefaultBoxApp - ? { - code_challenge: pkce.codeChallenge, - } - : {}), - }); + const authorizeUrl = isPublicClient + ? await getPublicClientAuthorizeUrl(publicClientAuth, { + redirectUri, + state, + authorizeRootURL: this.settings.authorizeRootURL, + }) + : sdk.getAuthorizeURL({ + response_type: 'code', + state, + redirect_uri: redirectUri, + ...(useDefaultBoxApp + ? { + code_challenge: pkce.codeChallenge, + } + : {}), + }); if (flags.code) { this.info( chalk`{green Please open ${authorizeUrl} to authorize the application and read parameters from the URL accessed after authorization.}` @@ -477,6 +630,9 @@ OAuthLoginCommand.description = ' (2) Your own Platform OAuth App\n' + ' Enter your Client ID and Client Secret when prompted. Use --platform-app to skip the prompt.\n' + '\n' + + ' (3) Your own Platform OAuth public client App\n' + + ' For apps registered as a public client, which have no client secret. Enter your Client ID when prompted; the login is protected with PKCE. Use --public-client to skip the prompt.\n' + + '\n' + 'Quickstart: run "box login -d" to sign in immediately. A browser window will open for authorization. Once access is granted, the environment is created and set as default — you can start running commands right away.\n' + '\n' + 'Headless environments: use --code (-c) if no browser is available. The CLI will display an authorize URL — visit it in an external browser, authorize and grant access to the app, then provide the state and authorization code back to the CLI when prompted.'; @@ -506,14 +662,23 @@ OAuthLoginCommand.flags = { 'This is the fastest way to integrate with Box — no app creation in the Developer Console is needed.\n' + 'Scopes are limited to content actions, allowing you to effectively operate with your files and folders.\n' + 'This flow requires a local callback server on a supported port (3000, 3001, 4000, 5000, or 8080). The default port is 3000; use --port to change it.', - exclusive: ['platform-app'], + exclusive: ['platform-app', 'public-client'], default: false, }), 'platform-app': Flags.boolean({ description: 'Skip the authentication method prompt and go directly to Platform App setup.\n' + 'You will be prompted for Client ID and Client Secret.', - exclusive: ['default-box-app'], + exclusive: ['default-box-app', 'public-client'], + default: false, + }), + 'public-client': Flags.boolean({ + description: + 'Skip the authentication method prompt and go directly to public client app setup.\n' + + 'Use this for an OAuth 2.0 app registered in the Developer Console as a public client, which has no client secret. ' + + 'Every login is protected with PKCE. You will be prompted for the Client ID only.\n' + + 'Cannot be combined with --reauthorize. To reauthorize a public client environment, run "box login --reauthorize --name ".', + exclusive: ['default-box-app', 'platform-app', 'reauthorize'], default: false, }), reauthorize: Flags.boolean({ @@ -534,6 +699,8 @@ module.exports._test = { SUPPORTED_DEFAULT_APP_PORTS, promptForAuthMethod, promptForPlatformAppCredentials, + promptForPublicClientCredentials, + getLoginErrorMessage, setOAuthCallbackTimeoutMs(timeoutMs) { oauthCallbackTimeoutMs = timeoutMs; }, diff --git a/src/commands/logout.js b/src/commands/logout.js index e5117df3..410781e9 100644 --- a/src/commands/logout.js +++ b/src/commands/logout.js @@ -2,11 +2,16 @@ const BoxCommand = require('../box-command'); const BoxSDK = require('box-node-sdk').default; +const BoxTsErrors = require('box-node-sdk/sdk-gen/box/errors'); const CLITokenCache = require('../token-cache'); const chalk = require('chalk'); const inquirer = require('../inquirer'); const pkg = require('../../package.json'); const { Flags } = require('@oclif/core'); +const { + isPublicClientEnvironment, + createPublicClientTsClient, +} = require('../public-client'); const SDK_CONFIG = Object.freeze({ analyticsClient: { version: pkg.version }, @@ -95,7 +100,10 @@ class OAuthLogoutCommand extends BoxCommand { let thrownError; const { clientId, clientSecret } = this.getClientCredentials(environment); - if (!clientId || !clientSecret) { + if (isPublicClientEnvironment(environment)) { + ({ response, thrownError } = + await this.revokePublicClientToken(tokenCache, environment)); + } else if (!clientId || !clientSecret) { thrownError = new Error('Invalid client credentials.'); response = undefined; } else { @@ -146,6 +154,35 @@ class OAuthLogoutCommand extends BoxCommand { ); } + /** + * Revoke the cached token of a public client environment, which has no client secret. + * The result has the same shape as the legacy SDK revoke response, so it is handled the same way. + * + * @param {CLITokenCache} tokenCache Token cache of the environment + * @param {Object} environment The environment + * @returns {Promise<{response: (Object|undefined), thrownError: (Error|undefined)}>} Revoke result + */ + async revokePublicClientToken(tokenCache, environment) { + try { + const { auth, client } = createPublicClientTsClient(this, { + clientId: environment.clientId, + tokenStorage: tokenCache, + }); + await auth.revokeToken(client.networkSession); + return { response: { statusCode: 200 } }; + } catch (error) { + if (error instanceof BoxTsErrors.BoxApiError && error.responseInfo) { + return { + response: { + statusCode: error.responseInfo.statusCode, + body: error.responseInfo.body, + }, + }; + } + return { thrownError: error }; + } + } + getClientCredentials(environment) { if (environment.boxConfigFilePath) { try { diff --git a/src/commands/tokens/revoke.js b/src/commands/tokens/revoke.js index c8586bc6..c648cf84 100644 --- a/src/commands/tokens/revoke.js +++ b/src/commands/tokens/revoke.js @@ -3,11 +3,40 @@ const BoxCommand = require('../../box-command'); const { Args } = require('@oclif/core'); const chalk = require('chalk'); +const { + AuthorizationManager, +} = require('box-node-sdk/sdk-gen/managers/authorization'); +const BoxTsErrors = require('box-node-sdk/sdk-gen/box/errors'); class TokensRevokeCommand extends BoxCommand { async run() { const { args } = await this.parse(TokensRevokeCommand); + if (this.usesPublicClientAuth()) { + // The legacy SDK always sends a client secret, which public clients do not have. + // The manager gets no auth, so the environment's own token is not sent with the request. + const authorizationManager = new AuthorizationManager({ + networkSession: this.tsClient.networkSession, + }); + try { + await authorizationManager.revokeAccessToken({ + clientId: this._publicClientAuth.config.clientId, + token: args.token, + }); + this.info(chalk`{green Token revoked.}`); + } catch (error) { + if (!(error instanceof BoxTsErrors.BoxApiError)) { + throw error; + } + // The SDK does not read the body of revoke responses, so Box's error description is not available. + const reason = + error.responseInfo?.body?.error_description ?? + `Request failed with status ${error.responseInfo?.statusCode}`; + this.info(chalk`{redBright Error revoking token! ${reason}}`); + } + return; + } + let response = await this.sdk.revokeTokens(args.token); if (response.statusCode === 200) { diff --git a/src/public-client-session-adapter.js b/src/public-client-session-adapter.js new file mode 100644 index 00000000..9e524f84 --- /dev/null +++ b/src/public-client-session-adapter.js @@ -0,0 +1,218 @@ +'use strict'; + +const BluebirdPromise = require('bluebird'); +const DEBUG = require('./debug'); +const { + createReauthorizeError, + isInvalidGrantError, +} = require('./public-client'); + +/** + * Legacy SDK session that gets tokens from the generated SDK's + * `BoxPublicClientOAuth`, so commands still using the legacy `BoxClient` work + * in public client environments. The legacy SDK only knows OAuth with a client + * secret, so refresh, downscope and revoke all go through the generated SDK auth. + * + * The legacy client chains Bluebird-only methods (`asCallback`) on everything + * a session returns, so every public method returns a Bluebird promise. + */ +class PublicClientSessionAdapter { + /** + * @param {BoxPublicClientOAuth} auth Generated SDK auth. Its token storage is shared with the generated SDK client. + * @param {Object} options Adapter options + * @param {string} options.environmentName Name of the CLI environment, used in reauthorize hints + * @param {number} options.expiryBufferMS Tokens expiring within this window are treated as expired + * @param {NetworkSession} options.networkSession Generated SDK network session used for token requests + * @param {Object} [options.initialToken] Token already read from the token cache, in its format + */ + constructor( + auth, + { environmentName, expiryBufferMS, networkSession, initialToken } + ) { + this._auth = auth; + this._environmentName = environmentName; + this._expiryBufferMS = expiryBufferMS; + this._networkSession = networkSession; + this._refreshPromise = null; + this._forceRefresh = false; + // Token in the CLI token cache format. Kept in memory like the built-in persistent + // session does, so the token cache (secure storage or file) is not read on every request. + this._token = initialToken?.accessToken ? initialToken : null; + } + + /** + * Get a valid access token, refreshing it when it is missing or about to expire. + * + * @returns {Promise} Bluebird promise resolving to the access token + */ + getAccessToken() { + return BluebirdPromise.resolve(this._getValidToken()).then( + (token) => token.accessToken + ); + } + + /** + * Downscope the current access token. Resolves to legacy SDK token info, + * which is what the legacy `BoxClient.exchangeToken()` returns. + * + * @param {string[]} scopes Scopes of the new token + * @param {string} [resource] Full URL of the item to restrict the token to + * @returns {Promise} Bluebird promise resolving to the token info + */ + exchangeToken(scopes, resource) { + return BluebirdPromise.resolve( + this._getValidToken().then(() => + this._auth.downscopeToken( + scopes, + resource ?? undefined, + undefined, + this._networkSession + ) + ) + ).then((token) => ({ + accessToken: token.accessToken, + accessTokenTTLMS: token.expiresIn * 1000, + acquiredAtMS: Date.now(), + })); + } + + /** + * Revoke the current tokens and remove them from the token cache. + * Part of the legacy session interface (`BoxClient.revokeTokens()`), not used by CLI commands today. + * + * @returns {Promise} Bluebird promise resolving when the tokens are revoked + */ + revokeTokens() { + return BluebirdPromise.resolve( + this._auth + .revokeToken(this._networkSession) + .then(() => this._auth.tokenStorage.clear()) + ); + } + + /** + * Called by the legacy client when the API rejects the access token as expired. + * Unlike the built-in persistent session, the token cache is not cleared, + * since it holds the refresh token. Instead the cached access token is + * marked as expired, so the next request, also in a later command, + * refreshes it. + * + * @param {Error} error The expired-token error from the API + * @returns {Promise} Bluebird promise rejecting with the given error + */ + handleExpiredTokensError(error) { + this._forceRefresh = true; + return BluebirdPromise.resolve(this._markCachedTokenExpired()).then( + () => { + throw error; + } + ); + } + + async _markCachedTokenExpired() { + // A running refresh is about to write new tokens. Writing back the token read here + // could overwrite them with the refresh token the refresh just used up. + if (this._refreshPromise) { + return; + } + try { + const token = await this._auth.tokenStorage.get(); + // Only the token this command used was rejected. A different token means another + // CLI process refreshed in the meantime, and its new refresh token must be kept. + if ( + token?.accessToken && + token.refreshToken && + token.accessToken === this._token?.accessToken + ) { + await this._auth.tokenStorage.store({ + accessToken: token.accessToken, + refreshToken: token.refreshToken, + expiresIn: 0, + }); + } + } catch (error) { + // The API error is what the user needs to see, so a cache failure must not replace it. + DEBUG.execute('Could not mark cached token as expired: %O', error); + } + } + + async _getValidToken() { + if (!this._token) { + const cachedToken = await this._auth.tokenStorage.get(); + if (!cachedToken?.accessToken) { + throw createReauthorizeError(this._environmentName); + } + this._token = cachedToken; + } + if (!this._forceRefresh && !this._isExpired(this._token)) { + return this._token; + } + return this._refresh(); + } + + _refresh() { + if (!this._refreshPromise) { + this._refreshPromise = this._refreshOnce().finally(() => { + this._refreshPromise = null; + }); + } + return this._refreshPromise; + } + + async _refreshOnce() { + const tokenBeforeRefresh = await this._auth.tokenStorage.get(); + const usedRefreshToken = tokenBeforeRefresh?.refreshToken; + try { + const token = await this._auth.refreshToken(this._networkSession); + return this._useToken({ + accessToken: token.accessToken, + refreshToken: token.refreshToken, + accessTokenTTLMS: token.expiresIn * 1000, + acquiredAtMS: Date.now(), + }); + } catch (error) { + if (!isInvalidGrantError(error)) { + throw error; + } + // A refresh token works once. If another CLI process refreshed first, its new tokens are in the cache. + const latestToken = await this._auth.tokenStorage.get(); + if ( + latestToken?.accessToken && + latestToken.refreshToken !== usedRefreshToken && + !this._isExpired(latestToken) + ) { + return this._useToken(latestToken); + } + throw createReauthorizeError(this._environmentName, error); + } + } + + _useToken(token) { + this._token = token; + this._forceRefresh = false; + return token; + } + + /** + * The CLI token cache stamps tokens with their acquisition time and TTL. + * A token without them cannot be dated, so it is refreshed. + * + * @param {Object} token Token read from the token cache + * @returns {boolean} True if the token must be refreshed before use + * @private + */ + _isExpired(token) { + if ( + typeof token.acquiredAtMS !== 'number' || + typeof token.accessTokenTTLMS !== 'number' + ) { + return true; + } + return ( + Date.now() + this._expiryBufferMS >= + token.acquiredAtMS + token.accessTokenTTLMS + ); + } +} + +module.exports = PublicClientSessionAdapter; diff --git a/src/public-client.js b/src/public-client.js new file mode 100644 index 00000000..7650aff7 --- /dev/null +++ b/src/public-client.js @@ -0,0 +1,132 @@ +'use strict'; + +const BoxTSSDK = require('box-node-sdk/sdk-gen'); +const BoxCLIError = require('./cli-error'); +const pkg = require('../package.json'); + +const SDK_AUTHORIZE_ROOT_URL = 'https://account.box.com/api'; + +/** + * Check whether a CLI environment authenticates as an OAuth 2.0 public client (PKCE, no client secret) + * + * @param {Object} [environment] A CLI environment + * @returns {boolean} True for public client environments + */ +function isPublicClientEnvironment(environment) { + return ( + environment?.authMethod === 'oauth20' && environment.publicClient === true + ); +} + +/** + * Build the generated SDK public client auth. + * + * @param {Object} options Options + * @param {string} options.clientId Client ID of the public client app + * @param {TokenStorage} [options.tokenStorage] Token storage, in-memory if not given + * @returns {BoxTSSDK.BoxPublicClientOAuth} The public client auth + */ +function createPublicClientAuth({ clientId, tokenStorage }) { + const config = new BoxTSSDK.PublicOAuthConfig({ + clientId, + ...(tokenStorage ? { tokenStorage } : {}), + }); + return new BoxTSSDK.BoxPublicClientOAuth({ config }); +} + +/** + * Build the public client auth and a TS SDK client that uses it, configured with + * the command's settings (proxy, base URLs, analytics header). + * + * @param {BoxCommand} command The command, whose `_configureTsSdk` applies the CLI settings + * @param {Object} options Options + * @param {string} options.clientId Client ID of the public client app + * @param {TokenStorage} [options.tokenStorage] Token storage, in-memory if not given + * @returns {{auth: BoxTSSDK.BoxPublicClientOAuth, client: BoxTSSDK.BoxClient}} The auth and the configured client + */ +function createPublicClientTsClient(command, { clientId, tokenStorage }) { + const auth = createPublicClientAuth({ clientId, tokenStorage }); + // _configureTsSdk adds headers to the config it gets, so every client needs its own. + const client = command._configureTsSdk(new BoxTSSDK.BoxClient({ auth }), { + request: { headers: { 'User-Agent': `Box CLI v${pkg.version}` } }, + }); + return { auth, client }; +} + +/** + * Build the authorize URL for a public client login, honoring the authorizeRootURL setting. + * + * @param {BoxTSSDK.BoxPublicClientOAuth} auth The public client auth. Stores the PKCE code verifier for the state. + * @param {Object} options Options + * @param {string} options.redirectUri Redirect URI registered for the app + * @param {string} options.state OAuth state + * @param {string} [options.authorizeRootURL] Custom authorize root URL from CLI settings + * @returns {Promise} The authorize URL + */ +async function getPublicClientAuthorizeUrl( + auth, + { redirectUri, state, authorizeRootURL } +) { + const url = await auth.getAuthorizeUrl({ redirectUri, state }); + if (!authorizeRootURL || !url.startsWith(SDK_AUTHORIZE_ROOT_URL)) { + return url; + } + return `${authorizeRootURL.replace(/\/+$/u, '')}${url.slice(SDK_AUTHORIZE_ROOT_URL.length)}`; +} + +/** + * Error for a public client environment whose tokens are missing or can no longer be refreshed. + * + * @param {string} environmentName Name of the environment + * @param {Error} [cause] The underlying error + * @returns {BoxCLIError} The error to throw + */ +function createReauthorizeError(environmentName, cause) { + const reason = cause + ? 'Your refresh token has expired or was revoked.' + : `No tokens are cached for environment "${environmentName}".`; + return new BoxCLIError( + `${reason}\nPlease run "box login --name ${environmentName} --reauthorize" to reauthorize the environment and then run your command again.`, + cause + ); +} + +/** + * Whether an error from the generated SDK is the OAuth `invalid_grant` error, + * which the token endpoint returns for an expired or revoked refresh token. + * + * @param {Error} error The error + * @returns {boolean} True for invalid_grant errors + */ +function isInvalidGrantError(error) { + return error?.responseInfo?.body?.error === 'invalid_grant'; +} + +/** + * Whether an error from the generated SDK means the refresh token was rejected: + * `invalid_grant` from a `grant_type=refresh_token` request. Other token requests, + * such as downscoping, can also return `invalid_grant` for unrelated reasons. + * + * @param {Error} error The error + * @returns {boolean} True if the refresh token is expired or revoked + */ +function isRefreshTokenRejectedError(error) { + if (!isInvalidGrantError(error)) { + return false; + } + const requestBody = error.requestInfo?.body; + return ( + typeof requestBody === 'string' && + new URLSearchParams(requestBody).get('grant_type') === 'refresh_token' + ); +} + +module.exports = { + isPublicClientEnvironment, + createPublicClientAuth, + createPublicClientTsClient, + getPublicClientAuthorizeUrl, + createReauthorizeError, + isInvalidGrantError, + isRefreshTokenRejectedError, +}; diff --git a/src/token-cache.js b/src/token-cache.js index a4b7cac8..dd75611c 100644 --- a/src/token-cache.js +++ b/src/token-cache.js @@ -175,9 +175,10 @@ class CLITokenCache { } /** - * Delete the token from both secure storage and file system - * @param {Function} callback The callback to pass results to - * @returns {void} + * Delete the token from both secure storage and file system. + * Without a callback, returns a promise, as the TS SDK token storage contract requires. + * @param {Function} [callback] The callback to pass results to + * @returns {Promise|void} A promise when called without a callback */ clear(callback) { const promises = []; @@ -235,11 +236,17 @@ class CLITokenCache { }) ); - Promise.all(promises) - .then(() => callback()) - .catch((error) => - callback(new BoxCLIError('Failed to delete token cache', error)) - ); + const cleared = (async () => { + try { + await Promise.all(promises); + } catch (error) { + throw new BoxCLIError('Failed to delete token cache', error); + } + })(); + if (typeof callback !== 'function') { + return cleared; + } + cleared.then(() => callback(), callback); } /** diff --git a/test/commands/login.test.js b/test/commands/login.test.js index c90eb7c6..abedc66b 100644 --- a/test/commands/login.test.js +++ b/test/commands/login.test.js @@ -11,6 +11,9 @@ const { getTokenInfoByAuthCode, } = require('../../src/login-helper'); const OAuthLoginCommand = require('../../src/commands/login'); +const CLITokenCache = require('../../src/token-cache'); +const BoxCLIError = require('../../src/cli-error'); +const { createHash } = require('node:crypto'); // Send a single callback request once the test decides flow timing. // Keeping this as a tiny helper makes callback assertions easier to read. @@ -189,8 +192,147 @@ describe('Login', function () { }); it('should mark --platform-app and --default-box-app as mutually exclusive', function () { - assert.deepInclude(OAuthLoginCommand.flags['platform-app'], { - exclusive: ['default-box-app'], + assert.include( + OAuthLoginCommand.flags['platform-app'].exclusive, + 'default-box-app' + ); + }); + + it('should expose --public-client flag, exclusive with the other app flags', function () { + assert.property(OAuthLoginCommand.flags, 'public-client'); + assert.sameMembers( + OAuthLoginCommand.flags['public-client'].exclusive, + ['default-box-app', 'platform-app', 'reauthorize'] + ); + assert.include( + OAuthLoginCommand.flags['default-box-app'].exclusive, + 'public-client' + ); + assert.include( + OAuthLoginCommand.flags['platform-app'].exclusive, + 'public-client' + ); + }); + }); + + describe('public client with --reauthorize', function () { + test.stub(BoxCommand.prototype, '_loadSettings', (stub) => + stub.resolves({}) + ) + .stderr() + .command([ + 'login', + '--reauthorize', + '-n', + 'my-app', + '--public-client', + ]) + .it( + 'should reject --public-client combined with --reauthorize', + (ctx) => { + assert.include(ctx.stderr, '--public-client'); + assert.include(ctx.stderr, '--reauthorize'); + assert.include(ctx.stderr, 'cannot also be provided'); + } + ); + }); + + describe('getLoginErrorMessage', function () { + const { getLoginErrorMessage } = OAuthLoginCommand._test; + + it('should show the error description from a wrapped API error', function () { + const error = new BoxCLIError( + 'Failed to exchange auth code for tokens.', + Object.assign(new Error('Request failed'), { + responseInfo: { + statusCode: 400, + body: { error_description: 'Invalid redirect URI' }, + }, + }) + ); + + assert.equal(getLoginErrorMessage(error), 'Invalid redirect URI'); + }); + + it('should add the cause to the message when the wrapped error is not an API error', function () { + const error = new BoxCLIError( + 'Failed to exchange auth code for tokens.', + new Error('No code verifier found for the given state.') + ); + + assert.equal( + getLoginErrorMessage(error), + 'Failed to exchange auth code for tokens. No code verifier found for the given state.' + ); + }); + + it('should show the message of an error without a cause', function () { + assert.equal( + getLoginErrorMessage(new Error('connect ECONNREFUSED')), + 'connect ECONNREFUSED' + ); + }); + }); + + describe('public client prompts', function () { + it('should prompt for a public client ID only when user enters "3"', async function () { + const promptStub = sandbox + .stub() + .onFirstCall() + .resolves({ choice: '3' }) + .onSecondCall() + .resolves({ clientId: ' public-client-id ' }); + + const result = await OAuthLoginCommand._test.promptForAuthMethod({ + prompt: promptStub, + }); + + assert.strictEqual(promptStub.callCount, 2); + assert.strictEqual( + promptStub.secondCall.args[0][0].message, + 'Enter the Client ID of the Public Client App:' + ); + assert.deepEqual(result, { + useDefaultBoxApp: false, + publicClient: true, + clientId: 'public-client-id', + }); + }); + + it('should ask again until the Client ID is not empty', async function () { + const promptStub = sandbox + .stub() + .onFirstCall() + .resolves({ clientId: '' }) + .onSecondCall() + .resolves({ clientId: ' ' }) + .onThirdCall() + .resolves({ clientId: 'public-client-id' }); + + const result = + await OAuthLoginCommand._test.promptForPublicClientCredentials({ + prompt: promptStub, + }); + + assert.strictEqual(promptStub.callCount, 3); + assert.strictEqual(result.clientId, 'public-client-id'); + }); + + it('should not prompt for a client secret', async function () { + const promptStub = sandbox + .stub() + .resolves({ clientId: 'public-client-id' }); + + const result = + await OAuthLoginCommand._test.promptForPublicClientCredentials({ + prompt: promptStub, + }); + + assert.isTrue(promptStub.calledOnce); + assert.deepEqual(result, { + useDefaultBoxApp: false, + publicClient: true, + clientId: 'public-client-id', }); }); }); @@ -320,8 +462,12 @@ describe('Login', function () { '[1] Log-in as a Box user (OAuth)' ); assert.include(promptConfig.message, '[2] Use a Box Platform App'); + assert.include( + promptConfig.message, + '[3] Use a Box Platform Public Client App (PKCE, no client secret)' + ); assert.include(promptConfig.message, '[q] Quit'); - assert.include(promptConfig.message, 'Enter 1, 2, or q:'); + assert.include(promptConfig.message, 'Enter 1, 2, 3, or q:'); }); it('should return null when user enters q to quit', async function () { @@ -680,4 +826,232 @@ describe('Login', function () { } ); }); + + describe('public client login', function () { + const PUBLIC_CLIENT_ID = 'public-client-id'; + let port; + let authorizeUrl; + let callbackStatusPromise; + let savedEnvironments; + let cachedTokenInfo; + + // .command() reads its args when the test runs, so the port can be set here. + // Pass a failedTokenResponse to make the token endpoint reject the authorization code. + function publicClientLoginTest(environments, args, failedTokenResponse) { + return test + .do(async () => { + port = await findFreePort([19_095, 19_096, 19_097, 19_098]); + args[args.length - 1] = String(port); + savedEnvironments = null; + cachedTokenInfo = {}; + callbackStatusPromise = null; + OAuthLoginCommand._test.setOAuthCallbackTimeoutMs(2000); + OAuthLoginCommand._test.setOpenAuthorizeInBrowser( + (openFn, apps, url) => { + authorizeUrl = new URL(url); + callbackStatusPromise = sendCallback( + `http://localhost:${port}/callback?state=${authorizeUrl.searchParams.get('state')}&code=auth-code` + ); + } + ); + }) + .stub(BoxCommand.prototype, '_loadSettings', (stub) => + stub.resolves({}) + ) + .stub(BoxCommand.prototype, 'getEnvironments', (stub) => + stub.callsFake(async () => structuredClone(environments)) + ) + .stub(BoxCommand.prototype, 'updateEnvironments', (stub) => + stub.callsFake(async (updated) => { + savedEnvironments = updated; + }) + ) + .stub(CLITokenCache.prototype, 'read', (stub) => + stub.callsFake((callback) => callback(null, cachedTokenInfo)) + ) + .stub(CLITokenCache.prototype, 'write', (stub) => + stub.callsFake((tokenInfo, callback) => { + cachedTokenInfo = tokenInfo; + callback(); + }) + ) + .nock('https://api.box.com', (api) => { + const tokenRequest = api.post('/oauth2/token', (body) => { + // PKCE: no client secret, and the verifier must match the challenge in the authorize URL + assert.deepEqual(Object.keys(body).sort(), [ + 'client_id', + 'code', + 'code_verifier', + 'grant_type', + ]); + assert.equal(body.grant_type, 'authorization_code'); + assert.equal(body.client_id, PUBLIC_CLIENT_ID); + assert.equal(body.code, 'auth-code'); + assert.equal( + createHash('sha256') + .update(body.code_verifier) + .digest('base64url'), + authorizeUrl.searchParams.get('code_challenge') + ); + return true; + }); + if (failedTokenResponse) { + tokenRequest.reply( + failedTokenResponse.status, + failedTokenResponse.body + ); + return; + } + tokenRequest + .reply(200, { + access_token: 'public-access-token', + refresh_token: 'public-refresh-token', + expires_in: 3600, + token_type: 'bearer', + restricted_to: [], + }) + .get('/2.0/users/me') + .matchHeader('Authorization', 'Bearer public-access-token') + .reply(200, { + type: 'user', + id: '33333', + login: 'public@example.com', + }); + }); + } + + const failedLoginArgs = ['login', '--public-client', '--port', 'PORT']; + publicClientLoginTest( + { default: '', environments: {} }, + failedLoginArgs, + { + status: 400, + body: { + error: 'invalid_grant', + error_description: 'The redirect URI is missing or does not match', + }, + } + ) + .stub(inquirer, 'prompt', (stub) => + stub.resolves({ clientId: PUBLIC_CLIENT_ID }) + ) + .stderr() + .command(failedLoginArgs) + .it( + 'should show the reason from Box when the token exchange fails', + async (ctx) => { + assert.strictEqual(await callbackStatusPromise, 500); + assert.include( + ctx.stderr, + 'Login failed: The redirect URI is missing or does not match' + ); + assert.isNull(savedEnvironments); + } + ); + + const loginArgs = ['login', '--public-client', '--port', 'PORT']; + publicClientLoginTest({ default: '', environments: {} }, loginArgs) + .stub(inquirer, 'prompt', (stub) => + stub.resolves({ clientId: PUBLIC_CLIENT_ID }) + ) + .stderr() + .command(loginArgs) + .it( + 'should log in with PKCE and create a public client environment without a secret', + async (ctx) => { + assert.strictEqual(await callbackStatusPromise, 200); + assert.include( + ctx.stderr, + 'Successfully logged in as public@example.com!' + ); + assert.equal( + authorizeUrl.origin + authorizeUrl.pathname, + 'https://account.box.com/api/oauth2/authorize' + ); + assert.equal( + authorizeUrl.searchParams.get('client_id'), + PUBLIC_CLIENT_ID + ); + assert.equal( + authorizeUrl.searchParams.get('redirect_uri'), + `http://localhost:${port}/callback` + ); + assert.equal( + authorizeUrl.searchParams.get('code_challenge_method'), + 'S256' + ); + assert.deepEqual(savedEnvironments, { + default: 'oauth', + environments: { + oauth: { + clientId: PUBLIC_CLIENT_ID, + name: 'oauth', + cacheTokens: true, + authMethod: 'oauth20', + publicClient: true, + }, + }, + }); + assert.equal( + cachedTokenInfo.accessToken, + 'public-access-token' + ); + assert.equal( + cachedTokenInfo.refreshToken, + 'public-refresh-token' + ); + } + ); + + const reauthorizeArgs = [ + 'login', + '--reauthorize', + '-n', + 'public-env', + '--port', + 'PORT', + ]; + let promptStub; + publicClientLoginTest( + { + default: 'public-env', + environments: { + 'public-env': { + clientId: PUBLIC_CLIENT_ID, + name: 'public-env', + cacheTokens: true, + authMethod: 'oauth20', + publicClient: true, + }, + }, + }, + reauthorizeArgs + ) + .do(() => { + promptStub = sandbox.stub(inquirer, 'prompt'); + }) + .stderr() + .command(reauthorizeArgs) + .it( + 'should reauthorize a public client environment with PKCE without prompting', + async (ctx) => { + assert.strictEqual(await callbackStatusPromise, 200); + assert.isTrue(promptStub.notCalled); + assert.include( + ctx.stderr, + 'Environment "public-env" has been updated' + ); + assert.deepEqual( + savedEnvironments.environments['public-env'], + { + clientId: PUBLIC_CLIENT_ID, + name: 'public-env', + cacheTokens: true, + authMethod: 'oauth20', + publicClient: true, + } + ); + } + ); + }); }); diff --git a/test/public-client-auth.test.js b/test/public-client-auth.test.js new file mode 100644 index 00000000..816ea319 --- /dev/null +++ b/test/public-client-auth.test.js @@ -0,0 +1,374 @@ +'use strict'; + +const { test } = require('@oclif/test'); +const { assert } = require('chai'); +const sinon = require('sinon'); +const BoxCommand = require('../src/box-command'); +const CLITokenCache = require('../src/token-cache'); +const { TEST_API_ROOT } = require('./helpers/test-helper'); + +const CLIENT_ID = 'public-client-id'; +const ENVIRONMENT_NAME = 'public-env'; +const ONE_HOUR_MS = 60 * 60 * 1000; + +// A public client has no secret, so refresh requests must not carry one. +function mockRefreshTokenRequest(api) { + return api + .post('/oauth2/token', (body) => { + assert.deepEqual(body, { + grant_type: 'refresh_token', + client_id: CLIENT_ID, + refresh_token: 'cached-refresh-token', + }); + return true; + }) + .reply(200, { + access_token: 'refreshed-access-token', + refresh_token: 'refreshed-refresh-token', + expires_in: 3600, + token_type: 'bearer', + restricted_to: [], + }); +} + +describe('Public client (PKCE) authentication', function () { + let environments; + let cachedTokenInfo; + + function useEnvironment(overrides = {}) { + environments = { + default: ENVIRONMENT_NAME, + environments: { + [ENVIRONMENT_NAME]: { + name: ENVIRONMENT_NAME, + authMethod: 'oauth20', + publicClient: true, + clientId: CLIENT_ID, + cacheTokens: true, + ...overrides, + }, + }, + }; + } + + function cacheToken(overrides = {}) { + cachedTokenInfo = { + accessToken: 'cached-access-token', + refreshToken: 'cached-refresh-token', + accessTokenTTLMS: ONE_HOUR_MS, + acquiredAtMS: Date.now(), + ...overrides, + }; + } + + function expireCachedToken() { + cacheToken({ acquiredAtMS: Date.now() - 2 * ONE_HOUR_MS }); + } + + // Token cache backed by memory, so tests never touch secure storage or disk. + function publicClientTest() { + return test + .stub(BoxCommand.prototype, 'getEnvironments', (stub) => + stub.callsFake(() => Promise.resolve(environments)) + ) + .stub(CLITokenCache.prototype, 'read', (stub) => + stub.callsFake((callback) => callback(null, cachedTokenInfo)) + ) + .stub(CLITokenCache.prototype, 'write', (stub) => + stub.callsFake((tokenInfo, callback) => { + cachedTokenInfo = tokenInfo; + callback(); + }) + ) + .stub(CLITokenCache.prototype, 'clear', (stub) => + stub.callsFake((callback) => { + cachedTokenInfo = {}; + callback(); + }) + ); + } + + beforeEach(function () { + useEnvironment(); + cacheToken(); + }); + + afterEach(function () { + sinon.restore(); + }); + + describe('legacy SDK client commands', function () { + publicClientTest() + .nock(TEST_API_ROOT, (api) => + api + .get('/2.0/users/me') + .matchHeader('Authorization', 'Bearer cached-access-token') + .reply(200, { type: 'user', id: '33333' }) + ) + .stdout() + .command(['users:get', 'me', '--json']) + .it('should use the cached access token', (context) => { + assert.equal(JSON.parse(context.stdout).id, '33333'); + // Secure storage reads are IPC calls, so the token cache is read once per command + assert.equal(CLITokenCache.prototype.read.callCount, 1); + }); + + publicClientTest() + .do(() => expireCachedToken()) + .nock(TEST_API_ROOT, (api) => + mockRefreshTokenRequest(api) + .get('/2.0/users/me') + .matchHeader( + 'Authorization', + 'Bearer refreshed-access-token' + ) + .reply(200, { type: 'user', id: '33333' }) + ) + .stdout() + .command(['users:get', 'me', '--json']) + .it( + 'should refresh an expired token without a client secret and cache it', + (context) => { + assert.equal(JSON.parse(context.stdout).id, '33333'); + assert.equal( + cachedTokenInfo.accessToken, + 'refreshed-access-token' + ); + assert.equal( + cachedTokenInfo.refreshToken, + 'refreshed-refresh-token' + ); + } + ); + + publicClientTest() + .do(() => expireCachedToken()) + .nock(TEST_API_ROOT, (api) => + api.post('/oauth2/token').reply(400, { + error: 'invalid_grant', + error_description: 'Refresh token has expired', + }) + ) + .stderr() + .command(['users:get', 'me', '--no-color']) + .it( + 'should ask to reauthorize when the refresh token has expired', + (context) => { + assert.include( + context.stderr, + 'Your refresh token has expired' + ); + assert.include( + context.stderr, + `box login --name ${ENVIRONMENT_NAME} --reauthorize` + ); + } + ); + + publicClientTest() + .do(() => { + cachedTokenInfo = {}; + }) + .stderr() + .command(['users:get', 'me', '--no-color']) + .it( + 'should ask to reauthorize when no token is cached', + (context) => { + assert.include( + context.stderr, + `box login --name ${ENVIRONMENT_NAME} --reauthorize` + ); + } + ); + + publicClientTest() + .nock(TEST_API_ROOT, (api) => + // An empty 401 body is how the legacy client recognizes an expired access token + api.get('/2.0/users/me').reply(401) + ) + .stderr() + .command(['users:get', 'me', '--no-color']) + .it( + 'should mark a rejected access token as expired and keep the refresh token', + () => { + assert.equal(cachedTokenInfo.accessTokenTTLMS, 0); + assert.equal( + cachedTokenInfo.refreshToken, + 'cached-refresh-token' + ); + } + ); + }); + + describe('TypeScript SDK client commands', function () { + publicClientTest() + .nock(TEST_API_ROOT, (api) => + api + .get('/2.0/hubs/12345') + .matchHeader('Authorization', 'Bearer cached-access-token') + .reply(200, { type: 'hubs', id: '12345' }) + ) + .stdout() + .command(['hubs:get', '12345', '--json']) + .it('should use the cached access token', (context) => { + assert.equal(JSON.parse(context.stdout).id, '12345'); + }); + + publicClientTest() + .nock(TEST_API_ROOT, (api) => + api + .get('/2.0/hubs/12345') + .reply(401, { + type: 'error', + status: 401, + code: 'unauthorized', + message: 'Unauthorized', + }) + .post('/oauth2/token', (body) => { + assert.notProperty(body, 'client_secret'); + return true; + }) + .reply(400, { + error: 'invalid_grant', + error_description: 'Refresh token has expired', + }) + ) + .stderr() + .command(['hubs:get', '12345', '--no-color']) + .it( + 'should ask to reauthorize when the refresh token has expired', + (context) => { + assert.include( + context.stderr, + 'Your refresh token has expired' + ); + } + ); + }); + + describe('tokens:exchange', function () { + publicClientTest() + .nock(TEST_API_ROOT, (api) => + api + .post('/oauth2/token', (body) => { + assert.equal( + body.grant_type, + 'urn:ietf:params:oauth:grant-type:token-exchange' + ); + assert.equal(body.subject_token, 'cached-access-token'); + assert.equal(body.scope, 'item_preview'); + assert.equal( + body.resource, + 'https://api.box.com/2.0/files/123' + ); + assert.notProperty(body, 'client_secret'); + return true; + }) + .reply(200, { + access_token: 'downscoped-token', + expires_in: 1800, + token_type: 'bearer', + restricted_to: [], + }) + ) + .stdout() + .command(['tokens:exchange', 'item_preview', '--file-id=123']) + .it('should downscope the cached token', (context) => { + assert.equal(context.stdout.trim(), 'downscoped-token'); + }); + + publicClientTest() + .nock(TEST_API_ROOT, (api) => + api.post('/oauth2/token').reply(400, { + error: 'invalid_grant', + error_description: 'The subject token is not valid', + }) + ) + .stderr() + .command(['tokens:exchange', 'item_preview', '--no-color']) + .it( + 'should show the downscope error instead of asking to reauthorize', + (context) => { + assert.include( + context.stderr, + 'invalid_grant - The subject token is not valid' + ); + assert.notInclude(context.stderr, 'refresh token has expired'); + } + ); + }); + + describe('tokens:revoke', function () { + let revokeRequestHeaders; + + publicClientTest() + .nock(TEST_API_ROOT, (api) => + api + .post('/oauth2/revoke', { + client_id: CLIENT_ID, + token: 'token-to-revoke', + }) + .reply(function () { + revokeRequestHeaders = this.req.headers; + return [200]; + }) + ) + .stderr() + .command(['tokens:revoke', 'token-to-revoke', '--no-color']) + .it( + "should revoke without a client secret or the environment's own token", + (context) => { + assert.include(context.stderr, 'Token revoked.'); + assert.notProperty(revokeRequestHeaders, 'authorization'); + } + ); + + publicClientTest() + .nock(TEST_API_ROOT, (api) => + api.post('/oauth2/revoke').reply(400, { + error: 'invalid_token', + error_description: 'The token is invalid', + }) + ) + .stderr() + .command(['tokens:revoke', 'token-to-revoke', '--no-color']) + .it( + 'should report a failed revoke like the confidential OAuth path', + (context) => { + assert.include( + context.stderr, + 'Error revoking token! Request failed with status 400' + ); + } + ); + }); + + describe('logout', function () { + publicClientTest() + .nock(TEST_API_ROOT, (api) => + api + .post('/oauth2/revoke', { + client_id: CLIENT_ID, + token: 'cached-access-token', + }) + .reply(200) + ) + .stderr() + .command([ + 'logout', + '--force', + '--on-revoke-failure=abort', + '--no-color', + ]) + .it( + 'should revoke without a client secret and clear the token cache', + (context) => { + assert.include( + context.stderr, + `Successfully logged out from "${ENVIRONMENT_NAME}" environment.` + ); + assert.isUndefined(cachedTokenInfo.accessToken); + } + ); + }); +}); diff --git a/test/public-client-session-adapter.test.js b/test/public-client-session-adapter.test.js new file mode 100644 index 00000000..832ed1fc --- /dev/null +++ b/test/public-client-session-adapter.test.js @@ -0,0 +1,417 @@ +'use strict'; + +const { assert } = require('chai'); +const sinon = require('sinon'); +const PublicClientSessionAdapter = require('../src/public-client-session-adapter'); +const CLITokenCache = require('../src/token-cache'); +const utilities = require('../src/util'); + +const ONE_HOUR_MS = 60 * 60 * 1000; +const EXPIRY_BUFFER_MS = 60 * 1000; +const NETWORK_SESSION = Object.freeze({ name: 'configured network session' }); + +function createTokenStorage(initialToken) { + let token = initialToken; + return { + get: sinon.stub().callsFake(async () => token), + store: sinon.stub().callsFake(async (newToken) => { + token = { + accessToken: newToken.accessToken, + refreshToken: newToken.refreshToken, + accessTokenTTLMS: newToken.expiresIn * 1000, + acquiredAtMS: Date.now(), + }; + }), + clear: sinon.stub().callsFake(async () => { + token = undefined; + }), + }; +} + +function freshToken(overrides = {}) { + return { + accessToken: 'cached-token', + refreshToken: 'cached-refresh-token', + accessTokenTTLMS: ONE_HOUR_MS, + acquiredAtMS: Date.now(), + ...overrides, + }; +} + +function expiredToken() { + return freshToken({ acquiredAtMS: Date.now() - 2 * ONE_HOUR_MS }); +} + +function createAuth(tokenStorage) { + return { + tokenStorage, + refreshToken: sinon.stub().callsFake(async () => { + const token = { + accessToken: 'refreshed-token', + refreshToken: 'refreshed-refresh-token', + expiresIn: 3600, + }; + await tokenStorage.store(token); + return token; + }), + revokeToken: sinon.stub().resolves(), + downscopeToken: sinon.stub().resolves({ + accessToken: 'downscoped-token', + expiresIn: 1800, + restrictedTo: [], + }), + }; +} + +function createAdapter(auth) { + return new PublicClientSessionAdapter(auth, { + environmentName: 'public-env', + expiryBufferMS: EXPIRY_BUFFER_MS, + networkSession: NETWORK_SESSION, + }); +} + +describe('PublicClientSessionAdapter', function () { + describe('getAccessToken()', function () { + it('returns a fresh cached token without refreshing', async function () { + const auth = createAuth(createTokenStorage(freshToken())); + + const accessToken = await createAdapter(auth).getAccessToken(); + + assert.equal(accessToken, 'cached-token'); + assert.isTrue(auth.refreshToken.notCalled); + }); + + it('returns a Bluebird promise, since the legacy client chains asCallback', function () { + const auth = createAuth(createTokenStorage(freshToken())); + + const promise = createAdapter(auth).getAccessToken(); + + assert.isFunction(promise.asCallback); + return promise; + }); + + it('refreshes an expired token with the configured network session', async function () { + const auth = createAuth(createTokenStorage(expiredToken())); + + const accessToken = await createAdapter(auth).getAccessToken(); + + assert.equal(accessToken, 'refreshed-token'); + assert.isTrue(auth.refreshToken.calledOnceWith(NETWORK_SESSION)); + }); + + it('refreshes a token that expires within the expiry buffer', async function () { + const auth = createAuth( + createTokenStorage( + freshToken({ + acquiredAtMS: + Date.now() - ONE_HOUR_MS + EXPIRY_BUFFER_MS / 2, + }) + ) + ); + + await createAdapter(auth).getAccessToken(); + + assert.isTrue(auth.refreshToken.calledOnce); + }); + + it('sends one refresh request for concurrent calls', async function () { + const auth = createAuth(createTokenStorage(expiredToken())); + const adapter = createAdapter(auth); + + const tokens = await Promise.all([ + adapter.getAccessToken(), + adapter.getAccessToken(), + ]); + + assert.deepEqual(tokens, ['refreshed-token', 'refreshed-token']); + assert.isTrue(auth.refreshToken.calledOnce); + }); + + it('uses the initial token without reading the token cache', async function () { + const tokenStorage = createTokenStorage(freshToken()); + const adapter = new PublicClientSessionAdapter(createAuth(tokenStorage), { + environmentName: 'public-env', + expiryBufferMS: EXPIRY_BUFFER_MS, + networkSession: NETWORK_SESSION, + initialToken: freshToken({ accessToken: 'initial-token' }), + }); + + const accessToken = await adapter.getAccessToken(); + + assert.equal(accessToken, 'initial-token'); + assert.isTrue(tokenStorage.get.notCalled); + }); + + it('reads the token cache only once for repeated calls', async function () { + const tokenStorage = createTokenStorage(freshToken()); + const adapter = createAdapter(createAuth(tokenStorage)); + + await adapter.getAccessToken(); + await adapter.getAccessToken(); + await adapter.getAccessToken(); + + assert.isTrue(tokenStorage.get.calledOnce); + }); + + it('keeps a refreshed token in memory without refreshing or reading the cache again', async function () { + const tokenStorage = createTokenStorage(expiredToken()); + const auth = createAuth(tokenStorage); + const adapter = createAdapter(auth); + + await adapter.getAccessToken(); + const readsAfterRefresh = tokenStorage.get.callCount; + const accessToken = await adapter.getAccessToken(); + + assert.equal(accessToken, 'refreshed-token'); + assert.isTrue(auth.refreshToken.calledOnce); + assert.equal(tokenStorage.get.callCount, readsAfterRefresh); + }); + + it('asks to reauthorize when no token is cached', async function () { + const auth = createAuth(createTokenStorage()); + + try { + await createAdapter(auth).getAccessToken(); + assert.fail('Expected getAccessToken() to reject'); + } catch (error) { + assert.include( + error.message, + 'box login --name public-env --reauthorize' + ); + } + assert.isTrue(auth.refreshToken.notCalled); + }); + + it('asks to reauthorize when the refresh token is rejected', async function () { + const auth = createAuth(createTokenStorage(expiredToken())); + auth.refreshToken.rejects( + Object.assign(new Error('Request failed'), { + responseInfo: { + statusCode: 400, + body: { + error: 'invalid_grant', + error_description: 'Refresh token has expired', + }, + }, + }) + ); + + try { + await createAdapter(auth).getAccessToken(); + assert.fail('Expected getAccessToken() to reject'); + } catch (error) { + assert.include(error.message, 'Your refresh token has expired'); + assert.include( + error.message, + 'box login --name public-env --reauthorize' + ); + } + }); + }); + + describe('parallel refresh', function () { + it('uses the tokens of a parallel refresh when its refresh token was already used', async function () { + const tokenStorage = createTokenStorage(expiredToken()); + const auth = createAuth(tokenStorage); + // Another CLI process refreshes first, so this refresh token is no longer valid. + auth.refreshToken.callsFake(async () => { + await tokenStorage.store({ + accessToken: 'parallel-token', + refreshToken: 'parallel-refresh-token', + expiresIn: 3600, + }); + throw Object.assign(new Error('Request failed'), { + responseInfo: { + statusCode: 400, + body: { error: 'invalid_grant' }, + }, + }); + }); + + const accessToken = await createAdapter(auth).getAccessToken(); + + assert.equal(accessToken, 'parallel-token'); + }); + }); + + describe('handleExpiredTokensError()', function () { + it('does not overwrite tokens that another process stored in the meantime', async function () { + const tokenStorage = createTokenStorage( + freshToken({ + accessToken: 'other-process-token', + refreshToken: 'other-process-refresh-token', + }) + ); + // This command still uses the token it read before the other process refreshed. + const adapter = new PublicClientSessionAdapter(createAuth(tokenStorage), { + environmentName: 'public-env', + expiryBufferMS: EXPIRY_BUFFER_MS, + networkSession: NETWORK_SESSION, + initialToken: freshToken(), + }); + + try { + await adapter.handleExpiredTokensError(new Error('Expired Auth')); + assert.fail('Expected handleExpiredTokensError() to reject'); + } catch (error) { + assert.equal(error.message, 'Expired Auth'); + } + + assert.isTrue(tokenStorage.store.notCalled); + }); + + it('does not touch the token cache while a refresh is running, so it cannot overwrite the new tokens', async function () { + const tokenStorage = createTokenStorage(expiredToken()); + const auth = createAuth(tokenStorage); + let finishRefresh; + auth.refreshToken.callsFake( + () => + new Promise((resolve) => { + finishRefresh = async () => { + const token = { + accessToken: 'refreshed-token', + refreshToken: 'refreshed-refresh-token', + expiresIn: 3600, + }; + await tokenStorage.store(token); + resolve(token); + }; + }) + ); + const adapter = createAdapter(auth); + + const tokenPromise = adapter.getAccessToken(); + while (!finishRefresh) { + await new Promise((resolve) => setImmediate(resolve)); + } + // Another request of the same command, sent with the old token, gets a 401 now. + const expiredError = new Error('Expired Auth'); + try { + await adapter.handleExpiredTokensError(expiredError); + assert.fail('Expected handleExpiredTokensError() to reject'); + } catch (error) { + assert.strictEqual(error, expiredError); + } + assert.isTrue( + tokenStorage.store.notCalled, + 'the token cache must not be written while the refresh is running' + ); + + await finishRefresh(); + assert.equal(await tokenPromise, 'refreshed-token'); + const cachedToken = await tokenStorage.get(); + assert.equal(cachedToken.refreshToken, 'refreshed-refresh-token'); + }); + + it('marks the cached access token as expired and keeps the refresh token, so the next command refreshes', async function () { + const tokenStorage = createTokenStorage(freshToken()); + const auth = createAuth(tokenStorage); + const expiredError = new Error('Expired Auth'); + const adapter = createAdapter(auth); + // The request that gets the 401 used the cached token. + await adapter.getAccessToken(); + + try { + await adapter.handleExpiredTokensError(expiredError); + assert.fail('Expected handleExpiredTokensError() to reject'); + } catch (error) { + assert.strictEqual(error, expiredError); + } + const cachedToken = await tokenStorage.get(); + assert.equal(cachedToken.refreshToken, 'cached-refresh-token'); + + // A new adapter stands for the next CLI command. + const accessToken = await createAdapter(auth).getAccessToken(); + assert.equal(accessToken, 'refreshed-token'); + assert.isTrue(auth.refreshToken.calledOnce); + }); + + it('keeps the cached refresh token and refreshes on the next call', async function () { + const tokenStorage = createTokenStorage(freshToken()); + const auth = createAuth(tokenStorage); + const adapter = createAdapter(auth); + const expiredError = new Error('Expired Auth'); + + try { + await adapter.handleExpiredTokensError(expiredError); + assert.fail('Expected handleExpiredTokensError() to reject'); + } catch (error) { + assert.strictEqual(error, expiredError); + } + assert.isTrue(tokenStorage.clear.notCalled); + + const accessToken = await adapter.getAccessToken(); + assert.equal(accessToken, 'refreshed-token'); + assert.isTrue(auth.refreshToken.calledOnce); + }); + }); + + describe('exchangeToken()', function () { + it('downscopes the token and returns legacy token info', async function () { + const auth = createAuth(createTokenStorage(freshToken())); + + const tokenInfo = await createAdapter(auth).exchangeToken( + ['item_preview'], + 'https://api.box.com/2.0/files/123' + ); + + assert.isTrue( + auth.downscopeToken.calledOnceWith( + ['item_preview'], + 'https://api.box.com/2.0/files/123', + undefined, + NETWORK_SESSION + ) + ); + assert.equal(tokenInfo.accessToken, 'downscoped-token'); + assert.equal(tokenInfo.accessTokenTTLMS, 1800 * 1000); + assert.isNumber(tokenInfo.acquiredAtMS); + }); + + it('passes no resource when downscoping to scopes only', async function () { + const auth = createAuth(createTokenStorage(freshToken())); + + await createAdapter(auth).exchangeToken(['item_preview'], null); + + assert.isUndefined(auth.downscopeToken.firstCall.args[1]); + }); + }); + + describe('revokeTokens()', function () { + it('revokes the token and clears the token cache', async function () { + const tokenStorage = createTokenStorage(freshToken()); + const auth = createAuth(tokenStorage); + + await createAdapter(auth).revokeTokens(); + + assert.isTrue(auth.revokeToken.calledOnceWith(NETWORK_SESSION)); + assert.isTrue(tokenStorage.clear.calledOnce); + assert.isTrue( + auth.revokeToken.calledBefore(tokenStorage.clear), + 'the token must be read for revocation before the cache is cleared' + ); + }); + + it('waits until the CLI token cache is deleted', async function () { + const tokenCache = new CLITokenCache('public-client-revoke-env'); + tokenCache.supportsSecureStorage = false; + let deleted = false; + const unlinkStub = sinon + .stub(utilities, 'unlinkAsync') + .callsFake(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + deleted = true; + }); + const auth = createAuth(tokenCache); + + try { + await createAdapter(auth).revokeTokens(); + assert.isTrue(unlinkStub.calledOnceWith(tokenCache.filePath)); + assert.isTrue(deleted); + } finally { + unlinkStub.restore(); + } + }); + }); +}); diff --git a/test/public-client.test.js b/test/public-client.test.js new file mode 100644 index 00000000..2f721620 --- /dev/null +++ b/test/public-client.test.js @@ -0,0 +1,48 @@ +'use strict'; + +const { assert } = require('chai'); +const sinon = require('sinon'); +const BoxTSSDK = require('box-node-sdk/sdk-gen'); +const { createPublicClientTsClient } = require('../src/public-client'); +const pkg = require('../package.json'); + +// Stands in for a BoxCommand: only _configureTsSdk is used. +function createCommand() { + return { _configureTsSdk: sinon.stub().callsFake((client) => client) }; +} + +describe('createPublicClientTsClient', function () { + it('builds a TS client that authenticates with the public client auth', function () { + const tokenStorage = { get: sinon.stub(), store: sinon.stub() }; + + const { auth, client } = createPublicClientTsClient(createCommand(), { + clientId: 'public-client-id', + tokenStorage, + }); + + assert.instanceOf(auth, BoxTSSDK.BoxPublicClientOAuth); + assert.equal(auth.config.clientId, 'public-client-id'); + assert.strictEqual(auth.tokenStorage, tokenStorage); + assert.instanceOf(client, BoxTSSDK.BoxClient); + assert.strictEqual(client.auth, auth); + }); + + it('configures the client with the CLI settings and User-Agent, using a fresh config each time', function () { + const command = createCommand(); + + createPublicClientTsClient(command, { clientId: 'public-client-id' }); + createPublicClientTsClient(command, { clientId: 'public-client-id' }); + + const [firstConfig, secondConfig] = command._configureTsSdk.args.map( + (args) => args[1] + ); + assert.deepEqual(firstConfig.request.headers, { + 'User-Agent': `Box CLI v${pkg.version}`, + }); + // _configureTsSdk adds headers to the config it gets, so calls must not share one + assert.notStrictEqual( + firstConfig.request.headers, + secondConfig.request.headers + ); + }); +}); diff --git a/test/token-cache.test.js b/test/token-cache.test.js index 6da729eb..2d1c428d 100644 --- a/test/token-cache.test.js +++ b/test/token-cache.test.js @@ -386,6 +386,39 @@ describe('CLITokenCache', function () { }); }); + it('should return a promise when clearing without a callback, as the TS SDK token storage contract requires', async function () { + const cacheWithoutSecure = new CLITokenCache('promise-clear-env'); + cacheWithoutSecure.supportsSecureStorage = false; + const unlinkStub = sinon.stub(utilities, 'unlinkAsync').resolves(); + + try { + await cacheWithoutSecure.clear(); + expect(unlinkStub.calledOnceWith(cacheWithoutSecure.filePath)) + .to.be.true; + } finally { + unlinkStub.restore(); + } + }); + + it('should reject the returned promise when clearing without a callback fails', async function () { + const cacheWithoutSecure = new CLITokenCache('promise-clear-env'); + cacheWithoutSecure.supportsSecureStorage = false; + const unlinkStub = sinon.stub(utilities, 'unlinkAsync').rejects( + Object.assign(new Error('Permission denied'), { + code: 'EACCES', + }) + ); + + try { + await cacheWithoutSecure.clear(); + expect.fail('Expected clear() to reject'); + } catch (error) { + expect(error.message).to.equal('Failed to delete token cache'); + } finally { + unlinkStub.restore(); + } + }); + it('should report secure storage deletion failures when clearing', function (done) { if (!tokenCache.supportsSecureStorage) { this.skip();