@opscompass/opscompass-cli 1.0.2 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,152 +1,106 @@
1
- # OpsCompass Command Line Interface
2
-
3
- Calls OpsCompass's HTTP APIs using the Bearer token strategy
4
-
5
- ## Login
6
-
7
- Login supports the two basic "native app" authentication flows:
8
-
9
- 1. PKCE, the "no-secret" authorization code flow, for clients with interactive browsers
10
- 1. Device authorization flow, for clients without interactive browsers
11
-
12
- ### PKCE
13
-
14
- When the user runs the default `opscompass login` command, we try to authenticate the user using PKCE. PKCE involves a few steps:
15
-
16
- 1. The OpsCompass CLI generates a couple short-lived secrets
17
- 1. The "code verifier", used when we redeem the authorization code
18
- 1. A "state", used when we receive the redirect back from the login site
19
- 1. The OpsCompass CLI builds a URL to launch in the system's default browser. The URL contains
20
- - The login flow ("response_type=code")
21
- - The user is logging in with the OpsCompass CLI (client_id, audience)
22
- - The user wants a long-lived session with a refresh token (scope=offline_access)
23
- - The SHA256 hash of the "code verifier" secret and that was the hashing algorithm used (code_challenge, code_challenge_method)
24
- - The "state" (state=generated_state_value)
25
- - And the redirect URI to send the user to once the login process is complete (redirect_uri=http://localhost:8400/login)
26
- 1. The CLI launches an HTTP server to receive the login response
27
- 1. The user goes through the login process in their browser: authenticating to our login site, possibly by logging in through an IdP (Microsoft or Google).
28
- 1. The login site redirects the user's browser to the local HTTP server the CLI was hosting
29
- 1. The "state" is verified in the response to match the one sent in the URL
30
- 1. The code from this response is sent along with the "code verifier", the client ID, and the redirect URI to redeem the authorization code for an access token
31
-
32
- If all of that is successful, the credentials are kept for later API calls.
33
- If anything fails, a warning is printed and the CLI shuts down its HTTP server.
34
-
35
- ### Device Authorization
36
-
37
- When the user runs `opscompass login --use-device-code`, it outputs a URL for the user to visit on another device to "remotely" authorize the CLI.
38
- This flow is designed to be used in scenarios where the host doesn't have an interactive browser (remote VMs/hosts, automated processes with output monitoring) or can't launch an HTTP server locally.
39
-
40
- 1. The OpsCompass CLI makes an API call to the login system to get a device code, which includes a short "public" code (like ABCD-EFGH) and a longer "private" code.
41
- 1. The CLI puts this code in a URL for the user, asking them to visit that URL on any device they can log in with.
42
- 1. The CLI starts polling using the "private" code to see if the user has completed the authorization process.
43
- 1. The user visits the printed URL on another device (or the same device).
44
- 1. The user logs in to OpsCompass, then verifies the code matches what the CLI output to authorize the device.
45
-
46
- If the user authorized the device and the CLI received its access token, the credentials are kept for later API calls.
47
- If the user does not authorize the CLI or a certain amount of time passes, a warning is printed.
48
-
49
- ### Re-Authenticating
50
-
51
- The user can run `opscompass login` or `opscompass login --use-device-code` as often as they need to. Each successful login attempt replaces the stored credentials with the new ones; however, failed login attempts do not remove credentials.
52
-
53
- ## Calling APIs
54
-
55
- APIs are called by performing actions on modules. Commands generally take the form:
56
-
57
- ```bash
58
- opscompass module action --parameter1 value --parameter2 value
59
- # examples:
60
- # opscompass resources get --company my-sample-company --id 12345
61
- ```
62
-
63
- The relevant API is called and its output is printed to the console.
64
-
65
- If no user token is available, the user is notified they need to run the `opscompass login` command again.
66
- If an invalid action is called, the available actions for that module are listed.
67
- If the required parameters are not provided for an action, the user is notified of which parameters are missing and the details of that action are provided.
68
-
69
- ## Modules
70
-
71
- Modules in this repo group APIs together. When adding support for a new API namespace to the CLI, you author a new Module. A module:
72
-
73
- - Exports a function that takes in an action and a "rest" array of args
74
- - Sets on that function whether the module requires login (usually true)
75
- - Routes actions to functions with a particular API's calling logic
76
- - Provides information about its actions when asked or provided with an improper command
77
- - Is added to the "modules" object exported by `modules.js`
78
-
79
- ### The module structure
80
-
81
- Modules will generally define a function for each method an API namespace exposes (for instance, listing all companies and getting details about a single company). Each function calls its specific API after doing appropriate parameter parsing and validating.
82
-
83
- ```JavaScript
84
- /* sampleModule.js */
85
- async function sampleAction1(...args) {
86
- // do something useful
87
- }
88
-
89
- async function printHelp() {
90
- console.log("Sample actions available:");
91
- console.log("sampleaction1 - Does something useful");
92
- }
93
-
94
-
95
- async function sampleModule(action, ...args) {
96
- switch (action?.toLowerCase()) {
97
- case "sampleaction1": return sampleAction1(args);
98
- default: return printHelp();
99
- }
100
- }
101
-
102
- sampleModule.requiresLogin = true;
103
-
104
- module.exports = sampleModule;
105
-
106
- /* modules.js */
107
- //...existing modules
108
- const samplemodule = require("./sampleModule.js");
109
-
110
- module.exports = {
111
- //...existing exports,
112
- samplemodule,
113
- };
114
- ```
115
-
116
- Modules are looked up from the modules object export by their name. Keys in the modules object need to be in all lower-case so the CLI's commands can be case-insensitive.
117
-
118
- The module function itself is called with all the parameters from the command line. It is responsible for routing the data to a specific function, which contains the logic for that function. If you want or need to go more layers than this, feel free to build your module as you need it to be. However, most APIs can be broken down the same way (parsing their parameters from the command line and calling their API).
119
-
120
- ### Individual API Functions
121
-
122
- Generally speaking, most API methods will take the parameters and parse them, making sure their required parameters are present (printing a helpful message about what's expected when they aren't). Once the parameters are all parsed, it calls its one API with that data. The `apiCaller` will do the work of looking up the stored access token and building the HTTP request according to the module, action, HTTP method (typically GET or POST), query parameters, and HTTP request body.
123
-
124
- ```JavaScript
125
- // calls the sampleAction API on the sampleModule function
126
- // based on the only expected parameter: --company
127
- // then prints its output directly to the console
128
- async function sampleAction(args) {
129
- if (!args || args[0] !== "--company" || !args[1]) {
130
- console.error("expected parameter: --company [company_id]");
131
- return printHelp();
132
- }
133
- console.log(await apiCaller("sampleModule", "sampleAction", "get", {
134
- company: args[1],
135
- }));
136
- }
137
- ```
138
-
139
- While this sample action is not particularly permissive about its argument parsing (it requires the first parameter be the one it cares about, it does _not_ handle mixed-case argument name, but it will ignore extra parameters), it does do what's expected of it: it validates its inputs, then calls its API, and prints the output to the console. Generally speaking, try to keep the standard output clear of logging messages, only let the actual data go out the standard output so that it may be pipelined into other tools to do something useful.
140
-
141
- ```PowerShell
142
- $actionOutput = opscompass sampleModule sampleAction --company someCompany | ConvertFrom-JSON
143
- if ($null -ne $actionOutput.someProperty) {
144
- # do something useful
145
- }
146
- ```
147
-
148
- ### Make What You Need
149
-
150
- While most APIs will have a straight-forward GET or POST structure taking basic structured data via query string or request body, other APIs will have more complex needs. Do what you need to do.
151
-
152
- For instance, the `login` process is a module: it exports a function, it parses its parameters, but it doesn't actually require an action be provided. Perhaps a module needs to read a file and take in the path to the file as its input instead of raw data. All of those things are fine, so long as you explain how to use it if the user calls `opscompass your-module help`. You should still try to follow the basic CLI structure though (`opscompass module action --parameter value --parameter value`) for consistency and always keep the standard output as quiet as you can outside the output of your actions.
1
+ # OpsCompass Command Line Interface
2
+
3
+ The OpsCompass Command Line Interface (the CLI) lets you interact with OpsCompass directly from your shell.
4
+
5
+ [[_TOC_]]
6
+
7
+ ## Login
8
+
9
+ Login supports the two basic "native app" authentication flows:
10
+
11
+ 1. Authorization Code with PKCE, the "no-secret" authorization code flow, for clients with interactive browsers
12
+ 1. Device authorization flow, for clients without interactive browsers
13
+
14
+ ### Authorization Code with PKCE
15
+
16
+ The most common flow is when you're running the CLI on a host with a web browser. Most users use this flow.
17
+
18
+ Start this flow by running `opscompass login`. The CLI generates some short-lived secrets that are used to make sure only the CLI receives your authentication token. The CLI also starts listening for local HTTP traffic on port 8400 to receive the authorization code from the login page.
19
+
20
+ The CLI will try to launch the system default browser asking you to log in to OpsCompass. Log in using the same credentials you use when logging into the OpsCompass web experience. If you haven't authorized the CLI before, after you log in and provide your MFA token, you'll be asked to authorize the CLI application.
21
+
22
+ Once you've logged in and authorized the CLI, the browser will redirect you to the local HTTP server hosted by the CLI. The CLI will take the authorization code and redeem it with the short-lived secrets to get the OpsCompass access token. If it's successful, the browser shows a "Logging in..." page. If anything fails, you'll see "Problems logging in" page. It stops listening for HTTP traffic at this point.
23
+
24
+ ### Device Authorization
25
+
26
+ For scenarios where a browser is unavailable, where the CLI can't listen for HTTP traffic, or where the CLI isn't able to launch a browser, you can use the Device Authorization flow.
27
+
28
+ To use Device Authorization, run `opscompass login --use-device-code`. The CLI will request a code from the login system and output a URL for you to visit.
29
+
30
+ 1. The OpsCompass CLI makes an API call to the login system to get a device code, which includes a short "public" code (like ABCD-EFGH) and a longer "private" code.
31
+ 1. You use the printed URL and code to log in and authorize yoru device.
32
+ 1. The CLI starts polling using the "private" code to see if you have completed the authorization process.
33
+
34
+ Once you log in and authorize the device, the next time the CLI polls with the "private" code, the CLI receives your OpsCompass access token and prints that you're logged in.
35
+
36
+ If you don't authorize the device or wait too long to complete the process, the CLI will print a warning that the process wasn't successful.
37
+
38
+ ### Access Token Usage
39
+
40
+ Once the CLI receives an access token, it will include that on all calls for resources as long as it remains valid. The CLI is also issued a refresh token, which is redeemed once the access token expires for a fresh access token.
41
+
42
+ Refresh tokens expire if you don't use the CLI regularly. Also, even with regular use, we occasionally require you to log in again.
43
+
44
+ ### Re-Authenticating
45
+
46
+ You can authenticate with `opscompass login` or `opscompass login --use-device-code` as often as you like. Each successful login attempt replaces the stored credentials with the new ones.
47
+
48
+ ## Using the CLI
49
+
50
+ The CLI is organized into sections called "modules." Each module exposes one or more "commands" that perform the corresponding action. Typically, modules cover a section of OpsCompass (resources, accounts, compliance) and commands are the actions for that section (listing, getting, getting details).
51
+
52
+ Full CLI commands generally take the form:
53
+
54
+ ```bash
55
+ opscompass module command --parameter1 value --parameter2 value
56
+ # examples:
57
+ # opscompass resources get --company my-sample-company --id 12345
58
+ ```
59
+
60
+ The relevant API is called and its output is printed to the standard output as JSON. Errors are logged to the standard error.
61
+
62
+ If no user token is available, you'll be notified that you need to run the `opscompass login` command again.
63
+
64
+ If an invalid module or command is given, the available modules or commands for that module are listed.
65
+
66
+ If the required parameters are not provided for a command, you'll be notified of which parameters are missing.
67
+
68
+ ## Getting Details of a Resource
69
+
70
+ You'll need a couple pieces of information to get the details of a single resource using the CLI. You'll need the company the resource is associated with and an identifier for the resource.
71
+
72
+ ### Company ID
73
+
74
+ If you want to get details of a resource, you'll need to know your company's ID in OpsCompass. You can get this by logging into OpsCompass. Your company will be in the URL.
75
+
76
+ For instance, if you're viewing the Inventory page, your URL will be:
77
+
78
+ ```
79
+ https://app.opscompass.com/your_company_id/inventory
80
+ ```
81
+
82
+ Here, the company id is `your_company_id`.
83
+
84
+ ### Resource ID
85
+
86
+ You'll also need to provide the ID of the resource you're trying to access. You can get this in two ways: from the cloud and from OpsCompass.
87
+
88
+ Each cloud has a different way to uniquely identify resources. For instance, Azure uses "Resource ID" and AWS uses "ARN".
89
+
90
+ When you have the cloud's ID for a resource, provide that with "--resource-id".
91
+
92
+ ```
93
+ opscompass resources get --company your_company_id --resource-id "/subscriptions/abcdef00-0000-4000-a000-123456781234/resourceGroups/A-Resource-Group/providers/Microsoft.Web/sites/yoursite"
94
+ ```
95
+
96
+ When you load a resource's details in the OpsCompass web experience, you'll see the resource's "OpsCompass ID" at the end of the URL. As we add more capabilities to search your resources using the CLI, this ID will be available through command output.
97
+
98
+ ```
99
+ https://app.opscompass.com/your_company_id/inventory/1234567
100
+ ```
101
+
102
+ Here, the OpsCompass ID of the resource is 1234567. When you have the OpsCompass ID for a resource, provide it with "--id"
103
+
104
+ ```
105
+ opscompass resources get --company your_company_id --id 1234567
106
+ ```
package/credentials.js CHANGED
@@ -1,83 +1,96 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- const { homedir } = require("os");
4
- const { redeemRefreshToken } = require("./oauth");
5
-
6
- const opscompassHome = path.join(homedir(), '.opscompass');
7
-
8
- async function storeCredentials(data) {
9
- // see if the .opscompass directory exists; if not, try to create it
10
- try {
11
- fs.accessSync(opscompassHome);
12
- } catch {
13
- // mode 700: only the user can interact with the directory
14
- // and can do everything in that directory (read, write, list)
15
- fs.mkdirSync(opscompassHome, { mode: "700" });
16
- }
17
-
18
- // promisify the callback of fs.writeFile
19
- return new Promise((resolve, reject) => {
20
- try {
21
- // calculate the expires_at from the expires_in
22
- if (data.expires_in) {
23
- data.expires_at = new Date(Date.now() + (data.expires_in * 1000));
24
- }
25
-
26
- // write the token data to the file
27
- fs.writeFile(
28
- path.join(opscompassHome, 'tokens.json'),
29
- JSON.stringify(data),
30
- // mode 600: the user can read/write (and not execute)
31
- // but only the user can interact with the file
32
- { mode: "600" },
33
- () => resolve());
34
- } catch (ex) {
35
- reject(ex);
36
- }
37
- });
38
- }
39
-
40
- async function getCredentials() {
41
- // promisify the callback from fs.readFile
42
- return new Promise((resolve, reject) => {
43
- try {
44
- fs.readFile(
45
- path.join(opscompassHome, 'tokens.json'),
46
- async (err, data) => {
47
- try {
48
- // if the read failed, reject
49
- if (err) {
50
- reject(err);
51
- return;
52
- }
53
-
54
- const tokensData = JSON.parse(data.toString());
55
- const expires_at = new Date(tokensData.expires_at);
56
-
57
- // if the token has already expired,
58
- // redeem the refresh token and return that
59
- if (new Date() > expires_at && tokensData.refresh_token) {
60
- const refreshedTokenResponse = await redeemRefreshToken(tokensData.refresh_token);
61
- const refreshedTokenData = refreshedTokenResponse.data;
62
- await storeCredentials(refreshedTokenData);
63
- resolve(refreshedTokenData);
64
- }
65
-
66
- // return the data from the file
67
- resolve(tokensData);
68
- } catch (innerError) {
69
- reject(innerError);
70
- }
71
- }
72
- );
73
- } catch (e) {
74
- // this should only happen if the path can't be built
75
- console.error(e);
76
- }
77
- });
78
- }
79
-
80
- module.exports = {
81
- getCredentials,
82
- storeCredentials,
83
- };
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+ const { redeemRefreshToken } = require("./oauth");
4
+ const { opscompassHome } = require("./environment/current.js");
5
+
6
+ function canReadStoredCredentials() {
7
+ try {
8
+ fs.accessSync(
9
+ path.join(
10
+ opscompassHome,
11
+ "tokens.json"
12
+ )
13
+ );
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+
20
+ async function storeCredentials(data) {
21
+ // see if the .opscompass directory exists; if not, try to create it
22
+ try {
23
+ fs.accessSync(opscompassHome);
24
+ } catch {
25
+ // mode 700: only the user can interact with the directory
26
+ // and can do everything in that directory (read, write, list)
27
+ fs.mkdirSync(opscompassHome, { mode: "700" });
28
+ }
29
+
30
+ // promisify the callback of fs.writeFile
31
+ return new Promise((resolve, reject) => {
32
+ try {
33
+ // calculate the expires_at from the expires_in
34
+ if (data.expires_in) {
35
+ data.expires_at = new Date(Date.now() + (data.expires_in * 1000));
36
+ }
37
+
38
+ // write the token data to the file
39
+ fs.writeFile(
40
+ path.join(opscompassHome, 'tokens.json'),
41
+ JSON.stringify(data),
42
+ // mode 600: the user can read/write (and not execute)
43
+ // but only the user can interact with the file
44
+ { mode: "600" },
45
+ () => resolve());
46
+ } catch (ex) {
47
+ reject(ex);
48
+ }
49
+ });
50
+ }
51
+
52
+ async function getCredentials() {
53
+ // promisify the callback from fs.readFile
54
+ return new Promise((resolve, reject) => {
55
+ try {
56
+ fs.readFile(
57
+ path.join(opscompassHome, 'tokens.json'),
58
+ async (err, data) => {
59
+ try {
60
+ // if the read failed, reject
61
+ if (err) {
62
+ reject(err);
63
+ return;
64
+ }
65
+
66
+ const tokensData = JSON.parse(data.toString());
67
+ const expires_at = new Date(tokensData.expires_at);
68
+
69
+ // if the token has already expired,
70
+ // redeem the refresh token and return that
71
+ if (new Date() > expires_at && tokensData.refresh_token) {
72
+ const refreshedTokenResponse = await redeemRefreshToken(tokensData.refresh_token);
73
+ const refreshedTokenData = refreshedTokenResponse.data;
74
+ await storeCredentials(refreshedTokenData);
75
+ resolve(refreshedTokenData);
76
+ }
77
+
78
+ // return the data from the file
79
+ resolve(tokensData);
80
+ } catch (innerError) {
81
+ reject(innerError);
82
+ }
83
+ }
84
+ );
85
+ } catch (e) {
86
+ // this should only happen if the path can't be built
87
+ console.error(e);
88
+ }
89
+ });
90
+ }
91
+
92
+ module.exports = {
93
+ canReadStoredCredentials,
94
+ getCredentials,
95
+ storeCredentials,
96
+ };
@@ -0,0 +1,21 @@
1
+ // production: OpsCompassClient is referenced from npm package
2
+
3
+ const {
4
+ OpsCompassClient,
5
+ OAuthHandler
6
+ } = require("@opscompass/opscompass-api");
7
+
8
+ const path = require("path");
9
+ const { homedir } = require("os");
10
+ const opscompassHome = path.join(homedir(), '.opscompass');
11
+
12
+ const clientId = "vOakDaOv4L26f3uuI4sp3KC1Sov3nsW2";
13
+ // default authDomain
14
+ // default audience
15
+ const oAuthClient = new OAuthHandler(clientId);
16
+
17
+ module.exports = {
18
+ OpsCompassClient,
19
+ oAuthClient,
20
+ opscompassHome,
21
+ };
@@ -0,0 +1,21 @@
1
+ // demo: @opscompass/opscompass-api-demo
2
+
3
+ const {
4
+ OpsCompassClient,
5
+ OAuthHandler
6
+ } = require("@opscompass/opscompass-api-demo");
7
+
8
+ const path = require("path");
9
+ const { homedir } = require("os");
10
+ const opscompassHome = path.join(homedir(), '.opscompassdemo');
11
+
12
+ const clientId = "XOPT3HDcwhskfVjc9IMjLXV1pov79blV";
13
+ const authDomain = "auth-dev.opscompass.com";
14
+ const audience = "https://opscompass-api-demo.azure-api.net";
15
+ const oAuthClient = new OAuthHandler(clientId, authDomain, audience);
16
+
17
+ module.exports = {
18
+ OpsCompassClient,
19
+ oAuthClient,
20
+ opscompassHome,
21
+ };
@@ -0,0 +1,21 @@
1
+ // dev: @opscompass/opscompass-api-dev
2
+
3
+ const {
4
+ OpsCompassClient,
5
+ OAuthHandler
6
+ } = require("@opscompass/opscompass-api-dev");
7
+
8
+ const path = require("path");
9
+ const { homedir } = require("os");
10
+ const opscompassHome = path.join(homedir(), '.opscompassdev');
11
+
12
+ const clientId = "XOPT3HDcwhskfVjc9IMjLXV1pov79blV";
13
+ const authDomain = "auth-dev.opscompass.com";
14
+ const audience = "https://fa-sampleapi-cus-dev.azurewebsites.net";
15
+ const oAuthClient = new OAuthHandler(clientId, authDomain, audience);
16
+
17
+ module.exports = {
18
+ OpsCompassClient,
19
+ oAuthClient,
20
+ opscompassHome,
21
+ };
@@ -0,0 +1,22 @@
1
+ // local: @opscompass/opscompass-api is pointing to the local file system.
2
+ // set up your local functions to use dev's token settings.
3
+
4
+ const {
5
+ OpsCompassClient,
6
+ OAuthHandler
7
+ } = require("@opscompass/opscompass-api");
8
+
9
+ const path = require("path");
10
+ const { homedir } = require("os");
11
+ const opscompassHome = path.join(homedir(), '.opscompassdev');
12
+
13
+ const clientId = "XOPT3HDcwhskfVjc9IMjLXV1pov79blV";
14
+ const authDomain = "auth-dev.opscompass.com";
15
+ const audience = "https://fa-sampleapi-cus-dev.azurewebsites.net";
16
+ const oAuthClient = new OAuthHandler(clientId, authDomain, audience);
17
+
18
+ module.exports = {
19
+ OpsCompassClient,
20
+ oAuthClient,
21
+ opscompassHome,
22
+ };
@@ -0,0 +1,21 @@
1
+ // production: OpsCompassClient is referenced from npm package
2
+
3
+ const {
4
+ OpsCompassClient,
5
+ OAuthHandler
6
+ } = require("@opscompass/opscompass-api");
7
+
8
+ const path = require("path");
9
+ const { homedir } = require("os");
10
+ const opscompassHome = path.join(homedir(), '.opscompass');
11
+
12
+ const clientId = "vOakDaOv4L26f3uuI4sp3KC1Sov3nsW2";
13
+ // default authDomain
14
+ // default audience
15
+ const oAuthClient = new OAuthHandler(clientId);
16
+
17
+ module.exports = {
18
+ OpsCompassClient,
19
+ oAuthClient,
20
+ opscompassHome,
21
+ };
package/error.js ADDED
@@ -0,0 +1,13 @@
1
+ module.exports = function handleError(e) {
2
+ // if there's no error, there's nothing to handle.
3
+ if (!e) return;
4
+
5
+ // Some error in the HTTP response:
6
+ // there should be a message. Log that alone.
7
+ // Everything else: log the entire exception to stderr.
8
+ if (e.isAxiosError && e.response?.data?.message) {
9
+ console.error(e.response.data.message);
10
+ } else {
11
+ console.error(e);
12
+ }
13
+ }