Skip to content

fix: validate drive import folder target#1485

Merged
wittam-01 merged 1 commit into
mainfrom
fix/drive-import-reject-wiki-folder-token
Jun 16, 2026
Merged

fix: validate drive import folder target#1485
wittam-01 merged 1 commit into
mainfrom
fix/drive-import-reject-wiki-folder-token

Conversation

@wittam-01

@wittam-01 wittam-01 commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator

Summary

Add preflight validation for drive +import --folder-token so the CLI verifies whether the provided target token resolves as a Wiki node before uploading import media. This keeps import target handling explicit and guides users to provide a Drive folder token.

Changes

  • Use wiki.spaces.get_node when drive +import --folder-token is provided to verify whether the token is a Wiki node.
  • Return a typed validation error on --folder-token when the target resolves as a Wiki node.
  • Surface the validation step in dry-run output and declare wiki:node:retrieve as a conditional scope.
  • Add unit coverage for Wiki-node validation and normal folder-token import flow, plus dry-run E2E coverage for the validation request shape.

Test Plan

  • make unit-test
  • go vet ./...
  • gofmt -l . produced no output
  • go mod tidy produced no go.mod / go.sum diff
  • GOTOOLCHAIN=go1.25.9 go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.1.6 run --new-from-rev=origin/main (0 issues)
  • go test ./shortcuts/drive -run 'TestDriveImport(RejectsWikiFolderToken|ContinuesWhenFolderTokenDoesNotResolveAsWiki|DryRunUsesExtensionlessDefaultName)'
  • LARK_CLI_BIN=/tmp/lark-cli-import-wiki-check go test ./tests/cli_e2e/drive -run TestDriveImportDryRunFolderTokenWikiProbe
  • Live validation in the agreed Drive/Wiki test locations: created a temporary Wiki node and Drive folder; verified the Wiki node target returns validation/invalid_argument, verified a Drive folder target imports docx successfully, and cleaned up all temporary resources.

Related Issues

  • None

Summary by CodeRabbit

  • New Features

    • Drive import now performs a wiki “probe” when --folder-token is provided, to distinguish wiki nodes from Drive folder tokens.
  • Bug Fixes

    • In execution mode, wiki node tokens passed via --folder-token are now rejected with a validation error and guidance to omit --folder-token for Drive root imports.
    • In both dry-run and execution, --folder-token is validated via the wiki probe; if it doesn’t resolve to a wiki node, the import continues as a Drive folder token.
  • Tests

    • Added unit and e2e coverage for the wiki probe behavior and updated dry-run expectations for the extra API call.

@github-actions github-actions Bot added domain/ccm PR touches the ccm domain size/M Single-domain feat or fix with limited business impact labels Jun 16, 2026
@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

DriveImport gains a wiki node probe for --folder-token validation. A new wiki:node:retrieve conditional scope is declared. Two helpers are added: a dry-run probe that issues a GET to the wiki get_node endpoint, and a runtime validator that rejects wiki node tokens with a ValidationError or falls through to Drive folder token handling. Unit and e2e tests cover both paths.

Changes

Wiki folder-token validation for drive +import

Layer / File(s) Summary
Wiki probe helper functions
shortcuts/drive/drive_import_common.go
Adds appendDriveImportFolderTokenWikiCheckDryRun (dry-run GET to wiki get_node) and rejectDriveImportWikiFolderToken (runtime validator that returns ValidationError for wiki tokens or falls through).
DriveImport wiring
shortcuts/drive/drive_import.go
Adds ConditionalScopes: []string{"wiki:node:retrieve"} to the shortcut definition, calls the dry-run wiki probe helper, and calls the runtime rejection helper after preflight.
Unit tests
shortcuts/drive/drive_import_common_test.go, shortcuts/drive/drive_import_test.go
Two new tests assert the wiki-rejection path (*errs.ValidationError with SubtypeInvalidArgument) and the node-not-found fallthrough path (import completes with correct mount_key). Existing dry-run test updated to expect 4 API calls and validate the wiki probe at index 0.
E2E dry-run test
tests/cli_e2e/drive/drive_import_dryrun_test.go
New TestDriveImportDryRunFolderTokenWikiProbe runs the CLI with --dry-run and --folder-token, asserting the wiki probe appears as the first API call and upload requests carry the expected mount_key.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

size/L

Suggested reviewers

  • fangshuyu-768

Poem

🐇 A wiki token tried to sneak in the door,
But the rabbit said, "Drive tokens only—no more!"
With a get_node probe and a ValidationError bright,
The folder-token guard keeps import flows right.
Hop hop, only Drive tokens tonight! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: validate drive import folder target' clearly and concisely describes the main change—adding validation for the drive import folder token target.
Description check ✅ Passed The PR description includes all required sections: a clear Summary explaining the motivation, a detailed Changes section listing the main modifications, a comprehensive Test Plan with checkboxes and specific test commands executed, and a Related Issues section.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/drive-import-reject-wiki-folder-token

Warning

Review ran into problems

🔥 Problems

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Jun 16, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@5f239c9a95216e68099d1ffaaca4dd44033837e4

🧩 Skill update

npx skills add larksuite/cli#fix/drive-import-reject-wiki-folder-token -y -g

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
shortcuts/drive/drive_import_common_test.go (1)

315-330: ⚡ Quick win

Strengthen typed metadata assertions for the rejection path.

This test already checks *errs.ValidationError + Param; please also assert category/subtype via errs.ProblemOf(err) so the error-path test validates typed metadata by contract, not only message/hint substrings.

As per coding guidelines, error-path tests should assert typed metadata via errs.ProblemOf, and based on learnings, keep errors.As for ValidationError.Param because ProblemOf does not expose Param.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/drive/drive_import_common_test.go` around lines 315 - 330, The test
validation in the rejection path for the `--folder-token` parameter check should
use `errs.ProblemOf(err)` in addition to the existing `errors.As` check to
validate the error's typed metadata by contract. After the successful
`errors.As` assertion for `*errs.ValidationError`, add an assertion that calls
`errs.ProblemOf(err)` and validates the returned error metadata (such as
category or problem type), while keeping the existing `errors.As` usage for
checking the `Param` field since `ProblemOf` does not expose that field. This
ensures the error-path test validates both the structured error type and its
categorized metadata.

Sources: Coding guidelines, Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@shortcuts/drive/drive_import_common.go`:
- Around line 314-315: The code at line 314 currently treats all
runtime.CallAPITyped errors as benign wiki-resolution failures and continues
silently. Instead, you need to differentiate between expected wiki-resolution
API failures (such as not-found or permission-denied errors) and unexpected
transport or internal errors. For expected failures like missing wiki nodes or
permission issues, continue with the current fallthrough behavior. For other
error types (transport, internal, or unexpected errors), propagate the error
unchanged by returning it rather than swallowing it, so that actual failures are
not masked as benign results.

---

Nitpick comments:
In `@shortcuts/drive/drive_import_common_test.go`:
- Around line 315-330: The test validation in the rejection path for the
`--folder-token` parameter check should use `errs.ProblemOf(err)` in addition to
the existing `errors.As` check to validate the error's typed metadata by
contract. After the successful `errors.As` assertion for
`*errs.ValidationError`, add an assertion that calls `errs.ProblemOf(err)` and
validates the returned error metadata (such as category or problem type), while
keeping the existing `errors.As` usage for checking the `Param` field since
`ProblemOf` does not expose that field. This ensures the error-path test
validates both the structured error type and its categorized metadata.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f7c69d08-2f00-45b5-877f-d9f24e6fbd12

📥 Commits

Reviewing files that changed from the base of the PR and between 3feb70b and 11e2ba0.

📒 Files selected for processing (5)
  • shortcuts/drive/drive_import.go
  • shortcuts/drive/drive_import_common.go
  • shortcuts/drive/drive_import_common_test.go
  • shortcuts/drive/drive_import_test.go
  • tests/cli_e2e/drive/drive_import_dryrun_test.go

Comment thread shortcuts/drive/drive_import_common.go Outdated
@codecov

codecov Bot commented Jun 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.54839% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.38%. Comparing base (72c2947) to head (5f239c9).
⚠️ Report is 10 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/drive/drive_import_common.go 92.85% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1485      +/-   ##
==========================================
+ Coverage   73.35%   73.38%   +0.02%     
==========================================
  Files         750      751       +1     
  Lines       69264    69905     +641     
==========================================
+ Hits        50811    51301     +490     
- Misses      14713    14804      +91     
- Partials     3740     3800      +60     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wittam-01
wittam-01 force-pushed the fix/drive-import-reject-wiki-folder-token branch 3 times, most recently from e8c5f3a to ae21aae Compare June 16, 2026 09:48

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
shortcuts/drive/drive_import_common.go (1)

277-299: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not swallow typed wiki-probe failures.

Line 297 currently treats every runtime.CallAPITyped failure as a benign “not wiki” result and continues. That masks transport/internal failures and downgrades error classification. Only expected wiki-resolution probe failures should fall through; otherwise return the typed error unchanged.

As per coding guidelines, when a lower layer already returns a typed error, pass it through unchanged to avoid downgrades in error classification.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/drive/drive_import_common.go` around lines 277 - 299, The code
currently treats all errors from the runtime.CallAPITyped call as benign "not a
wiki node" results and falls through to return nil, which masks actual transport
and internal failures. Instead of checking only if err == nil, you need to
distinguish between expected wiki-probe failures and genuine errors. When err is
not nil, check if it is an expected wiki-resolution failure (such as a "not
found" or similar expected type); only then continue with the fmt.Fprintf
fallthrough. For any other error from the CallAPITyped call, return the typed
error unchanged to preserve the error classification and avoid downgrades.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@shortcuts/drive/drive_import_common.go`:
- Around line 277-299: The code currently treats all errors from the
runtime.CallAPITyped call as benign "not a wiki node" results and falls through
to return nil, which masks actual transport and internal failures. Instead of
checking only if err == nil, you need to distinguish between expected wiki-probe
failures and genuine errors. When err is not nil, check if it is an expected
wiki-resolution failure (such as a "not found" or similar expected type); only
then continue with the fmt.Fprintf fallthrough. For any other error from the
CallAPITyped call, return the typed error unchanged to preserve the error
classification and avoid downgrades.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bd99e589-a297-4c4f-8f28-9591168079ca

📥 Commits

Reviewing files that changed from the base of the PR and between e8c5f3a and ae21aae.

📒 Files selected for processing (5)
  • shortcuts/drive/drive_import.go
  • shortcuts/drive/drive_import_common.go
  • shortcuts/drive/drive_import_common_test.go
  • shortcuts/drive/drive_import_test.go
  • tests/cli_e2e/drive/drive_import_dryrun_test.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • shortcuts/drive/drive_import_test.go
  • tests/cli_e2e/drive/drive_import_dryrun_test.go
  • shortcuts/drive/drive_import_common_test.go
  • shortcuts/drive/drive_import.go

@wittam-01
wittam-01 force-pushed the fix/drive-import-reject-wiki-folder-token branch from ae21aae to 85019bd Compare June 16, 2026 09:55
Change-Id: I43755c3966b0daa06b708d2b3d03294f439547fa
@wittam-01
wittam-01 force-pushed the fix/drive-import-reject-wiki-folder-token branch from 85019bd to 5f239c9 Compare June 16, 2026 09:58
@wittam-01 wittam-01 changed the title fix: reject wiki tokens for drive import folder target fix: validate drive import folder target Jun 16, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
shortcuts/drive/drive_import_test.go (1)

121-123: ⚡ Quick win

Assert wiki probe endpoint/method, not only nil body.

At Line 121-Line 123, this only proves the first call has no body. Please also assert API[0] is GET /open-apis/wiki/v2/spaces/get_node so the test actually locks the wiki-probe contract.

Suggested test hardening
 	var got struct {
 		API []struct {
+			Method string                 `json:"method"`
+			URL    string                 `json:"url"`
 			Body map[string]interface{} `json:"body"`
 		} `json:"api"`
 	}
@@
 	if got.API[0].Body != nil {
 		t.Fatalf("wiki probe should not have a request body, got %#v", got.API[0].Body)
 	}
+	if got.API[0].Method != "GET" || got.API[0].URL != "/open-apis/wiki/v2/spaces/get_node" {
+		t.Fatalf("first API call = %s %s, want GET /open-apis/wiki/v2/spaces/get_node", got.API[0].Method, got.API[0].URL)
+	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/drive/drive_import_test.go` around lines 121 - 123, The test
assertion at lines 121-123 only verifies that got.API[0].Body is nil, but does
not fully lock in the wiki-probe contract. Add additional assertions in the same
block to verify that API[0] has the correct HTTP method (GET) and the correct
endpoint path (/open-apis/wiki/v2/spaces/get_node) in addition to the existing
body nil check. This will ensure the test comprehensively validates the wiki
probe request contract rather than just checking for a nil body.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@shortcuts/drive/drive_import_test.go`:
- Around line 121-123: The test assertion at lines 121-123 only verifies that
got.API[0].Body is nil, but does not fully lock in the wiki-probe contract. Add
additional assertions in the same block to verify that API[0] has the correct
HTTP method (GET) and the correct endpoint path
(/open-apis/wiki/v2/spaces/get_node) in addition to the existing body nil check.
This will ensure the test comprehensively validates the wiki probe request
contract rather than just checking for a nil body.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6a4573d5-0ce6-439f-a7fb-ee1f403e9642

📥 Commits

Reviewing files that changed from the base of the PR and between 85019bd and 5f239c9.

📒 Files selected for processing (5)
  • shortcuts/drive/drive_import.go
  • shortcuts/drive/drive_import_common.go
  • shortcuts/drive/drive_import_common_test.go
  • shortcuts/drive/drive_import_test.go
  • tests/cli_e2e/drive/drive_import_dryrun_test.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • shortcuts/drive/drive_import.go
  • shortcuts/drive/drive_import_common_test.go
  • tests/cli_e2e/drive/drive_import_dryrun_test.go
  • shortcuts/drive/drive_import_common.go

@wittam-01
wittam-01 merged commit 4464ba7 into main Jun 16, 2026
22 checks passed
@wittam-01
wittam-01 deleted the fix/drive-import-reject-wiki-folder-token branch June 16, 2026 10:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/ccm PR touches the ccm domain size/M Single-domain feat or fix with limited business impact

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants