Skip to content

feat(tracking): add auth event tracking#987

Open
JackZhao10086 wants to merge 1 commit into
mainfrom
feat/auth_log_report
Open

feat(tracking): add auth event tracking#987
JackZhao10086 wants to merge 1 commit into
mainfrom
feat/auth_log_report

Conversation

@JackZhao10086
Copy link
Copy Markdown
Collaborator

@JackZhao10086 JackZhao10086 commented May 20, 2026

Summary

Add auth event tracking system that records authentication events (responses and errors) to local log files and reports them to a remote telemetry endpoint. This enables observability into auth failures and helps diagnose permission/token issues across CLI sessions.

Changes

  • Add internal/tracking package with event emission pipeline: LogAuthResponse and LogAuthError as public entry points
  • Local sink: append structured auth events to daily-rotated log files (auth-YYYY-MM-DD.log) under the workspace-aware config directory, with automatic 7-day cleanup
  • Remote sink: POST auth events as structured JSON to brand-specific telemetry endpoint (https://mcs-bd.feishu.cn/v1/list for feishu, disabled for lark), with 3s timeout and fail-open behavior
  • Add ResolveTelemetryEndpoint(brand) to resolve telemetry endpoint by brand, keeping tracking-specific config in the tracking package
  • Inject RuntimeDirFunc, AuthLogUserUniqueIDProvider, and AuthLogRemoteEndpointProvider via function variables to avoid core ↔ tracking import cycle
  • Integrate auth error logging into keychain operations (wrapError) and auth error hint enrichment (enrichMissingScopeError, logAuthFailureReason, logSecurityPolicyError)
  • Log auth HTTP response details (path, status, x-tt-logid) via logHTTPResponse and logSDKResponse in the auth package

Test Plan

  • Unit tests pass (go test -race ./internal/tracking/... ./internal/keychain/... ./internal/auth/... ./internal/cmdutil/... ./cmd/...)
  • go vet ./... passes
  • gofmt -l . produces no output

Related Issues

  • None

Summary by CodeRabbit

  • New Features

    • More detailed auth failure reasons shown to users (no token, expired, refresh failed/expired, permission denied)
    • Security-policy errors now produce a dedicated JSON error envelope
    • Added filesystem symlink support (readlink helper)
  • Improvements

    • Centralized auth event logging with local rotation and optional remote reporting
    • Enhanced auth error messages, hints and telemetry; per-user telemetry ID added to config
  • Refactor

    • Auth logging moved to a new centralized tracking module; legacy auth-log internals removed
  • Tests

    • Expanded tests for auth logging, telemetry endpoints and payload/behavior

Review Change Stack

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 20, 2026

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

Migrates auth logging to internal/tracking, implements structured auth failure reasons/timestamps, instruments root and hint flows to emit auth/security telemetry, wires tracking runtime/config and user-unique ID, and adds tests plus small VFS helpers.

Changes

Auth Telemetry Migration and Tracking Module

Layer / File(s) Summary
NeedAuthorizationError enrichment with reason codes
internal/auth/errors.go, internal/auth/uat_client.go
NeedAuthorizationError gains Reason and GrantedAt; UAT client returns explicit reasons (ReasonNoToken, ReasonRefreshFailed, ReasonRefreshExpired, etc.).
Tracking module implementation with local and remote telemetry
internal/tracking/event.go, internal/tracking/event_test.go
New tracking module: formats/truncates auth cmdlines, captures parent process, writes per-day local auth logs, optionally posts structured JSON to remote endpoint (injectable providers), includes test hooks and 7-day cleanup.
Migrate auth logging from keychain to tracking
internal/auth/auth_response_log.go, internal/auth/device_flow_test.go, internal/auth/verify_test.go, internal/keychain/keychain.go
Route logging and test hooks from keychain to tracking (LogAuthResponse, LogAuthError, SetAuthLogHooksForTest, FormatAuthCmdline).
Enhanced root command error handling and auth logging
cmd/root.go, cmd/error_auth_hint.go
Log SecurityPolicyError and raw auth failures via tracking.LogAuthError; convert NeedAuthorizationError to auth envelope; enrich permission-denial cases with structured reason and emit tracking events; construct structured auth-failure messages for hinting.
Config schema and factory wiring
internal/core/config.go, internal/cmdutil/factory_default.go, internal/cmdutil/factory_default_test.go
Add UserUniqueID to MultiAppConfig; wire tracking.RuntimeDirFunc; set tracking.AuthLogBrand and AuthLogAppID from resolved config; small test whitespace change.
VFS symlink helpers
internal/vfs/fs.go, internal/vfs/osfs.go, internal/vfs/default.go
Add Readlink to vfs.FS, implement OsFs.Readlink and DefaultFS wrapper used by tracking for symlink resolution.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as CLI/Auth code
  participant Local as Local Auth Log
  participant Remote as Remote Telemetry
  CLI->>Local: tracking.LogAuthResponse / tracking.LogAuthError
  Local->>Local: append to daily-rotated file
  CLI->>Remote: emitRemoteAuthEvent (if endpoint enabled)
  Remote->>Remote: POST JSON payload (timeout)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • larksuite/cli#235: Related earlier centralized auth response logging changes; this PR routes logging to the new tracking module.

Suggested labels

feature

Suggested reviewers

  • liangshuo-1
  • albertnusouo
  • evandance

Poem

🐰 I hopped through logs at break of dawn,

reason-tags and UUIDs drawn,
From keychain paths to tracking's light,
I stitched the hints and logged the fight,
A tiny rabbit's telemetry song.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% 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 'feat(tracking): add auth event tracking' clearly and concisely describes the main change—adding a new auth event tracking system to the codebase.
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.
Description check ✅ Passed PR description covers summary, changes, test plan, and follows the template structure with all required sections.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/auth_log_report

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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 added the size/XL Architecture-level or global-impact change label May 20, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
internal/cmdutil/factory_default_test.go (1)

20-20: ⚡ Quick win

Use stdlib filesystem APIs for test fixture setup in _test.go.

Please switch these fixture writes/dir-creation calls from vfs.* to os.* to keep tests decoupled from production FS abstractions.

Suggested patch
 import (
 	"context"
 	"errors"
+	"os"
 	"path/filepath"
 	"testing"
@@
-	"github.com/larksuite/cli/internal/vfs"
 	"github.com/larksuite/cli/internal/vfs/localfileio"
 )
@@
-	if err := vfs.WriteFile(filepath.Join(dir, "config.json"), raw, 0600); err != nil {
+	if err := os.WriteFile(filepath.Join(dir, "config.json"), raw, 0o600); err != nil {
 		t.Fatalf("WriteFile(config.json) error = %v", err)
 	}
@@
-	if err := vfs.MkdirAll(filepath.Join(core.GetConfigDir(), "locks"), 0700); err != nil {
+	if err := os.MkdirAll(filepath.Join(core.GetConfigDir(), "locks"), 0o700); err != nil {
 		t.Fatalf("MkdirAll(locks) error = %v", err)
 	}

Based on learnings: In larksuite/cli Go tests (*_test.go), use standard library filesystem APIs (os.Mkdir, os.Create, os.CreateTemp, os.WriteFile) for fixture setup and avoid vfs.* there.

Also applies to: 285-286, 329-330

🤖 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 `@internal/cmdutil/factory_default_test.go` at line 20, Tests are using the
production VFS helpers (imported as vfs and calls like vfs.MkdirAll /
vfs.WriteFile / vfs.CreateTemp) to create fixtures; switch those to the stdlib:
remove the vfs import and replace vfs.MkdirAll with os.MkdirAll,
vfs.WriteFile/vfs.Create with os.WriteFile or os.Create (and write to the file),
and vfs.CreateTemp with os.CreateTemp (or os.MkdirTemp as appropriate); ensure
you import "os" (and "path/filepath" only if needed) in the _test.go so tests
use standard filesystem APIs for fixture setup.
cmd/root.go (1)

362-375: 💤 Low value

Extract shared code-string resolution to avoid duplication.

The codeStr switch logic (lines 364-372) is identical to writeSecurityPolicyError (lines 260-267). Consider extracting a helper like securityPolicyCodeString(code int) string to keep them in sync.

♻️ Proposed refactor
+// securityPolicyCodeString maps a security policy error code to its string representation.
+func securityPolicyCodeString(code int) string {
+	switch code {
+	case internalauth.LarkErrBlockByPolicyTryAuth:
+		return "challenge_required"
+	case internalauth.LarkErrBlockByPolicy:
+		return "access_denied"
+	default:
+		return strconv.Itoa(code)
+	}
+}
+
 // logSecurityPolicyError logs a security policy error using tracking.LogAuthError.
 func logSecurityPolicyError(spErr *internalauth.SecurityPolicyError) {
-	var codeStr string
-	switch spErr.Code {
-	case internalauth.LarkErrBlockByPolicyTryAuth:
-		codeStr = "challenge_required"
-	case internalauth.LarkErrBlockByPolicy:
-		codeStr = "access_denied"
-	default:
-		codeStr = strconv.Itoa(spErr.Code)
-	}
+	codeStr := securityPolicyCodeString(spErr.Code)
 	errMsg := fmt.Sprintf("reason=security_policy code=%s message=%q", codeStr, spErr.Message)
 	tracking.LogAuthError("auth", "security_policy", fmt.Errorf(errMsg))
 }

Then update writeSecurityPolicyError to use the same helper.

🤖 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 `@cmd/root.go` around lines 362 - 375, Extract the duplicated switch that maps
security policy numeric codes to strings into a single helper function (e.g.,
securityPolicyCodeString(code int) string) and replace the switch in both
logSecurityPolicyError and writeSecurityPolicyError with calls to that helper;
ensure the helper returns "challenge_required" for
internalauth.LarkErrBlockByPolicyTryAuth, "access_denied" for
internalauth.LarkErrBlockByPolicy and otherwise returns strconv.Itoa(code), and
update both functions to use securityPolicyCodeString(spErr.Code) (or the
appropriate code value) to build their messages.
🤖 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 `@cmd/error_auth_hint.go`:
- Around line 82-102: The function extractNeedAuthorizationError is unused;
remove its entire definition from cmd/error_auth_hint.go (delete the
extractNeedAuthorizationError(...) block) and then clean up any now-unused
imports (e.g., errors or internalauth if they were only used by this function)
so the package compiles cleanly; ensure no other code references
extractNeedAuthorizationError before deleting.

In `@internal/auth/uat_client.go`:
- Around line 86-88: The code currently maps a nil refreshed result to
ReasonRefreshFailed; instead check whether the stored refresh token is expired
and return ReasonRefreshExpired in that case. Concretely, in the branch where
refreshed == nil inspect the stored token expiry field (e.g.,
stored.RefreshExpiry, stored.RefreshExpiresAt or stored.RefreshTokenExpiry—use
the actual field on the stored object) and if that timestamp is before
time.Now() return &NeedAuthorizationError{UserOpenId: opts.UserOpenId, Reason:
ReasonRefreshExpired, GrantedAt: stored.GrantedAt}; otherwise keep returning
ReasonRefreshFailed. Update the branch around refreshed == nil in uat_client.go
so telemetry differentiates expired refresh tokens from other refresh failures.

In `@internal/tracking/event.go`:
- Around line 194-203: The getParentProcessNameLinux function currently calls
os.Readlink and os.ReadFile directly; replace those calls with the repository
filesystem abstraction (use vfs.Readlink for "/proc/%d/exe" and vfs.ReadFile for
"/proc/%d/comm") so tests can mock FS access, preserving the same error handling
and returning filepath.Base(targetPath) and strings.TrimSpace(string(data)) as
before; update any other similar probes in this file to use vfs.* as well.

---

Nitpick comments:
In `@cmd/root.go`:
- Around line 362-375: Extract the duplicated switch that maps security policy
numeric codes to strings into a single helper function (e.g.,
securityPolicyCodeString(code int) string) and replace the switch in both
logSecurityPolicyError and writeSecurityPolicyError with calls to that helper;
ensure the helper returns "challenge_required" for
internalauth.LarkErrBlockByPolicyTryAuth, "access_denied" for
internalauth.LarkErrBlockByPolicy and otherwise returns strconv.Itoa(code), and
update both functions to use securityPolicyCodeString(spErr.Code) (or the
appropriate code value) to build their messages.

In `@internal/cmdutil/factory_default_test.go`:
- Line 20: Tests are using the production VFS helpers (imported as vfs and calls
like vfs.MkdirAll / vfs.WriteFile / vfs.CreateTemp) to create fixtures; switch
those to the stdlib: remove the vfs import and replace vfs.MkdirAll with
os.MkdirAll, vfs.WriteFile/vfs.Create with os.WriteFile or os.Create (and write
to the file), and vfs.CreateTemp with os.CreateTemp (or os.MkdirTemp as
appropriate); ensure you import "os" (and "path/filepath" only if needed) in the
_test.go so tests use standard filesystem APIs for fixture setup.
🪄 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: 964df8f1-abea-45b2-b5d8-d5c9f2faf263

📥 Commits

Reviewing files that changed from the base of the PR and between 27a5eed and 3c24f4c.

📒 Files selected for processing (15)
  • cmd/error_auth_hint.go
  • cmd/root.go
  • internal/auth/auth_response_log.go
  • internal/auth/device_flow_test.go
  • internal/auth/errors.go
  • internal/auth/uat_client.go
  • internal/auth/verify_test.go
  • internal/cmdutil/factory_default.go
  • internal/cmdutil/factory_default_test.go
  • internal/core/config.go
  • internal/keychain/auth_log.go
  • internal/keychain/auth_log_test.go
  • internal/keychain/keychain.go
  • internal/tracking/event.go
  • internal/tracking/event_test.go
💤 Files with no reviewable changes (2)
  • internal/keychain/auth_log_test.go
  • internal/keychain/auth_log.go

Comment thread cmd/error_auth_hint.go Outdated
Comment thread internal/auth/uat_client.go
Comment thread internal/tracking/event.go Outdated
@codecov
Copy link
Copy Markdown

codecov Bot commented May 20, 2026

Codecov Report

❌ Patch coverage is 43.06931% with 230 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.69%. Comparing base (c8b9809) to head (3dfd876).
⚠️ Report is 44 commits behind head on main.

Files with missing lines Patch % Lines
internal/tracking/auth.go 46.69% 106 Missing and 7 partials ⚠️
cmd/error_auth_hint.go 35.71% 30 Missing and 6 partials ⚠️
internal/tracking/event.go 35.84% 32 Missing and 2 partials ⚠️
cmd/root.go 39.13% 13 Missing and 1 partial ⚠️
internal/keychain/keychain.go 0.00% 10 Missing ⚠️
internal/auth/uat_client.go 0.00% 7 Missing ⚠️
internal/cmdutil/factory_default.go 63.15% 6 Missing and 1 partial ⚠️
internal/auth/auth_response_log.go 66.66% 2 Missing and 2 partials ⚠️
internal/auth/app_registration.go 0.00% 2 Missing ⚠️
internal/auth/errors.go 0.00% 1 Missing and 1 partial ⚠️
... and 1 more

❌ Your patch check has failed because the patch coverage (43.06%) is below the target coverage (60.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #987      +/-   ##
==========================================
+ Coverage   66.78%   67.69%   +0.91%     
==========================================
  Files         564      591      +27     
  Lines       52441    55457    +3016     
==========================================
+ Hits        35024    37543    +2519     
- Misses      14516    14784     +268     
- Partials     2901     3130     +229     

☔ View full report in Codecov by Sentry.
📢 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.

@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 20, 2026

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@3dfd8767e437043048dfb13fb7e2aabe551003bc

🧩 Skill update

npx skills add larksuite/cli#feat/auth_log_report -y -g

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
internal/tracking/event.go (1)

218-222: 💤 Low value

Dead code: macOS doesn't have /proc filesystem

The getParentProcessNameDarwin function attempts to read /proc/%d/exe via vfs.Readlink, but macOS does not have a /proc filesystem. This call will always fail and fall through to the ps command. Consider removing this unreachable branch to avoid confusion.

♻️ Suggested simplification
 func getParentProcessNameDarwin(ppid int) string {
-	exePath := fmt.Sprintf("/proc/%d/exe", ppid)
-	if targetPath, err := vfs.Readlink(exePath); err == nil {
-		return filepath.Base(targetPath)
-	}
-
 	cmd := exec.Command("ps", "-p", fmt.Sprintf("%d", ppid), "-o", "comm=")
 	var out bytes.Buffer
 	cmd.Stdout = &out
🤖 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 `@internal/tracking/event.go` around lines 218 - 222,
getParentProcessNameDarwin contains an unreachable branch that tries to read
"/proc/%d/exe" via vfs.Readlink (which macOS lacks); remove that branch and
simplify the function to directly use the existing ps-based fallback logic (keep
the ps invocation code path and any trimming/return logic) so there is no
attempt to read /proc using vfs.Readlink in getParentProcessNameDarwin.
🤖 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 `@internal/tracking/event.go`:
- Around line 218-222: getParentProcessNameDarwin contains an unreachable branch
that tries to read "/proc/%d/exe" via vfs.Readlink (which macOS lacks); remove
that branch and simplify the function to directly use the existing ps-based
fallback logic (keep the ps invocation code path and any trimming/return logic)
so there is no attempt to read /proc using vfs.Readlink in
getParentProcessNameDarwin.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2fe83d62-1c2a-407e-aded-f3aa827ad555

📥 Commits

Reviewing files that changed from the base of the PR and between 3c24f4c and f4bb17d.

📒 Files selected for processing (9)
  • cmd/error_auth_hint.go
  • cmd/root.go
  • internal/auth/uat_client.go
  • internal/cmdutil/factory_default.go
  • internal/cmdutil/factory_default_test.go
  • internal/tracking/event.go
  • internal/vfs/default.go
  • internal/vfs/fs.go
  • internal/vfs/osfs.go
💤 Files with no reviewable changes (1)
  • cmd/error_auth_hint.go

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
internal/tracking/event.go (1)

222-236: 💤 Low value

Dead code path: /proc does not exist on macOS

The getParentProcessNameDarwin function attempts to read /proc/%d/exe (Lines 223-226) before falling back to ps. macOS does not have a /proc filesystem, so vfs.Readlink will always fail here, making this block unreachable dead code. The fallback to ps works correctly, but this adds unnecessary overhead.

🧹 Remove dead code path
 func getParentProcessNameDarwin(ppid int) string {
-	exePath := fmt.Sprintf("/proc/%d/exe", ppid)
-	if targetPath, err := vfs.Readlink(exePath); err == nil {
-		return filepath.Base(targetPath)
-	}
-
 	cmd := exec.Command("ps", "-p", fmt.Sprintf("%d", ppid), "-o", "comm=")
 	var out bytes.Buffer
 	cmd.Stdout = &out
 	if err := cmd.Run(); err == nil {
 		return strings.TrimSpace(out.String())
 	}

 	return fmt.Sprintf("ppid=%d", ppid)
 }
🤖 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 `@internal/tracking/event.go` around lines 222 - 236, Remove the dead
/proc-based branch in getParentProcessNameDarwin: the call to
vfs.Readlink(fmt.Sprintf("/proc/%d/exe", ppid)) is unreachable on macOS, so
delete that block and directly use the existing ps fallback (exec.Command("ps",
"-p", fmt.Sprintf("%d", ppid), "-o", "comm="") with its bytes.Buffer stdout
handling) to obtain the parent process name; ensure the final fallback still
returns fmt.Sprintf("ppid=%d", ppid) if the ps command fails.
🤖 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 `@internal/tracking/event.go`:
- Around line 222-236: Remove the dead /proc-based branch in
getParentProcessNameDarwin: the call to vfs.Readlink(fmt.Sprintf("/proc/%d/exe",
ppid)) is unreachable on macOS, so delete that block and directly use the
existing ps fallback (exec.Command("ps", "-p", fmt.Sprintf("%d", ppid), "-o",
"comm="") with its bytes.Buffer stdout handling) to obtain the parent process
name; ensure the final fallback still returns fmt.Sprintf("ppid=%d", ppid) if
the ps command fails.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 904575b3-e0ab-4b60-9bc0-447bbbd82466

📥 Commits

Reviewing files that changed from the base of the PR and between 35465c7 and 1573c74.

📒 Files selected for processing (3)
  • internal/cmdutil/factory_default.go
  • internal/tracking/event.go
  • internal/tracking/event_test.go

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/tracking/event.go (1)

548-553: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fail closed for unknown/empty brand when resolving telemetry endpoint.

ResolveTelemetryEndpoint currently sends to Feishu for any non-"lark" value, including "". That makes misconfiguration/default-state route auth telemetry externally instead of disabling it. Prefer explicit allowlist ("feishu" only) and return empty for unknown/empty brands.

Proposed fix
 func ResolveTelemetryEndpoint(brand string) string {
-	if brand == "lark" {
-		return ""
-	}
-	return telemetryEndpointFeishu
+	switch strings.ToLower(strings.TrimSpace(brand)) {
+	case "feishu":
+		return telemetryEndpointFeishu
+	case "lark":
+		return ""
+	default:
+		return ""
+	}
 }
🤖 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 `@internal/tracking/event.go` around lines 548 - 553, ResolveTelemetryEndpoint
currently treats any non-"lark" brand (including empty) as Feishu; change it to
an explicit allowlist so only brand == "feishu" returns telemetryEndpointFeishu
and all other/unknown/empty brands return an empty string. Update the
ResolveTelemetryEndpoint function to check for "feishu" (not just not-"lark")
and return telemetryEndpointFeishu only in that case, otherwise return "" to
ensure unknown or empty brands fail closed.
🤖 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 `@internal/cmdutil/factory_default.go`:
- Around line 82-86: The NewDefault constructor must not call f.Config()
eagerly; remove the f.Config() invocation and the unconditional assignment to
tracking.AuthLogBrand and tracking.AuthLogAppID so construction doesn't force
credential/config resolution or swallow errors. Instead, set those tracking
globals only when a Config is successfully obtained elsewhere (e.g., after
explicit f.Config() calls or in the place that resolves configuration), or add a
dedicated helper like SetTrackingFromConfig(cfg) that callers invoke after
successful config resolution; ensure references to f.Config(), NewDefault,
tracking.AuthLogBrand and tracking.AuthLogAppID are updated accordingly.

---

Outside diff comments:
In `@internal/tracking/event.go`:
- Around line 548-553: ResolveTelemetryEndpoint currently treats any non-"lark"
brand (including empty) as Feishu; change it to an explicit allowlist so only
brand == "feishu" returns telemetryEndpointFeishu and all other/unknown/empty
brands return an empty string. Update the ResolveTelemetryEndpoint function to
check for "feishu" (not just not-"lark") and return telemetryEndpointFeishu only
in that case, otherwise return "" to ensure unknown or empty brands fail closed.
🪄 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: de4c6d47-50ef-4d18-af6d-9a02075d9fbd

📥 Commits

Reviewing files that changed from the base of the PR and between 1573c74 and 1df3757.

📒 Files selected for processing (4)
  • internal/cmdutil/factory_default.go
  • internal/cmdutil/factory_default_test.go
  • internal/tracking/event.go
  • internal/tracking/event_test.go
💤 Files with no reviewable changes (1)
  • internal/cmdutil/factory_default_test.go

Comment thread internal/cmdutil/factory_default.go Outdated
@JackZhao10086 JackZhao10086 force-pushed the feat/auth_log_report branch from 684c2e0 to 3dfd876 Compare May 22, 2026 06:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Architecture-level or global-impact change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant