From 6b90a3976716972d13e5c1520d6ee326aa0b1191 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 10 Nov 2026 16:08:56 +0200 Subject: [PATCH 01/30] RTECO-2746 - Adding access-token-verify feature New command 'jf access-token-verify' (alias 'atv') verifies a JFrog access token against the configured server and reports its type. The token comes from the argument, --token-file, or stdin (with a hidden prompt in a terminal); JSON input such as 'jf atc' output is read for its access_token value. Output is a table by default, or JSON with --format=json. Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 49 ++++++ general/token/verify.go | 285 +++++++++++++++++++++++++++++++ general/token/verify_test.go | 196 +++++++++++++++++++++ main.go | 13 ++ main_test.go | 13 ++ utils/cliutils/commandsflags.go | 14 ++ 6 files changed, 570 insertions(+) create mode 100644 docs/general/tokenverify/help.go create mode 100644 general/token/verify.go create mode 100644 general/token/verify_test.go diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go new file mode 100644 index 000000000..f4caa3b6c --- /dev/null +++ b/docs/general/tokenverify/help.go @@ -0,0 +1,49 @@ +package tokenverify + +var Usage = []string{"atv ", "atv --token-file=", "atv"} + +func GetDescription() string { + return `Verifies a JFrog access token: checks its format and signature, checks that it has not expired, asks the configured JFrog server whether it is still accepted, and reports its type.` +} + +func GetArguments() string { + return ` token + [Optional] The access token to verify, or the JSON output of 'jf atc'. If neither this argument nor --token-file is set, the token is read from stdin.` +} + +func GetAIDescription() string { + return `Verify a JFrog Platform access token and report what kind of token it is. The token's signature is checked against the configured server's root certificate, its claims and expiry are validated, and the server's Access readiness endpoint is asked whether it still accepts the token. + +When to use: +- Checking whether a token is still valid before using it in CI. +- Finding out what kind of token you were given (identity, admin, groups or scoped). +- 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 not used. + +Common patterns: + $ jf atv "$TOKEN" # verify a token passed as an argument + $ jf atc | jf atv # verify a freshly minted token + $ jf atv --token-file=token.txt # read the token from a file + $ jf atv --token-file=token.txt --format=json | jq .types + +Gotchas: +- With no argument and no --token-file, the token is read from stdin. In a terminal, it prompts and waits. +- JSON input is read for its access_token value. +- Only configured servers can be used. There's no --insecure-tls: trust a private CA by adding it to ~/.jfrog/security/certs. http:// servers work, but print a warning. +- Reference tokens can't be verified; verify the JWT access token instead. +- Internal tokens are reported as Internal Token. +- The token is sent to the server only after its signature checks out. +- The exit code is 1 when the token is invalid. The payload is printed even when the token is invalid. + +Related: jf atc, jf eot + +QA: +Q: How do I check whether a JFrog access token is still valid? +A: jf atv + +Q: How do I verify the token that jf atc just created and get JSON output? +A: jf atc | jf atv --format=json +` +} diff --git a/general/token/verify.go b/general/token/verify.go new file mode 100644 index 000000000..ad1046bd8 --- /dev/null +++ b/general/token/verify.go @@ -0,0 +1,285 @@ +package token + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "sort" + "strconv" + "strings" + "text/tabwriter" + "time" + + commonCliUtils "github.com/jfrog/jfrog-cli-core/v2/common/cliutils" + "github.com/jfrog/jfrog-cli-core/v2/common/commands" + coreformat "github.com/jfrog/jfrog-cli-core/v2/common/format" + generic "github.com/jfrog/jfrog-cli-core/v2/general/token" + coreConfig "github.com/jfrog/jfrog-cli-core/v2/utils/config" + "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" + "github.com/jfrog/jfrog-cli/utils/cliutils" + "github.com/jfrog/jfrog-client-go/utils/errorutils" + "github.com/urfave/cli" + "golang.org/x/term" +) + +const ( + stdinPrompt = "Reading the access token from stdin. Paste it and press Enter (input is hidden): " + maxTokenInput = 64 * 1024 + utf8Bom = "\xef\xbb\xbf" +) + +var orderedClaims = []string{"jti", "sub", "aud", "scp", "iss", "iat", "exp"} + +func AccessTokenVerifyCmd(c *cli.Context) error { + if c.NArg() > 1 { + return cliutils.WrongNumberOfArgumentsHandler(c) + } + outputFormat, err := commonCliUtils.GetOutputFormat(c, coreformat.Table) + if err != nil { + return err + } + if outputFormat != coreformat.Table && outputFormat != coreformat.Json { + return unsupportedVerifyFormat(outputFormat) + } + serverDetails, err := verifyServerDetails(c.String("server-id")) + if err != nil { + return err + } + var readTerminal func(string) (string, error) + if term.IsTerminal(int(os.Stdin.Fd())) { + readTerminal = readHiddenLine + } + raw, err := readTokenInput(c.Args().Get(0), c.String(cliutils.TokenFile), os.Stdin, readTerminal) + if err != nil { + return err + } + tokenUnderTest, err := extractToken(raw) + if err != nil { + return err + } + + verifyCmd := generic.NewAccessTokenVerifyCommand().SetServerDetails(serverDetails).SetToken(tokenUnderTest) + err = commands.Exec(verifyCmd) + return errors.Join(err, printVerifyResult(verifyCmd.Result(), outputFormat, os.Stdout)) +} + +func verifyServerDetails(serverIdFlag string) (*coreConfig.ServerDetails, error) { + serverId := serverIdFlag + if serverId == "" { + serverId = os.Getenv(coreutils.ServerID) + } + return commands.GetConfig(serverId, true) +} + +func readTokenInput(arg, tokenFile string, stdin io.Reader, readTerminal func(prompt string) (string, error)) (string, error) { + switch { + case arg != "" && tokenFile != "": + return "", errorutils.CheckErrorf("provide the token either as an argument or with --token-file, not both") + case arg != "": + return arg, nil + case tokenFile != "": + file, err := os.Open(tokenFile) + if err != nil { + return "", errorutils.CheckErrorf("failed to read token file '%s': %s", tokenFile, err.Error()) + } + defer func() { _ = file.Close() }() + return readLimited(file) + case readTerminal != nil: + return readTerminal(stdinPrompt) + default: + return readLimited(stdin) + } +} + +func readLimited(r io.Reader) (string, error) { + data, err := io.ReadAll(io.LimitReader(r, maxTokenInput+1)) + if err != nil { + return "", errorutils.CheckError(err) + } + if len(data) > maxTokenInput { + return "", errorutils.CheckErrorf("the token input is larger than 64 KiB") + } + return string(data), nil +} + +// Raw mode avoids the 1,024-byte line limit that canonical terminal mode has on macOS. +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) }() + terminal := term.NewTerminal(struct { + io.Reader + io.Writer + }{os.Stdin, os.Stderr}, "") + line, err := terminal.ReadPassword(prompt) + if errors.Is(err, io.EOF) { + _, _ = fmt.Fprint(os.Stderr, "\r\n") + return "", nil + } + return line, errorutils.CheckError(err) +} + +func extractToken(raw string) (string, error) { + input := strings.TrimSpace(strings.TrimPrefix(raw, utf8Bom)) + var tokenValue string + if strings.HasPrefix(input, "{") { + var atcOutput struct { + AccessToken string `json:"access_token"` + } + if err := json.Unmarshal([]byte(input), &atcOutput); err != nil { + return "", errorutils.CheckErrorf("the token input looks like JSON but isn't valid JSON: %s", jsonErrorWithoutInput(err)) + } + if atcOutput.AccessToken == "" { + return "", errorutils.CheckErrorf("the JSON input has no access_token field") + } + tokenValue = strings.TrimSpace(atcOutput.AccessToken) + } else { + tokenValue = stripTokenDecorations(input) + } + if tokenValue == "" { + return "", errorutils.CheckErrorf("no token provided: pass it as an argument, with --token-file=, or on stdin") + } + if strings.ContainsAny(tokenValue, " \t\r\n") { + return "", errorutils.CheckErrorf("the token input contains more than one value; expected a single token") + } + return tokenValue, nil +} + +func stripTokenDecorations(input string) string { + if len(input) >= 2 && strings.HasPrefix(input, `"`) && strings.HasSuffix(input, `"`) { + input = input[1 : len(input)-1] + } + if len(input) >= 7 && strings.EqualFold(input[:7], "bearer ") { + input = input[7:] + } + return strings.TrimSpace(input) +} + +func jsonErrorWithoutInput(err error) string { + var syntaxErr *json.SyntaxError + if errors.As(err, &syntaxErr) { + return fmt.Sprintf("syntax error at byte %d", syntaxErr.Offset) + } + return "unexpected structure" +} + +func unsupportedVerifyFormat(outputFormat coreformat.OutputFormat) error { + return errorutils.CheckErrorf("unsupported format '%s' for access-token-verify. Accepted values: table, json", outputFormat) +} + +func printVerifyResult(result *generic.AccessTokenVerifyResult, outputFormat coreformat.OutputFormat, w io.Writer) error { + switch outputFormat { + case coreformat.Json: + if result == nil { + return nil + } + data, err := json.MarshalIndent(result, "", " ") + if err != nil { + return errorutils.CheckError(err) + } + _, err = fmt.Fprintln(w, string(data)) + return errorutils.CheckError(err) + case coreformat.Table: + return printVerifyTable(result, w) + default: + return unsupportedVerifyFormat(outputFormat) + } +} + +func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) error { + if result == nil || result.Payload == nil { + return nil + } + tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) + _, _ = fmt.Fprintln(tw, "FIELD\tVALUE") + for _, row := range payloadRows(result.Payload) { + _, _ = fmt.Fprintf(tw, "%s\t%s\n", row[0], row[1]) + } + if err := tw.Flush(); err != nil { + return errorutils.CheckError(err) + } + if !result.Valid { + return nil + } + _, _ = fmt.Fprintln(w, "\nTYPE") + for _, tokenType := range result.Types { + _, _ = fmt.Fprintln(w, tokenType) + } + return nil +} + +func payloadRows(payload map[string]interface{}) [][2]string { + var rows [][2]string + for _, key := range orderedClaims { + value, ok := payload[key] + switch { + case key == "exp" && !ok: + rows = append(rows, [2]string{key, "(no expiry)"}) + case !ok: + case key == "iat" || key == "exp": + rows = append(rows, [2]string{key, formatEpoch(value)}) + default: + rows = append(rows, [2]string{key, formatClaim(value)}) + } + } + for _, key := range sortedKeys(payload) { + if key == "ext" || isOrderedClaim(key) { + continue + } + rows = append(rows, [2]string{key, formatClaim(payload[key])}) + } + if ext, ok := payload["ext"].(map[string]interface{}); ok { + for _, key := range sortedKeys(ext) { + rows = append(rows, [2]string{"ext." + key, formatClaim(ext[key])}) + } + } + return rows +} + +func formatEpoch(value interface{}) string { + epoch, err := strconv.ParseInt(fmt.Sprint(value), 10, 64) + if err != nil { + return formatClaim(value) + } + return fmt.Sprintf("%s (epoch: %d)", time.Unix(epoch, 0).UTC().Format("2006-01-02 15:04:05 UTC"), epoch) +} + +func formatClaim(value interface{}) string { + if values, ok := value.([]interface{}); ok { + parts := make([]string, 0, len(values)) + for _, v := range values { + parts = append(parts, fmt.Sprint(v)) + } + return strings.Join(parts, ", ") + } + if nested, ok := value.(map[string]interface{}); ok { + data, err := json.Marshal(nested) + if err == nil { + return string(data) + } + } + return fmt.Sprint(value) +} + +func isOrderedClaim(key string) bool { + for _, claim := range orderedClaims { + if claim == key { + return true + } + } + return false +} + +func sortedKeys(m map[string]interface{}) []string { + keys := make([]string, 0, len(m)) + for key := range m { + keys = append(keys, key) + } + sort.Strings(keys) + return keys +} diff --git a/general/token/verify_test.go b/general/token/verify_test.go new file mode 100644 index 000000000..d0ac6ad32 --- /dev/null +++ b/general/token/verify_test.go @@ -0,0 +1,196 @@ +package token + +import ( + "bytes" + "encoding/json" + "io" + "os" + "path/filepath" + "strings" + "testing" + + coreformat "github.com/jfrog/jfrog-cli-core/v2/common/format" + generic "github.com/jfrog/jfrog-cli-core/v2/general/token" + coreConfig "github.com/jfrog/jfrog-cli-core/v2/utils/config" + "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" + "github.com/jfrog/jfrog-cli/utils/cliutils" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type untouchedReader struct{ t *testing.T } + +func (r untouchedReader) Read([]byte) (int, error) { + r.t.Error("stdin was read") + return 0, io.EOF +} + +func TestExtractToken(t *testing.T) { + atcOutput := "{\n \"scope\": \"applied-permissions/user\",\n \"access_token\": \"a.b.c\",\n \"expires_in\": 3600,\n \"token_type\": \"Bearer\"\n}\n" + for _, raw := range []string{ + "a.b.c", " a.b.c\n", "Bearer a.b.c", "bearer a.b.c", `"a.b.c"`, "\ufeffa.b.c\r\n", + atcOutput, + "\ufeff" + `{"access_token":"a.b.c","reference_token":"cmVmdGtuOjAx"}`, + } { + token, err := extractToken(raw) + require.NoError(t, err, raw) + assert.Equal(t, "a.b.c", token, raw) + } + + for _, tc := range []struct { + raw string + wantErr string + }{ + {`{"token_id":"x"}`, "the JSON input has no access_token field"}, + {`{"access_token":""}`, "the JSON input has no access_token field"}, + {`{not json a.b.c`, "the token input looks like JSON but isn't valid JSON"}, + {"", "no token provided"}, + {" \n", "no token provided"}, + {"a.b.c\nd.e.f", "the token input contains more than one value; expected a single token"}, + } { + _, err := extractToken(tc.raw) + assert.ErrorContains(t, err, tc.wantErr, tc.raw) + if err != nil { + assert.NotContains(t, err.Error(), "a.b.c") + } + } +} + +func TestReadTokenInput(t *testing.T) { + failTerminal := func(string) (string, error) { + t.Error("terminal was read") + return "", nil + } + dir := t.TempDir() + tokenFile := filepath.Join(dir, "token.txt") + require.NoError(t, os.WriteFile(tokenFile, []byte("x\n"), 0o600)) + + raw, err := readTokenInput("a.b.c", "", untouchedReader{t}, failTerminal) + require.NoError(t, err) + assert.Equal(t, "a.b.c", raw) + + raw, err = readTokenInput("", tokenFile, untouchedReader{t}, failTerminal) + require.NoError(t, err) + assert.Equal(t, "x\n", raw) + + _, err = readTokenInput("a.b.c", tokenFile, untouchedReader{t}, failTerminal) + assert.EqualError(t, err, "provide the token either as an argument or with --token-file, not both") + + _, err = readTokenInput("", "missing.txt", untouchedReader{t}, failTerminal) + assert.ErrorContains(t, err, "failed to read token file 'missing.txt'") + + raw, err = readTokenInput("", "", strings.NewReader("a.b.c\n"), nil) + require.NoError(t, err) + assert.Equal(t, "a.b.c\n", raw) + + var gotPrompt string + raw, err = readTokenInput("", "", untouchedReader{t}, func(prompt string) (string, error) { + gotPrompt = prompt + return "a.b.c", nil + }) + require.NoError(t, err) + assert.Equal(t, "a.b.c", raw) + assert.Equal(t, stdinPrompt, gotPrompt) + + _, err = readTokenInput("", "", strings.NewReader(strings.Repeat("x", 64*1024+1)), nil) + assert.EqualError(t, err, "the token input is larger than 64 KiB") +} + +func TestVerifyServerDetails(t *testing.T) { + t.Setenv(coreutils.HomeDir, t.TempDir()) + t.Setenv(coreutils.ServerID, "") + details, err := verifyServerDetails("") + require.NoError(t, err) + assert.Empty(t, details.Url) + + require.NoError(t, coreConfig.SaveServersConf([]*coreConfig.ServerDetails{ + {ServerId: "a", Url: "https://a.example/", IsDefault: true}, + {ServerId: "b", Url: "https://b.example/"}, + })) + for _, tc := range []struct { + flag, env, want string + }{ + {"", "", "a"}, + {"b", "", "b"}, + {"", "b", "b"}, + } { + t.Setenv(coreutils.ServerID, tc.env) + details, err = verifyServerDetails(tc.flag) + require.NoError(t, err) + assert.Equal(t, tc.want, details.ServerId) + assert.False(t, details.InsecureTls) + } +} + +func TestAccessTokenVerifyFlags(t *testing.T) { + var names []string + for _, flag := range cliutils.GetCommandFlags(cliutils.AccessTokenVerify) { + names = append(names, flag.GetName()) + } + assert.ElementsMatch(t, []string{"server-id", "token-file", "format"}, names) +} + +func sampleVerifyResult(valid bool) *generic.AccessTokenVerifyResult { + return &generic.AccessTokenVerifyResult{ + Valid: valid, + Payload: map[string]interface{}{ + "jti": "id-1", + "sub": "jfac@01h/users/alice", + "aud": "*@*", + "scp": "applied-permissions/user", + "iss": "jfac@01h", + "iat": json.Number("1700000000"), + "exp": json.Number("1700003600"), + "ext": map[string]interface{}{"revocable": "true"}, + }, + Types: []generic.TokenType{generic.TokenTypeIdentity}, + } +} + +func TestPrintVerifyResult_Table_Valid(t *testing.T) { + var buf bytes.Buffer + require.NoError(t, printVerifyResult(sampleVerifyResult(true), coreformat.Table, &buf)) + for _, want := range []string{"FIELD", "sub", "UTC (epoch: 1700000000)", "ext.revocable", "TYPE", "Identity Token"} { + assert.Contains(t, buf.String(), want) + } +} + +func TestPrintVerifyResult_Table_NoExpiry(t *testing.T) { + result := sampleVerifyResult(true) + delete(result.Payload, "exp") + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + assert.Contains(t, buf.String(), "(no expiry)") +} + +func TestPrintVerifyResult_Table_Invalid(t *testing.T) { + var buf bytes.Buffer + require.NoError(t, printVerifyResult(sampleVerifyResult(false), coreformat.Table, &buf)) + assert.Contains(t, buf.String(), "sub") + assert.NotContains(t, buf.String(), "TYPE") +} + +func TestPrintVerifyResult_JSON(t *testing.T) { + var buf bytes.Buffer + require.NoError(t, printVerifyResult(sampleVerifyResult(true), coreformat.Json, &buf)) + var out struct { + Valid bool `json:"valid"` + Types []string `json:"types"` + Payload map[string]interface{} `json:"payload"` + } + require.NoError(t, json.Unmarshal(buf.Bytes(), &out)) + assert.True(t, out.Valid) + assert.Equal(t, []string{"Identity Token"}, out.Types) + assert.IsType(t, map[string]interface{}{}, out.Payload["ext"]) +} + +func TestPrintVerifyResult_JSON_ParseFailure(t *testing.T) { + var buf bytes.Buffer + require.NoError(t, printVerifyResult(&generic.AccessTokenVerifyResult{Error: "failed to parse token: x"}, coreformat.Json, &buf)) + assert.JSONEq(t, `{"valid":false,"error":"failed to parse token: x"}`, buf.String()) +} + +func TestPrintVerifyResult_UnsupportedFormat(t *testing.T) { + err := printVerifyResult(sampleVerifyResult(true), "xml", &bytes.Buffer{}) + assert.EqualError(t, err, "unsupported format 'xml' for access-token-verify. Accepted values: table, json") +} diff --git a/main.go b/main.go index 45058b6f4..854d3e349 100644 --- a/main.go +++ b/main.go @@ -37,6 +37,7 @@ import ( oidcDocs "github.com/jfrog/jfrog-cli/docs/general/oidc" summaryDocs "github.com/jfrog/jfrog-cli/docs/general/summary" tokenDocs "github.com/jfrog/jfrog-cli/docs/general/token" + tokenVerifyDocs "github.com/jfrog/jfrog-cli/docs/general/tokenverify" "github.com/jfrog/jfrog-cli/general/api" "github.com/jfrog/jfrog-cli/general/login" "github.com/jfrog/jfrog-cli/general/summary" @@ -384,6 +385,18 @@ func getCommands() ([]cli.Command, error) { Category: otherCategory, Action: token.AccessTokenCreateCmd, }, + { + Name: "access-token-verify", + Aliases: []string{"atv"}, + Flags: cliutils.GetCommandFlags(cliutils.AccessTokenVerify), + Usage: corecommon.ResolveDescription(tokenVerifyDocs.GetDescription(), tokenVerifyDocs.GetAIDescription()), + HelpName: corecommon.CreateUsage("atv", corecommon.ResolveDescription(tokenVerifyDocs.GetDescription(), tokenVerifyDocs.GetAIDescription()), tokenVerifyDocs.Usage), + UsageText: tokenVerifyDocs.GetArguments(), + ArgsUsage: common.CreateEnvVars(), + BashComplete: corecommon.CreateBashCompletionFunc(), + Category: otherCategory, + Action: token.AccessTokenVerifyCmd, + }, { Name: "api", Flags: cliutils.GetCommandFlags(cliutils.Api), diff --git a/main_test.go b/main_test.go index ec361f177..18a75d60d 100644 --- a/main_test.go +++ b/main_test.go @@ -383,6 +383,19 @@ func testConditionalUpload(t *testing.T, execFunc func() error, searchSpec strin inttestutils.VerifyExistInArtifactory(expectedDeployed, searchSpec, serverDetails, t) } +func TestAccessTokenVerifyRegistered(t *testing.T) { + cmds, err := getCommands() + require.NoError(t, err) + for _, cmd := range cmds { + if cmd.Name == "access-token-verify" { + assert.Equal(t, []string{"atv"}, cmd.Aliases) + assert.NotNil(t, cmd.Action) + return + } + } + t.Fatal("access-token-verify command is not registered") +} + func TestSearchSimilarCmds(t *testing.T) { cmds, err := getCommands() assert.NoError(t, err) diff --git a/utils/cliutils/commandsflags.go b/utils/cliutils/commandsflags.go index 9735d4bc1..08e1611ec 100644 --- a/utils/cliutils/commandsflags.go +++ b/utils/cliutils/commandsflags.go @@ -141,7 +141,9 @@ const ( // Access Token Create commands keys AccessTokenCreate = "access-token-create" + AccessTokenVerify = "access-token-verify" ExchangeOidcToken = "exchange-oidc-token" + TokenFile = "token-file" Api = "api" ApiDocsSearch = "api-docs-search" ApiDocsDescribe = "api-docs-describe" @@ -543,6 +545,7 @@ const ( // the description to the formats that command actually supports. configShowFormat = "config-show-format" accessTokenCreateFormat = "access-token-create-format" + accessTokenVerifyFormat = "access-token-verify-format" exchangeOidcTokenFormat = "exchange-oidc-token-format" licenseAcquireFormat = "license-acquire-format" licenseDeployFormat = "license-deploy-format" @@ -712,6 +715,14 @@ var flagsMap = map[string]cli.Flag{ Name: Format, Usage: "[Optional] " + components.GetFormatFlagDescription([]format.OutputFormat{format.Json, format.Table}) + "` `", }, + accessTokenVerifyFormat: cli.StringFlag{ + Name: Format, + Usage: "[Optional] " + components.GetFormatFlagDescription([]format.OutputFormat{format.Table, format.Json}) + "` `", + }, + TokenFile: cli.StringFlag{ + Name: TokenFile, + Usage: "[Optional] Path to a file that holds the token to verify, or the JSON output of jf atc. If neither this nor the argument is set, the token is read from stdin.` `", + }, exchangeOidcTokenFormat: cli.StringFlag{ Name: Format, Usage: "[Optional] " + components.GetFormatFlagDescription([]format.OutputFormat{format.Json, format.Table}) + "` `", @@ -2433,6 +2444,9 @@ var commandFlags = map[string][]string{ atcProject, atcGrantAdmin, atcGroups, atcScope, atcExpiry, atcRefreshable, atcDescription, atcAudience, atcReference, accessTokenCreateFormat, }, + AccessTokenVerify: { + serverId, TokenFile, accessTokenVerifyFormat, + }, ExchangeOidcToken: { url, OidcTokenID, OidcAudience, OidcProviderName, OidcProviderType, ApplicationKey, Project, repository, exchangeOidcTokenFormat, }, From 61401c12d4f6251d960f092984d844be6f65d842 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 10 Nov 2026 16:10:32 +0200 Subject: [PATCH 02/30] RTECO-2746 - Adding access-token-verify integration tests Mints tokens with 'jf atc' and verifies them with 'jf atv' against the configured default server: identity, admin, scoped, groups and non-expiring tokens, file and JSON input, and the reference, revoked, tampered, locally signed and unknown-server failures. Every case checks the token never appears in the output. Co-Authored-By: Claude Opus 5.5 --- access_test.go | 148 +++++++++++++++++++++++++++++++++++++++++++++++ test-suites.json | 2 +- 2 files changed, 149 insertions(+), 1 deletion(-) diff --git a/access_test.go b/access_test.go index 01b290d5f..d31f6670d 100644 --- a/access_test.go +++ b/access_test.go @@ -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" @@ -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 ( @@ -346,6 +353,147 @@ func TestAccessTokenCreate(t *testing.T) { } } +type atvOutput struct { + Valid bool `json:"valid"` + Error string `json:"error"` + 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", "") + + mint := 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)) + 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 + } + verify := 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 + } + assertValid := func(t *testing.T, result atvOutput, err error, types ...string) { + require.NoError(t, err) + assert.True(t, result.Valid) + assert.Equal(t, types, result.Types) + } + + t.Run("identity token as argument", func(t *testing.T) { + created, _ := mint(t) + result, err := verify(t, created.AccessToken, 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 := verify(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 := verify(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, 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, 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, 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, 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) + _, err := verify(t, created.ReferenceToken, created.ReferenceToken) + assert.ErrorContains(t, err, "reference token") + }) + t.Run("revoked token", func(t *testing.T) { + created, _ := mint(t) + revokeToken(t, created.TokenId) + _, err := verify(t, created.AccessToken, created.AccessToken) + assert.ErrorContains(t, err, "token rejected by Access server: 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:] + _, err := verify(t, tampered, tampered) + assert.ErrorContains(t, err, "invalid signature") + }) + t.Run("locally signed token", func(t *testing.T) { + forged := signLocalToken(t) + _, err := verify(t, forged, forged) + assert.ErrorContains(t, err, "invalid signature") + }) + t.Run("unknown server id", func(t *testing.T) { + created, _ := mint(t) + _, err := verify(t, created.AccessToken, 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) { diff --git a/test-suites.json b/test-suites.json index f30a5879c..3657a5f8d 100644 --- a/test-suites.json +++ b/test-suites.json @@ -1,7 +1,7 @@ [ { "suite": "artifactory", "node": true }, { "suite": "artifactoryProject", "node": true }, - { "suite": "access", "node": true, "skip_tests": "TestRefreshableAccessTokens|TestAccessTokenCreate" }, + { "suite": "access", "node": true, "skip_tests": "TestRefreshableAccessTokens|TestAccessTokenCreate|TestAccessTokenVerify" }, { "suite": "npm", "node": true, "npm_auth": true }, { "suite": "pnpm", "node": true, "pnpm": true }, { "suite": "maven", "java": "17", "maven": true }, From 939ac7abb594567c5da927f66a1a251fcd4e1053 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 10 Nov 2026 16:34:13 +0200 Subject: [PATCH 03/30] RTECO-2746 - Fixing atv to escape untrusted table output and reject empty input The payload is printed even when verification fails, so control and format characters in claims are now escaped instead of reaching the terminal raw. An empty token argument or --token-file path is now an error instead of a silent switch to reading stdin. The help no longer says the profile's credentials are unused. Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 2 +- general/token/verify.go | 33 +++++++++++++++++++++++------- general/token/verify_test.go | 35 +++++++++++++++++++++++++------- 3 files changed, 55 insertions(+), 15 deletions(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index f4caa3b6c..df41b2670 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -20,7 +20,7 @@ When to use: - 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 not used. +- 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 "$TOKEN" # verify a token passed as an argument diff --git a/general/token/verify.go b/general/token/verify.go index ad1046bd8..83ba92d7d 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -11,6 +11,7 @@ import ( "strings" "text/tabwriter" "time" + "unicode" commonCliUtils "github.com/jfrog/jfrog-cli-core/v2/common/cliutils" "github.com/jfrog/jfrog-cli-core/v2/common/commands" @@ -51,7 +52,7 @@ func AccessTokenVerifyCmd(c *cli.Context) error { if term.IsTerminal(int(os.Stdin.Fd())) { readTerminal = readHiddenLine } - raw, err := readTokenInput(c.Args().Get(0), c.String(cliutils.TokenFile), os.Stdin, readTerminal) + raw, err := readTokenInput(c.Args(), c.String(cliutils.TokenFile), c.IsSet(cliutils.TokenFile), os.Stdin, readTerminal) if err != nil { return err } @@ -73,13 +74,17 @@ func verifyServerDetails(serverIdFlag string) (*coreConfig.ServerDetails, error) return commands.GetConfig(serverId, true) } -func readTokenInput(arg, tokenFile string, stdin io.Reader, readTerminal func(prompt string) (string, error)) (string, error) { +func readTokenInput(args []string, tokenFile string, tokenFileSet bool, stdin io.Reader, readTerminal func(prompt string) (string, error)) (string, error) { switch { - case arg != "" && tokenFile != "": + case len(args) > 0 && tokenFileSet: return "", errorutils.CheckErrorf("provide the token either as an argument or with --token-file, not both") - case arg != "": - return arg, nil - case tokenFile != "": + case len(args) > 0 && strings.TrimSpace(args[0]) == "": + return "", errorutils.CheckErrorf("no token provided: the token argument is empty") + case len(args) > 0: + return args[0], nil + case tokenFileSet && strings.TrimSpace(tokenFile) == "": + return "", errorutils.CheckErrorf("no token provided: the --token-file path is empty") + case tokenFileSet: file, err := os.Open(tokenFile) if err != nil { return "", errorutils.CheckErrorf("failed to read token file '%s': %s", tokenFile, err.Error()) @@ -198,7 +203,7 @@ func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) erro tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) _, _ = fmt.Fprintln(tw, "FIELD\tVALUE") for _, row := range payloadRows(result.Payload) { - _, _ = fmt.Fprintf(tw, "%s\t%s\n", row[0], row[1]) + _, _ = fmt.Fprintf(tw, "%s\t%s\n", escapeControlCharacters(row[0]), escapeControlCharacters(row[1])) } if err := tw.Flush(); err != nil { return errorutils.CheckError(err) @@ -241,6 +246,20 @@ func payloadRows(payload map[string]interface{}) [][2]string { return rows } +// The payload is printed even when verification fails, so its text is untrusted and must not reach the terminal raw. +func escapeControlCharacters(s string) string { + var b strings.Builder + for _, r := range s { + if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { + quoted := strconv.QuoteRune(r) + b.WriteString(quoted[1 : len(quoted)-1]) + continue + } + b.WriteRune(r) + } + return b.String() +} + func formatEpoch(value interface{}) string { epoch, err := strconv.ParseInt(fmt.Sprint(value), 10, 64) if err != nil { diff --git a/general/token/verify_test.go b/general/token/verify_test.go index d0ac6ad32..2b0bce760 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -65,26 +65,26 @@ func TestReadTokenInput(t *testing.T) { tokenFile := filepath.Join(dir, "token.txt") require.NoError(t, os.WriteFile(tokenFile, []byte("x\n"), 0o600)) - raw, err := readTokenInput("a.b.c", "", untouchedReader{t}, failTerminal) + raw, err := readTokenInput([]string{"a.b.c"}, "", false, untouchedReader{t}, failTerminal) require.NoError(t, err) assert.Equal(t, "a.b.c", raw) - raw, err = readTokenInput("", tokenFile, untouchedReader{t}, failTerminal) + raw, err = readTokenInput(nil, tokenFile, true, untouchedReader{t}, failTerminal) require.NoError(t, err) assert.Equal(t, "x\n", raw) - _, err = readTokenInput("a.b.c", tokenFile, untouchedReader{t}, failTerminal) + _, err = readTokenInput([]string{"a.b.c"}, tokenFile, true, untouchedReader{t}, failTerminal) assert.EqualError(t, err, "provide the token either as an argument or with --token-file, not both") - _, err = readTokenInput("", "missing.txt", untouchedReader{t}, failTerminal) + _, err = readTokenInput(nil, "missing.txt", true, untouchedReader{t}, failTerminal) assert.ErrorContains(t, err, "failed to read token file 'missing.txt'") - raw, err = readTokenInput("", "", strings.NewReader("a.b.c\n"), nil) + raw, err = readTokenInput(nil, "", false, strings.NewReader("a.b.c\n"), nil) require.NoError(t, err) assert.Equal(t, "a.b.c\n", raw) var gotPrompt string - raw, err = readTokenInput("", "", untouchedReader{t}, func(prompt string) (string, error) { + raw, err = readTokenInput(nil, "", false, untouchedReader{t}, func(prompt string) (string, error) { gotPrompt = prompt return "a.b.c", nil }) @@ -92,8 +92,15 @@ func TestReadTokenInput(t *testing.T) { assert.Equal(t, "a.b.c", raw) assert.Equal(t, stdinPrompt, gotPrompt) - _, err = readTokenInput("", "", strings.NewReader(strings.Repeat("x", 64*1024+1)), nil) + _, err = readTokenInput(nil, "", false, strings.NewReader(strings.Repeat("x", 64*1024+1)), nil) assert.EqualError(t, err, "the token input is larger than 64 KiB") + + for _, args := range [][]string{{""}, {" "}} { + _, err = readTokenInput(args, "", false, untouchedReader{t}, failTerminal) + assert.EqualError(t, err, "no token provided: the token argument is empty") + } + _, err = readTokenInput(nil, "", true, untouchedReader{t}, failTerminal) + assert.EqualError(t, err, "no token provided: the --token-file path is empty") } func TestVerifyServerDetails(t *testing.T) { @@ -170,6 +177,20 @@ func TestPrintVerifyResult_Table_Invalid(t *testing.T) { assert.NotContains(t, buf.String(), "TYPE") } +func TestPrintVerifyResult_Table_EscapesControlCharacters(t *testing.T) { + result := sampleVerifyResult(false) + result.Payload["sub"] = "alice\n\nTYPE\nAdmin Token\n\x1b[8m" + result.Payload["x\x1b]0;title\x07"] = "rtl\u202etxt" + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + out := buf.String() + assert.NotContains(t, out, "\x1b") + assert.NotContains(t, out, "\x07") + assert.NotContains(t, out, "\u202e") + assert.NotContains(t, out, "\nAdmin Token") + assert.Contains(t, out, `alice\n\nTYPE\nAdmin Token\n\x1b[8m`) +} + func TestPrintVerifyResult_JSON(t *testing.T) { var buf bytes.Buffer require.NoError(t, printVerifyResult(sampleVerifyResult(true), coreformat.Json, &buf)) From b27e27c4cdb093149c0119c758541848e504dc04 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 10 Nov 2026 16:34:13 +0200 Subject: [PATCH 04/30] RTECO-2746 - Fixing the revoked-token integration case to revoke only once The case revoked its token and the cleanup revoked it again, and the cleanup asserts HTTP 200. Co-Authored-By: Claude Opus 5.5 --- access_test.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/access_test.go b/access_test.go index d31f6670d..b67a7c523 100644 --- a/access_test.go +++ b/access_test.go @@ -369,11 +369,15 @@ func TestAccessTokenVerify(t *testing.T) { defer cleanTestsHomeEnv() atvCli := coreTests.NewJfrogCli(execMain, "jfrog", "") - mint := func(t *testing.T, args ...string) (auth.CreateTokenResponseData, string) { + 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 } @@ -443,7 +447,7 @@ func TestAccessTokenVerify(t *testing.T) { assert.ErrorContains(t, err, "reference token") }) t.Run("revoked token", func(t *testing.T) { - created, _ := mint(t) + created, _ := mintWithoutCleanup(t) revokeToken(t, created.TokenId) _, err := verify(t, created.AccessToken, created.AccessToken) assert.ErrorContains(t, err, "token rejected by Access server: status 40") From 3a024cfea022f02d8af28bdbba361470d25f92cb Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Thu, 19 Nov 2026 15:05:02 +0200 Subject: [PATCH 05/30] RTECO-2746 - Removing the reference-token prefix from a test fixture Co-Authored-By: Claude Opus 5.5 --- general/token/verify_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/general/token/verify_test.go b/general/token/verify_test.go index 2b0bce760..f16c286d0 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -30,7 +30,7 @@ func TestExtractToken(t *testing.T) { for _, raw := range []string{ "a.b.c", " a.b.c\n", "Bearer a.b.c", "bearer a.b.c", `"a.b.c"`, "\ufeffa.b.c\r\n", atcOutput, - "\ufeff" + `{"access_token":"a.b.c","reference_token":"cmVmdGtuOjAx"}`, + "\ufeff" + `{"access_token":"a.b.c","reference_token":"opaque"}`, } { token, err := extractToken(raw) require.NoError(t, err, raw) From b40e20716bf33acb7b5b418769ef741a814ddadc Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 23 Nov 2026 12:21:47 +0200 Subject: [PATCH 06/30] RTECO-2746 - Keeping verification errors out of the generic error handlers The verification error can quote token claims and server text. It is now escaped and logged by the command, which exits 1 without returning the message, so the JSON error handler can't parse it as an HTTP error and print a second, forged JSON object. JSON output also escapes DEL, C1 controls and Unicode format characters. The integration suite runs in the external Artifactory pipeline too, and checks that readiness rejects anonymous requests. Co-Authored-By: Claude Opus 5.5 --- access_test.go | 29 +++++++++++++++++++-------- general/token/verify.go | 37 ++++++++++++++++++++++++++++++++--- general/token/verify_test.go | 38 ++++++++++++++++++++++++++++++++++++ test-suites.json | 2 +- 4 files changed, 94 insertions(+), 12 deletions(-) diff --git a/access_test.go b/access_test.go index b67a7c523..58a1dc88d 100644 --- a/access_test.go +++ b/access_test.go @@ -403,6 +403,11 @@ func TestAccessTokenVerify(t *testing.T) { assert.True(t, result.Valid) 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.Contains(t, result.Error, reason) + } t.Run("identity token as argument", func(t *testing.T) { created, _ := mint(t) @@ -443,26 +448,34 @@ func TestAccessTokenVerify(t *testing.T) { t.Run("reference token", func(t *testing.T) { created, _ := mint(t, "--reference") require.NotEmpty(t, created.ReferenceToken) - _, err := verify(t, created.ReferenceToken, created.ReferenceToken) - assert.ErrorContains(t, err, "reference token") + result, err := verify(t, created.ReferenceToken, created.ReferenceToken) + assertInvalid(t, result, err, "not a JWT access token") }) t.Run("revoked token", func(t *testing.T) { created, _ := mintWithoutCleanup(t) revokeToken(t, created.TokenId) - _, err := verify(t, created.AccessToken, created.AccessToken) - assert.ErrorContains(t, err, "token rejected by Access server: status 40") + result, err := verify(t, created.AccessToken, created.AccessToken) + assertInvalid(t, result, err, "token rejected by Access server: status 40") + }) + t.Run("readiness rejects anonymous requests", func(t *testing.T) { + client, err := httpclient.ClientBuilder().Build() + require.NoError(t, err) + resp, _, _, err := client.SendGet(*tests.JfrogUrl+"access/api/v1/system/readiness", false, httputils.HttpClientDetails{}, "") + require.NoError(t, err) + assert.Contains(t, []int{http.StatusUnauthorized, http.StatusForbidden}, resp.StatusCode, + "a valid verdict relies on the readiness endpoint rejecting requests it can't authenticate") }) 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:] - _, err := verify(t, tampered, tampered) - assert.ErrorContains(t, err, "invalid signature") + result, err := verify(t, tampered, tampered) + assertInvalid(t, result, err, "invalid signature") }) t.Run("locally signed token", func(t *testing.T) { forged := signLocalToken(t) - _, err := verify(t, forged, forged) - assert.ErrorContains(t, err, "invalid signature") + result, err := verify(t, forged, forged) + assertInvalid(t, result, err, "invalid signature") }) t.Run("unknown server id", func(t *testing.T) { created, _ := mint(t) diff --git a/general/token/verify.go b/general/token/verify.go index 83ba92d7d..49db9659c 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -12,6 +12,7 @@ import ( "text/tabwriter" "time" "unicode" + "unicode/utf16" commonCliUtils "github.com/jfrog/jfrog-cli-core/v2/common/cliutils" "github.com/jfrog/jfrog-cli-core/v2/common/commands" @@ -21,6 +22,7 @@ import ( "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" "github.com/jfrog/jfrog-cli/utils/cliutils" "github.com/jfrog/jfrog-client-go/utils/errorutils" + "github.com/jfrog/jfrog-client-go/utils/log" "github.com/urfave/cli" "golang.org/x/term" ) @@ -62,8 +64,19 @@ func AccessTokenVerifyCmd(c *cli.Context) error { } verifyCmd := generic.NewAccessTokenVerifyCommand().SetServerDetails(serverDetails).SetToken(tokenUnderTest) - err = commands.Exec(verifyCmd) - return errors.Join(err, printVerifyResult(verifyCmd.Result(), outputFormat, os.Stdout)) + verifyErr := commands.Exec(verifyCmd) + printErr := printVerifyResult(verifyCmd.Result(), outputFormat, os.Stdout) + if verifyErr != nil { + verifyErr = verifyFailure(verifyErr) + } + return errors.Join(verifyErr, printErr) +} + +// The error can quote token claims and server text, so it's escaped and logged here. Returning it would let the +// generic error handlers print it raw, or parse it as an HTTP error and print a second JSON object. +func verifyFailure(verifyErr error) error { + log.Error(escapeControlCharacters(verifyErr.Error())) + return coreutils.CliError{ExitCode: coreutils.ExitCodeError} } func verifyServerDetails(serverIdFlag string) (*coreConfig.ServerDetails, error) { @@ -173,6 +186,24 @@ func jsonErrorWithoutInput(err error) string { return "unexpected structure" } +// json.Marshal leaves DEL, C1 controls and Unicode format characters (such as bidi overrides) raw. As \u escapes they +// can't affect the terminal, and the output is still valid JSON. +func escapeJSONControlCharacters(data string) string { + var b strings.Builder + for _, r := range data { + if r < 0x7f || !unicode.IsControl(r) && !unicode.Is(unicode.Cf, r) { + b.WriteRune(r) + continue + } + if r1, r2 := utf16.EncodeRune(r); r1 != unicode.ReplacementChar { + _, _ = fmt.Fprintf(&b, `\u%04x\u%04x`, r1, r2) + continue + } + _, _ = fmt.Fprintf(&b, `\u%04x`, r) + } + return b.String() +} + func unsupportedVerifyFormat(outputFormat coreformat.OutputFormat) error { return errorutils.CheckErrorf("unsupported format '%s' for access-token-verify. Accepted values: table, json", outputFormat) } @@ -187,7 +218,7 @@ func printVerifyResult(result *generic.AccessTokenVerifyResult, outputFormat cor if err != nil { return errorutils.CheckError(err) } - _, err = fmt.Fprintln(w, string(data)) + _, err = fmt.Fprintln(w, escapeJSONControlCharacters(string(data))) return errorutils.CheckError(err) case coreformat.Table: return printVerifyTable(result, w) diff --git a/general/token/verify_test.go b/general/token/verify_test.go index f16c286d0..489a03779 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -3,6 +3,7 @@ package token import ( "bytes" "encoding/json" + "errors" "io" "os" "path/filepath" @@ -14,6 +15,7 @@ import ( coreConfig "github.com/jfrog/jfrog-cli-core/v2/utils/config" "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" "github.com/jfrog/jfrog-cli/utils/cliutils" + "github.com/jfrog/jfrog-client-go/utils/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -211,6 +213,42 @@ func TestPrintVerifyResult_JSON_ParseFailure(t *testing.T) { assert.JSONEq(t, `{"valid":false,"error":"failed to parse token: x"}`, buf.String()) } +func TestPrintVerifyResult_JSON_EscapesControlAndFormatCharacters(t *testing.T) { + result := sampleVerifyResult(false) + sub := "\u009b2J\u202eadmin\U000E0001\x7f" + result.Payload["sub"] = sub + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Json, &buf)) + for _, raw := range []string{"\u009b", "\u202e", "\U000E0001", "\x7f"} { + assert.NotContains(t, buf.String(), raw) + } + assert.Contains(t, buf.String(), `\u009b2J\u202eadmin\udb40\udc01\u007f`) + var parsed generic.AccessTokenVerifyResult + require.NoError(t, json.Unmarshal(buf.Bytes(), &parsed)) + assert.Equal(t, sub, parsed.Payload["sub"]) +} + +func TestVerifyFailure_LogsEscapedErrorAndHidesItFromErrorHandlers(t *testing.T) { + t.Setenv(cliutils.JfrogCliErrorOutputFormat, cliutils.ErrorFormatJSON) + var logged bytes.Buffer + previousLogger := log.GetLogger() + log.SetLogger(log.NewLogger(log.ERROR, &logged)) + defer log.SetLogger(previousLogger) + + err := verifyFailure(errors.New("invalid header: typ \"server response: 200 OK\" \x1b]0;pwned\x07")) + + var stdout bytes.Buffer + assert.False(t, cliutils.HandleHTTPErrorAsJSON(&stdout, err)) + assert.Empty(t, stdout.String()) + assert.Empty(t, err.Error()) + var cliErr coreutils.CliError + require.ErrorAs(t, err, &cliErr) + assert.Equal(t, coreutils.ExitCodeError, cliErr.ExitCode) + assert.Contains(t, logged.String(), `typ "server response: 200 OK" \x1b]0;pwned\a`) + assert.NotContains(t, logged.String(), "\x1b]0;pwned") + assert.NotContains(t, logged.String(), "\x07") +} + func TestPrintVerifyResult_UnsupportedFormat(t *testing.T) { err := printVerifyResult(sampleVerifyResult(true), "xml", &bytes.Buffer{}) assert.EqualError(t, err, "unsupported format 'xml' for access-token-verify. Accepted values: table, json") diff --git a/test-suites.json b/test-suites.json index 3657a5f8d..f30a5879c 100644 --- a/test-suites.json +++ b/test-suites.json @@ -1,7 +1,7 @@ [ { "suite": "artifactory", "node": true }, { "suite": "artifactoryProject", "node": true }, - { "suite": "access", "node": true, "skip_tests": "TestRefreshableAccessTokens|TestAccessTokenCreate|TestAccessTokenVerify" }, + { "suite": "access", "node": true, "skip_tests": "TestRefreshableAccessTokens|TestAccessTokenCreate" }, { "suite": "npm", "node": true, "npm_auth": true }, { "suite": "pnpm", "node": true, "pnpm": true }, { "suite": "maven", "java": "17", "maven": true }, From db467f3fa601986f22a00be58d217a0e97fce27b Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 23 Nov 2026 12:22:29 +0200 Subject: [PATCH 07/30] RTECO-2746 - Listing the Connect and roles token types in the help Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index df41b2670..b545f4b6b 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -16,7 +16,7 @@ func GetAIDescription() string { When to use: - Checking whether a token is still valid before using it in CI. -- Finding out what kind of token you were given (identity, admin, groups or scoped). +- Finding out what kind of token you were given (identity, admin, groups, roles, scoped or Connect). - Debugging authentication failures caused by an expired, revoked or foreign token. Prerequisites: @@ -33,7 +33,7 @@ Gotchas: - JSON input is read for its access_token value. - Only configured servers can be used. There's no --insecure-tls: trust a private CA by adding it to ~/.jfrog/security/certs. http:// servers work, but print a warning. - Reference tokens can't be verified; verify the JWT access token instead. -- Internal tokens are reported as Internal Token. +- Internal tokens are reported as Internal Token, except Connect pairing and device tokens, which are reported by name. - The token is sent to the server only after its signature checks out. - The exit code is 1 when the token is invalid. The payload is printed even when the token is invalid. From 292b67921df94edada5638933e2806917a2f5bd7 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 23 Nov 2026 12:56:55 +0200 Subject: [PATCH 08/30] RTECO-2746 - Removing the token argument from access-token-verify Command-line arguments are visible to other processes and kept in shell history, so atv now rejects any argument and reads the token only from --token-file or stdin. The integration tests pass tokens through --token-file. The anonymous readiness case is removed: Access readiness answers 200 to anonymous requests, so the revoked-token case is what shows that a presented token is checked. Co-Authored-By: Claude Opus 5.5 --- access_test.go | 44 ++++++++++++++++---------------- docs/general/tokenverify/help.go | 14 ++++------ general/token/verify.go | 23 +++++++---------- general/token/verify_test.go | 34 ++++++++++++------------ main.go | 1 - 5 files changed, 53 insertions(+), 63 deletions(-) diff --git a/access_test.go b/access_test.go index 58a1dc88d..38669cd50 100644 --- a/access_test.go +++ b/access_test.go @@ -386,7 +386,7 @@ func TestAccessTokenVerify(t *testing.T) { require.NoError(t, os.WriteFile(path, []byte(content), 0o600)) return path } - verify := func(t *testing.T, secret string, args ...string) (atvOutput, error) { + 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 { @@ -398,6 +398,9 @@ func TestAccessTokenVerify(t *testing.T) { } 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) @@ -409,77 +412,74 @@ func TestAccessTokenVerify(t *testing.T) { assert.Contains(t, result.Error, reason) } - t.Run("identity token as argument", func(t *testing.T) { + t.Run("identity token", func(t *testing.T) { created, _ := mint(t) - result, err := verify(t, created.AccessToken, created.AccessToken) + 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 := verify(t, created.AccessToken, "--token-file="+writeFile(t, created.AccessToken+"\n")) + 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 := verify(t, created.AccessToken, "--token-file="+writeFile(t, output)) + 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, created.AccessToken) + 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, created.AccessToken) + 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, created.AccessToken) + 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, created.AccessToken) + 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, created.ReferenceToken) + result, err := verify(t, created.ReferenceToken) assertInvalid(t, result, err, "not a JWT access token") }) t.Run("revoked token", func(t *testing.T) { created, _ := mintWithoutCleanup(t) revokeToken(t, created.TokenId) - result, err := verify(t, created.AccessToken, created.AccessToken) + result, err := verify(t, created.AccessToken) assertInvalid(t, result, err, "token rejected by Access server: status 40") }) - t.Run("readiness rejects anonymous requests", func(t *testing.T) { - client, err := httpclient.ClientBuilder().Build() - require.NoError(t, err) - resp, _, _, err := client.SendGet(*tests.JfrogUrl+"access/api/v1/system/readiness", false, httputils.HttpClientDetails{}, "") - require.NoError(t, err) - assert.Contains(t, []int{http.StatusUnauthorized, http.StatusForbidden}, resp.StatusCode, - "a valid verdict relies on the readiness endpoint rejecting requests it can't authenticate") - }) 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, tampered) + 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, forged) + 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, created.AccessToken, "--server-id=nope") + _, err := verify(t, created.AccessToken, "--server-id=nope") assert.ErrorContains(t, err, "nope") }) } diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index b545f4b6b..4e08f36b5 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -1,16 +1,11 @@ package tokenverify -var Usage = []string{"atv ", "atv --token-file=", "atv"} +var Usage = []string{"atv", "atv --token-file="} func GetDescription() string { return `Verifies a JFrog access token: checks its format and signature, checks that it has not expired, asks the configured JFrog server whether it is still accepted, and reports its type.` } -func GetArguments() string { - return ` token - [Optional] The access token to verify, or the JSON output of 'jf atc'. If neither this argument nor --token-file is set, the token is read from stdin.` -} - func GetAIDescription() string { return `Verify a JFrog Platform access token and report what kind of token it is. The token's signature is checked against the configured server's root certificate, its claims and expiry are validated, and the server's Access readiness endpoint is asked whether it still accepts the token. @@ -23,13 +18,14 @@ 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 "$TOKEN" # verify a token passed as an argument + $ jf atv # paste the token at the hidden prompt $ jf atc | jf atv # verify a freshly minted token $ jf atv --token-file=token.txt # read the token from a file $ jf atv --token-file=token.txt --format=json | jq .types Gotchas: -- With no argument and no --token-file, the token is read from stdin. In a terminal, it prompts and waits. +- 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. - JSON input is read for its access_token value. - Only configured servers can be used. There's no --insecure-tls: trust a private CA by adding it to ~/.jfrog/security/certs. http:// servers work, but print a warning. - Reference tokens can't be verified; verify the JWT access token instead. @@ -41,7 +37,7 @@ Related: jf atc, jf eot QA: Q: How do I check whether a JFrog access token is still valid? -A: jf atv +A: Run jf atv and paste the token at the prompt, or use jf atv --token-file= Q: How do I verify the token that jf atc just created and get JSON output? A: jf atc | jf atv --format=json diff --git a/general/token/verify.go b/general/token/verify.go index 49db9659c..06a07547b 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -28,16 +28,17 @@ import ( ) const ( - stdinPrompt = "Reading the access token from stdin. Paste it and press Enter (input is hidden): " - maxTokenInput = 64 * 1024 - utf8Bom = "\xef\xbb\xbf" + stdinPrompt = "Reading the access token from stdin. Paste it and press Enter (input is hidden): " + maxTokenInput = 64 * 1024 + utf8Bom = "\xef\xbb\xbf" + tokenArgumentError = "the token can't be passed as an argument, because arguments are visible to other processes and kept in shell history. Pass it with --token-file= or on stdin" ) var orderedClaims = []string{"jti", "sub", "aud", "scp", "iss", "iat", "exp"} func AccessTokenVerifyCmd(c *cli.Context) error { - if c.NArg() > 1 { - return cliutils.WrongNumberOfArgumentsHandler(c) + if c.NArg() > 0 { + return errorutils.CheckErrorf(tokenArgumentError) } outputFormat, err := commonCliUtils.GetOutputFormat(c, coreformat.Table) if err != nil { @@ -54,7 +55,7 @@ func AccessTokenVerifyCmd(c *cli.Context) error { if term.IsTerminal(int(os.Stdin.Fd())) { readTerminal = readHiddenLine } - raw, err := readTokenInput(c.Args(), c.String(cliutils.TokenFile), c.IsSet(cliutils.TokenFile), os.Stdin, readTerminal) + raw, err := readTokenInput(c.String(cliutils.TokenFile), c.IsSet(cliutils.TokenFile), os.Stdin, readTerminal) if err != nil { return err } @@ -87,14 +88,8 @@ func verifyServerDetails(serverIdFlag string) (*coreConfig.ServerDetails, error) return commands.GetConfig(serverId, true) } -func readTokenInput(args []string, tokenFile string, tokenFileSet bool, stdin io.Reader, readTerminal func(prompt string) (string, error)) (string, error) { +func readTokenInput(tokenFile string, tokenFileSet bool, stdin io.Reader, readTerminal func(prompt string) (string, error)) (string, error) { switch { - case len(args) > 0 && tokenFileSet: - return "", errorutils.CheckErrorf("provide the token either as an argument or with --token-file, not both") - case len(args) > 0 && strings.TrimSpace(args[0]) == "": - return "", errorutils.CheckErrorf("no token provided: the token argument is empty") - case len(args) > 0: - return args[0], nil case tokenFileSet && strings.TrimSpace(tokenFile) == "": return "", errorutils.CheckErrorf("no token provided: the --token-file path is empty") case tokenFileSet: @@ -160,7 +155,7 @@ func extractToken(raw string) (string, error) { tokenValue = stripTokenDecorations(input) } if tokenValue == "" { - return "", errorutils.CheckErrorf("no token provided: pass it as an argument, with --token-file=, or on stdin") + return "", errorutils.CheckErrorf("no token provided: pass it with --token-file= or on stdin") } if strings.ContainsAny(tokenValue, " \t\r\n") { return "", errorutils.CheckErrorf("the token input contains more than one value; expected a single token") diff --git a/general/token/verify_test.go b/general/token/verify_test.go index 489a03779..ab9f462cd 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "errors" + "flag" "io" "os" "path/filepath" @@ -18,6 +19,7 @@ import ( "github.com/jfrog/jfrog-client-go/utils/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/urfave/cli" ) type untouchedReader struct{ t *testing.T } @@ -67,26 +69,19 @@ func TestReadTokenInput(t *testing.T) { tokenFile := filepath.Join(dir, "token.txt") require.NoError(t, os.WriteFile(tokenFile, []byte("x\n"), 0o600)) - raw, err := readTokenInput([]string{"a.b.c"}, "", false, untouchedReader{t}, failTerminal) - require.NoError(t, err) - assert.Equal(t, "a.b.c", raw) - - raw, err = readTokenInput(nil, tokenFile, true, untouchedReader{t}, failTerminal) + raw, err := readTokenInput(tokenFile, true, untouchedReader{t}, failTerminal) require.NoError(t, err) assert.Equal(t, "x\n", raw) - _, err = readTokenInput([]string{"a.b.c"}, tokenFile, true, untouchedReader{t}, failTerminal) - assert.EqualError(t, err, "provide the token either as an argument or with --token-file, not both") - - _, err = readTokenInput(nil, "missing.txt", true, untouchedReader{t}, failTerminal) + _, err = readTokenInput("missing.txt", true, untouchedReader{t}, failTerminal) assert.ErrorContains(t, err, "failed to read token file 'missing.txt'") - raw, err = readTokenInput(nil, "", false, strings.NewReader("a.b.c\n"), nil) + raw, err = readTokenInput("", false, strings.NewReader("a.b.c\n"), nil) require.NoError(t, err) assert.Equal(t, "a.b.c\n", raw) var gotPrompt string - raw, err = readTokenInput(nil, "", false, untouchedReader{t}, func(prompt string) (string, error) { + raw, err = readTokenInput("", false, untouchedReader{t}, func(prompt string) (string, error) { gotPrompt = prompt return "a.b.c", nil }) @@ -94,17 +89,22 @@ func TestReadTokenInput(t *testing.T) { assert.Equal(t, "a.b.c", raw) assert.Equal(t, stdinPrompt, gotPrompt) - _, err = readTokenInput(nil, "", false, strings.NewReader(strings.Repeat("x", 64*1024+1)), nil) + _, err = readTokenInput("", false, strings.NewReader(strings.Repeat("x", 64*1024+1)), nil) assert.EqualError(t, err, "the token input is larger than 64 KiB") - for _, args := range [][]string{{""}, {" "}} { - _, err = readTokenInput(args, "", false, untouchedReader{t}, failTerminal) - assert.EqualError(t, err, "no token provided: the token argument is empty") - } - _, err = readTokenInput(nil, "", true, untouchedReader{t}, failTerminal) + _, err = readTokenInput("", true, untouchedReader{t}, failTerminal) assert.EqualError(t, err, "no token provided: the --token-file path is empty") } +func TestAccessTokenVerifyCmd_RejectsTokenArgument(t *testing.T) { + for _, args := range [][]string{{"a.b.c"}, {""}, {"a.b.c", "d.e.f"}} { + set := flag.NewFlagSet("atv", flag.ContinueOnError) + require.NoError(t, set.Parse(args)) + err := AccessTokenVerifyCmd(cli.NewContext(nil, set, nil)) + assert.EqualError(t, err, tokenArgumentError, args) + } +} + func TestVerifyServerDetails(t *testing.T) { t.Setenv(coreutils.HomeDir, t.TempDir()) t.Setenv(coreutils.ServerID, "") diff --git a/main.go b/main.go index 854d3e349..4b09d73e0 100644 --- a/main.go +++ b/main.go @@ -391,7 +391,6 @@ func getCommands() ([]cli.Command, error) { Flags: cliutils.GetCommandFlags(cliutils.AccessTokenVerify), Usage: corecommon.ResolveDescription(tokenVerifyDocs.GetDescription(), tokenVerifyDocs.GetAIDescription()), HelpName: corecommon.CreateUsage("atv", corecommon.ResolveDescription(tokenVerifyDocs.GetDescription(), tokenVerifyDocs.GetAIDescription()), tokenVerifyDocs.Usage), - UsageText: tokenVerifyDocs.GetArguments(), ArgsUsage: common.CreateEnvVars(), BashComplete: corecommon.CreateBashCompletionFunc(), Category: otherCategory, From eaf7464605a2025d8cd82975438642571603290d Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 23 Nov 2026 13:06:55 +0200 Subject: [PATCH 09/30] RTECO-2746 - Showing the token format and verifying reference tokens The output now starts with the token's format, JWT or Reference, and JSON output has a format field. For a reference token, the table lists the token details the server returned, with its epoch fields as dates. The help describes the tokens/me check and reference tokens, and the integration tests verify a reference token, a revoked reference token and a value that isn't a token. Co-Authored-By: Claude Opus 5.5 --- access_test.go | 19 ++++++++++++- docs/general/tokenverify/help.go | 13 +++++---- general/token/verify.go | 49 ++++++++++++++++++-------------- general/token/verify_test.go | 40 ++++++++++++++++++++++++-- 4 files changed, 92 insertions(+), 29 deletions(-) diff --git a/access_test.go b/access_test.go index 38669cd50..9b5d57627 100644 --- a/access_test.go +++ b/access_test.go @@ -356,6 +356,7 @@ func TestAccessTokenCreate(t *testing.T) { type atvOutput struct { Valid bool `json:"valid"` Error string `json:"error"` + Format string `json:"format"` Payload map[string]interface{} `json:"payload"` Types []string `json:"types"` } @@ -404,6 +405,7 @@ func TestAccessTokenVerify(t *testing.T) { assertValid := func(t *testing.T, result atvOutput, err error, types ...string) { require.NoError(t, err) assert.True(t, result.Valid) + assert.Equal(t, "JWT", result.Format) assert.Equal(t, types, result.Types) } assertInvalid := func(t *testing.T, result atvOutput, err error, reason string) { @@ -452,7 +454,22 @@ func TestAccessTokenVerify(t *testing.T) { created, _ := mint(t, "--reference") require.NotEmpty(t, created.ReferenceToken) result, err := verify(t, created.ReferenceToken) - assertInvalid(t, result, err, "not a JWT access token") + 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, "didn't accept it as a reference token") + assert.Empty(t, result.Format) + }) + t.Run("value that isn't a token", func(t *testing.T) { + result, err := verify(t, "notATokenValue") + assertInvalid(t, result, err, "didn't accept it as a reference token") }) t.Run("revoked token", func(t *testing.T) { created, _ := mintWithoutCleanup(t) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 4e08f36b5..e0203c9c9 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -3,15 +3,15 @@ package tokenverify var Usage = []string{"atv", "atv --token-file="} func GetDescription() string { - return `Verifies a JFrog access token: checks its format and signature, checks that it has not expired, asks the configured JFrog server whether it is still accepted, and reports its type.` + 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.` } func GetAIDescription() string { - return `Verify a JFrog Platform access token and report what kind of token it is. The token's signature is checked against the configured server's root certificate, its claims and expiry are validated, and the server's Access readiness endpoint is asked whether it still accepts the token. + 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's GET /access/api/v1/tokens/me endpoint is then called with the token, and only a token the server accepts is valid. A value that isn't a JWT is sent to that endpoint as a possible reference token, and its details come from the server. When to use: - Checking whether a token is still valid before using it in CI. -- Finding out what kind of token you were given (identity, admin, groups, roles, scoped or Connect). +- Finding out what kind of token you were given: a JWT or a reference token, and its type (identity, admin, groups, roles, scoped or Connect). - Debugging authentication failures caused by an expired, revoked or foreign token. Prerequisites: @@ -20,6 +20,7 @@ Prerequisites: 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 .types @@ -28,9 +29,11 @@ Gotchas: - Without --token-file, the token is read from stdin. In a terminal, it prompts and waits without echoing the input. - JSON input is read for its access_token value. - Only configured servers can be used. There's no --insecure-tls: trust a private CA by adding it to ~/.jfrog/security/certs. http:// servers work, but print a warning. -- Reference tokens can't be verified; verify the JWT access token instead. +- A value that isn't a JWT is treated as a reference token and sent to the server as is. If the server doesn't accept it, it's reported as invalid. +- JSON input is read for its access_token value, so to verify the reference token from jf atc --reference output, extract reference_token first. - Internal tokens are reported as Internal Token, except Connect pairing and device tokens, which are reported by name. -- The token is sent to the server only after its signature checks out. +- A JWT is sent to the server only after its signature checks out. +- --format=json output has a format field: JWT or Reference. For a reference token, the payload is the token details the server returned. - The exit code is 1 when the token is invalid. The payload is printed even when the token is invalid. Related: jf atc, jf eot diff --git a/general/token/verify.go b/general/token/verify.go index 06a07547b..fd778bc2c 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "os" + "slices" "sort" "strconv" "strings" @@ -34,7 +35,11 @@ const ( tokenArgumentError = "the token can't be passed as an argument, because arguments are visible to other processes and kept in shell history. Pass it with --token-file= or on stdin" ) -var orderedClaims = []string{"jti", "sub", "aud", "scp", "iss", "iat", "exp"} +var ( + orderedClaims = []string{"jti", "sub", "aud", "scp", "iss", "iat", "exp"} + orderedTokenDetails = []string{"token_id", "subject", "scope", "issuer", "issued_at", "expiry"} + epochFields = map[string]bool{"iat": true, "exp": true, "issued_at": true, "expiry": true, "last_used": true} +) func AccessTokenVerifyCmd(c *cli.Context) error { if c.NArg() > 0 { @@ -226,9 +231,12 @@ func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) erro if result == nil || result.Payload == nil { return nil } + if result.Format != "" { + _, _ = fmt.Fprintf(w, "FORMAT\n%s\n\n", result.Format) + } tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) _, _ = fmt.Fprintln(tw, "FIELD\tVALUE") - for _, row := range payloadRows(result.Payload) { + for _, row := range payloadRows(result.Payload, result.Format) { _, _ = fmt.Fprintf(tw, "%s\t%s\n", escapeControlCharacters(row[0]), escapeControlCharacters(row[1])) } if err := tw.Flush(); err != nil { @@ -244,25 +252,26 @@ func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) erro return nil } -func payloadRows(payload map[string]interface{}) [][2]string { +func payloadRows(payload map[string]interface{}, format generic.TokenFormat) [][2]string { + ordered := orderedClaims + if format == generic.TokenFormatReference { + ordered = orderedTokenDetails + } var rows [][2]string - for _, key := range orderedClaims { + for _, key := range ordered { value, ok := payload[key] switch { case key == "exp" && !ok: rows = append(rows, [2]string{key, "(no expiry)"}) - case !ok: - case key == "iat" || key == "exp": - rows = append(rows, [2]string{key, formatEpoch(value)}) - default: - rows = append(rows, [2]string{key, formatClaim(value)}) + case ok: + rows = append(rows, [2]string{key, formatValue(key, value)}) } } for _, key := range sortedKeys(payload) { - if key == "ext" || isOrderedClaim(key) { + if key == "ext" || slices.Contains(ordered, key) { continue } - rows = append(rows, [2]string{key, formatClaim(payload[key])}) + rows = append(rows, [2]string{key, formatValue(key, payload[key])}) } if ext, ok := payload["ext"].(map[string]interface{}); ok { for _, key := range sortedKeys(ext) { @@ -286,9 +295,16 @@ func escapeControlCharacters(s string) string { return b.String() } +func formatValue(key string, value interface{}) string { + if epochFields[key] { + return formatEpoch(value) + } + return formatClaim(value) +} + func formatEpoch(value interface{}) string { epoch, err := strconv.ParseInt(fmt.Sprint(value), 10, 64) - if err != nil { + if err != nil || epoch <= 0 { return formatClaim(value) } return fmt.Sprintf("%s (epoch: %d)", time.Unix(epoch, 0).UTC().Format("2006-01-02 15:04:05 UTC"), epoch) @@ -311,15 +327,6 @@ func formatClaim(value interface{}) string { return fmt.Sprint(value) } -func isOrderedClaim(key string) bool { - for _, claim := range orderedClaims { - if claim == key { - return true - } - } - return false -} - func sortedKeys(m map[string]interface{}) []string { keys := make([]string, 0, len(m)) for key := range m { diff --git a/general/token/verify_test.go b/general/token/verify_test.go index ab9f462cd..bee702c31 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -141,7 +141,8 @@ func TestAccessTokenVerifyFlags(t *testing.T) { func sampleVerifyResult(valid bool) *generic.AccessTokenVerifyResult { return &generic.AccessTokenVerifyResult{ - Valid: valid, + Valid: valid, + Format: generic.TokenFormatJWT, Payload: map[string]interface{}{ "jti": "id-1", "sub": "jfac@01h/users/alice", @@ -159,11 +160,44 @@ func sampleVerifyResult(valid bool) *generic.AccessTokenVerifyResult { func TestPrintVerifyResult_Table_Valid(t *testing.T) { var buf bytes.Buffer require.NoError(t, printVerifyResult(sampleVerifyResult(true), coreformat.Table, &buf)) - for _, want := range []string{"FIELD", "sub", "UTC (epoch: 1700000000)", "ext.revocable", "TYPE", "Identity Token"} { + assert.True(t, strings.HasPrefix(buf.String(), "FORMAT\nJWT\n\nFIELD"), buf.String()) + for _, want := range []string{"sub", "UTC (epoch: 1700000000)", "ext.revocable", "TYPE", "Identity Token"} { assert.Contains(t, buf.String(), want) } } +func TestPrintVerifyResult_Table_ReferenceToken(t *testing.T) { + result := &generic.AccessTokenVerifyResult{ + Valid: true, + Format: generic.TokenFormatReference, + Payload: map[string]interface{}{ + "token_id": "id-1", + "subject": "jfac@01h/users/alice", + "scope": "applied-permissions/user", + "issuer": "jfac@01h", + "issued_at": json.Number("1700000000"), + "expiry": json.Number("0"), + "last_used": json.Number("1700000100"), + "refreshable": false, + }, + Types: []generic.TokenType{generic.TokenTypeIdentity}, + } + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + out := buf.String() + assert.True(t, strings.HasPrefix(out, "FORMAT\nReference\n\nFIELD"), out) + var keys []string + for _, line := range strings.Split(out, "\n")[4:12] { + keys = append(keys, strings.Fields(line)[0]) + } + assert.Equal(t, []string{"token_id", "subject", "scope", "issuer", "issued_at", "expiry", "last_used", "refreshable"}, keys) + assert.Contains(t, out, "2023-11-14 22:13:20 UTC (epoch: 1700000000)") + assert.Contains(t, out, "UTC (epoch: 1700000100)") + assert.Regexp(t, `expiry\s+0\n`, out) + assert.NotContains(t, out, "(no expiry)") + assert.Contains(t, out, "TYPE\nIdentity Token") +} + func TestPrintVerifyResult_Table_NoExpiry(t *testing.T) { result := sampleVerifyResult(true) delete(result.Payload, "exp") @@ -198,11 +232,13 @@ func TestPrintVerifyResult_JSON(t *testing.T) { require.NoError(t, printVerifyResult(sampleVerifyResult(true), coreformat.Json, &buf)) var out struct { Valid bool `json:"valid"` + Format string `json:"format"` Types []string `json:"types"` Payload map[string]interface{} `json:"payload"` } require.NoError(t, json.Unmarshal(buf.Bytes(), &out)) assert.True(t, out.Valid) + assert.Equal(t, "JWT", out.Format) assert.Equal(t, []string{"Identity Token"}, out.Types) assert.IsType(t, map[string]interface{}{}, out.Payload["ext"]) } From 83c9c012fca12a279110973eac09fdfa0748f2d3 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 23 Nov 2026 15:18:59 +0200 Subject: [PATCH 10/30] RTECO-2746 - Describing scope-based token types in the atv help Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index e0203c9c9..7cef3dc2f 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -11,7 +11,7 @@ func GetAIDescription() string { 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 type (identity, admin, groups, roles, scoped or Connect). +- 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 or Connect). - Debugging authentication failures caused by an expired, revoked or foreign token. Prerequisites: @@ -31,7 +31,8 @@ Gotchas: - Only configured servers can be used. There's no --insecure-tls: trust a private CA by adding it to ~/.jfrog/security/certs. http:// servers work, but print a warning. - A value that isn't a JWT is treated as a reference token and sent to the server as is. If the server doesn't accept it, it's reported as invalid. - JSON input is read for its access_token value, so to verify the reference token from jf atc --reference output, extract reference_token first. -- Internal tokens are reported as Internal Token, except Connect pairing and device tokens, which are reported by name. +- 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 is internal when it has a scope starting with internal:. Connect pairing and device scopes are reported by name, and every other internal: scope as Internal Token, next to the token's other types. - A JWT is sent to the server only after its signature checks out. - --format=json output has a format field: JWT or Reference. For a reference token, the payload is the token details the server returned. - The exit code is 1 when the token is invalid. The payload is printed even when the token is invalid. From 1f9b89737cc47365b80cd8d9a45b52087cca3691 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 23 Nov 2026 16:14:42 +0200 Subject: [PATCH 11/30] RTECO-2746 - Discarding leftover pasted input at the atv prompt and fixing input, output and help gaps - The hidden prompt reads its own line without x/term's 4096-character cap, discards whatever is left in the terminal so it can't reach the shell, and rejects multi-line pastes. - Git Bash and other Cygwin terminals, which can't hide input, get an error instead of an echoed prompt. - UTF-16 token files (Windows PowerShell 5.1 redirection) are decoded. - A non-object ext claim is shown in the table. - The help and --token-file text match the current behaviour. - tokenUnderTest is renamed to tokenUnderInvestigation, and non-critical comments are removed. Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 5 +- general/token/prompt.go | 98 ++++++++++++++++++++++++++++++ general/token/prompt_other.go | 7 +++ general/token/prompt_test.go | 59 ++++++++++++++++++ general/token/prompt_unix.go | 27 ++++++++ general/token/prompt_unix_bsd.go | 10 +++ general/token/prompt_unix_other.go | 10 +++ general/token/prompt_windows.go | 15 +++++ general/token/verify.go | 73 +++++++++++----------- general/token/verify_test.go | 28 +++++++++ utils/cliutils/commandsflags.go | 2 +- 11 files changed, 291 insertions(+), 43 deletions(-) create mode 100644 general/token/prompt.go create mode 100644 general/token/prompt_other.go create mode 100644 general/token/prompt_test.go create mode 100644 general/token/prompt_unix.go create mode 100644 general/token/prompt_unix_bsd.go create mode 100644 general/token/prompt_unix_other.go create mode 100644 general/token/prompt_windows.go diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 7cef3dc2f..e9ad92a70 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -26,10 +26,9 @@ Common patterns: 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. -- JSON input is read for its access_token value. +- 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. http:// servers work, but print a warning. -- A value that isn't a JWT is treated as a reference token and sent to the server as is. If the server doesn't accept it, it's reported as invalid. +- 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. If the server doesn't accept it, it's reported as invalid. 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 is internal when it has a scope starting with internal:. Connect pairing and device scopes are reported by name, and every other internal: scope as Internal Token, next to the token's other types. diff --git a/general/token/prompt.go b/general/token/prompt.go new file mode 100644 index 000000000..cc7dc83f8 --- /dev/null +++ b/general/token/prompt.go @@ -0,0 +1,98 @@ +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= or through a pipe" + visibleTerminalError = "this terminal can't hide the token as you type it. Pass it with --token-file= 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 + } +} + +// Whatever is left in the terminal after the line would otherwise reach the shell as typed input, so it's discarded. +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] + switch { + case inSequence: + inSequence = b < 0x40 || b > 0x7e + case inEscape: + inEscape, inSequence = false, b == '[' || b == 'O' + 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) + } + } +} diff --git a/general/token/prompt_other.go b/general/token/prompt_other.go new file mode 100644 index 000000000..570346bc5 --- /dev/null +++ b/general/token/prompt_other.go @@ -0,0 +1,7 @@ +//go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !zos && !windows + +package token + +func discardPendingInput(int) string { + return "" +} diff --git a/general/token/prompt_test.go b/general/token/prompt_test.go new file mode 100644 index 000000000..f6bde367e --- /dev/null +++ b/general/token/prompt_test.go @@ -0,0 +1,59 @@ +package token + +import ( + "errors" + "strings" + "testing" + "testing/iotest" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestReadHiddenInput(t *testing.T) { + for _, tc := range []struct { + input, line, leftover string + }{ + {"a.b.c\r", "a.b.c", ""}, + {"a.b.c\r\n", "a.b.c", "\n"}, + {"a.b.c", "a.b.c", ""}, + {"{\n \"access_token\": \"a.b.c\"\n}\n", "{", " \"access_token\": \"a.b.c\"\n}\n"}, + {"a.b.x\x7fc\r", "a.b.c", ""}, + {"a.b.x\bc\r", "a.b.c", ""}, + {"wrong\x15a.b.c\r", "a.b.c", ""}, + {"a.\x1b[Db.c\x1bOA\r", "a.b.c", ""}, + {"a.b\x1b[1;5C.c\r", "a.b.c", ""}, + {"a.b\x1bx.c\r", "a.b.c", ""}, + {"a.\tb.c\r", "a.b.c", ""}, + {"ab\x04c\r", "abc", ""}, + {"\x04", "", ""}, + {"a.b.c\x03rest", "", "rest"}, + {"\u05d3\u05e0\u05d4\x7f\r", "\u05d3\u05e0", ""}, + } { + line, leftover, err := readHiddenInput(strings.NewReader(tc.input)) + require.NoError(t, err, tc.input) + assert.Equal(t, tc.line, line, tc.input) + assert.Equal(t, tc.leftover, leftover, tc.input) + } +} + +func TestReadHiddenInput_LongLineAcrossReads(t *testing.T) { + token := strings.Repeat("a", 10000) + line, leftover, err := readHiddenInput(iotest.OneByteReader(strings.NewReader(token + "\r"))) + require.NoError(t, err) + assert.Equal(t, token, line) + assert.Empty(t, leftover) +} + +func TestReadHiddenInput_SizeLimit(t *testing.T) { + line, _, err := readHiddenInput(strings.NewReader(strings.Repeat("a", maxTokenInput) + "\r")) + require.NoError(t, err) + assert.Len(t, line, maxTokenInput) + _, _, err = readHiddenInput(strings.NewReader(strings.Repeat("a", maxTokenInput+1) + "\r")) + assert.ErrorContains(t, err, "larger than 64 KiB") +} + +func TestReadHiddenInput_ReadError(t *testing.T) { + _, _, err := readHiddenInput(iotest.ErrReader(errors.New("boom"))) + assert.ErrorContains(t, err, "boom") +} diff --git a/general/token/prompt_unix.go b/general/token/prompt_unix.go new file mode 100644 index 000000000..e2a0aa20b --- /dev/null +++ b/general/token/prompt_unix.go @@ -0,0 +1,27 @@ +//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos + +package token + +import "golang.org/x/sys/unix" + +func discardPendingInput(fd int) string { + termios, err := unix.IoctlGetTermios(fd, ioctlGetTermios) + if err != nil { + return "" + } + termios.Cc[unix.VMIN] = 0 + termios.Cc[unix.VTIME] = 1 + if err = unix.IoctlSetTermios(fd, ioctlSetTermios, termios); err != nil { + return "" + } + var pending []byte + buf := make([]byte, 4096) + for len(pending) <= maxTokenInput { + n, err := unix.Read(fd, buf) + if n <= 0 || err != nil { + break + } + pending = append(pending, buf[:n]...) + } + return string(pending) +} diff --git a/general/token/prompt_unix_bsd.go b/general/token/prompt_unix_bsd.go new file mode 100644 index 000000000..da84ba4b9 --- /dev/null +++ b/general/token/prompt_unix_bsd.go @@ -0,0 +1,10 @@ +//go:build darwin || dragonfly || freebsd || netbsd || openbsd + +package token + +import "golang.org/x/sys/unix" + +const ( + ioctlGetTermios = unix.TIOCGETA + ioctlSetTermios = unix.TIOCSETA +) diff --git a/general/token/prompt_unix_other.go b/general/token/prompt_unix_other.go new file mode 100644 index 000000000..f97ce035a --- /dev/null +++ b/general/token/prompt_unix_other.go @@ -0,0 +1,10 @@ +//go:build aix || linux || solaris || zos + +package token + +import "golang.org/x/sys/unix" + +const ( + ioctlGetTermios = unix.TCGETS + ioctlSetTermios = unix.TCSETS +) diff --git a/general/token/prompt_windows.go b/general/token/prompt_windows.go new file mode 100644 index 000000000..a084f7734 --- /dev/null +++ b/general/token/prompt_windows.go @@ -0,0 +1,15 @@ +//go:build windows + +package token + +import ( + "time" + + "golang.org/x/sys/windows" +) + +func discardPendingInput(fd int) string { + time.Sleep(100 * time.Millisecond) + _ = windows.FlushConsoleInputBuffer(windows.Handle(fd)) + return "" +} diff --git a/general/token/verify.go b/general/token/verify.go index fd778bc2c..9f8fd86a9 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -1,6 +1,7 @@ package token import ( + "encoding/binary" "encoding/json" "errors" "fmt" @@ -25,14 +26,15 @@ import ( "github.com/jfrog/jfrog-client-go/utils/errorutils" "github.com/jfrog/jfrog-client-go/utils/log" "github.com/urfave/cli" - "golang.org/x/term" ) const ( - stdinPrompt = "Reading the access token from stdin. Paste it and press Enter (input is hidden): " - maxTokenInput = 64 * 1024 - utf8Bom = "\xef\xbb\xbf" - tokenArgumentError = "the token can't be passed as an argument, because arguments are visible to other processes and kept in shell history. Pass it with --token-file= or on stdin" + stdinPrompt = "Reading the access token from stdin. Paste it and press Enter (input is hidden): " + maxTokenInput = 64 * 1024 + utf8Bom = "\xef\xbb\xbf" + utf16LittleEndianBom = "\xff\xfe" + utf16BigEndianBom = "\xfe\xff" + tokenArgumentError = "the token can't be passed as an argument, because arguments are visible to other processes and kept in shell history. Pass it with --token-file= or on stdin" ) var ( @@ -56,20 +58,16 @@ func AccessTokenVerifyCmd(c *cli.Context) error { if err != nil { return err } - var readTerminal func(string) (string, error) - if term.IsTerminal(int(os.Stdin.Fd())) { - readTerminal = readHiddenLine - } - raw, err := readTokenInput(c.String(cliutils.TokenFile), c.IsSet(cliutils.TokenFile), os.Stdin, readTerminal) + raw, err := readTokenInput(c.String(cliutils.TokenFile), c.IsSet(cliutils.TokenFile), os.Stdin, terminalReader()) if err != nil { return err } - tokenUnderTest, err := extractToken(raw) + tokenUnderInvestigation, err := extractToken(raw) if err != nil { return err } - verifyCmd := generic.NewAccessTokenVerifyCommand().SetServerDetails(serverDetails).SetToken(tokenUnderTest) + verifyCmd := generic.NewAccessTokenVerifyCommand().SetServerDetails(serverDetails).SetToken(tokenUnderInvestigation) verifyErr := commands.Exec(verifyCmd) printErr := printVerifyResult(verifyCmd.Result(), outputFormat, os.Stdout) if verifyErr != nil { @@ -78,8 +76,6 @@ func AccessTokenVerifyCmd(c *cli.Context) error { return errors.Join(verifyErr, printErr) } -// The error can quote token claims and server text, so it's escaped and logged here. Returning it would let the -// generic error handlers print it raw, or parse it as an HTTP error and print a second JSON object. func verifyFailure(verifyErr error) error { log.Error(escapeControlCharacters(verifyErr.Error())) return coreutils.CliError{ExitCode: coreutils.ExitCodeError} @@ -122,28 +118,8 @@ func readLimited(r io.Reader) (string, error) { return string(data), nil } -// Raw mode avoids the 1,024-byte line limit that canonical terminal mode has on macOS. -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) }() - terminal := term.NewTerminal(struct { - io.Reader - io.Writer - }{os.Stdin, os.Stderr}, "") - line, err := terminal.ReadPassword(prompt) - if errors.Is(err, io.EOF) { - _, _ = fmt.Fprint(os.Stderr, "\r\n") - return "", nil - } - return line, errorutils.CheckError(err) -} - func extractToken(raw string) (string, error) { - input := strings.TrimSpace(strings.TrimPrefix(raw, utf8Bom)) + input := strings.TrimSpace(strings.TrimPrefix(decodeUTF16(raw), utf8Bom)) var tokenValue string if strings.HasPrefix(input, "{") { var atcOutput struct { @@ -168,6 +144,24 @@ func extractToken(raw string) (string, error) { return tokenValue, nil } +func decodeUTF16(raw string) string { + var order binary.ByteOrder + switch { + case strings.HasPrefix(raw, utf16LittleEndianBom): + order = binary.LittleEndian + case strings.HasPrefix(raw, utf16BigEndianBom): + order = binary.BigEndian + default: + return raw + } + data := raw[2:] + units := make([]uint16, 0, len(data)/2) + for i := 0; i+1 < len(data); i += 2 { + units = append(units, order.Uint16([]byte(data[i:i+2]))) + } + return string(utf16.Decode(units)) +} + func stripTokenDecorations(input string) string { if len(input) >= 2 && strings.HasPrefix(input, `"`) && strings.HasSuffix(input, `"`) { input = input[1 : len(input)-1] @@ -186,8 +180,6 @@ func jsonErrorWithoutInput(err error) string { return "unexpected structure" } -// json.Marshal leaves DEL, C1 controls and Unicode format characters (such as bidi overrides) raw. As \u escapes they -// can't affect the terminal, and the output is still valid JSON. func escapeJSONControlCharacters(data string) string { var b strings.Builder for _, r := range data { @@ -273,15 +265,18 @@ func payloadRows(payload map[string]interface{}, format generic.TokenFormat) [][ } rows = append(rows, [2]string{key, formatValue(key, payload[key])}) } - if ext, ok := payload["ext"].(map[string]interface{}); ok { + switch ext := payload["ext"].(type) { + case nil: + case map[string]interface{}: for _, key := range sortedKeys(ext) { rows = append(rows, [2]string{"ext." + key, formatClaim(ext[key])}) } + default: + rows = append(rows, [2]string{"ext", formatClaim(ext)}) } return rows } -// The payload is printed even when verification fails, so its text is untrusted and must not reach the terminal raw. func escapeControlCharacters(s string) string { var b strings.Builder for _, r := range s { diff --git a/general/token/verify_test.go b/general/token/verify_test.go index bee702c31..61365108b 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -2,6 +2,7 @@ package token import ( "bytes" + "encoding/binary" "encoding/json" "errors" "flag" @@ -10,6 +11,7 @@ import ( "path/filepath" "strings" "testing" + "unicode/utf16" coreformat "github.com/jfrog/jfrog-cli-core/v2/common/format" generic "github.com/jfrog/jfrog-cli-core/v2/general/token" @@ -41,6 +43,15 @@ func TestExtractToken(t *testing.T) { assert.Equal(t, "a.b.c", token, raw) } + for _, raw := range []string{ + utf16LittleEndianBom + encodeUTF16(strings.ReplaceAll(atcOutput, "\n", "\r\n"), binary.LittleEndian), + utf16BigEndianBom + encodeUTF16("a.b.c\r\n", binary.BigEndian), + } { + token, err := extractToken(raw) + require.NoError(t, err) + assert.Equal(t, "a.b.c", token) + } + for _, tc := range []struct { raw string wantErr string @@ -60,6 +71,15 @@ func TestExtractToken(t *testing.T) { } } +func encodeUTF16(s string, order binary.ByteOrder) string { + units := utf16.Encode([]rune(s)) + data := make([]byte, 2*len(units)) + for i, unit := range units { + order.PutUint16(data[2*i:], unit) + } + return string(data) +} + func TestReadTokenInput(t *testing.T) { failTerminal := func(string) (string, error) { t.Error("terminal was read") @@ -166,6 +186,14 @@ func TestPrintVerifyResult_Table_Valid(t *testing.T) { } } +func TestPrintVerifyResult_Table_ExtThatIsNotAnObject(t *testing.T) { + result := sampleVerifyResult(false) + result.Payload["ext"] = "not-json" + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + assert.Regexp(t, `\next\s+not-json\n`, buf.String()) +} + func TestPrintVerifyResult_Table_ReferenceToken(t *testing.T) { result := &generic.AccessTokenVerifyResult{ Valid: true, diff --git a/utils/cliutils/commandsflags.go b/utils/cliutils/commandsflags.go index 08e1611ec..88be4f4f4 100644 --- a/utils/cliutils/commandsflags.go +++ b/utils/cliutils/commandsflags.go @@ -721,7 +721,7 @@ var flagsMap = map[string]cli.Flag{ }, TokenFile: cli.StringFlag{ Name: TokenFile, - Usage: "[Optional] Path to a file that holds the token to verify, or the JSON output of jf atc. If neither this nor the argument is set, the token is read from stdin.` `", + Usage: "[Optional] Path to a file that holds the token to verify, or the JSON output of jf atc. Without it, the token is read from stdin.` `", }, exchangeOidcTokenFormat: cli.StringFlag{ Name: Format, From fde5f397f9ff800ce51f4faf35ec3f0b5c25ea43 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 11:59:31 +0200 Subject: [PATCH 12/30] RTECO-2746 - Showing atv results in colored tables with a verdict line Co-Authored-By: Claude Opus 5.5 --- general/token/verify.go | 172 +++++++++++++++++++++++++++++------ general/token/verify_test.go | 106 +++++++++++++++++---- 2 files changed, 228 insertions(+), 50 deletions(-) diff --git a/general/token/verify.go b/general/token/verify.go index 9f8fd86a9..5a1be42a9 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -11,11 +11,11 @@ import ( "sort" "strconv" "strings" - "text/tabwriter" "time" "unicode" "unicode/utf16" + "github.com/jedib0t/go-pretty/v6/table" commonCliUtils "github.com/jfrog/jfrog-cli-core/v2/common/cliutils" "github.com/jfrog/jfrog-cli-core/v2/common/commands" coreformat "github.com/jfrog/jfrog-cli-core/v2/common/format" @@ -34,13 +34,18 @@ const ( utf8Bom = "\xef\xbb\xbf" utf16LittleEndianBom = "\xff\xfe" utf16BigEndianBom = "\xfe\xff" + maxValueWidth = 80 + expiryWarningWindow = 7 * 24 * time.Hour tokenArgumentError = "the token can't be passed as an argument, because arguments are visible to other processes and kept in shell history. Pass it with --token-file= or on stdin" ) var ( orderedClaims = []string{"jti", "sub", "aud", "scp", "iss", "iat", "exp"} orderedTokenDetails = []string{"token_id", "subject", "scope", "issuer", "issued_at", "expiry"} - epochFields = map[string]bool{"iat": true, "exp": true, "issued_at": true, "expiry": true, "last_used": true} + epochFields = map[string]bool{"iat": true, "issued_at": true, "last_used": true} + expiryFields = map[string]bool{"exp": true, "expiry": true} + internalTypes = map[generic.TokenType]bool{generic.TokenTypeInternal: true, generic.TokenTypeConnectPairing: true, generic.TokenTypeConnectDevice: true} + now = time.Now ) func AccessTokenVerifyCmd(c *cli.Context) error { @@ -220,63 +225,113 @@ func printVerifyResult(result *generic.AccessTokenVerifyResult, outputFormat cor } func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) error { - if result == nil || result.Payload == nil { + if result == nil { return nil } - if result.Format != "" { - _, _ = fmt.Fprintf(w, "FORMAT\n%s\n\n", result.Format) + sections := []string{verdictLine(result)} + if result.Payload != nil { + fields := newVerifyTable("FIELD", "VALUE") + fields.SetColumnConfigs([]table.ColumnConfig{{Number: 2, WidthMax: maxValueWidth}}) + for _, row := range payloadRows(result.Payload, result.Format) { + fields.AppendRow(table.Row{row.key, row.value}) + } + sections = append(sections, fields.Render()) } - tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) - _, _ = fmt.Fprintln(tw, "FIELD\tVALUE") - for _, row := range payloadRows(result.Payload, result.Format) { - _, _ = fmt.Fprintf(tw, "%s\t%s\n", escapeControlCharacters(row[0]), escapeControlCharacters(row[1])) + if result.Valid { + types := newVerifyTable("TOKEN TYPE", "INTERNAL") + for _, tokenType := range result.Types { + types.AppendRow(typeRow(tokenType)) + } + sections = append(sections, types.Render()) } - if err := tw.Flush(); err != nil { - return errorutils.CheckError(err) + _, err := fmt.Fprintln(w, strings.Join(sections, "\n\n")) + return errorutils.CheckError(err) +} + +func newVerifyTable(headers ...interface{}) table.Writer { + tw := table.NewWriter() + tw.SetStyle(table.StyleLight) + tw.AppendHeader(headers) + return tw +} + +func verdictLine(result *generic.AccessTokenVerifyResult) string { + subject := "token" + if result.Format == generic.TokenFormatJWT { + subject = "JWT" + } else if result.Format != "" { + subject = string(result.Format) + " token" } - if !result.Valid { - return nil + if result.Valid { + return strings.TrimSpace(coreutils.PrintBold(coreutils.PrintGreen("\u2714 Valid " + subject))) + } + line := strings.TrimSpace(coreutils.PrintBold(coreutils.PrintRed("\u2716 Invalid " + subject))) + if result.Error != "" { + line += ": " + escapeControlCharacters(result.Error) + } + return line +} + +func typeRow(tokenType generic.TokenType) table.Row { + name := string(tokenType) + if tokenType == generic.TokenTypeUnknown { + name = coreutils.PrintComment(name) } - _, _ = fmt.Fprintln(w, "\nTYPE") - for _, tokenType := range result.Types { - _, _ = fmt.Fprintln(w, tokenType) + internal := "No" + if internalTypes[tokenType] { + internal = coreutils.PrintYellow("Yes") } - return nil + return table.Row{name, internal} } -func payloadRows(payload map[string]interface{}, format generic.TokenFormat) [][2]string { +type fieldRow struct { + key, value string +} + +func payloadRows(payload map[string]interface{}, format generic.TokenFormat) []fieldRow { ordered := orderedClaims if format == generic.TokenFormatReference { ordered = orderedTokenDetails } - var rows [][2]string + var rows []fieldRow for _, key := range ordered { value, ok := payload[key] switch { case key == "exp" && !ok: - rows = append(rows, [2]string{key, "(no expiry)"}) + rows = append(rows, fieldRow{fieldName(key), formatExpiry(nil)}) case ok: - rows = append(rows, [2]string{key, formatValue(key, value)}) + rows = append(rows, fieldRow{fieldName(key), formatValue(key, value)}) } } for _, key := range sortedKeys(payload) { if key == "ext" || slices.Contains(ordered, key) { continue } - rows = append(rows, [2]string{key, formatValue(key, payload[key])}) + rows = append(rows, fieldRow{fieldName(key), formatValue(key, payload[key])}) } switch ext := payload["ext"].(type) { case nil: case map[string]interface{}: for _, key := range sortedKeys(ext) { - rows = append(rows, [2]string{"ext." + key, formatClaim(ext[key])}) + rows = append(rows, fieldRow{coreutils.PrintComment("ext.") + fieldName(key), plainValue(formatClaim(ext[key]))}) } default: - rows = append(rows, [2]string{"ext", formatClaim(ext)}) + rows = append(rows, fieldRow{fieldName("ext"), plainValue(formatClaim(ext))}) } return rows } +func fieldName(key string) string { + return coreutils.PrintBold(escapeControlCharacters(key)) +} + +func plainValue(value string) string { + if value == "" { + return coreutils.PrintComment("(empty)") + } + return escapeControlCharacters(value) +} + func escapeControlCharacters(s string) string { var b strings.Builder for _, r := range s { @@ -291,18 +346,75 @@ func escapeControlCharacters(s string) string { } func formatValue(key string, value interface{}) string { - if epochFields[key] { + switch { + case expiryFields[key]: + return formatExpiry(value) + case epochFields[key]: return formatEpoch(value) + default: + return plainValue(formatClaim(value)) } - return formatClaim(value) } -func formatEpoch(value interface{}) string { +func parseEpoch(value interface{}) (int64, bool) { epoch, err := strconv.ParseInt(fmt.Sprint(value), 10, 64) - if err != nil || epoch <= 0 { - return formatClaim(value) + return epoch, err == nil +} + +func formatEpoch(value interface{}) string { + epoch, ok := parseEpoch(value) + if !ok || epoch <= 0 { + return plainValue(formatClaim(value)) + } + return epochDate(epoch) + " " + epochNumber(epoch) +} + +func formatExpiry(value interface{}) string { + if value == nil { + return "never" + } + epoch, ok := parseEpoch(value) + switch { + case ok && epoch == 0: + return "never" + case !ok || epoch < 0: + return plainValue(formatClaim(value)) + } + left := time.Unix(epoch, 0).Sub(now()) + switch { + case left <= 0: + return coreutils.PrintRed(epochDate(epoch)) + " " + epochNumber(epoch) + " " + coreutils.PrintRed("expired") + case left < expiryWarningWindow: + return coreutils.PrintYellow(epochDate(epoch)) + " " + epochNumber(epoch) + " " + coreutils.PrintYellow("expires in "+remaining(left)) + default: + return epochDate(epoch) + " " + epochNumber(epoch) + } +} + +func epochDate(epoch int64) string { + return time.Unix(epoch, 0).UTC().Format("2006-01-02 15:04:05 UTC") +} + +func epochNumber(epoch int64) string { + return coreutils.PrintComment(fmt.Sprintf("(%d)", epoch)) +} + +func remaining(d time.Duration) string { + switch { + case d >= 24*time.Hour: + return countOf(int(d/(24*time.Hour)), "day") + case d >= time.Hour: + return countOf(int(d/time.Hour), "hour") + default: + return countOf(int(d/time.Minute), "minute") + } +} + +func countOf(n int, unit string) string { + if n == 1 { + return "1 " + unit } - return fmt.Sprintf("%s (epoch: %d)", time.Unix(epoch, 0).UTC().Format("2006-01-02 15:04:05 UTC"), epoch) + return fmt.Sprintf("%d %ss", n, unit) } func formatClaim(value interface{}) string { diff --git a/general/token/verify_test.go b/general/token/verify_test.go index 61365108b..b6ba9e196 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -9,10 +9,13 @@ import ( "io" "os" "path/filepath" + "regexp" "strings" "testing" + "time" "unicode/utf16" + "github.com/gookit/color" coreformat "github.com/jfrog/jfrog-cli-core/v2/common/format" generic "github.com/jfrog/jfrog-cli-core/v2/general/token" coreConfig "github.com/jfrog/jfrog-cli-core/v2/utils/config" @@ -180,10 +183,13 @@ func sampleVerifyResult(valid bool) *generic.AccessTokenVerifyResult { func TestPrintVerifyResult_Table_Valid(t *testing.T) { var buf bytes.Buffer require.NoError(t, printVerifyResult(sampleVerifyResult(true), coreformat.Table, &buf)) - assert.True(t, strings.HasPrefix(buf.String(), "FORMAT\nJWT\n\nFIELD"), buf.String()) - for _, want := range []string{"sub", "UTC (epoch: 1700000000)", "ext.revocable", "TYPE", "Identity Token"} { - assert.Contains(t, buf.String(), want) + out := buf.String() + assert.True(t, strings.HasPrefix(out, "Valid JWT\n\n\u250c"), out) + for _, want := range []string{"FIELD", "VALUE", "2023-11-14 22:13:20 UTC (1700000000)", "ext.revocable", "TOKEN TYPE", "INTERNAL"} { + assert.Contains(t, out, want) } + assert.Regexp(t, `\x{2502} Identity Token\s+\x{2502} No\s+\x{2502}`, out) + assert.NotContains(t, out, "\x1b") } func TestPrintVerifyResult_Table_ExtThatIsNotAnObject(t *testing.T) { @@ -191,7 +197,7 @@ func TestPrintVerifyResult_Table_ExtThatIsNotAnObject(t *testing.T) { result.Payload["ext"] = "not-json" var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) - assert.Regexp(t, `\next\s+not-json\n`, buf.String()) + assert.Regexp(t, `\x{2502} ext\s+\x{2502} not-json\s+\x{2502}`, buf.String()) } func TestPrintVerifyResult_Table_ReferenceToken(t *testing.T) { @@ -205,6 +211,7 @@ func TestPrintVerifyResult_Table_ReferenceToken(t *testing.T) { "issuer": "jfac@01h", "issued_at": json.Number("1700000000"), "expiry": json.Number("0"), + "description": "", "last_used": json.Number("1700000100"), "refreshable": false, }, @@ -213,32 +220,91 @@ func TestPrintVerifyResult_Table_ReferenceToken(t *testing.T) { var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) out := buf.String() - assert.True(t, strings.HasPrefix(out, "FORMAT\nReference\n\nFIELD"), out) + assert.True(t, strings.HasPrefix(out, "Valid Reference token\n"), out) var keys []string - for _, line := range strings.Split(out, "\n")[4:12] { - keys = append(keys, strings.Fields(line)[0]) + for _, line := range strings.Split(out, "\n") { + if fields := strings.Fields(strings.Trim(line, "\u2502 ")); len(fields) > 0 && strings.HasPrefix(line, "\u2502") { + keys = append(keys, fields[0]) + } + } + assert.Equal(t, []string{"FIELD", "token_id", "subject", "scope", "issuer", "issued_at", "expiry", "description", "last_used", "refreshable", "TOKEN", "Identity"}, keys) + assert.Contains(t, out, "2023-11-14 22:13:20 UTC (1700000000)") + assert.Regexp(t, `expiry\s+\x{2502} never\s`, out) + assert.Regexp(t, `description\s+\x{2502} \(empty\)\s`, out) +} + +func TestPrintVerifyResult_Table_Expiry(t *testing.T) { + defer func(previous func() time.Time) { now = previous }(now) + now = func() time.Time { return time.Unix(1700000000, 0) } + for _, tc := range []struct { + exp interface{} + want string + }{ + {nil, "never"}, + {json.Number("0"), "never"}, + {json.Number("1699999999"), "expired"}, + {json.Number("1700003600"), "expires in 1 hour"}, + {json.Number("1700000000"), "expired"}, + {json.Number("1700259200"), "expires in 3 days"}, + {json.Number("1800000000"), "2027-01-15 08:00:00 UTC (1800000000)"}, + {"soon", "soon"}, + } { + result := sampleVerifyResult(true) + if tc.exp == nil { + delete(result.Payload, "exp") + } else { + result.Payload["exp"] = tc.exp + } + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + assert.Regexp(t, `exp\s+\x{2502} [^\x{2502}]*`+regexp.QuoteMeta(tc.want), buf.String(), tc.exp) } - assert.Equal(t, []string{"token_id", "subject", "scope", "issuer", "issued_at", "expiry", "last_used", "refreshable"}, keys) - assert.Contains(t, out, "2023-11-14 22:13:20 UTC (epoch: 1700000000)") - assert.Contains(t, out, "UTC (epoch: 1700000100)") - assert.Regexp(t, `expiry\s+0\n`, out) - assert.NotContains(t, out, "(no expiry)") - assert.Contains(t, out, "TYPE\nIdentity Token") } -func TestPrintVerifyResult_Table_NoExpiry(t *testing.T) { +func TestPrintVerifyResult_Table_Invalid(t *testing.T) { + result := sampleVerifyResult(false) + result.Error = "token expired at 2023-11-14 23:13:20 UTC" + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + out := buf.String() + assert.True(t, strings.HasPrefix(out, "Invalid JWT: token expired at 2023-11-14 23:13:20 UTC\n"), out) + assert.Contains(t, out, "sub") + assert.NotContains(t, out, "TOKEN TYPE") +} + +func TestPrintVerifyResult_Table_InvalidWithoutPayload(t *testing.T) { + var buf bytes.Buffer + result := &generic.AccessTokenVerifyResult{Error: "failed to parse token: invalid JWT format\x1b[2J"} + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + assert.Equal(t, "Invalid token: failed to parse token: invalid JWT format\\x1b[2J\n", buf.String()) +} + +func TestPrintVerifyResult_Table_InternalTypes(t *testing.T) { result := sampleVerifyResult(true) - delete(result.Payload, "exp") + result.Types = []generic.TokenType{generic.TokenTypeConnectDevice, generic.TokenTypeInternal, generic.TokenTypeAdmin, generic.TokenTypeUnknown} var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) - assert.Contains(t, buf.String(), "(no expiry)") + out := buf.String() + for _, row := range []string{"Connect Device Token\\s+\\x{2502} Yes", "Internal Token\\s+\\x{2502} Yes", "Admin Token\\s+\\x{2502} No", "Unknown Token Type\\s+\\x{2502} No"} { + assert.Regexp(t, row, out) + } } -func TestPrintVerifyResult_Table_Invalid(t *testing.T) { +func TestPrintVerifyResult_Table_ColorsKeepEscaping(t *testing.T) { + defer log.SetIsTerminalFlagsWithCallback(true)() + color.ForceOpenColor() + defer color.RevertColorLevel() + result := sampleVerifyResult(true) + result.Payload["sub"] = "alice\x1b]0;title\x07\x1b[8m" var buf bytes.Buffer - require.NoError(t, printVerifyResult(sampleVerifyResult(false), coreformat.Table, &buf)) - assert.Contains(t, buf.String(), "sub") - assert.NotContains(t, buf.String(), "TYPE") + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + out := buf.String() + require.Contains(t, out, "\x1b[", "colors should be on") + assert.Contains(t, out, "\u2714 Valid JWT") + assert.Contains(t, out, `alice\x1b]0;title\a\x1b[8m`) + withoutColors := regexp.MustCompile("\x1b\\[[0-9;]*m").ReplaceAllString(out, "") + assert.NotContains(t, withoutColors, "\x1b") + assert.NotContains(t, out, "\x07") } func TestPrintVerifyResult_Table_EscapesControlCharacters(t *testing.T) { From 7bddd881273321f196a8ad7d68b348f6fa3bbfb2 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 12:07:31 +0200 Subject: [PATCH 13/30] RTECO-2746 - Showing token types for failed verifications and dropping the INTERNAL column Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 6 +++--- general/token/verify.go | 28 +++++++++++++++------------- general/token/verify_test.go | 15 +++++++-------- 3 files changed, 25 insertions(+), 24 deletions(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index e9ad92a70..ef0e82c05 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -7,7 +7,7 @@ func GetDescription() string { } 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's GET /access/api/v1/tokens/me endpoint is then called with the token, and only a token the server accepts is valid. A value that isn't a JWT is sent to that endpoint as a possible reference token, and its details come from the server. + 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's GET /access/api/v1/tokens/me endpoint is then called with the token, and only a token the server accepts is valid. A value without dots isn't shaped like a JWT, so it's sent to that endpoint as a possible reference token, and its details come from the server. When to use: - Checking whether a token is still valid before using it in CI. @@ -31,10 +31,10 @@ Gotchas: - 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. If the server doesn't accept it, it's reported as invalid. 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 is internal when it has a scope starting with internal:. Connect pairing and device scopes are reported by name, and every other internal: scope as Internal Token, next to the token's other types. +- A token with a scope starting with internal: has Internal Token among its types. Connect pairing and device scopes are also reported by name. - A JWT is sent to the server only after its signature checks out. - --format=json output has a format field: JWT or Reference. For a reference token, the payload is the token details the server returned. -- The exit code is 1 when the token is invalid. The payload is printed even when the token is invalid. +- The exit code is 1 when the token is invalid. The payload and the types its scopes claim are printed even when the token is invalid; the table then marks the types as unverified. Related: jf atc, jf eot diff --git a/general/token/verify.go b/general/token/verify.go index 5a1be42a9..f7f426c0c 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -44,7 +44,6 @@ var ( orderedTokenDetails = []string{"token_id", "subject", "scope", "issuer", "issued_at", "expiry"} epochFields = map[string]bool{"iat": true, "issued_at": true, "last_used": true} expiryFields = map[string]bool{"exp": true, "expiry": true} - internalTypes = map[generic.TokenType]bool{generic.TokenTypeInternal: true, generic.TokenTypeConnectPairing: true, generic.TokenTypeConnectDevice: true} now = time.Now ) @@ -237,10 +236,14 @@ func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) erro } sections = append(sections, fields.Render()) } - if result.Valid { - types := newVerifyTable("TOKEN TYPE", "INTERNAL") + if len(result.Types) > 0 { + typeHeader := "TOKEN TYPE" + if !result.Valid { + typeHeader = "TOKEN TYPE (UNVERIFIED)" + } + types := newVerifyTable(typeHeader) for _, tokenType := range result.Types { - types.AppendRow(typeRow(tokenType)) + types.AppendRow(table.Row{typeName(tokenType)}) } sections = append(sections, types.Render()) } @@ -272,16 +275,15 @@ func verdictLine(result *generic.AccessTokenVerifyResult) string { return line } -func typeRow(tokenType generic.TokenType) table.Row { - name := string(tokenType) - if tokenType == generic.TokenTypeUnknown { - name = coreutils.PrintComment(name) - } - internal := "No" - if internalTypes[tokenType] { - internal = coreutils.PrintYellow("Yes") +func typeName(tokenType generic.TokenType) string { + switch tokenType { + case generic.TokenTypeInternal: + return coreutils.PrintYellow(string(tokenType)) + case generic.TokenTypeUnknown: + return coreutils.PrintComment(string(tokenType)) + default: + return string(tokenType) } - return table.Row{name, internal} } type fieldRow struct { diff --git a/general/token/verify_test.go b/general/token/verify_test.go index b6ba9e196..f1bb48325 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -185,10 +185,11 @@ func TestPrintVerifyResult_Table_Valid(t *testing.T) { require.NoError(t, printVerifyResult(sampleVerifyResult(true), coreformat.Table, &buf)) out := buf.String() assert.True(t, strings.HasPrefix(out, "Valid JWT\n\n\u250c"), out) - for _, want := range []string{"FIELD", "VALUE", "2023-11-14 22:13:20 UTC (1700000000)", "ext.revocable", "TOKEN TYPE", "INTERNAL"} { + for _, want := range []string{"FIELD", "VALUE", "2023-11-14 22:13:20 UTC (1700000000)", "ext.revocable", "TOKEN TYPE"} { assert.Contains(t, out, want) } - assert.Regexp(t, `\x{2502} Identity Token\s+\x{2502} No\s+\x{2502}`, out) + assert.Regexp(t, `\x{2502} Identity Token \x{2502}`, out) + assert.NotContains(t, out, "INTERNAL") assert.NotContains(t, out, "\x1b") } @@ -269,7 +270,8 @@ func TestPrintVerifyResult_Table_Invalid(t *testing.T) { out := buf.String() assert.True(t, strings.HasPrefix(out, "Invalid JWT: token expired at 2023-11-14 23:13:20 UTC\n"), out) assert.Contains(t, out, "sub") - assert.NotContains(t, out, "TOKEN TYPE") + assert.Contains(t, out, "TOKEN TYPE (UNVERIFIED)") + assert.Regexp(t, `\x{2502} Identity Token\s+\x{2502}`, out) } func TestPrintVerifyResult_Table_InvalidWithoutPayload(t *testing.T) { @@ -281,13 +283,10 @@ func TestPrintVerifyResult_Table_InvalidWithoutPayload(t *testing.T) { func TestPrintVerifyResult_Table_InternalTypes(t *testing.T) { result := sampleVerifyResult(true) - result.Types = []generic.TokenType{generic.TokenTypeConnectDevice, generic.TokenTypeInternal, generic.TokenTypeAdmin, generic.TokenTypeUnknown} + result.Types = []generic.TokenType{generic.TokenTypeConnectDevice, generic.TokenTypeAdmin, generic.TokenTypeUnknown, generic.TokenTypeInternal} var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) - out := buf.String() - for _, row := range []string{"Connect Device Token\\s+\\x{2502} Yes", "Internal Token\\s+\\x{2502} Yes", "Admin Token\\s+\\x{2502} No", "Unknown Token Type\\s+\\x{2502} No"} { - assert.Regexp(t, row, out) - } + assert.Regexp(t, `(?s)Connect Device Token.*Admin Token.*Unknown Token Type.*Internal Token`, buf.String()) } func TestPrintVerifyResult_Table_ColorsKeepEscaping(t *testing.T) { From b58b5a63e5bcbd45325ea0c8aa66a5653603555c Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 12:11:53 +0200 Subject: [PATCH 14/30] RTECO-2746 - Showing a no-data note for rejected reference tokens and a single error line Co-Authored-By: Claude Opus 5.5 --- access_test.go | 6 +++--- docs/general/tokenverify/help.go | 2 +- general/token/verify.go | 11 +++++++++-- general/token/verify_test.go | 25 ++++++++++++++++++++++++- 4 files changed, 37 insertions(+), 7 deletions(-) diff --git a/access_test.go b/access_test.go index 9b5d57627..acc915f95 100644 --- a/access_test.go +++ b/access_test.go @@ -464,12 +464,12 @@ func TestAccessTokenVerify(t *testing.T) { created, _ := mintWithoutCleanup(t, "--reference") revokeToken(t, created.TokenId) result, err := verify(t, created.ReferenceToken) - assertInvalid(t, result, err, "didn't accept it as a reference token") - assert.Empty(t, result.Format) + assertInvalid(t, result, err, "reference token revoked: status 401") + 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, "didn't accept it as a reference token") + assertInvalid(t, result, err, "reference token revoked: status 401") }) t.Run("revoked token", func(t *testing.T) { created, _ := mintWithoutCleanup(t) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index ef0e82c05..673dad302 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -28,7 +28,7 @@ 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. http:// servers work, but print a warning. -- 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. If the server doesn't accept it, it's reported as invalid. A value with dots that doesn't parse as a JWT fails locally and is never sent. +- 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. A 401 from the server is reported as a revoked token (Access answers the same way for a value that was never a token). 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 and device scopes are also reported by name. diff --git a/general/token/verify.go b/general/token/verify.go index f7f426c0c..94c122395 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -34,6 +34,7 @@ const ( utf8Bom = "\xef\xbb\xbf" utf16LittleEndianBom = "\xff\xfe" utf16BigEndianBom = "\xfe\xff" + noReferenceDataNote = "No token data to show: a reference token can't be parsed locally, and Access doesn't return the details of a revoked or rejected one." maxValueWidth = 80 expiryWarningWindow = 7 * 24 * time.Hour tokenArgumentError = "the token can't be passed as an argument, because arguments are visible to other processes and kept in shell history. Pass it with --token-file= or on stdin" @@ -81,7 +82,9 @@ func AccessTokenVerifyCmd(c *cli.Context) error { } func verifyFailure(verifyErr error) error { - log.Error(escapeControlCharacters(verifyErr.Error())) + if !log.IsStdOutTerminal() { + log.Error(escapeControlCharacters(verifyErr.Error())) + } return coreutils.CliError{ExitCode: coreutils.ExitCodeError} } @@ -228,6 +231,9 @@ func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) erro return nil } sections := []string{verdictLine(result)} + if result.Payload == nil && result.Format == generic.TokenFormatReference { + sections = append(sections, coreutils.PrintComment(noReferenceDataNote)) + } if result.Payload != nil { fields := newVerifyTable("FIELD", "VALUE") fields.SetColumnConfigs([]table.ColumnConfig{{Number: 2, WidthMax: maxValueWidth}}) @@ -270,7 +276,8 @@ func verdictLine(result *generic.AccessTokenVerifyResult) string { } line := strings.TrimSpace(coreutils.PrintBold(coreutils.PrintRed("\u2716 Invalid " + subject))) if result.Error != "" { - line += ": " + escapeControlCharacters(result.Error) + reason := strings.TrimPrefix(strings.TrimPrefix(result.Error, "reference "), "token ") + line += ": " + escapeControlCharacters(reason) } return line } diff --git a/general/token/verify_test.go b/general/token/verify_test.go index f1bb48325..e3f4a98d4 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -268,7 +268,7 @@ func TestPrintVerifyResult_Table_Invalid(t *testing.T) { var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) out := buf.String() - assert.True(t, strings.HasPrefix(out, "Invalid JWT: token expired at 2023-11-14 23:13:20 UTC\n"), out) + assert.True(t, strings.HasPrefix(out, "Invalid JWT: expired at 2023-11-14 23:13:20 UTC\n"), out) assert.Contains(t, out, "sub") assert.Contains(t, out, "TOKEN TYPE (UNVERIFIED)") assert.Regexp(t, `\x{2502} Identity Token\s+\x{2502}`, out) @@ -281,6 +281,29 @@ func TestPrintVerifyResult_Table_InvalidWithoutPayload(t *testing.T) { assert.Equal(t, "Invalid token: failed to parse token: invalid JWT format\\x1b[2J\n", buf.String()) } +func TestPrintVerifyResult_Table_RevokedReferenceToken(t *testing.T) { + result := &generic.AccessTokenVerifyResult{ + Format: generic.TokenFormatReference, + Error: "reference token revoked: status 401 from GET /access/api/v1/tokens/me", + } + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + assert.Equal(t, "Invalid Reference token: revoked: status 401 from GET /access/api/v1/tokens/me\n\n"+noReferenceDataNote+"\n", buf.String()) +} + +func TestVerifyFailure_NotLoggedWhenStdoutIsATerminal(t *testing.T) { + var logged bytes.Buffer + previousLogger := log.GetLogger() + log.SetLogger(log.NewLogger(log.ERROR, &logged)) + defer log.SetLogger(previousLogger) + defer log.SetIsTerminalFlagsWithCallback(true)() + err := verifyFailure(errors.New("reference token revoked")) + assert.Empty(t, logged.String()) + var cliErr coreutils.CliError + require.ErrorAs(t, err, &cliErr) + assert.Equal(t, coreutils.ExitCodeError, cliErr.ExitCode) +} + func TestPrintVerifyResult_Table_InternalTypes(t *testing.T) { result := sampleVerifyResult(true) result.Types = []generic.TokenType{generic.TokenTypeConnectDevice, generic.TokenTypeAdmin, generic.TokenTypeUnknown, generic.TokenTypeInternal} From e10cbe00f2784d64681c30adf61a9d0c0e7084b1 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 12:19:30 +0200 Subject: [PATCH 15/30] RTECO-2746 - Mentioning Mission Control pairing tokens in the atv help Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 673dad302..e52e1663b 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -11,7 +11,7 @@ func GetAIDescription() string { 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 or Connect). +- 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: @@ -31,7 +31,7 @@ Gotchas: - 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. A 401 from the server is reported as a revoked token (Access answers the same way for a value that was never a token). 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 and device scopes are also reported by name. +- 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. - --format=json output has a format field: JWT or Reference. For a reference token, the payload is the token details the server returned. - The exit code is 1 when the token is invalid. The payload and the types its scopes claim are printed even when the token is invalid; the table then marks the types as unverified. From a3c79516c42a9f4f0bd8f0baa35add50e90f9b81 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 12:24:29 +0200 Subject: [PATCH 16/30] RTECO-2746 - Describing the readiness check for JWTs in the atv help Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index e52e1663b..512cf5ad9 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -7,7 +7,7 @@ func GetDescription() string { } 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's GET /access/api/v1/tokens/me endpoint is then called with the token, and only a token the server accepts is valid. A value without dots isn't shaped like a JWT, so it's sent to that endpoint as a possible reference token, and its details come from the server. + 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's GET /access/api/v1/system/readiness endpoint is then called with the token, and only a token the server accepts is valid. A value without dots isn't shaped like a JWT, so it's sent to GET /access/api/v1/tokens/me as a possible reference token, and its details come from the server. When to use: - Checking whether a token is still valid before using it in CI. From 589a5234cf4634804f6358d43ec949974de864b6 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 12:28:55 +0200 Subject: [PATCH 17/30] RTECO-2746 - Reverting the readiness wording in the atv help Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 512cf5ad9..e52e1663b 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -7,7 +7,7 @@ func GetDescription() string { } 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's GET /access/api/v1/system/readiness endpoint is then called with the token, and only a token the server accepts is valid. A value without dots isn't shaped like a JWT, so it's sent to GET /access/api/v1/tokens/me as a possible reference token, and its details come from the server. + 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's GET /access/api/v1/tokens/me endpoint is then called with the token, and only a token the server accepts is valid. A value without dots isn't shaped like a JWT, so it's sent to that endpoint as a possible reference token, and its details come from the server. When to use: - Checking whether a token is still valid before using it in CI. From b22ebe8bc0fddda18150f413c9b787acb4538dff Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 12:33:20 +0200 Subject: [PATCH 18/30] RTECO-2746 - Forcing colors in the atv test with calls every gookit/color version has Co-Authored-By: Claude Opus 5.5 --- general/token/verify_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/general/token/verify_test.go b/general/token/verify_test.go index e3f4a98d4..b2ab1c9b8 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -314,8 +314,8 @@ func TestPrintVerifyResult_Table_InternalTypes(t *testing.T) { func TestPrintVerifyResult_Table_ColorsKeepEscaping(t *testing.T) { defer log.SetIsTerminalFlagsWithCallback(true)() - color.ForceOpenColor() - defer color.RevertColorLevel() + defer color.ForceSetColorLevel(color.TermColorLevel()) + color.ForceSetColorLevel(color.LevelRgb) result := sampleVerifyResult(true) result.Payload["sub"] = "alice\x1b]0;title\x07\x1b[8m" var buf bytes.Buffer From 0a8a54c2f9d89f755e13b78900641599bcd4e2ae Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 12:35:15 +0200 Subject: [PATCH 19/30] RTECO-2746 - Describing the system/version check for JWTs in the atv help Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index e52e1663b..fd5d22b61 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -7,7 +7,7 @@ func GetDescription() string { } 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's GET /access/api/v1/tokens/me endpoint is then called with the token, and only a token the server accepts is valid. A value without dots isn't shaped like a JWT, so it's sent to that endpoint as a possible reference token, and its details come from the server. + 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's GET /access/api/v1/system/version endpoint is then called with the token, and only a token the server accepts is valid. A value without dots isn't shaped like a JWT, so it's sent to GET /access/api/v1/tokens/me as a possible reference token, and its details come from the server. When to use: - Checking whether a token is still valid before using it in CI. From 5360cd8833ef084c8ee8af9f217e5ddf62086316 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 12:37:20 +0200 Subject: [PATCH 20/30] RTECO-2746 - Explaining what a 401 or 403 from system/version means in the atv help Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index fd5d22b61..4764f73d9 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -32,7 +32,7 @@ Gotchas: - 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. +- A JWT is sent to the server only after its signature checks out. A 401 or 403 from GET /access/api/v1/system/version means the JWT was revoked. - --format=json output has a format field: JWT or Reference. For a reference token, the payload is the token details the server returned. - The exit code is 1 when the token is invalid. The payload and the types its scopes claim are printed even when the token is invalid; the table then marks the types as unverified. From dcf879184a38c1272efbceb0da5ba345e5a0ac59 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 12:55:37 +0200 Subject: [PATCH 21/30] RTECO-2746 - Naming artifactory/api/system/version in the atv help and fixing the revoked JWT test expectation Co-Authored-By: Claude Opus 5.5 --- access_test.go | 2 +- docs/general/tokenverify/help.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/access_test.go b/access_test.go index acc915f95..d4e46e416 100644 --- a/access_test.go +++ b/access_test.go @@ -475,7 +475,7 @@ func TestAccessTokenVerify(t *testing.T) { created, _ := mintWithoutCleanup(t) revokeToken(t, created.TokenId) result, err := verify(t, created.AccessToken) - assertInvalid(t, result, err, "token rejected by Access server: status 40") + assertInvalid(t, result, err, "token revoked: status 40") }) t.Run("tampered signature", func(t *testing.T) { created, _ := mint(t) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 4764f73d9..7d95fdb11 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -7,7 +7,7 @@ func GetDescription() string { } 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's GET /access/api/v1/system/version endpoint is then called with the token, and only a token the server accepts is valid. A value without dots isn't shaped like a JWT, so it's sent to GET /access/api/v1/tokens/me as a possible reference token, and its details come from the server. + 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's GET /artifactory/api/system/version endpoint is then called with the token, and only a token the server accepts is valid. A value without dots isn't shaped like a JWT, so it's sent to GET /access/api/v1/tokens/me as a possible reference token, and its details come from the server. When to use: - Checking whether a token is still valid before using it in CI. @@ -32,7 +32,7 @@ Gotchas: - 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. A 401 or 403 from GET /access/api/v1/system/version means the JWT was revoked. +- A JWT is sent to the server only after its signature checks out. A 401 or 403 from GET /artifactory/api/system/version means the JWT was revoked. - --format=json output has a format field: JWT or Reference. For a reference token, the payload is the token details the server returned. - The exit code is 1 when the token is invalid. The payload and the types its scopes claim are printed even when the token is invalid; the table then marks the types as unverified. From 7fb2143cf948dbb484ddc3ede2bb0adfd4ce8519 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Tue, 24 Nov 2026 14:45:14 +0200 Subject: [PATCH 22/30] RTECO-2746 - Filtering on valid in the atv JSON example and explaining Artifactory audience rejections Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 4 ++-- general/token/prompt.go | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 7d95fdb11..46ca4cf94 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -22,7 +22,7 @@ Common patterns: $ 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 .types + $ jf atv --token-file=token.txt --format=json | jq 'select(.valid).types' # types only when the token is valid 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. @@ -32,7 +32,7 @@ Gotchas: - 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. A 401 or 403 from GET /artifactory/api/system/version means the JWT was revoked. +- A JWT is sent to the server only after its signature checks out. A 401 or 403 from GET /artifactory/api/system/version means the JWT was revoked, or, when its aud claim doesn't include Artifactory (jfrt@ or *@), that Artifactory isn't in its audience; the token may still be valid elsewhere. - --format=json output has a format field: JWT or Reference. For a reference token, the payload is the token details the server returned. - The exit code is 1 when the token is invalid. The payload and the types its scopes claim are printed even when the token is invalid; the table then marks the types as unverified. diff --git a/general/token/prompt.go b/general/token/prompt.go index cc7dc83f8..c4be9d1f1 100644 --- a/general/token/prompt.go +++ b/general/token/prompt.go @@ -36,7 +36,6 @@ func terminalReader() func(prompt string) (string, error) { } } -// Whatever is left in the terminal after the line would otherwise reach the shell as typed input, so it's discarded. func readHiddenLine(prompt string) (string, error) { fd := int(os.Stdin.Fd()) state, err := term.MakeRaw(fd) From 535ee9d0d3cd8c56b537c2df076ff94e56a9625c Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Wed, 25 Nov 2026 12:40:02 +0200 Subject: [PATCH 23/30] RTECO-2746 - Removing the http:// warning, like other commands that use the configured server Co-Authored-By: Claude Opus 5.5 --- docs/general/tokenverify/help.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 46ca4cf94..e407fd47c 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -27,7 +27,7 @@ Common patterns: 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. http:// servers work, but print a warning. +- 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. A 401 from the server is reported as a revoked token (Access answers the same way for a value that was never a token). 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. From 60000ca155119bbc5181edb0f395b7655c8669be Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Sun, 29 Nov 2026 10:58:47 +0200 Subject: [PATCH 24/30] RTECO-2746 - Showing a couldn't-verify verdict and the status field in atv output Co-Authored-By: Claude Opus 5.5 --- access_test.go | 3 +++ docs/general/tokenverify/help.go | 4 +++- general/token/verify.go | 3 +++ general/token/verify_test.go | 27 +++++++++++++++++++++++++-- 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/access_test.go b/access_test.go index d4e46e416..0cd99c7bd 100644 --- a/access_test.go +++ b/access_test.go @@ -355,6 +355,7 @@ 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"` @@ -405,12 +406,14 @@ func TestAccessTokenVerify(t *testing.T) { 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) } diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index e407fd47c..17ca99397 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -23,6 +23,7 @@ Common patterns: $ 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 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. @@ -34,7 +35,8 @@ Gotchas: - 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. A 401 or 403 from GET /artifactory/api/system/version means the JWT was revoked, or, when its aud claim doesn't include Artifactory (jfrt@ or *@), that Artifactory isn't in its audience; the token may still be valid elsewhere. - --format=json output has a format field: JWT or Reference. For a reference token, the payload is the token details the server returned. -- The exit code is 1 when the token is invalid. The payload and the types its scopes claim are printed even when the token is invalid; the table then marks the types as unverified. +- --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". +- 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 diff --git a/general/token/verify.go b/general/token/verify.go index 94c122395..18d6e61c2 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -275,6 +275,9 @@ func verdictLine(result *generic.AccessTokenVerifyResult) string { return strings.TrimSpace(coreutils.PrintBold(coreutils.PrintGreen("\u2714 Valid " + subject))) } line := strings.TrimSpace(coreutils.PrintBold(coreutils.PrintRed("\u2716 Invalid " + subject))) + if result.Status == generic.VerifyStatusUnverified { + line = strings.TrimSpace(coreutils.PrintBold(coreutils.PrintYellow("\u26a0 Couldn't verify " + subject))) + } if result.Error != "" { reason := strings.TrimPrefix(strings.TrimPrefix(result.Error, "reference "), "token ") line += ": " + escapeControlCharacters(reason) diff --git a/general/token/verify_test.go b/general/token/verify_test.go index b2ab1c9b8..55cfaf5b1 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -163,8 +163,13 @@ func TestAccessTokenVerifyFlags(t *testing.T) { } func sampleVerifyResult(valid bool) *generic.AccessTokenVerifyResult { + status := generic.VerifyStatusInvalid + if valid { + status = generic.VerifyStatusValid + } return &generic.AccessTokenVerifyResult{ Valid: valid, + Status: status, Format: generic.TokenFormatJWT, Payload: map[string]interface{}{ "jti": "id-1", @@ -274,6 +279,22 @@ func TestPrintVerifyResult_Table_Invalid(t *testing.T) { assert.Regexp(t, `\x{2502} Identity Token\s+\x{2502}`, out) } +func TestPrintVerifyResult_Table_Unverified(t *testing.T) { + result := sampleVerifyResult(false) + result.Status = generic.VerifyStatusUnverified + result.Error = "failed to check the token with the JFrog server (GET /artifactory/api/system/version): connection refused" + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + out := buf.String() + assert.True(t, strings.HasPrefix(out, "Couldn't verify JWT: failed to check the token with the JFrog server (GET /artifactory/api/system/version): connection refused\n"), out) + assert.NotContains(t, out, "Invalid") + assert.Contains(t, out, "TOKEN TYPE (UNVERIFIED)") + + buf.Reset() + require.NoError(t, printVerifyResult(result, coreformat.Json, &buf)) + assert.Contains(t, buf.String(), `"status": "unverified"`) +} + func TestPrintVerifyResult_Table_InvalidWithoutPayload(t *testing.T) { var buf bytes.Buffer result := &generic.AccessTokenVerifyResult{Error: "failed to parse token: invalid JWT format\x1b[2J"} @@ -348,12 +369,14 @@ func TestPrintVerifyResult_JSON(t *testing.T) { require.NoError(t, printVerifyResult(sampleVerifyResult(true), coreformat.Json, &buf)) var out struct { Valid bool `json:"valid"` + Status string `json:"status"` Format string `json:"format"` Types []string `json:"types"` Payload map[string]interface{} `json:"payload"` } require.NoError(t, json.Unmarshal(buf.Bytes(), &out)) assert.True(t, out.Valid) + assert.Equal(t, "valid", out.Status) assert.Equal(t, "JWT", out.Format) assert.Equal(t, []string{"Identity Token"}, out.Types) assert.IsType(t, map[string]interface{}{}, out.Payload["ext"]) @@ -361,8 +384,8 @@ func TestPrintVerifyResult_JSON(t *testing.T) { func TestPrintVerifyResult_JSON_ParseFailure(t *testing.T) { var buf bytes.Buffer - require.NoError(t, printVerifyResult(&generic.AccessTokenVerifyResult{Error: "failed to parse token: x"}, coreformat.Json, &buf)) - assert.JSONEq(t, `{"valid":false,"error":"failed to parse token: x"}`, buf.String()) + require.NoError(t, printVerifyResult(&generic.AccessTokenVerifyResult{Status: generic.VerifyStatusInvalid, Error: "failed to parse token: x"}, coreformat.Json, &buf)) + assert.JSONEq(t, `{"valid":false,"status":"invalid","error":"failed to parse token: x"}`, buf.String()) } func TestPrintVerifyResult_JSON_EscapesControlAndFormatCharacters(t *testing.T) { From 002324ceef422b7cda8f4a0247c0eee1b2606219 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Sun, 29 Nov 2026 12:24:32 +0200 Subject: [PATCH 25/30] RTECO-2746 - Describing the dual server check and noting a valid reference token without details Co-Authored-By: Claude Opus 5.5 --- access_test.go | 6 +++--- docs/general/tokenverify/help.go | 6 +++--- general/token/verify.go | 25 +++++++++++++++---------- general/token/verify_test.go | 11 +++++++++-- 4 files changed, 30 insertions(+), 18 deletions(-) diff --git a/access_test.go b/access_test.go index 0cd99c7bd..594701973 100644 --- a/access_test.go +++ b/access_test.go @@ -467,18 +467,18 @@ func TestAccessTokenVerify(t *testing.T) { created, _ := mintWithoutCleanup(t, "--reference") revokeToken(t, created.TokenId) result, err := verify(t, created.ReferenceToken) - assertInvalid(t, result, err, "reference token revoked: status 401") + assertInvalid(t, result, err, "token revoked: status 401 from GET /access/api/v1/tokens/me") 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, "reference token revoked: status 401") + assertInvalid(t, result, err, "token revoked: status 401 from GET /access/api/v1/tokens/me") }) 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, "token revoked: status 40") + assertInvalid(t, result, err, "status 40") }) t.Run("tampered signature", func(t *testing.T) { created, _ := mint(t) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 17ca99397..491813988 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -7,7 +7,7 @@ func GetDescription() string { } 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's GET /artifactory/api/system/version endpoint is then called with the token, and only a token the server accepts is valid. A value without dots isn't shaped like a JWT, so it's sent to GET /access/api/v1/tokens/me as a possible reference token, and its details come from the server. + 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. @@ -29,11 +29,11 @@ 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. A 401 from the server is reported as a revoked token (Access answers the same way for a value that was never a token). 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. +- 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. A 401 or 403 from GET /artifactory/api/system/version means the JWT was revoked, or, when its aud claim doesn't include Artifactory (jfrt@ or *@), that Artifactory isn't in its audience; the token may still be valid elsewhere. +- 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 token is revoked if they answered 401, rejected if either answered 403, and unverified if neither could be reached or answered as expected; the message lists both answers, with the server's reason. 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". - 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. diff --git a/general/token/verify.go b/general/token/verify.go index 18d6e61c2..2cc11e83a 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -29,15 +29,16 @@ import ( ) const ( - stdinPrompt = "Reading the access token from stdin. Paste it and press Enter (input is hidden): " - maxTokenInput = 64 * 1024 - utf8Bom = "\xef\xbb\xbf" - utf16LittleEndianBom = "\xff\xfe" - utf16BigEndianBom = "\xfe\xff" - noReferenceDataNote = "No token data to show: a reference token can't be parsed locally, and Access doesn't return the details of a revoked or rejected one." - maxValueWidth = 80 - expiryWarningWindow = 7 * 24 * time.Hour - tokenArgumentError = "the token can't be passed as an argument, because arguments are visible to other processes and kept in shell history. Pass it with --token-file= or on stdin" + stdinPrompt = "Reading the access token from stdin. Paste it and press Enter (input is hidden): " + maxTokenInput = 64 * 1024 + utf8Bom = "\xef\xbb\xbf" + utf16LittleEndianBom = "\xff\xfe" + utf16BigEndianBom = "\xfe\xff" + noReferenceDataNote = "No token data to show: a reference token can't be parsed locally, and the JFrog server didn't return its details." + noReferenceDetailsNote = "The JFrog server accepted the token but didn't return its details, so there's no token data to show." + maxValueWidth = 80 + expiryWarningWindow = 7 * 24 * time.Hour + tokenArgumentError = "the token can't be passed as an argument, because arguments are visible to other processes and kept in shell history. Pass it with --token-file= or on stdin" ) var ( @@ -232,7 +233,11 @@ func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) erro } sections := []string{verdictLine(result)} if result.Payload == nil && result.Format == generic.TokenFormatReference { - sections = append(sections, coreutils.PrintComment(noReferenceDataNote)) + note := noReferenceDataNote + if result.Valid { + note = noReferenceDetailsNote + } + sections = append(sections, coreutils.PrintComment(note)) } if result.Payload != nil { fields := newVerifyTable("FIELD", "VALUE") diff --git a/general/token/verify_test.go b/general/token/verify_test.go index 55cfaf5b1..dc9ee5fc3 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -305,11 +305,18 @@ func TestPrintVerifyResult_Table_InvalidWithoutPayload(t *testing.T) { func TestPrintVerifyResult_Table_RevokedReferenceToken(t *testing.T) { result := &generic.AccessTokenVerifyResult{ Format: generic.TokenFormatReference, - Error: "reference token revoked: status 401 from GET /access/api/v1/tokens/me", + Error: "token revoked: status 401 from GET /access/api/v1/tokens/me; status 401 from GET /artifactory/api/system/version", } var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) - assert.Equal(t, "Invalid Reference token: revoked: status 401 from GET /access/api/v1/tokens/me\n\n"+noReferenceDataNote+"\n", buf.String()) + assert.Equal(t, "Invalid Reference token: revoked: status 401 from GET /access/api/v1/tokens/me; status 401 from GET /artifactory/api/system/version\n\n"+noReferenceDataNote+"\n", buf.String()) +} + +func TestPrintVerifyResult_Table_ValidReferenceTokenWithoutDetails(t *testing.T) { + result := &generic.AccessTokenVerifyResult{Valid: true, Status: generic.VerifyStatusValid, Format: generic.TokenFormatReference} + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + assert.Equal(t, "Valid Reference token\n\n"+noReferenceDetailsNote+"\n", buf.String()) } func TestVerifyFailure_NotLoggedWhenStdoutIsATerminal(t *testing.T) { From 06c3b2ef36eedeb80fa13f4a6f23f7e2e3402991 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 30 Nov 2026 11:16:15 +0200 Subject: [PATCH 26/30] RTECO-2746 - Describing the single reported server failure and updating the expected messages Co-Authored-By: Claude Opus 5.5 --- access_test.go | 4 ++-- docs/general/tokenverify/help.go | 2 +- general/token/verify_test.go | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/access_test.go b/access_test.go index 594701973..70d36e674 100644 --- a/access_test.go +++ b/access_test.go @@ -467,12 +467,12 @@ func TestAccessTokenVerify(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 /access/api/v1/tokens/me") + 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 /access/api/v1/tokens/me") + 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) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 491813988..69a727c80 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -33,7 +33,7 @@ Gotchas: - 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 token is revoked if they answered 401, rejected if either answered 403, and unverified if neither could be reached or answered as expected; the message lists both answers, with the server's reason. A value that was never a token is reported as revoked too, since the server answers 401 for it. +- 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". - 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. diff --git a/general/token/verify_test.go b/general/token/verify_test.go index dc9ee5fc3..98227d33c 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -282,11 +282,11 @@ func TestPrintVerifyResult_Table_Invalid(t *testing.T) { func TestPrintVerifyResult_Table_Unverified(t *testing.T) { result := sampleVerifyResult(false) result.Status = generic.VerifyStatusUnverified - result.Error = "failed to check the token with the JFrog server (GET /artifactory/api/system/version): connection refused" + result.Error = "failed to check the token with the JFrog server: GET /artifactory/api/system/version failed: connection refused" var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) out := buf.String() - assert.True(t, strings.HasPrefix(out, "Couldn't verify JWT: failed to check the token with the JFrog server (GET /artifactory/api/system/version): connection refused\n"), out) + assert.True(t, strings.HasPrefix(out, "Couldn't verify JWT: failed to check the token with the JFrog server: GET /artifactory/api/system/version failed: connection refused\n"), out) assert.NotContains(t, out, "Invalid") assert.Contains(t, out, "TOKEN TYPE (UNVERIFIED)") @@ -305,11 +305,11 @@ func TestPrintVerifyResult_Table_InvalidWithoutPayload(t *testing.T) { func TestPrintVerifyResult_Table_RevokedReferenceToken(t *testing.T) { result := &generic.AccessTokenVerifyResult{ Format: generic.TokenFormatReference, - Error: "token revoked: status 401 from GET /access/api/v1/tokens/me; status 401 from GET /artifactory/api/system/version", + Error: "token revoked: status 401 from GET /artifactory/api/system/version: Token failed verification: parse", } var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) - assert.Equal(t, "Invalid Reference token: revoked: status 401 from GET /access/api/v1/tokens/me; status 401 from GET /artifactory/api/system/version\n\n"+noReferenceDataNote+"\n", buf.String()) + assert.Equal(t, "Invalid Reference token: revoked: status 401 from GET /artifactory/api/system/version: Token failed verification: parse\n\n"+noReferenceDataNote+"\n", buf.String()) } func TestPrintVerifyResult_Table_ValidReferenceTokenWithoutDetails(t *testing.T) { From 86a448cf5df2ac7ce3c315b7911c28d1fe153a0c Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 30 Nov 2026 13:18:55 +0200 Subject: [PATCH 27/30] RTECO-2746 - Keeping input after a lone Esc, rejecting any Unicode whitespace in the token and showing less than a minute left Co-Authored-By: Claude Opus 5.5 --- general/token/prompt.go | 9 +++++++-- general/token/prompt_test.go | 24 ++++++++++++++++++++++++ general/token/verify.go | 6 ++++-- general/token/verify_test.go | 6 ++++++ 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/general/token/prompt.go b/general/token/prompt.go index c4be9d1f1..861c6962f 100644 --- a/general/token/prompt.go +++ b/general/token/prompt.go @@ -64,11 +64,16 @@ func readHiddenInput(input io.Reader) (line, leftover string, err error) { 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+. + if inSequence || i > 0 { + continue + } + } switch { case inSequence: inSequence = b < 0x40 || b > 0x7e - case inEscape: - inEscape, inSequence = false, b == '[' || b == 'O' case b == keyEscape: inEscape = true case b == '\r' || b == '\n': diff --git a/general/token/prompt_test.go b/general/token/prompt_test.go index f6bde367e..2fc63d6c5 100644 --- a/general/token/prompt_test.go +++ b/general/token/prompt_test.go @@ -2,6 +2,7 @@ package token import ( "errors" + "io" "strings" "testing" "testing/iotest" @@ -45,6 +46,29 @@ func TestReadHiddenInput_LongLineAcrossReads(t *testing.T) { assert.Empty(t, leftover) } +func TestReadHiddenInput_EscapeAcrossReads(t *testing.T) { + for _, tc := range []struct { + parts []string + line string + }{ + {[]string{"\x1b", "eyJ.b.c\r"}, "eyJ.b.c"}, + {[]string{"a.b\x1b", "[D.c\r"}, "a.b.c"}, + {[]string{"a.b\x1b", "OA.c\r"}, "a.b.c"}, + {[]string{"a.b\x1b", "[1;", "5C.c\r"}, "a.b.c"}, + {[]string{"\x1b", "\x1b", "a.b.c\r"}, "a.b.c"}, + {[]string{"\x1bx", "a.b.c\r"}, "a.b.c"}, + } { + readers := make([]io.Reader, len(tc.parts)) + for i, part := range tc.parts { + readers[i] = strings.NewReader(part) + } + line, leftover, err := readHiddenInput(io.MultiReader(readers...)) + require.NoError(t, err, tc.parts) + assert.Equal(t, tc.line, line, tc.parts) + assert.Empty(t, leftover, tc.parts) + } +} + func TestReadHiddenInput_SizeLimit(t *testing.T) { line, _, err := readHiddenInput(strings.NewReader(strings.Repeat("a", maxTokenInput) + "\r")) require.NoError(t, err) diff --git a/general/token/verify.go b/general/token/verify.go index 2cc11e83a..535745c63 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -146,7 +146,7 @@ func extractToken(raw string) (string, error) { if tokenValue == "" { return "", errorutils.CheckErrorf("no token provided: pass it with --token-file= or on stdin") } - if strings.ContainsAny(tokenValue, " \t\r\n") { + if strings.ContainsFunc(tokenValue, unicode.IsSpace) { return "", errorutils.CheckErrorf("the token input contains more than one value; expected a single token") } return tokenValue, nil @@ -422,8 +422,10 @@ func remaining(d time.Duration) string { return countOf(int(d/(24*time.Hour)), "day") case d >= time.Hour: return countOf(int(d/time.Hour), "hour") - default: + case d >= time.Minute: return countOf(int(d/time.Minute), "minute") + default: + return "less than a minute" } } diff --git a/general/token/verify_test.go b/general/token/verify_test.go index 98227d33c..9e4fd8dd4 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -65,6 +65,9 @@ func TestExtractToken(t *testing.T) { {"", "no token provided"}, {" \n", "no token provided"}, {"a.b.c\nd.e.f", "the token input contains more than one value; expected a single token"}, + {"a.b.c\u00a0d.e.f", "the token input contains more than one value; expected a single token"}, + {"a.b.c\vd.e.f", "the token input contains more than one value; expected a single token"}, + {"a.b.c\u3000d.e.f", "the token input contains more than one value; expected a single token"}, } { _, err := extractToken(tc.raw) assert.ErrorContains(t, err, tc.wantErr, tc.raw) @@ -250,6 +253,9 @@ func TestPrintVerifyResult_Table_Expiry(t *testing.T) { {json.Number("0"), "never"}, {json.Number("1699999999"), "expired"}, {json.Number("1700003600"), "expires in 1 hour"}, + {json.Number("1700000060"), "expires in 1 minute"}, + {json.Number("1700000059"), "expires in less than a minute"}, + {json.Number("1700000001"), "expires in less than a minute"}, {json.Number("1700000000"), "expired"}, {json.Number("1700259200"), "expires in 3 days"}, {json.Number("1800000000"), "2027-01-15 08:00:00 UTC (1800000000)"}, From 4bb03cb4a10e6cbd92591be3b522bad7e7d471b5 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 30 Nov 2026 21:57:52 +0200 Subject: [PATCH 28/30] RTECO-2746 - Showing whether a valid token is revocable Co-Authored-By: Claude Opus 5.5 JFrog-AI-Session: claude-code/58e47ad8-d3e7-4127-a5bf-0eaefc719bec --- docs/general/tokenverify/help.go | 4 ++- general/token/verify.go | 14 +++++++++++ general/token/verify_test.go | 42 ++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 69a727c80..299220cdf 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -3,7 +3,7 @@ package tokenverify var Usage = []string{"atv", "atv --token-file="} 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.` + 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 { @@ -24,6 +24,7 @@ Common patterns: $ 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. @@ -36,6 +37,7 @@ Gotchas: - 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 diff --git a/general/token/verify.go b/general/token/verify.go index 535745c63..2b056286e 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -232,6 +232,9 @@ func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) erro return nil } sections := []string{verdictLine(result)} + if result.Revocability != "" { + sections = append(sections, "Revocability: "+revocabilityValue(result.Revocability)) + } if result.Payload == nil && result.Format == generic.TokenFormatReference { note := noReferenceDataNote if result.Valid { @@ -290,6 +293,17 @@ func verdictLine(result *generic.AccessTokenVerifyResult) string { return line } +func revocabilityValue(revocability generic.Revocability) string { + switch revocability { + case generic.NonRevocable: + return coreutils.PrintYellow(string(revocability)) + case generic.RevocabilityUnknown: + return coreutils.PrintComment(string(revocability)) + default: + return string(revocability) + } +} + func typeName(tokenType generic.TokenType) string { switch tokenType { case generic.TokenTypeInternal: diff --git a/general/token/verify_test.go b/general/token/verify_test.go index 9e4fd8dd4..449cd0912 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -441,3 +441,45 @@ func TestPrintVerifyResult_UnsupportedFormat(t *testing.T) { err := printVerifyResult(sampleVerifyResult(true), "xml", &bytes.Buffer{}) assert.EqualError(t, err, "unsupported format 'xml' for access-token-verify. Accepted values: table, json") } + +func TestPrintVerifyResult_Table_Revocability(t *testing.T) { + for _, revocability := range []generic.Revocability{generic.Revocable, generic.NonRevocable, generic.RevocabilityUnknown} { + result := sampleVerifyResult(true) + result.Revocability = revocability + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + assert.True(t, strings.HasPrefix(buf.String(), "Valid JWT\n\nRevocability: "+string(revocability)+"\n\n┌"), buf.String()) + } +} + +func TestPrintVerifyResult_Table_RevocabilityBeforeTheReferenceTokenNote(t *testing.T) { + result := &generic.AccessTokenVerifyResult{Valid: true, Status: generic.VerifyStatusValid, Format: generic.TokenFormatReference, Revocability: generic.RevocabilityUnknown} + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + assert.Equal(t, "Valid Reference token\n\nRevocability: unknown\n\n"+noReferenceDetailsNote+"\n", buf.String()) +} + +func TestPrintVerifyResult_Table_RevocabilityColors(t *testing.T) { + defer log.SetIsTerminalFlagsWithCallback(true)() + defer color.ForceSetColorLevel(color.TermColorLevel()) + color.ForceSetColorLevel(color.LevelRgb) + for revocability, want := range map[generic.Revocability]string{ + generic.Revocable: "revocable", + generic.NonRevocable: coreutils.PrintYellow("non-revocable"), + generic.RevocabilityUnknown: coreutils.PrintComment("unknown"), + } { + result := sampleVerifyResult(true) + result.Revocability = revocability + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + assert.Contains(t, buf.String(), "\n\nRevocability: "+want+"\n\n", revocability) + } +} + +func TestPrintVerifyResult_JSON_Revocability(t *testing.T) { + result := sampleVerifyResult(true) + result.Revocability = generic.NonRevocable + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Json, &buf)) + assert.True(t, strings.HasSuffix(buf.String(), " \"revocability\": \"non-revocable\"\n}\n"), buf.String()) +} From 19dd424c41ea98c460341ff01d5e9bfafce7cb10 Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 30 Nov 2026 22:16:48 +0200 Subject: [PATCH 29/30] RTECO-2746 - Showing the revocability next to the token types, in green when revocable, and the types in bold Co-Authored-By: Claude Opus 5.5 JFrog-AI-Session: claude-code/58e47ad8-d3e7-4127-a5bf-0eaefc719bec --- general/token/verify.go | 42 +++++++++++++++++-------- general/token/verify_test.go | 59 +++++++++++++++++++++++++++++++----- 2 files changed, 80 insertions(+), 21 deletions(-) diff --git a/general/token/verify.go b/general/token/verify.go index 2b056286e..af427453b 100644 --- a/general/token/verify.go +++ b/general/token/verify.go @@ -232,9 +232,6 @@ func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) erro return nil } sections := []string{verdictLine(result)} - if result.Revocability != "" { - sections = append(sections, "Revocability: "+revocabilityValue(result.Revocability)) - } if result.Payload == nil && result.Format == generic.TokenFormatReference { note := noReferenceDataNote if result.Valid { @@ -250,19 +247,38 @@ func printVerifyTable(result *generic.AccessTokenVerifyResult, w io.Writer) erro } sections = append(sections, fields.Render()) } + if len(result.Types) > 0 || result.Revocability != "" { + sections = append(sections, typesTable(result)) + } + _, err := fmt.Fprintln(w, strings.Join(sections, "\n\n")) + return errorutils.CheckError(err) +} + +func typesTable(result *generic.AccessTokenVerifyResult) string { + var headers table.Row if len(result.Types) > 0 { typeHeader := "TOKEN TYPE" if !result.Valid { typeHeader = "TOKEN TYPE (UNVERIFIED)" } - types := newVerifyTable(typeHeader) - for _, tokenType := range result.Types { - types.AppendRow(table.Row{typeName(tokenType)}) + headers = append(headers, typeHeader) + } + if result.Revocability != "" { + headers = append(headers, "TOKEN REVOCABILITY") + } + tw := newVerifyTable(headers...) + tw.SetColumnConfigs([]table.ColumnConfig{{Name: "TOKEN REVOCABILITY", AutoMerge: true}}) + for i := 0; i < max(len(result.Types), 1); i++ { + var row table.Row + if len(result.Types) > 0 { + row = append(row, typeName(result.Types[i])) + } + if result.Revocability != "" { + row = append(row, revocabilityValue(result.Revocability)) } - sections = append(sections, types.Render()) + tw.AppendRow(row) } - _, err := fmt.Fprintln(w, strings.Join(sections, "\n\n")) - return errorutils.CheckError(err) + return tw.Render() } func newVerifyTable(headers ...interface{}) table.Writer { @@ -300,18 +316,18 @@ func revocabilityValue(revocability generic.Revocability) string { case generic.RevocabilityUnknown: return coreutils.PrintComment(string(revocability)) default: - return string(revocability) + return coreutils.PrintGreen(string(revocability)) } } func typeName(tokenType generic.TokenType) string { switch tokenType { case generic.TokenTypeInternal: - return coreutils.PrintYellow(string(tokenType)) + return coreutils.PrintBold(coreutils.PrintYellow(string(tokenType))) case generic.TokenTypeUnknown: - return coreutils.PrintComment(string(tokenType)) + return coreutils.PrintBold(coreutils.PrintComment(string(tokenType))) default: - return string(tokenType) + return coreutils.PrintBold(string(tokenType)) } } diff --git a/general/token/verify_test.go b/general/token/verify_test.go index 449cd0912..b89e20166 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -442,21 +442,46 @@ func TestPrintVerifyResult_UnsupportedFormat(t *testing.T) { assert.EqualError(t, err, "unsupported format 'xml' for access-token-verify. Accepted values: table, json") } -func TestPrintVerifyResult_Table_Revocability(t *testing.T) { +func TestPrintVerifyResult_Table_RevocabilityNextToTheTokenType(t *testing.T) { for _, revocability := range []generic.Revocability{generic.Revocable, generic.NonRevocable, generic.RevocabilityUnknown} { result := sampleVerifyResult(true) result.Revocability = revocability var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) - assert.True(t, strings.HasPrefix(buf.String(), "Valid JWT\n\nRevocability: "+string(revocability)+"\n\n┌"), buf.String()) + out := buf.String() + assert.True(t, strings.HasPrefix(out, "Valid JWT\n\n\u250c"), out) + assert.NotContains(t, out, "Revocability:") + assert.Regexp(t, `\x{2502} TOKEN TYPE\s+\x{2502} TOKEN REVOCABILITY \x{2502}`, out) + assert.Regexp(t, `\x{2502} Identity Token\s+\x{2502} `+string(revocability)+`\s+\x{2502}\n\x{2514}`, out) } } -func TestPrintVerifyResult_Table_RevocabilityBeforeTheReferenceTokenNote(t *testing.T) { +func TestPrintVerifyResult_Table_RevocabilityIsShownOnceForSeveralTypes(t *testing.T) { + result := sampleVerifyResult(true) + result.Types = []generic.TokenType{generic.TokenTypeAdmin, generic.TokenTypeInternal} + result.Revocability = generic.NonRevocable + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + out := buf.String() + assert.Equal(t, 1, strings.Count(out, "non-revocable"), out) + assert.Regexp(t, `\x{2502} Admin Token\s+\x{2502} non-revocable\s+\x{2502}\n\x{2502} Internal Token\s+\x{2502}\s+\x{2502}`, out) +} + +func TestPrintVerifyResult_Table_RevocabilityWithoutTypes(t *testing.T) { result := &generic.AccessTokenVerifyResult{Valid: true, Status: generic.VerifyStatusValid, Format: generic.TokenFormatReference, Revocability: generic.RevocabilityUnknown} var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) - assert.Equal(t, "Valid Reference token\n\nRevocability: unknown\n\n"+noReferenceDetailsNote+"\n", buf.String()) + out := buf.String() + assert.True(t, strings.HasPrefix(out, "Valid Reference token\n\n"+noReferenceDetailsNote+"\n\n\u250c"), out) + assert.NotContains(t, out, "TOKEN TYPE") + assert.Regexp(t, `\x{2502} TOKEN REVOCABILITY \x{2502}\n\x{251c}[^\n]*\n\x{2502} unknown\s+\x{2502}`, out) +} + +func TestPrintVerifyResult_Table_NoRevocabilityColumnWithoutRevocability(t *testing.T) { + var buf bytes.Buffer + require.NoError(t, printVerifyResult(sampleVerifyResult(false), coreformat.Table, &buf)) + assert.Regexp(t, `\x{2502} TOKEN TYPE \(UNVERIFIED\) \x{2502}\n`, buf.String()) + assert.NotContains(t, buf.String(), "REVOCABILITY") } func TestPrintVerifyResult_Table_RevocabilityColors(t *testing.T) { @@ -464,15 +489,15 @@ func TestPrintVerifyResult_Table_RevocabilityColors(t *testing.T) { defer color.ForceSetColorLevel(color.TermColorLevel()) color.ForceSetColorLevel(color.LevelRgb) for revocability, want := range map[generic.Revocability]string{ - generic.Revocable: "revocable", - generic.NonRevocable: coreutils.PrintYellow("non-revocable"), - generic.RevocabilityUnknown: coreutils.PrintComment("unknown"), + generic.Revocable: "\u2502 " + coreutils.PrintGreen("revocable") + " ", + generic.NonRevocable: "\u2502 " + coreutils.PrintYellow("non-revocable") + " ", + generic.RevocabilityUnknown: "\u2502 " + coreutils.PrintComment("unknown") + " ", } { result := sampleVerifyResult(true) result.Revocability = revocability var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) - assert.Contains(t, buf.String(), "\n\nRevocability: "+want+"\n\n", revocability) + assert.Contains(t, buf.String(), want, revocability) } } @@ -483,3 +508,21 @@ func TestPrintVerifyResult_JSON_Revocability(t *testing.T) { require.NoError(t, printVerifyResult(result, coreformat.Json, &buf)) assert.True(t, strings.HasSuffix(buf.String(), " \"revocability\": \"non-revocable\"\n}\n"), buf.String()) } + +func TestPrintVerifyResult_Table_TypesAreBold(t *testing.T) { + defer log.SetIsTerminalFlagsWithCallback(true)() + defer color.ForceSetColorLevel(color.TermColorLevel()) + color.ForceSetColorLevel(color.LevelRgb) + result := sampleVerifyResult(true) + result.Types = []generic.TokenType{generic.TokenTypeAdmin, generic.TokenTypeInternal, generic.TokenTypeUnknown} + var buf bytes.Buffer + require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) + out := buf.String() + for _, want := range []string{ + coreutils.PrintBold("Admin Token"), + coreutils.PrintBold(coreutils.PrintYellow("Internal Token")), + coreutils.PrintBold(coreutils.PrintComment("Unknown Token Type")), + } { + assert.Contains(t, out, "\u2502 "+want+" ", want) + } +} From e99a0e1906c437bc06ecad2df87ce1e86baba9df Mon Sep 17 00:00:00 2001 From: Hanoch Giner Date: Mon, 30 Nov 2026 22:19:27 +0200 Subject: [PATCH 30/30] RTECO-2746 - Capitalizing the revocability values in the help and tests Co-Authored-By: Claude Opus 5.5 JFrog-AI-Session: claude-code/58e47ad8-d3e7-4127-a5bf-0eaefc719bec --- docs/general/tokenverify/help.go | 4 ++-- general/token/verify_test.go | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/general/tokenverify/help.go b/docs/general/tokenverify/help.go index 299220cdf..d09f8a7f0 100644 --- a/docs/general/tokenverify/help.go +++ b/docs/general/tokenverify/help.go @@ -24,7 +24,7 @@ Common patterns: $ 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 + $ 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. @@ -37,7 +37,7 @@ Gotchas: - 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. +- 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 diff --git a/general/token/verify_test.go b/general/token/verify_test.go index b89e20166..632f1b81d 100644 --- a/general/token/verify_test.go +++ b/general/token/verify_test.go @@ -463,8 +463,8 @@ func TestPrintVerifyResult_Table_RevocabilityIsShownOnceForSeveralTypes(t *testi var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Table, &buf)) out := buf.String() - assert.Equal(t, 1, strings.Count(out, "non-revocable"), out) - assert.Regexp(t, `\x{2502} Admin Token\s+\x{2502} non-revocable\s+\x{2502}\n\x{2502} Internal Token\s+\x{2502}\s+\x{2502}`, out) + assert.Equal(t, 1, strings.Count(out, "Non-revocable"), out) + assert.Regexp(t, `\x{2502} Admin Token\s+\x{2502} Non-revocable\s+\x{2502}\n\x{2502} Internal Token\s+\x{2502}\s+\x{2502}`, out) } func TestPrintVerifyResult_Table_RevocabilityWithoutTypes(t *testing.T) { @@ -474,7 +474,7 @@ func TestPrintVerifyResult_Table_RevocabilityWithoutTypes(t *testing.T) { out := buf.String() assert.True(t, strings.HasPrefix(out, "Valid Reference token\n\n"+noReferenceDetailsNote+"\n\n\u250c"), out) assert.NotContains(t, out, "TOKEN TYPE") - assert.Regexp(t, `\x{2502} TOKEN REVOCABILITY \x{2502}\n\x{251c}[^\n]*\n\x{2502} unknown\s+\x{2502}`, out) + assert.Regexp(t, `\x{2502} TOKEN REVOCABILITY \x{2502}\n\x{251c}[^\n]*\n\x{2502} Unknown\s+\x{2502}`, out) } func TestPrintVerifyResult_Table_NoRevocabilityColumnWithoutRevocability(t *testing.T) { @@ -489,9 +489,9 @@ func TestPrintVerifyResult_Table_RevocabilityColors(t *testing.T) { defer color.ForceSetColorLevel(color.TermColorLevel()) color.ForceSetColorLevel(color.LevelRgb) for revocability, want := range map[generic.Revocability]string{ - generic.Revocable: "\u2502 " + coreutils.PrintGreen("revocable") + " ", - generic.NonRevocable: "\u2502 " + coreutils.PrintYellow("non-revocable") + " ", - generic.RevocabilityUnknown: "\u2502 " + coreutils.PrintComment("unknown") + " ", + generic.Revocable: "\u2502 " + coreutils.PrintGreen("Revocable") + " ", + generic.NonRevocable: "\u2502 " + coreutils.PrintYellow("Non-revocable") + " ", + generic.RevocabilityUnknown: "\u2502 " + coreutils.PrintComment("Unknown") + " ", } { result := sampleVerifyResult(true) result.Revocability = revocability @@ -506,7 +506,7 @@ func TestPrintVerifyResult_JSON_Revocability(t *testing.T) { result.Revocability = generic.NonRevocable var buf bytes.Buffer require.NoError(t, printVerifyResult(result, coreformat.Json, &buf)) - assert.True(t, strings.HasSuffix(buf.String(), " \"revocability\": \"non-revocable\"\n}\n"), buf.String()) + assert.True(t, strings.HasSuffix(buf.String(), " \"revocability\": \"Non-revocable\"\n}\n"), buf.String()) } func TestPrintVerifyResult_Table_TypesAreBold(t *testing.T) {