Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions shortcuts/apps/apps_openapi_key_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} 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
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

func firstNonEmpty(a, b string) string {
if a != "" {
return a
Expand Down
155 changes: 155 additions & 0 deletions shortcuts/apps/apps_openapi_key_notice_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
7 changes: 3 additions & 4 deletions skills/lark-apps/references/lark-apps-openapi-key.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 / 错误信息。

## 一次性密钥语义
Expand Down
Loading