jsdelivr / globalping-cli

A simple CLI tool to run networking commands remotely from hundreds of globally distributed servers
Mozilla Public License 2.0
135 stars 14 forks source link

Add auth support via command #108

Closed MartinKolarik closed 1 week ago

MartinKolarik commented 3 months ago
  1. auth login - prints a link to open the web browser; the user signs in there and doesn't have to do anything else; then token is created and stored automatically
  2. auth login --with-token - reads and stores a token manually provided by the user via stdin
  3. auth status shows if there is a token stored or not
  4. auth logout removes the stored token (+ deletes from DB if it was created directly by the cli)

Implementation details

  1. Login:

    • Start a local server on one of the ports above. If none is available, print an error.
    • Use the authorization_code flow; print a message with a URL to the console and also attempt to automatically open it in the default browser.
    • When the user approves the app, he'll be redirected to localhost callback URL. Read the access code from there, request a token, and store it in ~/.globalping-cli. Redirect the user to https://dash.globalping.io/authorize/success if everything worked or https://dash.globalping.io/authorize/error if the token response failed. Shut down the local server.
  2. Login with token:

    • Read whatever the user provides. Use the introspection endpoint to validate that the token works (active: true). Store the token or print an error.
  3. Auth status:

    • If there's a token stored, use the introspection endpoint to validate it, then print a message "Logged in as {username}." This works regardless of how the token was obtained.
  4. Logout:

    • If the stored token was user-provided, just delete it. If it was requested via oauth, call the revocation endpoint with the refresh token (this will automatically revoke all access tokens too).

Notes on token handling

The oauth tokens will have an expiration of 30 days for the access token and 180 days for the refresh token. The refresh_token grant can be used to get a new pair of tokens. Store the expiration locally, and:

Make sure auth status works when the token is set via the ENV var too.

jimaek commented 3 months ago

How about we remove --with-token? And just keep login. If there's nothing after it then browser flow, if there's a string after it then save token.

MartinKolarik commented 3 months ago

The token will be read from stdin, not as an argument, that's why there is the flag. Passing tokens directly as arguments is a bad practice for security reasons, that's why virtually any CLI does it this way.

MartinKolarik commented 1 month ago

@radulucut I added details to my original post, and everything you need should be ready now. You should also be able to log in with your GitHub account at https://dash.globalping.io/ and test all parts of the functionality.