Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86ff7e2f50 | ||
|
|
45cb237f74 | ||
|
|
bd711108f9 |
@@ -28,6 +28,17 @@ jobs:
|
||||
- name: Install archive tooling
|
||||
run: sudo apt-get update && sudo apt-get install -y zip unzip
|
||||
|
||||
- name: Install rcodesign (ad-hoc sign darwin binaries from Linux)
|
||||
run: |
|
||||
set -eu
|
||||
RCS_VERSION="0.27.0"
|
||||
curl -fsSL -o /tmp/rcodesign.tar.gz \
|
||||
"https://github.com/indygreg/apple-platform-rs/releases/download/apple-codesign%2F${RCS_VERSION}/apple-codesign-${RCS_VERSION}-x86_64-unknown-linux-musl.tar.gz"
|
||||
mkdir -p /tmp/rcodesign
|
||||
tar -xzf /tmp/rcodesign.tar.gz -C /tmp/rcodesign --strip-components=1
|
||||
sudo install -m 0755 /tmp/rcodesign/rcodesign /usr/local/bin/rcodesign
|
||||
rcodesign --version
|
||||
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
with:
|
||||
|
||||
@@ -4,6 +4,22 @@ All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is inspired by [Keep a Changelog](https://keepachangelog.com/) and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [1.0.32] - 2026-05-25
|
||||
|
||||
Two user-visible regressions resolved plus two AI-agent discoverability fixes. `dws drive upload` was returning `HTTP 403 SignatureDoesNotMatch` for any file whose MIME detects to a non-empty value — basically every real file — because the helper added a client-side `Content-Type` fallback whenever `drive.get_upload_info` returned an empty headers map. DingTalk drive's OSS presigned PUT URLs are signed against an empty `Content-Type` at signing time, so any client-supplied header makes the signature OSS recomputes diverge from the server-signed one, and the PUT is rejected (#347). On Apple Silicon, `dws upgrade` was aborting at the "解压并验证" step with `signal: killed` because GoReleaser cross-compiles `darwin/arm64` binaries on `ubuntu-latest` with no codesign step, and macOS 11+ `amfid` SIGKILLs unsigned arm64 binaries on first exec (#339) — the release pipeline now ad-hoc signs every darwin tarball, and the upgrade client self-heals if it ever encounters an unsigned binary again. On the AI-agent discoverability side, `dws aitable attachment upload-file` (the one-shot prepare + PUT + commit composite) is no longer hidden from `--help` — agents that only browse the command tree were getting stuck at the prepare-only `attachment upload` step, which returns an upload URL + fileToken but doesn't actually upload. And `dws --help` itself now surfaces the missing-command upgrade hint that the custom `renderRootHelp` had been silently dropping from cobra's `root.Long`.
|
||||
|
||||
### Added
|
||||
|
||||
- **`dws aitable attachment upload-file` is now visible in `dws aitable attachment --help`** (#347, `internal/helpers/aitable.go`) — the hardcoded one-shot composite (prepare + HTTP PUT + commit, returns `fileToken` directly) was previously marked `Hidden:true` and only reachable by agents that read `skills/references/products/aitable.md`. Agents that only discover commands via `--help` were getting stuck at the sibling envelope-generated `attachment upload` (prepare-only): they'd receive `uploadUrl` + `fileToken`, have no idea how to consume the URL, and either write the URL into the attachment field as if it were a token (wrong shape — the field expects `[{"fileToken":"ft_xxx"}]`) or fall back to "please use the UI" messages, which made `dws` look broken even though the capability was fully implemented. Unhiding mirrors the discoverability pattern `lark-cli base +record-upload-attachment` already follows. `Short` is tightened to explicitly mention the 3 steps it bundles; `Long` calls out the prepare-only sibling and recommends `upload-file` as the default for AI agents. The sibling `attachment upload` (prepare-only) keeps its envelope-generated registration but gets a new `Long` that states it is only step 1 of a 3-step flow, lists what an agent must do after (HTTP PUT to `uploadUrl`, then write `[{"fileToken":"ft_xxx"}]` into the attachment field), and points to `upload-file` as the recommended one-shot alternative. `TestAITableUploadFileCommandIsDiscoverable` in `internal/helpers/aitable_upload_file_test.go` guards against re-introducing `Hidden:true`.
|
||||
- **`dws --help` root output now surfaces the `dws upgrade` hint when no listed command fits** (#347, `internal/app/root.go` + `internal/app/root_help.go`) — `root.Long` is set to `"提示: 如果遇到能力缺失、命令报错、新功能未注册、或无法完成任务, 请先用 'dws upgrade' 升级到最新版本后再试. 钉钉 OpenAPI 和 dws CLI 持续迭代, 新能力和 bugfix 会先在新版本上线."`. The custom `renderRootHelp` (which replaces cobra's default template to render the services / utilities sections) had been silently dropping `root.Long`; restoring it costs one `Fprintln` after the command list, separated by a blank line. The natural failure mode for both agents and users staring at `dws --help` is to give up or hack around when none of the listed commands fit — but in many cases the right action is simply `dws upgrade`, because new capabilities and bugfixes ship continuously and a missing command is usually a stale-binary issue. `TestRenderRootHelpIncludesLong` in `internal/app/visibility_test.go` uses a sentinel `Long` string and asserts the rendered output contains it verbatim, so any future rewrite of the help renderer that drops `Long` fails this test immediately.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`dws drive upload` no longer fails with `HTTP 403 SignatureDoesNotMatch` on any non-empty MIME type** (#347, `internal/helpers/drive.go`) — `httpPutDriveFile` was setting `req.Header["Content-Type"] = fallbackMIME` whenever the prepare_upload response returned an empty headers map. DingTalk drive's OSS presigned URLs sign `StringToSign` against an empty `Content-Type` at signing time, so any client-side header makes the signature OSS recomputes at PUT time differ from the server's presignature, and the upload is rejected with `403 SignatureDoesNotMatch`. This broke every `dws drive upload` for any file whose MIME detects to a non-empty value (`image/png`, `application/pdf`, every common binary) — i.e. essentially every real upload. Fix: drop the `hasContentType` / `fallbackMIME` path entirely, trust the server's headers map as authoritative; empty map means "no client-side headers needed", do not infer. `httpPutDriveFile`'s signature loses the `fallbackMIME` parameter. Manual verification: `curl -X PUT -H "Content-Type:" --data-binary @file <same-presigned-url>` returns `HTTP 200`, proving the only difference was the client-side `Content-Type`. `TestHttpPutDriveFile_NoContentTypeWhenServerHeadersEmpty` guards the empty-map path; `TestHttpPutDriveFile_PassthroughServerHeaders` guards that server-provided `Content-Type` / `x-oss-*` headers are forwarded verbatim. Important: `internal/helpers/aitable.go`'s `upload-file` helper deliberately keeps its `Set("Content-Type", mimeType)` call — its OSS endpoint uses a different signing mode (server includes the client-declared MIME in the signature, verified across 12 file types — all succeed). The two helpers must not be unified without re-validating both endpoints.
|
||||
- **`dws upgrade` no longer dies with `signal: killed` on Apple Silicon after fetching the new binary** (#339) — GoReleaser cross-compiles `darwin/arm64` binaries on `ubuntu-latest` with no codesign step, and macOS 11+ on Apple Silicon requires at least an ad-hoc signature on every arm64 binary; `amfid` SIGKILLs unsigned arm64 binaries on first exec, which the upgrade client surfaces as `signal: killed` and aborts at the "解压并验证" step. Two layers of fix:
|
||||
- **Release-side ad-hoc signing** (`scripts/release/post-goreleaser.sh` + `.github/workflows/release.yml`) — after GoReleaser produces the per-platform tarballs, `post-goreleaser.sh` unpacks each `dws-darwin-*.tar.gz`, applies an ad-hoc signature (`codesign --force --sign -` locally, `rcodesign` in CI), deterministically repacks the tarball, and rewrites the matching line in `checksums.txt` so the checksum stays consistent with the resigned tarball. `release.yml` installs `rcodesign 0.27.0` before GoReleaser runs. Every 1.0.32+ tarball ships signed; the install regression is fixed at the source.
|
||||
- **Client-side self-heal in `validateNewBinary`** (`internal/app/upgrade.go`) — when running the freshly-extracted binary returns `signal: killed` on darwin, the validator retries once after running `codesign --force --sign -` on the binary and clearing the `com.apple.quarantine` xattr. This keeps `dws upgrade` working even if a future release ever skips the signing step again, and covers users upgrading from older unsigned binaries. `internal/app/upgrade_test.go` (+80 lines) covers the retry path end-to-end: a stripped binary exits 137 on first exec, `validateNewBinary` recovers via ad-hoc sign + xattr clear, the final binary shows `Signature=adhoc` and runs.
|
||||
|
||||
## [1.0.31] - 2026-05-21
|
||||
|
||||
Closes the last drive-surface gap with the Wukong edition: `dws drive upload` lands as a single-shot composite (`drive.get_upload_info` → HTTP PUT to OSS → `drive.commit_upload`) so a local file reaches DingTalk drive in one CLI invocation, no manual three-step orchestration. Two more drive commands — `dws drive list-spaces` (list visible drive spaces) and `dws drive delete` (delete a drive file, routed via `serverOverride` to the doc MCP server) — ship via the portal envelope; `dws cache refresh` once to pick them up. Companion skill docs teach the agent to recognise dingpan URLs of the form `alidocs.dingtalk.com/document/edit?dentryKey=…` / `…/document/preview?dentryKey=…` and pass the whole URL through to `--node` instead of trying to extract `dentryKey` by hand (the server interprets `dentryKey` and a bare `nodeId` differently — manual extraction was failing).
|
||||
|
||||
@@ -410,7 +410,7 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
|
||||
| Attendance | `attendance` | 4 | `record` `shift` `summary` `rules` | Clock-in records, shift schedules, attendance summary, group rules |
|
||||
| Ding | `ding` | 2 | `message` | Send / recall DING messages |
|
||||
| Report | `report` | 7 | `create` `list` `detail` `template` `stats` `sent` | Create reports, sent/received list, templates, statistics |
|
||||
| AI Tables | `aitable` | 41 | `base` `table` `record` `field` `view` `dashboard` `chart` `import` `export` `attachment` `template` | Full CRUD for Bases / datasheets / records / fields / views; charts & dashboards with public-share configs; data import/export; attachments; templates |
|
||||
| AI Tables | `aitable` | 42 | `base` `table` `record` `field` `view` `dashboard` `chart` `import` `export` `attachment` `template` | Full CRUD for Bases / datasheets / records / fields / views; charts & dashboards with public-share configs; data import/export; attachments (prepare-only `upload` + one-shot `upload-file`); templates |
|
||||
| Doc | `doc` | 21 | `search` `list` `info` `read` `create` `update` `upload` `download` `copy` `move` `rename` `file` `folder` `block` `comment` | Search / read / write docs, file & folder create, block-level editing, comments (list / create / reply / create-inline), upload / download |
|
||||
| Drive | `drive` | 9 | `list` `list-spaces` `info` `download` `mkdir` `upload` `upload-info` `commit` `delete` | DingTalk drive file ops: list spaces, list / info / download, create folders, one-shot `upload` (three-step composite) or two-phase `upload-info` + `commit`, delete |
|
||||
| Minutes | `minutes` | 19 | `list` `get` `update` `mind-graph` `speaker` `hot-word` `upload` | List AI meeting notes (mine / shared), details (info / summary / keywords / transcription / todos / batch), title/summary updates, mind map, speaker replace, hot-word, upload session |
|
||||
@@ -423,7 +423,7 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
|
||||
| Live | `live` | 1 | `stream` | DingTalk live streaming: list my lives |
|
||||
| Raw API | `api` | 1 | — | Call any DingTalk OpenAPI directly (api / oapi dual-form), with automatic app-level token management |
|
||||
|
||||
> **212 commands across 19 products.** Full listing with descriptions and usage scenarios: [`docs/command-index.md`](./docs/command-index.md). Run `dws --help` for the top-level tree, or `dws <service> --help` for subcommands.
|
||||
> **213 commands across 19 products.** Full listing with descriptions and usage scenarios: [`docs/command-index.md`](./docs/command-index.md). Run `dws --help` for the top-level tree, or `dws <service> --help` for subcommands.
|
||||
|
||||
> **Note on `chat bot`**: bot capabilities (`send-by-bot` / `recall-by-bot` / `add-bot` / `send-by-webhook` / bot search) are merged into the relevant `chat` subtrees (e.g. `dws chat message send-by-bot`, `dws chat group members add-bot`) so the agent-facing command surface stays flat and discoverable. There is no longer a separate top-level `bot` product.
|
||||
|
||||
|
||||
+2
-2
@@ -410,7 +410,7 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
|
||||
| 考勤 | `attendance` | 4 | `record` `shift` `summary` `rules` | 打卡记录、排班查询、考勤摘要、考勤组规则 |
|
||||
| DING | `ding` | 2 | `message` | 发送 / 撤回 DING 消息 |
|
||||
| 日志 | `report` | 7 | `create` `list` `detail` `template` `stats` `sent` | 创建日志、收发列表、模版、详情、统计 |
|
||||
| AI 表格 | `aitable` | 41 | `base` `table` `record` `field` `view` `dashboard` `chart` `import` `export` `attachment` `template` | Base / 数据表 / 记录 / 字段 / 视图 全量 CRUD;图表 + 仪表盘(含分享配置);数据导入导出;附件;模板 |
|
||||
| AI 表格 | `aitable` | 42 | `base` `table` `record` `field` `view` `dashboard` `chart` `import` `export` `attachment` `template` | Base / 数据表 / 记录 / 字段 / 视图 全量 CRUD;图表 + 仪表盘(含分享配置);数据导入导出;附件(仅获取凭证的 `upload` + 一键上传 `upload-file`);模板 |
|
||||
| 文档 | `doc` | 21 | `search` `list` `info` `read` `create` `update` `upload` `download` `copy` `move` `rename` `file` `folder` `block` `comment` | 搜索 / 读写文档、文件与文件夹创建、块级编辑、评论(list / create / reply / create-inline)、上传 / 下载 |
|
||||
| 钉盘 | `drive` | 9 | `list` `list-spaces` `info` `download` `mkdir` `upload` `upload-info` `commit` `delete` | 钉盘文件操作:列出空间、文件列表 / 详情 / 下载、创建文件夹、一键 `upload`(三步合成)或两阶段 `upload-info` + `commit`、删除 |
|
||||
| AI 听记 | `minutes` | 19 | `list` `get` `update` `mind-graph` `speaker` `hot-word` `upload` | 听记列表(我创建 / 共享给我)、详情(info / summary / keywords / transcription / todos / batch)、标题/摘要更新、思维导图、发言人替换、热词、上传会话 |
|
||||
@@ -423,7 +423,7 @@ dws chat message send-by-bot --robot-code BOT_CODE --group GROUP_ID \
|
||||
| 直播 | `live` | 1 | `stream` | 钉钉直播:查看我的直播列表 |
|
||||
| Raw API | `api` | 1 | — | 直接调用任意钉钉 OpenAPI(api / oapi 双形态),自动管理应用级 Token |
|
||||
|
||||
> **19 个产品,212 条命令。** 完整命令清单(带描述与使用场景):[`docs/command-index.md`](./docs/command-index.md)。运行 `dws --help` 查看顶层命令树,或 `dws <service> --help` 查看子命令。
|
||||
> **19 个产品,213 条命令。** 完整命令清单(带描述与使用场景):[`docs/command-index.md`](./docs/command-index.md)。运行 `dws --help` 查看顶层命令树,或 `dws <service> --help` 查看子命令。
|
||||
|
||||
> **关于 `chat bot`**:机器人能力(`send-by-bot` / `recall-by-bot` / `add-bot` / `send-by-webhook` / bot 搜索)已合并到对应的 `chat` 子树下(例如 `dws chat message send-by-bot`、`dws chat group members add-bot`),保持 agent 视角下的命令面扁平易发现。不再有独立的顶层 `bot` 产品。
|
||||
|
||||
|
||||
@@ -267,6 +267,7 @@ func NewRootCommandWithEngine(rootCtx context.Context, engine *pipeline.Engine)
|
||||
root := &cobra.Command{
|
||||
Use: "dws",
|
||||
Short: "DWS CLI",
|
||||
Long: `提示: 如果遇到能力缺失、命令报错、新功能未注册、或无法完成任务, 请先用 'dws upgrade' 升级到最新版本后再试. 钉钉 OpenAPI 和 dws CLI 持续迭代, 新能力和 bugfix 会先在新版本上线.`,
|
||||
Args: cobra.NoArgs,
|
||||
SilenceErrors: true,
|
||||
SilenceUsage: true,
|
||||
|
||||
@@ -82,6 +82,16 @@ func renderRootHelp(root *cobra.Command) {
|
||||
_, _ = fmt.Fprintln(w)
|
||||
}
|
||||
_, _ = fmt.Fprintln(w, `Use "dws <service> --help" for more information about a discovered MCP service or "dws <command> --help" for utility commands.`)
|
||||
|
||||
// Render root.Long after the command list so agents see the upgrade
|
||||
// hint (or any other root-level guidance) after browsing all available
|
||||
// commands and concluding none of them fit. Cobra's default help template
|
||||
// would render Long automatically; the custom SetHelpFunc above replaces
|
||||
// it and dropped this, so we restore it explicitly here.
|
||||
if long := strings.TrimSpace(root.Long); long != "" {
|
||||
_, _ = fmt.Fprintln(w)
|
||||
_, _ = fmt.Fprintln(w, long)
|
||||
}
|
||||
}
|
||||
|
||||
// resolveVisibleProducts returns the set of top-level product IDs that should
|
||||
|
||||
+44
-6
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -580,13 +581,18 @@ func validateNewBinary(binaryPath, expectedVersion string) error {
|
||||
return fmt.Errorf("设置执行权限失败: %w", err)
|
||||
}
|
||||
|
||||
// Try running the binary
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
out, err := exec.CommandContext(ctx, binaryPath, "version").CombinedOutput()
|
||||
out, err := tryExecVersion(binaryPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("二进制无法执行: %w", err)
|
||||
// Apple Silicon kills unsigned arm64 binaries with SIGKILL via amfid.
|
||||
// Repair the binary in-place (ad-hoc codesign + drop quarantine) and retry once.
|
||||
if runtime.GOOS == "darwin" && isLikelyAMFIKill(err) {
|
||||
if repairErr := repairDarwinBinary(binaryPath); repairErr == nil {
|
||||
out, err = tryExecVersion(binaryPath)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("二进制无法执行: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if !strings.Contains(string(out), expectedVersion) {
|
||||
@@ -596,6 +602,38 @@ func validateNewBinary(binaryPath, expectedVersion string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func tryExecVersion(binaryPath string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
return exec.CommandContext(ctx, binaryPath, "version").CombinedOutput()
|
||||
}
|
||||
|
||||
// isLikelyAMFIKill returns true when err looks like macOS amfid SIGKILL'ing an
|
||||
// unsigned binary. Go reports this as "signal: killed".
|
||||
func isLikelyAMFIKill(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
msg := err.Error()
|
||||
return strings.Contains(msg, "signal: killed") || strings.Contains(msg, "signal: kill")
|
||||
}
|
||||
|
||||
// repairDarwinBinary applies an ad-hoc codesign and clears the quarantine xattr.
|
||||
// Used as a self-heal step when an unsigned binary is killed by amfid on Apple Silicon.
|
||||
func repairDarwinBinary(binaryPath string) error {
|
||||
// Best-effort: strip quarantine. Failure is fine (attribute often absent).
|
||||
_ = exec.Command("xattr", "-d", "com.apple.quarantine", binaryPath).Run()
|
||||
|
||||
if _, err := exec.LookPath("codesign"); err != nil {
|
||||
return fmt.Errorf("codesign 不可用: %w", err)
|
||||
}
|
||||
out, err := exec.Command("codesign", "--force", "--sign", "-", binaryPath).CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("codesign 失败: %v: %s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractTarGz extracts a .tar.gz file using the system tar command.
|
||||
func extractTarGz(archivePath, destDir string) error {
|
||||
os.MkdirAll(destDir, 0755)
|
||||
|
||||
@@ -7,8 +7,11 @@ import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -428,3 +431,80 @@ func TestNewUpgradeCommand_Help(t *testing.T) {
|
||||
t.Error("help should contain --rollback")
|
||||
}
|
||||
}
|
||||
|
||||
// --- isLikelyAMFIKill ---
|
||||
|
||||
func TestIsLikelyAMFIKill(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{"nil error", nil, false},
|
||||
{"signal killed (real Go format)", errors.New("signal: killed"), true},
|
||||
{"signal kill variant", errors.New("signal: kill"), true},
|
||||
{"unrelated error", errors.New("exit status 1"), false},
|
||||
{"file not found", errors.New("no such file or directory"), false},
|
||||
{"wrapped killed in middle", errors.New("exec: signal: killed: cleanup"), true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := isLikelyAMFIKill(tt.err); got != tt.want {
|
||||
t.Errorf("isLikelyAMFIKill(%v) = %v, want %v", tt.err, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- validateNewBinary self-heal (darwin only) ---
|
||||
//
|
||||
// On macOS, an unsigned arm64 binary is SIGKILL'd by amfid. This test verifies
|
||||
// validateNewBinary recovers via repairDarwinBinary (ad-hoc codesign) and
|
||||
// successfully re-executes the binary. We use go itself as a stand-in for the
|
||||
// new dws binary — it's a real signed Mach-O we can strip and re-sign.
|
||||
|
||||
func TestValidateNewBinary_RecoversFromUnsignedDarwin(t *testing.T) {
|
||||
if runtime.GOOS != "darwin" {
|
||||
t.Skip("amfid SIGKILL only happens on macOS")
|
||||
}
|
||||
if _, err := exec.LookPath("codesign"); err != nil {
|
||||
t.Skip("codesign not available")
|
||||
}
|
||||
|
||||
// Build a fresh dws binary into a temp dir.
|
||||
tmpDir := t.TempDir()
|
||||
bin := filepath.Join(tmpDir, "dws-test")
|
||||
|
||||
// Locate repo root from this test file's location.
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatalf("getwd: %v", err)
|
||||
}
|
||||
repoRoot := filepath.Join(wd, "..", "..")
|
||||
cmd := exec.Command("go", "build", "-o", bin, "./cmd")
|
||||
cmd.Dir = repoRoot
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("go build failed: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// Strip signature to reproduce the unsigned state from CI cross-compilation.
|
||||
if out, err := exec.Command("codesign", "--remove-signature", bin).CombinedOutput(); err != nil {
|
||||
t.Fatalf("strip signature: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// Sanity: confirm direct exec is killed.
|
||||
if _, err := tryExecVersion(bin); err == nil {
|
||||
t.Skip("unsigned binary executed without amfid kill — likely Intel Mac or SIP disabled")
|
||||
}
|
||||
|
||||
// validateNewBinary should self-heal and succeed.
|
||||
if err := validateNewBinary(bin, "dev"); err != nil {
|
||||
t.Fatalf("validateNewBinary did not recover: %v", err)
|
||||
}
|
||||
|
||||
// Verify the binary now has an ad-hoc signature.
|
||||
out, _ := exec.Command("codesign", "-dv", bin).CombinedOutput()
|
||||
if !strings.Contains(string(out), "Signature=adhoc") {
|
||||
t.Errorf("expected adhoc signature, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/market"
|
||||
@@ -123,3 +125,27 @@ func commandNames(cmds []*cobra.Command) []string {
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// TestRenderRootHelpIncludesLong guards that renderRootHelp surfaces the
|
||||
// root command's Long description in `dws --help` output. The custom
|
||||
// SetHelpFunc in root_help.go replaces cobra's default help template, which
|
||||
// previously caused root.Long to be silently dropped. The production
|
||||
// root.Long carries the "use 'dws upgrade' if a command is missing or
|
||||
// failing" hint that AI agents rely on when they cannot find a suitable
|
||||
// command — if this test fails after a help-rendering change, agents will
|
||||
// silently lose that guidance.
|
||||
func TestRenderRootHelpIncludesLong(t *testing.T) {
|
||||
const sentinel = "SENTINEL-LONG-MUST-APPEAR-IN-HELP"
|
||||
root := &cobra.Command{
|
||||
Use: "dws",
|
||||
Long: sentinel,
|
||||
}
|
||||
var out bytes.Buffer
|
||||
root.SetOut(&out)
|
||||
|
||||
renderRootHelp(root)
|
||||
|
||||
if !strings.Contains(out.String(), sentinel) {
|
||||
t.Fatalf("renderRootHelp must render root.Long verbatim in --help output; got:\n%s", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,13 +393,15 @@ func confirmDeletePrompt(cmd *cobra.Command, resourceType, resourceName string)
|
||||
|
||||
func newAITableUploadFileCommand(runner executor.Runner) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "upload-file",
|
||||
Short: i18n.T("本地文件一键上传到 AITable 附件字段"),
|
||||
Hidden: true,
|
||||
Long: `完整流程 (自动执行 3 步):
|
||||
1. dws aitable attachment upload → 获取 uploadUrl + fileToken
|
||||
2. HTTP PUT 上传文件到 OSS
|
||||
3. 返回 fileToken,可直接用于 record create/update`,
|
||||
Use: "upload-file",
|
||||
Short: i18n.T("本地文件一键上传到 AITable 附件字段 (3 步自动合一: prepare + PUT + 返回 fileToken)"),
|
||||
Long: `本地文件一键上传到 AITable 附件字段, 一行命令完成 3 步:
|
||||
1. prepare_attachment_upload → 获取 OSS 上传地址 uploadUrl + fileToken
|
||||
2. HTTP PUT 文件二进制 → OSS
|
||||
3. 返回 fileToken (可直接用于 dws aitable record create/update 的 attachment 字段)
|
||||
|
||||
推荐 AI Agent 优先使用此命令上传单个附件, 比手动调用 attachment upload (只 prepare)
|
||||
之后再自己 PUT 文件二进制要可靠得多.`,
|
||||
Example: " dws aitable attachment upload-file --base-id <BASE_ID> --file ./report.pdf",
|
||||
Args: cobra.NoArgs,
|
||||
DisableAutoGenTag: true,
|
||||
|
||||
@@ -594,8 +594,17 @@ func newAitableTemplateSearchCommand(runner executor.Runner) *cobra.Command {
|
||||
|
||||
func newAITableAttachmentUploadCommand(runner executor.Runner) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "upload",
|
||||
Short: i18n.T("准备附件上传"),
|
||||
Use: "upload",
|
||||
Short: i18n.T("准备附件上传 (仅返回 uploadUrl + fileToken, 不上传文件)"),
|
||||
Long: i18n.T(`准备附件上传 — 3 步流程的第 1 步.
|
||||
|
||||
本命令只调用 prepare_attachment_upload, 返回 OSS 上传地址 uploadUrl 和 fileToken,
|
||||
不实际上传文件二进制. 拿到响应后你还需要:
|
||||
2. HTTP PUT 文件二进制 → uploadUrl
|
||||
3. 把 fileToken 填到 record 的 attachment 字段, 格式 [{"fileToken":"ft_xxx"}]
|
||||
|
||||
推荐 AI Agent 直接用 'dws aitable attachment upload-file --base-id X --file ./report.pdf'
|
||||
一行完成 3 步, 不用自己处理 HTTP PUT 二进制.`),
|
||||
Example: " dws aitable attachment upload --base-id BASE_ID --file-name report.pdf --size 1024",
|
||||
Args: cobra.NoArgs,
|
||||
DisableAutoGenTag: true,
|
||||
|
||||
@@ -92,3 +92,18 @@ func TestAITableUploadFileUnwrapsRuntimeContent(t *testing.T) {
|
||||
t.Fatalf("fileToken = %#v, want ft_test_123", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAITableUploadFileCommandIsDiscoverable guards that the upload-file
|
||||
// command stays visible via --help. It was previously marked Hidden:true,
|
||||
// which caused AI agents (e.g. Lobster) to discover only the prepare-only
|
||||
// `attachment upload` command and get stuck after step 1, falling back to
|
||||
// "please use the UI to upload". Keeping this command discoverable is the
|
||||
// single change that unlocks the end-to-end attachment upload flow for
|
||||
// agents that only read --help.
|
||||
func TestAITableUploadFileCommandIsDiscoverable(t *testing.T) {
|
||||
runner := &uploadFileRunner{}
|
||||
cmd := newAITableUploadFileCommand(runner)
|
||||
if cmd.Hidden {
|
||||
t.Fatalf("upload-file command must not be Hidden: AI agents discover it via --help; hiding it strands them after step 1 (see commit message for full rationale)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,7 +190,7 @@ func runDriveUpload(cmd *cobra.Command, runner executor.Runner) error {
|
||||
|
||||
// Step 2: HTTP PUT to OSS
|
||||
fmt.Fprintln(os.Stderr, "[2/3] 上传文件到 OSS...")
|
||||
if err := httpPutDriveFile(cmd.Context(), resourceURL, ossHeaders, absPath, fileSize, mimeType); err != nil {
|
||||
if err := httpPutDriveFile(cmd.Context(), resourceURL, ossHeaders, absPath, fileSize); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -303,7 +303,26 @@ func parseDriveUploadInfo(resp map[string]any) (resourceURL, uploadID string, he
|
||||
return
|
||||
}
|
||||
|
||||
func httpPutDriveFile(ctx context.Context, resourceURL string, headers map[string]string, filePath string, fileSize int64, fallbackMIME string) error {
|
||||
// httpPutDriveFile uploads the file at filePath to a DingTalk drive OSS presigned URL.
|
||||
//
|
||||
// PROTOCOL CONTRACT: the headers map is authoritative. It contains the exact
|
||||
// and complete set of HTTP headers required for the upload. An empty map means
|
||||
// "no client-side headers needed" (this is the normal case for DingTalk drive,
|
||||
// where the signature is embedded in the URL query string).
|
||||
//
|
||||
// DO NOT add Content-Type or any other client-inferred header here. DingTalk
|
||||
// drive uses OSS v1 presigned URLs whose StringToSign includes the Content-Type
|
||||
// header that the server saw at signing time (typically empty). Any client-side
|
||||
// addition of Content-Type makes the signature computed by OSS at PUT time
|
||||
// differ from the server's presignature → 403 SignatureDoesNotMatch.
|
||||
//
|
||||
// If a future OSS endpoint requires header-based signing (Authorization header
|
||||
// instead of URL signing), introduce a separate helper rather than reintroducing
|
||||
// a fallback here. The aitable attachment upload helper in aitable.go does set
|
||||
// Content-Type because its OSS endpoint uses a different signing mode where the
|
||||
// server includes the client-declared mime in its signature computation; do not
|
||||
// unify the two helpers without re-validating both endpoints.
|
||||
func httpPutDriveFile(ctx context.Context, resourceURL string, headers map[string]string, filePath string, fileSize int64) error {
|
||||
f, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("无法打开文件: %w", err)
|
||||
@@ -315,15 +334,8 @@ func httpPutDriveFile(ctx context.Context, resourceURL string, headers map[strin
|
||||
return fmt.Errorf("构建 OSS 上传请求失败: %w", err)
|
||||
}
|
||||
req.ContentLength = fileSize
|
||||
hasContentType := false
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
if strings.EqualFold(k, "Content-Type") {
|
||||
hasContentType = true
|
||||
}
|
||||
}
|
||||
if !hasContentType && fallbackMIME != "" {
|
||||
req.Header.Set("Content-Type", fallbackMIME)
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 10 * time.Minute}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// Copyright 2026 Alibaba Group
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestHttpPutDriveFile_NoContentTypeWhenServerHeadersEmpty guards the fix for
|
||||
// the SignatureDoesNotMatch bug on DingTalk drive presigned OSS uploads.
|
||||
//
|
||||
// DingTalk drive returns an OSS presigned URL (signature in the URL query
|
||||
// string) and signs the upload with Content-Type left empty. Any client-side
|
||||
// Content-Type makes the signature OSS computes at PUT time differ from the
|
||||
// server presignature → 403 SignatureDoesNotMatch.
|
||||
//
|
||||
// Previous behavior: httpPutDriveFile fell back to a client-inferred mime when
|
||||
// the server's `headers` map was empty, which is the normal case for DingTalk
|
||||
// drive (`{"headers": {}}`). That fallback broke every PNG / image / typed-mime
|
||||
// upload in production.
|
||||
//
|
||||
// This test asserts the PUT request body contains no Content-Type header when
|
||||
// the server returns an empty headers map. If a future change reintroduces
|
||||
// client-side Content-Type fallback this test will fail loudly.
|
||||
func TestHttpPutDriveFile_NoContentTypeWhenServerHeadersEmpty(t *testing.T) {
|
||||
var receivedContentType string
|
||||
var receivedBody []byte
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPut {
|
||||
t.Fatalf("method = %s, want PUT", r.Method)
|
||||
}
|
||||
receivedContentType = r.Header.Get("Content-Type")
|
||||
receivedBody, _ = io.ReadAll(r.Body)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
tmp := filepath.Join(t.TempDir(), "test.png")
|
||||
wantBody := []byte("fake-png-bytes")
|
||||
if err := os.WriteFile(tmp, wantBody, 0o644); err != nil {
|
||||
t.Fatalf("WriteFile() error = %v", err)
|
||||
}
|
||||
|
||||
err := httpPutDriveFile(context.Background(), server.URL, map[string]string{}, tmp, int64(len(wantBody)))
|
||||
if err != nil {
|
||||
t.Fatalf("httpPutDriveFile() error = %v", err)
|
||||
}
|
||||
if receivedContentType != "" {
|
||||
t.Fatalf("Content-Type = %q, want empty (presigned URL signing requires no client-inferred headers)", receivedContentType)
|
||||
}
|
||||
if string(receivedBody) != string(wantBody) {
|
||||
t.Fatalf("uploaded body = %q, want %q", string(receivedBody), string(wantBody))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHttpPutDriveFile_PassthroughServerHeaders verifies that any header the
|
||||
// server returns in its prepare response is forwarded verbatim to the PUT
|
||||
// request. This is the symmetric guarantee to the test above: clients must
|
||||
// neither add nor drop headers — they pass through exactly what the server
|
||||
// declared.
|
||||
func TestHttpPutDriveFile_PassthroughServerHeaders(t *testing.T) {
|
||||
var receivedHeaders http.Header
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
receivedHeaders = r.Header.Clone()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
tmp := filepath.Join(t.TempDir(), "test.bin")
|
||||
if err := os.WriteFile(tmp, []byte("x"), 0o644); err != nil {
|
||||
t.Fatalf("WriteFile() error = %v", err)
|
||||
}
|
||||
|
||||
headers := map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
"x-oss-storage-class": "Standard",
|
||||
}
|
||||
err := httpPutDriveFile(context.Background(), server.URL, headers, tmp, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("httpPutDriveFile() error = %v", err)
|
||||
}
|
||||
if got := receivedHeaders.Get("Content-Type"); got != "application/octet-stream" {
|
||||
t.Fatalf("Content-Type = %q, want application/octet-stream", got)
|
||||
}
|
||||
if got := receivedHeaders.Get("x-oss-storage-class"); got != "Standard" {
|
||||
t.Fatalf("x-oss-storage-class = %q, want Standard", got)
|
||||
}
|
||||
}
|
||||
@@ -174,6 +174,74 @@ create_skills_zip() {
|
||||
)
|
||||
}
|
||||
|
||||
# ---------- darwin ad-hoc signing ----------
|
||||
#
|
||||
# Unsigned arm64 binaries are SIGKILL'd by amfid on Apple Silicon (macOS 11+).
|
||||
# We unpack each dws-darwin-*.tar.gz, ad-hoc sign the dws binary, repack
|
||||
# deterministically, and rewrite the corresponding line in checksums.txt.
|
||||
|
||||
sign_one_darwin_binary() {
|
||||
bin="$1"
|
||||
if command -v codesign >/dev/null 2>&1; then
|
||||
codesign --force --sign - "$bin"
|
||||
return
|
||||
fi
|
||||
if command -v rcodesign >/dev/null 2>&1; then
|
||||
rcodesign sign "$bin"
|
||||
return
|
||||
fi
|
||||
err "neither codesign nor rcodesign found — install rcodesign (cargo install apple-codesign) to ad-hoc sign darwin builds"
|
||||
}
|
||||
|
||||
update_checksum_entry() {
|
||||
filename="$1"
|
||||
new_sha="$2"
|
||||
checksum_path="$DIST_DIR/checksums.txt"
|
||||
[ -f "$checksum_path" ] || return 0
|
||||
tmp="$(mktemp)"
|
||||
grep -v " ${filename}\$" "$checksum_path" > "$tmp" 2>/dev/null || true
|
||||
printf '%s %s\n' "$new_sha" "$filename" >> "$tmp"
|
||||
mv "$tmp" "$checksum_path"
|
||||
}
|
||||
|
||||
sign_darwin_archives() {
|
||||
work="$(mktemp -d)"
|
||||
found_any=0
|
||||
for archive in "$DIST_DIR"/dws-darwin-*.tar.gz; do
|
||||
[ -f "$archive" ] || continue
|
||||
found_any=1
|
||||
name="$(basename "$archive")"
|
||||
say " signing $name"
|
||||
|
||||
stage="$work/${name%.tar.gz}"
|
||||
rm -rf "$stage"
|
||||
mkdir -p "$stage"
|
||||
tar -xzf "$archive" -C "$stage"
|
||||
|
||||
bin="$stage/dws"
|
||||
if [ ! -f "$bin" ]; then
|
||||
err "dws binary not found inside $name after extraction"
|
||||
fi
|
||||
sign_one_darwin_binary "$bin"
|
||||
|
||||
# Repack deterministically: sorted file order, zeroed owner/mtime so
|
||||
# rerunning the script produces byte-identical archives (and sha256s).
|
||||
(
|
||||
cd "$stage" \
|
||||
&& tar --sort=name --owner=0 --group=0 --numeric-owner \
|
||||
--mtime='2020-01-01 00:00Z' \
|
||||
-czf "$archive.new" .
|
||||
)
|
||||
mv "$archive.new" "$archive"
|
||||
|
||||
update_checksum_entry "$name" "$(sha256_file "$archive")"
|
||||
done
|
||||
rm -rf "$work"
|
||||
if [ "$found_any" -eq 0 ]; then
|
||||
say " (no darwin archives found, skipping)"
|
||||
fi
|
||||
}
|
||||
|
||||
write_checksums() {
|
||||
checksum_path="$DIST_DIR/checksums.txt"
|
||||
# Append skills zip checksum to goreleaser's checksums file
|
||||
@@ -186,6 +254,9 @@ write_checksums() {
|
||||
|
||||
version="$(resolve_version)"
|
||||
|
||||
say "==> Ad-hoc signing darwin binaries"
|
||||
sign_darwin_archives
|
||||
|
||||
say "==> Creating skills zip"
|
||||
create_skills_zip
|
||||
|
||||
|
||||
Reference in New Issue
Block a user