Compare commits

..
Author SHA1 Message Date
修雨 d2f87ff1dc test: run quality regressions in platform coverage 2026-07-16 09:33:22 +08:00
修雨 fcf795f17b Merge remote-tracking branch 'origin/main' into codex/fix-quality-eval-regressions
# Conflicts:
#	internal/cli/schema_agent_metadata/index.json
#	internal/cli/schema_agent_metadata_audit.json
#	internal/cli/schema_catalog.json
2026-07-16 09:20:58 +08:00
修雨 9daa95f2fd Merge origin/main into codex/fix-quality-eval-regressions 2026-07-16 00:08:24 +08:00
修雨 ec380b7e45 fix: make Windows helper coverage portable 2026-07-15 18:17:43 +08:00
修雨 44a3295aee Merge branch 'main' of https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli into codex/fix-quality-eval-regressions
# Conflicts:
#	internal/cli/schema_agent_metadata/index.json
#	internal/cli/schema_agent_metadata_audit.json
#	internal/cli/schema_catalog.json
2026-07-15 17:33:41 +08:00
修雨 282c9154d6 fix: expose todo attachment listing schema 2026-07-15 17:15:43 +08:00
修雨 5e682ac381 docs: record invalid target fixes 2026-07-15 14:28:45 +08:00
修雨 1167c1cfab fix: surface invalid sheet and todo targets 2026-07-15 12:08:02 +08:00
653 changed files with 39001 additions and 95729 deletions
-7
View File
@@ -5,13 +5,6 @@
## Verification
For an exact in-place `CHANGELOG.md`-only pull request, the full-suite checks
may be marked `N/A`, but the targeted CHANGELOG check is required. For every
other pull request, mark the targeted check `N/A` and complete the applicable
full-suite checks.
- [ ] Exact `CHANGELOG.md`-only check (otherwise `N/A`):
`./scripts/policy/check-changelog-pr.sh --fast-path "$(git merge-base HEAD origin/main)" HEAD`
- [ ] `make build`
- [ ] `make lint`
- [ ] `make test`
-6
View File
@@ -1,6 +0,0 @@
paths:
.github/workflows/release.yml:
ignore:
# GitHub Actions added concurrency.queue in 2026. actionlint v1.7.12's
# bundled workflow schema has not caught up with the platform syntax.
- 'unexpected key "queue" for "concurrency" section'
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="114" height="20" role="img" aria-label="coverage: 100.0%"><title>coverage: 100.0%</title><filter id="blur"><feGaussianBlur stdDeviation="16"/></filter><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="114" height="20" rx="3"/></clipPath><g clip-path="url(#r)"><rect width="61" height="20" fill="#555"/><rect x="61" width="53" height="20" fill="#4b0"/><rect width="114" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><g transform="scale(.1)"><g aria-hidden="true" fill="#010101"><text x="315" y="150" fill-opacity=".8" filter="url(#blur)" textLength="510">coverage</text><text x="315" y="150" fill-opacity=".3" textLength="510">coverage</text></g><text x="315" y="140" textLength="510">coverage</text></g><g transform="scale(.1)"><g aria-hidden="true" fill="#010101"><text x="865" y="150" fill-opacity=".8" filter="url(#blur)" textLength="430">100.0%</text><text x="865" y="150" fill-opacity=".3" textLength="430">100.0%</text></g><text x="865" y="140" textLength="430">100.0%</text></g></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="108" height="20" role="img" aria-label="coverage: 54.2%"><title>coverage: 54.2%</title><filter id="blur"><feGaussianBlur in="SourceGraphic" stdDeviation="16"/></filter><linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="r"><rect width="108" height="20" rx="3" fill="#fff"/></clipPath><g clip-path="url(#r)"><rect width="61" height="20" fill="#555"/><rect x="61" width="47" height="20" fill="#dd4343"/><rect width="108" height="20" fill="url(#s)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".80" filter="url(#blur)" transform="scale(.1)" textLength="510">coverage</text><text aria-hidden="true" x="315" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="510">coverage</text><text x="315" y="140" transform="scale(.1)" fill="#fff" textLength="510">coverage</text><text aria-hidden="true" x="835" y="150" fill="#010101" fill-opacity=".80" filter="url(#blur)" transform="scale(.1)" textLength="370">54.2%</text><text aria-hidden="true" x="835" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="370">54.2%</text><text x="835" y="140" transform="scale(.1)" fill="#fff" textLength="370">54.2%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

+48 -91
View File
@@ -1,11 +1,8 @@
name: Code Admission — AI Behavior
name: AI Behavior Check
on:
pull_request_target:
types: [opened, synchronize, reopened, labeled, unlabeled]
push:
branches:
- main
permissions:
contents: read
@@ -14,7 +11,7 @@ permissions:
jobs:
ai-behavior-check:
name: AI Behavior
name: AI Behavior Policy Evaluator
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
@@ -24,108 +21,68 @@ jobs:
uses: actions/github-script@v7
with:
script: |
const pullRequest = context.payload.pull_request;
const sha = context.eventName === 'push' ? context.sha : pullRequest.head.sha;
const sha = context.payload.pull_request.head.sha;
const setStatus = (state, description) =>
github.rest.repos.createCommitStatus({
owner: context.repo.owner,
repo: context.repo.repo,
sha,
state,
context: 'AI Behavior',
context: 'AI Behavior Check',
description,
});
await setStatus('pending', 'Evaluating AI-generated PR boundaries');
if (context.eventName === 'push') {
await setStatus('success', 'Not applicable to the protected main push');
core.notice('AI Behavior is a PR policy; the main push context is sealed.');
const labels = context.payload.pull_request.labels.map(({ name }) => name);
if (!labels.includes('ai-generated')) {
await setStatus('success', 'Not labeled ai-generated');
core.notice('Not an ai-generated PR; no AI-only policy applied.');
return;
}
try {
const expectedHead = pullRequest.head.sha;
const expectedBase = pullRequest.base.sha;
const currentPull = async (phase) => {
const { data: pull } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
});
if (pull.head.sha !== expectedHead || pull.base.sha !== expectedBase) {
throw new Error(
`Pull request revision changed during ${phase}: ` +
`expected base/head ${expectedBase}/${expectedHead}, ` +
`got ${pull.base.sha}/${pull.head.sha}`
);
}
return pull;
};
const before = await currentPull('pre-policy check');
const labels = before.labels.map(({ name }) => name);
if (!labels.includes('ai-generated')) {
await setStatus('success', 'Not labeled ai-generated');
core.notice('Not an ai-generated PR; no AI-only policy applied.');
return;
}
const files = await github.paginate(github.rest.pulls.listFiles, {
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
per_page: 100,
});
await currentPull('post-policy check');
const maxChangedFiles = 30;
if (files.length > maxChangedFiles) {
await setStatus(
'failure',
`Changes ${files.length} files; limit is ${maxChangedFiles}`
);
core.setFailed(
`AI-generated PR changes ${files.length} files; limit is ${maxChangedFiles}.`
);
return;
}
const isProtectedPath = (filename) =>
typeof filename === 'string' &&
(
filename.startsWith('.github/workflows/') ||
filename.startsWith('scripts/ci/') ||
filename.startsWith('scripts/policy/') ||
filename.startsWith('scripts/release/') ||
filename === 'test/fixtures/cli-interface-baseline.txt' ||
filename === '.goreleaser.yaml' ||
filename === 'Makefile'
);
const protectedPaths = [...new Set(
files
.flatMap(({ filename, previous_filename }) => [filename, previous_filename])
.filter(isProtectedPath)
)];
if (protectedPaths.length > 0) {
await setStatus('failure', 'Modifies protected release/CI infrastructure');
core.setFailed(
'AI-generated PR modifies protected release/CI infrastructure:\n' +
protectedPaths.map((filename) => ` - ${filename}`).join('\n') +
'\nSplit these changes into a human-owned PR with explicit review.'
);
return;
}
const files = await github.paginate(github.rest.pulls.listFiles, {
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
per_page: 100,
});
const maxChangedFiles = 30;
if (files.length > maxChangedFiles) {
await setStatus(
'success',
`Passed with ${files.length} changed files (limit ${maxChangedFiles})`
'failure',
`Changes ${files.length} files; limit is ${maxChangedFiles}`
);
core.notice(
`AI behavior check passed (${files.length} changed files; limit ${maxChangedFiles}).`
core.setFailed(
`AI-generated PR changes ${files.length} files; limit is ${maxChangedFiles}.`
);
} catch (error) {
await setStatus('error', 'Could not evaluate the exact pull request revision');
throw error;
return;
}
const protectedPaths = files
.map(({ filename }) => filename)
.filter((filename) =>
filename.startsWith('.github/workflows/') ||
filename.startsWith('scripts/release/') ||
filename === '.goreleaser.yaml' ||
filename === 'Makefile'
);
if (protectedPaths.length > 0) {
await setStatus('failure', 'Modifies protected release/CI infrastructure');
core.setFailed(
'AI-generated PR modifies protected release/CI infrastructure:\n' +
protectedPaths.map((filename) => ` - ${filename}`).join('\n') +
'\nSplit these changes into a human-owned PR with explicit review.'
);
return;
}
await setStatus(
'success',
`Passed with ${files.length} changed files (limit ${maxChangedFiles})`
);
core.notice(
`AI behavior check passed (${files.length} changed files; limit ${maxChangedFiles}).`
);
+129 -597
View File
@@ -9,189 +9,39 @@ on:
permissions:
contents: read
concurrency:
group: ci-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
pull-requests: read
outputs:
changelog_only: ${{ steps.classify.outputs.changelog_only }}
changelog_changed: ${{ steps.classify.outputs.changelog_changed }}
platform_sensitive: ${{ steps.classify.outputs.platform_sensitive }}
steps:
- name: Classify pull request scope
id: classify
uses: actions/github-script@v7
with:
script: |
let changelogOnly = false;
let changelogChanged = false;
let platformSensitive = context.eventName === 'push';
let files = [];
if (context.eventName === 'pull_request') {
const expectedHead = context.payload.pull_request.head.sha;
const expectedBase = context.payload.pull_request.base.sha;
const assertCurrentRevision = async (phase) => {
const { data: pull } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
});
if (pull.head.sha !== expectedHead || pull.base.sha !== expectedBase) {
throw new Error(
`Pull request revision changed during ${phase}: ` +
`expected base/head ${expectedBase}/${expectedHead}, ` +
`got ${pull.base.sha}/${pull.head.sha}`
);
}
return pull;
};
const before = await assertCurrentRevision('pre-classification');
files = await github.paginate(github.rest.pulls.listFiles, {
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
per_page: 100,
});
const after = await assertCurrentRevision('post-classification');
if (
before.changed_files !== files.length ||
after.changed_files !== files.length
) {
throw new Error(
`Pull request file list is incomplete: API reports ` +
`${after.changed_files} changed files, pagination returned ${files.length}`
);
}
changelogOnly =
files.length === 1 &&
files[0].filename === 'CHANGELOG.md' &&
files[0].status === 'modified' &&
!files[0].previous_filename;
changelogChanged = files.some(
({ filename, previous_filename }) =>
filename === 'CHANGELOG.md' ||
previous_filename === 'CHANGELOG.md'
);
const isPlatformSensitive = (filename) =>
typeof filename === 'string' &&
(
filename.startsWith('internal/auth/') ||
filename.startsWith('internal/keychain/') ||
/_(darwin|windows|linux|unix)\.go$/.test(filename) ||
filename.startsWith('scripts/release/') ||
filename.startsWith('scripts/install') ||
filename.startsWith('Formula/') ||
filename.startsWith('build/npm/') ||
filename === '.goreleaser.yaml' ||
filename === '.github/workflows/release.yml'
);
platformSensitive = files.some(
({ filename, previous_filename }) =>
isPlatformSensitive(filename) ||
isPlatformSensitive(previous_filename)
);
}
core.setOutput('changelog_only', String(changelogOnly));
core.setOutput('changelog_changed', String(changelogChanged));
core.setOutput('platform_sensitive', String(platformSensitive));
await core.summary
.addHeading('Code Admission scope')
.addRaw(`- Event: \`${context.eventName}\`\n`)
.addRaw(`- Exact modified CHANGELOG only: \`${changelogOnly}\`\n`)
.addRaw(`- CHANGELOG touched: \`${changelogChanged}\`\n`)
.addRaw(`- Native-platform risk paths touched: \`${platformSensitive}\`\n`)
.addRaw(`- Changed files: \`${files.length}\`\n`)
.write();
- name: Record CHANGELOG-only fast path
if: steps.classify.outputs.changelog_only == 'true'
run: echo "Lint is satisfied by the trusted CHANGELOG-only Policy path." >> "$GITHUB_STEP_SUMMARY"
- name: Check out repository
if: steps.classify.outputs.changelog_only != 'true'
uses: actions/checkout@v4
- name: Set up Go
if: steps.classify.outputs.changelog_only != 'true'
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Verify Test Package Plan
if: steps.classify.outputs.changelog_only != 'true'
run: make test-plan
- name: Format Check
if: steps.classify.outputs.changelog_only != 'true'
run: make format-check
run: |
unformatted="$(find cmd internal test scripts/policy -name '*.go' -print0 | xargs -0r gofmt -l)"
test -z "$unformatted" || (printf '%s\n' "$unformatted" && exit 1)
- name: Go Vet
if: steps.classify.outputs.changelog_only != 'true'
run: go vet ./...
- name: Check GitHub Actions workflows
if: steps.classify.outputs.changelog_only != 'true'
run: go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12
# golangci-lint temporarily disabled: v1.64.8 built with Go 1.24 is incompatible with Go 1.25
# - name: golangci-lint
# uses: golangci/golangci-lint-action@v6
# with:
# version: v1.64.8
# args: ./...
test-race:
name: "Test (race: ${{ matrix.shard }})"
needs: lint
if: ${{ needs.lint.outputs.changelog_only != 'true' }}
test:
name: Test
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
shard:
- app
- generators
- helpers
- remaining
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Build
if: ${{ matrix.shard == 'remaining' }}
run: make build
- name: Test shard with Race Detection
shell: bash
env:
DWS_PACKAGE_VERSION: 0.0.0-test
TEST_SHARD: ${{ matrix.shard }}
run: |
set -euo pipefail
package_output="$(./scripts/ci/test-packages.sh list "$TEST_SHARD")"
test -n "$package_output"
mapfile -t packages <<< "$package_output"
test "${#packages[@]}" -gt 0
go test -v -race -count=1 -timeout=10m "${packages[@]}"
test-release-scripts:
name: Test (release scripts)
needs: lint
if: ${{ needs.lint.outputs.changelog_only != 'true' }}
runs-on: ubuntu-latest
timeout-minutes: 15
timeout-minutes: 20
steps:
- name: Check out repository
uses: actions/checkout@v4
@@ -204,127 +54,22 @@ jobs:
- name: Install archive tooling
run: sudo apt-get update && sudo apt-get install -y zip unzip
- name: Build
run: make build
- name: Test with Race Detection
# The registry-first final-delivery gate validates all public commands
# and the complete generated Catalog under the race detector. Keep the
# package timeout aligned with the macOS race job so the Linux runner's
# five-minute default does not expire while that gate is still making
# progress.
run: go test -v -race -count=1 -timeout=10m ./cmd/... ./internal/...
- name: Test release scripts
shell: bash
env:
DWS_PACKAGE_VERSION: 0.0.0-test
run: |
set -euo pipefail
package_output="$(./scripts/ci/test-packages.sh list release-scripts)"
test -n "$package_output"
mapfile -t packages <<< "$package_output"
test "${#packages[@]}" -gt 0
go test -v -count=1 -timeout=10m "${packages[@]}"
test-cross-platform:
name: Test (cross-platform compile)
needs: lint
if: ${{ needs.lint.outputs.changelog_only != 'true' }}
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Compile supported operating systems
shell: bash
run: |
set -eu
for target in darwin/amd64 darwin/arm64 windows/amd64 windows/arm64; do
goos="${target%/*}"
goarch="${target#*/}"
output="$RUNNER_TEMP/dws-${goos}-${goarch}"
if [ "$goos" = windows ]; then
output="${output}.exe"
fi
printf 'compile %s/%s\n' "$goos" "$goarch"
CGO_ENABLED=0 GOOS="$goos" GOARCH="$goarch" \
go build -o "$output" ./cmd
done
test:
name: Test
needs:
- lint
- test-race
- test-release-scripts
- test-cross-platform
- test-darwin
- test-windows
if: ${{ always() && needs.lint.result == 'success' }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions: {}
steps:
- name: Verify test shards
env:
CHANGELOG_ONLY: ${{ needs.lint.outputs.changelog_only }}
PLATFORM_SENSITIVE: ${{ needs.lint.outputs.platform_sensitive }}
RACE_RESULT: ${{ needs.test-race.result }}
RELEASE_SCRIPTS_RESULT: ${{ needs.test-release-scripts.result }}
CROSS_PLATFORM_RESULT: ${{ needs.test-cross-platform.result }}
DARWIN_RESULT: ${{ needs.test-darwin.result }}
WINDOWS_RESULT: ${{ needs.test-windows.result }}
run: |
failed=0
if [ "$CHANGELOG_ONLY" = true ]; then
for shard in \
"race shards:$RACE_RESULT" \
"release scripts:$RELEASE_SCRIPTS_RESULT" \
"cross-platform compile:$CROSS_PLATFORM_RESULT" \
"macOS native:$DARWIN_RESULT" \
"Windows native:$WINDOWS_RESULT"
do
name="${shard%%:*}"
result="${shard#*:}"
printf '%s: %s\n' "$name" "$result"
if [ "$result" != skipped ]; then
failed=1
fi
done
test "$failed" -eq 0
exit
fi
for shard in \
"race shards:$RACE_RESULT" \
"release scripts:$RELEASE_SCRIPTS_RESULT" \
"cross-platform compile:$CROSS_PLATFORM_RESULT"
do
name="${shard%%:*}"
result="${shard#*:}"
printf '%s: %s\n' "$name" "$result"
if [ "$result" != "success" ]; then
failed=1
fi
done
native_expected=skipped
if [ "$PLATFORM_SENSITIVE" = true ]; then
native_expected=success
fi
for native in \
"macOS native:$DARWIN_RESULT" \
"Windows native:$WINDOWS_RESULT"
do
name="${native%%:*}"
result="${native#*:}"
printf '%s: %s\n' "$name" "$result"
if [ "$result" != "$native_expected" ]; then
failed=1
fi
done
test "$failed" -eq 0
run: go test -v -count=1 -timeout=5m ./test/scripts
test-darwin:
name: Test (macOS auth/keychain)
needs: lint
if: ${{ needs.lint.outputs.changelog_only != 'true' && needs.lint.outputs.platform_sensitive == 'true' }}
runs-on: macos-latest
timeout-minutes: 15
steps:
@@ -341,8 +86,6 @@ jobs:
test-windows:
name: Test (Windows)
needs: lint
if: ${{ needs.lint.outputs.changelog_only != 'true' && needs.lint.outputs.platform_sensitive == 'true' }}
runs-on: windows-latest
timeout-minutes: 15
steps:
@@ -360,13 +103,11 @@ jobs:
- name: Test Windows auth and DPAPI packages
run: go test -v -count=1 -timeout=10m ./internal/keychain ./internal/auth
- name: Test Windows auth migration and portable auth diagnostics
run: go test -v -count=1 -timeout=5m ./internal/app -run '^Test(CrossPlatformCoverage)?Auth(MigrateKeychain|StatusDiagnosticReportsCiphertextKeyMismatch|ExportRejectsWindowsDPAPIBackend|ImportRejectsWindowsDPAPIBackend)'
- name: Test Windows auth migration diagnostics
run: go test -v -count=1 -timeout=5m ./internal/app -run '^TestAuth(MigrateKeychain|StatusDiagnosticReportsCiphertextKeyMismatch)'
coverage-darwin:
name: Coverage (macOS)
needs: lint
if: ${{ needs.lint.outputs.changelog_only != 'true' && needs.lint.outputs.platform_sensitive == 'true' }}
runs-on: macos-latest
timeout-minutes: 20
steps:
@@ -409,8 +150,6 @@ jobs:
coverage-windows:
name: Coverage (Windows)
needs: lint
if: ${{ needs.lint.outputs.changelog_only != 'true' && needs.lint.outputs.platform_sensitive == 'true' }}
runs-on: windows-latest
timeout-minutes: 20
steps:
@@ -453,86 +192,10 @@ jobs:
name: coverage-windows
path: coverage-windows.txt
coverage-current:
name: Coverage (current)
needs: lint
if: ${{ needs.lint.outputs.changelog_only != 'true' }}
coverage:
name: Coverage
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Check out repository
uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Install archive tooling
run: sudo apt-get update && sudo apt-get install -y zip unzip
- name: Build
run: make build
- name: Run current unit tests with coverage
run: |
go test -count=1 -p 1 -coverprofile=coverage.txt -covermode=atomic ./ ./cmd/... ./internal/... ./skills/...
go tool cover -func=coverage.txt
- name: Upload current coverage profile
uses: actions/upload-artifact@v4
with:
name: coverage-current-profile
path: coverage.txt
retention-days: 1
coverage-supporting:
name: Coverage (supporting)
needs: lint
if: ${{ needs.lint.outputs.changelog_only != 'true' }}
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Check out repository
uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Install archive tooling
run: sudo apt-get update && sudo apt-get install -y zip unzip
- name: Run policy and shortcut coverage
run: |
go test -count=1 -coverprofile=coverage-policy.txt -covermode=atomic ./pkg/... ./scripts/policy/...
go test -count=1 \
-run '^(TestAllShortcuts|TestCrossPlatformCoverage)' \
-coverpkg=./internal/app,./internal/helpers,./internal/shortcut/... \
-coverprofile=coverage-shortcut.txt \
-covermode=atomic \
./internal/app ./internal/helpers ./internal/shortcut/...
- name: Upload supporting coverage profiles
uses: actions/upload-artifact@v4
with:
name: coverage-supporting-profiles
path: |
coverage-policy.txt
coverage-shortcut.txt
retention-days: 1
coverage-baseline:
name: Coverage (baseline)
needs: lint
if: ${{ needs.lint.outputs.changelog_only != 'true' }}
runs-on: ubuntu-latest
timeout-minutes: 20
timeout-minutes: 30
steps:
- name: Check out repository
uses: actions/checkout@v4
@@ -548,6 +211,9 @@ jobs:
- name: Install archive tooling
run: sudo apt-get update && sudo apt-get install -y zip unzip
- name: Build
run: make build
- name: Resolve authoritative coverage base
env:
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
@@ -565,9 +231,18 @@ jobs:
git rev-parse --verify "${base_ref}^{commit}" >/dev/null
echo "COVERAGE_BASE_REF=$base_ref" >> "$GITHUB_ENV"
- name: Run baseline unit tests with coverage
- name: Run current and baseline unit tests with coverage
run: |
set -eu
go test -count=1 -p 1 -coverprofile=coverage.txt -covermode=atomic ./ ./cmd/... ./internal/... ./skills/...
go test -count=1 -coverprofile=coverage-policy.txt -covermode=atomic ./pkg/... ./scripts/policy/...
go test -count=1 \
-run '^(TestAllShortcuts|TestCrossPlatformCoverage)' \
-coverpkg=./internal/app,./internal/helpers,./internal/shortcut/... \
-coverprofile=coverage-shortcut.txt \
-covermode=atomic \
./internal/app ./internal/helpers ./internal/shortcut/...
base_worktree="$(mktemp -d "${RUNNER_TEMP}/dws-coverage-base.XXXXXX")"
rmdir "$base_worktree"
cleanup() {
@@ -583,141 +258,18 @@ jobs:
-covermode=atomic \
./ ./cmd/... ./internal/... ./skills/...
)
- name: Upload baseline coverage profile
uses: actions/upload-artifact@v4
with:
name: coverage-baseline-profile
path: coverage-base.txt
retention-days: 1
coverage:
name: Coverage
needs:
- lint
- coverage-current
- coverage-supporting
- coverage-baseline
- coverage-darwin
- coverage-windows
if: ${{ always() && needs.lint.result == 'success' }}
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Verify coverage profile jobs
env:
CHANGELOG_ONLY: ${{ needs.lint.outputs.changelog_only }}
PLATFORM_SENSITIVE: ${{ needs.lint.outputs.platform_sensitive }}
CURRENT_RESULT: ${{ needs.coverage-current.result }}
SUPPORTING_RESULT: ${{ needs.coverage-supporting.result }}
BASELINE_RESULT: ${{ needs.coverage-baseline.result }}
DARWIN_RESULT: ${{ needs.coverage-darwin.result }}
WINDOWS_RESULT: ${{ needs.coverage-windows.result }}
run: |
failed=0
expected=success
native_expected=skipped
if [ "$CHANGELOG_ONLY" = true ]; then
expected=skipped
elif [ "$PLATFORM_SENSITIVE" = true ]; then
native_expected=success
fi
for profile in \
"current:$CURRENT_RESULT" \
"supporting:$SUPPORTING_RESULT" \
"baseline:$BASELINE_RESULT"
do
name="${profile%%:*}"
result="${profile#*:}"
printf '%s: %s\n' "$name" "$result"
if [ "$result" != "$expected" ]; then
failed=1
fi
done
for native in \
"macOS native:$DARWIN_RESULT" \
"Windows native:$WINDOWS_RESULT"
do
name="${native%%:*}"
result="${native#*:}"
printf '%s: %s\n' "$name" "$result"
if [ "$CHANGELOG_ONLY" = true ]; then
native_expected=skipped
fi
if [ "$result" != "$native_expected" ]; then
failed=1
fi
done
test "$failed" -eq 0
- name: Check out repository
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- name: Set up Go
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Resolve authoritative coverage base
if: needs.lint.outputs.changelog_only != 'true'
env:
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
PUSH_BEFORE_SHA: ${{ github.event.before }}
run: |
set -eu
base_ref="$PUSH_BEFORE_SHA"
if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then
base_ref="$(git merge-base "$PR_HEAD_SHA" "$PR_BASE_SHA")"
fi
if [ -z "$base_ref" ] || [ "$base_ref" = "0000000000000000000000000000000000000000" ]; then
base_ref="$(git rev-parse HEAD^)"
fi
git rev-parse --verify "${base_ref}^{commit}" >/dev/null
echo "COVERAGE_BASE_REF=$base_ref" >> "$GITHUB_ENV"
- name: Download current coverage profile
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/download-artifact@v4
with:
name: coverage-current-profile
path: .
- name: Download supporting coverage profiles
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/download-artifact@v4
with:
name: coverage-supporting-profiles
path: .
- name: Download baseline coverage profile
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/download-artifact@v4
with:
name: coverage-baseline-profile
path: .
go tool cover -func=coverage.txt
- name: Enforce coverage gate
if: needs.lint.outputs.changelog_only != 'true'
env:
COVERAGE_TARGET: "100"
COVERAGE_TARGET: "80"
COVERAGE_ENFORCE_OVERALL: "false"
COVERAGE_OVERALL_TOLERANCE: "0"
run: COVERAGE_ADDITIONAL_DIFF_PROFILE=coverage-shortcut.txt make coverage-gate BASE_REF="$COVERAGE_BASE_REF"
run: COVERAGE_ADDITIONAL_PROFILE=coverage-shortcut.txt make coverage-gate BASE_REF="$COVERAGE_BASE_REF"
- name: Generate coverage report
if: needs.lint.outputs.changelog_only != 'true'
run: go tool cover -html=coverage.txt -o coverage.html
- name: Upload coverage artifact
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/upload-artifact@v4
with:
name: coverage-report
@@ -729,114 +281,44 @@ jobs:
coverage.html
policy:
name: Policy
needs: lint
name: Policy Check
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Check out repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Go
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Verify pull request merge revision
if: github.event_name == 'pull_request'
env:
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
set -eu
test "$(git rev-parse HEAD^1)" = "$PR_BASE_SHA" || {
echo "checked-out merge first parent does not match event base" >&2
exit 1
}
test "$(git rev-parse HEAD^2)" = "$PR_HEAD_SHA" || {
echo "checked-out merge second parent does not match event head" >&2
exit 1
}
- name: Validate changed CHANGELOG content
if: github.event_name == 'pull_request'
env:
CLASSIFIED_CHANGELOG_CHANGED: ${{ needs.lint.outputs.changelog_changed }}
CHANGELOG_ONLY: ${{ needs.lint.outputs.changelog_only }}
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
set -eu
merge_changelog_changed=false
if git diff --no-ext-diff --find-renames --name-status \
"$PR_BASE_SHA" HEAD |
awk -F '\t' '
{
for (field = 2; field <= NF; field++) {
if ($field == "CHANGELOG.md") found = 1
}
}
END { exit !found }
'
then
merge_changelog_changed=true
fi
test "$merge_changelog_changed" = "$CLASSIFIED_CHANGELOG_CHANGED" || {
echo "Files API and synthetic merge tree disagree on CHANGELOG scope" >&2
exit 1
}
if [ "$merge_changelog_changed" != true ]; then
exit 0
fi
mode=--content-only
if [ "$CHANGELOG_ONLY" = true ]; then
mode=--fast-path
fi
./scripts/policy/check-changelog-pr.sh \
"$mode" "$PR_BASE_SHA" HEAD
- name: Record CHANGELOG-only fast path
if: needs.lint.outputs.changelog_only == 'true'
run: |
echo "Only the base-equivalent CHANGELOG validator ran; full Policy resumes on main." \
>> "$GITHUB_STEP_SUMMARY"
- name: Build
if: needs.lint.outputs.changelog_only != 'true'
run: make build
- name: Policy
if: needs.lint.outputs.changelog_only != 'true'
run: make policy
interface-integrity:
name: Interface Integrity
needs: lint
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Check out repository
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- name: Set up Go
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Build
if: needs.lint.outputs.changelog_only != 'true'
run: make build
- name: Resolve authoritative compatibility merge-base
if: needs.lint.outputs.changelog_only != 'true'
env:
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
@@ -861,7 +343,6 @@ jobs:
echo "COMPATIBILITY_STABLE_REF=$stable_ref" >> "$GITHUB_ENV"
- name: Check historical commands and help compatibility
if: needs.lint.outputs.changelog_only != 'true'
run: |
make authoritative-interface-integrity \
BASE_REF="$COMPATIBILITY_BASE_REF"
@@ -871,89 +352,140 @@ jobs:
fi
- name: Check complete Schema compatibility
if: needs.lint.outputs.changelog_only != 'true'
run: make schema-compatibility BASE_REF="$COMPATIBILITY_BASE_REF"
- name: Check skill command references
if: needs.lint.outputs.changelog_only != 'true'
run: make skill-command-integrity
- name: Record CHANGELOG-only fast path
if: needs.lint.outputs.changelog_only == 'true'
run: echo "Interface Integrity is unaffected by an exact CHANGELOG-only diff." >> "$GITHUB_STEP_SUMMARY"
cli-smoke:
name: CLI Smoke
needs: lint
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Check out repository
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/checkout@v4
- name: Set up Go
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Build
if: needs.lint.outputs.changelog_only != 'true'
run: make build
- name: Check public top-level commands
if: needs.lint.outputs.changelog_only != 'true'
run: make cli-smoke
- name: Record CHANGELOG-only fast path
if: needs.lint.outputs.changelog_only == 'true'
run: echo "CLI Smoke is unaffected by an exact CHANGELOG-only diff." >> "$GITHUB_STEP_SUMMARY"
mock-mcp-smoke:
name: Mock MCP
needs: lint
name: Mock MCP Smoke
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Check out repository
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/checkout@v4
- name: Set up Go
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Check HTTP and stdio MCP transport
if: needs.lint.outputs.changelog_only != 'true'
run: make mock-mcp-smoke
- name: Record CHANGELOG-only fast path
if: needs.lint.outputs.changelog_only == 'true'
run: echo "Mock MCP is unaffected by an exact CHANGELOG-only diff." >> "$GITHUB_STEP_SUMMARY"
edition-tests:
name: Edition
needs: lint
name: Edition Contract Tests
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Check out repository
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/checkout@v4
- name: Set up Go
if: needs.lint.outputs.changelog_only != 'true'
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Run edition contract tests
if: needs.lint.outputs.changelog_only != 'true'
run: go test -v -count=1 ./pkg/editiontest/...
- name: Record CHANGELOG-only fast path
if: needs.lint.outputs.changelog_only == 'true'
run: echo "Edition is unaffected by an exact CHANGELOG-only diff." >> "$GITHUB_STEP_SUMMARY"
ci-gate:
name: CI Gate
needs:
- lint
- test
- test-darwin
- test-windows
- coverage
- coverage-darwin
- coverage-windows
- policy
- interface-integrity
- cli-smoke
- mock-mcp-smoke
- edition-tests
if: ${{ always() }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions: {}
steps:
- name: Verify required checks
env:
LINT_RESULT: ${{ needs.lint.result }}
TEST_RESULT: ${{ needs.test.result }}
TEST_DARWIN_RESULT: ${{ needs.test-darwin.result }}
TEST_WINDOWS_RESULT: ${{ needs.test-windows.result }}
COVERAGE_RESULT: ${{ needs.coverage.result }}
COVERAGE_DARWIN_RESULT: ${{ needs.coverage-darwin.result }}
COVERAGE_WINDOWS_RESULT: ${{ needs.coverage-windows.result }}
POLICY_RESULT: ${{ needs.policy.result }}
INTERFACE_INTEGRITY_RESULT: ${{ needs.interface-integrity.result }}
CLI_SMOKE_RESULT: ${{ needs.cli-smoke.result }}
MOCK_MCP_SMOKE_RESULT: ${{ needs.mock-mcp-smoke.result }}
EDITION_TESTS_RESULT: ${{ needs.edition-tests.result }}
run: |
failed=0
for check in \
"Lint:$LINT_RESULT" \
"Test:$TEST_RESULT" \
"Test (macOS auth/keychain):$TEST_DARWIN_RESULT" \
"Test (Windows):$TEST_WINDOWS_RESULT" \
"Coverage:$COVERAGE_RESULT" \
"Coverage (macOS):$COVERAGE_DARWIN_RESULT" \
"Coverage (Windows):$COVERAGE_WINDOWS_RESULT" \
"Policy Check:$POLICY_RESULT" \
"Interface Integrity:$INTERFACE_INTEGRITY_RESULT" \
"CLI Smoke:$CLI_SMOKE_RESULT" \
"Mock MCP Smoke:$MOCK_MCP_SMOKE_RESULT" \
"Edition Contract Tests:$EDITION_TESTS_RESULT"
do
name="${check%%:*}"
result="${check#*:}"
printf '%s: %s\n' "$name" "$result"
if [ "$result" != "success" ]; then
failed=1
fi
done
test "$failed" -eq 0
notify-downstream:
name: Notify Wukong Overlay
needs: [ci-gate]
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
permissions: {}
steps:
- name: Trigger downstream CI
run: |
# Trigger internal GitLab CI pipeline via webhook.
# WUKONG_TRIGGER_TOKEN is a repository secret.
if [ -n "${{ secrets.WUKONG_TRIGGER_TOKEN }}" ]; then
curl --fail --silent --show-error \
-X POST \
-F "token=${{ secrets.WUKONG_TRIGGER_TOKEN }}" \
-F "ref=main" \
-F "variables[UPSTREAM_SHA]=${{ github.sha }}" \
"${{ secrets.WUKONG_TRIGGER_URL }}"
echo "Downstream CI triggered."
else
echo "No WUKONG_TRIGGER_TOKEN configured, skipping downstream notification."
fi
+17 -7
View File
@@ -1,5 +1,4 @@
# 把本仓库 main 代码自动镜像到 Gitee,供国内用户访问 raw 脚本入口。
# Release tag 与附件只由 release.yml 的受控 publication queue 发布。
# 把本仓库代码自动镜像到 Gitee,供国内用户访问(raw 脚本入口 + tags)。
# 用 HTTPS + 令牌直接 git push(无需 SSH key),复用已配置的 secret:
# GITEE_TOKEN —— Gitee 私人令牌(勾 projects)
# GITEE_USER —— 令牌所属 Gitee 用户名(用于 https 推送鉴权)
@@ -11,6 +10,8 @@ on:
push:
branches:
- main
tags:
- 'v*'
schedule:
- cron: '0 18 * * *'
workflow_dispatch:
@@ -22,14 +23,13 @@ concurrency:
jobs:
mirror:
runs-on: ubuntu-latest
if: ${{ github.ref_name == github.event.repository.default_branch && github.repository_owner == 'DingTalk-Real-AI' }}
# GitHub Actions 不允许在 job-level if 直接引用 secrets,故先用 env 暴露再在 step 守卫。
env:
GITEE_TOKEN: ${{ secrets.GITEE_TOKEN }}
GITEE_USER: ${{ secrets.GITEE_USER }}
GITEE_REPO: ${{ secrets.GITEE_REPO }}
steps:
- name: Checkout main history
- name: Checkout (full history + tags)
if: env.GITEE_TOKEN != ''
uses: actions/checkout@v4
with:
@@ -41,7 +41,14 @@ jobs:
set -eu
REMOTE="https://${GITEE_USER}:${GITEE_TOKEN}@gitee.com/${GITEE_REPO}.git"
git fetch --force origin 'refs/heads/main:refs/remotes/origin/main'
if [ "${GITHUB_REF_TYPE:-}" = "tag" ]; then
VERSION="$GITHUB_REF_NAME" ./scripts/release/sync-gitee-tag.sh
echo "✅ 已镜像 tag ${GITHUB_REF_NAME} 到 Gitee ${GITEE_REPO}"
exit 0
fi
# 取到 main 与所有 tag(落到 origin/* 与本地 tags,避免推当前分支引用冲突)
git fetch --force --tags origin 'refs/heads/main:refs/remotes/origin/main'
# Gitee 专属分支:在 origin/main 之上叠加一个 README 本地化 commit。
# GitHub 那份 README 不变;只有推往 Gitee 的副本被改写。
@@ -73,6 +80,9 @@ jobs:
git add README.md README_zh.md 2>/dev/null || true
git commit -m "docs(gitee): localize install commands + coverage badge for Gitee mirror" || true
# main 镜像对齐;release tag 由 release.yml 单独校验后创建,禁止在这里 force。
# 镜像对齐(force:Gitee 始终跟随 GitHub + Gitee 专属 README 本地化)
git push --force "$REMOTE" 'gitee-main:refs/heads/main'
echo "✅ 已镜像 main(含 Gitee README 本地化)到 Gitee ${GITEE_REPO}"
# Release tags are immutable. Push only missing tags and fail closed
# on a conflicting existing ref instead of trying to move it.
timeout --signal=TERM 180s git push --tags "$REMOTE"
echo "✅ 已镜像 main(+Gitee README 本地化) + tags 到 Gitee ${GITEE_REPO}"
+4 -5
View File
@@ -1,9 +1,8 @@
name: Main Integration — 主干集成
name: Multi Profile E2E
on:
pull_request:
push:
branches:
- main
workflow_dispatch:
permissions:
@@ -15,7 +14,7 @@ concurrency:
jobs:
multi-profile-e2e:
name: Multi-profile E2E
name: Multi Profile E2E
runs-on: ubuntu-latest
timeout-minutes: 15
env:
@@ -37,7 +36,7 @@ jobs:
mkdir -p .tmp-bin
bash scripts/dev/test-multi-profile-e2e.sh --keep-workdir | tee "$MULTI_PROFILE_E2E_LOG"
{
echo "### Multi-profile E2E"
echo "### Multi Profile E2E"
echo "- Command: \`bash scripts/dev/test-multi-profile-e2e.sh --keep-workdir\`"
echo "- Scope: isolated auth/profile storage, profile switch/use, one-shot profile override, CSV multi-profile aggregation, legacy migration"
echo "- Result: passed"
-38
View File
@@ -1,38 +0,0 @@
name: Main Integration — Wukong Overlay
on:
workflow_run:
workflows:
- CI
types:
- completed
permissions: {}
jobs:
notify-downstream:
name: Notify Wukong Overlay
if: >-
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_branch == 'main'
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Trigger downstream CI
env:
UPSTREAM_SHA: ${{ github.event.workflow_run.head_sha }}
WUKONG_TRIGGER_TOKEN: ${{ secrets.WUKONG_TRIGGER_TOKEN }}
WUKONG_TRIGGER_URL: ${{ secrets.WUKONG_TRIGGER_URL }}
run: |
if [ -n "$WUKONG_TRIGGER_TOKEN" ]; then
curl --fail --silent --show-error \
-X POST \
-F "token=$WUKONG_TRIGGER_TOKEN" \
-F "ref=main" \
-F "variables[UPSTREAM_SHA]=$UPSTREAM_SHA" \
"$WUKONG_TRIGGER_URL"
echo "Downstream CI triggered."
else
echo "No WUKONG_TRIGGER_TOKEN configured, skipping downstream notification."
fi
+71
View File
@@ -0,0 +1,71 @@
name: Publish npm release
on:
workflow_dispatch:
inputs:
version:
description: "Release tag to publish to npm (e.g. v1.0.48)"
required: true
type: string
permissions:
contents: read
jobs:
publish-npm:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Download GitHub release assets
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -eu
mkdir -p dist
gh release download "${{ inputs.version }}" \
--repo "${{ github.repository }}" \
--dir dist \
--pattern 'dws-*' \
--pattern 'checksums.txt' \
--clobber
ls -la dist
- name: Stage npm package
run: |
set -eu
version="${{ inputs.version }}"
semver="${version#v}"
pkg_root="dist/npm/dingtalk-workspace-cli"
rm -rf "$pkg_root"
mkdir -p "$pkg_root/assets" "$pkg_root/bin"
cp build/npm/install.js "$pkg_root/install.js"
cp build/npm/bin/dws.js "$pkg_root/bin/dws.js"
cp build/npm/README.md "$pkg_root/README.md"
sed "s|__VERSION__|${semver}|g" build/npm/package.json.tmpl > "$pkg_root/package.json"
cp dist/dws-* "$pkg_root/assets/"
cp dist/checksums.txt "$pkg_root/assets/"
test -f "$pkg_root/assets/dws-skills.zip"
cat "$pkg_root/package.json"
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
registry-url: "https://registry.npmjs.org"
- name: Publish stable to npm
if: ${{ github.repository_owner == 'DingTalk-Real-AI' && !contains(inputs.version, '-') }}
working-directory: dist/npm/dingtalk-workspace-cli
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Publish prerelease to npm beta
if: ${{ github.repository_owner == 'DingTalk-Real-AI' && contains(inputs.version, '-') }}
working-directory: dist/npm/dingtalk-workspace-cli
run: npm publish --access public --tag beta
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,55 @@
name: Sync release to Gitee
# Manually mirror a published GitHub release's assets to the matching Gitee
# release. Use this to repair a release whose Gitee mirror is incomplete (e.g.
# the Release job timed out mid-upload). It runs ONLY the idempotent Gitee sync
# step — it does not run GoReleaser and does not touch the GitHub release, so
# there is no release outage. The sync script skips assets already on Gitee, so
# this only uploads what is missing.
on:
workflow_dispatch:
inputs:
version:
description: "Release tag to mirror to Gitee (e.g. v1.0.42)"
required: true
type: string
permissions:
contents: read
jobs:
sync-gitee:
runs-on: ubuntu-latest
# Each step has its own ceiling. Their 115-minute sum leaves five minutes
# for runner scheduling/teardown inside this 120-minute job deadline.
timeout-minutes: 120
steps:
- name: Check out repository
uses: actions/checkout@v4
timeout-minutes: 5
- name: Download GitHub release assets
timeout-minutes: 10
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -eu
mkdir -p dist
gh release download "${{ inputs.version }}" \
--repo "${{ github.repository }}" \
--dir dist \
--pattern 'dws-*' \
--pattern 'checksums.txt' \
--clobber
ls -la dist
- name: Mirror release to Gitee (China)
# Idempotent: uploads only assets not already present on the Gitee release.
timeout-minutes: 100
run: ./scripts/release/sync-to-gitee.sh
env:
VERSION: ${{ inputs.version }}
GITEE_TOKEN: ${{ secrets.GITEE_TOKEN }}
GITEE_USER: ${{ secrets.GITEE_USER }}
GITEE_REPO: ${{ secrets.GITEE_REPO }}
-148
View File
@@ -1,148 +0,0 @@
name: Withdraw release
run-name: Withdraw ${{ inputs.version }}
on:
workflow_dispatch:
inputs:
version:
description: "Exact published version to withdraw (vX.Y.Z or vX.Y.Z-beta.N)"
required: true
type: string
reason:
description: "Public, single-line withdrawal reason (8-300 characters)"
required: true
type: string
confirmation:
description: "Type WITHDRAW followed by a space and the exact version"
required: true
type: string
permissions:
contents: read
# Share the publication lock with release.yml. A withdrawal and a publication
# must never mutate channel pointers concurrently.
concurrency:
group: dws-release-publication
cancel-in-progress: false
jobs:
withdraw:
name: Withdraw release from every distribution channel
environment: release-withdrawal
runs-on: ubuntu-latest
timeout-minutes: 180
permissions:
actions: read
contents: write
steps:
- name: Verify withdrawal environment protection
uses: actions/github-script@v7
with:
script: |
const { owner, repo } = context.repo;
const response = await github.request(
"GET /repos/{owner}/{repo}/environments/{environment_name}",
{ owner, repo, environment_name: "release-withdrawal" },
);
const reviewerRule = response.data.protection_rules.find(
(rule) => rule.type === "required_reviewers",
);
if (
!reviewerRule ||
reviewerRule.prevent_self_review !== true ||
!Array.isArray(reviewerRule.reviewers) ||
reviewerRule.reviewers.length === 0
) {
core.setFailed("release-withdrawal must require a reviewer and prevent self-review");
return;
}
if (response.data.deployment_branch_policy?.protected_branches !== true) {
core.setFailed("release-withdrawal must allow only protected branches");
}
if (response.data.can_admins_bypass !== false) {
core.setFailed("release-withdrawal must not allow administrator bypass");
}
- name: Require the exact current official default-branch commit
uses: actions/github-script@v7
with:
script: |
const expectedRepository = "DingTalk-Real-AI/dingtalk-workspace-cli";
const defaultBranch = context.payload.repository.default_branch;
if (context.eventName !== "workflow_dispatch") {
core.setFailed("release withdrawal accepts workflow_dispatch only");
return;
}
if (`${context.repo.owner}/${context.repo.repo}` !== expectedRepository) {
core.setFailed(`release withdrawal is restricted to ${expectedRepository}`);
return;
}
if (context.ref !== `refs/heads/${defaultBranch}`) {
core.setFailed(`release withdrawal must be dispatched from ${defaultBranch}`);
return;
}
const branch = await github.rest.git.getRef({
...context.repo,
ref: `heads/${defaultBranch}`,
});
if (branch.data.object.sha !== context.sha) {
core.setFailed(
`default branch advanced to ${branch.data.object.sha}; re-dispatch from the new head`,
);
}
- name: Check out trusted withdrawal tooling
uses: actions/checkout@v4
with:
ref: ${{ github.sha }}
fetch-depth: 0
persist-credentials: false
- name: Set up Node.js for npm channel withdrawal
uses: actions/setup-node@v4
with:
node-version: "22"
registry-url: "https://registry.npmjs.org"
- name: Withdraw immutable release and roll back channels
id: withdrawal
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
GITHUB_EVENT_DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
WITHDRAW_VERSION: ${{ inputs.version }}
WITHDRAW_REASON: ${{ inputs.reason }}
WITHDRAW_CONFIRMATION: ${{ inputs.confirmation }}
OSS_ACCESS_KEY_ID: ${{ secrets.OSS_ACCESS_KEY_ID }}
OSS_ACCESS_KEY_SECRET: ${{ secrets.OSS_ACCESS_KEY_SECRET }}
OSS_ENDPOINT: ${{ secrets.OSS_ENDPOINT }}
OSS_BUCKET: ${{ secrets.OSS_BUCKET }}
OSS_PREFIX: ${{ secrets.OSS_PREFIX }}
GITEE_TOKEN: ${{ secrets.GITEE_TOKEN }}
GITEE_USER: ${{ secrets.GITEE_USER }}
GITEE_REPO: ${{ secrets.GITEE_REPO }}
DWS_GITEE_ENABLED: ${{ vars.ENABLE_GITEE_UPLOAD_FALLBACK == 'true' && 'true' || 'false' }}
HOMEBREW_PR_TOKEN: ${{ secrets.HOMEBREW_PR_TOKEN }}
run: |
./scripts/release/withdraw-release.sh \
"$WITHDRAW_VERSION" \
"$WITHDRAW_REASON" \
"$WITHDRAW_CONFIRMATION"
- name: Report withdrawal boundary
if: ${{ always() }}
env:
VERSION: ${{ inputs.version }}
RESULT: ${{ steps.withdrawal.outcome }}
run: |
{
echo "### Release withdrawal: ${VERSION}"
echo
echo "- Workflow result: ${RESULT}"
echo "- Success means every configured channel was verified and the permanent withdrawn/${VERSION} tombstone remains as the version-reuse barrier."
echo "- Failure may occur before or after the tombstone/channel mutations; inspect the failed step and rerun the exact same inputs after fixing the cause."
echo "- The problem GitHub Release and original tag are removed after npm and every tag-enabled/configured mirror are rolled back, so GitHub installers stop resolving the bad version while the Homebrew rollback PR is reviewed."
echo "- npm is deprecated rather than unpublished; already-installed clients cannot be remotely downgraded."
echo "- If a Homebrew rollback PR was opened, this run remains failed until that PR is independently reviewed, merged, and the workflow is rerun."
} >> "$GITHUB_STEP_SUMMARY"
-8
View File
@@ -54,11 +54,3 @@ test/dev_functional/results.jsonl
/coverage-policy.txt
/coverage.html
dwsbin
# Local shortcut eval / real-backend capture artifacts — may contain real PII
# (employee names/emails, userIds, conversation & message IDs). Never commit.
/docs/shortcut-real-read-results.json
/docs/shortcut-real-write-results.json
/docs/shortcut-comparison.html
/docs/shortcut-gsb-eval.*
/scripts/run_shortcut_real_read_matrix.py
+7 -2
View File
@@ -1,14 +1,19 @@
# GoReleaser configuration for dws
# Docs: https://goreleaser.com
#
# To release, use scripts/release/release.sh. It seals main, validates the
# CHANGELOG and packages, then pushes the annotated tag for CI/CD to publish.
# To release:
# git tag -a v0.1.0 -m "Release v0.1.0"
# git push origin v0.1.0
#
# To test locally (no publish):
# goreleaser release --snapshot --clean
version: 2
before:
hooks:
- go mod tidy
builds:
- main: ./cmd
binary: dws
+345 -39
View File
@@ -1,51 +1,357 @@
# Repository Agent Guide
This file applies to the entire repository. Keep it as a routing page: load
the detailed guide for the surface you are changing instead of treating this
file as a repository wiki.
This file applies to the entire repository. Keep changes scoped, preserve
unrelated work, and use `gofmt` for every modified Go file.
## Always
## Build and test
- Preserve unrelated and pre-existing work; inspect `git status` before edits.
- Make the smallest coherent change and update its tests and user-facing docs.
- Use `gofmt` for every modified Go file.
- Treat repository code, tests, scripts, and versioned docs as the source of
truth. Do not depend on generated Wiki or CodeWiki content.
- Do not hand-edit generated Schema Catalog or Agent metadata. Change their
reviewed inputs or generators, then regenerate.
- Build: `go build ./cmd`
- Full test suite: `DWS_PACKAGE_VERSION=0.0.0-test go test ./...`
- Generate Schema assets: `go generate ./internal/cli`
- Check generated drift: `./scripts/policy/check-generated-drift.sh`
- Check the Schema contract: `./scripts/policy/check-schema-catalog.sh`
## Read by task
Generated Schema JSON is committed. Change its source inputs and generators,
then regenerate; do not hand-edit generated Catalog or Agent metadata files.
`internal/cli/schema_command_registry.json` is different: it is a reviewed
`CommandRegistry` source, not a generated snapshot. It is the single reviewed
source of stable canonical identity,
primary paths, aliases, and navigation. Edit it only when reviewed exposure,
identity, primary path, or aliases change; parameter, Skill, and metadata-only
changes must not rewrite it mechanically.
| Change surface | Required guide |
|---|---|
| Any implementation or review | [`CONTRIBUTING.md`](CONTRIBUTING.md) and [`docs/coding-agent-guide.md`](docs/coding-agent-guide.md) |
| Writing a task for a coding agent | [`docs/coding-agent-task-template.md`](docs/coding-agent-task-template.md) |
| Overall architecture or package layering | [`docs/architecture.md`](docs/architecture.md) |
| Product command handler behavior | [`internal/helpers/AGENTS.md`](internal/helpers/AGENTS.md) |
| Helpers package/file layout or megafile splits | [`docs/helpers-structure-guide.md`](docs/helpers-structure-guide.md) |
| Bundled skill authoring (`skills/`) | [`skills/AGENTS.md`](skills/AGENTS.md) and [`docs/skill-authoring-guide.md`](docs/skill-authoring-guide.md) |
| CLI paths, flags, Schema, Agent metadata, or generated Catalog | [`docs/schema-contributor-guide.md`](docs/schema-contributor-guide.md) |
| CI, release, packaging, or repository automation | [`docs/automation.md`](docs/automation.md) |
| Agent identification headers or host integration | [`docs/agent-code.md`](docs/agent-code.md) |
## Agent Schema contract
Read the closest code and tests for the affected package as well. Nested
`AGENTS.md` files take precedence for their subtrees.
The Schema data flow is one way:
## Common checks
```text
1. app.NewRootCommand()
└─ builds the real Cobra command tree and flags
Choose checks from the matrix in `docs/coding-agent-guide.md`; do not claim a
check that was not run.
2. schema_command_registry.json
+ schema_hints/metadata/<product>.json tool parameters (+ cli_path)
└─ forms EffectiveCommandRegistry
└─ binds exactly to real Cobra leaves and aliases
```bash
make coding-agent-harness
make build
make format-check
make test
make policy
git diff --check
3. Parameter resolution
Cobra flags
+ schema_parameter_bindings.json
+ metadata tool parameters
└─ produces ParameterSpec and constraints
4. Agent and interface semantics
schema_hints/selection/<product>.json (selection prose)
+ schema_hints/metadata/<product>.json (safety/interface/runtime_gate)
+ pinned MCP metadata
└─ resolves Agent metadata by source precedence
Markdown is evidence only; it is not concatenated into final prose
5. One typed hub
BoundCommandRegistry
+ ParameterSpec
+ Agent metadata
+ Interface metadata
└─ resolves every command exactly once into ToolSpec
└─ aggregates SchemaRegistry + SchemaIndex
6. One-way publication
SchemaRegistry
└─ internal/cli/schema_catalog.json
└─ dws schema list/product/group/leaf/--all
```
For Schema work, the minimum generation entry point is `make generate-schema`.
For CLI path or flag changes, also run
`./scripts/policy/check-command-surface.sh --strict`. Report failures,
environment limits, and unrun checks explicitly in the handoff.
Parameter overlays from metadata are merged into `EffectiveCommandRegistry`
*before* Cobra binding; after that point there is no second identity source and
no identity precedence winner. The binder must reject a missing/non-runnable
Cobra path, an alias collision, and any native identity annotation that
disagrees with the effective registry. A missing native identity annotation is
allowed because annotations are implementation-side assertions, not identity
fallbacks.
The assembler resolves every bound command exactly once into one `ToolSpec`.
Build-time gates and the snapshot serializer consume that source-resolved typed
registry/index. Runtime projections and delivery gates consume the typed
registry/index returned by the production snapshot loader. Neither path may
reopen annotations, merge source records, or use a previous Catalog or other
generated JSON as a source. `schema_catalog.json` is output-only in the
generation graph. The production loader decoding the embedded published
snapshot is a delivery boundary, not source resolution; it must never create or
repair a Cobra command, flag, registry entry, or later Catalog generation.
This split is architecturally isomorphic to Lark's typed metadata registry,
navigation catalog, and schema renderer. DWS intentionally preserves its
existing flat JSON wire contract for compatibility; do not treat architectural
alignment as permission to make an unversioned wire-format change.
The reviewed `CommandRegistry` is the sole source of stable command identity
and navigation. The executable Cobra tree remains the source of truth for
whether a CLI path exists, is runnable, and which flags it accepts. Schema
coverage is bidirectional:
1. Every final `SchemaRegistry` tool, including its serialized Catalog
projection, must resolve to an executable Cobra command.
2. Every public runnable Cobra leaf must either resolve to Schema or appear as
an exact, reviewed exclusion with a non-empty reason in
`internal/cli/schema_command_exclusions.json`.
Do not use prefix or wildcard exclusions: they can silently hide future
commands. Remove an exclusion when its command enters Schema; stale, invalid,
or duplicate exclusions must fail generation and CI.
When adding or changing an Agent-visible command, review all relevant inputs:
- `internal/cli/schema_command_registry.json` for the reviewed
`CommandRegistry`: canonical identity, primary CLI path, aliases, and stable
navigation. It is the identity source and is not a generated artifact.
- `internal/cli/schema_command_registry.schema.json` is its closed,
machine-readable editing contract. Preserve the local `$schema` reference;
unknown fields, invalid visibility values, stale paths, and collisions fail
Go validation and policy.
- `internal/cli/schema_hints/metadata/<product>.json` for safety, interface,
`runtime_gate`, and optional parameter overlays (`parameters` / `cli_path`).
- `internal/cli/schema_hints/selection/<product>.json` for reviewed Agent
selection prose (`agent_summary`, `use_when`, `avoid_when`, `examples`).
- `internal/cli/schema_hints/index.json` only maps product IDs to those files.
- Native Runtime Schema identity annotations, when present, as consistency
assertions against `EffectiveCommandRegistry`. They must agree exactly and
must never materialize, infer, or override registry identity.
- Flag-to-interface property mappings and required/default semantics.
- Generated files under `internal/cli/schema_agent_metadata/` and
`internal/cli/schema_catalog.json` after running generation.
Run the reverse-completeness tests whenever the Cobra tree changes. A command
that works through `dws <path>` but cannot be found through the matching
`dws schema` lookup is a contract failure unless it has a reviewed exact
exclusion.
Metadata parameter overlays must reference an exact public runnable Cobra leaf
and real flags. They may override Schema description, interface-property/type
mapping, `required`, and `required_when`; they must not create commands or
flags, define an interface, or advertise an unknown RPC. Every authored entry
requires `reviewed: true` and a non-empty review reason.
For Agent-authored metadata or selection edits:
1. Confirm the exact command and flag names in the current Cobra tree.
2. Edit only the owning block (`metadata/` or `selection/`); do not mix fields.
3. Add the smallest possible entry; do not copy generated Catalog fields into
the input.
4. Describe user-visible semantics in `review_reason` and parameter
descriptions.
5. Run generation, drift, Schema policy, and the focused CLI tests before
proposing the change.
## Agent curation workflow (Schema hints)
Use this workflow when refreshing Agent selection prose and confirmation
alignment. Prefer **agent-authored review** over bulk merge scripts that dump
`selection-review.json` or Skill Markdown into Catalog fields.
Human-authored inputs are split into two blocks:
| Block | Path | Owns |
|---|---|---|
| **metadata** | `internal/cli/schema_hints/metadata/<product>.json` | `effect` / `risk` / `confirmation` / `idempotency` / `interface_*` / `runtime_gate` / optional `parameters` |
| **selection** | `internal/cli/schema_hints/selection/<product>.json` | `agent_summary` / `use_when` / `avoid_when` / `examples` (+ product routing) |
`index.json` only maps product IDs to those files. Do not mix selection fields
into metadata files or metadata fields into selection files.
### Goals
1. **Selection prose** is decision-oriented (Feishu/Lark style): trigger intent,
sibling-command routing, and outcome shape — not a restatement of the
summary. Delivered Catalog provenance is `reviewed_explicit` from
`selection/`.
2. **Safety** follows Runtime: `confirmation=user_required` iff the tool's
metadata `runtime_gate != none` (for example `confirm_delete`, `typed_yes`,
`confirm_dangerous`).
3. **Parameter overrides** (former Manual `commands`) live on metadata tools as
`parameters` (+ `cli_path`) and are applied into EffectiveCommandRegistry.
### Authoring
For every curated tool:
1. Edit `metadata/<product>.json` for safety/interface/gates/parameters.
2. Edit `selection/<product>.json` for selection prose (`reviewed: true`,
`review_reason`, `source_refs`).
3. Run `make generate-schema`. Do not hand-edit generated
`schema_agent_metadata/` or `schema_catalog.json`.
### Pull live MCP descriptions (personal token)
Pinned `internal/cli/schema_mcp_metadata.json` is a sanitized baseline. Prefer
live Schema from a logged-in personal session:
```bash
dws auth status # token_valid should be true
dws cache refresh # refresh discovery / tools cache
dws schema <mcp-canonical> -f json
# or CLI path: dws schema --cli-path "drive copy" -f json
```
Resolve MCP identity via `interface_ref` when CLI canonical ≠ MCP path
(example: CLI `drive.copy_document` → live `doc.copy_document`). On pull
failure, fall back to Skill + Cobra Help + pinned MCP, and record evidence
(for example `live-dws-schema:<path>#FAILED`). Never print or commit tokens.
Precedence when sources disagree: **Runtime/Cobra > live MCP > pinned MCP >
Skill (evidence only)**.
### Parallel product agents
Split work by product groups. Each agent must:
- Read Skill, Cobra/`--help`, Runtime confirmation sites, and live `dws schema`
for its tools.
- Hand-write selection + metadata; forbid wholesale JSON merges from review
dumps.
- Edit only its `metadata/<product>.json` and `selection/<product>.json`.
- **Never** `git checkout` unrelated product files to “clean scope”.
### Regenerate and gates
```bash
make generate-schema
./scripts/policy/check-runtime-confirmation-truth.sh
go test ./internal/app -run '^TestSheetFinalSchemaConfirmationMatchesRuntimeGuards$' -count=1
```
Example rules (fail generation otherwise):
- At most two examples per tool; no `--yes` in stored examples.
- Examples must match live Cobra argv (path, flags, required groups).
- No shell comments in examples.
After generation, spot-check Catalog: selection provenance is
`reviewed_explicit` from `selection/`, and `user_required` count equals
metadata `runtime_gate != none`.
`make generate-schema` is a full deterministic snapshot rebuild, not an
incremental patch over the previous Catalog. It rereads every reviewed input,
removes stale generated product metadata, and rewrites the exact metadata and
Catalog projections. Incremental work happens only when an Agent or human
edits selected `metadata/` or `selection/` entries; the next publication still
recomputes all outputs. Generated files must never be read back as merge input,
and byte guards fail generation if it changes the hint inputs or CommandRegistry.
Selection prose may choose a more or less restrictive recommendation. It cannot
create a Cobra command or flag, change parameter facts, invent an
RPC/interface, alter safety metadata, or bypass command completeness. Examples
must use an executable primary/alias path and flags accepted by the live Cobra
command; never add `--yes` to stored examples.
Every example is always checked against its real `BoundCommand`: exact path,
accepted flags, Cobra required flags/positionals, and the effective
`require_one_of`, `require_together`, and `mutually_exclusive` constraints must
all pass before execution eligibility is considered. A missing required value,
constraint failure, runtime error, or MCP resolution error is a contract bug;
none is a valid reason to skip an example.
Example execution defaults to contract validation only. Runtime execution is
opt-in: an example enters `dry_run` only when its final `ToolSpec` publishes an
explicit reviewed dry-run capability. The test never injects `--yes`, and
`risk`/`confirmation` values do not manufacture preview support. A narrow
runtime precondition that cannot be derived from the typed contract may use an
exact zero-based `example_dispositions` entry with `mode=contract_only`,
`reviewed=true`, one of the schema-enumerated reason codes, and a concrete
non-empty reason. Such a disposition may only narrow an explicit dry-run
capability; it cannot turn an ordinary contract-only example into a skip.
Duplicate, missing, and out-of-range indexes fail validation. Never catch a
dry-run failure and dynamically downgrade it to `contract_only`.
Normal Go tests run the exhaustive contract gate. Run
`make test-schema-agent-examples` to additionally execute the eligible subset
through the real Cobra `--dry-run` path with isolated HOME and blocked proxies.
The test reports stable `total`, `contract`, `dry_run`, `contract_only`,
`reviewed_manual`, and per-reason counts; changing those counts requires a
review of the corresponding typed dry-run capability or manual disposition.
This target is also part of `make policy`.
Treat every tool `use_when` entry as a reviewed positive selection scenario
whose expected result is that tool's canonical path, and every `avoid_when`
entry as a reviewed negative scenario that must not choose that tool. The
deterministic gate derives a typed evaluation fixture from these same fields;
it requires exact tool coverage, a real runnable `BoundCommandRegistry`
primary command, at least one positive and negative assertion per tool, and no
literal contradictory expectations. It does not claim that string matching
proves natural-language understanding.
Semantic selection is an explicit opt-in live-model check. Run the smoke set
(one positive and one negative scenario per product) with
`DWS_AGENT_SELECTION_LIVE=1 ARK_API_KEY=... ARK_BASE_URL=... ARK_MODEL=... go test ./internal/app -run TestManualAgentSelectionArkLive -count=1`.
Add `DWS_AGENT_SELECTION_FULL=1` to evaluate every committed tool scenario, or
set `DWS_AGENT_SELECTION_CASES` to comma-separated fixture case IDs. Normal CI
never calls a model; its blockers remain the reproducible fixture, binding,
example, provenance, and final-delivery facts.
The live evaluator sends only case IDs/scenarios plus one same-product
candidate table; expected/forbidden assertions stay local and must never be
included in the model prompt. Built-in Ark HTTPS bases are allowlisted. A
different HTTPS provider requires its exact base in
`DWS_AGENT_SELECTION_ALLOWED_BASE_URLS`; plaintext HTTP is accepted only for a
loopback test server so API credentials are never sent to an arbitrary clear
text endpoint.
## Safety metadata
Parameter and safety resolution is mostly source-precedence based and
value-neutral: do not choose a winner because one value looks stricter. A
higher-priority reviewed metadata/explicit source may intentionally raise or
lower description, mapping, `effect`, `risk`, `confirmation`, or `idempotency`.
Preserve all candidates and the selected source in provenance, and fail
same-precedence conflicts rather than silently merging them.
`required` is the exception. Cobra `MarkFlagRequired` is a hard floor: the
final Agent projection must keep `required=true` and cannot be lowered by
manual/hint overlays. Overlays may still raise an optional flag to required.
`cli_required` continues to mirror the executable Cobra marker.
For command text, reviewed `ToolSchemaHint` wins first, then command-specific
Cobra Help, then MCP metadata. Generic RPC prose may remain an unselected
provenance candidate (and parameter-level `interface_description`); it must not
overwrite a specialized leaf's title or description.
For every delivered `ToolSpec` and `ParameterSpec` field, the provenance
winner value must exactly equal the delivered value. Checking only source,
count, presence, or hash is not a sufficient final-delivery invariant.
The same resolved `ToolSpec` must drive every projection. The full leaf payload
must equal the corresponding tool in `schema --all` and the full Catalog tool.
Overview/product/group summaries and Catalog summaries must equal
`ToolSpec.ToSummaryPayload()`. An alias lookup may change only the view fields
`cli_path` and `is_alias`; it must not re-resolve or mutate the command
contract.
This build-time rule is distinct from runtime drift handling. If shipped Help
and leaf Schema disagree, pass only flags accepted by Cobra. For conflicting
safety information, do not silently take the less restrictive behavior: use
the safer interpretation or stop and report the contract drift.
Do not infer one safety field from another. In particular, `effect=destructive`
or `risk=high` does not mechanically rewrite `confirmation`; the final
precedence winner for each field is authoritative. When
`confirmation=user_required`, obtain confirmation before adding `--yes`.
Keep CLI confirmation behavior and Schema metadata consistent, and add a
semantic regression test through the final embedded loader/query delivery
path; a generator unit test or JSON count alone is insufficient.
## Current Schema boundaries
- `schema list` remains a progressive overview. `schema --all` is the stable
full-export contract: every final `SchemaIndex` tool must contain its
complete leaf parameters, constraints, and safety semantics, including an empty
`parameters` object for commands without flags. Keep it suitable for the #602
compatibility baseline and fail rather than silently emitting a partial
export.
- `schema --all` is not normal command discovery. Use overview -> product/group
-> leaf for routine Agent work. `--compact` is supported for context-saving
projections, but a compact full export is not a complete compatibility
baseline.
- `dws <path> --help` defines whether Cobra exposes a path and which flags the
executable accepts. A leaf Schema defines Agent selection, parameter mapping
and constraints, and safety/confirmation semantics. A conflict is contract
drift, not permission to guess.
- Schema and Help describe commands; neither returns DingTalk business data.
After discovery, execute the real read/search/list command to obtain data.
+2 -138
View File
@@ -6,152 +6,15 @@ The format is inspired by [Keep a Changelog](https://keepachangelog.com/) and th
## [Unreleased]
## [1.0.54] - 2026-07-21
This release promotes the validated `v1.0.54-beta.2` baseline to stable. It restores the default transport envelope for personal event output with opt-in flattening, plus Schema CLI path and plugin overlay compatibility fixes.
### Changed
- **Personal event output compatibility** (#743) — `event consume` once again preserves the transport envelope by default for `ndjson`/`json`/`pretty`, while retaining the existing `compact` processor. New Agent workflows opt into the event-specific top-level DTO with `--flatten`, which is mutually exclusive with `-f raw` and `--debug-raw-events`; `event schema --flatten` describes that DTO, while the default schema describes `type/event_type/data/headers` and points to `.data | fromjson`.
### Fixed
- **Schema CLI path compatibility** (#738) — user-facing Schema lookups once again accept space-, dot-, and slash-separated CLI paths without weakening strict canonical identity resolution.
- **Plugin CLI overlays** (#701) — installed plugins register their manifest-authored command trees again for HTTP and stdio servers, and a plugin may now replace a hidden compatibility fallback (for example `conference`) instead of being skipped as a distribution conflict.
## [1.0.54-beta.2] - 2026-07-21
This beta revalidates the same `v1.0.54-beta.1` source through the cloud release path with a sealed `OSS-Mirror: deferred` policy, because the manually tagged `v1.0.54-beta.1` push run failed on the unavailable OSS mirror channel after GitHub and npm delivery.
### Changed
- **Release delivery only** — no source changes since `v1.0.54-beta.1`; see that section for the user-visible changes under validation (#743, #738, #701).
## [1.0.54-beta.1] - 2026-07-21
This beta validates the restored default transport envelope for personal event output with opt-in flattening, plus Schema CLI path and plugin overlay compatibility fixes, on top of the validated `v1.0.53-beta.7` baseline.
### Changed
- **Personal event output compatibility** (#743) — `event consume` once again preserves the transport envelope by default for `ndjson`/`json`/`pretty`, while retaining the existing `compact` processor. New Agent workflows opt into the event-specific top-level DTO with `--flatten`, which is mutually exclusive with `-f raw` and `--debug-raw-events`; `event schema --flatten` describes that DTO, while the default schema describes `type/event_type/data/headers` and points to `.data | fromjson`.
### Fixed
- **Schema CLI path compatibility** (#738) — user-facing Schema lookups once again accept space-, dot-, and slash-separated CLI paths without weakening strict canonical identity resolution.
- **Plugin CLI overlays** (#701) — installed plugins register their manifest-authored command trees again for HTTP and stdio servers, and a plugin may now replace a hidden compatibility fallback (for example `conference`) instead of being skipped as a distribution conflict.
## [1.0.53] - 2026-07-21
This release promotes the validated `v1.0.53-beta.7` baseline to stable. It adds enterprise onboarding, declarative shortcuts, Sheet/Aitable writes, multi-account profiles, and broader personal IM events, while hardening authentication and the guarded release path.
### Added
- **Enterprise and office command coverage** — adds enterprise creation, employee invitation, and account provisioning commands; 366 declarative service shortcuts; Sheet import commands; and Aitable workflow create/update support with reviewed Schema contracts.
- **Multiple accounts in one DingTalk organization** — profiles can distinguish accounts by organization and user, select them explicitly, and log out one account or an entire organization without overwriting another account's credentials.
- **Expanded personal IM event subscriptions** (#651) — adds read-receipt, recall, and reaction events for one-to-one and group chats, plus specified-sender subscriptions by staff ID or OpenDingTalk ID.
- **Official multi-platform Homebrew channel** — ships separate stable and keg-only beta Formulae for macOS and Linux across amd64 and arm64, with isolated update PRs.
### Changed
- **Personal event output contract** (#651) — `event consume` now emits event-specific top-level structured fields; scripts that consumed the former transport envelope must use the flat fields or select `-f raw`, while `--debug-raw-events` retains the diagnostic envelope.
- **Guarded release lifecycle** — beta/stable publication now uses explicit promotion, immutable delivery proofs, protected recovery, and tag-bound optional OSS policy; an unprovisioned OSS mirror is sealed as `deferred` so GitHub, npm, and Homebrew are not blocked.
- **Relaxed stable promotion contract** (#729) — a stable release still requires a delivered, non-withdrawn beta baseline in its commit history, but no longer requires a byte-identical tree with that beta; reviewed commits merged to `main` after the beta can now ship in the stable release. Local releases now accept any sealed commit contained in `main` history and push only the release tag, so `main` is never frozen during the beta-to-stable window.
### Fixed
- **Authentication and credential reliability** — organization-policy denials stop before mutation or polling, long-running clients reload and refresh access tokens consistently, concurrent credential writes are atomic, and Windows portable-auth commands fail before reading or writing unsupported credential bundles.
- **Command validation and compatibility** — invalid Sheet/task targets fail locally, IM shortcuts preserve AI-tag and alias compatibility, and Aitable import uploads require and forward a positive file size.
- **Release publication reliability** — GitHub draft publication is bound to one verified release ID and exact assets, preflight uses isolated installer worktrees, guarded local tags remain compatible, cloud planning fingerprints the actual allocated release refs, and npm channel verification waits for bounded registry propagation without moving tags.
- **Package-manager version verification** (#735) — npm-vendored, Homebrew-installed, and packaged release binaries are now verified by searching their raw bytes for the injected version marker, so a correctly versioned stable binary is no longer rejected when the short version marker coalesces with adjacent printable linker metadata; incorrect or missing markers still fail closed.
## [1.0.53-beta.7] - 2026-07-21
This beta validates bounded npm channel verification after registry publication.
### Fixed
- **npm dist-tag eventual consistency** — Release delivery now tolerates a briefly stale `latest` or `beta` read after publishing by retrying only when npm reports a valid older version. Registry errors, invalid or incomparable tags, and channels that never converge still fail closed without moving any tag during verification.
## [1.0.53-beta.6] - 2026-07-21
This beta validates guarded local release compatibility and tag-bound OSS deferral so an unprovisioned mirror cannot block the primary release channels.
### Changed
- **Tag-bound optional OSS release mirror** — Official cloud Release runs no longer block GitHub, npm, and Homebrew delivery when an OSS bucket has not been provisioned. Cloud tags immutably record `OSS-Mirror: enabled|deferred`; publication, repair, and withdrawal consume that sealed policy instead of the current repository variable. Enabled releases remain fail-closed, while deferred releases skip the nonexistent channel and cannot be backfilled without a future audited repair proof.
### Fixed
- **Guarded local release compatibility** — The tag-push Release workflow now accepts the `Channel`-only annotated tags created by the guarded local release entry while continuing to reject any partial cloud-only seal metadata.
- **Cloud release tag allocation fingerprint** — Release planning now fingerprints the actual `v*` and `withdrawn/v*` refs fetched from GitHub, matching the seal job's API view instead of hashing an empty non-wildcard ref prefix and rejecting every publish before tag creation.
## [1.0.53-beta.5] - 2026-07-21
This beta validates long-running access-token recovery and the faster, recoverable guarded release path introduced after v1.0.53-beta.4.
### Changed
- **Fast guarded beta and stable releases** — successful local release checks now leave a six-hour proof bound to the exact version, commit, repository identity, remote `main`, and stable baseline, so the subsequent guarded `--publish` invocation revalidates authority without repeating tests and packaging. A default-branch governance smoke uses the same dedicated immutable-release credential as the tag workflow before any tag is allocated.
- **Protected existing-tag recovery** — `dws-release recover <version>` can resume a failed, unpublished annotated tag through the normal contract, build, Developer ID signing, immutable GitHub Release, Homebrew, npm, and OSS jobs. Recovery requires the exact tag object, peeled commit, failed tag-push run, typed version confirmation, and the protected `release-recovery` environment; successful runs are accepted as future beta/stable delivery evidence.
### Fixed
- **Long-running event authentication recovery** — personal and portal event streams resolve the current access token for every ticket request, refresh a server-rejected token with compare-and-refresh semantics, and reconnect with backoff when refresh is temporarily blocked by network failures, rate limits, or 5xx responses.
- **Consistent access-token caching and errors** — runtime, recovery, Skill, PAT polling, and personal/portal event clients now resolve user access tokens through one expiry- and publication-aware manager, so long-running processes reload rotated credentials while keychain, refresh, parse, permission, and cancellation failures remain observable instead of being collapsed into “not authenticated.”
- **Tag-push GitHub Release publication** — Draft publication now locks one GitHub Release database ID, verifies its exact tag, channel, notes, recovery marker, asset set, and uploaded bytes, then publishes and rechecks that same ID as immutable. Recovery runs use the trusted default-branch release helpers instead of the sealed tag's historical scripts, fixing the Draft-only `GET /releases/tags/{tag}` 404 without allowing the release identity to drift during recovery.
- **Release preflight reliability** — source-mode installer tests now use isolated temporary checkouts and HOME directories instead of overwriting and deleting the real repository `dws` binary, release preflight explicitly rebuilds before policy checks, and the full-suite runner gives the growing script package a non-flaky five-minute per-suite budget.
## [1.0.53-beta.4] - 2026-07-17
This beta validates the expanded personal IM event subscriptions and the flattened `event consume` structured output introduced after v1.0.53-beta.3.
### Added
- **Expanded personal IM event subscriptions** (#651) — adds one-to-one and group events for message read receipts, recalls, and reactions; publishes the specified-sender receive event; and lets one-to-one/sender subscriptions target either a staff `--user` or an `--open-dingtalk-id`. Event Schema now exposes these alternatives through machine-readable parameter constraints.
### Changed
- **Personal event structured output is now flat** (#651) — `event consume` projects NDJSON/JSON/pretty/compact output into event-specific top-level DTOs, so consumers read fields such as `content`, `sender`, and `conversation_id` directly instead of parsing `.data | fromjson`. This is a breaking change for scripts using the former transport envelope; the original server payload remains available through `-f raw`, while `--debug-raw-events` preserves the full diagnostic envelope.
## [1.0.53-beta.3] - 2026-07-17
This beta validates multi-account profile support and the post-v1.0.53-beta.2 compatibility fixes for Windows portable authentication, IM shortcuts, and Aitable import uploads.
### Added
- **Multiple accounts in one DingTalk organization** — profiles are keyed by `corpId:userId`, `--profile` accepts organization IDs/names plus user IDs/names, and organization-only selection uses its explicitly remembered current account or asks for an exact account when ambiguous.
### Changed
- **Profile-scoped logout and consistent token storage** — `dws auth logout --profile` can remove one account or every account in an organization, while identity token slots remain the source of truth and legacy organization/global mirrors stay compatible without overwriting newer account credentials.
### Fixed
- **Windows portable-auth contract** — `dws auth export` and `dws auth import` now fail early without reading credentials, bundles, or writing files instead of claiming portable-bundle support for DPAPI-protected HKCU Registry credentials.
- **IM shortcut message tags and compatibility aliases** (#646) — IM send shortcuts now add the same AI-sent marker as `chat message send` by default, support `--ai-tag=false` to opt out, and preserve compatible search, conversation-ID, and page-size aliases.
- **Aitable import upload file-size validation** (#654) — `dws aitable import upload` and `dws aitable +import-upload` now require a positive `--file-size` and always send it to the upload-preparation API, preventing invalid requests without the actual file size.
## [1.0.53-beta.2] - 2026-07-16
This beta validates the accumulated post-v1.0.52 command surface, release automation, and runtime hardening changes, including enterprise contact onboarding, declarative shortcuts, Sheet/Aitable writes, multi-platform Homebrew formulas, and credential and target-validation fixes.
### Added
- **Contact enterprise onboarding commands** — adds `contact org create`, `contact user invite`, and `contact account create` for creating a DingTalk enterprise, inviting an employee by mobile, and provisioning an enterprise login account, with reviewed Schema contracts and mono/multi Skill routing.
- **Declarative shortcut commands** (#592) — adds 366 `dws <service> +<command>` shortcuts across 16 services, including one-to-one MCP wrappers and multi-step smart workflows. Shortcuts publish stable Agent-visible contracts with named flags, validation and confirmation metadata, dry-run protection for writes, catalog/help routing, and optional local YAML extensions and usage recording.
- **Sheet imports and Aitable workflow writes** (#624) — adds `dws sheet import` / `sheet import create` for converting local xlsx/xls files into new online sheets, `sheet import get` for polling import tasks, and `dws aitable workflow create/update` for applying validated `workflow-dsl/v1` definitions, with matching reviewed Agent Schema and bundled Skill guidance.
- **Official multi-platform Homebrew channel** — stable `Formula/dingtalk-workspace-cli.rb` and keg-only `Formula/dingtalk-workspace-cli-beta.rb` live in this repository and select signed macOS Intel/Apple Silicon or Linux amd64/arm64 artifacts at install time. Stable and beta releases open isolated Formula update PRs after final artifact signing, so beta never replaces the stable Formula. Agent Skills stay under `pkgshare` without mutating the user's home directory, and both tracks are covered by the six-channel post-release verifier.
### Changed
- **Guarded prerelease and stable automation** — adds the guided `dws-release` entry for one-command CHANGELOG preparation, validation-only and annotated-tag publication flows; promotes only an explicitly validated beta; verifies command-tree compatibility and all six packaged binaries; and serializes immutable GitHub Release, npm channel, OSS, Homebrew, and optional Gitee delivery with fail-closed recovery checks.
- **Reviewed historical release recovery proofs** — release preflight can recognize an explicitly pinned successful recovery delivery for a historical stable tag while still rejecting arbitrary workflow dispatches, mismatched commits, and incomplete release, signing, or publication jobs.
### Fixed
- **PAT organization-policy denials stop immediately** — `PAT_ORG_POLICY_DENIED` now remains terminal even if a backend also returns `flowId`, authorization URLs, or client credentials; the CLI does not mutate process credentials, open a browser, poll, or retry until an organization administrator changes the policy.
- **Sheet and task invalid-target failures** — `sheet range read/get` now rejects a null cell-info response instead of printing `null` and exiting successfully, while task completion and attachment listing verify that a task exists before calling lenient backend endpoints. Attachment listing is also published through Runtime Schema for schema-first Agent discovery.
- **Concurrent credential writes and reentrant CLI execution** — secure-token writers now use isolated, exclusive temporary files before atomic replacement so concurrent processes cannot remove each other's in-flight data, and repeated in-process CLI runs close the previous file logger before replacing it instead of retaining the prior log-file handle.
- **Sheet and Todo invalid-target failures** — `sheet range read/get` now rejects a null cell-info response instead of printing `null` and exiting successfully, while Todo completion and attachment listing verify that a task exists before calling lenient backend endpoints. Attachment listing is also published through Runtime Schema for schema-first Agent discovery.
## [1.0.52] - 2026-07-14
@@ -255,6 +118,7 @@ This release promotes the sealed **remove-discovery delivery** from the beta lin
- **Command-surface regression tests** — root-command tests now cover real `contact label`/`role` dry-runs, hidden top-level contact compatibility entries, `chat file upload` downline behavior, and `calendar event list --dry-run`.
- **Release hygiene tests** — skill markdown policy still blocks unsupported conference routes, plugin loader tests assert optional validation failures stay quiet at WARN level, and doc version cursor extraction has nested-envelope coverage.
## [1.0.47] - 2026-07-05
This release adds **connector supervision & health monitoring** (`dev connect list/status/restart/stop`) and fixes **bot-to-bot @-mention** delivery end-to-end.
+5 -9
View File
@@ -10,13 +10,9 @@ under the project [Apache License 2.0](./LICENSE).
## Before You Start
1. Read `README.md`.
2. Normalize the task and select checks with
[`docs/coding-agent-guide.md`](./docs/coding-agent-guide.md).
3. Read the relevant docs under `docs/`. CLI/Schema/Agent metadata work must
also follow
[`docs/schema-contributor-guide.md`](./docs/schema-contributor-guide.md).
4. Inspect the code and tests for the area you will change.
5. Decide the smallest safe change that satisfies the request.
2. Read the relevant docs under `docs/`.
3. Inspect the code and tests for the area you will change.
4. Decide the smallest safe change that satisfies the request.
Maintainers and automation authors should also read
`docs/automation.md` for repo-local release and agent workflow
@@ -40,8 +36,8 @@ Common repository checks already used here include:
./scripts/policy/check-open-source-assets.sh
go test ./...
make test
make test-plan
make lint
bash test/scripts/run_all_tests.sh --jobs 8
./scripts/policy/check-generated-drift.sh
./scripts/policy/check-command-surface.sh --strict
./scripts/release/verify-package-managers.sh
@@ -52,7 +48,7 @@ git diff --check
1. Keep implementation and tests in sync.
2. Run `./scripts/dev/ci-local.sh`.
3. Run `./scripts/policy/check-command-surface.sh --strict` when command paths/flags change. CI also runs `./scripts/policy/check-command-compatibility.sh --base-ref <main-ref> --stable-ref <latest-GA-tag>` against both the target branch and latest stable release.
3. Run `./scripts/policy/check-command-surface.sh --strict` when command paths/flags change.
4. Run `./scripts/policy/check-generated-drift.sh` when generated artifacts may change.
5. Run `./scripts/release/verify-package-managers.sh` when packaging or installer surfaces change (run `make package` first).
6. Update docs and `CHANGELOG.md` for behavior/interface changes.
+11 -11
View File
@@ -1,33 +1,33 @@
class DingtalkWorkspaceCliBeta < Formula
desc "Automate DingTalk workspace tasks from the terminal (beta channel)"
homepage "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli"
version "1.0.54-beta.2"
version "1.0.52-beta.5"
license "Apache-2.0"
keg_only "it is the beta channel and conflicts with dingtalk-workspace-cli"
on_macos do
if Hardware::CPU.arm?
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.54-beta.2/dws-darwin-arm64.tar.gz"
sha256 "46b57bed1f6e9f7ba007d8a86a6f5eb280fdeb557fc9bb5946f14f9b1f8f0c9f"
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.52-beta.5/dws-darwin-arm64.tar.gz"
sha256 "7164f2b0389ce0c3bc1d745b5c98082c1ef92c8547c9b123dcb4e83fe172f92e"
else
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.54-beta.2/dws-darwin-amd64.tar.gz"
sha256 "1b7fd08e64b1c86bbcee217604ffe07e0e8f1b3b5c4de518534386972bcf0f9b"
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.52-beta.5/dws-darwin-amd64.tar.gz"
sha256 "6ebd48fb96009cf2a81eb0af15216ba050620db55470d5c9937467aa66558879"
end
end
on_linux do
if Hardware::CPU.arm?
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.54-beta.2/dws-linux-arm64.tar.gz"
sha256 "108d3861ef606519f9934530d29654eab55a73607d1ee6775461f98ef5a6acd4"
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.52-beta.5/dws-linux-arm64.tar.gz"
sha256 "5f718244665c33a9327130874788d0fad36824ec29eb437ab82aa83e3d5a0579"
else
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.54-beta.2/dws-linux-amd64.tar.gz"
sha256 "6cb96ee09419bbbcc1eb336218ac2aa1d9ca0ed5cbd5a80c79bc20e1e1f03ff7"
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.52-beta.5/dws-linux-amd64.tar.gz"
sha256 "e79abccc1e093b946be89282bd034ba60ab479cc8ee1a51001eb0d441c66125c"
end
end
resource "skills" do
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.54-beta.2/dws-skills.zip"
sha256 "572b93f04a10268d185ad1f8e70e0d412949ae056be8494a9949387076fd14bc"
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.52-beta.5/dws-skills.zip"
sha256 "64c48271de89a94f9c184a475692e0e2f5e23bc0480c10824f717b21e3a83097"
end
def install
+11 -13
View File
@@ -1,33 +1,32 @@
class DingtalkWorkspaceCli < Formula
desc "Automate DingTalk workspace tasks from the terminal"
homepage "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli"
version "1.0.54"
version "1.0.52"
license "Apache-2.0"
on_macos do
if Hardware::CPU.arm?
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.54/dws-darwin-arm64.tar.gz"
sha256 "8ae0e52cf973f6fb3df61c67a41fd11e2df417a0c815762b6060cbcb5e600c08"
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.52/dws-darwin-arm64.tar.gz"
sha256 "4f6b4d064a76bcefac42feb5f356253fe43f9499b8cec9d2cdf202e7d3b9b60c"
else
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.54/dws-darwin-amd64.tar.gz"
sha256 "11b711b9d70dea62304bf5f8206c56b4e7ea91148dafe97fb7c0f844a2a61da3"
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.52/dws-darwin-amd64.tar.gz"
sha256 "abc87128f4b98d0a01ea99235449031971db8fa4ce94167403e3b736c4b81e9a"
end
end
on_linux do
if Hardware::CPU.arm?
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.54/dws-linux-arm64.tar.gz"
sha256 "9c7ecb4c8cd55644b2faa73f6ce7843c0279b23793e23deb5061692ea71a0cf1"
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.52/dws-linux-arm64.tar.gz"
sha256 "0d357ef0535f99f2f63b5ecbfdee9c32448be2a2c24f3096c03126b3b7570bc5"
else
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.54/dws-linux-amd64.tar.gz"
sha256 "8a0bc245747fc3facf98c8103c06da46852a30bff31ac93b0aa874e8c7e46db7"
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.52/dws-linux-amd64.tar.gz"
sha256 "b7dfd9a4b3489211359261747ed0cb9c8c261434bb762ad3f76df33bdbabd5cb"
end
end
resource "skills" do
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.54/dws-skills.zip"
sha256 "7450fd0115c75bfe6820c7099f348973d9353cca9d8d647c9cddcd70978a7ec0"
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.52/dws-skills.zip"
sha256 "0fa3c8dec500c1659e6480d6772ae901b2d12d24322dd5d7283f016024290c21"
end
def install
@@ -53,7 +52,6 @@ class DingtalkWorkspaceCli < Formula
<<~EOS
Agent Skills are bundled in #{pkgshare}/skills/dws.
Run `dws skill setup` to install them into your Agent directories.
EOS
end
+13 -77
View File
@@ -1,14 +1,9 @@
GO ?= go
DWS_PACKAGE_VERSION ?= 0.0.0-test
REMOTE ?=
PUBLISH ?= 0
YES ?= 0
DWS_POLICY_TMPDIR ?= $(CURDIR)/.worktrees/policy-tmp
POLICY_GOTMPDIR ?= $(DWS_POLICY_TMPDIR)/go
POLICY_ENV = DWS_POLICY_TMPDIR="$(DWS_POLICY_TMPDIR)" GOTMPDIR="$(POLICY_GOTMPDIR)"
GO_SOURCE_LIST = git ls-files -z --cached --others --exclude-standard -- '*.go'
.PHONY: all help build rebuild test test-plan lint format-check fmt policy coding-agent-harness coding-agent-task edition-test interface-integrity authoritative-interface-integrity coverage-gate coverage-gate-platform update-interface-baseline reset-interface-baseline schema-compatibility skill-command-integrity cli-smoke mock-mcp-smoke test-schema-agent-examples generate-schema generate-schema-agent-metadata generate-schema-catalog package release release-pre release-stable changelog-pre changelog-stable publish-homebrew-formula setup-hooks
.PHONY: all help build rebuild test lint fmt policy edition-test interface-integrity authoritative-interface-integrity coverage-gate coverage-gate-platform update-interface-baseline reset-interface-baseline schema-compatibility skill-command-integrity cli-smoke mock-mcp-smoke test-schema-agent-examples generate-schema generate-schema-agent-metadata generate-schema-catalog package release publish-homebrew-formula setup-hooks
all: setup-hooks fmt lint build test rebuild
@@ -16,17 +11,13 @@ help:
@printf "Available targets:\n"
@printf " make build - Build the dws CLI binary\n"
@printf " make test - Run the Go test suite\n"
@printf " make test-plan - Verify every default Go package belongs to one CI test shard\n"
@printf " make lint - Run formatting checks, go vet, and staticcheck\n"
@printf " make format-check - Check all repository Go source files with gofmt\n"
@printf " make fmt - Format all repository Go source files\n"
@printf " make lint - Run formatting checks and golangci-lint when available\n"
@printf " make fmt - Format Go source files\n"
@printf " make policy - Check the built dws plus open-source and Schema policies\n"
@printf " make coding-agent-harness - Validate coding-agent task intake, routing, and self-check contracts\n"
@printf " make coding-agent-task TASK=<file> - Validate a filled coding-agent task contract\n"
@printf " make interface-integrity - Check historical commands and help contracts still work\n"
@printf " make authoritative-interface-integrity BASE_REF=<ref> - Check the Git-owned PR merge-base\n"
@printf " make coverage-gate BASE_REF=<ref> - Enforce overall non-regression and 100%% changed-code coverage\n"
@printf " make coverage-gate-platform BASE_REF=<ref> PROFILE=<file> - Enforce 100%% native changed-code coverage\n"
@printf " make coverage-gate BASE_REF=<ref> - Enforce overall non-regression and changed-code coverage\n"
@printf " make coverage-gate-platform BASE_REF=<ref> PROFILE=<file> - Enforce native-platform changed-code coverage\n"
@printf " make update-interface-baseline - Add new CLI contracts without removing history\n"
@printf " make reset-interface-baseline - DANGEROUS: replace all CLI compatibility history\n"
@printf " make schema-compatibility BASE_REF=<ref> - Check the complete Schema contract against the PR merge-base\n"
@@ -37,11 +28,8 @@ help:
@printf " make generate-schema - Regenerate embedded Agent metadata and the release Catalog\n"
@printf " make generate-schema-agent-metadata - Regenerate versioned Agent metadata\n"
@printf " make generate-schema-catalog - Regenerate the embedded release Catalog\n"
@printf " make package - Build all release artifacts locally\n"
@printf " make changelog-pre VERSION=vX.Y.Z-beta.N - Prepare prerelease notes\n"
@printf " make changelog-stable VERSION=vX.Y.Z FROM_BETA=vX.Y.Z-beta.N - Prepare stable notes\n"
@printf " make release-pre VERSION=vX.Y.Z-beta.N [PUBLISH=1] - Validate or publish prerelease\n"
@printf " make release-stable VERSION=vX.Y.Z FROM_BETA=vX.Y.Z-beta.N [PUBLISH=1] - Validate or publish stable\n"
@printf " make package - Build all release artifacts locally (goreleaser snapshot)\n"
@printf " make release - Build and publish a release via goreleaser\n"
@printf " make publish-homebrew-formula - Push dist/homebrew/dingtalk-workspace-cli.rb to a tap repo\n"
build:
@@ -51,32 +39,13 @@ rebuild:
@./scripts/dev/build.sh
test:
@DWS_PACKAGE_VERSION="$(DWS_PACKAGE_VERSION)" $(GO) test -count=1 -timeout=10m ./...
test-plan:
@./scripts/ci/test-packages.sh verify
@./test/scripts/run_all_tests.sh
lint:
@./scripts/dev/lint.sh
format-check:
@set -eu; \
go_files="$$(mktemp "$${TMPDIR:-/tmp}/dws-go-files.XXXXXX")"; \
trap 'rm -f "$$go_files"' EXIT HUP INT TERM; \
$(GO_SOURCE_LIST) > "$$go_files"; \
unformatted="$$(xargs -0 sh -c 'if [ "$$#" -gt 0 ]; then exec gofmt -l -- "$$@"; fi' sh < "$$go_files")"; \
if [ -n "$$unformatted" ]; then \
printf '%s\n' "$$unformatted"; \
printf '%s\n' "Go files are not formatted. Run 'make fmt'." >&2; \
exit 1; \
fi
fmt:
@set -eu; \
go_files="$$(mktemp "$${TMPDIR:-/tmp}/dws-go-files.XXXXXX")"; \
trap 'rm -f "$$go_files"' EXIT HUP INT TERM; \
$(GO_SOURCE_LIST) > "$$go_files"; \
xargs -0 sh -c 'if [ "$$#" -gt 0 ]; then exec gofmt -w -- "$$@"; fi' sh < "$$go_files"
@find cmd internal test scripts/policy -name '*.go' -print0 2>/dev/null | xargs -0r gofmt -w
policy:
@mkdir -p "$(POLICY_GOTMPDIR)"
@@ -88,13 +57,6 @@ policy:
@$(POLICY_ENV) ./scripts/policy/check-schema-binary.sh
@$(POLICY_ENV) $(MAKE) test-schema-agent-examples
coding-agent-harness:
@./scripts/policy/check-coding-agent-harness.sh
coding-agent-task:
@test -n "$(TASK)" || { printf '%s\n' 'TASK is required, e.g. make coding-agent-task TASK=task.md' >&2; exit 2; }
@./scripts/policy/check-coding-agent-harness.sh -task "$(TASK)"
edition-test:
$(GO) test -v -count=1 ./pkg/editiontest/...
@@ -167,8 +129,8 @@ generate-schema-catalog:
-output internal/cli/schema_catalog.json
package:
@version="$(if $(VERSION),$(VERSION),v0.0.0-SNAPSHOT)"; VERSION="$${version#v}" ./scripts/dev/build-all.sh
@version="$(if $(VERSION),$(VERSION),v0.0.0-SNAPSHOT)"; DWS_PACKAGE_VERSION="$$version" ./scripts/release/post-goreleaser.sh
@./scripts/dev/build-all.sh
@./scripts/release/post-goreleaser.sh
publish-homebrew-formula:
@./scripts/release/publish-homebrew-formula.sh
@@ -176,32 +138,6 @@ publish-homebrew-formula:
setup-hooks:
@git config core.hooksPath scripts/hooks 2>/dev/null || true
changelog-pre:
@test -n "$(VERSION)" || (printf 'VERSION is required, e.g. v1.2.3-beta.1\n' >&2; exit 2)
@./scripts/release/prepare-changelog.sh prerelease "$(VERSION)"
changelog-stable:
@test -n "$(VERSION)" || (printf 'VERSION is required, e.g. v1.2.3\n' >&2; exit 2)
@test -n "$(FROM_BETA)" || (printf 'FROM_BETA is required, e.g. v1.2.3-beta.2\n' >&2; exit 2)
@./scripts/release/prepare-changelog.sh stable "$(VERSION)" --from-beta "$(FROM_BETA)"
release-pre:
@test -n "$(VERSION)" || (printf 'VERSION is required, e.g. v1.2.3-beta.1\n' >&2; exit 2)
@test -n "$(REMOTE)" || (printf 'REMOTE is required, e.g. origin\n' >&2; exit 2)
@args=""; \
if [ "$(PUBLISH)" = "1" ]; then args="$$args --publish"; fi; \
if [ "$(YES)" = "1" ]; then args="$$args --yes"; fi; \
./scripts/release/release.sh prerelease "$(VERSION)" --remote "$(REMOTE)" $$args
release-stable:
@test -n "$(VERSION)" || (printf 'VERSION is required, e.g. v1.2.3\n' >&2; exit 2)
@test -n "$(FROM_BETA)" || (printf 'FROM_BETA is required, e.g. v1.2.3-beta.2\n' >&2; exit 2)
@test -n "$(REMOTE)" || (printf 'REMOTE is required, e.g. origin\n' >&2; exit 2)
@args=""; \
if [ "$(PUBLISH)" = "1" ]; then args="$$args --publish"; fi; \
if [ "$(YES)" = "1" ]; then args="$$args --yes"; fi; \
./scripts/release/release.sh stable "$(VERSION)" --from-beta "$(FROM_BETA)" --remote "$(REMOTE)" $$args
release:
@printf 'Use make release-pre or make release-stable; direct goreleaser publishing is disabled.\n' >&2
@exit 2
goreleaser release --clean
@./scripts/release/post-goreleaser.sh
+12 -28
View File
@@ -283,22 +283,16 @@ Credentials are securely persisted after first login (Keychain). Subsequent runs
<details>
<summary><strong>Multiple organizations (profiles)</strong></summary>
`dws` can stay logged in to several DingTalk accounts at once, including multiple accounts in the same organization. A profile is uniquely identified by `corpId:userId`; the current profile decides which identity a command runs as.
`dws` can stay logged in to several DingTalk organizations at once. Each organization is one **profile**; the current profile decides which org a command runs against (credentials are stored per organization).
```bash
dws auth login # add or refresh one account
dws profile list # list every logged-in account
dws profile switch <corpId:userId> # persistently switch; use - to toggle back
dws profile switch "<corpName>:<userName>" # friendly input; names must be unique
dws --profile <corpId> contact user search --query "..." # use that org's explicitly recorded current account
dws --profile <corpId:userId> contact user search --query "..." # use one exact account without changing the default
dws auth login # log in to another org → adds a profile (first login becomes the primary)
dws profile list # list logged-in orgs (primary / current marker, status)
dws profile switch <name|corpId> # switch the default org (use - to toggle back to the previous one)
dws --profile <name|corpId> contact user search --query "..." # run one command against a specific org, without changing the default
```
Selectors support `corpId:userId`, `corpId:userName`, `corpName:userId`, and `corpName:userName`. Friendly names are input aliases only; use the stable `profile` value returned by `profile list` for automation. Duplicate organization or account names fail with explicit `corpId:userId` candidates. If an organization has multiple accounts but no recorded current account, `--profile <corpId>` fails instead of choosing the first or most recently used account.
`currentProfile`, `previousProfile`, and per-organization defaults are stored as exact identities. `primaryProfile` remains in JSON only for compatibility and is not used for selection. `profile list` reads status and expiry from each real identity Token without refreshing it. `auth logout --profile <corpId>` removes all local accounts in that organization; an exact selector or local profile name removes one account.
Cross-org reads are orchestrated by the agent rather than a built-in `--all-orgs`: list profiles, group by `corpId`, and use the unique `isOrgCurrent=true` account for each organization. If a multi-account organization has no default, ask the user to choose an account first. Writes default to the current account — confirm both organization and account before cross-org writes.
Cross-org reads are orchestrated by the agent rather than a built-in `--all-orgs`: list the profiles, run the query per org with `--profile`, then merge. Writes default to the current org only — confirm the target org before writing across orgs.
On macOS, an unreadable registered token slot blocks a new OAuth login rather than risking a mixed Keychain/file-DEK state. If normal terminal commands can still read the login while a sandbox using `DWS_DISABLE_KEYCHAIN=1` cannot, migrate the legacy and profile auth entries without exposing tokens:
@@ -308,7 +302,7 @@ env -u DWS_DISABLE_KEYCHAIN dws auth migrate-keychain --to file-dek --yes --form
DWS_DISABLE_KEYCHAIN=1 dws auth status --format json
```
The migration validates every selected auth ciphertext before writing, ignores unrelated application secrets, and can be rerun after an interrupted commit. If validation identifies genuinely damaged ciphertext, remove only the affected account with `dws auth logout --profile <corpId:userId>`, or all accounts in one organization with `--profile <corpId>`, then log in again. Use `dws auth reset` only when you intend to discard every local profile.
The migration validates every selected auth ciphertext before writing, ignores unrelated application secrets, and can be rerun after an interrupted commit. If validation identifies genuinely damaged ciphertext, remove only the affected profile with `dws auth logout --profile <name|corpId>`, then log in again. Use `dws auth reset` only when you intend to discard every local profile.
</details>
@@ -329,9 +323,6 @@ dws auth status # confirm "Refresh Token: valid"
```
The bundle includes the encrypted keychain under `~/.local/share/dws-cli` (with `auth-token.enc` and `dek`) plus required `~/.dws` config files.
Windows export and import are intentionally rejected before credentials or
bundles are read: Windows stores credentials as DPAPI-protected HKCU Registry
values, and the current file-DEK bundle has no safe DPAPI-to-portable conversion.
</details>
@@ -476,8 +467,6 @@ Env vars: `DWS_SKILL_MODE=mono|multi` (also honored by `install.sh` / `install.p
`dws event consume` subscribes as the currently logged-in user over a managed Stream WebSocket and emits each event as one NDJSON line on stdout. The public catalog currently covers messages that mention the current user, one-to-one messages with a specified user, and messages in a specified group.
The default `ndjson`, `json`, and `pretty` output preserves the transport envelope (`type`, `event_type`, string `data`, and `headers`) for existing scripts; `compact` retains its existing processor. Add `--flatten` to emit the stable top-level business fields used by Agent workflows. `--format` controls JSON serialization; `--flatten` controls the data structure and cannot be combined with `-f raw` or `--debug-raw-events`.
> **Prerequisite**: run `dws auth login`. Personal identity is resolved from the OAuth token and cannot be supplied through command-line identity flags.
For an event-focused installation, use the official convenience installer:
@@ -489,27 +478,22 @@ curl -fsSL https://raw.githubusercontent.com/DingTalk-Real-AI/dingtalk-workspace
```bash
# Inspect the public personal event catalog and schema
dws event list
dws event schema user_im_message_receive_o2o --flatten
dws event schema user_im_message_receive_o2o
# Listen for messages that mention the current user
dws event consume user_im_message_receive_at --flatten -f ndjson
dws event consume user_im_message_receive_at -f ndjson
# Listen for one-to-one messages with a specified user
dws event consume user_im_message_receive_o2o --user <userId> --flatten -f ndjson
# Listen by openDingtalkId (external contact, bot, or cross-organization identity)
dws event consume user_im_message_receive_o2o --open-dingtalk-id <openDingtalkId> --flatten -f ndjson
dws event consume user_im_message_receive_o2o --user <userId> -f ndjson
# Listen for messages in a specified group
dws event consume user_im_message_receive_group --group <openConversationId> --flatten -f ndjson
dws event consume user_im_message_receive_group --group <openConversationId> -f ndjson
# Inspect local consumers and cancel a subscription
dws event status
dws event stop <subscribe_id>
```
For one-to-one and specified-sender events, use exactly one target identity: `--user` for an internal `userId`, or `--open-dingtalk-id` for an `openDingtalkId`. The CLI does not infer or convert between these identity types.
| Feature | Details |
|---------|---------|
| Managed lifecycle | `consume` creates or reuses the personal subscription; `stop` cancels it and cleans local state |
@@ -671,7 +655,7 @@ See [`docs/robot-quickstart.md`](./docs/robot-quickstart.md) for the full 4-step
| Service | Command | Capabilities |
|---------|---------|--------------|
| Contact | `contact` | Look up users, departments, labels, roster profiles and dismissals; create enterprises and enterprise accounts; invite employees |
| Contact | `contact` | Look up users by name / mobile / job-number, departments, labels & roles, roster profiles & dismissals |
| Chat / IM | `chat` (`im`) | Send / reply / search messages, group & member management, bot & webhook messaging, reactions, recall |
| Calendar | `calendar` | Events CRUD, attendees, meeting rooms, free/busy & time suggestions |
| Todo | `todo` | Create / list / update / complete tasks and comments |
+12 -25
View File
@@ -280,22 +280,16 @@ dws auth login --client-id <your-app-key> --client-secret <your-app-secret>
<details>
<summary><strong>多组织(profile)</strong></summary>
`dws` 可以同时登录多个钉钉账号,同一组织也能保留多个账号。一个 profile 由 `corpId + userId` 唯一确定。
`dws` 可以同时登录多个钉钉组织。一个组织就是一个 **profile**,当前 profile 决定本次命令操作哪个组织(凭证按组织分别存储)。
```bash
dws auth login # 新增或刷新一个账号
dws profile list # 列出全部账号,profile 字段是稳定的 corpId:userId
dws profile switch <corpId:userId> # 持久切换账号;用 - 切回上一个
dws profile switch "组织名:用户名" # 名称输入要求唯一
dws --profile <corpId> contact user search --query "..." # 使用该组织明确记录的当前账号
dws --profile <corpId:userId> contact user search --query "..." # 单次精确指定账号,不改默认账号
dws auth login # 再登录一个组织 → 新增一个 profile(首次登录的为主组织)
dws profile list # 列出已登录组织(主 / 当前标记、状态)
dws profile switch <名称|corpId> # 切换默认组织(用 - 切回上一个)
dws --profile <名称|corpId> contact user search --query "..." # 单次对指定组织执行,不改默认组织
```
支持 `corpId:userId`、`corpId:userName`、`corpName:userId`、`corpName:userName`。名称只用于输入,自动化应使用 `profile list` 返回的稳定 `profile`。组织名或用户名重名时会列出候选并报错;同组织多账号但没有明确当前账号时,只传组织也会报错,不会选择第一项或最近使用账号。
`currentProfile`、`previousProfile` 和组织默认账号都保存精确身份。`primaryProfile` 只为 JSON 兼容保留,不再参与选择。`profile list` 直接读取各身份 Token 计算状态和到期时间,不触发刷新。`auth logout --profile <corpId>` 退出该组织全部账号;精确选择器或本地 profile 名只退出一个账号。
跨组织读取由 agent 编排,而非内置 `--all-orgs`:先 `dws profile list`,每个组织使用唯一的 `isOrgCurrent=true` 账号;若多账号组织没有默认账号,先让用户指定账号。写操作默认只在当前账号执行——跨组织写之前先确认目标组织和账号。
跨组织读取由 agent 编排,而非内置 `--all-orgs`:先 `dws profile list` 拿到组织,再对每个组织带 `--profile` 各查一遍,然后合并。写操作默认只在当前组织进行——跨组织写之前先确认目标组织。
macOS 下,如果已登记的 token slot 无法解密,为避免把系统 Keychain 和 file-DEK 写成混合状态,新的 OAuth 登录会直接拒绝。如果普通终端仍能读取登录态、只有设置 `DWS_DISABLE_KEYCHAIN=1` 的沙箱读不到,可在不暴露 token 的情况下迁移 legacy 与各 profile 的认证条目:
@@ -305,7 +299,7 @@ env -u DWS_DISABLE_KEYCHAIN dws auth migrate-keychain --to file-dek --yes --form
DWS_DISABLE_KEYCHAIN=1 dws auth status --format json
```
迁移会先验证全部认证密文再写入、忽略无关的应用密钥;提交中断后可安全重跑。如果预检确认是密文本身损坏,优先使用 `dws auth logout --profile <corpId:userId>` 只清理受影响账号;只有确认要丢弃全部本地 profile 时才用 `dws auth reset`。
迁移会先验证全部认证密文再写入、忽略无关的应用密钥;提交中断后可安全重跑。如果预检确认是密文本身损坏,报错会给出对应 `corpId`;只清理这个组织可执行 `dws auth logout --profile <名称|corpId>`,再重新登录。只有确认要丢弃全部本地 profile 时才用 `dws auth reset`。
</details>
@@ -470,8 +464,6 @@ DWS_SKILL_SOURCE=/path/to/skills dws skill setup --mode multi
`dws event consume` 使用当前 OAuth 登录用户建立托管的 Stream WebSocket 长连接,并把每条事件以 NDJSON 一行输出到 stdout。当前公开目录包括:当前用户被 @ 的消息、与指定用户的单聊消息、指定群的消息。
默认 `ndjson`、`json`、`pretty` 输出保留兼容 transport envelope(`type`、`event_type`、字符串 `data`、`headers`),`compact` 继续沿用原 processor。Agent 或新脚本显式加 `--flatten` 后,输出稳定的顶层业务字段。`--format` 控制 JSON 序列化,`--flatten` 控制数据结构,且不能与 `-f raw` 或 `--debug-raw-events` 同时使用。
> **前置条件**:先运行 `dws auth login`。个人身份从 OAuth token 解析,不允许通过命令行伪造。
只需要 event 能力时,可以使用官方便捷安装脚本:
@@ -483,27 +475,22 @@ curl -fsSL https://raw.githubusercontent.com/DingTalk-Real-AI/dingtalk-workspace
```bash
# 查看公开个人事件目录和 schema
dws event list
dws event schema user_im_message_receive_o2o --flatten
dws event schema user_im_message_receive_o2o
# 监听当前用户被 @ 的消息
dws event consume user_im_message_receive_at --flatten -f ndjson
dws event consume user_im_message_receive_at -f ndjson
# 监听与指定用户的单聊消息
dws event consume user_im_message_receive_o2o --user <userId> --flatten -f ndjson
# 使用 openDingtalkId 监听外部联系人、机器人或跨组织身份
dws event consume user_im_message_receive_o2o --open-dingtalk-id <openDingtalkId> --flatten -f ndjson
dws event consume user_im_message_receive_o2o --user <userId> -f ndjson
# 监听指定群的消息
dws event consume user_im_message_receive_group --group <openConversationId> --flatten -f ndjson
dws event consume user_im_message_receive_group --group <openConversationId> -f ndjson
# 查看本地 consume,并取消指定订阅
dws event status
dws event stop <subscribe_id>
```
单聊和指定发送人事件必须且只能选择一种目标身份:企业内部 `userId` 使用 `--user`,`openDingtalkId` 使用 `--open-dingtalk-id`。CLI 不会自动猜测或转换身份类型。
| 特性 | 说明 |
|------|------|
| 自动编排 | `consume` 创建或复用个人订阅,`stop` 取消订阅并清理本地状态 |
@@ -660,7 +647,7 @@ dws dev connect --channel auto --robot-client-id <id> --robot-client-secret <sec
| 服务 | 命令 | 能力 |
|------|------|------|
| 通讯录 | `contact` | 按姓名 / 手机号 / 工号查人,部门、角色标签、花名册与离职;创建企业、企业账号及邀请员工 |
| 通讯录 | `contact` | 按姓名 / 手机号 / 工号查人,部门、角色标签、花名册与离职 |
| 群聊 | `chat`(`im`)| 发送 / 回复 / 搜索消息,群与成员管理,机器人与 Webhook 发消息,表情反应,撤回 |
| 日历 | `calendar` | 日程 CRUD、参与者、会议室、闲忙与时间建议 |
| 待办 | `todo` | 创建 / 列表 / 修改 / 完成待办及评论 |
-195
View File
@@ -1,195 +0,0 @@
// 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.
// interface-snapshot is an internal CI helper. It is intentionally a separate
// binary so it can be copied into a temporary worktree and compiled against an
// older revision's real Cobra root.
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/app"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/i18n"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/interfacesnapshot"
)
func main() {
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
}
func run(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
printUsage(stderr)
return 2
}
switch args[0] {
case "generate":
if err := runGenerate(args[1:], stdout, stderr); err != nil {
fmt.Fprintln(stderr, err)
return 2
}
return 0
case "compare":
compatible, err := runCompare(args[1:], stdout, stderr)
if err != nil {
fmt.Fprintln(stderr, err)
return 2
}
if !compatible {
return 1
}
return 0
default:
fmt.Fprintf(stderr, "unknown command %q\n", args[0])
printUsage(stderr)
return 2
}
}
func runGenerate(args []string, stdout, stderr io.Writer) error {
flags := flag.NewFlagSet("generate", flag.ContinueOnError)
flags.SetOutput(stderr)
output := flags.String("output", "-", "snapshot output path, or - for stdout")
if err := flags.Parse(args); err != nil {
return err
}
if flags.NArg() != 0 {
return fmt.Errorf("generate accepts no positional arguments")
}
home, err := os.MkdirTemp("", "dws-interface-snapshot-*")
if err != nil {
return fmt.Errorf("create isolated home: %w", err)
}
defer os.RemoveAll(home)
environment := map[string]string{
"DWS_CONFIG_DIR": home,
"DWS_LANG": "en",
"HOME": home,
"NO_COLOR": "1",
"USERPROFILE": home,
}
type previousEnv struct {
value string
set bool
}
previous := make(map[string]previousEnv, len(environment))
for key, value := range environment {
oldValue, wasSet := os.LookupEnv(key)
previous[key] = previousEnv{value: oldValue, set: wasSet}
if err := os.Setenv(key, value); err != nil {
return fmt.Errorf("set %s: %w", key, err)
}
}
defer func() {
for key, old := range previous {
if old.set {
_ = os.Setenv(key, old.value)
} else {
_ = os.Unsetenv(key)
}
}
}()
previousLang := i18n.Lang()
defer i18n.SetLang(previousLang)
i18n.SetLang("en")
snapshot := interfacesnapshot.Capture(app.NewRootCommand())
if *output == "-" {
return interfacesnapshot.Write(stdout, snapshot)
}
file, err := os.Create(filepath.Clean(*output))
if err != nil {
return fmt.Errorf("create snapshot %q: %w", *output, err)
}
writeErr := interfacesnapshot.Write(file, snapshot)
closeErr := file.Close()
if writeErr != nil {
return fmt.Errorf("write snapshot %q: %w", *output, writeErr)
}
if closeErr != nil {
return fmt.Errorf("close snapshot %q: %w", *output, closeErr)
}
return nil
}
func runCompare(args []string, stdout, stderr io.Writer) (bool, error) {
flags := flag.NewFlagSet("compare", flag.ContinueOnError)
flags.SetOutput(stderr)
currentPath := flags.String("current", "", "candidate snapshot path")
basePath := flags.String("base", "", "target main/development baseline snapshot path")
stablePath := flags.String("stable", "", "latest stable GA snapshot path")
if err := flags.Parse(args); err != nil {
return false, err
}
if flags.NArg() != 0 {
return false, fmt.Errorf("compare accepts no positional arguments")
}
if *currentPath == "" {
return false, fmt.Errorf("compare requires --current")
}
if *basePath == "" && *stablePath == "" {
return false, fmt.Errorf("compare requires --base, --stable, or both")
}
current, err := readSnapshot(*currentPath)
if err != nil {
return false, fmt.Errorf("read current snapshot: %w", err)
}
references := make(map[string]interfacesnapshot.Snapshot, 2)
if *basePath != "" {
references["main"], err = readSnapshot(*basePath)
if err != nil {
return false, fmt.Errorf("read main/development baseline snapshot: %w", err)
}
}
if *stablePath != "" {
references["stable"], err = readSnapshot(*stablePath)
if err != nil {
return false, fmt.Errorf("read stable snapshot: %w", err)
}
}
report := interfacesnapshot.CompareAll(current, references)
encoder := json.NewEncoder(stdout)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
if err := encoder.Encode(report); err != nil {
return false, fmt.Errorf("write comparison report: %w", err)
}
return report.Compatible, nil
}
func readSnapshot(path string) (interfacesnapshot.Snapshot, error) {
file, err := os.Open(filepath.Clean(path))
if err != nil {
return interfacesnapshot.Snapshot{}, err
}
defer file.Close()
return interfacesnapshot.Read(file)
}
func printUsage(w io.Writer) {
fmt.Fprintln(w, "usage:")
fmt.Fprintln(w, " interface-snapshot generate [--output FILE]")
fmt.Fprintln(w, " interface-snapshot compare --current FILE [--base FILE] [--stable FILE]")
}
-130
View File
@@ -1,130 +0,0 @@
// 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 main
import (
"bytes"
"os"
"path/filepath"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/interfacesnapshot"
)
func TestCrossPlatformCoverageRunGenerateCapturesActualRootOffline(t *testing.T) {
var stdout, stderr bytes.Buffer
if exitCode := run([]string{"generate"}, &stdout, &stderr); exitCode != 0 {
t.Fatalf("run(generate) exit=%d stderr=%s", exitCode, stderr.String())
}
snapshot, err := interfacesnapshot.Read(bytes.NewReader(stdout.Bytes()))
if err != nil {
t.Fatalf("decode generated snapshot: %v", err)
}
commands := make(map[string]interfacesnapshot.Command, len(snapshot.Commands))
for _, command := range snapshot.Commands {
commands[command.Path] = command
}
for _, path := range []string{"dws", "dws chat", "dws dev app create"} {
if _, ok := commands[path]; !ok {
t.Errorf("actual root snapshot is missing %q", path)
}
}
for _, path := range []string{"dws completion", "dws help"} {
if _, ok := commands[path]; ok {
t.Errorf("framework-noise path %q leaked into snapshot", path)
}
}
create := commands["dws dev app create"]
if !hasFlag(create.LocalFlags, "name", "string") {
t.Errorf("dev app create local flags do not contain --name string: %#v", create.LocalFlags)
}
if !hasFlag(create.InheritedFlags, "profile", "string") {
t.Errorf("dev app create inherited flags do not contain --profile string: %#v", create.InheritedFlags)
}
}
func TestCrossPlatformCoverageRunCompareUsesBothSnapshotInputsAndExitCode(t *testing.T) {
current := commandSnapshot("dws")
mergeBase := commandSnapshot("dws")
stable := commandSnapshot("dws", "dws legacy")
dir := t.TempDir()
currentPath := writeSnapshot(t, dir, "current.json", current)
mergeBasePath := writeSnapshot(t, dir, "base.json", mergeBase)
stablePath := writeSnapshot(t, dir, "stable.json", stable)
var stdout, stderr bytes.Buffer
exitCode := run([]string{
"compare",
"--current", currentPath,
"--base", mergeBasePath,
"--stable", stablePath,
}, &stdout, &stderr)
if exitCode != 1 {
t.Fatalf("run(compare) exit=%d, want 1; stdout=%s stderr=%s", exitCode, stdout.String(), stderr.String())
}
if !bytes.Contains(stdout.Bytes(), []byte(`"reference": "main"`)) ||
!bytes.Contains(stdout.Bytes(), []byte(`"reference": "stable"`)) ||
!bytes.Contains(stdout.Bytes(), []byte(`"kind": "command_removed"`)) {
t.Fatalf("comparison report does not contain both references and the blocking change:\n%s", stdout.String())
}
}
func commandSnapshot(paths ...string) interfacesnapshot.Snapshot {
commands := make([]interfacesnapshot.Command, 0, len(paths))
for _, path := range paths {
commands = append(commands, interfacesnapshot.Command{
Path: path,
Aliases: []string{},
LocalFlags: []interfacesnapshot.Flag{},
InheritedFlags: []interfacesnapshot.Flag{},
})
}
return interfacesnapshot.Snapshot{
SchemaVersion: interfacesnapshot.SchemaVersion,
Rules: interfacesnapshot.Rules{
ExcludedCommandSubtrees: []string{},
ExcludedFlags: []string{},
},
Commands: commands,
}
}
func writeSnapshot(t *testing.T, dir, name string, snapshot interfacesnapshot.Snapshot) string {
t.Helper()
path := filepath.Join(dir, name)
file, err := os.Create(path)
if err != nil {
t.Fatalf("create %s: %v", path, err)
}
if err := interfacesnapshot.Write(file, snapshot); err != nil {
file.Close()
t.Fatalf("write %s: %v", path, err)
}
if err := file.Close(); err != nil {
t.Fatalf("close %s: %v", path, err)
}
return path
}
func hasFlag(flags []interfacesnapshot.Flag, name, flagType string) bool {
for _, flag := range flags {
if flag.Name == name && flag.Type == flagType {
return true
}
}
return false
}
+1 -3
View File
@@ -19,8 +19,6 @@ import (
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/app"
)
var exit = os.Exit
func main() {
exit(app.Execute())
os.Exit(app.Execute())
}
-27
View File
@@ -1,27 +0,0 @@
package main
import (
"os"
"testing"
)
func TestCrossPlatformCoverageMainExitsWithSuccessfulVersionCommand(t *testing.T) {
previousExit := exit
previousArgs := os.Args
t.Cleanup(func() {
exit = previousExit
os.Args = previousArgs
})
called := false
code := -1
exit = func(value int) {
called = true
code = value
}
os.Args = []string{"dws", "version"}
main()
if !called || code != 0 {
t.Fatalf("main exit = called %v, code %d", called, code)
}
}
-58
View File
@@ -2,29 +2,6 @@
`dws` is a Go CLI with a versioned, static command surface for DingTalk MCP capabilities. Cobra help serves humans; the embedded Command Catalog serves AI agents.
## Change Rules
Prescriptive layering for new code. Keep descriptions here concise; scoped
guides own the details.
1. Dependencies point inward: `cmd` → `internal/app` → `internal/helpers` →
shared layers (`executor`, `transport`, `output`, `errors`, `safety`,
`cobracmd`). Shared layers never import `helpers` or `app`.
2. New product commands go to `internal/helpers` following
[`helpers-structure-guide.md`](helpers-structure-guide.md); do not add
product logic to `internal/app`, `internal/cli`, or transport.
3. New shared behavior joins the existing shared package that owns the
contract; do not create a new shared package for a single caller.
4. Schema/Agent metadata changes start from reviewed inputs in `internal/cli`
per [`schema-contributor-guide.md`](schema-contributor-guide.md); never
hand-edit generated Catalog output.
5. Bundled skill content under `skills/` follows
[`skill-authoring-guide.md`](skill-authoring-guide.md); skills are embedded
via `skills/embed.go` and ship with the binary.
6. A new top-level package (under `internal/` or `pkg/`) requires a stated
boundary reason in its PR and an update to the Repository Structure list
below.
## High-Level Flow
1. `cmd` is the CLI entrypoint, invoking `internal/app` to build the root Cobra command tree.
@@ -66,38 +43,3 @@ guides own the details.
- `skills/`: bundled agent skills (mono/ and multi/ layouts)
- `test/`: CLI, integration, contract, unit, and skill E2E tests
- `scripts/`: install scripts, policy checks, and CI helpers
## Quality Pipeline
Quality enforcement is layered so a pull request receives fast, deterministic
admission feedback without pretending that downstream integration has already
run.
```mermaid
flowchart TB
PR["Pull request"] --> CA["CI"]
subgraph CA_CHECKS["Nine required contexts"]
L["Lint"]
T["Test"]
C["Coverage"]
P["Policy"]
E["Edition"]
I["Interface Integrity"]
A["AI Behavior"]
S["CLI Smoke"]
M["Mock MCP"]
end
CA --> CA_CHECKS
CA_CHECKS --> MAIN["Protected main"]
MAIN --> MP["Main Integration — 主干集成<br/>Multi-profile E2E"]
MAIN --> PLATFORM["Risk-selected / release native platform validation"]
MP --> RELEASE["Release delivery"]
PLATFORM --> RELEASE
```
Complete Multi-profile E2E and the ordinary full native-platform matrix are
downstream of PR admission. PRs still run primary-environment assurance and
fast cross-platform compilation; auth, keychain, OS-specific, installer, and
release changes additionally select native platform tests before merge. See
[`docs/ci-pr-gates.md`](ci-pr-gates.md) for the exact context and ruleset
contract.
+6 -62
View File
@@ -65,77 +65,21 @@ git diff --check
## Homebrew Formula PR Automation
Official tag releases require the repository Actions secret
`HOMEBREW_PR_TOKEN`. Prefer a fine-grained personal access token owned by a
maintainer or release-bot account, limited to this repository with
`Contents: write` and `Pull requests: write`. If organization policy prevents
that account from targeting the repository, use a dedicated classic token with
`HOMEBREW_PR_TOKEN`. The `DingTalk-Real-AI` organization currently does not
allow fine-grained personal access tokens to target this repository, so use a
classic personal access token owned by a maintainer or release-bot account with
only the `public_repo` scope. Do not reuse a broad developer token.
Store the dedicated token as the `HOMEBREW_PR_TOKEN` repository Actions secret
and rotate it before its configured expiration. Replace it immediately if it is
exposed, its owner loses repository access, or the release-bot ownership
changes. The Release workflow uses this
Store the non-expiring token as the `HOMEBREW_PR_TOKEN` repository Actions
secret. Replace it immediately if it is exposed, its owner loses repository
access, or the release-bot ownership changes. The Release workflow uses this
dedicated token only to push an `automation/homebrew-*` branch and open the
stable or beta Formula PR. It does not push Formula changes directly to `main`.
The default-branch governance preflight and every tag contract authenticate the
token before publication, reject over-scoped classic tokens, confirm its
identity, and run a controlled write canary. The canary pushes a unique
`automation/homebrew-token-canary-*` branch with a `[skip ci]` commit, creates a
draft PR, closes it, and deletes the branch with the same token. This proves both
Contents and Pull requests write access before publication without merging
anything. The gate also rejects reuse of `RELEASE_GOVERNANCE_TOKEN`.
No maintainer environment variable is required when creating a tag. Using the
built-in `GITHUB_TOKEN` is insufficient because organization policy prevents
Actions from creating pull requests, and its generated PR events may require
separate workflow approval.
## Release Governance and Recovery
Store `RELEASE_GOVERNANCE_TOKEN` as a dedicated Actions secret with only
repository `Administration: read`. The immutable-releases REST endpoint is an
administration setting and cannot be read by the workflow's built-in
`GITHUB_TOKEN`. Both the default-branch governance preflight and the tag
contract use this same credential so a missing or expired identity is detected
before an irreversible tag is created.
Create a protected `release-recovery` environment limited to protected
branches, with a required reviewer, self-review disabled, and administrator
bypass disabled. The workflow reads the environment through the GitHub API and
fails closed unless the required-reviewer, prevent-self-review, and protected-
branch rules are present.
Recovery is restricted to an existing annotated tag whose exact tag object,
commit, and failed tag-push run all match; it then reuses the normal release
jobs. Do not put publication secrets in temporary branches or create ad-hoc
recovery workflows.
Cloud-sealed releases mirror to OSS only when the repository variable
`ENABLE_OSS_MIRROR` is exactly `true`. Leave the variable unset while no Bucket
is provisioned; GitHub, npm, and Homebrew delivery can then complete without
running the OSS step. Once enabled, missing credentials, an invalid Bucket, or
an upload failure remains fail-closed. The cloud tag immutably records the
decision as `OSS-Mirror: enabled|deferred`; publication and withdrawal consume
that sealed value instead of the variable's later state. Deferred releases
cannot use `repair_oss_version`; enabling OSS applies to later release tags
until an audited immutable repair marker is implemented.
If an immutable GitHub Release and npm package were delivered but an enabled
downstream China mirror failed, dispatch the normal `Release` workflow from the
protected default branch with exactly one of `repair_gitee_version` or
`repair_oss_version`. Channel repair accepts a fully successful exact release,
or a failed exact-tag run only when its latest attempt completed the release
contract, build, Apple signature, immutable GitHub publication, and npm
delivery checks for the exact tagged commit. OSS repair additionally requires
the tag's sealed policy to be `enabled`. It then downloads and re-verifies the
immutable assets before invoking only the selected mirror. For a failed
release, an OSS repair requires the OSS step itself to be the recorded failure.
A Gitee repair accepts either a failed Gitee job or a Gitee job that was
skipped behind that OSS failure; the latter is an explicit Gitee backfill and
does not claim that OSS has been repaired. Gitee repair requires `GITEE_TOKEN`,
`GITEE_USER`, and `GITEE_REPO`; OSS repair requires `OSS_ACCESS_KEY_ID`,
`OSS_ACCESS_KEY_SECRET`, `OSS_ENDPOINT`, and `OSS_BUCKET` (with optional
`OSS_PREFIX`) as Actions secrets. Missing credentials fail the selected repair
closed.
## Handoff Checklist
Before handoff, include:
+65 -137
View File
@@ -1,158 +1,86 @@
# CI — PR 合入门禁
# Pull request quality gates
The pull-request admission layer has exactly nine required external contexts:
The repository defines five focused checks in addition to its existing CI:
| Required context | Contract |
|---|---|
| `Lint` | Stable PR revision classification, formatting, `go vet`, and Actionlint |
| `Test` | Race/unit/release-script tests plus fast cross-platform compilation |
| `Coverage` | Overall non-regression and 100% changed-code coverage |
| `Policy` | Repository policy and the fail-closed CHANGELOG contract |
| `Edition` | Edition contract tests |
| `Interface Integrity` | CLI, Schema, Skill, and stable-release compatibility |
| `AI Behavior` | Base-owned policy for PRs labeled `ai-generated` |
| `CLI Smoke` | Offline help for every public top-level command |
| `Mock MCP` | HTTP and stdio MCP lifecycle smoke tests |
- **Interface Integrity** enforces backwards compatibility. Every historical
command path and alias must still resolve, every historical command must
still render `-h`, and historical flags must keep their type and shorthand.
New commands, aliases, and flags are allowed. The same job compares the full
complete `dws schema --all` contract with the PR merge-base, blocking removed
products/tools/parameters, incompatible parameter or interface mappings,
constraint drift, and safety-semantic drift. It also checks that executable
`dws ...` references in `skills/**/*.md` resolve to real commands.
Help compatibility covers command/alias/flag spelling, flag type and
shorthand; descriptive prose may evolve without breaking the gate.
- **Coverage** runs unit tests on every pull request and prints both overall and
changed-code statement coverage. During the migration to the 80% repository
target, overall coverage may not regress from a profile generated from the
merge-base with the same test command, while changed production Go
statements must meet 80%. Linux, Windows, and macOS each generate a native
coverage profile for changed packages and enforce the threshold against
changed files buildable on that platform, so build-tagged source cannot be
hidden by an Ubuntu-only profile. Overall non-regression allows 0.1 percentage point of measurement
variance to avoid failing unchanged code on test-path noise. Set
`COVERAGE_ENFORCE_OVERALL=true` once repository coverage reaches 80% to make
the overall target fail closed as well.
- **CLI Smoke** builds the release binary and renders offline help for the root
and every public top-level command.
- **Mock MCP Smoke** runs the existing HTTP and stdio MCP lifecycle tests
(`Initialize -> ListTools -> CallTool`).
- **AI Behavior Check** applies to pull requests labeled `ai-generated`. It
limits the change to 30 files and blocks release/CI infrastructure changes.
It uses `pull_request_target` without checking out PR code, so the policy
cannot be bypassed by changing the workflow in the same pull request. The
evaluator writes an `AI Behavior Check` commit status to the PR head SHA so
GitHub rulesets can require it.
The workflow display name is `CI`. Parallel helper
jobs may implement `Test` and `Coverage`, but they are not ruleset contexts.
Do not require an aggregate alias or a downstream integration check in place of
the nine contracts above.
## Running the compatibility gates
`AI Behavior` is evaluated by a `pull_request_target` workflow that never
checks out or executes PR code. It writes the exact `AI Behavior` status to the
current PR head. Its Files API read is bracketed by base/head revision checks,
so a synchronize race fails closed. The same workflow supplies a successful
`AI Behavior` check run on protected `main` pushes for release governance.
## Exact CHANGELOG-only fast path
A pull request qualifies only when GitHub reports exactly one changed file,
that file is an in-place modification of `CHANGELOG.md`, and the base and head
both retain it as a regular non-executable `100644` blob. Add, delete, rename,
symlink, executable-mode, and second-file changes do not qualify.
`Lint` classifies the Files API result only after verifying that the API's base
and head equal the event revision both before and after pagination. `Policy`
checks out GitHub's PR merge ref and verifies its parents:
```text
HEAD^1 = pull_request.base.sha
HEAD^2 = pull_request.head.sha
```
It then runs:
```sh
./scripts/policy/check-changelog-pr.sh \
--fast-path "$PR_BASE_SHA" HEAD
```
Because the verified PR diff contains only `CHANGELOG.md`, the validator and
its policy dependencies in that merge tree are byte-for-byte the current base
versions. Validation targets the synthetic merge tree, not the feature-branch
tree, so a stale branch cannot supply an older validator or combine with newer
base notes into an invalid final CHANGELOG.
All nine admission contexts are still emitted and must succeed. Expensive
implementation helpers are skipped; the named contexts record that their code
surface is unaffected. After merge, the protected `main` push executes the
full admission suite.
Any PR that touches `CHANGELOG.md` but also changes another file runs the same
content contract in `Policy` with `--content-only`. That mode permits the
second file but still rejects invalid dates or versions, missing bullets,
placeholder `TODO`/`TBD`, unmanaged-section changes, and unsafe tree modes.
Adding a second file therefore cannot bypass CHANGELOG validation.
## Platform and downstream boundaries
Ordinary PRs run the primary Linux assurance plus fast Darwin/Windows compile
checks. Full native macOS/Windows tests and platform coverage run on a PR only
when its diff touches auth, keychain, OS-specific Go files, installers,
packaging, Formulae, or release automation. Protected `main` pushes run the
complete native matrix.
Complete `Multi-profile E2E` is not a PR admission context. It belongs to the
`Main Integration — 主干集成` workflow and runs only after a push to `main` (or
an explicit manual dispatch). A failing downstream run remains a real
regression and must be repaired, but it must not be represented by a synthetic
successful PR check.
```mermaid
flowchart TB
PR["Pull request"] --> ADMISSION["CI"]
ADMISSION --> L["Lint"]
ADMISSION --> T["Test"]
ADMISSION --> C["Coverage"]
ADMISSION --> P["Policy"]
ADMISSION --> E["Edition"]
ADMISSION --> I["Interface Integrity"]
ADMISSION --> A["AI Behavior"]
ADMISSION --> S["CLI Smoke"]
ADMISSION --> M["Mock MCP"]
ADMISSION --> MAIN["Protected main"]
MAIN --> NATIVE["Full native platform matrix"]
MAIN --> E2E["Multi-profile E2E"]
MAIN --> RELEASE["Release delivery"]
```
## Running focused gates locally
Run the contracts relevant to the change:
Run:
```sh
make build
make policy
make interface-integrity
make authoritative-interface-integrity BASE_REF=<merge-base>
make schema-compatibility BASE_REF=<merge-base>
make skill-command-integrity
make cli-smoke
make mock-mcp-smoke
go test -v -count=1 ./pkg/editiontest/...
make coverage-gate BASE_REF=<merge-base>
# Run on the corresponding native runner with its generated profile:
make coverage-gate-platform BASE_REF=<merge-base> PROFILE=<coverage-profile>
```
For an exact CHANGELOG-only branch:
CI derives the authoritative Interface snapshots from both the PR merge-base
and the latest reachable stable release tag. The complete Schema snapshot comes
from the PR merge-base, which contains the registry-first Schema introduced on
`main`. The candidate branch cannot bless a breaking change by editing a
fixture. Schema additions are allowed; historical products, tools, parameters,
parameter mappings, positional execution fields, constraints, and safety
semantics remain protected. Positional descriptions are documentation and may
change without breaking compatibility.
```sh
base_ref=$(git merge-base HEAD origin/main)
./scripts/policy/check-changelog-pr.sh --fast-path "$base_ref" HEAD
```
`make update-interface-baseline` still extends the local checked-in Interface
fixture used by `make interface-integrity`. Updates are monotonic: they add new
commands and flags without removing history.
`make coverage-gate` is an enforcement step, not a profile generator. CI
generates the candidate, supporting, merge-base, and (when risk-selected)
native profiles before the aggregate `Coverage` context evaluates them. The
aggregate and native gates require 100% coverage for changed executable Go
statements. Overall coverage remains an unrounded, zero-tolerance merge-base
non-regression check. Candidate and baseline profiles are evaluated by the
same block-deduplicating checker; supporting policy and shortcut profiles
contribute to changed-code coverage only. The checked-in badge is presentation
only and is never read as a gate input.
Compatibility checks derive authoritative Interface snapshots from the PR
merge-base and the latest reachable stable release. The candidate cannot bless
a breaking change by editing a fixture. Schema additions are allowed;
historical products, tools, parameters, mappings, positional execution fields,
constraints, and safety semantics remain protected.
For an intentional compatibility reset at a major-version boundary, run
`make reset-interface-baseline`. This replaces all CLI compatibility history
with the current command tree and must receive explicit human review.
## Required GitHub repository settings
The `main` quality ruleset must enable strict required-status-check policy
(`strict_required_status_checks_policy=true`) so a PR is revalidated whenever
`main` advances. It must require these exact contexts and no legacy aliases:
Create a ruleset for `main` that requires pull requests and code-owner review,
then mark these aggregate status checks as required:
- `Lint`
- `Test`
- `Coverage`
- `Policy`
- `Edition`
- `Interface Integrity`
- `AI Behavior`
- `CLI Smoke`
- `Mock MCP`
- `CI Gate`
- `Multi Profile E2E`
- `AI Behavior Check`
Do not require helper jobs, `Multi-profile E2E`, or an aggregate admission
alias. Update ruleset contexts only after the new names have appeared on the
protected branch, so a rename cannot silently remove enforcement or leave an
unproducible required context.
`CI Gate` fails closed unless every first-layer CI job succeeds, including
lint, tests, native Linux/Windows/macOS coverage, policy,
Interface/Schema/Skill integrity, and smoke tests. Requiring the aggregate
check keeps repository rules stable when an internal job is renamed or split.
The `ai-generated` label must be applied by the PR-creation automation or by a
maintainer; GitHub cannot infer reliably whether a human-authored PR contains
AI-generated code.
-112
View File
@@ -1,112 +0,0 @@
# Coding Agent Workflow
This is the task intake and self-check contract for coding agents working in
this repository. It is intentionally independent of external Wiki systems:
the checked-out repository is the execution context and evidence source.
## 1. Normalize the task input
Start from the copyable
[`coding-agent-task-template.md`](coding-agent-task-template.md). Keep one
primary outcome per task. Fill unknown fields from the issue, nearby code,
tests, and versioned docs; state any assumption that can affect behavior.
For a saved, filled template, run `make coding-agent-task TASK=path/to/task.md`.
The local checker rejects missing required fields, unsupported task kinds, and
unresolved placeholders before implementation begins.
Do not invent acceptance criteria that expand the requested behavior. Stop for
user input only when the unresolved choice would change externally visible
behavior, compatibility, destructive scope, credentials, or external state.
## 2. Establish the baseline
1. Run `git status --short` and identify pre-existing changes.
2. Read the applicable guides linked from the root `AGENTS.md`.
3. Locate the implementation and its closest tests with `rg`/`rg --files`.
4. Reproduce the bug or capture the current contract before changing it.
5. Pick the smallest owning layer; avoid duplicating policy in a caller when a
shared typed layer already owns it.
Never clean, overwrite, stage, or reformat unrelated user changes. If a
required file is already modified, inspect the overlap and preserve both
intents or stop with the exact conflict.
## 3. Implement from authoritative inputs
- Go behavior belongs in the package that owns the contract, with focused
tests beside it.
- Product handlers under `internal/helpers` follow
[`helpers-structure-guide.md`](helpers-structure-guide.md): thin
`{product}.go` wiring plus `{product}_{resource}.go` files; do not enlarge
megafiles such as `chat.go`.
- Public CLI paths and flags must match the live Cobra tree and compatibility
policies.
- Schema and Agent-facing changes start from reviewed source inputs; generated
outputs are publication artifacts.
- Documentation describes behavior that exists in the same change.
- Secrets, tokens, local identities, and private endpoints must not enter code,
fixtures, logs, or handoff output.
For generated files, run the repository generator and inspect the resulting
diff. A large or unrelated generated diff is a signal to stop and find the
wrong input or nondeterminism, not something to accept automatically.
## 4. Select validation by change surface
Run the narrow check while iterating, then the applicable admission checks
before handoff. `make help` is the authoritative target list.
| Changed surface | Focused check | Admission checks |
|---|---|---|
| Documentation only | inspect links/examples | `git diff --check` |
| Go implementation | `go test ./path/to/package` | `make format-check`, `make test` |
| CLI paths or flags | focused command/help tests | `make build`, `./scripts/policy/check-command-surface.sh --strict`, `make interface-integrity` |
| Schema registry, hints, or generators | focused generator/app tests | `make generate-schema`, `./scripts/policy/check-generated-drift.sh`, `./scripts/policy/check-schema-catalog.sh`, `make test-schema-agent-examples` |
| Skill command examples | inspect referenced `dws` help | `make skill-command-integrity` |
| CI or test sharding | run the affected script/test | `make test-plan`, `make lint`, and the CI workflow's pinned actionlint command when workflows change |
| Packaging or installers | focused release-script tests | `make package`, `./scripts/release/verify-package-managers.sh` |
| Authentication, transport, or OS-specific code | focused tests, including failure paths | `make test`; run relevant platform checks or disclose the unavailable platform |
`make policy` is the combined policy gate and is appropriate for command,
Schema, generated-asset, or broad cross-cutting changes. Platform credentials
and live services are not prerequisites for ordinary unit tests; never turn a
missing credential into permission to skip deterministic checks.
The guide contract itself is executable. Run `make coding-agent-harness` after
changing `AGENTS.md`, this guide, the Schema contributor guide, helpers
structure guide, or their routed commands and paths. This remains a local,
opt-in agent aid and is not wired into CI.
## Design references
This repository adapts two patterns without copying their product-specific
rules:
- [Lark CLI's contributor guide](https://github.com/larksuite/cli/blob/5efaf65aec59c33899475bb90e6bff1bc3b5b65c/AGENTS.md): one primary goal, machine-consumable errors/output, and validation selected by behavior surface.
- [WeCom CLI's root routing guide](https://github.com/WecomTeam/wecom-cli/blob/9eb7898b959861af879495e211e37431fa908f19/AGENTS.md) and [human helper template](https://github.com/WecomTeam/wecom-cli/blob/9eb7898b959861af879495e211e37431fa908f19/src/helpers/HUMANS.md): a thin root guide, scoped implementation guidance, and a copyable request format.
## 5. Pre-handoff self-check
Confirm every applicable item:
- The diff implements the stated goal and no unrelated cleanup.
- Pre-existing changes are still present and were not attributed to this task.
- New behavior has a regression test; removed behavior has an explicit reason.
- Public command paths, flags, output, exit behavior, and compatibility remain
intentional.
- Destructive or mutating operations retain the required confirmation path.
- Generated files came from their reviewed inputs and generation is clean.
- Docs and examples use commands accepted by current help/Schema.
- Errors preserve actionable context without leaking secrets.
- `git diff --check` passes and the final diff has been read.
- Every reported check is labeled passed, failed, or not run with a reason.
Use this compact handoff shape:
```text
Outcome: what is now true
Files: intentional files changed
Validation: exact commands and results
Limits: unrun checks, environment constraints, follow-ups
```
-35
View File
@@ -1,35 +0,0 @@
# Coding Agent Task Template
Copy this block into an issue or coding-agent request. One task should have one
primary outcome; split unrelated outcomes instead of hiding them in acceptance
criteria.
```text
Task kind: bug | feature | refactor | docs | policy | release
Goal (one primary outcome):
Current behavior and evidence:
Acceptance criteria:
In scope (packages/files/surfaces):
Out of scope:
Compatibility constraints:
Interface impact (commands/flags/output/errors/exit codes/Schema):
Safety or data-mutation constraints:
Expected validation:
Known environment limitations:
```
For a command or remote-interface task, add the smallest concrete invocation
and contract evidence available:
```text
CLI path and example argv:
Current --help or Schema excerpt:
Remote method and request/response shape, if relevant:
Expected stdout/stderr and exit behavior:
Mutation preview/confirmation behavior:
```
Do not paste credentials, tokens, private endpoints, or production business
data. Use redacted fixtures and say which evidence is unavailable. Save the
filled block and run `make coding-agent-task TASK=path/to/task.md` to validate
it before implementation.
+2 -5
View File
@@ -164,19 +164,16 @@ _Group chats, conversations, messages, and robot/webhook integrations._
## `dws contact` — Contact Directory
_Users, departments, directory lookups, and enterprise onboarding._
_Users, departments, and directory lookups._
**9 commands**
**6 commands**
| Command | Description | When to use |
|---|---|---|
| `dws contact account create` | Create a dedicated login account in the current enterprise. | When the user explicitly asks for an enterprise account or login account, rather than a new enterprise organization. |
| `dws contact dept list-members` | List members of a specific department by department ID. | When the agent needs the roster of a department to target communication or build a team overview. |
| `dws contact dept search` | Search departments in the organization's contact directory by keyword. | When the agent needs to resolve a department name to a department ID. |
| `dws contact org create` | Create a new DingTalk enterprise organization. | When the user explicitly asks to create or initialize an enterprise and provides its name and creator display name. |
| `dws contact user get` | Batch-fetch detailed profile information for one or more users by user ID. | When the agent needs names, titles, emails, or departments for a known set of user IDs. |
| `dws contact user get-self` | Retrieve the profile of the currently authenticated user. | When the agent needs to identify who it is acting on behalf of (user ID, name, org). |
| `dws contact user invite` | Invite one employee by mobile number into the current enterprise. | When the user explicitly asks to add an employee and has supplied the employee name and mobile number. |
| `dws contact user search` | Search users in the contact directory by keyword (name, title, etc.). | When the agent needs to resolve a person's display name to a user ID. |
| `dws contact user search-mobile` | Look up a user by mobile phone number. | When the agent has only a phone number and needs to find the corresponding DingTalk user. |
+8 -5
View File
@@ -1,8 +1,10 @@
# Event consume — AI subprocess contract
Defines the stable `dws event consume` subprocess contract so an
orchestrator can determine when the consumer is ready, stop it cleanly,
and machine-read why it exited.
Aligns `dws event consume` with the "AI subprocess contract" that
`lark-cli event consume` exposes, so any orchestrator (Claude Code's
Monitor, a bash bridge, systemd, an agent plugin) can drive it with zero
ambiguity: know when it is ready, stop it cleanly, and machine-read why it
exited.
Scope of this branch: the four **contract** items below. Reconnect
resilience (keeping the stream alive across a transient upstream drop) is
@@ -14,6 +16,7 @@ tracked separately and intentionally out of scope here.
- `--duration D` — wall-clock budget (exit 0). Kept as `--duration`, NOT
aliased to `--timeout`: the global `--timeout` is the HTTP request
timeout (int seconds) and would collide (different type and meaning).
Docs note the lark-cli name difference.
- Bus idle-shutdown fires only with **zero** consumers, so a connected
consumer is never idle-killed.
- SIGINT/SIGTERM already cancel the run context and return cleanly.
@@ -25,7 +28,7 @@ tracked separately and intentionally out of scope here.
On connect, emit a fixed stderr line **before** any stdout event:
```
[event] ready event_key=<key> bus_pid=<pid> subscribe_id=<id>
[event] ready event_key=<key> bus_pid=<pid>
```
Parents block on stderr until this line, then read stdout. Suppressed
@@ -72,7 +75,7 @@ or runtime failure (permissions, network, params) = non-zero, with no
### 4. Cleanup on exit (no `kill -9`)
Ownership-based cleanup:
Ownership-based, matching lark-cli:
- If this run **created** the subscription (no `--subscribe-id`), a clean
exit (SIGTERM / SIGINT / stdin-EOF / limit / timeout) **unsubscribes**
it server-side and sends Bye.
-214
View File
@@ -1,214 +0,0 @@
# Helpers Package Structure Guide
This is the coding-structure contract for product commands under
`internal/helpers/`. Business teams and coding agents must follow it when
adding or moving CLI leaves. Behavioral contracts (stdout, errors, confirmation,
Schema) stay in [`internal/helpers/AGENTS.md`](../internal/helpers/AGENTS.md);
this document only owns file layout and split rules.
Reference implementations already in-tree:
| Pattern | Use as |
|---|---|
| [`sheet.go`](../internal/helpers/sheet.go) + `sheet_*.go` | Preferred product layout: thin root wiring, resource files |
| [`chat_media_upload.go`](../internal/helpers/chat_media_upload.go) | Incremental extract from a megafile without behavior change |
| `connect_*.go` | Concern-based split inside the same `helpers` package |
Anti-pattern to stop growing: single megafiles such as `chat.go` / `aitable.go`
(thousands of lines). New work must not enlarge them.
## 1. Package boundary
Keep product handlers in the flat package `helpers`:
```text
internal/helpers/ # package helpers (default)
register_products.go # public product registration table
{product}.go # product root: new{Product}Command()
{product}_{resource}.go # one resource / cohesive concern
{product}_{resource}_test.go # focused tests beside the file
helpers.go / interfaces.go … # cross-product shared machinery
```
Do **not** create `internal/helpers/{product}/` subpackages by default. The flat
package exists so leaves can share unexported helpers (`callMCPToolOnServer`,
flag validators, confirmation wrappers, transport adapters) without exporting a
public API surface. Split into a subpackage only when the concern is a real
library boundary with its own tests and almost no need for helpers-private
symbols—and get an explicit review for that exception.
Repository layers outside helpers stay unchanged:
| Layer | Owns |
|---|---|
| `internal/app` | Root/static wiring, plugin load |
| `internal/helpers` | Product Cobra trees and handler behavior |
| `internal/cobracmd` | Shared Cobra construction primitives |
| `internal/executor`, `internal/transport` | Invocation and transport |
| `internal/output`, `internal/errors`, `internal/safety` | Projection, failures, confirmation |
| `internal/cli` | Schema identity / Agent metadata |
Ordinary product leaves belong in helpers. Do not push product business mapping
into app, transport, or Schema generators.
## 2. File roles inside a product
### 2.1 Product root — `{product}.go`
Owns exactly one entry constructor, registered from `register_products.go`:
```go
func newChatCommand() *cobra.Command { /* wire subgroups only */ }
```
The root file should:
1. Define the product `cobra.Command` (`Use` / `Short` / `Long` / aliases).
2. Call resource factories and `AddCommand` them.
3. Register product-level aliases or hint stubs when needed.
4. Avoid large inline `RunE` bodies for leaves.
Target size: wiring-only, roughly under **400 lines** (see `sheet.go` ≈ 270).
If the root grows past that because leaves are inlined, extract a resource file.
### 2.2 Resource / concern file — `{product}_{resource}.go`
Split on the **CLI path segment or cohesive concern**, not on “one function per
file”:
| CLI path | File |
|---|---|
| `dws chat group …` | `chat_group.go` |
| `dws chat message …` | `chat_message.go` |
| `dws chat media …` | `chat_media_upload.go` (or `chat_media.go`) |
| `dws sheet filter-view …` | `sheet_filter_view.go` |
| `dws sheet dimension …` | `sheet_dimension.go` |
Each file exposes one or more unexported factories, for example:
```go
func newChatGroupCmd() *cobra.Command { … }
func newChatMessageCmd() *cobra.Command { … }
func newWorkbookCmds() []*cobra.Command { … }
```
The product root only wires those factories. Prefer keeping a leaf’s flags,
`RunE`, and nearby request-mapping helpers in the same resource file until a
helper is reused by multiple resources.
Soft size guide per resource file:
| Lines | Action |
|---|---|
| &lt; 600 | Normal |
| 600–1000 | Prefer splitting the next cohesive subgroup before adding more |
| &gt; 1000 | Required split before landing substantial new leaves |
“One command per file” is **not** required. Tiny sibling leaves that share
flags and mapping belong together. Split when the file holds multiple unrelated
resources or becomes hard to review.
### 2.3 Shared product helpers — `{product}_{concern}.go`
Use a concern suffix when code is shared across resources and is not itself a
command tree:
- `sheet_validate.go` — shared validation
- `chat_args.go` / similar — grant/arg builders used by several leaves
- `connect_command.go` — slash-command parsing used by the daemon
Do not park unrelated products’ utilities in these files. Cross-product
machinery belongs in non-prefixed shared files (`helpers.go`, `interfaces.go`,
output/error helpers), never copied per product.
### 2.4 Tests
- Name tests after the file or scenario: `chat_message_search_test.go`,
`sheet_filter_view_test.go`.
- Prefer exercising public product construction (`newChatCommand().Find(…)`)
for command-surface regressions.
- Pure helpers may be unit-tested directly in the same package.
- A mechanical file split without behavior change should keep existing tests
green with no assertion edits; if tests must change, the split leaked a
behavior or visibility change and needs review.
## 3. Registration and naming
1. Public products enter the CLI only through the table in
`register_products.go` (`new{Product}Command` factories). Do not invent a
second registration path for ordinary product leaves.
2. Constructor names stay unexported (`new…`) unless a deliberate test helper
requires otherwise.
3. File names are lowercase snake_case. Match the CLI resource token when
practical (`filter-view` → `filter_view`).
4. Do not hand-edit generated sync markers in `register_products.go` outside
the product-registration workflow that owns that file.
## 4. How to add a new command (business-team checklist)
1. Confirm the owning product and CLI path with `dws <product> --help`.
2. Open `{product}.go` only to wire `AddCommand`; put the leaf in
`{product}_{resource}.go`.
3. If the product is still a megafile (`chat.go`, `aitable.go`, …) and your
resource file does not exist yet, **create the resource file and move only
the subgroup you need** (or add the new leaf there and wire it from the
root). Do not append another large leaf into the megafile.
4. Keep stdout / stderr / error / confirmation contracts from
`internal/helpers/AGENTS.md`.
5. If path, flags, safety, or Agent selection change, follow
[`schema-contributor-guide.md`](schema-contributor-guide.md).
6. Add or extend the closest test; run
`go test ./internal/helpers -count=1` (or a tighter `-run`) plus the checks
selected by [`coding-agent-guide.md`](coding-agent-guide.md).
## 5. Migrating an existing megafile
Mechanical splits are welcome and preferred over “big-bang” rewrites.
Rules for a split PR:
1. **Behavior-neutral**: same command paths, flags, help text, request mapping,
confirmation, and output.
2. **Stable entrypoint**: keep `new{Product}Command()` as the registration
symbol; only its body becomes wiring.
3. **Move by resource**: extract one CLI subgroup per commit/PR when possible
(`group`, `message`, `category`, …).
4. **No drive-by cleanups** in the same PR (renames, flag redesign, Schema
edits) unless the task explicitly includes them.
5. **Stop growing the megafile**: after the first extract, new leaves for that
resource go to the new file only.
Suggested first-wave split for `chat` (illustrative, not mandatory order):
| Extract to | Contents |
|---|---|
| `chat.go` | `newChatCommand()` wiring only |
| `chat_permission.go` | `chmod`, `data-auth` |
| `chat_group.go` | `group` tree |
| `chat_message.go` | `message` tree |
| `chat_category.go` | `category` tree |
| `chat_bot.go` | `bot` tree |
| `chat_conversation.go` | top-level conversation ops (`set-top`, mute, red-point, …) |
| existing `chat_media_upload.go` | keep; optionally rename to `chat_media.go` only in a dedicated rename PR |
Apply the same pattern to `aitable`, `attendance`, `mail`, and `doc` when those
products take new work.
## 6. What this guide does not change
- Wire format, MCP method names, or Schema identity rules.
- The choice to keep `package helpers` flat.
- Runtime confirmation / dry-run policy (still owned by safety + Schema metadata).
- Permission to skip tests because a change was “only a move”—moves still need
the product’s focused tests green.
## 7. Harness check
After editing this guide or its links from `AGENTS.md` /
`internal/helpers/AGENTS.md`, run:
```bash
make coding-agent-harness
```
This check is a local, opt-in agent aid; it is not part of `make policy` or CI.
-195
View File
@@ -1,195 +0,0 @@
# 发布手册(预发 / 正式)
发布只走一条受控链路:GitHub Actions 的 `Release` workflow 负责版本分配、封板、构建、签名和下游发布;Homebrew 以 workflow 自动创建的 Formula PR 经独立审核合入为交付边界。本地 `dws-release` 仍是兼容入口,但不再要求某一台固定电脑承担打包;不要直接运行 `goreleaser release`,也不要手工补打、移动或复用 tag。
发布前必须完成平台治理:目标 GitHub 仓库已启用 immutable releases,`main` 精确要求 `CI` workflow 的九个 context:`Lint`、`Test`、`Coverage`、`Policy`、`Edition`、`Interface Integrity`、`AI Behavior`、`CLI Smoke`、`Mock MCP`。云端和本地入口都会在封 tag 前检查 immutable releases、当前 SHA 的全部九个 context 和在途 Release;`v*` tag ruleset 仍需仓库管理员预先配置。
## 推荐入口:GitHub 云端发布
任何具有仓库写权限、因而可以手动运行 Actions workflow 的成员,都可以基于当时最新的 `main` 发起发布:
1. 在 GitHub Actions 打开 `Release`,选择 `Run workflow`,分支必须是默认分支 `main`。
2. `release_operation=plan`,选择 `release_channel=beta|stable`;仅在开始新 beta 线时选择 `release_bump=patch|minor|major`。
3. workflow summary 会给出唯一的下一版本。把对应的精确 `CHANGELOG.md` 章节通过 PR 合入 `main`。
4. 再次运行,改为 `release_operation=publish`,并输入 `PUBLISH beta` 或 `PUBLISH stable`。
`plan` 是纯只读操作,不创建 tag、预留版本号或生成包。CHANGELOG 合入期间若另一个发布先占用了该版本,`publish` 会重新分配并因 CHANGELOG 章节不匹配而拒绝,需要重新 plan。`publish` 会先再次确认 dispatch SHA 仍是当前 `main`、Code Admission 和平台治理均通过,再由唯一的 write job 使用 GitHub API 原子创建 annotated tag;同一次 run 随即进入既有的跨平台构建、GitHub/npm、可选 OSS/Gitee 发布和 Homebrew PR DAG。内置 `GITHUB_TOKEN` 创建的 tag 不依赖第二条 workflow 被再次触发。
OSS 镜像默认不参与发布 DAG,适用于尚未创建 Bucket 的仓库。云端封板会把当时的仓库变量 `ENABLE_OSS_MIRROR=true` 记录为不可变 tag 元数据 `OSS-Mirror: enabled`,否则记录为 `deferred`;后续发布和撤回只读取该 sealed policy,不读取变量的当前值。`enabled` 继续对缺失凭据、无效 Bucket、上传、pointer 和撤回失败保持 fail-closed;`deferred` 明确跳过不存在的渠道。为避免补发后撤回遗漏,deferred 版本暂不接受 `repair_oss_version`,启用 OSS 只影响后续新 tag,直到补齐可审计的不可变 repair 证明。
## 自动版本规则
- beta:如果存在尚未封正式版的最高版本线,自动取 `beta.N+1`;否则从最新已分配正式版按所选 patch/minor/major 开新线并取 `beta.1`。
- stable:先锁定最高开放版本线上的最新已分配 beta,再要求它已成功交付且未撤回;不会跳过失败/撤回的最新 beta 去选择更早版本。正式版 core 与该 beta 完全相同。
- `vX.Y.Z`、`vX.Y.Z-beta.N` 一经分配就永久占用。撤回时创建 `withdrawn/v...` 墓碑,原编号永不复用。
- 例如撤回 `v1.0.53-beta.5` 后,下一 beta 是 `v1.0.53-beta.6`;撤回正式版 `v1.0.53` 后,下一 patch 修复线是 `v1.0.54-beta.1`,验证后再发布 `v1.0.54`。
- 如果最新 beta 已撤回,禁止直接用更早 beta 晋级正式版;必须先构建下一个 beta。
## 全平台撤回与回滚
已公开版本出现问题时,在 GitHub Actions 运行 `Withdraw release`,分支必须选择当前默认分支 `main`,并填写:
- `version`:精确版本,例如 `v1.0.53` 或 `v1.0.53-beta.5`。
- `reason`:8–300 字符的单行公开原因。
- `confirmation`:精确输入 `WITHDRAW <version>`,例如 `WITHDRAW v1.0.53`。
该 workflow 使用与发布相同的串行 publication lock,并进入受保护的 `release-withdrawal` environment。它只接受已经由 Release workflow 完整交付的 public immutable release,自动选择同一渠道中最新的、更早且未撤回的完整版本作为回退目标,然后按以下顺序执行:
1. 先创建永久 annotated tag `withdrawn/<version>`,记录原 tag object、commit、原因、申请人和 workflow run。这个墓碑是版本号永久占用记录,永不移动、永不删除。
2. 先验证 Homebrew Formula;若它仍指向问题版本,先创建回退 PR,再继续其他渠道撤回。这样 PR 创建失败时只留下可安全续跑的墓碑,不会先造成渠道分裂。若 Formula 尚未指向问题版本或已经处于安全版本,则直接校验。
3. GitHub Release 先标记为 withdrawn;npm 精确版本执行 `deprecate`,并把 `latest` / `beta` dist-tag 回退;只有目标 tag 封存了 `OSS-Mirror: enabled` 时,OSS 才会先补齐回退版本资产,再移动 `latest.txt` / `beta.txt` 并删除问题版本目录;启用 Gitee 时同样先补齐回退 Release,再删除问题 Release 和 tag。
4. npm 以及目标 tag 启用或发布时配置的镜像渠道均已验证安全后,删除 GitHub 上的问题 Release 和原 `v...` tag,并验证 `/releases/latest` 对正式版回到安全版本。若本次创建了 Homebrew PR,run 最后故意保持失败,直到另一名维护者审核合入;合入后,从新的 `main` 使用完全相同的 version、reason 和 confirmation 重跑并完成。永久 `withdrawn/v...` 墓碑始终保留。
GitHub、npm、OSS、Gitee 和 Homebrew 的“回滚”指新的安装、升级和渠道解析不再拿到问题版本。已经装到用户电脑上的二进制无法被服务端强制降级;用户必须重新安装回退版本、安装后续修复版,或使用 CLI 自带的本地 rollback 能力。npm 不执行 `unpublish`:问题版本保留明确的弃用警告,但 `latest` / `beta` 不再指向它;即使 registry 允许删除,已发布过的版本号也不会重新使用。
撤回前必须存在同一渠道中更早、完整交付且未撤回的安全版本;若目标是该渠道第一个版本、没有安全候选,workflow 会在创建墓碑或修改任何渠道前 fail closed,需要先决定明确的替代策略。CLI 本地 rollback 也只有在本机仍保留上一次升级备份时可用。
撤回以“精确版本”为单位,不会因为正式版曾由某个 beta 晋级就隐式级联修改另一个渠道。若同一缺陷同时存在于正式版及其 beta,应先撤回正式版,再撤回对应 beta,并分别使用各自的精确确认串;每次都只会把该渠道回退到自己的安全候选。
撤回正式版 `v1.0.53` 后,`v1.0.53` 仍被墓碑视为已分配。下一次 patch 发布从 `v1.0.54-beta.1` 开始,验证后晋级 `v1.0.54`。撤回 `v1.0.53-beta.5` 后,同一开放版本线继续为 `v1.0.53-beta.6`;不会退回或复用 `beta.5`。
## 兼容入口:本地发布
安装发布 Skill 后直接运行:
```bash
dws-release
```
零参数会进入引导模式。仓库内的等价入口是 `./scripts/release/dws-release.sh`。第一次使用只需配置一次生产发布远端,命令会把远端名及其规范化仓库身份一起保存在当前 Git 仓库中:
```bash
dws-release config --remote origin
```
之后命令按仓库状态自动走到正确步骤:缺少精确 CHANGELOG 章节时只生成模板并停止;补全、提交并合入 `main` 后,再运行同一条命令就会安全快进本地 `main` 并执行完整预检。若同名 remote 后续被改指向其他仓库会直接拒绝。只有显式增加 `--publish` 才会进入 tag 发布,且底层仍要求最终版本确认。
## 发布模型
```text
main 上的候选代码 + beta CHANGELOG
→ vX.Y.Z-beta.N(预发验证)
→ 补正式 CHANGELOG;允许继续通过 PR 合入新 commit
→ vX.Y.Z(正式发布,封板提交必须包含该 beta 提交)
```
云端入口自动选择本次最新、已交付且未撤回的 beta;本地入口必须显式指定。流水线要求该 beta 已成功交付、未撤回,且 beta 提交必须位于正式发布封板提交的历史中——不能跳过 beta 直接发正式版,但允许在 beta 之后把经过 review 合入 `main` 的 commit 一起发布。
## 预发发布
运行统一入口:
```bash
dws-release v1.2.3-beta.1
```
如果 CHANGELOG 尚不存在,该命令只生成模板并停止。补全内容、删除所有 `TODO`,提交后通过 PR 合入 `main`;然后重新运行完全相同的命令,它会执行完整预检:
```bash
dws-release v1.2.3-beta.1
```
预检包含测试、策略检查、旧正式版命令树兼容检查、全平台打包、npm 安装验证,以及 macOS 环境下的 Homebrew 安装验证。它还会从默认分支触发一次无发布权限的 `Release governance preflight`,用正式流水线相同的身份检查该精确 commit 的九个 Code Admission context 和 immutable releases。通过后会在当前 Git worktree 的私有 Git 状态目录写入一个有效期六小时的证明,绑定版本、精确 commit、发布仓库、beta/stable 基线和远端 `main`:
```bash
dws-release v1.2.3-beta.1 --publish
```
若源码、版本、远端身份和 stable 基线均未变化,`--publish` 会复用该证明,只执行远端契约、发布身份和最终治理复核,不再重复测试与打包。也可以直接运行 `--publish`;没有可复用证明时只会完整执行一次预检。命令在封 tag 前仍要求再次输入完整版本号,统一入口不提供跳过确认的参数。
## 正式发布
beta 验证通过后,运行正式版入口:
```bash
dws-release v1.2.3 --from-beta v1.2.3-beta.1
```
首次运行只生成正式版 CHANGELOG 并停止。补全内容、删除 `TODO`,提交后通过 PR 合入 `main`;重新运行同一条命令做完整预检,确认后增加 `--publish`:
```bash
dws-release v1.2.3 --from-beta v1.2.3-beta.1
dws-release v1.2.3 --from-beta v1.2.3-beta.1 --publish
```
本地入口的 `FROM_BETA` 不会自动推断;云端入口会按上述规则唯一选择。两种入口都会把它写入 stable annotated tag 的 `From-Beta` 元数据,CI 会再次读取和验证。
## CHANGELOG 契约
每个 tag 必须有唯一、非空且不含 `TODO/TBD` 的精确章节:
```markdown
## [1.2.3-beta.1] - 2026-07-11
### Changed
- 本次 beta 验证的用户可见变化。
```
正式版使用 `## [1.2.3] - YYYY-MM-DD`。该章节会直接成为 GitHub Release Notes。
## CI/CD 保证
- 只接受 `vX.Y.Z-beta.N` 和 `vX.Y.Z`,且新版本必须高于上一正式版。这里的“上一正式版”必须同时具备公开非草稿 GitHub Release 和同 tag/commit 的成功 Release workflow;只有 tag、没有交付成功的孤儿版本会阻断后续发布,要求走受保护恢复补齐。云端 tag 会固定 `Release-Run`、requester、commit 和版本分配指纹,交付验证按该精确 run/attempt 及完整 job graph 取证,不接受任意 `workflow_dispatch`。历史版本若曾通过专用 recovery workflow 完成交付,只能使用仓库内 `delivered-stable-recoveries.json` 中精确到 tag、commit、run、workflow SHA 与 attempt 的 reviewed 证据。
- tag 必须是 annotated tag;本地脚本要求封板提交已通过 PR 合入并包含在远端 `main` 历史中,发布只推送 tag。CI 允许其后 `main` 继续前进,但始终要求封板提交位于 `main` 历史中。
- 日常 CI 和发布前都会对比“最新已交付正式版”的完整命令树;若长时间预检期间该 baseline 发生变化,会针对新的 baseline 重新比较。
- GoReleaser 只构建;Darwin 重签、checksums 重算和 npm 安装验证通过后,才统一上传 GitHub Release 的最终产物。
- 六个平台归档会逐个解包并核验二进制内嵌版本;公开资产集合、checksums 集合和 npm tarball integrity 都必须精确一致。npm tarball 固定由 npm `10.9.2` 打包,避免重跑时因 runner 自带 npm 漂移产生不同字节。
- stable 发布到 npm `latest`;prerelease 发布到 npm `beta`。启用 `ENABLE_OSS_MIRROR=true` 后,stable 同步 OSS `latest.txt` 和共享安装脚本,prerelease 只同步 OSS `beta.txt`,不会覆盖稳定入口。
- Release workflow 使用一个最多容纳 100 个 pending run 的串行 publication queue;版本规划、云端封板、发布、恢复、修复和撤回共享同一发布锁。
- 本地 tag push 失败时会删除本次新建的本地 tag。远端 tag 一旦创建,后续发布归 CI 所有;发布中途失败时走受保护恢复,禁止改 tag 指向或复用版本号。只有已经公开版本经过受保护的全渠道撤回并留下永久 `withdrawn/...` 墓碑后,撤回 workflow 才会在最后一步删除原 tag。
npm 补发只允许从默认分支触发 Release workflow 的 `repair_npm_version`。它只支持启用 immutable releases 后、由本流水线成功产出的公开 immutable release:目标必须是 `main` 历史中的 annotated tag,并且同 commit 的 `Build immutable GitHub Release` job 已成功。即使后续 npm 分发失败,这个独立的产物封存边界仍可作为补发依据。补发会用目标 commit 的 npm 模板重组包,逐平台核验资产和二进制版本,再发布到隔离的 `backfill` dist-tag,不会回滚 `latest` / `beta`。历史 mutable release 不进入自动补发路径,避免把可被替换的资产带入 npm。
已启用的 OSS 或 Gitee 分发失败且 GitHub immutable Release、npm 已交付时,从受保护的默认分支触发
Release workflow,并且只填写 `repair_oss_version` 或 `repair_gitee_version` 之一。channel
repair 会精确绑定失败 tag run 的最新 attempt,且 OSS repair 要求 tag 的 sealed policy 为 `enabled`;contract、构建、Developer ID 签名、
immutable GitHub 发布和 npm delivery 必须全部成功,且只能有一个 OSS/Gitee 下游失败,
随后才会下载并重新校验原始资产、修复所选镜像。OSS repair 必须匹配失败的 OSS step;
Gitee repair 还允许其 job 因该 OSS 失败而 skipped,此时只代表 Gitee backfill 成功,
不会把仍未修复的 OSS 标成成功。该证据不能用于 beta → stable 或
stable baseline,后两者仍要求整条 Release 成功或受保护 recovery 成功。不要重跑旧
attempt 的单个 failed job,以免在 attempts 之间拼接交付证据。独立 Gitee release
workflow 和本地直发脚本已停用,避免绕开 publication queue 或用重新构建的不同字节覆盖镜像。
## 既有 tag 的紧急恢复
云端封板或本地 tag push 已成功、但 Release workflow 失败且 GitHub Release 尚未公开时,不要新建临时 workflow、移动 tag 或跳过门禁。在最新且干净的 `main` worktree 运行:
```bash
dws-release recover v1.2.3-beta.1
```
命令会自动解析 annotated tag object、peeled commit,以及 tag 绑定的失败云端 run 或最近一次匹配的失败 tag-push run;也可以用 `--failed-run <run-id>` 精确指定。确认完整版本号后,它从默认分支触发受保护的恢复模式并等待完成。恢复模式必须满足:
- 输入精确绑定原 annotated tag object、commit 和失败的 sealed `Release` run;云端 run 还必须与 tag 内的 run ID、attempt、requester 完全一致,commit 必须仍在 `main` 历史中。
- 目标只允许不存在 GitHub Release 或仍为 Draft;已经公开的版本不能全量重建:单个下游故障走对应的 channel repair,版本本身有问题则走受保护的全平台 withdrawal。
- `release-recovery` environment 必须限制为受保护分支、配置至少一名 required reviewer,并禁止自审;workflow 会通过 API 复核这些设置,未配置时 fail closed。
- 恢复复用正常的 contract、构建、Developer ID 签名、资产校验、immutable 发布、Homebrew、npm,以及已启用的 OSS jobs,不存在 recovery 专用 publisher 或门禁跳过。
- 如果 GitHub Release 已在 recovery 中封存、后续 Homebrew/npm 校验发生瞬时失败,只重跑该 run 的 failed jobs;流水线仅在隐藏 run marker、tag object、commit 和 finalized artifact 字节全部精确一致时复用公开 Release。
成功的默认分支恢复 run 会成为后续 beta → stable 和 stable baseline 验证的可审计交付证据;历史临时分支恢复仍只接受 reviewed manifest 中的固定证据。
云端 seal 后不要使用 GitHub 的 “Re-run failed jobs” 作为交付修复:annotated tag 永久绑定最初的 run attempt,普通 rerun 不会成为可接受的交付证据。GitHub Release 尚未公开时走上述 protected recovery;已经公开且仅 npm/OSS/Gitee 某一渠道失败时走对应 repair;版本内容本身有问题时走 withdrawal。
OSS 的 `latest.txt` / `beta.txt` 是镜像频道元数据;当前仓库安装器仍主要从 GitHub/Gitee 解析版本。启用 OSS 后,发布和撤回把它作为受控分发渠道处理,保证一旦外部消费者接入该 pointer,也不会继续解析到已撤回版本;未启用时两条流程都明确跳过不存在的 OSS 渠道。
Release workflow 会生成 Darwin/Linux 双架构 Formula,并分别为 stable/beta 打开 Homebrew PR;tap 的默认分支仍以独立审核合入为交付边界。撤回 workflow 使用相同模板和回退版本 checksums 打开反向 PR;问题 GitHub Release 会先被移除以阻止新安装,永久墓碑和 workflow 日志承担审计/续跑依据。
## 平台治理前置
仓库管理员还需要在 GitHub 平台配置以下不可由脚本替代的规则:
- `main` 必须精确要求 `Lint`、`Test`、`Coverage`、`Policy`、`Edition`、`Interface Integrity`、`AI Behavior`、`CLI Smoke`、`Mock MCP` 九个 Code Admission context;tag workflow 也会通过 Checks API 再确认该封板 SHA 上九项全部成功。
- 必须启用 immutable releases;它只保护启用后发布的 release,因此应在第一次使用新流水线前配置。为 `v*` 增加 tag ruleset,限制创建权限,并在 release 发布前保护 tag 的短暂窗口。
- tag ruleset 还必须覆盖 `withdrawn/v*`:只允许受保护的撤回 workflow 创建墓碑,禁止更新或删除墓碑;同时应允许 Release workflow 创建新的 `v*`,允许撤回 workflow 在全部渠道回退后删除精确的问题 `v*`。若组织级规则阻止这两个 workflow 的预期动作,发布或撤回会 fail closed,不能靠手工移动 tag 绕过。
- 配置 `RELEASE_GOVERNANCE_TOKEN` Actions secret,只授予目标仓库 `Administration: read`;内置 `GITHUB_TOKEN` 不具备 immutable-releases API 所需的仓库治理权限。每次本地预检和 tag workflow 都使用这一个身份进行 fail-closed 验证。
- 配置 `APPLE_CERTIFICATE_P12_BASE64`、`APPLE_CERTIFICATE_PASSWORD` 和具备发布权限的 `NPM_TOKEN`;撤回还要求该 npm 身份能够执行 `deprecate` 和修改 dist-tag。
- 启用 OSS 镜像时,先创建有效 Bucket,再设置仓库变量 `ENABLE_OSS_MIRROR=true`,并配置 `OSS_ACCESS_KEY_ID`、`OSS_ACCESS_KEY_SECRET`、`OSS_ENDPOINT`、`OSS_BUCKET`,按需配置 `OSS_PREFIX`。启用后发布保持 fail-closed;撤回身份必须能够补齐安全版本资产、写 `latest.txt` / `beta.txt` 并删除问题版本前缀。尚未 provision Bucket 时保持该变量未设置或不等于 `true`,新 tag 会封存 `OSS-Mirror: deferred` 并跳过 OSS;该版本不能通过现有 repair 流程事后改成启用。
- 若启用 Gitee fallback,设置 `ENABLE_GITEE_UPLOAD_FALLBACK=true`,并配置 `GITEE_TOKEN`、`GITEE_USER`、`GITEE_REPO`;该身份必须能够创建和删除目标仓库的 Release 与 tag。
- 单独配置 `HOMEBREW_PR_TOKEN`,优先使用仅授权本仓库且具备 `Contents: write`、`Pull requests: write` 的 fine-grained PAT;若组织策略不允许该账号使用 fine-grained PAT,则回退到仅带 `public_repo` scope 的专用 classic PAT。治理预检和 tag contract 会验证 token 身份、classic scope,并用 `[skip ci]` 临时分支和 draft PR 完成真实写权限 canary,随后立即关闭 PR、删除分支;任何清理失败都会 fail closed。门禁也会拒绝与治理 token 复用。
- 创建 `release-recovery` environment,只允许受保护分支,设置 required reviewer、禁止自审并关闭管理员绕过。workflow 会读取 environment 的 required-reviewer、prevent-self-review 和 protected-branch 规则;规则缺失时紧急恢复会失败,正常 beta/stable tag 发布不受影响。
- 创建 `release-withdrawal` environment,只允许受保护分支,设置至少一名 required reviewer、禁止申请人自审并关闭管理员绕过。撤回 workflow 会通过 API 复核这些规则;任何一项缺失都会在触碰 npm、OSS、Gitee、Homebrew 或 GitHub Release 前失败。
- 仓库或组织的 Actions 策略必须允许 `Release` 与 `Withdraw release` workflow 的 `GITHUB_TOKEN` 获得各 job 声明的 `contents: write`。若上述发布凭证采用 environment secret,确认 `release-withdrawal` 审批完成后能够读取撤回所需的 npm、OSS、Gitee 和 Homebrew 凭证。
immutable releases,或任一 Code Admission context 缺失、未成功时,发布脚本会自动拒绝封 tag。tag ruleset 可能来自组织层,脚本不自动推断其最终作用范围;管理员确认不能省略,脚本约定也不能替代平台强制。
-150
View File
@@ -1,150 +0,0 @@
# Schema and Agent Contract Contributor Guide
Read this guide when changing public CLI commands, Schema identity or
parameters, Agent selection/safety metadata, or generated Schema assets.
## Ownership and data flow
The publication graph is one way:
```text
Cobra command tree
+ reviewed CommandRegistry identity/navigation
+ reviewed metadata parameter overlays
-> EffectiveCommandRegistry and executable binding
+ parameter bindings
+ reviewed selection and safety/interface metadata
+ pinned MCP metadata
-> one resolved ToolSpec registry/index
-> generated Agent metadata and embedded Schema Catalog
-> dws schema projections and runtime metadata lookup
```
The owning sources are:
| Concern | Authoritative input |
|---|---|
| Executable paths and accepted flags | Cobra tree built by `app.NewRootCommand()` |
| Stable canonical identity, primary path, aliases, navigation | `internal/cli/schema_command_registry.json` |
| Registry editing contract | `internal/cli/schema_command_registry.schema.json` |
| Safety, interface, runtime gates, parameter overlays | `internal/cli/schema_hints/metadata/<product>.json` |
| Agent selection prose and examples | `internal/cli/schema_hints/selection/<product>.json` |
| Product-to-hint-file routing | `internal/cli/schema_hints/index.json` |
| Flag/property bindings | `internal/cli/schema_parameter_bindings.json` |
| Sanitized interface fallback | `internal/cli/schema_mcp_metadata.json` |
| Exact reviewed omissions from Schema | `internal/cli/schema_command_exclusions.json` |
Generated files under `internal/cli/schema_agent_metadata/` and
`internal/cli/schema_catalog.json` are output only. Runtime loading is a delivery
boundary: it must not create or repair commands, flags, registry entries, or
generation inputs.
## Invariants
1. Every delivered tool resolves to a public runnable Cobra leaf.
2. Every public runnable Cobra leaf resolves to Schema or has one exact,
reviewed exclusion with a non-empty reason. Wildcard/prefix exclusions are
forbidden.
3. The reviewed CommandRegistry is the only stable identity/navigation source.
Native annotations, when present, are consistency assertions and must agree.
4. Metadata overlays may describe or constrain real flags; they cannot create
commands, flags, interfaces, or unknown RPCs.
5. Cobra-required flags are a hard floor. An overlay may make an optional flag
required but cannot make a Cobra-required flag optional.
6. Each tool is resolved once into one typed `ToolSpec`; all Catalog, `schema
--all`, leaf, summary, safety, and runtime projections derive from it.
7. Provenance winner values must equal delivered values. Same-precedence
conflicts fail instead of being merged silently.
8. `confirmation=user_required` requires user confirmation before `--yes`.
Do not infer confirmation mechanically from risk/effect; keep runtime gates
and published metadata consistent.
9. Stored examples use real primary/alias paths and accepted flags, satisfy all
required/constraint rules, contain no shell comments, and never add `--yes`.
10. `schema --all` remains the complete compatibility export. Routine discovery
should use overview, product/group, then leaf queries.
When Help and shipped Schema disagree, treat it as contract drift. Cobra still
defines executable flags; use the safer interpretation for confirmation or
stop rather than guessing.
Parameter and safety resolution is source-precedence based and otherwise
value-neutral: a value must not win merely because it looks stricter. Preserve
all candidates and the selected source, and fail same-precedence conflicts.
Command text resolves from reviewed tool hints, then command-specific Cobra
help, then MCP metadata; generic RPC prose must not replace a specialized
leaf's description. An alias lookup may change only view fields such as
`cli_path` and `is_alias`, never the resolved command contract.
## Editing workflow
1. Confirm the live path and flags in the Cobra tree and current `--help`.
2. Change only the owning reviewed block. Do not copy generated Catalog fields
into inputs or mix selection fields into metadata files.
3. Keep registry edits limited to intentional identity/navigation changes.
4. For selection prose, write decision-oriented routing: when to choose the
command, when a sibling is better, and the result shape. Do not restate help.
5. For parameter overlays, use an exact runnable leaf and real flags; set
`reviewed: true` with a concrete review reason.
6. Regenerate the complete snapshot; publication is deterministic even when
only one product input changed.
7. Inspect authored and generated diffs separately, then run the gates below.
Pinned MCP metadata is a sanitized fallback. When a task requires refreshing
it and a personal session is available, inspect live metadata with `dws auth
status`, `dws cache refresh`, and `dws schema <canonical> -f json`. Never print
or commit tokens. Evidence precedence is Runtime/Cobra, live MCP, pinned MCP,
then Skill prose as evidence only.
## Required checks
```bash
make generate-schema
./scripts/policy/check-runtime-confirmation-truth.sh
./scripts/policy/check-generated-drift.sh
./scripts/policy/check-schema-catalog.sh
./scripts/policy/check-command-surface.sh --strict
make test-schema-agent-examples
```
Also run focused tests for the changed binder, generator, command, or runtime
consumer. Run reverse-completeness tests whenever the Cobra tree changes.
Agent examples are contract-checked by default. Eligible reviewed dry-run
examples are additionally exercised by `make test-schema-agent-examples` with
isolated state; a runtime failure must not be converted into an ad hoc skip.
Live-model selection evaluation is optional and never a normal CI dependency.
An example enters runtime dry-run only when its final typed contract publishes
an explicit reviewed dry-run capability. Risk or confirmation metadata does
not manufacture preview support, and the harness never injects `--yes`. A
narrow precondition that cannot be derived from the contract may use an exact,
reviewed `example_dispositions` entry to narrow dry-run to contract-only; it
must not become a general skip or a fallback applied after execution fails.
Every `use_when` entry is a positive selection fixture and every `avoid_when`
entry is a negative fixture for that tool. The deterministic gate checks
coverage and contradictions; it does not claim to prove natural-language
understanding. When explicitly requested, the optional live-model smoke test
can be run with:
```bash
DWS_AGENT_SELECTION_LIVE=1 \
ARK_API_KEY=... ARK_BASE_URL=... ARK_MODEL=... \
go test ./internal/app -run TestManualAgentSelectionArkLive -count=1
```
Use `DWS_AGENT_SELECTION_FULL=1` for the full fixture or
`DWS_AGENT_SELECTION_CASES=<comma-separated-ids>` for selected cases. A custom
HTTPS provider must be explicitly allowlisted; plaintext is accepted only for
a loopback test server so credentials are not sent over arbitrary clear text.
## Runtime boundaries
- `schema list` is a progressive overview; `schema --all` is the complete,
non-compact compatibility baseline with full parameters, constraints, and
safety semantics.
- `--compact` saves discovery context but is not a full compatibility export.
- `dws <path> --help` decides whether a path and its flags are executable. Leaf
Schema owns Agent selection, mapping, constraints, and safety semantics.
- Help and Schema describe commands; they do not return DingTalk business
data. Execute the real read/list/search command after discovery.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
-75
View File
@@ -1,75 +0,0 @@
# Skill Authoring Guide
Contract for the bundled agent skills under `skills/`. Skills are embedded via
`skills/embed.go` and installed by `dws skill setup`, so every edit ships with
the binary. Keep skill prose concise: long command references belong in
`references/`, not in `SKILL.md`.
## Layout
| Path | Role |
|---|---|
| `skills/mono/` | Single bundled skill (stable mode) with shared `references/` and `scripts/` |
| `skills/multi/dingtalk-<product>/` | One skill per product (experimental mode) |
| `skills/multi/dws-shared/` | Shared prerequisite: auth, global flags, routing, safety |
| `skills/embed.go` | Embeds `mono` + `multi`; do not add new roots |
A product skill directory contains:
```text
dingtalk-<product>/
SKILL.md # frontmatter + concise routing/usage prose
references/ # long command references, playbooks
scripts/ # executable recipes (python), kept minimal
```
## SKILL.md contract
Frontmatter:
```yaml
---
name: dingtalk-<product>
description: <触发场景>. Use when … Distinct from <相邻skill>(…). 命令前缀:dws <product>。
cli_version: ">=<minimum dws version>"
metadata:
category: product
stability: experimental
requires:
bins:
- dws
---
```
Body rules:
- State the safety rules directly in concise prose; there is no injected
preamble mechanism in this repository.
- State the `dws-shared` prerequisite for multi skills.
- Route by intent: shortcuts table first when one covers the scenario, then
scripts/recipes, then atomic commands with `dws schema` / `--help`.
- Every referenced `dws` command must exist in the current binary; verify with
`dws <cmd> --help` and keep prose version-agnostic ("以当前 dws 二进制为准").
- Mutating commands must point at the leaf Schema `confirmation` contract; do
not invent confirmation rules in prose.
## Dual-write rule
Skill behavior described in prose must match the CLI it references. When a
command, flag, or confirmation contract changes, update the affected `SKILL.md`
/ `references/` in the same change; when skill routing changes, check whether
Schema selection hints (`internal/cli/schema_hints/`) need a reviewed update
per [`schema-contributor-guide.md`](schema-contributor-guide.md).
## Validation
| Change | Check |
|---|---|
| Any skill edit | `make skill-command-integrity` |
| Referenced CLI surface changed | `./scripts/policy/check-command-surface.sh --strict` |
| Schema hints touched | `make generate-schema` + schema gates |
| Recipe scripts | run the script's own smoke path or `test/skill_e2e` when applicable |
`make skill-command-integrity` builds `scripts/policy/skill-command-check` and
verifies every `dws` command referenced by skills resolves against the current
binary. Run it before handoff; do not claim a command exists without it.
+1 -3
View File
@@ -49,8 +49,6 @@ var AllowedMethods = map[string]bool{
"GET": true, "POST": true, "PUT": true, "PATCH": true, "DELETE": true,
}
var newHTTPRequest = http.NewRequestWithContext
// RawAPIRequest describes a raw API request to DingTalk OpenAPI.
type RawAPIRequest struct {
Method string // GET, POST, PUT, PATCH, DELETE
@@ -114,7 +112,7 @@ func (c *APIClient) Do(ctx context.Context, req RawAPIRequest) (*RawAPIResponse,
bodyReader = bytes.NewReader(data)
}
httpReq, err := newHTTPRequest(ctx, method, fullURL, bodyReader)
httpReq, err := http.NewRequestWithContext(ctx, method, fullURL, bodyReader)
if err != nil {
return nil, fmt.Errorf("creating HTTP request: %w", err)
}
-293
View File
@@ -1,293 +0,0 @@
package apiclient
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/output"
)
type failingReader struct{ err error }
func (r failingReader) Read([]byte) (int, error) { return 0, r.err }
type failingWriter struct{ err error }
func (w failingWriter) Write([]byte) (int, error) { return 0, w.err }
func TestCrossPlatformCoverageDryRunAndParseCoverageEdges(t *testing.T) {
for _, tc := range []struct {
base string
path string
}{
{DefaultBaseURL, "/v1.0/test"},
{LegacyBaseURL, "/topapi/test"},
} {
var out bytes.Buffer
err := PrintDryRun(&out, RawAPIRequest{
Method: "post", Path: tc.path,
Params: map[string]any{"page": 1}, Data: map[string]any{"name": "value"},
}, tc.base, "token-value")
if err != nil || !strings.Contains(out.String(), "Dry Run") || !strings.Contains(out.String(), "toke****") {
t.Fatalf("PrintDryRun(%s) = %q, %v", tc.base, out.String(), err)
}
}
var out bytes.Buffer
if err := PrintDryRun(&out, RawAPIRequest{Method: "get", Path: "/x", Params: map[string]any{"bad": make(chan int)}, Data: make(chan int)}, DefaultBaseURL, "tiny"); err != nil {
t.Fatalf("PrintDryRun unsupported preview: %v", err)
}
wantErr := errors.New("read failed")
if _, err := ParseJSONMap("-", "--params", failingReader{err: wantErr}); !errors.Is(err, wantErr) {
t.Fatalf("ParseJSONMap read error = %v", err)
}
if got, err := ParseJSONMap("-", "--params", strings.NewReader(" \n")); err != nil || got != nil {
t.Fatalf("ParseJSONMap empty stdin = %#v, %v", got, err)
}
if _, err := ParseOptionalBody("POST", "-", failingReader{err: wantErr}); !errors.Is(err, wantErr) {
t.Fatalf("ParseOptionalBody read error = %v", err)
}
if got, err := ParseOptionalBody("POST", "-", strings.NewReader(" \n")); err != nil || got != nil {
t.Fatalf("ParseOptionalBody empty stdin = %#v, %v", got, err)
}
if _, err := ParseOptionalBody("POST", "{", strings.NewReader("")); err == nil {
t.Fatal("invalid optional body should fail")
}
}
func TestCrossPlatformCoverageResponseHandlingCoverageEdges(t *testing.T) {
jsonHeader := http.Header{"Content-Type": []string{"application/json"}}
textHeader := http.Header{"Content-Type": []string{"text/plain"}}
var out, errOut bytes.Buffer
opts := ResponseOptions{Format: output.FormatJSON, Out: &out, ErrOut: &errOut}
if err := HandleResponse(&RawAPIResponse{StatusCode: 500, Header: textHeader, Body: []byte(" failed ")}, opts); err == nil {
t.Fatal("plain HTTP error should fail")
}
for _, body := range [][]byte{nil, []byte("{")} {
if err := HandleResponse(&RawAPIResponse{StatusCode: 200, Header: jsonHeader, Body: body}, opts); err == nil {
t.Errorf("invalid JSON body %q should fail", body)
}
}
out.Reset()
if err := HandleResponse(&RawAPIResponse{StatusCode: 200, Header: jsonHeader, Body: []byte(`{"ok":true}`)}, opts); err != nil || !strings.Contains(out.String(), "ok") {
t.Fatalf("successful JSON response = %q, %v", out.String(), err)
}
for _, payload := range []string{
`{"errcode":1}`,
`{"message":"message failure"}`,
`{"error":"error failure"}`,
`{}`,
} {
status := 200
if !strings.Contains(payload, "errcode") {
status = 500
}
if err := HandleResponse(&RawAPIResponse{StatusCode: status, Header: jsonHeader, Body: []byte(payload)}, opts); err == nil {
t.Errorf("business/HTTP payload %s should fail", payload)
}
}
if err := checkDingTalkError([]any{1}, 200); err != nil || checkDingTalkError(map[string]any{"errcode": 0}, 200) != nil {
t.Fatal("successful DingTalk response classified as error")
}
if err := HandleResponse(&RawAPIResponse{StatusCode: 200, Header: textHeader, Body: []byte("binary")}, opts); err == nil {
t.Fatal("binary response without filename should fail")
}
invalidCD := http.Header{"Content-Type": []string{"application/octet-stream"}, "Content-Disposition": []string{`attachment; filename="unterminated`}}
if inferFilename(invalidCD) != "" {
t.Fatal("invalid content disposition should not infer filename")
}
if inferFilename(http.Header{}) != "" {
t.Fatal("missing content disposition should not infer filename")
}
dir := t.TempDir()
blockedParent := filepath.Join(dir, "file")
if err := os.WriteFile(blockedParent, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
opts.OutputPath = filepath.Join(blockedParent, "child.bin")
if err := handleBinaryResponse(&RawAPIResponse{Header: textHeader, Body: []byte("x")}, opts); err == nil {
t.Fatal("binary mkdir failure should fail")
}
opts.OutputPath = dir
if err := handleBinaryResponse(&RawAPIResponse{Header: textHeader, Body: []byte("x")}, opts); err == nil {
t.Fatal("binary write to directory should fail")
}
opts.OutputPath = ""
inferred := filepath.Join(dir, "inferred.bin")
header := http.Header{"Content-Type": []string{"application/octet-stream"}, "Content-Disposition": []string{`attachment; filename="` + inferred + `"`}}
if err := handleBinaryResponse(&RawAPIResponse{Header: header, Body: []byte("bytes")}, opts); err != nil {
t.Fatalf("inferred binary save: %v", err)
}
if !strings.Contains(errOut.String(), "已保存") {
t.Fatalf("binary status = %q", errOut.String())
}
for _, ct := range []string{" application/json; charset=utf-8 ", "text/json", "application/problem+json", "text/plain"} {
_ = isJSONContentType(ct)
}
for _, value := range []any{float64(1), 2, int64(3), json.Number("4"), json.Number("bad"), "5"} {
_ = toFloat64(value)
}
}
func TestCrossPlatformCoveragePaginationParsingAndInjectionEdges(t *testing.T) {
jsonHeader := http.Header{"Content-Type": []string{"application/json"}}
for _, resp := range []*RawAPIResponse{
{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/plain"}}, Body: []byte("x")},
{StatusCode: 200, Header: jsonHeader},
{StatusCode: 200, Header: jsonHeader, Body: []byte("{")},
{StatusCode: 500, Header: jsonHeader, Body: []byte(`{"message":"bad"}`)},
} {
if _, _, _, err := parsePaginatedResponse(resp); err == nil {
t.Errorf("parsePaginatedResponse(%#v) should fail", resp)
}
}
responses := []struct {
body string
more bool
token string
}{
{`{"result":{"has_more":true,"next_cursor":12}}`, true, "12"},
{`{"has_more":true,"next_cursor":13}`, true, "13"},
{`{"next_token":"next"}`, true, "next"},
{`{"result":[],"has_more":false}`, false, ""},
}
for _, tc := range responses {
_, more, token, err := parsePaginatedResponse(&RawAPIResponse{StatusCode: 200, Header: jsonHeader, Body: []byte(tc.body)})
if err != nil || more != tc.more || token != tc.token {
t.Errorf("pagination %s = %v, %q, %v", tc.body, more, token, err)
}
}
getCases := []RawAPIRequest{
{Method: "GET"},
{Method: "GET", Params: map[string]any{"cursor": "old"}},
{Method: "GET", Params: map[string]any{"next_token": "old"}},
{Method: "POST", Data: map[string]any{"cursor": "old"}},
{Method: "PUT", Data: map[string]any{}},
{Method: "POST", Data: "not-a-map"},
}
for _, req := range getCases {
_ = injectPageToken(req, "new")
}
logf(nil, "ignored")
}
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }
func jsonHTTPResponse(body string) *http.Response {
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(body))}
}
func TestCrossPlatformCoveragePaginationControlFlowEdges(t *testing.T) {
wantErr := errors.New("transport failed")
client := NewClient("token", DefaultBaseURL)
client.HTTPClient.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/plain"}}, Body: io.NopCloser(strings.NewReader("bad"))}, nil
})
if _, err := client.PaginateAll(context.Background(), RawAPIRequest{Method: "GET", Path: "/x"}, PaginationOptions{}); err == nil {
t.Fatal("first page parse error should fail")
}
client.HTTPClient.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) { return nil, wantErr })
if _, err := client.PaginateAll(context.Background(), RawAPIRequest{Method: "GET", Path: "/x"}, PaginationOptions{}); !errors.Is(err, wantErr) {
t.Fatalf("first page transport error = %v", err)
}
calls := 0
client.HTTPClient.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) {
calls++
if calls == 1 {
return jsonHTTPResponse(`{"next_token":"next"}`), nil
}
return nil, wantErr
})
if pages, err := client.PaginateAll(context.Background(), RawAPIRequest{Method: "GET", Path: "/x"}, PaginationOptions{PageDelay: 1}); err == nil || len(pages) != 1 {
t.Fatalf("later transport error pages=%d err=%v", len(pages), err)
}
calls = 0
var logs bytes.Buffer
client.HTTPClient.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) {
calls++
if calls == 1 {
return jsonHTTPResponse(`{"next_token":"next"}`), nil
}
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/plain"}}, Body: io.NopCloser(strings.NewReader("bad"))}, nil
})
if pages, err := client.PaginateAll(context.Background(), RawAPIRequest{Method: "GET", Path: "/x"}, PaginationOptions{PageDelay: 1, LogWriter: &logs}); err != nil || len(pages) != 1 || !strings.Contains(logs.String(), "解析失败") {
t.Fatalf("later parse failure pages=%d logs=%q err=%v", len(pages), logs.String(), err)
}
client.HTTPClient.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) {
return jsonHTTPResponse(`{"next_token":"next"}`), nil
})
ctx, cancel := context.WithCancel(context.Background())
cancel()
if pages, err := client.PaginateAll(ctx, RawAPIRequest{Method: "GET", Path: "/x"}, PaginationOptions{PageDelay: 10}); !errors.Is(err, context.Canceled) || len(pages) != 1 {
t.Fatalf("pagination cancellation pages=%d err=%v", len(pages), err)
}
logs.Reset()
if pages, err := client.PaginateAll(context.Background(), RawAPIRequest{Method: "GET", Path: "/x"}, PaginationOptions{PageLimit: 1, PageDelay: 1, LogWriter: &logs}); err != nil || len(pages) != 1 || !strings.Contains(logs.String(), "安全上限") {
t.Fatalf("pagination safety cap pages=%d logs=%q err=%v", len(pages), logs.String(), err)
}
}
func TestCrossPlatformCoverageClientAndValidationFailureEdges(t *testing.T) {
client := NewClient("token", DefaultBaseURL)
if _, err := client.Do(context.Background(), RawAPIRequest{Method: "GET", Path: "https://api.dingtalk.com/%zz"}); err == nil {
t.Fatal("Do with invalid URL should fail")
}
if _, err := client.Do(context.Background(), RawAPIRequest{Method: "GET", Path: "https://example.test/x"}); err == nil {
t.Fatal("Do to untrusted host should fail")
}
if _, err := client.Do(context.Background(), RawAPIRequest{Method: "POST", Path: "/x", Data: make(chan int)}); err == nil {
t.Fatal("unmarshalable request body should fail")
}
if _, err := client.buildURL("https://api.dingtalk.com/%zz", nil); err == nil {
t.Fatal("invalid URL should fail")
}
oldNewRequest := newHTTPRequest
t.Cleanup(func() { newHTTPRequest = oldNewRequest })
wantCreateErr := errors.New("request creation failed")
newHTTPRequest = func(context.Context, string, string, io.Reader) (*http.Request, error) { return nil, wantCreateErr }
if _, err := client.Do(context.Background(), RawAPIRequest{Method: "GET", Path: "/x"}); !errors.Is(err, wantCreateErr) {
t.Fatalf("request creation error = %v", err)
}
newHTTPRequest = oldNewRequest
wantErr := errors.New("request failed")
client.HTTPClient.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) { return nil, wantErr })
if _, err := client.Do(context.Background(), RawAPIRequest{Method: "GET", Path: "/x"}); !errors.Is(err, wantErr) {
t.Fatalf("HTTP transport error = %v", err)
}
client.HTTPClient.Transport = roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(failingReader{err: wantErr})}, nil
})
if _, err := client.Do(context.Background(), RawAPIRequest{Method: "GET", Path: "/x"}); !errors.Is(err, wantErr) {
t.Fatalf("response read error = %v", err)
}
if ValidateTargetHost("http://%zz") == nil {
t.Fatal("invalid target URL should fail")
}
for _, r := range []rune{0x200B, 0xFEFF, 0x202A, 0x2028, 0x2066, 0x061C, 0xFDD0} {
if !isDangerousUnicode(r) || ValidateUserInput("x"+string(r), "field") == nil {
t.Errorf("dangerous rune %U was accepted", r)
}
}
if isDangerousUnicode('中') || ValidateUserInput("safe\t\n中文", "field") != nil {
t.Fatal("safe Unicode/input was rejected")
}
}
-223
View File
@@ -1,223 +0,0 @@
package app
import (
"context"
"errors"
"os"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
)
type tokenManagerSnapshotProvider struct {
load func() (*authpkg.TokenData, error)
}
func (p tokenManagerSnapshotProvider) GetAccessToken(context.Context) (string, error) {
data, err := p.load()
if err != nil || data == nil {
return "", err
}
return data.AccessToken, nil
}
func (p tokenManagerSnapshotProvider) GetTokenSnapshot(context.Context) (*authpkg.TokenData, error) {
return p.load()
}
type tokenManagerLegacyGetter struct {
token string
err error
}
func (g tokenManagerLegacyGetter) GetToken() (string, string, error) {
return g.token, "file", g.err
}
func installTokenManagerFakes(t *testing.T, load func() (*authpkg.TokenData, error)) {
t.Helper()
oldProvider, oldLegacy := newAccessTokenProvider, newLegacyTokenManager
oldEdition := edition.Get()
edition.Override(&edition.Hooks{})
newAccessTokenProvider = func(string) accessTokenGetter {
return tokenManagerSnapshotProvider{load: load}
}
newLegacyTokenManager = func(string) legacyTokenGetter {
return tokenManagerLegacyGetter{err: authpkg.ErrTokenDataNotFound}
}
t.Cleanup(func() {
newAccessTokenProvider, newLegacyTokenManager = oldProvider, oldLegacy
edition.Override(oldEdition)
})
}
func TestCrossPlatformCoverageTokenManagerCachesUntilMarkerRevisionChanges(t *testing.T) {
configDir := t.TempDir()
if err := authpkg.WriteTokenMarker(configDir); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
token := "token-a"
installTokenManagerFakes(t, func() (*authpkg.TokenData, error) {
calls.Add(1)
return &authpkg.TokenData{AccessToken: token, ExpiresAt: time.Now().Add(time.Hour)}, nil
})
manager := NewTokenManager()
first, err := manager.Get(context.Background(), configDir, "")
if err != nil || first.AccessToken != "token-a" {
t.Fatalf("first token = %#v, %v", first, err)
}
second, err := manager.Get(context.Background(), configDir, "")
if err != nil || second.AccessToken != "token-a" || calls.Load() != 1 {
t.Fatalf("cached token = %#v, %v, calls=%d", second, err, calls.Load())
}
token = "token-b"
if err := authpkg.WriteTokenMarker(configDir); err != nil {
t.Fatal(err)
}
rotated, err := manager.Get(context.Background(), configDir, "")
if err != nil || rotated.AccessToken != "token-b" || calls.Load() != 2 {
t.Fatalf("rotated token = %#v, %v, calls=%d", rotated, err, calls.Load())
}
}
func TestCrossPlatformCoverageTokenManagerDoesNotCacheWithoutExpiryOrRevision(t *testing.T) {
configDir := t.TempDir()
var calls atomic.Int32
installTokenManagerFakes(t, func() (*authpkg.TokenData, error) {
calls.Add(1)
return &authpkg.TokenData{AccessToken: "token"}, nil
})
manager := NewTokenManager()
for range 2 {
if _, err := manager.Get(context.Background(), configDir, ""); err != nil {
t.Fatal(err)
}
}
if calls.Load() != 2 {
t.Fatalf("provider calls = %d, want 2", calls.Load())
}
}
func TestCrossPlatformCoverageTokenManagerTreatsMalformedMarkerAsUncacheable(t *testing.T) {
configDir := t.TempDir()
if err := os.WriteFile(filepath.Join(configDir, "token.json"), []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
installTokenManagerFakes(t, func() (*authpkg.TokenData, error) {
calls.Add(1)
return &authpkg.TokenData{AccessToken: "token", ExpiresAt: time.Now().Add(time.Hour)}, nil
})
manager := NewTokenManager()
for range 2 {
if snapshot, err := manager.Get(context.Background(), configDir, ""); err != nil || snapshot.AccessToken != "token" {
t.Fatalf("snapshot = %#v, error = %v", snapshot, err)
}
}
if calls.Load() != 2 {
t.Fatalf("provider calls = %d, want 2", calls.Load())
}
}
func TestCrossPlatformCoverageTokenManagerDoesNotCacheOpaqueEditionStorageWithProviderFallback(t *testing.T) {
configDir := t.TempDir()
if err := authpkg.WriteTokenMarker(configDir); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
installTokenManagerFakes(t, func() (*authpkg.TokenData, error) {
calls.Add(1)
return &authpkg.TokenData{AccessToken: "token", ExpiresAt: time.Now().Add(time.Hour)}, nil
})
edition.Override(&edition.Hooks{
LoadToken: func(string) ([]byte, error) { return nil, nil },
TokenProvider: func(_ context.Context, fallback func() (string, error)) (string, error) {
return fallback()
},
})
manager := NewTokenManager()
for range 2 {
if _, err := manager.Get(context.Background(), configDir, ""); err != nil {
t.Fatal(err)
}
}
if calls.Load() != 2 {
t.Fatalf("provider calls = %d, want 2", calls.Load())
}
}
func TestCrossPlatformCoverageTokenManagerCoalescesConcurrentLoads(t *testing.T) {
configDir := t.TempDir()
if err := authpkg.WriteTokenMarker(configDir); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
release := make(chan struct{})
installTokenManagerFakes(t, func() (*authpkg.TokenData, error) {
calls.Add(1)
<-release
return &authpkg.TokenData{AccessToken: "token", ExpiresAt: time.Now().Add(time.Hour)}, nil
})
manager := NewTokenManager()
const workers = 8
var wg sync.WaitGroup
wg.Add(workers)
errs := make(chan error, workers)
for range workers {
go func() {
defer wg.Done()
_, err := manager.Get(context.Background(), configDir, "")
errs <- err
}()
}
for calls.Load() == 0 {
time.Sleep(time.Millisecond)
}
close(release)
wg.Wait()
close(errs)
for err := range errs {
if err != nil {
t.Fatal(err)
}
}
if calls.Load() != 1 {
t.Fatalf("provider calls = %d, want 1", calls.Load())
}
}
func TestCrossPlatformCoverageTokenManagerPreservesProviderFailure(t *testing.T) {
configDir := t.TempDir()
want := errors.New("keychain permission denied")
installTokenManagerFakes(t, func() (*authpkg.TokenData, error) { return nil, want })
_, err := NewTokenManager().Get(context.Background(), configDir, "")
if !errors.Is(err, want) {
t.Fatalf("error = %v, want cause %v", err, want)
}
if errors.Is(err, authpkg.ErrTokenDataNotFound) {
t.Fatalf("provider failure was misclassified as missing credentials: %v", err)
}
}
func TestCrossPlatformCoverageTokenResolutionErrorOnlyClassifiesTrueMissingCredential(t *testing.T) {
missing := tokenResolutionError(authpkg.ErrTokenDataNotFound)
var typed interface{ Unwrap() error }
if !errors.As(missing, &typed) || !errors.Is(missing, authpkg.ErrTokenDataNotFound) {
t.Fatalf("missing error = %v", missing)
}
want := errors.New("decrypt failed")
if got := tokenResolutionError(want); !errors.Is(got, want) || errors.Is(got, authpkg.ErrTokenDataNotFound) {
t.Fatalf("storage error = %v", got)
}
if got := tokenResolutionError(context.Canceled); !errors.Is(got, context.Canceled) {
t.Fatalf("cancellation = %v", got)
}
}
+37 -257
View File
@@ -21,283 +21,63 @@ import (
"log/slog"
"path/filepath"
"strings"
"sync"
"time"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
)
const accessTokenRefreshWindow = 5 * time.Minute
type legacyTokenGetter interface {
GetToken() (string, string, error)
}
type accessTokenSnapshotGetter interface {
GetTokenSnapshot(context.Context) (*authpkg.TokenData, error)
}
// AccessTokenSnapshot is the minimal bearer view needed by the process cache.
// Refresh-token material never leaves the auth package.
type AccessTokenSnapshot struct {
AccessToken string
ExpiresAt time.Time
Source string
}
type tokenManagerKey struct {
configDir string
profile string
}
type tokenManagerEntry struct {
mu sync.Mutex
snapshot AccessTokenSnapshot
revision string
}
// TokenManager is the only process cache for user access tokens. Cache entries
// are isolated by config directory and profile, expiry-aware, and invalidated
// by the credential publication marker written by auth storage.
type TokenManager struct {
mu sync.Mutex
entries map[tokenManagerKey]*tokenManagerEntry
now func() time.Time
}
func NewTokenManager() *TokenManager {
return &TokenManager{entries: make(map[tokenManagerKey]*tokenManagerEntry), now: time.Now}
}
var runtimeTokenManager = NewTokenManager()
var (
newAccessTokenProvider = func(configDir string) accessTokenGetter {
discard := slog.New(slog.NewTextHandler(io.Discard, nil))
provider := authpkg.NewOAuthProvider(configDir, discard)
configureOAuthProviderCompatibility(provider, configDir)
return provider
// resolveAccessTokenFromDir loads OAuth then legacy token from configDir, applying
// the same host compatibility hooks as MCP. It mirrors the former body of
// getCachedRuntimeToken (excluding process-level cache and timing).
func resolveAccessTokenFromDir(ctx context.Context, configDir string) (string, error) {
disc := slog.New(slog.NewTextHandler(io.Discard, nil))
provider := authpkg.NewOAuthProvider(configDir, disc)
configureOAuthProviderCompatibility(provider, configDir)
token, tokenErr := provider.GetAccessToken(ctx)
if tokenErr == nil && strings.TrimSpace(token) != "" {
return strings.TrimSpace(token), nil
}
newLegacyTokenManager = func(configDir string) legacyTokenGetter {
manager := authpkg.NewManager(configDir, nil)
configureLegacyAuthManagerCompatibility(manager)
return manager
if tokenErr != nil && errors.Is(tokenErr, authpkg.ErrTokenDecryption) {
return "", tokenErr
}
)
manager := authpkg.NewManager(configDir, nil)
configureLegacyAuthManagerCompatibility(manager)
if leg, _, err := manager.GetToken(); err == nil && strings.TrimSpace(leg) != "" {
return strings.TrimSpace(leg), nil
}
return "", nil
}
// Get resolves an access token for the active runtime profile.
func (m *TokenManager) Get(ctx context.Context, configDir, explicitToken string) (AccessTokenSnapshot, error) {
if token := strings.TrimSpace(explicitToken); token != "" {
return AccessTokenSnapshot{AccessToken: token, Source: "explicit"}, nil
// ResolveAuxiliaryAccessToken resolves a bearer token for HTTP clients that should
// align with MCP tool calls. Non-empty explicitToken wins. When configDir matches
// the active edition config directory, the same process-cached path as MCP is used.
// Otherwise tokens are loaded from configDir with host compatibility hooks applied.
func ResolveAuxiliaryAccessToken(ctx context.Context, configDir, explicitToken string) (string, error) {
if t := strings.TrimSpace(explicitToken); t != "" {
return t, nil
}
if strings.TrimSpace(configDir) == "" {
return AccessTokenSnapshot{}, fmt.Errorf("config directory is empty")
return "", fmt.Errorf("config directory is empty")
}
key := tokenManagerKey{
configDir: canonicalTokenConfigDir(configDir),
profile: strings.TrimSpace(authpkg.RuntimeProfile()),
}
entry := m.entry(key)
entry.mu.Lock()
defer entry.mu.Unlock()
now := time.Now()
if m != nil && m.now != nil {
now = m.now()
}
revision, present, err := authpkg.ReadTokenMarkerRevision(configDir)
if err != nil {
return AccessTokenSnapshot{}, err
}
if tokenSnapshotUsable(entry.snapshot, now) && present && revision != "" && revision == entry.revision {
return entry.snapshot, nil
}
// Treat the marker and credential as one optimistic snapshot. A concurrent
// login/refresh between the reads causes a retry instead of caching stale A
// under the publication marker for B.
for attempt := 0; attempt < 4; attempt++ {
beforeRevision, beforePresent, err := authpkg.ReadTokenMarkerRevision(configDir)
if err != nil {
return AccessTokenSnapshot{}, err
if filepath.Clean(configDir) == filepath.Clean(defaultConfigDir()) {
if tok := resolveRuntimeAuthToken(ctx, ""); tok != "" {
return tok, nil
}
snapshot, err := resolveTokenSnapshotWithEdition(ctx, configDir, key.profile)
if err != nil {
return AccessTokenSnapshot{}, err
}
afterRevision, afterPresent, err := authpkg.ReadTokenMarkerRevision(configDir)
if err != nil {
return AccessTokenSnapshot{}, err
}
if beforePresent != afterPresent || beforeRevision != afterRevision {
continue
}
if strings.TrimSpace(snapshot.AccessToken) == "" {
return AccessTokenSnapshot{}, noCredentialsError()
}
if tokenSnapshotUsable(snapshot, now) && afterPresent && afterRevision != "" {
entry.snapshot = snapshot
entry.revision = afterRevision
} else {
entry.snapshot = AccessTokenSnapshot{}
entry.revision = ""
}
return snapshot, nil
return "", noCredentialsError()
}
return AccessTokenSnapshot{}, fmt.Errorf("token publication changed repeatedly while resolving credentials")
}
func (m *TokenManager) entry(key tokenManagerKey) *tokenManagerEntry {
m.mu.Lock()
defer m.mu.Unlock()
if m.entries == nil {
m.entries = make(map[tokenManagerKey]*tokenManagerEntry)
}
entry := m.entries[key]
if entry == nil {
entry = &tokenManagerEntry{}
m.entries[key] = entry
}
return entry
}
func (m *TokenManager) Invalidate() {
if m == nil {
return
}
m.mu.Lock()
m.entries = make(map[tokenManagerKey]*tokenManagerEntry)
m.mu.Unlock()
}
func resolveTokenSnapshotWithEdition(ctx context.Context, configDir, profile string) (AccessTokenSnapshot, error) {
hooks := edition.Get()
opaqueStorage := hooks.LoadToken != nil || hooks.SaveToken != nil || hooks.DeleteToken != nil
provider := hooks.TokenProvider
if provider == nil {
snapshot, err := resolveAccessTokenSnapshotFromDir(ctx, configDir, profile)
if err != nil {
return AccessTokenSnapshot{}, err
}
// Opaque edition storage hooks have no publication-revision contract.
// Resolve them on every logical request instead of caching a token that
// may be replaced outside the default auth store.
if opaqueStorage {
snapshot.ExpiresAt = time.Time{}
}
return snapshot, nil
}
var fallbackSnapshot AccessTokenSnapshot
var fallbackCalled bool
token, err := provider(ctx, func() (string, error) {
fallbackCalled = true
var fallbackErr error
fallbackSnapshot, fallbackErr = resolveAccessTokenSnapshotFromDir(ctx, configDir, profile)
if fallbackErr != nil {
return "", fallbackErr
}
return fallbackSnapshot.AccessToken, nil
})
if err != nil {
return AccessTokenSnapshot{}, fmt.Errorf("edition token provider: %w", err)
}
token = strings.TrimSpace(token)
if token == "" {
return AccessTokenSnapshot{}, noCredentialsError()
}
if fallbackCalled && token == fallbackSnapshot.AccessToken {
if opaqueStorage {
fallbackSnapshot.ExpiresAt = time.Time{}
}
return fallbackSnapshot, nil
}
// Edition providers expose no lifetime metadata, so resolve them on every
// logical request instead of recreating a process-lifetime string cache.
return AccessTokenSnapshot{AccessToken: token, Source: "edition"}, nil
}
func resolveAccessTokenSnapshotFromDir(ctx context.Context, configDir, profile string) (AccessTokenSnapshot, error) {
provider := newAccessTokenProvider(configDir)
if snapshotProvider, ok := provider.(accessTokenSnapshotGetter); ok {
data, err := snapshotProvider.GetTokenSnapshot(ctx)
if err == nil && data != nil && strings.TrimSpace(data.AccessToken) != "" {
return AccessTokenSnapshot{
AccessToken: strings.TrimSpace(data.AccessToken),
ExpiresAt: data.ExpiresAt,
Source: "oauth",
}, nil
}
if err != nil && !errors.Is(err, authpkg.ErrTokenDataNotFound) {
return AccessTokenSnapshot{}, err
}
if strings.TrimSpace(profile) != "" {
return AccessTokenSnapshot{}, authpkg.ErrTokenDataNotFound
}
return resolveLegacyToken(configDir, err)
}
token, err := provider.GetAccessToken(ctx)
if err == nil && strings.TrimSpace(token) != "" {
return AccessTokenSnapshot{AccessToken: strings.TrimSpace(token), Source: "oauth_compat"}, nil
}
if err != nil && !errors.Is(err, authpkg.ErrTokenDataNotFound) {
return AccessTokenSnapshot{}, err
}
if strings.TrimSpace(profile) != "" {
return AccessTokenSnapshot{}, authpkg.ErrTokenDataNotFound
}
return resolveLegacyToken(configDir, err)
}
func resolveLegacyToken(configDir string, oauthErr error) (AccessTokenSnapshot, error) {
token, source, err := newLegacyTokenManager(configDir).GetToken()
if err == nil && strings.TrimSpace(token) != "" {
return AccessTokenSnapshot{AccessToken: strings.TrimSpace(token), Source: source}, nil
}
if err != nil && !errors.Is(err, authpkg.ErrTokenDataNotFound) {
return AccessTokenSnapshot{}, err
}
if oauthErr != nil {
return AccessTokenSnapshot{}, oauthErr
}
return AccessTokenSnapshot{}, authpkg.ErrTokenDataNotFound
}
func resolveAccessTokenFromDir(ctx context.Context, configDir string) (string, error) {
snapshot, err := resolveAccessTokenSnapshotFromDir(ctx, configDir, authpkg.RuntimeProfile())
tok, err := resolveAccessTokenFromDir(ctx, configDir)
if err != nil {
return "", err
}
return snapshot.AccessToken, nil
}
// ResolveAuxiliaryAccessToken resolves every non-runner bearer token through
// the same TokenManager used by MCP tool calls.
func ResolveAuxiliaryAccessToken(ctx context.Context, configDir, explicitToken string) (string, error) {
snapshot, err := runtimeTokenManager.Get(ctx, configDir, explicitToken)
if err != nil {
return "", err
if tok != "" {
return tok, nil
}
return snapshot.AccessToken, nil
}
func tokenSnapshotUsable(snapshot AccessTokenSnapshot, now time.Time) bool {
return strings.TrimSpace(snapshot.AccessToken) != "" &&
!snapshot.ExpiresAt.IsZero() &&
now.Before(snapshot.ExpiresAt.Add(-accessTokenRefreshWindow))
}
func canonicalTokenConfigDir(configDir string) string {
if absolute, err := filepath.Abs(configDir); err == nil {
return filepath.Clean(absolute)
}
return filepath.Clean(configDir)
return "", noCredentialsError()
}
func noCredentialsError() error {
if edition.Get().IsEmbedded {
return fmt.Errorf("认证信息已失效,请重新认证: %w", authpkg.ErrTokenDataNotFound)
return fmt.Errorf("认证信息已失效,请重新认证")
}
return fmt.Errorf("no credentials found, run: dws auth login: %w", authpkg.ErrTokenDataNotFound)
return fmt.Errorf("no credentials found, run: dws auth login")
}
-53
View File
@@ -5,15 +5,7 @@ package app
import (
"context"
"errors"
"net/http"
"path/filepath"
"strings"
"testing"
"time"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/keychain"
)
func TestResolveAuxiliaryAccessToken_explicitToken(t *testing.T) {
@@ -32,48 +24,3 @@ func TestResolveAuxiliaryAccessToken_emptyConfigDir(t *testing.T) {
t.Fatal("expected error for empty config directory")
}
}
func TestResolveAccessTokenFromDirPreservesRefreshFailure(t *testing.T) {
root := t.TempDir()
configDir := filepath.Join(root, "config")
t.Setenv(keychain.DisableKeychainEnv, "1")
t.Setenv(keychain.StorageDirEnv, filepath.Join(root, "keychain"))
if err := authpkg.SaveTokenData(configDir, &authpkg.TokenData{
AccessToken: "expired-access",
RefreshToken: "refresh-token",
ExpiresAt: time.Now().Add(-time.Hour),
RefreshExpAt: time.Now().Add(24 * time.Hour),
CorpID: "corp_refresh",
UserID: "user_refresh",
ClientID: "client_refresh",
Source: "mcp",
}); err != nil {
t.Fatalf("SaveTokenData() error = %v", err)
}
originalTransport := http.DefaultTransport
t.Cleanup(func() {
http.DefaultTransport = originalTransport
})
http.DefaultTransport = refreshFailureRoundTripFunc(func(*http.Request) (*http.Response, error) {
return nil, errors.New("refresh endpoint rejected token")
})
token, err := resolveAccessTokenFromDir(context.Background(), configDir)
if token != "" {
t.Fatalf("token = %q, want empty", token)
}
if err == nil {
t.Fatal("resolveAccessTokenFromDir() error = nil")
}
if !strings.Contains(err.Error(), "refresh endpoint rejected token") {
t.Fatalf("error = %q, want original refresh failure", err)
}
}
type refreshFailureRoundTripFunc func(*http.Request) (*http.Response, error)
func (f refreshFailureRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
+11 -17
View File
@@ -38,19 +38,6 @@ type apiFlags struct {
baseURL string
}
type appTokenGetter interface {
GetToken(context.Context) (string, error)
}
var newAppTokenProvider = func(configDir, appKey, appSecret string) appTokenGetter {
return &authpkg.AppTokenProvider{ConfigDir: configDir, AppKey: appKey, AppSecret: appSecret}
}
var (
apiClientID = authpkg.ClientID
apiClientSecret = authpkg.ClientSecret
)
// newAPICommand creates the `dws api` subcommand for raw DingTalk OpenAPI calls.
func newAPICommand(flags *GlobalFlags) *cobra.Command {
af := &apiFlags{}
@@ -284,7 +271,10 @@ func parseQueryStringToJSON(rawQuery string) string {
return "{}"
}
data, _ := json.Marshal(paramsMap)
data, err := json.Marshal(paramsMap)
if err != nil {
return "{}"
}
return string(data)
}
@@ -299,8 +289,8 @@ func resolveRawAPIToken(ctx context.Context, explicitToken string) (string, erro
}
// Resolve app credentials (clientID/clientSecret).
appKey := apiClientID()
appSecret := apiClientSecret()
appKey := authpkg.ClientID()
appSecret := authpkg.ClientSecret()
if appKey == "" || appSecret == "" || strings.HasPrefix(appKey, "<") || strings.HasPrefix(appSecret, "<") {
return "", apperrors.NewAuth(
@@ -318,7 +308,11 @@ func resolveRawAPIToken(ctx context.Context, explicitToken string) (string, erro
// Use AppTokenProvider for automatic caching and refresh.
configDir := defaultConfigDir()
provider := newAppTokenProvider(configDir, appKey, appSecret)
provider := &authpkg.AppTokenProvider{
ConfigDir: configDir,
AppKey: appKey,
AppSecret: appSecret,
}
token, err := provider.GetToken(ctx)
if err != nil {
return "", apperrors.NewAuth(fmt.Sprintf("获取应用级访问令牌失败: %v", err))
-404
View File
@@ -1,404 +0,0 @@
package app
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/plugin"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/spf13/cobra"
)
type appFailWriter struct{ err error }
func (w appFailWriter) Write([]byte) (int, error) { return 0, w.err }
type fakeAccessTokenGetter struct {
token string
err error
}
func (g fakeAccessTokenGetter) GetAccessToken(context.Context) (string, error) {
return g.token, g.err
}
func (g fakeAccessTokenGetter) ForceRefreshRejectedToken(context.Context, string) (string, error) {
return g.token, g.err
}
type fakeLegacyTokenGetter struct {
token string
err error
}
func (g fakeLegacyTokenGetter) GetToken() (string, string, error) {
return g.token, "test", g.err
}
type fakeAppTokenGetter struct {
token string
err error
}
func (g fakeAppTokenGetter) GetToken(context.Context) (string, error) { return g.token, g.err }
type fakeSkillDirEntry struct{ dir bool }
func (e fakeSkillDirEntry) Name() string { return "entry" }
func (e fakeSkillDirEntry) IsDir() bool { return e.dir }
func (e fakeSkillDirEntry) Type() os.FileMode { return 0 }
func (e fakeSkillDirEntry) Info() (os.FileInfo, error) { return nil, nil }
func docPreflightServer(t *testing.T, result map[string]any) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var request struct {
ID int `json:"id"`
}
_ = json.NewDecoder(r.Body).Decode(&request)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"jsonrpc": "2.0",
"id": request.ID,
"result": result,
})
}))
}
func TestCrossPlatformCoverageDocDownloadPreflightCoverage(t *testing.T) {
runner := &runtimeRunner{}
base := executor.Invocation{CanonicalProduct: "doc", Tool: "download_file", Params: map[string]any{"nodeId": " node "}}
if err := runner.preflightDocDownload(context.Background(), transport.NewClient(nil), "", executor.Invocation{}); err != nil {
t.Fatal(err)
}
if err := runner.preflightDocDownload(context.Background(), transport.NewClient(nil), "", executor.Invocation{CanonicalProduct: "DOC", Tool: "download_file"}); err != nil {
t.Fatal(err)
}
if !isDocDownloadInvocation(base) || docDownloadNodeID(map[string]any{"node": " n "}) != "n" || docDownloadNodeID(map[string]any{"dentryUuid": " d "}) != "d" || docDownloadNodeID(map[string]any{"nodeId": 1}) != "" {
t.Fatal("doc download invocation helpers returned unexpected values")
}
if documentInfoExtension(map[string]any{"data": map[string]any{"extension": " doc "}}) != "doc" ||
documentInfoExtension(map[string]any{"extension": " pdf "}) != "pdf" ||
stringAtPath(map[string]any{"x": "value"}, "x", "nested") != "" ||
stringAtPath(map[string]any{"x": 1}, "x") != "" {
t.Fatal("document extension helpers returned unexpected values")
}
if unsupportedAXLSDownloadError() == nil {
t.Fatal("missing AXLS validation error")
}
oldEdition := edition.Get()
t.Cleanup(func() { edition.Override(oldEdition) })
hookErr := errors.New("classified")
for _, tc := range []struct {
name string
result map[string]any
hooks *edition.Hooks
want string
}{
{name: "ok", result: map[string]any{"content": map[string]any{"result": map[string]any{"extension": "docx"}}}, hooks: &edition.Hooks{}},
{name: "edition classifier", result: map[string]any{"content": map[string]any{}}, hooks: &edition.Hooks{ClassifyToolResult: func(map[string]any) error { return hookErr }}, want: "classified"},
{name: "pat", result: map[string]any{"content": map[string]any{"errorCode": "PAT_NO_PERMISSION"}}, hooks: &edition.Hooks{}, want: "PAT_NO_PERMISSION"},
{name: "mcp error", result: map[string]any{"isError": true, "content": []map[string]any{{"type": "text", "text": "mcp failed"}}}, hooks: &edition.Hooks{}, want: "mcp failed"},
{name: "business error", result: map[string]any{"content": map[string]any{"success": false, "errorMsg": "business failed"}}, hooks: &edition.Hooks{}, want: "business failed"},
{name: "axls", result: map[string]any{"content": map[string]any{"data": map[string]any{"extension": "AXLS"}}}, hooks: &edition.Hooks{}, want: "extension=axls"},
} {
t.Run(tc.name, func(t *testing.T) {
edition.Override(tc.hooks)
server := docPreflightServer(t, tc.result)
defer server.Close()
client := transport.NewClient(nil)
client.TrustedDomains = []string{"127.0.0.1"}
err := runner.preflightDocDownload(context.Background(), client, server.URL, base)
if tc.want == "" && err != nil {
t.Fatalf("preflight error = %v", err)
}
if tc.want != "" && (err == nil || !strings.Contains(err.Error(), tc.want)) {
t.Fatalf("preflight error = %v, want %q", err, tc.want)
}
})
}
server := docPreflightServer(t, map[string]any{})
endpoint := server.URL
server.Close()
client := transport.NewClient(nil)
client.TrustedDomains = []string{"127.0.0.1"}
client.MaxRetries = 0
if err := runner.preflightDocDownload(context.Background(), client, endpoint, base); err == nil {
t.Fatal("network preflight failure succeeded")
}
}
func TestCrossPlatformCoverageRootHelpRemainingCoverage(t *testing.T) {
configureRootHelp(nil)
renderRootGlobalFlags(nil)
if visiblePersistentFlags(nil) != nil || formatRootFlag(nil) != "" || commandShort(nil) != "" || visibleMCPRootCommands(nil) != nil || visibleUtilityRootCommands(nil) != nil {
t.Fatal("nil root helper contract changed")
}
oldEdition := edition.Get()
edition.Override(&edition.Hooks{VisibleProducts: func() []string { return []string{"service"} }})
t.Cleanup(func() { edition.Override(oldEdition); SetDynamicServers(nil) })
root := &cobra.Command{Use: "root", Long: "long help"}
root.SetOut(io.Discard)
root.PersistentFlags().StringP("value", "x", "", "value")
root.PersistentFlags().Bool("hidden", false, "hidden")
_ = root.PersistentFlags().MarkHidden("hidden")
root.AddCommand(&cobra.Command{Use: "service", Short: "service"}, &cobra.Command{Use: "utility", Short: "utility"})
configureRootHelp(root)
if err := root.Commands()[0].Help(); err != nil {
t.Fatal(err)
}
root.SetArgs([]string{"help", "missing"})
if err := root.Execute(); err != nil {
t.Fatal(err)
}
root.SetArgs([]string{"help", "utility"})
if err := root.Execute(); err != nil {
t.Fatal(err)
}
if got := formatRootFlag(root.PersistentFlags().Lookup("value")); !strings.Contains(got, "-x") {
t.Fatalf("formatted flag = %q", got)
}
if got := formatRootFlag(root.PersistentFlags().Lookup("hidden")); !strings.Contains(got, "--hidden") {
t.Fatalf("formatted long flag = %q", got)
}
_ = commandShort(&cobra.Command{Use: "help", Short: "Help about any command"})
renderRootGlobalFlags(&cobra.Command{Use: "no-flags"})
edition.Override(&edition.Hooks{})
SetDynamicServers(nil)
_ = visibleMCPRootCommands(root)
}
func TestCrossPlatformCoverageConfigAndTokenSeamsCoverage(t *testing.T) {
oldHome, oldExe, oldEval := userHomeDir, executablePath, evaluateSymlink
oldEdition := edition.Get()
t.Cleanup(func() {
userHomeDir, executablePath, evaluateSymlink = oldHome, oldExe, oldEval
edition.Override(oldEdition)
})
t.Setenv("DWS_CONFIG_DIR", "")
edition.Override(&edition.Hooks{})
userHomeDir = func() (string, error) { return "", errors.New("home") }
executablePath = func() (string, error) { return "", errors.New("exe") }
if got := defaultConfigDir(); got != ".dws" {
t.Fatalf("fallback config dir = %q", got)
}
executablePath = func() (string, error) { return filepath.Join("", "tmp", "dws"), nil }
evaluateSymlink = func(string) (string, error) { return "", errors.New("link") }
if got := exeRelativeConfigDir(); !strings.HasSuffix(got, filepath.Join("tmp", ".dws")) {
t.Fatalf("executable config dir = %q", got)
}
userHomeDir = func() (string, error) { return "/home/test", nil }
if got := defaultConfigDir(); got != filepath.Join("/home/test", ".dws") {
t.Fatalf("home config dir = %q", got)
}
edition.Override(&edition.Hooks{ConfigDir: func() string { return "/edition" }})
if got := defaultConfigDir(); got != "/edition" {
t.Fatalf("edition config dir = %q", got)
}
oldProvider, oldManager := newAccessTokenProvider, newLegacyTokenManager
t.Cleanup(func() { newAccessTokenProvider, newLegacyTokenManager = oldProvider, oldManager })
newAccessTokenProvider = func(string) accessTokenGetter { return fakeAccessTokenGetter{err: authpkg.ErrTokenDecryption} }
if _, err := resolveAccessTokenFromDir(context.Background(), "unused"); !errors.Is(err, authpkg.ErrTokenDecryption) {
t.Fatalf("decryption error = %v", err)
}
newAccessTokenProvider = func(string) accessTokenGetter {
return fakeAccessTokenGetter{err: authpkg.ErrTokenDataNotFound}
}
newLegacyTokenManager = func(string) legacyTokenGetter { return fakeLegacyTokenGetter{token: " legacy "} }
if got, err := resolveAccessTokenFromDir(context.Background(), "unused"); err != nil || got != "legacy" {
t.Fatalf("legacy token = %q, %v", got, err)
}
authpkg.SetRuntimeProfile("corp:user")
t.Cleanup(func() { authpkg.SetRuntimeProfile("") })
if got, err := resolveAccessTokenFromDir(context.Background(), "unused"); got != "" || !errors.Is(err, authpkg.ErrTokenDataNotFound) {
t.Fatalf("explicit profile fallback = token %q error %v, want profile error", got, err)
}
authpkg.SetRuntimeProfile("")
newAccessTokenProvider = func(string) accessTokenGetter { return fakeAccessTokenGetter{err: errors.New("load")} }
newLegacyTokenManager = func(string) legacyTokenGetter { return fakeLegacyTokenGetter{err: errors.New("missing")} }
edition.Override(&edition.Hooks{})
other := filepath.Join(t.TempDir(), "other")
if _, err := ResolveAuxiliaryAccessToken(context.Background(), other, ""); err == nil {
t.Fatal("auxiliary provider failure succeeded")
}
newAccessTokenProvider = func(string) accessTokenGetter { return fakeAccessTokenGetter{err: authpkg.ErrTokenDecryption} }
if _, err := ResolveAuxiliaryAccessToken(context.Background(), other, ""); !errors.Is(err, authpkg.ErrTokenDecryption) {
t.Fatalf("auxiliary decryption error = %v", err)
}
t.Setenv("DWS_CONFIG_DIR", other)
ResetRuntimeTokenCache()
if _, err := ResolveAuxiliaryAccessToken(context.Background(), other, ""); err == nil {
t.Fatal("current config without credentials succeeded")
}
edition.Override(&edition.Hooks{IsEmbedded: true})
if !strings.Contains(noCredentialsError().Error(), "认证") {
t.Fatal("embedded credentials error changed")
}
}
func TestCrossPlatformCoverageForceRefreshAndStdioFailureCoverage(t *testing.T) {
oldLoad, oldFactory := loadRefreshTokenData, newRefreshProvider
oldStop := stopStdio
t.Cleanup(func() {
loadRefreshTokenData, newRefreshProvider = oldLoad, oldFactory
stopStdio = oldStop
stdioMu.Lock()
stdioClients = make(map[string]*transport.StdioClient)
stdioMu.Unlock()
})
fail := errors.New("failure")
_ = oldFactory(t.TempDir())
loadRefreshTokenData = func(string) (*authpkg.TokenData, error) { return nil, fail }
if _, err := ForceRefreshAccessToken(context.Background(), "config"); !errors.Is(err, fail) {
t.Fatalf("load rejected token error = %v", err)
}
loadRefreshTokenData = func(string) (*authpkg.TokenData, error) {
return &authpkg.TokenData{AccessToken: "rejected"}, nil
}
for _, tc := range []struct {
getter fakeAccessTokenGetter
want string
}{
{getter: fakeAccessTokenGetter{err: fail}, want: "failure"},
{getter: fakeAccessTokenGetter{token: " "}, want: "empty"},
{getter: fakeAccessTokenGetter{token: " refreshed "}},
} {
newRefreshProvider = func(string) rejectedAccessTokenRefresher { return tc.getter }
got, err := ForceRefreshAccessToken(context.Background(), "config")
if tc.want != "" && (err == nil || !strings.Contains(err.Error(), tc.want)) {
t.Fatalf("refresh error = %v, want %q", err, tc.want)
}
if tc.want == "" && (err != nil || got != "refreshed") {
t.Fatalf("refreshed token = %q, %v", got, err)
}
}
stopStdio = func(*transport.StdioClient) error { return fail }
RegisterStdioClient("all", transport.NewStdioClient("unused", nil, nil))
StopAllStdioClients()
RegisterStdioClient("one", transport.NewStdioClient("unused", nil, nil))
if !StopStdioClient("one") {
t.Fatal("registered stdio client not stopped")
}
RegisterStdioClient("plugin/server", transport.NewStdioClient("unused", nil, nil))
if got := StopStdioClientsByPlugin("plugin"); got != 1 {
t.Fatalf("stopped plugin clients = %d", got)
}
}
func TestCrossPlatformCoverageOverlayRecoveryHostAndHelperRemainingCoverage(t *testing.T) {
root := t.TempDir()
writeOverlay := filepath.Join(root, "overlay.json")
if err := os.WriteFile(writeOverlay, []byte(`{"toolOverrides":{"tool":{}}}`), 0o600); err != nil {
t.Fatal(err)
}
for _, raw := range []json.RawMessage{
json.RawMessage(`"missing.json"`),
json.RawMessage(`"unterminated`),
json.RawMessage(`{`),
json.RawMessage(`"overlay.json"`),
json.RawMessage(`{"id":"","command":"","toolOverrides":{"tool":{}}}`),
} {
p := &plugin.Plugin{Root: root, Manifest: plugin.Manifest{Name: "plugin", Description: "description", MCPServers: map[string]*plugin.MCPServer{"server": {CLI: raw}}}}
overlay := resolveStdioOverlay(p, plugin.StdioServerClient{Key: "server", Client: transport.NewStdioClient("unused", nil, nil)})
if overlay.ID == "" || overlay.Command == "" {
t.Fatalf("overlay defaults missing: %#v", overlay)
}
}
p := &plugin.Plugin{Root: root, Manifest: plugin.Manifest{Name: "plugin", Description: "description", MCPServers: map[string]*plugin.MCPServer{"server": {CLI: json.RawMessage(`{}`)}}}}
if descriptor := registerStdioServerFromManifest(p, plugin.StdioServerClient{Key: "server"}); descriptor.Endpoint == "" {
t.Fatalf("empty overlay descriptor = %#v", descriptor)
}
p.Manifest.MCPServers["server"].CLI = json.RawMessage(`{"toolOverrides":{"tool":{}}}`)
if descriptor := registerStdioServerFromManifest(p, plugin.StdioServerClient{Key: "server", Client: transport.NewStdioClient("unused", nil, nil)}); descriptor.Endpoint == "" {
t.Fatalf("stdio overlay registration = %#v", descriptor)
}
oldEdition := edition.Get()
t.Cleanup(func() { edition.Override(oldEdition); SetDynamicServers(nil) })
edition.Override(&edition.Hooks{ConfigDir: func() string { return "" }})
captureRuntimeFailure(executor.Invocation{}, nil, nil)
captureRuntimeFailure(executor.Invocation{}, errors.New("raw"), nil)
oldArgs := os.Args
os.Args = []string{"dws", "doc", "download", "--node", "n"}
if got := runtimeCommandPath(executor.Invocation{}); len(got) != 2 {
t.Fatalf("runtime command path = %#v", got)
}
os.Args = oldArgs
t.Setenv(authpkg.AgentCodeEnv, "")
if hostControlProviderFromEnv() != "" {
t.Fatal("host control enabled without agent code")
}
t.Setenv(authpkg.AgentCodeEnv, "agent")
edition.Override(&edition.Hooks{MergeHeaders: func(headers map[string]string) map[string]string { return headers }})
if got := hostControlProviderFromEnv(); got != edition.DefaultOSSClawType {
t.Fatalf("default claw type = %q", got)
}
edition.Override(&edition.Hooks{MergeHeaders: func(map[string]string) map[string]string { return map[string]string{"claw-type": "custom"} }})
if got := effectiveClawType(); got != "custom" {
t.Fatalf("custom claw type = %q", got)
}
}
func TestCrossPlatformCoverageConfigAndCacheCommandRemainingCoverage(t *testing.T) {
for _, command := range []*cobra.Command{newConfigCommand(), newCacheCommand()} {
command.SetOut(io.Discard)
if err := command.RunE(command, nil); err != nil {
t.Fatal(err)
}
}
t.Setenv("DWS_CONFIG_DIR", "configured")
configCmd := &cobra.Command{Use: "config"}
var configOut bytes.Buffer
configCmd.SetOut(&configOut)
if err := writeConfigJSON(configCmd, filterVisible(nil), true); err != nil {
t.Fatal(err)
}
list := newConfigListCommand()
list.SetOut(io.Discard)
_ = list.Flags().Set("category", "core")
_ = list.Flags().Set("show-values", "true")
_ = list.Flags().Set("show-hidden", "true")
_ = list.Flags().Set("json", "true")
if err := runConfigList(list, nil); err != nil {
t.Fatal(err)
}
cacheRoot := &cobra.Command{Use: "root"}
cacheRoot.PersistentFlags().String("format", "", "")
cacheCmd := &cobra.Command{Use: "cache"}
cacheRoot.AddCommand(cacheCmd)
for _, format := range []string{"json", "pretty", "table"} {
_ = cacheRoot.PersistentFlags().Set("format", format)
cacheCmd.SetOut(io.Discard)
if err := printCacheCompatNotice(cacheCmd, "status"); err != nil {
t.Fatal(err)
}
}
fail := errors.New("write")
cacheCmd.SetOut(appFailWriter{err: fail})
_ = cacheRoot.PersistentFlags().Set("format", "pretty")
if err := printCacheCompatNotice(cacheCmd, "status"); !errors.Is(err, fail) {
t.Fatalf("pretty write error = %v", err)
}
_ = cacheRoot.PersistentFlags().Set("format", "table")
if err := printCacheCompatNotice(cacheCmd, "status"); !errors.Is(err, fail) {
t.Fatalf("table write error = %v", err)
}
}
-282
View File
@@ -1,282 +0,0 @@
package app
import (
"context"
"errors"
"io"
"io/fs"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/apiclient"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/mcptypes"
"github.com/spf13/cobra"
)
func TestCrossPlatformCoverageAPIAndTimingRemainingCoverage(t *testing.T) {
oldProvider := newAppTokenProvider
oldClientID, oldClientSecret := apiClientID, apiClientSecret
oldMarshal, oldMkdir := timingMarshalIndent, timingMkdirAll
oldWrite, oldRemove, oldRename := timingWriteFile, timingRemove, timingRename
oldRead, oldHome := timingReadFile, timingUserHomeDir
t.Cleanup(func() {
newAppTokenProvider = oldProvider
apiClientID, apiClientSecret = oldClientID, oldClientSecret
timingMarshalIndent, timingMkdirAll = oldMarshal, oldMkdir
timingWriteFile, timingRemove, timingRename = oldWrite, oldRemove, oldRename
timingReadFile, timingUserHomeDir = oldRead, oldHome
authpkg.SetClientID("")
authpkg.SetClientSecret("")
})
fail := errors.New("failure")
apiClientID = func() string { return "" }
apiClientSecret = func() string { return "" }
if _, err := resolveRawAPIToken(context.Background(), ""); err == nil {
t.Fatal("missing raw API credentials succeeded")
}
apiClientID = func() string { return "<placeholder>" }
apiClientSecret = func() string { return "secret" }
if _, err := resolveRawAPIToken(context.Background(), ""); err == nil {
t.Fatal("placeholder raw API credentials succeeded")
}
apiClientID, apiClientSecret = authpkg.ClientID, authpkg.ClientSecret
authpkg.SetClientID("app-key")
authpkg.SetClientSecret("app-secret")
for _, tc := range []struct {
getter fakeAppTokenGetter
want string
}{
{getter: fakeAppTokenGetter{err: fail}, want: "failure"},
{getter: fakeAppTokenGetter{token: " "}, want: "为空"},
{getter: fakeAppTokenGetter{token: " token "}},
} {
newAppTokenProvider = func(string, string, string) appTokenGetter { return tc.getter }
got, err := resolveRawAPIToken(context.Background(), "")
if tc.want != "" && (err == nil || !containsText(err.Error(), tc.want)) {
t.Fatalf("raw token error = %v, want %q", err, tc.want)
}
if tc.want == "" && (err != nil || got != "token") {
t.Fatalf("raw token = %q, %v", got, err)
}
}
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
endpoint := server.URL
server.Close()
apiclient.AllowedHosts["127.0.0.1"] = true
t.Cleanup(func() { delete(apiclient.AllowedHosts, "127.0.0.1") })
cmd := &cobra.Command{Use: "api"}
cmd.SetContext(context.Background())
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
if err := runAPI(cmd, []string{"GET", "/path"}, &GlobalFlags{Token: "token", Timeout: 1}, &apiFlags{baseURL: endpoint}); err == nil {
t.Fatal("closed raw API endpoint succeeded")
}
collector := NewTimingCollector()
collector.Print(io.Discard)
t.Setenv(PerfReportEnv, t.TempDir()+"/report.json")
timingMarshalIndent = func(any, string, string) ([]byte, error) { return nil, fail }
collector.WriteReportIfEnabled("v", "cmd")
timingMarshalIndent = oldMarshal
timingUserHomeDir = func() (string, error) { return "", fail }
t.Setenv(PerfReportEnv, "auto")
collector.WriteReportIfEnabled("v", "cmd")
if defaultPerfReportPath() != "" {
t.Fatal("home-dir failure produced a report path")
}
t.Setenv(PerfReportEnv, t.TempDir()+"/report.json")
timingMkdirAll = func(string, os.FileMode) error { return fail }
collector.WriteReportIfEnabled("v", "cmd")
timingMkdirAll = oldMkdir
timingWriteFile = func(string, []byte, os.FileMode) error { return fail }
removed := false
timingRemove = func(string) error { removed = true; return nil }
collector.WriteReportIfEnabled("v", "cmd")
if !removed {
t.Fatal("failed temporary report was not removed")
}
timingWriteFile = oldWrite
timingRemove = oldRemove
renamed := false
timingRename = func(string, string) error { renamed = true; return fail }
collector.WriteReportIfEnabled("v", "cmd")
if !renamed {
t.Fatal("report rename was not attempted")
}
timingReadFile = func(string) ([]byte, error) { return []byte("{"), nil }
if _, err := LoadLatestReport(); err == nil {
t.Fatal("malformed performance report succeeded")
}
}
func TestCrossPlatformCoverageDirectRuntimeRemainingCoverage(t *testing.T) {
oldEdition := edition.Get()
t.Cleanup(func() {
edition.Override(oldEdition)
SetDynamicServers(nil)
})
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
for _, raw := range []string{
"not a url",
"https://mcp.dingtalk.com/path?q=1#fragment",
"https://pre-mcp.example.test:8443/path/",
"https://mcp.example.test/path/",
} {
if err := os.WriteFile(filepath.Join(configDir, "mcp_url"), []byte(raw), 0o600); err != nil {
t.Fatal(err)
}
if got := defaultPATGatewayBaseURL(); got == "" {
t.Fatalf("gateway for %q is blank", raw)
}
}
endpoints := map[string]string{}
products := map[string]bool{}
aliases := map[string]string{}
tools := map[string]string{}
registerDynamicServer(mcptypes.ServerDescriptor{CLI: mcptypes.CLIOverlay{Skip: true}}, endpoints, products, aliases, tools)
registerDynamicServer(mcptypes.ServerDescriptor{
Endpoint: "https://server.test",
CLI: mcptypes.CLIOverlay{
ID: "id", Command: "command", Aliases: []string{"alias", " "},
Tools: []mcptypes.CLITool{{Name: "tool"}, {Name: " "}},
ToolOverrides: map[string]mcptypes.CLIToolOverride{"override": {}, " ": {}},
},
}, endpoints, products, aliases, tools)
if endpoints["command"] == "" || aliases["alias"] != "id" || tools["override"] == "" {
t.Fatalf("registered dynamic server = %#v %#v %#v", endpoints, aliases, tools)
}
SetDynamicServers(nil)
dynamicMu.Lock()
dynamicEndpoints = map[string]string{}
dynamicProducts = map[string]bool{}
dynamicAliases = map[string]string{}
dynamicToolEndpoints = map[string]string{}
dynamicMu.Unlock()
if got, ok := directRuntimeEndpoint(defaultPATProductID, ""); !ok || got == "" {
t.Fatal("cold-start PAT fallback did not resolve")
}
SetDynamicServers(nil)
if _, ok := directRuntimeEndpoint(" ", " "); ok {
t.Fatal("blank runtime endpoint resolved")
}
t.Setenv("DINGTALK_CUSTOM_MCP_URL", "https://override.test")
if got, ok := directRuntimeEndpoint("custom", ""); !ok || got != "https://override.test" {
t.Fatalf("environment runtime endpoint = %q, %v", got, ok)
}
if got, ok := directRuntimeEndpoint(devappProductID, ""); !ok || got == "" {
t.Fatal("devapp fallback did not resolve")
}
if got, ok := directRuntimeEndpoint(defaultPATProductID, ""); !ok || got == "" {
t.Fatal("PAT fallback did not resolve")
}
edition.Override(&edition.Hooks{
StaticServers: func() []edition.ServerInfo { return []edition.ServerInfo{{ID: "other", Endpoint: ""}} },
SupplementServers: func() []edition.ServerInfo {
return []edition.ServerInfo{{ID: "other", Endpoint: "https://other.test", Prefixes: []string{" ", "wanted"}}}
},
})
if got, ok := directRuntimeEndpoint("wanted", ""); !ok || got != "https://other.test" {
t.Fatalf("edition runtime endpoint = %q, %v", got, ok)
}
dynamicMu.Lock()
dynamicEndpoints, dynamicProducts, dynamicAliases, dynamicToolEndpoints = nil, nil, nil, nil
dynamicMu.Unlock()
AppendDynamicServer(mcptypes.ServerDescriptor{
Endpoint: "https://append.test",
CLI: mcptypes.CLIOverlay{
ID: "append", Command: "append-command", Aliases: []string{"append-alias"},
Tools: []mcptypes.CLITool{{Name: "append-tool"}},
ToolOverrides: map[string]mcptypes.CLIToolOverride{
"append-override": {}, "skip": {ServerOverride: "other"}, " ": {},
},
},
})
if got, ok := directRuntimeToolEndpoint("append-override"); !ok || got != "https://append.test" {
t.Fatalf("append override endpoint = %q, %v", got, ok)
}
}
func containsText(value, substring string) bool {
for i := 0; i+len(substring) <= len(value); i++ {
if value[i:i+len(substring)] == substring {
return true
}
}
return false
}
func TestCrossPlatformCoverageEmbeddedSkillAndTinyCommandsRemainingCoverage(t *testing.T) {
oldStat, oldTemp, oldRemove := embeddedSkillStat, embeddedSkillMkdirTemp, embeddedSkillRemoveAll
oldWalk, oldRead := embeddedSkillWalkDir, embeddedSkillReadFile
oldMkdir, oldWrite := embeddedSkillMkdirAll, embeddedSkillWriteFile
t.Cleanup(func() {
embeddedSkillStat, embeddedSkillMkdirTemp, embeddedSkillRemoveAll = oldStat, oldTemp, oldRemove
embeddedSkillWalkDir, embeddedSkillReadFile = oldWalk, oldRead
embeddedSkillMkdirAll, embeddedSkillWriteFile = oldMkdir, oldWrite
})
fail := errors.New("failure")
embeddedSkillStat = func(string) (os.FileInfo, error) { return nil, nil }
embeddedSkillMkdirTemp = func(string, string) (string, error) { return "", fail }
if _, _, err := materializeEmbeddedSkillSource("codex"); !errors.Is(err, fail) {
t.Fatalf("embedded mkdir error = %v", err)
}
embeddedSkillMkdirTemp = func(string, string) (string, error) { return t.TempDir(), nil }
removed := false
embeddedSkillRemoveAll = func(string) error { removed = true; return nil }
embeddedSkillWalkDir = func(_ string, fn fs.WalkDirFunc) error {
return fn("entry", nil, fail)
}
if _, _, err := materializeEmbeddedSkillSource("codex"); !errors.Is(err, fail) || !removed {
t.Fatalf("embedded walk error = %v, removed=%v", err, removed)
}
embeddedSkillWalkDir = func(_ string, fn fs.WalkDirFunc) error {
return fn("skills/codex/file", fakeSkillDirEntry{}, nil)
}
embeddedSkillReadFile = func(string) ([]byte, error) { return nil, fail }
if _, _, err := materializeEmbeddedSkillSource("codex"); !errors.Is(err, fail) {
t.Fatalf("embedded read error = %v", err)
}
embeddedSkillReadFile = func(string) ([]byte, error) { return []byte("skill"), nil }
embeddedSkillMkdirAll = func(string, os.FileMode) error { return fail }
if _, _, err := materializeEmbeddedSkillSource("codex"); !errors.Is(err, fail) {
t.Fatalf("embedded nested mkdir error = %v", err)
}
embeddedSkillWalkDir = func(_ string, fn fs.WalkDirFunc) error {
return fn("skills/codex/dir", fakeSkillDirEntry{dir: true}, nil)
}
if _, _, err := materializeEmbeddedSkillSource("codex"); !errors.Is(err, fail) {
t.Fatalf("embedded directory mkdir error = %v", err)
}
embeddedSkillWalkDir = func(_ string, fn fs.WalkDirFunc) error {
return fn("skills/codex/file", fakeSkillDirEntry{}, nil)
}
embeddedSkillMkdirAll = func(string, os.FileMode) error { return nil }
embeddedSkillWriteFile = func(string, []byte, os.FileMode) error { return fail }
if _, _, err := materializeEmbeddedSkillSource("codex"); !errors.Is(err, fail) {
t.Fatalf("embedded write error = %v", err)
}
merged := mergeTopLevelCommands([]*cobra.Command{nil, {}})
if len(merged) != 0 {
t.Fatalf("empty legacy commands = %#v", merged)
}
root := &cobra.Command{Use: "root"}
completion := newCompletionCommand(root)
if err := completion.RunE(completion, []string{"other"}); err != nil {
t.Fatal(err)
}
catalog := newCatalogCommand(nil)
catalog.SetOut(io.Discard)
if err := catalog.RunE(catalog, nil); err != nil {
t.Fatal(err)
}
}
+8 -37
View File
@@ -13,18 +13,9 @@ import (
"time"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/audit"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/output"
"github.com/spf13/cobra"
)
var (
auditCSVWrite = func(writer *csv.Writer, record []string) error { return writer.Write(record) }
auditCSVFlush = func(writer *csv.Writer) { writer.Flush() }
auditCSVError = func(writer *csv.Writer) error { return writer.Error() }
auditExit = os.Exit
auditVerify = audit.VerifyFile
)
func newAuditCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "audit",
@@ -118,35 +109,15 @@ func newAuditVerifyCommand() *cobra.Command {
}
}
valid, brokenAt, verifyErr := auditVerify(target)
if output.ResolveFormat(cmd, output.FormatTable) == output.FormatJSON {
if verifyErr != nil && brokenAt == 0 {
return fmt.Errorf("校验失败: %w", verifyErr)
}
payload := map[string]any{
"valid": valid,
"file": target,
"brokenAt": brokenAt,
}
if verifyErr != nil {
payload["reason"] = verifyErr.Error()
}
if err := output.WriteCommandPayload(cmd, payload, output.FormatTable); err != nil {
return err
}
if !valid {
auditExit(1)
}
return nil
}
if verifyErr != nil {
return fmt.Errorf("校验失败: %w", verifyErr)
valid, brokenAt, err := audit.VerifyFile(target)
if err != nil {
return fmt.Errorf("校验失败: %w", err)
}
if valid {
fmt.Printf("✓ %s 哈希链完整(全部通过)\n", filepath.Base(target))
} else {
fmt.Printf("✗ %s 哈希链在第 %d 行断裂\n", filepath.Base(target), brokenAt)
auditExit(1)
os.Exit(1)
}
return nil
},
@@ -208,7 +179,7 @@ func exportCSV(files []string) error {
w := csv.NewWriter(os.Stdout)
header := []string{"timestamp", "execution_id", "user_id", "corp_id", "product", "command", "result", "duration_ms", "error_category"}
if err := auditCSVWrite(w, header); err != nil {
if err := w.Write(header); err != nil {
return fmt.Errorf("写入 CSV 表头失败: %w", err)
}
@@ -242,7 +213,7 @@ func exportCSV(files []string) error {
strconv.FormatInt(evt.DurationMs, 10),
evt.ErrCategory,
}
if err := auditCSVWrite(w, row); err != nil {
if err := w.Write(row); err != nil {
f.Close()
return fmt.Errorf("写入 CSV 记录失败: %w", err)
}
@@ -254,8 +225,8 @@ func exportCSV(files []string) error {
f.Close()
}
auditCSVFlush(w)
if err := auditCSVError(w); err != nil {
w.Flush()
if err := w.Error(); err != nil {
return fmt.Errorf("刷新 CSV 输出失败: %w", err)
}
return nil
-264
View File
@@ -1,264 +0,0 @@
package app
import (
"encoding/csv"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/audit"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/logging"
)
type auditCoverageSink struct {
events []*audit.Event
emitErr error
closeErr error
}
func (sink *auditCoverageSink) Emit(event *audit.Event) error {
sink.events = append(sink.events, event)
return sink.emitErr
}
func (sink *auditCoverageSink) Close() error { return sink.closeErr }
func TestCrossPlatformCoverageAuditCommandsAndFileHelpersCoverage(t *testing.T) {
originalExit, originalVerify := auditExit, auditVerify
t.Cleanup(func() { auditExit, auditVerify = originalExit, originalVerify })
dir := t.TempDir()
t.Setenv(audit.EnvAuditDir, dir)
if auditDir() != dir {
t.Fatalf("auditDir() = %q", auditDir())
}
tail := newAuditTailCommand()
tail.SetArgs([]string{"--lines", "1"})
if err := tail.Execute(); err == nil || !strings.Contains(err.Error(), "无审计记录") {
t.Fatalf("audit tail(empty) error = %v", err)
}
path := filepath.Join(dir, "audit-20260101.jsonl")
if err := os.WriteFile(path, []byte("one\ntwo\n"), 0o600); err != nil {
t.Fatal(err)
}
tail = newAuditTailCommand()
tail.SetArgs([]string{"--lines", "1"})
if err := tail.Execute(); err != nil {
t.Fatal(err)
}
if _, err := tailFile(filepath.Join(dir, "missing"), 1); err == nil {
t.Fatal("tailFile(missing) error = nil")
}
tailErrorDir := t.TempDir()
if err := os.Mkdir(filepath.Join(tailErrorDir, "audit-20260101.jsonl"), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv(audit.EnvAuditDir, tailErrorDir)
tail = newAuditTailCommand()
if err := tail.Execute(); err == nil {
t.Fatal("audit tail(directory record) error = nil")
}
oversize := filepath.Join(dir, "oversize")
if err := os.WriteFile(oversize, []byte(strings.Repeat("x", 2*1024*1024)), 0o600); err != nil {
t.Fatal(err)
}
if _, err := tailFile(oversize, 1); err == nil {
t.Fatal("tailFile(oversize) error = nil")
}
exportDir := t.TempDir()
t.Setenv(audit.EnvAuditDir, exportDir)
export := newAuditExportCommand()
if err := export.Execute(); err == nil || !strings.Contains(err.Error(), "无审计文件") {
t.Fatalf("audit export(empty) error = %v", err)
}
if err := os.WriteFile(filepath.Join(exportDir, "audit-20260102.jsonl"), []byte("{}\n"), 0o600); err != nil {
t.Fatal(err)
}
for _, format := range []string{"jsonl", "csv"} {
export = newAuditExportCommand()
export.SetArgs([]string{"--since", "2026-01-01", "--until", "2026-01-03", "--format", format})
if err := export.Execute(); err != nil {
t.Fatalf("audit export(%s) error = %v", format, err)
}
}
export = newAuditExportCommand()
export.SetArgs([]string{"--format", "xml"})
if err := export.Execute(); err == nil || !strings.Contains(err.Error(), "不支持的格式") {
t.Fatalf("audit export(xml) error = %v", err)
}
t.Setenv(audit.EnvAuditDir, filepath.Join(exportDir, "missing"))
export = newAuditExportCommand()
if err := export.Execute(); err == nil || !strings.Contains(err.Error(), "查找审计文件失败") {
t.Fatalf("audit export(missing dir) error = %v", err)
}
if err := exportJSONL([]string{filepath.Join(dir, "missing")}); err == nil {
t.Fatal("exportJSONL(missing) error = nil")
}
if err := exportJSONL([]string{oversize}); err == nil {
t.Fatal("exportJSONL(oversize) error = nil")
}
if err := exportCSV([]string{filepath.Join(dir, "missing")}); err == nil {
t.Fatal("exportCSV(missing) error = nil")
}
blank := filepath.Join(dir, "blank")
if err := os.WriteFile(blank, []byte("\n \n{}\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := exportCSV([]string{blank}); err != nil {
t.Fatal(err)
}
if err := exportCSV([]string{oversize}); err == nil {
t.Fatal("exportCSV(oversize) error = nil")
}
originalWrite, originalFlush, originalError := auditCSVWrite, auditCSVFlush, auditCSVError
t.Cleanup(func() { auditCSVWrite, auditCSVFlush, auditCSVError = originalWrite, originalFlush, originalError })
auditCSVWrite = func(*csv.Writer, []string) error { return errors.New("write") }
if err := exportCSV(nil); err == nil || !strings.Contains(err.Error(), "表头") {
t.Fatalf("exportCSV(header error) = %v", err)
}
calls := 0
auditCSVWrite = func(writer *csv.Writer, row []string) error {
calls++
if calls > 1 {
return errors.New("row")
}
return originalWrite(writer, row)
}
if err := exportCSV([]string{blank}); err == nil || !strings.Contains(err.Error(), "记录") {
t.Fatalf("exportCSV(row error) = %v", err)
}
auditCSVWrite = originalWrite
auditCSVError = func(*csv.Writer) error { return errors.New("flush") }
if err := exportCSV(nil); err == nil || !strings.Contains(err.Error(), "刷新") {
t.Fatalf("exportCSV(flush error) = %v", err)
}
t.Setenv(audit.EnvAuditDir, t.TempDir())
verify := newAuditVerifyCommand()
if err := verify.Execute(); err == nil || !strings.Contains(err.Error(), "无审计文件") {
t.Fatalf("audit verify(empty) error = %v", err)
}
verify = newAuditVerifyCommand()
verify.SetArgs([]string{"--file", filepath.Join(dir, "missing")})
if err := verify.Execute(); err == nil || !strings.Contains(err.Error(), "校验失败") {
t.Fatalf("audit verify(missing) error = %v", err)
}
validDir := t.TempDir()
writer, err := audit.NewDateRotatingWriter(validDir, 1)
if err != nil {
t.Fatal(err)
}
sink := audit.NewFileSink(writer, audit.NewChain(validDir), nil)
if err := sink.Emit(&audit.Event{Timestamp: time.Now(), Product: "test", Command: "ok"}); err != nil {
t.Fatal(err)
}
if err := sink.Close(); err != nil {
t.Fatal(err)
}
validFile, err := audit.LatestAuditFile(validDir)
if err != nil {
t.Fatal(err)
}
verify = newAuditVerifyCommand()
verify.SetArgs([]string{"--file", validFile})
if err := verify.Execute(); err != nil {
t.Fatal(err)
}
broken := filepath.Join(t.TempDir(), "audit-broken.jsonl")
if err := os.WriteFile(broken, []byte(`{"prev_hash":"wrong","hash":"wrong"}`+"\n"), 0o600); err != nil {
t.Fatal(err)
}
exitCode := 0
auditExit = func(code int) { exitCode = code }
auditVerify = func(string) (bool, int, error) { return false, 1, nil }
verify = newAuditVerifyCommand()
verify.SetArgs([]string{"--file", broken})
if err := verify.Execute(); err != nil || exitCode != 1 {
t.Fatalf("audit verify(broken) = %v, exit=%d", err, exitCode)
}
t.Setenv(audit.EnvAuditDir, "")
if auditDir() == "" {
t.Fatal("default auditDir() is empty")
}
}
func TestCrossPlatformCoverageAuditRuntimeCoverage(t *testing.T) {
previousSink, previousLoader := sharedAuditSink, loadTokenForProfile
t.Cleanup(func() {
sharedAuditSink = previousSink
loadTokenForProfile = previousLoader
auditSinkOnce, auditCloseOnce = sync.Once{}, sync.Once{}
resetAuditIdentityCache()
})
sharedAuditSink = nil
auditCloseOnce = sync.Once{}
CloseAuditSink()
failedClose := &auditCoverageSink{closeErr: errors.New("close")}
sharedAuditSink = failedClose
auditCloseOnce = sync.Once{}
CloseAuditSink()
bad := filepath.Join(t.TempDir(), "file")
if err := os.WriteFile(bad, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv(audit.EnvAudit, "1")
t.Setenv(audit.EnvAuditDir, filepath.Join(bad, "child"))
auditSinkOnce = sync.Once{}
sharedAuditSink = nil
if _, ok := setupAuditSink().(audit.NopSink); !ok {
t.Fatalf("setupAuditSink(error) = %T", sharedAuditSink)
}
t.Setenv(audit.EnvAuditDebug, "1")
fileLogger = logging.Setup(t.TempDir())
t.Cleanup(func() {
if fileLogger != nil {
fileLogger.Close()
fileLogger = nil
}
})
auditReport("coverage %d", 1)
loadTokenForProfile = func(string, string) (*auth.TokenData, error) { return nil, errors.New("identity") }
resetAuditIdentityCache()
if actor, _ := auditIdentity(); actor.UserID != "" {
t.Fatalf("auditIdentity(error) = %+v", actor)
}
invocation := executor.Invocation{CanonicalProduct: "calendar", Tool: "list", Params: map[string]any{"token": "secret"}}
emitAudit(nil, "nil", time.Now(), invocation, "https://example.com?token=secret", nil, "test")
emitAudit(audit.NopSink{}, "nop", time.Now(), invocation, "", nil, "test")
recording := &auditCoverageSink{}
emitAudit(recording, "ok", time.Now(), invocation, "https://example.com?token=secret", nil, "test")
if len(recording.events) != 1 || recording.events[0].Result != "success" {
t.Fatalf("successful audit events = %#v", recording.events)
}
typed := &apperrors.Error{Category: apperrors.CategoryAuth, Reason: "expired"}
emitAudit(recording, "typed", time.Now(), invocation, "", typed, "test")
if recording.events[1].ErrReason != "expired" {
t.Fatalf("typed audit event = %#v", recording.events[1])
}
recording.emitErr = errors.New("emit")
emitAudit(recording, "failed", time.Now(), invocation, "", errors.New("plain"), "test")
if category, reason := classifyAuditError(nil); category != "" || reason != "" {
t.Fatalf("classifyAuditError(nil) = %q, %q", category, reason)
}
if category, reason := classifyAuditError(fmt.Errorf("wrapped: %w", typed)); category != string(apperrors.CategoryAuth) || reason != "expired" {
t.Fatalf("classifyAuditError(typed) = %q, %q", category, reason)
}
if category, reason := classifyAuditError(errors.New("plain")); category != "unknown" || reason != "plain" {
t.Fatalf("classifyAuditError(plain) = %q, %q", category, reason)
}
}
@@ -1,65 +0,0 @@
// 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.
package app
import (
"bytes"
"encoding/json"
"errors"
"testing"
"github.com/spf13/cobra"
)
func executeAuditVerifyJSON(t *testing.T, verify func(string) (bool, int, error)) (map[string]any, int, error) {
t.Helper()
previousVerify, previousExit := auditVerify, auditExit
t.Cleanup(func() {
auditVerify, auditExit = previousVerify, previousExit
})
auditVerify = verify
exitCode := 0
auditExit = func(code int) { exitCode = code }
root := &cobra.Command{Use: "dws"}
root.SilenceErrors = true
root.SilenceUsage = true
root.PersistentFlags().String("format", "json", "output format")
root.AddCommand(newAuditVerifyCommand())
var stdout bytes.Buffer
root.SetOut(&stdout)
root.SetArgs([]string{"verify", "--file", "/tmp/audit.jsonl"})
err := root.Execute()
var payload map[string]any
if decodeErr := json.Unmarshal(stdout.Bytes(), &payload); decodeErr != nil {
t.Fatalf("audit verify stdout must be one JSON document: %v\n%s", decodeErr, stdout.String())
}
return payload, exitCode, err
}
func TestCrossPlatformCoverageAuditVerifyJSONOutputIsSingleDocument(t *testing.T) {
payload, exitCode, err := executeAuditVerifyJSON(t, func(string) (bool, int, error) {
return true, 0, nil
})
if err != nil || exitCode != 0 {
t.Fatalf("audit verify returned err=%v exit=%d", err, exitCode)
}
if payload["valid"] != true || payload["file"] != "/tmp/audit.jsonl" || payload["brokenAt"] != float64(0) {
t.Fatalf("unexpected audit payload: %#v", payload)
}
}
func TestCrossPlatformCoverageAuditVerifyBrokenJSONIncludesReasonBeforeExit(t *testing.T) {
payload, exitCode, err := executeAuditVerifyJSON(t, func(string) (bool, int, error) {
return false, 3, errors.New("prev_hash mismatch")
})
if err != nil || exitCode != 1 {
t.Fatalf("broken audit verify returned err=%v exit=%d", err, exitCode)
}
if payload["valid"] != false || payload["brokenAt"] != float64(3) || payload["reason"] != "prev_hash mismatch" {
t.Fatalf("unexpected broken audit payload: %#v", payload)
}
}
+97 -281
View File
@@ -30,7 +30,6 @@ import (
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/helpers"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/keychain"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/logging"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/pat"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
@@ -86,7 +85,7 @@ func buildAuthCommand(patCaller edition.ToolCaller) *cobra.Command {
newAuthMigrateKeychainCommand(),
newAuthExportCommand(),
newAuthImportCommand(),
newAuthExchangeCommand(patCaller),
newAuthExchangeCommand(),
newAuthResetCommand(),
)
return cmd
@@ -137,7 +136,7 @@ func newAuthLoginCommand(patCaller edition.ToolCaller) *cobra.Command {
AccessToken: cfg.Token,
ExpiresAt: time.Now().Add(config.ManualTokenExpiry),
}
if err := authSaveTokenData(configDir, tokenData); err != nil {
if err := authpkg.SaveTokenData(configDir, tokenData); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to persist auth token: %v", err))
}
case cfg.Device:
@@ -147,10 +146,7 @@ func newAuthLoginCommand(patCaller edition.ToolCaller) *cobra.Command {
provider := authpkg.NewDeviceFlowProvider(configDir, nil)
provider.Output = cmd.ErrOrStderr()
provider.NoBrowser, _ = cmd.Flags().GetBool("no-browser")
provider.IdentityEnricher = func(ctx context.Context, data *authpkg.TokenData) error {
return enrichAuthLoginProfileFromContact(ctx, configDir, patCaller, data)
}
tokenData, err = authDeviceLogin(provider, loginCtx)
tokenData, err = provider.Login(loginCtx)
if err != nil {
return apperrors.NewAuth(fmt.Sprintf("device authorization failed: %v", err))
}
@@ -162,11 +158,8 @@ func newAuthLoginCommand(patCaller edition.ToolCaller) *cobra.Command {
provider.Output = cmd.ErrOrStderr()
provider.NoBrowser, _ = cmd.Flags().GetBool("no-browser")
provider.TargetCorpID = cfg.TargetCorpID
provider.IdentityEnricher = func(ctx context.Context, data *authpkg.TokenData) error {
return enrichAuthLoginProfileFromContact(ctx, configDir, patCaller, data)
}
configureOAuthProviderCompatibility(provider, configDir)
tokenData, err = authOAuthLogin(provider, loginCtx, authLoginForcesAuthorization(cfg))
tokenData, err = provider.Login(loginCtx, authLoginForcesAuthorization(cfg))
if err != nil {
return apperrors.NewAuth(fmt.Sprintf("dingtalk login failed: %v", err))
}
@@ -174,18 +167,22 @@ func newAuthLoginCommand(patCaller edition.ToolCaller) *cobra.Command {
ResetRuntimeTokenCache()
clearCompatCache()
if tokenData != nil && strings.TrimSpace(tokenData.CorpID) != "" {
_ = enrichAuthLoginProfileFromContact(cmd.Context(), configDir, patCaller, tokenData)
ResetRuntimeTokenCache()
clearCompatCache()
}
w := cmd.OutOrStdout()
runPostLoginAuthorization := func() error {
if !recommendAuthMode {
return nil
}
restoreProfile := replaceRuntimeProfile(authpkg.TokenProfileSelector(tokenData))
defer restoreProfile()
recommendScopeMode := pat.LoginRecommendScopeRecommended
var initialPlan *pat.LoginRecommendPlan
if postLoginTUIMode {
var planErr error
initialPlan, planErr = authPlanLoginRecommend(cmd.Context(), patCaller)
initialPlan, planErr = pat.PlanLoginRecommendAuthorization(cmd.Context(), patCaller)
if planErr != nil {
return planErr
}
@@ -210,11 +207,11 @@ func newAuthLoginCommand(patCaller edition.ToolCaller) *cobra.Command {
retryFormat = "table"
}
run := func(ctx context.Context) error {
return authRunLoginRecommend(ctx, patCaller, cmd.ErrOrStderr(), opts)
return pat.RunLoginRecommendAuthorizationWithOptions(ctx, patCaller, cmd.ErrOrStderr(), opts)
}
err := run(cmd.Context())
if patErr := apperrors.AsPatAuthCheckError(err); patErr != nil {
return authRunDirectPATWait(
return runDirectPATAuthCheckWaitOnly(
cmd.Context(),
&GlobalFlags{Format: retryFormat},
patErr,
@@ -237,7 +234,11 @@ func newAuthLoginCommand(patCaller edition.ToolCaller) *cobra.Command {
return err
}
fmt.Fprintln(w)
fmt.Fprintln(w, authLoginStatusLine("登录成功!"))
if !cfg.Device && tokenData != nil && tokenData.IsAccessTokenValid() && !authLoginForcesAuthorization(cfg) {
fmt.Fprintln(w, authLoginStatusLine("Token 有效,无需重新登录"))
} else {
fmt.Fprintln(w, authLoginStatusLine("登录成功!"))
}
if tokenData != nil {
if tokenData.CorpName != "" {
fmt.Fprintln(w, authLoginInfoLine("企业", tokenData.CorpName))
@@ -278,53 +279,12 @@ func newAuthLoginCommand(patCaller edition.ToolCaller) *cobra.Command {
}
var (
authLoginGuideActionSelector = selectAuthLoginGuideAction
authLoginGuideActionApplier = applyAuthLoginGuideAction
authLoginManualCredentialsPrompt = promptAuthLoginManualCredentials
loginRecommendScopeModeSelector = selectLoginRecommendScopeMode
loginRecommendProductSelector = selectLoginRecommendProducts
authLoginInteractiveTerminal = isInteractiveTerminal
migrateKeychainToFileDEK = authpkg.MigrateKeychainToFileDEK
authMigrateTarget = func(cmd *cobra.Command) (string, error) { return cmd.Flags().GetString("to") }
authRunForm = (*huh.Form).Run
authSaveTokenData = authpkg.SaveTokenData
authSaveAppConfig = authpkg.SaveAppConfig
authDeviceLogin = func(provider *authpkg.DeviceFlowProvider, ctx context.Context) (*authpkg.TokenData, error) {
return provider.Login(ctx)
}
authOAuthLogin = func(provider *authpkg.OAuthProvider, ctx context.Context, force bool) (*authpkg.TokenData, error) {
return provider.Login(ctx, force)
}
authOAuthStatus = func(provider *authpkg.OAuthProvider) (*authpkg.TokenData, error) { return provider.Status() }
authOAuthAccessToken = func(provider *authpkg.OAuthProvider, ctx context.Context) (string, error) {
return provider.GetAccessToken(ctx)
}
authOAuthExchange = func(provider *authpkg.OAuthProvider, ctx context.Context, code, uid string) (*authpkg.TokenData, error) {
return provider.ExchangeAuthCode(ctx, code, uid)
}
authPlanLoginRecommend = pat.PlanLoginRecommendAuthorization
authRunLoginRecommend = pat.RunLoginRecommendAuthorizationWithOptions
authRunDirectPATWait = runDirectPATAuthCheckWaitOnly
authResolveProfile = authpkg.ResolveProfile
authResolveProfileDeletion = authpkg.ResolveProfileDeletionScope
authRevokeToken = authpkg.RevokeTokenRemote
authRevokeTokenForData = authpkg.RevokeTokenRemoteForData
authLoadTokenForProfile = authpkg.LoadTokenDataForProfile
authDeleteProfileToken = authpkg.DeleteTokenDataForProfile
authEnsureProfilesMigration = authpkg.EnsureProfilesMigration
authLoadProfiles = authpkg.LoadProfiles
authDeleteAllTokenData = authpkg.DeleteAllTokenData
authDeleteTokenData = authpkg.DeleteTokenData
authMarkProfileStatus = authpkg.MarkProfileStatus
authPortableExportSupported = authpkg.PortableExportSupported
authPortableSourceReady = authpkg.PortableAuthSourceReady
authPortableTargetPopulated = authpkg.PortableAuthTargetPopulated
authExportPortableBundle = authpkg.ExportPortableAuthBundle
authImportPortableBundle = authpkg.ImportPortableAuthBundle
authAtomicWrite = helpers.AtomicWrite
authReadFile = os.ReadFile
authRemove = os.Remove
authDeleteAppConfig = authpkg.DeleteAppConfig
authLoginGuideActionSelector = selectAuthLoginGuideAction
authLoginGuideActionApplier = applyAuthLoginGuideAction
loginRecommendScopeModeSelector = selectLoginRecommendScopeMode
loginRecommendProductSelector = selectLoginRecommendProducts
authLoginInteractiveTerminal = isInteractiveTerminal
migrateKeychainToFileDEK = authpkg.MigrateKeychainToFileDEK
)
func selectAuthLoginGuideAction() (authLoginGuideAction, error) {
@@ -341,7 +301,7 @@ func selectAuthLoginGuideAction() (authLoginGuideAction, error) {
Value(&choice),
),
).WithTheme(authLoginHuhTheme())
if err := authRunForm(form); err != nil {
if err := form.Run(); err != nil {
return "", fmt.Errorf("使用引导选择中止: %w", err)
}
return choice, nil
@@ -355,13 +315,13 @@ func applyAuthLoginGuideAction(cmd *cobra.Command, configDir string, action auth
fmt.Fprintln(cmd.ErrOrStderr(), "一键配置智能体应用暂未开放,已继续使用 CLI 登录")
return nil
case authLoginGuideManualCredentials:
clientID, clientSecret, err := authLoginManualCredentialsPrompt()
clientID, clientSecret, err := promptAuthLoginManualCredentials()
if err != nil {
return err
}
authpkg.SetClientID(clientID)
authpkg.SetClientSecret(clientSecret)
if err := authSaveAppConfig(configDir, &authpkg.AppConfig{
if err := authpkg.SaveAppConfig(configDir, &authpkg.AppConfig{
ClientID: clientID,
ClientSecret: authpkg.PlainSecret(clientSecret),
}); err != nil {
@@ -375,34 +335,33 @@ func applyAuthLoginGuideAction(cmd *cobra.Command, configDir string, action auth
func promptAuthLoginManualCredentials() (string, string, error) {
var clientID, clientSecret string
nonEmpty := func(label string) func(string) error {
return func(value string) error {
if strings.TrimSpace(value) == "" {
return fmt.Errorf("%s 不能为空", label)
}
return nil
}
}
form := huh.NewForm(
huh.NewGroup(
huh.NewInput().
Title("输入 AppKey").
Value(&clientID).
Validate(authLoginNonEmpty("AppKey")),
Validate(nonEmpty("AppKey")),
huh.NewInput().
Title("输入 AppSecret").
EchoMode(huh.EchoModePassword).
Value(&clientSecret).
Validate(authLoginNonEmpty("AppSecret")),
Validate(nonEmpty("AppSecret")),
),
).WithTheme(authLoginHuhTheme())
if err := authRunForm(form); err != nil {
if err := form.Run(); err != nil {
return "", "", fmt.Errorf("应用凭证输入中止: %w", err)
}
return strings.TrimSpace(clientID), strings.TrimSpace(clientSecret), nil
}
func authLoginNonEmpty(label string) func(string) error {
return func(value string) error {
if strings.TrimSpace(value) == "" {
return fmt.Errorf("%s 不能为空", label)
}
return nil
}
}
func selectLoginRecommendScopeMode() (pat.LoginRecommendScopeMode, error) {
choice := pat.LoginRecommendScopeRecommended
form := huh.NewForm(
@@ -417,7 +376,7 @@ func selectLoginRecommendScopeMode() (pat.LoginRecommendScopeMode, error) {
Value(&choice),
),
).WithTheme(authLoginHuhTheme())
if err := authRunForm(form); err != nil {
if err := form.Run(); err != nil {
return "", fmt.Errorf("授权范围选择中止: %w", err)
}
return choice, nil
@@ -429,10 +388,9 @@ func newAuthLogoutCommand() *cobra.Command {
Short: "清除认证信息(默认退出所有组织)",
Long: `清除本机钉钉登录态。
默认退出全部账号。--profile 传组织时退出该组织全部账号;传精确账号或本地 profile 名时只退出一个账号。`,
默认退出所有已登录组织 profile;指定 --profile 时只退出该组织,不影响其他组织。`,
Example: ` dws auth logout
dws auth logout --profile <corpId>
dws auth logout --profile <corpId>:<userId>
dws auth logout --profile "钉钉"`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -462,7 +420,7 @@ func newAuthLogoutCommand() *cobra.Command {
return nil
},
}
cmd.Flags().String("profile", "", "指定组织或账号:corpId、corpName、corpId:userId、corpId:userName、corpName:userId、corpName:userName 或本地 profile 名")
cmd.Flags().String("profile", "", "指定要退出的 profile 名或 corpId")
return cmd
}
@@ -475,8 +433,7 @@ func newAuthStatusCommand() *cobra.Command {
指定 --profile 时只读取并刷新被选中的 token slot,不会修改 currentProfile。`,
Example: ` dws auth status
dws auth status --profile <corpId>
dws auth status --profile <corpId>:<userId>
dws auth status --profile "钉钉:孙博文"
dws auth status --profile "钉钉"
dws auth status --profile <corpId> --format json`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -485,17 +442,6 @@ func newAuthStatusCommand() *cobra.Command {
if err != nil {
return apperrors.NewInternal("failed to read --profile")
}
profileSelector = strings.TrimSpace(profileSelector)
if profileSelector != "" {
selected, resolveErr := authpkg.ResolveProfile(configDir, profileSelector)
if resolveErr != nil {
return apperrors.NewValidation(resolveErr.Error())
}
if selected == nil {
return apperrors.NewValidation(fmt.Sprintf("profile %q not found", profileSelector))
}
profileSelector = authpkg.ProfileSelector(*selected)
}
restoreProfile := pushRuntimeProfile(profileSelector)
defer restoreProfile()
@@ -503,38 +449,32 @@ func newAuthStatusCommand() *cobra.Command {
refreshed := false
var tokenData *authpkg.TokenData
var statusErr error
var refreshFailure error
provider := authpkg.NewOAuthProvider(configDir, nil)
configureOAuthProviderCompatibility(provider, configDir)
if data, err := authOAuthStatus(provider); err == nil {
if data, err := provider.Status(); err == nil {
tokenData = data
if !data.IsAccessTokenValid() && data.IsRefreshTokenValid() {
refreshCtx, cancel := context.WithTimeout(cmd.Context(), 15*time.Second)
_, refreshErr := authOAuthAccessToken(provider, refreshCtx)
_, refreshErr := provider.GetAccessToken(refreshCtx)
cancel()
if refreshErr == nil {
if updatedData, statusErr := authOAuthStatus(provider); statusErr == nil {
if updatedData, statusErr := provider.Status(); statusErr == nil {
tokenData = updatedData
refreshed = true
}
} else if edition.Get().AutoPurgeToken {
refreshFailure = refreshErr
_ = authDeleteTokenData(configDir)
_ = authpkg.DeleteTokenData(configDir)
} else if tokenData != nil {
refreshFailure = refreshErr
_ = authMarkProfileStatus(configDir, authpkg.TokenProfileSelector(tokenData), authpkg.ProfileStatusExpired)
_ = authpkg.MarkProfileStatus(configDir, tokenData.CorpID, authpkg.ProfileStatusExpired)
}
}
if refreshFailure == nil && authStatusAuthenticated(tokenData) {
if authStatusAuthenticated(tokenData) {
authenticated = true
}
} else {
statusErr = err
}
diagnostic := authStatusDiagnosticFromError(statusErr)
if refreshFailure != nil {
diagnostic = authStatusRefreshDiagnostic(refreshFailure)
}
// Check if JSON output is requested
format, _ := cmd.Root().PersistentFlags().GetString("format")
@@ -579,7 +519,7 @@ func newAuthStatusCommand() *cobra.Command {
return nil
},
}
cmd.Flags().String("profile", "", "指定组织或账号:corpId、corpName、corpId:userId、corpId:userName、corpName:userId、corpName:userName 或本地 profile 名")
cmd.Flags().String("profile", "", "指定要查看的 profile 名或 corpId")
return cmd
}
@@ -596,7 +536,7 @@ func newAuthMigrateKeychainCommand() *cobra.Command {
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
target, err := authMigrateTarget(cmd)
target, err := cmd.Flags().GetString("to")
if err != nil {
return apperrors.NewInternal("failed to read --to")
}
@@ -643,56 +583,36 @@ func newAuthMigrateKeychainCommand() *cobra.Command {
}
func logoutOneProfile(_ *cobra.Command, ctx context.Context, configDir, selector string) error {
selected, exact, err := authResolveProfileDeletion(configDir, selector)
if err != nil {
if _, err := authpkg.ResolveProfile(configDir, selector); err != nil {
return apperrors.NewValidation(err.Error())
}
if selected == nil {
return apperrors.NewValidation(fmt.Sprintf("profile %q not found", selector))
}
stableSelector := selected.CorpID
if exact {
stableSelector = authpkg.ProfileSelector(*selected)
if data, loadErr := authLoadTokenForProfile(configDir, stableSelector); loadErr == nil {
_ = authRevokeTokenForData(ctx, data)
}
} else if cfg, loadErr := authLoadProfiles(configDir); loadErr == nil {
for _, profile := range cfg.Profiles {
if profile.CorpID != selected.CorpID {
continue
}
if data, tokenErr := authLoadTokenForProfile(configDir, authpkg.ProfileSelector(profile)); tokenErr == nil {
_ = authRevokeTokenForData(ctx, data)
}
}
}
if err := authDeleteProfileToken(configDir, stableSelector); err != nil {
if strings.Contains(err.Error(), "not found") {
return apperrors.NewValidation(err.Error())
}
restoreProfile := pushRuntimeProfile(selector)
defer restoreProfile()
_ = authpkg.RevokeTokenRemote(ctx)
if err := authpkg.DeleteTokenDataForProfile(configDir, selector); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to clear token data: %v", err))
}
return nil
}
func logoutAllProfiles(_ *cobra.Command, ctx context.Context, configDir string) error {
if err := authEnsureProfilesMigration(configDir); err != nil {
if err := authpkg.EnsureProfilesMigration(configDir); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to migrate profiles: %v", err))
}
cfg, err := authLoadProfiles(configDir)
cfg, err := authpkg.LoadProfiles(configDir)
if err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to load profiles: %v", err))
}
if cfg == nil || len(cfg.Profiles) == 0 {
_ = authRevokeToken(ctx)
_ = authpkg.RevokeTokenRemote(ctx)
} else {
for _, profile := range cfg.Profiles {
if data, tokenErr := authLoadTokenForProfile(configDir, authpkg.ProfileSelector(profile)); tokenErr == nil {
_ = authRevokeTokenForData(ctx, data)
}
restoreProfile := pushRuntimeProfile(profile.CorpID)
_ = authpkg.RevokeTokenRemote(ctx)
restoreProfile()
}
}
if err := authDeleteAllTokenData(configDir); err != nil {
if err := authpkg.DeleteAllTokenData(configDir); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to clear token data: %v", err))
}
return nil
@@ -710,19 +630,7 @@ func pushRuntimeProfile(selector string) func() {
}
}
func replaceRuntimeProfile(selector string) func() {
previous := authpkg.RuntimeProfile()
authpkg.SetRuntimeProfile(strings.TrimSpace(selector))
return func() {
authpkg.SetRuntimeProfile(previous)
}
}
func newAuthExportCommand() *cobra.Command {
return newAuthExportCommandWithSupport(authpkg.PortableExportSupportError)
}
func newAuthExportCommandWithSupport(supportError func() error) *cobra.Command {
cmd := &cobra.Command{
Use: "export",
Short: "导出可迁移认证包",
@@ -747,21 +655,18 @@ func newAuthExportCommandWithSupport(supportError func() error) *cobra.Command {
if !asBase64 && output == "" {
return apperrors.NewValidation("--output is required unless --base64 is used")
}
if err := supportError(); err != nil {
return apperrors.NewValidation(err.Error())
}
if !authPortableExportSupported() {
if !authpkg.PortableExportSupported() {
return apperrors.NewValidation(fmt.Sprintf(
"macOS 导出认证包需要 file-DEK 模式;请先设置 %s=1 并运行 dws auth status 验证,只有提示密钥不匹配且确认可丢弃旧登录态时,才执行 dws auth reset 后重新登录",
keychain.DisableKeychainEnv,
))
}
if !authPortableSourceReady() {
if !authpkg.PortableAuthSourceReady() {
return apperrors.NewValidation("尚未登录,请先运行 dws auth login --recommend")
}
var bundle bytes.Buffer
if err := authExportPortableBundle(defaultConfigDir(), &bundle); err != nil {
if err := authpkg.ExportPortableAuthBundle(defaultConfigDir(), &bundle); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to export auth bundle: %v", err))
}
@@ -771,7 +676,7 @@ func newAuthExportCommandWithSupport(supportError func() error) *cobra.Command {
_, err := cmd.OutOrStdout().Write(payload)
return err
}
if err := authAtomicWrite(output, payload, config.FilePerm); err != nil {
if err := helpers.AtomicWrite(output, payload, config.FilePerm); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to write auth bundle: %v", err))
}
fmt.Fprintf(cmd.OutOrStdout(), "[OK] 已导出认证包: %s\n", output)
@@ -779,7 +684,7 @@ func newAuthExportCommandWithSupport(supportError func() error) *cobra.Command {
return nil
}
if err := authAtomicWrite(output, bundle.Bytes(), config.FilePerm); err != nil {
if err := helpers.AtomicWrite(output, bundle.Bytes(), config.FilePerm); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to write auth bundle: %v", err))
}
fmt.Fprintf(cmd.OutOrStdout(), "[OK] 已导出认证包: %s\n", output)
@@ -793,10 +698,6 @@ func newAuthExportCommandWithSupport(supportError func() error) *cobra.Command {
}
func newAuthImportCommand() *cobra.Command {
return newAuthImportCommandWithSupport(authpkg.PortableImportSupportError)
}
func newAuthImportCommandWithSupport(supportError func() error) *cobra.Command {
cmd := &cobra.Command{
Use: "import",
Short: "导入可迁移认证包",
@@ -825,15 +726,13 @@ func newAuthImportCommandWithSupport(supportError func() error) *cobra.Command {
if err != nil {
return apperrors.NewInternal("failed to read --force")
}
if err := supportError(); err != nil {
return apperrors.NewValidation(err.Error())
}
configDir := defaultConfigDir()
if !force && authPortableTargetPopulated(configDir) {
if !force && authpkg.PortableAuthTargetPopulated(configDir) {
return apperrors.NewValidation("检测到已有登录态,请使用 --force 确认覆盖")
}
payload, err := authReadFile(input)
payload, err := os.ReadFile(input)
if err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to read auth bundle: %v", err))
}
@@ -843,7 +742,7 @@ func newAuthImportCommandWithSupport(supportError func() error) *cobra.Command {
return apperrors.NewValidation(fmt.Sprintf("invalid base64 auth bundle: %v", err))
}
}
report, err := authImportPortableBundle(configDir, bytes.NewReader(payload))
report, err := authpkg.ImportPortableAuthBundle(configDir, bytes.NewReader(payload))
if err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to import auth bundle: %v", err))
}
@@ -863,7 +762,7 @@ func newAuthImportCommandWithSupport(supportError func() error) *cobra.Command {
return cmd
}
func newAuthExchangeCommand(caller edition.ToolCaller) *cobra.Command {
func newAuthExchangeCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "exchange",
Short: "Exchange an authorization code for credentials",
@@ -885,13 +784,10 @@ func newAuthExchangeCommand(caller edition.ToolCaller) *cobra.Command {
configDir := defaultConfigDir()
provider := authpkg.NewOAuthProvider(configDir, nil)
provider.IdentityEnricher = func(ctx context.Context, data *authpkg.TokenData) error {
return enrichAuthLoginProfileFromContact(ctx, configDir, caller, data)
}
configureOAuthProviderCompatibility(provider, configDir)
exchangeCtx, cancel := context.WithTimeout(cmd.Context(), time.Minute)
defer cancel()
tokenData, err := authOAuthExchange(provider, exchangeCtx, code, strings.TrimSpace(uid))
tokenData, err := provider.ExchangeAuthCode(exchangeCtx, code, strings.TrimSpace(uid))
if err != nil {
return apperrors.NewAuth(fmt.Sprintf("failed to exchange authorization code: %v", err))
}
@@ -930,12 +826,12 @@ func newAuthResetCommand() *cobra.Command {
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
configDir := defaultConfigDir()
if err := authDeleteAllTokenData(configDir); err != nil {
if err := authpkg.DeleteAllTokenData(configDir); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to reset token data: %v", err))
}
_ = authRemove(filepath.Join(configDir, "mcp_url"))
_ = authRemove(filepath.Join(configDir, "token"))
_ = authDeleteAppConfig(configDir)
_ = os.Remove(filepath.Join(configDir, "mcp_url"))
_ = os.Remove(filepath.Join(configDir, "token"))
_ = authpkg.DeleteAppConfig(configDir)
ResetRuntimeTokenCache()
clearCompatCache()
w := cmd.OutOrStdout()
@@ -1011,22 +907,20 @@ func selectLoginRecommendProducts(products []pat.LoginRecommendProduct) ([]strin
Options(options...).
Height(height).
Value(&selected).
Validate(authLoginProductsNonEmpty),
Validate(func(values []string) error {
if len(values) == 0 {
return fmt.Errorf("至少选择一个授权业务域")
}
return nil
}),
),
).WithTheme(authLoginHuhTheme())
if err := authRunForm(form); err != nil {
if err := form.Run(); err != nil {
return nil, fmt.Errorf("授权业务域选择中止: %w", err)
}
return selected, nil
}
func authLoginProductsNonEmpty(values []string) error {
if len(values) == 0 {
return fmt.Errorf("至少选择一个授权业务域")
}
return nil
}
func authLoginHuhTheme() *huh.Theme {
t := huh.ThemeBase()
@@ -1210,19 +1104,6 @@ func resolveAuthLoginConfig(cmd *cobra.Command) (authLoginConfig, error) {
if err != nil {
return authLoginConfig{}, err
}
flow := "oauth"
if strings.TrimSpace(token) != "" {
flow = "token"
} else if device {
flow = "device"
}
logging.AuthDebug(
"auth.login.request",
"flow", flow,
"profile_selector", strings.TrimSpace(profileSelector),
"target_corp_id", targetCorpID,
"recommend", recommend,
)
return authLoginConfig{
Token: strings.TrimSpace(token),
Force: force,
@@ -1242,7 +1123,7 @@ func resolveAuthLoginTargetCorpID(configDir, selector string) (string, error) {
if selector == "" {
return "", nil
}
if profile, err := authResolveProfile(configDir, selector); err == nil && profile != nil {
if profile, err := authpkg.ResolveProfile(configDir, selector); err == nil && profile != nil {
return strings.TrimSpace(profile.CorpID), nil
}
if strings.HasPrefix(selector, "ding") {
@@ -1258,11 +1139,7 @@ type contactProfileIdentity struct {
UserName string
}
type tokenOverrideToolCaller interface {
CallToolWithToken(ctx context.Context, token, productID, toolName string, args map[string]any) (*edition.ToolResult, error)
}
func enrichAuthLoginProfileFromContact(ctx context.Context, _ string, caller edition.ToolCaller, data *authpkg.TokenData) error {
func enrichAuthLoginProfileFromContact(ctx context.Context, configDir string, caller edition.ToolCaller, data *authpkg.TokenData) error {
if caller == nil || data == nil {
return nil
}
@@ -1270,62 +1147,24 @@ func enrichAuthLoginProfileFromContact(ctx context.Context, _ string, caller edi
if corpID == "" {
return nil
}
logging.AuthDebug(
"auth.login.identity.lookup.start",
"corp_id", corpID,
"user_id", strings.TrimSpace(data.UserID),
"user_name", strings.TrimSpace(data.UserName),
"corp_name", strings.TrimSpace(data.CorpName),
)
if strings.TrimSpace(data.CorpName) != "" && strings.TrimSpace(data.UserID) != "" && strings.TrimSpace(data.UserName) != "" {
logging.AuthDebug(
"auth.login.identity.lookup.result",
"source", "token_exchange",
"corp_id", corpID,
"user_id", strings.TrimSpace(data.UserID),
"user_name", strings.TrimSpace(data.UserName),
"corp_name", strings.TrimSpace(data.CorpName),
)
return nil
}
var (
result *edition.ToolResult
err error
)
if tokenCaller, ok := caller.(tokenOverrideToolCaller); ok && strings.TrimSpace(data.AccessToken) != "" {
result, err = tokenCaller.CallToolWithToken(ctx, data.AccessToken, "contact", "get_current_user_profile", nil)
} else {
if strings.TrimSpace(data.UserID) == "" {
return fmt.Errorf("login identity lookup requires an in-memory token override")
}
return nil
}
restoreProfile := pushRuntimeProfile(corpID)
defer restoreProfile()
ResetRuntimeTokenCache()
result, err := caller.CallTool(ctx, "contact", "get_current_user_profile", map[string]any{
"profile": corpID,
})
if err != nil {
logging.AuthDebug(
"auth.login.identity.lookup.error",
"corp_id", corpID,
"existing_user_id", strings.TrimSpace(data.UserID),
"error", err,
)
if strings.TrimSpace(data.UserID) != "" {
return nil
}
return err
}
identity, ok := contactProfileIdentityFromToolResult(result)
if !ok {
logging.AuthDebug("auth.login.identity.lookup.empty", "corp_id", corpID)
return nil
}
logging.AuthDebug(
"auth.login.identity.lookup.result",
"source", "contact.get_current_user_profile",
"corp_id", strings.TrimSpace(identity.CorpID),
"user_id", strings.TrimSpace(identity.UserID),
"user_name", strings.TrimSpace(identity.UserName),
"corp_name", strings.TrimSpace(identity.CorpName),
)
if identity.CorpID != "" && identity.CorpID != corpID {
return fmt.Errorf("contact profile corpId %q does not match login corpId %q", identity.CorpID, corpID)
}
@@ -1341,23 +1180,12 @@ func enrichAuthLoginProfileFromContact(ctx context.Context, _ string, caller edi
updated.UserName = identity.UserName
}
if updated.CorpName == data.CorpName && updated.UserID == data.UserID && updated.UserName == data.UserName {
logging.AuthDebug(
"auth.login.identity.resolved",
"corp_id", corpID,
"user_id", strings.TrimSpace(data.UserID),
"user_name", strings.TrimSpace(data.UserName),
"changed", false,
)
return nil
}
if err := authpkg.SaveTokenData(configDir, &updated); err != nil {
return err
}
*data = updated
logging.AuthDebug(
"auth.login.identity.resolved",
"corp_id", strings.TrimSpace(data.CorpID),
"user_id", strings.TrimSpace(data.UserID),
"user_name", strings.TrimSpace(data.UserName),
"changed", true,
)
return nil
}
@@ -1384,7 +1212,6 @@ func contactProfileIdentityFromJSON(data []byte) (contactProfileIdentity, bool)
OrgName string `json:"orgName"`
UserID string `json:"userId"`
UserIDLower string `json:"userid"`
OrgUserID string `json:"orgUserId"`
OrgUserName string `json:"orgUserName"`
Name string `json:"name"`
} `json:"orgEmployeeModel"`
@@ -1400,7 +1227,7 @@ func contactProfileIdentityFromJSON(data []byte) (contactProfileIdentity, bool)
identity := contactProfileIdentity{
CorpID: strings.TrimSpace(org.CorpID),
CorpName: strings.TrimSpace(org.OrgName),
UserID: firstNonEmptyString(org.UserID, org.UserIDLower, org.OrgUserID),
UserID: firstNonEmptyString(org.UserID, org.UserIDLower),
UserName: firstNonEmptyString(org.OrgUserName, org.Name),
}
return identity, identity.CorpID != "" || identity.CorpName != "" || identity.UserID != "" || identity.UserName != ""
@@ -1487,17 +1314,6 @@ func authStatusDiagnosticFromError(err error) *authStatusDiagnostic {
}
}
func authStatusRefreshDiagnostic(err error) *authStatusDiagnostic {
if err == nil {
return nil
}
return &authStatusDiagnostic{
Reason: "token_refresh_failed",
Message: fmt.Sprintf("Token 刷新失败: %v", err),
Hint: "请重新运行 dws auth login 完成授权。",
}
}
func writeAuthStatusJSON(w io.Writer, authenticated, refreshed bool, data *authpkg.TokenData, diagnostic *authStatusDiagnostic) error {
resp := authStatusResponse{
Success: true,
@@ -1,841 +0,0 @@
package app
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"testing"
"time"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/keychain"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/pat"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/charmbracelet/huh"
"github.com/spf13/cobra"
)
type authCoverageCaller struct {
result *edition.ToolResult
err error
}
func (c *authCoverageCaller) CallTool(context.Context, string, string, map[string]any) (*edition.ToolResult, error) {
return c.result, c.err
}
func (c *authCoverageCaller) CallToolWithToken(ctx context.Context, _ string, productID, toolName string, args map[string]any) (*edition.ToolResult, error) {
return c.CallTool(ctx, productID, toolName, args)
}
func (*authCoverageCaller) Format() string { return "json" }
func (*authCoverageCaller) DryRun() bool { return false }
func (*authCoverageCaller) Fields() string { return "" }
func (*authCoverageCaller) JQ() string { return "" }
func authCoverageRoot(child *cobra.Command, format string, yes bool) (*cobra.Command, *bytes.Buffer, *bytes.Buffer) {
root := &cobra.Command{Use: "dws"}
root.SetContext(context.Background())
child.SetContext(context.Background())
root.PersistentFlags().String("format", format, "")
root.PersistentFlags().Bool("yes", yes, "")
root.PersistentFlags().String("profile", "", "")
root.AddCommand(child)
out := &bytes.Buffer{}
errOut := &bytes.Buffer{}
root.SetOut(out)
root.SetErr(errOut)
return root, out, errOut
}
func authCoverageRunLogin(t *testing.T, caller edition.ToolCaller, format string, yes bool, flags map[string]string) (string, string, error) {
t.Helper()
cmd := newAuthLoginCommand(caller)
root, out, errOut := authCoverageRoot(cmd, format, yes)
for name, value := range flags {
flagSet := cmd.Flags()
if root.PersistentFlags().Lookup(name) != nil {
flagSet = root.PersistentFlags()
}
if err := flagSet.Set(name, value); err != nil {
t.Fatalf("set %s: %v", name, err)
}
}
err := cmd.RunE(cmd, nil)
return out.String(), errOut.String(), err
}
func TestCrossPlatformCoverageAuthCoverageFormsParentAndTargets(t *testing.T) {
oldEdition := edition.Get()
oldClientID := authpkg.ClientID()
oldClientSecret := authpkg.ClientSecret()
oldRunForm := authRunForm
oldPrompt := authLoginManualCredentialsPrompt
oldSaveConfig := authSaveAppConfig
oldResolve := authResolveProfile
t.Cleanup(func() {
edition.Override(oldEdition)
authpkg.SetClientID(oldClientID)
authpkg.SetClientSecret(oldClientSecret)
authRunForm = oldRunForm
authLoginManualCredentialsPrompt = oldPrompt
authSaveAppConfig = oldSaveConfig
authResolveProfile = oldResolve
})
edition.Override(&edition.Hooks{})
parent := buildAuthCommand(nil)
if parent.CommandPath() == "" || parent.RunE(parent, nil) != nil {
t.Fatal("auth parent should render help")
}
edition.Override(&edition.Hooks{HideAuthLogin: true})
if got := buildAuthCommand(nil).Commands(); len(got) != 7 {
t.Fatalf("hidden-login subcommands = %d, want 7", len(got))
}
authRunForm = func(*huh.Form) error { return nil }
if choice, err := selectAuthLoginGuideAction(); err != nil || choice != authLoginGuideDirectCLI {
t.Fatalf("guide choice = %q, %v", choice, err)
}
if id, secret, err := promptAuthLoginManualCredentials(); err != nil || id != "" || secret != "" {
t.Fatalf("manual prompt = %q/%q, %v", id, secret, err)
}
if mode, err := selectLoginRecommendScopeMode(); err != nil || mode != pat.LoginRecommendScopeRecommended {
t.Fatalf("scope mode = %q, %v", mode, err)
}
products := []pat.LoginRecommendProduct{{ProductCode: "doc"}, {ProductCode: ""}}
if selected, err := selectLoginRecommendProducts(products); err != nil || len(selected) != 1 || selected[0] != "doc" {
t.Fatalf("selected products = %#v, %v", selected, err)
}
if selected, err := selectLoginRecommendProducts(nil); err != nil || selected != nil {
t.Fatalf("empty selected products = %#v, %v", selected, err)
}
if selected, err := selectLoginRecommendProducts([]pat.LoginRecommendProduct{{}}); err != nil || selected != nil {
t.Fatalf("blank selected products = %#v, %v", selected, err)
}
many := make([]pat.LoginRecommendProduct, 16)
for i := range many {
many[i].ProductCode = fmt.Sprintf("p%d", i)
}
if selected, err := selectLoginRecommendProducts(many); err != nil || len(selected) != 16 {
t.Fatalf("many selected products = %d, %v", len(selected), err)
}
if authLoginProductsNonEmpty(nil) == nil || authLoginProductsNonEmpty([]string{"doc"}) != nil {
t.Fatal("product validator mismatch")
}
authRunForm = func(*huh.Form) error { return errors.New("cancel") }
if _, err := selectAuthLoginGuideAction(); err == nil {
t.Fatal("guide cancellation should fail")
}
if _, _, err := promptAuthLoginManualCredentials(); err == nil {
t.Fatal("credential cancellation should fail")
}
if _, err := selectLoginRecommendScopeMode(); err == nil {
t.Fatal("scope cancellation should fail")
}
if _, err := selectLoginRecommendProducts(products); err == nil {
t.Fatal("product cancellation should fail")
}
if authLoginNonEmpty("field")(" ") == nil || authLoginNonEmpty("field")("value") != nil {
t.Fatal("non-empty validator mismatch")
}
cmd := &cobra.Command{}
cmd.SetErr(io.Discard)
if err := applyAuthLoginGuideAction(cmd, t.TempDir(), authLoginGuideDirectCLI); err != nil {
t.Fatal(err)
}
if err := applyAuthLoginGuideAction(cmd, t.TempDir(), authLoginGuideConfigureAgentApp); err != nil {
t.Fatal(err)
}
if err := applyAuthLoginGuideAction(cmd, t.TempDir(), "unknown"); err == nil {
t.Fatal("unknown guide action should fail")
}
authLoginManualCredentialsPrompt = func() (string, string, error) { return "", "", errors.New("cancel") }
if err := applyAuthLoginGuideAction(cmd, t.TempDir(), authLoginGuideManualCredentials); err == nil {
t.Fatal("manual prompt error should propagate")
}
authLoginManualCredentialsPrompt = func() (string, string, error) { return "id", "secret", nil }
authSaveAppConfig = func(string, *authpkg.AppConfig) error { return errors.New("save") }
if err := applyAuthLoginGuideAction(cmd, t.TempDir(), authLoginGuideManualCredentials); err == nil {
t.Fatal("app-config save error should propagate")
}
authSaveAppConfig = func(string, *authpkg.AppConfig) error { return nil }
if err := applyAuthLoginGuideAction(cmd, t.TempDir(), authLoginGuideManualCredentials); err != nil {
t.Fatal(err)
}
authResolveProfile = func(string, string) (*authpkg.Profile, error) {
return &authpkg.Profile{CorpID: " ding-profile "}, nil
}
if got, err := resolveAuthLoginTargetCorpID("cfg", "name"); err != nil || got != "ding-profile" {
t.Fatalf("resolved target = %q, %v", got, err)
}
authResolveProfile = func(string, string) (*authpkg.Profile, error) { return nil, errors.New("missing") }
for selector, want := range map[string]struct {
value string
err bool
}{"": {"", false}, "ding-direct": {"ding-direct", false}, "other": {"", true}} {
got, err := resolveAuthLoginTargetCorpID("cfg", selector)
if got != want.value || (err != nil) != want.err {
t.Fatalf("target %q = %q, %v", selector, got, err)
}
}
badToken := &cobra.Command{}
badToken.Flags().Bool("token", false, "")
if _, err := resolveAuthLoginConfig(badToken); err == nil {
t.Fatal("invalid token flag should fail")
}
badDevice := &cobra.Command{}
badDevice.Flags().String("token", "", "")
badDevice.Flags().String("device", "", "")
if _, err := resolveAuthLoginConfig(badDevice); err == nil {
t.Fatal("invalid device flag should fail")
}
badForce := &cobra.Command{}
badForce.Flags().String("token", "", "")
badForce.Flags().Bool("device", false, "")
badForce.Flags().String("force", "", "")
if _, err := resolveAuthLoginConfig(badForce); err == nil {
t.Fatal("invalid force flag should fail")
}
badRecommend := &cobra.Command{}
badRecommend.Flags().String("token", "", "")
badRecommend.Flags().Bool("device", false, "")
badRecommend.Flags().Bool("force", false, "")
badRecommend.Flags().String("recommend", "", "")
if _, err := resolveAuthLoginConfig(badRecommend); err == nil {
t.Fatal("invalid recommend flag should fail")
}
}
func TestCrossPlatformCoverageAuthCoverageLoginFlows(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
oldSave := authSaveTokenData
oldDevice := authDeviceLogin
oldOAuth := authOAuthLogin
oldRunRecommend := authRunLoginRecommend
oldRunWait := authRunDirectPATWait
oldPlan := authPlanLoginRecommend
oldScope := loginRecommendScopeModeSelector
oldProducts := loginRecommendProductSelector
oldInteractive := authLoginInteractiveTerminal
oldResolve := authResolveProfile
t.Cleanup(func() {
authSaveTokenData = oldSave
authDeviceLogin = oldDevice
authOAuthLogin = oldOAuth
authRunLoginRecommend = oldRunRecommend
authRunDirectPATWait = oldRunWait
authPlanLoginRecommend = oldPlan
loginRecommendScopeModeSelector = oldScope
loginRecommendProductSelector = oldProducts
authLoginInteractiveTerminal = oldInteractive
authResolveProfile = oldResolve
})
authInteractiveFalse := func() bool { return false }
authLoginInteractiveTerminal = authInteractiveFalse
authResolveProfile = func(string, string) (*authpkg.Profile, error) { return nil, errors.New("missing") }
if _, _, err := authCoverageRunLogin(t, nil, "table", true, map[string]string{"profile": "bad"}); err == nil {
t.Fatal("invalid login profile should fail")
}
authSaveTokenData = func(string, *authpkg.TokenData) error { return errors.New("save") }
if _, _, err := authCoverageRunLogin(t, nil, "table", true, map[string]string{"token": "token"}); err == nil {
t.Fatal("token save should fail")
}
authSaveTokenData = func(string, *authpkg.TokenData) error { return nil }
if out, _, err := authCoverageRunLogin(t, nil, "table", true, map[string]string{"token": " token "}); err != nil || !strings.Contains(out, "登录成功") {
t.Fatalf("token login = %q, %v", out, err)
}
if out, _, err := authCoverageRunLogin(t, nil, "json", true, map[string]string{"token": "token"}); err != nil || !strings.Contains(out, `"token_valid": true`) {
t.Fatalf("json token login = %q, %v", out, err)
}
authDeviceLogin = func(*authpkg.DeviceFlowProvider, context.Context) (*authpkg.TokenData, error) {
return nil, errors.New("device")
}
if _, _, err := authCoverageRunLogin(t, nil, "table", true, map[string]string{"device": "true"}); err == nil {
t.Fatal("device error should propagate")
}
authDeviceLogin = func(*authpkg.DeviceFlowProvider, context.Context) (*authpkg.TokenData, error) {
return &authpkg.TokenData{AccessToken: "a", ExpiresAt: time.Now().Add(time.Hour)}, nil
}
if _, _, err := authCoverageRunLogin(t, nil, "table", true, map[string]string{"device": "true", "no-browser": "true"}); err != nil {
t.Fatal(err)
}
authOAuthLogin = func(*authpkg.OAuthProvider, context.Context, bool) (*authpkg.TokenData, error) {
return nil, errors.New("oauth")
}
if _, _, err := authCoverageRunLogin(t, nil, "table", true, nil); err == nil {
t.Fatal("oauth error should propagate")
}
authOAuthLogin = func(*authpkg.OAuthProvider, context.Context, bool) (*authpkg.TokenData, error) {
return &authpkg.TokenData{
AccessToken: "a", ExpiresAt: time.Now().Add(time.Hour), RefreshToken: "r", RefreshExpAt: time.Now().Add(48 * time.Hour),
CorpName: "Corp", CorpID: "ding1", UserName: "User", UserID: "u",
}, nil
}
caller := &authCoverageCaller{result: &edition.ToolResult{Content: []edition.ContentBlock{{Text: `{}`}}}}
if out, _, err := authCoverageRunLogin(t, caller, "table", true, map[string]string{"no-browser": "true"}); err != nil || !strings.Contains(out, "Corp") {
t.Fatalf("oauth success = %q, %v", out, err)
}
authRunLoginRecommend = func(context.Context, edition.ToolCaller, io.Writer, pat.LoginRecommendOptions) error {
return errors.New("recommend")
}
if _, _, err := authCoverageRunLogin(t, nil, "table", true, map[string]string{"token": "x", "recommend": "true"}); err == nil {
t.Fatal("recommend error should propagate")
}
if _, _, err := authCoverageRunLogin(t, nil, "json", true, map[string]string{"token": "x", "recommend": "true"}); err == nil {
t.Fatal("JSON recommend error should propagate")
}
authRunLoginRecommend = func(context.Context, edition.ToolCaller, io.Writer, pat.LoginRecommendOptions) error {
return &apperrors.PATError{RawJSON: `{"code":"PAT_SCOPE_AUTH_REQUIRED"}`}
}
waited := false
authRunDirectPATWait = func(context.Context, *GlobalFlags, *apperrors.PATError, io.Writer) error {
waited = true
return nil
}
if _, _, err := authCoverageRunLogin(t, nil, "json", true, map[string]string{"token": "x", "recommend": "true"}); err != nil || !waited {
t.Fatalf("PAT wait = %v, waited=%v", err, waited)
}
authLoginInteractiveTerminal = func() bool { return true }
authPlanLoginRecommend = func(context.Context, edition.ToolCaller) (*pat.LoginRecommendPlan, error) {
return nil, errors.New("plan")
}
if _, _, err := authCoverageRunLogin(t, nil, "table", false, map[string]string{"token": "x"}); err == nil {
t.Fatal("plan error should propagate")
}
authPlanLoginRecommend = func(context.Context, edition.ToolCaller) (*pat.LoginRecommendPlan, error) {
return &pat.LoginRecommendPlan{AllGranted: true}, nil
}
if _, stderr, err := authCoverageRunLogin(t, nil, "table", false, map[string]string{"token": "x"}); err != nil || !strings.Contains(stderr, "全部授权") {
t.Fatalf("all-granted plan = %q, %v", stderr, err)
}
authPlanLoginRecommend = func(context.Context, edition.ToolCaller) (*pat.LoginRecommendPlan, error) {
return &pat.LoginRecommendPlan{Scopes: []string{"scope"}, Products: []pat.LoginRecommendProduct{{ProductCode: "doc"}}}, nil
}
loginRecommendScopeModeSelector = func() (pat.LoginRecommendScopeMode, error) { return "", errors.New("scope") }
if _, _, err := authCoverageRunLogin(t, nil, "table", false, map[string]string{"token": "x"}); err == nil {
t.Fatal("scope selector error should propagate")
}
loginRecommendScopeModeSelector = func() (pat.LoginRecommendScopeMode, error) { return pat.LoginRecommendScopeAll, nil }
loginRecommendProductSelector = func([]pat.LoginRecommendProduct) ([]string, error) { return []string{"doc"}, nil }
selected := false
authRunLoginRecommend = func(_ context.Context, _ edition.ToolCaller, _ io.Writer, opts pat.LoginRecommendOptions) error {
if opts.ProductSelector != nil {
_, err := opts.ProductSelector(opts.InitialPlan.Products)
selected = err == nil
}
return nil
}
if _, _, err := authCoverageRunLogin(t, nil, "table", false, map[string]string{"token": "x"}); err != nil || !selected {
t.Fatalf("interactive recommendation = %v, selected=%v", err, selected)
}
}
func TestCrossPlatformCoverageAuthCoverageContactEnrichment(t *testing.T) {
oldSave := authSaveTokenData
t.Cleanup(func() { authSaveTokenData = oldSave })
ctx := context.Background()
if err := enrichAuthLoginProfileFromContact(ctx, "cfg", nil, nil); err != nil {
t.Fatal(err)
}
if err := enrichAuthLoginProfileFromContact(ctx, "cfg", &authCoverageCaller{}, &authpkg.TokenData{}); err != nil {
t.Fatal(err)
}
complete := &authpkg.TokenData{CorpID: "ding", CorpName: "Corp", UserID: "u", UserName: "User"}
if err := enrichAuthLoginProfileFromContact(ctx, "cfg", &authCoverageCaller{}, complete); err != nil {
t.Fatal(err)
}
if err := enrichAuthLoginProfileFromContact(ctx, "cfg", &authCoverageCaller{err: errors.New("call")}, &authpkg.TokenData{CorpID: "ding"}); err == nil {
t.Fatal("caller error should propagate")
}
if err := enrichAuthLoginProfileFromContact(
ctx,
"cfg",
&authCoverageCaller{err: errors.New("call")},
&authpkg.TokenData{CorpID: "ding", UserID: "known", AccessToken: "token"},
); err != nil {
t.Fatalf("optional contact metadata failure with known userId = %v", err)
}
for _, text := range []string{"", "not-json", `{"result":[]}`, `{"result":[{"orgEmployeeModel":{}}]}`} {
caller := &authCoverageCaller{result: &edition.ToolResult{Content: []edition.ContentBlock{{Text: text}}}}
if err := enrichAuthLoginProfileFromContact(ctx, "cfg", caller, &authpkg.TokenData{CorpID: "ding", AccessToken: "token"}); err != nil {
t.Fatalf("invalid contact %q: %v", text, err)
}
}
mismatch := &authCoverageCaller{result: &edition.ToolResult{Content: []edition.ContentBlock{{Text: `{"result":[{"orgEmployeeModel":{"corpId":"other"}}]}`}}}}
if err := enrichAuthLoginProfileFromContact(ctx, "cfg", mismatch, &authpkg.TokenData{CorpID: "ding", AccessToken: "token"}); err == nil {
t.Fatal("corp mismatch should fail")
}
same := &authCoverageCaller{result: &edition.ToolResult{Content: []edition.ContentBlock{{Text: `{"result":[{"orgEmployeeModel":{"corpId":"ding","orgName":"Corp","userid":"u","name":"User"}}]}`}}}}
if err := enrichAuthLoginProfileFromContact(ctx, "cfg", same, complete); err != nil {
t.Fatal(err)
}
unchangedPartial := &authCoverageCaller{result: &edition.ToolResult{Content: []edition.ContentBlock{{Text: `{"result":[{"orgEmployeeModel":{"corpId":"ding","orgName":"Corp","userid":"u"}}]}`}}}}
if err := enrichAuthLoginProfileFromContact(ctx, "cfg", unchangedPartial, &authpkg.TokenData{CorpID: "ding", CorpName: "Corp", UserID: "u"}); err != nil {
t.Fatal(err)
}
authSaveTokenData = func(string, *authpkg.TokenData) error { return errors.New("save") }
data := &authpkg.TokenData{CorpID: "ding", AccessToken: "token"}
if err := enrichAuthLoginProfileFromContact(ctx, "cfg", same, data); err != nil || data.CorpName != "Corp" || data.UserID != "u" {
t.Fatalf("enriched = %#v, %v", data, err)
}
if _, ok := contactProfileIdentityFromToolResult(nil); ok {
t.Fatal("nil result should not parse")
}
if got := firstNonEmptyString(" ", " value ", "later"); got != "value" {
t.Fatalf("first non-empty = %q", got)
}
}
func TestCrossPlatformCoverageAuthCoverageDefaultSeamClosures(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
configDir := t.TempDir()
device := authpkg.NewDeviceFlowProvider(configDir, nil)
_, _ = authDeviceLogin(device, ctx)
oauth := authpkg.NewOAuthProvider(configDir, nil)
oauth.NoBrowser = true
_, _ = authOAuthStatus(oauth)
_, _ = authOAuthAccessToken(oauth, ctx)
_, _ = authOAuthLogin(oauth, ctx, true)
_, _ = authOAuthExchange(oauth, ctx, "code", "uid")
_ = fmt.Sprintf("%v", os.ErrNotExist)
}
func TestCrossPlatformCoverageAuthCoverageStatusAndLogout(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
oldEdition := edition.Get()
oldStatus := authOAuthStatus
oldAccess := authOAuthAccessToken
oldDelete := authDeleteTokenData
oldMark := authMarkProfileStatus
oldResolve := authResolveProfile
oldResolveDeletion := authResolveProfileDeletion
oldRevoke := authRevokeToken
oldRevokeForData := authRevokeTokenForData
oldLoadTokenForProfile := authLoadTokenForProfile
oldDeleteProfile := authDeleteProfileToken
oldMigrate := authEnsureProfilesMigration
oldLoadProfiles := authLoadProfiles
oldDeleteAll := authDeleteAllTokenData
t.Cleanup(func() {
edition.Override(oldEdition)
authOAuthStatus = oldStatus
authOAuthAccessToken = oldAccess
authDeleteTokenData = oldDelete
authMarkProfileStatus = oldMark
authResolveProfile = oldResolve
authResolveProfileDeletion = oldResolveDeletion
authRevokeToken = oldRevoke
authRevokeTokenForData = oldRevokeForData
authLoadTokenForProfile = oldLoadTokenForProfile
authDeleteProfileToken = oldDeleteProfile
authEnsureProfilesMigration = oldMigrate
authLoadProfiles = oldLoadProfiles
authDeleteAllTokenData = oldDeleteAll
})
badStatus := newAuthStatusCommand()
bad := &cobra.Command{}
bad.Flags().Bool("profile", false, "")
if err := badStatus.RunE(bad, nil); err == nil {
t.Fatal("invalid profile flag should fail")
}
runStatus := func(format string) (string, error) {
cmd := newAuthStatusCommand()
_, out, _ := authCoverageRoot(cmd, format, false)
err := cmd.RunE(cmd, nil)
return out.String(), err
}
authOAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) { return nil, nil }
edition.Override(&edition.Hooks{})
if out, err := runStatus("table"); err != nil || !strings.Contains(out, "auth login") {
t.Fatalf("plain unauthenticated status = %q, %v", out, err)
}
authOAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) {
return nil, keychain.NewUnavailableError("read", errors.New("status"))
}
edition.Override(&edition.Hooks{})
if out, err := runStatus("table"); err != nil || !strings.Contains(out, "未登录") {
t.Fatalf("status error = %q, %v", out, err)
}
if out, err := runStatus("json"); err != nil || !strings.Contains(out, `"authenticated": false`) {
t.Fatalf("json status error = %q, %v", out, err)
}
now := time.Now()
valid := &authpkg.TokenData{AccessToken: "a", ExpiresAt: now.Add(time.Hour), CorpID: "ding", CorpName: "Corp"}
authOAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) { return valid, nil }
if out, err := runStatus("table"); err != nil || !strings.Contains(out, "已登录") || !strings.Contains(out, "缺失或已过期") {
t.Fatalf("valid access status = %q, %v", out, err)
}
valid.RefreshToken = "r"
valid.RefreshExpAt = now.Add(time.Hour)
if out, err := runStatus("table"); err != nil || !strings.Contains(out, "Refresh Token:") {
t.Fatalf("valid refresh status = %q, %v", out, err)
}
expired := &authpkg.TokenData{AccessToken: "a", ExpiresAt: now.Add(-time.Hour), RefreshToken: "r", RefreshExpAt: now.Add(time.Hour), CorpID: "ding"}
updated := &authpkg.TokenData{AccessToken: "new", ExpiresAt: now.Add(time.Hour), RefreshToken: "r", RefreshExpAt: now.Add(time.Hour), CorpID: "ding"}
calls := 0
authOAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) {
calls++
if calls == 1 {
return expired, nil
}
return updated, nil
}
authOAuthAccessToken = func(*authpkg.OAuthProvider, context.Context) (string, error) { return "new", nil }
if out, err := runStatus("table"); err != nil || !strings.Contains(out, "自动刷新") {
t.Fatalf("refreshed status = %q, %v", out, err)
}
calls = 0
authOAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) {
calls++
if calls == 1 {
return expired, nil
}
return nil, errors.New("second status")
}
if _, err := runStatus("table"); err != nil {
t.Fatal(err)
}
authOAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) { return expired, nil }
authOAuthAccessToken = func(*authpkg.OAuthProvider, context.Context) (string, error) { return "", errors.New("refresh") }
deleted := false
marked := false
authDeleteTokenData = func(string) error { deleted = true; return errors.New("ignored") }
authMarkProfileStatus = func(string, string, string) error { marked = true; return errors.New("ignored") }
edition.Override(&edition.Hooks{AutoPurgeToken: true})
if _, err := runStatus("table"); err != nil || !deleted {
t.Fatalf("auto-purge = %v, deleted=%v", err, deleted)
}
edition.Override(&edition.Hooks{})
if _, err := runStatus("table"); err != nil || !marked {
t.Fatalf("mark-expired = %v, marked=%v", err, marked)
}
authResolveProfileDeletion = func(string, string) (*authpkg.Profile, bool, error) { return nil, false, errors.New("missing") }
if err := logoutOneProfile(nil, context.Background(), "cfg", "x"); err == nil {
t.Fatal("missing profile should fail")
}
authResolveProfileDeletion = func(string, string) (*authpkg.Profile, bool, error) {
return &authpkg.Profile{CorpID: "ding", UserID: "user"}, true, nil
}
authLoadTokenForProfile = func(string, string) (*authpkg.TokenData, error) {
return &authpkg.TokenData{CorpID: "ding", UserID: "user"}, nil
}
authRevokeTokenForData = func(context.Context, *authpkg.TokenData) error { return errors.New("ignored") }
var deletedSelector string
authDeleteProfileToken = func(_ string, selector string) error {
deletedSelector = selector
return errors.New("delete")
}
if err := logoutOneProfile(nil, context.Background(), "cfg", "x"); err == nil {
t.Fatal("profile delete should fail")
}
if deletedSelector != "ding:user" {
t.Fatalf("exact deletion selector = %q, want stable identity selector", deletedSelector)
}
authDeleteProfileToken = func(_ string, selector string) error {
deletedSelector = selector
return nil
}
if err := logoutOneProfile(nil, context.Background(), "cfg", "x"); err != nil {
t.Fatal(err)
}
if deletedSelector != "ding:user" {
t.Fatalf("exact deletion selector = %q, want stable identity selector", deletedSelector)
}
authResolveProfileDeletion = func(string, string) (*authpkg.Profile, bool, error) {
return &authpkg.Profile{CorpID: "ding", UserID: "user"}, false, nil
}
authLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) {
return &authpkg.ProfilesConfig{Profiles: []authpkg.Profile{{CorpID: "ding", UserID: "user"}}}, nil
}
if err := logoutOneProfile(nil, context.Background(), "cfg", "organization-name"); err != nil {
t.Fatal(err)
}
if deletedSelector != "ding" {
t.Fatalf("organization deletion selector = %q, want stable corpId", deletedSelector)
}
authEnsureProfilesMigration = func(string) error { return errors.New("migrate") }
if err := logoutAllProfiles(nil, context.Background(), "cfg"); err == nil {
t.Fatal("migration should fail")
}
authEnsureProfilesMigration = func(string) error { return nil }
authLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) { return nil, errors.New("load") }
if err := logoutAllProfiles(nil, context.Background(), "cfg"); err == nil {
t.Fatal("load profiles should fail")
}
revokes := 0
authRevokeToken = func(context.Context) error { revokes++; return nil }
authRevokeTokenForData = func(context.Context, *authpkg.TokenData) error { revokes++; return nil }
authLoadTokenForProfile = func(string, string) (*authpkg.TokenData, error) {
return &authpkg.TokenData{AccessToken: "token"}, nil
}
authLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) { return nil, nil }
authDeleteAllTokenData = func(string) error { return nil }
if err := logoutAllProfiles(nil, context.Background(), "cfg"); err != nil || revokes != 1 {
t.Fatalf("empty profiles = %v, revokes=%d", err, revokes)
}
authLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) {
return &authpkg.ProfilesConfig{Profiles: []authpkg.Profile{{CorpID: "a"}, {CorpID: "b"}}}, nil
}
if err := logoutAllProfiles(nil, context.Background(), "cfg"); err != nil || revokes != 3 {
t.Fatalf("profile revokes = %v, revokes=%d", err, revokes)
}
authDeleteAllTokenData = func(string) error { return errors.New("delete all") }
if err := logoutAllProfiles(nil, context.Background(), "cfg"); err == nil {
t.Fatal("delete-all should fail")
}
logoutFailure := newAuthLogoutCommand()
_, _, _ = authCoverageRoot(logoutFailure, "table", false)
if err := logoutFailure.RunE(logoutFailure, nil); err == nil {
t.Fatal("logout-all command failure should propagate")
}
logoutFailure = newAuthLogoutCommand()
_, _, _ = authCoverageRoot(logoutFailure, "table", false)
_ = logoutFailure.Flags().Set("profile", "ding")
authDeleteProfileToken = func(string, string) error { return errors.New("delete") }
if err := logoutFailure.RunE(logoutFailure, nil); err == nil {
t.Fatal("logout-one command failure should propagate")
}
logout := newAuthLogoutCommand()
badLogout := &cobra.Command{}
badLogout.Flags().Bool("profile", false, "")
badLogout.SetContext(context.Background())
if err := logout.RunE(badLogout, nil); err == nil {
t.Fatal("invalid logout profile flag should fail")
}
authDeleteAllTokenData = func(string) error { return nil }
authLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) { return &authpkg.ProfilesConfig{}, nil }
_, out, _ := authCoverageRoot(logout, "table", false)
if err := logout.RunE(logout, nil); err != nil || !strings.Contains(out.String(), "重新登录") {
t.Fatalf("logout = %q, %v", out.String(), err)
}
edition.Override(&edition.Hooks{IsEmbedded: true})
authDeleteProfileToken = func(string, string) error { return nil }
logout = newAuthLogoutCommand()
_, out, _ = authCoverageRoot(logout, "table", false)
if err := logout.Flags().Set("profile", "ding"); err != nil {
t.Fatal(err)
}
if err := logout.RunE(logout, nil); err != nil || strings.Contains(out.String(), "重新登录") {
t.Fatalf("embedded logout = %q, %v", out.String(), err)
}
}
func TestCrossPlatformCoverageAuthCoveragePortableExchangeAndReset(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
oldEdition := edition.Get()
oldSupported := authPortableExportSupported
oldReady := authPortableSourceReady
oldTarget := authPortableTargetPopulated
oldExport := authExportPortableBundle
oldImport := authImportPortableBundle
oldAtomic := authAtomicWrite
oldRead := authReadFile
oldExchange := authOAuthExchange
oldDeleteAll := authDeleteAllTokenData
oldRemove := authRemove
oldDeleteConfig := authDeleteAppConfig
t.Cleanup(func() {
edition.Override(oldEdition)
authPortableExportSupported = oldSupported
authPortableSourceReady = oldReady
authPortableTargetPopulated = oldTarget
authExportPortableBundle = oldExport
authImportPortableBundle = oldImport
authAtomicWrite = oldAtomic
authReadFile = oldRead
authOAuthExchange = oldExchange
authDeleteAllTokenData = oldDeleteAll
authRemove = oldRemove
authDeleteAppConfig = oldDeleteConfig
})
export := newAuthExportCommandWithSupport(func() error { return nil })
badString := &cobra.Command{}
badString.Flags().Bool("output", false, "")
if err := export.RunE(badString, nil); err == nil {
t.Fatal("invalid output flag should fail")
}
badBool := &cobra.Command{}
badBool.Flags().String("output", "x", "")
badBool.Flags().String("base64", "", "")
if err := export.RunE(badBool, nil); err == nil {
t.Fatal("invalid base64 flag should fail")
}
_, _, _ = authCoverageRoot(export, "table", false)
if err := export.RunE(export, nil); err == nil {
t.Fatal("missing export output should fail")
}
authPortableExportSupported = func() bool { return false }
_ = export.Flags().Set("output", "out")
if err := export.RunE(export, nil); err == nil {
t.Fatal("unsupported export should fail")
}
authPortableExportSupported = func() bool { return true }
authPortableSourceReady = func() bool { return false }
if err := export.RunE(export, nil); err == nil {
t.Fatal("unready export should fail")
}
authPortableSourceReady = func() bool { return true }
authExportPortableBundle = func(string, io.Writer) error { return errors.New("export") }
if err := export.RunE(export, nil); err == nil {
t.Fatal("export failure should propagate")
}
authExportPortableBundle = func(_ string, w io.Writer) error { _, _ = io.WriteString(w, "bundle"); return nil }
authAtomicWrite = func(string, []byte, os.FileMode) error { return errors.New("write") }
if err := export.RunE(export, nil); err == nil {
t.Fatal("raw write should fail")
}
authAtomicWrite = func(string, []byte, os.FileMode) error { return nil }
if err := export.RunE(export, nil); err != nil {
t.Fatal(err)
}
export = newAuthExportCommandWithSupport(func() error { return nil })
_, out, _ := authCoverageRoot(export, "table", false)
_ = export.Flags().Set("base64", "true")
export.SetOut(&appFailWriter{err: errors.New("stdout")})
if err := export.RunE(export, nil); err == nil {
t.Fatal("stdout failure should propagate")
}
export.SetOut(out)
_ = export.Flags().Set("output", "encoded")
authAtomicWrite = func(string, []byte, os.FileMode) error { return errors.New("write") }
if err := export.RunE(export, nil); err == nil {
t.Fatal("base64 write should fail")
}
authAtomicWrite = func(string, []byte, os.FileMode) error { return nil }
if err := export.RunE(export, nil); err != nil {
t.Fatal(err)
}
importCmd := newAuthImportCommandWithSupport(func() error { return nil })
badInput := &cobra.Command{}
badInput.Flags().Bool("input", false, "")
if err := importCmd.RunE(badInput, nil); err == nil {
t.Fatal("invalid input flag should fail")
}
badImportBase64 := &cobra.Command{}
badImportBase64.Flags().String("input", "x", "")
badImportBase64.Flags().String("base64", "", "")
if err := importCmd.RunE(badImportBase64, nil); err == nil {
t.Fatal("invalid import base64 flag should fail")
}
badForce := &cobra.Command{}
badForce.Flags().String("input", "x", "")
badForce.Flags().Bool("base64", false, "")
badForce.Flags().String("force", "", "")
if err := importCmd.RunE(badForce, nil); err == nil {
t.Fatal("invalid force flag should fail")
}
_, out, _ = authCoverageRoot(importCmd, "table", false)
if err := importCmd.RunE(importCmd, nil); err == nil {
t.Fatal("missing input should fail")
}
_ = importCmd.Flags().Set("input", "bundle")
authPortableTargetPopulated = func(string) bool { return true }
if err := importCmd.RunE(importCmd, nil); err == nil {
t.Fatal("populated target should require force")
}
authPortableTargetPopulated = func(string) bool { return false }
authReadFile = func(string) ([]byte, error) { return nil, errors.New("read") }
if err := importCmd.RunE(importCmd, nil); err == nil {
t.Fatal("read failure should propagate")
}
authReadFile = func(string) ([]byte, error) { return []byte("%%%"), nil }
_ = importCmd.Flags().Set("base64", "true")
if err := importCmd.RunE(importCmd, nil); err == nil {
t.Fatal("invalid base64 should fail")
}
authReadFile = func(string) ([]byte, error) { return []byte("YnVuZGxl"), nil }
authImportPortableBundle = func(string, io.Reader) (authpkg.PortableImportReport, error) {
return authpkg.PortableImportReport{}, errors.New("import")
}
if err := importCmd.RunE(importCmd, nil); err == nil {
t.Fatal("import failure should propagate")
}
authImportPortableBundle = func(string, io.Reader) (authpkg.PortableImportReport, error) {
return authpkg.PortableImportReport{BundleOS: "other", OSMismatch: true}, nil
}
if err := importCmd.RunE(importCmd, nil); err != nil {
t.Fatal(err)
}
authImportPortableBundle = func(string, io.Reader) (authpkg.PortableImportReport, error) {
return authpkg.PortableImportReport{}, nil
}
if err := importCmd.RunE(importCmd, nil); err != nil {
t.Fatal(err)
}
exchange := newAuthExchangeCommand(nil)
badCode := &cobra.Command{}
badCode.Flags().Bool("code", false, "")
if err := exchange.RunE(badCode, nil); err == nil {
t.Fatal("invalid code flag should fail")
}
badUID := &cobra.Command{}
badUID.Flags().String("code", "code", "")
badUID.Flags().Bool("uid", false, "")
if err := exchange.RunE(badUID, nil); err == nil {
t.Fatal("invalid uid flag should fail")
}
_, out, _ = authCoverageRoot(exchange, "table", false)
if err := exchange.RunE(exchange, nil); err == nil {
t.Fatal("missing code should fail")
}
_ = exchange.Flags().Set("code", "code")
authOAuthExchange = func(*authpkg.OAuthProvider, context.Context, string, string) (*authpkg.TokenData, error) {
return nil, errors.New("exchange")
}
if err := exchange.RunE(exchange, nil); err == nil {
t.Fatal("exchange error should propagate")
}
authOAuthExchange = func(*authpkg.OAuthProvider, context.Context, string, string) (*authpkg.TokenData, error) {
return &authpkg.TokenData{CorpID: "ding", ExpiresAt: time.Now().Add(time.Hour)}, nil
}
_ = exchange.Flags().Set("uid", " user ")
if err := exchange.RunE(exchange, nil); err != nil || !strings.Contains(out.String(), "ding") {
t.Fatalf("exchange = %q, %v", out.String(), err)
}
reset := newAuthResetCommand()
_, out, _ = authCoverageRoot(reset, "table", false)
authDeleteAllTokenData = func(string) error { return errors.New("reset") }
if err := reset.RunE(reset, nil); err == nil {
t.Fatal("reset delete should fail")
}
removed := 0
authDeleteAllTokenData = func(string) error { return nil }
authRemove = func(string) error { removed++; return errors.New("ignored") }
authDeleteAppConfig = func(string) error { removed++; return errors.New("ignored") }
edition.Override(&edition.Hooks{})
if err := reset.RunE(reset, nil); err != nil || removed != 3 || !strings.Contains(out.String(), "重新登录") {
t.Fatalf("reset = %q, %v, removed=%d", out.String(), err, removed)
}
edition.Override(&edition.Hooks{IsEmbedded: true})
reset = newAuthResetCommand()
_, out, _ = authCoverageRoot(reset, "table", false)
if err := reset.RunE(reset, nil); err != nil || strings.Contains(out.String(), "重新登录") {
t.Fatalf("embedded reset = %q, %v", out.String(), err)
}
}
+50 -563
View File
@@ -20,11 +20,9 @@ import (
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
@@ -38,33 +36,29 @@ import (
)
func TestAuthExportImportBase64RoundTrip(t *testing.T) {
originalSupported := authPortableExportSupported
originalReady := authPortableSourceReady
originalExport := authExportPortableBundle
originalTarget := authPortableTargetPopulated
originalImport := authImportPortableBundle
t.Cleanup(func() {
authPortableExportSupported = originalSupported
authPortableSourceReady = originalReady
authExportPortableBundle = originalExport
authPortableTargetPopulated = originalTarget
authImportPortableBundle = originalImport
})
t.Setenv(keychain.DisableKeychainEnv, "1")
sourceKeychain := filepath.Join(t.TempDir(), "source-keychain")
sourceConfig := filepath.Join(t.TempDir(), ".dws")
t.Setenv(keychain.StorageDirEnv, sourceKeychain)
t.Setenv("DWS_CONFIG_DIR", sourceConfig)
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
bundle := []byte("portable-auth-bundle")
authPortableExportSupported = func() bool { return true }
authPortableSourceReady = func() bool { return true }
authExportPortableBundle = func(_ string, w io.Writer) error {
_, err := w.Write(bundle)
return err
original := &authpkg.TokenData{
AccessToken: "access-cli",
RefreshToken: "refresh-cli",
ExpiresAt: time.Now().Add(-time.Hour),
RefreshExpAt: time.Now().Add(24 * time.Hour),
ClientID: "client-cli",
Source: "mcp",
}
if err := authpkg.SaveTokenData(sourceConfig, original); err != nil {
t.Fatalf("SaveTokenData() error = %v", err)
}
exportCmd := newAuthExportCommandWithSupport(func() error { return nil })
exportCmd := NewRootCommand()
var exported bytes.Buffer
exportCmd.SetOut(&exported)
exportCmd.SetErr(&bytes.Buffer{})
exportCmd.SetArgs([]string{"--base64"})
exportCmd.SetArgs([]string{"auth", "export", "--base64"})
if err := exportCmd.Execute(); err != nil {
t.Fatalf("auth export --base64 error = %v", err)
}
@@ -78,245 +72,34 @@ func TestAuthExportImportBase64RoundTrip(t *testing.T) {
t.Fatalf("write input bundle error = %v", err)
}
authPortableTargetPopulated = func(string) bool { return false }
var imported []byte
authImportPortableBundle = func(_ string, r io.Reader) (authpkg.PortableImportReport, error) {
var err error
imported, err = io.ReadAll(r)
return authpkg.PortableImportReport{}, err
}
importCmd := newAuthImportCommandWithSupport(func() error { return nil })
importCmd.SetOut(&bytes.Buffer{})
importCmd.SetErr(&bytes.Buffer{})
importCmd.SetArgs([]string{"--input", inputPath, "--base64"})
if err := importCmd.Execute(); err != nil {
t.Fatalf("auth import --base64 error = %v", err)
}
if !bytes.Equal(imported, bundle) {
t.Fatalf("imported bundle = %q, want %q", imported, bundle)
}
}
func TestCrossPlatformCoverageAuthExportUnsupportedBackendIsValidationError(t *testing.T) {
exportCmd := newAuthExportCommandWithSupport(func() error {
return errors.New("portable auth export is unavailable for the test backend")
})
exportCmd.SetOut(&bytes.Buffer{})
exportCmd.SetErr(&bytes.Buffer{})
exportCmd.SetArgs([]string{"--base64"})
err := exportCmd.Execute()
if err == nil {
t.Fatal("auth export should reject an unsupported credential backend")
}
var appErr *apperrors.Error
if !errors.As(err, &appErr) || appErr.Category != apperrors.CategoryValidation {
t.Fatalf("expected validation error, got %T: %v", err, err)
}
if !strings.Contains(err.Error(), "test backend") {
t.Fatalf("error = %v, want backend-specific reason", err)
}
}
func TestCrossPlatformCoverageAuthExportRejectsWindowsDPAPIBackend(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows DPAPI contract requires a native Windows runner")
}
t.Cleanup(CloseFileLogger)
exportCmd := NewRootCommand()
exportCmd.SetOut(&bytes.Buffer{})
exportCmd.SetErr(&bytes.Buffer{})
exportCmd.SetArgs([]string{"auth", "export", "--base64"})
err := exportCmd.Execute()
if err == nil {
t.Fatal("auth export should reject the Windows DPAPI backend")
}
var appErr *apperrors.Error
if !errors.As(err, &appErr) || appErr.Category != apperrors.CategoryValidation {
t.Fatalf("expected validation error, got %T: %v", err, err)
}
for _, want := range []string{"Windows", "DPAPI", "HKCU"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("error = %v, want substring %q", err, want)
}
}
}
func TestCrossPlatformCoverageAuthImportUnsupportedBackendIsValidationErrorBeforeReadingInput(t *testing.T) {
root := t.TempDir()
configDir := filepath.Join(root, ".dws")
keychainDir := filepath.Join(root, "keychain")
t.Setenv("DWS_CONFIG_DIR", configDir)
t.Setenv(keychain.StorageDirEnv, keychainDir)
importCmd := newAuthImportCommandWithSupport(func() error {
return errors.New("portable auth import is unavailable for the test backend")
})
importCmd.SetOut(&bytes.Buffer{})
importCmd.SetErr(&bytes.Buffer{})
importCmd.SetArgs([]string{"--input", filepath.Join(root, "missing-bundle.tar.gz")})
err := importCmd.Execute()
if err == nil {
t.Fatal("auth import should reject an unsupported credential backend")
}
var appErr *apperrors.Error
if !errors.As(err, &appErr) || appErr.Category != apperrors.CategoryValidation {
t.Fatalf("expected validation error, got %T: %v", err, err)
}
if !strings.Contains(err.Error(), "test backend") {
t.Fatalf("error = %v, want backend-specific reason", err)
}
for _, path := range []string{configDir, keychainDir} {
if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
t.Fatalf("unsupported import touched %s: stat error = %v", path, statErr)
}
}
}
func TestCrossPlatformCoverageAuthImportRejectsWindowsDPAPIBackend(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows DPAPI contract requires a native Windows runner")
}
root := t.TempDir()
// NewRootCommand initializes the normal CLI file logger below configDir.
// Register its cleanup after TempDir so the Windows handle is closed before
// testing removes the temporary directory.
t.Cleanup(CloseFileLogger)
configDir := filepath.Join(root, ".dws")
keychainDir := filepath.Join(root, "keychain")
inputPath := filepath.Join(root, "bundle.tar.gz")
if err := os.WriteFile(inputPath, []byte("the capability guard must run before this input is read"), 0o600); err != nil {
t.Fatalf("write input sentinel error = %v", err)
}
t.Setenv("DWS_CONFIG_DIR", configDir)
t.Setenv(keychain.StorageDirEnv, keychainDir)
targetKeychain := filepath.Join(targetRoot, "target-keychain")
targetConfig := filepath.Join(targetRoot, ".dws")
t.Setenv(keychain.StorageDirEnv, targetKeychain)
t.Setenv("DWS_CONFIG_DIR", targetConfig)
importCmd := NewRootCommand()
importCmd.SetOut(&bytes.Buffer{})
importCmd.SetErr(&bytes.Buffer{})
importCmd.SetArgs([]string{"auth", "import", "--input", inputPath})
err := importCmd.Execute()
if err == nil {
t.Fatal("auth import should reject the Windows DPAPI backend")
}
var appErr *apperrors.Error
if !errors.As(err, &appErr) || appErr.Category != apperrors.CategoryValidation {
t.Fatalf("expected validation error, got %T: %v", err, err)
}
for _, want := range []string{"Windows", "DPAPI", "HKCU"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("error = %v, want substring %q", err, want)
}
}
// The root command may create configDir/logs as part of normal CLI startup.
// The capability guard must still run before any auth state is imported.
for _, path := range []string{
keychainDir,
authpkg.ProfilesPath(configDir),
filepath.Join(configDir, "app.json"),
filepath.Join(configDir, "token.json"),
} {
if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {
t.Fatalf("unsupported Windows import touched %s: stat error = %v", path, statErr)
}
}
}
func TestCrossPlatformCoverageAuthImportRejectsWindowsDPAPIBackendWithPopulatedCredentialBeforeRead(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows DPAPI contract requires a native Windows runner")
importCmd.SetArgs([]string{"auth", "import", "--input", inputPath, "--base64"})
if err := importCmd.Execute(); err != nil {
t.Fatalf("auth import --base64 error = %v", err)
}
previous, previousErr := authpkg.LoadTokenDataKeychain()
if previousErr != nil && !errors.Is(previousErr, authpkg.ErrTokenDataNotFound) {
t.Fatalf("capture existing Windows credential: %v", previousErr)
}
hadPrevious := previousErr == nil
t.Cleanup(func() {
if hadPrevious {
_ = authpkg.SaveTokenDataKeychain(previous)
} else {
_ = authpkg.DeleteTokenDataKeychain()
}
})
want := &authpkg.TokenData{
AccessToken: "windows-existing-access",
RefreshToken: "windows-existing-refresh",
RefreshExpAt: time.Now().Add(24 * time.Hour),
CorpID: "windows-existing-corp",
}
if err := authpkg.SaveTokenDataKeychain(want); err != nil {
t.Fatalf("seed cleanup-scoped Windows DPAPI credential: %v", err)
}
originalTarget := authPortableTargetPopulated
originalRead := authReadFile
targetChecks := 0
bundleReads := 0
authPortableTargetPopulated = func(configDir string) bool {
targetChecks++
return originalTarget(configDir)
}
authReadFile = func(path string) ([]byte, error) {
bundleReads++
return originalRead(path)
}
t.Cleanup(func() {
authPortableTargetPopulated = originalTarget
authReadFile = originalRead
})
root := t.TempDir()
inputPath := filepath.Join(root, "bundle.tar.gz")
if err := os.WriteFile(inputPath, []byte("unsupported Windows import must not read this bundle"), 0o600); err != nil {
t.Fatalf("write bundle sentinel: %v", err)
}
t.Setenv("DWS_CONFIG_DIR", filepath.Join(root, ".dws"))
importCmd := newAuthImportCommand()
importCmd.SetOut(&bytes.Buffer{})
importCmd.SetErr(&bytes.Buffer{})
importCmd.SetArgs([]string{"--input", inputPath})
err := importCmd.Execute()
if err == nil {
t.Fatal("auth import should reject a populated Windows DPAPI backend")
}
var appErr *apperrors.Error
if !errors.As(err, &appErr) || appErr.Category != apperrors.CategoryValidation {
t.Fatalf("expected validation error, got %T: %v", err, err)
}
for _, required := range []string{"Windows", "DPAPI", "HKCU"} {
if !strings.Contains(err.Error(), required) {
t.Fatalf("error = %v, want substring %q", err, required)
}
}
if strings.Contains(err.Error(), "--force") {
t.Fatalf("unsupported Windows import suggested impossible --force remediation: %v", err)
}
if targetChecks != 0 || bundleReads != 0 {
t.Fatalf("unsupported Windows import inspected credentials/bundle: target_checks=%d bundle_reads=%d", targetChecks, bundleReads)
}
got, err := authpkg.LoadTokenDataKeychain()
loaded, err := authpkg.LoadTokenData(targetConfig)
if err != nil {
t.Fatalf("reload Windows DPAPI credential after rejection: %v", err)
t.Fatalf("LoadTokenData() after CLI import error = %v", err)
}
if got.AccessToken != want.AccessToken || got.RefreshToken != want.RefreshToken || got.CorpID != want.CorpID {
t.Fatalf("Windows auth state changed after rejected import: got=%#v want=%#v", got, want)
if loaded.RefreshToken != original.RefreshToken {
t.Fatalf("refresh token = %q, want %q", loaded.RefreshToken, original.RefreshToken)
}
if !loaded.IsRefreshTokenValid() {
t.Fatal("refresh token should remain valid after CLI import")
}
}
func TestCrossPlatformCoverageAuthImportRequiresForceWhenPopulated(t *testing.T) {
func TestAuthImportRequiresForceWhenPopulated(t *testing.T) {
t.Setenv(keychain.DisableKeychainEnv, "1")
root := t.TempDir()
t.Cleanup(CloseFileLogger)
configDir := filepath.Join(root, ".dws")
t.Setenv(keychain.StorageDirEnv, filepath.Join(root, "keychain"))
t.Setenv("DWS_CONFIG_DIR", configDir)
@@ -334,42 +117,11 @@ func TestCrossPlatformCoverageAuthImportRequiresForceWhenPopulated(t *testing.T)
t.Fatalf("write bundle stub error = %v", err)
}
importCmd := newAuthImportCommandWithSupport(func() error { return nil })
importCmd := NewRootCommand()
var stderr bytes.Buffer
importCmd.SetOut(&bytes.Buffer{})
importCmd.SetErr(&stderr)
importCmd.SetArgs([]string{"--input", bundlePath})
err := importCmd.Execute()
if err == nil {
t.Fatal("auth import without --force should fail when auth exists")
}
var appErr *apperrors.Error
if !errors.As(err, &appErr) || appErr.Category != apperrors.CategoryValidation {
t.Fatalf("expected validation error, got %T: %v", err, err)
}
if !strings.Contains(err.Error(), "--force") {
t.Fatalf("error = %v, want --force hint", err)
}
}
func TestAuthImportRequiresForceWhenPopulated(t *testing.T) {
originalTarget := authPortableTargetPopulated
authPortableTargetPopulated = func(string) bool { return true }
t.Cleanup(func() { authPortableTargetPopulated = originalTarget })
root := t.TempDir()
configDir := filepath.Join(root, ".dws")
t.Setenv("DWS_CONFIG_DIR", configDir)
bundlePath := filepath.Join(root, "bundle.tar.gz")
if err := os.WriteFile(bundlePath, []byte("not-a-real-bundle"), 0o600); err != nil {
t.Fatalf("write bundle stub error = %v", err)
}
importCmd := newAuthImportCommandWithSupport(func() error { return nil })
importCmd.SetOut(&bytes.Buffer{})
importCmd.SetErr(&bytes.Buffer{})
importCmd.SetArgs([]string{"--input", bundlePath})
importCmd.SetArgs([]string{"auth", "import", "--input", bundlePath})
err := importCmd.Execute()
if err == nil {
t.Fatal("auth import without --force should fail when auth exists")
@@ -499,7 +251,7 @@ func TestAuthStatusDiagnosticReportsCiphertextKeyMismatch(t *testing.T) {
}
}
func TestAuthStatusRefreshFailureReportsUnauthenticatedDiagnostic(t *testing.T) {
func TestAuthStatusRefreshFailureLeavesStoredTokenIntact(t *testing.T) {
// Isolate keychain storage to a per-test directory so the saved
// token can't leak into other test packages running in parallel.
t.Setenv(keychain.StorageDirEnv, t.TempDir())
@@ -518,9 +270,6 @@ func TestAuthStatusRefreshFailureReportsUnauthenticatedDiagnostic(t *testing.T)
ExpiresAt: time.Now().Add(-time.Hour),
RefreshExpAt: time.Now().Add(24 * time.Hour),
CorpID: "dingcorp",
UserID: "user-dingcorp",
ClientID: "client-dingcorp",
Source: "mcp",
})
if err != nil {
t.Skipf("SaveTokenData() unavailable in this environment: %v", err)
@@ -538,7 +287,7 @@ func TestAuthStatusRefreshFailureReportsUnauthenticatedDiagnostic(t *testing.T)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"--format", "json", "auth", "status"})
cmd.SetArgs([]string{"auth", "status"})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v\noutput:\n%s", err, out.String())
@@ -549,18 +298,8 @@ func TestAuthStatusRefreshFailureReportsUnauthenticatedDiagnostic(t *testing.T)
t.Fatal("secure token data should remain in keychain after refresh failure")
}
var resp authStatusResponse
if err := json.Unmarshal(out.Bytes(), &resp); err != nil {
t.Fatalf("Unmarshal() error = %v\noutput:\n%s", err, out.String())
}
if resp.Authenticated {
t.Fatalf("authenticated = true after refresh failure: %+v", resp)
}
if resp.Reason != "token_refresh_failed" {
t.Fatalf("reason = %q, want token_refresh_failed: %+v", resp.Reason, resp)
}
if !strings.Contains(resp.Message, "refresh failed") {
t.Fatalf("message = %q, want original refresh failure", resp.Message)
if !bytes.Contains(out.Bytes(), []byte("\"authenticated\"")) {
t.Fatalf("output should still report authenticated status:\n%s", out.String())
}
}
@@ -608,35 +347,8 @@ func TestAuthStatusProfileOverrideDoesNotSwitchCurrentProfile(t *testing.T) {
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
if cfg.CurrentProfile != "corp_secondary:user-corp_secondary" {
t.Fatalf("currentProfile = %q, want unchanged exact secondary identity", cfg.CurrentProfile)
}
}
func TestAuthStatusRejectsAmbiguousProfileSelector(t *testing.T) {
first := authLogoutTestToken("corp_first")
first.CorpName = "Shared Org"
second := authLogoutTestToken("corp_second")
second.CorpName = "Shared Org"
setupAuthLogoutProfiles(t, first, second)
cmd := NewRootCommand()
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"--format", "json", "auth", "status", "--profile", "Shared Org"})
err := cmd.Execute()
if err == nil {
t.Fatalf("auth status accepted ambiguous profile selector\noutput:\n%s", out.String())
}
var appErr *apperrors.Error
if !errors.As(err, &appErr) || appErr.Category != apperrors.CategoryValidation {
t.Fatalf("error = %T %v, want validation error", err, err)
}
for _, candidate := range []string{"corp_first", "corp_second"} {
if !strings.Contains(err.Error(), candidate) {
t.Fatalf("error = %q, want candidate %q", err.Error(), candidate)
}
if cfg.CurrentProfile != "corp_secondary" {
t.Fatalf("currentProfile = %q, want unchanged corp_secondary", cfg.CurrentProfile)
}
}
@@ -810,8 +522,8 @@ func TestAuthLogoutProfileDeletesOnlySelectedProfile(t *testing.T) {
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
if cfg.PrimaryProfile != "" || cfg.CurrentProfile != "corp_secondary:user-corp_secondary" {
t.Fatalf("profiles pointers = primary %q current %q", cfg.PrimaryProfile, cfg.CurrentProfile)
if cfg.PrimaryProfile != "corp_secondary" || cfg.CurrentProfile != "corp_secondary" {
t.Fatalf("profiles pointers = primary %q current %q, want corp_secondary/corp_secondary", cfg.PrimaryProfile, cfg.CurrentProfile)
}
if len(cfg.Profiles) != 1 || cfg.Profiles[0].CorpID != "corp_secondary" {
t.Fatalf("profiles = %#v, want only corp_secondary retained", cfg.Profiles)
@@ -831,102 +543,6 @@ func TestAuthLogoutProfileDeletesOnlySelectedProfile(t *testing.T) {
}
}
func TestAuthLogoutExactProfilePreservesSameCorpAccount(t *testing.T) {
first := authLogoutTestToken("corp_same")
first.UserID = "user_1"
second := authLogoutTestToken("corp_same")
second.AccessToken = "access-second"
second.RefreshToken = "refresh-second"
second.UserID = "user_2"
configDir := setupAuthLogoutProfiles(t, first, second)
originalTransport := http.DefaultTransport
t.Cleanup(func() {
http.DefaultTransport = originalTransport
})
http.DefaultTransport = roundTripFunc(func(req *http.Request) (*http.Response, error) {
return nil, errors.New("remote revoke disabled in unit test")
})
cmd := NewRootCommand()
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"auth", "logout", "--profile", "corp_same:user_2"})
if err := cmd.Execute(); err != nil {
t.Fatalf("auth logout exact profile error = %v\noutput:\n%s", err, out.String())
}
cfg, err := authpkg.LoadProfiles(configDir)
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
if len(cfg.Profiles) != 1 || cfg.Profiles[0].UserID != "user_1" {
t.Fatalf("profiles = %#v, want only user_1 retained", cfg.Profiles)
}
if authpkg.TokenDataExistsKeychainForIdentity("corp_same", "user_2") {
t.Fatal("selected identity token should be deleted")
}
loaded, err := authpkg.LoadTokenDataForProfile(configDir, "corp_same")
if err != nil {
t.Fatalf("LoadTokenDataForProfile(org) error = %v", err)
}
if loaded.UserID != "user_1" || loaded.AccessToken != first.AccessToken {
t.Fatalf("org current token = %#v, want retained user_1", loaded)
}
}
func TestAuthLogoutLocalProfileNameRevokesOnlySelectedAccount(t *testing.T) {
first := authLogoutTestToken("corp_same")
first.UserID = "user_1"
first.UserName = "账号一"
second := authLogoutTestToken("corp_same")
second.AccessToken = "access-second"
second.RefreshToken = "refresh-second"
second.UserID = "user_2"
second.UserName = "账号二"
configDir := setupAuthLogoutProfiles(t, first, second)
cfg, err := authpkg.LoadProfiles(configDir)
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
var selector string
for _, profile := range cfg.Profiles {
if profile.UserID == "user_2" {
selector = profile.Name
}
}
if selector == "" || selector == second.CorpName {
t.Fatalf("second local profile name = %q, want unique non-org alias", selector)
}
requests := 0
originalTransport := http.DefaultTransport
t.Cleanup(func() {
http.DefaultTransport = originalTransport
})
http.DefaultTransport = roundTripFunc(func(*http.Request) (*http.Response, error) {
requests++
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader("")),
}, nil
})
cmd := NewRootCommand()
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"auth", "logout", "--profile", selector})
if err := cmd.Execute(); err != nil {
t.Fatalf("auth logout local profile error = %v\noutput:\n%s", err, out.String())
}
if requests != 1 {
t.Fatalf("remote revoke requests = %d, want 1", requests)
}
}
func TestAuthLoginPostLoginTUIModeRespectsRecommendAndFormat(t *testing.T) {
newRoot := func(t *testing.T) *cobra.Command {
t.Helper()
@@ -1012,15 +628,8 @@ func TestLoginRecommendProductLabelMatchesTUITarget(t *testing.T) {
}
func TestResolveAuthLoginConfigReadsInheritedYes(t *testing.T) {
t.Setenv("DWS_DEBUG_AUTH", "1")
var logs bytes.Buffer
previousLogger := slog.Default()
slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})))
t.Cleanup(func() { slog.SetDefault(previousLogger) })
root := &cobra.Command{Use: "dws"}
root.PersistentFlags().Bool("yes", false, "")
root.PersistentFlags().String("profile", "", "")
login := &cobra.Command{Use: "login"}
login.Flags().String("token", "", "")
login.Flags().Bool("device", false, "")
@@ -1045,11 +654,6 @@ func TestResolveAuthLoginConfigReadsInheritedYes(t *testing.T) {
if !cfg.Yes {
t.Fatal("Yes = false, want true")
}
if got := logs.String(); !strings.Contains(got, `"msg":"auth.login.request"`) ||
!strings.Contains(got, `"profile_selector":""`) ||
!strings.Contains(got, `"target_corp_id":""`) {
t.Fatalf("login request diagnostic log missing selector resolution:\n%s", got)
}
}
func TestAuthLoginForcesAuthorizationByDefault(t *testing.T) {
@@ -1100,12 +704,6 @@ func TestAuthLoginRecommendSkipsPostLoginTUI(t *testing.T) {
`{"success":true,"data":{"items":[{"scope":"calendar.event:read","productCode":"calendar","productName":"日历"}],"selectedScopes":["calendar.event:read"]}}`,
`{"success":true,"data":{"grantedScopes":["calendar.event:read"]}}`,
}}
authpkg.SetRuntimeProfile("corp_old:user_old")
t.Cleanup(func() { authpkg.SetRuntimeProfile("") })
var authorizationProfiles []string
fake.beforeCall = func(string) {
authorizationProfiles = append(authorizationProfiles, authpkg.RuntimeProfile())
}
cmd := newAuthLoginCommand(fake)
var out bytes.Buffer
cmd.SetOut(&out)
@@ -1124,61 +722,6 @@ func TestAuthLoginRecommendSkipsPostLoginTUI(t *testing.T) {
if got := fake.args[0]["recommend"]; got != true {
t.Fatalf("--recommend plan recommend = %#v, want true", got)
}
for _, profile := range authorizationProfiles {
if profile != "" {
t.Fatalf("manual token post-login profile = %q, want empty runtime selector", profile)
}
}
if got := authpkg.RuntimeProfile(); got != "corp_old:user_old" {
t.Fatalf("runtime profile after authorization = %q, want restored selector", got)
}
}
func TestAuthLoginRecommendUsesNewExactIdentity(t *testing.T) {
t.Setenv(keychain.DisableKeychainEnv, "1")
t.Setenv(keychain.StorageDirEnv, t.TempDir())
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
oldOAuthLogin := authOAuthLogin
oldInteractive := authLoginInteractiveTerminal
t.Cleanup(func() {
authOAuthLogin = oldOAuthLogin
authLoginInteractiveTerminal = oldInteractive
authpkg.SetRuntimeProfile("")
})
authLoginInteractiveTerminal = func() bool { return false }
authOAuthLogin = func(*authpkg.OAuthProvider, context.Context, bool) (*authpkg.TokenData, error) {
return &authpkg.TokenData{
AccessToken: "new-token",
CorpID: "corp_same",
UserID: "user_new",
ExpiresAt: time.Now().Add(time.Hour),
}, nil
}
fake := &authLoginRecommendSequenceCaller{responses: []string{
`{"success":true,"data":{"items":[],"selectedScopes":[]}}`,
}}
var authorizationProfiles []string
fake.beforeCall = func(string) {
authorizationProfiles = append(authorizationProfiles, authpkg.RuntimeProfile())
}
authpkg.SetRuntimeProfile("corp_same:user_old")
cmd := newAuthLoginCommand(fake)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{"--recommend"})
if err := cmd.Execute(); err != nil {
t.Fatalf("auth login --recommend error = %v", err)
}
for _, profile := range authorizationProfiles {
if profile != "corp_same:user_new" {
t.Fatalf("post-login authorization profile = %q, want new exact identity", profile)
}
}
if got := authpkg.RuntimeProfile(); got != "corp_same:user_old" {
t.Fatalf("runtime profile after authorization = %q, want restored old identity", got)
}
}
func TestAuthLoginDefaultTUIModeSkipsSelectorWhenAllGranted(t *testing.T) {
@@ -1403,7 +946,7 @@ func TestAuthLoginDefaultTUIRunsAfterLoginTokenSaved(t *testing.T) {
}
}
func TestEnrichAuthLoginProfileFromContactBeforePersist(t *testing.T) {
func TestEnrichAuthLoginProfileFromContactPersistsCorpName(t *testing.T) {
t.Setenv(keychain.DisableKeychainEnv, "1")
t.Setenv(keychain.StorageDirEnv, t.TempDir())
configDir := t.TempDir()
@@ -1418,8 +961,12 @@ func TestEnrichAuthLoginProfileFromContactBeforePersist(t *testing.T) {
ClientID: "client-id",
Source: "mcp",
}
if err := authpkg.SaveTokenData(configDir, token); err != nil {
t.Fatalf("SaveTokenData() error = %v", err)
}
fake := &authLoginRecommendSequenceCaller{responses: []string{
`{"success":true,"result":[{"isAdmin":false,"orgEmployeeModel":{"jobNumber":"202397","orgId":null,"orgName":"钉钉(中国)信息技术有限公司","orgUserId":"011352590165863362195","orgUserName":"玄玦(主用钉)"}}]}`,
`{"success":true,"result":[{"orgEmployeeModel":{"corpId":"ding32fff839a3e0105d","orgName":"钉钉(中国)信息技术有限公司","userId":"011352590165863362195","orgUserName":"玄玦(主用钉)"}}]}`,
}}
if err := enrichAuthLoginProfileFromContact(context.Background(), configDir, fake, token); err != nil {
t.Fatalf("enrichAuthLoginProfileFromContact() error = %v", err)
@@ -1430,16 +977,6 @@ func TestEnrichAuthLoginProfileFromContactBeforePersist(t *testing.T) {
if token.UserID != "011352590165863362195" || token.UserName != "玄玦(主用钉)" {
t.Fatalf("token user identity = (%q, %q), want contact result", token.UserID, token.UserName)
}
cfg, err := authpkg.LoadProfiles(configDir)
if err != nil {
t.Fatalf("LoadProfiles() before persist error = %v", err)
}
if len(cfg.Profiles) != 0 {
t.Fatalf("identity enrichment persisted token early: %#v", cfg.Profiles)
}
if err := authpkg.SaveTokenData(configDir, token); err != nil {
t.Fatalf("SaveTokenData() error = %v", err)
}
loaded, err := authpkg.LoadTokenDataForProfile(configDir, "ding32fff839a3e0105d")
if err != nil {
@@ -1451,50 +988,8 @@ func TestEnrichAuthLoginProfileFromContactBeforePersist(t *testing.T) {
if len(fake.tools) != 1 || fake.tools[0] != "get_current_user_profile" {
t.Fatalf("tool calls = %v, want get_current_user_profile", fake.tools)
}
if len(fake.args[0]) != 0 {
t.Fatalf("contact profile args = %#v, want no arguments", fake.args[0])
}
if len(fake.tokens) != 1 || fake.tokens[0] != "access-token" {
t.Fatalf("token overrides = %v, want access-token", fake.tokens)
}
}
func TestEnrichAuthLoginProfileLogsIdentityResolutionWithoutCredentials(t *testing.T) {
t.Setenv("DWS_DEBUG_AUTH", "1")
var logs bytes.Buffer
previousLogger := slog.Default()
slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})))
t.Cleanup(func() { slog.SetDefault(previousLogger) })
token := &authpkg.TokenData{
AccessToken: "secret-access-token",
RefreshToken: "secret-refresh-token",
CorpID: "ding_same_corp",
}
fake := &authLoginRecommendSequenceCaller{responses: []string{
`{"success":true,"result":[{"orgEmployeeModel":{"corpId":"ding_same_corp","orgName":"同一组织","userId":"user_two","orgUserName":"账号二"}}]}`,
}}
if err := enrichAuthLoginProfileFromContact(context.Background(), t.TempDir(), fake, token); err != nil {
t.Fatalf("enrichAuthLoginProfileFromContact() error = %v", err)
}
got := logs.String()
for _, want := range []string{
`"msg":"auth.login.identity.lookup.start"`,
`"msg":"auth.login.identity.lookup.result"`,
`"corp_id":"ding_same_corp"`,
`"user_id":"user_two"`,
`"user_name":"账号二"`,
} {
if !strings.Contains(got, want) {
t.Fatalf("diagnostic logs missing %q:\n%s", want, got)
}
}
for _, secret := range []string{"secret-access-token", "secret-refresh-token"} {
if strings.Contains(got, secret) {
t.Fatalf("diagnostic logs exposed credential %q:\n%s", secret, got)
}
if got := fake.args[0]["profile"]; got != "ding32fff839a3e0105d" {
t.Fatalf("contact profile arg = %#v, want ding32fff839a3e0105d", got)
}
}
@@ -1508,7 +1003,6 @@ type authLoginRecommendSequenceCaller struct {
responses []string
tools []string
args []map[string]any
tokens []string
beforeCall func(toolName string)
}
@@ -1530,11 +1024,6 @@ func (f *authLoginRecommendSequenceCaller) CallTool(_ context.Context, _ string,
return &edition.ToolResult{Content: []edition.ContentBlock{{Type: "text", Text: response}}}, nil
}
func (f *authLoginRecommendSequenceCaller) CallToolWithToken(ctx context.Context, token, productID, toolName string, args map[string]any) (*edition.ToolResult, error) {
f.tokens = append(f.tokens, token)
return f.CallTool(ctx, productID, toolName, args)
}
func (f *authLoginRecommendSequenceCaller) Format() string { return "table" }
func (f *authLoginRecommendSequenceCaller) DryRun() bool { return false }
@@ -1584,11 +1073,9 @@ func setupAuthLogoutProfiles(t *testing.T, tokens ...*authpkg.TokenData) string
ResetRuntimeTokenCache()
clearCompatCache()
t.Cleanup(func() {
_ = authpkg.DeleteAllTokenData(configDir)
authpkg.SetRuntimeProfile("")
ResetRuntimeTokenCache()
clearCompatCache()
CloseFileLogger()
})
for _, token := range tokens {
@@ -1,70 +0,0 @@
package app
import (
"bytes"
"errors"
"strings"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/keychain"
"github.com/spf13/cobra"
)
func TestAuthMigrateKeychainRemainingBranches(t *testing.T) {
originalMigrate, originalTarget := migrateKeychainToFileDEK, authMigrateTarget
t.Cleanup(func() {
migrateKeychainToFileDEK, authMigrateTarget = originalMigrate, originalTarget
})
newRoot := func(format string) (*cobra.Command, *bytes.Buffer) {
root := &cobra.Command{Use: "dws"}
root.PersistentFlags().Bool("dry-run", false, "")
root.PersistentFlags().Bool("yes", false, "")
root.PersistentFlags().String("format", format, "")
root.AddCommand(newAuthMigrateKeychainCommand())
var output bytes.Buffer
root.SetOut(&output)
root.SetErr(&output)
return root, &output
}
t.Setenv(keychain.DisableKeychainEnv, "")
authMigrateTarget = func(*cobra.Command) (string, error) { return "", errors.New("flag") }
root, _ := newRoot("text")
root.SetArgs([]string{"migrate-keychain", "--dry-run"})
if err := root.Execute(); err == nil || !strings.Contains(err.Error(), "--to") {
t.Fatalf("target flag error = %v", err)
}
authMigrateTarget = originalTarget
root, _ = newRoot("text")
root.SetArgs([]string{"migrate-keychain", "--to", "other", "--dry-run"})
if err := root.Execute(); err == nil || !strings.Contains(err.Error(), "file-dek") {
t.Fatalf("unsupported target error = %v", err)
}
migrateKeychainToFileDEK = func(string, bool) (int, error) { return 0, errors.New("backend") }
root, _ = newRoot("text")
root.SetArgs([]string{"migrate-keychain", "--dry-run"})
if err := root.Execute(); err == nil || !strings.Contains(err.Error(), "backend") {
t.Fatalf("migration backend error = %v", err)
}
migrateKeychainToFileDEK = func(string, bool) (int, error) { return 3, nil }
for _, test := range []struct {
args []string
want string
}{
{[]string{"migrate-keychain", "--dry-run"}, "预检通过"},
{[]string{"migrate-keychain", "--yes"}, "迁移完成"},
} {
root, output := newRoot("text")
root.SetArgs(test.args)
if err := root.Execute(); err != nil || !strings.Contains(output.String(), test.want) {
t.Fatalf("migrate %v = %v, %q", test.args, err, output.String())
}
}
}
// Keep the original test name for the focused macOS auth workflow while also
// opting the coverage fixture into the native platform coverage gate.
func TestCrossPlatformCoverageAuthMigrateKeychainRemainingBranches(t *testing.T) {
TestAuthMigrateKeychainRemainingBranches(t)
}
-136
View File
@@ -15,15 +15,6 @@ package app
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/logging"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/authretry"
)
// authRetryingKey marks a context that has already attempted one
@@ -32,35 +23,8 @@ import (
// to the user instead.
type authRetryingKeyType struct{}
type authRefreshFailureError struct {
rejection error
refresh error
}
func (e *authRefreshFailureError) Error() string {
return "automatic access token refresh failed"
}
func (e *authRefreshFailureError) Unwrap() []error {
if e == nil {
return nil
}
return []error{e.rejection, e.refresh}
}
var authRetryingKey = authRetryingKeyType{}
var (
runnerForceRefreshRejectedAccessToken = forceRefreshRejectedAccessToken
runnerExecuteAuthRetry func(*runtimeRunner, context.Context, string, executor.Invocation) (executor.Result, error)
)
func init() {
runnerExecuteAuthRetry = func(r *runtimeRunner, ctx context.Context, endpoint string, invocation executor.Invocation) (executor.Result, error) {
return r.executeInvocation(ctx, endpoint, invocation)
}
}
// IsAuthRetrying reports whether the current context is already inside an
// AuthRefreshRequired retry. Mirrors IsPatRetrying.
func IsAuthRetrying(ctx context.Context) bool {
@@ -70,103 +34,3 @@ func IsAuthRetrying(ctx context.Context) bool {
v, _ := ctx.Value(authRetryingKey).(bool)
return v
}
func withAuthRetrying(ctx context.Context) context.Context {
if ctx == nil {
ctx = context.Background()
}
return context.WithValue(ctx, authRetryingKey, true)
}
func authRefreshLogger() *slog.Logger {
if logger := FileLoggerInstance(); logger != nil {
return logger
}
return slog.Default()
}
func (r *runtimeRunner) managesRuntimeOAuth(hasPluginAuth bool) bool {
if r == nil || hasPluginAuth {
return false
}
return r.globalFlags == nil || strings.TrimSpace(r.globalFlags.Token) == ""
}
// retryAuthRefreshRequired consumes only the explicit edition marker. It does
// not infer retryability from free text, generic auth categories, HTTP 403, or
// ordinary business errors.
func (r *runtimeRunner) retryAuthRefreshRequired(
ctx context.Context,
endpoint string,
invocation executor.Invocation,
rejectedAccessToken string,
markerErr error,
hasPluginAuth bool,
) (executor.Result, error, bool) {
marker, marked := authretry.As(markerErr)
if !marked {
return executor.Result{}, nil, false
}
cause := marker.Cause
if cause == nil {
cause = markerErr
}
// Explicit --token and plugin credentials are not backed by the default
// OAuth refresh store. Preserve the overlay cause without mutating an
// unrelated persisted login.
if !r.managesRuntimeOAuth(hasPluginAuth) {
return executor.Result{}, cause, true
}
if IsAuthRetrying(ctx) {
authRefreshLogger().Warn("auth.runtime.refresh.retry_exhausted",
"product", invocation.CanonicalProduct,
"tool", invocation.Tool,
)
return executor.Result{}, cause, true
}
if _, err := runnerForceRefreshRejectedAccessToken(ctx, defaultConfigDir(), rejectedAccessToken); err != nil {
// Keep every log credential-safe. The returned error chain retains the
// complete cause for in-process diagnosis; even DWS_DEBUG_AUTH must not
// serialize an OAuth response body or other attacker-controlled text.
authRefreshLogger().Warn("auth.runtime.refresh.failed",
"product", invocation.CanonicalProduct,
"tool", invocation.Tool,
"stage", "force_refresh_rejected_token",
"error_type", fmt.Sprintf("%T", err),
)
logging.AuthDebug("auth.runtime.refresh.failed.detail",
"product", invocation.CanonicalProduct,
"tool", invocation.Tool,
"stage", "force_refresh_rejected_token",
"error_type", fmt.Sprintf("%T", err),
)
combined := &authRefreshFailureError{rejection: cause, refresh: err}
return executor.Result{}, apperrors.NewAuth(
"automatic access token refresh failed",
apperrors.WithOperation("auth/token/refresh"),
apperrors.WithReason("auth_refresh_failed"),
apperrors.WithHint("本地凭证已保留;可稍后重试,若持续失败请查看认证诊断日志。"),
apperrors.WithCause(combined),
), true
}
logging.AuthDebug("auth.runtime.refresh.succeeded",
"product", invocation.CanonicalProduct,
"tool", invocation.Tool,
)
result, err := runnerExecuteAuthRetry(r, withAuthRetrying(ctx), endpoint, invocation)
return result, err, true
}
// isRefreshableTransportAuthError deliberately excludes HTTP/RPC 403 and
// generic CategoryAuth values. OnAuthError may request a refresh only for an
// exact transport-level unauthorized signal.
func isRefreshableTransportAuthError(err error) bool {
var typed *apperrors.Error
if !errors.As(err, &typed) || typed.Category != apperrors.CategoryAuth {
return false
}
return typed.Reason == "http_401" || typed.RPCCode == 401
}
@@ -1,354 +0,0 @@
// 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 app
import (
"bytes"
"context"
"errors"
"log/slog"
"strings"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/audit"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/authretry"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
)
func installAuthRefreshRunnerSeams(t *testing.T) {
t.Helper()
previousHooks := edition.Get()
previousCall := runnerCallTool
previousPreflight := runnerPreflightDocDownload
previousRefresh := runnerForceRefreshRejectedAccessToken
previousRetry := runnerExecuteAuthRetry
previousCapture := runnerCaptureRuntimeFailure
previousProfile := authpkg.RuntimeProfile()
pluginAuthMu.Lock()
previousPlugins := pluginAuthRegistry
pluginAuthRegistry = make(map[string]*PluginAuth)
pluginAuthMu.Unlock()
runnerPreflightDocDownload = func(*runtimeRunner, context.Context, *transport.Client, string, executor.Invocation) error {
return nil
}
runnerCaptureRuntimeFailure = func(executor.Invocation, error, error) {}
authpkg.SetRuntimeProfile("")
runtimeTokenManager.Invalidate()
t.Setenv("DWS_CONFIG_DIR", "")
t.Setenv("DWS_DEBUG_AUTH", "0")
t.Cleanup(func() {
edition.Override(previousHooks)
runnerCallTool = previousCall
runnerPreflightDocDownload = previousPreflight
runnerForceRefreshRejectedAccessToken = previousRefresh
runnerExecuteAuthRetry = previousRetry
runnerCaptureRuntimeFailure = previousCapture
authpkg.SetRuntimeProfile(previousProfile)
runtimeTokenManager.Invalidate()
pluginAuthMu.Lock()
pluginAuthRegistry = previousPlugins
pluginAuthMu.Unlock()
})
}
func authRefreshTestRunner(flags *GlobalFlags) *runtimeRunner {
return &runtimeRunner{
transport: transport.NewClient(nil),
globalFlags: flags,
auditSink: audit.NopSink{},
}
}
func authRefreshTestInvocation() executor.Invocation {
return executor.Invocation{
CanonicalProduct: "auth-retry-test-product",
Tool: "test_tool",
Params: map[string]any{"value": "safe"},
}
}
func authRefreshTokenHooks(configDir string, token *string, classify func(map[string]any) error) *edition.Hooks {
return &edition.Hooks{
ConfigDir: func() string { return configDir },
TokenProvider: func(context.Context, func() (string, error)) (string, error) {
return *token, nil
},
ClassifyToolResult: classify,
}
}
func TestCrossPlatformCoverageRunnerRetriesEditionAuthMarkerOnce(t *testing.T) {
installAuthRefreshRunnerSeams(t)
configDir := t.TempDir()
token := "old-access"
rejection := apperrors.NewAuth("server rejected access token", apperrors.WithReason("access_token_rejected"))
edition.Override(authRefreshTokenHooks(configDir, &token, func(content map[string]any) error {
if expired, _ := content["expired"].(bool); expired {
return &authretry.AuthRefreshRequired{Cause: rejection}
}
return nil
}))
var callTokens []string
runnerCallTool = func(client *transport.Client, _ context.Context, _, _ string, _ map[string]any) (transport.ToolCallResult, error) {
callTokens = append(callTokens, client.AuthToken)
if len(callTokens) == 1 {
return transport.ToolCallResult{Content: map[string]any{"expired": true}}, nil
}
return transport.ToolCallResult{Content: map[string]any{"value": "ok"}}, nil
}
refreshCalls := 0
runnerForceRefreshRejectedAccessToken = func(_ context.Context, gotDir, rejected string) (string, error) {
refreshCalls++
if gotDir != configDir || rejected != "old-access" {
t.Fatalf("refresh input = dir %q token %q", gotDir, rejected)
}
token = "new-access"
return token, nil
}
result, err := authRefreshTestRunner(nil).executeInvocation(context.Background(), "https://example.test", authRefreshTestInvocation())
if err != nil {
t.Fatal(err)
}
if refreshCalls != 1 || len(callTokens) != 2 || callTokens[0] != "old-access" || callTokens[1] != "new-access" {
t.Fatalf("refreshes=%d call tokens=%v", refreshCalls, callTokens)
}
content, _ := result.Response["content"].(map[string]any)
if content["value"] != "ok" || content["success"] != true {
t.Fatalf("result content = %#v", content)
}
}
func TestCrossPlatformCoverageRunnerRefreshFailurePreservesBothCausesAndSafeLog(t *testing.T) {
installAuthRefreshRunnerSeams(t)
t.Setenv("DWS_DEBUG_AUTH", "1")
configDir := t.TempDir()
token := "old-access"
rejection := apperrors.NewAuth("server rejected access token", apperrors.WithReason("access_token_rejected"))
edition.Override(authRefreshTokenHooks(configDir, &token, func(map[string]any) error {
return &authretry.AuthRefreshRequired{Cause: rejection}
}))
runnerCallTool = func(*transport.Client, context.Context, string, string, map[string]any) (transport.ToolCallResult, error) {
return transport.ToolCallResult{Content: map[string]any{"expired": true}}, nil
}
refreshErr := errors.New(`oauth refresh response parse failed: body={"access_token":"access-token-secret","refresh_token":"refresh-token-secret","uid":"uid-secret-value"}`)
runnerForceRefreshRejectedAccessToken = func(context.Context, string, string) (string, error) {
return "", refreshErr
}
var logs bytes.Buffer
previousLogger := slog.Default()
slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})))
t.Cleanup(func() { slog.SetDefault(previousLogger) })
_, err := authRefreshTestRunner(nil).executeInvocation(context.Background(), "https://example.test", authRefreshTestInvocation())
if !errors.Is(err, rejection) || !errors.Is(err, refreshErr) {
t.Fatalf("error = %v, want rejection and refresh causes", err)
}
var typed *apperrors.Error
if !errors.As(err, &typed) || typed.Category != apperrors.CategoryAuth || typed.Reason != "auth_refresh_failed" || typed.Operation != "auth/token/refresh" {
t.Fatalf("refresh envelope = %#v", typed)
}
var rendered bytes.Buffer
if printErr := apperrors.PrintJSON(&rendered, err); printErr != nil {
t.Fatal(printErr)
}
for _, want := range []string{`"category": "auth"`, `"reason": "auth_refresh_failed"`, `"operation": "auth/token/refresh"`} {
if !strings.Contains(rendered.String(), want) {
t.Fatalf("structured stderr missing %s: %s", want, rendered.String())
}
}
for _, secret := range []string{"access-token-secret", "refresh-token-secret", "uid-secret-value"} {
if strings.Contains(err.Error(), secret) || strings.Contains(logs.String(), secret) || strings.Contains(rendered.String(), secret) {
t.Fatalf("auth output leaked %q: error=%q logs=%s stderr=%s", secret, err, logs.String(), rendered.String())
}
}
for _, want := range []string{"auth.runtime.refresh.failed", "auth.runtime.refresh.failed.detail", "force_refresh_rejected_token", "error_type"} {
if !strings.Contains(logs.String(), want) {
t.Fatalf("safe refresh log missing %q: %s", want, logs.String())
}
}
}
func TestCrossPlatformCoverageRunnerSecondEditionMarkerReturnsSecondCause(t *testing.T) {
installAuthRefreshRunnerSeams(t)
configDir := t.TempDir()
token := "old-access"
firstCause := errors.New("first rejection")
secondCause := errors.New("second rejection")
edition.Override(authRefreshTokenHooks(configDir, &token, func(content map[string]any) error {
attempt, _ := content["attempt"].(int)
if attempt == 1 {
return &authretry.AuthRefreshRequired{Cause: firstCause}
}
return &authretry.AuthRefreshRequired{Cause: secondCause}
}))
calls := 0
runnerCallTool = func(*transport.Client, context.Context, string, string, map[string]any) (transport.ToolCallResult, error) {
calls++
return transport.ToolCallResult{Content: map[string]any{"attempt": calls}}, nil
}
refreshCalls := 0
runnerForceRefreshRejectedAccessToken = func(context.Context, string, string) (string, error) {
refreshCalls++
token = "new-access"
return token, nil
}
_, err := authRefreshTestRunner(nil).executeInvocation(context.Background(), "https://example.test", authRefreshTestInvocation())
if !errors.Is(err, secondCause) || errors.Is(err, firstCause) {
t.Fatalf("error = %v, want only second rejection cause", err)
}
if calls != 2 || refreshCalls != 1 {
t.Fatalf("calls=%d refreshes=%d", calls, refreshCalls)
}
}
func TestCrossPlatformCoverageRunnerOnAuthErrorOnlyRetriesExactUnauthorized(t *testing.T) {
t.Run("http 401 marker retries once", func(t *testing.T) {
installAuthRefreshRunnerSeams(t)
configDir := t.TempDir()
token := "old-access"
rejection := errors.New("transport rejected token")
hookCalls := 0
hooks := authRefreshTokenHooks(configDir, &token, nil)
hooks.OnAuthError = func(string, error) error {
hookCalls++
return &authretry.AuthRefreshRequired{Cause: rejection}
}
edition.Override(hooks)
calls := 0
var callTokens []string
runnerCallTool = func(client *transport.Client, _ context.Context, _, _ string, _ map[string]any) (transport.ToolCallResult, error) {
calls++
callTokens = append(callTokens, client.AuthToken)
if calls == 1 {
return transport.ToolCallResult{}, apperrors.NewAuth("unauthorized", apperrors.WithReason("http_401"))
}
return transport.ToolCallResult{Content: map[string]any{"value": "ok"}}, nil
}
refreshCalls := 0
runnerForceRefreshRejectedAccessToken = func(context.Context, string, string) (string, error) {
refreshCalls++
token = "new-access"
return token, nil
}
if _, err := authRefreshTestRunner(nil).executeInvocation(context.Background(), "https://example.test", authRefreshTestInvocation()); err != nil {
t.Fatal(err)
}
if hookCalls != 1 || refreshCalls != 1 || calls != 2 || strings.Join(callTokens, ",") != "old-access,new-access" {
t.Fatalf("hook=%d refresh=%d calls=%d tokens=%v", hookCalls, refreshCalls, calls, callTokens)
}
})
for _, tc := range []struct {
name string
err error
}{
{name: "http 403", err: apperrors.NewAuth("forbidden", apperrors.WithReason("http_403"))},
{name: "ordinary auth", err: apperrors.NewAuth("load failed", apperrors.WithReason("auth_load_failed"))},
} {
t.Run(tc.name+" does not enter hook", func(t *testing.T) {
installAuthRefreshRunnerSeams(t)
configDir := t.TempDir()
token := "old-access"
hookCalls := 0
hooks := authRefreshTokenHooks(configDir, &token, nil)
hooks.OnAuthError = func(string, error) error {
hookCalls++
return &authretry.AuthRefreshRequired{Cause: errors.New("must not run")}
}
edition.Override(hooks)
runnerCallTool = func(*transport.Client, context.Context, string, string, map[string]any) (transport.ToolCallResult, error) {
return transport.ToolCallResult{}, tc.err
}
refreshCalls := 0
runnerForceRefreshRejectedAccessToken = func(context.Context, string, string) (string, error) {
refreshCalls++
return "", nil
}
_, err := authRefreshTestRunner(nil).executeInvocation(context.Background(), "https://example.test", authRefreshTestInvocation())
if !errors.Is(err, tc.err) || hookCalls != 0 || refreshCalls != 0 {
t.Fatalf("error=%v hook=%d refresh=%d", err, hookCalls, refreshCalls)
}
})
}
}
func TestCrossPlatformCoverageRunnerDoesNotRefreshExplicitTokenMarker(t *testing.T) {
installAuthRefreshRunnerSeams(t)
rejection := errors.New("explicit token rejected")
edition.Override(&edition.Hooks{ClassifyToolResult: func(map[string]any) error {
return &authretry.AuthRefreshRequired{Cause: rejection}
}})
calls := 0
runnerCallTool = func(*transport.Client, context.Context, string, string, map[string]any) (transport.ToolCallResult, error) {
calls++
return transport.ToolCallResult{Content: map[string]any{"expired": true}}, nil
}
refreshCalls := 0
runnerForceRefreshRejectedAccessToken = func(context.Context, string, string) (string, error) {
refreshCalls++
return "", nil
}
_, err := authRefreshTestRunner(&GlobalFlags{Token: "explicit-token"}).executeInvocation(context.Background(), "https://example.test", authRefreshTestInvocation())
if !errors.Is(err, rejection) || calls != 1 || refreshCalls != 0 {
t.Fatalf("error=%v calls=%d refresh=%d", err, calls, refreshCalls)
}
}
func TestCrossPlatformCoverageRunnerRetriesPreflightEditionMarkerOnce(t *testing.T) {
installAuthRefreshRunnerSeams(t)
configDir := t.TempDir()
token := "old-access"
rejection := errors.New("preflight token rejected")
edition.Override(authRefreshTokenHooks(configDir, &token, nil))
preflightCalls := 0
runnerPreflightDocDownload = func(*runtimeRunner, context.Context, *transport.Client, string, executor.Invocation) error {
preflightCalls++
if preflightCalls == 1 {
return &authretry.AuthRefreshRequired{Cause: rejection}
}
return nil
}
toolCalls := 0
runnerCallTool = func(*transport.Client, context.Context, string, string, map[string]any) (transport.ToolCallResult, error) {
toolCalls++
return transport.ToolCallResult{Content: map[string]any{"value": "ok"}}, nil
}
refreshCalls := 0
runnerForceRefreshRejectedAccessToken = func(context.Context, string, string) (string, error) {
refreshCalls++
token = "new-access"
return token, nil
}
if _, err := authRefreshTestRunner(nil).executeInvocation(context.Background(), "https://example.test", authRefreshTestInvocation()); err != nil {
t.Fatal(err)
}
if preflightCalls != 2 || toolCalls != 1 || refreshCalls != 1 {
t.Fatalf("preflights=%d tools=%d refreshes=%d", preflightCalls, toolCalls, refreshCalls)
}
}
-9
View File
@@ -49,15 +49,6 @@ func RegisterPluginAuth(productID string, auth *PluginAuth) {
pluginAuthRegistry[productID] = auth
}
// ClearPluginAuth removes credentials for a plugin product. Registration uses
// this before applying an accepted descriptor so a descriptor without custom
// auth cannot inherit stale credentials from an earlier root construction.
func ClearPluginAuth(productID string) {
pluginAuthMu.Lock()
defer pluginAuthMu.Unlock()
delete(pluginAuthRegistry, productID)
}
// LookupPluginAuth returns the authentication credentials registered
// for the given product ID, or nil if none exists.
func LookupPluginAuth(productID string) (*PluginAuth, bool) {
+4 -2
View File
@@ -65,8 +65,10 @@ func printCacheCompatNotice(cmd *cobra.Command, command string) error {
case "", "json":
return json.NewEncoder(cmd.OutOrStdout()).Encode(notice)
case "pretty":
data, _ := json.MarshalIndent(notice, "", " ")
var err error
data, err := json.MarshalIndent(notice, "", " ")
if err != nil {
return err
}
_, err = fmt.Fprintln(cmd.OutOrStdout(), string(data))
return err
default:
+5 -8
View File
@@ -33,11 +33,8 @@ func init() {
// Build-time variables injected via ldflags when available.
var (
buildTime = "unknown"
gitCommit = "unknown"
userHomeDir = os.UserHomeDir
executablePath = os.Executable
evaluateSymlink = filepath.EvalSymlinks
buildTime = "unknown"
gitCommit = "unknown"
)
func defaultConfigDir() string {
@@ -47,7 +44,7 @@ func defaultConfigDir() string {
if fn := edition.Get().ConfigDir; fn != nil {
return fn()
}
homeDir, err := userHomeDir()
homeDir, err := os.UserHomeDir()
if err != nil {
return exeRelativeConfigDir()
}
@@ -55,11 +52,11 @@ func defaultConfigDir() string {
}
func exeRelativeConfigDir() string {
exePath, err := executablePath()
exePath, err := os.Executable()
if err != nil {
return ".dws"
}
realPath, err := evaluateSymlink(exePath)
realPath, err := filepath.EvalSymlinks(exePath)
if err != nil {
realPath = exePath
}
+1 -3
View File
@@ -7,9 +7,7 @@ import (
func TestDefaultConfigDirUsesHomeDirectoryInOSSMode(t *testing.T) {
homeDir := filepath.Join(t.TempDir(), "home")
originalUserHomeDir := userHomeDir
userHomeDir = func() (string, error) { return homeDir, nil }
t.Cleanup(func() { userHomeDir = originalUserHomeDir })
t.Setenv("HOME", homeDir)
t.Setenv("DWS_CONFIG_DIR", "")
got := defaultConfigDir()
File diff suppressed because it is too large Load Diff
-308
View File
@@ -1,308 +0,0 @@
package app
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/apiclient"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/mcptypes"
"github.com/spf13/cobra"
)
func appRPCServer(t *testing.T, initOK, listOK bool) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req struct {
ID int `json:"id"`
Method string `json:"method"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
w.Header().Set("Content-Type", "application/json")
switch req.Method {
case "initialize":
if !initOK {
_ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "error": map[string]any{"code": -32601, "message": "init"}})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "result": map[string]any{"protocolVersion": "2025-03-26"}})
case "tools/list":
if !listOK {
_ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "error": map[string]any{"code": -1, "message": "list"}})
return
}
_ = json.NewEncoder(w).Encode(map[string]any{
"jsonrpc": "2.0",
"id": req.ID,
"result": map[string]any{
"tools": []any{map[string]any{
"name": "tool",
"description": "desc",
"inputSchema": map[string]any{
"properties": map[string]any{"id": map[string]any{"type": "string"}},
"required": []any{"id", 1, ""},
},
}},
},
})
default:
_ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": req.ID, "result": map[string]any{}})
}
}))
}
func TestCrossPlatformCoveragePluginAuthCoverage(t *testing.T) {
registerPluginAuthFromHeaders(mcptypes.ServerDescriptor{Key: "fallback", Endpoint: "%", AuthHeaders: map[string]string{"Authorization": "token"}})
registerPluginAuthFromHeaders(mcptypes.ServerDescriptor{Key: "server", Endpoint: "https://x.test", CLI: mcptypes.CLIOverlay{ID: "cli"}, AuthHeaders: map[string]string{"Authorization": "Bearer token", "X": "Y"}})
registerPluginAuthFromHeaders(mcptypes.ServerDescriptor{Key: "none"})
if got, ok := LookupPluginAuth("cli"); !ok || got == nil || got.Token != "token" {
t.Fatalf("registered plugin auth = %#v, %v", got, ok)
}
}
func TestCrossPlatformCoverageRawAPIAndTokenCoverage(t *testing.T) {
oldProvider := newAccessTokenProvider
oldManager := newLegacyTokenManager
t.Cleanup(func() {
newAccessTokenProvider = oldProvider
newLegacyTokenManager = oldManager
})
cmd := &cobra.Command{Use: "api"}
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetContext(context.Background())
invalid := []struct {
args []string
gf GlobalFlags
af apiFlags
}{
{[]string{"GET", "/x?a=1"}, GlobalFlags{}, apiFlags{}},
{[]string{"TRACE", "/x"}, GlobalFlags{}, apiFlags{}},
{[]string{"GET", "../x"}, GlobalFlags{}, apiFlags{}},
{[]string{"GET", "/x"}, GlobalFlags{}, apiFlags{params: "x\x00"}},
{[]string{"POST", "/x"}, GlobalFlags{}, apiFlags{data: "x\x00"}},
{[]string{"POST", "/x"}, GlobalFlags{}, apiFlags{params: "-", data: "-"}},
{[]string{"GET", "/x"}, GlobalFlags{Output: "x"}, apiFlags{pageAll: true}},
{[]string{"GET", "/x"}, GlobalFlags{}, apiFlags{params: "{"}},
{[]string{"POST", "/x"}, GlobalFlags{}, apiFlags{data: "{"}},
{[]string{"GET", "https://evil.test/x"}, GlobalFlags{Token: "t"}, apiFlags{}},
}
for _, tc := range invalid {
if err := runAPI(cmd, tc.args, &tc.gf, &tc.af); err == nil {
t.Fatalf("invalid API %#v succeeded", tc)
}
}
for _, raw := range []string{"", "a=1&empty=&=x", "a=1&b=2"} {
if got := parseQueryStringToJSON(raw); got == "" {
t.Fatalf("query JSON %q empty", raw)
}
}
if got, err := resolveRawAPIToken(context.Background(), " token "); err != nil || got != "token" {
t.Fatalf("explicit raw token = %q, %v", got, err)
}
authpkg.SetClientID("")
authpkg.SetClientSecret("")
if _, err := resolveRawAPIToken(context.Background(), ""); err == nil {
t.Fatal("missing app credentials succeeded")
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.Contains(r.URL.Path, "fail") {
w.WriteHeader(http.StatusInternalServerError)
_, _ = io.WriteString(w, `{"error":"bad"}`)
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"items": []any{1}, "hasMore": false})
}))
defer server.Close()
host := strings.TrimPrefix(server.URL, "http://")
host = strings.Split(host, ":")[0]
apiclient.AllowedHosts[host] = true
t.Cleanup(func() { delete(apiclient.AllowedHosts, host) })
gf := &GlobalFlags{Token: "token", DryRun: true, Format: "json", Timeout: 1}
af := &apiFlags{baseURL: server.URL}
if err := runAPI(cmd, []string{"GET", "/ok"}, gf, af); err != nil || out.Len() == 0 {
t.Fatalf("API dry run = %q, %v", out.String(), err)
}
out.Reset()
gf.DryRun = false
if err := runAPI(cmd, []string{"GET", "/ok"}, gf, af); err != nil || out.Len() == 0 {
t.Fatalf("API request = %q, %v", out.String(), err)
}
out.Reset()
af.pageAll = true
if err := runAPI(cmd, []string{"GET", "/ok"}, gf, af); err != nil || out.Len() == 0 {
t.Fatalf("API pagination = %q, %v", out.String(), err)
}
client := apiclient.NewClient("token", server.URL)
if err := runPaginated(context.Background(), client, apiclient.RawAPIRequest{Method: "GET", Path: "/fail"}, &apiFlags{}, apiclient.ResponseOptions{Out: io.Discard, ErrOut: io.Discard}); err == nil {
t.Fatal("failed pagination succeeded")
}
if _, err := ResolveAuxiliaryAccessToken(context.Background(), "", ""); err == nil {
t.Fatal("empty auxiliary config succeeded")
}
if got, err := ResolveAuxiliaryAccessToken(context.Background(), "ignored", " explicit "); err != nil || got != "explicit" {
t.Fatalf("explicit auxiliary token = %q, %v", got, err)
}
dir := t.TempDir()
newAccessTokenProvider = func(string) accessTokenGetter { return fakeAccessTokenGetter{token: "saved"} }
newLegacyTokenManager = func(string) legacyTokenGetter { return fakeLegacyTokenGetter{} }
if got, err := resolveAccessTokenFromDir(context.Background(), dir); err != nil || got != "saved" {
t.Fatalf("saved access token = %q, %v", got, err)
}
newAccessTokenProvider = func(string) accessTokenGetter { return fakeAccessTokenGetter{} }
missing := t.TempDir()
if got, err := resolveAccessTokenFromDir(context.Background(), missing); got != "" || !errors.Is(err, authpkg.ErrTokenDataNotFound) {
t.Fatalf("missing access token = %q, %v", got, err)
}
if _, err := ResolveAuxiliaryAccessToken(context.Background(), missing, ""); err == nil {
t.Fatal("missing auxiliary credentials succeeded")
}
if _, err := ForceRefreshAccessToken(context.Background(), ""); err == nil {
t.Fatal("empty force refresh config succeeded")
}
if _, err := ForceRefreshAccessToken(context.Background(), missing); err == nil {
t.Fatal("missing force refresh token succeeded")
}
}
func TestCrossPlatformCoverageRootUtilityAndTimingCoverage(t *testing.T) {
_ = resolveVerbosity(nil)
for _, flags := range []struct {
debug bool
verbose bool
format string
json bool
}{{}, {verbose: true}, {debug: true}, {format: "json"}, {format: "table"}, {json: true}} {
flagCmd := &cobra.Command{Use: "flags"}
flagCmd.Flags().Bool("debug", flags.debug, "")
flagCmd.Flags().Bool("verbose", flags.verbose, "")
flagCmd.Flags().String("format", flags.format, "")
flagCmd.Flags().Bool("json", false, "")
if flags.json {
_ = flagCmd.Flags().Set("json", "true")
}
_ = resolveVerbosity(flagCmd)
_ = commandRequestsJSONErrors(flagCmd)
_ = wantsJSONErrors(flagCmd)
}
_ = commandRequestsJSONErrors(nil)
_ = wantsJSONErrors(nil)
if got, changed := normalizeProfileFlagArgs([]string{"--profile", "a,", "b"}); !changed || len(got) == 0 {
t.Fatalf("profile args = %#v, %v", got, changed)
}
if _, changed := normalizeProfileFlagArgs([]string{"--profile"}); changed {
t.Fatal("incomplete profile flag changed")
}
if preparseProfileFlag([]string{"--profile=a"}) != "a" || preparseProfileFlag([]string{"--profile", "b"}) != "b" || preparseProfileFlag(nil) != "" {
t.Fatal("profile preparse mismatch")
}
if !argsChanged([]string{"a"}, []string{"b"}) || argsChanged([]string{"a"}, []string{"a"}) {
t.Fatal("argsChanged mismatch")
}
cmd := &cobra.Command{Use: "root"}
cmd.SetContext(context.Background())
cmd.Flags().String("output", "", "")
if err := configureOutputSink(cmd); err != nil {
t.Fatal(err)
}
path := filepath.Join(t.TempDir(), "nested", "out.txt")
_ = cmd.Flags().Set("output", path)
if err := configureOutputSink(cmd); err != nil {
t.Fatal(err)
}
_, _ = io.WriteString(cmd.OutOrStdout(), "data")
if err := closeOutputSink(cmd); err != nil {
t.Fatal(err)
}
local := &cobra.Command{Use: "local"}
local.SetContext(context.Background())
local.SetOut(io.Discard)
local.Flags().String("output", "", "")
if err := configureOutputSink(local); err != nil {
t.Fatal(err)
}
if err := validateOptionalPath("--x", ""); err != nil {
t.Fatal(err)
}
if err := validateOptionalPath("--x", "bad\x00path"); err == nil {
t.Fatal("unsafe path succeeded")
}
root := &cobra.Command{Use: "root", Short: "root"}
bindPersistentFlags(root, &GlobalFlags{})
root.AddCommand(&cobra.Command{Use: "alpha", Short: "alpha"}, &cobra.Command{Use: "hidden", Hidden: true})
configureRootHelp(root)
var help bytes.Buffer
root.SetOut(&help)
_ = root.Help()
renderRootGlobalFlags(root)
_ = visiblePersistentFlags(root)
for _, command := range root.Commands() {
_ = commandShort(command)
}
_ = visibleMCPRootCommands(root)
_ = visibleUtilityRootCommands(root)
tc := NewTimingCollector()
tc.Record("a", time.Microsecond)
tc.Record("b", 2*time.Second)
for _, d := range []time.Duration{time.Nanosecond, time.Microsecond, time.Millisecond, time.Second} {
_ = formatDuration(d)
}
for _, debug := range []bool{false, true} {
if debug {
t.Setenv(PerfDebugEnv, "1")
} else {
t.Setenv(PerfDebugEnv, "")
}
tc.PrintIfEnabled()
}
var timingOut bytes.Buffer
tc.Print(&timingOut)
if timingOut.Len() == 0 {
t.Fatal("timing output empty")
}
t.Setenv("HOME", t.TempDir())
if defaultPerfReportPath() == "" {
t.Fatal("default perf path empty")
}
t.Setenv(PerfReportEnv, "auto")
tc.WriteReportIfEnabled("v", "cmd")
if _, err := LoadLatestReport(); err != nil {
t.Fatal(err)
}
t.Setenv(PerfReportEnv, "")
tc.WriteReportIfEnabled("v", "cmd")
_ = exeRelativeConfigDir()
merged := mergeTopLevelCommands([]*cobra.Command{{Use: "a"}, {Use: "a"}, {Use: "b"}, nil})
if len(merged) != 2 {
t.Fatalf("merged commands = %#v", merged)
}
dedupRoot := &cobra.Command{Use: "root"}
dedupRoot.AddCommand(&cobra.Command{Use: "same"}, &cobra.Command{Use: "same"})
deduplicateCommands(dedupRoot)
addPluginCommandsSafe(dedupRoot, []*cobra.Command{{Use: "same"}, {Use: "new"}})
_ = newCompletionCommand(dedupRoot)
_ = newCatalogCommand(nil)
_ = newConfigCommand()
_ = newCacheCommand()
_ = newVersionCommand()
_ = newRecoveryCommand(context.Background(), nil, &GlobalFlags{})
_ = newAPICommand(&GlobalFlags{})
_ = NewRootCommand(context.Background())
}
+3
View File
@@ -309,6 +309,9 @@ func editionServerEndpoint(productID string) (string, bool) {
return "", false
}
hooks := edition.Get()
if hooks == nil {
return "", false
}
if endpoint, ok := endpointFromEditionServers(productID, hooks.StaticServers); ok {
return endpoint, true
}
+7 -13
View File
@@ -30,14 +30,7 @@ import (
"github.com/spf13/cobra"
)
var (
doctorKeychainDiagnose = keychain.Diagnose
doctorAuthStatus = (*authpkg.OAuthProvider).Status
doctorAuthAccessToken = (*authpkg.OAuthProvider).GetAccessToken
doctorHTTPDo = (*http.Client).Do
doctorFetchLatestRelease = func() (*upgrade.ReleaseInfo, error) { return upgrade.NewClient().FetchLatestRelease() }
doctorNeedsUpgrade = upgrade.NeedsUpgrade
)
var doctorKeychainDiagnose = keychain.Diagnose
// checkStatus represents the outcome of a single doctor check.
type checkStatus string
@@ -143,7 +136,7 @@ func doctorCheckAuth(ctx context.Context, w io.Writer, jsonOut bool) checkResult
provider := authpkg.NewOAuthProvider(configDir, nil)
configureOAuthProviderCompatibility(provider, configDir)
data, err := doctorAuthStatus(provider)
data, err := provider.Status()
if err != nil || data == nil {
if diagnostic := authStatusDiagnosticFromError(err); diagnostic != nil {
r := checkResult{
@@ -171,7 +164,7 @@ func doctorCheckAuth(ctx context.Context, w io.Writer, jsonOut bool) checkResult
if data.IsAccessTokenValid() || data.IsRefreshTokenValid() {
if !data.IsAccessTokenValid() {
refreshCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
_, refreshErr := doctorAuthAccessToken(provider, refreshCtx)
_, refreshErr := provider.GetAccessToken(refreshCtx)
cancel()
if refreshErr != nil {
r := checkResult{
@@ -270,7 +263,7 @@ func doctorCheckNetwork(ctx context.Context, w io.Writer, jsonOut bool, timeout
return r
}
resp, err := doctorHTTPDo(httpClient, req)
resp, err := httpClient.Do(req)
latency := time.Since(start)
if err != nil {
r := checkResult{
@@ -324,7 +317,8 @@ func doctorCheckVersion(w io.Writer, jsonOut bool, timeout time.Duration) checkR
currentVer := version
latest, err := doctorFetchLatestRelease()
client := upgrade.NewClient()
latest, err := client.FetchLatestRelease()
if err != nil {
r := checkResult{
Name: "version",
@@ -338,7 +332,7 @@ func doctorCheckVersion(w io.Writer, jsonOut bool, timeout time.Duration) checkR
return r
}
if doctorNeedsUpgrade(currentVer, latest.Version) {
if upgrade.NeedsUpgrade(currentVer, latest.Version) {
r := checkResult{
Name: "version",
Status: statusWarn,
-133
View File
@@ -1,133 +0,0 @@
package app
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/keychain"
upgradepkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/upgrade"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
)
func TestCrossPlatformCoverageDoctorRemainingCoverage(t *testing.T) {
oldEdition := edition.Get()
oldDiagnose := doctorKeychainDiagnose
oldStatus := doctorAuthStatus
oldAccess := doctorAuthAccessToken
oldHTTP := doctorHTTPDo
oldLatest := doctorFetchLatestRelease
oldNeeds := doctorNeedsUpgrade
oldRead := timingReadFile
t.Cleanup(func() {
edition.Override(oldEdition)
doctorKeychainDiagnose = oldDiagnose
doctorAuthStatus = oldStatus
doctorAuthAccessToken = oldAccess
doctorHTTPDo = oldHTTP
doctorFetchLatestRelease = oldLatest
doctorNeedsUpgrade = oldNeeds
timingReadFile = oldRead
})
edition.Override(&edition.Hooks{})
doctorKeychainDiagnose = func() keychain.Diagnostic { return keychain.Diagnostic{OK: true, Message: "ok"} }
buf := &bytes.Buffer{}
doctorAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) { return nil, nil }
if got := doctorCheckAuth(context.Background(), buf, false); got.Status != statusFail || got.Hint == "" {
t.Fatalf("missing auth = %#v", got)
}
edition.Override(&edition.Hooks{IsEmbedded: true})
if got := doctorCheckAuth(context.Background(), io.Discard, true); got.Status != statusFail || got.Hint != "" {
t.Fatalf("embedded missing auth = %#v", got)
}
edition.Override(&edition.Hooks{})
now := time.Now()
valid := &authpkg.TokenData{AccessToken: "a", ExpiresAt: now.Add(time.Hour)}
doctorAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) { return valid, nil }
if got := doctorCheckAuth(context.Background(), buf, false); got.Status != statusPass {
t.Fatalf("valid auth = %#v", got)
}
refresh := &authpkg.TokenData{RefreshToken: "r", RefreshExpAt: now.Add(time.Hour)}
doctorAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) { return refresh, nil }
doctorAuthAccessToken = func(*authpkg.OAuthProvider, context.Context) (string, error) { return "", errors.New("refresh") }
if got := doctorCheckAuth(context.Background(), buf, false); got.Status != statusWarn {
t.Fatalf("refresh failure = %#v", got)
}
doctorAuthAccessToken = func(*authpkg.OAuthProvider, context.Context) (string, error) { return "a", nil }
if got := doctorCheckAuth(context.Background(), buf, false); got.Status != statusPass {
t.Fatalf("refresh success = %#v", got)
}
expired := &authpkg.TokenData{AccessToken: "a", ExpiresAt: now.Add(-time.Hour)}
doctorAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) { return expired, nil }
if got := doctorCheckAuth(context.Background(), buf, false); got.Status != statusFail || got.Hint == "" {
t.Fatalf("expired auth = %#v", got)
}
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
if err := os.WriteFile(filepath.Join(configDir, "mcp_url"), []byte(":"), 0o600); err != nil {
t.Fatal(err)
}
if got := doctorCheckNetwork(context.Background(), buf, false, time.Second); got.Status != statusFail {
t.Fatalf("invalid network URL = %#v", got)
}
if err := os.WriteFile(filepath.Join(configDir, "mcp_url"), []byte("https://example.test"), 0o600); err != nil {
t.Fatal(err)
}
doctorHTTPDo = func(*http.Client, *http.Request) (*http.Response, error) { return nil, errors.New("network") }
if got := doctorCheckNetwork(context.Background(), buf, false, time.Second); got.Status != statusFail {
t.Fatalf("network failure = %#v", got)
}
doctorHTTPDo = func(*http.Client, *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("ok"))}, nil
}
if got := doctorCheckNetwork(context.Background(), buf, false, time.Second); got.Status != statusPass {
t.Fatalf("network success = %#v", got)
}
doctorFetchLatestRelease = func() (*upgradepkg.ReleaseInfo, error) { return nil, errors.New("latest") }
if got := doctorCheckVersion(buf, false, time.Second); got.Status != statusFail {
t.Fatalf("version failure = %#v", got)
}
doctorFetchLatestRelease = func() (*upgradepkg.ReleaseInfo, error) { return &upgradepkg.ReleaseInfo{Version: "99.0.0"}, nil }
doctorNeedsUpgrade = func(string, string) bool { return true }
if got := doctorCheckVersion(buf, false, time.Second); got.Status != statusWarn {
t.Fatalf("version warning = %#v", got)
}
doctorNeedsUpgrade = func(string, string) bool { return false }
if got := doctorCheckVersion(buf, false, time.Second); got.Status != statusPass {
t.Fatalf("version pass = %#v", got)
}
doctorAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) { return valid, nil }
doctorFetchLatestRelease = func() (*upgradepkg.ReleaseInfo, error) { return &upgradepkg.ReleaseInfo{Version: version}, nil }
timingReadFile = func(string) ([]byte, error) {
return []byte(`{"command":"test","timestamp":"2026-01-01T00:00:00Z","phases":[]}`), nil
}
doctor := newDoctorCommand()
doctor.SetContext(context.Background())
doctor.SetOut(io.Discard)
_ = doctor.Flags().Set("json", "true")
_ = doctor.Flags().Set("perf", "true")
_ = doctor.Flags().Set("timeout", "0")
if err := doctor.RunE(doctor, nil); err != nil {
t.Fatal(err)
}
doctorAuthStatus = func(*authpkg.OAuthProvider) (*authpkg.TokenData, error) { return nil, errors.New("not logged in") }
doctor = newDoctorCommand()
doctor.SetContext(context.Background())
doctor.SetOut(io.Discard)
if err := doctor.RunE(doctor, nil); err == nil {
t.Fatal("doctor failures should return an error")
}
}
+50 -89
View File
@@ -44,32 +44,6 @@ import (
"github.com/spf13/cobra"
)
var (
eventRunPersonalConsume = runPersonalEventConsume
eventRunPersonalList = runPersonalEventList
eventRunPersonalStatus = runPersonalEventStatus
eventRunPersonalStop = runPersonalEventStop
eventNormalizeAs = normalizeEventAs
eventResolveCredentials = resolveEventCredentials
eventConsumeRun = consume.Run
eventRunForeground = runForegroundBus
eventNewEventSource = newEventSource
eventNewDingtalkSource = source.New
eventResolveAccessToken = ResolveAuxiliaryAccessToken
eventForceRefreshRejected = forceRefreshRejectedAccessToken
eventBusRun = bus.Run
eventReadyFDFromEnv = busctl.ReadyFDFromEnv
eventResolvePersonal = resolvePersonalEventIdentity
eventNewPersonalSource = newPersonalStreamSource
eventMkdirAll = os.MkdirAll
eventOpenFile = os.OpenFile
eventEnumerateBuses = busctl.EnumerateBuses
eventFindBus = busctl.FindBusByClientID
eventQueryEntry = busctl.QueryEntry
eventStopBus = busctl.Stop
eventResolveAppCredentials = authpkg.ResolveAppCredentialsStrict
)
// newEventCommand returns the `event` parent command and all its subcommands.
// Wired into root.go's utilityCommands list.
func newEventCommand() *cobra.Command {
@@ -112,7 +86,6 @@ func newEventConsumeCommand() *cobra.Command {
dryRun bool
foreground bool
asIdentity string
flatten bool
personalOpts personalConsumeOptions
streamOpts eventStreamTicketOptions
)
@@ -128,11 +101,7 @@ func newEventConsumeCommand() *cobra.Command {
json 每事件多行美化 JSON(必须配 --max-events 或 --duration)
pretty 同 json,未来加颜色
raw 仅 SDK 原始 payload,无外层封装
compact 单行紧凑 JSON;不传 --flatten 时沿用原 compact processor
数据结构:
ndjson/json/pretty 默认保持 transport envelope(type/event_type/data/headers)
--flatten 结构化格式输出稳定的顶层业务字段,适合 Agent / 脚本直接消费
compact 扁平化 + 解析嵌套 + 抽取语义字段(Agent 友好)
默认使用当前 OAuth 登录态自动创建/复用个人订阅并建立个人长连接;非默认组织加
--profile。连上后 stderr 打就绪行 [event] ready,等它出现再读 stdout;停机用
@@ -143,13 +112,12 @@ SIGTERM、关 stdin,或先用 dws event stop <subscribe_id> --dry-run 预览
Args: cobra.MaximumNArgs(1),
DisableAutoGenTag: true,
RunE: func(c *cobra.Command, args []string) error {
as, err := eventNormalizeAs(asIdentity)
as, err := normalizeEventAs(asIdentity)
if err != nil {
return err
}
if as == "user" {
personalOpts.EventKey = firstArg(args)
personalOpts.Flatten = flatten
personalOpts.Common = commonConsumeOptions{
EventTypes: eventTypes,
Filter: filter,
@@ -167,13 +135,12 @@ SIGTERM、关 stdin,或先用 dws event stop <subscribe_id> --dry-run 预览
personalOpts.StreamTicketMode = streamOpts.Mode
personalOpts.StreamTicketURL = streamOpts.TicketURL
personalOpts.StreamSourceID = streamOpts.SourceID
return eventRunPersonalConsume(c, personalOpts)
return runPersonalEventConsume(c, personalOpts)
}
if personalOpts.DebugRawEvents {
return fmt.Errorf("event consume: --debug-raw-events is only supported with --as user")
}
if err := rejectChangedFlags(c, "user",
"flatten",
"subscribe-id",
"rule",
"name",
@@ -182,7 +149,6 @@ SIGTERM、关 stdin,或先用 dws event stop <subscribe_id> --dry-run 预览
"ttl",
"ephemeral",
"user",
"open-dingtalk-id",
"group",
"personal-event-base-url",
); err != nil {
@@ -198,7 +164,7 @@ SIGTERM、关 stdin,或先用 dws event stop <subscribe_id> --dry-run 预览
// Portal ticket normal mode uses portal-managed app credentials, so
// local ClientSecret is intentionally not required there.
configDir := defaultConfigDir()
clientID, clientSecret, err := eventResolveCredentials(configDir, streamOpts)
clientID, clientSecret, err := resolveEventCredentials(configDir, streamOpts)
if err != nil {
return fmt.Errorf("event consume: %w", err)
}
@@ -255,7 +221,9 @@ SIGTERM、关 stdin,或先用 dws event stop <subscribe_id> --dry-run 预览
}
// Arm the stdin-EOF shutdown watcher only for a pipe-style,
// unbounded run (see shouldWatchStdinEOF).
applyEventConsumeStdin(&cfg, maxEvents, duration, c.InOrStdin())
if shouldWatchStdinEOF(maxEvents, duration) {
cfg.Stdin = c.InOrStdin()
}
// Step 5: validation (flag-only rules).
if err := consume.ValidateConfig(cfg); err != nil {
@@ -271,9 +239,9 @@ SIGTERM、关 stdin,或先用 dws event stop <subscribe_id> --dry-run 预览
// Step 6: foreground mode runs the bus in-process. Otherwise
// consume.Run discovers / forks the bus and dials it.
if foreground {
return eventRunForeground(ctx, cfg, configDir, clientSecret, streamOpts)
return runForegroundBus(ctx, cfg, configDir, clientSecret, streamOpts)
}
return eventConsumeRun(ctx, cfg)
return consume.Run(ctx, cfg)
},
}
@@ -287,8 +255,6 @@ SIGTERM、关 stdin,或先用 dws event stop <subscribe_id> --dry-run 预览
"提示 bus 客户端期望 compact 渲染(语义透传,bus 仍按原 payload 投递)")
f.StringVarP(&formatRaw, "format", "f", "ndjson",
"输出格式 (ndjson/json/pretty/raw/compact);事件流默认 ndjson")
f.BoolVar(&flatten, "flatten", false,
"将个人事件 transport envelope 投影为稳定的顶层业务字段")
f.StringVar(&outputDir, "output-dir", "",
"每事件写一个文件到该目录 ({type}_{id}_{ts}.json);与 stdout 互斥")
f.StringArrayVar(&routesRaw, "route", nil,
@@ -323,9 +289,7 @@ SIGTERM、关 stdin,或先用 dws event stop <subscribe_id> --dry-run 预览
"或从外部先用 dws event stop <subscribe_id> --dry-run 预览、确认后加 --yes(会一并退订);"+
"请勿 kill -9(会跳过退订、泄漏服务端订阅)")
f.StringVar(&personalOpts.UserID, "user", "",
"单聊对端或指定发送人的 userId(与 --open-dingtalk-id 二选一)")
f.StringVar(&personalOpts.OpenDingTalkID, "open-dingtalk-id", "",
"单聊对端或指定发送人的 openDingtalkId(与 --user 二选一)")
"个人单聊对端 userId")
f.StringVar(&personalOpts.GroupID, "group", "",
"group 规则:openConversationId")
f.StringVar(&personalOpts.ControlBaseURL, "personal-event-base-url", "",
@@ -360,7 +324,7 @@ SIGTERM、关 stdin,或先用 dws event stop <subscribe_id> --dry-run 预览
// can run `dws event consume` from another shell to consume the events.
// v2 may add a "foreground + in-process consumer" combined mode.
func runForegroundBus(ctx context.Context, cfg consume.Config, configDir, clientSecret string, streamOpts eventStreamTicketOptions) error {
src, err := eventNewEventSource(ctx, configDir, cfg.ClientID, clientSecret, streamOpts)
src, err := newEventSource(ctx, configDir, cfg.ClientID, clientSecret, streamOpts)
if err != nil {
return err
}
@@ -375,7 +339,7 @@ func runForegroundBus(ctx context.Context, cfg consume.Config, configDir, client
Logger: slog.Default(),
}
bus.ApplyEnvTuning(&busCfg)
return eventBusRun(ctx, busCfg)
return bus.Run(ctx, busCfg)
}
type eventStreamTicketOptions struct {
@@ -423,14 +387,22 @@ func eventStreamBusID(streamOpts eventStreamTicketOptions) string {
return "portal-ticket-normal:" + sourceID
}
func newEventSource(_ context.Context, configDir, clientID, clientSecret string, streamOpts eventStreamTicketOptions) (*source.DingtalkSource, error) {
func newEventSource(ctx context.Context, configDir, clientID, clientSecret string, streamOpts eventStreamTicketOptions) (*source.DingtalkSource, error) {
if !streamOpts.enabled() {
return eventNewDingtalkSource(source.Config{
return source.New(source.Config{
ClientID: clientID,
ClientSecret: clientSecret,
})
}
token, err := ResolveAuxiliaryAccessToken(ctx, configDir, "")
if err != nil {
return nil, fmt.Errorf("event stream ticket: resolve user token: %w", err)
}
if strings.TrimSpace(token) == "" {
return nil, errors.New("event stream ticket: empty user token")
}
portalClientID := clientID
portalClientSecret := clientSecret
if streamOpts.usesPortalNormalMode() {
@@ -438,17 +410,12 @@ func newEventSource(_ context.Context, configDir, clientID, clientSecret string,
portalClientSecret = ""
}
return eventNewDingtalkSource(source.Config{
return source.New(source.Config{
ClientID: portalClientID,
ClientSecret: portalClientSecret,
PortalTicket: &source.PortalTicketConfig{
TicketURL: eventStreamTicketURL(streamOpts.TicketURL),
AccessTokenProvider: func(ctx context.Context) (string, error) {
return eventResolveAccessToken(ctx, configDir, "")
},
ForceRefreshToken: func(ctx context.Context, rejectedToken string) (string, error) {
return eventForceRefreshRejected(ctx, configDir, rejectedToken)
},
TicketURL: eventStreamTicketURL(streamOpts.TicketURL),
AccessToken: token,
SourceID: eventStreamSourceID(streamOpts.SourceID),
Mode: streamOpts.Mode,
ClientID: portalClientID,
@@ -507,7 +474,7 @@ func newEventBusCommand() *cobra.Command {
// Acquire ReadyPipe early so pre-bus.Run failures can signal
// 'E' to the parent process instead of silently dying.
readyPipe := eventReadyFDFromEnv()
readyPipe := busctl.ReadyFDFromEnv()
failEarly := func(err error) error {
if readyPipe != nil {
// 'E' signals failure; the trailing text lets the parent
@@ -528,7 +495,7 @@ func newEventBusCommand() *cobra.Command {
sourceKind = dwsevent.SourceKindAppStream
}
if sourceKind == dwsevent.SourceKindPersonalStream {
identity, err := eventResolvePersonal(ctx, configDir, streamOpts.SourceID)
identity, err := resolvePersonalEventIdentity(ctx, configDir, streamOpts.SourceID)
if err != nil {
return failEarly(fmt.Errorf("event _bus: %w", err))
}
@@ -539,7 +506,7 @@ func newEventBusCommand() *cobra.Command {
editionName := editionNameOrDefault()
workDir := eventWorkDir(configDir, editionName, dwsevent.SourceKindPersonalStream, identityHash)
endpoint := defaultIPCEndpoint(workDir, editionName, dwsevent.SourceKindPersonalStream, identityHash)
src, err := eventNewPersonalSource(ctx, personalStreamSourceOptions{
src, err := newPersonalStreamSource(ctx, personalStreamSourceOptions{
ConfigDir: configDir,
Identity: identity,
TicketMode: streamOpts.Mode,
@@ -549,8 +516,8 @@ func newEventBusCommand() *cobra.Command {
if err != nil {
return failEarly(err)
}
if err := eventMkdirAll(workDir, config.DirPerm); err == nil {
if lf, ferr := eventOpenFile(filepath.Join(workDir, "bus.log"),
if err := os.MkdirAll(workDir, config.DirPerm); err == nil {
if lf, ferr := os.OpenFile(filepath.Join(workDir, "bus.log"),
os.O_CREATE|os.O_WRONLY|os.O_APPEND, config.FilePerm); ferr == nil {
defer lf.Close()
slog.SetDefault(slog.New(slog.NewTextHandler(lf, &slog.HandlerOptions{Level: slog.LevelInfo})))
@@ -570,10 +537,10 @@ func newEventBusCommand() *cobra.Command {
Logger: slog.Default(),
}
bus.ApplyEnvTuning(&busCfg)
return eventBusRun(ctx, busCfg)
return bus.Run(ctx, busCfg)
}
resolvedID, secret, err := eventResolveCredentials(configDir, streamOpts)
resolvedID, secret, err := resolveEventCredentials(configDir, streamOpts)
if err != nil {
return failEarly(fmt.Errorf("event _bus: %w", err))
}
@@ -586,7 +553,7 @@ func newEventBusCommand() *cobra.Command {
workDir := eventWorkDir(configDir, editionName, dwsevent.SourceKindAppStream, clientIDHash)
endpoint := defaultIPCEndpoint(workDir, editionName, dwsevent.SourceKindAppStream, clientIDHash)
src, err := eventNewEventSource(ctx, configDir, clientID, secret, streamOpts)
src, err := newEventSource(ctx, configDir, clientID, secret, streamOpts)
if err != nil {
return failEarly(err)
}
@@ -595,8 +562,8 @@ func newEventBusCommand() *cobra.Command {
// own log lines never pollute stdout/stderr (which busctl/Spawn
// detached). Best-effort: if mkdir / open fails we fall back
// to slog.Default (stderr) so we at least see startup errors.
if err := eventMkdirAll(workDir, config.DirPerm); err == nil {
if lf, ferr := eventOpenFile(filepath.Join(workDir, "bus.log"),
if err := os.MkdirAll(workDir, config.DirPerm); err == nil {
if lf, ferr := os.OpenFile(filepath.Join(workDir, "bus.log"),
os.O_CREATE|os.O_WRONLY|os.O_APPEND, config.FilePerm); ferr == nil {
defer lf.Close()
slog.SetDefault(slog.New(slog.NewTextHandler(lf, &slog.HandlerOptions{Level: slog.LevelInfo})))
@@ -618,7 +585,7 @@ func newEventBusCommand() *cobra.Command {
// env-var tuning (only fills in fields left at zero; explicit
// flags above keep precedence).
bus.ApplyEnvTuning(&busCfg)
return eventBusRun(ctx, busCfg)
return bus.Run(ctx, busCfg)
},
}
cmd.Flags().StringVar(&clientIDOverride, "client-id", "",
@@ -675,7 +642,7 @@ func newEventListCommand() *cobra.Command {
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(c *cobra.Command, _ []string) error {
as, err := eventNormalizeAs(asIdentity)
as, err := normalizeEventAs(asIdentity)
if err != nil {
return err
}
@@ -683,7 +650,7 @@ func newEventListCommand() *cobra.Command {
if err := rejectPersonalEventUnsupportedFlags(c, "all", "all-editions", "client-id"); err != nil {
return fmt.Errorf("event list: %w", err)
}
return eventRunPersonalList(c, personalListOptions{
return runPersonalEventList(c, personalListOptions{
Category: category,
EnabledOnly: enabledOnly,
IncludePending: includePending,
@@ -737,7 +704,7 @@ func newEventStatusCommand() *cobra.Command {
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(c *cobra.Command, _ []string) error {
as, err := eventNormalizeAs(asIdentity)
as, err := normalizeEventAs(asIdentity)
if err != nil {
return err
}
@@ -746,7 +713,7 @@ func newEventStatusCommand() *cobra.Command {
return fmt.Errorf("event status: %w", err)
}
personalOpts.Format = formatRaw
return eventRunPersonalStatus(c, personalOpts)
return runPersonalEventStatus(c, personalOpts)
}
if err := rejectChangedFlags(c, "user", "event", "status", "subscribe-id", "personal-event-base-url", "stream-source-id"); err != nil {
return fmt.Errorf("event status: %w", err)
@@ -797,14 +764,14 @@ func collectEntries(c *cobra.Command, clientIDOver string, all, allEditions bool
// --all-editions trumps --all (scan whole tree)
if allEditions {
entries, err := eventEnumerateBuses(configDir, "")
entries, err := busctl.EnumerateBuses(configDir, "")
if err != nil {
return nil, err
}
return queryAll(entries), nil
}
if all {
entries, err := eventEnumerateBuses(configDir, editionName)
entries, err := busctl.EnumerateBuses(configDir, editionName)
if err != nil {
return nil, err
}
@@ -815,14 +782,14 @@ func collectEntries(c *cobra.Command, clientIDOver string, all, allEditions bool
// otherwise resolve via strict resolver.
clientID := clientIDOver
if clientID == "" {
resolved, _, _, _, err := eventResolveAppCredentials(configDir)
resolved, _, _, _, err := authpkg.ResolveAppCredentialsStrict(configDir)
if err != nil {
return nil, fmt.Errorf("event status: resolve credentials: %w (or pass --client-id)", err)
}
clientID = resolved
}
hash := dwsevent.ClientIDHash(clientID)
entry := eventFindBus(configDir, editionName, hash)
entry := busctl.FindBusByClientID(configDir, editionName, hash)
if entry == nil {
// No directory at all — render an empty "not running" so the user
// sees a useful answer instead of an error.
@@ -846,13 +813,13 @@ func collectEntries(c *cobra.Command, clientIDOver string, all, allEditions bool
if entry.Meta == nil {
entry.Meta = &bus.Meta{ClientID: clientID, Edition: editionName}
}
return []busctl.EntryStatus{eventQueryEntry(*entry)}, nil
return []busctl.EntryStatus{busctl.QueryEntry(*entry)}, nil
}
func queryAll(entries []busctl.BusEntry) []busctl.EntryStatus {
out := make([]busctl.EntryStatus, 0, len(entries))
for _, e := range entries {
out = append(out, eventQueryEntry(e))
out = append(out, busctl.QueryEntry(e))
}
return out
}
@@ -1022,7 +989,7 @@ func newEventStopCommand() *cobra.Command {
Args: cobra.MaximumNArgs(1),
DisableAutoGenTag: true,
RunE: func(c *cobra.Command, args []string) error {
as, err := eventNormalizeAs(asIdentity)
as, err := normalizeEventAs(asIdentity)
if err != nil {
return err
}
@@ -1041,7 +1008,7 @@ func newEventStopCommand() *cobra.Command {
if !eventStopConfirmed(c) {
return eventStopConfirmationRequired("event stop 会取消个人事件订阅并停止本地消费")
}
return eventRunPersonalStop(c, opts)
return runPersonalEventStop(c, opts)
}
if err := rejectChangedFlags(c, "user", "all", "personal-event-base-url", "stream-source-id"); err != nil {
return fmt.Errorf("event stop: %w", err)
@@ -1056,14 +1023,14 @@ func newEventStopCommand() *cobra.Command {
return eventStopConfirmationRequired("event stop 会停止事件消费")
}
configDir := defaultConfigDir()
clientID, _, _, _, err := eventResolveAppCredentials(configDir)
clientID, _, _, _, err := authpkg.ResolveAppCredentialsStrict(configDir)
if err != nil {
return fmt.Errorf("event stop: %w", err)
}
editionName := editionNameOrDefault()
clientIDHash := dwsevent.ClientIDHash(clientID)
workDir := eventWorkDir(configDir, editionName, dwsevent.SourceKindAppStream, clientIDHash)
if err := eventStopBus(busctl.StopConfig{WorkDir: workDir}); err != nil {
if err := busctl.Stop(busctl.StopConfig{WorkDir: workDir}); err != nil {
if errors.Is(err, busctl.ErrNotRunning) {
fmt.Fprintln(c.OutOrStdout(), "bus is not running")
return nil
@@ -1232,12 +1199,6 @@ func shouldWatchStdinEOF(maxEvents int, duration time.Duration) bool {
return fi.Mode()&os.ModeCharDevice == 0
}
func applyEventConsumeStdin(cfg *consume.Config, maxEvents int, duration time.Duration, stdin io.Reader) {
if cfg != nil && shouldWatchStdinEOF(maxEvents, duration) {
cfg.Stdin = stdin
}
}
// eventTypesWithDefault picks the catch-all list from registry when the
// user did not pass --event-types.
func eventTypesWithDefault(types []string) []string {
@@ -1,562 +0,0 @@
package app
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
dwsevent "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/bus"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/busctl"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/consume"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/personal"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/source"
eventtransport "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/transport"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/spf13/cobra"
)
func TestCrossPlatformCoverageEventConsumeCommandAllBranchesCoverage(t *testing.T) {
oldPersonal := eventRunPersonalConsume
oldCreds, oldConsume, oldForeground := eventResolveCredentials, eventConsumeRun, eventRunForeground
oldNormalize := eventNormalizeAs
t.Cleanup(func() {
eventRunPersonalConsume = oldPersonal
eventResolveCredentials, eventConsumeRun, eventRunForeground = oldCreds, oldConsume, oldForeground
eventNormalizeAs = oldNormalize
})
eventNormalizeAs = func(value string) (string, error) {
if strings.EqualFold(strings.TrimSpace(value), "app") {
return "app", nil
}
return normalizeEventAs(value)
}
fail := errors.New("failure")
personalCalled := false
eventRunPersonalConsume = func(*cobra.Command, personalConsumeOptions) error { personalCalled = true; return nil }
cmd := newEventConsumeCommand()
cmd.SetContext(context.Background())
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
if err := cmd.RunE(cmd, []string{"event.key"}); err != nil || !personalCalled {
t.Fatalf("personal consume = %v, called=%v", err, personalCalled)
}
makeApp := func() *cobra.Command {
command := newEventConsumeCommand()
command.SetContext(context.Background())
command.SetOut(io.Discard)
command.SetErr(io.Discard)
_ = command.Flags().Set("as", "app")
return command
}
invalid := newEventConsumeCommand()
_ = invalid.Flags().Set("as", "invalid")
if err := invalid.RunE(invalid, nil); err == nil {
t.Fatal("invalid event identity succeeded")
}
debug := makeApp()
_ = debug.Flags().Set("debug-raw-events", "true")
if err := debug.RunE(debug, nil); err == nil {
t.Fatal("app debug-raw-events succeeded")
}
userFlag := makeApp()
_ = userFlag.Flags().Set("subscribe-id", "sub")
if err := userFlag.RunE(userFlag, nil); err == nil {
t.Fatal("app personal flag succeeded")
}
if err := makeApp().RunE(makeApp(), []string{"event.key"}); err == nil {
t.Fatal("app event key succeeded")
}
eventResolveCredentials = func(string, eventStreamTicketOptions) (string, string, error) { return "", "", fail }
if err := makeApp().RunE(makeApp(), nil); !errors.Is(err, fail) {
t.Fatalf("event credentials error = %v", err)
}
eventResolveCredentials = func(string, eventStreamTicketOptions) (string, string, error) { return "client", "secret", nil }
badRoute := makeApp()
_ = badRoute.Flags().Set("route", "bad")
if err := badRoute.RunE(badRoute, nil); err == nil {
t.Fatal("invalid event route succeeded")
}
invalidConfig := makeApp()
_ = invalidConfig.Flags().Set("format", "json")
if err := invalidConfig.RunE(invalidConfig, nil); err == nil {
t.Fatal("unbounded JSON event stream succeeded")
}
conflict := makeApp()
conflict.Flags().String("output", "", "")
_ = conflict.Flags().Set("output-dir", t.TempDir())
_ = conflict.Flags().Set("output", filepath.Join(t.TempDir(), "out"))
if err := conflict.RunE(conflict, nil); err == nil {
t.Fatal("event output conflict succeeded")
}
eventConsumeRun = func(context.Context, consume.Config) error { return fail }
t.Setenv(authpkg.EnvClientID, "half-set")
t.Setenv(authpkg.EnvClientSecret, "")
valid := makeApp()
_ = valid.Flags().Set("format", "table")
_ = valid.Flags().Set("max-events", "1")
if err := valid.RunE(valid, nil); !errors.Is(err, fail) {
t.Fatalf("event consume run error = %v", err)
}
eventRunForeground = func(context.Context, consume.Config, string, string, eventStreamTicketOptions) error { return fail }
foreground := makeApp()
_ = foreground.Flags().Set("foreground", "true")
if err := foreground.RunE(foreground, nil); !errors.Is(err, fail) {
t.Fatalf("foreground event error = %v", err)
}
}
func TestCrossPlatformCoverageEventSourcesAndForegroundCoverage(t *testing.T) {
oldNew, oldToken, oldEventSource, oldBus := eventNewDingtalkSource, eventResolveAccessToken, eventNewEventSource, eventBusRun
oldEdition := edition.Get()
t.Cleanup(func() {
eventNewDingtalkSource, eventResolveAccessToken = oldNew, oldToken
eventNewEventSource, eventBusRun = oldEventSource, oldBus
edition.Override(oldEdition)
})
fail := errors.New("failure")
eventNewDingtalkSource = func(source.Config, ...source.SourceOption) (*source.DingtalkSource, error) { return nil, fail }
if _, err := newEventSource(context.Background(), "config", "client", "secret", eventStreamTicketOptions{}); !errors.Is(err, fail) {
t.Fatalf("SDK event source error = %v", err)
}
eventNewDingtalkSource = func(source.Config, ...source.SourceOption) (*source.DingtalkSource, error) {
return &source.DingtalkSource{}, nil
}
if _, err := newEventSource(context.Background(), "config", "client", "secret", eventStreamTicketOptions{}); err != nil {
t.Fatal(err)
}
stream := eventStreamTicketOptions{Mode: "custom"}
var captured source.Config
eventNewDingtalkSource = func(cfg source.Config, _ ...source.SourceOption) (*source.DingtalkSource, error) {
captured = cfg
return &source.DingtalkSource{}, nil
}
eventResolveAccessToken = func(context.Context, string, string) (string, error) { return "", fail }
if _, err := newEventSource(context.Background(), "config", "client", "secret", stream); err != nil {
t.Fatalf("stream source construction = %v", err)
}
if _, err := captured.PortalTicket.AccessTokenProvider(context.Background()); !errors.Is(err, fail) {
t.Fatalf("stream token provider error = %v", err)
}
eventResolveAccessToken = func(context.Context, string, string) (string, error) { return "token", nil }
for _, mode := range []string{"custom", "normal"} {
if _, err := newEventSource(context.Background(), "config", "client", "secret", eventStreamTicketOptions{Mode: mode}); err != nil {
t.Fatalf("stream source %s = %v", mode, err)
}
}
edition.Override(&edition.Hooks{Name: "test"})
eventNewEventSource = func(context.Context, string, string, string, eventStreamTicketOptions) (*source.DingtalkSource, error) {
return nil, fail
}
if err := runForegroundBus(context.Background(), consume.Config{}, "config", "secret", eventStreamTicketOptions{}); !errors.Is(err, fail) {
t.Fatalf("foreground source error = %v", err)
}
eventNewEventSource = func(context.Context, string, string, string, eventStreamTicketOptions) (*source.DingtalkSource, error) {
return &source.DingtalkSource{}, nil
}
eventBusRun = func(context.Context, bus.Config) error { return fail }
cfg := consume.Config{WorkDir: t.TempDir(), IPCEndpoint: filepath.Join(t.TempDir(), "bus.sock"), ClientID: "client"}
if err := runForegroundBus(context.Background(), cfg, "config", "secret", eventStreamTicketOptions{}); !errors.Is(err, fail) {
t.Fatalf("foreground bus error = %v", err)
}
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
if err := os.WriteFile(filepath.Join(configDir, "mcp_url"), []byte("https://pre-mcp.example.test"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("DWS_STREAM_SOURCE_ID", "")
if got := defaultEventStreamSourceID(); got != "pre_open_source" {
t.Fatalf("pre stream source ID = %q", got)
}
}
func TestCrossPlatformCoverageEventBusCommandAllBranchesCoverage(t *testing.T) {
oldReady, oldPersonal, oldPersonalSource := eventReadyFDFromEnv, eventResolvePersonal, eventNewPersonalSource
oldCreds, oldSource, oldRun := eventResolveCredentials, eventNewEventSource, eventBusRun
oldMkdir, oldOpen := eventMkdirAll, eventOpenFile
t.Cleanup(func() {
eventReadyFDFromEnv, eventResolvePersonal, eventNewPersonalSource = oldReady, oldPersonal, oldPersonalSource
eventResolveCredentials, eventNewEventSource, eventBusRun = oldCreds, oldSource, oldRun
eventMkdirAll, eventOpenFile = oldMkdir, oldOpen
})
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
fail := errors.New("failure")
makeBus := func(kind string) *cobra.Command {
cmd := newEventBusCommand()
cmd.SetContext(context.Background())
_ = cmd.Flags().Set("source-kind", kind)
return cmd
}
read, write, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
eventReadyFDFromEnv = func() *os.File { return write }
eventResolvePersonal = func(context.Context, string, string) (personal.Identity, error) { return personal.Identity{}, fail }
if err := makeBus(string(dwsevent.SourceKindPersonalStream)).RunE(makeBus(string(dwsevent.SourceKindPersonalStream)), nil); !errors.Is(err, fail) {
t.Fatalf("personal identity error = %v", err)
}
marker := make([]byte, 1)
_, _ = read.Read(marker)
_ = read.Close()
if marker[0] != 'E' {
t.Fatalf("ready failure marker = %q", marker)
}
eventReadyFDFromEnv = func() *os.File { return nil }
eventResolvePersonal = func(context.Context, string, string) (personal.Identity, error) {
return personal.Identity{AccessToken: "token", ClientID: "client", SourceID: "open"}, nil
}
eventNewPersonalSource = func(context.Context, personalStreamSourceOptions) (*source.PersonalSource, error) { return nil, fail }
personalCmd := makeBus(string(dwsevent.SourceKindPersonalStream))
_ = personalCmd.Flags().Set("client-id", "override")
if err := personalCmd.RunE(personalCmd, nil); !errors.Is(err, fail) {
t.Fatalf("personal stream source error = %v", err)
}
eventNewPersonalSource = func(context.Context, personalStreamSourceOptions) (*source.PersonalSource, error) {
return &source.PersonalSource{}, nil
}
eventMkdirAll = func(string, os.FileMode) error { return nil }
eventOpenFile = func(string, int, os.FileMode) (*os.File, error) { return os.CreateTemp(t.TempDir(), "bus-log") }
eventBusRun = func(context.Context, bus.Config) error { return fail }
if err := personalCmd.RunE(personalCmd, nil); !errors.Is(err, fail) {
t.Fatalf("personal bus run error = %v", err)
}
eventResolveCredentials = func(string, eventStreamTicketOptions) (string, string, error) { return "", "", fail }
if err := makeBus(string(dwsevent.SourceKindAppStream)).RunE(makeBus(string(dwsevent.SourceKindAppStream)), nil); !errors.Is(err, fail) {
t.Fatalf("app bus credentials error = %v", err)
}
eventResolveCredentials = func(string, eventStreamTicketOptions) (string, string, error) { return "client", "secret", nil }
eventNewEventSource = func(context.Context, string, string, string, eventStreamTicketOptions) (*source.DingtalkSource, error) {
return nil, fail
}
appCmd := makeBus("")
_ = appCmd.Flags().Set("client-id", "override")
if err := appCmd.RunE(appCmd, nil); !errors.Is(err, fail) {
t.Fatalf("app event source error = %v", err)
}
eventNewEventSource = func(context.Context, string, string, string, eventStreamTicketOptions) (*source.DingtalkSource, error) {
return &source.DingtalkSource{}, nil
}
if err := appCmd.RunE(appCmd, nil); !errors.Is(err, fail) {
t.Fatalf("app bus run error = %v", err)
}
eventMkdirAll = func(string, os.FileMode) error { return fail }
if err := appCmd.RunE(appCmd, nil); !errors.Is(err, fail) {
t.Fatalf("app bus run after log mkdir failure = %v", err)
}
}
func TestCrossPlatformCoverageEventListStatusCollectAndStopCoverage(t *testing.T) {
oldList, oldStatus, oldStopPersonal := eventRunPersonalList, eventRunPersonalStatus, eventRunPersonalStop
oldEnum, oldFind, oldQuery, oldStop := eventEnumerateBuses, eventFindBus, eventQueryEntry, eventStopBus
oldCreds := eventResolveAppCredentials
oldNormalize := eventNormalizeAs
t.Cleanup(func() {
eventRunPersonalList, eventRunPersonalStatus, eventRunPersonalStop = oldList, oldStatus, oldStopPersonal
eventEnumerateBuses, eventFindBus, eventQueryEntry, eventStopBus = oldEnum, oldFind, oldQuery, oldStop
eventResolveAppCredentials = oldCreds
eventNormalizeAs = oldNormalize
})
eventNormalizeAs = func(value string) (string, error) {
if strings.EqualFold(strings.TrimSpace(value), "app") {
return "app", nil
}
return normalizeEventAs(value)
}
fail := errors.New("failure")
eventRunPersonalList = func(*cobra.Command, personalListOptions) error { return fail }
list := newEventListCommand()
list.SetOut(io.Discard)
if err := list.RunE(list, nil); !errors.Is(err, fail) {
t.Fatalf("personal list error = %v", err)
}
eventRunPersonalStatus = func(*cobra.Command, personalStatusOptions) error { return fail }
status := newEventStatusCommand()
status.SetOut(io.Discard)
if err := status.RunE(status, nil); !errors.Is(err, fail) {
t.Fatalf("personal status error = %v", err)
}
eventRunPersonalStop = func(*cobra.Command, personalStopOptions) error { return fail }
stop := newEventStopCommand()
stop.SetOut(io.Discard)
stop.Flags().Bool("yes", false, "")
_ = stop.Flags().Set("yes", "true")
if err := stop.RunE(stop, []string{"sub"}); !errors.Is(err, fail) {
t.Fatalf("personal stop error = %v", err)
}
eventEnumerateBuses = func(string, string) ([]busctl.BusEntry, error) { return nil, fail }
if _, err := collectEntries(&cobra.Command{}, "client", false, true); !errors.Is(err, fail) {
t.Fatalf("all-editions collect error = %v", err)
}
if _, err := collectEntries(&cobra.Command{}, "client", true, false); !errors.Is(err, fail) {
t.Fatalf("all collect error = %v", err)
}
eventEnumerateBuses = func(string, string) ([]busctl.BusEntry, error) {
return []busctl.BusEntry{{ClientIDHash: "hash"}}, nil
}
eventQueryEntry = func(entry busctl.BusEntry) busctl.EntryStatus { return busctl.EntryStatus{Entry: entry} }
if got, err := collectEntries(&cobra.Command{}, "client", false, true); err != nil || len(got) != 1 {
t.Fatalf("all-editions entries = %#v, %v", got, err)
}
if got, err := collectEntries(&cobra.Command{}, "client", true, false); err != nil || len(got) != 1 {
t.Fatalf("all entries = %#v, %v", got, err)
}
eventResolveAppCredentials = func(string) (string, string, authpkg.CredentialSource, authpkg.CredentialSource, error) {
return "", "", authpkg.CredentialSourceUnknown, authpkg.CredentialSourceUnknown, fail
}
if _, err := collectEntries(&cobra.Command{}, "", false, false); !errors.Is(err, fail) {
t.Fatalf("single credentials error = %v", err)
}
eventResolveAppCredentials = func(string) (string, string, authpkg.CredentialSource, authpkg.CredentialSource, error) {
return "client", "secret", authpkg.CredentialSourceEnv, authpkg.CredentialSourceEnv, nil
}
eventFindBus = func(string, string, string) *busctl.BusEntry { return nil }
if got, err := collectEntries(&cobra.Command{}, "", false, false); err != nil || len(got) != 1 || got[0].Entry.State != busctl.BusStateNotRunning {
t.Fatalf("missing bus entry = %#v, %v", got, err)
}
eventFindBus = func(string, string, string) *busctl.BusEntry { return &busctl.BusEntry{} }
if got, err := collectEntries(&cobra.Command{}, "client", false, false); err != nil || len(got) != 1 || got[0].Entry.Meta == nil {
t.Fatalf("found bus entry = %#v, %v", got, err)
}
appList := newEventListCommand()
appList.SetOut(io.Discard)
_ = appList.Flags().Set("as", "app")
_ = appList.Flags().Set("client-id", "client")
if err := appList.RunE(appList, nil); err != nil {
t.Fatal(err)
}
rejectedList := newEventListCommand()
_ = rejectedList.Flags().Set("as", "app")
_ = rejectedList.Flags().Set("category", "chat")
if err := rejectedList.RunE(rejectedList, nil); err == nil {
t.Fatal("app list personal flag succeeded")
}
eventFindBus = func(string, string, string) *busctl.BusEntry {
return &busctl.BusEntry{State: busctl.BusStateOrphan, Meta: &bus.Meta{ClientID: "client"}}
}
eventQueryEntry = func(entry busctl.BusEntry) busctl.EntryStatus { return busctl.EntryStatus{Entry: entry} }
appStatus := newEventStatusCommand()
appStatus.SetOut(io.Discard)
_ = appStatus.Flags().Set("as", "app")
_ = appStatus.Flags().Set("client-id", "client")
_ = appStatus.Flags().Set("fail-on-orphan", "true")
if err := appStatus.RunE(appStatus, nil); err == nil {
t.Fatal("orphan event status succeeded")
}
rejectedStatus := newEventStatusCommand()
_ = rejectedStatus.Flags().Set("as", "app")
_ = rejectedStatus.Flags().Set("event", "key")
if err := rejectedStatus.RunE(rejectedStatus, nil); err == nil {
t.Fatal("app status personal flag succeeded")
}
appStop := func() *cobra.Command {
cmd := newEventStopCommand()
cmd.SetOut(io.Discard)
cmd.Flags().Bool("yes", true, "")
_ = cmd.Flags().Set("as", "app")
return cmd
}
changedStop := appStop()
_ = changedStop.Flags().Set("all", "true")
if err := changedStop.RunE(changedStop, nil); err == nil {
t.Fatal("app stop personal flag succeeded")
}
if err := appStop().RunE(appStop(), []string{"sub"}); err == nil {
t.Fatal("app subscribe ID succeeded")
}
eventResolveAppCredentials = func(string) (string, string, authpkg.CredentialSource, authpkg.CredentialSource, error) {
return "", "", authpkg.CredentialSourceUnknown, authpkg.CredentialSourceUnknown, fail
}
if err := appStop().RunE(appStop(), nil); !errors.Is(err, fail) {
t.Fatalf("app stop credentials error = %v", err)
}
eventResolveAppCredentials = func(string) (string, string, authpkg.CredentialSource, authpkg.CredentialSource, error) {
return "client", "secret", authpkg.CredentialSourceEnv, authpkg.CredentialSourceEnv, nil
}
eventStopBus = func(busctl.StopConfig) error { return busctl.ErrNotRunning }
if err := appStop().RunE(appStop(), nil); err != nil {
t.Fatalf("already stopped bus = %v", err)
}
eventStopBus = func(busctl.StopConfig) error { return fail }
if err := appStop().RunE(appStop(), nil); !errors.Is(err, fail) {
t.Fatalf("stop bus error = %v", err)
}
eventStopBus = func(busctl.StopConfig) error { return nil }
if err := appStop().RunE(appStop(), nil); err != nil {
t.Fatalf("stop bus success = %v", err)
}
}
func TestCrossPlatformCoverageEventCommandParentCoverage(t *testing.T) {
cmd := newEventCommand()
cmd.SetOut(io.Discard)
if err := cmd.RunE(cmd, nil); err != nil {
t.Fatal(err)
}
if !strings.Contains(cmd.Use, "event") {
t.Fatal("event command use changed")
}
}
func TestCrossPlatformCoverageEventCommandPureAndRenderBranchesCoverage(t *testing.T) {
t.Setenv(authpkg.EnvClientID, "client")
t.Setenv(authpkg.EnvClientSecret, "secret")
if got := (eventStreamTicketOptions{Mode: "custom", SourceID: " source ", TicketURL: " https://ticket "}).spawnArgs(); len(got) != 6 {
t.Fatalf("stream spawn args = %#v", got)
}
if id, secret, err := resolveEventCredentials(t.TempDir(), eventStreamTicketOptions{}); err != nil || id != "client" || secret != "secret" {
t.Fatalf("app credentials = %q, %q, %v", id, secret, err)
}
if id, secret, err := resolveEventCredentials(t.TempDir(), eventStreamTicketOptions{Mode: "normal", SourceID: "source"}); err != nil || id != "portal-ticket-normal:source" || secret != "" {
t.Fatalf("portal credentials = %q, %q, %v", id, secret, err)
}
if eventStreamTicketURL(" https://ticket ") != "https://ticket" || eventStreamSourceID(" source ") != "source" {
t.Fatal("explicit event stream routing changed")
}
t.Setenv("DWS_STREAM_SOURCE_ID", "environment")
if defaultEventStreamSourceID() != "environment" {
t.Fatal("environment stream source ID ignored")
}
oldEdition := edition.Get()
edition.Override(&edition.Hooks{})
t.Cleanup(func() { edition.Override(oldEdition) })
if editionNameOrDefault() != "open" || sourceKindLabel("") != string(dwsevent.SourceKindAppStream) {
t.Fatal("default event labels changed")
}
if !strings.Contains(eventWorkDir("config", "open", "", "hash"), string(dwsevent.SourceKindAppStream)) {
t.Fatal("default event workdir changed")
}
if _, err := normalizeEventAs("bot"); err == nil {
t.Fatal("bot events became public unexpectedly")
}
flags := &cobra.Command{}
flags.Flags().Bool("all", false, "")
if err := rejectPersonalEventUnsupportedFlags(flags, "all"); err != nil {
t.Fatal(err)
}
_ = flags.Flags().Set("all", "true")
if err := rejectPersonalEventUnsupportedFlags(flags, "all"); err == nil {
t.Fatal("personal unsupported flag accepted")
}
if firstArg(nil) != "" || firstArg([]string{"value"}) != "value" || len(eventTypesWithDefault([]string{"type"})) != 1 {
t.Fatal("event helper defaults changed")
}
_ = eventTypesWithDefault(nil)
live := &eventtransport.StatusResp{
Bus: eventtransport.StatusBus{UptimeSecs: 12},
SourceState: eventtransport.StatusSource{State: "connected", Source: "hook", ReconnectCount: 1},
Consumers: []eventtransport.StatusConsumer{
{PID: 1, Received: 2, Dropped: 3},
{PID: 2, EventTypes: []string{"chat"}, SubscribeID: "sub"},
},
PerEventTypeCounters: map[string]eventtransport.Counters{"chat": {Received: 2, Dropped: 1}},
}
entries := []busctl.EntryStatus{
{Entry: busctl.BusEntry{State: busctl.BusStateNotRunning, ClientIDHash: "not-running"}},
{Entry: busctl.BusEntry{State: busctl.BusStateOrphan, HolderPID: 3, Meta: &bus.Meta{ClientID: "orphan", SourceID: "source", StartedAt: time.Now()}}},
{Entry: busctl.BusEntry{State: busctl.BusStateRunning, HolderPID: 4, Meta: &bus.Meta{ClientID: "offline", StartedAt: time.Now().Add(-time.Minute)}}},
{Entry: busctl.BusEntry{State: busctl.BusStateRunning, HolderPID: 5, Meta: &bus.Meta{ClientID: "live"}}, Live: live},
}
if err := renderStatus(io.Discard, entries, "text"); err != nil {
t.Fatal(err)
}
if err := renderStatus(io.Discard, entries, "json"); err != nil {
t.Fatal(err)
}
if err := renderStatus(appFailWriter{err: errors.New("write")}, entries, "json"); err == nil {
t.Fatal("status JSON write failure succeeded")
}
listEntries := []listEntry{
{ClientIDHash: "hash", BusState: busctl.BusStateNotRunning},
{ClientID: "client", SourceKind: dwsevent.SourceKindPersonalStream, BusState: busctl.BusStateRunning, BusPID: 2, Consumers: live.Consumers},
}
if err := renderList(io.Discard, listEntries, "table"); err != nil {
t.Fatal(err)
}
if err := renderList(io.Discard, listEntries, "json"); err != nil {
t.Fatal(err)
}
if err := renderList(appFailWriter{err: errors.New("write")}, listEntries, "json"); err == nil {
t.Fatal("list JSON write failure succeeded")
}
if got := buildListEntry(busctl.EntryStatus{Entry: busctl.BusEntry{Meta: &bus.Meta{ClientID: "client"}}, Live: live}); len(got.Consumers) != 2 {
t.Fatalf("live list entry = %#v", got)
}
}
func TestCrossPlatformCoverageEventCommandClosureErrorBranchesCoverage(t *testing.T) {
oldNormalize := eventNormalizeAs
oldList, oldStatus := eventRunPersonalList, eventRunPersonalStatus
oldCreds, oldFind, oldQuery := eventResolveAppCredentials, eventFindBus, eventQueryEntry
t.Cleanup(func() {
eventNormalizeAs = oldNormalize
eventRunPersonalList, eventRunPersonalStatus = oldList, oldStatus
eventResolveAppCredentials, eventFindBus, eventQueryEntry = oldCreds, oldFind, oldQuery
})
eventNormalizeAs = func(value string) (string, error) {
if strings.TrimSpace(value) == "app" {
return "app", nil
}
return normalizeEventAs(value)
}
personalList := newEventListCommand()
_ = personalList.Flags().Set("all", "true")
if err := personalList.RunE(personalList, nil); err == nil {
t.Fatal("personal list app flag succeeded")
}
personalStatus := newEventStatusCommand()
_ = personalStatus.Flags().Set("fail-on-orphan", "true")
if err := personalStatus.RunE(personalStatus, nil); err == nil {
t.Fatal("personal status app flag succeeded")
}
fail := errors.New("failure")
eventResolveAppCredentials = func(string) (string, string, authpkg.CredentialSource, authpkg.CredentialSource, error) {
return "", "", authpkg.CredentialSourceUnknown, authpkg.CredentialSourceUnknown, fail
}
appList := newEventListCommand()
_ = appList.Flags().Set("as", "app")
if err := appList.RunE(appList, nil); !errors.Is(err, fail) {
t.Fatalf("app list collect error = %v", err)
}
appStatus := newEventStatusCommand()
_ = appStatus.Flags().Set("as", "app")
if err := appStatus.RunE(appStatus, nil); !errors.Is(err, fail) {
t.Fatalf("app status collect error = %v", err)
}
eventResolveAppCredentials = func(string) (string, string, authpkg.CredentialSource, authpkg.CredentialSource, error) {
return "client", "secret", authpkg.CredentialSourceEnv, authpkg.CredentialSourceEnv, nil
}
eventFindBus = func(string, string, string) *busctl.BusEntry {
return &busctl.BusEntry{State: busctl.BusStateRunning, Meta: &bus.Meta{ClientID: "client"}}
}
eventQueryEntry = func(entry busctl.BusEntry) busctl.EntryStatus { return busctl.EntryStatus{Entry: entry} }
appStatus = newEventStatusCommand()
appStatus.SetOut(io.Discard)
_ = appStatus.Flags().Set("as", "app")
_ = appStatus.Flags().Set("fail-on-orphan", "true")
if err := appStatus.RunE(appStatus, nil); err != nil {
t.Fatalf("healthy status with orphan gate = %v", err)
}
appStatus = newEventStatusCommand()
appStatus.SetOut(appFailWriter{err: errors.New("write")})
_ = appStatus.Flags().Set("as", "app")
_ = appStatus.Flags().Set("format", "json")
if err := appStatus.RunE(appStatus, nil); err == nil {
t.Fatal("status render failure should propagate")
}
}
@@ -1,47 +0,0 @@
package app
import (
"context"
"errors"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/source"
)
// TestCrossPlatformCoverageNewEventSourceWiresForceRefreshRejectedToken asserts the portal ticket
// source receives a ForceRefreshToken callback that forwards the actual
// rejected token into the app-level compare-and-refresh chain.
func TestCrossPlatformCoverageNewEventSourceWiresForceRefreshRejectedToken(t *testing.T) {
oldNew, oldRefresh := eventNewDingtalkSource, eventForceRefreshRejected
t.Cleanup(func() { eventNewDingtalkSource, eventForceRefreshRejected = oldNew, oldRefresh })
var captured source.Config
eventNewDingtalkSource = func(cfg source.Config, _ ...source.SourceOption) (*source.DingtalkSource, error) {
captured = cfg
return &source.DingtalkSource{}, nil
}
var gotDir, gotRejected string
eventForceRefreshRejected = func(_ context.Context, configDir, rejectedToken string) (string, error) {
gotDir, gotRejected = configDir, rejectedToken
return "fresh", nil
}
if _, err := newEventSource(context.Background(), "config-dir", "client", "secret", eventStreamTicketOptions{Mode: "custom"}); err != nil {
t.Fatal(err)
}
if captured.PortalTicket == nil || captured.PortalTicket.ForceRefreshToken == nil {
t.Fatal("ForceRefreshToken not wired into portal ticket config")
}
tok, err := captured.PortalTicket.ForceRefreshToken(context.Background(), "rejected-token")
if err != nil || tok != "fresh" {
t.Fatalf("force refresh = %q, %v", tok, err)
}
if gotDir != "config-dir" || gotRejected != "rejected-token" {
t.Fatalf("wiring passed dir %q rejected %q", gotDir, gotRejected)
}
fail := errors.New("refresh failed")
eventForceRefreshRejected = func(context.Context, string, string) (string, error) { return "", fail }
if _, err := captured.PortalTicket.ForceRefreshToken(context.Background(), "x"); !errors.Is(err, fail) {
t.Fatalf("refresh error = %v", err)
}
}
+86 -178
View File
@@ -37,7 +37,6 @@ import (
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/consume"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/personal"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/source"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/transport"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/config"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/spf13/cobra"
@@ -61,7 +60,6 @@ type commonConsumeOptions struct {
type personalConsumeOptions struct {
Common commonConsumeOptions
EventKey string
Flatten bool
DebugRawEvents bool
SubscribeID string
Rule string
@@ -71,7 +69,6 @@ type personalConsumeOptions struct {
TTL time.Duration
Ephemeral bool
UserID string
OpenDingTalkID string
GroupID string
ControlBaseURL string
StreamTicketMode string
@@ -110,48 +107,22 @@ type personalStreamSourceOptions struct {
ClientIDOverride string
}
var (
personalResolveEventIdentity = resolvePersonalEventIdentity
personalEnsureSubscription = ensurePersonalSubscription
personalGetSubscription = (*personal.Client).GetSubscription
personalCreateSubscription = (*personal.Client).CreateSubscription
personalDeleteSubscription = (*personal.Client).DeleteSubscription
personalListSubscriptions = (*personal.Client).ListSubscriptions
personalUpsertRunState = personal.UpsertRunState
personalRemoveRunStates = personal.RemoveRunStates
personalLoadRunStates = personal.LoadRunStates
personalConsumeRun = consume.Run
personalValidateConsumeConfig = consume.ValidateConfig
personalValidateNoOutputConflict = consume.ValidateNoOutputConflict
personalNewStreamSource = newPersonalStreamSource
personalBusRun = bus.Run
personalFindBusByIdentity = busctl.FindBusByIdentity
personalQueryEntry = busctl.QueryEntry
personalQueryStatus = busctl.QueryStatus
personalStopBus = busctl.Stop
personalFindProcess = os.FindProcess
personalSignalProcess = (*os.Process).Signal
personalResolveAuxiliaryAccessToken = ResolveAuxiliaryAccessToken
personalForceRefreshRejectedToken = forceRefreshRejectedAccessToken
personalLoadTokenData = authpkg.LoadTokenData
personalClientID = authpkg.ClientID
personalResolveAppCredentialsStrict = authpkg.ResolveAppCredentialsStrict
)
func newEventSchemaCommand() *cobra.Command {
var asIdentity string
var formatRaw string
var flatten bool
cmd := &cobra.Command{
Use: "schema <event_key>",
Short: "显示事件 schema",
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
RunE: func(c *cobra.Command, args []string) error {
_, err := normalizeEventAs(asIdentity)
as, err := normalizeEventAs(asIdentity)
if err != nil {
return err
}
if as != "user" {
return fmt.Errorf("event schema is only supported with --as user")
}
def, ok := personal.Lookup(args[0])
if !ok {
return fmt.Errorf("unknown personal event key %q", args[0])
@@ -159,12 +130,11 @@ func newEventSchemaCommand() *cobra.Command {
if !def.Public {
return personal.PublicAvailabilityError(args[0])
}
return renderPersonalSchema(c.OutOrStdout(), def, formatRaw, flatten)
return renderPersonalSchema(c.OutOrStdout(), def, formatRaw)
},
}
cmd.Flags().StringVar(&asIdentity, "as", "user", "事件身份: user")
cmd.Flags().StringVarP(&formatRaw, "format", "f", "json", "输出格式: json")
cmd.Flags().BoolVar(&flatten, "flatten", false, "显示 --flatten 消费模式对应的顶层业务字段 schema")
hideEventInternalFlags(cmd, "as")
cli.AnnotateRuntimePositionals(cmd, cli.RuntimeSchemaPositional{
Name: "event_key",
@@ -192,7 +162,7 @@ func runPersonalEventList(c *cobra.Command, opts personalListOptions) error {
return tw.Flush()
}
func renderPersonalSchema(w io.Writer, def personal.Definition, format string, flatten bool) error {
func renderPersonalSchema(w io.Writer, def personal.Definition, format string) error {
format = strings.ToLower(strings.TrimSpace(format))
if format == "" {
format = "json"
@@ -202,7 +172,7 @@ func renderPersonalSchema(w io.Writer, def personal.Definition, format string, f
}
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(personal.BuildSchemaDocumentForMode(def, flatten))
return enc.Encode(personal.BuildSchemaDocument(def))
}
func runPersonalEventConsume(c *cobra.Command, opts personalConsumeOptions) error {
@@ -210,21 +180,8 @@ func runPersonalEventConsume(c *cobra.Command, opts personalConsumeOptions) erro
if err := ensurePublicPersonalEvent(opts.EventKey); err != nil {
return err
}
rawFormat := ""
if f := c.Flags().Lookup("format"); f != nil && f.Changed {
rawFormat = opts.Common.FormatRaw
}
normalised, fellback := consume.NormalizeFormat(rawFormat)
if fellback && !opts.Common.Quiet {
fmt.Fprintf(c.ErrOrStderr(), "WARN: --format %q has no meaning for event stream; using ndjson\n", rawFormat)
}
if err := validatePersonalEventOutputMode(opts.Flatten, opts.DebugRawEvents, normalised); err != nil {
return fmt.Errorf("event consume --as user: %w", err)
}
projector := personalEventProjector(opts.DebugRawEvents, opts.Flatten)
configDir := defaultConfigDir()
identity, err := personalResolveEventIdentity(ctx, configDir, opts.StreamSourceID)
identity, err := resolvePersonalEventIdentity(ctx, configDir, opts.StreamSourceID)
if err != nil {
return fmt.Errorf("event consume --as user: %w", err)
}
@@ -237,12 +194,16 @@ func runPersonalEventConsume(c *cobra.Command, opts personalConsumeOptions) erro
if err != nil {
return fmt.Errorf("event consume --as user: %w", err)
}
rawFormat := ""
if f := c.Flags().Lookup("format"); f != nil && f.Changed {
rawFormat = opts.Common.FormatRaw
}
normalised, fellback := consume.NormalizeFormat(rawFormat)
if fellback && !opts.Common.Quiet {
fmt.Fprintf(c.ErrOrStderr(), "WARN: --format %q has no meaning for event stream; using ndjson\n", rawFormat)
}
if opts.Common.DryRun {
if strings.TrimSpace(opts.SubscribeID) == "" {
if err := validatePersonalSubscriptionOptions(opts); err != nil {
return fmt.Errorf("event consume --as user: %w", err)
}
}
cfg := consume.Config{
WorkDir: workDir,
IPCEndpoint: ipcEndpoint,
@@ -253,10 +214,8 @@ func runPersonalEventConsume(c *cobra.Command, opts personalConsumeOptions) erro
Duration: opts.Common.Duration,
EventKey: opts.EventKey,
Format: normalised,
Flatten: opts.Flatten,
OutputDir: opts.Common.OutputDir,
Routes: routes,
Projector: projector,
Stderr: c.ErrOrStderr(),
Quiet: opts.Common.Quiet,
Foreground: opts.Common.Foreground,
@@ -264,18 +223,18 @@ func runPersonalEventConsume(c *cobra.Command, opts personalConsumeOptions) erro
DryRun: true,
}
applyPersonalConsumeFilters(&cfg, opts, strings.TrimSpace(opts.SubscribeID), opts.EventKey)
return personalConsumeRun(ctx, cfg)
return consume.Run(ctx, cfg)
}
client := newPersonalEventControlClient(configDir, personalEventControlBaseURL(opts.ControlBaseURL, configDir), identity)
sub, eventKey, ruleType, err := personalEnsureSubscription(ctx, client, identity, opts)
client := personal.NewClient(personalEventControlBaseURL(opts.ControlBaseURL, configDir), identity)
sub, eventKey, ruleType, err := ensurePersonalSubscription(ctx, client, identity, opts)
if err != nil {
return fmt.Errorf("event consume --as user: %w", err)
}
if sub.SubscribeID == "" {
return fmt.Errorf("event consume --as user: server returned empty subscribe_id")
}
if err := personalUpsertRunState(workDir, personal.RunState{
if err := personal.UpsertRunState(workDir, personal.RunState{
SubscribeID: sub.SubscribeID,
EventKey: eventKey,
RuleType: ruleType,
@@ -286,11 +245,11 @@ func runPersonalEventConsume(c *cobra.Command, opts personalConsumeOptions) erro
return fmt.Errorf("event consume --as user: save run state: %w", err)
}
cleanup := func() {
_ = personalDeleteSubscription(client, context.Background(), sub.SubscribeID)
_ = personalRemoveRunStates(workDir, []string{sub.SubscribeID})
_ = client.DeleteSubscription(context.Background(), sub.SubscribeID)
_ = personal.RemoveRunStates(workDir, []string{sub.SubscribeID})
}
// Ownership-based cleanup: a subscription this run CREATED is
// unsubscribed on exit
// Ownership-based cleanup (AI-subprocess contract, aligned with
// lark-cli): a subscription this run CREATED is unsubscribed on exit
// (any exit — SIGTERM / stdin-EOF / limit / timeout / error), so nothing
// leaks server-side. A subscription REUSED via --subscribe-id is left
// intact — the caller owns its lifecycle. --ephemeral forces cleanup
@@ -301,44 +260,43 @@ func runPersonalEventConsume(c *cobra.Command, opts personalConsumeOptions) erro
}
cfg := consume.Config{
WorkDir: workDir,
IPCEndpoint: ipcEndpoint,
ClientID: identity.ClientID,
SpawnExtraArgs: personalBusSpawnArgs(identity, opts.StreamTicketMode, opts.StreamTicketURL),
Compact: opts.Common.Compact,
MaxEvents: opts.Common.MaxEvents,
Duration: opts.Common.Duration,
EventKey: eventKey,
Format: normalised,
Flatten: opts.Flatten,
OutputDir: opts.Common.OutputDir,
Routes: routes,
Projector: projector,
ReadySubscribeID: sub.SubscribeID,
Stdout: c.OutOrStdout(),
Stderr: c.ErrOrStderr(),
Quiet: opts.Common.Quiet,
Foreground: opts.Common.Foreground,
Force: opts.Common.Force,
WorkDir: workDir,
IPCEndpoint: ipcEndpoint,
ClientID: identity.ClientID,
SpawnExtraArgs: personalBusSpawnArgs(identity, opts.StreamTicketMode, opts.StreamTicketURL),
Compact: opts.Common.Compact,
MaxEvents: opts.Common.MaxEvents,
Duration: opts.Common.Duration,
EventKey: eventKey,
Format: normalised,
OutputDir: opts.Common.OutputDir,
Routes: routes,
Stdout: c.OutOrStdout(),
Stderr: c.ErrOrStderr(),
Quiet: opts.Common.Quiet,
Foreground: opts.Common.Foreground,
Force: opts.Common.Force,
}
// Arm the stdin-EOF shutdown watcher only for a pipe-style, unbounded
// run (see shouldWatchStdinEOF).
applyEventConsumeStdin(&cfg, opts.Common.MaxEvents, opts.Common.Duration, c.InOrStdin())
if shouldWatchStdinEOF(opts.Common.MaxEvents, opts.Common.Duration) {
cfg.Stdin = c.InOrStdin()
}
applyPersonalConsumeFilters(&cfg, opts, sub.SubscribeID, eventKey)
if opts.DebugRawEvents && !opts.Common.Quiet {
fmt.Fprintf(c.ErrOrStderr(), "debug raw events enabled: local event filters disabled\nworkdir: %s\nbus_log: %s\n",
workDir, filepath.Join(workDir, "bus.log"))
}
if err := personalValidateConsumeConfig(cfg); err != nil {
if err := consume.ValidateConfig(cfg); err != nil {
return err
}
if o := c.Flags().Lookup("output"); o != nil && o.Changed {
if err := personalValidateNoOutputConflict(cfg, o.Value.String()); err != nil {
if err := consume.ValidateNoOutputConflict(cfg, o.Value.String()); err != nil {
return err
}
}
if opts.Common.Foreground {
src, err := personalNewStreamSource(ctx, personalStreamSourceOptions{
src, err := newPersonalStreamSource(ctx, personalStreamSourceOptions{
ConfigDir: configDir,
Identity: identity,
TicketMode: opts.StreamTicketMode,
@@ -361,42 +319,19 @@ func runPersonalEventConsume(c *cobra.Command, opts personalConsumeOptions) erro
Source: src,
}
bus.ApplyEnvTuning(&busCfg)
err = personalBusRun(ctx, busCfg)
err = bus.Run(ctx, busCfg)
if err != nil && !opts.Ephemeral {
cleanup()
}
return err
}
err = personalConsumeRun(ctx, cfg)
err = consume.Run(ctx, cfg)
if err != nil && !opts.Ephemeral {
cleanup()
}
return err
}
func personalEventProjector(debugRawEvents, flatten bool) consume.Projector {
if debugRawEvents {
return func(ev transport.Event) (any, error) { return ev, nil }
}
if flatten {
return personal.ProjectOutput
}
return nil
}
func validatePersonalEventOutputMode(flatten, debugRawEvents bool, format consume.Format) error {
if !flatten {
return nil
}
if debugRawEvents {
return fmt.Errorf("--flatten and --debug-raw-events are mutually exclusive")
}
if format == consume.FormatRaw {
return fmt.Errorf("--flatten and --format raw are mutually exclusive")
}
return nil
}
func applyPersonalConsumeFilters(cfg *consume.Config, opts personalConsumeOptions, subscribeID, eventKey string) {
if cfg == nil {
return
@@ -412,22 +347,9 @@ func applyPersonalConsumeFilters(cfg *consume.Config, opts personalConsumeOption
cfg.SubscribeID = strings.TrimSpace(subscribeID)
}
func validatePersonalSubscriptionOptions(opts personalConsumeOptions) error {
if _, _, err := personal.BuildRuleParam(opts.EventKey, personal.RuleOptions{
RuleType: opts.Rule,
UserID: opts.UserID,
OpenDingTalkID: opts.OpenDingTalkID,
GroupID: opts.GroupID,
}); err != nil {
return err
}
_, _, err := personal.BuildFilter(opts.FilterJSON, opts.QueryCSV)
return err
}
func ensurePersonalSubscription(ctx context.Context, client *personal.Client, identity personal.Identity, opts personalConsumeOptions) (*personal.Subscription, string, string, error) {
if strings.TrimSpace(opts.SubscribeID) != "" {
sub, err := personalGetSubscription(client, ctx, opts.SubscribeID)
sub, err := client.GetSubscription(ctx, opts.SubscribeID)
if err != nil {
return nil, "", "", err
}
@@ -454,10 +376,9 @@ func ensurePersonalSubscription(ctx context.Context, client *personal.Client, id
return nil, "", "", err
}
ruleType, ruleParam, err := personal.BuildRuleParam(opts.EventKey, personal.RuleOptions{
RuleType: opts.Rule,
UserID: opts.UserID,
OpenDingTalkID: opts.OpenDingTalkID,
GroupID: opts.GroupID,
RuleType: opts.Rule,
UserID: opts.UserID,
GroupID: opts.GroupID,
})
if err != nil {
return nil, "", "", err
@@ -478,7 +399,7 @@ func ensurePersonalSubscription(ctx context.Context, client *personal.Client, id
if opts.TTL > 0 {
req.TTLSeconds = int64(opts.TTL.Seconds())
}
sub, err := personalCreateSubscription(client, ctx, req)
sub, err := client.CreateSubscription(ctx, req)
if err != nil {
return nil, "", "", err
}
@@ -491,17 +412,17 @@ func runPersonalEventStatus(c *cobra.Command, opts personalStatusOptions) error
return err
}
configDir := defaultConfigDir()
identity, err := personalResolveEventIdentity(ctx, configDir, opts.StreamSourceID)
identity, err := resolvePersonalEventIdentity(ctx, configDir, opts.StreamSourceID)
if err != nil {
return fmt.Errorf("event status --as user: %w", err)
}
identityHash := dwsevent.IdentityHash(identity.Key())
editionName := editionNameOrDefault()
workDir := eventWorkDir(configDir, editionName, dwsevent.SourceKindPersonalStream, identityHash)
entry := personalFindBusByIdentity(configDir, editionName, dwsevent.SourceKindPersonalStream, identityHash)
entry := busctl.FindBusByIdentity(configDir, editionName, dwsevent.SourceKindPersonalStream, identityHash)
var qs busctl.EntryStatus
if entry != nil {
qs = personalQueryEntry(*entry)
qs = busctl.QueryEntry(*entry)
} else {
qs = busctl.EntryStatus{Entry: busctl.BusEntry{
WorkDir: workDir,
@@ -523,7 +444,7 @@ func runPersonalEventStatus(c *cobra.Command, opts personalStatusOptions) error
if status == "" || status == "all" {
status = ""
}
subs, err := personalListSubscriptions(newPersonalEventControlClient(configDir, personalEventControlBaseURL(opts.ControlBaseURL, configDir), identity), ctx, personal.ListOptions{
subs, err := personal.NewClient(personalEventControlBaseURL(opts.ControlBaseURL, configDir), identity).ListSubscriptions(ctx, personal.ListOptions{
Status: status,
EventKey: opts.EventKey,
SubscribeID: opts.SubscribeID,
@@ -626,7 +547,7 @@ func runPersonalEventStop(c *cobra.Command, opts personalStopOptions) error {
}
configDir := defaultConfigDir()
identity, err := personalResolveEventIdentity(ctx, configDir, opts.StreamSourceID)
identity, err := resolvePersonalEventIdentity(ctx, configDir, opts.StreamSourceID)
if err != nil {
return fmt.Errorf("event stop --as user: %w", err)
}
@@ -638,20 +559,20 @@ func runPersonalEventStop(c *cobra.Command, opts personalStopOptions) error {
if err != nil {
return fmt.Errorf("event stop --as user: %w", err)
}
client := newPersonalEventControlClient(configDir, personalEventControlBaseURL(opts.ControlBaseURL, configDir), identity)
client := personal.NewClient(personalEventControlBaseURL(opts.ControlBaseURL, configDir), identity)
for _, id := range subscribeIDs {
if err := personalDeleteSubscription(client, ctx, id); err != nil {
if err := client.DeleteSubscription(ctx, id); err != nil {
return fmt.Errorf("event stop --as user: cancel subscription %s: %w", id, err)
}
}
if err := personalRemoveRunStates(workDir, subscribeIDs); err != nil {
if err := personal.RemoveRunStates(workDir, subscribeIDs); err != nil {
return fmt.Errorf("event stop --as user: update local state: %w", err)
}
if err := interruptPersonalConsumers(ipcEndpoint, subscribeIDs); err != nil {
fmt.Fprintf(c.ErrOrStderr(), "WARN: failed to stop matching local consume process: %v\n", err)
}
remaining, err := personalLoadRunStates(workDir)
remaining, err := personal.LoadRunStates(workDir)
if err != nil {
return fmt.Errorf("event stop --as user: load remaining local state: %w", err)
}
@@ -661,7 +582,7 @@ func runPersonalEventStop(c *cobra.Command, opts personalStopOptions) error {
}
busState := "personal bus stopped"
if err := personalStopBus(busctl.StopConfig{WorkDir: workDir}); err != nil {
if err := busctl.Stop(busctl.StopConfig{WorkDir: workDir}); err != nil {
if errors.Is(err, busctl.ErrNotRunning) {
busState = "personal bus is not running"
} else {
@@ -683,7 +604,7 @@ func personalStopTargets(workDir, explicit string, all bool) ([]string, error) {
if !all {
return nil, fmt.Errorf("subscribe_id is required unless --all is set")
}
states, err := personalLoadRunStates(workDir)
states, err := personal.LoadRunStates(workDir)
if err != nil {
return nil, err
}
@@ -708,7 +629,7 @@ func interruptPersonalConsumers(ipcEndpoint string, subscribeIDs []string) error
if ipcEndpoint == "" || len(targets) == 0 {
return nil
}
status, err := personalQueryStatus(ipcEndpoint)
status, err := busctl.QueryStatus(ipcEndpoint)
if err != nil {
return nil
}
@@ -723,11 +644,11 @@ func interruptPersonalConsumers(ipcEndpoint string, subscribeIDs []string) error
if _, ok := signalled[consumer.PID]; ok {
continue
}
proc, err := personalFindProcess(consumer.PID)
proc, err := os.FindProcess(consumer.PID)
if err != nil {
return fmt.Errorf("find consume pid=%d: %w", consumer.PID, err)
}
if err := personalSignalProcess(proc, os.Interrupt); err != nil && !errors.Is(err, os.ErrProcessDone) {
if err := proc.Signal(os.Interrupt); err != nil && !errors.Is(err, os.ErrProcessDone) {
return fmt.Errorf("signal consume pid=%d: %w", consumer.PID, err)
}
signalled[consumer.PID] = struct{}{}
@@ -744,14 +665,11 @@ func printPersonalStopResult(w io.Writer, subscribeIDs []string, single bool, bu
}
func resolvePersonalEventIdentity(ctx context.Context, configDir string, sourceIDOverride string) (personal.Identity, error) {
accessToken, err := personalResolveAuxiliaryAccessToken(ctx, configDir, "")
accessToken, err := ResolveAuxiliaryAccessToken(ctx, configDir, "")
if err != nil {
return personal.Identity{}, err
}
tokenData, err := personalLoadTokenData(configDir)
if err != nil && !errors.Is(err, authpkg.ErrTokenDataNotFound) {
return personal.Identity{}, fmt.Errorf("load OAuth identity metadata: %w", err)
}
tokenData, _ := authpkg.LoadTokenData(configDir)
var corpID, userID, clientID, refreshToken string
if tokenData != nil {
corpID = tokenData.CorpID
@@ -766,10 +684,10 @@ func resolvePersonalEventIdentity(ctx context.Context, configDir string, sourceI
userID = resolveRuntimeDefault(ctx, "$currentUserId")
}
if clientID == "" {
clientID = personalClientID()
clientID = authpkg.ClientID()
}
if clientID == "" {
if id, _, _, _, err := personalResolveAppCredentialsStrict(configDir); err == nil {
if id, _, _, _, err := authpkg.ResolveAppCredentialsStrict(configDir); err == nil {
clientID = id
}
}
@@ -797,15 +715,6 @@ func resolvePersonalEventIdentity(ctx context.Context, configDir string, sourceI
}, nil
}
func newPersonalEventControlClient(configDir, baseURL string, identity personal.Identity) *personal.Client {
identity.AccessToken = ""
client := personal.NewClient(baseURL, identity)
client.AccessTokenProvider = func(ctx context.Context) (string, error) {
return personalResolveAuxiliaryAccessToken(ctx, configDir, "")
}
return client
}
func personalTokenSubject(kind, token string) string {
token = strings.TrimSpace(token)
if token == "" {
@@ -841,7 +750,7 @@ func newPersonalStreamSource(ctx context.Context, opts personalStreamSourceOptio
clientID := opts.Identity.ClientID
clientSecret := ""
if mode == "custom" {
resolvedID, secret, _, _, err := personalResolveAppCredentialsStrict(opts.ConfigDir)
resolvedID, secret, _, _, err := authpkg.ResolveAppCredentialsStrict(opts.ConfigDir)
if err != nil {
return nil, err
}
@@ -854,12 +763,7 @@ func newPersonalStreamSource(ctx context.Context, opts personalStreamSourceOptio
}
_ = ctx
return source.NewPersonal(source.PersonalConfig{
AccessTokenProvider: func(ctx context.Context) (string, error) {
return personalResolveAuxiliaryAccessToken(ctx, opts.ConfigDir, "")
},
ForceRefreshToken: func(ctx context.Context, rejectedToken string) (string, error) {
return personalForceRefreshRejectedToken(ctx, opts.ConfigDir, rejectedToken)
},
AccessToken: opts.Identity.AccessToken,
ClientID: clientID,
ClientSecret: clientSecret,
SourceID: opts.Identity.SourceID,
@@ -874,14 +778,15 @@ func personalBusSpawnArgs(identity personal.Identity, ticketMode, ticketURL stri
"--source-kind", string(dwsevent.SourceKindPersonalStream),
"--stream-source-id", identity.SourceID,
}
// Forward the exact account so the detached _bus child resolves the same
// credentials as the parent, including when one organization has multiple
// logged-in users.
// Forward the organization so the detached _bus child resolves
// credentials for the SAME profile the parent used. Without this the
// child falls back to the default profile's token slot and fails to
// authenticate the personal stream for a non-default `--profile`
// (symptom: "bus child reported startup failure on ready pipe", no
// bus.log). --profile accepts a corpId; the root pre-parses it into the
// runtime profile before the _bus handler resolves the identity.
if cid := strings.TrimSpace(identity.CorpID); cid != "" {
args = append(args, "--profile", authpkg.ProfileSelector(authpkg.Profile{
CorpID: identity.CorpID,
UserID: identity.UserID,
}))
args = append(args, "--profile", cid)
}
if strings.TrimSpace(ticketMode) != "" {
args = append(args, "--stream-ticket-mode", ticketMode)
@@ -947,7 +852,10 @@ func personalEventStreamSourceID(raw string) string {
if v := strings.TrimSpace(raw); v != "" {
return v
}
return strings.TrimSpace(edition.PersonalEventSourceID())
if v := strings.TrimSpace(edition.PersonalEventSourceID()); v != "" {
return v
}
return "open"
}
func personalEventMCPBaseURL(configDir string) string {
+3 -99
View File
@@ -19,12 +19,10 @@ import (
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/consume"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/personal"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/transport"
"github.com/spf13/cobra"
)
func TestApplyPersonalConsumeFiltersDebugRawEvents(t *testing.T) {
cfg := consume.Config{EventKey: personal.EventSingleChat, ReadySubscribeID: "sub-1"}
cfg := consume.Config{}
opts := personalConsumeOptions{
DebugRawEvents: true,
Common: commonConsumeOptions{
@@ -36,9 +34,6 @@ func TestApplyPersonalConsumeFiltersDebugRawEvents(t *testing.T) {
if cfg.EventTypes != nil || cfg.Filter != "" || cfg.SubscribeID != "" {
t.Fatalf("raw debug filters = eventTypes=%#v filter=%q subscribeID=%q, want catch-all", cfg.EventTypes, cfg.Filter, cfg.SubscribeID)
}
if cfg.EventKey != personal.EventSingleChat || cfg.ReadySubscribeID != "sub-1" {
t.Fatalf("raw debug cleared ready identity: eventKey=%q subscribeID=%q", cfg.EventKey, cfg.ReadySubscribeID)
}
}
func TestApplyPersonalConsumeFiltersDefault(t *testing.T) {
@@ -53,94 +48,6 @@ func TestApplyPersonalConsumeFiltersDefault(t *testing.T) {
}
}
func TestPersonalEventProjectorSelectsExplicitModes(t *testing.T) {
if personalEventProjector(false, false) != nil {
t.Fatal("default personal consume should preserve transport envelope")
}
if personalEventProjector(false, true) == nil {
t.Fatal("flatten personal consume projector = nil")
}
projector := personalEventProjector(true, false)
if projector == nil {
t.Fatal("debug raw personal consume projector = nil")
}
ev := transport.Event{
EventID: "raw-event",
Data: `{"payload":{"uid":100001,"bizid":"internal-bizid"}}`,
Headers: map[string]string{"TOPIC": "raw"},
}
projected, err := projector(ev)
if err != nil {
t.Fatal(err)
}
if got, ok := projected.(transport.Event); !ok || got.EventID != ev.EventID || got.Data != ev.Data || got.Headers["TOPIC"] != "raw" {
t.Fatalf("debug raw projection = %#v", projected)
}
}
func TestEventConsumeFlattenRejectsRawModesBeforeIdentityResolution(t *testing.T) {
for _, tc := range []struct {
name string
args []string
want string
}{
{
name: "raw format",
args: []string{personal.EventMention, "--flatten", "--format", "raw"},
want: "--flatten and --format raw are mutually exclusive",
},
{
name: "raw debug",
args: []string{personal.EventMention, "--flatten", "--debug-raw-events"},
want: "--flatten and --debug-raw-events are mutually exclusive",
},
} {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
cmd := newEventConsumeCommand()
cmd.SilenceUsage = true
cmd.SilenceErrors = true
cmd.SetArgs(tc.args)
err := cmd.Execute()
if err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("Execute() error = %v, want %q", err, tc.want)
}
if strings.Contains(err.Error(), "login") || strings.Contains(err.Error(), "token") {
t.Fatalf("output-mode validation ran after identity resolution: %v", err)
}
})
}
}
func TestValidatePersonalEventOutputModeAllowsFlattenStructuredFormats(t *testing.T) {
for _, format := range []consume.Format{consume.FormatNDJSON, consume.FormatJSON, consume.FormatPretty, consume.FormatCompact} {
if err := validatePersonalEventOutputMode(true, false, format); err != nil {
t.Fatalf("validatePersonalEventOutputMode(true, false, %q) error = %v", format, err)
}
}
}
func TestEventConsumeFlattenFlagIsForwarded(t *testing.T) {
oldRun := eventRunPersonalConsume
t.Cleanup(func() { eventRunPersonalConsume = oldRun })
var got personalConsumeOptions
eventRunPersonalConsume = func(_ *cobra.Command, opts personalConsumeOptions) error {
got = opts
return nil
}
cmd := newEventConsumeCommand()
cmd.SilenceUsage = true
cmd.SilenceErrors = true
cmd.SetArgs([]string{personal.EventMention, "--flatten", "--format", "compact"})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v", err)
}
if !got.Flatten || got.Common.FormatRaw != "compact" {
t.Fatalf("forwarded options = %#v", got)
}
}
func TestEventConsumeDebugRawEventsRequiresUserMode(t *testing.T) {
cmd := newEventConsumeCommand()
cmd.SilenceUsage = true
@@ -165,7 +72,7 @@ func TestEventConsumeAsAppRejectedBeforeEventKeyValidation(t *testing.T) {
func TestEventConsumePersonalParamSpecFlags(t *testing.T) {
cmd := newEventConsumeCommand()
for _, name := range []string{"user", "open-dingtalk-id", "group", "query"} {
for _, name := range []string{"user", "group", "query"} {
if cmd.Flags().Lookup(name) == nil {
t.Fatalf("flag --%s is not registered", name)
}
@@ -177,7 +84,6 @@ func TestEventConsumePersonalParamSpecFlags(t *testing.T) {
"sender-union-id",
"open-conversation-id",
"keyword",
"odid",
} {
if cmd.Flags().Lookup(name) != nil {
t.Fatalf("retired flag --%s is still registered", name)
@@ -193,7 +99,6 @@ func TestEventConsumeRetiredPersonalFlagsAreUnknown(t *testing.T) {
"sender-union-id",
"open-conversation-id",
"keyword",
"odid",
} {
t.Run(name, func(t *testing.T) {
cmd := newEventConsumeCommand()
@@ -210,8 +115,7 @@ func TestEventConsumeRetiredPersonalFlagsAreUnknown(t *testing.T) {
func TestEventConsumeAsAppRejectedBeforePersonalParamSpecFlags(t *testing.T) {
for _, args := range [][]string{
{"--as", "app", "--user", "test-user-001"},
{"--as", "app", "--open-dingtalk-id", "open-user-1"},
{"--as", "app", "--user", "507971"},
{"--as", "app", "--group", "cid"},
{"--as", "app", "--query", "报警"},
} {
@@ -1,54 +0,0 @@
package app
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
dwsevent "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/personal"
)
// TestCrossPlatformCoverageNewPersonalStreamSourceWiresForceRefreshRejectedToken asserts the
// personal stream source receives a ForceRefreshToken callback that forwards
// the rejected token into the app-level compare-and-refresh chain.
func TestCrossPlatformCoverageNewPersonalStreamSourceWiresForceRefreshRejectedToken(t *testing.T) {
oldAux := personalResolveAuxiliaryAccessToken
oldRefresh := personalForceRefreshRejectedToken
t.Cleanup(func() {
personalResolveAuxiliaryAccessToken = oldAux
personalForceRefreshRejectedToken = oldRefresh
})
personalResolveAuxiliaryAccessToken = func(context.Context, string, string) (string, error) {
return "old-token", nil
}
refreshErr := errors.New("refresh rejected")
var gotDir, gotRejected string
personalForceRefreshRejectedToken = func(_ context.Context, configDir, rejectedToken string) (string, error) {
gotDir, gotRejected = configDir, rejectedToken
return "", refreshErr
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer srv.Close()
src, err := newPersonalStreamSource(context.Background(), personalStreamSourceOptions{
ConfigDir: "config-dir",
Identity: personal.Identity{ClientID: "client", SourceID: "source"},
TicketURL: srv.URL,
})
if err != nil {
t.Fatal(err)
}
// The 401 ticket response routes the rejected token through the wired
// ForceRefreshToken; the unknown refresh failure stays fatal.
if err := src.Start(context.Background(), func(*dwsevent.RawEvent) {}); !errors.Is(err, refreshErr) {
t.Fatalf("Start() error = %v, want wrapped refresh error", err)
}
if gotDir != "config-dir" || gotRejected != "old-token" {
t.Fatalf("refresh wiring got dir %q rejected %q", gotDir, gotRejected)
}
}
@@ -1,370 +0,0 @@
package app
import (
"bytes"
"context"
"errors"
"io"
"os"
"strings"
"testing"
"time"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
dwsevent "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/bus"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/busctl"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/consume"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/personal"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/source"
eventtransport "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/transport"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
"github.com/spf13/cobra"
)
func TestCrossPlatformCoveragePersonalEventRemainingSchemaAndSubscriptionCoverage(t *testing.T) {
for _, args := range [][]string{
{"known", "--as", "app"},
{"not-a-real-event"},
} {
cmd := newEventSchemaCommand()
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs(args)
if err := cmd.Execute(); err == nil {
t.Fatalf("schema args %#v succeeded", args)
}
}
oldGet := personalGetSubscription
oldCreate := personalCreateSubscription
t.Cleanup(func() {
personalGetSubscription = oldGet
personalCreateSubscription = oldCreate
})
client := personal.NewClient("https://example.test", personal.Identity{})
wantErr := errors.New("subscription")
personalGetSubscription = func(*personal.Client, context.Context, string) (*personal.Subscription, error) { return nil, wantErr }
if _, _, _, err := ensurePersonalSubscription(context.Background(), client, personal.Identity{}, personalConsumeOptions{SubscribeID: "sub"}); !errors.Is(err, wantErr) {
t.Fatalf("get subscription error = %v", err)
}
personalGetSubscription = func(*personal.Client, context.Context, string) (*personal.Subscription, error) {
return &personal.Subscription{}, nil
}
if _, _, _, err := ensurePersonalSubscription(context.Background(), client, personal.Identity{}, personalConsumeOptions{SubscribeID: "sub"}); err == nil {
t.Fatal("empty subscription event key succeeded")
}
personalGetSubscription = func(*personal.Client, context.Context, string) (*personal.Subscription, error) {
return &personal.Subscription{EventKey: personal.EventFromUser}, nil
}
if _, key, rule, err := ensurePersonalSubscription(context.Background(), client, personal.Identity{}, personalConsumeOptions{SubscribeID: "sub"}); err != nil || key != personal.EventFromUser || rule != "sender" {
t.Fatalf("sender subscription = %q %q, %v", key, rule, err)
}
personalGetSubscription = func(*personal.Client, context.Context, string) (*personal.Subscription, error) {
return &personal.Subscription{EventKey: personal.EventMention}, nil
}
if _, _, rule, err := ensurePersonalSubscription(context.Background(), client, personal.Identity{}, personalConsumeOptions{SubscribeID: "sub"}); err != nil || rule == "" {
t.Fatalf("default subscription rule = %q, %v", rule, err)
}
personalCreateSubscription = func(*personal.Client, context.Context, personal.CreateSubscriptionRequest) (*personal.Subscription, error) {
return nil, wantErr
}
if _, _, _, err := ensurePersonalSubscription(context.Background(), client, personal.Identity{}, personalConsumeOptions{EventKey: personal.EventMention}); !errors.Is(err, wantErr) {
t.Fatalf("create subscription error = %v", err)
}
}
func TestCrossPlatformCoveragePersonalEventRemainingConsumeCoverage(t *testing.T) {
oldIdentity := personalResolveEventIdentity
oldEnsure := personalEnsureSubscription
oldUpsert := personalUpsertRunState
oldDelete := personalDeleteSubscription
oldRemove := personalRemoveRunStates
oldConsume := personalConsumeRun
oldValidate := personalValidateConsumeConfig
oldConflict := personalValidateNoOutputConflict
oldNewSource := personalNewStreamSource
oldBusRun := personalBusRun
t.Cleanup(func() {
personalResolveEventIdentity = oldIdentity
personalEnsureSubscription = oldEnsure
personalUpsertRunState = oldUpsert
personalDeleteSubscription = oldDelete
personalRemoveRunStates = oldRemove
personalConsumeRun = oldConsume
personalValidateConsumeConfig = oldValidate
personalValidateNoOutputConflict = oldConflict
personalNewStreamSource = oldNewSource
personalBusRun = oldBusRun
})
wantErr := errors.New("consume")
cmd := newPersonalCoverageCommand()
personalResolveEventIdentity = func(context.Context, string, string) (personal.Identity, error) { return personal.Identity{}, wantErr }
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention}); !errors.Is(err, wantErr) {
t.Fatalf("identity error = %v", err)
}
identity := personal.Identity{AccessToken: "token", CorpID: "corp", UserID: "user", ClientID: "client", SourceID: "source"}
personalResolveEventIdentity = func(context.Context, string, string) (personal.Identity, error) { return identity, nil }
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention, Common: commonConsumeOptions{RoutesRaw: []string{"bad-route"}}}); err == nil {
t.Fatal("invalid route succeeded")
}
personalConsumeRun = func(context.Context, consume.Config) error { return wantErr }
_ = cmd.Flags().Set("format", "table")
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention, Common: commonConsumeOptions{DryRun: true, FormatRaw: "bogus"}}); !errors.Is(err, wantErr) {
t.Fatalf("dry-run consume error = %v", err)
}
personalEnsureSubscription = func(context.Context, *personal.Client, personal.Identity, personalConsumeOptions) (*personal.Subscription, string, string, error) {
return nil, "", "", wantErr
}
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention}); !errors.Is(err, wantErr) {
t.Fatalf("ensure subscription error = %v", err)
}
personalEnsureSubscription = func(context.Context, *personal.Client, personal.Identity, personalConsumeOptions) (*personal.Subscription, string, string, error) {
return &personal.Subscription{}, personal.EventMention, "at", nil
}
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention}); err == nil || !strings.Contains(err.Error(), "empty subscribe_id") {
t.Fatalf("empty subscription = %v", err)
}
personalEnsureSubscription = func(context.Context, *personal.Client, personal.Identity, personalConsumeOptions) (*personal.Subscription, string, string, error) {
return &personal.Subscription{SubscribeID: "sub"}, personal.EventMention, "at", nil
}
personalUpsertRunState = func(string, personal.RunState) error { return wantErr }
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention}); !errors.Is(err, wantErr) {
t.Fatalf("state upsert error = %v", err)
}
deletes := 0
personalUpsertRunState = func(string, personal.RunState) error { return nil }
personalDeleteSubscription = func(*personal.Client, context.Context, string) error { deletes++; return nil }
personalRemoveRunStates = func(string, []string) error { return nil }
personalValidateConsumeConfig = func(consume.Config) error { return wantErr }
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention, DebugRawEvents: true}); !errors.Is(err, wantErr) {
t.Fatalf("validate error = %v", err)
}
personalValidateConsumeConfig = func(consume.Config) error { return nil }
_ = cmd.Flags().Set("output", "file")
personalValidateNoOutputConflict = func(consume.Config, string) error { return wantErr }
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention}); !errors.Is(err, wantErr) {
t.Fatalf("output conflict = %v", err)
}
personalValidateNoOutputConflict = func(consume.Config, string) error { return nil }
personalNewStreamSource = func(context.Context, personalStreamSourceOptions) (*source.PersonalSource, error) {
return nil, wantErr
}
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention, Common: commonConsumeOptions{Foreground: true}}); !errors.Is(err, wantErr) || deletes == 0 {
t.Fatalf("foreground source error = %v deletes=%d", err, deletes)
}
before := deletes
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention, Ephemeral: true, Common: commonConsumeOptions{Foreground: true}}); !errors.Is(err, wantErr) || deletes == before {
t.Fatalf("ephemeral source error = %v deletes=%d", err, deletes)
}
personalNewStreamSource = func(context.Context, personalStreamSourceOptions) (*source.PersonalSource, error) { return nil, nil }
personalBusRun = func(context.Context, bus.Config) error { return wantErr }
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention, Common: commonConsumeOptions{Foreground: true}}); !errors.Is(err, wantErr) {
t.Fatalf("bus run error = %v", err)
}
personalConsumeRun = func(context.Context, consume.Config) error { return wantErr }
if err := runPersonalEventConsume(cmd, personalConsumeOptions{EventKey: personal.EventMention}); !errors.Is(err, wantErr) {
t.Fatalf("background consume error = %v", err)
}
}
func TestCrossPlatformCoveragePersonalEventRemainingStatusStopAndInterruptCoverage(t *testing.T) {
oldIdentity := personalResolveEventIdentity
oldFindBus := personalFindBusByIdentity
oldQueryEntry := personalQueryEntry
oldList := personalListSubscriptions
oldDelete := personalDeleteSubscription
oldRemove := personalRemoveRunStates
oldLoad := personalLoadRunStates
oldStop := personalStopBus
oldQueryStatus := personalQueryStatus
oldFindProcess := personalFindProcess
oldSignal := personalSignalProcess
t.Cleanup(func() {
personalResolveEventIdentity = oldIdentity
personalFindBusByIdentity = oldFindBus
personalQueryEntry = oldQueryEntry
personalListSubscriptions = oldList
personalDeleteSubscription = oldDelete
personalRemoveRunStates = oldRemove
personalLoadRunStates = oldLoad
personalStopBus = oldStop
personalQueryStatus = oldQueryStatus
personalFindProcess = oldFindProcess
personalSignalProcess = oldSignal
})
wantErr := errors.New("status-stop")
cmd := newPersonalCoverageCommand()
personalResolveEventIdentity = func(context.Context, string, string) (personal.Identity, error) { return personal.Identity{}, wantErr }
if err := runPersonalEventStatus(cmd, personalStatusOptions{}); !errors.Is(err, wantErr) {
t.Fatalf("status identity error = %v", err)
}
if err := runPersonalEventStop(cmd, personalStopOptions{SubscribeID: "sub"}); !errors.Is(err, wantErr) {
t.Fatalf("stop identity error = %v", err)
}
identity := personal.Identity{ClientID: "client", SourceID: "source"}
personalResolveEventIdentity = func(context.Context, string, string) (personal.Identity, error) { return identity, nil }
entry := &busctl.BusEntry{State: busctl.BusStateRunning}
personalFindBusByIdentity = func(string, string, dwsevent.SourceKind, string) *busctl.BusEntry { return entry }
personalQueryEntry = func(busctl.BusEntry) busctl.EntryStatus { return busctl.EntryStatus{Entry: *entry} }
personalListSubscriptions = func(*personal.Client, context.Context, personal.ListOptions) ([]personal.Subscription, error) {
return nil, wantErr
}
if err := runPersonalEventStatus(cmd, personalStatusOptions{}); !errors.Is(err, wantErr) {
t.Fatalf("status list error = %v", err)
}
personalListSubscriptions = func(*personal.Client, context.Context, personal.ListOptions) ([]personal.Subscription, error) {
return nil, nil
}
if err := runPersonalEventStatus(cmd, personalStatusOptions{Status: "all", Format: "json"}); err != nil {
t.Fatalf("status entry JSON = %v", err)
}
personalLoadRunStates = func(string) ([]personal.RunState, error) { return nil, wantErr }
if err := runPersonalEventStop(cmd, personalStopOptions{All: true}); !errors.Is(err, wantErr) {
t.Fatalf("stop targets error = %v", err)
}
personalDeleteSubscription = func(*personal.Client, context.Context, string) error { return wantErr }
if err := runPersonalEventStop(cmd, personalStopOptions{SubscribeID: "sub"}); !errors.Is(err, wantErr) {
t.Fatalf("delete error = %v", err)
}
personalDeleteSubscription = func(*personal.Client, context.Context, string) error { return nil }
personalRemoveRunStates = func(string, []string) error { return wantErr }
if err := runPersonalEventStop(cmd, personalStopOptions{SubscribeID: "sub"}); !errors.Is(err, wantErr) {
t.Fatalf("remove error = %v", err)
}
personalRemoveRunStates = func(string, []string) error { return nil }
personalQueryStatus = func(string) (*eventtransport.StatusResp, error) { return nil, wantErr }
personalLoadRunStates = func(string) ([]personal.RunState, error) { return nil, wantErr }
if err := runPersonalEventStop(cmd, personalStopOptions{SubscribeID: "sub"}); !errors.Is(err, wantErr) {
t.Fatalf("remaining state error = %v", err)
}
personalQueryStatus = func(string) (*eventtransport.StatusResp, error) {
return &eventtransport.StatusResp{Consumers: []eventtransport.StatusConsumer{{SubscribeID: "sub", PID: 123}}}, nil
}
personalFindProcess = func(int) (*os.Process, error) { return nil, wantErr }
personalLoadRunStates = func(string) ([]personal.RunState, error) { return []personal.RunState{{SubscribeID: "other"}}, nil }
if err := runPersonalEventStop(cmd, personalStopOptions{SubscribeID: "sub"}); err != nil {
t.Fatalf("interrupt warning stop = %v", err)
}
personalLoadRunStates = func(string) ([]personal.RunState, error) { return []personal.RunState{{SubscribeID: "other"}}, nil }
if err := runPersonalEventStop(cmd, personalStopOptions{SubscribeID: "sub"}); err != nil {
t.Fatalf("remaining bus stop = %v", err)
}
personalLoadRunStates = func(string) ([]personal.RunState, error) { return nil, nil }
personalStopBus = func(busctl.StopConfig) error { return busctl.ErrNotRunning }
if err := runPersonalEventStop(cmd, personalStopOptions{SubscribeID: "sub"}); err != nil {
t.Fatalf("not running stop = %v", err)
}
personalStopBus = func(busctl.StopConfig) error { return wantErr }
if err := runPersonalEventStop(cmd, personalStopOptions{SubscribeID: "sub"}); !errors.Is(err, wantErr) {
t.Fatalf("bus stop error = %v", err)
}
personalLoadRunStates = func(string) ([]personal.RunState, error) {
return []personal.RunState{{}, {SubscribeID: "b"}, {SubscribeID: "a"}}, nil
}
if got, err := personalStopTargets("", "", true); err != nil || strings.Join(got, ",") != "a,b" {
t.Fatalf("stop target filtering = %#v, %v", got, err)
}
status := &eventtransport.StatusResp{Consumers: []eventtransport.StatusConsumer{
{SubscribeID: "other", PID: 1},
{SubscribeID: "sub", PID: 0},
{SubscribeID: "sub", PID: os.Getpid()},
{SubscribeID: "sub", PID: 123},
{SubscribeID: "sub", PID: 123},
}}
personalQueryStatus = func(string) (*eventtransport.StatusResp, error) { return status, nil }
personalFindProcess = func(int) (*os.Process, error) { return nil, wantErr }
if err := interruptPersonalConsumers("ipc", []string{" sub ", ""}); !errors.Is(err, wantErr) {
t.Fatalf("find process error = %v", err)
}
proc := &os.Process{}
personalFindProcess = func(int) (*os.Process, error) { return proc, nil }
personalSignalProcess = func(*os.Process, os.Signal) error { return wantErr }
if err := interruptPersonalConsumers("ipc", []string{"sub"}); !errors.Is(err, wantErr) {
t.Fatalf("signal process error = %v", err)
}
personalSignalProcess = func(*os.Process, os.Signal) error { return os.ErrProcessDone }
if err := interruptPersonalConsumers("ipc", []string{"sub"}); err != nil {
t.Fatalf("completed process signal = %v", err)
}
}
func TestCrossPlatformCoveragePersonalEventRemainingIdentityAndSourceCoverage(t *testing.T) {
oldAux := personalResolveAuxiliaryAccessToken
oldLoad := personalLoadTokenData
oldClientID := personalClientID
oldCredentials := personalResolveAppCredentialsStrict
oldEdition := edition.Get()
t.Cleanup(func() {
personalResolveAuxiliaryAccessToken = oldAux
personalLoadTokenData = oldLoad
personalClientID = oldClientID
personalResolveAppCredentialsStrict = oldCredentials
edition.Override(oldEdition)
})
wantErr := errors.New("identity")
personalResolveAuxiliaryAccessToken = func(context.Context, string, string) (string, error) { return "", wantErr }
if _, err := resolvePersonalEventIdentity(context.Background(), "", ""); !errors.Is(err, wantErr) {
t.Fatalf("aux token error = %v", err)
}
personalResolveAuxiliaryAccessToken = func(context.Context, string, string) (string, error) { return "access", nil }
personalLoadTokenData = func(string) (*authpkg.TokenData, error) { return nil, nil }
personalClientID = func() string { return "" }
personalResolveAppCredentialsStrict = func(string) (string, string, authpkg.CredentialSource, authpkg.CredentialSource, error) {
return "resolved", "secret", "", "", nil
}
edition.Override(&edition.Hooks{RuntimeDefaults: func() map[string]edition.RuntimeDefaultFn {
return map[string]edition.RuntimeDefaultFn{
"$corpId": func(context.Context) (string, bool) { return " corp ", true },
"$currentUserId": func(context.Context) (string, bool) { return " user ", true },
}
}})
if got, err := resolvePersonalEventIdentity(context.Background(), "", "source"); err != nil || got.ClientID != "resolved" || got.CorpID != "corp" {
t.Fatalf("resolved identity = %#v, %v", got, err)
}
personalResolveAppCredentialsStrict = func(string) (string, string, authpkg.CredentialSource, authpkg.CredentialSource, error) {
return "", "", "", "", wantErr
}
edition.Override(&edition.Hooks{})
if _, err := resolvePersonalEventIdentity(context.Background(), "", ""); err == nil {
t.Fatal("missing client ID succeeded")
}
if got := resolveRuntimeDefault(context.Background(), "missing"); got != "" {
t.Fatalf("missing runtime default = %q", got)
}
if _, err := newPersonalStreamSource(context.Background(), personalStreamSourceOptions{ConfigDir: "", Identity: personal.Identity{}, TicketMode: "custom"}); !errors.Is(err, wantErr) {
t.Fatalf("custom credential error = %v", err)
}
personalResolveAppCredentialsStrict = func(string) (string, string, authpkg.CredentialSource, authpkg.CredentialSource, error) {
return "resolved", "secret", "", "", nil
}
if src, err := newPersonalStreamSource(context.Background(), personalStreamSourceOptions{Identity: personal.Identity{AccessToken: "token", SourceID: "source"}, TicketMode: "custom"}); err != nil || src == nil {
t.Fatalf("custom resolved source = %#v, %v", src, err)
}
if got := personalEventStreamSourceID(""); got != "open" {
t.Fatalf("default stream source = %q", got)
}
if got := configuredMCPBaseURL(""); got != "" {
t.Fatalf("default missing configured MCP = %q", got)
}
}
func newPersonalCoverageCommand() *cobra.Command {
cmd := &cobra.Command{Use: "event"}
cmd.SetContext(context.Background())
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
cmd.Flags().String("format", "table", "")
cmd.Flags().String("output", "", "")
return cmd
}
var _ = time.Second
+38 -273
View File
@@ -18,9 +18,7 @@ import (
"encoding/json"
"strings"
"testing"
"time"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/personal"
"github.com/spf13/cobra"
)
@@ -45,18 +43,8 @@ func TestPersonalEventListHidesSchemaIDs(t *testing.T) {
}
got := out.String()
assertPersonalOutputHidesSchemaIDs(t, got)
for _, eventKey := range []string{
personal.EventFromUser,
personal.EventReadO2O,
personal.EventReadGroup,
personal.EventRecallO2O,
personal.EventRecallGroup,
personal.EventReactionO2O,
personal.EventReactionGroup,
} {
if !strings.Contains(got, eventKey) {
t.Fatalf("list output missing %s: %s", eventKey, got)
}
if strings.Contains(got, personal.EventFromUser) {
t.Fatalf("list output exposed hidden event %s: %s", personal.EventFromUser, got)
}
})
}
@@ -76,8 +64,8 @@ func TestEventListDefaultsToUser(t *testing.T) {
if !strings.Contains(got, personal.EventSingleChat) || !strings.Contains(got, "EVENT_KEY") {
t.Fatalf("list output = %s, want personal event catalog", got)
}
if !strings.Contains(got, personal.EventFromUser) {
t.Fatalf("list output missing public event %s: %s", personal.EventFromUser, got)
if strings.Contains(got, personal.EventFromUser) {
t.Fatalf("list output exposed hidden event %s: %s", personal.EventFromUser, got)
}
if strings.Contains(got, "CLIENT_ID") || strings.Contains(got, "ClientSecret") {
t.Fatalf("list default appears to use legacy application output: %s", got)
@@ -188,44 +176,7 @@ func TestPersonalEventSchemaHidesSchemaIDs(t *testing.T) {
}
}
func TestPersonalEventSchemaDefaultsToTransportEnvelope(t *testing.T) {
cmd := newEventSchemaCommand()
cmd.SilenceUsage = true
cmd.SilenceErrors = true
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetArgs([]string{personal.EventSingleChat})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v", err)
}
var doc map[string]any
if err := json.Unmarshal(out.Bytes(), &doc); err != nil {
t.Fatalf("schema output is not JSON: %v\n%s", err, out.String())
}
if doc["jq_root_path"] != ".data | fromjson" {
t.Fatalf("jq_root_path = %#v, want .data | fromjson", doc["jq_root_path"])
}
schema, ok := doc["schema"].(map[string]any)
if !ok {
t.Fatalf("schema = %#v, want object", doc["schema"])
}
props, ok := schema["properties"].(map[string]any)
if !ok {
t.Fatalf("schema.properties = %#v, want object", schema["properties"])
}
for _, field := range []string{"type", "seq", "event_type", "data", "headers", "subscribe_id"} {
if _, ok := props[field]; !ok {
t.Fatalf("default envelope schema missing %q: %#v", field, props)
}
}
for _, field := range []string{"content", "sender", "conversation_id", "timestamp"} {
if _, ok := props[field]; ok {
t.Fatalf("default envelope schema unexpectedly contains flat field %q", field)
}
}
}
func TestPersonalEventFlattenedSchemaUsesSingleJSONSchema(t *testing.T) {
func TestPersonalEventSchemaUsesSingleJSONSchema(t *testing.T) {
for _, eventKey := range []string{
personal.EventMention,
personal.EventSingleChat,
@@ -237,7 +188,7 @@ func TestPersonalEventFlattenedSchemaUsesSingleJSONSchema(t *testing.T) {
cmd.SilenceErrors = true
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetArgs([]string{eventKey, "--flatten"})
cmd.SetArgs([]string{eventKey})
if err := cmd.Execute(); err != nil {
t.Fatalf("Execute() error = %v", err)
}
@@ -295,8 +246,8 @@ func TestPersonalEventFlattenedSchemaUsesSingleJSONSchema(t *testing.T) {
t.Fatalf("schema output for %s leaked %q: %s", eventKey, leaked, got)
}
}
if doc["jq_root_path"] != "." {
t.Fatalf("jq_root_path = %#v, want .", doc["jq_root_path"])
if doc["jq_root_path"] != ".data | fromjson" {
t.Fatalf("jq_root_path = %#v, want .data | fromjson", doc["jq_root_path"])
}
schema, ok := doc["schema"].(map[string]any)
if !ok {
@@ -313,80 +264,6 @@ func TestPersonalEventFlattenedSchemaUsesSingleJSONSchema(t *testing.T) {
}
}
func TestPersonalActionEventSchemaMatchesFlatOutput(t *testing.T) {
tests := []struct {
eventKeys []string
properties []string
}{
{
eventKeys: []string{personal.EventReadO2O, personal.EventReadGroup},
properties: []string{
"type", "event_id", "timestamp", "subscribe_id", "message_id",
"conversation_id", "reader", "reader_open_dingtalk_id", "sender",
"sender_open_dingtalk_id", "read_time", "event_time",
},
},
{
eventKeys: []string{personal.EventRecallO2O, personal.EventRecallGroup},
properties: []string{
"type", "event_id", "timestamp", "subscribe_id", "message_id",
"conversation_id", "recaller", "recaller_open_dingtalk_id", "sender",
"sender_open_dingtalk_id", "recall_time", "event_time",
},
},
{
eventKeys: []string{personal.EventReactionO2O, personal.EventReactionGroup},
properties: []string{
"type", "event_id", "timestamp", "subscribe_id", "message_id",
"conversation_id", "operator", "operator_open_dingtalk_id", "reaction_name",
"reaction_text", "operation_type", "operation_time", "sender",
"sender_open_dingtalk_id", "event_time",
},
},
}
for _, tt := range tests {
for _, eventKey := range tt.eventKeys {
t.Run(eventKey, func(t *testing.T) {
cmd := newEventSchemaCommand()
cmd.SilenceUsage = true
cmd.SilenceErrors = true
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetArgs([]string{eventKey, "--flatten"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
var doc map[string]any
if err := json.Unmarshal(out.Bytes(), &doc); err != nil {
t.Fatalf("schema output is not JSON: %v\n%s", err, out.String())
}
if doc["event_key"] != eventKey || doc["jq_root_path"] != "." {
t.Fatalf("schema metadata = %#v", doc)
}
schema, ok := doc["schema"].(map[string]any)
if !ok {
t.Fatalf("schema = %#v", doc["schema"])
}
properties, ok := schema["properties"].(map[string]any)
if !ok || len(properties) != len(tt.properties) {
t.Fatalf("schema.properties = %#v, want exactly %d flat fields", schema["properties"], len(tt.properties))
}
for _, field := range tt.properties {
if _, ok := properties[field]; !ok {
t.Fatalf("schema missing %q: %#v", field, properties)
}
}
for _, internal := range []string{"payload", "uid", "corpid", "clientId", "filterSubId", "bizid"} {
if _, ok := properties[internal]; ok {
t.Fatalf("schema exposed internal property %q", internal)
}
}
})
}
}
}
func TestEventSchemaDefaultsToUser(t *testing.T) {
cmd := newEventSchemaCommand()
cmd.SilenceUsage = true
@@ -404,152 +281,40 @@ func TestEventSchemaDefaultsToUser(t *testing.T) {
if doc["event_key"] != personal.EventSingleChat {
t.Fatalf("event_key = %#v, want %s", doc["event_key"], personal.EventSingleChat)
}
if doc["jq_root_path"] != ".data | fromjson" {
t.Fatalf("jq_root_path = %#v, want default envelope path", doc["jq_root_path"])
}
}
func TestPersonalEventFromUserIsPubliclyAvailable(t *testing.T) {
if err := ensurePublicPersonalEvent(personal.EventFromUser); err != nil {
t.Fatalf("ensurePublicPersonalEvent() error = %v", err)
}
schemaCmd := newEventSchemaCommand()
schemaCmd.SilenceUsage = true
schemaCmd.SilenceErrors = true
var schemaOut bytes.Buffer
schemaCmd.SetOut(&schemaOut)
schemaCmd.SetArgs([]string{personal.EventFromUser})
if err := schemaCmd.Execute(); err != nil {
t.Fatalf("schema Execute() error = %v", err)
}
var doc map[string]any
if err := json.Unmarshal(schemaOut.Bytes(), &doc); err != nil {
t.Fatalf("schema output is not JSON: %v\n%s", err, schemaOut.String())
}
if doc["event_key"] != personal.EventFromUser || doc["rule_type"] != "sender" {
t.Fatalf("schema document = %#v", doc)
}
configDir := setupPersonalIdentityToken(t, &authpkg.TokenData{
AccessToken: "access-1",
RefreshToken: "refresh-1",
ExpiresAt: time.Now().Add(time.Hour),
RefreshExpAt: time.Now().Add(24 * time.Hour),
CorpID: "corp-1",
UserID: "user-1",
ClientID: "client-1",
})
t.Setenv("DWS_CONFIG_DIR", configDir)
consumeCmd := newEventConsumeCommand()
consumeCmd.SilenceUsage = true
consumeCmd.SilenceErrors = true
consumeCmd.SetArgs([]string{personal.EventFromUser, "--user", "test-user-001", "--dry-run"})
if err := consumeCmd.Execute(); err != nil {
t.Fatalf("consume dry-run Execute() error = %v", err)
}
openIDConsumeCmd := newEventConsumeCommand()
openIDConsumeCmd.SilenceUsage = true
openIDConsumeCmd.SilenceErrors = true
openIDConsumeCmd.SetArgs([]string{personal.EventFromUser, "--open-dingtalk-id", "open-user-1", "--dry-run"})
if err := openIDConsumeCmd.Execute(); err != nil {
t.Fatalf("consume openDingtalkId dry-run Execute() error = %v", err)
}
conflictingTargetCmd := newEventConsumeCommand()
conflictingTargetCmd.SilenceUsage = true
conflictingTargetCmd.SilenceErrors = true
conflictingTargetCmd.SetArgs([]string{personal.EventFromUser, "--user", "test-user-001", "--open-dingtalk-id", "open-user-1", "--dry-run"})
err := conflictingTargetCmd.Execute()
if err == nil || !strings.Contains(err.Error(), "--user and --open-dingtalk-id are mutually exclusive for "+personal.EventFromUser) {
t.Fatalf("conflicting target identity error = %v", err)
}
groupOpenIDCmd := newEventConsumeCommand()
groupOpenIDCmd.SilenceUsage = true
groupOpenIDCmd.SilenceErrors = true
groupOpenIDCmd.SetArgs([]string{personal.EventInChat, "--group", "cid-1", "--open-dingtalk-id", "open-user-1", "--dry-run"})
err = groupOpenIDCmd.Execute()
if err == nil || !strings.Contains(err.Error(), "--open-dingtalk-id is not supported for "+personal.EventInChat+"; use --group") {
t.Fatalf("group openDingtalkId error = %v", err)
}
missingUserCmd := newEventConsumeCommand()
missingUserCmd.SilenceUsage = true
missingUserCmd.SilenceErrors = true
missingUserCmd.SetArgs([]string{personal.EventFromUser})
err = missingUserCmd.Execute()
if err == nil || !strings.Contains(err.Error(), "one of --user or --open-dingtalk-id is required for "+personal.EventFromUser) {
t.Fatalf("missing target identity error = %v", err)
}
}
func TestEventConsumeCobraSchemaIncludesOpenDingTalkID(t *testing.T) {
root := NewRootCommand()
root.SilenceUsage = true
root.SilenceErrors = true
var out bytes.Buffer
root.SetOut(&out)
root.SetArgs([]string{"schema", "event consume"})
if err := root.Execute(); err != nil {
t.Fatalf("schema event consume Execute() error = %v", err)
}
var doc map[string]any
if err := json.Unmarshal(out.Bytes(), &doc); err != nil {
t.Fatalf("schema output is not JSON: %v\n%s", err, out.String())
}
params, ok := doc["parameters"].(map[string]any)
if !ok {
t.Fatalf("schema parameters = %#v", doc["parameters"])
}
if _, ok := params["open-dingtalk-id"]; !ok {
t.Fatalf("schema parameters missing open-dingtalk-id: %#v", params)
}
if _, ok := params["odid"]; ok {
t.Fatalf("schema parameters unexpectedly include odid alias: %#v", params)
}
if _, ok := params["flatten"]; !ok {
t.Fatalf("schema parameters missing flatten: %#v", params)
}
for _, name := range []string{"user", "open-dingtalk-id", "group"} {
param, ok := params[name].(map[string]any)
if !ok {
t.Fatalf("schema parameter %s = %#v", name, params[name])
}
if got, exists := param["required_when"]; exists {
t.Fatalf("schema parameter %s unexpectedly declares required_when = %#v", name, got)
}
}
constraints, ok := doc["constraints"].(map[string]any)
if !ok {
t.Fatalf("schema constraints = %#v", doc["constraints"])
}
assertJSONConstraintGroup := func(field string, want []string) {
t.Helper()
groups, ok := constraints[field].([]any)
if !ok {
t.Fatalf("schema constraint %s = %#v", field, constraints[field])
}
for _, rawGroup := range groups {
group, ok := rawGroup.([]any)
if !ok || len(group) != len(want) {
continue
func TestPersonalEventFromUserIsNotPubliclyAvailable(t *testing.T) {
for _, tc := range []struct {
name string
cmd *cobra.Command
args []string
}{
{
name: "schema",
cmd: newEventSchemaCommand(),
args: []string{personal.EventFromUser},
},
{
name: "consume",
cmd: newEventConsumeCommand(),
args: []string{personal.EventFromUser, "--user", "507971", "--dry-run"},
},
{
name: "status",
cmd: newEventStatusCommand(),
args: []string{"--event", personal.EventFromUser},
},
} {
t.Run(tc.name, func(t *testing.T) {
tc.cmd.SilenceUsage = true
tc.cmd.SilenceErrors = true
tc.cmd.SetArgs(tc.args)
err := tc.cmd.Execute()
if err == nil || !strings.Contains(err.Error(), "event "+personal.EventFromUser+" is not publicly available yet") {
t.Fatalf("Execute() error = %v, want not publicly available", err)
}
matched := true
for i := range want {
if group[i] != want[i] {
matched = false
break
}
}
if matched {
return
}
}
t.Fatalf("schema constraint %s = %#v, missing %#v", field, groups, want)
})
}
assertJSONConstraintGroup("require_one_of", []string{"event_key", "subscribe-id"})
}
func TestPersonalEventSchemaRejectsTableFormat(t *testing.T) {
+2 -3
View File
@@ -41,18 +41,17 @@ func TestShouldWatchStdinEOF_BoundedIsNeverArmed(t *testing.T) {
func TestPersonalBusSpawnArgs_ForwardsProfile(t *testing.T) {
args := personalBusSpawnArgs(personal.Identity{
CorpID: "dinga626d60c1128d449",
UserID: "user_123",
SourceID: "open",
}, "", "")
found := false
for i := 0; i+1 < len(args); i++ {
if args[i] == "--profile" && args[i+1] == "dinga626d60c1128d449:user_123" {
if args[i] == "--profile" && args[i+1] == "dinga626d60c1128d449" {
found = true
break
}
}
if !found {
t.Errorf("spawn args must forward --profile <corpId>:<userId>; got %v", args)
t.Errorf("spawn args must forward --profile <corpId>; got %v", args)
}
// No CorpID → no --profile appended (avoid an empty flag value).
+1 -1
View File
@@ -47,7 +47,7 @@ func bindPersistentFlags(cmd *cobra.Command, flags *GlobalFlags) {
cmd.PersistentFlags().BoolVar(&flags.Mock, "mock", false, "使用 Mock 数据 (开发调试用)")
cmd.PersistentFlags().StringVarP(&flags.Output, "output", "o", "", "Write command output to a file")
_ = cmd.PersistentFlags().MarkHidden("output")
cmd.PersistentFlags().StringVar(&flags.Profile, "profile", "", "一次性指定组织或账号;支持 corpId/corpName 与 userId/userName 组合,推荐使用 profile list 返回的 corpId:userId;多个按 CSV 逗号分隔")
cmd.PersistentFlags().StringVar(&flags.Profile, "profile", "", "一次性指定本次命令使用的组织 profile 名或 corpId;多个按 CSV 逗号分隔,如 corpA,corpB")
cmd.PersistentFlags().IntVar(&flags.Timeout, "timeout", 30, "HTTP 请求超时时间 (秒)")
cmd.PersistentFlags().StringVar(&flags.Token, "token", "", "Override the configured API token")
_ = cmd.PersistentFlags().MarkHidden("token")
+17 -40
View File
@@ -23,56 +23,33 @@ import (
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
)
type accessTokenGetter interface {
GetAccessToken(context.Context) (string, error)
}
type rejectedAccessTokenRefresher interface {
ForceRefreshRejectedToken(context.Context, string) (string, error)
}
var (
loadRefreshTokenData = authpkg.LoadTokenData
newRefreshProvider = func(configDir string) rejectedAccessTokenRefresher {
disc := slog.New(slog.NewTextHandler(io.Discard, nil))
provider := authpkg.NewOAuthProvider(configDir, disc)
configureOAuthProviderCompatibility(provider, configDir)
return provider
}
)
// ForceRefreshAccessToken forces a single refresh_token exchange and returns
// the new access_token. It is intended for callers that have observed a
// server-side rejection (HTTP 401 or business code such as
// TOKEN_VERIFIED_FAILED) on what locally appeared to be a still-valid token.
//
// It snapshots the current access token, then delegates to the OAuth
// provider's dual-locked compare-and-refresh operation. If another caller has
// already rotated the token, that newer token is reused without another
// refresh request.
// Steps:
// 1. MarkAccessTokenStale rewrites ExpiresAt to a past instant so
// OAuthProvider.GetAccessToken's fast-path will miss.
// 2. NewOAuthProvider + GetAccessToken triggers lockedRefresh, which uses the
// existing dual-layer lock (process + file) to serialize concurrent
// refresh attempts across goroutines and processes.
// 3. ResetRuntimeTokenCache clears the per-process sync.Once cache so the
// next resolveAuthToken call re-reads from disk.
//
// Existing OAuthProvider.GetAccessToken behaviour is unchanged; this helper
// is the only entry point that orchestrates "force refresh" semantics.
func ForceRefreshAccessToken(ctx context.Context, configDir string) (string, error) {
if strings.TrimSpace(configDir) == "" {
return "", fmt.Errorf("config directory is empty")
}
data, err := loadRefreshTokenData(configDir)
if err != nil {
return "", err
if err := authpkg.MarkAccessTokenStale(configDir); err != nil {
return "", fmt.Errorf("mark access token stale: %w", err)
}
if data == nil || strings.TrimSpace(data.AccessToken) == "" {
return "", fmt.Errorf("stored access token is empty")
}
return forceRefreshRejectedAccessToken(ctx, configDir, data.AccessToken)
}
func forceRefreshRejectedAccessToken(ctx context.Context, configDir, rejectedAccessToken string) (string, error) {
if strings.TrimSpace(configDir) == "" {
return "", fmt.Errorf("config directory is empty")
}
if strings.TrimSpace(rejectedAccessToken) == "" {
return "", fmt.Errorf("rejected access token is empty")
}
provider := newRefreshProvider(configDir)
tok, err := provider.ForceRefreshRejectedToken(ctx, rejectedAccessToken)
disc := slog.New(slog.NewTextHandler(io.Discard, nil))
provider := authpkg.NewOAuthProvider(configDir, disc)
configureOAuthProviderCompatibility(provider, configDir)
tok, err := provider.GetAccessToken(ctx)
if err != nil {
return "", err
}
+4 -10
View File
@@ -27,27 +27,21 @@ import (
"github.com/spf13/cobra"
)
func newLegacyPublicCommands(runner executor.Runner, caller edition.ToolCaller, loadUserShortcuts bool) []*cobra.Command {
func newLegacyPublicCommands(runner executor.Runner, caller edition.ToolCaller) []*cobra.Command {
injectStaticServers()
helpers.InitDeps(caller)
commands := helpers.NewPublicCommands(runner)
// Load user-defined shortcuts (~/.dws/shortcuts/*.yaml) BEFORE compiling the
// command tree, so distilled high-frequency operations mount alongside the
// built-ins. Conflicts with built-ins are skipped inside Load.
if loadUserShortcuts {
if _, err := userdef.Load(); err != nil {
slog.Warn("shortcut: failed to load user-defined shortcuts", "error", err)
}
if _, err := userdef.Load(); err != nil {
slog.Warn("shortcut: failed to load user-defined shortcuts", "error", err)
}
// Built-in + user shortcuts (`dws <service> +<command>`) share the same
// command tree; mergeTopLevelCommands folds each shortcut's service parent
// into the matching helper command so the `+leaf` sits alongside existing
// subcommands.
if loadUserShortcuts {
commands = append(commands, builtin.Commands()...)
} else {
commands = append(commands, builtin.BaseCommands()...)
}
commands = append(commands, builtin.Commands()...)
return mergeTopLevelCommands(commands)
}
+2 -61
View File
@@ -50,9 +50,8 @@ func TestRuntimeRunnerAggregatesCommaSeparatedProfiles(t *testing.T) {
t.Fatalf("profiles[%d].ok = %#v, want true", i, entry["ok"])
}
resultPayload := entry["result"].(map[string]any)
wantProfile := wantCorpID + ":user-" + wantCorpID
if resultPayload["runtimeProfile"] != wantProfile {
t.Fatalf("profiles[%d].result.runtimeProfile = %#v, want %q", i, resultPayload["runtimeProfile"], wantProfile)
if resultPayload["runtimeProfile"] != wantCorpID {
t.Fatalf("profiles[%d].result.runtimeProfile = %#v, want %q", i, resultPayload["runtimeProfile"], wantCorpID)
}
}
}
@@ -76,37 +75,6 @@ func TestRuntimeRunnerDeduplicatesCommaSeparatedProfilesByCorpID(t *testing.T) {
}
}
func TestRuntimeRunnerDeduplicatesByResolvedIdentityInSameCorp(t *testing.T) {
first := authLogoutTestToken("corp_same")
first.UserID = "user_1"
second := authLogoutTestToken("corp_same")
second.AccessToken = "access-second"
second.RefreshToken = "refresh-second"
second.UserID = "user_2"
configDir := setupAuthLogoutProfiles(t, first, second)
selections, multi, err := resolveMultiProfileSelections(
configDir,
"corp_same,corp_same:user_1,corp_same:user_2",
)
if err != nil {
t.Fatalf("resolveMultiProfileSelections() error = %v", err)
}
if !multi {
t.Fatal("multi = false, want true")
}
if len(selections) != 2 {
t.Fatalf("selections len = %d, want 2: %#v", len(selections), selections)
}
got := []string{
authpkg.ProfileSelector(selections[0].Profile),
authpkg.ProfileSelector(selections[1].Profile),
}
if strings.Join(got, ",") != "corp_same:user_2,corp_same:user_1" {
t.Fatalf("resolved identities = %v, want current user_2 then user_1", got)
}
}
func TestRuntimeRunnerKeepsSingleProfileBehavior(t *testing.T) {
setupAuthLogoutProfiles(t, authLogoutTestToken("corp_a"), authLogoutTestToken("corp_b"))
authpkg.SetRuntimeProfile("corp_a")
@@ -123,38 +91,11 @@ func TestRuntimeRunnerKeepsSingleProfileBehavior(t *testing.T) {
if _, ok := result.Response["content"].(map[string]any)["multiProfile"]; ok {
t.Fatalf("single profile unexpectedly returned aggregate content: %#v", result.Response)
}
if got := result.Response["content"].(map[string]any)["runtimeProfile"]; got != "corp_a:user-corp_a" {
t.Fatalf("fallback runtime profile = %#v, want exact identity selector", got)
}
if got := authpkg.RuntimeProfile(); got != "corp_a" {
t.Fatalf("runtime profile after Run = %q, want corp_a", got)
}
}
func TestRuntimeRunnerRejectsAmbiguousSingleProfile(t *testing.T) {
first := authLogoutTestToken("corp_first")
first.CorpName = "Shared Org"
second := authLogoutTestToken("corp_second")
second.CorpName = "Shared Org"
setupAuthLogoutProfiles(t, first, second)
authpkg.SetRuntimeProfile("Shared Org")
runner := &runtimeRunner{fallback: multiProfileFallbackRunner{}}
_, err := runner.Run(context.Background(), executor.Invocation{
Kind: "helper_invocation",
CanonicalProduct: "contact",
Tool: "get_current_user_profile",
})
if err == nil {
t.Fatal("Run() accepted ambiguous single profile selector")
}
for _, candidate := range []string{"corp_first", "corp_second"} {
if !strings.Contains(err.Error(), candidate) {
t.Fatalf("error = %q, want candidate %q", err.Error(), candidate)
}
}
}
func TestCommaNamedProfileStillResolvesAsSingleProfile(t *testing.T) {
configDir := setupAuthLogoutProfiles(t, authLogoutTestToken("corp_comma"), authLogoutTestToken("corp_other"))
cfg, err := authpkg.LoadProfiles(configDir)
+45 -62
View File
@@ -48,26 +48,10 @@ const (
PatAuthPollInterval = 5 * time.Second
patScopeAuthRequiredCode = "PAT_SCOPE_AUTH_REQUIRED"
patOrgPolicyDeniedCode = "PAT_ORG_POLICY_DENIED"
)
var openBrowserFunc = tryOpenBrowser
var (
patAuthorizationTimeout = PatAuthRetryTimeout
patAuthorizationPollInterval = PatAuthPollInterval
patResolveAccessToken = ResolveAuxiliaryAccessToken
patWaitForAuthorization = WaitForPatAuthorization
patPollDeviceFlowWithInterval = pollPatDeviceFlowWithInterval
patSaveAppConfig = authpkg.SaveAppConfig
patExchangeCodeForToken = authpkg.ExchangeCodeForToken
patSaveTokenData = authpkg.SaveTokenData
patSleep = time.Sleep
patPollHTTPDo = (*http.Client).Do
patPollNewRequest = http.NewRequestWithContext
patBrowserOpenCommand = browserOpenCommand
)
type patSuppressBrowserOpenKeyType struct{}
var patSuppressBrowserOpenKey = patSuppressBrowserOpenKeyType{}
@@ -250,13 +234,12 @@ func enrichPATErrorWithOpenBrowser(raw string, openBrowser bool) string {
delete(data, "authUrl")
delete(data, "authorizationUrl")
}
if code, _ := payload["code"].(string); code == "PAT_ORG_POLICY_DENIED" {
data["openBrowser"] = false
} else {
data["openBrowser"] = openBrowser
}
data["openBrowser"] = openBrowser
encoded, _ := marshalSingleLineJSONNoHTMLEscape(payload)
encoded, err := marshalSingleLineJSONNoHTMLEscape(payload)
if err != nil {
return raw
}
return string(encoded)
}
@@ -272,10 +255,10 @@ func patAuthorizationURIFromData(data map[string]any) string {
// WaitForPatAuthorization polls until the user completes authorization or timeout.
// It returns true if authorization was completed, false if timed out or cancelled.
func WaitForPatAuthorization(ctx context.Context, configDir string, output io.Writer) (bool, error) {
timeout := patAuthorizationTimeout
func WaitForPatAuthorization(ctx context.Context, configDir string, output io.Writer) bool {
timeout := PatAuthRetryTimeout
deadline := time.Now().Add(timeout)
pollTicker := time.NewTicker(patAuthorizationPollInterval)
pollTicker := time.NewTicker(PatAuthPollInterval)
defer pollTicker.Stop()
start := time.Now()
@@ -290,26 +273,27 @@ func WaitForPatAuthorization(ctx context.Context, configDir string, output io.Wr
select {
case <-ctx.Done():
fmt.Fprintf(output, "%s 操作已取消\n", tui.StateMark("error"))
return false, ctx.Err()
return false
case <-time.After(time.Until(deadline)):
fmt.Fprintf(output, "%s 等待授权超时 (%s)\n", tui.StateMark("error"), timeout)
fmt.Fprintf(output, " %s 请重新执行命令\n", tui.Dim("ℹ"))
return false, nil
return false
case <-pollTicker.C:
pollCount++
elapsed := time.Since(start).Truncate(time.Second)
remaining := time.Until(deadline).Truncate(time.Second)
// Check the same resolver used by every outbound bearer request.
if _, err := patResolveAccessToken(ctx, configDir, ""); err == nil {
fmt.Fprintf(output, "\r%s %s (%s 已用, %s 剩余) \n",
tui.StateMark("ok"), tui.Bold("授权成功!"), elapsed, remaining)
fmt.Fprintln(output)
return true, nil
} else if !stderrors.Is(err, authpkg.ErrTokenDataNotFound) {
return false, fmt.Errorf("check authorization token: %w", err)
// Check if token is now valid
tokenData, err := authpkg.LoadTokenData(configDir)
if err == nil && tokenData != nil {
if tokenData.IsAccessTokenValid() || tokenData.IsRefreshTokenValid() {
fmt.Fprintf(output, "\r%s %s (%s 已用, %s 剩余) \n",
tui.StateMark("ok"), tui.Bold("授权成功!"), elapsed, remaining)
fmt.Fprintln(output)
return true
}
}
// Show polling status
@@ -339,10 +323,7 @@ func retryWithPatAuthRetry(ctx context.Context, runner executor.Runner, invocati
PrintPatAuthError(output, scopeErr)
// Wait for user to complete authorization
authorized, waitErr := patWaitForAuthorization(ctx, configDir, output)
if waitErr != nil {
return executor.Result{}, waitErr
}
authorized := WaitForPatAuthorization(ctx, configDir, output)
if !authorized {
return executor.Result{}, apperrors.NewAuth(
"等待用户授权超时",
@@ -519,15 +500,6 @@ func handlePatAuthCheck(
if patData.Data.URI == "" {
patData.Data.URI = patData.Data.AuthorizationURL
}
// Organization-policy denial is terminal until an administrator changes
// the policy. Return it before reading browser policy, mutating process-wide
// credentials, opening a browser, polling, or retrying the invocation even
// when a lenient backend also supplies active-flow fields.
if patData.Code == patOrgPolicyDeniedCode {
return executor.Result{}, &apperrors.PATError{
RawJSON: enrichPATErrorWithOpenBrowser(patErr.RawJSON, false),
}
}
slog.Debug("PAT auth check",
"clientId", patData.Data.ClientID,
@@ -607,7 +579,7 @@ func handlePatAuthCheck(
pollCtx, cancel := context.WithTimeout(ctx, patPollTimeout)
defer cancel()
status, authCode, err := patPollDeviceFlowWithInterval(
status, authCode, err := pollPatDeviceFlowWithInterval(
pollCtx, patData.Data.FlowID, configDir, output,
resolvePATPollInterval(patData.Data.PollIntervalSecs),
)
@@ -622,7 +594,7 @@ func handlePatAuthCheck(
fmt.Fprintln(output)
if appCfg != nil {
if err := patSaveAppConfig(configDir, appCfg); err != nil {
if err := authpkg.SaveAppConfig(configDir, appCfg); err != nil {
slog.Warn("failed to persist approved app config from PAT", "error", err)
fmt.Fprintf(output, " \u26a0 保存应用配置失败: %v (下次启动可能需要重新授权)\n", err)
}
@@ -631,12 +603,12 @@ func handlePatAuthCheck(
// Exchange authCode for a fresh access token (mirrors device_flow loginOnce).
if authCode != "" {
slog.Debug("PAT retry: exchanging authCode for token", "hasCode", true)
tokenData, exchErr := patExchangeCodeForToken(ctx, configDir, authCode)
tokenData, exchErr := authpkg.ExchangeCodeForToken(ctx, configDir, authCode)
if exchErr != nil {
slog.Warn("PAT retry: exchangeCode failed, retrying with existing token", "error", exchErr)
fmt.Fprintf(output, " %s 换取新 token 失败: %v (将使用现有凭证重试)\n", tui.StateMark("warning"), exchErr)
} else {
if err := patSaveTokenData(configDir, tokenData); err != nil {
if err := authpkg.SaveTokenData(configDir, tokenData); err != nil {
slog.Warn("PAT retry: failed to save new token", "error", err)
fmt.Fprintf(output, " %s 保存新 token 失败: %v\n", tui.StateMark("warning"), err)
} else {
@@ -661,7 +633,7 @@ func handlePatAuthCheck(
// Workaround: brief delay to let server-side authorization state propagate
// before retrying. Without this the retry may use stale credentials.
slog.Debug("PAT retry: waiting for server-side state propagation", "delay", "1s")
patSleep(1 * time.Second)
time.Sleep(1 * time.Second)
// Retry the original invocation with pat-retrying flag to prevent recursion.
fmt.Fprintf(output, "%s %s\n", tui.StateMark("ok"), tui.Bold("授权完成,正在重试..."))
@@ -733,7 +705,10 @@ func enrichPATErrorForHostControl(raw string) string {
apperrors.ApplyHostMutations(payload)
// stderr JSON MUST be single-line.
encoded, _ := marshalSingleLineJSONNoHTMLEscape(payload)
encoded, err := marshalSingleLineJSONNoHTMLEscape(payload)
if err != nil {
return raw
}
return string(encoded)
}
@@ -764,7 +739,10 @@ func buildPATScopeJSON(scopeErr *PatScopeError, includeHostControl bool) string
"data": data,
}
// stderr JSON MUST be single-line.
b, _ := jsonutil.Marshal(payload)
b, err := jsonutil.Marshal(payload)
if err != nil {
return `{"success":false,"code":"PAT_SCOPE_AUTH_REQUIRED"}`
}
return string(b)
}
@@ -796,6 +774,12 @@ func pollPatDeviceFlowWithInterval(ctx context.Context, flowID string, configDir
pollURL := fmt.Sprintf("%s%s?flowId=%s",
authpkg.GetMCPBaseURL(), authpkg.DevicePollPath, url.QueryEscape(flowID))
// Load user access token for the poll request header.
var accessToken string
if tokenData, err := authpkg.LoadTokenData(configDir); err == nil && tokenData != nil {
accessToken = tokenData.AccessToken
}
// Use a client that does NOT follow redirects, so we can detect SSO 302.
noRedirectClient := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
@@ -819,19 +803,15 @@ func pollPatDeviceFlowWithInterval(ctx context.Context, flowID string, configDir
pollCount++
fmt.Fprintf(output, "\r%s [%d] 等待授权中... ", tui.Dim("⟳"), pollCount)
req, err := patPollNewRequest(ctx, http.MethodGet, pollURL, nil)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, pollURL, nil)
if err != nil {
slog.Debug("PAT poll: failed to create request", "error", err)
continue
}
accessToken, tokenErr := patResolveAccessToken(ctx, configDir, "")
if tokenErr != nil && !stderrors.Is(tokenErr, authpkg.ErrTokenDataNotFound) {
return "", "", fmt.Errorf("resolve PAT poll access token: %w", tokenErr)
}
if accessToken != "" {
req.Header.Set("x-user-access-token", accessToken)
}
resp, err := patPollHTTPDo(noRedirectClient, req)
resp, err := noRedirectClient.Do(req)
if err != nil {
slog.Debug("PAT poll: request failed", "error", err)
continue // transient network error, keep polling
@@ -878,6 +858,9 @@ func resolvePATPollInterval(seconds int) time.Duration {
return patPollInterval
}
interval := time.Duration(seconds) * time.Second
if interval < time.Second {
return time.Second
}
if interval > patMaxPollInterval {
return patMaxPollInterval
}
@@ -899,7 +882,7 @@ func browserOpenCommand(goos, rawURL string) *exec.Cmd {
// tryOpenBrowser opens rawURL in the default browser; errors are silently ignored.
func tryOpenBrowser(rawURL string) error {
cmd := patBrowserOpenCommand(runtime.GOOS, rawURL)
cmd := browserOpenCommand(runtime.GOOS, rawURL)
if cmd == nil {
return nil
}
@@ -1,283 +0,0 @@
package app
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"os/exec"
"strings"
"testing"
"time"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
)
func TestCrossPlatformCoveragePATRetryRemainingPureAndWaitCoverage(t *testing.T) {
typed := apperrors.NewAPI("ordinary", apperrors.WithHint("insufficient_scope"))
if !isPatScopeError(typed) {
t.Fatal("typed insufficient_scope was not recognized")
}
typed = apperrors.NewAPI("ordinary", apperrors.WithReason("reason"))
if got := extractPatScopeError(typed); !strings.Contains(got.Message, "reason") {
t.Fatalf("typed scope message = %q", got.Message)
}
var out bytes.Buffer
PrintPatAuthError(&out, &PatScopeError{Identity: "user", ErrorType: "missing_scope", Message: "missing", Hint: "login"})
if !strings.Contains(out.String(), "dws auth login") {
t.Fatalf("PAT output = %q", out.String())
}
if wantsStructuredPATOutputFromRunner(runnerCoverageFallback{}) {
t.Fatal("non-runtime runner requested structured PAT output")
}
if got := enrichPATErrorWithOpenBrowser("", true); got != "" {
t.Fatalf("empty enriched PAT = %q", got)
}
if got := enrichPATErrorWithOpenBrowser("not-json", true); got != "not-json" {
t.Fatalf("malformed enriched PAT = %q", got)
}
if got := enrichPATErrorWithOpenBrowser(`{"code":"x"}`, true); !strings.Contains(got, "openBrowser") {
t.Fatalf("missing data enrichment = %q", got)
}
if got := patAuthorizationURIFromData(map[string]any{"authorizationUrl": " final "}); got != "final" {
t.Fatalf("authorization URI = %q", got)
}
if err := openPATAuthorizationURI(""); err != nil {
t.Fatal(err)
}
oldTimeout := patAuthorizationTimeout
oldInterval := patAuthorizationPollInterval
oldResolve := patResolveAccessToken
t.Cleanup(func() {
patAuthorizationTimeout = oldTimeout
patAuthorizationPollInterval = oldInterval
patResolveAccessToken = oldResolve
})
patAuthorizationTimeout = 50 * time.Millisecond
patAuthorizationPollInterval = time.Millisecond
patResolveAccessToken = func(context.Context, string, string) (string, error) {
return "token", nil
}
out.Reset()
if ok, err := WaitForPatAuthorization(context.Background(), "", &out); err != nil || !ok {
t.Fatal("valid token did not authorize")
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
out.Reset()
if ok, err := WaitForPatAuthorization(ctx, "", &out); ok || !errors.Is(err, context.Canceled) {
t.Fatalf("cancelled authorization = %v, %v", ok, err)
}
patAuthorizationTimeout = time.Millisecond
patAuthorizationPollInterval = time.Hour
out.Reset()
if ok, err := WaitForPatAuthorization(context.Background(), "", &out); err != nil || ok {
t.Fatalf("timed out authorization = %v, %v", ok, err)
}
patAuthorizationTimeout = 5 * time.Millisecond
patAuthorizationPollInterval = time.Millisecond
patResolveAccessToken = func(context.Context, string, string) (string, error) {
return "", authpkg.ErrTokenDataNotFound
}
out.Reset()
if ok, err := WaitForPatAuthorization(context.Background(), "", &out); err != nil || ok || !strings.Contains(out.String(), "等待授权中") {
t.Fatalf("invalid-token polling = %v, %v, output %q", ok, err, out.String())
}
}
func TestCrossPlatformCoveragePATRetryRemainingOrchestrationCoverage(t *testing.T) {
oldWait := patWaitForAuthorization
oldPoll := patPollDeviceFlowWithInterval
oldSaveApp := patSaveAppConfig
oldExchange := patExchangeCodeForToken
oldSaveToken := patSaveTokenData
oldSleep := patSleep
oldOpen := openBrowserFunc
t.Cleanup(func() {
patWaitForAuthorization = oldWait
patPollDeviceFlowWithInterval = oldPoll
patSaveAppConfig = oldSaveApp
patExchangeCodeForToken = oldExchange
patSaveTokenData = oldSaveToken
patSleep = oldSleep
openBrowserFunc = oldOpen
})
t.Setenv(authpkg.AgentCodeEnv, "")
t.Setenv("DWS_CONFIG_DIR", t.TempDir())
scope := &PatScopeError{OriginalError: "missing", Identity: "user", ErrorType: "missing_scope", Message: "missing", Hint: "login", MissingScope: "calendar:read"}
patWaitForAuthorization = func(context.Context, string, io.Writer) (bool, error) { return false, nil }
if _, err := retryWithPatAuthRetry(context.Background(), runnerCoverageFallback{}, executor.Invocation{}, scope, t.TempDir(), io.Discard); err == nil {
t.Fatal("PAT retry timeout succeeded")
}
wantErr := errors.New("runner failed")
patWaitForAuthorization = func(context.Context, string, io.Writer) (bool, error) { return true, nil }
if _, err := retryWithPatAuthRetry(context.Background(), runnerCoverageFallback{err: wantErr}, executor.Invocation{}, scope, t.TempDir(), io.Discard); !errors.Is(err, wantErr) {
t.Fatalf("authorized retry = %v", err)
}
patErr := &apperrors.PATError{RawJSON: `{"code":"PAT_NO_PERMISSION"}`}
if err := runDirectPATAuthCheck(context.Background(), nil, patErr, nil, io.Discard); !errors.Is(err, patErr) {
t.Fatalf("nil direct retry = %v", err)
}
if err := runDirectPATAuthCheckWithMode(context.Background(), nil, patErr, nil, io.Discard, true); !errors.Is(err, patErr) {
t.Fatalf("nil retry mode = %v", err)
}
badRetry := errors.New("retry callback")
patPollDeviceFlowWithInterval = func(context.Context, string, string, io.Writer, time.Duration) (string, string, error) {
return authpkg.StatusApproved, "", nil
}
patSleep = func(time.Duration) {}
if err := runDirectPATAuthCheck(context.Background(), nil, &apperrors.PATError{RawJSON: patRaw("f", "", "")}, func(context.Context) error { return badRetry }, io.Discard); !errors.Is(err, badRetry) {
t.Fatalf("direct retry callback = %v", err)
}
malformedPAT := &apperrors.PATError{RawJSON: `{`}
if _, err := handlePatAuthCheck(context.Background(), &runtimeRunner{}, executor.Invocation{}, malformedPAT, t.TempDir(), io.Discard); !errors.Is(err, malformedPAT) {
t.Fatalf("malformed PAT handler = %v", err)
}
openBrowserFunc = func(string) error { return nil }
for _, raw := range []string{
`{"code":"x","data":{"flowId":"f","authUrl":"https://auth.test","desc":"authorize"}}`,
`{"code":"x","data":{"flowId":"f","authorizationUrl":"https://auth2.test"}}`,
} {
patPollDeviceFlowWithInterval = func(context.Context, string, string, io.Writer, time.Duration) (string, string, error) {
return "", "", wantErr
}
ctx := context.WithValue(context.Background(), patSuppressBrowserOpenKey, true)
if _, err := handlePatAuthCheck(ctx, &runtimeRunner{}, executor.Invocation{}, &apperrors.PATError{RawJSON: raw}, t.TempDir(), io.Discard); err == nil {
t.Fatal("poll failure returned nil")
}
}
statuses := []string{authpkg.StatusRejected, authpkg.StatusExpired, authpkg.StatusCancelled, "UNKNOWN"}
for _, status := range statuses {
patPollDeviceFlowWithInterval = func(context.Context, string, string, io.Writer, time.Duration) (string, string, error) {
return status, "", nil
}
if _, err := handlePatAuthCheck(context.WithValue(context.Background(), patSuppressBrowserOpenKey, true), &runtimeRunner{}, executor.Invocation{}, &apperrors.PATError{RawJSON: patRaw("f", "", "")}, t.TempDir(), io.Discard); err == nil {
t.Fatalf("status %s returned nil", status)
}
}
patPollDeviceFlowWithInterval = func(context.Context, string, string, io.Writer, time.Duration) (string, string, error) {
return authpkg.StatusApproved, "code", nil
}
patSaveAppConfig = func(string, *authpkg.AppConfig) error { return wantErr }
patExchangeCodeForToken = func(context.Context, string, string) (*authpkg.TokenData, error) { return nil, wantErr }
skip := executor.Invocation{Params: map[string]any{"retryAfterApproval": false}}
if got, err := handlePatAuthCheck(context.Background(), &runtimeRunner{}, skip, &apperrors.PATError{RawJSON: patRaw("f", "client", "secret")}, t.TempDir(), io.Discard); err != nil || !got.Invocation.Implemented {
t.Fatalf("approved skip = %#v, %v", got, err)
}
patSaveAppConfig = func(string, *authpkg.AppConfig) error { return nil }
patExchangeCodeForToken = func(context.Context, string, string) (*authpkg.TokenData, error) {
return &authpkg.TokenData{AccessToken: "token"}, nil
}
patSaveTokenData = func(string, *authpkg.TokenData) error { return wantErr }
r := &runtimeRunner{fallback: runnerCoverageFallback{result: executor.Result{Response: map[string]any{"ok": true}}}}
if _, err := handlePatAuthCheck(context.Background(), r, executor.Invocation{}, &apperrors.PATError{RawJSON: patRaw("f", "client", "")}, t.TempDir(), io.Discard); err != nil {
t.Fatalf("approved retry with save failure = %v", err)
}
patSaveTokenData = func(string, *authpkg.TokenData) error { return nil }
if _, err := handlePatAuthCheck(context.Background(), r, executor.Invocation{}, &apperrors.PATError{RawJSON: patRaw("f", "", "")}, t.TempDir(), io.Discard); err != nil {
t.Fatalf("approved retry = %v", err)
}
for _, inv := range []executor.Invocation{{}, {Params: map[string]any{}}, {Params: map[string]any{"retryAfterApproval": "no"}}, {Params: map[string]any{"retryAfterApproval": true}}} {
if shouldSkipPATRetryAfterApproval(inv) {
t.Fatalf("unexpected skip for %#v", inv.Params)
}
}
if got := enrichPATErrorForHostControl(""); got != "" {
t.Fatalf("empty host PAT = %q", got)
}
if got := enrichPATErrorForHostControl("bad"); got != "bad" {
t.Fatalf("bad host PAT = %q", got)
}
if got := enrichPATErrorForHostControl(`{"value":1}`); !strings.Contains(got, "value") {
t.Fatalf("generic host PAT = %q", got)
}
if _, err := marshalSingleLineJSONNoHTMLEscape(map[string]any{"bad": func() {}}); err == nil {
t.Fatal("unsupported JSON value succeeded")
}
}
func patRaw(flowID, clientID, secret string) string {
return `{"code":"x","data":{"desc":"authorize","flowId":"` + flowID + `","uri":"https://auth.test","clientId":"` + clientID + `","clientSecret":"` + secret + `"}}`
}
func TestCrossPlatformCoveragePATRetryRemainingPollAndBrowserCoverage(t *testing.T) {
oldDo := patPollHTTPDo
oldRequest := patPollNewRequest
oldResolve := patResolveAccessToken
oldBrowser := patBrowserOpenCommand
t.Cleanup(func() {
patPollHTTPDo = oldDo
patPollNewRequest = oldRequest
patResolveAccessToken = oldResolve
patBrowserOpenCommand = oldBrowser
})
patResolveAccessToken = func(context.Context, string, string) (string, error) { return "token", nil }
cancelled, cancelNow := context.WithCancel(context.Background())
cancelNow()
if status, _, err := pollPatDeviceFlowWithInterval(cancelled, "flow", t.TempDir(), io.Discard, 0); err != nil || status != authpkg.StatusCancelled {
t.Fatalf("zero-interval cancelled poll = %q, %v", status, err)
}
expired, cancelExpired := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer cancelExpired()
if status, _, err := pollPatDeviceFlowWithInterval(expired, "flow", t.TempDir(), io.Discard, time.Millisecond); err != nil || status != authpkg.StatusExpired {
t.Fatalf("expired-context poll = %q, %v", status, err)
}
ctx, cancel := context.WithCancel(context.Background())
patPollHTTPDo = func(*http.Client, *http.Request) (*http.Response, error) {
cancel()
return nil, errors.New("network")
}
if status, _, err := pollPatDeviceFlowWithInterval(ctx, "flow", t.TempDir(), io.Discard, time.Millisecond); err != nil || status != authpkg.StatusCancelled {
t.Fatalf("network poll = %q, %v", status, err)
}
ctx, cancel = context.WithCancel(context.Background())
patPollHTTPDo = func(*http.Client, *http.Request) (*http.Response, error) {
cancel()
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("{"))}, nil
}
if status, _, err := pollPatDeviceFlowWithInterval(ctx, "flow", t.TempDir(), io.Discard, time.Millisecond); err != nil || status != authpkg.StatusCancelled {
t.Fatalf("malformed poll = %q, %v", status, err)
}
ctx, cancel = context.WithCancel(context.Background())
patPollNewRequest = func(context.Context, string, string, io.Reader) (*http.Request, error) {
cancel()
return nil, errors.New("request")
}
if status, _, err := pollPatDeviceFlowWithInterval(ctx, "flow", t.TempDir(), io.Discard, time.Millisecond); err != nil || status != authpkg.StatusCancelled {
t.Fatalf("invalid request poll = %q, %v", status, err)
}
patPollNewRequest = oldRequest
var out bytes.Buffer
t.Setenv("DWS_DEBUG_PAT_POLL", "1")
printPATPollDebugResponse(&out, 500, nil)
if !strings.Contains(out.String(), "empty body") {
t.Fatalf("empty debug response = %q", out.String())
}
for _, goos := range []string{"darwin", "linux", "windows", "plan9"} {
_ = browserOpenCommand(goos, "https://example.test")
}
patBrowserOpenCommand = func(string, string) *exec.Cmd { return nil }
if err := tryOpenBrowser("https://example.test"); err != nil {
t.Fatal(err)
}
patBrowserOpenCommand = func(string, string) *exec.Cmd { return exec.Command("definitely-not-a-real-dws-command") }
if err := tryOpenBrowser("https://example.test"); err == nil {
t.Fatal("missing browser command started")
}
}
-89
View File
@@ -650,95 +650,6 @@ func TestEnrichPATErrorWithOpenBrowserKeepsAuthorizationURLAmpersandReadable(t *
}
}
func TestCrossPlatformCoverageHandlePatAuthCheckOrgPolicyDenied(t *testing.T) {
t.Setenv(authpkg.AgentCodeEnv, "")
originalClientID := authpkg.ClientID()
originalClientSecret := authpkg.ClientSecret()
t.Cleanup(func() {
authpkg.SetClientID(originalClientID)
authpkg.SetClientSecret(originalClientSecret)
})
originalOpenBrowser := openBrowserFunc
t.Cleanup(func() { openBrowserFunc = originalOpenBrowser })
for _, test := range []struct {
name string
format string
}{
{name: "structured", format: "json"},
{name: "human"},
} {
t.Run(test.name, func(t *testing.T) {
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
if _, err := pat.SetBrowserPolicy(configDir, "", true); err != nil {
t.Fatalf("SetBrowserPolicy(default) error = %v", err)
}
authpkg.SetClientID("existing-client-id")
authpkg.SetClientSecret("existing-client-secret")
opened := false
openBrowserFunc = func(string) error {
opened = true
return nil
}
retried := false
runner := &runtimeRunner{
globalFlags: &GlobalFlags{Format: test.format},
fallback: &mockRunner{runFunc: func(context.Context, executor.Invocation) (executor.Result, error) {
retried = true
return executor.Result{}, nil
}},
}
raw := `{"success":false,"code":"PAT_ORG_POLICY_DENIED","data":{"hint":"组织策略已禁止当前工具所需的开源数据权限","scope":"contact.user.read","flowId":"terminal-flow","uri":"https://example.com/pat","clientId":"denied-client-id","clientSecret":"denied-client-secret","openBrowser":true}}`
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
var out bytes.Buffer
_, err := handlePatAuthCheck(ctx, runner, executor.Invocation{
CanonicalProduct: "contact",
Tool: "get_current_user_profile",
CanonicalPath: "contact.get_current_user_profile",
}, &apperrors.PATError{RawJSON: raw}, configDir, &out)
if err == nil {
t.Fatal("expected PATError")
}
if got := strings.TrimSpace(out.String()); got != "" {
t.Fatalf("terminal denial produced human authorization or polling output %q", got)
}
if opened {
t.Fatal("terminal denial opened a browser")
}
if retried {
t.Fatal("terminal denial retried the invocation")
}
if got := authpkg.ClientID(); got != "existing-client-id" {
t.Fatalf("client ID = %q, want existing process credential preserved", got)
}
if got := authpkg.ClientSecret(); got != "existing-client-secret" {
t.Fatalf("client secret = %q, want existing process credential preserved", got)
}
patOut, ok := err.(*apperrors.PATError)
if !ok {
t.Fatalf("expected *PATError, got %T: %v", err, err)
}
var payload map[string]any
if err := json.Unmarshal([]byte(patOut.RawJSON), &payload); err != nil {
t.Fatalf("json.Unmarshal(PAT payload) error = %v\nraw=%s", err, patOut.RawJSON)
}
data, _ := payload["data"].(map[string]any)
if got, ok := data["openBrowser"].(bool); !ok || got {
t.Fatalf("data.openBrowser = %#v, want false", data["openBrowser"])
}
if got, _ := data["hint"].(string); !strings.Contains(got, "组织策略") {
t.Fatalf("data.hint = %q, want org policy guidance", got)
}
})
}
}
func TestHandlePatAuthCheck_Approved(t *testing.T) {
t.Setenv(authpkg.AgentCodeEnv, "")
server, configDir := setupHandlePATServer(t, "APPROVED", "test-auth-code")
+12 -24
View File
@@ -26,18 +26,6 @@ import (
"github.com/spf13/cobra"
)
var (
pluginInstallFromGit = (*plugin.Loader).InstallFromGit
pluginStat = os.Stat
pluginMkdirAll = os.MkdirAll
pluginWriteFile = os.WriteFile
pluginAbs = filepath.Abs
pluginRegisterDev = (*plugin.Loader).RegisterDevPlugin
pluginListInstalled = (*plugin.Loader).ListInstalled
pluginParseManifest = plugin.ParseManifest
pluginBuild = plugin.BuildPlugin
)
func newPluginCommand() *cobra.Command {
pluginCmd := newPlaceholderParent("plugin", i18n.T("插件管理"))
@@ -110,7 +98,7 @@ func newPluginInstallCommand() *cobra.Command {
loader := plugin.NewLoader(RawVersion())
if gitURL != "" {
p, err := pluginInstallFromGit(loader, gitURL)
p, err := loader.InstallFromGit(gitURL)
if err != nil {
return apperrors.NewInternal(fmt.Sprintf("install failed: %v", err))
}
@@ -259,7 +247,7 @@ func newPluginCreateCommand() *cobra.Command {
}
dir := filepath.Join(".", name)
if _, err := pluginStat(dir); err == nil {
if _, err := os.Stat(dir); err == nil {
return apperrors.NewValidation(fmt.Sprintf("directory %q already exists", dir))
}
@@ -270,7 +258,7 @@ func newPluginCreateCommand() *cobra.Command {
filepath.Join(dir, "hooks"),
}
for _, d := range dirs {
if err := pluginMkdirAll(d, 0o755); err != nil {
if err := os.MkdirAll(d, 0o755); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to create directory: %v", err))
}
}
@@ -298,7 +286,7 @@ func newPluginCreateCommand() *cobra.Command {
}
`, name, desc, pluginType, RawVersion(), name)
if err := pluginWriteFile(filepath.Join(dir, "plugin.json"), []byte(pluginJSON), 0o644); err != nil {
if err := os.WriteFile(filepath.Join(dir, "plugin.json"), []byte(pluginJSON), 0o644); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to write plugin.json: %v", err))
}
@@ -329,7 +317,7 @@ Use this skill when the user mentions:
- Conversion rules
`, name, desc, RawVersion(), name, name)
if err := pluginWriteFile(filepath.Join(dir, "skills", name, "SKILL.md"), []byte(skillMD), 0o644); err != nil {
if err := os.WriteFile(filepath.Join(dir, "skills", name, "SKILL.md"), []byte(skillMD), 0o644); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to write SKILL.md: %v", err))
}
@@ -338,7 +326,7 @@ Use this skill when the user mentions:
"hooks": []
}
`
if err := pluginWriteFile(filepath.Join(dir, "hooks", "hooks.json"), []byte(hooksJSON), 0o644); err != nil {
if err := os.WriteFile(filepath.Join(dir, "hooks", "hooks.json"), []byte(hooksJSON), 0o644); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to write hooks.json: %v", err))
}
@@ -389,7 +377,7 @@ to unregister.`,
// Register dev plugin
dir := args[0]
absDir, err := pluginAbs(dir)
absDir, err := filepath.Abs(dir)
if err != nil {
return apperrors.NewValidation(fmt.Sprintf("invalid path: %v", err))
}
@@ -403,7 +391,7 @@ to unregister.`,
return apperrors.NewValidation(fmt.Sprintf("validation failed: %v", err))
}
if err := pluginRegisterDev(loader, m.Name, absDir); err != nil {
if err := loader.RegisterDevPlugin(m.Name, absDir); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to register: %v", err))
}
@@ -594,10 +582,10 @@ func newPluginConfigUnsetCommand() *cobra.Command {
// loadDeclaredUserConfig loads the userConfig section from a plugin's manifest.
func loadDeclaredUserConfig(loader *plugin.Loader, pluginName string) map[string]plugin.ConfigItem {
plugins := pluginListInstalled(loader)
plugins := loader.ListInstalled()
for _, p := range plugins {
if p.Name == pluginName {
m, err := pluginParseManifest(filepath.Join(p.Path, "plugin.json"))
m, err := plugin.ParseManifest(filepath.Join(p.Path, "plugin.json"))
if err != nil {
return nil
}
@@ -638,7 +626,7 @@ The build configuration is read from the "build" field in plugin.json:
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
dir := args[0]
absDir, err := pluginAbs(dir)
absDir, err := filepath.Abs(dir)
if err != nil {
return apperrors.NewValidation(fmt.Sprintf("invalid path: %v", err))
}
@@ -658,7 +646,7 @@ The build configuration is read from the "build" field in plugin.json:
" }", m.Name))
}
if err := pluginBuild(absDir); err != nil {
if err := plugin.BuildPlugin(absDir); err != nil {
return apperrors.NewInternal(err.Error())
}
@@ -1,181 +0,0 @@
package app
import (
"bytes"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/plugin"
"github.com/spf13/cobra"
)
func pluginCoverageRun(cmd *cobra.Command, args ...string) (string, error) {
out := &bytes.Buffer{}
cmd.SetOut(out)
cmd.SetErr(io.Discard)
cmd.SilenceErrors = true
cmd.SilenceUsage = true
cmd.SetArgs(args)
err := cmd.Execute()
return out.String(), err
}
func TestCrossPlatformCoveragePluginCommandRemainingCoverage(t *testing.T) {
oldGit := pluginInstallFromGit
oldStat := pluginStat
oldMkdir := pluginMkdirAll
oldWrite := pluginWriteFile
oldAbs := pluginAbs
oldRegister := pluginRegisterDev
oldBuild := pluginBuild
oldList, oldParse := pluginListInstalled, pluginParseManifest
t.Cleanup(func() {
pluginInstallFromGit = oldGit
pluginStat = oldStat
pluginMkdirAll = oldMkdir
pluginWriteFile = oldWrite
pluginAbs = oldAbs
pluginRegisterDev = oldRegister
pluginBuild = oldBuild
pluginListInstalled, pluginParseManifest = oldList, oldParse
})
home := t.TempDir()
work := t.TempDir()
t.Setenv("HOME", home)
oldWD, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.Chdir(work); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(oldWD) })
fail := errors.New("failure")
pluginListInstalled = func(*plugin.Loader) []plugin.PluginInfo {
return []plugin.PluginInfo{{Name: "broken", Path: "missing"}}
}
pluginParseManifest = func(string) (*plugin.Manifest, error) { return nil, fail }
if got := loadDeclaredUserConfig(plugin.NewLoader(RawVersion()), "broken"); got != nil {
t.Fatalf("broken declared config = %#v", got)
}
pluginListInstalled, pluginParseManifest = oldList, oldParse
pluginInstallFromGit = func(*plugin.Loader, string) (*plugin.Plugin, error) { return nil, fail }
if _, err := pluginCoverageRun(newPluginInstallCommand(), "--git", "https://example.test/org/plugin.git"); err == nil {
t.Fatal("git install failure should propagate")
}
pluginInstallFromGit = func(*plugin.Loader, string) (*plugin.Plugin, error) {
return &plugin.Plugin{Manifest: plugin.Manifest{Name: "git-plugin", Version: "1.0.0"}}, nil
}
if out, err := pluginCoverageRun(newPluginInstallCommand(), "--git", "https://example.test/org/plugin.git"); err != nil || !strings.Contains(out, "git-plugin") {
t.Fatalf("git install = %q, %v", out, err)
}
if _, err := pluginCoverageRun(newPluginDisableCommand(), "missing"); err == nil {
t.Fatal("disable missing plugin should fail")
}
invalidDir := filepath.Join(work, "invalid")
if err := os.MkdirAll(invalidDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(invalidDir, "plugin.json"), []byte(`{"name":"ok-name","version":"1.0.0","type":"invalid"}`), 0o600); err != nil {
t.Fatal(err)
}
if _, err := pluginCoverageRun(newPluginValidateCommand(), invalidDir); err == nil {
t.Fatal("invalid manifest validation should fail")
}
pluginStat = func(string) (os.FileInfo, error) { return nil, os.ErrNotExist }
pluginMkdirAll = func(string, os.FileMode) error { return fail }
if _, err := pluginCoverageRun(newPluginCreateCommand(), "mkdir-plugin"); err == nil {
t.Fatal("scaffold mkdir failure should propagate")
}
pluginMkdirAll = oldMkdir
for _, target := range []string{"plugin.json", "SKILL.md", "hooks.json"} {
name := "write-" + strings.ToLower(strings.TrimSuffix(target, filepath.Ext(target)))
pluginWriteFile = func(path string, data []byte, mode os.FileMode) error {
if strings.HasSuffix(path, target) {
return fail
}
return oldWrite(path, data, mode)
}
if _, err := pluginCoverageRun(newPluginCreateCommand(), name); err == nil {
t.Fatalf("scaffold %s failure should propagate", target)
}
}
pluginWriteFile = oldWrite
pluginAbs = func(string) (string, error) { return "", fail }
if _, err := pluginCoverageRun(newPluginDevCommand(), "dir"); err == nil {
t.Fatal("dev absolute-path failure should propagate")
}
pluginAbs = oldAbs
if _, err := pluginCoverageRun(newPluginDevCommand(), invalidDir); err == nil {
t.Fatal("dev manifest validation should fail")
}
validDir := filepath.Join(work, "valid")
if err := os.MkdirAll(validDir, 0o755); err != nil {
t.Fatal(err)
}
manifest := `{
"name":"valid-plugin","version":"1.0.0","type":"user",
"userConfig":{
"API_KEY":{"description":"secret key","sensitive":true},
"PLAIN":{"description":"plain value","default":"default"},
"UNSET":{"description":"required value"}
},
"build":{"command":"true","output":"bin/server"}
}`
if err := os.WriteFile(filepath.Join(validDir, "plugin.json"), []byte(manifest), 0o600); err != nil {
t.Fatal(err)
}
pluginRegisterDev = func(*plugin.Loader, string, string) error { return fail }
if _, err := pluginCoverageRun(newPluginDevCommand(), validDir); err == nil {
t.Fatal("dev registration failure should propagate")
}
loader := plugin.NewLoader(RawVersion())
installed, err := loader.InstallFromDir(validDir)
if err != nil {
// The declared build output is intentionally absent; install a no-build copy.
noBuild := strings.Replace(manifest, ",\n \"build\":{\"command\":\"true\",\"output\":\"bin/server\"}", "", 1)
if writeErr := os.WriteFile(filepath.Join(validDir, "plugin.json"), []byte(noBuild), 0o600); writeErr != nil {
t.Fatal(writeErr)
}
installed, err = loader.InstallFromDir(validDir)
}
if err != nil {
t.Fatal(err)
}
loader.SetPluginConfig("valid-plugin", "API_KEY", "abcdefghijk")
loader.SetPluginConfig("valid-plugin", "PLAIN", "value")
for _, args := range [][]string{{"valid-plugin"}, {"valid-plugin", "--json"}} {
out, runErr := pluginCoverageRun(newPluginConfigListCommand(), args...)
if runErr != nil || !strings.Contains(out, "UNSET") || !strings.Contains(out, "abcd") {
t.Fatalf("config list %#v = %q, %v", args, out, runErr)
}
}
if err := os.WriteFile(filepath.Join(installed.Root, "plugin.json"), []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
if got := loadDeclaredUserConfig(loader, "valid-plugin"); got != nil {
t.Fatalf("corrupt declared config = %#v", got)
}
pluginAbs = func(string) (string, error) { return "", fail }
if _, err := pluginCoverageRun(newPluginBuildCommand(), validDir); err == nil {
t.Fatal("build absolute-path failure should propagate")
}
pluginAbs = oldAbs
if err := os.WriteFile(filepath.Join(validDir, "plugin.json"), []byte(manifest), 0o600); err != nil {
t.Fatal(err)
}
pluginBuild = func(string) error { return fail }
if _, err := pluginCoverageRun(newPluginBuildCommand(), validDir); err == nil {
t.Fatal("plugin build failure should propagate")
}
}
File diff suppressed because it is too large Load Diff
@@ -1,675 +0,0 @@
// Copyright 2026 Alibaba Group
// Licensed under the Apache License, Version 2.0 (the "License");
package app
import (
"context"
"encoding/json"
"errors"
"reflect"
"strings"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/cobracmd"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/cmdutil"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/mcptypes"
"github.com/spf13/cobra"
)
type pluginFailRunner struct{}
func (pluginFailRunner) Run(context.Context, executor.Invocation) (executor.Result, error) {
return executor.Result{}, errors.New("runner failed")
}
type pluginWrongFlagValue struct{}
func (pluginWrongFlagValue) String() string { return "" }
func (pluginWrongFlagValue) Set(string) error { return nil }
func (pluginWrongFlagValue) Type() string { return "wrong" }
func TestPluginCompilerRejectsInvalidDuplicateAndEmptyDefinitions(t *testing.T) {
invalidRoot := conferencePluginDescriptor()
invalidRoot.CLI.Command = "Invalid Root"
if commands := buildPluginCommands([]mcptypes.ServerDescriptor{invalidRoot}, executor.EchoRunner{}, nil); len(commands) != 0 {
t.Fatalf("invalid root produced commands %#v", commands)
}
descriptor := conferencePluginDescriptor()
descriptor.CLI.Groups = map[string]mcptypes.CLIGroupDef{
"empty": {Description: "removed when no leaf survives"},
}
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"": {CLIName: "blank-tool"},
"hidden": {CLIName: "hidden", Hidden: true},
"invalid": {CLIName: "Invalid Leaf"},
"first": {CLIName: "same"},
"second": {CLIName: "same"},
}
commands := buildPluginCommands([]mcptypes.ServerDescriptor{descriptor}, executor.EchoRunner{}, nil)
if len(commands) != 1 {
t.Fatalf("commands = %#v", commands)
}
if requireOptionalPluginChild(commands[0], "same") == nil {
t.Fatal("valid leaf was not retained")
}
if requireOptionalPluginChild(commands[0], "empty") != nil {
t.Fatal("empty group was not pruned")
}
empty := conferencePluginDescriptor()
empty.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"hidden": {CLIName: "hidden", Hidden: true},
}
if commands := buildPluginCommands([]mcptypes.ServerDescriptor{empty}, executor.EchoRunner{}, nil); len(commands) != 0 {
t.Fatalf("empty overlay produced commands %#v", commands)
}
}
func TestPluginLeafExecutionErrorsAndBodyWrapper(t *testing.T) {
base := conferencePluginDescriptor()
base.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"wrapped": {
CLIName: "wrapped",
BodyWrapper: "body",
Flags: map[string]mcptypes.CLIFlagOverride{
"value": {Required: true},
},
},
}
runner := &pluginCaptureRunner{}
root := pluginTestRoot(buildPluginCommands([]mcptypes.ServerDescriptor{base}, runner, nil)...)
root.SetArgs([]string{"conference", "wrapped", "--value", "ok", "--params", `{"body":{"old":1},"_meta":"kept"}`})
if err := root.Execute(); err != nil {
t.Fatalf("wrapped command: %v", err)
}
want := map[string]any{
"_meta": "kept",
"body": map[string]any{"old": float64(1), "value": "ok"},
}
if !reflect.DeepEqual(runner.invocations[0].Params, want) {
t.Fatalf("wrapped params = %#v, want %#v", runner.invocations[0].Params, want)
}
for _, testCase := range []struct {
name string
runner executor.Runner
args []string
}{
{name: "invalid json", runner: executor.EchoRunner{}, args: []string{"conference", "wrapped", "--json", "["}},
{name: "missing required", runner: executor.EchoRunner{}, args: []string{"conference", "wrapped"}},
{name: "missing runner", runner: nil, args: []string{"conference", "wrapped", "--value", "ok"}},
{name: "runner error", runner: pluginFailRunner{}, args: []string{"conference", "wrapped", "--value", "ok"}},
} {
t.Run(testCase.name, func(t *testing.T) {
commandRoot := pluginTestRoot(buildPluginCommands([]mcptypes.ServerDescriptor{base}, testCase.runner, nil)...)
commandRoot.SetArgs(testCase.args)
if err := commandRoot.Execute(); err == nil {
t.Fatal("expected command error")
}
})
}
for _, flagName := range []string{"json", "params"} {
t.Run("unreadable "+flagName, func(t *testing.T) {
commands := buildPluginCommands([]mcptypes.ServerDescriptor{base}, executor.EchoRunner{}, nil)
leaf := requirePluginChild(t, commands[0], "wrapped")
leaf.Flags().Lookup(flagName).Value = pluginWrongFlagValue{}
commandRoot := pluginTestRoot(commands...)
commandRoot.SetArgs([]string{"conference", "wrapped", "--value", "ok"})
if err := commandRoot.Execute(); err == nil {
t.Fatal("expected unreadable flag error")
}
})
}
}
func TestPluginBindingCompilerCoversAliasesAndPositionalValidators(t *testing.T) {
reservations := pluginFlagReservations{
names: map[string]bool{"reserved": true},
shorthands: map[string]bool{},
}
bindings, _, _, ok := registerPluginBindings("alias", mcptypes.CLIToolOverride{
Flags: map[string]mcptypes.CLIFlagOverride{
"value": {Alias: "value", Aliases: []string{"", "Bad", "value", "other"}},
},
}, reservations)
if !ok || !reflect.DeepEqual(bindings[0].names, []string{"value", "other"}) {
t.Fatalf("alias bindings = (%#v, %v)", bindings, ok)
}
if _, _, _, ok := registerPluginBindings("conflict", mcptypes.CLIToolOverride{
Flags: map[string]mcptypes.CLIFlagOverride{"value": {Alias: "reserved"}},
}, reservations); ok {
t.Fatal("reserved flag was accepted")
}
if _, _, _, ok := registerPluginBindings("negative", mcptypes.CLIToolOverride{
Flags: map[string]mcptypes.CLIFlagOverride{"value": {Positional: true, PositionalIndex: -1}},
}, reservations); ok {
t.Fatal("negative positional index was accepted")
}
if _, _, _, ok := registerPluginBindings("duplicate", mcptypes.CLIToolOverride{
Flags: map[string]mcptypes.CLIFlagOverride{
"first": {Positional: true, PositionalIndex: 0},
"second": {Positional: true, PositionalIndex: 0},
},
}, reservations); ok {
t.Fatal("duplicate positional index was accepted")
}
if _, _, _, ok := registerPluginBindings("gap", mcptypes.CLIToolOverride{
Flags: map[string]mcptypes.CLIFlagOverride{
"second": {Positional: true, PositionalIndex: 1},
},
}, reservations); ok {
t.Fatal("non-contiguous positional indexes were accepted")
}
for _, testCase := range []struct {
name string
flags map[string]mcptypes.CLIFlagOverride
wantUse string
valid []string
invalid []string
}{
{
name: "exact",
flags: map[string]mcptypes.CLIFlagOverride{
"second": {Positional: true, PositionalIndex: 1, Required: true},
"first": {Positional: true, PositionalIndex: 0, Required: true},
},
wantUse: "exact [first] [second]", valid: []string{"a", "b"}, invalid: []string{"a"},
},
{
name: "range",
flags: map[string]mcptypes.CLIFlagOverride{
"first": {Positional: true, PositionalIndex: 0, Required: true},
"second": {Positional: true, PositionalIndex: 1},
},
wantUse: "range [first] [second]", valid: []string{"a"}, invalid: []string{},
},
{
name: "maximum",
flags: map[string]mcptypes.CLIFlagOverride{
"first": {Positional: true, PositionalIndex: 0},
"second": {Positional: true, PositionalIndex: 1},
},
wantUse: "maximum [first] [second]", valid: []string{}, invalid: []string{"a", "b", "c"},
},
} {
t.Run(testCase.name, func(t *testing.T) {
_, use, validator, ok := registerPluginBindings(testCase.name, mcptypes.CLIToolOverride{Flags: testCase.flags}, reservations)
if !ok || use != testCase.wantUse {
t.Fatalf("binding contract = (%q, %v)", use, ok)
}
cmd := &cobra.Command{Use: testCase.name}
if err := validator(cmd, testCase.valid); err != nil {
t.Fatalf("valid args: %v", err)
}
if err := validator(cmd, testCase.invalid); err == nil {
t.Fatal("invalid args were accepted")
}
})
}
}
func TestPluginFlagRegistrationAndReadingCoversAllKinds(t *testing.T) {
cmd := &cobra.Command{Use: "leaf"}
override := mcptypes.CLIToolOverride{Flags: map[string]mcptypes.CLIFlagOverride{
"integer": {Default: "2", Shorthand: "i", Hidden: true},
"float": {Default: "1.5"},
"boolean": {Default: "true"},
"slice": {Default: "one, ,two"},
"json": {Default: `{"old":true}`},
"string": {Default: "text"},
}}
bindings := []pluginFlagBinding{
{property: "integer", names: []string{"integer", "integer-alias"}, kind: pluginFlagInt},
{property: "float", names: []string{"float"}, kind: pluginFlagFloat},
{property: "boolean", names: []string{"boolean"}, kind: pluginFlagBool},
{property: "slice", names: []string{"slice"}, kind: pluginFlagStringSlice},
{property: "json", names: []string{"json-value"}, kind: pluginFlagJSON},
{property: "string", names: []string{"string"}, kind: pluginFlagString},
}
registerPluginFlags(cmd, bindings, override, pluginFlagReservations{shorthands: map[string]bool{}})
for name, raw := range map[string]string{
"integer": "3", "float": "2.5", "boolean": "false",
"slice": "three,four", "json-value": `{"ok":true}`, "string": "changed",
} {
if err := cmd.Flags().Set(name, raw); err != nil {
t.Fatalf("set --%s: %v", name, err)
}
}
wants := map[string]any{
"integer": 3,
"float": 2.5,
"boolean": false,
"slice": []string{"three", "four"},
"json": map[string]any{"ok": true},
"string": "changed",
}
for _, binding := range bindings {
value, err := readPluginFlag(cmd.Flags(), binding.names[0], binding.kind)
if err != nil || !reflect.DeepEqual(value, wants[binding.property]) {
t.Fatalf("read %s = (%#v, %v), want %#v", binding.property, value, err, wants[binding.property])
}
}
if !cmd.Flags().Lookup("integer").Hidden || !cmd.Flags().Lookup("integer-alias").Hidden {
t.Fatal("hidden primary or alias flag was exposed")
}
if err := cmd.Flags().Set("json-value", "{"); err != nil {
t.Fatal(err)
}
if _, err := readPluginFlag(cmd.Flags(), "json-value", pluginFlagJSON); err == nil {
t.Fatal("invalid JSON flag was accepted")
}
cmd.Flags().Lookup("json-value").Value = pluginWrongFlagValue{}
if _, err := readPluginFlag(cmd.Flags(), "json-value", pluginFlagJSON); err == nil {
t.Fatal("wrong JSON flag type was accepted")
}
}
func TestCollectPluginBindingsCoversEveryValueSourceAndFailure(t *testing.T) {
t.Run("sources", func(t *testing.T) {
cmd := &cobra.Command{Use: "leaf"}
registerPluginFlag(cmd.Flags(), "flag", "", "", pluginFlagString, "")
if err := cmd.Flags().Set("flag", "from-flag"); err != nil {
t.Fatal(err)
}
t.Setenv("PLUGIN_COVERAGE_ENV", "7")
params := map[string]any{"existing": "from-json"}
bindings := []pluginFlagBinding{
{property: "flag", names: []string{"flag"}, kind: pluginFlagString},
{property: "existing", kind: pluginFlagString},
{property: "positional", kind: pluginFlagBool, positional: true, positionalIndex: 0},
{property: "default", kind: pluginFlagFloat, defaultProvided: true, defaultValue: "1.5"},
{property: "env", kind: pluginFlagInt, envDefault: "PLUGIN_COVERAGE_ENV"},
{property: "optional", kind: pluginFlagString},
}
if err := collectPluginBindings(cmd, []string{"true"}, bindings, params); err != nil {
t.Fatal(err)
}
want := map[string]any{
"flag": "from-flag", "existing": "from-json", "positional": true,
"default": 1.5, "env": 7,
}
if !reflect.DeepEqual(params, want) {
t.Fatalf("params = %#v, want %#v", params, want)
}
})
for _, testCase := range []struct {
name string
prepare func(t *testing.T, cmd *cobra.Command)
args []string
binding pluginFlagBinding
params map[string]any
}{
{
name: "wrong flag type",
prepare: func(t *testing.T, cmd *cobra.Command) {
cmd.Flags().String("value", "", "")
if err := cmd.Flags().Set("value", "x"); err != nil {
t.Fatal(err)
}
},
binding: pluginFlagBinding{property: "value", names: []string{"value"}, kind: pluginFlagInt},
},
{name: "invalid positional", args: []string{"maybe"}, binding: pluginFlagBinding{property: "value", kind: pluginFlagBool, positional: true, positionalIndex: 0}},
{name: "invalid default", binding: pluginFlagBinding{property: "value", kind: pluginFlagInt, defaultProvided: true, defaultValue: "bad"}},
{
name: "invalid env",
prepare: func(t *testing.T, _ *cobra.Command) { t.Setenv("PLUGIN_COVERAGE_BAD_ENV", "bad") },
binding: pluginFlagBinding{property: "value", kind: pluginFlagInt, envDefault: "PLUGIN_COVERAGE_BAD_ENV"},
},
{name: "missing named required", binding: pluginFlagBinding{property: "value", names: []string{"value"}, required: true}},
{name: "missing positional required", binding: pluginFlagBinding{property: "value", required: true, positional: true, positionalIndex: 0}},
{name: "required omitted", binding: pluginFlagBinding{property: "value", required: true, defaultProvided: true, defaultValue: "", omitWhen: "empty"}},
} {
t.Run(testCase.name, func(t *testing.T) {
cmd := &cobra.Command{Use: "leaf"}
if testCase.prepare != nil {
testCase.prepare(t, cmd)
}
if err := collectPluginBindings(cmd, testCase.args, []pluginFlagBinding{testCase.binding}, testCase.params); err == nil {
t.Fatal("expected binding error")
}
})
}
params := map[string]any{"value": ""}
if err := collectPluginBindings(&cobra.Command{Use: "leaf"}, nil, []pluginFlagBinding{{
property: "value", kind: pluginFlagString, omitWhen: "empty",
}}, params); err != nil {
t.Fatal(err)
}
if _, exists := params["value"]; exists {
t.Fatal("optional empty value was not omitted")
}
}
func TestPluginValueAndNamingHelpers(t *testing.T) {
parseCases := []struct {
kind pluginFlagKind
raw string
want any
}{
{pluginFlagInt, " 2 ", 2},
{pluginFlagFloat, " 2.5 ", 2.5},
{pluginFlagBool, "true", true},
{pluginFlagStringSlice, "one, ,two", []string{"one", "two"}},
{pluginFlagJSON, `{"ok":true}`, map[string]any{"ok": true}},
{pluginFlagString, " raw ", " raw "},
}
for _, testCase := range parseCases {
got, err := parsePluginValue(testCase.raw, testCase.kind)
if err != nil || !reflect.DeepEqual(got, testCase.want) {
t.Fatalf("parse %q = (%#v, %v), want %#v", testCase.raw, got, err, testCase.want)
}
}
for _, testCase := range []struct {
kind pluginFlagKind
raw string
}{
{pluginFlagInt, "bad"}, {pluginFlagFloat, "bad"}, {pluginFlagBool, "bad"}, {pluginFlagJSON, "{"},
} {
if _, err := parsePluginValue(testCase.raw, testCase.kind); err == nil {
t.Fatalf("invalid %q was accepted", testCase.raw)
}
}
omitCases := []struct {
value any
mode string
want bool
}{
{nil, "", true}, {" ", "", true}, {[]string{}, "", true},
{"", "never", false}, {false, "zero", true}, {0, "zero", true},
{float64(0), "zero", true}, {true, "zero", false}, {1, "zero", false},
{float64(1), "zero", false}, {[]any{}, "zero", true}, {map[string]any{}, "zero", true},
{[]any{"value"}, "zero", false}, {map[string]any{"value": true}, "zero", false},
{struct{}{}, "zero", false}, {false, "", false},
}
for _, testCase := range omitCases {
if got := shouldOmitPluginValue(testCase.value, testCase.mode); got != testCase.want {
t.Fatalf("omit (%#v, %q) = %v, want %v", testCase.value, testCase.mode, got, testCase.want)
}
}
wrapPluginParams(nil, "body")
untouched := map[string]any{"value": 1}
wrapPluginParams(untouched, " ")
wrapped := map[string]any{"body": map[string]any{"old": 1}, "value": 2, "_meta": 3}
wrapPluginParams(wrapped, "body")
wantWrapped := map[string]any{"body": map[string]any{"old": 1, "value": 2}, "_meta": 3}
if !reflect.DeepEqual(wrapped, wantWrapped) {
t.Fatalf("wrapped = %#v, want %#v", wrapped, wantWrapped)
}
kinds := map[string]pluginFlagKind{
"int": pluginFlagInt, "integer": pluginFlagInt,
"float": pluginFlagFloat, "float64": pluginFlagFloat, "number": pluginFlagFloat,
"bool": pluginFlagBool, "boolean": pluginFlagBool,
"stringSlice": pluginFlagStringSlice, "string_slice": pluginFlagStringSlice,
"array": pluginFlagStringSlice, "[]string": pluginFlagStringSlice,
"json": pluginFlagJSON, "object": pluginFlagJSON, "unknown": pluginFlagString,
}
for raw, want := range kinds {
if got := pluginFlagKindFromString(raw); got != want {
t.Fatalf("kind %q = %v, want %v", raw, got, want)
}
}
used := map[string]bool{}
reserved := map[string]bool{"r": true}
if got := safePluginShorthand(" x ", used, reserved); got != "x" || !used["x"] {
t.Fatalf("safe shorthand = %q / %#v", got, used)
}
for _, raw := range []string{"", "xy", "x", "r"} {
if got := safePluginShorthand(raw, used, reserved); got != "" {
t.Fatalf("unsafe shorthand %q = %q", raw, got)
}
}
baseReservations := pluginReservedFlags(nil)
root := &cobra.Command{Use: "dws"}
root.PersistentFlags().StringP("custom", "c", "", "")
rootReservations := pluginReservedFlags(root)
if !baseReservations.names["yes"] || !rootReservations.names["custom"] || !rootReservations.shorthands["c"] {
t.Fatalf("reservations = %#v / %#v", baseReservations, rootReservations)
}
if got := safePluginAliases([]string{"", "help", "auth", "cmd", "cmd", "ok", "Bad"}, "cmd"); !reflect.DeepEqual(got, []string{"ok"}) {
t.Fatalf("aliases = %#v", got)
}
if got := derivePluginCommandName("conference_getCurrent2Status", []string{"other", "conference"}); got != "get-current2-status" {
t.Fatalf("derived name = %q", got)
}
if got := pluginKebabName(" HTTP2.Foo_bar baz@ "); got != "http2-foo-bar-baz@" {
t.Fatalf("kebab name = %q", got)
}
for _, name := range []string{"", "1bad", "bad-", "bad--name", "bad_name", "bad@name"} {
if validPluginKebabName(name) {
t.Fatalf("invalid kebab name %q was accepted", name)
}
}
if !validPluginKebabName("good-name2") || validPluginCommandName("help") || validPluginFlagName("json") || validPluginFlagName("params") {
t.Fatal("name validation contract failed")
}
if got := firstNonEmptyPluginString(" ", " value "); got != "value" || firstNonEmptyPluginString("", " ") != "" {
t.Fatal("first non-empty string contract failed")
}
}
func TestPluginConstraintGroupAndRootHelpers(t *testing.T) {
cmd := &cobra.Command{Use: "leaf"}
for _, name := range []string{"a", "b", "c"} {
cmd.Flags().String(name, "", "")
}
applyPluginFlagConstraints(cmd, mcptypes.CLIToolOverride{
MutuallyExclusive: [][]string{{"a", "b"}, {"a", "missing"}},
RequireOneOf: [][]string{{"a", "b"}, {"missing"}},
RequireTogether: [][]string{{"b", "c"}, {"c", "missing"}},
})
bindings := []pluginFlagBinding{{names: []string{"a"}}, {names: []string{"b"}}, {names: []string{"c"}}}
if !validPluginFlagConstraints(bindings, mcptypes.CLIToolOverride{
MutuallyExclusive: [][]string{{"a", "b"}},
RequireOneOf: [][]string{{"a"}},
RequireTogether: [][]string{{"b", "c"}},
}) {
t.Fatal("valid plugin constraints were rejected")
}
for _, invalid := range []mcptypes.CLIToolOverride{
{MutuallyExclusive: [][]string{{"a"}}},
{RequireOneOf: [][]string{{"missing"}}},
{RequireTogether: [][]string{{"a", "a"}}},
} {
if validPluginFlagConstraints(bindings, invalid) {
t.Fatalf("invalid plugin constraints were accepted: %#v", invalid)
}
}
groups := map[string]*cobra.Command{}
root := &cobra.Command{Use: "root"}
group := ensurePluginGroup(root, "parent.child", "child description", groups)
if group.Name() != "child" || group.Short != "child description" || !cmdutil.IsPluginSourced(group) {
t.Fatalf("group = %#v", group)
}
if again := ensurePluginGroup(root, "parent.child", "ignored", groups); again != group {
t.Fatal("existing group was not reused")
}
for _, invalid := range []string{"safe.bad_name", "_bad", ".parent", "parent."} {
if got := ensurePluginGroup(root, invalid, "invalid", groups); got != nil {
t.Fatalf("invalid group path %q produced %#v", invalid, got)
}
}
mergePluginRoot(nil, root)
mergePluginRoot(root, nil)
destination := &cobra.Command{Use: "plugin", Aliases: []string{"one"}}
source := &cobra.Command{Use: "plugin", Aliases: []string{"one", "two"}}
source.AddCommand(&cobra.Command{Use: "leaf"})
mergePluginRoot(destination, source)
if !reflect.DeepEqual(destination.Aliases, []string{"one", "two"}) || requireOptionalPluginChild(destination, "leaf") == nil {
t.Fatalf("merged root = %#v", destination)
}
pruneEmptyPluginGroups(nil)
pruneRoot := &cobra.Command{Use: "root"}
empty := cobracmd.NewGroupCommand("empty", "empty")
nonEmpty := cobracmd.NewGroupCommand("non-empty", "non-empty")
nonEmpty.AddCommand(&cobra.Command{Use: "leaf"})
pruneRoot.AddCommand(empty, nonEmpty)
pruneEmptyPluginGroups(pruneRoot)
if requireOptionalPluginChild(pruneRoot, "empty") != nil || requireOptionalPluginChild(pruneRoot, "non-empty") == nil {
t.Fatal("empty plugin groups were not pruned correctly")
}
if pluginRootBoolFlag(nil, "yes") {
t.Fatal("nil command reported a root flag")
}
noFlag := &cobra.Command{Use: "root"}
if pluginRootBoolFlag(noFlag, "yes") {
t.Fatal("missing flag reported true")
}
wrongType := &cobra.Command{Use: "root"}
wrongType.PersistentFlags().String("yes", "true", "")
if pluginRootBoolFlag(wrongType, "yes") {
t.Fatal("wrong flag type reported true")
}
boolRoot := &cobra.Command{Use: "root"}
boolRoot.PersistentFlags().Bool("yes", false, "")
if err := boolRoot.PersistentFlags().Set("yes", "true"); err != nil {
t.Fatal(err)
}
if !pluginRootBoolFlag(boolRoot, "yes") {
t.Fatal("true root flag was not observed")
}
if err := pluginConfirmationRequired("dws plugin"); err == nil || !strings.Contains(err.Error(), "sensitive") {
t.Fatalf("confirmation error = %v", err)
}
}
func TestUnsupportedPluginSemanticsReportEveryField(t *testing.T) {
overlays := []struct {
value mcptypes.CLIOverlay
want string
}{
{mcptypes.CLIOverlay{Parent: "root"}, "parent"},
{mcptypes.CLIOverlay{Group: "group"}, "group"},
{mcptypes.CLIOverlay{ServerDeps: []string{"other"}}, "serverDeps"},
{mcptypes.CLIOverlay{Hints: map[string]json.RawMessage{"x": json.RawMessage(`{}`)}}, "hintCommands"},
{mcptypes.CLIOverlay{RedirectTo: "other"}, "redirectTo"},
{mcptypes.CLIOverlay{}, ""},
}
for _, testCase := range overlays {
if got := unsupportedPluginOverlay(testCase.value); got != testCase.want {
t.Fatalf("unsupported overlay = %q, want %q", got, testCase.want)
}
}
tools := []struct {
value mcptypes.CLIToolOverride
want string
}{
{mcptypes.CLIToolOverride{CLIAliases: []string{"x"}}, "cliAliases"},
{mcptypes.CLIToolOverride{OutputFormat: map[string]any{"x": true}}, "outputFormat"},
{mcptypes.CLIToolOverride{ServerOverride: "other"}, "serverOverride"},
{mcptypes.CLIToolOverride{RedirectTo: "x"}, "redirectTo"},
{mcptypes.CLIToolOverride{Pipeline: []json.RawMessage{json.RawMessage(`{}`)}}, "pipeline"},
{mcptypes.CLIToolOverride{}, ""},
}
for _, testCase := range tools {
if got := unsupportedPluginToolOverride(testCase.value); got != testCase.want {
t.Fatalf("unsupported tool = %q, want %q", got, testCase.want)
}
}
flags := []struct {
value mcptypes.CLIFlagOverride
want string
}{
{mcptypes.CLIFlagOverride{MapsTo: "x"}, "mapsTo"},
{mcptypes.CLIFlagOverride{Transform: "x"}, "transform"},
{mcptypes.CLIFlagOverride{TransformArgs: map[string]any{"x": true}}, "transformArgs"},
{mcptypes.CLIFlagOverride{RuntimeDefault: "x"}, "runtimeDefault"},
{mcptypes.CLIFlagOverride{PipelineLocal: true}, "pipelineLocal"},
{mcptypes.CLIFlagOverride{Type: "mystery"}, "type"},
{mcptypes.CLIFlagOverride{OmitWhen: "sometimes"}, "omitWhen"},
{mcptypes.CLIFlagOverride{}, ""},
}
for _, testCase := range flags {
if got := unsupportedPluginFlagOverride(testCase.value); got != testCase.want {
t.Fatalf("unsupported flag = %q, want %q", got, testCase.want)
}
}
for _, value := range []string{"", "string", "integer", "float64", "boolean", "stringSlice", "array", "json", "object"} {
if !supportedPluginFlagType(value) {
t.Fatalf("supported plugin flag type %q was rejected", value)
}
}
for _, value := range []string{"", "empty", "zero", "never"} {
if !supportedPluginOmitMode(value) {
t.Fatalf("supported plugin omit mode %q was rejected", value)
}
}
}
func TestUnsupportedPluginDescriptorRejectsEveryInvalidLayer(t *testing.T) {
testCases := []struct {
name string
mutate func(*mcptypes.ServerDescriptor)
want string
}{
{name: "overlay", mutate: func(value *mcptypes.ServerDescriptor) { value.CLI.Parent = "root" }, want: "parent"},
{name: "no tools", mutate: func(value *mcptypes.ServerDescriptor) { value.CLI.ToolOverrides = nil }, want: ""},
{name: "root", mutate: func(value *mcptypes.ServerDescriptor) { value.CLI.Command = "Bad" }, want: "command"},
{name: "declared group", mutate: func(value *mcptypes.ServerDescriptor) {
value.CLI.Groups = map[string]mcptypes.CLIGroupDef{"bad_name": {}}
}, want: "groups"},
{name: "blank tool", mutate: func(value *mcptypes.ServerDescriptor) {
value.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{"": {}}
}, want: "tool"},
{name: "tool semantics", mutate: func(value *mcptypes.ServerDescriptor) {
value.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{"tool": {ServerOverride: "drive"}}
}, want: "serverOverride"},
{name: "hidden tool", mutate: func(value *mcptypes.ServerDescriptor) {
value.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{"tool": {Hidden: true, ServerOverride: "drive"}}
}, want: ""},
{name: "derived leaf", mutate: func(value *mcptypes.ServerDescriptor) {
value.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{"conference_derived_tool": {}}
}, want: ""},
{name: "leaf", mutate: func(value *mcptypes.ServerDescriptor) {
value.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{"tool": {CLIName: "Bad"}}
}, want: "cliName"},
{name: "leaf group", mutate: func(value *mcptypes.ServerDescriptor) {
value.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{"tool": {CLIName: "leaf", Group: "bad_name"}}
}, want: "group"},
{name: "flags", mutate: func(value *mcptypes.ServerDescriptor) {
value.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{"tool": {
CLIName: "leaf",
Flags: map[string]mcptypes.CLIFlagOverride{"value": {Alias: "yes"}},
}}
}, want: "flags"},
{name: "constraints", mutate: func(value *mcptypes.ServerDescriptor) {
value.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{"tool": {
CLIName: "leaf",
Flags: map[string]mcptypes.CLIFlagOverride{"value": {}},
RequireTogether: [][]string{{"value", "missing"}},
}}
}, want: "constraints"},
{name: "valid", want: ""},
}
root := pluginTestRoot()
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
descriptor := conferencePluginDescriptor()
if testCase.mutate != nil {
testCase.mutate(&descriptor)
}
if got := unsupportedPluginDescriptor(root, descriptor); got != testCase.want {
t.Fatalf("unsupported descriptor = %q, want %q", got, testCase.want)
}
})
}
}
-809
View File
@@ -1,809 +0,0 @@
// 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 app
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"strings"
"sync/atomic"
"testing"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/pipeline"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/cmdutil"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/mcptypes"
"github.com/spf13/cobra"
)
type pluginCaptureRunner struct {
invocations []executor.Invocation
}
func (r *pluginCaptureRunner) Run(_ context.Context, invocation executor.Invocation) (executor.Result, error) {
r.invocations = append(r.invocations, invocation)
return executor.Result{Invocation: invocation}, nil
}
func conferencePluginDescriptor() mcptypes.ServerDescriptor {
return mcptypes.ServerDescriptor{
Key: "conference-local",
DisplayName: "conference/conference-local",
Description: "conference plugin",
Endpoint: "stdio://conference/conference-local",
Source: "plugin",
HasCLIMeta: true,
CLI: mcptypes.CLIOverlay{
ID: "conference-local",
Command: "conference",
Description: "视频会议:发起/邀请入会/会中控制",
Prefixes: []string{"conference"},
Groups: map[string]mcptypes.CLIGroupDef{
"camera": {Description: "摄像头控制"},
"mic": {Description: "麦克风控制"},
"share": {Description: "屏幕共享"},
},
ToolOverrides: map[string]mcptypes.CLIToolOverride{
"create_conference": {
CLIName: "start",
Description: "发起即时会议",
Flags: map[string]mcptypes.CLIFlagOverride{
"title": {Description: "会议标题"},
},
},
"get_conference_status": {
CLIName: "status",
Description: "查询当前会议状态",
},
"ai_end_meeting_for_all": {
CLIName: "end",
Description: "结束会议(所有人)",
IsSensitive: true,
},
"ai_open_camera": {
CLIName: "open",
Group: "camera",
Description: "打开摄像头",
},
"ai_mute_mic": {
CLIName: "mute",
Group: "mic",
Description: "静音自己",
},
"ai_share_desktop": {
CLIName: "start",
Group: "share",
Description: "开始共享桌面",
Flags: map[string]mcptypes.CLIFlagOverride{
"capture_speaker": {Description: "是否共享电脑音频"},
},
},
},
},
}
}
func pluginTestRoot(commands ...*cobra.Command) *cobra.Command {
root := &cobra.Command{
Use: "dws",
SilenceErrors: true,
SilenceUsage: true,
}
root.PersistentFlags().Bool("dry-run", false, "")
root.PersistentFlags().Bool("yes", false, "")
root.PersistentFlags().StringP("format", "f", "json", "")
root.SetOut(io.Discard)
root.SetErr(io.Discard)
root.AddCommand(commands...)
return root
}
func requirePluginChild(t *testing.T, parent *cobra.Command, names ...string) *cobra.Command {
t.Helper()
current := parent
for _, name := range names {
var next *cobra.Command
for _, child := range current.Commands() {
if child.Name() == name {
next = child
break
}
}
if next == nil {
t.Fatalf("missing plugin command %q below %q", name, current.CommandPath())
}
current = next
}
return current
}
func TestPluginOverlayBuildsConferenceTreeAndDispatchesOriginalProperties(t *testing.T) {
runner := &pluginCaptureRunner{}
commands := buildPluginCommands([]mcptypes.ServerDescriptor{conferencePluginDescriptor()}, runner, nil)
if len(commands) != 1 {
t.Fatalf("plugin roots = %d, want 1", len(commands))
}
conference := commands[0]
if conference.Name() != "conference" || conference.Short != "视频会议:发起/邀请入会/会中控制" {
t.Fatalf("conference root = %q / %q", conference.Name(), conference.Short)
}
if !cmdutil.IsPluginSourced(conference) {
t.Fatal("conference root is missing plugin provenance")
}
if got := requirePluginChild(t, conference, "camera").Short; got != "摄像头控制" {
t.Fatalf("camera group short = %q", got)
}
if got := requirePluginChild(t, conference, "camera", "open").Short; got != "打开摄像头" {
t.Fatalf("camera open short = %q", got)
}
requirePluginChild(t, conference, "mic", "mute")
requirePluginChild(t, conference, "status")
share := requirePluginChild(t, conference, "share", "start")
flag := share.Flags().Lookup("capture-speaker")
if flag == nil || flag.Usage != "是否共享电脑音频" {
t.Fatalf("capture-speaker flag = %#v", flag)
}
root := pluginTestRoot(commands...)
root.SetArgs([]string{
"conference", "start",
"--json", `{"from_json":"kept","title":"json"}`,
"--params", `{"from_params":2,"title":"params"}`,
"--title", "验证会议",
"--dry-run",
})
if err := root.Execute(); err != nil {
t.Fatalf("conference start: %v", err)
}
if len(runner.invocations) != 1 {
t.Fatalf("runner calls = %d, want 1", len(runner.invocations))
}
invocation := runner.invocations[0]
if invocation.Kind != "compat_invocation" ||
invocation.CanonicalProduct != "conference-local" ||
invocation.Tool != "create_conference" ||
!invocation.DryRun {
t.Fatalf("conference invocation = %#v", invocation)
}
wantParams := map[string]any{
"from_json": "kept",
"from_params": float64(2),
"title": "验证会议",
}
if !reflect.DeepEqual(invocation.Params, wantParams) {
t.Fatalf("conference params = %#v, want %#v", invocation.Params, wantParams)
}
precedenceRunner := &pluginCaptureRunner{}
precedenceRoot := pluginTestRoot(buildPluginCommands(
[]mcptypes.ServerDescriptor{conferencePluginDescriptor()},
precedenceRunner,
nil,
)...)
precedenceRoot.SetArgs([]string{
"conference", "start",
"--json", `{"title":"json"}`,
"--params", `{"title":"params"}`,
"--dry-run",
})
if err := precedenceRoot.Execute(); err != nil {
t.Fatalf("conference payload precedence: %v", err)
}
if got := precedenceRunner.invocations[0].Params["title"]; got != "params" {
t.Fatalf("conference payload title = %#v, want --params value", got)
}
}
func TestPluginOverlayTypedFlags(t *testing.T) {
descriptor := conferencePluginDescriptor()
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"typed_tool": {
CLIName: "typed",
Flags: map[string]mcptypes.CLIFlagOverride{
"conversationId": {Required: true, Description: "conversation"},
"enabled": {Type: "bool"},
"limit": {Type: "int"},
"tags": {Type: "stringSlice"},
},
},
}
runner := &pluginCaptureRunner{}
root := pluginTestRoot(buildPluginCommands([]mcptypes.ServerDescriptor{descriptor}, runner, nil)...)
root.SetArgs([]string{
"conference", "typed",
"--conversation-id", "cid",
"--enabled=false",
"--limit", "3",
"--tags", "one,two",
"--dry-run",
})
if err := root.Execute(); err != nil {
t.Fatalf("typed plugin command: %v", err)
}
if len(runner.invocations) != 1 {
t.Fatalf("runner calls = %d", len(runner.invocations))
}
invocation := runner.invocations[0]
if invocation.CanonicalProduct != "conference-local" {
t.Fatalf("canonical product = %q", invocation.CanonicalProduct)
}
want := map[string]any{
"conversationId": "cid",
"enabled": false,
"limit": 3,
"tags": []string{"one", "two"},
}
if !reflect.DeepEqual(invocation.Params, want) {
t.Fatalf("typed params = %#v, want %#v", invocation.Params, want)
}
}
func TestPluginSensitiveCommandRequiresConfirmation(t *testing.T) {
for _, testCase := range []struct {
name string
args []string
wantCalls int
wantDry bool
wantError bool
}{
{name: "blocked", args: []string{"conference", "end"}, wantError: true},
{name: "preview", args: []string{"conference", "end", "--dry-run"}, wantCalls: 1, wantDry: true},
{name: "confirmed", args: []string{"conference", "end", "--yes"}, wantCalls: 1},
} {
t.Run(testCase.name, func(t *testing.T) {
runner := &pluginCaptureRunner{}
root := pluginTestRoot(buildPluginCommands(
[]mcptypes.ServerDescriptor{conferencePluginDescriptor()}, runner, nil)...)
root.SetArgs(testCase.args)
err := root.Execute()
if testCase.wantError {
var appErr *apperrors.Error
if !errors.As(err, &appErr) ||
appErr.Category != apperrors.CategoryValidation ||
appErr.Reason != "confirmation_required" {
t.Fatalf("sensitive error = %#v", err)
}
} else if err != nil {
t.Fatalf("sensitive command: %v", err)
}
if len(runner.invocations) != testCase.wantCalls {
t.Fatalf("runner calls = %d, want %d", len(runner.invocations), testCase.wantCalls)
}
if testCase.wantCalls == 1 && runner.invocations[0].DryRun != testCase.wantDry {
t.Fatalf("dry-run = %v, want %v", runner.invocations[0].DryRun, testCase.wantDry)
}
})
}
}
func TestPluginOverlayMergesServersWithoutProbingHTTP(t *testing.T) {
isolatePluginRuntime(t)
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
calls.Add(1)
}))
defer server.Close()
first := conferencePluginDescriptor()
first.Endpoint = server.URL
first.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"one": {CLIName: "one"},
}
second := first
second.Key = "conference-extra"
second.DisplayName = "conference/conference-extra"
second.Endpoint = server.URL + "/extra"
second.CLI.ID = "conference-extra"
second.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"two": {CLIName: "two"},
}
registerPluginHTTPServer(first)
registerPluginHTTPServer(second)
runner := &pluginCaptureRunner{}
commands := buildPluginCommands([]mcptypes.ServerDescriptor{second, first}, runner, nil)
if len(commands) != 1 {
t.Fatalf("merged roots = %d, want 1", len(commands))
}
requirePluginChild(t, commands[0], "one")
requirePluginChild(t, commands[0], "two")
root := pluginTestRoot(commands...)
root.SetArgs([]string{"conference", "--help"})
if err := root.Execute(); err != nil {
t.Fatalf("conference help: %v", err)
}
if got := calls.Load(); got != 0 {
t.Fatalf("HTTP calls while building help = %d, want 0", got)
}
for _, command := range []string{"one", "two"} {
root.SetArgs([]string{"conference", command, "--dry-run"})
if err := root.Execute(); err != nil {
t.Fatalf("conference %s: %v", command, err)
}
}
if len(runner.invocations) != 2 ||
runner.invocations[0].CanonicalProduct != "conference-local" ||
runner.invocations[1].CanonicalProduct != "conference-extra" {
t.Fatalf("merged routes = %#v", runner.invocations)
}
}
func TestPluginCanReplaceHiddenFallbackButNotVisibleDistributionCommand(t *testing.T) {
root := &cobra.Command{Use: "dws"}
fallback := &cobra.Command{Use: "conference", Hidden: true}
fallback.AddCommand(&cobra.Command{Use: "meeting"})
distribution := &cobra.Command{Use: "drive"}
root.AddCommand(fallback, distribution)
conference := buildPluginCommands(
[]mcptypes.ServerDescriptor{conferencePluginDescriptor()},
executor.EchoRunner{},
nil,
)[0]
drive := &cobra.Command{Use: "drive"}
cmdutil.MarkPluginSource(drive)
addPluginCommandsSafe(root, []*cobra.Command{conference, drive})
gotConference := requirePluginChild(t, root, "conference")
if gotConference == fallback || gotConference.Hidden {
t.Fatalf("conference fallback was not replaced: %#v", gotConference)
}
requirePluginChild(t, gotConference, "status")
if gotDrive := requirePluginChild(t, root, "drive"); gotDrive != distribution {
t.Fatal("visible distribution command was replaced by a plugin")
}
}
func TestConflictingPluginDescriptorCannotReplaceDistributionEndpoint(t *testing.T) {
isolatePluginRuntime(t)
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
pluginDir := filepath.Join(configDir, "plugins", "user", "drive-hijack")
if err := os.MkdirAll(pluginDir, 0o755); err != nil {
t.Fatal(err)
}
manifest := `{
"name":"drive-hijack",
"version":"1.0.0",
"mcpServers":{
"drive":{
"type":"streamable-http",
"endpoint":"https://plugin.invalid/mcp",
"cli":{
"id":"drive-service",
"command":"drive-hijack",
"toolOverrides":{"plugin_tool":{"cliName":"plugin-tool"}}
}
}
}
}`
if err := os.WriteFile(filepath.Join(pluginDir, "plugin.json"), []byte(manifest), 0o600); err != nil {
t.Fatal(err)
}
AppendDynamicServer(mcptypes.ServerDescriptor{
Key: "drive",
Endpoint: "https://distribution.invalid/mcp",
CLI: mcptypes.CLIOverlay{ID: "drive-service", Command: "drive"},
})
root := &cobra.Command{Use: "dws"}
root.AddCommand(&cobra.Command{Use: "drive"})
if commands := loadPlugins(root, nil, executor.EchoRunner{}); len(commands) != 0 {
t.Fatalf("conflicting plugin commands = %#v", commands)
}
if endpoint, ok := directRuntimeEndpoint("drive-service", "plugin_tool"); !ok ||
endpoint != "https://distribution.invalid/mcp" {
t.Fatalf("drive endpoint after rejected plugin = (%q, %v)", endpoint, ok)
}
}
func TestSchemaSourceRootDoesNotLoadRuntimePlugins(t *testing.T) {
isolatePluginRuntime(t)
previous := rootLoadPlugins
t.Cleanup(func() { rootLoadPlugins = previous })
var calls atomic.Int32
rootLoadPlugins = func(*cobra.Command, *pipeline.Engine, executor.Runner) []*cobra.Command {
calls.Add(1)
AppendDynamicServer(conferencePluginDescriptor())
return buildPluginCommands(
[]mcptypes.ServerDescriptor{conferencePluginDescriptor()},
executor.EchoRunner{},
nil,
)
}
base := NewSchemaSourceRootCommand()
if calls.Load() != 0 {
t.Fatalf("Schema source root loaded plugins %d times", calls.Load())
}
baseConference := requirePluginChild(t, base, "conference")
if !baseConference.Hidden || requireOptionalPluginChild(baseConference, "status") != nil {
t.Fatal("Schema source root contains installed conference plugin commands")
}
runtime := NewRootCommand()
if calls.Load() != 1 {
t.Fatalf("runtime root plugin loads = %d, want 1", calls.Load())
}
runtimeConference := requirePluginChild(t, runtime, "conference")
if runtimeConference.Hidden {
t.Fatal("runtime conference plugin is hidden")
}
requirePluginChild(t, runtimeConference, "status")
}
func requireOptionalPluginChild(parent *cobra.Command, name string) *cobra.Command {
for _, child := range parent.Commands() {
if child.Name() == name {
return child
}
}
return nil
}
func TestPluginDerivedNamesAndReservedAliases(t *testing.T) {
descriptor := conferencePluginDescriptor()
descriptor.CLI.Aliases = []string{"auth", "conf", "conf"}
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"conference_getCurrentStatus": {},
}
commands := buildPluginCommands([]mcptypes.ServerDescriptor{descriptor}, executor.EchoRunner{}, nil)
if len(commands) != 1 || !reflect.DeepEqual(commands[0].Aliases, []string{"conf"}) {
t.Fatalf("plugin aliases = %#v", commands)
}
if requireOptionalPluginChild(commands[0], "get-current-status") == nil {
var names []string
for _, command := range commands[0].Commands() {
names = append(names, command.Name())
}
t.Fatalf("derived command missing, got %s", strings.Join(names, ", "))
}
}
func TestPluginFlagsCannotShadowHostControls(t *testing.T) {
host := pluginTestRoot()
host.PersistentFlags().StringP("host-extra", "x", "", "")
reservations := pluginReservedFlags(host)
for name := range reservations.names {
t.Run(name, func(t *testing.T) {
descriptor := conferencePluginDescriptor()
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"unsafe": {
CLIName: "unsafe",
IsSensitive: true,
Flags: map[string]mcptypes.CLIFlagOverride{
"value": {Alias: name},
},
},
}
if commands := buildPluginCommands(
[]mcptypes.ServerDescriptor{descriptor},
executor.EchoRunner{},
host,
); len(commands) != 0 {
t.Fatalf("reserved host flag %q produced commands %#v", name, commands)
}
})
}
}
func TestPluginShorthandsCannotShadowHostOrHelp(t *testing.T) {
host := pluginTestRoot()
host.PersistentFlags().StringP("host-extra", "x", "", "")
descriptor := conferencePluginDescriptor()
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"safe": {
CLIName: "safe",
Flags: map[string]mcptypes.CLIFlagOverride{
"alpha": {Shorthand: "f"},
"bravo": {Shorthand: "h"},
"charlie": {Shorthand: "o"},
"delta": {Shorthand: "v"},
"echo": {Shorthand: "x"},
"foxtrot": {Shorthand: "y"},
},
},
}
runner := &pluginCaptureRunner{}
commands := buildPluginCommands(
[]mcptypes.ServerDescriptor{descriptor},
runner,
host,
)
if len(commands) != 1 {
t.Fatalf("plugin commands = %#v", commands)
}
host.AddCommand(commands...)
leaf := requirePluginChild(t, commands[0], "safe")
for _, name := range []string{"alpha", "bravo", "charlie", "delta", "echo", "foxtrot"} {
if shorthand := leaf.Flags().Lookup(name).Shorthand; shorthand != "" {
t.Fatalf("--%s shorthand = %q, want empty", name, shorthand)
}
}
host.SetArgs([]string{"conference", "safe", "-h"})
if err := host.Execute(); err != nil {
t.Fatalf("plugin help: %v", err)
}
if len(runner.invocations) != 0 {
t.Fatalf("help executed plugin: %#v", runner.invocations)
}
}
func TestPluginPayloadPrecedenceRequiredAndTypedPositionals(t *testing.T) {
descriptor := conferencePluginDescriptor()
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"payload": {
CLIName: "payload",
Flags: map[string]mcptypes.CLIFlagOverride{
"title": {Required: true},
"mode": {Default: "fallback"},
"enabled": {Positional: true, PositionalIndex: 0, Alias: "enabled-value", Required: true, Type: "bool"},
},
},
}
for _, testCase := range []struct {
name string
args []string
wantEnabled bool
}{
{
name: "flag satisfies dual positional",
args: []string{
"conference", "payload",
"--params", `{"title":"from-json","mode":"from-json"}`,
"--enabled-value=true",
"--dry-run",
},
wantEnabled: true,
},
{
name: "json beats positional",
args: []string{
"conference", "payload", "true",
"--params", `{"title":"from-json","mode":"from-json","enabled":false}`,
"--dry-run",
},
wantEnabled: false,
},
} {
t.Run(testCase.name, func(t *testing.T) {
runner := &pluginCaptureRunner{}
root := pluginTestRoot(buildPluginCommands(
[]mcptypes.ServerDescriptor{descriptor},
runner,
nil,
)...)
root.SetArgs(testCase.args)
if err := root.Execute(); err != nil {
t.Fatalf("payload command: %v", err)
}
if len(runner.invocations) != 1 {
t.Fatalf("runner calls = %d", len(runner.invocations))
}
params := runner.invocations[0].Params
if params["title"] != "from-json" ||
params["mode"] != "from-json" ||
params["enabled"] != testCase.wantEnabled {
t.Fatalf("payload params = %#v", params)
}
})
}
}
func TestPluginDescriptorWinnerKeepsRouteAuthAndClientAtomic(t *testing.T) {
isolatePluginRuntime(t)
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
writeManifest := func(name, manifest string) {
t.Helper()
directory := filepath.Join(configDir, "plugins", "user", name)
if err := os.MkdirAll(directory, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(directory, "plugin.json"), []byte(manifest), 0o600); err != nil {
t.Fatal(err)
}
}
writeManifest("alpha-plugin", `{
"name":"alpha-plugin",
"version":"1.0.0",
"mcpServers":{
"alpha":{
"type":"streamable-http",
"endpoint":"https://alpha.invalid/mcp",
"headers":{"Authorization":"Bearer alpha-secret"},
"cli":{
"id":"shared-plugin-id",
"command":"alpha-command",
"toolOverrides":{"alpha_tool":{"cliName":"alpha"}}
}
},
"alpha-extra":{
"type":"streamable-http",
"endpoint":"https://alpha-extra.invalid/mcp",
"cli":{
"id":"alpha-extra-id",
"command":"alpha-command",
"toolOverrides":{"extra_tool":{"cliName":"extra"}}
}
}
}
}`)
writeManifest("beta-plugin", `{
"name":"beta-plugin",
"version":"1.0.0",
"mcpServers":{
"beta":{
"type":"stdio",
"command":"bin/beta",
"cli":{
"id":"shared-plugin-id",
"command":"beta-command",
"toolOverrides":{"beta_tool":{"cliName":"beta"}}
}
}
}
}`)
root := pluginTestRoot()
commands := loadPlugins(root, nil, executor.EchoRunner{})
if len(commands) != 1 || commands[0].Name() != "alpha-command" {
t.Fatalf("plugin winner commands = %#v", commands)
}
requirePluginChild(t, commands[0], "alpha")
requirePluginChild(t, commands[0], "extra")
endpoint, ok := directRuntimeEndpoint("shared-plugin-id", "alpha_tool")
if !ok || endpoint != "https://alpha.invalid/mcp" {
t.Fatalf("winner endpoint = (%q, %v)", endpoint, ok)
}
extraEndpoint, ok := directRuntimeEndpoint("alpha-extra-id", "extra_tool")
if !ok || extraEndpoint != "https://alpha-extra.invalid/mcp" {
t.Fatalf("merged server endpoint = (%q, %v)", extraEndpoint, ok)
}
auth, ok := LookupPluginAuth("shared-plugin-id")
if !ok || auth.Token != "alpha-secret" {
t.Fatalf("winner auth = (%#v, %v)", auth, ok)
}
if _, ok := LookupStdioClient("beta-plugin/beta"); ok {
t.Fatal("losing stdio client was registered")
}
}
func TestUnsupportedPluginOverlaySemanticsFailClosed(t *testing.T) {
for _, mutate := range []func(*mcptypes.ServerDescriptor){
func(descriptor *mcptypes.ServerDescriptor) {
descriptor.CLI.RedirectTo = "drive"
},
func(descriptor *mcptypes.ServerDescriptor) {
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"unsafe": {
CLIName: "unsafe",
Flags: map[string]mcptypes.CLIFlagOverride{
"source": {MapsTo: "target"},
},
},
}
},
func(descriptor *mcptypes.ServerDescriptor) {
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"unsafe": {
CLIName: "unsafe",
Pipeline: []json.RawMessage{json.RawMessage(`{"tool":"one"}`)},
},
}
},
func(descriptor *mcptypes.ServerDescriptor) {
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"unsafe": {CLIName: "unsafe", ServerOverride: "drive"},
}
},
func(descriptor *mcptypes.ServerDescriptor) {
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"unsafe": {
CLIName: "unsafe",
Flags: map[string]mcptypes.CLIFlagOverride{
"Body.query": {},
},
},
}
},
func(descriptor *mcptypes.ServerDescriptor) {
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"unsafe": {CLIName: "unsafe", Group: "safe.bad_name"},
}
},
func(descriptor *mcptypes.ServerDescriptor) {
descriptor.CLI.ToolOverrides = map[string]mcptypes.CLIToolOverride{
"unsafe": {
CLIName: "unsafe",
Flags: map[string]mcptypes.CLIFlagOverride{"value": {}},
RequireTogether: [][]string{{"value", "missing"}},
},
}
},
} {
descriptor := conferencePluginDescriptor()
mutate(&descriptor)
if commands := buildPluginCommands(
[]mcptypes.ServerDescriptor{descriptor},
executor.EchoRunner{},
nil,
); len(commands) != 0 {
t.Fatalf("unsupported overlay produced commands %#v", commands)
}
}
}
func TestUnsupportedPluginDescriptorsDoNotRegisterRuntimeState(t *testing.T) {
isolatePluginRuntime(t)
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
writeManifest := func(name, manifest string) {
t.Helper()
directory := filepath.Join(configDir, "plugins", "user", name)
if err := os.MkdirAll(directory, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(directory, "plugin.json"), []byte(manifest), 0o600); err != nil {
t.Fatal(err)
}
}
writeManifest("unsafe-http", `{
"name":"unsafe-http",
"version":"1.0.0",
"mcpServers":{"unsafe":{
"type":"streamable-http",
"endpoint":"https://unsafe.invalid/mcp",
"headers":{"Authorization":"Bearer unsafe-secret"},
"cli":{"id":"unsafe-http-id","command":"unsafe-http","toolOverrides":{
"unsafe_tool":{"cliName":"run","serverOverride":"drive"}
}}
}}
}`)
writeManifest("unsafe-stdio", `{
"name":"unsafe-stdio",
"version":"1.0.0",
"mcpServers":{"unsafe":{
"type":"stdio",
"command":"bin/unsafe",
"cli":{"id":"unsafe-stdio-id","command":"unsafe-stdio","toolOverrides":{
"unsafe_tool":{"cliName":"run","flags":{"value":{"mapsTo":"target"}}}
}}
}}
}`)
root := pluginTestRoot()
if commands := loadPlugins(root, nil, executor.EchoRunner{}); len(commands) != 0 {
t.Fatalf("unsupported plugin descriptors produced commands %#v", commands)
}
if endpoint, ok := directRuntimeEndpoint("unsafe-http-id", "unsafe_tool"); ok {
t.Fatalf("unsupported HTTP descriptor registered endpoint %q", endpoint)
}
if _, ok := LookupPluginAuth("unsafe-http-id"); ok {
t.Fatal("unsupported HTTP descriptor registered plugin auth")
}
if _, ok := LookupStdioClient("unsafe-stdio/unsafe"); ok {
t.Fatal("unsupported stdio descriptor registered a client")
}
}
-239
View File
@@ -1,239 +0,0 @@
// 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 app
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/cli"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
)
func pluginToolInputSchema(
tools transport.ToolsListResult,
toolName string,
) (map[string]any, bool) {
for _, tool := range tools.Tools {
if strings.TrimSpace(tool.Name) == strings.TrimSpace(toolName) {
return tool.InputSchema, true
}
}
return nil, false
}
func normalizePluginInputParams(
params map[string]any,
schema map[string]any,
) (map[string]any, error) {
schema = canonicalPluginInputSchema(schema)
normalized := make(map[string]any, len(params))
for key, value := range params {
normalized[key] = value
}
if _, err := coercePluginSchemaValue(normalized, schema); err != nil {
return nil, cliInputValidationError(err)
}
if err := cli.ValidateInputSchema(normalized, schema); err != nil {
return nil, err
}
return normalized, nil
}
func canonicalPluginInputSchema(schema map[string]any) map[string]any {
if len(schema) == 0 {
return schema
}
cloned := make(map[string]any, len(schema))
for key, value := range schema {
cloned[key] = clonePluginSchemaValue(key, value)
}
return cloned
}
func clonePluginSchemaValue(key string, value any) any {
switch typed := value.(type) {
case map[string]any:
cloned := make(map[string]any, len(typed))
for childKey, childValue := range typed {
cloned[childKey] = clonePluginSchemaValue(childKey, childValue)
}
return cloned
case []any:
cloned := make([]any, len(typed))
for index, item := range typed {
cloned[index] = clonePluginSchemaValue(key, item)
}
return cloned
case []string:
cloned := make([]string, len(typed))
for index, item := range typed {
if key == "type" {
item = canonicalPluginSchemaType(item)
}
cloned[index] = item
}
return cloned
case string:
if key == "type" {
return canonicalPluginSchemaType(typed)
}
return typed
default:
return value
}
}
func canonicalPluginSchemaType(value string) string {
switch strings.ToLower(strings.TrimSpace(value)) {
case "bool":
return "boolean"
case "int":
return "integer"
case "float":
return "number"
default:
return value
}
}
func cliInputValidationError(err error) error {
if err == nil {
return nil
}
return apperrors.NewValidation(
fmt.Sprintf("input schema normalization failed: %v", err),
apperrors.WithReason("plugin_input_schema_invalid"),
)
}
func coercePluginSchemaValue(value any, schema map[string]any) (any, error) {
target := singlePluginSchemaType(schema)
if raw, ok := value.(string); ok {
trimmed := strings.TrimSpace(raw)
switch target {
case "bool", "boolean":
parsed, err := strconv.ParseBool(trimmed)
if err != nil {
return nil, fmt.Errorf("cannot convert %q to boolean: %w", raw, err)
}
value = parsed
case "int", "integer":
parsed, err := strconv.Atoi(trimmed)
if err != nil {
return nil, fmt.Errorf("cannot convert %q to integer: %w", raw, err)
}
value = parsed
case "float", "number":
parsed, err := strconv.ParseFloat(trimmed, 64)
if err != nil {
return nil, fmt.Errorf("cannot convert %q to number: %w", raw, err)
}
value = parsed
case "object":
var parsed map[string]any
if err := json.Unmarshal([]byte(trimmed), &parsed); err != nil {
return nil, fmt.Errorf("cannot convert plugin parameter to object: %w", err)
}
if parsed == nil {
return nil, fmt.Errorf("cannot convert plugin parameter to object: expected a JSON object")
}
value = parsed
case "array":
var parsed []any
if strings.HasPrefix(trimmed, "[") {
if err := json.Unmarshal([]byte(trimmed), &parsed); err != nil {
return nil, fmt.Errorf("cannot convert plugin parameter to array: %w", err)
}
} else if trimmed != "" {
for _, item := range strings.Split(trimmed, ",") {
if item = strings.TrimSpace(item); item != "" {
parsed = append(parsed, item)
}
}
}
value = parsed
}
}
switch typed := value.(type) {
case map[string]any:
properties, _ := schema["properties"].(map[string]any)
for key, propertyValue := range typed {
propertySchema, _ := properties[key].(map[string]any)
if len(propertySchema) == 0 {
continue
}
coerced, err := coercePluginSchemaValue(propertyValue, propertySchema)
if err != nil {
return nil, fmt.Errorf("%s: %w", key, err)
}
typed[key] = coerced
}
return typed, nil
case []string:
items := make([]any, len(typed))
for index, item := range typed {
items[index] = item
}
value = items
}
if items, ok := value.([]any); ok {
itemSchema, _ := schema["items"].(map[string]any)
if len(itemSchema) == 0 {
return items, nil
}
for index, item := range items {
coerced, err := coercePluginSchemaValue(item, itemSchema)
if err != nil {
return nil, fmt.Errorf("item %d: %w", index, err)
}
items[index] = coerced
}
return items, nil
}
return value, nil
}
func singlePluginSchemaType(schema map[string]any) string {
var types []string
switch typed := schema["type"].(type) {
case string:
types = []string{typed}
case []string:
types = typed
case []any:
for _, value := range typed {
if text, ok := value.(string); ok {
types = append(types, text)
}
}
}
var target string
for _, candidate := range types {
candidate = strings.TrimSpace(candidate)
if candidate == "" || candidate == "null" {
continue
}
if target != "" && target != candidate {
return ""
}
target = candidate
}
return target
}
@@ -1,229 +0,0 @@
// Copyright 2026 Alibaba Group
// Licensed under the Apache License, Version 2.0
package app
import (
"errors"
"reflect"
"strings"
"testing"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
)
func TestPluginToolInputSchemaMatchesTrimmedName(t *testing.T) {
want := map[string]any{"type": "object"}
tools := transport.ToolsListResult{Tools: []transport.ToolDescriptor{
{Name: "other", InputSchema: map[string]any{"type": "string"}},
{Name: " create_conference ", InputSchema: want},
}}
got, ok := pluginToolInputSchema(tools, " create_conference ")
if !ok || !reflect.DeepEqual(got, want) {
t.Fatalf("pluginToolInputSchema() = (%#v, %v), want (%#v, true)", got, ok, want)
}
if got, ok := pluginToolInputSchema(tools, "missing"); ok || got != nil {
t.Fatalf("missing pluginToolInputSchema() = (%#v, %v), want (nil, false)", got, ok)
}
}
func TestNormalizePluginInputParamsCoercesNestedValues(t *testing.T) {
schema := map[string]any{
"type": "object",
"required": []string{"enabled"},
"properties": map[string]any{
"enabled": map[string]any{"type": []any{"null", "bool"}},
"count": map[string]any{"type": "int"},
"ratio": map[string]any{"type": "float"},
"settings": map[string]any{
"type": "object",
"properties": map[string]any{
"active": map[string]any{"type": "bool"},
},
},
"ids": map[string]any{
"type": []string{"array", "null"},
"items": map[string]any{"type": "int"},
},
"labels": map[string]any{
"type": "array",
"items": map[string]any{"type": "string"},
},
"booleans": map[string]any{
"type": "array",
"items": map[string]any{"type": "bool"},
},
"ambiguous": map[string]any{"type": []string{"string", "int"}},
},
}
params := map[string]any{
"enabled": " true ",
"count": " 7 ",
"ratio": " 2.5 ",
"settings": `{"active":"false"}`,
"ids": `["1", "2"]`,
"labels": "alpha, , beta",
"booleans": []string{"true", "false"},
"ambiguous": "9",
}
got, err := normalizePluginInputParams(params, schema)
if err != nil {
t.Fatalf("normalizePluginInputParams() error = %v", err)
}
want := map[string]any{
"enabled": true,
"count": 7,
"ratio": 2.5,
"settings": map[string]any{"active": false},
"ids": []any{1, 2},
"labels": []any{"alpha", "beta"},
"booleans": []any{true, false},
"ambiguous": "9",
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("normalizePluginInputParams() = %#v, want %#v", got, want)
}
properties := schema["properties"].(map[string]any)
if gotType := properties["enabled"].(map[string]any)["type"].([]any)[1]; gotType != "bool" {
t.Fatalf("normalization mutated source schema type to %#v", gotType)
}
if gotValue := params["enabled"]; gotValue != " true " {
t.Fatalf("normalization mutated source params to %#v", gotValue)
}
}
func TestNormalizePluginInputParamsReportsConversionPath(t *testing.T) {
tests := []struct {
name string
value any
fieldSchema map[string]any
wantText string
}{
{name: "boolean", value: "sometimes", fieldSchema: map[string]any{"type": "bool"}, wantText: "cannot convert"},
{name: "integer", value: "1.5", fieldSchema: map[string]any{"type": "int"}, wantText: "integer"},
{name: "number", value: "many", fieldSchema: map[string]any{"type": "float"}, wantText: "number"},
{name: "object", value: "{", fieldSchema: map[string]any{"type": "object"}, wantText: "object"},
{name: "null object", value: "null", fieldSchema: map[string]any{"type": "object"}, wantText: "expected a JSON object"},
{name: "array", value: "[", fieldSchema: map[string]any{"type": "array"}, wantText: "array"},
{
name: "nested property",
value: `{"active":"sometimes"}`,
fieldSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"active": map[string]any{"type": "bool"},
},
},
wantText: "field: active:",
},
{
name: "array item",
value: "1,not-an-int",
fieldSchema: map[string]any{
"type": "array",
"items": map[string]any{"type": "int"},
},
wantText: "item 1",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
schema := map[string]any{
"type": "object",
"properties": map[string]any{"field": tt.fieldSchema},
}
_, err := normalizePluginInputParams(map[string]any{"field": tt.value}, schema)
if err == nil {
t.Fatal("normalizePluginInputParams() error = nil, want conversion error")
}
var appError *apperrors.Error
if !errors.As(err, &appError) ||
appError.Category != apperrors.CategoryValidation ||
appError.Reason != "plugin_input_schema_invalid" {
t.Fatalf("conversion error = %#v, want categorized plugin schema validation error", err)
}
if !strings.Contains(err.Error(), tt.wantText) {
t.Fatalf("conversion error = %q, want text %q", err, tt.wantText)
}
})
}
}
func TestNormalizePluginInputParamsRunsSchemaValidation(t *testing.T) {
schema := map[string]any{
"type": "object",
"required": []any{"name"},
"properties": map[string]any{
"name": map[string]any{"type": "string"},
},
}
if _, err := normalizePluginInputParams(map[string]any{}, schema); err == nil ||
!strings.Contains(err.Error(), "$.name is required") {
t.Fatalf("required-field validation error = %v", err)
}
}
func TestPluginInputSchemaHelperEdges(t *testing.T) {
if got := canonicalPluginInputSchema(nil); got != nil {
t.Fatalf("canonicalPluginInputSchema(nil) = %#v, want nil", got)
}
if got := clonePluginSchemaValue("minimum", 1); got != 1 {
t.Fatalf("clonePluginSchemaValue(scalar) = %#v, want 1", got)
}
if got := cliInputValidationError(nil); got != nil {
t.Fatalf("cliInputValidationError(nil) = %v, want nil", got)
}
if got, err := coercePluginSchemaValue("", map[string]any{"type": "array"}); err != nil || !reflect.DeepEqual(got, []any(nil)) {
t.Fatalf("empty array coercion = (%#v, %v), want nil slice", got, err)
}
items := []any{"unchanged"}
if got, err := coercePluginSchemaValue(items, map[string]any{"type": "array"}); err != nil || !reflect.DeepEqual(got, items) {
t.Fatalf("array without item schema = (%#v, %v)", got, err)
}
if got, err := coercePluginSchemaValue(12, map[string]any{"type": "integer"}); err != nil || got != 12 {
t.Fatalf("non-string scalar coercion = (%#v, %v), want (12, nil)", got, err)
}
unknown := map[string]any{"unknown": "unchanged"}
if got, err := coercePluginSchemaValue(unknown, map[string]any{
"type": "object",
"properties": map[string]any{},
}); err != nil || !reflect.DeepEqual(got, unknown) {
t.Fatalf("unknown property coercion = (%#v, %v), want unchanged map", got, err)
}
tests := []struct {
name string
schema map[string]any
want string
}{
{name: "missing", schema: map[string]any{}, want: ""},
{name: "single string", schema: map[string]any{"type": "integer"}, want: "integer"},
{name: "single string slice", schema: map[string]any{"type": []string{"null", "number"}}, want: "number"},
{name: "any slice", schema: map[string]any{"type": []any{nil, 3, "", "null", "boolean"}}, want: "boolean"},
{name: "ambiguous", schema: map[string]any{"type": []any{"string", "integer"}}, want: ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := singlePluginSchemaType(tt.schema); got != tt.want {
t.Fatalf("singlePluginSchemaType(%#v) = %q, want %q", tt.schema, got, tt.want)
}
})
}
for raw, want := range map[string]string{
" BOOL ": "boolean",
"Int": "integer",
"FLOAT": "number",
"custom": "custom",
} {
if got := canonicalPluginSchemaType(raw); got != want {
t.Errorf("canonicalPluginSchemaType(%q) = %q, want %q", raw, got, want)
}
}
}
-109
View File
@@ -1,109 +0,0 @@
// 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 app
import (
"context"
"errors"
"reflect"
"testing"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
)
func TestPluginStdioExecutionNormalizesAndValidatesLiveSchema(t *testing.T) {
isolatePluginRuntime(t)
previousInit := runnerStdioEnsureInitialized
previousList := runnerStdioListTools
previousCall := runnerStdioCallTool
t.Cleanup(func() {
runnerStdioEnsureInitialized = previousInit
runnerStdioListTools = previousList
runnerStdioCallTool = previousCall
})
client := transport.NewStdioClient("unused", nil, nil)
RegisterStdioClient("conference/local", client)
runnerStdioEnsureInitialized = func(*transport.StdioClient, context.Context) error {
return nil
}
runnerStdioListTools = func(*transport.StdioClient, context.Context) (transport.ToolsListResult, error) {
return transport.ToolsListResult{
Tools: []transport.ToolDescriptor{{
Name: "create_conference",
InputSchema: map[string]any{
"type": "object",
"required": []any{"title"},
"properties": map[string]any{
"title": map[string]any{"type": "string"},
"capture_speaker": map[string]any{"type": "bool"},
},
"additionalProperties": false,
},
}},
}, nil
}
var calledParams map[string]any
runnerStdioCallTool = func(
_ *transport.StdioClient,
_ context.Context,
_ string,
params map[string]any,
) (transport.ToolCallResult, error) {
calledParams = params
return transport.ToolCallResult{Content: map[string]any{"ok": true}}, nil
}
runner := &runtimeRunner{}
invocation := executor.Invocation{
CanonicalProduct: "conference-local",
Tool: "create_conference",
Params: map[string]any{
"title": "schema validation",
"capture_speaker": "true",
},
}
result, err := runner.executeInvocation(
context.Background(),
"stdio://conference/local",
invocation,
)
if err != nil {
t.Fatalf("stdio plugin execution: %v", err)
}
wantParams := map[string]any{
"title": "schema validation",
"capture_speaker": true,
}
if !reflect.DeepEqual(calledParams, wantParams) ||
!reflect.DeepEqual(result.Invocation.Params, wantParams) {
t.Fatalf("normalized wire params = %#v, result = %#v", calledParams, result.Invocation.Params)
}
calledParams = nil
invocation.Params = map[string]any{"capture_speaker": "true"}
_, err = runner.executeInvocation(
context.Background(),
"stdio://conference/local",
invocation,
)
var appError *apperrors.Error
if !errors.As(err, &appError) ||
appError.Category != apperrors.CategoryValidation ||
calledParams != nil {
t.Fatalf("missing required schema validation = %#v, call params = %#v", err, calledParams)
}
}
@@ -1,369 +0,0 @@
// 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.
package app
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"reflect"
"testing"
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/pipeline"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/plugin"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/shortcut/userdef"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/cmdutil"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/mcptypes"
"github.com/spf13/cobra"
)
type schemaSourceContextKey struct{}
func TestSchemaSourceRootPropagatesContextWithoutLoadingPlugins(t *testing.T) {
previous := rootLoadPlugins
t.Cleanup(func() { rootLoadPlugins = previous })
pluginLoads := 0
rootLoadPlugins = func(*cobra.Command, *pipeline.Engine, executor.Runner) []*cobra.Command {
pluginLoads++
return nil
}
wantContext := context.WithValue(context.Background(), schemaSourceContextKey{}, "schema")
root := NewSchemaSourceRootCommand(wantContext)
if root.Context() != wantContext {
t.Fatal("Schema source root did not retain the caller context")
}
if pluginLoads != 0 {
t.Fatalf("Schema source root loaded runtime plugins %d times", pluginLoads)
}
}
func TestCollectPluginServerCandidatesSortsAndSkipsInvalidStdio(t *testing.T) {
previousDescriptors := rootPluginDescriptors
previousClients := rootPluginStdioClients
previousDescriptor := rootPluginStdioDescriptor
t.Cleanup(func() {
rootPluginDescriptors = previousDescriptors
rootPluginStdioClients = previousClients
rootPluginStdioDescriptor = previousDescriptor
})
first := &plugin.Plugin{Manifest: plugin.Manifest{Name: "first"}}
second := &plugin.Plugin{Manifest: plugin.Manifest{Name: "second"}}
wantContext := &plugin.UserContext{UserID: "user", CorpID: "corp"}
client := transport.NewStdioClient("unused", nil, nil)
rootPluginDescriptors = func(owner *plugin.Plugin) []mcptypes.ServerDescriptor {
if owner == first {
return []mcptypes.ServerDescriptor{{Key: "same"}, {Key: " beta "}}
}
return []mcptypes.ServerDescriptor{{Key: "aardvark"}}
}
rootPluginStdioClients = func(owner *plugin.Plugin, gotContext *plugin.UserContext) []plugin.StdioServerClient {
if gotContext != wantContext {
t.Fatalf("stdio user context = %#v, want %#v", gotContext, wantContext)
}
if owner != first {
return nil
}
return []plugin.StdioServerClient{
{Key: "same", Client: client},
{Key: " alpha ", Client: client},
{Key: "invalid", Client: client},
}
}
rootPluginStdioDescriptor = func(_ *plugin.Plugin, stdio plugin.StdioServerClient) (mcptypes.ServerDescriptor, bool) {
if stdio.Key == "invalid" {
return mcptypes.ServerDescriptor{}, false
}
return mcptypes.ServerDescriptor{Key: stdio.Key}, true
}
candidates := collectPluginServerCandidates([]*plugin.Plugin{first, second}, wantContext)
if len(candidates) != 5 {
t.Fatalf("candidate count = %d, want 5", len(candidates))
}
gotKeys := make([]string, 0, len(candidates))
gotKinds := make([]string, 0, len(candidates))
for _, candidate := range candidates {
gotKeys = append(gotKeys, candidate.descriptor.Key)
if candidate.stdioClient == nil {
gotKinds = append(gotKinds, "http")
} else {
gotKinds = append(gotKinds, "stdio")
if candidate.stdioClient.Client != client {
t.Fatal("stdio candidate did not retain its client")
}
}
}
if want := []string{" alpha ", " beta ", "same", "same", "aardvark"}; !reflect.DeepEqual(gotKeys, want) {
t.Fatalf("candidate keys = %#v, want %#v", gotKeys, want)
}
if want := []string{"stdio", "http", "http", "stdio", "http"}; !reflect.DeepEqual(gotKinds, want) {
t.Fatalf("candidate transports = %#v, want %#v", gotKinds, want)
}
}
func TestPluginDescriptorBlankIdentityAndDistributionOwnership(t *testing.T) {
isolatePluginRuntime(t)
blank := mcptypes.ServerDescriptor{
Key: " ",
CLI: mcptypes.CLIOverlay{
ID: " ",
Command: " ",
Aliases: []string{"", " "},
},
}
if claims := pluginDescriptorIdentityClaims(blank); len(claims) != 0 {
t.Fatalf("blank descriptor claims = %#v, want none", claims)
}
if rootName := pluginDescriptorRootName(blank); rootName != "" {
t.Fatalf("blank descriptor root = %q", rootName)
}
owner := &plugin.Plugin{Manifest: plugin.Manifest{Name: "blank"}}
accepted := selectPluginServerCandidates(
&cobra.Command{Use: "dws"},
[]pluginServerCandidate{
{owner: owner, descriptor: mcptypes.ServerDescriptor{CLI: mcptypes.CLIOverlay{Skip: true}}},
{owner: owner, descriptor: blank},
},
)
if len(accepted) != 1 {
t.Fatalf("blank descriptor candidates = %#v, want one accepted candidate", accepted)
}
if distributionRootOwns(nil, "visible") {
t.Fatal("nil root claimed a command")
}
root := &cobra.Command{Use: "dws"}
visible := &cobra.Command{Use: "visible", Aliases: []string{" visible-alias "}}
hiddenFallback := &cobra.Command{Use: "conference", Hidden: true}
hiddenOwned := &cobra.Command{Use: "hidden-owned", Hidden: true}
pluginOwned := &cobra.Command{Use: "plugin-owned", Aliases: []string{"plugin-alias"}}
cmdutil.MarkPluginSource(pluginOwned)
root.AddCommand(visible, hiddenFallback, hiddenOwned, pluginOwned)
for _, name := range []string{"visible", "visible-alias", "hidden-owned"} {
if !distributionRootOwns(root, name) {
t.Errorf("distribution root did not claim %q", name)
}
}
for _, name := range []string{"conference", "plugin-owned", "plugin-alias", "missing"} {
if distributionRootOwns(root, name) {
t.Errorf("distribution root unexpectedly claimed %q", name)
}
}
}
func TestReplaceableFallbackIdentitySurvivesDistributionConflictChecks(t *testing.T) {
isolatePluginRuntime(t)
SetDynamicServers([]mcptypes.ServerDescriptor{
{
Key: "conference",
Endpoint: "https://example.com/conference/mcp",
CLI: mcptypes.CLIOverlay{ID: "conference"},
},
{
Key: "chat",
Endpoint: "https://example.com/chat/mcp",
CLI: mcptypes.CLIOverlay{ID: "chat"},
},
})
root := &cobra.Command{Use: "dws"}
root.AddCommand(&cobra.Command{Use: "conference", Hidden: true})
distributionProducts := DirectRuntimeProductIDs()
conferenceDescriptor := mcptypes.ServerDescriptor{
Key: "conference-local",
DisplayName: "conference/conference-local",
CLI: mcptypes.CLIOverlay{ID: "conference-local", Command: "conference"},
}
if pluginDescriptorConflictsWithDistribution(root, conferenceDescriptor, distributionProducts) {
t.Fatal("replaceable fallback identity blocked plugin server selection")
}
chatDescriptor := mcptypes.ServerDescriptor{
Key: "chat-local",
DisplayName: "chat/chat-local",
CLI: mcptypes.CLIOverlay{ID: "chat-local", Command: "chat"},
}
if !pluginDescriptorConflictsWithDistribution(root, chatDescriptor, distributionProducts) {
t.Fatal("non-replaceable distribution product no longer conflicts")
}
reservedDescriptor := mcptypes.ServerDescriptor{
Key: "auth-local",
DisplayName: "auth/auth-local",
CLI: mcptypes.CLIOverlay{ID: "auth-local", Command: "auth"},
}
if !pluginDescriptorConflictsWithDistribution(root, reservedDescriptor, distributionProducts) {
t.Fatal("reserved command name no longer conflicts")
}
first := &plugin.Plugin{Manifest: plugin.Manifest{Name: "conference"}}
second := &plugin.Plugin{Manifest: plugin.Manifest{Name: "other"}}
accepted := selectPluginServerCandidates(root, []pluginServerCandidate{
{owner: first, descriptor: conferenceDescriptor},
{
owner: second,
descriptor: mcptypes.ServerDescriptor{
Key: "conference-other",
DisplayName: "other/conference-other",
CLI: mcptypes.CLIOverlay{ID: "conference-other", Command: "conference"},
},
},
})
if len(accepted) != 1 {
t.Fatalf("accepted candidates = %d, want the first conference plugin only", len(accepted))
}
if accepted[0].owner != first {
t.Fatalf("accepted owner = %q, want the first conference plugin", accepted[0].owner.Manifest.Name)
}
}
func TestAddPluginCommandsSafeFiltersConflictingAliases(t *testing.T) {
root := &cobra.Command{Use: "dws"}
root.AddCommand(&cobra.Command{Use: "taken"})
command := &cobra.Command{
Use: "extension",
Aliases: []string{"", "extension", "auth", "taken", "shared", " shared ", " okay "},
}
addPluginCommandsSafe(root, []*cobra.Command{
command,
{Use: "shared"},
{Use: "other", Aliases: []string{"extension"}},
})
if want := []string{"shared", "okay"}; !reflect.DeepEqual(command.Aliases, want) {
t.Fatalf("filtered aliases = %#v, want %#v", command.Aliases, want)
}
if child := findDirectChild(root, "shared"); child != nil {
t.Fatal("an accepted alias was also registered as a plugin primary command")
}
other := findDirectChild(root, "other")
if other == nil || len(other.Aliases) != 0 {
t.Fatalf("later plugin aliases = %#v", other)
}
}
func TestStdioRunnerReportsToolsListFailureAndMissingTool(t *testing.T) {
isolatePluginRuntime(t)
previousInit := runnerStdioEnsureInitialized
previousList := runnerStdioListTools
previousCall := runnerStdioCallTool
t.Cleanup(func() {
runnerStdioEnsureInitialized = previousInit
runnerStdioListTools = previousList
runnerStdioCallTool = previousCall
})
client := transport.NewStdioClient("unused", nil, nil)
RegisterStdioClient("plugin/server", client)
runnerStdioEnsureInitialized = func(*transport.StdioClient, context.Context) error { return nil }
toolCalls := 0
runnerStdioCallTool = func(*transport.StdioClient, context.Context, string, map[string]any) (transport.ToolCallResult, error) {
toolCalls++
return transport.ToolCallResult{}, nil
}
runner := &runtimeRunner{}
invocation := executor.Invocation{CanonicalProduct: "overlay-id", Tool: "wanted"}
listFailure := errors.New("list failed")
runnerStdioListTools = func(*transport.StdioClient, context.Context) (transport.ToolsListResult, error) {
return transport.ToolsListResult{}, listFailure
}
_, err := runner.executeStdioInvocationAtEndpoint(context.Background(), "stdio://plugin/server", invocation)
assertPluginRuntimeError(t, err, apperrors.CategoryAPI, "tools/list", "stdio_tools_list_error")
runnerStdioListTools = func(*transport.StdioClient, context.Context) (transport.ToolsListResult, error) {
return transport.ToolsListResult{Tools: []transport.ToolDescriptor{{Name: "other"}}}, nil
}
_, err = runner.executeStdioInvocationAtEndpoint(context.Background(), "stdio://plugin/server", invocation)
assertPluginRuntimeError(t, err, apperrors.CategoryValidation, "", "plugin_tool_not_found")
if toolCalls != 0 {
t.Fatalf("tools/call attempts after tools/list failures = %d", toolCalls)
}
}
func TestStdioManifestDescriptorAndRegistrationFailClosed(t *testing.T) {
isolatePluginRuntime(t)
p := &plugin.Plugin{
Manifest: plugin.Manifest{
Name: "broken-plugin",
MCPServers: map[string]*plugin.MCPServer{
"local": {CLI: json.RawMessage(`{`)},
},
},
}
server := plugin.StdioServerClient{
Key: "local",
Client: transport.NewStdioClient("unused", nil, nil),
}
if descriptor, ok := stdioServerDescriptorFromManifest(p, server); ok || !reflect.ValueOf(descriptor).IsZero() {
t.Fatalf("invalid descriptor = (%#v, %v), want zero, false", descriptor, ok)
}
if descriptor := registerStdioServerFromManifest(p, server); !reflect.ValueOf(descriptor).IsZero() {
t.Fatalf("invalid registered descriptor = %#v, want zero", descriptor)
}
if _, ok := LookupStdioClient("broken-plugin/local"); ok {
t.Fatal("invalid stdio manifest registered a client")
}
}
func TestLegacyCommandsContinueWhenUserShortcutLoadFails(t *testing.T) {
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
shortcutDir := filepath.Join(configDir, "shortcuts")
if err := os.MkdirAll(shortcutDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(shortcutDir, "broken.yaml"), []byte("version: ["), 0o600); err != nil {
t.Fatal(err)
}
if _, loadErrors := userdef.Load(); len(loadErrors) == 0 {
t.Fatal("malformed shortcut fixture did not fail to load")
}
runner := executor.EchoRunner{}
caller := newToolCallerAdapter(runner, &GlobalFlags{})
if commands := newLegacyPublicCommands(runner, caller, true); len(commands) == 0 {
t.Fatal("legacy commands were dropped after a user shortcut load error")
}
}
func findDirectChild(root *cobra.Command, name string) *cobra.Command {
for _, command := range root.Commands() {
if command.Name() == name {
return command
}
}
return nil
}
func assertPluginRuntimeError(
t *testing.T,
err error,
wantCategory apperrors.Category,
wantOperation string,
wantReason string,
) {
t.Helper()
var appError *apperrors.Error
if !errors.As(err, &appError) {
t.Fatalf("runtime error = %#v, want structured app error", err)
}
if appError.Category != wantCategory ||
appError.Operation != wantOperation ||
appError.Reason != wantReason {
t.Fatalf("runtime error = %#v, want category=%q operation=%q reason=%q", appError, wantCategory, wantOperation, wantReason)
}
}
+2 -38
View File
@@ -5,7 +5,6 @@
package app
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
@@ -13,7 +12,6 @@ import (
"sync/atomic"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/plugin"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/mcptypes"
@@ -37,11 +35,6 @@ func isolatePluginRuntime(t *testing.T) {
stdioClients = make(map[string]*transport.StdioClient)
stdioMu.Unlock()
pluginAuthMu.Lock()
previousPluginAuth := pluginAuthRegistry
pluginAuthRegistry = make(map[string]*PluginAuth)
pluginAuthMu.Unlock()
t.Cleanup(func() {
StopAllStdioClients()
dynamicMu.Lock()
@@ -53,9 +46,6 @@ func isolatePluginRuntime(t *testing.T) {
stdioMu.Lock()
stdioClients = previousStdio
stdioMu.Unlock()
pluginAuthMu.Lock()
pluginAuthRegistry = previousPluginAuth
pluginAuthMu.Unlock()
})
}
@@ -87,40 +77,14 @@ func TestRegisterPluginHTTPServerDoesNotProbeEndpoint(t *testing.T) {
func TestRegisterStdioServerFromManifestDoesNotStartProcess(t *testing.T) {
isolatePluginRuntime(t)
marker := t.TempDir() + "/started"
pluginRoot := t.TempDir()
if err := os.WriteFile(pluginRoot+"/overlay.json", []byte(`{
"id":"local",
"command":"lazy-stdio",
"groups":{"health":{"description":"health checks"}},
"toolOverrides":{"ping":{"cliName":"ping","group":"health"}}
}`), 0o600); err != nil {
t.Fatal(err)
}
client := transport.NewStdioClient("/bin/sh", []string{
"-c", fmt.Sprintf("printf started > %q", marker),
}, nil)
p := &plugin.Plugin{
Manifest: plugin.Manifest{
Name: "lazy-stdio",
Description: "lazy stdio test",
MCPServers: map[string]*plugin.MCPServer{
"local": {
Type: "stdio",
Command: "unused",
CLI: json.RawMessage(`"overlay.json"`),
},
},
},
Root: pluginRoot,
Manifest: plugin.Manifest{Name: "lazy-stdio", Description: "lazy stdio test"},
Root: t.TempDir(),
}
descriptor := registerStdioServerFromManifest(p, plugin.StdioServerClient{Key: "local", Client: client})
commands := buildPluginCommands([]mcptypes.ServerDescriptor{descriptor}, executor.EchoRunner{}, nil)
root := pluginTestRoot(commands...)
root.SetArgs([]string{"lazy-stdio", "--help"})
if err := root.Execute(); err != nil {
t.Fatalf("lazy stdio help: %v", err)
}
requirePluginChild(t, commands[0], "health", "ping")
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("stdio process started during registration: stat error = %v", err)
+44 -34
View File
@@ -14,7 +14,10 @@
package app
import (
"encoding/json"
"log/slog"
"os"
"path/filepath"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/plugin"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/mcptypes"
@@ -30,26 +33,50 @@ import (
// When no CLI metadata is present, a minimal overlay keyed by the server
// name is returned so callers can still build an identity descriptor.
func resolveStdioOverlay(p *plugin.Plugin, sc plugin.StdioServerClient) mcptypes.CLIOverlay {
overlay, ok := p.ResolveCLIOverlay(sc.Key)
if !ok {
return mcptypes.CLIOverlay{
ID: sc.Key,
Command: sc.Key,
Skip: true,
serverID := sc.Key
overlay := mcptypes.CLIOverlay{
ID: serverID,
Command: serverID,
}
srv, ok := p.Manifest.MCPServers[sc.Key]
if !ok || len(srv.CLI) == 0 {
return overlay
}
cliData := srv.CLI
// A JSON string is interpreted as a relative path to an external
// overlay file (e.g. "overlay.json") anchored at the plugin root.
if len(cliData) > 0 && cliData[0] == '"' {
var cliPath string
if err := json.Unmarshal(cliData, &cliPath); err == nil && cliPath != "" {
absPath := filepath.Join(p.Root, cliPath)
if fileData, readErr := os.ReadFile(absPath); readErr == nil {
cliData = fileData
} else {
slog.Warn("plugin: failed to read CLI overlay file",
"plugin", p.Manifest.Name, "path", absPath, "error", readErr)
}
}
}
if err := json.Unmarshal(cliData, &overlay); err != nil {
slog.Warn("plugin: failed to parse CLI overlay for stdio server",
"plugin", p.Manifest.Name, "server", sc.Key, "error", err)
}
if overlay.ID == "" {
overlay.ID = serverID
}
if overlay.Command == "" {
overlay.Command = serverID
}
return overlay
}
func stdioServerDescriptorFromManifest(
p *plugin.Plugin,
sc plugin.StdioServerClient,
) (mcptypes.ServerDescriptor, bool) {
overlay, ok := p.ResolveCLIOverlay(sc.Key)
if !ok {
return mcptypes.ServerDescriptor{}, false
}
return mcptypes.ServerDescriptor{
// registerStdioServerFromManifest registers an endpoint descriptor and an
// unstarted client from versioned plugin metadata. Tool discovery is not part
// of command-tree construction; execution starts and initializes the client.
func registerStdioServerFromManifest(p *plugin.Plugin, sc plugin.StdioServerClient) mcptypes.ServerDescriptor {
overlay := resolveStdioOverlay(p, sc)
descriptor := mcptypes.ServerDescriptor{
Key: sc.Key,
DisplayName: p.Manifest.Name + "/" + sc.Key,
Description: p.Manifest.Description,
@@ -57,30 +84,13 @@ func stdioServerDescriptorFromManifest(
Source: "plugin",
CLI: overlay,
HasCLIMeta: true,
}, true
}
}
func registerResolvedStdioServer(
p *plugin.Plugin,
sc plugin.StdioServerClient,
descriptor mcptypes.ServerDescriptor,
) {
AppendDynamicServer(descriptor)
RegisterStdioClient(p.Manifest.Name+"/"+sc.Key, sc.Client)
slog.Debug("plugin: stdio server registered from manifest",
"plugin", p.Manifest.Name, "server", sc.Key,
"toolOverrides", len(descriptor.CLI.ToolOverrides))
}
// registerStdioServerFromManifest registers an endpoint descriptor and an
// unstarted client from versioned plugin metadata. Tool discovery is not part
// of command-tree construction; execution starts and initializes the client.
func registerStdioServerFromManifest(p *plugin.Plugin, sc plugin.StdioServerClient) mcptypes.ServerDescriptor {
descriptor, ok := stdioServerDescriptorFromManifest(p, sc)
if !ok {
return mcptypes.ServerDescriptor{}
}
registerResolvedStdioServer(p, sc, descriptor)
"toolOverrides", len(overlay.ToolOverrides))
return descriptor
}
+98 -199
View File
@@ -18,6 +18,7 @@ import (
"errors"
"fmt"
"io"
"sort"
"strings"
"time"
@@ -33,17 +34,15 @@ func newProfileCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "profile",
Short: "组织 profile 管理",
Long: `管理本机已登录的钉钉账号 profile。
Long: `管理本机已登录的钉钉组织 profile。
每个 profile 由 corpId + userId 唯一确定,同一组织可保存多个账号。业务命令可通过
全局 --profile 临时指定组织或账号,profile switch/use 才会持久修改默认账号。`,
每个 profile 对应一个已授权组织。业务命令可通过全局 --profile 临时指定组织,
profile switch/use 才会持久修改默认组织上下文。`,
Example: ` dws profile list
dws profile switch
dws profile switch <corpId>
dws profile switch <corpId>:<userId>
dws profile switch "<corpName>:<userName>"
dws profile switch -
dws --profile <corpId>:<userId> contact user get-self`,
dws --profile <corpId> contact user get-self`,
Args: cobra.NoArgs,
TraverseChildren: true,
DisableAutoGenTag: true,
@@ -59,26 +58,26 @@ func newProfileListCommand() *cobra.Command {
return &cobra.Command{
Use: "list",
Aliases: []string{"ls"},
Short: "列出全部已登录账号 profile",
Long: "列出本机全部已登录账号。状态和到期时间直接读取各身份 Token,列表本身不会刷新 Token。",
Short: "列出已登录组织 profile",
Long: "列出本机已登录的所有组织 profile,包含当前组织、主组织、组织名、corpId、状态和用户信息。",
Example: ` dws profile list
dws profile list --format json`,
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
configDir := defaultConfigDir()
if err := profileEnsureProfilesMigration(configDir); err != nil {
if err := authpkg.EnsureProfilesMigration(configDir); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to migrate profiles: %v", err))
}
cfg, err := profileLoadProfiles(configDir)
cfg, err := authpkg.LoadProfiles(configDir)
if err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to load profiles: %v", err))
}
format, _ := cmd.Root().PersistentFlags().GetString("format")
if strings.EqualFold(strings.TrimSpace(format), "json") {
return writeProfileListJSON(cmd.OutOrStdout(), configDir, cfg)
return writeProfileListJSON(cmd.OutOrStdout(), cfg)
}
writeProfileListTable(cmd.OutOrStdout(), configDir, cfg)
writeProfileListTable(cmd.OutOrStdout(), cfg)
return nil
},
}
@@ -86,9 +85,9 @@ func newProfileListCommand() *cobra.Command {
func newProfileUseCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "use [profile-selector|-]",
Short: "切换当前账号 profile(兼容 profile switch)",
Long: "兼容命令,语义等同于 dws profile switch。选择器支持组织 ID/名称、账号 ID/名称组合或本地 profile 名;- 切回上一个账号。",
Use: "use [name|corpId|-]",
Short: "切换当前组织 profile(兼容 profile switch)",
Long: "兼容命令,语义等同于 dws profile switch。可用组织名、profile 名、corpId 或 - 切回上一个组织。",
Example: ` dws profile use <corpId>
dws profile use --name "钉钉"
dws profile use -`,
@@ -104,21 +103,18 @@ func newProfileUseCommand() *cobra.Command {
func newProfileSwitchCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "switch [profile-selector|-]",
Short: "切换当前账号 profile",
Long: `切换默认账号 profile,并记录 previousProfile 以支持 dws profile switch - 快速切回。
Use: "switch [name|corpId|-]",
Short: "切换当前组织 profile",
Long: `切换默认组织 profile,并记录 previousProfile 以支持 dws profile switch - 快速切回。
选择器支持 corpId:userId、corpId:userName、corpName:userId、corpName:userName,
也兼容单独的 corpId、唯一 corpName 和本地 profile 名。组织或账号名称重名时会报错,
要求改用稳定的 corpId:userId。不带参数时交互选择;单次执行请使用全局 --profile。`,
不带参数时,交互终端会展示组织选择器;非交互环境请显式传入组织名、profile 名或 corpId。
需要只影响单次业务命令时,请使用全局 --profile。`,
Example: ` dws profile switch
dws profile switch <corpId>
dws profile switch <corpId>:<userId>
dws profile switch "<corpName>:<userName>"
dws profile switch --corpId <corpId>
dws profile switch --name "钉钉"
dws profile switch -
dws --profile <corpId>:<userId> contact user get-self`,
dws --profile <corpId> contact user get-self`,
Args: cobra.MaximumNArgs(1),
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -143,13 +139,6 @@ func addProfileSwitchSelectorFlags(cmd *cobra.Command) {
var (
profileSwitchSelector = selectProfileSwitchProfile
profileSwitchInteractiveTerminal = isInteractiveTerminal
profileSwitchTUIRunner = runProfileSwitchTUI
profileEnsureProfilesMigration = authpkg.EnsureProfilesMigration
profileLoadProfiles = authpkg.LoadProfiles
profileLoadTokenData = authpkg.LoadTokenDataForProfile
profileUsePrevious = authpkg.UsePreviousProfile
profileSetCurrent = authpkg.SetCurrentProfile
profileRunTeaProgram = (*tea.Program).Run
)
const (
@@ -229,9 +218,9 @@ func switchProfileAndWrite(cmd *cobra.Command, configDir, selector string, usedT
err error
)
if strings.TrimSpace(selector) == "-" {
profile, err = profileUsePrevious(configDir)
profile, err = authpkg.UsePreviousProfile(configDir)
} else {
profile, err = profileSetCurrent(configDir, selector)
profile, err = authpkg.SetCurrentProfile(configDir, selector)
}
if err != nil {
return apperrors.NewValidation(err.Error())
@@ -240,7 +229,7 @@ func switchProfileAndWrite(cmd *cobra.Command, configDir, selector string, usedT
clearCompatCache()
format, _ := cmd.Root().PersistentFlags().GetString("format")
if strings.EqualFold(strings.TrimSpace(format), "json") && !(usedTUI && authLoginAllowsInteractiveDefault(cmd, format)) {
cfg, loadErr := profileLoadProfiles(configDir)
cfg, loadErr := authpkg.LoadProfiles(configDir)
if loadErr != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to load profiles: %v", loadErr))
}
@@ -252,12 +241,12 @@ func switchProfileAndWrite(cmd *cobra.Command, configDir, selector string, usedT
func selectProfileSwitchProfile(cmd *cobra.Command, configDir string) (string, error) {
if !profileSwitchInteractiveTerminal() {
return "", apperrors.NewValidation("profile selector required in non-interactive mode; use dws profile switch <corpId|corpId:userId|corpName:userName>")
return "", apperrors.NewValidation("profile selector required in non-interactive mode; use dws profile switch <name|corpId>")
}
if err := profileEnsureProfilesMigration(configDir); err != nil {
if err := authpkg.EnsureProfilesMigration(configDir); err != nil {
return "", apperrors.NewInternal(fmt.Sprintf("failed to migrate profiles: %v", err))
}
cfg, err := profileLoadProfiles(configDir)
cfg, err := authpkg.LoadProfiles(configDir)
if err != nil {
return "", apperrors.NewInternal(fmt.Sprintf("failed to load profiles: %v", err))
}
@@ -266,9 +255,12 @@ func selectProfileSwitchProfile(cmd *cobra.Command, configDir string) (string, e
}
choice := strings.TrimSpace(cfg.CurrentProfile)
if choice == "" {
choice = authpkg.ProfileSelector(cfg.Profiles[0])
choice = strings.TrimSpace(cfg.PrimaryProfile)
}
return profileSwitchTUIRunner(cmd, cfg, choice)
if choice == "" {
choice = cfg.Profiles[0].CorpID
}
return runProfileSwitchTUI(cmd, cfg, choice)
}
func runProfileSwitchTUI(cmd *cobra.Command, cfg *authpkg.ProfilesConfig, selectedCorpID string) (string, error) {
@@ -280,7 +272,7 @@ func runProfileSwitchTUI(cmd *cobra.Command, cfg *authpkg.ProfilesConfig, select
tea.WithOutput(cmd.ErrOrStderr()),
tea.WithContext(cmd.Context()),
)
finalModel, err := profileRunTeaProgram(program)
finalModel, err := program.Run()
if err != nil {
if errors.Is(err, tea.ErrInterrupted) {
return "", apperrors.NewValidation("组织选择中止: user aborted")
@@ -308,7 +300,7 @@ func newProfileSwitchTUIModel(cfg *authpkg.ProfilesConfig, selectedCorpID string
if cfg != nil {
model.profiles = profileSwitchSortedProfiles(cfg.Profiles)
}
model.selected = profileSwitchProfileIndex(model.profiles, selectedCorpID, cfg)
model.selected = profileSwitchProfileIndex(model.profiles, selectedCorpID)
if model.selected < 0 {
model.selected = 0
}
@@ -317,7 +309,40 @@ func newProfileSwitchTUIModel(cfg *authpkg.ProfilesConfig, selectedCorpID string
}
func profileSwitchSortedProfiles(profiles []authpkg.Profile) []authpkg.Profile {
return append([]authpkg.Profile(nil), profiles...)
sorted := append([]authpkg.Profile(nil), profiles...)
sort.SliceStable(sorted, func(i, j int) bool {
left, leftOK := profileSwitchSortTime(sorted[i])
right, rightOK := profileSwitchSortTime(sorted[j])
if leftOK && rightOK && !left.Equal(right) {
return left.After(right)
}
if leftOK != rightOK {
return leftOK
}
return false
})
return sorted
}
func profileSwitchSortTime(p authpkg.Profile) (time.Time, bool) {
for _, raw := range []string{p.LastLoginAt, p.UpdatedAt, p.LastUsedAt} {
if t, ok := parseProfileSwitchTime(raw); ok {
return t, true
}
}
return time.Time{}, false
}
func parseProfileSwitchTime(raw string) (time.Time, bool) {
raw = strings.TrimSpace(raw)
if raw == "" {
return time.Time{}, false
}
t, err := time.Parse(time.RFC3339, raw)
if err != nil {
return time.Time{}, false
}
return t, true
}
func (m profileSwitchTUIModel) Init() tea.Cmd {
@@ -428,31 +453,17 @@ func (m profileSwitchTUIModel) selectedCorpID() string {
if m.selected < 0 || m.selected >= len(m.profiles) {
return ""
}
return authpkg.ProfileSelector(m.profiles[m.selected])
return strings.TrimSpace(m.profiles[m.selected].CorpID)
}
func profileSwitchProfileIndex(profiles []authpkg.Profile, selector string, cfg *authpkg.ProfilesConfig) int {
selector = strings.TrimSpace(selector)
if corpID, userID, exact := authpkg.ParseIdentitySelector(selector); exact {
for i, p := range profiles {
if strings.TrimSpace(p.CorpID) == corpID && strings.TrimSpace(p.UserID) == userID {
return i
}
}
return -1
}
fallback := -1
func profileSwitchProfileIndex(profiles []authpkg.Profile, corpID string) int {
corpID = strings.TrimSpace(corpID)
for i, p := range profiles {
if strings.TrimSpace(p.CorpID) == selector {
if fallback < 0 {
fallback = i
}
if profileIsOrgCurrent(p, cfg) {
return i
}
if strings.TrimSpace(p.CorpID) == corpID {
return i
}
}
return fallback
return -1
}
func profileSwitchOptionLabel(p authpkg.Profile, cfg *authpkg.ProfilesConfig) string {
@@ -464,29 +475,11 @@ func profileSwitchOptionLabel(p authpkg.Profile, cfg *authpkg.ProfilesConfig) st
}
func profileSwitchProfileCells(p authpkg.Profile, cfg *authpkg.ProfilesConfig) (string, string) {
orgName := profileOrgName(p)
if cfg != nil {
sameCorp := 0
for _, candidate := range cfg.Profiles {
if candidate.CorpID == p.CorpID {
sameCorp++
}
}
if sameCorp > 1 {
user := strings.TrimSpace(p.UserName)
if user == "" {
user = strings.TrimSpace(p.UserID)
}
if user != "" {
orgName += " / " + user
}
}
}
return orgName, profileSwitchProfileStatus(p, cfg)
return profileOrgName(p), profileSwitchProfileStatus(p, cfg)
}
func profileSwitchProfileStatus(p authpkg.Profile, cfg *authpkg.ProfilesConfig) string {
if cfg != nil && profileSelectorSelectsProfile(cfg.CurrentProfile, p, profileIsOrgCurrent(p, cfg), profileCountForCorp(cfg, p.CorpID) <= 1) {
if cfg != nil && p.CorpID == cfg.CurrentProfile {
return "当前组织"
}
return ""
@@ -576,7 +569,6 @@ type profileUseResponse struct {
}
type profileView struct {
Profile string `json:"profile"`
CorpID string `json:"corpId"`
CorpName string `json:"corpName"`
UserID string `json:"userId,omitempty"`
@@ -590,16 +582,15 @@ type profileView struct {
LastUsedAt string `json:"lastUsedAt,omitempty"`
IsPrimary bool `json:"isPrimary"`
IsCurrent bool `json:"isCurrent"`
IsOrgCurrent bool `json:"isOrgCurrent"`
}
func writeProfileListJSON(w io.Writer, configDir string, cfg *authpkg.ProfilesConfig) error {
func writeProfileListJSON(w io.Writer, cfg *authpkg.ProfilesConfig) error {
resp := profileListResponse{
Success: true,
PrimaryProfile: cfg.PrimaryProfile,
CurrentProfile: cfg.CurrentProfile,
PreviousProfile: cfg.PreviousProfile,
Profiles: profileViews(configDir, cfg),
Profiles: profileViews(cfg),
}
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
@@ -615,50 +606,44 @@ func writeProfileUseJSON(w io.Writer, profile *authpkg.Profile, cfg *authpkg.Pro
primaryProfile = cfg.PrimaryProfile
currentProfile = cfg.CurrentProfile
}
resp.Profile = profileViewFromProfile(
*profile,
cfg,
primaryProfile,
currentProfile,
profileCountForCorp(cfg, profile.CorpID) <= 1,
nil,
)
resp.Profile = profileViewFromProfile(*profile, primaryProfile, currentProfile)
}
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(resp)
}
func writeProfileListTable(w io.Writer, configDir string, cfg *authpkg.ProfilesConfig) {
func writeProfileListTable(w io.Writer, cfg *authpkg.ProfilesConfig) {
if cfg == nil || len(cfg.Profiles) == 0 {
fmt.Fprintln(w, "未找到已登录 profile")
return
}
fmt.Fprintf(w, "%-3s %-28s %-34s %-10s %s\n", "CUR", "ORG_NAME", "CORP_ID", "STATUS", "USER")
fmt.Fprintf(w, "%-3s %-3s %-28s %-34s %-10s %s\n", "CUR", "PRI", "ORG_NAME", "CORP_ID", "STATUS", "USER")
for _, p := range cfg.Profiles {
view := profileViewFromProfile(
p,
cfg,
cfg.PrimaryProfile,
cfg.CurrentProfile,
profileCountForCorp(cfg, p.CorpID) == 1,
loadProfileTokenState(configDir, p),
)
current := ""
if view.IsCurrent {
if p.CorpID == cfg.CurrentProfile {
current = "*"
}
primary := ""
if p.CorpID == cfg.PrimaryProfile {
primary = "*"
}
user := p.UserName
if user == "" {
user = p.UserID
}
status := p.Status
if status == "" {
status = authpkg.ProfileStatusActive
}
fmt.Fprintf(
w,
"%-3s %-28s %-34s %-10s %s\n",
"%-3s %-3s %-28s %-34s %-10s %s\n",
current,
primary,
clipProfileCell(profileOrgName(p), 28),
clipProfileCell(p.CorpID, 34),
view.Status,
status,
user,
)
}
@@ -686,40 +671,19 @@ func profileOrgName(p authpkg.Profile) string {
return strings.TrimSpace(p.CorpID)
}
type profileTokenState struct {
Status string
ExpiresAt string
RefreshExpAt string
}
func profileViews(configDir string, cfg *authpkg.ProfilesConfig) []profileView {
func profileViews(cfg *authpkg.ProfilesConfig) []profileView {
if cfg == nil {
return nil
}
views := make([]profileView, 0, len(cfg.Profiles))
for _, p := range cfg.Profiles {
views = append(views, profileViewFromProfile(
p,
cfg,
cfg.PrimaryProfile,
cfg.CurrentProfile,
profileCountForCorp(cfg, p.CorpID) == 1,
loadProfileTokenState(configDir, p),
))
views = append(views, profileViewFromProfile(p, cfg.PrimaryProfile, cfg.CurrentProfile))
}
return views
}
func profileViewFromProfile(
p authpkg.Profile,
cfg *authpkg.ProfilesConfig,
primaryProfile, currentProfile string,
onlyAccountInOrg bool,
tokenState *profileTokenState,
) profileView {
isOrgCurrent := profileIsOrgCurrent(p, cfg)
view := profileView{
Profile: authpkg.ProfileSelector(p),
func profileViewFromProfile(p authpkg.Profile, primaryProfile, currentProfile string) profileView {
return profileView{
CorpID: p.CorpID,
CorpName: profileOrgName(p),
UserID: p.UserID,
@@ -731,74 +695,9 @@ func profileViewFromProfile(
RefreshExpAt: p.RefreshExpAt,
LastLoginAt: p.LastLoginAt,
LastUsedAt: p.LastUsedAt,
IsPrimary: profileSelectorSelectsProfile(primaryProfile, p, isOrgCurrent, onlyAccountInOrg),
IsCurrent: profileSelectorSelectsProfile(currentProfile, p, isOrgCurrent, onlyAccountInOrg),
IsOrgCurrent: isOrgCurrent,
IsPrimary: p.CorpID == primaryProfile,
IsCurrent: p.CorpID == currentProfile,
}
if tokenState != nil {
view.Status = tokenState.Status
view.ExpiresAt = tokenState.ExpiresAt
view.RefreshExpAt = tokenState.RefreshExpAt
}
return view
}
func loadProfileTokenState(configDir string, profile authpkg.Profile) *profileTokenState {
data, err := profileLoadTokenData(configDir, authpkg.ProfileSelector(profile))
if errors.Is(err, authpkg.ErrTokenDataNotFound) || (err == nil && data == nil) {
return &profileTokenState{Status: authpkg.ProfileStatusRevoked}
}
if err != nil {
return &profileTokenState{Status: authpkg.ProfileStatusUnavailable}
}
status := authpkg.ProfileStatusExpired
if data.IsAccessTokenValid() {
status = authpkg.ProfileStatusActive
}
return &profileTokenState{
Status: status,
ExpiresAt: profileTokenTime(data.ExpiresAt),
RefreshExpAt: profileTokenTime(data.RefreshExpAt),
}
}
func profileTokenTime(value time.Time) string {
if value.IsZero() {
return ""
}
return value.Format(time.RFC3339)
}
func profileSelectorSelectsProfile(selector string, profile authpkg.Profile, isOrgCurrent, onlyAccountInOrg bool) bool {
selector = strings.TrimSpace(selector)
if corpID, userID, exact := authpkg.ParseIdentitySelector(selector); exact {
return corpID == strings.TrimSpace(profile.CorpID) && userID == strings.TrimSpace(profile.UserID)
}
return selector == strings.TrimSpace(profile.CorpID) && (isOrgCurrent || onlyAccountInOrg)
}
func profileCountForCorp(cfg *authpkg.ProfilesConfig, corpID string) int {
if cfg == nil {
return 0
}
count := 0
for _, profile := range cfg.Profiles {
if strings.TrimSpace(profile.CorpID) == strings.TrimSpace(corpID) {
count++
}
}
return count
}
func profileIsOrgCurrent(profile authpkg.Profile, cfg *authpkg.ProfilesConfig) bool {
if cfg == nil {
return false
}
selector := strings.TrimSpace(cfg.OrgCurrentProfiles[strings.TrimSpace(profile.CorpID)])
if corpID, userID, exact := authpkg.ParseIdentitySelector(selector); exact {
return corpID == strings.TrimSpace(profile.CorpID) && userID == strings.TrimSpace(profile.UserID)
}
return profileCountForCorp(cfg, profile.CorpID) == 1
}
func clipProfileCell(value string, limit int) string {
+19 -205
View File
@@ -16,11 +16,9 @@ package app
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
tea "github.com/charmbracelet/bubbletea"
@@ -82,10 +80,8 @@ func TestProfileListRootCommandJSONIncludesCorpName(t *testing.T) {
if !resp.Success {
t.Fatal("success = false, want true")
}
if resp.PrimaryProfile != "" ||
resp.CurrentProfile != "corp_secondary:user-corp_secondary" ||
resp.PreviousProfile != "corp_primary:user-corp_primary" {
t.Fatalf("profile pointers = primary %q current %q previous %q", resp.PrimaryProfile, resp.CurrentProfile, resp.PreviousProfile)
if resp.PrimaryProfile != "corp_primary" || resp.CurrentProfile != "corp_secondary" || resp.PreviousProfile != "corp_primary" {
t.Fatalf("profile pointers = primary %q current %q previous %q, want corp_primary/corp_secondary/corp_primary", resp.PrimaryProfile, resp.CurrentProfile, resp.PreviousProfile)
}
if len(resp.Profiles) != 2 {
t.Fatalf("profiles len = %d, want 2", len(resp.Profiles))
@@ -100,181 +96,6 @@ func TestProfileListRootCommandJSONIncludesCorpName(t *testing.T) {
}
}
func TestProfileListRootCommandJSONIncludesAllAccountsInSameCorp(t *testing.T) {
first := authLogoutTestToken("corp_same")
first.UserID = "user_1"
first.UserName = "账号一"
second := authLogoutTestToken("corp_same")
second.AccessToken = "access-second"
second.RefreshToken = "refresh-second"
second.UserID = "user_2"
second.UserName = "账号二"
setupAuthLogoutProfiles(t, first, second)
cmd := NewRootCommand()
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"--format", "json", "profile", "list"})
if err := cmd.Execute(); err != nil {
t.Fatalf("profile list --format json error = %v\noutput:\n%s", err, out.String())
}
var resp profileListResponse
if err := json.Unmarshal(out.Bytes(), &resp); err != nil {
t.Fatalf("Unmarshal() error = %v\noutput:\n%s", err, out.String())
}
if len(resp.Profiles) != 2 {
t.Fatalf("profiles len = %d, want 2: %#v", len(resp.Profiles), resp.Profiles)
}
got := make(map[string]profileView, len(resp.Profiles))
for _, profile := range resp.Profiles {
got[profile.Profile] = profile
}
if _, ok := got["corp_same:user_1"]; !ok {
t.Fatalf("profiles missing corp_same:user_1: %#v", resp.Profiles)
}
current, ok := got["corp_same:user_2"]
if !ok {
t.Fatalf("profiles missing corp_same:user_2: %#v", resp.Profiles)
}
if !current.IsOrgCurrent || !current.IsCurrent || current.IsPrimary {
t.Fatalf("last login account markers = %#v, want org-current/current and deprecated primary=false", current)
}
if got["corp_same:user_1"].IsOrgCurrent {
t.Fatalf("older account unexpectedly marked org current: %#v", got["corp_same:user_1"])
}
}
func TestProfileListUsesRealIdentityTokenState(t *testing.T) {
token := authLogoutTestToken("corp_real")
token.ExpiresAt = time.Date(2026, 7, 16, 17, 38, 0, 0, time.Local)
token.RefreshExpAt = time.Date(2026, 8, 16, 17, 38, 0, 0, time.Local)
configDir := setupAuthLogoutProfiles(t, token)
cfg, err := authpkg.LoadProfiles(configDir)
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
cfg.Profiles[0].Status = authpkg.ProfileStatusActive
cfg.Profiles[0].ExpiresAt = "2026-07-16T22:29:00+08:00"
cfg.Profiles[0].RefreshExpAt = "2026-09-16T22:29:00+08:00"
if err := authpkg.SaveProfiles(configDir, cfg); err != nil {
t.Fatalf("SaveProfiles() error = %v", err)
}
cmd := NewRootCommand()
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"--format", "json", "profile", "list"})
if err := cmd.Execute(); err != nil {
t.Fatalf("profile list error = %v\noutput:\n%s", err, out.String())
}
var resp profileListResponse
if err := json.Unmarshal(out.Bytes(), &resp); err != nil {
t.Fatalf("Unmarshal() error = %v\noutput:\n%s", err, out.String())
}
if len(resp.Profiles) != 1 {
t.Fatalf("profiles len = %d, want 1", len(resp.Profiles))
}
got := resp.Profiles[0]
if got.ExpiresAt != token.ExpiresAt.Format(time.RFC3339) {
t.Fatalf("expiresAt = %q, want real token %q", got.ExpiresAt, token.ExpiresAt.Format(time.RFC3339))
}
if got.RefreshExpAt != token.RefreshExpAt.Format(time.RFC3339) {
t.Fatalf("refreshExpAt = %q, want real token %q", got.RefreshExpAt, token.RefreshExpAt.Format(time.RFC3339))
}
if got.Status != authpkg.ProfileStatusExpired {
t.Fatalf("status = %q, want expired", got.Status)
}
}
func TestProfileListDistinguishesMissingAndUnavailableTokenState(t *testing.T) {
originalLoad := profileLoadTokenData
t.Cleanup(func() { profileLoadTokenData = originalLoad })
profile := authpkg.Profile{CorpID: "corp", UserID: "user"}
profileLoadTokenData = func(string, string) (*authpkg.TokenData, error) {
return nil, authpkg.ErrTokenDataNotFound
}
if state := loadProfileTokenState("cfg", profile); state.Status != authpkg.ProfileStatusRevoked {
t.Fatalf("missing token status = %q, want revoked", state.Status)
}
profileLoadTokenData = func(string, string) (*authpkg.TokenData, error) {
return nil, errors.New("keychain unavailable")
}
if state := loadProfileTokenState("cfg", profile); state.Status != authpkg.ProfileStatusUnavailable {
t.Fatalf("unavailable token status = %q, want unavailable", state.Status)
}
}
func TestProfileListCurrentFlagsUseStoredExactSelectors(t *testing.T) {
first := authLogoutTestToken("corp_same")
first.UserID = "user_1"
first.UserName = "账号一"
second := authLogoutTestToken("corp_same")
second.AccessToken = "access-second"
second.RefreshToken = "refresh-second"
second.UserID = "user_2"
second.UserName = "账号二"
configDir := setupAuthLogoutProfiles(t, first, second)
cfg, err := authpkg.LoadProfiles(configDir)
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
cfg.PrimaryProfile = ""
cfg.CurrentProfile = "corp_same:user_1"
cfg.OrgCurrentProfiles["corp_same"] = "corp_same:user_1"
if err := authpkg.SaveProfiles(configDir, cfg); err != nil {
t.Fatalf("SaveProfiles() error = %v", err)
}
cmd := NewRootCommand()
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"--format", "json", "profile", "list"})
if err := cmd.Execute(); err != nil {
t.Fatalf("profile list error = %v\noutput:\n%s", err, out.String())
}
var resp profileListResponse
if err := json.Unmarshal(out.Bytes(), &resp); err != nil {
t.Fatalf("Unmarshal() error = %v\noutput:\n%s", err, out.String())
}
got := make(map[string]profileView, len(resp.Profiles))
for _, profile := range resp.Profiles {
got[profile.Profile] = profile
}
if !got["corp_same:user_1"].IsCurrent || !got["corp_same:user_1"].IsOrgCurrent {
t.Fatalf("first account flags = %#v, want current and org current", got["corp_same:user_1"])
}
if got["corp_same:user_2"].IsCurrent || got["corp_same:user_2"].IsOrgCurrent {
t.Fatalf("second account flags = %#v, want neither current nor org current", got["corp_same:user_2"])
}
if got["corp_same:user_1"].IsPrimary || got["corp_same:user_2"].IsPrimary {
t.Fatalf("deprecated isPrimary should be false without primaryProfile: %#v", got)
}
}
func TestProfileListTableOmitsDeprecatedPrimaryColumn(t *testing.T) {
setupAuthLogoutProfiles(t, authLogoutTestToken("corp_table"))
cmd := NewRootCommand()
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
cmd.SetArgs([]string{"profile", "list"})
if err := cmd.Execute(); err != nil {
t.Fatalf("profile list error = %v\noutput:\n%s", err, out.String())
}
header := strings.SplitN(out.String(), "\n", 2)[0]
if strings.Contains(header, "PRI") {
t.Fatalf("profile list header still contains deprecated PRI column: %q", header)
}
}
func TestProfileUseRootCommandSwitchesOrganizationAndLegacyMirror(t *testing.T) {
configDir := setupAuthLogoutProfiles(t,
authLogoutTestToken("corp_primary"),
@@ -289,7 +110,6 @@ func TestProfileUseRootCommandSwitchesOrganizationAndLegacyMirror(t *testing.T)
if err := cmd.Execute(); err != nil {
t.Fatalf("profile use corp_primary error = %v\noutput:\n%s", err, out.String())
}
CloseFileLogger()
if !bytes.Contains(out.Bytes(), []byte("组织: corp_primary org")) {
t.Fatalf("profile use output should include organization name:\n%s", out.String())
}
@@ -297,9 +117,8 @@ func TestProfileUseRootCommandSwitchesOrganizationAndLegacyMirror(t *testing.T)
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
if cfg.CurrentProfile != "corp_primary:user-corp_primary" ||
cfg.PreviousProfile != "corp_secondary:user-corp_secondary" {
t.Fatalf("profile pointers = current %q previous %q", cfg.CurrentProfile, cfg.PreviousProfile)
if cfg.CurrentProfile != "corp_primary" || cfg.PreviousProfile != "corp_secondary" {
t.Fatalf("profile pointers = current %q previous %q, want corp_primary/corp_secondary", cfg.CurrentProfile, cfg.PreviousProfile)
}
legacyToken, err := authpkg.LoadTokenData(configDir)
if err != nil {
@@ -317,7 +136,6 @@ func TestProfileUseRootCommandSwitchesOrganizationAndLegacyMirror(t *testing.T)
if err := cmd.Execute(); err != nil {
t.Fatalf("profile use - error = %v\noutput:\n%s", err, out.String())
}
CloseFileLogger()
if !bytes.Contains(out.Bytes(), []byte("组织: corp_secondary org")) {
t.Fatalf("profile use - output should include organization name:\n%s", out.String())
}
@@ -325,9 +143,8 @@ func TestProfileUseRootCommandSwitchesOrganizationAndLegacyMirror(t *testing.T)
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
if cfg.CurrentProfile != "corp_secondary:user-corp_secondary" ||
cfg.PreviousProfile != "corp_primary:user-corp_primary" {
t.Fatalf("profile pointers = current %q previous %q", cfg.CurrentProfile, cfg.PreviousProfile)
if cfg.CurrentProfile != "corp_secondary" || cfg.PreviousProfile != "corp_primary" {
t.Fatalf("profile pointers = current %q previous %q, want corp_secondary/corp_primary", cfg.CurrentProfile, cfg.PreviousProfile)
}
legacyToken, err = authpkg.LoadTokenData(configDir)
if err != nil {
@@ -359,9 +176,8 @@ func TestProfileSwitchRootCommandSwitchesPrimaryOrganizationAndLegacyMirror(t *t
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
if cfg.CurrentProfile != "corp_primary:user-corp_primary" ||
cfg.PreviousProfile != "corp_secondary:user-corp_secondary" {
t.Fatalf("profile pointers = current %q previous %q", cfg.CurrentProfile, cfg.PreviousProfile)
if cfg.CurrentProfile != "corp_primary" || cfg.PreviousProfile != "corp_secondary" {
t.Fatalf("profile pointers = current %q previous %q, want corp_primary/corp_secondary", cfg.CurrentProfile, cfg.PreviousProfile)
}
legacyToken, err := authpkg.LoadTokenData(configDir)
if err != nil {
@@ -386,13 +202,12 @@ func TestProfileSwitchRootCommandSupportsCorpIDFlag(t *testing.T) {
if err := cmd.Execute(); err != nil {
t.Fatalf("profile switch --corpId error = %v\noutput:\n%s", err, out.String())
}
CloseFileLogger()
cfg, err := authpkg.LoadProfiles(configDir)
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
if cfg.CurrentProfile != "corp_primary:user-corp_primary" {
t.Fatalf("currentProfile = %q, want corp_primary:user-corp_primary", cfg.CurrentProfile)
if cfg.CurrentProfile != "corp_primary" {
t.Fatalf("currentProfile = %q, want corp_primary", cfg.CurrentProfile)
}
cmd = NewRootCommand()
@@ -403,13 +218,12 @@ func TestProfileSwitchRootCommandSupportsCorpIDFlag(t *testing.T) {
if err := cmd.Execute(); err != nil {
t.Fatalf("profile use --corp error = %v\noutput:\n%s", err, out.String())
}
CloseFileLogger()
cfg, err = authpkg.LoadProfiles(configDir)
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
if cfg.CurrentProfile != "corp_secondary:user-corp_secondary" {
t.Fatalf("currentProfile = %q, want corp_secondary:user-corp_secondary", cfg.CurrentProfile)
if cfg.CurrentProfile != "corp_secondary" {
t.Fatalf("currentProfile = %q, want corp_secondary", cfg.CurrentProfile)
}
}
@@ -469,8 +283,8 @@ func TestProfileSwitchNoArgsUsesTUISelector(t *testing.T) {
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
if cfg.CurrentProfile != "corp_primary:user-corp_primary" {
t.Fatalf("currentProfile = %q, want corp_primary:user-corp_primary", cfg.CurrentProfile)
if cfg.CurrentProfile != "corp_primary" {
t.Fatalf("currentProfile = %q, want corp_primary", cfg.CurrentProfile)
}
}
@@ -540,7 +354,7 @@ func TestProfileSwitchTUIViewUsesFixedOuterTable(t *testing.T) {
}
}
func TestProfileSwitchTUIPreservesStoredOrderInsteadOfSortingByTime(t *testing.T) {
func TestProfileSwitchTUISortsLatestLoggedInProfilesFirst(t *testing.T) {
cfg := &authpkg.ProfilesConfig{
PrimaryProfile: "old",
CurrentProfile: "old",
@@ -552,7 +366,7 @@ func TestProfileSwitchTUIPreservesStoredOrderInsteadOfSortingByTime(t *testing.T
}
model := newProfileSwitchTUIModel(cfg, "old")
gotOrder := []string{model.profiles[0].CorpID, model.profiles[1].CorpID, model.profiles[2].CorpID}
wantOrder := []string{"old", "new", "fallback"}
wantOrder := []string{"new", "fallback", "old"}
if strings.Join(gotOrder, ",") != strings.Join(wantOrder, ",") {
t.Fatalf("profile order = %v, want %v", gotOrder, wantOrder)
}
@@ -689,8 +503,8 @@ func TestProfileUseNoArgsUsesTUISelector(t *testing.T) {
if err != nil {
t.Fatalf("LoadProfiles() error = %v", err)
}
if cfg.CurrentProfile != "corp_primary:user-corp_primary" {
t.Fatalf("currentProfile = %q, want corp_primary:user-corp_primary", cfg.CurrentProfile)
if cfg.CurrentProfile != "corp_primary" {
t.Fatalf("currentProfile = %q, want corp_primary", cfg.CurrentProfile)
}
}
@@ -731,7 +545,7 @@ func TestWriteProfileListTableIncludesCorpName(t *testing.T) {
},
}
var buf bytes.Buffer
writeProfileListTable(&buf, "", cfg)
writeProfileListTable(&buf, cfg)
out := buf.String()
for _, want := range []string{
"ORG_NAME",
-165
View File
@@ -1,165 +0,0 @@
package app
import (
"context"
"errors"
"io"
"testing"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
tea "github.com/charmbracelet/bubbletea"
"github.com/spf13/cobra"
)
func TestCrossPlatformCoverageProfileRemainingCoverage(t *testing.T) {
oldMigrate := profileEnsureProfilesMigration
oldLoad := profileLoadProfiles
oldPrevious := profileUsePrevious
oldCurrent := profileSetCurrent
oldInteractive := profileSwitchInteractiveTerminal
oldTUI := profileSwitchTUIRunner
oldProgram := profileRunTeaProgram
t.Cleanup(func() {
profileEnsureProfilesMigration = oldMigrate
profileLoadProfiles = oldLoad
profileUsePrevious = oldPrevious
profileSetCurrent = oldCurrent
profileSwitchInteractiveTerminal = oldInteractive
profileSwitchTUIRunner = oldTUI
profileRunTeaProgram = oldProgram
})
fail := errors.New("failure")
list := newProfileListCommand()
_, _, _ = authCoverageRoot(list, "table", false)
profileEnsureProfilesMigration = func(string) error { return fail }
if err := list.RunE(list, nil); err == nil {
t.Fatal("profile-list migration should fail")
}
profileEnsureProfilesMigration = func(string) error { return nil }
profileLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) { return nil, fail }
if err := list.RunE(list, nil); err == nil {
t.Fatal("profile-list load should fail")
}
selectorCmd := &cobra.Command{}
addProfileSwitchSelectorFlags(selectorCmd)
_ = selectorCmd.Flags().Set("name", " ")
if _, err := profileSwitchSelectorFromCommand(selectorCmd, nil); err == nil {
t.Fatal("blank profile selector should fail")
}
profileSetCurrent = func(string, string) (*authpkg.Profile, error) {
return &authpkg.Profile{CorpID: "ding", CorpName: "Corp"}, nil
}
profileUsePrevious = func(string) (*authpkg.Profile, error) { return nil, fail }
cmd := &cobra.Command{}
_, _, _ = authCoverageRoot(cmd, "table", false)
if err := switchProfileAndWrite(cmd, "cfg", "-", false); err == nil {
t.Fatal("previous-profile error should fail")
}
profileUsePrevious = func(string) (*authpkg.Profile, error) { return &authpkg.Profile{CorpID: "previous"}, nil }
if err := switchProfileAndWrite(cmd, "cfg", "-", false); err != nil {
t.Fatal(err)
}
jsonCmd := &cobra.Command{}
_, _, _ = authCoverageRoot(jsonCmd, "json", false)
profileLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) { return nil, fail }
if err := switchProfileAndWrite(jsonCmd, "cfg", "ding", false); err == nil {
t.Fatal("JSON profile load should fail")
}
profileLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) {
return &authpkg.ProfilesConfig{CurrentProfile: "ding"}, nil
}
jsonCmd.SetOut(&appFailWriter{err: fail})
if err := switchProfileAndWrite(jsonCmd, "cfg", "ding", false); err == nil {
t.Fatal("JSON profile write should fail")
}
profileSwitchInteractiveTerminal = func() bool { return true }
profileEnsureProfilesMigration = func(string) error { return fail }
if _, err := selectProfileSwitchProfile(cmd, "cfg"); err == nil {
t.Fatal("selector migration should fail")
}
profileEnsureProfilesMigration = func(string) error { return nil }
profileLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) { return nil, fail }
if _, err := selectProfileSwitchProfile(cmd, "cfg"); err == nil {
t.Fatal("selector load should fail")
}
profileLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) { return nil, nil }
if _, err := selectProfileSwitchProfile(cmd, "cfg"); err == nil {
t.Fatal("empty selector profiles should fail")
}
choices := []string{}
profileSwitchTUIRunner = func(_ *cobra.Command, _ *authpkg.ProfilesConfig, choice string) (string, error) {
choices = append(choices, choice)
return choice, nil
}
for _, cfg := range []*authpkg.ProfilesConfig{
{CurrentProfile: "current", PrimaryProfile: "primary", Profiles: []authpkg.Profile{{CorpID: "first"}}},
{PrimaryProfile: "primary", Profiles: []authpkg.Profile{{CorpID: "first"}}},
{Profiles: []authpkg.Profile{{CorpID: "first"}}},
} {
profileLoadProfiles = func(string) (*authpkg.ProfilesConfig, error) { return cfg, nil }
if _, err := selectProfileSwitchProfile(cmd, "cfg"); err != nil {
t.Fatal(err)
}
}
if len(choices) != 3 || choices[0] != "current" || choices[1] != "first" || choices[2] != "first" {
t.Fatalf("profile choices = %#v", choices)
}
tuiCmd := &cobra.Command{}
tuiCmd.SetContext(context.Background())
tuiCmd.SetIn(io.NopCloser(&emptyReader{}))
tuiCmd.SetErr(io.Discard)
cfg := &authpkg.ProfilesConfig{Profiles: []authpkg.Profile{{CorpID: "ding"}}}
profileRunTeaProgram = func(*tea.Program) (tea.Model, error) { return nil, tea.ErrInterrupted }
if _, err := runProfileSwitchTUI(tuiCmd, cfg, "ding"); err == nil {
t.Fatal("interrupted TUI should fail")
}
profileRunTeaProgram = func(*tea.Program) (tea.Model, error) { return nil, fail }
if _, err := runProfileSwitchTUI(tuiCmd, cfg, "ding"); err == nil {
t.Fatal("failed TUI should fail")
}
profileRunTeaProgram = func(*tea.Program) (tea.Model, error) { return structModel{}, nil }
if _, err := runProfileSwitchTUI(tuiCmd, cfg, "ding"); err == nil {
t.Fatal("wrong TUI model should fail")
}
for _, model := range []profileSwitchTUIModel{{aborted: true}, {submitted: false}} {
model := model
profileRunTeaProgram = func(*tea.Program) (tea.Model, error) { return model, nil }
if _, err := runProfileSwitchTUI(tuiCmd, cfg, "ding"); err == nil {
t.Fatal("aborted TUI should fail")
}
}
final := newProfileSwitchTUIModel(cfg, "ding")
final.submitted = true
profileRunTeaProgram = func(*tea.Program) (tea.Model, error) { return final, nil }
if got, err := runProfileSwitchTUI(tuiCmd, cfg, "ding"); err != nil || got != "ding" {
t.Fatalf("submitted TUI = %q, %v", got, err)
}
profiles := make([]authpkg.Profile, 8)
model := profileSwitchTUIModel{profiles: profiles, selected: 7, offset: 99}
model.ensureSelectedVisible()
if model.offset != 3 {
t.Fatalf("clamped offset = %d", model.offset)
}
model.offset = -2
model.selected = 0
model.ensureSelectedVisible()
if model.offset != 0 {
t.Fatalf("negative offset = %d", model.offset)
}
}
type emptyReader struct{}
func (*emptyReader) Read([]byte) (int, error) { return 0, io.EOF }
type structModel struct{}
func (structModel) Init() tea.Cmd { return nil }
func (structModel) Update(tea.Msg) (tea.Model, tea.Cmd) { return structModel{}, nil }
func (structModel) View() string { return "" }
+3 -12
View File
@@ -18,11 +18,6 @@ import (
"github.com/spf13/cobra"
)
var (
recoverySavePlan = (*recovery.Store).SavePlan
recoverySaveAnalysis = (*recovery.Store).SaveAnalysis
)
func newRecoveryCommand(_ context.Context, loader cli.CatalogLoader, flags *GlobalFlags) *cobra.Command {
var (
planUseLast bool
@@ -65,7 +60,7 @@ func newRecoveryCommand(_ context.Context, loader cli.CatalogLoader, flags *Glob
EnableDocSearch: true,
})
recovery.HydratePlanForEvent(last.EventID, last.Context, last.Replay, &plan)
if err := recoverySavePlan(store, last.EventID, plan); err != nil {
if err := store.SavePlan(last.EventID, plan); err != nil {
return fmt.Errorf("保存恢复计划失败: %w", err)
}
@@ -95,7 +90,7 @@ func newRecoveryCommand(_ context.Context, loader cli.CatalogLoader, flags *Glob
planner := recovery.NewPlanner(runtime)
executor := recovery.NewExecutor(planner, runtime)
bundle := executor.Execute(cmd.Context(), *last)
if err := recoverySaveAnalysis(store, last.EventID, bundle.Plan, bundle); err != nil {
if err := store.SaveAnalysis(last.EventID, bundle.Plan, bundle); err != nil {
return fmt.Errorf("保存恢复分析失败: %w", err)
}
@@ -333,11 +328,7 @@ func (r *recoveryRuntime) CallToolDirect(ctx context.Context, serverID, toolName
if err != nil {
return nil, err
}
authToken, err := resolveRuntimeAuthToken(ctx, recoveryRuntimeToken(r.flags))
if err != nil {
return nil, tokenResolutionError(err)
}
tc := r.transport.WithAuth(authToken, resolveIdentityHeaders())
tc := r.transport.WithAuth(resolveRuntimeAuthToken(ctx, recoveryRuntimeToken(r.flags)), resolveIdentityHeaders())
result, err := tc.CallTool(ctx, endpoint, toolName, args)
if err != nil {
return nil, err
@@ -1,153 +0,0 @@
package app
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/cli"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/recovery"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
)
func recoveryCoverageRun(cmdArgs ...string) (string, error) {
cmd := newRecoveryCommand(context.Background(), cli.StaticLoader{}, &GlobalFlags{})
out := &strings.Builder{}
cmd.SetOut(out)
cmd.SetErr(io.Discard)
cmd.SetArgs(cmdArgs)
err := cmd.Execute()
return out.String(), err
}
func TestCrossPlatformCoverageRecoveryCommandRemainingCoverage(t *testing.T) {
oldSavePlan, oldSaveAnalysis := recoverySavePlan, recoverySaveAnalysis
t.Cleanup(func() {
recoverySavePlan, recoverySaveAnalysis = oldSavePlan, oldSaveAnalysis
})
configDir := t.TempDir()
t.Setenv("DWS_CONFIG_DIR", configDir)
store := recovery.NewStore(configDir)
last, err := store.Capture(recovery.RecoveryContext{ServerID: "doc", ToolName: "get"})
if err != nil {
t.Fatal(err)
}
recoverySavePlan = func(*recovery.Store, string, recovery.RecoveryPlan) error { return errors.New("save plan") }
if _, err := recoveryCoverageRun("plan", "--last"); err == nil {
t.Fatal("injected plan save failure succeeded")
}
recoverySavePlan = oldSavePlan
recoverySaveAnalysis = func(*recovery.Store, string, recovery.RecoveryPlan, recovery.RecoveryBundle) error {
return errors.New("save analysis")
}
if _, err := recoveryCoverageRun("execute", "--last"); err == nil {
t.Fatal("injected analysis save failure succeeded")
}
recoverySaveAnalysis = oldSaveAnalysis
parent := newRecoveryCommand(context.Background(), nil, nil)
parent.SetOut(io.Discard)
if err := parent.RunE(parent, nil); err != nil {
t.Fatal(err)
}
if out, err := recoveryCoverageRun("plan", "--last"); err != nil || !strings.Contains(out, last.EventID) {
t.Fatalf("recovery plan = %q, %v", out, err)
}
if out, err := recoveryCoverageRun("execute", "--event-id", last.EventID); err != nil || out == "" {
t.Fatalf("recovery execute = %q, %v", out, err)
}
for _, args := range [][]string{
{"finalize"},
{"finalize", "--event-id", last.EventID},
{"finalize", "--event-id", last.EventID, "--outcome", "unknown"},
{"finalize", "--event-id", last.EventID, "--outcome", "recovered", "--execution-file", "missing"},
} {
if _, err := recoveryCoverageRun(args...); err == nil {
t.Fatalf("recovery finalize %#v should fail", args)
}
}
executionPath := filepath.Join(t.TempDir(), "execution.json")
if err := os.WriteFile(executionPath, []byte(`{"action":"retry","attempt":1,"result":"ok"}`), 0o600); err != nil {
t.Fatal(err)
}
if out, err := recoveryCoverageRun("finalize", "--event-id", last.EventID, "--outcome", "handoff", "--execution-file", executionPath); err != nil || !strings.Contains(out, "execution_recorded") {
t.Fatalf("recovery finalize = %q, %v", out, err)
}
if _, err := recoveryCoverageRun("finalize", "--event-id", last.EventID, "--outcome", "failed"); err != nil {
t.Fatal(err)
}
if _, err := loadRecoverySnapshot(store, true, last.EventID); err == nil {
t.Fatal("conflicting snapshot selectors should fail")
}
if _, err := loadRecoverySnapshot(store, false, "missing"); err == nil {
t.Fatal("missing event snapshot should fail")
}
if _, err := loadRecoverySnapshot(store, false, ""); err == nil {
t.Fatal("empty snapshot selector should fail")
}
missingStore := recovery.NewStore(t.TempDir())
if _, err := loadRecoverySnapshot(missingStore, true, ""); err == nil {
t.Fatal("missing latest snapshot should fail")
}
eventsPath := filepath.Join(configDir, "recovery", "recovery_events.jsonl")
if err := os.Remove(eventsPath); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(eventsPath, 0o700); err != nil {
t.Fatal(err)
}
if _, err := recoveryCoverageRun("plan", "--last"); err == nil {
t.Fatal("recovery plan save should fail")
}
if _, err := recoveryCoverageRun("execute", "--last"); err == nil {
t.Fatal("recovery analysis save should fail")
}
if _, err := recoveryCoverageRun("finalize", "--event-id", last.EventID, "--outcome", "recovered"); err == nil {
t.Fatal("recovery finalization save should fail")
}
}
func TestCrossPlatformCoverageRecoveryExecutionAndRuntimeRemainingCoverage(t *testing.T) {
t.Setenv("DINGTALK_DEVDOC_MCP_URL", "http://127.0.0.1:1")
path := filepath.Join(t.TempDir(), "execution.json")
if err := os.WriteFile(path, []byte(`{"attempts":{}}`), 0o600); err != nil {
t.Fatal(err)
}
if _, err := loadRecoveryExecution(path); err == nil {
t.Fatal("invalid attempts should fail")
}
if _, err := decodeRecoveryAttempts([]byte(`[{}`), nil, "", ""); err == nil {
t.Fatal("invalid attempt array should fail")
}
fail := errors.New("catalog")
SetDynamicServers(nil)
runtime := &recoveryRuntime{
loader: cli.CatalogLoaderFrom(cli.Catalog{}, fail),
transport: transport.NewClient(nil),
}
if _, err := runtime.CallToolDirect(context.Background(), "missing", "tool", nil); !errors.Is(err, fail) {
t.Fatalf("direct resolution error = %v", err)
}
if got, err := runtime.Search(context.Background(), "query", recovery.RecoveryContext{}); err == nil || got.DocSearch.Status != "error" {
t.Fatalf("search error = %#v, %v", got, err)
}
if got := parseDocSearchItems(&transport.ToolCallResult{Content: map[string]any{}, Blocks: []transport.ContentBlock{{Text: "not-json"}}}); got != nil {
t.Fatalf("empty doc search items = %#v", got)
}
for _, payload := range []map[string]any{
{"data": map[string]any{}},
{"result": map[string]any{}},
} {
if got := parseDocSearchItemsFromMap(payload); got != nil {
t.Fatalf("empty nested doc search items = %#v", got)
}
}
}
-123
View File
@@ -1,123 +0,0 @@
package app
import (
"bytes"
"context"
"errors"
"os"
"strings"
"testing"
authpkg "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/auth"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/event/consume"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/transport"
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/mcptypes"
"github.com/spf13/cobra"
)
func TestCrossPlatformCoverageEventStopPreviewConfirmationAndStdinCoverage(t *testing.T) {
originalNormalize := eventNormalizeAs
t.Cleanup(func() { eventNormalizeAs = originalNormalize })
eventNormalizeAs = func(string) (string, error) { return "app", nil }
newStopRoot := func(dryRun, yes bool) (*cobra.Command, *bytes.Buffer) {
root := &cobra.Command{Use: "dws"}
root.PersistentFlags().Bool("dry-run", dryRun, "")
root.PersistentFlags().Bool("yes", yes, "")
root.AddCommand(newEventStopCommand())
var output bytes.Buffer
root.SetOut(&output)
root.SetErr(&output)
return root, &output
}
root, output := newStopRoot(true, false)
root.SetArgs([]string{"stop"})
if err := root.Execute(); err != nil || !strings.Contains(output.String(), "dry_run") {
t.Fatalf("event stop dry-run = %v, %q", err, output.String())
}
root, _ = newStopRoot(false, false)
root.SetArgs([]string{"stop"})
if err := root.Execute(); err == nil || !strings.Contains(err.Error(), "--yes") {
t.Fatalf("event stop confirmation error = %v", err)
}
originalStdin := os.Stdin
t.Cleanup(func() { os.Stdin = originalStdin })
closed, err := os.CreateTemp(t.TempDir(), "closed")
if err != nil {
t.Fatal(err)
}
if err := closed.Close(); err != nil {
t.Fatal(err)
}
os.Stdin = closed
if shouldWatchStdinEOF(0, 0) {
t.Fatal("shouldWatchStdinEOF(closed stdin) = true")
}
read, write, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer read.Close()
defer write.Close()
os.Stdin = read
if !shouldWatchStdinEOF(0, 0) {
t.Fatal("shouldWatchStdinEOF(pipe) = false")
}
var cfg consume.Config
applyEventConsumeStdin(nil, 0, 0, strings.NewReader("ignored"))
applyEventConsumeStdin(&cfg, 1, 0, strings.NewReader("bounded"))
if cfg.Stdin != nil {
t.Fatal("bounded consume received stdin watcher")
}
wantReader := strings.NewReader("pipe")
applyEventConsumeStdin(&cfg, 0, 0, wantReader)
if cfg.Stdin != wantReader {
t.Fatal("unbounded pipe consume did not receive stdin")
}
}
func TestCrossPlatformCoverageRunnerPluginStdioAndDryRunErrorCoverage(t *testing.T) {
if _, err := (*runtimeRunner)(nil).Run(context.Background(), executor.Invocation{}); err == nil {
t.Fatal("nil runtime runner error = nil")
}
t.Setenv(authpkg.AgentCodeEnv, "codex")
t.Setenv("HOME", t.TempDir())
t.Setenv(envDingtalkAgent, "agent")
t.Setenv(envDingtalkTraceID, "trace")
t.Setenv(envDingtalkMessageID, "message")
headers := resolveIdentityHeaders()
for _, key := range []string{"x-dws-agent-instance-id", "x-dingtalk-agent", "x-dingtalk-trace-id", "x-dingtalk-message-id"} {
if headers[key] == "" {
t.Fatalf("identity header %q missing: %#v", key, headers)
}
}
stdioMu.Lock()
previous := stdioClients
stdioClients = map[string]*transport.StdioClient{"plugin/server": transport.NewStdioClient("missing", nil, nil)}
stdioMu.Unlock()
t.Cleanup(func() {
stdioMu.Lock()
stdioClients = previous
stdioMu.Unlock()
})
if _, ok := LookupStdioClient("server"); !ok {
t.Fatal("LookupStdioClient(server suffix) failed")
}
if StopStdioClient("missing") {
t.Fatal("StopStdioClient(missing) = true")
}
registerPluginHTTPServer(mcptypes.ServerDescriptor{Key: "coverage", Endpoint: "https://example.test", AuthHeaders: map[string]string{"Authorization": "Bearer token"}})
originalDryRun := toolCallerDryRun
t.Cleanup(func() { toolCallerDryRun = originalDryRun })
toolCallerDryRun = func(context.Context, executor.Invocation) (executor.Result, error) {
return executor.Result{}, errors.New("dry-run")
}
adapter := newToolCallerAdapter(nil, &GlobalFlags{DryRun: true})
if _, err := adapter.CallTool(context.Background(), "product", "tool", nil); err == nil {
t.Fatal("tool caller dry-run error = nil")
}
}
+57 -386
View File
@@ -23,9 +23,7 @@ import (
"os"
"os/signal"
"path/filepath"
"sort"
"strings"
"sync"
"syscall"
"time"
@@ -52,31 +50,6 @@ type outputFileContextKey struct{}
const recoveryEventStderrPrefix = "RECOVERY_EVENT_ID="
var (
rootNormalizeProcessProfileArgs = normalizeProcessProfileArgs
rootExecuteCommand = (*cobra.Command).ExecuteC
rootNewRootCommandWithEngine = NewRootCommandWithEngine
rootRunPreParse = pipeline.RunPreParse
rootLatestRecoveryCapture = recovery.LatestCapture
rootResetRecoveryState = recovery.ResetRuntimeState
rootStopAllStdioClients = StopAllStdioClients
rootLoadPlugins = loadPlugins
rootMkdirAll = os.MkdirAll
rootCreateFile = os.Create
rootCloseFile = (*os.File).Close
rootPluginInjectConfigEnv = (*plugin.Loader).InjectPluginConfigEnv
rootPluginLoadUser = (*plugin.Loader).LoadUser
rootPluginLoadDev = (*plugin.Loader).LoadDev
rootPluginDescriptors = (*plugin.Plugin).ToServerDescriptors
rootPluginStdioClients = (*plugin.Plugin).StdioClients
rootRegisterPluginHTTPServer = registerPluginHTTPServer
rootPluginStdioDescriptor = stdioServerDescriptorFromManifest
rootRegisterResolvedStdioServer = registerResolvedStdioServer
rootPluginLoadHooks = (*plugin.Plugin).LoadHooks
rootPluginSyncSkills = plugin.SyncSkills
rootAuthLoadTokenData = authpkg.LoadTokenData
)
// Execute runs the root command and returns the process exit code.
func Execute() (exitCode int) {
defer func() {
@@ -86,13 +59,13 @@ func Execute() (exitCode int) {
}
}()
restoreArgs := rootNormalizeProcessProfileArgs()
restoreArgs := normalizeProcessProfileArgs()
defer restoreArgs()
timing := NewTimingCollector()
defer func() {
rootStopAllStdioClients() // Ensure child processes are terminated on exit
CloseAuditSink() // Drain async audit forwards on all exit paths,
StopAllStdioClients() // Ensure child processes are terminated on exit
CloseAuditSink() // Drain async audit forwards on all exit paths,
// including command errors where Cobra skips PersistentPostRunE.
timing.PrintIfEnabled()
timing.WriteReportIfEnabled(RawVersion(), SanitizeCommand(os.Args))
@@ -105,17 +78,17 @@ func Execute() (exitCode int) {
ctx = WithTimingCollector(ctx, timing)
initStart := time.Now()
rootResetRecoveryState()
recovery.ResetRuntimeState()
engine := newPipelineEngine()
root := rootNewRootCommandWithEngine(ctx, engine)
root := NewRootCommandWithEngine(ctx, engine)
timing.Record("cmd_init", time.Since(initStart))
// Run PreParse handlers on raw argv before Cobra parses flags.
// This corrects model-generated errors like --userId → --user-id
// and --limit100 → --limit 100.
rootRunPreParse(root, engine)
pipeline.RunPreParse(root, engine)
executed, err := rootExecuteCommand(root)
executed, err := root.ExecuteC()
if err != nil {
if executed == nil {
executed = root
@@ -127,7 +100,7 @@ func Execute() (exitCode int) {
_, _ = fmt.Fprintln(os.Stderr)
}
_ = printExecutionError(executed, os.Stdout, os.Stderr, err)
if last := rootLatestRecoveryCapture(); last != nil && last.EventID != "" {
if last := recovery.LatestCapture(); last != nil && last.EventID != "" {
_, _ = fmt.Fprintf(os.Stderr, "%s%s\n", recoveryEventStderrPrefix, last.EventID)
}
return apperrors.ExitCode(err)
@@ -282,6 +255,9 @@ func commandRequestsJSONErrors(cmd *cobra.Command) bool {
cmd.InheritedFlags(),
cmd.PersistentFlags(),
} {
if flags == nil {
continue
}
if flag := flags.Lookup("format"); flag != nil {
if value, err := flags.GetString("format"); err == nil && strings.EqualFold(strings.TrimSpace(value), "json") {
return true
@@ -308,28 +284,13 @@ func NewRootCommand(ctx ...context.Context) *cobra.Command {
if len(ctx) > 0 && ctx[0] != nil {
rootCtx = ctx[0]
}
return newRootCommandWithEngine(rootCtx, nil, true)
}
// NewSchemaSourceRootCommand constructs the distribution-owned command tree
// used by Schema generation and command-surface policy. Installed plugins and
// user-defined shortcuts must not change the reviewed embedded Schema.
func NewSchemaSourceRootCommand(ctx ...context.Context) *cobra.Command {
var rootCtx context.Context
if len(ctx) > 0 && ctx[0] != nil {
rootCtx = ctx[0]
}
return newRootCommandWithEngine(rootCtx, nil, false)
return NewRootCommandWithEngine(rootCtx, nil)
}
// NewRootCommandWithEngine constructs the root CLI command with an
// optional pipeline engine for input correction. When engine is nil,
// no pipeline processing is applied.
func NewRootCommandWithEngine(rootCtx context.Context, engine *pipeline.Engine) *cobra.Command {
return newRootCommandWithEngine(rootCtx, engine, true)
}
func newRootCommandWithEngine(rootCtx context.Context, engine *pipeline.Engine, loadRuntimeExtensions bool) *cobra.Command {
if rootCtx == nil {
rootCtx = context.Background()
}
@@ -413,9 +374,16 @@ func newRootCommandWithEngine(rootCtx context.Context, engine *pipeline.Engine,
}
root.AddCommand(utilityCommands...)
root.AddCommand(newLegacyPublicCommands(runner, patCaller, loadRuntimeExtensions)...)
root.AddCommand(newLegacyPublicCommands(runner, patCaller)...)
root.AddCommand(newLegacyHiddenCommands(runner)...)
// --- Plugin loading: runs AFTER legacy commands so plugin endpoints can
// be appended on top of the static endpoint registry.
pluginCmds := loadPlugins(engine, runner)
if len(pluginCmds) > 0 {
addPluginCommandsSafe(root, pluginCmds)
}
// PAT authorization commands (open-source core)
pat.RegisterCommands(root, patCaller)
@@ -424,15 +392,6 @@ func newRootCommandWithEngine(rootCtx context.Context, engine *pipeline.Engine,
fn(root, caller)
deduplicateCommands(root)
}
if loadRuntimeExtensions {
// Resolve plugins only after the complete distribution command tree is
// present, so endpoint and Cobra conflict checks see PAT and edition
// commands as well as the open-source base.
pluginCmds := rootLoadPlugins(root, engine, runner)
if len(pluginCmds) > 0 {
addPluginCommandsSafe(root, pluginCmds)
}
}
hideNonDirectRuntimeCommands(root)
configureRootHelp(root)
// Set custom flag error handler for better UX
@@ -650,17 +609,12 @@ var reservedCommands = map[string]bool{
"schema": true, "mcp": true, "help": true,
}
var replaceablePluginFallbacks = map[string]bool{
"conference": true,
}
// addPluginCommandsSafe registers plugin commands with conflict detection.
//
// Rules:
// - Plugin vs reserved (auth/plugin/cache/...) → reject, warn
// - Plugin vs plugin (same name) → reject later one, warn
// - Plugin vs hidden compatibility fallback → allow, plugin wins
// - Plugin vs visible distribution command → reject, warn
// - Plugin vs Market dynamic command → allow, plugin wins
func addPluginCommandsSafe(root *cobra.Command, pluginCmds []*cobra.Command) {
// Build index of existing commands before plugin registration.
existing := make(map[string]bool)
@@ -688,47 +642,17 @@ func addPluginCommandsSafe(root *cobra.Command, pluginCmds []*cobra.Command) {
}
pluginSeen[name] = true
// An alias must not bypass the same protections applied to primary
// plugin command names or shadow another root command.
filteredAliases := make([]string, 0, len(cmd.Aliases))
for _, rawAlias := range cmd.Aliases {
alias := strings.TrimSpace(rawAlias)
if alias == "" || alias == name || reservedCommands[alias] ||
existing[alias] || pluginSeen[alias] {
if alias != "" {
slog.Warn("plugin: command alias conflicts with an existing command, skipping",
"command", name, "alias", alias)
}
continue
}
pluginSeen[alias] = true
filteredAliases = append(filteredAliases, alias)
}
cmd.Aliases = filteredAliases
// Rule 3: an installed plugin may replace a hidden compatibility
// fallback (for example conference), but never a visible distribution
// command that participates in the reviewed base interface.
// Rule 3: plugin vs Market — plugin wins, remove the old one.
if existing[name] {
for _, old := range root.Commands() {
if old.Name() == name {
if !old.Hidden || !replaceablePluginFallbacks[name] ||
cmdutil.IsPluginSourced(old) {
slog.Warn("plugin: command conflicts with a visible distribution command, skipping",
"command", name)
cmd = nil
break
}
root.RemoveCommand(old)
slog.Debug("plugin: overriding hidden compatibility command",
slog.Debug("plugin: overriding Market command",
"command", name)
break
}
}
}
if cmd == nil {
continue
}
root.AddCommand(cmd)
}
@@ -767,10 +691,10 @@ func configureOutputSink(cmd *cobra.Command) error {
if err := validateOptionalPath("--output", outputPath); err != nil {
return err
}
if err := rootMkdirAll(filepath.Dir(outputPath), 0o755); err != nil {
if err := os.MkdirAll(filepath.Dir(outputPath), 0o755); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to prepare output directory: %v", err))
}
file, err := rootCreateFile(outputPath)
file, err := os.Create(outputPath)
if err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to create output file: %v", err))
}
@@ -784,7 +708,7 @@ func closeOutputSink(cmd *cobra.Command) error {
if !ok || file == nil {
return nil
}
if err := rootCloseFile(file); err != nil {
if err := file.Close(); err != nil {
return apperrors.NewInternal(fmt.Sprintf("failed to close output file: %v", err))
}
return nil
@@ -803,10 +727,7 @@ func validateOptionalPath(flagName, path string) error {
// fileLogger holds the package-level file logger for diagnostics.
// It is initialized by configureLogLevel and closed by CloseFileLogger.
var (
fileLoggerMu sync.Mutex
fileLogger *logging.FileLogger
)
var fileLogger *logging.FileLogger
// configureLogLevel sets the global slog level based on --debug and --verbose flags
// and initializes the file logger for diagnostics.
@@ -828,24 +749,14 @@ func configureLogLevel(flags *GlobalFlags) {
// Initialize file logger — writes to ~/.dws/logs/dws.log at DEBUG level
// regardless of stderr level. All slog calls are captured for diagnostics.
logger := logging.Setup(defaultConfigDir())
fileHandler := slog.NewJSONHandler(logger.Writer(), &slog.HandlerOptions{Level: slog.LevelDebug})
defaultLogger := slog.New(logging.NewMultiHandler(stderrHandler, fileHandler))
fileLogger = logging.Setup(defaultConfigDir())
fileHandler := slog.NewJSONHandler(fileLogger.Writer(), &slog.HandlerOptions{Level: slog.LevelDebug})
fileLoggerMu.Lock()
defer fileLoggerMu.Unlock()
previous := fileLogger
fileLogger = logger
slog.SetDefault(defaultLogger)
if previous != nil {
_ = previous.Close()
}
slog.SetDefault(slog.New(logging.NewMultiHandler(stderrHandler, fileHandler)))
}
// FileLoggerInstance returns the package-level file logger, or nil if not initialized.
func FileLoggerInstance() *slog.Logger {
fileLoggerMu.Lock()
defer fileLoggerMu.Unlock()
if fileLogger == nil {
return nil
}
@@ -854,42 +765,25 @@ func FileLoggerInstance() *slog.Logger {
// CloseFileLogger flushes and closes the file logger.
func CloseFileLogger() {
fileLoggerMu.Lock()
defer fileLoggerMu.Unlock()
if fileLogger != nil {
_ = fileLogger.Close()
fileLogger = nil
fileLogger.Close()
}
}
// loadPlugins registers versioned plugin manifests, stdio clients, hooks, and
// skills. It deliberately does not initialize MCP transports or call
// tools/list while constructing the command tree.
type pluginServerCandidate struct {
owner *plugin.Plugin
order int
descriptor mcptypes.ServerDescriptor
stdioClient *plugin.StdioServerClient
}
type pluginIdentityOwner struct {
plugin *plugin.Plugin
serverKey string
rootName string
shareable bool
}
func loadPlugins(root *cobra.Command, engine *pipeline.Engine, runner executor.Runner) []*cobra.Command {
func loadPlugins(engine *pipeline.Engine, _ executor.Runner) []*cobra.Command {
pluginLoader := plugin.NewLoader(RawVersion())
// 0a. Inject plugin config values from settings.json as environment
// variables so that expandPluginVars can resolve ${KEY} references
// in plugin.json headers, endpoints, etc. User-set env vars take
// precedence (InjectPluginConfigEnv skips already-set keys).
rootPluginInjectConfigEnv(pluginLoader)
pluginLoader.InjectPluginConfigEnv()
// Load TokenData once; reused for stdio injection below.
tokenData, _ := rootAuthLoadTokenData(defaultConfigDir())
tokenData, _ := authpkg.LoadTokenData(defaultConfigDir())
var userCtx *plugin.UserContext
if tokenData != nil {
// Inject user context if either UserID or CorpID is present.
@@ -902,41 +796,32 @@ func loadPlugins(root *cobra.Command, engine *pipeline.Engine, runner executor.R
}
// 1. Load user plugins (per settings.json)
userPlugins := rootPluginLoadUser(pluginLoader)
userPlugins := pluginLoader.LoadUser()
// 2. Load dev plugins (registered via `dws plugin dev`)
devPlugins := rootPluginLoadDev(pluginLoader)
sortPluginsForRegistration(userPlugins)
sortPluginsForRegistration(devPlugins)
devPlugins := pluginLoader.LoadDev()
allPlugins := append(userPlugins, devPlugins...)
descriptorsByPlugin := make(map[*plugin.Plugin][]mcptypes.ServerDescriptor, len(allPlugins))
// 3. Resolve every descriptor once, then choose identity winners before
// mutating endpoint, auth, or stdio-client registries. This keeps the
// visible command and its transport owned by the same plugin.
candidates := collectPluginServerCandidates(allPlugins, userCtx)
accepted := selectPluginServerCandidates(root, candidates)
for _, candidate := range accepted {
if candidate.stdioClient != nil {
rootRegisterResolvedStdioServer(
candidate.owner,
*candidate.stdioClient,
candidate.descriptor,
)
} else {
rootRegisterPluginHTTPServer(candidate.descriptor)
// 3. Register HTTP descriptors and authentication from the manifest.
for _, p := range allPlugins {
for _, srv := range p.ToServerDescriptors() {
registerPluginHTTPServer(srv)
}
descriptorsByPlugin[candidate.owner] = append(
descriptorsByPlugin[candidate.owner],
candidate.descriptor,
)
}
// 4. Register plugin hooks into pipeline engine
// 4. Register stdio descriptors and unstarted clients. The subprocess is
// started and initialized only when a command is actually executed.
for _, p := range allPlugins {
for _, sc := range p.StdioClients(userCtx) {
registerStdioServerFromManifest(p, sc)
}
}
// 5. Register plugin hooks into pipeline engine
if engine != nil {
for _, p := range allPlugins {
hooksCfg, err := rootPluginLoadHooks(p)
hooksCfg, err := p.LoadHooks()
if err != nil {
slog.Warn("plugin: failed to load hooks",
"plugin", p.Manifest.Name, "error", err)
@@ -951,8 +836,8 @@ func loadPlugins(root *cobra.Command, engine *pipeline.Engine, runner executor.R
}
}
// 5. Sync plugin skills to agent directories
rootPluginSyncSkills(allPlugins)
// 7. Sync plugin skills to agent directories
plugin.SyncSkills(allPlugins)
if len(allPlugins) > 0 {
slog.Debug("plugins loaded",
@@ -961,228 +846,11 @@ func loadPlugins(root *cobra.Command, engine *pipeline.Engine, runner executor.R
)
}
var pluginCommands []*cobra.Command
for _, p := range allPlugins {
// Build each plugin independently. addPluginCommandsSafe deliberately
// resolves cross-plugin root conflicts with first-plugin-wins semantics.
pluginCommands = append(pluginCommands, buildPluginCommands(descriptorsByPlugin[p], runner, root)...)
}
return pluginCommands
}
func sortPluginsForRegistration(plugins []*plugin.Plugin) {
sort.SliceStable(plugins, func(i, j int) bool {
left := strings.TrimSpace(plugins[i].Manifest.Name) + "\x00" + strings.TrimSpace(plugins[i].Root)
right := strings.TrimSpace(plugins[j].Manifest.Name) + "\x00" + strings.TrimSpace(plugins[j].Root)
return left < right
})
}
func collectPluginServerCandidates(
plugins []*plugin.Plugin,
userCtx *plugin.UserContext,
) []pluginServerCandidate {
var candidates []pluginServerCandidate
for order, owner := range plugins {
for _, descriptor := range rootPluginDescriptors(owner) {
candidates = append(candidates, pluginServerCandidate{
owner: owner,
order: order,
descriptor: descriptor,
})
}
for _, stdioClient := range rootPluginStdioClients(owner, userCtx) {
descriptor, ok := rootPluginStdioDescriptor(owner, stdioClient)
if !ok {
continue
}
clientCopy := stdioClient
candidates = append(candidates, pluginServerCandidate{
owner: owner,
order: order,
descriptor: descriptor,
stdioClient: &clientCopy,
})
}
}
sort.SliceStable(candidates, func(i, j int) bool {
if candidates[i].order != candidates[j].order {
return candidates[i].order < candidates[j].order
}
left := strings.TrimSpace(candidates[i].descriptor.Key)
right := strings.TrimSpace(candidates[j].descriptor.Key)
if left != right {
return left < right
}
return candidates[i].stdioClient == nil && candidates[j].stdioClient != nil
})
return candidates
}
func selectPluginServerCandidates(
root *cobra.Command,
candidates []pluginServerCandidate,
) []pluginServerCandidate {
distributionProducts := DirectRuntimeProductIDs()
owners := make(map[string]pluginIdentityOwner)
for identity := range distributionProducts {
if replaceablePluginFallbacks[identity] {
continue
}
owners[identity] = pluginIdentityOwner{serverKey: "distribution"}
}
accepted := make([]pluginServerCandidate, 0, len(candidates))
for _, candidate := range candidates {
descriptor := candidate.descriptor
if descriptor.CLI.Skip {
continue
}
if reason := unsupportedPluginDescriptor(root, descriptor); reason != "" {
slog.Warn("plugin: descriptor CLI semantics are unsupported, skipping",
"plugin", candidate.owner.Manifest.Name,
"server", descriptor.Key,
"field", reason)
continue
}
if pluginDescriptorConflictsWithDistribution(root, descriptor, distributionProducts) {
continue
}
claims := pluginDescriptorIdentityClaims(descriptor)
conflict := ""
for identity, shareable := range claims {
existing, exists := owners[identity]
if !exists {
continue
}
rootName := pluginDescriptorRootName(descriptor)
if shareable && existing.shareable &&
existing.plugin == candidate.owner &&
existing.rootName == rootName {
continue
}
conflict = identity
break
}
if conflict != "" {
slog.Warn("plugin: descriptor identity already owned, skipping",
"plugin", candidate.owner.Manifest.Name,
"server", descriptor.Key,
"identity", conflict)
continue
}
rootName := pluginDescriptorRootName(descriptor)
for identity, shareable := range claims {
if existing, exists := owners[identity]; exists &&
shareable && existing.shareable &&
existing.plugin == candidate.owner &&
existing.rootName == rootName {
continue
}
owners[identity] = pluginIdentityOwner{
plugin: candidate.owner,
serverKey: descriptor.Key,
rootName: rootName,
shareable: shareable,
}
}
accepted = append(accepted, candidate)
}
return accepted
}
func pluginDescriptorIdentityClaims(descriptor mcptypes.ServerDescriptor) map[string]bool {
claims := make(map[string]bool)
canonicalID := firstNonEmptyPluginString(descriptor.CLI.ID, descriptor.Key)
if canonicalID != "" {
claims[canonicalID] = false
}
for _, identity := range append(
[]string{pluginDescriptorRootName(descriptor)},
descriptor.CLI.Aliases...,
) {
identity = strings.TrimSpace(identity)
if identity == "" {
continue
}
if _, exists := claims[identity]; !exists {
claims[identity] = true
}
}
return claims
}
func pluginDescriptorRootName(descriptor mcptypes.ServerDescriptor) string {
return firstNonEmptyPluginString(
descriptor.CLI.Command,
descriptor.CLI.ID,
descriptor.Key,
)
}
func pluginDescriptorConflictsWithDistribution(
root *cobra.Command,
descriptor mcptypes.ServerDescriptor,
distributionProducts map[string]bool,
) bool {
candidates := append(
[]string{
firstNonEmptyPluginString(descriptor.CLI.ID, descriptor.Key),
pluginDescriptorRootName(descriptor),
},
descriptor.CLI.Aliases...,
)
for _, candidate := range candidates {
candidate = strings.TrimSpace(candidate)
if candidate == "" {
continue
}
if !reservedCommands[candidate] && replaceablePluginFallbacks[candidate] {
// The distribution ships only a hidden compatibility fallback for
// this name; plugins may claim it and the later command merge in
// addPluginCommandsSafe still rejects visible non-fallback owners.
continue
}
if reservedCommands[candidate] ||
distributionProducts[candidate] ||
distributionRootOwns(root, candidate) {
slog.Warn("plugin: descriptor conflicts with a distribution command, skipping",
"plugin", descriptor.DisplayName,
"server", descriptor.Key,
"identity", candidate)
return true
}
}
return false
}
func distributionRootOwns(root *cobra.Command, name string) bool {
if root == nil {
return false
}
for _, command := range root.Commands() {
if cmdutil.IsPluginSourced(command) {
continue
}
if command.Name() == name {
if command.Hidden && replaceablePluginFallbacks[name] {
return false
}
return true
}
for _, alias := range command.Aliases {
if strings.TrimSpace(alias) == name {
return true
}
}
}
return false
return nil
}
func registerPluginHTTPServer(srv mcptypes.ServerDescriptor) {
AppendDynamicServer(srv)
productID := firstNonEmptyPluginString(srv.CLI.ID, srv.Key)
ClearPluginAuth(productID)
if len(srv.AuthHeaders) > 0 {
registerPluginAuthFromHeaders(srv)
}
@@ -1211,7 +879,10 @@ func registerPluginAuthFromHeaders(srv mcptypes.ServerDescriptor) {
host := parsed.Hostname()
trustedDomains = []string{host, "*." + host}
}
productID := firstNonEmptyPluginString(srv.CLI.ID, srv.Key)
productID := strings.TrimSpace(srv.CLI.ID)
if productID == "" {
productID = srv.Key
}
RegisterPluginAuth(productID, &PluginAuth{
Token: authToken,
ExtraHeaders: extraHeaders,

Some files were not shown because too many files have changed in this diff Show More