chore: import upstream snapshot with attribution
CI / license-header (push) Has been skipped
CI / e2e-dry-run (push) Has been skipped
CI / fast-gate (push) Failing after 0s
Test PR Label Logic / test-pr-labels (push) Failing after 1s
Skill Format Check / check-format (push) Failing after 2s
CI / security (push) Failing after 5s
CI / unit-test (push) Has been skipped
CI / lint (push) Has been skipped
CI / script-test (push) Has been skipped
CI / deterministic-gate (push) Has been skipped
CI / coverage (push) Has been skipped
CI / results (push) Has been cancelled
CI / deadcode (push) Has been cancelled
CI / e2e-live (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:22:54 +08:00
commit bf9395e022
2349 changed files with 588574 additions and 0 deletions
+381
View File
@@ -0,0 +1,381 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package credential
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"sync"
extcred "github.com/larksuite/cli/extension/credential"
"github.com/larksuite/cli/internal/auth"
"github.com/larksuite/cli/internal/core"
)
// DefaultAccountResolver is implemented by the default account provider.
type DefaultAccountResolver interface {
ResolveAccount(ctx context.Context) (*Account, error)
}
// DefaultTokenResolver is implemented by the default token provider.
type DefaultTokenResolver interface {
ResolveToken(ctx context.Context, req TokenSpec) (*TokenResult, error)
}
var (
getStoredToken = auth.GetStoredToken
getStoredTokenStatus = auth.TokenStatus
)
type credentialSource interface {
Name() string
TryResolveToken(ctx context.Context, req TokenSpec) (*TokenResult, bool, error)
ResolveIdentityHint(ctx context.Context, acct *Account) (*IdentityHint, error)
}
type extensionTokenSource struct {
provider extcred.Provider
}
func (s extensionTokenSource) Name() string { return s.provider.Name() }
func (s extensionTokenSource) TryResolveToken(ctx context.Context, req TokenSpec) (*TokenResult, bool, error) {
tok, err := s.provider.ResolveToken(ctx, extcred.TokenSpec{
Type: extcred.TokenType(req.Type.String()),
AppID: req.AppID,
})
if err != nil {
return nil, false, err
}
if tok == nil {
return nil, false, nil
}
if tok.Value == "" {
return nil, false, &MalformedTokenResultError{Source: s.Name(), Type: req.Type, Reason: "empty token"}
}
return &TokenResult{Token: tok.Value, Scopes: tok.Scopes}, true, nil
}
func (s extensionTokenSource) ResolveIdentityHint(ctx context.Context, acct *Account) (*IdentityHint, error) {
hint := &IdentityHint{}
if acct == nil {
return hint, nil
}
hint.DefaultAs = acct.DefaultAs
// Extension sources verify user identity via enrichUserInfo, so a resolved
// UserOpenId is sufficient here; no keychain-backed token status lookup is needed.
if acct.UserOpenId != "" {
hint.AutoAs = core.AsUser
return hint, nil
}
ids := extcred.IdentitySupport(acct.SupportedIdentities)
switch {
case ids.UserOnly():
hint.AutoAs = core.AsUser
case ids.BotOnly():
hint.AutoAs = core.AsBot
}
return hint, nil
}
type defaultTokenSource struct {
resolver DefaultTokenResolver
}
func (s defaultTokenSource) Name() string { return "default" }
func (s defaultTokenSource) TryResolveToken(ctx context.Context, req TokenSpec) (*TokenResult, bool, error) {
if s.resolver == nil {
return nil, false, nil
}
result, err := s.resolver.ResolveToken(ctx, req)
if err != nil {
return nil, false, err
}
if result == nil {
return nil, false, &MalformedTokenResultError{Source: s.Name(), Type: req.Type, Reason: "nil token result"}
}
if result.Token == "" {
return nil, false, &MalformedTokenResultError{Source: s.Name(), Type: req.Type, Reason: "empty token"}
}
return result, true, nil
}
func (s defaultTokenSource) ResolveIdentityHint(ctx context.Context, acct *Account) (*IdentityHint, error) {
hint := &IdentityHint{}
if acct == nil {
return hint, nil
}
hint.DefaultAs = acct.DefaultAs
if acct.UserOpenId == "" {
hint.AutoAs = core.AsBot
return hint, nil
}
stored := getStoredToken(acct.AppID, acct.UserOpenId)
if stored == nil {
hint.AutoAs = core.AsBot
return hint, nil
}
if getStoredTokenStatus(stored) == "expired" {
hint.AutoAs = core.AsBot
return hint, nil
}
hint.AutoAs = core.AsUser
return hint, nil
}
// CredentialProvider is the unified entry point for all credential resolution.
type CredentialProvider struct {
providers []extcred.Provider
defaultAcct DefaultAccountResolver
defaultToken DefaultTokenResolver
httpClient func() (*http.Client, error)
warnOut io.Writer
accountOnce sync.Once
account *Account
accountErr error
selectedSource credentialSource
hintOnce sync.Once
hint *IdentityHint
hintErr error
}
// NewCredentialProvider creates a CredentialProvider.
func NewCredentialProvider(providers []extcred.Provider, defaultAcct DefaultAccountResolver, defaultToken DefaultTokenResolver, httpClient func() (*http.Client, error)) *CredentialProvider {
return &CredentialProvider{
providers: providers,
defaultAcct: defaultAcct,
defaultToken: defaultToken,
httpClient: httpClient,
}
}
func (p *CredentialProvider) SetWarnOut(warnOut io.Writer) *CredentialProvider {
p.warnOut = warnOut
return p
}
// ResolveAccount resolves app credentials. Result is cached after first call.
// NOTE: Uses sync.Once — only the context from the first call is used for resolution.
// Subsequent calls return the cached result regardless of their context.
// This is acceptable for CLI (single invocation per process) but not for long-running servers.
func (p *CredentialProvider) ResolveAccount(ctx context.Context) (*Account, error) {
p.accountOnce.Do(func() {
p.account, p.accountErr = p.doResolveAccount(ctx)
})
return p.account, p.accountErr
}
func (p *CredentialProvider) doResolveAccount(ctx context.Context) (*Account, error) {
for _, prov := range p.providers {
acct, err := prov.ResolveAccount(ctx)
if err != nil {
return nil, err
}
if acct != nil {
internal := convertAccount(acct)
source := extensionTokenSource{provider: prov}
if err := p.enrichUserInfo(ctx, internal, source); err != nil {
if p.warnOut != nil {
_, _ = fmt.Fprintf(p.warnOut, "warning: unable to verify user identity from credential source %q: %v\n", source.Name(), err)
}
// enrichUserInfo failure is non-fatal: SupportedIdentities
// (used for strict mode) is already set by the provider.
// Clear unverified user identity for safety.
internal.UserOpenId = ""
internal.UserName = ""
}
p.selectedSource = source
return internal, nil
}
}
if p.defaultAcct != nil {
acct, err := p.defaultAcct.ResolveAccount(ctx)
if err != nil {
return nil, err
}
p.selectedSource = defaultTokenSource{resolver: p.defaultToken}
return acct, nil
}
return nil, core.NotConfiguredError()
}
// enrichUserInfo resolves user identity when extension provides a UAT.
// If UAT is available, user_info API call is mandatory (security: verify token validity).
// If no UAT from extension, falls back to provider-supplied OpenID.
func (p *CredentialProvider) enrichUserInfo(ctx context.Context, acct *Account, source credentialSource) error {
if p.httpClient == nil || source == nil {
return nil
}
tok, found, err := source.TryResolveToken(ctx, TokenSpec{Type: TokenTypeUAT, AppID: acct.AppID})
if err != nil {
var blockErr *extcred.BlockError
if errors.As(err, &blockErr) {
return nil // provider explicitly blocks UAT; skip enrichment
}
return fmt.Errorf("failed to resolve UAT for user identity verification: %w", err)
}
if !found {
return nil
}
// Have UAT — must verify and resolve identity
hc, err := p.httpClient()
if err != nil {
return fmt.Errorf("failed to get HTTP client for user_info: %w", err)
}
info, err := fetchUserInfo(ctx, hc, acct.Brand, tok.Token)
if err != nil {
return fmt.Errorf("failed to verify user identity: %w", err)
}
acct.UserOpenId = info.OpenID
acct.UserName = info.Name
return nil
}
func (p *CredentialProvider) selectedCredentialSource(ctx context.Context) (credentialSource, error) {
if p.selectedSource != nil {
return p.selectedSource, nil
}
if p.defaultAcct == nil {
return nil, nil
}
if _, err := p.ResolveAccount(ctx); err != nil {
return nil, err
}
if p.selectedSource == nil {
return nil, fmt.Errorf("credential provider resolved an account without selecting a token source")
}
return p.selectedSource, nil
}
func resolveTokenFromSource(ctx context.Context, source credentialSource, req TokenSpec) (*TokenResult, error) {
result, found, err := source.TryResolveToken(ctx, req)
if err != nil {
return nil, err
}
if !found {
return nil, &TokenUnavailableError{Source: source.Name(), Type: req.Type}
}
return result, nil
}
// ResolveIdentityHint resolves default/auto identity guidance from the selected source.
// NOTE: Uses sync.Once — only the context from the first call is used for resolution.
// This matches ResolveAccount and keeps identity decisions stable within one CLI invocation.
func (p *CredentialProvider) ResolveIdentityHint(ctx context.Context) (*IdentityHint, error) {
p.hintOnce.Do(func() {
p.hint, p.hintErr = p.doResolveIdentityHint(ctx)
})
return p.hint, p.hintErr
}
func (p *CredentialProvider) doResolveIdentityHint(ctx context.Context) (*IdentityHint, error) {
acct, err := p.ResolveAccount(ctx)
if err != nil {
return nil, err
}
if acct == nil {
return &IdentityHint{}, nil
}
source, err := p.selectedCredentialSource(ctx)
if err != nil {
return nil, err
}
if source == nil {
return &IdentityHint{}, nil
}
hint, err := source.ResolveIdentityHint(ctx, acct)
if err != nil {
return nil, err
}
if hint == nil {
return &IdentityHint{}, nil
}
return hint, nil
}
// ResolveToken resolves an access token.
func (p *CredentialProvider) ResolveToken(ctx context.Context, req TokenSpec) (*TokenResult, error) {
source, err := p.selectedCredentialSource(ctx)
if err != nil {
return nil, err
}
if source != nil {
return resolveTokenFromSource(ctx, source, req)
}
for _, prov := range p.providers {
source := extensionTokenSource{provider: prov}
result, found, err := source.TryResolveToken(ctx, req)
if err != nil {
return nil, err
}
if found {
return result, nil
}
}
source = defaultTokenSource{resolver: p.defaultToken}
result, found, err := source.TryResolveToken(ctx, req)
if err != nil {
return nil, err
}
if found {
return result, nil
}
return nil, &TokenUnavailableError{Type: req.Type}
}
// ActiveExtensionProviderName reports whether an extension provider is managing
// credentials. It probes p.providers (extension providers only, not defaultAcct)
// and returns the name of the first engaged provider.
//
// "Engaged" means: ResolveAccount returns a non-nil account, OR returns a
// *extcred.BlockError (provider configured but misconfigured — still counts as
// external). Any other error is propagated to the caller.
//
// Returns ("", nil) when no extension provider is active (built-in keychain path).
// Safe to call multiple times — probes providers directly without the sync.Once cache.
func (p *CredentialProvider) ActiveExtensionProviderName(ctx context.Context) (string, error) {
for _, prov := range p.providers {
acct, err := prov.ResolveAccount(ctx)
if err != nil {
var blockErr *extcred.BlockError
if errors.As(err, &blockErr) {
name := blockErr.Provider
if name == "" {
name = prov.Name()
}
if name == "" {
name = "external"
}
return name, nil
}
return "", err
}
if acct != nil {
if name := prov.Name(); name != "" {
return name, nil
}
return "external", nil
}
}
return "", nil
}
func convertAccount(ext *extcred.Account) *Account {
return &Account{
AppID: ext.AppID,
AppSecret: ext.AppSecret,
Brand: core.LarkBrand(ext.Brand),
DefaultAs: core.Identity(ext.DefaultAs),
ProfileName: ext.ProfileName,
UserOpenId: ext.OpenID,
SupportedIdentities: uint8(ext.SupportedIdentities),
}
}
@@ -0,0 +1,493 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package credential
import (
"bytes"
"context"
"errors"
"net/http"
"strings"
"testing"
extcred "github.com/larksuite/cli/extension/credential"
"github.com/larksuite/cli/internal/auth"
"github.com/larksuite/cli/internal/core"
)
type mockExtProvider struct {
name string
account *extcred.Account
token *extcred.Token
err error
accountErr error
tokenErr error
}
func (m *mockExtProvider) Name() string { return m.name }
func (m *mockExtProvider) ResolveAccount(ctx context.Context) (*extcred.Account, error) {
if m.accountErr != nil {
return nil, m.accountErr
}
return m.account, m.err
}
func (m *mockExtProvider) ResolveToken(ctx context.Context, req extcred.TokenSpec) (*extcred.Token, error) {
if m.tokenErr != nil {
return nil, m.tokenErr
}
return m.token, m.err
}
type mockDefaultAcct struct {
account *Account
err error
}
func (m *mockDefaultAcct) ResolveAccount(ctx context.Context) (*Account, error) {
return m.account, m.err
}
type mockDefaultToken struct {
result *TokenResult
err error
}
func (m *mockDefaultToken) ResolveToken(ctx context.Context, req TokenSpec) (*TokenResult, error) {
return m.result, m.err
}
func TestCredentialProvider_AccountFromExtension(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "env", account: &extcred.Account{AppID: "ext_app", Brand: "lark"}}},
&mockDefaultAcct{account: &Account{AppID: "default_app"}},
&mockDefaultToken{}, nil,
)
acct, err := cp.ResolveAccount(context.Background())
if err != nil {
t.Fatal(err)
}
if acct.AppID != "ext_app" {
t.Errorf("expected ext_app, got %s", acct.AppID)
}
}
func TestCredentialProvider_AccountFallsToDefault(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "skip"}},
&mockDefaultAcct{account: &Account{AppID: "default_app", Brand: "feishu"}},
&mockDefaultToken{}, nil,
)
acct, err := cp.ResolveAccount(context.Background())
if err != nil {
t.Fatal(err)
}
if acct.AppID != "default_app" {
t.Errorf("expected default_app, got %s", acct.AppID)
}
}
func TestCredentialProvider_AccountBlockStopsChain(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "blocker", err: &extcred.BlockError{Provider: "blocker", Reason: "denied"}}},
&mockDefaultAcct{account: &Account{AppID: "default_app"}},
&mockDefaultToken{}, nil,
)
_, err := cp.ResolveAccount(context.Background())
if err == nil {
t.Fatal("expected error")
}
var blockErr *extcred.BlockError
if !errors.As(err, &blockErr) {
t.Fatalf("expected BlockError, got %T", err)
}
}
func TestCredentialProvider_AccountCached(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "env", account: &extcred.Account{AppID: "cached"}}},
nil, nil, nil,
)
a1, _ := cp.ResolveAccount(context.Background())
a2, _ := cp.ResolveAccount(context.Background())
if a1 != a2 {
t.Error("expected same pointer (cached)")
}
}
func TestCredentialProvider_TokenFromExtension(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{
name: "env",
account: &extcred.Account{AppID: "ext_app", Brand: "feishu"},
token: &extcred.Token{Value: "ext_tok", Source: "env"},
}},
&mockDefaultAcct{}, &mockDefaultToken{result: &TokenResult{Token: "default_tok"}}, nil,
)
result, err := cp.ResolveToken(context.Background(), TokenSpec{Type: TokenTypeUAT})
if err != nil {
t.Fatal(err)
}
if result.Token != "ext_tok" {
t.Errorf("expected ext_tok, got %s", result.Token)
}
}
func TestCredentialProvider_TokenFallsToDefault(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "skip"}},
&mockDefaultAcct{}, &mockDefaultToken{result: &TokenResult{Token: "default_tok"}}, nil,
)
result, err := cp.ResolveToken(context.Background(), TokenSpec{Type: TokenTypeUAT})
if err != nil {
t.Fatal(err)
}
if result.Token != "default_tok" {
t.Errorf("expected default_tok, got %s", result.Token)
}
}
func TestCredentialProvider_TokenDoesNotMixSourcesAfterDefaultAccountSelection(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "env", token: &extcred.Token{Value: "ext_tok", Source: "env"}}},
&mockDefaultAcct{account: &Account{AppID: "default_app", Brand: core.BrandFeishu}},
&mockDefaultToken{result: &TokenResult{Token: "default_tok"}},
nil,
)
if _, err := cp.ResolveAccount(context.Background()); err != nil {
t.Fatalf("ResolveAccount() error = %v", err)
}
result, err := cp.ResolveToken(context.Background(), TokenSpec{Type: TokenTypeUAT})
if err != nil {
t.Fatalf("ResolveToken() error = %v", err)
}
if result.Token != "default_tok" {
t.Fatalf("ResolveToken() token = %q, want %q", result.Token, "default_tok")
}
}
func TestCredentialProvider_SelectedSourceWithoutTokenReturnsUnavailableError(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{
name: "env",
account: &extcred.Account{AppID: "ext_app", Brand: "feishu"},
}},
nil, nil, nil,
)
if _, err := cp.ResolveAccount(context.Background()); err != nil {
t.Fatalf("ResolveAccount() error = %v", err)
}
_, err := cp.ResolveToken(context.Background(), TokenSpec{Type: TokenTypeUAT})
if err == nil {
t.Fatal("ResolveToken() error = nil, want unavailable error")
}
var unavailableErr *TokenUnavailableError
if !errors.As(err, &unavailableErr) {
t.Fatalf("ResolveToken() error type = %T, want *TokenUnavailableError", err)
}
if unavailableErr.Source != "env" || unavailableErr.Type != TokenTypeUAT {
t.Fatalf("ResolveToken() unavailable error = %+v, want source env and type uat", unavailableErr)
}
}
func TestCredentialProvider_ResolveTokenPropagatesNonBlockExtensionError(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "env", err: errors.New("provider exploded")}},
nil,
&mockDefaultToken{result: &TokenResult{Token: "default_tok"}},
nil,
)
_, err := cp.ResolveToken(context.Background(), TokenSpec{Type: TokenTypeUAT})
if err == nil || err.Error() != "provider exploded" {
t.Fatalf("ResolveToken() error = %v, want provider exploded", err)
}
}
func TestCredentialProvider_ResolveIdentityHint_FromExtensionAccount(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "env", account: &extcred.Account{
AppID: "ext_app",
Brand: "feishu",
DefaultAs: extcred.IdentityUser,
SupportedIdentities: extcred.SupportsUser,
}}},
nil, nil, nil,
)
hint, err := cp.ResolveIdentityHint(context.Background())
if err != nil {
t.Fatalf("ResolveIdentityHint() error = %v", err)
}
if hint.DefaultAs != core.AsUser {
t.Fatalf("ResolveIdentityHint() defaultAs = %q, want %q", hint.DefaultAs, core.AsUser)
}
if hint.AutoAs != core.AsUser {
t.Fatalf("ResolveIdentityHint() autoAs = %q, want %q", hint.AutoAs, core.AsUser)
}
}
func TestCredentialProvider_ResolveIdentityHint_DefaultSourceUsesStoredTokenState(t *testing.T) {
origGetStoredToken := getStoredToken
origTokenStatus := getStoredTokenStatus
t.Cleanup(func() {
getStoredToken = origGetStoredToken
getStoredTokenStatus = origTokenStatus
})
getStoredToken = func(appID, userOpenID string) *auth.StoredUAToken {
if appID != "default_app" || userOpenID != "ou_default" {
t.Fatalf("GetStoredToken() args = (%q, %q), want (%q, %q)", appID, userOpenID, "default_app", "ou_default")
}
return &auth.StoredUAToken{AppId: appID, UserOpenId: userOpenID}
}
getStoredTokenStatus = func(token *auth.StoredUAToken) string {
return "valid"
}
cp := NewCredentialProvider(
nil,
&mockDefaultAcct{account: &Account{AppID: "default_app", Brand: core.BrandFeishu, UserOpenId: "ou_default"}},
&mockDefaultToken{result: &TokenResult{Token: "default_tok"}},
nil,
)
hint, err := cp.ResolveIdentityHint(context.Background())
if err != nil {
t.Fatalf("ResolveIdentityHint() error = %v", err)
}
if hint.AutoAs != core.AsUser {
t.Fatalf("ResolveIdentityHint() autoAs = %q, want %q", hint.AutoAs, core.AsUser)
}
}
func TestCredentialProvider_ResolveIdentityHint_CachesResult(t *testing.T) {
origGetStoredToken := getStoredToken
origTokenStatus := getStoredTokenStatus
t.Cleanup(func() {
getStoredToken = origGetStoredToken
getStoredTokenStatus = origTokenStatus
})
storedCalls := 0
statusCalls := 0
getStoredToken = func(appID, userOpenID string) *auth.StoredUAToken {
storedCalls++
return &auth.StoredUAToken{AppId: appID, UserOpenId: userOpenID}
}
getStoredTokenStatus = func(token *auth.StoredUAToken) string {
statusCalls++
return "valid"
}
cp := NewCredentialProvider(
nil,
&mockDefaultAcct{account: &Account{AppID: "default_app", Brand: core.BrandFeishu, UserOpenId: "ou_default"}},
&mockDefaultToken{result: &TokenResult{Token: "default_tok"}},
nil,
)
for i := 0; i < 2; i++ {
hint, err := cp.ResolveIdentityHint(context.Background())
if err != nil {
t.Fatalf("ResolveIdentityHint() error = %v", err)
}
if hint.AutoAs != core.AsUser {
t.Fatalf("ResolveIdentityHint() autoAs = %q, want %q", hint.AutoAs, core.AsUser)
}
}
if storedCalls != 1 {
t.Fatalf("GetStoredToken() calls = %d, want 1", storedCalls)
}
if statusCalls != 1 {
t.Fatalf("TokenStatus() calls = %d, want 1", statusCalls)
}
}
func TestCredentialProvider_ResolveTokenTreatsEmptyDefaultTokenAsMalformed(t *testing.T) {
cp := NewCredentialProvider(
nil,
nil,
&mockDefaultToken{result: &TokenResult{Token: ""}},
nil,
)
_, err := cp.ResolveToken(context.Background(), TokenSpec{Type: TokenTypeUAT})
if err == nil || !strings.Contains(err.Error(), "empty token") {
t.Fatalf("ResolveToken() error = %v, want malformed empty token error", err)
}
}
func TestCredentialProvider_ResolveAccountDoesNotEnrichWithTokenFromDifferentProvider(t *testing.T) {
httpClientCalls := 0
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "env", token: &extcred.Token{Value: "ext_tok", Source: "env"}}},
&mockDefaultAcct{account: &Account{
AppID: "default_app",
Brand: core.BrandFeishu,
UserOpenId: "ou_default",
UserName: "Default User",
}},
&mockDefaultToken{},
func() (*http.Client, error) {
httpClientCalls++
return nil, errors.New("unexpected enrich call")
},
)
acct, err := cp.ResolveAccount(context.Background())
if err != nil {
t.Fatalf("ResolveAccount() error = %v", err)
}
if httpClientCalls != 0 {
t.Fatalf("httpClient() called %d times, want 0", httpClientCalls)
}
if acct.UserOpenId != "ou_default" || acct.UserName != "Default User" {
t.Fatalf("resolved user = (%q, %q), want (%q, %q)", acct.UserOpenId, acct.UserName, "ou_default", "Default User")
}
}
func TestCredentialProvider_ResolveAccountClearsUnverifiedExtensionIdentityOnTokenError(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "env", account: &extcred.Account{
AppID: "ext_app",
Brand: "feishu",
OpenID: "ou_ext",
}, tokenErr: errors.New("token lookup failed")}},
nil,
nil,
func() (*http.Client, error) {
t.Fatal("httpClient() should not be called when token lookup fails")
return nil, nil
},
)
acct, err := cp.ResolveAccount(context.Background())
if err != nil {
t.Fatalf("ResolveAccount() error = %v", err)
}
if acct.UserOpenId != "" || acct.UserName != "" {
t.Fatalf("resolved user = (%q, %q), want cleared unverified identity", acct.UserOpenId, acct.UserName)
}
}
func TestCredentialProvider_ResolveAccountWarnsWhenExtensionIdentityVerificationFails(t *testing.T) {
var warnBuf bytes.Buffer
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "env", account: &extcred.Account{
AppID: "ext_app",
Brand: "feishu",
OpenID: "ou_ext",
}, tokenErr: errors.New("token lookup failed")}},
nil,
nil,
func() (*http.Client, error) {
t.Fatal("httpClient() should not be called when token lookup fails")
return nil, nil
},
)
cp.SetWarnOut(&warnBuf)
acct, err := cp.ResolveAccount(context.Background())
if err != nil {
t.Fatalf("ResolveAccount() error = %v", err)
}
if acct.UserOpenId != "" || acct.UserName != "" {
t.Fatalf("resolved user = (%q, %q), want cleared unverified identity", acct.UserOpenId, acct.UserName)
}
if !strings.Contains(warnBuf.String(), "unable to verify user identity from credential source \"env\"") {
t.Fatalf("warning output = %q, want source-specific verification warning", warnBuf.String())
}
if !strings.Contains(warnBuf.String(), "token lookup failed") {
t.Fatalf("warning output = %q, want underlying error", warnBuf.String())
}
}
func TestCredentialProvider_ResolveTokenDoesNotBypassFailedDefaultAccountResolution(t *testing.T) {
cp := NewCredentialProvider(
nil,
&mockDefaultAcct{err: errors.New("config unavailable")},
&mockDefaultToken{result: &TokenResult{Token: "default_tok"}},
nil,
)
_, err := cp.ResolveToken(context.Background(), TokenSpec{Type: TokenTypeUAT})
if err == nil || err.Error() != "config unavailable" {
t.Fatalf("ResolveToken() error = %v, want config unavailable", err)
}
}
func TestActiveExtensionProviderName_ExtActive(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "env", account: &extcred.Account{AppID: "app"}}},
nil, nil, nil,
)
name, err := cp.ActiveExtensionProviderName(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if name != "env" {
t.Errorf("got %q, want %q", name, "env")
}
}
func TestActiveExtensionProviderName_BlockError(t *testing.T) {
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{
name: "env",
accountErr: &extcred.BlockError{Provider: "env", Reason: "APP_ID missing"},
}},
nil, nil, nil,
)
name, err := cp.ActiveExtensionProviderName(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if name != "env" {
t.Errorf("got %q, want %q", name, "env")
}
}
func TestActiveExtensionProviderName_NoExtProvider(t *testing.T) {
cp := NewCredentialProvider(nil, nil, nil, nil)
name, err := cp.ActiveExtensionProviderName(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if name != "" {
t.Errorf("got %q, want empty string", name)
}
}
func TestActiveExtensionProviderName_UnexpectedError(t *testing.T) {
sentinel := errors.New("network timeout")
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "env", accountErr: sentinel}},
nil, nil, nil,
)
_, err := cp.ActiveExtensionProviderName(context.Background())
if !errors.Is(err, sentinel) {
t.Errorf("got %v, want sentinel error", err)
}
}
func TestActiveExtensionProviderName_SkipsNilProvider(t *testing.T) {
// nil account + nil error = provider not applicable; fallback returns ""
cp := NewCredentialProvider(
[]extcred.Provider{&mockExtProvider{name: "sidecar"}}, // no account set → returns nil, nil
nil, nil, nil,
)
name, err := cp.ActiveExtensionProviderName(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if name != "" {
t.Errorf("got %q, want empty string", name)
}
}
+183
View File
@@ -0,0 +1,183 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package credential
import (
"context"
"fmt"
"io"
"net/http"
"sync"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/auth"
"github.com/larksuite/cli/internal/core"
"github.com/larksuite/cli/internal/errclass"
"github.com/larksuite/cli/internal/keychain"
extcred "github.com/larksuite/cli/extension/credential"
)
// classifyTATResponseCode wraps a deterministic (non-transient) failure from the
// unified Token Endpoint into the canonical typed errs.* error. The v3 endpoint
// reports failures using the OAuth 2.0 model — an `error` string plus an
// optional numeric `code` — instead of the legacy `{code, msg}` shape.
//
// invalid_client / unauthorized_client mean the configured app_id/app_secret
// cannot mint a token; from the user's perspective that is the same actionable
// CategoryConfig/InvalidClient failure the legacy 10003/10014 codes produced.
// Every other deterministic error falls through to BuildAPIError, which still
// yields a typed error so probe callers (errs.IsTyped) surface it rather than
// swallowing it. Transient/server-side failures (5xx / server_error) are
// filtered out by FetchTAT before this is called, so they stay untyped.
func classifyTATResponseCode(code int, oauthErr, errDesc, brand, appID string) error {
msg := errDesc
if msg == "" {
msg = oauthErr
}
switch oauthErr {
case "invalid_client", "unauthorized_client":
return errs.NewConfigError(errs.SubtypeInvalidClient, "%s", msg).
WithCode(code).
WithHint("%s", errclass.ConfigHint(errs.SubtypeInvalidClient))
}
if err := errclass.BuildAPIError(map[string]any{
"code": code,
"msg": msg,
}, errclass.ClassifyContext{
Brand: brand,
AppID: appID,
}); err != nil {
return err
}
// BuildAPIError returns nil for code 0 (Feishu's success convention), but this
// function is only reached once FetchTAT has ruled out success — a non-credential
// OAuth error (e.g. invalid_scope) can arrive with code 0 and is still a
// deterministic rejection. Back it with a typed APIError so callers never receive
// the ("", nil) "empty token, no error" pair.
return errs.NewAPIError(errs.SubtypeUnknown, "%s", msg).WithCode(code)
}
// DefaultAccountProvider resolves account from config.json via keychain.
type DefaultAccountProvider struct {
keychain func() keychain.KeychainAccess
profile string
}
func NewDefaultAccountProvider(kc func() keychain.KeychainAccess, profile string) *DefaultAccountProvider {
if kc == nil {
kc = keychain.Default
}
return &DefaultAccountProvider{keychain: kc, profile: profile}
}
func (p *DefaultAccountProvider) ResolveAccount(ctx context.Context) (*Account, error) {
// Load config once — used for both credentials and strict mode.
multi, err := core.LoadMultiAppConfig()
if err != nil {
return nil, core.NotConfiguredError()
}
cfg, err := core.ResolveConfigFromMulti(multi, p.keychain(), p.profile)
if err != nil {
return nil, err
}
cfg.SupportedIdentities = strictModeToIdentitySupport(multi, p.profile)
return AccountFromCliConfig(cfg), nil
}
// strictModeToIdentitySupport maps the config-level strict mode to
// the SupportedIdentities bitflag using an already-loaded MultiAppConfig.
func strictModeToIdentitySupport(multi *core.MultiAppConfig, profileOverride string) uint8 {
app := multi.CurrentAppConfig(profileOverride)
var mode core.StrictMode
if app != nil && app.StrictMode != nil {
mode = *app.StrictMode
} else {
mode = multi.StrictMode
}
switch mode {
case core.StrictModeBot:
return uint8(extcred.SupportsBot)
case core.StrictModeUser:
return uint8(extcred.SupportsUser)
default:
return 0
}
}
// DefaultTokenProvider resolves UAT/TAT using keychain + direct HTTP calls.
// No SDK/LarkClient dependency — eliminates circular dependency with Factory.
type DefaultTokenProvider struct {
defaultAcct *DefaultAccountProvider
httpClient func() (*http.Client, error)
errOut io.Writer
tatOnce sync.Once
tatResult *TokenResult
tatErr error
}
func NewDefaultTokenProvider(defaultAcct *DefaultAccountProvider, httpClient func() (*http.Client, error), errOut io.Writer) *DefaultTokenProvider {
return &DefaultTokenProvider{defaultAcct: defaultAcct, httpClient: httpClient, errOut: errOut}
}
func (p *DefaultTokenProvider) ResolveToken(ctx context.Context, req TokenSpec) (*TokenResult, error) {
switch req.Type {
case TokenTypeUAT:
return p.resolveUAT(ctx)
case TokenTypeTAT:
return p.resolveTAT(ctx)
default:
return nil, fmt.Errorf("unsupported token type: %s", req.Type)
}
}
// resolveUAT resolves a user access token. Not cached (unlike TAT) because UAT
// may be refreshed between calls and GetValidAccessToken handles its own caching.
func (p *DefaultTokenProvider) resolveUAT(ctx context.Context) (*TokenResult, error) {
acct, err := p.defaultAcct.ResolveAccount(ctx)
if err != nil {
return nil, err
}
httpClient, err := p.httpClient()
if err != nil {
return nil, err
}
token, err := auth.GetValidAccessToken(httpClient, auth.NewUATCallOptions(acct.ToCliConfig(), p.errOut))
if err != nil {
return nil, err
}
stored := auth.GetStoredToken(acct.AppID, acct.UserOpenId)
scopes := ""
if stored != nil {
scopes = stored.Scope
}
return &TokenResult{Token: token, Scopes: scopes}, nil
}
// resolveTAT resolves a tenant access token. The result is cached after the first
// call via sync.Once — only the context from the first call is used.
func (p *DefaultTokenProvider) resolveTAT(ctx context.Context) (*TokenResult, error) {
p.tatOnce.Do(func() {
p.tatResult, p.tatErr = p.doResolveTAT(ctx)
})
return p.tatResult, p.tatErr
}
func (p *DefaultTokenProvider) doResolveTAT(ctx context.Context) (*TokenResult, error) {
acct, err := p.defaultAcct.ResolveAccount(ctx)
if err != nil {
return nil, err
}
httpClient, err := p.httpClient()
if err != nil {
return nil, err
}
token, err := FetchTAT(ctx, httpClient, acct.Brand, acct.AppID, acct.AppSecret)
if err != nil {
return nil, err
}
return &TokenResult{Token: token}, nil
}
@@ -0,0 +1,94 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package credential
import (
"errors"
"testing"
"github.com/larksuite/cli/errs"
)
func TestDefaultTokenProvider_Dispatches(t *testing.T) {
// Just verify the type implements DefaultTokenResolver
var _ DefaultTokenResolver = &DefaultTokenProvider{}
}
func TestDefaultAccountProvider_Implements(t *testing.T) {
var _ DefaultAccountResolver = &DefaultAccountProvider{}
}
// TestClassifyTATResponseCode_InvalidClient_MapsToInvalidClient pins that the
// unified Token Endpoint's OAuth2 invalid_client error surfaces as
// CategoryConfig/InvalidClient — the configured app_id/app_secret cannot mint a
// tenant access token, the same actionable failure the legacy 10003/10014 codes
// produced. The numeric code is intentionally not asserted: the v3 endpoint may
// return invalid_client with no Lark code (code defaults to 0).
func TestClassifyTATResponseCode_InvalidClient_MapsToInvalidClient(t *testing.T) {
err := classifyTATResponseCode(0, "invalid_client", "client authentication failed", "feishu", "cli_app_x")
if err == nil {
t.Fatal("expected non-nil error for invalid_client")
}
var cfgErr *errs.ConfigError
if !errors.As(err, &cfgErr) {
t.Fatalf("expected *errs.ConfigError, got %T: %v", err, err)
}
if cfgErr.Category != errs.CategoryConfig {
t.Errorf("Category = %q, want %q", cfgErr.Category, errs.CategoryConfig)
}
if cfgErr.Subtype != errs.SubtypeInvalidClient {
t.Errorf("Subtype = %q, want %q", cfgErr.Subtype, errs.SubtypeInvalidClient)
}
if cfgErr.Hint == "" {
t.Error("Hint must be non-empty so the user gets a recovery action")
}
}
// TestClassifyTATResponseCode_UnauthorizedClient_MapsToInvalidClient pins that
// unauthorized_client is treated as the same credential failure as
// invalid_client.
func TestClassifyTATResponseCode_UnauthorizedClient_MapsToInvalidClient(t *testing.T) {
err := classifyTATResponseCode(0, "unauthorized_client", "client not authorized", "feishu", "cli_app_x")
var cfgErr *errs.ConfigError
if !errors.As(err, &cfgErr) {
t.Fatalf("expected *errs.ConfigError, got %T: %v", err, err)
}
if cfgErr.Subtype != errs.SubtypeInvalidClient {
t.Errorf("Subtype = %q, want %q", cfgErr.Subtype, errs.SubtypeInvalidClient)
}
}
// TestClassifyTATResponseCode_OtherErrorFallsThrough pins that OAuth errors
// outside the credential set fall through to the generic BuildAPIError fallback
// — still typed, but not a ConfigError. The mapping is narrow and intentional.
func TestClassifyTATResponseCode_OtherErrorFallsThrough(t *testing.T) {
err := classifyTATResponseCode(20068, "invalid_scope", "unauthorized scope", "feishu", "cli_app_x")
if err == nil {
t.Fatal("expected non-nil error for invalid_scope")
}
var cfgErr *errs.ConfigError
if errors.As(err, &cfgErr) {
t.Fatalf("invalid_scope must not be classified as ConfigError, got %T", err)
}
}
// TestClassifyTATResponseCode_CodeZeroOtherError_StillTyped pins the code-0
// backstop: a non-credential OAuth error (e.g. invalid_scope) that arrives with no
// numeric code (code 0) must still produce a non-nil typed error. BuildAPIError
// returns nil for code 0 (Feishu's success convention); without the backstop,
// FetchTAT would surface this deterministic rejection as ("", nil) — an empty token
// with no error.
func TestClassifyTATResponseCode_CodeZeroOtherError_StillTyped(t *testing.T) {
err := classifyTATResponseCode(0, "invalid_scope", "the requested scope is not granted", "feishu", "cli_app_x")
if err == nil {
t.Fatal("expected non-nil error for code-0 invalid_scope (must not be swallowed as success)")
}
if !errs.IsTyped(err) {
t.Fatalf("expected a typed errs.* error, got %T %v", err, err)
}
var cfgErr *errs.ConfigError
if errors.As(err, &cfgErr) {
t.Fatalf("code-0 invalid_scope must not be a ConfigError, got %T", err)
}
}
+160
View File
@@ -0,0 +1,160 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package credential_test
import (
"context"
"testing"
extcred "github.com/larksuite/cli/extension/credential"
envprovider "github.com/larksuite/cli/extension/credential/env"
"github.com/larksuite/cli/internal/core"
"github.com/larksuite/cli/internal/credential"
"github.com/larksuite/cli/internal/envvars"
"github.com/larksuite/cli/internal/i18n"
"github.com/larksuite/cli/internal/keychain"
)
type noopKC struct{}
func (n *noopKC) Get(service, account string) (string, error) { return "", nil }
func (n *noopKC) Set(service, account, value string) error { return nil }
func (n *noopKC) Remove(service, account string) error { return nil }
func TestFullChain_EnvWins(t *testing.T) {
t.Setenv(envvars.CliAppID, "env_app")
t.Setenv(envvars.CliAppSecret, "env_secret")
t.Setenv(envvars.CliUserAccessToken, "env_uat")
ep := &envprovider.Provider{}
cp := credential.NewCredentialProvider(
[]extcred.Provider{ep},
nil, nil, nil,
)
acct, err := cp.ResolveAccount(context.Background())
if err != nil {
t.Fatal(err)
}
if acct.AppID != "env_app" {
t.Errorf("expected env_app, got %s", acct.AppID)
}
result, err := cp.ResolveToken(context.Background(), credential.TokenSpec{
Type: credential.TokenTypeUAT, AppID: "env_app",
})
if err != nil {
t.Fatal(err)
}
if result.Token != "env_uat" {
t.Errorf("expected env_uat, got %s", result.Token)
}
}
func TestFullChain_Fallthrough(t *testing.T) {
// env provider returns nil (no env vars set), falls through to default token
ep := &envprovider.Provider{}
mock := &mockDefaultTokenProvider{token: "mock_tok", scopes: "drive:read"}
cp := credential.NewCredentialProvider(
[]extcred.Provider{ep},
nil, mock, nil,
)
result, err := cp.ResolveToken(context.Background(), credential.TokenSpec{
Type: credential.TokenTypeUAT, AppID: "app1",
})
if err != nil {
t.Fatal(err)
}
if result.Token != "mock_tok" || result.Scopes != "drive:read" {
t.Errorf("unexpected: %+v", result)
}
}
type mockDefaultTokenProvider struct {
token string
scopes string
}
func (m *mockDefaultTokenProvider) ResolveToken(ctx context.Context, req credential.TokenSpec) (*credential.TokenResult, error) {
return &credential.TokenResult{Token: m.token, Scopes: m.scopes}, nil
}
func TestFullChain_ConfigStrictMode(t *testing.T) {
t.Setenv(envvars.CliAppID, "")
t.Setenv(envvars.CliAppSecret, "")
dir := t.TempDir()
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", dir)
botMode := core.StrictModeBot
multi := &core.MultiAppConfig{
Apps: []core.AppConfig{{
AppId: "cfg_app",
AppSecret: core.PlainSecret("cfg_secret"),
Brand: core.BrandLark,
StrictMode: &botMode,
}},
}
if err := core.SaveMultiAppConfig(multi); err != nil {
t.Fatal(err)
}
ep := &envprovider.Provider{}
defaultAcct := credential.NewDefaultAccountProvider(func() keychain.KeychainAccess { return &noopKC{} }, "")
cp := credential.NewCredentialProvider(
[]extcred.Provider{ep},
defaultAcct, nil, nil,
)
acct, err := cp.ResolveAccount(context.Background())
if err != nil {
t.Fatal(err)
}
if acct.SupportedIdentities != uint8(extcred.SupportsBot) {
t.Errorf("expected SupportsBot (%d), got %d", extcred.SupportsBot, acct.SupportedIdentities)
}
}
// TestFullChain_LangSurvivesProductionPath exercises the exact data flow the
// production Factory uses (factory_default.go Phase 3): disk → multi config →
// DefaultAccountProvider.ResolveAccount → Account → ToCliConfig. If Lang gets
// dropped at the credential boundary (as it would when Account lacks the field),
// shortcuts/common/runner.go RuntimeContext.Lang() returns "" and downstream
// consumers (mail signature, etc.) silently fall back to defaults — defeating
// the whole point of persisting --lang.
func TestFullChain_LangSurvivesProductionPath(t *testing.T) {
t.Setenv(envvars.CliAppID, "")
t.Setenv(envvars.CliAppSecret, "")
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
multi := &core.MultiAppConfig{
Apps: []core.AppConfig{{
AppId: "cfg_app",
AppSecret: core.PlainSecret("cfg_secret"),
Brand: core.BrandFeishu,
Lang: i18n.LangJaJP,
}},
}
if err := core.SaveMultiAppConfig(multi); err != nil {
t.Fatalf("SaveMultiAppConfig: %v", err)
}
defaultAcct := credential.NewDefaultAccountProvider(func() keychain.KeychainAccess { return &noopKC{} }, "")
acct, err := defaultAcct.ResolveAccount(context.Background())
if err != nil {
t.Fatalf("ResolveAccount: %v", err)
}
if acct.Lang != i18n.LangJaJP {
t.Errorf("Account.Lang = %q, want %q (DefaultAccountProvider must propagate Lang from config)", acct.Lang, i18n.LangJaJP)
}
cfg := acct.ToCliConfig()
if cfg == nil {
t.Fatal("ToCliConfig() = nil")
}
if cfg.Lang != i18n.LangJaJP {
t.Errorf("CliConfig.Lang = %q, want %q (this is the value RuntimeContext.Lang() reads in production)", cfg.Lang, i18n.LangJaJP)
}
}
+102
View File
@@ -0,0 +1,102 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package credential
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/larksuite/cli/internal/core"
)
// FetchTAT performs a single HTTP POST to mint a tenant access token via the
// unified OAuth 2.0 Token Endpoint ({accounts}/oauth/v3/token) using the
// client_credentials grant with client_secret_post authentication. It does not
// read configuration or keychain, so callers that already hold plaintext
// credentials (e.g. the post-`config init` probe) can validate them without a
// second keychain round-trip.
//
// A deterministic client-side rejection (e.g. invalid_client) returns the
// canonical typed error from classifyTATResponseCode — the SAME classification
// doResolveTAT (and thus every token-resolving command) produces, so callers
// see one consistent envelope. Transport failures, unreadable/unparseable
// bodies, and transient server-side failures (5xx / server_error) are returned
// raw (untyped), leaving them ambiguous; a caller can use errs.IsTyped to tell a
// deterministic credential rejection apart from upstream/transport noise.
//
// The caller owns the context timeout.
func FetchTAT(ctx context.Context, httpClient *http.Client, brand core.LarkBrand, appID, appSecret string) (string, error) {
ep := core.ResolveEndpoints(brand)
endpoint := ep.Accounts + core.OAuthTokenV3Path
form := url.Values{}
form.Set("grant_type", "client_credentials")
form.Set("client_id", appID)
form.Set("client_secret", appSecret)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return "", fmt.Errorf("failed to read TAT response: %w", err)
}
var result struct {
Code int `json:"code"`
AccessToken string `json:"access_token"`
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
Msg string `json:"msg"`
}
if err := json.Unmarshal(body, &result); err != nil {
// An unparseable body is ambiguous (covers non-JSON error pages and
// truncated payloads); stay untyped so probe callers treat it as noise.
return "", fmt.Errorf("failed to parse TAT response (HTTP %d): %w", resp.StatusCode, err)
}
if result.Code == 0 && result.AccessToken != "" {
return result.AccessToken, nil
}
// Transient/server-side failures stay untyped so probe callers stay silent and
// retryers can back off; only deterministic client rejections are typed. Covers
// 5xx, HTTP 429 rate-limit, and the OAuth transient error strings (server_error,
// temporarily_unavailable, slow_down) — matching the legacy "non-2xx is noise"
// behavior so a rate-limited probe is not surfaced as a hard credential error.
if resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests ||
result.Error == "server_error" || result.Error == "temporarily_unavailable" ||
result.Error == "slow_down" {
return "", fmt.Errorf("TAT endpoint transient failure (HTTP %d, code=%d, error=%q): %s",
resp.StatusCode, result.Code, result.Error, result.ErrorDescription)
}
// A 2xx with neither token nor error is a malformed success — ambiguous, untyped.
if result.Code == 0 && result.Error == "" {
return "", fmt.Errorf("TAT response missing access_token (HTTP %d)", resp.StatusCode)
}
// Prefer the OAuth error_description; fall back to the legacy Lark `msg` so a
// gateway-level {code, msg} response (carrying no OAuth fields) still yields a
// non-empty typed message instead of a bare "API error: [code]".
desc := result.ErrorDescription
if desc == "" {
desc = result.Msg
}
return "", classifyTATResponseCode(result.Code, result.Error, desc, string(brand), appID)
}
+309
View File
@@ -0,0 +1,309 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package credential
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/core"
)
// stubRoundTripper lets us assert request shape and return canned responses.
type stubRoundTripper struct {
gotReq *http.Request
gotBody string
respCode int
respBody string
err error
}
func (s *stubRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
s.gotReq = req
if req.Body != nil {
b, _ := io.ReadAll(req.Body)
s.gotBody = string(b)
}
if s.err != nil {
return nil, s.err
}
return &http.Response{
StatusCode: s.respCode,
Body: io.NopCloser(strings.NewReader(s.respBody)),
Header: make(http.Header),
}, nil
}
func TestFetchTAT_Success(t *testing.T) {
rt := &stubRoundTripper{
respCode: 200,
respBody: `{"code":0,"access_token":"t-abc","token_type":"Bearer","expires_in":7200}`,
}
hc := &http.Client{Transport: rt}
token, err := FetchTAT(context.Background(), hc, core.BrandFeishu, "cli_app", "secret_x")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if token != "t-abc" {
t.Errorf("token = %q, want t-abc", token)
}
if rt.gotReq.URL.String() != "https://accounts.feishu.cn/oauth/v3/token" {
t.Errorf("url = %s", rt.gotReq.URL.String())
}
if ct := rt.gotReq.Header.Get("Content-Type"); ct != "application/x-www-form-urlencoded" {
t.Errorf("Content-Type = %q, want application/x-www-form-urlencoded", ct)
}
// client_secret_post: grant_type + client_id + client_secret in the form body.
for _, want := range []string{"grant_type=client_credentials", "client_id=cli_app", "client_secret=secret_x"} {
if !strings.Contains(rt.gotBody, want) {
t.Errorf("request body missing %q: %s", want, rt.gotBody)
}
}
}
// invalid_client (wrong app_id/app_secret on the client_credentials grant) is a
// deterministic client-side rejection that FetchTAT routes to
// classifyTATResponseCode as CategoryConfig / SubtypeInvalidClient — the same
// typed error doResolveTAT (and thus every token-resolving command) returns.
// The v3 endpoint reports it as HTTP 400 with the OAuth2 error body (wrong
// secret → code 20002, unknown app → code 20048).
func TestFetchTAT_InvalidClient_ConfigInvalidClient(t *testing.T) {
rt := &stubRoundTripper{respCode: 400, respBody: `{"error":"invalid_client","error_description":"The client secret is invalid.","code":20002}`}
hc := &http.Client{Transport: rt}
token, err := FetchTAT(context.Background(), hc, core.BrandFeishu, "cli_app", "secret_x")
if err == nil {
t.Fatal("expected error for invalid_client")
}
if token != "" {
t.Errorf("token = %q, want empty", token)
}
var cfgErr *errs.ConfigError
if !errors.As(err, &cfgErr) {
t.Fatalf("error not *errs.ConfigError: %T %v", err, err)
}
if cfgErr.Category != errs.CategoryConfig {
t.Errorf("Category = %q, want %q", cfgErr.Category, errs.CategoryConfig)
}
if cfgErr.Subtype != errs.SubtypeInvalidClient {
t.Errorf("Subtype = %q, want %q", cfgErr.Subtype, errs.SubtypeInvalidClient)
}
}
// Any other deterministic client-side OAuth error (e.g. invalid_scope) still
// yields a typed error (errs.IsTyped) via BuildAPIError — so a probe caller
// surfaces it rather than silently swallowing it — but is NOT classified as a
// credential (invalid_client) problem.
func TestFetchTAT_OtherClientError_Typed(t *testing.T) {
rt := &stubRoundTripper{respCode: 400, respBody: `{"code":20068,"error":"invalid_scope","error_description":"unauthorized scope"}`}
hc := &http.Client{Transport: rt}
_, err := FetchTAT(context.Background(), hc, core.BrandFeishu, "cli_app", "secret_x")
if err == nil {
t.Fatal("expected error for invalid_scope")
}
if !errs.IsTyped(err) {
t.Fatalf("expected a typed errs.* error, got %T %v", err, err)
}
var cfgErr *errs.ConfigError
if errors.As(err, &cfgErr) {
t.Errorf("invalid_scope must not be classified as ConfigError/InvalidClient, got %T", err)
}
}
// A deterministic OAuth error that arrives WITHOUT a numeric code (code defaults to
// 0) must still surface as a non-nil typed error — never the ("", nil) success pair.
// Guards the code-0 backstop in classifyTATResponseCode: BuildAPIError returns nil
// for code 0, which would otherwise swallow this rejection into an empty-token success.
func TestFetchTAT_OtherClientError_CodeZero_Typed(t *testing.T) {
rt := &stubRoundTripper{respCode: 400, respBody: `{"error":"invalid_scope","error_description":"the requested scope is not granted"}`}
hc := &http.Client{Transport: rt}
tok, err := FetchTAT(context.Background(), hc, core.BrandFeishu, "cli_app", "secret_x")
if err == nil {
t.Fatal("expected non-nil error for code-0 invalid_scope (must not return empty token + nil error)")
}
if tok != "" {
t.Errorf("token = %q, want empty", tok)
}
if !errs.IsTyped(err) {
t.Fatalf("expected a typed errs.* error, got %T %v", err, err)
}
}
// A gateway-style {code, msg} error (no OAuth error / error_description fields)
// must still surface its msg on the typed error, not degrade to a generic
// "API error: [code]". Guards the legacy-msg fallback in FetchTAT.
func TestFetchTAT_LarkStyleMsg_FallsBackOnTypedError(t *testing.T) {
rt := &stubRoundTripper{respCode: 400, respBody: `{"code":99999,"msg":"app ticket invalid"}`}
hc := &http.Client{Transport: rt}
_, err := FetchTAT(context.Background(), hc, core.BrandFeishu, "cli_app", "secret_x")
if err == nil {
t.Fatal("expected error for {code, msg} response")
}
if !errs.IsTyped(err) {
t.Fatalf("expected a typed errs.* error, got %T %v", err, err)
}
if !strings.Contains(err.Error(), "app ticket invalid") {
t.Errorf("typed error must carry the Lark msg, got: %v", err)
}
}
// Transient server-side failures (5xx / server_error) are NOT deterministic
// credential rejections — they must stay UNTYPED so a probe caller treats them
// as upstream noise and stays silent (and retryers can back off).
func TestFetchTAT_ServerError_Untyped(t *testing.T) {
rt := &stubRoundTripper{respCode: 500, respBody: `{"code":20050,"error":"server_error","error_description":"please retry"}`}
hc := &http.Client{Transport: rt}
_, err := FetchTAT(context.Background(), hc, core.BrandFeishu, "cli_app", "secret_x")
if err == nil {
t.Fatal("expected error for server_error")
}
if errs.IsTyped(err) {
t.Errorf("server_error must be UNTYPED (transient), got typed %T %v", err, err)
}
}
// Rate-limiting is transient, not a deterministic credential rejection — an HTTP
// 429 (even with a parseable OAuth body) and the OAuth slow_down error must both
// stay UNTYPED so a rate-limited probe stays silent and retryers can back off.
func TestFetchTAT_RateLimit_Untyped(t *testing.T) {
cases := []struct {
name string
code int
body string
}{
{"http 429", 429, `{"code":99991400,"error":"too_many_requests","error_description":"rate limit exceeded"}`},
{"oauth slow_down", 200, `{"error":"slow_down","error_description":"polling too fast"}`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rt := &stubRoundTripper{respCode: tc.code, respBody: tc.body}
hc := &http.Client{Transport: rt}
_, err := FetchTAT(context.Background(), hc, core.BrandFeishu, "cli_app", "secret_x")
if err == nil {
t.Fatal("expected error for rate-limit")
}
if errs.IsTyped(err) {
t.Errorf("rate-limit must be UNTYPED (transient), got typed %T %v", err, err)
}
})
}
}
// Non-2xx HTTP with a non-JSON body is ambiguous (not a structured OAuth
// rejection) — it must stay UNTYPED so a probe caller treats it as upstream
// noise and stays silent.
func TestFetchTAT_HTTPNon200_Untyped(t *testing.T) {
for _, code := range []int{401, 403, 500, 503} {
rt := &stubRoundTripper{respCode: code, respBody: `whatever`}
hc := &http.Client{Transport: rt}
_, err := FetchTAT(context.Background(), hc, core.BrandFeishu, "cli_app", "secret_x")
if err == nil {
t.Fatalf("HTTP %d: expected error", code)
}
if errs.IsTyped(err) {
t.Errorf("HTTP %d: must be UNTYPED (ambiguous), got typed %T %v", code, err, err)
}
}
}
func TestFetchTAT_TransportError_Untyped(t *testing.T) {
sentinel := errors.New("network down")
rt := &stubRoundTripper{err: sentinel}
hc := &http.Client{Transport: rt}
_, err := FetchTAT(context.Background(), hc, core.BrandFeishu, "cli_app", "secret_x")
if err == nil {
t.Fatal("expected error")
}
if errs.IsTyped(err) {
t.Errorf("transport error must be UNTYPED, got typed %T", err)
}
if !errors.Is(err, sentinel) {
t.Errorf("error chain missing sentinel: %v", err)
}
}
func TestFetchTAT_ParseError_Untyped(t *testing.T) {
rt := &stubRoundTripper{respCode: 200, respBody: `not json`}
hc := &http.Client{Transport: rt}
_, err := FetchTAT(context.Background(), hc, core.BrandFeishu, "cli_app", "secret_x")
if err == nil {
t.Fatal("expected parse error")
}
if errs.IsTyped(err) {
t.Errorf("parse error must be UNTYPED, got typed %T", err)
}
}
func TestFetchTAT_BrandRouting(t *testing.T) {
tests := []struct {
brand core.LarkBrand
wantURL string
}{
{core.BrandFeishu, "https://accounts.feishu.cn/oauth/v3/token"},
{core.BrandLark, "https://accounts.larksuite.com/oauth/v3/token"},
}
for _, tc := range tests {
t.Run(string(tc.brand), func(t *testing.T) {
rt := &stubRoundTripper{respCode: 200, respBody: `{"code":0,"access_token":"t","token_type":"Bearer"}`}
hc := &http.Client{Transport: rt}
if _, err := FetchTAT(context.Background(), hc, tc.brand, "a", "b"); err != nil {
t.Fatal(err)
}
if got := rt.gotReq.URL.String(); got != tc.wantURL {
t.Errorf("url = %s, want %s", got, tc.wantURL)
}
})
}
}
func TestFetchTAT_ContextCanceled(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done()
}))
defer srv.Close()
rt := &urlRewriteRT{base: srv.URL}
hc := &http.Client{Transport: rt}
ctx, cancel := context.WithCancel(context.Background())
cancel() // pre-canceled
_, err := FetchTAT(ctx, hc, core.BrandFeishu, "a", "b")
if err == nil {
t.Fatal("expected error for canceled context")
}
if errs.IsTyped(err) {
t.Errorf("canceled context must be UNTYPED, got typed %T", err)
}
if !errors.Is(err, context.Canceled) {
t.Errorf("error chain missing context.Canceled: %v", err)
}
}
// urlRewriteRT forwards requests to a fixed base URL (test server).
type urlRewriteRT struct{ base string }
func (r *urlRewriteRT) RoundTrip(req *http.Request) (*http.Response, error) {
newURL := r.base + req.URL.Path
req2, err := http.NewRequestWithContext(req.Context(), req.Method, newURL, req.Body)
if err != nil {
return nil, err
}
req2.Header = req.Header
return http.DefaultTransport.RoundTrip(req2)
}
+180
View File
@@ -0,0 +1,180 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package credential
import (
"context"
"fmt"
"strings"
extcred "github.com/larksuite/cli/extension/credential"
"github.com/larksuite/cli/internal/core"
"github.com/larksuite/cli/internal/i18n"
)
// Account is the credential-layer view of the active runtime account.
// It intentionally mirrors only the resolved fields needed by runtime auth
// and identity selection, without exposing core.CliConfig as a dependency.
type Account struct {
ProfileName string
AppID string
AppSecret string
Brand core.LarkBrand
DefaultAs core.Identity
UserOpenId string
UserName string
Lang i18n.Lang
SupportedIdentities uint8
}
const runtimePlaceholderAppSecret = "__LARKSUITE_CLI_TOKEN_ONLY__"
// HasRealAppSecret reports whether secret is an actual app secret rather than
// an empty/token-only marker or the internal runtime placeholder.
func HasRealAppSecret(secret string) bool {
return secret != "" && secret != runtimePlaceholderAppSecret
}
// RuntimeAppSecret returns the SDK-compatible app secret used at runtime.
// Token-only sources intentionally have no real secret; this helper injects a
// private placeholder so downstream SDK validation can proceed while callers
// still distinguish real secrets with HasRealAppSecret.
func RuntimeAppSecret(secret string) string {
if HasRealAppSecret(secret) {
return secret
}
return runtimePlaceholderAppSecret
}
func normalizeAccountAppSecret(secret string) string {
if HasRealAppSecret(secret) {
return secret
}
return extcred.NoAppSecret
}
// AccountFromCliConfig copies the resolved config view into a credential.Account.
func AccountFromCliConfig(cfg *core.CliConfig) *Account {
if cfg == nil {
return nil
}
return &Account{
ProfileName: cfg.ProfileName,
AppID: cfg.AppID,
AppSecret: normalizeAccountAppSecret(cfg.AppSecret),
Brand: cfg.Brand,
DefaultAs: cfg.DefaultAs,
UserOpenId: cfg.UserOpenId,
UserName: cfg.UserName,
Lang: cfg.Lang,
SupportedIdentities: cfg.SupportedIdentities,
}
}
// ToCliConfig copies the credential-layer account into the downstream config
// shape, normalizing the brand so runtime consumers never see raw casing.
func (a *Account) ToCliConfig() *core.CliConfig {
if a == nil {
return nil
}
return &core.CliConfig{
ProfileName: a.ProfileName,
AppID: a.AppID,
AppSecret: normalizeAccountAppSecret(a.AppSecret),
Brand: core.ParseBrand(string(a.Brand)),
DefaultAs: a.DefaultAs,
UserOpenId: a.UserOpenId,
UserName: a.UserName,
Lang: a.Lang,
SupportedIdentities: a.SupportedIdentities,
}
}
// AccountProvider resolves app credentials.
// Returns nil, nil to indicate "I don't handle this, try next provider".
type AccountProvider interface {
ResolveAccount(ctx context.Context) (*Account, error)
}
// TokenType distinguishes UAT from TAT.
// Uses string constants matching extension/credential.TokenType for zero-cost conversion.
type TokenType string
const (
TokenTypeUAT TokenType = "uat" // User Access Token
TokenTypeTAT TokenType = "tat" // Tenant Access Token
)
func (t TokenType) String() string { return string(t) }
// ParseTokenType converts a string to TokenType.
func ParseTokenType(s string) (TokenType, bool) {
switch strings.ToLower(s) {
case "uat":
return TokenTypeUAT, true
case "tat":
return TokenTypeTAT, true
default:
return "", false
}
}
// TokenSpec is the input to TokenProvider.ResolveToken.
type TokenSpec struct {
Type TokenType
AppID string // identifies which app (multi-account); not sensitive
}
// TokenResult is the output of TokenProvider.ResolveToken.
type TokenResult struct {
Token string
Scopes string // optional, space-separated; empty = skip scope pre-check
}
// IdentityHint is credential-layer guidance for resolving the effective identity.
type IdentityHint struct {
DefaultAs core.Identity
AutoAs core.Identity
}
// TokenUnavailableError reports that no usable token was available.
type TokenUnavailableError struct {
Source string
Type TokenType
}
func (e *TokenUnavailableError) Error() string {
if e.Source != "" {
return fmt.Sprintf("no %s available from credential source %q", e.Type, e.Source)
}
return fmt.Sprintf("no credential provider returned a token for %s", e.Type)
}
// MalformedTokenResultError reports that a source returned an invalid token payload.
type MalformedTokenResultError struct {
Source string
Type TokenType
Reason string
}
func (e *MalformedTokenResultError) Error() string {
return fmt.Sprintf("credential source %q returned malformed %s token: %s", e.Source, e.Type, e.Reason)
}
// TokenProvider resolves a runtime access token.
// Top-level resolvers should return a non-nil token or an error.
// Chain participants may use nil, nil internally to indicate "try next source".
type TokenProvider interface {
ResolveToken(ctx context.Context, req TokenSpec) (*TokenResult, error)
}
// NewTokenSpec returns a TokenSpec with the token type automatically
// selected based on identity: TAT for bot, UAT for user.
func NewTokenSpec(identity core.Identity, appID string) TokenSpec {
t := TokenTypeUAT
if identity.IsBot() {
t = TokenTypeTAT
}
return TokenSpec{Type: t, AppID: appID}
}
+140
View File
@@ -0,0 +1,140 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package credential
import (
"testing"
"github.com/larksuite/cli/internal/core"
"github.com/larksuite/cli/internal/i18n"
)
func TestTokenTypeString(t *testing.T) {
tests := []struct {
tt TokenType
want string
}{
{TokenTypeUAT, "uat"},
{TokenTypeTAT, "tat"},
{TokenType("custom"), "custom"},
}
for _, tc := range tests {
if got := tc.tt.String(); got != tc.want {
t.Errorf("TokenType(%q).String() = %q, want %q", tc.tt, got, tc.want)
}
}
}
func TestParseTokenType(t *testing.T) {
tests := []struct {
s string
want TokenType
ok bool
}{
{"uat", TokenTypeUAT, true},
{"tat", TokenTypeTAT, true},
{"UAT", TokenTypeUAT, true},
{"bad", "", false},
}
for _, tc := range tests {
got, ok := ParseTokenType(tc.s)
if ok != tc.ok || (ok && got != tc.want) {
t.Errorf("ParseTokenType(%q) = (%v, %v), want (%v, %v)", tc.s, got, ok, tc.want, tc.ok)
}
}
}
func TestAccountFromCliConfigAndBack_ReturnCopies(t *testing.T) {
cfg := &core.CliConfig{
ProfileName: "target",
AppID: "app-1",
AppSecret: "secret-1",
Brand: core.BrandLark,
DefaultAs: "user",
UserOpenId: "ou_123",
UserName: "alice",
Lang: i18n.LangJaJP,
SupportedIdentities: 3,
}
acct := AccountFromCliConfig(cfg)
if acct == nil {
t.Fatal("AccountFromCliConfig() = nil")
}
if acct.AppID != cfg.AppID || acct.ProfileName != cfg.ProfileName || acct.UserName != cfg.UserName {
t.Fatalf("AccountFromCliConfig() = %#v, want copied fields from %#v", acct, cfg)
}
if acct.Lang != cfg.Lang {
t.Fatalf("AccountFromCliConfig().Lang = %q, want %q", acct.Lang, cfg.Lang)
}
roundtrip := acct.ToCliConfig()
if roundtrip == nil {
t.Fatal("ToCliConfig() = nil")
}
if roundtrip.AppID != cfg.AppID || roundtrip.ProfileName != cfg.ProfileName || roundtrip.UserName != cfg.UserName {
t.Fatalf("ToCliConfig() = %#v, want copied fields from %#v", roundtrip, cfg)
}
if roundtrip.Lang != cfg.Lang {
t.Fatalf("ToCliConfig().Lang = %q, want %q (production Factory path reads Lang via this conversion)", roundtrip.Lang, cfg.Lang)
}
roundtrip.AppID = "mutated-cli"
acct.AppID = "mutated-account"
if cfg.AppID != "app-1" {
t.Fatalf("cfg.AppID = %q, want original value", cfg.AppID)
}
if roundtrip.AppID != "mutated-cli" {
t.Fatalf("roundtrip.AppID = %q, want mutated value", roundtrip.AppID)
}
if acct.AppID != "mutated-account" {
t.Fatalf("acct.AppID = %q, want mutated value", acct.AppID)
}
}
func TestAccountToCliConfig_TokenOnlySecretPreservesNoAppSecret(t *testing.T) {
acct := &Account{
ProfileName: "env",
AppID: "app-1",
AppSecret: "",
Brand: core.BrandFeishu,
}
cfg := acct.ToCliConfig()
if cfg == nil {
t.Fatal("ToCliConfig() = nil")
}
if cfg.AppSecret != "" {
t.Fatalf("AppSecret = %q, want empty string", cfg.AppSecret)
}
roundtrip := AccountFromCliConfig(cfg)
if roundtrip == nil {
t.Fatal("AccountFromCliConfig() = nil")
}
if roundtrip.AppSecret != "" {
t.Fatalf("roundtrip.AppSecret = %q, want empty string", roundtrip.AppSecret)
}
}
func TestRuntimeAppSecret_TokenOnlyUsesPlaceholder(t *testing.T) {
if got := RuntimeAppSecret(""); got == "" {
t.Fatal("RuntimeAppSecret(\"\") = empty, want non-empty placeholder")
}
if HasRealAppSecret(RuntimeAppSecret("")) {
t.Fatalf("HasRealAppSecret(RuntimeAppSecret(\"\")) = true, want false")
}
if got := RuntimeAppSecret("secret-1"); got != "secret-1" {
t.Fatalf("RuntimeAppSecret(real) = %q, want %q", got, "secret-1")
}
}
// The credential-layer ingress normalizes brand casing for all runtime consumers.
func TestToCliConfig_NormalizesBrand(t *testing.T) {
acct := &Account{AppID: "cli_x", Brand: " LARK "}
if got := acct.ToCliConfig().Brand; got != core.BrandLark {
t.Errorf("Brand = %q, want %q", got, core.BrandLark)
}
}
+56
View File
@@ -0,0 +1,56 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package credential
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/larksuite/cli/internal/core"
)
type userInfo struct {
OpenID string
Name string
}
// fetchUserInfo calls /open-apis/authen/v1/user_info with a UAT to get the user's identity.
func fetchUserInfo(ctx context.Context, httpClient *http.Client, brand core.LarkBrand, uat string) (*userInfo, error) {
ep := core.ResolveEndpoints(brand)
url := ep.Open + "/open-apis/authen/v1/user_info"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+uat)
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("user_info API returned HTTP %d", resp.StatusCode)
}
var result struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
OpenID string `json:"open_id"`
Name string `json:"name"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
if result.Code != 0 {
return nil, fmt.Errorf("user_info API error: [%d] %s", result.Code, result.Msg)
}
return &userInfo{OpenID: result.Data.OpenID, Name: result.Data.Name}, nil
}