From 1e5dab7450591f238daaccd5c096e8556f0eb352 Mon Sep 17 00:00:00 2001 From: lvxinsheng Date: Thu, 5 Nov 2026 16:21:08 +0800 Subject: [PATCH 1/4] test(apps): pin one-time key notice placement for json vs human formats --- .../apps/apps_openapi_key_notice_test.go | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 shortcuts/apps/apps_openapi_key_notice_test.go diff --git a/shortcuts/apps/apps_openapi_key_notice_test.go b/shortcuts/apps/apps_openapi_key_notice_test.go new file mode 100644 index 0000000000..797528c776 --- /dev/null +++ b/shortcuts/apps/apps_openapi_key_notice_test.go @@ -0,0 +1,155 @@ +// Copyright (c) 2026 Lark Technologies Pte. Ltd. +// SPDX-License-Identifier: MIT + +package apps + +import ( + "bytes" + "context" + "encoding/json" + "strings" + "testing" + + "github.com/larksuite/cli/internal/httpmock" + "github.com/larksuite/cli/shortcuts/common" +) + +// shownOnceNotice is the one-time-secret guidance shared by create/reset. +const shownOnceNotice = "this api_key is shown only once" + +func issuedKeyErrBuffer(t *testing.T, rctx *common.RuntimeContext) *bytes.Buffer { + t.Helper() + buf, ok := rctx.IO().ErrOut.(*bytes.Buffer) + if !ok { + t.Fatalf("ErrOut is not *bytes.Buffer: %T", rctx.IO().ErrOut) + } + return buf +} + +func registerCreateIssuedKey(reg *httpmock.Registry) { + reg.Register(&httpmock.Stub{ + Method: "POST", + URL: "/open-apis/spark/v1/apps/app_x/oapi_apikeys", + Body: map[string]interface{}{ + "code": 0, "msg": "", + "data": map[string]interface{}{ + "api_key_id": "k1", + "info": map[string]interface{}{ + "api_key_id": "k1", "name": "partner-test", + "api_key": "xxxxxxxxxxxx", "status": float64(1), + }, + }, + }, + }) +} + +func registerResetIssuedKey(reg *httpmock.Registry) { + reg.Register(&httpmock.Stub{ + Method: "POST", + URL: "/open-apis/spark/v1/apps/app_x/oapi_apikeys/1/refresh", + Body: map[string]interface{}{ + "code": 0, "msg": "", + "data": map[string]interface{}{ + "api_key": "xxxxxxxxxxxx", + "info": map[string]interface{}{"api_key_id": "k1", "name": "k", "api_key": "xxxxxxxxxxxx", "status": float64(1)}, + }, + }, + }) +} + +// In JSON mode the one-time notice rides inside the success envelope and +// nothing is written to stderr, so stdout stays one parseable JSON document +// even when a caller merges the streams with 2>&1. +func TestOpenAPIKeyCreate_JSON_NoticeInEnvelopeNotStderr(t *testing.T) { + rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, + createFlagDefs(), + map[string]string{"app-id": "app_x", "name": "partner-test"}) + registerCreateIssuedKey(reg) + stderrBuf := issuedKeyErrBuffer(t, rctx) + + if err := AppsOpenAPIKeyCreate.Execute(context.Background(), rctx); err != nil { + t.Fatalf("Execute() = %v", err) + } + + var env struct { + OK bool `json:"ok"` + Data map[string]interface{} `json:"data"` + } + if err := json.Unmarshal(stdoutBuf.Bytes(), &env); err != nil { + t.Fatalf("stdout must be a single pure JSON document: %v\n%s", err, stdoutBuf.String()) + } + if !env.OK { + t.Errorf("envelope ok = false, want true") + } + notice, _ := env.Data["notice"].(string) + if !strings.Contains(notice, shownOnceNotice) { + t.Errorf("data.notice must carry the one-time guidance, got %q", notice) + } + if env.Data["api_key"] != "xxxxxxxxxxxx" { + t.Errorf("data.api_key must carry the raw secret once, got %v", env.Data["api_key"]) + } + if strings.Contains(stderrBuf.String(), shownOnceNotice) || strings.Contains(stderrBuf.String(), "warning:") { + t.Errorf("json mode must not print the notice to stderr:\n%s", stderrBuf.String()) + } + // Even after `2>&1` the merged stream must still parse as JSON — the + // original bug had the warning prepended and broken decoding. + merged := append(append([]byte{}, stdoutBuf.Bytes()...), stderrBuf.Bytes()...) + var mergedEnv map[string]interface{} + if err := json.Unmarshal(merged, &mergedEnv); err != nil { + t.Errorf("merged stdout+stderr (2>&1) must still parse as JSON: %v\n%s", err, string(merged)) + } +} + +// Reset shares the same output path and must follow the same JSON contract. +func TestOpenAPIKeyReset_JSON_NoticeInEnvelopeNotStderr(t *testing.T) { + rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, + map[string]string{"app-id": "string", "key-id": "string", "yes": "bool"}, + map[string]string{"app-id": "app_x", "key-id": "1", "yes": "true"}) + registerResetIssuedKey(reg) + stderrBuf := issuedKeyErrBuffer(t, rctx) + + if err := AppsOpenAPIKeyReset.Execute(context.Background(), rctx); err != nil { + t.Fatalf("Execute() = %v", err) + } + + var env struct { + OK bool `json:"ok"` + Data map[string]interface{} `json:"data"` + } + if err := json.Unmarshal(stdoutBuf.Bytes(), &env); err != nil { + t.Fatalf("stdout must be a single pure JSON document: %v\n%s", err, stdoutBuf.String()) + } + if notice, _ := env.Data["notice"].(string); !strings.Contains(notice, shownOnceNotice) { + t.Errorf("data.notice must carry the one-time guidance, got %q", notice) + } + if strings.Contains(stderrBuf.String(), shownOnceNotice) { + t.Errorf("json mode must not print the notice to stderr:\n%s", stderrBuf.String()) + } +} + +// In human (pretty) mode the warning keeps going to stderr and stdout carries +// the readable key block — behavior is unchanged for interactive use. +func TestOpenAPIKeyCreate_Pretty_WarningOnStderr(t *testing.T) { + rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, + createFlagDefs(), + map[string]string{"app-id": "app_x", "name": "partner-test"}) + rctx.Format = "pretty" + registerCreateIssuedKey(reg) + stderrBuf := issuedKeyErrBuffer(t, rctx) + + if err := AppsOpenAPIKeyCreate.Execute(context.Background(), rctx); err != nil { + t.Fatalf("Execute() = %v", err) + } + + stderr := stderrBuf.String() + if !strings.Contains(stderr, "warning:") || !strings.Contains(stderr, shownOnceNotice) { + t.Errorf("pretty mode must keep the one-time warning on stderr:\n%s", stderr) + } + stdout := stdoutBuf.String() + if !strings.Contains(stdout, "API key:") || !strings.Contains(stdout, "xxxxxxxxxxxx") { + t.Errorf("pretty mode must print the readable key block to stdout:\n%s", stdout) + } + if strings.Contains(stdout, "\"ok\"") { + t.Errorf("pretty mode must not emit the JSON envelope:\n%s", stdout) + } +} From c95d2f2920d138c8d52ced20c0d0000fdebd1371 Mon Sep 17 00:00:00 2001 From: lvxinsheng Date: Thu, 5 Nov 2026 16:21:09 +0800 Subject: [PATCH 2/4] fix(apps): keep openapi-key one-time notice inside JSON envelope --- shortcuts/apps/apps_openapi_key_create.go | 25 +++++++++++++++++-- .../references/lark-apps-openapi-key.md | 7 +++--- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/shortcuts/apps/apps_openapi_key_create.go b/shortcuts/apps/apps_openapi_key_create.go index 173e412844..1151ff2624 100644 --- a/shortcuts/apps/apps_openapi_key_create.go +++ b/shortcuts/apps/apps_openapi_key_create.go @@ -82,8 +82,14 @@ func buildOpenAPIKeyCreateBody(rctx *common.RuntimeContext) (map[string]interfac return body, nil } +// apiKeyShownOnceNotice is the guidance attached to a freshly issued secret. +const apiKeyShownOnceNotice = "this api_key is shown only once and is NOT stored by lark-cli — copy it now and store it in your own secret manager." + // outputIssuedKey emits {api_key_id, api_key(raw, once), info(redacted)} for -// create/reset, plus a one-time stderr warning. The raw secret is NEVER persisted. +// create/reset. The one-time guidance must never break machine parsing of +// stdout: in JSON/NDJSON it rides inside the envelope as data.notice, while +// human formats (pretty/table/csv) keep the warning on stderr. The raw secret +// is NEVER persisted. func outputIssuedKey(rctx *common.RuntimeContext, data map[string]interface{}) error { info := common.GetMap(data, "info") raw := common.GetString(info, "api_key") @@ -95,13 +101,28 @@ func outputIssuedKey(rctx *common.RuntimeContext, data map[string]interface{}) e "api_key": raw, "info": redactKeyInfo(info), } - fmt.Fprintln(rctx.IO().ErrOut, "warning: this api_key is shown only once and is NOT stored by lark-cli — copy it now and store it in your own secret manager.") + if formatIsJSON(rctx.Format) { + out["notice"] = apiKeyShownOnceNotice + } else { + fmt.Fprintln(rctx.IO().ErrOut, "warning: "+apiKeyShownOnceNotice) + } rctx.OutFormat(out, nil, func(w io.Writer) { fmt.Fprintf(w, "API key ID: %v\nAPI key: %v (shown once)\n", out["api_key_id"], raw) }) return nil } +// formatIsJSON reports whether the selected --format renders the success +// envelope as JSON. The default format (empty string) is JSON. +func formatIsJSON(format string) bool { + switch format { + case "", "json", "ndjson": + return true + default: + return false + } +} + func firstNonEmpty(a, b string) string { if a != "" { return a diff --git a/skills/lark-apps/references/lark-apps-openapi-key.md b/skills/lark-apps/references/lark-apps-openapi-key.md index 3005e45865..a101a9f9d8 100644 --- a/skills/lark-apps/references/lark-apps-openapi-key.md +++ b/skills/lark-apps/references/lark-apps-openapi-key.md @@ -18,10 +18,9 @@ ## 脱敏口径(安全关键) - `list` / `get` / `update` / `enable` / `disable`:返回结构里 **无** `api_key` 字段,只有 `key_preview`(格式:`****` + 原始密钥末 4 位,如 `****5f4a`)。 -- `create` / `reset`:**仅** 在 `data.api_key`(顶层)返回原始密钥一次;同时在 stderr 打印一次性提示: - ``` - warning: this api_key is shown only once and is NOT stored by lark-cli — copy it now and store it in your own secret manager. - ``` +- `create` / `reset`:**仅** 在 `data.api_key`(顶层)返回原始密钥一次。一次性提示(shown only once)随 `--format` 分流,机器解析不要合并标准流: + - `--format json`(默认)/ `ndjson`:提示在 `data.notice`,stderr 不输出,stdout 始终是单一纯 JSON 文档;脚本只读 stdout 即可,即使用户写了 `2>&1` 合流仍可解析。 + - `--format pretty` / `table` / `csv`:提示以 `warning: this api_key is shown only once ...` 打到 stderr,stdout 保持人类可读输出。 - 原始密钥绝不写入 cache / config / recent / debug log / 错误信息。 ## 一次性密钥语义 From 97afe8dcb340a574c361a5fb90efefc4a46d8491 Mon Sep 17 00:00:00 2001 From: lvxinsheng Date: Thu, 5 Nov 2026 20:13:31 +0800 Subject: [PATCH 3/4] fix(apps): align one-time notice routing with emitter format resolution Only human formats (pretty/table/csv) print the one-time secret guidance to stderr; the JSON default, ndjson, and unrecognized values that the emitter falls back to JSON for now carry it in the emitted data. NDJSON exposes it as a top-level notice field since it has no envelope wrapper. --- shortcuts/apps/apps_openapi_key_create.go | 32 +++++---- .../apps/apps_openapi_key_notice_test.go | 69 +++++++++++++++++++ .../references/lark-apps-openapi-key.md | 3 +- 3 files changed, 90 insertions(+), 14 deletions(-) diff --git a/shortcuts/apps/apps_openapi_key_create.go b/shortcuts/apps/apps_openapi_key_create.go index 1151ff2624..f0eade8374 100644 --- a/shortcuts/apps/apps_openapi_key_create.go +++ b/shortcuts/apps/apps_openapi_key_create.go @@ -9,6 +9,7 @@ import ( "io" "strings" + "github.com/larksuite/cli/internal/output" "github.com/larksuite/cli/internal/validate" "github.com/larksuite/cli/shortcuts/common" ) @@ -87,9 +88,10 @@ const apiKeyShownOnceNotice = "this api_key is shown only once and is NOT stored // outputIssuedKey emits {api_key_id, api_key(raw, once), info(redacted)} for // create/reset. The one-time guidance must never break machine parsing of -// stdout: in JSON/NDJSON it rides inside the envelope as data.notice, while -// human formats (pretty/table/csv) keep the warning on stderr. The raw secret -// is NEVER persisted. +// stdout: machine formats (the JSON default, ndjson, and unknown values the +// emitter silently falls back to JSON for) carry it inside the returned data +// as notice, while human formats (pretty/table/csv) keep the warning on +// stderr. The raw secret is NEVER persisted. func outputIssuedKey(rctx *common.RuntimeContext, data map[string]interface{}) error { info := common.GetMap(data, "info") raw := common.GetString(info, "api_key") @@ -101,10 +103,10 @@ func outputIssuedKey(rctx *common.RuntimeContext, data map[string]interface{}) e "api_key": raw, "info": redactKeyInfo(info), } - if formatIsJSON(rctx.Format) { - out["notice"] = apiKeyShownOnceNotice - } else { + if issuedKeyUsesHumanWarning(rctx.Format) { fmt.Fprintln(rctx.IO().ErrOut, "warning: "+apiKeyShownOnceNotice) + } else { + out["notice"] = apiKeyShownOnceNotice } rctx.OutFormat(out, nil, func(w io.Writer) { fmt.Fprintf(w, "API key ID: %v\nAPI key: %v (shown once)\n", out["api_key_id"], raw) @@ -112,15 +114,19 @@ func outputIssuedKey(rctx *common.RuntimeContext, data map[string]interface{}) e return nil } -// formatIsJSON reports whether the selected --format renders the success -// envelope as JSON. The default format (empty string) is JSON. -func formatIsJSON(format string) bool { - switch format { - case "", "json", "ndjson": +// issuedKeyUsesHumanWarning reports whether the selected --format renders the +// issued key as human-readable output, in which case the one-time guidance +// stays on stderr. This mirrors the emitter's own format resolution in +// internal/output: pretty is intercepted before ParseFormat and never reaches +// it, while only table/csv are human formats among the parsed values. Every +// other value (the JSON default, ndjson, and unrecognized values that fall +// back to JSON) keeps the notice inside the emitted data. +func issuedKeyUsesHumanWarning(format string) bool { + if format == "pretty" { return true - default: - return false } + f, _ := output.ParseFormat(format) + return f == output.FormatTable || f == output.FormatCSV } func firstNonEmpty(a, b string) string { diff --git a/shortcuts/apps/apps_openapi_key_notice_test.go b/shortcuts/apps/apps_openapi_key_notice_test.go index 797528c776..921d795870 100644 --- a/shortcuts/apps/apps_openapi_key_notice_test.go +++ b/shortcuts/apps/apps_openapi_key_notice_test.go @@ -153,3 +153,72 @@ func TestOpenAPIKeyCreate_Pretty_WarningOnStderr(t *testing.T) { t.Errorf("pretty mode must not emit the JSON envelope:\n%s", stdout) } } + +// NDJSON is an envelope-less single-line record: the notice rides at the top +// level next to api_key (there is no data wrapper), and stderr stays clean. +func TestOpenAPIKeyCreate_NDJSON_TopLevelNoticeNotStderr(t *testing.T) { + rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, + createFlagDefs(), + map[string]string{"app-id": "app_x", "name": "partner-test"}) + rctx.Format = "ndjson" + registerCreateIssuedKey(reg) + stderrBuf := issuedKeyErrBuffer(t, rctx) + + if err := AppsOpenAPIKeyCreate.Execute(context.Background(), rctx); err != nil { + t.Fatalf("Execute() = %v", err) + } + + line := strings.TrimRight(stdoutBuf.String(), "\n") + if strings.Contains(line, "\n") { + t.Fatalf("ndjson must emit a single line, got:\n%s", stdoutBuf.String()) + } + var rec map[string]interface{} + if err := json.Unmarshal([]byte(line), &rec); err != nil { + t.Fatalf("ndjson line must be JSON: %v\n%s", err, line) + } + if _, ok := rec["data"]; ok { + t.Errorf("ndjson record must not carry the envelope data wrapper: %v", rec) + } + if notice, _ := rec["notice"].(string); !strings.Contains(notice, shownOnceNotice) { + t.Errorf("top-level notice must carry the one-time guidance, got %q", rec["notice"]) + } + if rec["api_key"] != "xxxxxxxxxxxx" { + t.Errorf("top-level api_key must carry the raw secret once, got %v", rec["api_key"]) + } + if strings.Contains(stderrBuf.String(), shownOnceNotice) { + t.Errorf("ndjson mode must not print the notice to stderr:\n%s", stderrBuf.String()) + } +} + +// An unrecognized --format is what the emitter itself falls back to JSON for, +// so the notice must follow that same resolution instead of leaking to +// stderr. The emitter's own unknown-format warning is out of scope. +func TestOpenAPIKeyCreate_UnknownFormat_FallsBackToEnvelopeNotice(t *testing.T) { + rctx, stdoutBuf, reg := newOpenAPIKeyRCtx(t, + createFlagDefs(), + map[string]string{"app-id": "app_x", "name": "partner-test"}) + rctx.Format = "bogus" + registerCreateIssuedKey(reg) + stderrBuf := issuedKeyErrBuffer(t, rctx) + + if err := AppsOpenAPIKeyCreate.Execute(context.Background(), rctx); err != nil { + t.Fatalf("Execute() = %v", err) + } + + var env struct { + OK bool `json:"ok"` + Data map[string]interface{} `json:"data"` + } + if err := json.Unmarshal(stdoutBuf.Bytes(), &env); err != nil { + t.Fatalf("unknown format must fall back to a JSON envelope: %v\n%s", err, stdoutBuf.String()) + } + if !env.OK { + t.Errorf("envelope ok = false, want true") + } + if notice, _ := env.Data["notice"].(string); !strings.Contains(notice, shownOnceNotice) { + t.Errorf("data.notice must carry the one-time guidance, got %q", env.Data["notice"]) + } + if strings.Contains(stderrBuf.String(), shownOnceNotice) { + t.Errorf("unknown-format fallback must not print the notice to stderr:\n%s", stderrBuf.String()) + } +} diff --git a/skills/lark-apps/references/lark-apps-openapi-key.md b/skills/lark-apps/references/lark-apps-openapi-key.md index a101a9f9d8..ee711030f4 100644 --- a/skills/lark-apps/references/lark-apps-openapi-key.md +++ b/skills/lark-apps/references/lark-apps-openapi-key.md @@ -19,7 +19,8 @@ - `list` / `get` / `update` / `enable` / `disable`:返回结构里 **无** `api_key` 字段,只有 `key_preview`(格式:`****` + 原始密钥末 4 位,如 `****5f4a`)。 - `create` / `reset`:**仅** 在 `data.api_key`(顶层)返回原始密钥一次。一次性提示(shown only once)随 `--format` 分流,机器解析不要合并标准流: - - `--format json`(默认)/ `ndjson`:提示在 `data.notice`,stderr 不输出,stdout 始终是单一纯 JSON 文档;脚本只读 stdout 即可,即使用户写了 `2>&1` 合流仍可解析。 + - `--format json`(默认):标准信封,提示在 `data.notice`,stderr 不输出,stdout 始终是单一纯 JSON 文档;脚本只读 stdout 即可,即使用户写了 `2>&1` 合流仍可解析。 + - `--format ndjson`:无信封单行记录、没有 `data` 外壳,提示在顶层 `notice` 字段(与 `api_key` 同级),stderr 同样不输出。 - `--format pretty` / `table` / `csv`:提示以 `warning: this api_key is shown only once ...` 打到 stderr,stdout 保持人类可读输出。 - 原始密钥绝不写入 cache / config / recent / debug log / 错误信息。 From 5a3a3ad8cb470c3147160ad3e22fb6500c720c74 Mon Sep 17 00:00:00 2001 From: lvxinsheng Date: Fri, 6 Nov 2026 15:54:22 +0800 Subject: [PATCH 4/4] docs(apps): clarify one-time key placement for json vs ndjson --- skills/lark-apps/references/lark-apps-openapi-key.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/skills/lark-apps/references/lark-apps-openapi-key.md b/skills/lark-apps/references/lark-apps-openapi-key.md index ee711030f4..737ff220e9 100644 --- a/skills/lark-apps/references/lark-apps-openapi-key.md +++ b/skills/lark-apps/references/lark-apps-openapi-key.md @@ -18,9 +18,9 @@ ## 脱敏口径(安全关键) - `list` / `get` / `update` / `enable` / `disable`:返回结构里 **无** `api_key` 字段,只有 `key_preview`(格式:`****` + 原始密钥末 4 位,如 `****5f4a`)。 -- `create` / `reset`:**仅** 在 `data.api_key`(顶层)返回原始密钥一次。一次性提示(shown only once)随 `--format` 分流,机器解析不要合并标准流: - - `--format json`(默认):标准信封,提示在 `data.notice`,stderr 不输出,stdout 始终是单一纯 JSON 文档;脚本只读 stdout 即可,即使用户写了 `2>&1` 合流仍可解析。 - - `--format ndjson`:无信封单行记录、没有 `data` 外壳,提示在顶层 `notice` 字段(与 `api_key` 同级),stderr 同样不输出。 +- `create` / `reset`:原始密钥只返回一次、CLI 绝不重存;字段位置随 `--format` 分流,机器解析不要合并标准流: + - `--format json`(默认):标准信封,密钥在 `data.api_key`、提示在 `data.notice`,stderr 不输出,stdout 始终是单一纯 JSON 文档;脚本只读 stdout 即可,即使用户写了 `2>&1` 合流仍可解析。 + - `--format ndjson`:无信封单行记录、没有 `data` 外壳,密钥与提示分别在顶层 `api_key`、`notice` 字段,stderr 同样不输出。 - `--format pretty` / `table` / `csv`:提示以 `warning: this api_key is shown only once ...` 打到 stderr,stdout 保持人类可读输出。 - 原始密钥绝不写入 cache / config / recent / debug log / 错误信息。