Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
6b90a39
RTECO-2746 - Adding access-token-verify feature
hanochg Nov 10, 2026
61401c1
RTECO-2746 - Adding access-token-verify integration tests
hanochg Nov 10, 2026
939ac7a
RTECO-2746 - Fixing atv to escape untrusted table output and reject e…
hanochg Nov 10, 2026
b27e27c
RTECO-2746 - Fixing the revoked-token integration case to revoke only…
hanochg Nov 10, 2026
06c9f7d
RTECO-2746 - Merge master into RTECO-2746-access-token-verify
hanochg Nov 16, 2026
3a024cf
RTECO-2746 - Removing the reference-token prefix from a test fixture
hanochg Nov 19, 2026
b40e207
RTECO-2746 - Keeping verification errors out of the generic error han…
hanochg Nov 23, 2026
db467f3
RTECO-2746 - Listing the Connect and roles token types in the help
hanochg Nov 23, 2026
292b679
RTECO-2746 - Removing the token argument from access-token-verify
hanochg Nov 23, 2026
eaf7464
RTECO-2746 - Showing the token format and verifying reference tokens
hanochg Nov 23, 2026
83c9c01
RTECO-2746 - Describing scope-based token types in the atv help
hanochg Nov 23, 2026
1f9b897
RTECO-2746 - Discarding leftover pasted input at the atv prompt and f…
hanochg Nov 23, 2026
fde5f39
RTECO-2746 - Showing atv results in colored tables with a verdict line
hanochg Nov 24, 2026
7bddd88
RTECO-2746 - Showing token types for failed verifications and droppin…
hanochg Nov 24, 2026
b58b5a6
RTECO-2746 - Showing a no-data note for rejected reference tokens and…
hanochg Nov 24, 2026
e10cbe0
RTECO-2746 - Mentioning Mission Control pairing tokens in the atv help
hanochg Nov 24, 2026
a3c7951
RTECO-2746 - Describing the readiness check for JWTs in the atv help
hanochg Nov 24, 2026
589a523
RTECO-2746 - Reverting the readiness wording in the atv help
hanochg Nov 24, 2026
b22ebe8
RTECO-2746 - Forcing colors in the atv test with calls every gookit/c…
hanochg Nov 24, 2026
0a8a54c
RTECO-2746 - Describing the system/version check for JWTs in the atv …
hanochg Nov 24, 2026
5360cd8
RTECO-2746 - Explaining what a 401 or 403 from system/version means i…
hanochg Nov 24, 2026
dcf8791
RTECO-2746 - Naming artifactory/api/system/version in the atv help an…
hanochg Nov 24, 2026
7fb2143
RTECO-2746 - Filtering on valid in the atv JSON example and explainin…
hanochg Nov 24, 2026
535ee9d
RTECO-2746 - Removing the http:// warning, like other commands that u…
hanochg Nov 25, 2026
60000ca
RTECO-2746 - Showing a couldn't-verify verdict and the status field i…
hanochg Nov 29, 2026
002324c
RTECO-2746 - Describing the dual server check and noting a valid refe…
hanochg Nov 29, 2026
06c3b2e
RTECO-2746 - Describing the single reported server failure and updati…
hanochg Nov 30, 2026
86a448c
RTECO-2746 - Keeping input after a lone Esc, rejecting any Unicode wh…
hanochg Nov 30, 2026
4bb03cb
RTECO-2746 - Showing whether a valid token is revocable
hanochg Nov 30, 2026
19dd424
RTECO-2746 - Showing the revocability next to the token types, in gre…
hanochg Nov 30, 2026
e99a0e1
RTECO-2746 - Capitalizing the revocability values in the help and tests
hanochg Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
185 changes: 185 additions & 0 deletions access_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
package main

import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/jfrog/jfrog-cli-core/v2/general/token"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/jfrog/jfrog-cli-core/v2/artifactory/utils"
"github.com/jfrog/jfrog-cli-core/v2/common/commands"
Expand All @@ -23,6 +29,7 @@ import (
"github.com/jfrog/jfrog-client-go/utils/errorutils"
"github.com/jfrog/jfrog-client-go/utils/io/httputils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

var (
Expand Down Expand Up @@ -346,6 +353,184 @@ func TestAccessTokenCreate(t *testing.T) {
}
}

type atvOutput struct {
Valid bool `json:"valid"`
Status string `json:"status"`
Error string `json:"error"`
Format string `json:"format"`
Payload map[string]interface{} `json:"payload"`
Types []string `json:"types"`
}

func TestAccessTokenVerify(t *testing.T) {
initAccessTest(t)
if *tests.JfrogAccessToken == "" {
t.Skip("access token verify tests mint tokens with an admin access token, but a token is not provided. Skipping...")
}
createJfrogHomeConfig(t, true)
defer cleanTestsHomeEnv()
atvCli := coreTests.NewJfrogCli(execMain, "jfrog", "")

mintWithoutCleanup := func(t *testing.T, args ...string) (auth.CreateTokenResponseData, string) {
var created auth.CreateTokenResponseData
output, err := runAtcWithCloudFallback(t, append([]string{"atc"}, args...)...)
require.NoError(t, err)
require.NoError(t, json.Unmarshal([]byte(output), &created))
return created, output
}
mint := func(t *testing.T, args ...string) (auth.CreateTokenResponseData, string) {
created, output := mintWithoutCleanup(t, args...)
t.Cleanup(func() { revokeToken(t, created.TokenId) })
return created, output
}
writeFile := func(t *testing.T, content string) string {
path := filepath.Join(t.TempDir(), "token.txt")
require.NoError(t, os.WriteFile(path, []byte(content), 0o600))
return path
}
runAtv := func(t *testing.T, secret string, args ...string) (atvOutput, error) {
output, err := atvCli.RunCliCmdWithOutputs(t, append([]string{"atv", "--format=json"}, args...)...)
assert.NotContains(t, output, secret)
if err != nil {
assert.NotContains(t, err.Error(), secret)
}
var result atvOutput
if strings.TrimSpace(output) != "" {
assert.NoError(t, json.Unmarshal([]byte(output), &result))
}
return result, err
}
verify := func(t *testing.T, token string, args ...string) (atvOutput, error) {
return runAtv(t, token, append([]string{"--token-file=" + writeFile(t, token)}, args...)...)
}
assertValid := func(t *testing.T, result atvOutput, err error, types ...string) {
require.NoError(t, err)
assert.True(t, result.Valid)
assert.Equal(t, "valid", result.Status)
assert.Equal(t, "JWT", result.Format)
assert.Equal(t, types, result.Types)
}
assertInvalid := func(t *testing.T, result atvOutput, err error, reason string) {
require.Error(t, err)
assert.False(t, result.Valid)
assert.Equal(t, "invalid", result.Status)
assert.Contains(t, result.Error, reason)
}

t.Run("identity token", func(t *testing.T) {
created, _ := mint(t)
result, err := verify(t, created.AccessToken)
assertValid(t, result, err, "Identity Token")
})
t.Run("token file with the bare token", func(t *testing.T) {
created, _ := mint(t)
result, err := runAtv(t, created.AccessToken, "--token-file="+writeFile(t, created.AccessToken+"\n"))
assertValid(t, result, err, "Identity Token")
})
t.Run("token file with jf atc JSON output", func(t *testing.T) {
created, output := mint(t)
result, err := runAtv(t, created.AccessToken, "--token-file="+writeFile(t, output))
assertValid(t, result, err, "Identity Token")
})
t.Run("admin token", func(t *testing.T) {
created, _ := mint(t, "--grant-admin")
result, err := verify(t, created.AccessToken)
assertValid(t, result, err, "Admin Token")
})
t.Run("scoped token", func(t *testing.T) {
created, _ := mint(t, "--scope=system:metrics:r")
result, err := verify(t, created.AccessToken)
assertValid(t, result, err, "Scoped Token")
})
t.Run("groups token", func(t *testing.T) {
created, _ := mint(t, "--groups=group1,group2")
result, err := verify(t, created.AccessToken)
assertValid(t, result, err, "Applied Permissions Groups Token")
})
t.Run("token without expiry", func(t *testing.T) {
created, _ := mint(t, auth.ExtractUsernameFromAccessToken(*tests.JfrogAccessToken), "--expiry=0")
result, err := verify(t, created.AccessToken)
assertValid(t, result, err, "Identity Token")
assert.NotContains(t, result.Payload, "exp")
})
t.Run("reference token", func(t *testing.T) {
created, _ := mint(t, "--reference")
require.NotEmpty(t, created.ReferenceToken)
result, err := verify(t, created.ReferenceToken)
require.NoError(t, err)
assert.True(t, result.Valid)
assert.Equal(t, "Reference", result.Format)
assert.Equal(t, []string{"Identity Token"}, result.Types)
assert.Equal(t, created.TokenId, result.Payload["token_id"])
})
t.Run("revoked reference token", func(t *testing.T) {
created, _ := mintWithoutCleanup(t, "--reference")
revokeToken(t, created.TokenId)
result, err := verify(t, created.ReferenceToken)
assertInvalid(t, result, err, "token revoked: status 401 from GET /artifactory/api/system/version")
assert.Equal(t, "Reference", result.Format)
})
t.Run("value that isn't a token", func(t *testing.T) {
result, err := verify(t, "notATokenValue")
assertInvalid(t, result, err, "token revoked: status 401 from GET /artifactory/api/system/version")
})
t.Run("revoked token", func(t *testing.T) {
created, _ := mintWithoutCleanup(t)
revokeToken(t, created.TokenId)
result, err := verify(t, created.AccessToken)
assertInvalid(t, result, err, "status 40")
})
t.Run("tampered signature", func(t *testing.T) {
created, _ := mint(t)
i := len(created.AccessToken) - 10
tampered := created.AccessToken[:i] + flipBase64Char(created.AccessToken[i]) + created.AccessToken[i+1:]
result, err := verify(t, tampered)
assertInvalid(t, result, err, "invalid signature")
})
t.Run("locally signed token", func(t *testing.T) {
forged := signLocalToken(t)
result, err := verify(t, forged)
assertInvalid(t, result, err, "invalid signature")
})
t.Run("token as an argument is rejected", func(t *testing.T) {
created, _ := mint(t)
_, err := runAtv(t, created.AccessToken, created.AccessToken)
assert.ErrorContains(t, err, "can't be passed as an argument")
})
t.Run("unknown server id", func(t *testing.T) {
created, _ := mint(t)
_, err := verify(t, created.AccessToken, "--server-id=nope")
assert.ErrorContains(t, err, "nope")
})
}

func flipBase64Char(c byte) string {
if c == 'A' {
return "B"
}
return "A"
}

func signLocalToken(t *testing.T) string {
key, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
encode := func(v interface{}) string {
data, err := json.Marshal(v)
require.NoError(t, err)
return base64.RawURLEncoding.EncodeToString(data)
}
now := time.Now().Unix()
signingInput := encode(map[string]string{"alg": "RS256", "typ": "JWT", "ver": "2", "kid": "forged"}) + "." +
encode(map[string]interface{}{
"jti": "forged", "sub": "jfac@01h/users/admin", "aud": "*@*", "scp": "applied-permissions/admin",
"iss": "jfac@01h", "iat": now - 60, "exp": now + 3600,
})
digest := sha256.Sum256([]byte(signingInput))
signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, digest[:])
require.NoError(t, err)
return signingInput + "." + base64.RawURLEncoding.EncodeToString(signature)
}

func runAtcWithCloudFallback(t *testing.T, args ...string) (string, error) {
output, err := accessCli.RunCliCmdWithOutputs(t, args...)
if err == nil || !isInvalidFormattedNameError(err) {
Expand Down
52 changes: 52 additions & 0 deletions docs/general/tokenverify/help.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package tokenverify

var Usage = []string{"atv", "atv --token-file=<path>"}

func GetDescription() string {
return `Verifies a JFrog access token, JWT or reference. A JWT's signature and expiry are checked locally first. The configured JFrog server is then asked whether it accepts the token, and the token's format and type are reported. For a valid token, its revocability is reported too.`
}

func GetAIDescription() string {
return `Verify a JFrog Platform access token, JWT or reference, and report its format and what kind of token it is. For a JWT, the signature is checked against the configured server's root certificate and the claims and expiry are validated. The server is then asked with the token through GET /artifactory/api/system/version and, if that doesn't accept it, GET /access/api/v1/tokens/me; the token is valid when either accepts it. A value without dots isn't shaped like a JWT, so it's treated as a possible reference token and checked the same way, tokens/me first, since that call also returns the token's details.

When to use:
- Checking whether a token is still valid before using it in CI.
- Finding out what kind of token you were given: a JWT or a reference token, and its types (identity, admin, groups, roles, entitlements, scoped, internal, Connect or Mission Control pairing).
- Debugging authentication failures caused by an expired, revoked or foreign token.

Prerequisites:
- A server configured with jf config add or jf login. Its credentials are never used to verify the token, and its tokens are never refreshed.

Common patterns:
$ jf atv # paste the token at the hidden prompt
$ jf atc | jf atv # verify a freshly minted token
$ jf atc --reference | jq -r .reference_token | jf atv # verify a reference token
$ jf atv --token-file=token.txt # read the token from a file
$ jf atv --token-file=token.txt --format=json | jq 'select(.valid).types' # types only when the token is valid
$ jf atv --token-file=token.txt --format=json | jq -r .status # valid, invalid or unverified
$ jf atv --token-file=token.txt --format=json | jq -r .revocability # Revocable, Non-revocable or Unknown

Gotchas:
- The token can't be passed as an argument, because arguments are visible to other processes and kept in shell history. Use stdin or --token-file.
- Without --token-file, the token is read from stdin. In a terminal, it prompts and waits without echoing the input. The prompt reads a single line: if the pasted text has more lines, it's all discarded, so pass multi-line input such as jf atc's JSON with --token-file or through a pipe. Terminals that can't hide input, such as Git Bash's, need --token-file or a pipe.
- Only configured servers can be used. There's no --insecure-tls: trust a private CA by adding it to ~/.jfrog/security/certs.
- A value without dots isn't shaped like a JWT, so it's treated as a reference token and sent to the server as is. Only the server knows a reference token's details, so a revoked one has no data to show. A value with dots that doesn't parse as a JWT fails locally and is never sent.
- JSON input is read for its access_token value, so to verify the reference token from jf atc --reference output, extract reference_token first.
- The types come from the token's scopes only, one per kind of scope, so a token can have several. Quoted scopes and the legacy member-of-groups: and api:* scopes are recognized.
- A token with a scope starting with internal: has Internal Token among its types. Connect pairing, Connect device and Mission Control pairing scopes are also reported by name.
- A JWT is sent to the server only after its signature checks out. The token is checked with two calls, GET /artifactory/api/system/version and GET /access/api/v1/tokens/me, because each turns away some valid tokens (Artifactory a token whose audience excludes it, tokens/me some scopes). The second call is made only when the first doesn't accept the token. When neither does, the message shows the last call's answer, or the last 401 or 403 when there was one, with the server's error message: the token is revoked for a 401, rejected for a 403, and unverified when neither call could be reached or answered as expected. A value that was never a token is reported as revoked too, since the server answers 401 for it.
- --format=json output has a format field: JWT or Reference. For a reference token, the payload is the token details the server returned.
- --format=json output has a status field: valid, invalid (the token was checked and failed), or unverified (the check couldn't be done: no configured server, the server couldn't be reached, or it answered unexpectedly). The table shows the last case as "Couldn't verify".
- A valid token also gets a revocability: Revocable, Non-revocable or Unknown. A non-revocable token can't be revoked and stays valid until it expires. It's decided from the token's expiry, its ext.revocable mark, whether it's refreshable, and the server's revocable expiry threshold, which is read anonymously from GET /access/api/v1/config/shared. It's Unknown when something it depends on couldn't be checked, e.g. a reference token's ext field, which the server doesn't return.
- The exit code is 1 when the token is invalid or unverified; check status in the JSON output to tell them apart. The payload and the types its scopes claim are printed even then; the table marks the types as unverified.

Related: jf atc, jf eot

QA:
Q: How do I check whether a JFrog access token is still valid?
A: Run jf atv and paste the token at the prompt, or use jf atv --token-file=<path>

Q: How do I verify the token that jf atc just created and get JSON output?
A: jf atc | jf atv --format=json
`
}
102 changes: 102 additions & 0 deletions general/token/prompt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package token

import (
"errors"
"fmt"
"io"
"os"
"strings"
"unicode/utf8"

"github.com/jfrog/jfrog-client-go/utils/errorutils"
"github.com/mattn/go-isatty"
"golang.org/x/term"
)

const (
keyCtrlC = 0x03
keyCtrlD = 0x04
keyCtrlH = 0x08
keyCtrlU = 0x15
keyEscape = 0x1b
keyBackspace = 0x7f

multiLineInputError = "the pasted text has more than one line, so it was discarded. Paste the token on its own, or pass it with --token-file=<path> or through a pipe"
visibleTerminalError = "this terminal can't hide the token as you type it. Pass it with --token-file=<path> or through a pipe"
)

func terminalReader() func(prompt string) (string, error) {
switch fd := os.Stdin.Fd(); {
case term.IsTerminal(int(fd)):
return readHiddenLine
case isatty.IsCygwinTerminal(fd):
return func(string) (string, error) { return "", errorutils.CheckErrorf(visibleTerminalError) }
default:
return nil
}
}

func readHiddenLine(prompt string) (string, error) {
fd := int(os.Stdin.Fd())
state, err := term.MakeRaw(fd)
if err != nil {
return "", errorutils.CheckError(err)
}
defer func() { _ = term.Restore(fd, state) }()
_, _ = fmt.Fprint(os.Stderr, prompt)
line, leftover, err := readHiddenInput(os.Stdin)
leftover += discardPendingInput(fd)
_, _ = fmt.Fprint(os.Stderr, "\r\n")
if err != nil {
return "", err
}
if strings.TrimSpace(leftover) != "" {
return "", errorutils.CheckErrorf(multiLineInputError)
}
return line, nil
}

func readHiddenInput(input io.Reader) (line, leftover string, err error) {
var value []byte
inEscape, inSequence := false, false
buf := make([]byte, 4096)
for {
n, readErr := input.Read(buf)
for i := 0; i < n; i++ {
b := buf[i]
if inEscape {
inEscape, inSequence = false, b == '[' || b == 'O'
// An Esc that ended the previous read was a key press of its own, not Alt+<key>.
if inSequence || i > 0 {
continue
}
}
switch {
case inSequence:
inSequence = b < 0x40 || b > 0x7e
case b == keyEscape:
inEscape = true
case b == '\r' || b == '\n':
return string(value), string(buf[i+1 : n]), nil
case b == keyCtrlC || b == keyCtrlD && len(value) == 0:
return "", string(buf[i+1 : n]), nil
case b == keyBackspace || b == keyCtrlH:
_, size := utf8.DecodeLastRune(value)
value = value[:len(value)-size]
case b == keyCtrlU:
value = value[:0]
case b < 0x20:
case len(value) == maxTokenInput:
return "", string(buf[i+1 : n]), errorutils.CheckErrorf("the token input is larger than 64 KiB")
default:
value = append(value, b)
}
}
if errors.Is(readErr, io.EOF) {
return string(value), "", nil
}
if readErr != nil {
return "", "", errorutils.CheckError(readErr)
}
}
}
7 changes: 7 additions & 0 deletions general/token/prompt_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !zos && !windows

package token

func discardPendingInput(int) string {
return ""
}
Loading
Loading