Skip to content

feat(jwtinfo): allow reading JWT token from file#24

Merged
xenOs76 merged 3 commits intomainfrom
feat/read_token_from_file
Apr 4, 2026
Merged

feat(jwtinfo): allow reading JWT token from file#24
xenOs76 merged 3 commits intomainfrom
feat/read_token_from_file

Conversation

@xenOs76
Copy link
Copy Markdown
Owner

@xenOs76 xenOs76 commented Apr 4, 2026

Summary by CodeRabbit

  • New Features

    • Added a command-line option to load JWT tokens directly from a file and a backing token-file loading flow.
    • Added a helper to read and validate tokens from files before use.
  • Improvements

    • Support for two token sources (file or HTTP request) with clearer control flow.
    • Improved, more specific error messages for token-file reads, token requests, request-values parsing, and token output.
    • Token decoding and JWKS checks now only run when token data is present.

@xenOs76 xenOs76 self-assigned this Apr 4, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 4, 2026

Warning

Rate limit exceeded

@xenOs76 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 2 minutes and 41 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 2 minutes and 41 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 31371129-3866-4ac7-b112-f65eb7cc37d6

📥 Commits

Reviewing files that changed from the base of the PR and between 3162384 and 930b725.

📒 Files selected for processing (1)
  • cmd/jwtinfo.go
📝 Walkthrough

Walkthrough

Adds a --token-file CLI flag and branch to load JWTs from a file or via HTTP. Introduces ReadTokenFromFile which reads and validates a JWT from disk. Adjusts command flow, error messages, and downstream gating based on presence of a raw access token.

Changes

Cohort / File(s) Summary
CLI: token-file flag & control flow
cmd/jwtinfo.go
Added --token-file flag and tokenFile state; command now selects token source: read from file (ReadTokenFromFile) when set, otherwise request via HTTP using existing request-values flags. Removed previous early-exit condition and updated error messages and gating so decode/parse/print run only when tokenData.AccessTokenRaw != "".
Token read helper
internal/jwtinfo/jwtinfo.go
Added exported ReadTokenFromFile(fileName string) (JwtTokenData, error) which reads file bytes, trims whitespace, stores in JwtTokenData.AccessTokenRaw, and validates with jwt.NewParser().ParseUnverified; separate error wrapping for file-read vs JWT-parse failures.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as CLI
  participant FS as FileSystem
  participant HTTP as TokenEndpoint
  participant JWT as JWT Parser
  participant JWKS as JWKS (optional)

  CLI->>CLI: parse flags (--token-file, --request-url, --jwks-url, ...)
  alt token-file provided
    CLI->>FS: Read token file
    FS-->>CLI: token bytes
    CLI->>JWT: ParseUnverified(token)
    JWT-->>CLI: token claims
  else token-file not provided
    CLI->>HTTP: Request token (request-values)
    HTTP-->>CLI: token response
    CLI->>JWT: ParseUnverified(token)
    JWT-->>CLI: token claims
  end
  alt jwks-url provided
    CLI->>JWKS: Fetch/parse JWKS
    JWKS-->>CLI: keys
    CLI->>JWT: Parse/Validate with JWKS
    JWT-->>CLI: validated token
  end
  CLI->>CLI: print token info
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nibble bytes from files so neat,

A token found beneath my feet.
No HTTP hop, just quiet cheer—
I parse and dance, the claims appear.

🚥 Pre-merge checks | ✅ 2 | ❌ 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 (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main feature addition: enabling JWT token reading from a file. It aligns with the core changes across both modified files.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/read_token_from_file

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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: 2

🧹 Nitpick comments (1)
cmd/jwtinfo.go (1)

54-70: Address linter whitespace violations.

Static analysis flags several whitespace issues in this block (wsl_v5 rules). Adding blank lines before declarations and returns improves readability and satisfies the linter.

Proposed formatting fix
 	Run: func(cmd *cobra.Command, args []string) {
 		// TODO: display version and exit
 		// TODO: remove global --config option
-
 		var err error
+
 		var tokenData jwtinfo.JwtTokenData
 
 		if tokenFile != "" {
 			tokenData, err = jwtinfo.ReadTokenFromFile(tokenFile)
 			if err != nil {
 				fmt.Printf(
 					"error while reading token value from file: %s",
 					err,
 				)
+
 				return
 			}
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/jwtinfo.go` around lines 54 - 70, The Run function's block has linter
whitespace (wsl_v5) violations around declarations and the early return; in the
Run func (the anonymous Run handler) add a blank line before the local
declarations (var err error, var tokenData jwtinfo.JwtTokenData) and add a blank
line before the return inside the tokenFile error branch (the branch that calls
jwtinfo.ReadTokenFromFile), so spacing separates declarations and control flow
for readability and to satisfy the linter.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@cmd/jwtinfo.go`:
- Around line 61-114: The code currently reads tokenData from
jwtinfo.ReadTokenFromFile when tokenFile is set and then always attempts
jwtinfo.RequestToken when requestURL is set, allowing the HTTP result to
overwrite the file result; change the control flow so the sources are mutually
exclusive (either return an error if both tokenFile and requestURL are provided,
or use an else-if to prioritize one source), updating the logic around the
tokenFile/requestURL checks and the tokenData assignment (symbols: tokenFile,
requestURL, tokenData, jwtinfo.ReadTokenFromFile, jwtinfo.RequestToken) and
ensure the CLI prints a clear error or usage message when both flags are
supplied.

In `@internal/jwtinfo/jwtinfo.go`:
- Around line 129-149: ReadTokenFromFile should trim whitespace from the file
contents before storing into JwtTokenData.AccessTokenRaw to avoid downstream
base64 decode failures (see DecodeBase64 which splits AccessTokenRaw on "."), so
call strings.TrimSpace on the read data when constructing td; also fix the error
message returned on read failure to say "unable to read token file" instead of
the copy-pasted text, and return the token with a nil error (return td, nil) on
success.

---

Nitpick comments:
In `@cmd/jwtinfo.go`:
- Around line 54-70: The Run function's block has linter whitespace (wsl_v5)
violations around declarations and the early return; in the Run func (the
anonymous Run handler) add a blank line before the local declarations (var err
error, var tokenData jwtinfo.JwtTokenData) and add a blank line before the
return inside the tokenFile error branch (the branch that calls
jwtinfo.ReadTokenFromFile), so spacing separates declarations and control flow
for readability and to satisfy the linter.
🪄 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: 77f12bd4-97dc-431d-9843-6ac37155771e

📥 Commits

Reviewing files that changed from the base of the PR and between 59211a7 and 7d38829.

📒 Files selected for processing (2)
  • cmd/jwtinfo.go
  • internal/jwtinfo/jwtinfo.go

@xenOs76 xenOs76 merged commit 85c238a into main Apr 4, 2026
3 checks passed
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.

1 participant