close
Skip to content

feat: add infisical status command to inspect auth/session state#2

Open
yaswanthkumar1995 wants to merge 3 commits into
mainfrom
feat/status-command
Open

feat: add infisical status command to inspect auth/session state#2
yaswanthkumar1995 wants to merge 3 commits into
mainfrom
feat/status-command

Conversation

@yaswanthkumar1995
Copy link
Copy Markdown
Owner

@yaswanthkumar1995 yaswanthkumar1995 commented Apr 12, 2026

Resolves Infisical#156

Description 📣

Adds a new infisical status command that displays the current authentication and session state, making it easy to answer common questions like "Am I logged in?", "Is my session valid?", and "When does my token expire?" — without having to run another command and hope it works.

What it displays

Field Description
Authenticated Whether the user/machine identity is currently logged in
Session valid Whether the current token/session is still valid (not expired)
Domain The Infisical API URL being used
Auth method user for interactive login, or machine identity type (universal-auth, kubernetes, aws-iam, etc.)
User Email of the logged-in user (user auth only)
Token source Where the machine identity token was loaded from (flag/env)
Token expires at Token expiry timestamp with color-coded warnings (yellow < 5 min, red = expired)

Detection order

  1. Checks for machine identity tokens first (from --token flag or INFISICAL_TOKEN env var)
  2. Falls back to the logged-in user session from the local keyring/config

--json flag

Supports --json for machine-readable output, useful in CI/CD pipelines and automation scripts:

$ infisical status --json
{
  "authenticated": true,
  "sessionValid": true,
  "domain": "https://app.infisical.com/api",
  "authMethod": "user",
  "user": "user@example.com",
  "expiresAt": "2026-04-12T18:30:00Z"
}

Human-readable output

$ infisical status
Authenticated:       yes
Session valid:       yes
Domain:              https://app.infisical.com/api
Auth method:         user
User:                user@example.com
Token expires at:    2026-04-12T18:30:00Z (expires in 2h15m30s)

When not authenticated, provides guidance:

Authenticated:       no

Not logged in. Run infisical login to authenticate.

Type ✨

  • Bug fix
  • New feature
  • Improvement
  • Breaking change
  • Documentation

Tests 🔧

# Check status when logged in
infisical status

# JSON output for CI/CD
infisical status --json

# Verify expired session detection
# (let token expire, then run)
infisical status

# Machine identity token detection
INFISICAL_TOKEN=<token> infisical status

Summary by CodeRabbit

  • New Features
    • Added an infisical status command to display authentication state, session validity, auth method, domain, token source, and token expiration.
    • Prioritizes machine tokens when present and falls back to user session details; parses token expiry to indicate expired/soon/remaining time.
    • Supports no-argument invocation with --json for machine-readable output and human-friendly colored output; reads configured domain overrides.

Add 'infisical status' command that displays current authentication
state including: login status, session validity, domain, auth method,
user email, and token expiry with color-coded warnings.

Supports --json flag for machine-readable output in CI/CD pipelines
and scripts.

Resolves Infisical#156
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 12, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d7fa24dd-4a61-49b5-8c9a-8cdafcf32274

📥 Commits

Reviewing files that changed from the base of the PR and between 7d08c4a and 6e6595a.

📒 Files selected for processing (1)
  • packages/cmd/status.go

📝 Walkthrough

Walkthrough

Adds a new infisical status Cobra CLI command that reports authentication/session state (machine token or user), domain/profile, auth method, token expiry (JWT exp parsed without verification), supports --json and --token flags, prints human-readable or JSON output, and emits a PostHog telemetry event.

Changes

Cohort / File(s) Summary
Status command
packages/cmd/status.go
New Cobra command status (Args: cobra.ExactArgs(0)) with --json and --token flags. Adds statusOutput struct and functions: getStatus, extractJWTExpiry, printStatusJSON, printStatusHuman, and init. Logic: prefer machine token via util.GetInfisicalToken -> fallback to util.GetCurrentLoggedInUserDetails, extract JWT exp without signature verification, populate fields (Authenticated, SessionValid, Domain, Profile, AuthMethod, User, ExpiresAt, TokenSource), format output, handle errors, emit cli-command:status telemetry.

Sequence Diagram

sequenceDiagram
    participant User as User
    participant CLI as "infisical status"
    participant Token as "util.GetInfisicalToken"
    participant Auth as "util.GetCurrentLoggedInUserDetails"
    participant JWT as "extractJWTExpiry"
    participant Output as "printStatus{Human/JSON}"
    participant PH as "PostHog (telemetry)"

    User->>CLI: run command
    CLI->>Token: attempt machine token (optional --token)
    alt machine token found
        Token-->>CLI: token + source
        CLI->>JWT: parse exp (no sig verify)
        JWT-->>CLI: expiry or none
        CLI->>Output: build authenticated machine status
    else no machine token
        Token-->>CLI: none
        CLI->>Auth: check user session
        alt user logged in
            Auth-->>CLI: user details + jwt
            CLI->>JWT: parse exp (no sig verify)
            JWT-->>CLI: expiry or none
            CLI->>Output: build authenticated user status
        else not logged in or error
            Auth-->>CLI: unauthenticated
            CLI->>Output: build unauthenticated status
        end
    end
    CLI->>Output: format and print (JSON or human)
    CLI->>PH: emit cli-command:status with props
    Output-->>User: display result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I sniffed the tokens in the grass today,
Machine or user—now I know the way,
JSON or pretty, expiry in sight,
I hopped through the code and set things right,
Status revealed — a joyful bunny yay! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding a new infisical status command for inspecting authentication and session state.
Description check ✅ Passed The PR description is comprehensive, following the template structure with description, type selection, and tests. It includes detailed explanation of features, examples, and contributor acknowledgment.
Linked Issues check ✅ Passed The implementation addresses all primary coding requirements from issue #156: displays authenticated status, session validity, domain, auth method, user/identity, token expiry with warnings, supports --json output, and detects both machine and user authentication.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing the infisical status command as specified in issue #156; no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/status-command

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/cmd/status.go`:
- Around line 65-68: The machine-token expiry check in the
extractJWTExpiry(token.Token) branch flips validity only on exact expiry; change
the comparison to use the same 30-second safety buffer as user sessions (i.e.,
treat the token as expired if expiry.Before(time.Now().Add(30*time.Second))) or
use the shared expiry buffer constant used for sessions, so status.SessionValid
is set to false earlier and matches session logic.
- Around line 96-100: The code sets status.Domain from
configFile.LoggedInUserDomain (in util.GetConfigFile path), which may be just a
base host rather than the full API URL; update the assignment so status.Domain
returns the API URL instead—either by reading the explicit API URL field if
present on the config (e.g., configFile.APIURL / configFile.ApiUrl) or by
constructing the API endpoint from LoggedInUserDomain (ensure correct scheme and
path), and replace the current assignment in the block that reads
util.GetConfigFile() / LoggedInUserDomain so the CLI returns "Domain/API URL" as
required by the command contract.
- Around line 174-175: The message shown when session is invalid always
instructs the user to run infisical login; change the logic around the
status.SessionValid branch to branch on the authentication method (e.g., a field
like status.AuthMethod / status.AuthType on the status object) before calling
util.PrintfStdout, so that for user-based auth you print the existing
bold("infisical login") hint and for machine-token/universal-auth you print a
different remediation (e.g., refresh the service token, update CI secrets, or
point to the docs) instead; update the code that currently calls
util.PrintfStdout("\nSession expired. Run %s to re-authenticate.\n",
bold("infisical login")) to choose the message based on the auth method in
status.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 23e759ff-e4d8-4343-9c9d-88aa73e154ec

📥 Commits

Reviewing files that changed from the base of the PR and between c6a4cf0 and d017034.

📒 Files selected for processing (1)
  • packages/cmd/status.go

Comment thread packages/cmd/status.go
Comment thread packages/cmd/status.go
Comment thread packages/cmd/status.go Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (3)
packages/cmd/status.go (3)

65-68: ⚠️ Potential issue | 🟡 Minor

Use the same expiry safety buffer for machine tokens.

Line 66 treats machine tokens as valid until exact expiry, which can report “valid” moments before failure. Align it with the session buffer logic (30s).

Suggested fix
-			if expiry.Before(time.Now()) {
+			if expiry.Before(time.Now().Add(30 * time.Second)) {
 				status.SessionValid = false
 			}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cmd/status.go` around lines 65 - 68, The machine-token expiry check
uses exact expiry; update the compare to apply the same 30s safety buffer used
for sessions. In the block that calls extractJWTExpiry(token.Token) (and sets
status.SessionValid), change the condition to treat tokens as expired if expiry
is before time.Now().Add(30 * time.Second) so machine tokens are considered
invalid within the same safety window.

96-100: ⚠️ Potential issue | 🟠 Major

Return API URL format in Domain for user-session status.

Line 99 assigns raw LoggedInUserDomain, which may not be the API URL format expected by this command output.

Suggested fix
 	configFile, err := util.GetConfigFile()
 	if err == nil {
 		if configFile.LoggedInUserDomain != "" {
-			status.Domain = configFile.LoggedInUserDomain
+			status.Domain = util.AppendAPIEndpoint(configFile.LoggedInUserDomain)
 		}
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cmd/status.go` around lines 96 - 100, The code assigns raw
configFile.LoggedInUserDomain to status.Domain (inside the util.GetConfigFile()
success path) but the command expects an API URL format; update this block to
normalize/convert LoggedInUserDomain into the API URL format before setting
status.Domain—either call an existing helper (e.g., a domain->API URL
normalization util) or implement small logic to ensure the scheme and API path
are present (e.g., add https:// if missing and the expected API path/port) so
status.Domain always contains the canonical API URL rather than the raw domain
string.

174-175: ⚠️ Potential issue | 🟠 Major

Show auth-method-specific remediation for expired sessions.

Line 175 always recommends infisical login, which is incorrect for machine-token flows and CI usage.

Suggested fix
 	if !status.SessionValid {
-		util.PrintfStdout("\nSession expired. Run %s to re-authenticate.\n", bold("infisical login"))
+		if status.AuthMethod == "user" {
+			util.PrintfStdout("\nSession expired. Run %s to re-authenticate.\n", bold("infisical login"))
+		} else {
+			util.PrintfStdout("\nSession expired. Refresh/provide a valid machine token (%s or env var).\n", bold("--token"))
+		}
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cmd/status.go` around lines 174 - 175, The session-expired message
always recommends "infisical login" (using util.PrintfStdout and bold) but must
vary by auth method; update the status.SessionValid false handling to branch on
the auth method (e.g., read status.AuthMethod or status.IsMachineToken /
status.IsCI) and print an auth-method-specific remediation: for
interactive/OAuth show the existing "infisical login" suggestion, for
machine-token show guidance to (re)set the machine token (e.g., export
INFISICAL_TOKEN or re-run with --token), and for CI show a CI-specific note
pointing to setting the CI secret or docs; keep using util.PrintfStdout and bold
for command/variable emphasis and ensure the new branches replace the single
hardcoded message.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@packages/cmd/status.go`:
- Around line 65-68: The machine-token expiry check uses exact expiry; update
the compare to apply the same 30s safety buffer used for sessions. In the block
that calls extractJWTExpiry(token.Token) (and sets status.SessionValid), change
the condition to treat tokens as expired if expiry is before time.Now().Add(30 *
time.Second) so machine tokens are considered invalid within the same safety
window.
- Around line 96-100: The code assigns raw configFile.LoggedInUserDomain to
status.Domain (inside the util.GetConfigFile() success path) but the command
expects an API URL format; update this block to normalize/convert
LoggedInUserDomain into the API URL format before setting status.Domain—either
call an existing helper (e.g., a domain->API URL normalization util) or
implement small logic to ensure the scheme and API path are present (e.g., add
https:// if missing and the expected API path/port) so status.Domain always
contains the canonical API URL rather than the raw domain string.
- Around line 174-175: The session-expired message always recommends "infisical
login" (using util.PrintfStdout and bold) but must vary by auth method; update
the status.SessionValid false handling to branch on the auth method (e.g., read
status.AuthMethod or status.IsMachineToken / status.IsCI) and print an
auth-method-specific remediation: for interactive/OAuth show the existing
"infisical login" suggestion, for machine-token show guidance to (re)set the
machine token (e.g., export INFISICAL_TOKEN or re-run with --token), and for CI
show a CI-specific note pointing to setting the CI secret or docs; keep using
util.PrintfStdout and bold for command/variable emphasis and ensure the new
branches replace the single hardcoded message.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5f327ff0-b02d-428a-aa1a-99b4b8473373

📥 Commits

Reviewing files that changed from the base of the PR and between d017034 and 7d08c4a.

📒 Files selected for processing (1)
  • packages/cmd/status.go

- Add 30s expiry buffer for machine tokens (consistent with user sessions)
- Normalize LoggedInUserDomain to API URL via AppendAPIEndpoint
- Show auth-method-specific remediation for expired sessions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature request: add a CLI command to inspect current login/session status

1 participant