Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions internal/api/test/usage_identity_siwc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package test

import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"

. "cpa-usage-keeper/internal/api"
"cpa-usage-keeper/internal/entities"
"cpa-usage-keeper/internal/repository"
"cpa-usage-keeper/internal/service"
)

func TestUsageIdentitySIWCNullableListPageAndDetail(t *testing.T) {
db := openAPITestDatabase(t)
ctx := context.Background()
now := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)
expiry := time.Date(2026, 11, 2, 3, 30, 0, 0, time.FixedZone("west", -7*3600))
rows := []entities.UsageIdentity{
{Identity: "known", Type: "codex", SIWCBindSupported: new(false), SIWCBound: new(true), UseSIWC: new(false), SIWCStatus: new("future"), SIWCExpiresAt: &expiry},
{Identity: "unknown", Type: "claude"},
}
if err := repository.ReplaceUsageIdentitiesForAuthType(ctx, db, rows, entities.UsageIdentityAuthTypeCredential, now); err != nil {
t.Fatal(err)
}
router := NewRouter(nil, nil, nil, nil, AuthConfig{}, nil, "", OptionalProviders{UsageIdentity: service.NewUsageIdentityService(db)})
read := func(path string) map[string]any {
t.Helper()
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil))
if response.Code != http.StatusOK {
t.Fatalf("%s status %d: %s", path, response.Code, response.Body.String())
}
var body map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
return body
}
assertKnown := func(row map[string]any) {
t.Helper()
if row["siwc_bind_supported"] != false || row["siwc_bound"] != true || row["use_siwc"] != false || row["siwc_status"] != "future" {
t.Fatalf("known values = %+v", row)
}
value, ok := row["siwc_expires_at"].(string)
if !ok {
t.Fatalf("missing expiry: %+v", row)
}
parsed, err := time.Parse(time.RFC3339Nano, value)
if err != nil || !parsed.Equal(expiry) {
t.Fatalf("expiry %q: %v", value, err)
}
}
assertUnknown := func(row map[string]any) {
t.Helper()
for _, field := range []string{"siwc_bind_supported", "siwc_bound", "use_siwc", "siwc_status", "siwc_expires_at"} {
if value, ok := row[field]; !ok || value != nil {
t.Fatalf("%s = %v, present %v", field, value, ok)
}
}
}
for _, path := range []string{"/api/v1/usage/identities", "/api/v1/usage/identities/page?auth_type=1"} {
listed := read(path)["identities"].([]any)
if len(listed) != 2 {
t.Fatalf("%s count = %d", path, len(listed))
}
for _, item := range listed {
row := item.(map[string]any)
switch row["identity"] {
case "known":
assertKnown(row)
assertKnown(read("/api/v1/usage/identities/" + row["id"].(string)))
case "unknown":
assertUnknown(row)
assertUnknown(read("/api/v1/usage/identities/" + row["id"].(string)))
default:
t.Fatalf("unexpected identity: %+v", row)
}
}
}
}
10 changes: 10 additions & 0 deletions internal/api/usage_identities.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ type usageIdentityResponse struct {
Priority *int `json:"priority,omitempty"`
Disabled bool `json:"disabled"`
Note *string `json:"note,omitempty"`
SIWCBindSupported *bool `json:"siwc_bind_supported"`
SIWCBound *bool `json:"siwc_bound"`
UseSIWC *bool `json:"use_siwc"`
SIWCStatus *string `json:"siwc_status"`
SIWCExpiresAt *time.Time `json:"siwc_expires_at"`
Subscription *quota.SubscriptionInfo `json:"subscription,omitempty"`
ActiveStart *time.Time `json:"active_start,omitempty"`
ActiveUntil *time.Time `json:"active_until,omitempty"`
Expand Down Expand Up @@ -335,6 +340,11 @@ func mapUsageIdentityResponseWithHealth(item entities.UsageIdentity, health *ser
Priority: item.Priority,
Disabled: disabled,
Note: item.Note,
SIWCBindSupported: item.SIWCBindSupported,
SIWCBound: item.SIWCBound,
UseSIWC: item.UseSIWC,
SIWCStatus: item.SIWCStatus,
SIWCExpiresAt: item.SIWCExpiresAt,
Subscription: quota.ResolveIdentitySubscription(item),
ActiveStart: item.ActiveStart,
ActiveUntil: item.ActiveUntil,
Expand Down
61 changes: 33 additions & 28 deletions internal/cpa/dto/credentials/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,34 +18,39 @@ type CredentialsResponse struct {

// Credential 保存凭证列表中单个凭证的原始响应字段。
type Credential struct {
AuthIndex string `json:"auth_index"`
Name string `json:"name"`
Path string `json:"path"`
Email string `json:"email"`
Type string `json:"type"`
Provider string `json:"provider"`
Label string `json:"label"`
Status string `json:"status"`
Source string `json:"source"`
Prefix string `json:"prefix"`
Priority *int `json:"priority"`
Disabled *bool `json:"disabled"`
Note *string `json:"note"`
Unavailable bool `json:"unavailable"`
RuntimeOnly bool `json:"runtime_only"`
Account string `json:"account,omitempty"`
ProjectID string `json:"project_id,omitempty"`
Sub *CredentialXAIUserIDValue `json:"sub,omitempty"`
Subject *CredentialXAIUserIDValue `json:"subject,omitempty"`
UserID *CredentialXAIUserIDValue `json:"user_id,omitempty"`
UserIDCamel *CredentialXAIUserIDValue `json:"userId,omitempty"`
Metadata *CredentialClaims `json:"metadata,omitempty"`
Attributes *CredentialClaims `json:"attributes,omitempty"`
OAuth *CredentialOAuth `json:"oauth,omitempty"`
User *CredentialUser `json:"user,omitempty"`
IDToken *CredentialIDToken `json:"id_token"`
xaiOAuthSet bool
xaiUserSet bool
AuthIndex string `json:"auth_index"`
Name string `json:"name"`
Path string `json:"path"`
Email string `json:"email"`
Type string `json:"type"`
Provider string `json:"provider"`
Label string `json:"label"`
Status string `json:"status"`
Source string `json:"source"`
Prefix string `json:"prefix"`
Priority *int `json:"priority"`
Disabled *bool `json:"disabled"`
Note *string `json:"note"`
SIWCBindSupported *bool `json:"siwc_bind_supported"`
SIWCBound *bool `json:"siwc_bound"`
UseSIWC *bool `json:"use_siwc"`
SIWCStatus *string `json:"siwc_status"`
SIWCExpiresAt *time.Time `json:"siwc_expires_at"`
Unavailable bool `json:"unavailable"`
RuntimeOnly bool `json:"runtime_only"`
Account string `json:"account,omitempty"`
ProjectID string `json:"project_id,omitempty"`
Sub *CredentialXAIUserIDValue `json:"sub,omitempty"`
Subject *CredentialXAIUserIDValue `json:"subject,omitempty"`
UserID *CredentialXAIUserIDValue `json:"user_id,omitempty"`
UserIDCamel *CredentialXAIUserIDValue `json:"userId,omitempty"`
Metadata *CredentialClaims `json:"metadata,omitempty"`
Attributes *CredentialClaims `json:"attributes,omitempty"`
OAuth *CredentialOAuth `json:"oauth,omitempty"`
User *CredentialUser `json:"user,omitempty"`
IDToken *CredentialIDToken `json:"id_token"`
xaiOAuthSet bool
xaiUserSet bool
}

// CredentialClaims 是 CPA credential 中可能携带身份 subject 的通用 claims DTO。
Expand Down
45 changes: 45 additions & 0 deletions internal/cpa/dto/credentials/test/siwc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package test

import (
"encoding/json"
"testing"
"time"

"cpa-usage-keeper/internal/cpa/dto/credentials"
)

func TestCredentialDecodesNullableSIWCFields(t *testing.T) {
tests := []struct {
name, input string
bind, bound, use *bool
status *string
expires *time.Time
}{
{"true and false", `{"siwc_bind_supported":true,"siwc_bound":false,"use_siwc":true,"siwc_status":"valid","siwc_expires_at":"2026-11-01T12:34:56+08:00"}`, new(true), new(false), new(true), new("valid"), new(time.Date(2026, 11, 1, 12, 34, 56, 0, time.FixedZone("", 8*3600)))},
{"opposite booleans", `{"siwc_bind_supported":false,"siwc_bound":true,"use_siwc":false,"siwc_status":"future"}`, new(false), new(true), new(false), new("future"), nil},
{"explicit null", `{"siwc_bind_supported":null,"siwc_bound":null,"use_siwc":null,"siwc_status":null,"siwc_expires_at":null}`, nil, nil, nil, nil, nil},
{"missing", `{}`, nil, nil, nil, nil, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var file credentials.Credential
if err := json.Unmarshal([]byte(tt.input), &file); err != nil {
t.Fatal(err)
}
if !equalSIWCValue(file.SIWCBindSupported, tt.bind) || !equalSIWCValue(file.SIWCBound, tt.bound) || !equalSIWCValue(file.UseSIWC, tt.use) || !equalSIWCValue(file.SIWCStatus, tt.status) {
t.Fatalf("decoded SIWC fields: %+v", file)
}
if (file.SIWCExpiresAt == nil) != (tt.expires == nil) || (file.SIWCExpiresAt != nil && !file.SIWCExpiresAt.Equal(*tt.expires)) {
t.Fatalf("decoded expiry = %v, want %v", file.SIWCExpiresAt, tt.expires)
}
})
}
var file credentials.Credential
if err := json.Unmarshal([]byte(`{"siwc_expires_at":"not-a-time"}`), &file); err == nil {
t.Fatal("malformed expiry must fail decoding like other credential timestamps")
}
}

func equalSIWCValue[T comparable](a, b *T) bool {
return a == nil && b == nil || a != nil && b != nil && *a == *b
}
6 changes: 6 additions & 0 deletions internal/entities/usage_identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ type UsageIdentity struct {
ProjectID *string
XAIUserID *string

SIWCBindSupported *bool `gorm:"column:siwc_bind_supported"`
SIWCBound *bool `gorm:"column:siwc_bound"`
UseSIWC *bool `gorm:"column:use_siwc"`
SIWCStatus *string `gorm:"column:siwc_status"`
SIWCExpiresAt *time.Time `gorm:"column:siwc_expires_at;serializer:storageTime"`

ActiveStart *time.Time `gorm:"serializer:storageTime"`
ActiveUntil *time.Time `gorm:"serializer:storageTime"`
PlanType *string
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package migration

import (
"fmt"

"cpa-usage-keeper/internal/entities"
"gorm.io/gorm"
)

func addUsageIdentitySIWCFieldsMigration(tx *gorm.DB) error {
if !tx.Migrator().HasTable(&entities.UsageIdentity{}) {
return nil
}
// 仅增 nullable 列,旧身份在首次成功同步前保留未知状态。
for _, field := range []string{"SIWCBindSupported", "SIWCBound", "UseSIWC", "SIWCStatus", "SIWCExpiresAt"} {
if tx.Migrator().HasColumn(&entities.UsageIdentity{}, field) {
continue
}
if err := tx.Migrator().AddColumn(&entities.UsageIdentity{}, field); err != nil {
return fmt.Errorf("add usage identity SIWC field %s: %w", field, err)
}
}
return nil
}
2 changes: 2 additions & 0 deletions internal/repository/migration/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ const (
migrationRecoverExecutionUsageEvents = "20261018_recover_execution_usage_events"
migrationAddUsageEventEffectiveServiceTier = "20261023_usage_event_effective_service_tier"
migrationAddPluginAPIKeySources = "20261028_plugin_api_key_sources"
migrationAddUsageIdentitySIWCFields = "20261029_usage_identity_siwc_fields"
)

type schemaMigration struct {
Expand Down Expand Up @@ -322,6 +323,7 @@ func orderedMigrations() []databaseMigration {
{version: "20261020_add_auth_session_oidc_identity", run: addAuthSessionOIDCIdentityMigration},
{version: migrationAddUsageEventEffectiveServiceTier, run: addUsageEventEffectiveServiceTierMigration},
{version: migrationAddPluginAPIKeySources, run: addPluginAPIKeySourcesMigration},
{version: migrationAddUsageIdentitySIWCFields, run: addUsageIdentitySIWCFieldsMigration},
}
}

Expand Down
1 change: 1 addition & 0 deletions internal/repository/migration/test/migration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ func TestOrderedMigrationsPreservesExecutionOrder(t *testing.T) {
"20261020_add_auth_session_oidc_identity",
"20261023_usage_event_effective_service_tier",
"20261028_plugin_api_key_sources",
"20261029_usage_identity_siwc_fields",
}
assertStringSlicesEqual(t, want, got)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package test

import (
"testing"

"cpa-usage-keeper/internal/repository/migration"
)

func TestUsageIdentitySIWCFieldsMigrationPreservesLegacyRows(t *testing.T) {
db := openUnmigratedTestDatabase(t)
for _, statement := range []string{
`CREATE TABLE usage_identities (id INTEGER PRIMARY KEY, identity TEXT, alias TEXT, total_requests INTEGER)`,
`INSERT INTO usage_identities VALUES (1, 'auth-1', 'local alias', 42)`,
`CREATE TRIGGER guard_identity BEFORE UPDATE ON usage_identities BEGIN SELECT RAISE(ABORT, 'legacy row rewrite'); END`,
} {
if err := db.Exec(statement).Error; err != nil {
t.Fatal(err)
}
}
const version = "20261029_usage_identity_siwc_fields"
runOnlyMigration(t, db, version)
var count int64
if err := db.Raw(`SELECT count(*) FROM usage_identities WHERE id = 1 AND identity = 'auth-1' AND alias = 'local alias' AND total_requests = 42 AND siwc_bind_supported IS NULL AND siwc_bound IS NULL AND use_siwc IS NULL AND siwc_status IS NULL AND siwc_expires_at IS NULL`).Scan(&count).Error; err != nil {
t.Fatal(err)
}
if count != 1 {
t.Fatal("legacy values changed or SIWC fields did not default to NULL")
}
if err := db.Exec("DELETE FROM schema_migrations WHERE version = ?", version).Error; err != nil {
t.Fatal(err)
}
if err := migration.Run(db); err != nil {
t.Fatalf("rerun migration: %v", err)
}
}
63 changes: 63 additions & 0 deletions internal/repository/test/usage_identities_siwc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package test

import (
"context"
"testing"
"time"

"cpa-usage-keeper/internal/entities"
"cpa-usage-keeper/internal/repository"
)

func TestUsageIdentitySIWCMetadataChangesIndependently(t *testing.T) {
ctx := context.Background()
now := time.Date(2026, 11, 1, 1, 30, 0, 0, time.UTC)
expiry := now.Add(10 * time.Hour)
for _, tc := range []struct {
name string
change func(*entities.UsageIdentity)
check func(entities.UsageIdentity) bool
}{
{"bind capability", func(row *entities.UsageIdentity) { row.SIWCBindSupported = new(false) }, func(row entities.UsageIdentity) bool { return row.SIWCBindSupported != nil && !*row.SIWCBindSupported }},
{"bound", func(row *entities.UsageIdentity) { row.SIWCBound = new(false) }, func(row entities.UsageIdentity) bool { return row.SIWCBound != nil && !*row.SIWCBound }},
{"use", func(row *entities.UsageIdentity) { row.UseSIWC = new(false) }, func(row entities.UsageIdentity) bool { return row.UseSIWC != nil && !*row.UseSIWC }},
{"status", func(row *entities.UsageIdentity) { row.SIWCStatus = new("future") }, func(row entities.UsageIdentity) bool { return row.SIWCStatus != nil && *row.SIWCStatus == "future" }},
{"expiry", func(row *entities.UsageIdentity) { row.SIWCExpiresAt = &expiry }, func(row entities.UsageIdentity) bool {
return row.SIWCExpiresAt != nil && row.SIWCExpiresAt.Equal(expiry)
}},
} {
t.Run(tc.name, func(t *testing.T) {
db := openTestDatabase(t)
row := entities.UsageIdentity{Identity: "auth", AuthTypeName: "oauth", Type: "codex"}
sync := func(at time.Time) {
t.Helper()
if err := repository.ReplaceUsageIdentitiesForAuthType(ctx, db, []entities.UsageIdentity{row}, entities.UsageIdentityAuthTypeCredential, at); err != nil {
t.Fatal(err)
}
}
read := func() entities.UsageIdentity {
t.Helper()
got, err := repository.GetActiveCredentialUsageIdentityByAuthIndex(ctx, db, "auth")
if err != nil {
t.Fatal(err)
}
return got
}
sync(now)
tc.change(&row)
sync(now.Add(time.Hour))
if got := read(); !tc.check(got) || !got.UpdatedAt.Equal(now.Add(time.Hour)) {
t.Fatalf("single-field update: %+v", got)
}
sync(now.Add(2 * time.Hour))
if got := read(); !got.UpdatedAt.Equal(now.Add(time.Hour)) {
t.Fatalf("unchanged field rewrote identity: %+v", got)
}
row = entities.UsageIdentity{Identity: "auth", AuthTypeName: "oauth", Type: "codex"}
sync(now.Add(3 * time.Hour))
if got := read(); got.SIWCBindSupported != nil || got.SIWCBound != nil || got.UseSIWC != nil || got.SIWCStatus != nil || got.SIWCExpiresAt != nil || !got.UpdatedAt.Equal(now.Add(3*time.Hour)) {
t.Fatalf("single-field clear: %+v", got)
}
})
}
}
Loading
Loading