Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
31 changes: 29 additions & 2 deletions shortcuts/apps/apps_openapi_key_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -82,8 +83,15 @@ 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: 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")
Expand All @@ -95,13 +103,32 @@ 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 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)
})
return nil
}

// 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
}
f, _ := output.ParseFormat(format)
return f == output.FormatTable || f == output.FormatCSV
}

func firstNonEmpty(a, b string) string {
if a != "" {
return a
Expand Down
224 changes: 224 additions & 0 deletions shortcuts/apps/apps_openapi_key_notice_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
// 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)
}
}

// 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())
}
}
8 changes: 4 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,10 @@
## 脱敏口径(安全关键)

- `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`(默认):标准信封,提示在 `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 / 错误信息。

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