Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions cmd/error_presenter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
package cmd

import (
"encoding/json"
"errors"
"fmt"
"strings"
"testing"

Expand All @@ -20,6 +22,96 @@ import (
"github.com/spf13/cobra"
)

func TestHandleRootErrorPreservesSanitizedPermissionDiagnostic(t *testing.T) {
for _, identity := range []string{"user", "bot"} {
for _, code := range []int{1061004, 99991679, 99991672} {
t.Run(fmt.Sprintf("%s/%d", identity, code), func(t *testing.T) {
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
f, stdout, stderr, _ := cmdutil.TestFactory(t, nil)
f.ResolvedIdentity = core.Identity(identity)
const secret = "private-credential-example"
source := errclass.BuildAPIError(map[string]any{
"code": code, "msg": "Static denial", "log_id": "example-log-id",
"error": map[string]any{
"message": "Rendered denial. password=\"first-line\n" + secret + "\"",
"details": []any{map[string]any{"value": "Resource is in another tenant. 'token=first-line\n" + secret + "'"}},
"permission_violations": []any{map[string]any{"subject": "docx:document"}},
"troubleshooter": "https://example.test/diagnostic",
},
}, errclass.ClassifyContext{Brand: "lark", AppID: "cli_demo", Identity: identity})
var permission *errs.PermissionError
if !errors.As(source, &permission) {
t.Fatalf("source = %T, want permission error", source)
}
cause := errors.New("private unexported cause")
permission.WithCause(cause)
wrapped := fmt.Errorf("request failed: %w", source)
presented := presentRootError(f, wrapped, recovery.NewProjector(nil))
if !errors.Is(presented, cause) {
t.Fatal("presentation lost wrapped cause")
}
exit := handleRootError(f, wrapped, recovery.NewProjector(nil))
if exit != 3 || stdout.Len() != 0 {
t.Fatalf("exit = %d, stdout = %q; want exit 3 and stderr-only envelope", exit, stdout.String())
}
var envelope struct {
OK bool `json:"ok"`
Identity string `json:"identity"`
Error errs.PermissionError `json:"error"`
}
if err := json.Unmarshal(stderr.Bytes(), &envelope); err != nil {
t.Fatalf("invalid stderr JSON: %v", err)
}
got := envelope.Error
if envelope.OK || envelope.Identity != identity || got.Identity != identity ||
got.Problem != permission.Problem || got.ConsoleURL != permission.ConsoleURL ||
strings.Join(got.MissingScopes, ",") != "docx:document" {
t.Fatalf("canonical machine/recovery fields changed: %s", stderr.String())
}
if got.Upstream == nil || got.Upstream.Message != "Rendered denial. [REDACTED]" ||
len(got.Upstream.Details) != 1 || got.Upstream.Details[0] != "Resource is in another tenant. [REDACTED]" {
t.Fatalf("root presentation dropped sanitized diagnostic: %s", stderr.String())
}
if strings.Contains(stderr.String(), secret) || strings.Contains(stderr.String(), cause.Error()) {
t.Fatalf("stderr leaked a credential or cause: %s", stderr.String())
}
})
}
}
}

func TestHandleRootErrorRedactsEncodedAndObfuscatedDiagnostics(t *testing.T) {
for name, payload := range map[string]string{
"unsigned_jwt": "eyJhbGciOiJub25lIn0.eyJzdWIiOiJBbGljZSJ9.",
"base64": "/+Hi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8=",
"ansi_scheme": "Bear\x1b[31mer\x1b[0mprivate-value-example",
"unicode_name": "'Jose\u0301's private payroll'",
} {
t.Run(name, func(t *testing.T) {
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
f, stdout, stderr, _ := cmdutil.TestFactory(t, nil)
source := errclass.BuildAPIError(map[string]any{
"code": 1061004, "msg": "Request denied for " + payload,
"error": map[string]any{"details": []any{map[string]any{"value": "Request denied for " + payload}}},
}, errclass.ClassifyContext{})
if exit := handleRootError(f, source, recovery.NewProjector(nil)); exit != 3 || stdout.Len() != 0 {
t.Fatalf("exit = %d, stdout = %q; want exit 3 and stderr-only failure", exit, stdout.String())
}
var envelope struct {
Error errs.PermissionError `json:"error"`
}
if err := json.Unmarshal(stderr.Bytes(), &envelope); err != nil {
t.Fatalf("invalid stderr JSON: %v", err)
}
got := envelope.Error.Upstream
const want = "Request denied for [REDACTED]"
if got == nil || got.Message != want || len(got.Details) != 1 || got.Details[0] != want {
t.Fatalf("encoded or obfuscated content reached stderr: %s", stderr.String())
}
})
}
}

func TestRootErrorPresenterCompletesDirectPermissionRecoveryWithoutMutatingProducer(t *testing.T) {
cause := errors.New("permission cause")
source := errs.NewPermissionError(errs.SubtypeMissingScope, "missing scope").
Expand Down
38 changes: 38 additions & 0 deletions errs/ERROR_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,44 @@ Canonical mapping: `internal/output/exitcode.go` `ExitCodeForCategory`.
> field stays formal because it is the protocol-level taxonomy; the Go
> type favors call-site readability.

### Upstream permission diagnostics

API-classified `PermissionError` values may add an optional `error.upstream`
object with `message`, `details` (an array of strings), and `truncated` (only
when true). This is informational prose, not a new reason code. Existing
`type`, `subtype`, `code`, `message`, `hint`, identity, scope fields, trace fields,
and exit code remain authoritative and unchanged. Local preflight errors do
not invent upstream diagnostics; absent text omits the object.

The classifier reads only `error.message` (preferred) or top-level `msg`, and
the first four `error.details[].value` entries. It never serializes arbitrary
response maps, headers or payloads. Each input string over 8 KiB is omitted
in full rather than exposing a partially inspected credential. After redaction
and whitespace/control normalization, message output is limited to 1024 UTF-8
bytes and each detail to 256 UTF-8 bytes, including a truncation ellipsis.
`truncated: true` also signals omitted oversized inputs or additional details;
an object containing only that marker is valid. Redaction alone does not set it.

Sanitization conservatively redacts credential/header assignments (including
their remaining line and folded continuation lines), Bearer/Basic-prefixed values
(including values joined to the scheme by terminal/control cleanup), JWT-shaped
values including empty signatures, standard/URL-safe Base64-like opaque strings
including padding, known token/identity values, full URLs, email-like tokens and
phone patterns, quoted fragments and long opaque strings. Quoted payload echoes are discarded
even when their keys are unknown; an unfinished quoted value is redacted through
the end of input. Word-internal apostrophes remain prose and do not close a
single-quoted echo, including after combining Unicode marks. URL and email-like
matching includes apostrophes and other token punctuation. Whitespace separators
are normalized before terminal
sanitization can remove them. All matches are found in the original normalized
text, and overlapping or adjacent sensitive spans
are redacted together. Assignment matching cannot split multiline quoted
content and expose its continuation. Redaction runs before output truncation.
This is a bounded diagnostic summary, not a lossless response capture or a
general-purpose PII detector: arbitrary names or secrets in unlabelled prose
cannot be identified reliably. Do not use it to forward raw business payloads
or treat server-supplied prose as trusted instructions.

## Flow

```
Expand Down
35 changes: 29 additions & 6 deletions errs/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,17 +219,28 @@ func (e *AuthenticationError) WithCause(cause error) *AuthenticationError {

// ============================= PermissionError ===============================

// UpstreamDiagnostic is an informational, sanitized summary of an API error
// before permission classification replaces its message and recovery hint.
// It is not a raw response or a machine-readable reason. Producers must redact
// sensitive content and bound both the input they inspect and the output.
type UpstreamDiagnostic struct {
Message string `json:"message,omitempty"`
Details []string `json:"details,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}

// PermissionError is the typed error for CategoryAuthorization.
// Cause preserves an optional wrapped sentinel for errors.Is / errors.Unwrap;
// it is intentionally not serialized.
type PermissionError struct {
Problem
MissingScopes []string `json:"missing_scopes,omitempty"`
RequestedScopes []string `json:"requested_scopes,omitempty"`
GrantedScopes []string `json:"granted_scopes,omitempty"`
Identity string `json:"identity,omitempty"`
ConsoleURL string `json:"console_url,omitempty"`
Cause error `json:"-"`
MissingScopes []string `json:"missing_scopes,omitempty"`
RequestedScopes []string `json:"requested_scopes,omitempty"`
GrantedScopes []string `json:"granted_scopes,omitempty"`
Identity string `json:"identity,omitempty"`
ConsoleURL string `json:"console_url,omitempty"`
Upstream *UpstreamDiagnostic `json:"upstream,omitempty"`
Cause error `json:"-"`
}

// Unwrap is nil-receiver safe; see ValidationError.Unwrap.
Expand Down Expand Up @@ -303,6 +314,18 @@ func (e *PermissionError) WithConsoleURL(url string) *PermissionError {
return e
}

// WithUpstream copies an already sanitized diagnostic, including its details.
// Passing nil clears the optional diagnostic.
func (e *PermissionError) WithUpstream(upstream *UpstreamDiagnostic) *PermissionError {
e.Upstream = nil
if upstream != nil {
clone := *upstream
clone.Details = slices.Clone(upstream.Details)
e.Upstream = &clone
}
return e
}

func (e *PermissionError) WithCause(cause error) *PermissionError {
e.Cause = cause
return e
Expand Down
72 changes: 72 additions & 0 deletions errs/upstream_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package errs_test

import (
"encoding/json"
"testing"

"github.com/larksuite/cli/errs"
)

func TestPermissionErrorWithUpstreamOwnsDiagnostic(t *testing.T) {
diagnostic := &errs.UpstreamDiagnostic{
Message: "API reason", Details: []string{"API detail"}, Truncated: true,
}
err := errs.NewPermissionError(errs.SubtypePermissionDenied, "canonical message").WithUpstream(diagnostic)
diagnostic.Message = "changed"
diagnostic.Details[0] = "changed"
diagnostic.Truncated = false
if err.Upstream.Message != "API reason" || err.Upstream.Details[0] != "API detail" || !err.Upstream.Truncated {
t.Fatalf("builder aliases input: %+v", err.Upstream)
}
if got := err.WithUpstream(nil); got != err || got.Upstream != nil {
t.Fatalf("nil must clear the optional diagnostic: %+v", got)
}
}

func TestPermissionErrorUpstreamJSONCompatibility(t *testing.T) {
err := errs.NewPermissionError(errs.SubtypePermissionDenied, "canonical message").WithCode(1061004).WithIdentity("user")
const legacy = `{"type":"authorization","subtype":"permission_denied","code":1061004,"message":"canonical message","identity":"user"}`
b, marshalErr := json.Marshal(err)
if marshalErr != nil {
t.Fatal(marshalErr)
}
if string(b) != legacy {
t.Fatalf("absent diagnostic changed legacy JSON: %s", b)
}
err.WithUpstream(&errs.UpstreamDiagnostic{Message: "API reason", Details: []string{"API detail"}, Truncated: true})
b, marshalErr = json.Marshal(err)
if marshalErr != nil {
t.Fatal(marshalErr)
}
const want = `{"type":"authorization","subtype":"permission_denied","code":1061004,"message":"canonical message","identity":"user","upstream":{"message":"API reason","details":["API detail"],"truncated":true}}`
if string(b) != want {
t.Fatalf("diagnostic is not an additive typed-error extension: %s", b)
}
// Existing consumers that ignore unknown fields still decode the same
// machine fields and canonical message from the extended error.
var oldConsumer struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
Code int `json:"code"`
Message string `json:"message"`
Identity string `json:"identity"`
}
if decodeErr := json.Unmarshal(b, &oldConsumer); decodeErr != nil {
t.Fatal(decodeErr)
}
if oldConsumer.Type != "authorization" || oldConsumer.Subtype != "permission_denied" || oldConsumer.Code != 1061004 ||
oldConsumer.Message != "canonical message" || oldConsumer.Identity != "user" {
t.Fatalf("legacy consumer contract changed: %+v", oldConsumer)
}
err.WithUpstream(&errs.UpstreamDiagnostic{Message: "API reason"})
b, marshalErr = json.Marshal(err.Upstream)
if marshalErr != nil {
t.Fatal(marshalErr)
}
if string(b) != `{"message":"API reason"}` {
t.Fatalf("empty details and false truncated must be omitted: %s", b)
}
}
13 changes: 8 additions & 5 deletions internal/errclass/classify.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,10 @@ func BuildAPIError(resp map[string]any, cc ClassifyContext) error {
// prompt — rather than fabricated structured params. Lifted before the
// category switch so any classified arm inherits it; the CategoryAPI arm
// below prefers this server detail over the context-free APIHint default.
detailHint := liftErrorDetailValues(resp)
if detailHint != "" {
base.Hint = detailHint
// Authorization has canonical recovery; retain its upstream reasons only
// through the bounded, sanitized diagnostic path instead of joining them.
if meta.Category != errs.CategoryAuthorization {
base.Hint = liftErrorDetailValues(resp)
}

switch meta.Category {
Expand Down Expand Up @@ -302,7 +303,7 @@ func APIHint(subtype errs.Subtype) string {

func buildPermissionError(p errs.Problem, resp map[string]any, cc ClassifyContext) error {
missing := extractMissingScopes(resp)
return buildPermissionErrorFromFacts(p, missing, cc)
return buildPermissionErrorFromFacts(p, missing, cc, permissionDiagnostic(resp))
}

// NewMissingScopeError constructs the same typed missing-scope error as the
Expand All @@ -317,10 +318,11 @@ func NewMissingScopeError(brand, appID, identity string, missing []string) error
},
missing,
ClassifyContext{Brand: brand, AppID: appID, Identity: identity},
nil,
)
}

func buildPermissionErrorFromFacts(p errs.Problem, missing []string, cc ClassifyContext) error {
func buildPermissionErrorFromFacts(p errs.Problem, missing []string, cc ClassifyContext, upstream *errs.UpstreamDiagnostic) error {
missing = append([]string(nil), missing...)
identity := cc.Identity
if identity == "" {
Expand All @@ -338,6 +340,7 @@ func buildPermissionErrorFromFacts(p errs.Problem, missing []string, cc Classify
Problem: p,
MissingScopes: missing,
Identity: identity,
Upstream: upstream,
}
// ConsoleURL is the developer-console deep-link an app developer follows to
// apply for a missing scope. The typed machine field is attached only to
Expand Down
11 changes: 6 additions & 5 deletions internal/errclass/classify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -698,10 +698,10 @@ func TestExtractMissingScopes_Dedup(t *testing.T) {
// A future drift in subtype-specific field gating therefore fails this test
// without the test hand-copying either implementation.
//
// One upstream-derived field is a documented exception: `code` (the Lark
// API numeric code). The pre-flight check runs against a locally cached
// Upstream-derived `code` and `upstream` diagnostics are documented exceptions.
// The pre-flight check runs against a locally cached
// scope list and has no upstream response to extract it from. The
// comparison below strips that key from both envelopes so the assertion
// comparison below strips those keys from both envelopes so the assertion
// isolates the contract fields that MUST converge: Subtype, Category,
// Message, Hint, Identity, MissingScopes, ConsoleURL.
func TestServiceShortcutEnvelopeConverge(t *testing.T) {
Expand Down Expand Up @@ -730,7 +730,7 @@ func TestServiceShortcutEnvelopeConverge(t *testing.T) {
t.Fatal("direct path failed to emit typed envelope")
}

// Strip `code` from both envelopes — see test doc above.
// Strip server-only fields from both envelopes — see test doc above.
stripA := stripUpstreamFields(t, bufA.Bytes())
stripB := stripUpstreamFields(t, bufB.Bytes())
if stripA != stripB {
Expand All @@ -739,7 +739,7 @@ func TestServiceShortcutEnvelopeConverge(t *testing.T) {
}

// stripUpstreamFields parses an envelope JSON and re-marshals it with the
// upstream-derived "code" key removed from the inner "error" block. Used by
// upstream-derived "code" and "upstream" keys removed from the inner "error" block. Used by
// the convergence test to isolate contract fields shared between the
// dispatcher and pre-flight paths.
func stripUpstreamFields(t *testing.T, raw []byte) string {
Expand All @@ -750,6 +750,7 @@ func stripUpstreamFields(t *testing.T, raw []byte) string {
}
if errBlock, ok := obj["error"].(map[string]any); ok {
delete(errBlock, "code")
delete(errBlock, "upstream")
}
out, err := json.Marshal(obj)
if err != nil {
Expand Down
Loading
Loading