feat(payment): 虎皮椒聚合支付 - 官方插件与跨平台可执行文件
新增 xunhupay 官方包,支付 RPC 与宿主只保留订单和验签边界;官方支付包同时带上各系统 provider,避免把 Linux ELF 当成本机入口。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
e5a5f0ccc8
commit
a23df0cb32
63 files changed
+2070
-128
No files matched your search
@@ -187,7 +187,7 @@ func (s *Service) AdminPaymentProviders(actor *model.User) ([]AdminPaymentProvid
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
manifest, _ := paymentManifestForProvider(descriptor.ID)
|
||||
manifest, _ := s.paymentManifestForProvider(descriptor.ID)
|
||||
view := AdminPaymentProviderView{PaymentProviderView: base, Values: map[string]string{}, SecretConfigured: map[string]bool{}, ConfigFields: manifest.Configuration.Fields}
|
||||
if config != nil {
|
||||
values, err := s.decryptPaymentConfig(config)
|
||||
@@ -220,11 +220,14 @@ func (s *Service) UpdatePaymentProviderConfig(actor *model.User, providerID stri
|
||||
return nil, BadAuthRequest("未知支付渠道")
|
||||
}
|
||||
descriptor := provider.Descriptor()
|
||||
manifest, ok := paymentManifestForProvider(descriptor.ID)
|
||||
manifest, ok := s.paymentManifestForProvider(descriptor.ID)
|
||||
if !ok {
|
||||
return nil, BadAuthRequest("支付插件清单不存在")
|
||||
}
|
||||
policy, ok := paymentExpiryPolicy(manifest, descriptor.ID)
|
||||
if !ok {
|
||||
return nil, BadAuthRequest("支付插件清单不存在")
|
||||
}
|
||||
policy := manifest.Contributes.PaymentProviders[0].ExpiryPolicy
|
||||
if request.CloseAfterMinutes < policy.MinMinutes || request.CloseAfterMinutes > policy.MaxMinutes {
|
||||
return nil, BadAuthRequest(fmt.Sprintf("未支付关闭时间必须为 %d-%d 分钟", policy.MinMinutes, policy.MaxMinutes))
|
||||
}
|
||||
@@ -318,8 +321,10 @@ func (s *Service) UpdatePaymentProviderConfig(actor *model.User, providerID stri
|
||||
|
||||
func (s *Service) paymentProviderView(descriptor payment.Descriptor) (PaymentProviderView, *model.PaymentProviderConfig, error) {
|
||||
view := PaymentProviderView{ID: descriptor.ID, PluginID: descriptor.PluginID, Name: descriptor.Name, Icon: descriptor.Icon, CheckoutMode: descriptor.CheckoutMode}
|
||||
if manifest, ok := paymentManifestForProvider(descriptor.ID); ok && len(manifest.Contributes.PaymentProviders) > 0 {
|
||||
view.CloseAfterMinutes = manifest.Contributes.PaymentProviders[0].ExpiryPolicy.DefaultMinutes
|
||||
if manifest, ok := s.paymentManifestForProvider(descriptor.ID); ok {
|
||||
if policy, found := paymentExpiryPolicy(manifest, descriptor.ID); found {
|
||||
view.CloseAfterMinutes = policy.DefaultMinutes
|
||||
}
|
||||
}
|
||||
state, err := s.pluginStateForUser(nil, descriptor.PluginID, s.Plugins())
|
||||
if err == nil {
|
||||
@@ -339,7 +344,24 @@ func (s *Service) paymentProviderView(descriptor payment.Descriptor) (PaymentPro
|
||||
return view, config, nil
|
||||
}
|
||||
|
||||
func paymentManifestForProvider(providerID string) (protocol.Manifest, bool) {
|
||||
func (s *Service) paymentManifestForProvider(providerID string) (protocol.Manifest, bool) {
|
||||
providerID = strings.TrimSpace(providerID)
|
||||
if providerID == "" {
|
||||
return protocol.Manifest{}, false
|
||||
}
|
||||
if s != nil {
|
||||
for _, plugin := range s.Plugins() {
|
||||
for _, contribution := range plugin.Manifest.Contributes.PaymentProviders {
|
||||
if contribution.ID == providerID {
|
||||
return protocolManifestFromPluginView(plugin), true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return bundledPaymentManifestForProvider(providerID)
|
||||
}
|
||||
|
||||
func bundledPaymentManifestForProvider(providerID string) (protocol.Manifest, bool) {
|
||||
for _, manifest := range bundledPaymentPluginManifests() {
|
||||
for _, contribution := range manifest.Contributes.PaymentProviders {
|
||||
if contribution.ID == providerID {
|
||||
@@ -350,6 +372,34 @@ func paymentManifestForProvider(providerID string) (protocol.Manifest, bool) {
|
||||
return protocol.Manifest{}, false
|
||||
}
|
||||
|
||||
func protocolManifestFromPluginView(plugin PluginView) protocol.Manifest {
|
||||
return protocol.Manifest{
|
||||
APIVersion: plugin.Manifest.APIVersion,
|
||||
Metadata: protocol.Metadata{
|
||||
ID: plugin.Manifest.ID, Version: plugin.Manifest.Version, Name: plugin.Manifest.Name,
|
||||
Vendor: plugin.Manifest.Author, Description: plugin.Manifest.Description,
|
||||
Documentation: plugin.Manifest.Documentation,
|
||||
},
|
||||
Surfaces: plugin.Manifest.Surfaces,
|
||||
Runtime: plugin.Manifest.Runtime,
|
||||
Permissions: plugin.Manifest.Permissions,
|
||||
Configuration: plugin.Manifest.Configuration,
|
||||
Contributes: plugin.Manifest.Contributes,
|
||||
}
|
||||
}
|
||||
|
||||
func paymentExpiryPolicy(manifest protocol.Manifest, providerID string) (protocol.ManifestPaymentExpiryPolicy, bool) {
|
||||
for _, contribution := range manifest.Contributes.PaymentProviders {
|
||||
if contribution.ID == providerID {
|
||||
return contribution.ExpiryPolicy, true
|
||||
}
|
||||
}
|
||||
if len(manifest.Contributes.PaymentProviders) == 1 {
|
||||
return manifest.Contributes.PaymentProviders[0].ExpiryPolicy, true
|
||||
}
|
||||
return protocol.ManifestPaymentExpiryPolicy{}, false
|
||||
}
|
||||
|
||||
func (s *Service) decryptPaymentConfig(config *model.PaymentProviderConfig) (payment.Config, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New("支付渠道配置不存在")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"infinite-canvas/backend/internal/payment"
|
||||
@@ -59,7 +60,7 @@ func TestSystemPaymentPluginsRegisterRPCProviders(t *testing.T) {
|
||||
if registry == nil {
|
||||
t.Fatal("payment registry is nil")
|
||||
}
|
||||
for _, providerID := range []string{PaymentProviderAlipay, PaymentProviderWeChat} {
|
||||
for _, providerID := range []string{PaymentProviderAlipay, PaymentProviderWeChat, "xunhupay-aggregate"} {
|
||||
provider, ok := registry.Get(providerID)
|
||||
if !ok {
|
||||
t.Fatalf("payment provider %q is missing", providerID)
|
||||
@@ -70,6 +71,14 @@ func TestSystemPaymentPluginsRegisterRPCProviders(t *testing.T) {
|
||||
if provider.Descriptor().PluginID == "" || provider.Descriptor().PluginVersion == "" {
|
||||
t.Fatalf("payment provider %q is missing plugin identity: %#v", providerID, provider.Descriptor())
|
||||
}
|
||||
err := provider.ValidateConfig(nil)
|
||||
var providerErr *payment.ProviderError
|
||||
if !errors.As(err, &providerErr) {
|
||||
t.Fatalf("provider %q ValidateConfig() = %T %v, want ProviderError", providerID, err, err)
|
||||
}
|
||||
if providerErr.Code == "plugin_executable_missing" || providerErr.Code == "plugin_exec_format_error" || providerErr.Code == "plugin_start_failed" {
|
||||
t.Fatalf("provider %q failed to start: %#v cause=%v", providerID, providerErr, providerErr.Cause)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +92,7 @@ func TestPaymentRegistryFailsClosedWhenOfficialPackagesAreMissing(t *testing.T)
|
||||
if registry == nil {
|
||||
t.Fatal("payment registry is nil")
|
||||
}
|
||||
for _, providerID := range []string{PaymentProviderAlipay, PaymentProviderWeChat} {
|
||||
for _, providerID := range []string{PaymentProviderAlipay, PaymentProviderWeChat, "xunhupay-aggregate"} {
|
||||
if _, ok := registry.Get(providerID); ok {
|
||||
t.Fatalf("payment provider %q unexpectedly came from host fallback", providerID)
|
||||
}
|
||||
@@ -107,3 +116,38 @@ func TestTopupProductCreditAmountStaysWithinSafeLimit(t *testing.T) {
|
||||
t.Fatalf("maximum safe top-up credits: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestXunHuPayOfficialPackageIsPaymentPlugin(t *testing.T) {
|
||||
center, err := newPluginRuntime(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var plugin PluginView
|
||||
for _, item := range center.list() {
|
||||
if item.Manifest.ID == "official-payment-xunhupay" {
|
||||
plugin = item
|
||||
plugin.Management = pluginManagementFromView(item)
|
||||
break
|
||||
}
|
||||
}
|
||||
if plugin.Manifest.ID == "" {
|
||||
t.Fatal("official-payment-xunhupay is missing")
|
||||
}
|
||||
if plugin.Management.Kind != PluginKindPayment || plugin.Source != PluginOriginOfficial {
|
||||
t.Fatalf("xunhupay plugin = %#v", plugin)
|
||||
}
|
||||
if len(plugin.Manifest.Contributes.PaymentProviders) != 1 || plugin.Manifest.Contributes.PaymentProviders[0].ID != "xunhupay-aggregate" {
|
||||
t.Fatalf("xunhupay contributions = %#v", plugin.Manifest.Contributes.PaymentProviders)
|
||||
}
|
||||
registry := center.paymentRegistrySnapshot()
|
||||
if registry == nil {
|
||||
t.Fatal("payment registry is nil")
|
||||
}
|
||||
provider, ok := registry.Get("xunhupay-aggregate")
|
||||
if !ok {
|
||||
t.Fatal("xunhupay-aggregate provider is missing")
|
||||
}
|
||||
if _, ok := provider.(*payment.RPCProvider); !ok {
|
||||
t.Fatalf("xunhupay provider type = %T", provider)
|
||||
}
|
||||
}
|
||||
@@ -139,12 +139,47 @@ func TestPaymentRuntimeRejectsInvalidDigest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaymentRuntimeReadyAcceptsTaggedBackend(t *testing.T) {
|
||||
packageData := paymentRuntimePackageFiles(t, map[string][]byte{"backend/provider-darwin-arm64": []byte("darwin-provider")})
|
||||
pkg, err := protocol.ParsePluginPackage(packageData)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
packageDir := t.TempDir()
|
||||
runtimeDir, err := materializePaymentBackend(packageDir, pluginHash(packageData), pkg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(runtimeDir, "backend", "provider")); !os.IsNotExist(err) {
|
||||
t.Fatalf("canonical provider should be absent: %v", err)
|
||||
}
|
||||
actual, err := os.ReadFile(filepath.Join(runtimeDir, "backend", "provider-darwin-arm64"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(actual, []byte("darwin-provider")) {
|
||||
t.Fatalf("tagged runtime provider = %q", actual)
|
||||
}
|
||||
if !paymentRuntimeReady(runtimeDir, pluginHash(packageData), "backend/provider") {
|
||||
t.Fatal("tagged payment runtime was not marked ready")
|
||||
}
|
||||
}
|
||||
|
||||
func paymentRuntimePackage(t *testing.T, provider []byte) []byte {
|
||||
t.Helper()
|
||||
return paymentRuntimePackageFiles(t, map[string][]byte{"backend/provider": provider})
|
||||
}
|
||||
|
||||
func paymentRuntimePackageFiles(t *testing.T, files map[string][]byte) []byte {
|
||||
t.Helper()
|
||||
manifest := []byte(`{"apiVersion":"yingce.plugin/v1","id":"test-payment-runtime","version":"1.0.0","name":"Test Payment Runtime","author":"Test","enabled":true,"runtime":{"backend":"rpc","backendEntry":"backend/provider"},"contributes":{"paymentProviders":[{"id":"test-payment","label":"Test Payment","icon":"brand:test","checkoutMode":"redirect","expiryPolicy":{"defaultMinutes":30,"minMinutes":5,"maxMinutes":1440}}]}}`)
|
||||
payload := map[string][]byte{"manifest.json": manifest}
|
||||
for name, content := range files {
|
||||
payload[name] = content
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
writer := zip.NewWriter(&buffer)
|
||||
for name, content := range map[string][]byte{"manifest.json": manifest, "backend/provider": provider} {
|
||||
for name, content := range payload {
|
||||
file, err := writer.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -118,6 +118,21 @@ func pluginManagement(pluginID string, source string) PluginManagementView {
|
||||
}
|
||||
}
|
||||
|
||||
func pluginManagementFromView(plugin PluginView) PluginManagementView {
|
||||
policy := pluginManagement(plugin.Manifest.ID, plugin.Source)
|
||||
if policy.Kind != PluginKindProtocol || len(plugin.Manifest.Contributes.PaymentProviders) == 0 {
|
||||
return policy
|
||||
}
|
||||
origin := strings.TrimSpace(plugin.Source)
|
||||
if origin == "" {
|
||||
origin = PluginOriginOfficial
|
||||
}
|
||||
return PluginManagementView{
|
||||
Origin: origin, Kind: PluginKindPayment,
|
||||
ActivationScope: PluginScopeSystem, ConfigurationScope: PluginConfigurationSystem,
|
||||
}
|
||||
}
|
||||
|
||||
func knownPluginIDs(items []PluginView) []string {
|
||||
seen := make(map[string]struct{}, len(items)+len(officialApplicationPolicies)+len(systemPaymentPolicies))
|
||||
ids := make([]string, 0, len(items)+len(officialApplicationPolicies)+len(systemPaymentPolicies))
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
"infinite-canvas/backend/internal/protocol"
|
||||
"infinite-canvas/backend/internal/repository"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
@@ -70,6 +71,22 @@ func TestUploadedManifestCannotClaimUserActivationScope(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaymentContributionInfersPaymentManagementKind(t *testing.T) {
|
||||
plugin := PluginView{
|
||||
Source: PluginOriginOfficial,
|
||||
Manifest: PluginManifestView{
|
||||
ID: "official-payment-xunhupay",
|
||||
Contributes: protocol.ManifestContributions{PaymentProviders: []protocol.ManifestPaymentProvider{{
|
||||
ID: "xunhupay-aggregate", Label: "虎皮椒聚合支付", Icon: "assets/icon.svg", CheckoutMode: "qr_code",
|
||||
}}},
|
||||
},
|
||||
}
|
||||
policy := pluginManagementFromView(plugin)
|
||||
if policy.Kind != PluginKindPayment || policy.Origin != PluginOriginOfficial || policy.ActivationScope != PluginScopeSystem {
|
||||
t.Fatalf("inferred payment policy = %#v", policy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtCritiqueIsUserToggleableApplication(t *testing.T) {
|
||||
policy := pluginManagement(PluginAIArtCritique, "bundled")
|
||||
if policy.Origin != PluginOriginOfficial || policy.Kind != PluginKindApplication || policy.ActivationScope != PluginScopeUser || policy.ConfigurationScope != PluginConfigurationNone {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
@@ -91,6 +92,15 @@ type pluginRegistryRecord struct {
|
||||
}
|
||||
|
||||
func newPluginRuntime(dataDir string) (*pluginRuntime, error) {
|
||||
dataDir = strings.TrimSpace(dataDir)
|
||||
if dataDir == "" {
|
||||
return nil, errors.New("plugin data directory is empty")
|
||||
}
|
||||
var err error
|
||||
dataDir, err = filepath.Abs(dataDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("plugin data directory is invalid: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(dataDir, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("create plugin registry directory: %w", err)
|
||||
}
|
||||
@@ -519,8 +529,24 @@ func paymentRuntimeReady(root, digest, backendEntry string) bool {
|
||||
if err != nil || strings.TrimSpace(string(ready)) != digest {
|
||||
return false
|
||||
}
|
||||
entry, err := os.Stat(filepath.Join(root, filepath.FromSlash(backendEntry)))
|
||||
return err == nil && !entry.IsDir()
|
||||
return protocol.HasAnyPaymentRPCBackend(backendEntry, paymentRuntimeBackendFiles(root))
|
||||
}
|
||||
|
||||
func paymentRuntimeBackendFiles(root string) map[string][]byte {
|
||||
files := map[string][]byte{}
|
||||
backendRoot := filepath.Join(root, "backend")
|
||||
_ = filepath.WalkDir(backendRoot, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil || entry.IsDir() {
|
||||
return err
|
||||
}
|
||||
rel, relErr := filepath.Rel(root, path)
|
||||
if relErr != nil {
|
||||
return nil
|
||||
}
|
||||
files[filepath.ToSlash(rel)] = []byte{1}
|
||||
return nil
|
||||
})
|
||||
return files
|
||||
}
|
||||
|
||||
func (c *pluginRuntime) list() []PluginView {
|
||||
|
||||
@@ -137,7 +137,7 @@ func (s *Service) Plugins() []PluginView {
|
||||
}
|
||||
items := s.pluginRuntime.list()
|
||||
for index := range items {
|
||||
items[index].Management = pluginManagement(items[index].Manifest.ID, items[index].Source)
|
||||
items[index].Management = pluginManagementFromView(items[index])
|
||||
}
|
||||
return items
|
||||
}
|
||||
@@ -202,7 +202,7 @@ func (s *Service) InstallPluginForAdmin(actor *model.User, data []byte, fileName
|
||||
if err != nil {
|
||||
return PluginView{}, err
|
||||
}
|
||||
plugin.Management = pluginManagement(plugin.Manifest.ID, plugin.Source)
|
||||
plugin.Management = pluginManagementFromView(plugin)
|
||||
now := time.Now()
|
||||
state := &model.PluginPlatformState{PluginID: plugin.Manifest.ID, Available: plugin.Status == "enabled", UpdatedBy: actor.ID, CreatedAt: now, UpdatedAt: now}
|
||||
if err := s.repo.SavePluginPlatformState(state); err != nil {
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const CurrentSchemaVersion int64 = 18
|
||||
const CurrentSchemaVersion int64 = 19
|
||||
|
||||
const baselineSchemaChecksum = "sha256:open-ai-canvas-schema-v1-20260830"
|
||||
const schemaMigrationAppliedAtIndexChecksum = "sha256:schema-migrations-applied-at-index-v2-20260830"
|
||||
@@ -76,6 +76,7 @@ var schemaMigrations = []migration{
|
||||
{version: 18, name: "agent_memory_settings", checksum: "sha256:agent-memory-settings-v18-20260917", apply: func(tx *gorm.DB) error {
|
||||
return tx.AutoMigrate(&model.AgentMemorySetting{})
|
||||
}},
|
||||
{version: 19, name: "payment_plugin_version", checksum: "sha256:payment-plugin-version-v19-20260917", apply: migrateSchemaV19},
|
||||
}
|
||||
|
||||
func migrateSchemaV14(tx *gorm.DB) error {
|
||||
@@ -239,6 +240,28 @@ func migrateSchemaV5(tx *gorm.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateSchemaV19(tx *gorm.DB) error {
|
||||
for _, value := range []any{&model.PaymentProviderConfig{}, &model.PaymentOrder{}} {
|
||||
if !tx.Migrator().HasTable(value) {
|
||||
continue
|
||||
}
|
||||
if err := addPaymentPluginVersionColumn(tx, value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func addPaymentPluginVersionColumn(tx *gorm.DB, value any) error {
|
||||
if tx.Migrator().HasColumn(value, "plugin_version") {
|
||||
return nil
|
||||
}
|
||||
if err := tx.Migrator().AddColumn(value, "PluginVersion"); err != nil {
|
||||
return fmt.Errorf("增加支付插件版本列:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func migrateSchemaV6(tx *gorm.DB) error {
|
||||
if !tx.Migrator().HasTable(&model.Resource{}) {
|
||||
return fmt.Errorf("资源表不存在")
|
||||
|
||||
@@ -44,6 +44,9 @@ func TestMigrateSchemaRecordsAndValidatesVersion(t *testing.T) {
|
||||
if !db.Migrator().HasTable(&model.AgentMemorySetting{}) {
|
||||
t.Fatal("schema migration v18 did not create agent memory settings")
|
||||
}
|
||||
if !db.Migrator().HasColumn(&model.PaymentProviderConfig{}, "plugin_version") || !db.Migrator().HasColumn(&model.PaymentOrder{}, "plugin_version") {
|
||||
t.Fatal("schema migration v19 did not add payment plugin version columns")
|
||||
}
|
||||
if err := MigrateSchema(db); err != nil {
|
||||
t.Fatalf("migration should be idempotent: %v", err)
|
||||
}
|
||||
@@ -153,6 +156,38 @@ func TestMigrateSchemaV18UpgradesExistingDatabase(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateSchemaV19AddsPaymentPluginVersion(t *testing.T) {
|
||||
db, err := Open(Config{Driver: "sqlite", DSN: "file:migration-payment-plugin-version-v19?mode=memory&cache=shared"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := MigrateSchema(db); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Migrator().DropColumn(&model.PaymentProviderConfig{}, "PluginVersion"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Migrator().DropColumn(&model.PaymentOrder{}, "PluginVersion"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Where("version = ?", 19).Delete(&schemaMigration{}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := MigrateSchema(db); err != nil {
|
||||
t.Fatalf("upgrade from v18: %v", err)
|
||||
}
|
||||
if !db.Migrator().HasColumn(&model.PaymentProviderConfig{}, "plugin_version") {
|
||||
t.Fatal("v19 upgrade did not add payment_provider_configs.plugin_version")
|
||||
}
|
||||
if !db.Migrator().HasColumn(&model.PaymentOrder{}, "plugin_version") {
|
||||
t.Fatal("v19 upgrade did not add payment_orders.plugin_version")
|
||||
}
|
||||
status, err := ReadSchemaStatus(db)
|
||||
if err != nil || !status.Ready || status.Current != CurrentSchemaVersion {
|
||||
t.Fatalf("unexpected upgraded schema status: %+v, %v", status, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateSchemaV8AllowsReusingArchivedLogicalModelCode(t *testing.T) {
|
||||
db, err := Open(Config{Driver: "sqlite", DSN: "file:migration-logical-model-active-code?mode=memory&cache=shared"})
|
||||
if err != nil {
|
||||
|
||||
+197
-26
@@ -10,6 +10,8 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"debug/elf"
|
||||
"debug/macho"
|
||||
"debug/pe"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -25,6 +27,8 @@ import (
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/protocol"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -35,6 +39,7 @@ const (
|
||||
|
||||
type RPCProvider struct {
|
||||
descriptor Descriptor
|
||||
entry string
|
||||
command string
|
||||
dir string
|
||||
}
|
||||
@@ -49,7 +54,11 @@ func NewRPCProvider(descriptor Descriptor, packageDir, entry string) (*RPCProvid
|
||||
if strings.TrimSpace(packageDir) == "" {
|
||||
return nil, errors.New("payment plugin package directory is empty")
|
||||
}
|
||||
return &RPCProvider{descriptor: descriptor, command: filepath.Join(packageDir, filepath.FromSlash(entry)), dir: packageDir}, nil
|
||||
packageDir, err := filepath.Abs(packageDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("payment plugin package directory is invalid: %w", err)
|
||||
}
|
||||
return &RPCProvider{descriptor: descriptor, entry: entry, dir: packageDir}, nil
|
||||
}
|
||||
|
||||
func (p *RPCProvider) Descriptor() Descriptor { return p.descriptor }
|
||||
@@ -73,10 +82,14 @@ type rpcResponse struct {
|
||||
}
|
||||
|
||||
func (p *RPCProvider) call(ctx context.Context, request rpcRequest, output any) error {
|
||||
if p == nil || strings.TrimSpace(p.command) == "" {
|
||||
if p == nil {
|
||||
return errors.New("payment plugin runtime is unavailable")
|
||||
}
|
||||
info, err := os.Stat(p.command)
|
||||
command, err := p.executable()
|
||||
if err != nil {
|
||||
return p.startError(err)
|
||||
}
|
||||
info, err := os.Stat(command)
|
||||
if err != nil {
|
||||
return p.startError(err)
|
||||
}
|
||||
@@ -86,7 +99,7 @@ func (p *RPCProvider) call(ctx context.Context, request rpcRequest, output any)
|
||||
if runtime.GOOS != "windows" && info.Mode().Perm()&0o111 == 0 {
|
||||
return p.startError(fmt.Errorf("payment plugin executable has no execute bit: %w", syscall.EACCES))
|
||||
}
|
||||
if err := validatePaymentExecutablePlatform(p.command); err != nil {
|
||||
if err := validatePaymentExecutablePlatform(command); err != nil {
|
||||
return p.startError(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, pluginRPCTimeout)
|
||||
@@ -95,9 +108,9 @@ func (p *RPCProvider) call(ctx context.Context, request rpcRequest, output any)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, p.command)
|
||||
cmd := exec.CommandContext(ctx, command)
|
||||
cmd.Dir = p.dir
|
||||
cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent"}
|
||||
cmd.Env = paymentPluginCommandEnv()
|
||||
cmd.Stdin = strings.NewReader(string(payload) + "\n")
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
@@ -148,21 +161,96 @@ func (p *RPCProvider) call(ctx context.Context, request rpcRequest, output any)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *RPCProvider) executable() (string, error) {
|
||||
if p == nil {
|
||||
return "", errors.New("payment plugin runtime is unavailable")
|
||||
}
|
||||
if strings.TrimSpace(p.command) != "" {
|
||||
return p.command, nil
|
||||
}
|
||||
command, err := ResolveRPCBackendPath(p.dir, p.entry)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
command, err = filepath.Abs(command)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p.command = command
|
||||
return command, nil
|
||||
}
|
||||
|
||||
func (p *RPCProvider) startError(cause error) error {
|
||||
providerErr := classifyPaymentPluginStartError(cause)
|
||||
command := strings.TrimSpace(p.command)
|
||||
if command == "" {
|
||||
command, _ = ResolveRPCBackendPath(p.dir, p.entry)
|
||||
}
|
||||
log.Printf(
|
||||
"payment plugin executable failed: provider=%q plugin=%q host=%s/%s command=%q code=%s error=%v",
|
||||
p.descriptor.ID,
|
||||
p.descriptor.PluginID,
|
||||
runtime.GOOS,
|
||||
runtime.GOARCH,
|
||||
p.command,
|
||||
command,
|
||||
providerErr.Code,
|
||||
cause,
|
||||
)
|
||||
return providerErr
|
||||
}
|
||||
|
||||
func paymentPluginCommandEnv() []string {
|
||||
if runtime.GOOS == "windows" {
|
||||
systemRoot := strings.TrimSpace(os.Getenv("SystemRoot"))
|
||||
if systemRoot == "" {
|
||||
systemRoot = strings.TrimSpace(os.Getenv("SYSTEMROOT"))
|
||||
}
|
||||
env := []string{"HOME=" + filepath.Join("C:\\", "nonexistent")}
|
||||
if systemRoot != "" {
|
||||
env = append(env, "SystemRoot="+systemRoot, "SYSTEMROOT="+systemRoot)
|
||||
}
|
||||
return env
|
||||
}
|
||||
return []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent"}
|
||||
}
|
||||
|
||||
func ResolveRPCBackendPath(packageDir, entry string) (string, error) {
|
||||
if strings.TrimSpace(packageDir) == "" {
|
||||
return "", fmt.Errorf("payment plugin executable for %s/%s is missing: %w", runtime.GOOS, runtime.GOARCH, os.ErrNotExist)
|
||||
}
|
||||
var missingErr, formatErr error
|
||||
for _, candidate := range protocol.PaymentRPCBackendCandidates(entry, runtime.GOOS, runtime.GOARCH) {
|
||||
target := filepath.Join(packageDir, filepath.FromSlash(candidate))
|
||||
info, err := os.Stat(target)
|
||||
if err != nil {
|
||||
if missingErr == nil {
|
||||
missingErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if info.IsDir() {
|
||||
if missingErr == nil {
|
||||
missingErr = os.ErrNotExist
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := validatePaymentExecutablePlatform(target); err != nil {
|
||||
if formatErr == nil {
|
||||
formatErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
if formatErr != nil {
|
||||
return "", fmt.Errorf("payment plugin executable for %s/%s is incompatible: %w", runtime.GOOS, runtime.GOARCH, formatErr)
|
||||
}
|
||||
if missingErr == nil {
|
||||
missingErr = os.ErrNotExist
|
||||
}
|
||||
return "", fmt.Errorf("payment plugin executable for %s/%s is missing: %w", runtime.GOOS, runtime.GOARCH, missingErr)
|
||||
}
|
||||
|
||||
func classifyPaymentPluginStartError(cause error) *ProviderError {
|
||||
switch {
|
||||
case errors.Is(cause, os.ErrNotExist), errors.Is(cause, syscall.ENOENT), errors.Is(cause, exec.ErrNotFound):
|
||||
@@ -177,9 +265,6 @@ func classifyPaymentPluginStartError(cause error) *ProviderError {
|
||||
}
|
||||
|
||||
func validatePaymentExecutablePlatform(command string) error {
|
||||
if runtime.GOOS != "linux" {
|
||||
return nil
|
||||
}
|
||||
file, err := os.Open(command)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -190,26 +275,90 @@ func validatePaymentExecutablePlatform(command string) error {
|
||||
if _, err := io.ReadFull(file, magic[:]); err != nil {
|
||||
return fmt.Errorf("payment plugin executable header is incomplete: %w", syscall.ENOEXEC)
|
||||
}
|
||||
if bytes.Equal(magic[:2], []byte{'M', 'Z'}) {
|
||||
return fmt.Errorf("payment plugin executable is Windows PE on linux/%s: %w", runtime.GOARCH, syscall.ENOEXEC)
|
||||
}
|
||||
if isMachOMagic(magic) {
|
||||
return fmt.Errorf("payment plugin executable is Mach-O on linux/%s: %w", runtime.GOARCH, syscall.ENOEXEC)
|
||||
}
|
||||
if !bytes.Equal(magic[:], []byte{0x7f, 'E', 'L', 'F'}) {
|
||||
// Scripts and other kernel-supported executable formats are left to
|
||||
// cmd.Start. Unknown binary data will be classified from ENOEXEC there.
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
if bytes.Equal(magic[:2], []byte{'M', 'Z'}) {
|
||||
return fmt.Errorf("payment plugin executable is Windows PE on linux/%s: %w", runtime.GOARCH, syscall.ENOEXEC)
|
||||
}
|
||||
if isMachOMagic(magic) {
|
||||
return fmt.Errorf("payment plugin executable is Mach-O on linux/%s: %w", runtime.GOARCH, syscall.ENOEXEC)
|
||||
}
|
||||
if !bytes.Equal(magic[:], []byte{0x7f, 'E', 'L', 'F'}) {
|
||||
return nil
|
||||
}
|
||||
binary, err := elf.NewFile(file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("payment plugin ELF header is invalid: %w", syscall.ENOEXEC)
|
||||
}
|
||||
defer binary.Close()
|
||||
expected, ok := expectedPaymentELFMachine(runtime.GOARCH)
|
||||
if binary.Class != elf.ELFCLASS64 || (ok && binary.Machine != expected) {
|
||||
return fmt.Errorf("payment plugin ELF architecture mismatch: host=linux/%s class=%s machine=%s: %w", runtime.GOARCH, binary.Class, binary.Machine, syscall.ENOEXEC)
|
||||
}
|
||||
return nil
|
||||
case "darwin":
|
||||
if bytes.Equal(magic[:], []byte{0x7f, 'E', 'L', 'F'}) {
|
||||
return fmt.Errorf("payment plugin executable is ELF on darwin/%s: %w", runtime.GOARCH, syscall.ENOEXEC)
|
||||
}
|
||||
if bytes.Equal(magic[:2], []byte{'M', 'Z'}) {
|
||||
return fmt.Errorf("payment plugin executable is Windows PE on darwin/%s: %w", runtime.GOARCH, syscall.ENOEXEC)
|
||||
}
|
||||
if !isMachOMagic(magic) {
|
||||
return nil
|
||||
}
|
||||
return validateMachOArchitecture(command)
|
||||
case "windows":
|
||||
if bytes.Equal(magic[:], []byte{0x7f, 'E', 'L', 'F'}) {
|
||||
return fmt.Errorf("payment plugin executable is ELF on windows/%s: %w", runtime.GOARCH, syscall.ENOEXEC)
|
||||
}
|
||||
if isMachOMagic(magic) {
|
||||
return fmt.Errorf("payment plugin executable is Mach-O on windows/%s: %w", runtime.GOARCH, syscall.ENOEXEC)
|
||||
}
|
||||
if !bytes.Equal(magic[:2], []byte{'M', 'Z'}) {
|
||||
return nil
|
||||
}
|
||||
return validateWindowsPEArchitecture(command)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
binary, err := elf.NewFile(file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("payment plugin ELF header is invalid: %w", syscall.ENOEXEC)
|
||||
func validateMachOArchitecture(command string) error {
|
||||
expected, ok := expectedMachOCPU(runtime.GOARCH)
|
||||
file, err := macho.Open(command)
|
||||
if err == nil {
|
||||
defer file.Close()
|
||||
if ok && file.Cpu != expected {
|
||||
return fmt.Errorf("payment plugin Mach-O architecture mismatch: host=darwin/%s cpu=%s: %w", runtime.GOARCH, file.Cpu, syscall.ENOEXEC)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
defer binary.Close()
|
||||
expected, ok := expectedPaymentELFMachine(runtime.GOARCH)
|
||||
if binary.Class != elf.ELFCLASS64 || (ok && binary.Machine != expected) {
|
||||
return fmt.Errorf("payment plugin ELF architecture mismatch: host=linux/%s class=%s machine=%s: %w", runtime.GOARCH, binary.Class, binary.Machine, syscall.ENOEXEC)
|
||||
fat, fatErr := macho.OpenFat(command)
|
||||
if fatErr != nil {
|
||||
return fmt.Errorf("payment plugin Mach-O header is invalid: %w", syscall.ENOEXEC)
|
||||
}
|
||||
defer fat.Close()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
for _, arch := range fat.Arches {
|
||||
if arch.Cpu == expected {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("payment plugin Mach-O architecture mismatch: host=darwin/%s: %w", runtime.GOARCH, syscall.ENOEXEC)
|
||||
}
|
||||
|
||||
func validateWindowsPEArchitecture(command string) error {
|
||||
file, err := pe.Open(command)
|
||||
if err != nil {
|
||||
return fmt.Errorf("payment plugin PE header is invalid: %w", syscall.ENOEXEC)
|
||||
}
|
||||
defer file.Close()
|
||||
expected, ok := expectedPEMachine(runtime.GOARCH)
|
||||
if ok && file.Machine != expected {
|
||||
return fmt.Errorf("payment plugin PE architecture mismatch: host=windows/%s machine=%d: %w", runtime.GOARCH, file.Machine, syscall.ENOEXEC)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -232,6 +381,28 @@ func expectedPaymentELFMachine(arch string) (elf.Machine, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
func expectedMachOCPU(arch string) (macho.Cpu, bool) {
|
||||
switch arch {
|
||||
case "amd64":
|
||||
return macho.CpuAmd64, true
|
||||
case "arm64":
|
||||
return macho.CpuArm64, true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func expectedPEMachine(arch string) (uint16, bool) {
|
||||
switch arch {
|
||||
case "amd64":
|
||||
return pe.IMAGE_FILE_MACHINE_AMD64, true
|
||||
case "arm64":
|
||||
return pe.IMAGE_FILE_MACHINE_ARM64, true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
func (p *RPCProvider) ValidateConfig(config Config) error {
|
||||
return p.call(context.Background(), rpcRequest{Version: pluginRPCVersion, Operation: "validate_config", Config: config}, nil)
|
||||
}
|
||||
|
||||
@@ -82,6 +82,148 @@ func TestRPCProviderClassifiesExecutableStartFailures(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRPCProviderRejectsIncompatibleFallbackBinary(t *testing.T) {
|
||||
if runtime.GOOS == "linux" {
|
||||
t.Skip("linux already classifies foreign binaries in TestRPCProviderClassifiesExecutableStartFailures")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
entry := filepath.Join(dir, "backend", "provider")
|
||||
if err := os.MkdirAll(filepath.Dir(entry), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(entry, []byte{0x7f, 'E', 'L', 'F', 0x02, 0x01, 0x01, 0x00}, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider, err := NewRPCProvider(Descriptor{ID: "test-provider", PluginID: "test-plugin"}, dir, "backend/provider")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = provider.ValidateConfig(Config{})
|
||||
var providerErr *ProviderError
|
||||
if !errors.As(err, &providerErr) {
|
||||
t.Fatalf("ValidateConfig() error = %T %v, want ProviderError", err, err)
|
||||
}
|
||||
if providerErr.Code != "plugin_exec_format_error" || providerErr.Message != "支付插件可执行文件与当前操作系统或 CPU 架构不兼容" {
|
||||
t.Fatalf("ProviderError = %#v", providerErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRPCBackendPathPrefersHostTaggedBinary(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("tagged fallback uses a POSIX shell script")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
backend := filepath.Join(dir, "backend")
|
||||
if err := os.MkdirAll(backend, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(backend, "provider"), []byte{0x7f, 'E', 'L', 'F', 0x02, 0x01, 0x01, 0x00}, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tagged := "provider-" + runtime.GOOS + "-" + runtime.GOARCH
|
||||
script := []byte("#!/bin/sh\nexit 0\n")
|
||||
if err := os.WriteFile(filepath.Join(backend, tagged), script, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resolved, err := ResolveRPCBackendPath(dir, "backend/provider")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if filepath.Base(resolved) != tagged {
|
||||
t.Fatalf("resolved %q, want tagged %q", resolved, tagged)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRPCProviderStartsOfficialHostArtifact(t *testing.T) {
|
||||
artifact := "provider-" + runtime.GOOS + "-" + runtime.GOARCH
|
||||
if runtime.GOOS == "windows" {
|
||||
artifact += ".exe"
|
||||
}
|
||||
sourceDir := filepath.Join("..", "..", "..", "plugin-packages", "official-payment-xunhupay", "backend")
|
||||
hostBinary, err := os.ReadFile(filepath.Join(sourceDir, artifact))
|
||||
if err != nil {
|
||||
t.Fatalf("read host artifact: %v", err)
|
||||
}
|
||||
fallback, err := os.ReadFile(filepath.Join(sourceDir, "provider"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
backend := filepath.Join(dir, "backend")
|
||||
if err := os.MkdirAll(backend, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(backend, artifact), hostBinary, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(backend, "provider"), fallback, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider, err := NewRPCProvider(Descriptor{ID: "xunhupay-aggregate", PluginID: "official-payment-xunhupay"}, dir, "backend/provider")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = provider.ValidateConfig(Config{})
|
||||
var providerErr *ProviderError
|
||||
if !errors.As(err, &providerErr) {
|
||||
t.Fatalf("ValidateConfig() error = %T %v, want ProviderError", err, err)
|
||||
}
|
||||
if providerErr.Code == "plugin_executable_missing" || providerErr.Code == "plugin_exec_format_error" || providerErr.Code == "plugin_start_failed" {
|
||||
t.Fatalf("host artifact failed to start: %#v cause=%v", providerErr, providerErr.Cause)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRPCProviderStartsFromRelativePackageDir(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("relative package directories are asserted against POSIX path resolution")
|
||||
}
|
||||
artifact := "provider-" + runtime.GOOS + "-" + runtime.GOARCH
|
||||
source := filepath.Join("..", "..", "..", "plugin-packages", "official-payment-xunhupay", "backend", artifact)
|
||||
hostBinary, err := os.ReadFile(source)
|
||||
if err != nil {
|
||||
t.Fatalf("read host artifact: %v", err)
|
||||
}
|
||||
absDir := t.TempDir()
|
||||
relDir, err := filepath.Rel(mustWorkingDir(t), absDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if filepath.IsAbs(relDir) {
|
||||
t.Fatalf("test setup produced an absolute package dir %q", relDir)
|
||||
}
|
||||
backend := filepath.Join(absDir, "backend")
|
||||
if err := os.MkdirAll(backend, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(backend, artifact), hostBinary, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider, err := NewRPCProvider(Descriptor{ID: "xunhupay-aggregate", PluginID: "official-payment-xunhupay"}, relDir, "backend/provider")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !filepath.IsAbs(provider.dir) {
|
||||
t.Fatalf("package dir = %q, want absolute", provider.dir)
|
||||
}
|
||||
err = provider.ValidateConfig(Config{})
|
||||
var providerErr *ProviderError
|
||||
if !errors.As(err, &providerErr) {
|
||||
t.Fatalf("ValidateConfig() error = %T %v, want ProviderError", err, err)
|
||||
}
|
||||
if providerErr.Code == "plugin_executable_missing" || providerErr.Code == "plugin_exec_format_error" || providerErr.Code == "plugin_start_failed" {
|
||||
t.Fatalf("relative package dir failed to start host artifact: %#v cause=%v", providerErr, providerErr.Cause)
|
||||
}
|
||||
}
|
||||
|
||||
func mustWorkingDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func TestClassifyPaymentPluginStartError(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -13,10 +13,10 @@ import (
|
||||
|
||||
const (
|
||||
PluginPackageFormat = "yingce.plugin/package-v1"
|
||||
PluginPackageMaxBytes = 16 << 20
|
||||
PluginPackageMaxBytes = 48 << 20
|
||||
PluginManifestMaxBytes = 512 << 10
|
||||
pluginPackageMaxFiles = 256
|
||||
pluginPackageMaxEntry = 8 << 20
|
||||
pluginPackageMaxEntry = 16 << 20
|
||||
)
|
||||
|
||||
// PluginPackage is the transport envelope for every uploaded plugin. The
|
||||
@@ -117,7 +117,11 @@ func validatePluginPackageRuntime(manifest Manifest, files map[string][]byte) er
|
||||
if !strings.HasPrefix(entry, "backend/") || path.Clean(entry) != entry {
|
||||
return fmt.Errorf("manifest.runtime.backendEntry must point inside backend/")
|
||||
}
|
||||
if _, ok := files[entry]; !ok {
|
||||
if backend == "rpc" {
|
||||
if !HasAnyPaymentRPCBackend(entry, files) {
|
||||
return fmt.Errorf("manifest runtime backend entry %q is missing a host-executable artifact", entry)
|
||||
}
|
||||
} else if _, ok := files[entry]; !ok {
|
||||
return fmt.Errorf("manifest runtime backend entry %q is missing from package", entry)
|
||||
}
|
||||
if backend == "wasm" && !strings.HasSuffix(strings.ToLower(entry), ".wasm") {
|
||||
|
||||
@@ -42,6 +42,33 @@ func TestParsePluginPackageValidatesWebEntry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePluginPackageAcceptsTaggedRPCBackend(t *testing.T) {
|
||||
manifest := []byte(`{
|
||||
"apiVersion":"yingce.plugin/v1",
|
||||
"id":"tagged-payment",
|
||||
"name":"Tagged Payment",
|
||||
"version":"1.0.0",
|
||||
"author":"Test",
|
||||
"enabled":true,
|
||||
"runtime":{"backend":"rpc","backendEntry":"backend/provider"},
|
||||
"contributes":{"paymentProviders":[{"id":"tagged-pay","label":"Tagged","icon":"brand:test","checkoutMode":"qr_code","expiryPolicy":{"defaultMinutes":30,"minMinutes":5,"maxMinutes":1440}}]}
|
||||
}`)
|
||||
pkg, err := ParsePluginPackage(zipPluginPackage(t, map[string][]byte{
|
||||
"manifest.json": manifest,
|
||||
"backend/provider-darwin-arm64": []byte("darwin-provider"),
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := pkg.Files["backend/provider"]; ok {
|
||||
t.Fatal("canonical backend/provider should not be required when a tagged artifact exists")
|
||||
}
|
||||
|
||||
if _, err := ParsePluginPackage(zipPluginPackage(t, map[string][]byte{"manifest.json": manifest})); err == nil {
|
||||
t.Fatal("rpc package without any backend artifact was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func zipPluginPackage(t *testing.T, files map[string][]byte) []byte {
|
||||
t.Helper()
|
||||
var buffer bytes.Buffer
|
||||
|
||||
@@ -12,8 +12,23 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
var officialPaymentPackageIDs = []string{
|
||||
"official-payment-wechat-native",
|
||||
"official-payment-alipay-page",
|
||||
"official-payment-xunhupay",
|
||||
}
|
||||
|
||||
var officialPaymentTaggedArtifacts = []string{
|
||||
"backend/provider-linux-amd64",
|
||||
"backend/provider-linux-arm64",
|
||||
"backend/provider-darwin-amd64",
|
||||
"backend/provider-darwin-arm64",
|
||||
"backend/provider-windows-amd64.exe",
|
||||
"backend/provider-windows-arm64.exe",
|
||||
}
|
||||
|
||||
func TestOfficialPaymentArtifactsAreCanonicalLinuxAMD64(t *testing.T) {
|
||||
for _, packageID := range []string{"official-payment-wechat-native", "official-payment-alipay-page"} {
|
||||
for _, packageID := range officialPaymentPackageIDs {
|
||||
t.Run(packageID, func(t *testing.T) {
|
||||
root := filepath.Join("..", "..", "..", "plugin-packages")
|
||||
providerPath := filepath.Join(root, packageID, "backend", "provider")
|
||||
@@ -33,6 +48,10 @@ func TestOfficialPaymentArtifactsAreCanonicalLinuxAMD64(t *testing.T) {
|
||||
if !bytes.Equal(directoryProvider, packagedProvider) {
|
||||
t.Fatal("directory provider differs from .yingce-plugin backend/provider")
|
||||
}
|
||||
linuxAMD64 := pkg.Files["backend/provider-linux-amd64"]
|
||||
if !bytes.Equal(directoryProvider, linuxAMD64) {
|
||||
t.Fatal("canonical backend/provider differs from backend/provider-linux-amd64")
|
||||
}
|
||||
binary, err := elf.NewFile(bytes.NewReader(directoryProvider))
|
||||
if err != nil {
|
||||
t.Fatalf("provider is not ELF: %v", err)
|
||||
@@ -52,31 +71,91 @@ func TestOfficialPaymentArtifactsAreCanonicalLinuxAMD64(t *testing.T) {
|
||||
t.Fatalf("provider build settings = GOOS=%s GOARCH=%s CGO_ENABLED=%s", settings["GOOS"], settings["GOARCH"], settings["CGO_ENABLED"])
|
||||
}
|
||||
|
||||
for _, name := range officialPaymentTaggedArtifacts {
|
||||
directoryTagged, err := os.ReadFile(filepath.Join(root, packageID, filepath.FromSlash(name)))
|
||||
if err != nil {
|
||||
t.Fatalf("missing directory artifact %s: %v", name, err)
|
||||
}
|
||||
packagedTagged := pkg.Files[name]
|
||||
if !bytes.Equal(directoryTagged, packagedTagged) {
|
||||
t.Fatalf("directory %s differs from packaged artifact", name)
|
||||
}
|
||||
taggedInfo, err := buildinfo.Read(bytes.NewReader(directoryTagged))
|
||||
if err != nil {
|
||||
t.Fatalf("read %s build info: %v", name, err)
|
||||
}
|
||||
taggedSettings := make(map[string]string, len(taggedInfo.Settings))
|
||||
for _, setting := range taggedInfo.Settings {
|
||||
taggedSettings[setting.Key] = setting.Value
|
||||
}
|
||||
wantOS, wantArch := expectedPaymentArtifactPlatform(name)
|
||||
if taggedSettings["GOOS"] != wantOS || taggedSettings["GOARCH"] != wantArch || taggedSettings["CGO_ENABLED"] != "0" {
|
||||
t.Fatalf("%s build settings = GOOS=%s GOARCH=%s CGO_ENABLED=%s", name, taggedSettings["GOOS"], taggedSettings["GOARCH"], taggedSettings["CGO_ENABLED"])
|
||||
}
|
||||
}
|
||||
|
||||
if runtime.GOOS == "linux" && runtime.GOARCH == "amd64" {
|
||||
fileInfo, err := os.Stat(providerPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fileInfo.Mode().Perm()&0o111 == 0 {
|
||||
t.Fatal("provider is not executable")
|
||||
}
|
||||
command := exec.Command(providerPath)
|
||||
command.Stdin = bytes.NewBufferString("invalid-json\n")
|
||||
output, err := command.Output()
|
||||
if err != nil {
|
||||
t.Fatalf("provider smoke test failed: %v", err)
|
||||
}
|
||||
var response struct {
|
||||
OK bool `json:"ok"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if err := json.Unmarshal(output, &response); err != nil {
|
||||
t.Fatalf("provider smoke response is invalid JSON: %v", err)
|
||||
}
|
||||
if response.OK || response.Code != "invalid_request" {
|
||||
t.Fatalf("provider smoke response = %s", output)
|
||||
}
|
||||
smokePaymentProvider(t, providerPath)
|
||||
return
|
||||
}
|
||||
hostCandidates := PaymentRPCBackendCandidates("backend/provider", runtime.GOOS, runtime.GOARCH)
|
||||
if len(hostCandidates) == 0 {
|
||||
t.Fatalf("no RPC candidates for %s/%s", runtime.GOOS, runtime.GOARCH)
|
||||
}
|
||||
hostArtifact := hostCandidates[0]
|
||||
hostPath := filepath.Join(root, packageID, filepath.FromSlash(hostArtifact))
|
||||
if _, err := os.Stat(hostPath); err != nil {
|
||||
t.Fatalf("host artifact %s is missing: %v", hostArtifact, err)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
smokePaymentProvider(t, hostPath)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func expectedPaymentArtifactPlatform(name string) (string, string) {
|
||||
switch name {
|
||||
case "backend/provider-linux-amd64":
|
||||
return "linux", "amd64"
|
||||
case "backend/provider-linux-arm64":
|
||||
return "linux", "arm64"
|
||||
case "backend/provider-darwin-amd64":
|
||||
return "darwin", "amd64"
|
||||
case "backend/provider-darwin-arm64":
|
||||
return "darwin", "arm64"
|
||||
case "backend/provider-windows-amd64.exe":
|
||||
return "windows", "amd64"
|
||||
case "backend/provider-windows-arm64.exe":
|
||||
return "windows", "arm64"
|
||||
default:
|
||||
return "", ""
|
||||
}
|
||||
}
|
||||
|
||||
func smokePaymentProvider(t *testing.T, providerPath string) {
|
||||
t.Helper()
|
||||
fileInfo, err := os.Stat(providerPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fileInfo.Mode().Perm()&0o111 == 0 {
|
||||
t.Fatal("provider is not executable")
|
||||
}
|
||||
command := exec.Command(providerPath)
|
||||
command.Stdin = bytes.NewBufferString("invalid-json\n")
|
||||
output, err := command.Output()
|
||||
if err != nil {
|
||||
t.Fatalf("provider smoke test failed: %v", err)
|
||||
}
|
||||
var response struct {
|
||||
OK bool `json:"ok"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
if err := json.Unmarshal(output, &response); err != nil {
|
||||
t.Fatalf("provider smoke response is invalid JSON: %v", err)
|
||||
}
|
||||
if response.OK || response.Code != "invalid_request" {
|
||||
t.Fatalf("provider smoke response = %s", output)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func PaymentRPCBackendCandidates(entry, goos, goarch string) []string {
|
||||
entry = strings.TrimSuffix(strings.TrimSpace(entry), ".exe")
|
||||
goos = strings.TrimSpace(goos)
|
||||
goarch = strings.TrimSpace(goarch)
|
||||
if entry == "" || goos == "" || goarch == "" || path.Clean(entry) != entry || !strings.HasPrefix(entry, "backend/") {
|
||||
return nil
|
||||
}
|
||||
base := path.Base(entry)
|
||||
dir := path.Dir(entry)
|
||||
tagged := entry + "-" + goos + "-" + goarch
|
||||
nested := dir + "/" + goos + "-" + goarch + "/" + base
|
||||
candidates := make([]string, 0, 6)
|
||||
if goos == "windows" {
|
||||
candidates = append(candidates, tagged+".exe", nested+".exe", entry+".exe")
|
||||
}
|
||||
candidates = append(candidates, tagged, nested, entry)
|
||||
return uniqueStrings(candidates)
|
||||
}
|
||||
|
||||
func HasAnyPaymentRPCBackend(entry string, files map[string][]byte) bool {
|
||||
entry = strings.TrimSuffix(strings.TrimSpace(entry), ".exe")
|
||||
if entry == "" {
|
||||
return false
|
||||
}
|
||||
if _, ok := files[entry]; ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := files[entry+".exe"]; ok {
|
||||
return true
|
||||
}
|
||||
prefix := entry + "-"
|
||||
nestedRoot := path.Dir(entry) + "/"
|
||||
base := path.Base(entry)
|
||||
for name := range files {
|
||||
if strings.HasPrefix(name, prefix) {
|
||||
return true
|
||||
}
|
||||
rest, ok := strings.CutPrefix(name, nestedRoot)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
slash := strings.IndexByte(rest, '/')
|
||||
if slash <= 0 {
|
||||
continue
|
||||
}
|
||||
leaf := rest[slash+1:]
|
||||
if leaf == base || leaf == base+".exe" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func uniqueStrings(values []string) []string {
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
if _, exists := seen[value]; exists {
|
||||
continue
|
||||
}
|
||||
seen[value] = struct{}{}
|
||||
result = append(result, value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package protocol
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPaymentRPCBackendCandidatesPreferPlatformTaggedFiles(t *testing.T) {
|
||||
darwin := PaymentRPCBackendCandidates("backend/provider", "darwin", "arm64")
|
||||
if got, want := darwin[0], "backend/provider-darwin-arm64"; got != want {
|
||||
t.Fatalf("darwin candidates[0] = %q, want %q (%v)", got, want, darwin)
|
||||
}
|
||||
windows := PaymentRPCBackendCandidates("backend/provider", "windows", "amd64")
|
||||
if got, want := windows[0], "backend/provider-windows-amd64.exe"; got != want {
|
||||
t.Fatalf("windows candidates[0] = %q, want %q (%v)", got, want, windows)
|
||||
}
|
||||
if windows[len(windows)-1] != "backend/provider" {
|
||||
t.Fatalf("windows fallback = %v", windows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasAnyPaymentRPCBackendAcceptsTaggedArtifacts(t *testing.T) {
|
||||
if HasAnyPaymentRPCBackend("backend/provider", map[string][]byte{"backend/provider-darwin-arm64": {1}}) != true {
|
||||
t.Fatal("tagged darwin provider should be accepted")
|
||||
}
|
||||
if HasAnyPaymentRPCBackend("backend/provider", map[string][]byte{"backend/windows-amd64/provider.exe": {1}}) != true {
|
||||
t.Fatal("nested windows provider should be accepted")
|
||||
}
|
||||
if HasAnyPaymentRPCBackend("backend/provider", map[string][]byte{"backend/unrelated": {1}}) {
|
||||
t.Fatal("unrelated backend file should not satisfy the payment entry")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user