mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 08:01:07 +00:00
Merge branch 'main' of https://github.com/chenyme/grok2api
This commit is contained in:
commit
fee63588d7
12 files changed
+675
-9
No files matched your search
@@ -0,0 +1,169 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
cliprovider "github.com/chenyme/grok2api/backend/internal/infra/provider/cli"
|
||||
consoleprovider "github.com/chenyme/grok2api/backend/internal/infra/provider/console"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
// consoleEntries 生成逗号拼接的 Console 账号对象字面量,供裸数组与 accounts 包装形态混合构造。
|
||||
func consoleEntries(start, count int, token func(index int) string) string {
|
||||
var builder strings.Builder
|
||||
for index := start; index < start+count; index++ {
|
||||
if index > start {
|
||||
builder.WriteByte(',')
|
||||
}
|
||||
fmt.Fprintf(&builder, `{"sso_token":%q}`, token(index))
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func distinctConsoleToken(index int) string { return fmt.Sprintf("token-%d", index) }
|
||||
|
||||
func newConsoleImportService(t *testing.T) (*Service, *relational.AccountRepository) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "import-limit.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := relational.NewAccountRepository(database)
|
||||
service := NewService(accounts, nil, nil, nil, provider.NewRegistry(consoleprovider.NewAdapter(consoleprovider.Config{}, nil, nil, nil)), cipher, nil)
|
||||
return service, accounts
|
||||
}
|
||||
|
||||
func countConsoleAccounts(t *testing.T, accounts *relational.AccountRepository) int64 {
|
||||
t.Helper()
|
||||
_, total, err := accounts.List(context.Background(), repository.AccountListQuery{
|
||||
Page: repository.PageQuery{Limit: 1}, Filter: repository.AccountListFilter{Provider: string(accountdomain.ProviderConsole)},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// 跨文件聚合边界:裸数组 + accounts 包装混排,合计恰好触及 maxCredentialImportAccounts 时允许导入。
|
||||
func TestImportConsoleDocumentsAcceptsExactlyAtAggregateLimitAcrossFiles(t *testing.T) {
|
||||
service, accounts := newConsoleImportService(t)
|
||||
half := maxCredentialImportAccounts / 2
|
||||
rest := maxCredentialImportAccounts - half
|
||||
arrayDoc := []byte("[" + consoleEntries(0, half, distinctConsoleToken) + "]")
|
||||
wrapperDoc := []byte(`{"provider":"grok_console","accounts":[` + consoleEntries(half, rest, distinctConsoleToken) + "]}")
|
||||
|
||||
result, err := service.ImportConsoleCredentialDocumentsWithProgress(context.Background(), [][]byte{arrayDoc, wrapperDoc}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Created != maxCredentialImportAccounts || countConsoleAccounts(t, accounts) != int64(maxCredentialImportAccounts) {
|
||||
t.Fatalf("result = %#v, stored = %d", result, countConsoleAccounts(t, accounts))
|
||||
}
|
||||
}
|
||||
|
||||
// 单文件均未超限、跨文件合计超限(max/2 + 其余+1)时:整批 ErrImportLimit,且不得有任何部分写入。
|
||||
func TestImportConsoleDocumentsRejectsAggregateOverflowWithoutPartialWrites(t *testing.T) {
|
||||
service, accounts := newConsoleImportService(t)
|
||||
half := maxCredentialImportAccounts / 2
|
||||
rest := maxCredentialImportAccounts - half + 1
|
||||
arrayDoc := []byte("[" + consoleEntries(0, half, distinctConsoleToken) + "]")
|
||||
wrapperDoc := []byte(`{"provider":"grok_console","accounts":[` + consoleEntries(half, rest, distinctConsoleToken) + "]}")
|
||||
|
||||
_, err := service.ImportConsoleCredentialDocumentsWithProgress(context.Background(), [][]byte{arrayDoc, wrapperDoc}, nil, nil)
|
||||
if !errors.Is(err, ErrImportLimit) {
|
||||
t.Fatalf("error = %v, want import limit", err)
|
||||
}
|
||||
if stored := countConsoleAccounts(t, accounts); stored != 0 {
|
||||
t.Fatalf("expected zero persisted accounts on aggregate overflow, got %d", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// Web/Console adapter 在单个文件内按 token 去重,service 再按 SourceKey
|
||||
// 对跨文件结果去重。本用例验证最终落库数量,不代表重复项可豁免解析总量限制。
|
||||
func TestImportConsoleDocumentsCountDeduplicatedTokens(t *testing.T) {
|
||||
service, accounts := newConsoleImportService(t)
|
||||
duplicateDoc := []byte(`[{"sso_token":"shared"},{"sso_token":"shared"}]`)
|
||||
sameAgainDoc := []byte(`[{"sso_token":"shared"},{"sso_token":"fresh"}]`)
|
||||
|
||||
result, err := service.ImportConsoleCredentialDocumentsWithProgress(context.Background(), [][]byte{duplicateDoc, sameAgainDoc}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Created != 2 || countConsoleAccounts(t, accounts) != 2 {
|
||||
t.Fatalf("result = %#v, stored = %d, want deduplicated count 2", result, countConsoleAccounts(t, accounts))
|
||||
}
|
||||
}
|
||||
|
||||
// 跨文件去重发生在 parsedAccounts 累计之后,因此第二个文件即使只重复已有
|
||||
// SourceKey,也必须计入解析总量限制,且超限时整批不得写入。
|
||||
func TestImportConsoleDocumentsCountsCrossFileDuplicatesTowardLimit(t *testing.T) {
|
||||
service, accounts := newConsoleImportService(t)
|
||||
fullDoc := []byte("[" + consoleEntries(0, maxCredentialImportAccounts, distinctConsoleToken) + "]")
|
||||
duplicateDoc := []byte(`[{"sso_token":"token-0"}]`)
|
||||
|
||||
_, err := service.ImportConsoleCredentialDocumentsWithProgress(context.Background(), [][]byte{fullDoc, duplicateDoc}, nil, nil)
|
||||
if !errors.Is(err, ErrImportLimit) {
|
||||
t.Fatalf("error = %v, want import limit", err)
|
||||
}
|
||||
if stored := countConsoleAccounts(t, accounts); stored != 0 {
|
||||
t.Fatalf("expected zero persisted accounts on aggregate overflow, got %d", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// SourceKey 去重不得豁免总量限制:service 层按解析条目数(去重前)累计。
|
||||
// Build adapter 不在解析阶段去重,同 refresh_token 派生相同 SourceKey,
|
||||
// 本用例覆盖单个文件内部的重复来源同样计入限制。
|
||||
func TestImportBuildDocumentsCountsDuplicateSourcesTowardLimit(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "import-limit-build.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := relational.NewAccountRepository(database)
|
||||
service := NewService(accounts, nil, nil, nil, provider.NewRegistry(cliprovider.NewAdapter(cliprovider.Config{}, cipher)), cipher, nil)
|
||||
|
||||
duplicateEntry := `{"refresh_token":"same-refresh"}`
|
||||
duplicateDoc := []byte("[" + strings.Repeat(duplicateEntry+",", maxCredentialImportAccounts-2) + duplicateEntry + "]")
|
||||
freshDoc := []byte(`[{"refresh_token":"fresh-1"},{"refresh_token":"fresh-2"}]`)
|
||||
|
||||
_, err = service.ImportCredentialDocumentsWithProgress(ctx, [][]byte{duplicateDoc, freshDoc}, nil, nil)
|
||||
if !errors.Is(err, ErrImportLimit) {
|
||||
t.Fatalf("error = %v, want import limit", err)
|
||||
}
|
||||
_, total, listErr := accounts.List(ctx, repository.AccountListQuery{
|
||||
Page: repository.PageQuery{Limit: 1}, Filter: repository.AccountListFilter{Provider: string(accountdomain.ProviderBuild)},
|
||||
})
|
||||
if listErr != nil {
|
||||
t.Fatal(listErr)
|
||||
}
|
||||
if total != 0 {
|
||||
t.Fatalf("expected zero persisted accounts, got %d", total)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
egressapp "github.com/chenyme/grok2api/backend/internal/application/egress"
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
@@ -1452,7 +1454,16 @@ func (s *Service) syncWebCredentialsToConsole(ctx context.Context, values []acco
|
||||
if err != nil {
|
||||
return ImportResult{}, fmt.Errorf("解密 Grok Web SSO: %w", err)
|
||||
}
|
||||
parsed, err := adapter.ParseImportedCredentials([]byte(token))
|
||||
// 非法 UTF-8 会被 json.Marshal 静默改写为 U+FFFD,显式拒绝优于静默改动(不应回显 token 内容)。
|
||||
if !utf8.ValidString(token) {
|
||||
return ImportResult{}, fmt.Errorf("解密 Grok Web SSO: 凭据不是合法 UTF-8")
|
||||
}
|
||||
// 内部调用固定走 JSON 对象路径,避免 plain token 被格式嗅探(如「[」JSON 保留前缀)误判。
|
||||
payload, err := json.Marshal(map[string]string{"sso_token": token})
|
||||
if err != nil {
|
||||
return ImportResult{}, fmt.Errorf("生成 Grok Console SSO 凭据: %w", err)
|
||||
}
|
||||
parsed, err := adapter.ParseImportedCredentials(payload)
|
||||
if err != nil {
|
||||
return ImportResult{}, fmt.Errorf("生成 Grok Console SSO 凭据: %w", err)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -12,6 +14,7 @@ import (
|
||||
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
consoleprovider "github.com/chenyme/grok2api/backend/internal/infra/provider/console"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/runtime/memory"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
@@ -159,6 +162,156 @@ func TestSyncWebAccountsToConsoleIsIdempotentAndPreservesBuildLink(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
// 内部同步必须以 {"sso_token": ...} 固定 JSON 形态传递 token:与 token 内容形态无关,
|
||||
// 不被导入解析器的格式嗅探(如「[」JSON 保留前缀)误判。
|
||||
// 本用例只验证服务侧载荷的字节级确定性;真实 Console adapter 的归一化语义见
|
||||
// TestSyncWebAccountsToConsoleRoundTripsThroughRealAdapter。
|
||||
func TestSyncWebAccountsToConsoleWrapsTokenAsDeterministicJSON(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "web-console-wrap.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 覆盖 JSON 转义与「[」保留前缀字符;不含 \r\n/NUL/sso= 前缀/分号——这些会在真实
|
||||
// Console adapter 的 sanitizeSSOToken 中被剥除,不属于可稳定往返的形态。
|
||||
weirdToken := "[bracketed-sso-\"quoted\" and spaces"
|
||||
encrypted, err := cipher.Encrypt(weirdToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := relational.NewAccountRepository(database)
|
||||
webAccount, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO,
|
||||
Name: "Grok Web weird", SourceKey: "sso:" + security.HashToken(weirdToken),
|
||||
EncryptedAccessToken: encrypted, Enabled: true, AuthStatus: accountdomain.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var captured []byte
|
||||
service := NewService(accounts, nil, nil, nil, provider.NewRegistry(consoleSSOCodecAdapter{lastPayload: &captured}), cipher, memory.NewLockStore())
|
||||
|
||||
result, err := service.SyncWebAccountsToConsoleWithProgress(ctx, []uint64{webAccount.ID}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Created != 1 || len(result.AccountIDs) != 1 {
|
||||
t.Fatalf("sync result = %#v", result)
|
||||
}
|
||||
// 载荷必须是 json.Marshal 的精确字节(单键对象、token 被正确转义),而非事后可还原就行。
|
||||
expectedPayload, err := json.Marshal(map[string]string{"sso_token": weirdToken})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(captured, expectedPayload) {
|
||||
t.Fatalf("payload = %s, want exact bytes %s", captured, expectedPayload)
|
||||
}
|
||||
}
|
||||
|
||||
// 服务的 JSON 封装与真实 Console adapter 的归一化链路必须端到端等价:
|
||||
// token 原样保存、SourceKey 与原纯文本路径一致(二次同步是更新而非新增)。
|
||||
func TestSyncWebAccountsToConsoleRoundTripsThroughRealAdapter(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "web-console-roundtrip.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
weirdToken := "[bracketed-sso-\"quoted\" and spaces"
|
||||
encrypted, err := cipher.Encrypt(weirdToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := relational.NewAccountRepository(database)
|
||||
webAccount, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO,
|
||||
Name: "Grok Web weird", SourceKey: "sso:" + security.HashToken(weirdToken),
|
||||
EncryptedAccessToken: encrypted, Enabled: true, AuthStatus: accountdomain.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := NewService(accounts, nil, nil, nil, provider.NewRegistry(consoleprovider.NewAdapter(consoleprovider.Config{}, nil, nil, nil)), cipher, memory.NewLockStore())
|
||||
|
||||
first, err := service.SyncWebAccountsToConsoleWithProgress(ctx, []uint64{webAccount.ID}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.Created != 1 || len(first.AccountIDs) != 1 {
|
||||
t.Fatalf("first sync = %#v", first)
|
||||
}
|
||||
consoleAccount, err := accounts.Get(ctx, first.AccountIDs[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decrypted, err := cipher.Decrypt(consoleAccount.EncryptedAccessToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 真实 adapter 的 SourceKey 必须与原纯文本路径一致("console-sso:"+hash(token)),否则存量账号会重复创建。
|
||||
if decrypted != weirdToken || consoleAccount.SourceKey != "console-sso:"+security.HashToken(weirdToken) {
|
||||
t.Fatalf("console account token=%q sourceKey=%q", decrypted, consoleAccount.SourceKey)
|
||||
}
|
||||
second, err := service.SyncWebAccountsToConsoleWithProgress(ctx, []uint64{webAccount.ID}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if second.Created != 0 || second.Updated != 1 || len(second.AccountIDs) != 1 || second.AccountIDs[0] != consoleAccount.ID {
|
||||
t.Fatalf("second sync = %#v", second)
|
||||
}
|
||||
}
|
||||
|
||||
// 非法 UTF-8 的解密结果不得被 json.Marshal 静默改写(U+FFFD 替换),应显式失败。
|
||||
func TestSyncWebAccountsToConsoleRejectsInvalidUTF8Token(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "web-console-utf8.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.Close() })
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
brokenToken := string([]byte{0xff, 0xfe, 'a'})
|
||||
encrypted, err := cipher.Encrypt(brokenToken)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts := relational.NewAccountRepository(database)
|
||||
webAccount, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{
|
||||
Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO,
|
||||
Name: "Grok Web broken", SourceKey: "sso:" + security.HashToken(brokenToken),
|
||||
EncryptedAccessToken: encrypted, Enabled: true, AuthStatus: accountdomain.AuthStatusActive,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := NewService(accounts, nil, nil, nil, provider.NewRegistry(consoleSSOCodecAdapter{}), cipher, memory.NewLockStore())
|
||||
|
||||
if _, err := service.SyncWebAccountsToConsoleWithProgress(ctx, []uint64{webAccount.ID}, nil, nil); err == nil || !strings.Contains(err.Error(), "UTF-8") {
|
||||
t.Fatalf("error = %v, want invalid UTF-8 rejection", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyncAllWebAccountsToConsoleProcessesMoreThanLegacyLimitInBatches(t *testing.T) {
|
||||
const totalAccounts = maxWebConsoleSyncAccounts + 1
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
@@ -228,7 +381,10 @@ func (r *webConsoleBatchRepository) UpsertManyByIdentity(_ context.Context, valu
|
||||
return results, nil
|
||||
}
|
||||
|
||||
type consoleSSOCodecAdapter struct{ parseCalls *atomic.Int64 }
|
||||
type consoleSSOCodecAdapter struct {
|
||||
parseCalls *atomic.Int64
|
||||
lastPayload *[]byte
|
||||
}
|
||||
|
||||
func (consoleSSOCodecAdapter) Provider() accountdomain.Provider { return accountdomain.ProviderConsole }
|
||||
|
||||
@@ -236,7 +392,20 @@ func (a consoleSSOCodecAdapter) ParseImportedCredentials(data []byte) ([]provide
|
||||
if a.parseCalls != nil {
|
||||
a.parseCalls.Add(1)
|
||||
}
|
||||
if a.lastPayload != nil {
|
||||
*a.lastPayload = append([]byte(nil), data...)
|
||||
}
|
||||
token := strings.TrimSpace(string(data))
|
||||
// 服务内部同步现在以 {"sso_token": ...} 封装 token;解开以与真实 console adapter 的 JSON 路径行为对齐。
|
||||
if strings.HasPrefix(token, "{") {
|
||||
var document struct {
|
||||
SSOToken string `json:"sso_token"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(token), &document); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
token = document.SSOToken
|
||||
}
|
||||
return []provider.CredentialSeed{{
|
||||
Provider: accountdomain.ProviderConsole, AuthType: accountdomain.AuthTypeSSO,
|
||||
Name: "Grok Console " + security.HashToken(token)[:8], SourceKey: "console-sso:" + security.HashToken(token), AccessToken: token,
|
||||
|
||||
@@ -280,6 +280,30 @@ func TestParseImportedCredentialsJSONSequence(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 批量注册工具导出的顶层裸数组形态。
|
||||
func TestParseImportedCredentialsBareArray(t *testing.T) {
|
||||
data := []byte(`[{"type":"xai","access_token":"access-1","refresh_token":"refresh-1","email":"user@example.com","user_id":"user-1","expires_at":"2026-08-01T00:00:00Z"}` +
|
||||
`,{"type":"xai","refresh_token":"refresh-2"}]`)
|
||||
values, err := parseImportedCredentials(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 2 || values[0].AccessToken != "access-1" || values[0].Email != "user@example.com" || values[0].UserID != "user-1" || values[0].ExpiresAt.IsZero() || values[1].RefreshToken != "refresh-2" {
|
||||
t.Fatalf("bare array import = %#v", values)
|
||||
}
|
||||
if values[0].SourceKey == values[1].SourceKey {
|
||||
t.Fatal("不同账号生成了相同来源标识")
|
||||
}
|
||||
}
|
||||
|
||||
// null 元素不在解码层拦截,归一化阶段须带账号序号报错。
|
||||
func TestParseImportedCredentialsBareArrayRejectsNullElement(t *testing.T) {
|
||||
_, err := parseImportedCredentials([]byte(`[{"refresh_token":"refresh-1"},null]`))
|
||||
if err == nil || !strings.Contains(err.Error(), "第 2 个账号") {
|
||||
t.Fatalf("error = %v, want indexed normalize error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseImportedCredentialsLooseAccountsDocument(t *testing.T) {
|
||||
data := []byte("{\n \"accounts\": [\n" +
|
||||
"{\"access_token\":\"access-1\",\"sub\":\"user-1\"}\n" +
|
||||
|
||||
@@ -416,6 +416,35 @@ func TestConsoleImportAcceptsJSONLines(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 「[」为 JSON 保留前缀:顶层裸数组必须走 JSON 解析,不得落入纯文本路径静默导入。
|
||||
func TestConsoleImportAcceptsBareArray(t *testing.T) {
|
||||
values, err := parseImportedCredentials([]byte(`[{"name":"console-a","sso_token":"token-a","cloudflare_cookies":"cf_clearance=abc"},{"sso_token":"token-b"}]`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 2 || values[0].Name != "console-a" || values[0].AccessToken != "token-a" || values[1].AccessToken != "token-b" {
|
||||
t.Fatalf("bare array values = %#v", values)
|
||||
}
|
||||
if values[0].CloudflareCookies != "cf_clearance=abc" {
|
||||
t.Fatalf("cloudflare cookies = %q", values[0].CloudflareCookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleImportBareArrayErrors(t *testing.T) {
|
||||
// 空数组:JSON 路径解析出 0 个账号,而不是被当成空文本导入。
|
||||
if _, err := parseImportedCredentials([]byte("[]")); err == nil || !strings.Contains(err.Error(), "没有 Grok Console 账号") {
|
||||
t.Fatalf("empty array error = %v", err)
|
||||
}
|
||||
// null 元素:归一化阶段带账号序号报错。
|
||||
if _, err := parseImportedCredentials([]byte(`[{"sso_token":"token-a"},null]`)); err == nil || !strings.Contains(err.Error(), "第 2 个账号缺少 sso_token") {
|
||||
t.Fatalf("null element error = %v", err)
|
||||
}
|
||||
// 非法 [ 开头输入:明确 JSON 报错,禁止静默当纯文本导入。
|
||||
if _, err := parseImportedCredentials([]byte("[not-json")); err == nil || !strings.Contains(err.Error(), "JSON") {
|
||||
t.Fatalf("malformed array error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleRetryAfterParsesCompoundDuration(t *testing.T) {
|
||||
if value := consoleRetryAfter([]byte(`Rate limit reached. Resets in: 1h 2m 3s`)); value != time.Hour+2*time.Minute+3*time.Second {
|
||||
t.Fatalf("retry after = %s", value)
|
||||
|
||||
@@ -36,7 +36,8 @@ func parseImportedCredentials(data []byte) ([]provider.CredentialSeed, error) {
|
||||
if trimmed == "" {
|
||||
return nil, fmt.Errorf("账号文件中没有 Grok Console 账号")
|
||||
}
|
||||
if !strings.HasPrefix(trimmed, "{") {
|
||||
// 「[」为 JSON 保留前缀:顶层裸数组走 JSON 解析,避免被当成纯文本 token 静默导入。
|
||||
if !strings.HasPrefix(trimmed, "{") && !strings.HasPrefix(trimmed, "[") {
|
||||
return parsePlainTextCredentials(trimmed)
|
||||
}
|
||||
entries, err := provider.DecodeCredentialJSONEntries[importEntry](data, string(account.ProviderConsole), maxImportAccounts)
|
||||
|
||||
@@ -11,8 +11,9 @@ import (
|
||||
|
||||
var utf8BOM = []byte{0xef, 0xbb, 0xbf}
|
||||
|
||||
// DecodeCredentialJSONEntries accepts a regular credential document or a
|
||||
// sequence of JSON objects, including one object per line.
|
||||
// DecodeCredentialJSONEntries accepts a regular credential document, a
|
||||
// top-level JSON array of credential objects, or a sequence of JSON objects,
|
||||
// including one object per line.
|
||||
func DecodeCredentialJSONEntries[T any](data []byte, expectedProvider string, limit int) ([]T, error) {
|
||||
data = bytes.TrimPrefix(data, utf8BOM)
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
@@ -28,6 +29,31 @@ func DecodeCredentialJSONEntries[T any](data []byte, expectedProvider string, li
|
||||
}
|
||||
|
||||
line := lineAtJSONOffset(data, start)
|
||||
|
||||
// 顶层裸数组:外部批量导出工具产出的常见形态。
|
||||
// 行号以数组起始行为准;元素错误额外给出序号定位。
|
||||
if trimmed := bytes.TrimSpace(raw); len(trimmed) > 0 && trimmed[0] == '[' {
|
||||
var elements []json.RawMessage
|
||||
if err := json.Unmarshal(raw, &elements); err != nil {
|
||||
return nil, fmt.Errorf("第 %d 行的账号数组 JSON 格式无效", line)
|
||||
}
|
||||
// 超限先于逐元素解析拦截,数组中混有非法元素时同样优先报告限额。
|
||||
if limit > 0 && len(elements) > limit-len(entries) {
|
||||
return nil, fmt.Errorf("%w: 单次最多导入 %d 个账号", ErrCredentialLimit, limit)
|
||||
}
|
||||
for index, element := range elements {
|
||||
// 结构预检:仅兼容对象与 null(null 归一为零值,交后续 normalize 报出带序号的明确错误)。
|
||||
if e := bytes.TrimSpace(element); len(e) == 0 || (e[0] != '{' && !bytes.Equal(e, []byte("null"))) {
|
||||
return nil, fmt.Errorf("第 %d 行账号数组的第 %d 个元素必须是 JSON 对象", line, index+1)
|
||||
}
|
||||
var value T
|
||||
if err := json.Unmarshal(element, &value); err != nil {
|
||||
return nil, fmt.Errorf("第 %d 行账号数组的第 %d 个元素内容无效", line, index+1)
|
||||
}
|
||||
entries = append(entries, value)
|
||||
}
|
||||
continue
|
||||
}
|
||||
var object map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &object); err != nil || object == nil {
|
||||
return nil, fmt.Errorf("第 %d 行必须是 JSON 对象", line)
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -10,6 +12,19 @@ type credentialJSONTestEntry struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// 计数型 entry:证明限额预检发生在任何元素解析之前(而非仅仅错误优先级靠前)。
|
||||
type countedJSONEntry struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
var countedJSONEntryUnmarshalCalls atomic.Int32
|
||||
|
||||
func (e *countedJSONEntry) UnmarshalJSON(data []byte) error {
|
||||
countedJSONEntryUnmarshalCalls.Add(1)
|
||||
type plain countedJSONEntry
|
||||
return json.Unmarshal(data, (*plain)(e))
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesAcceptsDocumentAndJSONLines(t *testing.T) {
|
||||
data := []byte("\xef\xbb\xbf{\n \"provider\": \"grok_test\",\n \"accounts\": [{\"token\":\"one\"}]\n}\r\n\r\n{\"token\":\"two\"}\r\n")
|
||||
values, err := DecodeCredentialJSONEntries[credentialJSONTestEntry](data, "grok_test", 10)
|
||||
@@ -32,7 +47,7 @@ func TestDecodeCredentialJSONEntriesReportsMalformedLineWithoutContent(t *testin
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesRejectsNonObjects(t *testing.T) {
|
||||
for _, data := range []string{`[{"token":"one"}]`, `"token"`, `null`} {
|
||||
for _, data := range []string{`"token"`, `null`} {
|
||||
if _, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte(data), "grok_test", 10); err == nil || !strings.Contains(err.Error(), "必须是 JSON 对象") {
|
||||
t.Fatalf("data = %s, error = %v", data, err)
|
||||
}
|
||||
@@ -53,3 +68,179 @@ func TestDecodeCredentialJSONEntriesRejectsWrongProvider(t *testing.T) {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesAcceptsBareArray(t *testing.T) {
|
||||
values, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte(`[{"token":"one"},{"token":"two"}]`), "grok_test", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 2 || values[0].Token != "one" || values[1].Token != "two" {
|
||||
t.Fatalf("values = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesAcceptsEmptyArray(t *testing.T) {
|
||||
values, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte("[]\n"), "grok_test", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 0 {
|
||||
t.Fatalf("values = %#v", values)
|
||||
}
|
||||
|
||||
values, err = DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte("[]\n{\"token\":\"one\"}"), "grok_test", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 1 || values[0].Token != "one" {
|
||||
t.Fatalf("values = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesMergesArrayAndJSONLinesInOrder(t *testing.T) {
|
||||
values, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte("[{\"token\":\"one\"}]\n{\"token\":\"two\"}\n"), "grok_test", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 2 || values[0].Token != "one" || values[1].Token != "two" {
|
||||
t.Fatalf("values = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesAcceptsConsecutiveArrays(t *testing.T) {
|
||||
values, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte("[{\"token\":\"one\"}] [{\"token\":\"two\"}]"), "grok_test", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 2 || values[0].Token != "one" || values[1].Token != "two" {
|
||||
t.Fatalf("values = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesAcceptsMultilineArrayAfterObject(t *testing.T) {
|
||||
data := []byte("{\"token\":\"zero\"}\n[\n {\"token\": \"one\"},\n {\"token\": \"two\"}\n]\n")
|
||||
values, err := DecodeCredentialJSONEntries[credentialJSONTestEntry](data, "grok_test", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 3 || values[0].Token != "zero" || values[1].Token != "one" || values[2].Token != "two" {
|
||||
t.Fatalf("values = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesAcceptsMultilineArrayWithBOMAndCRLF(t *testing.T) {
|
||||
data := []byte("\xef\xbb\xbf[\r\n {\"token\":\"one\"},\r\n {\"token\":\"two\"}\r\n]")
|
||||
values, err := DecodeCredentialJSONEntries[credentialJSONTestEntry](data, "grok_test", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 2 || values[0].Token != "one" || values[1].Token != "two" {
|
||||
t.Fatalf("values = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesRejectsArrayWithNonObjectElements(t *testing.T) {
|
||||
for _, data := range []string{`[42]`, `["token"]`, `[true]`, `[[{"token":"one"}]]`} {
|
||||
_, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte(data), "grok_test", 10)
|
||||
if err == nil || !strings.Contains(err.Error(), "第 1 个元素必须是 JSON 对象") {
|
||||
t.Fatalf("data = %s, error = %v", data, err)
|
||||
}
|
||||
}
|
||||
|
||||
_, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte(`[{"token":"one"}, 42]`), "grok_test", 10)
|
||||
if err == nil || !strings.Contains(err.Error(), "第 2 个元素必须是 JSON 对象") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesRejectsArrayElementWithInvalidContent(t *testing.T) {
|
||||
_, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte(`[{"token":123}]`), "grok_test", 10)
|
||||
if err == nil || !strings.Contains(err.Error(), "第 1 个元素内容无效") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesArrayErrorsDoNotLeakSecrets(t *testing.T) {
|
||||
// 哨兵位于合法前序元素:错误文本不得捎带它。
|
||||
_, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte(`[{"token":"s3cr3t-sentinel"}, 42]`), "grok_test", 10)
|
||||
if err == nil {
|
||||
t.Fatal("expected element error")
|
||||
}
|
||||
if strings.Contains(err.Error(), "s3cr3t-sentinel") {
|
||||
t.Fatalf("error leaks import contents: %v", err)
|
||||
}
|
||||
// 哨兵位于实际报错的元素内部(字段类型错误):错误文本同样不得捎带。
|
||||
_, err = DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte(`[{"token":123,"note":"s3cr3t-sentinel"}]`), "grok_test", 10)
|
||||
if err == nil || !strings.Contains(err.Error(), "内容无效") {
|
||||
t.Fatalf("error = %v, want invalid element content", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "s3cr3t-sentinel") {
|
||||
t.Fatalf("error leaks element contents: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesPassesNullElementsThrough(t *testing.T) {
|
||||
values, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte(`[null, {"token":"one"}]`), "grok_test", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 2 || values[0].Token != "" || values[1].Token != "one" {
|
||||
t.Fatalf("values = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesAllowsArrayExactlyAtLimit(t *testing.T) {
|
||||
values, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte(`[{"token":"one"},{"token":"two"}]`), "grok_test", 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 2 {
|
||||
t.Fatalf("values = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesLimitTakesPriorityOverBadElements(t *testing.T) {
|
||||
_, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte(`[{"token":"one"}, "bad-element"]`), "grok_test", 1)
|
||||
if !errors.Is(err, ErrCredentialLimit) {
|
||||
t.Fatalf("error = %v, want credential limit", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 限额预检必须发生在任何元素解析之前:超限数组中没有一个元素被 unmarshal。
|
||||
func TestDecodeCredentialJSONEntriesLimitSkipsElementParsingEntirely(t *testing.T) {
|
||||
countedJSONEntryUnmarshalCalls.Store(0)
|
||||
_, err := DecodeCredentialJSONEntries[countedJSONEntry]([]byte(`[{"token":"one"},{"token":"two"}]`), "grok_test", 1)
|
||||
if !errors.Is(err, ErrCredentialLimit) {
|
||||
t.Fatalf("error = %v, want credential limit", err)
|
||||
}
|
||||
if calls := countedJSONEntryUnmarshalCalls.Load(); calls != 0 {
|
||||
t.Fatalf("element unmarshal ran %d times despite limit pre-check", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// 行号契约:数组元素错误报「数组起始行 + 元素序号」,不追求元素实际物理行。
|
||||
func TestDecodeCredentialJSONEntriesReportsArrayStartLineWithElementIndex(t *testing.T) {
|
||||
data := []byte("{\"token\":\"zero\"}\n[\n {\"token\":\"one\"},\n 42\n]\n")
|
||||
_, err := DecodeCredentialJSONEntries[credentialJSONTestEntry](data, "grok_test", 10)
|
||||
if err == nil || !strings.Contains(err.Error(), "第 2 行账号数组的第 2 个元素") {
|
||||
t.Fatalf("error = %v, want array start line with element index", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesReportsMalformedLineAfterArray(t *testing.T) {
|
||||
_, err := DecodeCredentialJSONEntries[credentialJSONTestEntry]([]byte("[{\"token\":\"one\"}]\n\nnot-json\n"), "grok_test", 10)
|
||||
if err == nil || !strings.Contains(err.Error(), "第 3 行") {
|
||||
t.Fatalf("error = %v, want line number", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "not-json") {
|
||||
t.Fatalf("error exposes import contents: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCredentialJSONEntriesRejectsCommaLessMultilineArray(t *testing.T) {
|
||||
data := []byte("[\n{\"token\":\"one\"}\n{\"token\":\"two\"}\n]")
|
||||
_, err := DecodeCredentialJSONEntries[credentialJSONTestEntry](data, "grok_test", 10)
|
||||
if err == nil || !strings.Contains(err.Error(), "格式无效") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,8 @@ func (a *Adapter) ParseImportedCredentials(data []byte) ([]provider.CredentialSe
|
||||
if trimmed == "" {
|
||||
return nil, fmt.Errorf("账号文件中没有 Grok Web 账号")
|
||||
}
|
||||
if !strings.HasPrefix(trimmed, "{") {
|
||||
// 「[」为 JSON 保留前缀:顶层裸数组走 JSON 解析,避免被当成纯文本 token 静默导入。
|
||||
if !strings.HasPrefix(trimmed, "{") && !strings.HasPrefix(trimmed, "[") {
|
||||
return parsePlainTextCredentials(trimmed)
|
||||
}
|
||||
entries, err := provider.DecodeCredentialJSONEntries[importEntry](data, string(account.ProviderWeb), maxImportAccounts)
|
||||
|
||||
@@ -75,3 +75,42 @@ func TestWebCredentialJSONLinesRejectMalformedLine(t *testing.T) {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 「[」为 JSON 保留前缀:顶层裸数组必须走 JSON 解析,不得落入纯文本路径静默导入。
|
||||
func TestWebCredentialBareArrayUsesJSONPath(t *testing.T) {
|
||||
adapter := &Adapter{}
|
||||
values, err := adapter.ParseImportedCredentials([]byte(`[{"name":"primary","sso_token":"token-one","tier":"super","email":"one@example.com"},{"token":"token-two"}]`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 2 || values[0].Name != "primary" || values[0].AccessToken != "token-one" || values[0].WebTier != account.WebTierSuper || values[0].Email != "one@example.com" || values[1].AccessToken != "token-two" {
|
||||
t.Fatalf("bare array values = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebCredentialBareArrayWithBOM(t *testing.T) {
|
||||
adapter := &Adapter{}
|
||||
values, err := adapter.ParseImportedCredentials([]byte("\xef\xbb\xbf[{\"sso_token\":\"token-one\"}]"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(values) != 1 || values[0].AccessToken != "token-one" {
|
||||
t.Fatalf("bare array values = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebCredentialBareArrayErrors(t *testing.T) {
|
||||
adapter := &Adapter{}
|
||||
// 空数组:JSON 路径解析出 0 个账号,而不是被当成空文本导入。
|
||||
if _, err := adapter.ParseImportedCredentials([]byte("[]")); err == nil || !strings.Contains(err.Error(), "没有 Grok Web 账号") {
|
||||
t.Fatalf("empty array error = %v", err)
|
||||
}
|
||||
// null 元素:归一化阶段带账号序号报错。
|
||||
if _, err := adapter.ParseImportedCredentials([]byte(`[{"sso_token":"token-one"},null]`)); err == nil || !strings.Contains(err.Error(), "第 2 个账号缺少 sso_token") {
|
||||
t.Fatalf("null element error = %v", err)
|
||||
}
|
||||
// 非法 [ 开头输入:明确 JSON 报错,禁止静默当纯文本导入。
|
||||
if _, err := adapter.ParseImportedCredentials([]byte("[not-json")); err == nil || !strings.Contains(err.Error(), "JSON") {
|
||||
t.Fatalf("malformed array error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -31,7 +32,9 @@ func TestPrepareWritesPrivateScopedBootstrap(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
// Windows has no POSIX permission bits: the os.WriteFile mode argument
|
||||
// is ignored and files always report 0666-style permissions.
|
||||
if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("mode = %o", info.Mode().Perm())
|
||||
}
|
||||
var payload bootstrapFile
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -120,7 +121,9 @@ func TestUpdateQualityGuardConfigWritesPrivateAtomicFile(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0o600 {
|
||||
// Windows has no POSIX permission bits: the os.WriteFile mode argument
|
||||
// is ignored and files always report 0666-style permissions.
|
||||
if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("runtime config mode = %o", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user