mirror of
https://github.com/majd/ipatool
synced 2026-11-29 02:37:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b02b4c555 | ||
|
|
d69faf83c8 | ||
|
|
5a6dfe0582 | ||
|
|
b352566155 | ||
|
|
6194bf4ecd | ||
|
|
20290220cd |
No files matched your search
@@ -95,6 +95,14 @@ func downloadCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return err
|
||||
}
|
||||
|
||||
// Purchasing may persist a server-corrected storefront.
|
||||
info, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = info.Account
|
||||
purchaseRequired = false
|
||||
purchased = true
|
||||
dependencies.Logger.Verbose().
|
||||
|
||||
+53
-15
@@ -141,7 +141,7 @@ var _ = Describe("Download command", func() {
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.accountInfoCalls).To(Equal(2))
|
||||
Expect(store.purchaseInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs[0].Platform).To(Equal(platform))
|
||||
Expect(store.purchaseInputs[0].App).To(Equal(appstore.App{ID: 42}))
|
||||
@@ -167,7 +167,7 @@ var _ = Describe("Download command", func() {
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.accountInfoCalls).To(Equal(2))
|
||||
Expect(store.loginInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs).To(HaveLen(2))
|
||||
Expect(store.purchaseInputs[0].Platform).To(Equal(appstore.PlatformMacOS))
|
||||
@@ -198,7 +198,7 @@ var _ = Describe("Download command", func() {
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.accountInfoCalls).To(Equal(1 + purchaseCount))
|
||||
Expect(store.loginInputs).To(Equal([]appstore.LoginInput{{Email: account.Email, Password: account.Password}}))
|
||||
Expect(store.lookupInputs).To(HaveLen(len(downloadErrors)))
|
||||
Expect(store.lookupInputs[0].Account).To(Equal(account))
|
||||
@@ -223,6 +223,38 @@ var _ = Describe("Download command", func() {
|
||||
Entry("retains the refreshed token for a subsequent purchase", []error{appstore.ErrPasswordTokenExpired, appstore.ErrLicenseRequired, nil}, 1),
|
||||
)
|
||||
|
||||
DescribeTable("downloads using the storefront persisted during purchase", func(refresh bool) {
|
||||
original := appstore.Account{Email: "user@example.com", Password: "password", PasswordToken: "old-token", StoreFront: "143441-1,34"}
|
||||
corrected := original
|
||||
corrected.StoreFront = "143462-1,34"
|
||||
store := &fakeDownloadAppStore{
|
||||
account: original, downloadErrors: []error{appstore.ErrLicenseRequired, nil},
|
||||
purchaseStorefront: corrected.StoreFront,
|
||||
}
|
||||
if refresh {
|
||||
corrected.PasswordToken = "new-token"
|
||||
store.loginAccount = corrected
|
||||
store.purchaseErrors = []error{appstore.ErrPasswordTokenExpired, nil}
|
||||
}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
command := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
command.SetArgs([]string{"--app-id", "42", "--purchase"})
|
||||
command.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
Expect(command.Execute()).To(Succeed())
|
||||
Expect(store.downloadInputs).To(HaveLen(2))
|
||||
Expect(store.downloadInputs[0].Account).To(Equal(original))
|
||||
Expect(store.downloadInputs[1].Account).To(Equal(corrected))
|
||||
if refresh {
|
||||
Expect(store.loginInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs).To(HaveLen(2))
|
||||
Expect(store.purchaseInputs[1].Account).To(Equal(corrected))
|
||||
} else {
|
||||
Expect(store.loginInputs).To(BeEmpty())
|
||||
}
|
||||
}, Entry("immediate success", false), Entry("token refresh after correction", true))
|
||||
|
||||
It("returns an account read error before attempting a download", func() {
|
||||
store := &fakeDownloadAppStore{accountInfoError: errors.New("account unavailable")}
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
@@ -251,22 +283,24 @@ func (f *fakeSinfReplicator) ReplicateSinf(input appstore.ReplicateSinfInput) er
|
||||
}
|
||||
|
||||
type fakeDownloadAppStore struct {
|
||||
account appstore.Account
|
||||
accountInfoCalls int
|
||||
accountInfoError error
|
||||
downloadErrors []error
|
||||
downloadInputs []appstore.DownloadInput
|
||||
loginAccount appstore.Account
|
||||
loginInputs []appstore.LoginInput
|
||||
lookupInputs []appstore.LookupInput
|
||||
lookupOutput appstore.LookupOutput
|
||||
lookupError error
|
||||
purchaseErrors []error
|
||||
purchaseInputs []appstore.PurchaseInput
|
||||
account appstore.Account
|
||||
accountInfoCalls int
|
||||
accountInfoError error
|
||||
downloadErrors []error
|
||||
downloadInputs []appstore.DownloadInput
|
||||
loginAccount appstore.Account
|
||||
loginInputs []appstore.LoginInput
|
||||
lookupInputs []appstore.LookupInput
|
||||
lookupOutput appstore.LookupOutput
|
||||
lookupError error
|
||||
purchaseErrors []error
|
||||
purchaseInputs []appstore.PurchaseInput
|
||||
purchaseStorefront string
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
f.loginInputs = append(f.loginInputs, input)
|
||||
f.account = f.loginAccount
|
||||
|
||||
return appstore.LoginOutput{Account: f.loginAccount}, nil
|
||||
}
|
||||
@@ -295,6 +329,10 @@ func (*fakeDownloadAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.
|
||||
|
||||
func (f *fakeDownloadAppStore) Purchase(input appstore.PurchaseInput) error {
|
||||
f.purchaseInputs = append(f.purchaseInputs, input)
|
||||
if f.purchaseStorefront != "" {
|
||||
f.account.StoreFront = f.purchaseStorefront
|
||||
}
|
||||
|
||||
index := len(f.purchaseInputs) - 1
|
||||
|
||||
if index < len(f.purchaseErrors) && f.purchaseErrors[index] != nil {
|
||||
|
||||
@@ -385,6 +385,73 @@ var _ = Describe("MCP server", func() {
|
||||
}
|
||||
}, Entry("explicit opt in", true), Entry("no opt in", false))
|
||||
|
||||
DescribeTable("uses a purchase-corrected storefront for MCP downloads", func(refresh bool) {
|
||||
account.DirectoryServicesID = "123456"
|
||||
account.StoreFront = "143441-1,34"
|
||||
var downloads []appstore.Account
|
||||
purchases := 0
|
||||
expectedPurchases := 1
|
||||
if refresh {
|
||||
expectedPurchases = 2
|
||||
}
|
||||
store.download = func(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
downloads = append(downloads, input.Account)
|
||||
if purchases < expectedPurchases {
|
||||
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
|
||||
}
|
||||
store.purchase = func(input appstore.PurchaseInput) error {
|
||||
purchases++
|
||||
account.StoreFront = "143462-1,34"
|
||||
if refresh && purchases == 1 {
|
||||
return appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
store.login = func(appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
account.PasswordToken = "new-token"
|
||||
|
||||
return appstore.LoginOutput{Account: account}, nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": true})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(purchases).To(Equal(expectedPurchases))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("purchased", true))
|
||||
Expect(downloads[0].StoreFront).To(Equal("143441-1,34"))
|
||||
Expect(downloads[len(downloads)-1].StoreFront).To(Equal("143462-1,34"))
|
||||
if refresh {
|
||||
Expect(downloads[len(downloads)-1].PasswordToken).To(Equal("new-token"))
|
||||
}
|
||||
}, Entry("immediate success", false), Entry("after token refresh", true))
|
||||
|
||||
DescribeTable("propagates errors after purchasing during an MCP download", func(accountReadFails bool) {
|
||||
failure := errors.New("fixture post-purchase failure")
|
||||
downloads := 0
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
downloads++
|
||||
if downloads == 1 {
|
||||
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{}, failure
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error {
|
||||
if accountReadFails {
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, failure
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": true})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(failure.Error()))
|
||||
}, Entry("reloading the saved account", true), Entry("retrying the download", false))
|
||||
|
||||
It("refreshes an expired session using saved credentials", func() {
|
||||
var login appstore.LoginInput
|
||||
var accounts []appstore.Account
|
||||
|
||||
@@ -217,6 +217,12 @@ func (t *mcpTools) download(ctx context.Context, input mcpDownloadInput) (mcpDow
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
info, accountErr := t.store.AccountInfo()
|
||||
if accountErr != nil {
|
||||
return mcpDownloadOutput{}, accountErr
|
||||
}
|
||||
|
||||
downloadInput.Account = info.Account
|
||||
purchased = true
|
||||
out, err = t.store.Download(downloadInput)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Unicorn 2.1.4's machine_initialize calls init_get_clock for every engine.
|
||||
// On Unix this briefly switches the process-wide use_rt_clock from monotonic
|
||||
// time to wall time, which can make another engine's timeout expire immediately.
|
||||
// Initialize only while no engines are executing; initialized engines can still
|
||||
// execute concurrently, including nested calls from guest callbacks.
|
||||
var engineClock clockState
|
||||
|
||||
type clockState struct {
|
||||
mu sync.Mutex
|
||||
active int
|
||||
idle chan struct{}
|
||||
}
|
||||
|
||||
func (c *clockState) initialize(ctx context.Context, initialize func() error) error {
|
||||
for {
|
||||
c.mu.Lock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
c.mu.Unlock()
|
||||
|
||||
return fmt.Errorf("wait for Unicorn clock: %w", err)
|
||||
}
|
||||
|
||||
if c.active == 0 {
|
||||
err := initialize()
|
||||
c.mu.Unlock()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if c.idle == nil {
|
||||
c.idle = make(chan struct{})
|
||||
}
|
||||
|
||||
idle := c.idle
|
||||
c.mu.Unlock()
|
||||
|
||||
select {
|
||||
case <-idle:
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("wait for Unicorn clock: %w", ctx.Err())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *clockState) beginEmulation() func() {
|
||||
c.mu.Lock()
|
||||
c.active++
|
||||
c.mu.Unlock()
|
||||
|
||||
return func() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
c.active--
|
||||
if c.active == 0 && c.idle != nil {
|
||||
close(c.idle)
|
||||
c.idle = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Unicorn clock initialization", func() {
|
||||
It("waits for every active emulation and permits nested calls while waiting", func() {
|
||||
var clock clockState
|
||||
|
||||
firstDone := clock.beginEmulation()
|
||||
secondDone := clock.beginEmulation()
|
||||
initialized := make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
result <- clock.initialize(context.Background(), func() error {
|
||||
close(initialized)
|
||||
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
|
||||
Consistently(initialized, 20*time.Millisecond).ShouldNot(BeClosed())
|
||||
firstDone()
|
||||
Consistently(initialized, 20*time.Millisecond).ShouldNot(BeClosed())
|
||||
|
||||
nestedDone := clock.beginEmulation()
|
||||
secondDone()
|
||||
Consistently(initialized, 20*time.Millisecond).ShouldNot(BeClosed())
|
||||
nestedDone()
|
||||
Eventually(initialized).Should(BeClosed())
|
||||
|
||||
var err error
|
||||
|
||||
Eventually(result).Should(Receive(&err))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
})
|
||||
|
||||
It("waits for initialization before starting emulation", func() {
|
||||
var clock clockState
|
||||
|
||||
initializing := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
started := make(chan func(), 1)
|
||||
|
||||
go func() {
|
||||
result <- clock.initialize(context.Background(), func() error {
|
||||
close(initializing)
|
||||
<-release
|
||||
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
|
||||
Eventually(initializing).Should(BeClosed())
|
||||
|
||||
go func() { started <- clock.beginEmulation() }()
|
||||
|
||||
Consistently(started, 20*time.Millisecond).ShouldNot(Receive())
|
||||
close(release)
|
||||
|
||||
var done func()
|
||||
|
||||
Eventually(started).Should(Receive(&done))
|
||||
done()
|
||||
|
||||
var err error
|
||||
|
||||
Eventually(result).Should(Receive(&err))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
})
|
||||
|
||||
It("cancels initialization while another engine is executing", func() {
|
||||
var clock clockState
|
||||
|
||||
done := clock.beginEmulation()
|
||||
defer done()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
initialized := make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
result <- clock.initialize(ctx, func() error {
|
||||
close(initialized)
|
||||
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
|
||||
Consistently(result, 20*time.Millisecond).ShouldNot(Receive())
|
||||
cancel()
|
||||
|
||||
var err error
|
||||
|
||||
Eventually(result).Should(Receive(&err))
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(initialized).NotTo(BeClosed())
|
||||
})
|
||||
|
||||
It("releases the clock after initialization fails", func() {
|
||||
var clock clockState
|
||||
|
||||
failure := errors.New("initialization failed")
|
||||
Expect(clock.initialize(context.Background(), func() error { return failure })).To(MatchError(failure))
|
||||
Expect(clock.initialize(context.Background(), func() error { return nil })).To(Succeed())
|
||||
done := clock.beginEmulation()
|
||||
done()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Concurrent Unicorn engines", func() {
|
||||
It("does not time out active engines while initializing other engines", func() {
|
||||
const address = uint64(0x1200000)
|
||||
const count = 8
|
||||
|
||||
engines := make([]*Engine, count)
|
||||
started := make(chan struct{}, count)
|
||||
results := make(chan error, count)
|
||||
|
||||
for i := range engines {
|
||||
engine, err := New(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(engine.Close)
|
||||
engines[i] = engine
|
||||
Expect(engine.MemMap(address, 4096)).To(Succeed())
|
||||
Expect(engine.MemWrite(address, []byte{0, 0, 0, 0x14})).To(Succeed()) // b .
|
||||
|
||||
var deadline time.Time
|
||||
|
||||
_, err = engine.AddCodeHook(address, address, func(uint64, uint32) {
|
||||
if deadline.IsZero() {
|
||||
deadline = time.Now().Add(time.Second)
|
||||
started <- struct{}{}
|
||||
}
|
||||
|
||||
time.Sleep(100 * time.Microsecond)
|
||||
|
||||
if time.Now().After(deadline) {
|
||||
_ = engine.Stop()
|
||||
}
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
}
|
||||
|
||||
for _, engine := range engines {
|
||||
go func() {
|
||||
results <- engine.StartBounded(address, address+4, time.Minute, 0)
|
||||
}()
|
||||
}
|
||||
|
||||
for range count {
|
||||
Eventually(started).Should(Receive())
|
||||
}
|
||||
|
||||
for range 200 {
|
||||
other, err := New(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(other.MemMap(address, 4096)).To(Succeed())
|
||||
Expect(other.Close()).To(Succeed())
|
||||
}
|
||||
|
||||
for range count {
|
||||
var err error
|
||||
|
||||
Eventually(results).Should(Receive(&err))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
queryPageSize = 2
|
||||
queryTimeout = 4
|
||||
controlCPUModel = uint32(7 | 1<<26 | 1<<30)
|
||||
arm64CPUModelMax = uint32(3)
|
||||
@@ -142,6 +143,19 @@ func newEngine(ctx context.Context, loadLibrary func(context.Context) (library,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// uc_open and CPU model selection leave initialization lazy. Force it here
|
||||
// so later memory/register operations cannot reset the shared timeout clock.
|
||||
if err := engineClock.initialize(ctx, func() error {
|
||||
var pageSize uint64
|
||||
|
||||
return engine.err(engine.api.query(engine.handle, queryPageSize, &pageSize))
|
||||
}); err != nil {
|
||||
_ = engine.api.close(engine.handle)
|
||||
_ = library.close()
|
||||
|
||||
return nil, fmt.Errorf("initialize arm64 emulator: %w", err)
|
||||
}
|
||||
|
||||
runtime.SetFinalizer(engine, func(engine *Engine) {
|
||||
_ = engine.Close()
|
||||
})
|
||||
@@ -319,6 +333,9 @@ func (e *Engine) Start(begin, end uint64) error {
|
||||
return err
|
||||
}
|
||||
|
||||
doneEmulation := engineClock.beginEmulation()
|
||||
defer doneEmulation()
|
||||
|
||||
return e.executionError(e.err(e.api.emuStart(handle, begin, end, 0, 0)))
|
||||
}
|
||||
|
||||
@@ -343,6 +360,9 @@ func (e *Engine) StartBounded(begin, end uint64, timeout time.Duration, instruct
|
||||
return err
|
||||
}
|
||||
|
||||
doneEmulation := engineClock.beginEmulation()
|
||||
defer doneEmulation()
|
||||
|
||||
if err := e.executionError(e.err(e.api.emuStart(handle, begin, end, microseconds, instructionLimit))); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ func (e *executor) Send(request apphttp.Request, body []byte) (*http.Response, e
|
||||
direct.Header.Set("User-Agent", apphttp.DefaultUserAgent)
|
||||
}
|
||||
|
||||
return e.backend.requestTransport(emulator.Request{Operation: "authenticate"})(direct)
|
||||
return e.backend.requestTransport(emulator.Request{Operation: "authenticate", Timeout: request.Timeout})(direct)
|
||||
}
|
||||
|
||||
input := emulator.Request{URL: request.URL, Method: request.Method, Operation: e.operation, Format: string(request.ResponseFormat), Timeout: request.Timeout, Body: body, Headers: make(http.Header), NoRedirects: request.NoRedirects, Raw: request.ResponseFormat == apphttp.ResponseFormatRaw}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/store/emulator"
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
@@ -97,6 +98,16 @@ var _ = Describe("Store connection reuse", func() {
|
||||
Expect(err).To(MatchError(ContainSubstring("deadline exceeded")))
|
||||
Expect(get("request", "/").StatusCode).To(Equal(http.StatusOK))
|
||||
})
|
||||
It("honors the public bag request timeout", func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
_, err := backend.Client("bag-direct").Send(apphttp.Request{
|
||||
URL: server.URL + "/slow", Method: http.MethodGet,
|
||||
Context: ctx, Timeout: 20 * time.Millisecond,
|
||||
}, nil)
|
||||
Expect(err).To(MatchError(ContainSubstring("deadline exceeded")))
|
||||
Expect(ctx.Err()).NotTo(HaveOccurred())
|
||||
})
|
||||
It("cancels an active stream without closing an unrelated pooled connection", func() {
|
||||
api := get("request", "/")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
@@ -101,6 +101,10 @@ func (r *Runtime) Execute(input Request) (response *http.Response, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
if input.Operation == "purchase" {
|
||||
r.installTermsActionAdapter()
|
||||
}
|
||||
|
||||
parameters := input.Parameters
|
||||
|
||||
if input.Operation == "authenticate" {
|
||||
|
||||
@@ -44,6 +44,7 @@ type Runtime struct {
|
||||
lastResponse *http.Response
|
||||
transportError error
|
||||
streamResponse, noRedirects, authRequest bool
|
||||
termsActionAdapterInstalled bool
|
||||
|
||||
taskLocalFrames map[uint64][]taskLocalBinding
|
||||
transport func(*http.Request) (*http.Response, error)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package emulator
|
||||
|
||||
import "github.com/majd/ipatool/v2/internal/store/terms"
|
||||
|
||||
// The caller handles account terms over the Store API. Reject only presentation
|
||||
// of that page, allowing Execute to return the original finance response instead
|
||||
// of falling back to AppKit. Other finance actions keep their native behavior.
|
||||
func (r *Runtime) installTermsActionAdapter() {
|
||||
if r.termsActionAdapterInstalled {
|
||||
return
|
||||
}
|
||||
|
||||
const class = "AMSFinanceActionResponse"
|
||||
|
||||
const selector = "handleGotoURL:taskInfo:gotoType:accountURL:tidContinue:retryOnSuccess:"
|
||||
|
||||
implementation := r.lookup(class, selector, true)
|
||||
block := r.hostBlock(func() {
|
||||
if !terms.IsPageURL(r.String(r.arg(2))) {
|
||||
arguments := make([]uint64, 8)
|
||||
for index := range arguments {
|
||||
arguments[index] = r.arg(index)
|
||||
}
|
||||
|
||||
r.callbackFunction(implementation, arguments, func() {})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
failure := r.New("NSError", map[string]uint64{
|
||||
"domain": r.New("NSString", "IPAToolStoreTerms"),
|
||||
"code": r.New("NSNumber", int64(1)),
|
||||
"userInfo": r.New("NSDictionary", map[string]uint64{}),
|
||||
})
|
||||
r.callbackFunction(r.lookup("AMSPromise", "promiseWithError:", true),
|
||||
[]uint64{r.ClassAddress("AMSPromise"), r.selector("promiseWithError:"), failure}, func() {})
|
||||
})
|
||||
r.methods[methodKey(class, selector, true)] = r.read64(block + 16)
|
||||
r.termsActionAdapterInstalled = true
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package emulator
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/store/profile"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
var _ = Describe("Purchase terms presentation", func() {
|
||||
DescribeTable("returns the original terms response to the caller", func(compressed bool) {
|
||||
ctx := context.Background()
|
||||
bundle, err := assets.Load(ctx)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
prepared, err := profile.Load(ctx)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
guest, err := open(ctx, bundle.AppleMediaServices, prepared, true)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(guest.Close)
|
||||
body := []byte(`<plist version="1.0"><dict><key>pings</key><array></array><key>jingleDocType</key><string>buyProductFailure</string><key>jingleAction</key><string>buyProduct</string><key>action</key><dict><key>kind</key><string>Goto</string><key>url</key><string>https://p45-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/termsPage</string><key>target</key><string>main</string></dict></dict></plist>`)
|
||||
headers := http.Header{"Content-Type": {"text/xml; charset=UTF-8"}}
|
||||
var expected map[string]any
|
||||
_, err = plist.Unmarshal(body, &expected)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
if compressed {
|
||||
var buffer bytes.Buffer
|
||||
writer := gzip.NewWriter(&buffer)
|
||||
_, err = writer.Write(body)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(writer.Close()).To(Succeed())
|
||||
body = buffer.Bytes()
|
||||
headers.Set("Content-Encoding", "gzip")
|
||||
}
|
||||
calls := 0
|
||||
response, err := guest.Execute(Request{
|
||||
Operation: "purchase", URL: "https://p45-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/buyProduct", Method: http.MethodPost,
|
||||
HardwareID: []byte{0, 1, 2, 3, 4, 5}, Bag: map[string]any{"buyProduct": "https://buy.itunes.apple.com/request"},
|
||||
Parameters: map[string]any{"price": "0", "productType": "C", "salableAdamId": "1234", "pricingParameters": "STDQ"},
|
||||
Transport: func(request *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
|
||||
return &http.Response{StatusCode: http.StatusOK, Header: headers.Clone(), Body: io.NopCloser(bytes.NewReader(body))}, nil
|
||||
},
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(response.Body.Close)
|
||||
actual, err := io.ReadAll(response.Body)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(calls).To(Equal(1))
|
||||
var decoded map[string]any
|
||||
_, err = plist.Unmarshal(actual, &decoded)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(decoded).To(Equal(expected))
|
||||
Expect(response.Header.Get("Content-Encoding")).To(BeEmpty())
|
||||
}, Entry("plain XML", false), Entry("gzip, as in issue 665", true))
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
// Package terms identifies the Store's account terms flow.
|
||||
package terms
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IsBuyHost accepts the Store purchase service and its numbered account pods.
|
||||
func IsBuyHost(host string) bool {
|
||||
host = strings.ToLower(host)
|
||||
if host == "buy.itunes.apple.com" {
|
||||
return true
|
||||
}
|
||||
|
||||
pod, ok := strings.CutSuffix(host, "-buy.itunes.apple.com")
|
||||
if !ok || len(pod) < 2 || pod[0] != 'p' {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, digit := range pod[1:] {
|
||||
if digit < '0' || digit > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// IsPageURL identifies the terms action returned by buyProduct.
|
||||
func IsPageURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
|
||||
return err == nil && u.Scheme == "https" && IsBuyHost(u.Hostname()) &&
|
||||
(u.Port() == "" || u.Port() == "443") && u.User == nil && u.Fragment == "" && u.RawPath == "" &&
|
||||
u.Path == "/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/termsPage"
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
func purchaseStorefrontCorrection(result purchaseResult, current string) string {
|
||||
if result.FailureType != "-128" || result.Metrics.DialogID != "MZCommerce.CountryMismatch" || result.Dialog.OKButtonAction.Kind != "Goto" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Only interpret Apple's known store-switch action. Do not navigate to a
|
||||
// response-supplied URL or infer a country from localized dialog text.
|
||||
u, err := url.Parse(result.Dialog.OKButtonAction.URL)
|
||||
if err != nil || u.Scheme != "https" || u.Hostname() != "itunes.apple.com" ||
|
||||
(u.Port() != "" && u.Port() != "443") || u.User != nil || u.Fragment != "" || u.RawPath != "" ||
|
||||
u.Path != "/WebObjects/MZStore.woa/wa/resetAndRedirect" {
|
||||
return ""
|
||||
}
|
||||
|
||||
query, err := url.ParseQuery(u.RawQuery)
|
||||
if err != nil || len(query["dsf"]) != 1 {
|
||||
return ""
|
||||
}
|
||||
|
||||
identifier := query.Get("dsf")
|
||||
number, err := strconv.ParseUint(identifier, 10, 32)
|
||||
|
||||
if err != nil || number == 0 || strconv.FormatUint(number, 10) != identifier {
|
||||
return ""
|
||||
}
|
||||
|
||||
current = strings.TrimSpace(current)
|
||||
|
||||
previous := storefrontIdentifier(current)
|
||||
if identifier == previous {
|
||||
return ""
|
||||
}
|
||||
|
||||
// Retain the client's language/platform suffix, changing only the country.
|
||||
return identifier + strings.TrimPrefix(current, previous)
|
||||
}
|
||||
|
||||
func (t *appstore) saveAccountStorefront(dsid, storefront string) error {
|
||||
// Serialize with native login so a correction cannot overwrite fresh tokens.
|
||||
t.authStateMu.Lock()
|
||||
defer t.authStateMu.Unlock()
|
||||
|
||||
if t.keychain == nil || dsid == "" {
|
||||
return errors.New("saved account is required for storefront recovery")
|
||||
}
|
||||
|
||||
info, err := t.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if info.Account.DirectoryServicesID != dsid {
|
||||
return errors.New("saved account changed during storefront recovery")
|
||||
}
|
||||
|
||||
info.Account.StoreFront = storefront
|
||||
|
||||
data, err := json.Marshal(info.Account)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encode corrected account: %w", err)
|
||||
}
|
||||
|
||||
if err := t.keychain.Set("account", data); err != nil {
|
||||
return fmt.Errorf("failed to save corrected account: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *appstore) loginStorefront(result http.Result[loginResult], dsid string) (string, error) {
|
||||
if storefront, err := result.GetHeader(HTTPHeaderStoreFront); err == nil && strings.TrimSpace(storefront) != "" {
|
||||
return storefront, nil
|
||||
}
|
||||
|
||||
// The request-storefront header is an echo, not an account-country update.
|
||||
// Keep a saved storefront for the same DSID when refreshing credentials.
|
||||
if t.keychain != nil {
|
||||
info, err := t.AccountInfo()
|
||||
if err != nil && !errors.Is(err, keyring.ErrKeyNotFound) && !errors.Is(err, fs.ErrNotExist) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if err == nil && dsid != "" && info.Account.DirectoryServicesID == dsid && info.Account.StoreFront != "" {
|
||||
return info.Account.StoreFront, nil
|
||||
}
|
||||
}
|
||||
|
||||
// A first login may supply only this provisional routing hint. A later
|
||||
// CountryMismatch response can establish and persist the actual country.
|
||||
storefront, err := result.GetHeader(HTTPHeaderRequestStoreFront)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get storefront header: %w", err)
|
||||
}
|
||||
|
||||
return storefront, nil
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
// Relevant fields from the decoded response in issue #666.
|
||||
const countryMismatchFixture = `<plist version="1.0"><dict>
|
||||
<key>metrics</key><dict><key>dialogId</key><string>MZCommerce.CountryMismatch</string></dict>
|
||||
<key>failureType</key><string>-128</string>
|
||||
<key>customerMessage</key><string>Account Not In This Store</string>
|
||||
<key>dialog</key><dict>
|
||||
<key>explanation</key><string>Your account is not valid for use in the U.S. store. You must switch to the Japanese store before purchasing.</string>
|
||||
<key>okButtonAction</key><dict><key>kind</key><string>Goto</string>
|
||||
<key>url</key><string>https://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=143462</string></dict>
|
||||
</dict></dict></plist>`
|
||||
|
||||
var _ = Describe("Account storefront recovery", func() {
|
||||
var store *appstore
|
||||
var chain *storefrontTestKeychain
|
||||
var client *http.MockClient[purchaseResult]
|
||||
var loginClient *http.MockClient[loginResult]
|
||||
var account Account
|
||||
var mismatch http.Result[purchaseResult]
|
||||
var input PurchaseInput
|
||||
BeforeEach(func() {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
client = http.NewMockClient[purchaseResult](ctrl)
|
||||
loginClient = http.NewMockClient[loginResult](ctrl)
|
||||
hardware := machine.NewMockMachine(ctrl)
|
||||
hardware.EXPECT().MacAddress().Return("00:01:02:03:04:05", nil).AnyTimes()
|
||||
account = Account{Email: "user@example.com", DirectoryServicesID: "123456", StoreFront: "143441-1,34", PasswordToken: "old-token", Password: "password", Pod: "30", Name: "Test User"}
|
||||
data, err := json.Marshal(account)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
chain = &storefrontTestKeychain{data: data}
|
||||
store = &appstore{keychain: chain, purchaseClient: client, loginClient: loginClient, machine: hardware}
|
||||
input = PurchaseInput{Account: account, App: App{ID: 1234}}
|
||||
mismatch = http.Result[purchaseResult]{StatusCode: 200}
|
||||
_, err = plist.Unmarshal([]byte(countryMismatchFixture), &mismatch.Data)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
})
|
||||
|
||||
DescribeTable("recovers using Apple's account country while preserving client suffixes", func(identifier string) {
|
||||
mismatch.Data.Dialog.OKButtonAction.URL = strings.Replace(mismatch.Data.Dialog.OKButtonAction.URL, "143462", identifier, 1)
|
||||
calls := 0
|
||||
var first http.Request
|
||||
client.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[purchaseResult], error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
first = request
|
||||
|
||||
return mismatch, nil
|
||||
}
|
||||
Expect(request.URL).To(Equal(first.URL))
|
||||
Expect(request.Method).To(Equal(first.Method))
|
||||
Expect(request.Payload).To(Equal(first.Payload))
|
||||
Expect(request.Headers["X-Apple-Store-Front"]).To(Equal(identifier + "-1,34"))
|
||||
Expect(request.Headers["X-Token"]).To(Equal("old-token"))
|
||||
info, err := store.AccountInfo()
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
expected := account
|
||||
expected.StoreFront = identifier + "-1,34"
|
||||
Expect(info.Account).To(Equal(expected))
|
||||
|
||||
return http.Result[purchaseResult]{StatusCode: 200, Data: purchaseResult{JingleDocType: "purchaseSuccess"}}, nil
|
||||
}).Times(2)
|
||||
Expect(store.Purchase(input)).To(Succeed())
|
||||
Expect(chain.writes).To(Equal(1))
|
||||
}, Entry("JP", "143462"), Entry("AE", "143481"), Entry("TR", "143480"))
|
||||
|
||||
It("preserves a correction across token refresh and a new appstore instance", func() {
|
||||
calls := 0
|
||||
client.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[purchaseResult], error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return mismatch, nil
|
||||
}
|
||||
Expect(request.Headers["X-Apple-Store-Front"]).To(Equal("143462-1,34"))
|
||||
if calls == 2 {
|
||||
return http.Result[purchaseResult]{Data: purchaseResult{FailureType: FailureTypePasswordTokenExpired}}, nil
|
||||
}
|
||||
Expect(request.Headers["X-Token"]).To(Equal("new-token"))
|
||||
|
||||
return http.Result[purchaseResult]{StatusCode: 200, Data: purchaseResult{JingleDocType: "purchaseSuccess"}}, nil
|
||||
}).Times(3)
|
||||
Expect(errors.Is(store.Purchase(input), ErrPasswordTokenExpired)).To(BeTrue())
|
||||
loginClient.EXPECT().Send(gomock.Any()).Return(http.Result[loginResult]{StatusCode: 200,
|
||||
Headers: map[string]string{HTTPHeaderRequestStoreFront: "143441-1,34", HTTPHeaderPod: "45"},
|
||||
Data: loginResult{PasswordToken: "new-token", DirectoryServicesID: account.DirectoryServicesID},
|
||||
}, nil)
|
||||
refreshed := &appstore{keychain: chain, loginClient: loginClient, purchaseClient: client, machine: store.machine}
|
||||
acc, err := refreshed.login(account.Email, account.Password, "", "000102030405", testAuthEndpoint, &stubActionSigner{})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(acc.StoreFront).To(Equal("143462-1,34"))
|
||||
Expect(acc.PasswordToken).To(Equal("new-token"))
|
||||
Expect(acc.Pod).To(Equal("45"))
|
||||
info, err := refreshed.AccountInfo()
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(info.Account).To(Equal(acc))
|
||||
input.Account = acc
|
||||
Expect(refreshed.Purchase(input)).To(Succeed())
|
||||
})
|
||||
|
||||
It("stops after one correction even if Apple proposes another country", func() {
|
||||
second := mismatch
|
||||
second.Data.Dialog.OKButtonAction.URL = strings.Replace(second.Data.Dialog.OKButtonAction.URL, "143462", "143480", 1)
|
||||
gomock.InOrder(client.EXPECT().Send(gomock.Any()).Return(mismatch, nil), client.EXPECT().Send(gomock.Any()).Return(second, nil))
|
||||
Expect(store.Purchase(input)).To(MatchError(ContainSubstring("Account Not In This Store")))
|
||||
Expect(chain.writes).To(Equal(1))
|
||||
info, err := store.AccountInfo()
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(info.Account.StoreFront).To(Equal("143462-1,34"))
|
||||
})
|
||||
|
||||
It("preserves the corrected storefront for the Arcade fallback", func() {
|
||||
gomock.InOrder(
|
||||
client.EXPECT().Send(gomock.Any()).Return(mismatch, nil),
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[purchaseResult]{Data: purchaseResult{FailureType: FailureTypeTemporarilyUnavailable}}, nil),
|
||||
client.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[purchaseResult], error) {
|
||||
Expect(request.Headers["X-Apple-Store-Front"]).To(Equal("143462-1,34"))
|
||||
Expect(request.Payload.(*http.XMLPayload).Content["pricingParameters"]).To(Equal(PricingParameterAppleArcade))
|
||||
|
||||
return http.Result[purchaseResult]{Data: purchaseResult{JingleDocType: "purchaseSuccess"}}, nil
|
||||
}),
|
||||
)
|
||||
Expect(store.Purchase(input)).To(Succeed())
|
||||
})
|
||||
|
||||
DescribeTable("does not replay a purchase when its correction cannot be persisted", func(kind string) {
|
||||
switch kind {
|
||||
case "read":
|
||||
chain.readErr = errors.New("keychain read failed")
|
||||
case "write":
|
||||
chain.writeErr = errors.New("keychain write failed")
|
||||
case "different account":
|
||||
chain.data = []byte(`{"directoryServicesIdentifier":"other","storeFront":"143480"}`)
|
||||
case "missing identity":
|
||||
input.Account.DirectoryServicesID = ""
|
||||
}
|
||||
original := string(chain.data)
|
||||
client.EXPECT().Send(gomock.Any()).Return(mismatch, nil).Times(1)
|
||||
Expect(store.Purchase(input)).To(MatchError(ContainSubstring("failed to correct account storefront")))
|
||||
Expect(string(chain.data)).To(Equal(original))
|
||||
Expect(chain.writes).To(BeZero())
|
||||
}, Entry("read error", "read"), Entry("write error", "write"), Entry("account changed", "different account"), Entry("missing DSID", "missing identity"))
|
||||
|
||||
It("retains saved credentials when the caller holds an older account copy", func() {
|
||||
saved := account
|
||||
saved.PasswordToken = "newer-saved-token"
|
||||
var err error
|
||||
chain.data, err = json.Marshal(saved)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
failure := errors.New("connection lost")
|
||||
gomock.InOrder(client.EXPECT().Send(gomock.Any()).Return(mismatch, nil), client.EXPECT().Send(gomock.Any()).Return(http.Result[purchaseResult]{}, failure))
|
||||
Expect(errors.Is(store.Purchase(input), failure)).To(BeTrue())
|
||||
info, err := store.AccountInfo()
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(info.Account.PasswordToken).To(Equal(saved.PasswordToken))
|
||||
Expect(info.Account.StoreFront).To(Equal("143462-1,34"))
|
||||
})
|
||||
|
||||
DescribeTable("ignores malformed or unrelated store-switch URLs", func(actionURL string) {
|
||||
mismatch.Data.Dialog.OKButtonAction.URL = actionURL
|
||||
client.EXPECT().Send(gomock.Any()).Return(mismatch, nil).Times(1)
|
||||
Expect(store.Purchase(input)).To(HaveOccurred())
|
||||
Expect(chain.writes).To(BeZero())
|
||||
},
|
||||
Entry("different host", "https://example.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=143462"),
|
||||
Entry("host suffix", "https://itunes.apple.com.example.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=143462"),
|
||||
Entry("HTTP", "http://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=143462"),
|
||||
Entry("credentials", "https://user@itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=143462"),
|
||||
Entry("port", "https://itunes.apple.com:8080/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=143462"),
|
||||
Entry("terms", "https://itunes.apple.com/WebObjects/MZFinance.woa/wa/termsPage?dsf=143462"),
|
||||
Entry("encoded path", "https://itunes.apple.com/WebObjects/MZStore.woa/wa/%72esetAndRedirect?dsf=143462"),
|
||||
Entry("missing country", "https://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect"),
|
||||
Entry("empty country", "https://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf="),
|
||||
Entry("duplicate country", "https://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=143462&dsf=143480"),
|
||||
Entry("invalid query", "https://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=%zz"),
|
||||
Entry("zero", "https://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=0"),
|
||||
Entry("overflow", "https://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=99999999999999999999"),
|
||||
Entry("suffix in country", "https://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=143462-1,34"),
|
||||
Entry("fragment", "https://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=143462#other"),
|
||||
Entry("unchanged country", "https://itunes.apple.com/WebObjects/MZStore.woa/wa/resetAndRedirect?dsf=143441"),
|
||||
)
|
||||
|
||||
DescribeTable("requires an explicit CountryMismatch rejection", func(kind string) {
|
||||
switch kind {
|
||||
case "metrics":
|
||||
mismatch.Data.Metrics.DialogID = "MZCommerce.AccountDisabled"
|
||||
case "failure":
|
||||
mismatch.Data.FailureType = "other"
|
||||
case "action":
|
||||
mismatch.Data.Dialog.OKButtonAction.Kind = "OpenURL"
|
||||
case "status":
|
||||
mismatch.StatusCode = 403
|
||||
}
|
||||
client.EXPECT().Send(gomock.Any()).Return(mismatch, nil).Times(1)
|
||||
Expect(store.Purchase(input)).To(HaveOccurred())
|
||||
Expect(chain.writes).To(BeZero())
|
||||
}, Entry("unrelated dialog", "metrics"), Entry("unrelated failure", "failure"), Entry("unrelated action", "action"), Entry("non-success HTTP status", "status"))
|
||||
})
|
||||
|
||||
var _ = Describe("Login storefront selection", func() {
|
||||
DescribeTable("keeps saved storefronts only for the same account when Apple supplies an echo", func(savedID, explicit, echo, expected string) {
|
||||
chain := &storefrontTestKeychain{}
|
||||
if savedID != "" {
|
||||
var err error
|
||||
chain.data, err = json.Marshal(Account{DirectoryServicesID: savedID, StoreFront: "143462-1,34"})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
}
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
client := http.NewMockClient[loginResult](ctrl)
|
||||
headers := map[string]string{}
|
||||
if explicit != "" {
|
||||
headers[HTTPHeaderStoreFront] = explicit
|
||||
}
|
||||
if echo != "" {
|
||||
headers[HTTPHeaderRequestStoreFront] = echo
|
||||
}
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[loginResult]{StatusCode: 200, Headers: headers, Data: loginResult{DirectoryServicesID: "123456", PasswordToken: "new-token"}}, nil)
|
||||
store := &appstore{keychain: chain, loginClient: client}
|
||||
account, err := store.login("user@example.com", "password", "", "000102030405", testAuthEndpoint, &stubActionSigner{})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(account.StoreFront).To(Equal(expected))
|
||||
Expect(account.PasswordToken).To(Equal("new-token"))
|
||||
},
|
||||
Entry("same account, misleading echo", "123456", "", "143441-1,34", "143462-1,34"),
|
||||
Entry("same account, missing storefront headers", "123456", "", "", "143462-1,34"),
|
||||
Entry("authoritative update", "123456", "143480-1,34", "143441-1,34", "143480-1,34"),
|
||||
Entry("different account", "654321", "", "143441-1,34", "143441-1,34"),
|
||||
Entry("first login", "", "", "143441-1,34", "143441-1,34"),
|
||||
)
|
||||
|
||||
It("does not overwrite saved state when reading it fails", func() {
|
||||
chain := &storefrontTestKeychain{readErr: errors.New("keychain unavailable")}
|
||||
store := &appstore{keychain: chain}
|
||||
_, err := store.loginStorefront(http.Result[loginResult]{Headers: map[string]string{HTTPHeaderRequestStoreFront: "143441"}}, "123456")
|
||||
Expect(err).To(MatchError(ContainSubstring("keychain unavailable")))
|
||||
Expect(chain.writes).To(BeZero())
|
||||
})
|
||||
})
|
||||
|
||||
type storefrontTestKeychain struct {
|
||||
data []byte
|
||||
readErr, writeErr error
|
||||
writes int
|
||||
}
|
||||
|
||||
func (k *storefrontTestKeychain) Get(key string) ([]byte, error) {
|
||||
if k.readErr != nil {
|
||||
return nil, k.readErr
|
||||
}
|
||||
|
||||
if key != "account" || k.data == nil {
|
||||
return nil, keyring.ErrKeyNotFound
|
||||
}
|
||||
|
||||
return append([]byte(nil), k.data...), nil
|
||||
}
|
||||
func (k *storefrontTestKeychain) Set(key string, data []byte) error {
|
||||
if k.writeErr != nil {
|
||||
return k.writeErr
|
||||
}
|
||||
|
||||
if key != "account" {
|
||||
return fmt.Errorf("unexpected key %q", key)
|
||||
}
|
||||
|
||||
k.data = append([]byte(nil), data...)
|
||||
k.writes++
|
||||
|
||||
return nil
|
||||
}
|
||||
func (k *storefrontTestKeychain) Remove(string) error {
|
||||
k.data = nil
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -47,13 +47,16 @@ type appstore struct {
|
||||
loginClient http.Client[loginResult]
|
||||
searchClient http.Client[searchResult]
|
||||
purchaseClient http.Client[purchaseResult]
|
||||
termsClient http.Client[termsResult]
|
||||
downloadClient http.Client[downloadResult]
|
||||
kbsyncGenerator kbsyncGenerator
|
||||
kbsyncCache kbsyncCache
|
||||
platformClient http.Client[platformVersionLookupResult]
|
||||
storefrontClient http.Client[[]byte]
|
||||
storefrontBagClient http.Client[storefrontBagResult]
|
||||
storefrontsMu sync.Mutex
|
||||
storefrontCountryCodes map[string]string
|
||||
storefrontListLoaded bool
|
||||
bagClient http.Client[bagResult]
|
||||
ownedAppsClient http.Client[[]byte]
|
||||
httpClient http.Client[interface{}]
|
||||
@@ -101,10 +104,12 @@ func NewAppStore(args Args) AppStore {
|
||||
loginClient: http.NewClient[loginResult](http.Args{CookieJar: args.CookieJar, Authentication: true, Executor: backend.Client("authenticate")}),
|
||||
searchClient: http.NewClient[searchResult](clientArgs),
|
||||
purchaseClient: http.NewClient[purchaseResult](http.Args{CookieJar: args.CookieJar, Executor: backend.Client("purchase")}),
|
||||
termsClient: http.NewClient[termsResult](http.Args{CookieJar: args.CookieJar, Timeout: http.DefaultAuthenticationTimeout, Executor: backend.Client("request")}),
|
||||
downloadClient: http.NewClient[downloadResult](clientArgs),
|
||||
kbsyncGenerator: defaultKBSyncGenerator,
|
||||
platformClient: http.NewClient[platformVersionLookupResult](clientArgs),
|
||||
storefrontClient: http.NewClient[[]byte](clientArgs),
|
||||
storefrontBagClient: http.NewClient[storefrontBagResult](http.Args{CookieJar: args.CookieJar, Timeout: http.DefaultAuthenticationTimeout, Executor: backend.Client("bag-direct")}),
|
||||
bagClient: http.NewClient[bagResult](http.Args{CookieJar: args.CookieJar, Timeout: http.DefaultAuthenticationTimeout, Executor: backend.Client("bag-direct")}),
|
||||
ownedAppsClient: http.NewClient[[]byte](clientArgs),
|
||||
httpClient: http.NewClient[interface{}](http.Args{CookieJar: args.CookieJar, Executor: backend.Client("transfer")}),
|
||||
|
||||
@@ -70,7 +70,7 @@ func (t *appstore) bag(guid string) (BagOutput, error) {
|
||||
return BagOutput{AuthEndpoint: config.AuthEndpoint, SAPConfig: config}, nil
|
||||
}
|
||||
|
||||
// Download endpoints do not require the authentication-specific SAP configuration.
|
||||
// Service endpoint discovery does not require the authentication-specific SAP configuration.
|
||||
func (t *appstore) fetchURLBag(guid string) (urlBag, error) {
|
||||
res, err := t.bagClient.Send(t.bagRequest(guid))
|
||||
if err != nil {
|
||||
@@ -82,11 +82,19 @@ func (t *appstore) fetchURLBag(guid string) (urlBag, error) {
|
||||
}
|
||||
|
||||
bag := res.Data.URLBag
|
||||
if bag.TermsInfoEndpoint == "" {
|
||||
bag.TermsInfoEndpoint = res.Data.TermsInfoEndpoint
|
||||
}
|
||||
|
||||
if bag.TermsCheckEndpoint == "" {
|
||||
bag.TermsCheckEndpoint = res.Data.TermsCheckEndpoint
|
||||
}
|
||||
|
||||
if bag.AuthEndpoint != "" || bag.EntDownloadEndpoint != "" ||
|
||||
bag.RedownloadEndpoint != "" || bag.UpdateEndpoint != "" ||
|
||||
bag.SAPSetupEndpoint != "" || bag.SAPSetupCertEndpoint != "" ||
|
||||
bag.SAPVersion != "" {
|
||||
return res.Data.URLBag, nil
|
||||
return bag, nil
|
||||
}
|
||||
|
||||
return urlBag{
|
||||
@@ -97,6 +105,8 @@ func (t *appstore) fetchURLBag(guid string) (urlBag, error) {
|
||||
SAPSetupEndpoint: res.Data.SAPSetupEndpoint,
|
||||
SAPSetupCertEndpoint: res.Data.SAPSetupCertEndpoint,
|
||||
SAPVersion: res.Data.SAPVersion,
|
||||
TermsInfoEndpoint: bag.TermsInfoEndpoint,
|
||||
TermsCheckEndpoint: bag.TermsCheckEndpoint,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -109,6 +119,8 @@ type bagResult struct {
|
||||
SAPSetupEndpoint string `plist:"sign-sap-setup,omitempty"`
|
||||
SAPSetupCertEndpoint string `plist:"sign-sap-setup-cert,omitempty"`
|
||||
SAPVersion string `plist:"sign-sap-version,omitempty"`
|
||||
TermsInfoEndpoint string `plist:"getTermsByCountryAndTypeSrv,omitempty"`
|
||||
TermsCheckEndpoint string `plist:"terms-check,omitempty"`
|
||||
}
|
||||
|
||||
type urlBag struct {
|
||||
@@ -119,6 +131,8 @@ type urlBag struct {
|
||||
SAPSetupEndpoint string `plist:"sign-sap-setup,omitempty"`
|
||||
SAPSetupCertEndpoint string `plist:"sign-sap-setup-cert,omitempty"`
|
||||
SAPVersion string `plist:"sign-sap-version,omitempty"`
|
||||
TermsInfoEndpoint string `plist:"getTermsByCountryAndTypeSrv,omitempty"`
|
||||
TermsCheckEndpoint string `plist:"terms-check,omitempty"`
|
||||
}
|
||||
|
||||
func validateSAPConfig(config SAPConfig) error {
|
||||
@@ -177,8 +191,13 @@ func validateAuthenticationEndpoint(endpoint string) error {
|
||||
}
|
||||
|
||||
func (*appstore) bagRequest(guid string) http.Request {
|
||||
endpoint := fmt.Sprintf("https://%s%s?ix=6", PrivateInitDomain, PrivateInitPath)
|
||||
if guid != "" {
|
||||
endpoint += "&guid=" + url.QueryEscape(guid)
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s?ix=6&guid=%s", PrivateInitDomain, PrivateInitPath, guid),
|
||||
URL: endpoint,
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
|
||||
@@ -165,6 +165,26 @@ var _ = Describe("HTTPRangeReaderAt", func() {
|
||||
Expect(string(buf[:n])).To(Equal("ef"))
|
||||
Expect(rangeLog).To(ContainElement("bytes=4-5"))
|
||||
})
|
||||
|
||||
It("serves small sequential reads from one read-ahead request", func() {
|
||||
data := bytes.Repeat([]byte("0123456789abcdef"), 4096)
|
||||
rangeLog := []string{}
|
||||
server, _, _ := testIPAServerWithRangeLog(data, &rangeLog)
|
||||
defer server.Close()
|
||||
|
||||
reader, _, err := newHTTPRangeReaderAt(newDownloadTestClient(), server.URL)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
buf := make([]byte, 4096)
|
||||
for off := int64(1024); off+int64(len(buf)) <= int64(len(data)); off += int64(len(buf)) {
|
||||
n, err := reader.ReadAt(buf, off)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(buf[:n]).To(Equal(data[off : off+int64(n)]))
|
||||
}
|
||||
|
||||
// The first entry is the size probe made when the reader is opened.
|
||||
Expect(rangeLog).To(Equal([]string{"bytes=0-0", fmt.Sprintf("bytes=1024-%d", len(data)-1)}))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("AppStore (GetVersionMetadata)", func() {
|
||||
|
||||
@@ -234,15 +234,6 @@ func (t *appstore) login(email, password, authCode, guid, endpoint string, signe
|
||||
request = t.loginRequest(email, password, authCode, guid, request.URL, attempt, signer)
|
||||
}
|
||||
|
||||
sf, err := res.GetHeader(HTTPHeaderStoreFront)
|
||||
if errors.Is(err, http.ErrHeaderNotFound) {
|
||||
sf, err = res.GetHeader(HTTPHeaderRequestStoreFront)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return Account{}, NewErrorWithMetadata(fmt.Errorf("failed to get storefront header: %w", err), res)
|
||||
}
|
||||
|
||||
pod, err := res.GetHeader(HTTPHeaderPod)
|
||||
if err != nil && !errors.Is(err, http.ErrHeaderNotFound) {
|
||||
return Account{}, NewErrorWithMetadata(fmt.Errorf("failed to get pod header: %w", err), res)
|
||||
@@ -259,6 +250,11 @@ func (t *appstore) login(email, password, authCode, guid, endpoint string, signe
|
||||
return Account{}, NewErrorWithMetadata(errors.New("apple returned no directory services identifier"), res)
|
||||
}
|
||||
|
||||
sf, err := t.loginStorefront(res, directoryServicesID)
|
||||
if err != nil {
|
||||
return Account{}, NewErrorWithMetadata(err, res)
|
||||
}
|
||||
|
||||
accountEmail := res.Data.Account.Email
|
||||
if accountEmail == "" {
|
||||
accountEmail = email
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
@@ -31,10 +32,19 @@ type versionMetadata struct {
|
||||
ReleaseDate time.Time
|
||||
}
|
||||
|
||||
// rangeReaderReadAhead is the minimum size of a remote read. archive/zip parses the central
|
||||
// directory through a 4 KiB bufio.Reader, and every request made through the Store client
|
||||
// runs in the emulator, so each miss reads ahead and later reads are served from memory.
|
||||
const rangeReaderReadAhead int64 = 1 << 20
|
||||
|
||||
type httpRangeReaderAt struct {
|
||||
client apphttp.Client[interface{}]
|
||||
url string
|
||||
size int64
|
||||
|
||||
mu sync.Mutex
|
||||
windowStart int64
|
||||
window []byte
|
||||
}
|
||||
|
||||
func newHTTPRangeReaderAt(client apphttp.Client[interface{}], url string) (*httpRangeReaderAt, int64, error) {
|
||||
@@ -76,35 +86,47 @@ func remoteFileSize(client apphttp.Client[interface{}], url string) (int64, erro
|
||||
return 0, fmt.Errorf("expected partial content response, got status %d", res.StatusCode)
|
||||
}
|
||||
|
||||
size, err := parseContentRangeSize(res.Header.Get("Content-Range"))
|
||||
start, end, size, err := parseContentRange(res.Header.Get("Content-Range"))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if start != 0 || end != 0 {
|
||||
return 0, fmt.Errorf("unexpected content range for size probe: bytes %d-%d/%d", start, end, size)
|
||||
}
|
||||
|
||||
return size, nil
|
||||
}
|
||||
|
||||
func parseContentRangeSize(header string) (int64, error) {
|
||||
func parseContentRange(header string) (int64, int64, int64, error) {
|
||||
if header == "" {
|
||||
return 0, errors.New("content range is empty")
|
||||
return 0, 0, 0, errors.New("content range is empty")
|
||||
}
|
||||
|
||||
slash := strings.LastIndex(header, "/")
|
||||
if slash == -1 || slash == len(header)-1 {
|
||||
return 0, fmt.Errorf("invalid content range: %s", header)
|
||||
unitAndRange, sizeText, ok := strings.Cut(header, "/")
|
||||
if !ok {
|
||||
return 0, 0, 0, fmt.Errorf("invalid content range: %s", header)
|
||||
}
|
||||
|
||||
sizeText := header[slash+1:]
|
||||
if sizeText == "*" {
|
||||
return 0, fmt.Errorf("invalid content range size: %s", sizeText)
|
||||
rangeText, ok := strings.CutPrefix(unitAndRange, "bytes ")
|
||||
if !ok {
|
||||
return 0, 0, 0, fmt.Errorf("invalid content range: %s", header)
|
||||
}
|
||||
|
||||
size, err := strconv.ParseInt(sizeText, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to parse content range size: %w", err)
|
||||
startText, endText, ok := strings.Cut(rangeText, "-")
|
||||
if !ok {
|
||||
return 0, 0, 0, fmt.Errorf("invalid content range: %s", header)
|
||||
}
|
||||
|
||||
return size, nil
|
||||
start, startErr := strconv.ParseInt(startText, 10, 64)
|
||||
end, endErr := strconv.ParseInt(endText, 10, 64)
|
||||
size, sizeErr := strconv.ParseInt(sizeText, 10, 64)
|
||||
|
||||
if startErr != nil || endErr != nil || sizeErr != nil || start < 0 || end < start || end >= size {
|
||||
return 0, 0, 0, fmt.Errorf("invalid content range: %s", header)
|
||||
}
|
||||
|
||||
return start, end, size, nil
|
||||
}
|
||||
|
||||
func (r *httpRangeReaderAt) ReadAt(p []byte, off int64) (int, error) {
|
||||
@@ -120,24 +142,55 @@ func (r *httpRangeReaderAt) ReadAt(p []byte, off int64) (int, error) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
requestEnd := off + int64(len(p)) - 1
|
||||
rangeEnd := requestEnd
|
||||
readLength := min(int64(len(p)), r.size-off)
|
||||
end := off + readLength
|
||||
|
||||
if rangeEnd >= r.size {
|
||||
rangeEnd = r.size - 1
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
windowStart, window := r.windowStart, r.window
|
||||
|
||||
var readErr error
|
||||
|
||||
if off < r.windowStart || end > r.windowStart+int64(len(r.window)) {
|
||||
fetchEnd := off + min(max(int64(len(p)), rangeReaderReadAhead), r.size-off)
|
||||
|
||||
window, readErr = r.fetch(off, fetchEnd-1)
|
||||
windowStart = off
|
||||
|
||||
// Only complete responses become cache entries. A valid partial prefix
|
||||
// can still satisfy this read without replacing the previous window.
|
||||
if readErr == nil {
|
||||
r.windowStart = windowStart
|
||||
r.window = window
|
||||
}
|
||||
}
|
||||
|
||||
n := copy(p[:readLength], window[off-windowStart:])
|
||||
if int64(n) < readLength {
|
||||
return n, readErr
|
||||
}
|
||||
|
||||
if n < len(p) {
|
||||
return n, io.EOF
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// fetch downloads bytes start...stop (inclusive) with a single range request.
|
||||
func (r *httpRangeReaderAt) fetch(start, stop int64) ([]byte, error) {
|
||||
req, err := r.client.NewRequest("GET", r.url, nil)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create request: %w", err)
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept-Encoding", "identity")
|
||||
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", off, rangeEnd))
|
||||
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, stop))
|
||||
|
||||
res, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("request failed: %w", err)
|
||||
return nil, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res != nil && res.Body != nil {
|
||||
@@ -145,25 +198,26 @@ func (r *httpRangeReaderAt) ReadAt(p []byte, off int64) (int, error) {
|
||||
}
|
||||
|
||||
if res.StatusCode != http.StatusPartialContent {
|
||||
return 0, fmt.Errorf("expected partial content response, got status %d", res.StatusCode)
|
||||
}
|
||||
|
||||
readLength := int(rangeEnd-off) + 1
|
||||
|
||||
n, err := io.ReadFull(res.Body, p[:readLength])
|
||||
if err == io.ErrUnexpectedEOF || err == io.EOF {
|
||||
return n, io.EOF
|
||||
return nil, fmt.Errorf("expected partial content response, got status %d", res.StatusCode)
|
||||
}
|
||||
|
||||
actualStart, actualStop, actualSize, err := parseContentRange(res.Header.Get("Content-Range"))
|
||||
if err != nil {
|
||||
return n, fmt.Errorf("failed to read response body: %w", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if requestEnd >= r.size {
|
||||
return n, io.EOF
|
||||
if actualStart != start || actualStop != stop || actualSize != r.size {
|
||||
return nil, fmt.Errorf("unexpected content range: bytes %d-%d/%d, expected bytes %d-%d/%d", actualStart, actualStop, actualSize, start, stop, r.size)
|
||||
}
|
||||
|
||||
return n, nil
|
||||
data := make([]byte, stop-start+1)
|
||||
|
||||
n, err := io.ReadFull(res.Body, data)
|
||||
if err != nil {
|
||||
return data[:n], fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (t *appstore) readVersionMetadataFromIPA(url string) (versionMetadata, error) {
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
gohttp "net/http"
|
||||
"strings"
|
||||
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
func testRangeResponseReader(size int64, respond func(*gohttp.Request) *gohttp.Response) *httpRangeReaderAt {
|
||||
client := apphttp.NewMockClient[interface{}](gomock.NewController(GinkgoT()))
|
||||
client.EXPECT().NewRequest(gohttp.MethodGet, "https://example.test/app.ipa", nil).
|
||||
DoAndReturn(gohttp.NewRequest).AnyTimes()
|
||||
client.EXPECT().Do(gomock.Any()).DoAndReturn(func(request *gohttp.Request) (*gohttp.Response, error) {
|
||||
return respond(request), nil
|
||||
}).AnyTimes()
|
||||
|
||||
return &httpRangeReaderAt{client: client, url: "https://example.test/app.ipa", size: size}
|
||||
}
|
||||
|
||||
var _ = Describe("HTTP range read-ahead", func() {
|
||||
var data []byte
|
||||
|
||||
BeforeEach(func() {
|
||||
data = make([]byte, 2*rangeReaderReadAhead)
|
||||
for i := range data {
|
||||
data[i] = byte(i % 251)
|
||||
}
|
||||
})
|
||||
|
||||
It("refills a read that crosses the cached window", func() {
|
||||
ranges := []string{}
|
||||
server, _, _ := testIPAServerWithRangeLog(data, &ranges)
|
||||
defer server.Close()
|
||||
reader, _, err := newHTTPRangeReaderAt(newDownloadTestClient(), server.URL)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
buffer := make([]byte, 4096)
|
||||
for _, offset := range []int64{0, rangeReaderReadAhead - 2048, rangeReaderReadAhead} {
|
||||
count, err := reader.ReadAt(buffer, offset)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(len(buffer)))
|
||||
Expect(buffer).To(Equal(data[offset : offset+int64(len(buffer))]))
|
||||
}
|
||||
|
||||
Expect(ranges).To(Equal([]string{
|
||||
"bytes=0-0",
|
||||
fmt.Sprintf("bytes=0-%d", rangeReaderReadAhead-1),
|
||||
fmt.Sprintf("bytes=%d-%d", rangeReaderReadAhead-2048, 2*rangeReaderReadAhead-2049),
|
||||
}))
|
||||
})
|
||||
|
||||
It("refills backward reads and isolates cached data from caller mutation", func() {
|
||||
ranges := []string{}
|
||||
server, _, _ := testIPAServerWithRangeLog(data, &ranges)
|
||||
defer server.Close()
|
||||
reader, _, err := newHTTPRangeReaderAt(newDownloadTestClient(), server.URL)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
buffer := make([]byte, 4096)
|
||||
for _, offset := range []int64{rangeReaderReadAhead, 0, 0} {
|
||||
clear(buffer)
|
||||
count, err := reader.ReadAt(buffer, offset)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(len(buffer)))
|
||||
Expect(buffer).To(Equal(data[offset : offset+int64(len(buffer))]))
|
||||
}
|
||||
|
||||
Expect(ranges).To(HaveLen(3))
|
||||
})
|
||||
|
||||
It("preserves EOF behavior when reads are served from the cache", func() {
|
||||
ranges := []string{}
|
||||
server, _, _ := testIPAServerWithRangeLog([]byte("abcdef"), &ranges)
|
||||
defer server.Close()
|
||||
reader, size, err := newHTTPRangeReaderAt(newDownloadTestClient(), server.URL)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
_, err = reader.ReadAt(make([]byte, 1), 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
buffer := make([]byte, 4)
|
||||
count, err := reader.ReadAt(buffer, 4)
|
||||
Expect(err).To(Equal(io.EOF))
|
||||
Expect(count).To(Equal(2))
|
||||
Expect(string(buffer[:count])).To(Equal("ef"))
|
||||
|
||||
count, err = reader.ReadAt(buffer[:2], 4)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(2))
|
||||
|
||||
count, err = reader.ReadAt(buffer, size)
|
||||
Expect(err).To(Equal(io.EOF))
|
||||
Expect(count).To(BeZero())
|
||||
Expect(ranges).To(Equal([]string{"bytes=0-0", "bytes=0-5"}))
|
||||
})
|
||||
|
||||
It("supports independent concurrent reads", func() {
|
||||
server, _, _ := testIPAServer(data)
|
||||
defer server.Close()
|
||||
reader, _, err := newHTTPRangeReaderAt(newDownloadTestClient(), server.URL)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
finished := make(chan error, 8)
|
||||
for i := range 8 {
|
||||
go func() {
|
||||
offset := int64(i * 200000)
|
||||
buffer := make([]byte, 4096)
|
||||
_, err := reader.ReadAt(buffer, offset)
|
||||
if err == nil && !bytes.Equal(buffer, data[offset:offset+int64(len(buffer))]) {
|
||||
err = errors.New("incorrect concurrent range")
|
||||
}
|
||||
|
||||
finished <- err
|
||||
}()
|
||||
}
|
||||
|
||||
for range 8 {
|
||||
Eventually(finished).Should(Receive(BeNil()))
|
||||
}
|
||||
})
|
||||
|
||||
DescribeTable("preserves received bytes when read-ahead is interrupted", func(body string, expectedErr error) {
|
||||
calls := 0
|
||||
reader := testRangeResponseReader(rangeReaderReadAhead, func(*gohttp.Request) *gohttp.Response {
|
||||
calls++
|
||||
|
||||
return &gohttp.Response{
|
||||
StatusCode: gohttp.StatusPartialContent,
|
||||
Header: gohttp.Header{"Content-Range": []string{fmt.Sprintf("bytes 0-%d/%d", rangeReaderReadAhead-1, rangeReaderReadAhead)}},
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
})
|
||||
|
||||
for range 2 {
|
||||
buffer := make([]byte, 4)
|
||||
count, err := reader.ReadAt(buffer, 0)
|
||||
if expectedErr == nil {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
} else {
|
||||
Expect(errors.Is(err, expectedErr)).To(BeTrue())
|
||||
}
|
||||
|
||||
Expect(count).To(Equal(min(len(body), len(buffer))))
|
||||
Expect(string(buffer[:count])).To(Equal(body[:count]))
|
||||
}
|
||||
|
||||
Expect(calls).To(Equal(2))
|
||||
},
|
||||
Entry("a complete requested prefix", "abcd", nil),
|
||||
Entry("some speculative bytes", "abcdef", nil),
|
||||
Entry("an incomplete requested prefix", "abc", io.ErrUnexpectedEOF),
|
||||
Entry("an empty response body", "", io.EOF),
|
||||
)
|
||||
|
||||
It("retains the previous cache after an interrupted read-ahead request", func() {
|
||||
calls := 0
|
||||
reader := testRangeResponseReader(2*rangeReaderReadAhead, func(request *gohttp.Request) *gohttp.Response {
|
||||
calls++
|
||||
start, stop, err := testRangeBounds(request.Header.Get("Range"), int(2*rangeReaderReadAhead))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
body := []byte("bcde")
|
||||
if start == 0 {
|
||||
body = bytes.Repeat([]byte("a"), int(rangeReaderReadAhead))
|
||||
}
|
||||
|
||||
return &gohttp.Response{
|
||||
StatusCode: gohttp.StatusPartialContent,
|
||||
Header: gohttp.Header{"Content-Range": []string{fmt.Sprintf("bytes %d-%d/%d", start, stop, 2*rangeReaderReadAhead)}},
|
||||
Body: io.NopCloser(bytes.NewReader(body)),
|
||||
}
|
||||
})
|
||||
|
||||
buffer := make([]byte, 4)
|
||||
for _, offset := range []int64{0, rangeReaderReadAhead, 0} {
|
||||
_, err := reader.ReadAt(buffer, offset)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
if offset == 0 {
|
||||
Expect(string(buffer)).To(Equal("aaaa"))
|
||||
} else {
|
||||
Expect(string(buffer)).To(Equal("bcde"))
|
||||
}
|
||||
}
|
||||
|
||||
Expect(calls).To(Equal(2))
|
||||
})
|
||||
|
||||
DescribeTable("rejects invalid response ranges before caching", func(header string) {
|
||||
calls := 0
|
||||
reader := testRangeResponseReader(32, func(*gohttp.Request) *gohttp.Response {
|
||||
calls++
|
||||
|
||||
return &gohttp.Response{
|
||||
StatusCode: gohttp.StatusPartialContent,
|
||||
Header: gohttp.Header{"Content-Range": []string{header}},
|
||||
Body: io.NopCloser(strings.NewReader(strings.Repeat("x", 28))),
|
||||
}
|
||||
})
|
||||
|
||||
buffer := make([]byte, 4)
|
||||
count, err := reader.ReadAt(buffer, 4)
|
||||
Expect(err).To(MatchError(ContainSubstring("content range")))
|
||||
Expect(count).To(BeZero())
|
||||
|
||||
header = "bytes 4-31/32"
|
||||
count, err = reader.ReadAt(buffer, 4)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(4))
|
||||
Expect(string(buffer)).To(Equal("xxxx"))
|
||||
Expect(calls).To(Equal(2))
|
||||
},
|
||||
Entry("missing header", ""),
|
||||
Entry("wrong start", "bytes 5-31/32"),
|
||||
Entry("wrong end", "bytes 4-30/32"),
|
||||
Entry("wrong file size", "bytes 4-31/33"),
|
||||
Entry("unknown file size", "bytes 4-31/*"),
|
||||
Entry("wrong unit", "items 4-31/32"),
|
||||
Entry("negative start", "bytes -4-31/32"),
|
||||
Entry("reversed bounds", "bytes 31-4/32"),
|
||||
Entry("end beyond EOF", "bytes 4-32/32"),
|
||||
)
|
||||
|
||||
It("clamps EOF reads without overflowing large offsets", func() {
|
||||
reader := testRangeResponseReader(math.MaxInt64, func(request *gohttp.Request) *gohttp.Response {
|
||||
Expect(request.Header.Get("Range")).To(Equal(fmt.Sprintf("bytes=%d-%d", int64(math.MaxInt64-4), int64(math.MaxInt64-1))))
|
||||
|
||||
return &gohttp.Response{
|
||||
StatusCode: gohttp.StatusPartialContent,
|
||||
Header: gohttp.Header{"Content-Range": []string{fmt.Sprintf("bytes %d-%d/%d", int64(math.MaxInt64-4), int64(math.MaxInt64-1), int64(math.MaxInt64))}},
|
||||
Body: io.NopCloser(strings.NewReader("tail")),
|
||||
}
|
||||
})
|
||||
|
||||
buffer := make([]byte, 8)
|
||||
count, err := reader.ReadAt(buffer, math.MaxInt64-4)
|
||||
Expect(err).To(Equal(io.EOF))
|
||||
Expect(count).To(Equal(4))
|
||||
Expect(string(buffer[:count])).To(Equal("tail"))
|
||||
})
|
||||
})
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
gohttp "net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/store/terms"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
@@ -34,10 +35,10 @@ func (t *appstore) Purchase(input PurchaseInput) error {
|
||||
return errors.New("purchasing paid apps is not supported")
|
||||
}
|
||||
|
||||
err = t.purchaseWithParams(input.Account, input.App, guid, PricingParameterAppStore)
|
||||
err = t.purchaseWithParams(&input.Account, input.App, guid, PricingParameterAppStore)
|
||||
if err != nil {
|
||||
if input.Platform != PlatformMacOS && err == ErrTemporarilyUnavailable {
|
||||
err = t.purchaseWithParams(input.Account, input.App, guid, PricingParameterAppleArcade)
|
||||
err = t.purchaseWithParams(&input.Account, input.App, guid, PricingParameterAppleArcade)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to purchase item with param '%s': %w", PricingParameterAppleArcade, err)
|
||||
}
|
||||
@@ -56,14 +57,58 @@ type purchaseResult struct {
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
JingleDocType string `plist:"jingleDocType,omitempty"`
|
||||
Status int `plist:"status,omitempty"`
|
||||
Metrics struct {
|
||||
DialogID string `plist:"dialogId,omitempty"`
|
||||
} `plist:"metrics,omitempty" json:"-"`
|
||||
Dialog loginDialogResult `plist:"dialog,omitempty" json:"-"`
|
||||
Action loginDialogActionResult `plist:"action,omitempty" json:"-"`
|
||||
}
|
||||
|
||||
func (t *appstore) purchaseWithParams(acc Account, app App, guid string, pricingParameters string) error {
|
||||
req := t.purchaseRequest(acc, app, acc.StoreFront, guid, pricingParameters)
|
||||
res, err := t.purchaseClient.Send(req)
|
||||
func (t *appstore) purchaseWithParams(acc *Account, app App, guid string, pricingParameters string) error {
|
||||
var res http.Result[purchaseResult]
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
var err error
|
||||
|
||||
storefrontRecovered, termsAccepted := false, false
|
||||
|
||||
for {
|
||||
req := t.purchaseRequest(*acc, app, acc.StoreFront, guid, pricingParameters)
|
||||
|
||||
res, err = t.purchaseClient.Send(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
break
|
||||
}
|
||||
|
||||
if storefront := purchaseStorefrontCorrection(res.Data, acc.StoreFront); storefront != "" && !storefrontRecovered {
|
||||
if err := t.saveAccountStorefront(acc.DirectoryServicesID, storefront); err != nil {
|
||||
return fmt.Errorf("failed to correct account storefront: %w", err)
|
||||
}
|
||||
|
||||
acc.StoreFront = storefront
|
||||
storefrontRecovered = true
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if res.Data.JingleDocType == "buyProductFailure" && res.Data.Action.Kind == "Goto" && terms.IsPageURL(res.Data.Action.URL) {
|
||||
if termsAccepted {
|
||||
return errors.New("apple still requires terms acceptance after confirming the current terms")
|
||||
}
|
||||
|
||||
if err := t.acceptPurchaseTerms(*acc, guid); err != nil {
|
||||
return fmt.Errorf("failed to accept App Store terms: %w", err)
|
||||
}
|
||||
|
||||
termsAccepted = true
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeTemporarilyUnavailable {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
gohttp "net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/store/emulator"
|
||||
"github.com/majd/ipatool/v2/internal/store/profile"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("CountryMismatch framework response", func() {
|
||||
It("recovers the reported dialog through the real encoder and response interpreter", func() {
|
||||
ctx := context.Background()
|
||||
bundle, err := assets.Load(ctx)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
prepared, err := profile.Load(ctx)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
account := Account{DirectoryServicesID: "123456", StoreFront: "143441-1,34", PasswordToken: "fixture-token", Pod: "30"}
|
||||
data, err := json.Marshal(account)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
chain := &storefrontTestKeychain{data: data}
|
||||
var storefronts, endpoints []string
|
||||
executor := &storefrontEmulatorExecutor{
|
||||
image: bundle.AppleMediaServices, prepared: prepared,
|
||||
transport: func(request *gohttp.Request) (*gohttp.Response, error) {
|
||||
storefronts = append(storefronts, request.Header.Get("X-Apple-Store-Front"))
|
||||
endpoints = append(endpoints, request.URL.String())
|
||||
body := countryMismatchFixture
|
||||
if len(storefronts) > 1 {
|
||||
body = `<plist version="1.0"><dict><key>jingleDocType</key><string>purchaseSuccess</string><key>status</key><integer>0</integer></dict></plist>`
|
||||
}
|
||||
|
||||
return &gohttp.Response{StatusCode: gohttp.StatusOK, Header: gohttp.Header{"Content-Type": {"text/xml; charset=UTF-8"}}, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
},
|
||||
}
|
||||
hardware := machine.NewMockMachine(gomock.NewController(GinkgoT()))
|
||||
hardware.EXPECT().MacAddress().Return("00:01:02:03:04:05", nil)
|
||||
store := &appstore{keychain: chain, machine: hardware, purchaseClient: http.NewClient[purchaseResult](http.Args{Executor: executor})}
|
||||
Expect(store.Purchase(PurchaseInput{Account: account, App: App{ID: 1234}})).To(Succeed())
|
||||
Expect(storefronts).To(Equal([]string{"143441-1,34", "143462-1,34"}))
|
||||
Expect(endpoints).To(HaveEach("https://p30-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/buyProduct"))
|
||||
info, err := store.AccountInfo()
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(info.Account.StoreFront).To(Equal("143462-1,34"))
|
||||
})
|
||||
})
|
||||
|
||||
type storefrontEmulatorExecutor struct {
|
||||
image []byte
|
||||
prepared profile.Data
|
||||
transport func(*gohttp.Request) (*gohttp.Response, error)
|
||||
}
|
||||
|
||||
func (e *storefrontEmulatorExecutor) Send(request http.Request, _ []byte) (*gohttp.Response, error) {
|
||||
guest, err := emulator.Open(context.Background(), e.image, e.prepared)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open fixture runtime: %w", err)
|
||||
}
|
||||
|
||||
defer guest.Close()
|
||||
|
||||
headers := gohttp.Header{}
|
||||
for key, value := range request.Headers {
|
||||
headers.Set(key, value)
|
||||
}
|
||||
|
||||
response, err := guest.Execute(emulator.Request{
|
||||
Operation: "purchase", URL: request.URL, Method: request.Method, Headers: headers,
|
||||
HardwareID: []byte{0, 1, 2, 3, 4, 5}, Parameters: request.Payload.(*http.XMLPayload).Content,
|
||||
Bag: map[string]any{"buyProduct": request.URL}, Transport: e.transport,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("execute fixture request: %w", err)
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
func (*storefrontEmulatorExecutor) Do(*gohttp.Request) (*gohttp.Response, error) {
|
||||
return nil, errors.New("unexpected direct request")
|
||||
}
|
||||
@@ -1,14 +1,11 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
func testStorefrontCountryCodes() map[string]string {
|
||||
@@ -30,10 +27,6 @@ func availableStorefrontsFixture() []byte {
|
||||
</array></dict></plist>`)
|
||||
}
|
||||
|
||||
func storefrontGenreFixture(identifier, countryCode string) []byte {
|
||||
return []byte(fmt.Sprintf(`{"storePlatformData":{"genre":{"meta":{"storefront":{"cc":%q,"id":%q}}}}}`, countryCode, identifier))
|
||||
}
|
||||
|
||||
func storefrontSearchItemFixture(kind, adamID, platform, salableAdamID, externalVersionID string) string {
|
||||
return fmt.Sprintf(`{
|
||||
"$kind":%q,
|
||||
@@ -71,117 +64,6 @@ var _ = Describe("App Store storefront data", func() {
|
||||
Entry("bare storefront", "143443", "DE"),
|
||||
)
|
||||
|
||||
Describe("available storefront discovery", func() {
|
||||
It("fetches and caches the storefront country codes", func() {
|
||||
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
|
||||
store := &appstore{storefrontClient: client}
|
||||
client.EXPECT().Send(http.Request{
|
||||
URL: availableStorefrontsURL,
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatRaw,
|
||||
}).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil).Times(1)
|
||||
|
||||
Expect(store.countryCodeFromStoreFront("143441-1,34")).To(Equal("US"))
|
||||
Expect(store.countryCodeFromStoreFront("143443")).To(Equal("DE"))
|
||||
})
|
||||
|
||||
It("retries discovery after a request failure", func() {
|
||||
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
|
||||
store := &appstore{storefrontClient: client}
|
||||
requestErr := errors.New("connection reset")
|
||||
gomock.InOrder(
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{}, requestErr),
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil),
|
||||
)
|
||||
|
||||
_, err := store.countryCodeFromStoreFront("143441")
|
||||
Expect(err).To(MatchError(ContainSubstring("available storefronts request failed")))
|
||||
Expect(errors.Is(err, requestErr)).To(BeTrue())
|
||||
Expect(store.countryCodeFromStoreFront("143441")).To(Equal("US"))
|
||||
})
|
||||
|
||||
DescribeTable("resolves storefronts omitted from the available list", func(identifier, countryCode string) {
|
||||
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
|
||||
store := &appstore{storefrontClient: client}
|
||||
gomock.InOrder(
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil),
|
||||
client.EXPECT().Send(http.Request{
|
||||
URL: storefrontGenreURL,
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatRaw,
|
||||
NoRedirects: true,
|
||||
Headers: map[string]string{"X-Apple-Store-Front": identifier + "-2,29"},
|
||||
}).Return(http.Result[[]byte]{StatusCode: 200, Data: storefrontGenreFixture(identifier, countryCode)}, nil),
|
||||
)
|
||||
|
||||
Expect(store.countryCodeFromStoreFront(identifier + "-19,29")).To(Equal(countryCode))
|
||||
Expect(store.countryCodeFromStoreFront(identifier)).To(Equal(countryCode))
|
||||
},
|
||||
Entry("China", "143465", "CN"),
|
||||
)
|
||||
|
||||
DescribeTable("rejects inactive legacy storefronts", func(identifier string) {
|
||||
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
|
||||
store := &appstore{storefrontClient: client}
|
||||
gomock.InOrder(
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil),
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 302}, nil),
|
||||
)
|
||||
|
||||
_, err := store.countryCodeFromStoreFront(identifier)
|
||||
|
||||
Expect(err).To(MatchError(fmt.Sprintf("country code mapping for store front (%s) was not found", identifier)))
|
||||
},
|
||||
Entry("Bangladesh", "143490"),
|
||||
Entry("Liechtenstein", "143522"),
|
||||
)
|
||||
|
||||
It("discovers a missing storefront ID for phone login", func() {
|
||||
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
|
||||
store := &appstore{
|
||||
storefrontClient: client,
|
||||
storefrontCountryCodes: map[string]string{
|
||||
"143464": "SG",
|
||||
"143466": "KR",
|
||||
},
|
||||
}
|
||||
client.EXPECT().Send(gomock.Any()).Do(func(request http.Request) {
|
||||
Expect(request.URL).To(Equal(storefrontGenreURL))
|
||||
Expect(request.Headers).To(HaveKeyWithValue("X-Apple-Store-Front", "143465-2,29"))
|
||||
}).Return(http.Result[[]byte]{StatusCode: 200, Data: storefrontGenreFixture("143465", "CN")}, nil)
|
||||
|
||||
Expect(store.discoverStorefrontID("CN")).To(Equal("143465"))
|
||||
Expect(store.storefrontID("CN")).To(Equal("143465"))
|
||||
})
|
||||
|
||||
It("rejects an unknown ID when Apple defaults it to a known storefront", func() {
|
||||
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
|
||||
store := &appstore{storefrontClient: client}
|
||||
gomock.InOrder(
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil),
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: storefrontGenreFixture("143441", "US")}, nil),
|
||||
)
|
||||
|
||||
_, err := store.countryCodeFromStoreFront("999999")
|
||||
|
||||
Expect(err).To(MatchError("country code mapping for store front (999999) was not found"))
|
||||
})
|
||||
|
||||
DescribeTable("rejects unusable discovery responses", func(status int, body []byte, message string) {
|
||||
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
|
||||
store := &appstore{storefrontClient: client}
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: status, Data: body}, nil)
|
||||
|
||||
_, err := store.countryCodeFromStoreFront("143441")
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring(message)))
|
||||
},
|
||||
Entry("HTTP error", 503, nil, "available storefronts request failed"),
|
||||
Entry("malformed plist", 200, []byte("not a plist"), "failed to decode available storefronts"),
|
||||
Entry("empty storefront list", 200, []byte(`<plist><dict><key>storefronts</key><array/></dict></plist>`), "contains no storefronts"),
|
||||
)
|
||||
})
|
||||
|
||||
Describe("storefrontVisionApps", func() {
|
||||
It("keeps unique native visionOS apps in storefront order and applies the limit", func() {
|
||||
body := storefrontPageFixture(
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/store/terms"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type termsResult struct {
|
||||
Status *int `json:"status"`
|
||||
TermsVersionID json.RawMessage `json:"termsVersionId"`
|
||||
LatestTermsVersionID json.RawMessage `json:"latestTermsVersionId"`
|
||||
IsCurrent bool `json:"isCurrent"`
|
||||
ErrorMessageKey string `json:"errorMessageKey"`
|
||||
}
|
||||
|
||||
func (t *appstore) acceptPurchaseTerms(acc Account, guid string) error {
|
||||
if t.termsClient == nil || t.bagClient == nil {
|
||||
return errors.New("terms client is not configured")
|
||||
}
|
||||
|
||||
if dsid, err := strconv.ParseUint(acc.DirectoryServicesID, 10, 64); err != nil || dsid == 0 {
|
||||
return errors.New("account identifier is required for terms acceptance")
|
||||
}
|
||||
|
||||
country, err := t.countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
bag, err := t.fetchURLBag(guid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
infoURL, err := termsEndpoint(bag.TermsInfoEndpoint, acc.Pod, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
checkURL, err := termsEndpoint(bag.TermsCheckEndpoint, acc.Pod, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
query := infoURL.Query()
|
||||
query.Set("cc", country)
|
||||
query.Set("termsType", "MZStore.NewTermsAndConditionsStatement")
|
||||
infoURL.RawQuery = query.Encode()
|
||||
|
||||
info, err := t.termsClient.Send(termsRequest(acc, infoURL.String(), http.MethodGET, nil))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to retrieve current terms: %w", err)
|
||||
}
|
||||
|
||||
if err = checkTermsResponse(info); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
version, err := termsVersion(info.Data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Apple's Commerce UI posts the account DSID and the current version returned
|
||||
// by getTermsByCountryAndTypeSrv to the bag's terms-check endpoint.
|
||||
body, err := json.Marshal(map[string]any{"id": acc.DirectoryServicesID, "accepted": version})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encode terms acceptance: %w", err)
|
||||
}
|
||||
|
||||
accepted, err := t.termsClient.Send(termsRequest(acc, checkURL.String(), http.MethodPOST, &http.RawPayload{Content: body}))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to submit terms acceptance: %w", err)
|
||||
}
|
||||
|
||||
if err = checkTermsResponse(accepted); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !accepted.Data.IsCurrent {
|
||||
return errors.New("apple did not confirm acceptance of the current terms")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func termsVersion(result termsResult) (json.RawMessage, error) {
|
||||
version := result.LatestTermsVersionID
|
||||
if len(version) == 0 || string(version) == "null" {
|
||||
version = result.TermsVersionID
|
||||
}
|
||||
|
||||
var number json.Number
|
||||
if err := json.Unmarshal(version, &number); err != nil {
|
||||
return nil, errors.New("apple returned an invalid terms version")
|
||||
}
|
||||
|
||||
value, err := strconv.ParseUint(number.String(), 10, 64)
|
||||
if err != nil || value == 0 || strconv.FormatUint(value, 10) != number.String() {
|
||||
return nil, errors.New("apple returned an invalid terms version")
|
||||
}
|
||||
|
||||
return version, nil
|
||||
}
|
||||
|
||||
func checkTermsResponse(response http.Result[termsResult]) error {
|
||||
if response.Data.ErrorMessageKey == "MZFinance.TermsCheckLoginRequired" {
|
||||
return ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if response.StatusCode != gohttp.StatusOK {
|
||||
return fmt.Errorf("unexpected terms response status: %d", response.StatusCode)
|
||||
}
|
||||
|
||||
if response.Data.Status == nil {
|
||||
return errors.New("apple returned a terms response without a status")
|
||||
}
|
||||
|
||||
if *response.Data.Status != 0 {
|
||||
return fmt.Errorf("apple terms request failed with status %d", *response.Data.Status)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func termsRequest(acc Account, endpoint, method string, payload http.Payload) http.Request {
|
||||
return http.Request{
|
||||
URL: endpoint, Method: method, ResponseFormat: http.ResponseFormatJSON, Payload: payload,
|
||||
Headers: map[string]string{
|
||||
"Accept": "application/json", "Content-Type": "application/json", "User-Agent": storeAuthenticationUserAgent,
|
||||
"X-Dsid": acc.DirectoryServicesID, "iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Token": acc.PasswordToken, "X-Apple-Store-Front": acc.StoreFront,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func termsEndpoint(raw, pod string, acceptance bool) (*url.URL, error) {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Scheme != "https" || u.User != nil || u.Fragment != "" || u.RawPath != "" || (u.Port() != "" && u.Port() != "443") {
|
||||
return nil, errors.New("invalid terms endpoint in bag")
|
||||
}
|
||||
|
||||
if _, err = url.ParseQuery(u.RawQuery); err != nil {
|
||||
return nil, errors.New("invalid terms endpoint query in bag")
|
||||
}
|
||||
|
||||
if !acceptance {
|
||||
if !strings.EqualFold(u.Hostname(), "amp-account.itunes.apple.com") || u.Path != "/account/terms/info" {
|
||||
return nil, errors.New("unsupported terms information endpoint in bag")
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
if !terms.IsBuyHost(u.Hostname()) || (u.Path != "/account/terms" && u.Path != "/WebObjects/MZFinance.woa/wa/termsCheckSrv") {
|
||||
return nil, errors.New("unsupported terms acceptance endpoint in bag")
|
||||
}
|
||||
|
||||
if strings.EqualFold(u.Hostname(), "buy.itunes.apple.com") && pod != "" {
|
||||
host := "p" + pod + "-buy.itunes.apple.com"
|
||||
if !terms.IsBuyHost(host) {
|
||||
return nil, errors.New("invalid account pod for terms acceptance")
|
||||
}
|
||||
|
||||
u.Host = host
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
gohttp "net/http"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/store/emulator"
|
||||
"github.com/majd/ipatool/v2/internal/store/profile"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
var _ = Describe("Terms purchase continuation through the framework", func() {
|
||||
DescribeTable("handles the gzip terms action and requires server-confirmed acceptance", func(confirm bool) {
|
||||
ctx := context.Background()
|
||||
bundle, err := assets.Load(ctx)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
prepared, err := profile.Load(ctx)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
var compressed bytes.Buffer
|
||||
writer := gzip.NewWriter(&compressed)
|
||||
_, err = writer.Write([]byte(purchaseTermsFixture))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(writer.Close()).To(Succeed())
|
||||
type exchange struct {
|
||||
method, endpoint, body string
|
||||
header gohttp.Header
|
||||
}
|
||||
var exchanges []exchange
|
||||
purchaseCount := 0
|
||||
accepted := false
|
||||
transport := func(request *gohttp.Request) (*gohttp.Response, error) {
|
||||
var body []byte
|
||||
if request.Body != nil {
|
||||
var readErr error
|
||||
body, readErr = io.ReadAll(request.Body)
|
||||
if readErr != nil {
|
||||
return nil, fmt.Errorf("read fixture request: %w", readErr)
|
||||
}
|
||||
}
|
||||
exchanges = append(exchanges, exchange{method: request.Method, endpoint: request.URL.String(), body: string(body), header: request.Header.Clone()})
|
||||
headers := gohttp.Header{"Content-Type": {"application/json"}}
|
||||
response := []byte(`{"status":-1}`)
|
||||
switch request.URL.Path {
|
||||
case PrivateAppStoreAPIPathPurchase:
|
||||
purchaseCount++
|
||||
headers.Set("Content-Type", "text/xml; charset=UTF-8")
|
||||
if purchaseCount == 1 {
|
||||
headers.Set("Content-Encoding", "gzip")
|
||||
response = compressed.Bytes()
|
||||
} else if accepted {
|
||||
response = []byte(`<plist version="1.0"><dict><key>jingleDocType</key><string>purchaseSuccess</string><key>status</key><integer>0</integer></dict></plist>`)
|
||||
}
|
||||
case "/account/terms/info":
|
||||
response = []byte(`{"status":0,"termsVersionId":290461,"latestTermsVersionId":290462}`)
|
||||
case "/account/terms":
|
||||
var data map[string]json.RawMessage
|
||||
if json.Unmarshal(body, &data) == nil && string(data["id"]) == `"123456"` && string(data["accepted"]) == "290462" {
|
||||
accepted = confirm
|
||||
response = []byte(fmt.Sprintf(`{"status":0,"isCurrent":%t}`, confirm))
|
||||
}
|
||||
}
|
||||
|
||||
return &gohttp.Response{StatusCode: gohttp.StatusOK, Header: headers, Body: io.NopCloser(bytes.NewReader(response))}, nil
|
||||
}
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
hardware := machine.NewMockMachine(ctrl)
|
||||
hardware.EXPECT().MacAddress().Return("00:01:02:03:04:05", nil)
|
||||
bagClient := http.NewMockClient[bagResult](ctrl)
|
||||
bagClient.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: 200, Data: bagResult{URLBag: urlBag{TermsInfoEndpoint: "https://amp-account.itunes.apple.com/account/terms/info", TermsCheckEndpoint: "https://buy.itunes.apple.com/account/terms"}}}, nil)
|
||||
store := &appstore{
|
||||
machine: hardware, bagClient: bagClient, storefrontCountryCodes: map[string]string{"143462": "JP"},
|
||||
purchaseClient: http.NewClient[purchaseResult](http.Args{Executor: &termsEmulatorExecutor{image: bundle.AppleMediaServices, prepared: prepared, operation: "purchase", transport: transport}}),
|
||||
termsClient: http.NewClient[termsResult](http.Args{Executor: &termsEmulatorExecutor{image: bundle.AppleMediaServices, prepared: prepared, operation: "request", transport: transport}}),
|
||||
}
|
||||
err = store.Purchase(PurchaseInput{Account: Account{DirectoryServicesID: "123456", PasswordToken: "fixture-token", StoreFront: "143462-1,34", Pod: "45"}, App: App{ID: 1234}})
|
||||
if confirm {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(exchanges).To(HaveLen(4))
|
||||
Expect(purchaseCount).To(Equal(2))
|
||||
} else {
|
||||
Expect(err).To(MatchError(ContainSubstring("did not confirm acceptance")))
|
||||
Expect(exchanges).To(HaveLen(3))
|
||||
Expect(purchaseCount).To(Equal(1))
|
||||
}
|
||||
Expect(exchanges[1].method).To(Equal(gohttp.MethodGet))
|
||||
Expect(exchanges[1].endpoint).To(ContainSubstring("cc=JP"))
|
||||
Expect(exchanges[2].method).To(Equal(gohttp.MethodPost))
|
||||
Expect(exchanges[2].endpoint).To(Equal("https://p45-buy.itunes.apple.com/account/terms"))
|
||||
for _, exchange := range exchanges {
|
||||
Expect(exchange.header.Get("X-Dsid")).To(Equal("123456"))
|
||||
Expect(exchange.header.Get("X-Token")).To(Equal("fixture-token"))
|
||||
Expect(exchange.header.Get("X-Apple-Store-Front")).To(Equal("143462-1,34"))
|
||||
}
|
||||
if confirm {
|
||||
var first, last map[string]any
|
||||
_, err = plist.Unmarshal([]byte(exchanges[0].body), &first)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
_, err = plist.Unmarshal([]byte(exchanges[3].body), &last)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
for _, key := range []string{"salableAdamId", "price", "productType", "pricingParameters", "guid"} {
|
||||
Expect(last[key]).To(Equal(first[key]))
|
||||
}
|
||||
}
|
||||
}, Entry("confirmed acceptance", true), Entry("unconfirmed acceptance", false))
|
||||
})
|
||||
|
||||
type termsEmulatorExecutor struct {
|
||||
image []byte
|
||||
prepared profile.Data
|
||||
operation string
|
||||
transport func(*gohttp.Request) (*gohttp.Response, error)
|
||||
}
|
||||
|
||||
func (e *termsEmulatorExecutor) Send(request http.Request, _ []byte) (*gohttp.Response, error) {
|
||||
guest, err := emulator.Open(context.Background(), e.image, e.prepared)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open fixture runtime: %w", err)
|
||||
}
|
||||
|
||||
defer guest.Close()
|
||||
|
||||
input := emulator.Request{Operation: e.operation, URL: request.URL, Method: request.Method, Format: string(request.ResponseFormat), Headers: gohttp.Header{}, HardwareID: []byte{0, 1, 2, 3, 4, 5}, Bag: map[string]any{"buyProduct": request.URL}, Transport: e.transport}
|
||||
for key, value := range request.Headers {
|
||||
input.Headers.Set(key, value)
|
||||
}
|
||||
|
||||
if payload, ok := request.Payload.(*http.XMLPayload); ok {
|
||||
input.Parameters = payload.Content
|
||||
}
|
||||
|
||||
if payload, ok := request.Payload.(*http.RawPayload); ok {
|
||||
input.Body = payload.Content
|
||||
}
|
||||
|
||||
response, err := guest.Execute(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("execute fixture request: %w", err)
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
func (*termsEmulatorExecutor) Do(*gohttp.Request) (*gohttp.Response, error) {
|
||||
return nil, errors.New("unexpected direct request")
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
const purchaseTermsFixture = `<plist version="1.0"><dict><key>pings</key><array></array><key>jingleDocType</key><string>buyProductFailure</string><key>jingleAction</key><string>buyProduct</string><key>action</key><dict><key>kind</key><string>Goto</string><key>url</key><string>https://p45-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/termsPage</string><key>target</key><string>main</string></dict></dict></plist>`
|
||||
|
||||
var _ = Describe("Automatic purchase terms acceptance", func() {
|
||||
var store *appstore
|
||||
var purchases *http.MockClient[purchaseResult]
|
||||
var termClient *http.MockClient[termsResult]
|
||||
var bags *http.MockClient[bagResult]
|
||||
var input PurchaseInput
|
||||
var blocked, success http.Result[purchaseResult]
|
||||
zero := 0
|
||||
info := http.Result[termsResult]{StatusCode: 200, Data: termsResult{Status: &zero, TermsVersionID: json.RawMessage(`290462`)}}
|
||||
accepted := http.Result[termsResult]{StatusCode: 200, Data: termsResult{Status: &zero, IsCurrent: true}}
|
||||
BeforeEach(func() {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
purchases = http.NewMockClient[purchaseResult](ctrl)
|
||||
termClient = http.NewMockClient[termsResult](ctrl)
|
||||
bags = http.NewMockClient[bagResult](ctrl)
|
||||
hardware := machine.NewMockMachine(ctrl)
|
||||
hardware.EXPECT().MacAddress().Return("00:01:02:03:04:05", nil).AnyTimes()
|
||||
store = &appstore{purchaseClient: purchases, termsClient: termClient, bagClient: bags, machine: hardware, storefrontCountryCodes: testStorefrontCountryCodes()}
|
||||
store.storefrontCountryCodes["143462"] = "JP"
|
||||
input = PurchaseInput{Account: Account{DirectoryServicesID: "123456", StoreFront: "143462-1,34", PasswordToken: "fixture-token", Pod: "45"}, App: App{ID: 1234}}
|
||||
blocked = http.Result[purchaseResult]{StatusCode: 200}
|
||||
_, err := plist.Unmarshal([]byte(purchaseTermsFixture), &blocked.Data)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
success = http.Result[purchaseResult]{StatusCode: 200, Data: purchaseResult{JingleDocType: "purchaseSuccess"}}
|
||||
})
|
||||
expectBag := func() {
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: 200, Data: bagResult{
|
||||
TermsInfoEndpoint: "https://amp-account.itunes.apple.com/account/terms/info",
|
||||
TermsCheckEndpoint: "https://buy.itunes.apple.com/account/terms",
|
||||
}}, nil)
|
||||
}
|
||||
|
||||
It("retrieves the account country's current version, accepts it, and retries the unchanged purchase", func() {
|
||||
var original http.Request
|
||||
calls := 0
|
||||
purchases.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[purchaseResult], error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
original = request
|
||||
|
||||
return blocked, nil
|
||||
}
|
||||
Expect(request).To(Equal(original))
|
||||
|
||||
return success, nil
|
||||
}).Times(2)
|
||||
expectBag()
|
||||
gomock.InOrder(
|
||||
termClient.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[termsResult], error) {
|
||||
u, err := url.Parse(request.URL)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(u.Host).To(Equal("amp-account.itunes.apple.com"))
|
||||
Expect(u.Query().Get("cc")).To(Equal("JP"))
|
||||
Expect(u.Query().Get("termsType")).To(Equal("MZStore.NewTermsAndConditionsStatement"))
|
||||
Expect(request.Method).To(Equal(http.MethodGET))
|
||||
Expect(request.Headers["X-Apple-Store-Front"]).To(Equal(input.Account.StoreFront))
|
||||
Expect(request.Headers["X-Token"]).To(Equal(input.Account.PasswordToken))
|
||||
|
||||
return info, nil
|
||||
}),
|
||||
termClient.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[termsResult], error) {
|
||||
Expect(request.Method).To(Equal(http.MethodPOST))
|
||||
Expect(request.URL).To(Equal("https://p45-buy.itunes.apple.com/account/terms"))
|
||||
Expect(request.Headers["X-Dsid"]).To(Equal(input.Account.DirectoryServicesID))
|
||||
Expect(request.Headers["Content-Type"]).To(Equal("application/json"))
|
||||
var data map[string]json.RawMessage
|
||||
Expect(json.Unmarshal(request.Payload.(*http.RawPayload).Content, &data)).To(Succeed())
|
||||
Expect(string(data["id"])).To(Equal(`"123456"`))
|
||||
Expect(string(data["accepted"])).To(Equal(`290462`))
|
||||
|
||||
return accepted, nil
|
||||
}),
|
||||
)
|
||||
Expect(store.Purchase(input)).To(Succeed())
|
||||
})
|
||||
|
||||
It("preserves storefront recovery before accepting terms", func() {
|
||||
input.Account.StoreFront = "143441-1,34"
|
||||
saved, err := json.Marshal(input.Account)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
store.keychain = &storefrontTestKeychain{data: saved}
|
||||
mismatch := http.Result[purchaseResult]{StatusCode: 200}
|
||||
_, err = plist.Unmarshal([]byte(countryMismatchFixture), &mismatch.Data)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
gomock.InOrder(purchases.EXPECT().Send(gomock.Any()).Return(mismatch, nil), purchases.EXPECT().Send(gomock.Any()).Return(blocked, nil), purchases.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[purchaseResult], error) {
|
||||
Expect(request.Headers["X-Apple-Store-Front"]).To(Equal("143462-1,34"))
|
||||
|
||||
return success, nil
|
||||
}))
|
||||
expectBag()
|
||||
gomock.InOrder(termClient.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[termsResult], error) {
|
||||
Expect(request.URL).To(ContainSubstring("cc=JP"))
|
||||
|
||||
return info, nil
|
||||
}), termClient.EXPECT().Send(gomock.Any()).Return(accepted, nil))
|
||||
Expect(store.Purchase(input)).To(Succeed())
|
||||
})
|
||||
|
||||
It("does not loop if Apple still requires terms after confirming acceptance", func() {
|
||||
purchases.EXPECT().Send(gomock.Any()).Return(blocked, nil).Times(2)
|
||||
expectBag()
|
||||
gomock.InOrder(termClient.EXPECT().Send(gomock.Any()).Return(info, nil), termClient.EXPECT().Send(gomock.Any()).Return(accepted, nil))
|
||||
Expect(store.Purchase(input)).To(MatchError(ContainSubstring("still requires terms acceptance")))
|
||||
})
|
||||
|
||||
It("does not submit acceptance when the terms version is missing", func() {
|
||||
purchases.EXPECT().Send(gomock.Any()).Return(blocked, nil).Times(1)
|
||||
expectBag()
|
||||
termClient.EXPECT().Send(gomock.Any()).Return(http.Result[termsResult]{StatusCode: 200, Data: termsResult{Status: &zero}}, nil).Times(1)
|
||||
Expect(store.Purchase(input)).To(MatchError(ContainSubstring("invalid terms version")))
|
||||
})
|
||||
|
||||
DescribeTable("does not retry the purchase without confirmed acceptance", func(result http.Result[termsResult], failure error) {
|
||||
purchases.EXPECT().Send(gomock.Any()).Return(blocked, nil).Times(1)
|
||||
expectBag()
|
||||
gomock.InOrder(termClient.EXPECT().Send(gomock.Any()).Return(info, nil), termClient.EXPECT().Send(gomock.Any()).Return(result, failure))
|
||||
Expect(store.Purchase(input)).To(HaveOccurred())
|
||||
},
|
||||
Entry("not current", http.Result[termsResult]{StatusCode: 200, Data: termsResult{Status: &zero}}, nil),
|
||||
Entry("missing status", http.Result[termsResult]{StatusCode: 200, Data: termsResult{IsCurrent: true}}, nil),
|
||||
Entry("HTTP failure", http.Result[termsResult]{StatusCode: 500, Data: accepted.Data}, nil),
|
||||
Entry("transport failure", http.Result[termsResult]{}, errors.New("fixture network failure")),
|
||||
)
|
||||
|
||||
DescribeTable("preserves expired-token recovery during the terms flow", func(expiredAtAcceptance bool) {
|
||||
purchases.EXPECT().Send(gomock.Any()).Return(blocked, nil).Times(1)
|
||||
expectBag()
|
||||
expiration := http.Result[termsResult]{StatusCode: 200, Data: termsResult{ErrorMessageKey: "MZFinance.TermsCheckLoginRequired"}}
|
||||
if expiredAtAcceptance {
|
||||
gomock.InOrder(termClient.EXPECT().Send(gomock.Any()).Return(info, nil), termClient.EXPECT().Send(gomock.Any()).Return(expiration, nil))
|
||||
} else {
|
||||
termClient.EXPECT().Send(gomock.Any()).Return(expiration, nil)
|
||||
}
|
||||
Expect(errors.Is(store.Purchase(input), ErrPasswordTokenExpired)).To(BeTrue())
|
||||
}, Entry("retrieving terms", false), Entry("accepting terms", true))
|
||||
|
||||
DescribeTable("does not act on unrelated or invalid purchase actions", func(kind, document, endpoint string) {
|
||||
blocked.Data.Action.Kind = kind
|
||||
blocked.Data.Action.URL = endpoint
|
||||
blocked.Data.JingleDocType = document
|
||||
purchases.EXPECT().Send(gomock.Any()).Return(blocked, nil).Times(1)
|
||||
Expect(store.Purchase(input)).To(HaveOccurred())
|
||||
},
|
||||
Entry("different action", "OpenURL", "buyProductFailure", "https://p45-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/termsPage"),
|
||||
Entry("different document", "Goto", "other", "https://p45-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/termsPage"),
|
||||
Entry("different host", "Goto", "buyProductFailure", "https://example.com/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/termsPage"),
|
||||
Entry("different page", "Goto", "buyProductFailure", "https://p45-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/accountSummary"),
|
||||
)
|
||||
})
|
||||
|
||||
var _ = Describe("Terms protocol validation", func() {
|
||||
DescribeTable("uses the current version without changing its JSON type", func(current, latest, want string) {
|
||||
result, err := termsVersion(termsResult{TermsVersionID: json.RawMessage(current), LatestTermsVersionID: json.RawMessage(latest)})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(result)).To(Equal(want))
|
||||
}, Entry("numeric version", "290462", "", "290462"), Entry("string version", `"290462"`, "", `"290462"`), Entry("newer version", "290462", "290463", "290463"))
|
||||
DescribeTable("rejects invalid versions before acceptance", func(value string) {
|
||||
_, err := termsVersion(termsResult{TermsVersionID: json.RawMessage(value)})
|
||||
Expect(err).To(HaveOccurred())
|
||||
}, Entry("missing", ""), Entry("null", "null"), Entry("zero", "0"), Entry("negative", "-1"), Entry("fraction", "1.5"), Entry("object", "{}"), Entry("boolean", "true"), Entry("text", `"unknown"`))
|
||||
DescribeTable("rejects untrusted or unrelated bag endpoints", func(endpoint string, acceptance bool) {
|
||||
_, err := termsEndpoint(endpoint, "45", acceptance)
|
||||
Expect(err).To(HaveOccurred())
|
||||
}, Entry("external info", "https://example.com/account/terms/info", false), Entry("HTTP info", "http://amp-account.itunes.apple.com/account/terms/info", false), Entry("info credentials", "https://user@amp-account.itunes.apple.com/account/terms/info", false), Entry("external acceptance", "https://example.com/account/terms", true), Entry("unrelated acceptance", "https://buy.itunes.apple.com/account/delete", true), Entry("host suffix", "https://buy.itunes.apple.com.example.com/account/terms", true), Entry("non-numbered pod", "https://evil-buy.itunes.apple.com/account/terms", true), Entry("encoded path", "https://buy.itunes.apple.com/account/%74erms", true))
|
||||
It("does not expose action URLs in existing purchase error metadata", func() {
|
||||
result := purchaseResult{Action: loginDialogActionResult{Kind: "Goto", URL: "https://example.com/?token=secret"}}
|
||||
data, err := json.Marshal(result)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(strings.Contains(string(data), "secret")).To(BeFalse())
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Terms endpoints in URL bags", func() {
|
||||
DescribeTable("retains terms endpoints without changing authentication endpoint selection", func(data bagResult, auth, info, check string) {
|
||||
client := http.NewMockClient[bagResult](gomock.NewController(GinkgoT()))
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: 200, Data: data}, nil)
|
||||
store := &appstore{bagClient: client}
|
||||
bag, err := store.fetchURLBag("000102030405")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(bag.AuthEndpoint).To(Equal(auth))
|
||||
Expect(bag.TermsInfoEndpoint).To(Equal(info))
|
||||
Expect(bag.TermsCheckEndpoint).To(Equal(check))
|
||||
},
|
||||
Entry("flat terms with nested authentication", bagResult{URLBag: urlBag{AuthEndpoint: "nested-auth"}, TermsInfoEndpoint: "info", TermsCheckEndpoint: "check"}, "nested-auth", "info", "check"),
|
||||
Entry("nested terms with flat authentication", bagResult{URLBag: urlBag{TermsInfoEndpoint: "info", TermsCheckEndpoint: "check"}, AuthEndpoint: "flat-auth"}, "flat-auth", "info", "check"),
|
||||
Entry("nested terms take precedence", bagResult{URLBag: urlBag{TermsInfoEndpoint: "nested-info", TermsCheckEndpoint: "nested-check"}, TermsInfoEndpoint: "flat-info", TermsCheckEndpoint: "flat-check"}, "", "nested-info", "nested-check"),
|
||||
)
|
||||
})
|
||||
+114
-166
@@ -1,10 +1,10 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -12,12 +12,6 @@ import (
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
const (
|
||||
availableStorefrontsURL = "https://itunes.apple.com/WebObjects/MZStore.woa/wa/availableStoreFronts"
|
||||
storefrontGenreURL = "https://apps.apple.com/genre/id36"
|
||||
maxStorefrontIDRange = 1000
|
||||
)
|
||||
|
||||
type availableStorefrontsResult struct {
|
||||
Storefronts []availableStorefront `plist:"storefronts"`
|
||||
}
|
||||
@@ -27,211 +21,124 @@ type availableStorefront struct {
|
||||
ID int64 `plist:"id"`
|
||||
}
|
||||
|
||||
type storefrontGenrePage struct {
|
||||
StorePlatformData map[string]struct {
|
||||
Meta struct {
|
||||
Storefront struct {
|
||||
CountryCode string `json:"cc"`
|
||||
ID string `json:"id"`
|
||||
} `json:"storefront"`
|
||||
} `json:"meta"`
|
||||
} `json:"storePlatformData"`
|
||||
type storefrontBagResult struct {
|
||||
StorefrontID any `plist:"storeFrontId"`
|
||||
CountryCode string `plist:"currentStorefrontCountryCodeISO2A"`
|
||||
AvailableStorefrontsURL string `plist:"available-storefronts"`
|
||||
URLBag struct {
|
||||
AvailableStorefrontsURL string `plist:"available-storefronts"`
|
||||
} `plist:"urlBag"`
|
||||
}
|
||||
|
||||
type storefrontMapping struct{ id, country string }
|
||||
|
||||
func (t *appstore) countryCodeFromStoreFront(storeFront string) (string, error) {
|
||||
if err := t.discoverAvailableStorefronts(); err != nil {
|
||||
return "", err
|
||||
if !validStorefrontIdentifier(storefrontIdentifier(storeFront)) {
|
||||
return "", storefrontMappingError(storeFront)
|
||||
}
|
||||
|
||||
identifier := storefrontIdentifier(storeFront)
|
||||
if countryCode := t.cachedStorefrontCountryCode(identifier); countryCode != "" {
|
||||
return countryCode, nil
|
||||
}
|
||||
|
||||
countryCode, found, err := t.discoverStorefrontCountryCode(identifier)
|
||||
mapping, err := t.discoverStorefront(storeFront, "")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if found {
|
||||
return countryCode, nil
|
||||
}
|
||||
|
||||
return "", storefrontMappingError(storeFront)
|
||||
return mapping.country, nil
|
||||
}
|
||||
|
||||
func (t *appstore) storefrontID(countryCode string) string {
|
||||
t.storefrontsMu.Lock()
|
||||
defer t.storefrontsMu.Unlock()
|
||||
|
||||
for identifier, code := range t.storefrontCountryCodes {
|
||||
if code == countryCode {
|
||||
return identifier
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
return findStorefrontMapping(t.storefrontCountryCodes, "", countryCode).id
|
||||
}
|
||||
|
||||
func (t *appstore) discoverStorefrontID(countryCode string) (string, error) {
|
||||
if err := t.discoverAvailableStorefronts(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
countryCode = strings.ToUpper(strings.TrimSpace(countryCode))
|
||||
if identifier := t.storefrontID(countryCode); identifier != "" {
|
||||
return identifier, nil
|
||||
if !validStorefrontCountry(countryCode) {
|
||||
return "", fmt.Errorf("invalid storefront country code (%s)", countryCode)
|
||||
}
|
||||
|
||||
identifiers, err := t.missingStorefrontIdentifiers()
|
||||
mapping, err := t.discoverStorefront("", countryCode)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
for _, identifier := range identifiers {
|
||||
resolvedCountryCode, found, resolveErr := t.discoverStorefrontCountryCode(identifier)
|
||||
if resolveErr != nil {
|
||||
return "", resolveErr
|
||||
}
|
||||
|
||||
if found && resolvedCountryCode == countryCode {
|
||||
return identifier, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("store front mapping for country code (%s) was not found", countryCode)
|
||||
return mapping.id, nil
|
||||
}
|
||||
|
||||
func (t *appstore) cachedStorefrontCountryCode(identifier string) string {
|
||||
// A scoped bag identifies its actual storefront, including countries omitted by
|
||||
// available-storefronts. Validate both fields: Apple defaults unknown IDs to US
|
||||
// while echoing the requested ID in the response headers.
|
||||
func (t *appstore) discoverStorefront(storeFront, country string) (storefrontMapping, error) {
|
||||
t.storefrontsMu.Lock()
|
||||
defer t.storefrontsMu.Unlock()
|
||||
|
||||
return t.storefrontCountryCodes[identifier]
|
||||
}
|
||||
|
||||
func (t *appstore) missingStorefrontIdentifiers() ([]string, error) {
|
||||
t.storefrontsMu.Lock()
|
||||
defer t.storefrontsMu.Unlock()
|
||||
|
||||
minimum, maximum := int64(0), int64(0)
|
||||
known := make(map[int64]struct{}, len(t.storefrontCountryCodes))
|
||||
|
||||
for identifier := range t.storefrontCountryCodes {
|
||||
value, err := strconv.ParseInt(identifier, 10, 64)
|
||||
if err != nil || value <= 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
known[value] = struct{}{}
|
||||
|
||||
if minimum == 0 || value < minimum {
|
||||
minimum = value
|
||||
}
|
||||
|
||||
if value > maximum {
|
||||
maximum = value
|
||||
}
|
||||
identifier := storefrontIdentifier(storeFront)
|
||||
if mapping := findStorefrontMapping(t.storefrontCountryCodes, identifier, country); mapping.id != "" {
|
||||
return mapping, nil
|
||||
}
|
||||
|
||||
if minimum == 0 || maximum-minimum > maxStorefrontIDRange {
|
||||
return nil, errors.New("available storefront identifier range is invalid")
|
||||
if t.storefrontBagClient == nil {
|
||||
return storefrontMapping{}, errors.New("storefront bag client is not configured")
|
||||
}
|
||||
|
||||
identifiers := make([]string, 0, maximum-minimum+1-int64(len(known)))
|
||||
|
||||
for identifier := minimum; identifier <= maximum; identifier++ {
|
||||
if _, ok := known[identifier]; !ok {
|
||||
identifiers = append(identifiers, strconv.FormatInt(identifier, 10))
|
||||
}
|
||||
request := t.bagRequest("")
|
||||
if identifier != "" {
|
||||
request.Headers["X-Apple-Store-Front"] = strings.TrimSpace(storeFront)
|
||||
} else {
|
||||
request.URL += "&cc=" + url.QueryEscape(country)
|
||||
}
|
||||
|
||||
return identifiers, nil
|
||||
}
|
||||
|
||||
func (t *appstore) discoverStorefrontCountryCode(identifier string) (string, bool, error) {
|
||||
if _, err := strconv.ParseInt(identifier, 10, 64); err != nil {
|
||||
return "", false, nil
|
||||
}
|
||||
|
||||
if t.storefrontClient == nil {
|
||||
return "", false, errors.New("storefront client is not configured")
|
||||
}
|
||||
|
||||
res, err := t.storefrontClient.Send(http.Request{
|
||||
URL: storefrontGenreURL,
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatRaw,
|
||||
NoRedirects: true,
|
||||
Headers: map[string]string{
|
||||
"X-Apple-Store-Front": identifier + "-2,29",
|
||||
},
|
||||
})
|
||||
response, err := t.storefrontBagClient.Send(request)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("storefront country code request failed: %w", err)
|
||||
return storefrontMapping{}, fmt.Errorf("storefront bag request failed: %w", err)
|
||||
}
|
||||
|
||||
if (res.StatusCode >= gohttp.StatusMultipleChoices && res.StatusCode < gohttp.StatusBadRequest) || res.StatusCode == gohttp.StatusNotFound {
|
||||
return "", false, nil
|
||||
if response.StatusCode != gohttp.StatusOK {
|
||||
return storefrontMapping{}, NewErrorWithMetadata(errors.New("storefront bag request failed"), response)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return "", false, NewErrorWithMetadata(errors.New("storefront country code request failed"), res)
|
||||
}
|
||||
bag := response.Data
|
||||
id := fmt.Sprint(bag.StorefrontID)
|
||||
code := strings.ToUpper(strings.TrimSpace(bag.CountryCode))
|
||||
|
||||
var page storefrontGenrePage
|
||||
|
||||
if err = json.Unmarshal(res.Data, &page); err != nil {
|
||||
return "", false, fmt.Errorf("failed to decode storefront country code: %w", err)
|
||||
}
|
||||
|
||||
var (
|
||||
countryCode string
|
||||
foundIdentifier bool
|
||||
)
|
||||
|
||||
for _, data := range page.StorePlatformData {
|
||||
storefront := data.Meta.Storefront
|
||||
if storefront.ID == identifier {
|
||||
foundIdentifier = true
|
||||
countryCode = strings.ToUpper(strings.TrimSpace(storefront.CountryCode))
|
||||
|
||||
break
|
||||
if validStorefrontIdentifier(id) && validStorefrontCountry(code) &&
|
||||
(identifier == "" || id == identifier) && (country == "" || code == country) {
|
||||
if t.storefrontCountryCodes == nil {
|
||||
t.storefrontCountryCodes = make(map[string]string)
|
||||
}
|
||||
|
||||
t.storefrontCountryCodes[id] = code
|
||||
|
||||
return storefrontMapping{id: id, country: code}, nil
|
||||
}
|
||||
|
||||
if !foundIdentifier {
|
||||
return "", false, nil
|
||||
// Older bag formats can omit the identity metadata. Their advertised list
|
||||
// remains a dynamic fallback; never guess an endpoint or a country mapping.
|
||||
endpoint := bag.URLBag.AvailableStorefrontsURL
|
||||
if endpoint == "" {
|
||||
endpoint = bag.AvailableStorefrontsURL
|
||||
}
|
||||
|
||||
if len(countryCode) != 2 {
|
||||
return "", false, errors.New("storefront country code response contains no country code")
|
||||
if err := t.discoverAvailableStorefronts(endpoint); err != nil {
|
||||
return storefrontMapping{}, err
|
||||
}
|
||||
|
||||
for _, character := range countryCode {
|
||||
if character < 'A' || character > 'Z' {
|
||||
return "", false, errors.New("storefront country code response contains an invalid country code")
|
||||
}
|
||||
if mapping := findStorefrontMapping(t.storefrontCountryCodes, identifier, country); mapping.id != "" {
|
||||
return mapping, nil
|
||||
}
|
||||
|
||||
t.storefrontsMu.Lock()
|
||||
defer t.storefrontsMu.Unlock()
|
||||
|
||||
for knownIdentifier, knownCountryCode := range t.storefrontCountryCodes {
|
||||
if knownCountryCode == countryCode && knownIdentifier != identifier {
|
||||
return "", false, nil
|
||||
}
|
||||
if identifier != "" {
|
||||
return storefrontMapping{}, storefrontMappingError(storeFront)
|
||||
}
|
||||
|
||||
t.storefrontCountryCodes[identifier] = countryCode
|
||||
|
||||
return countryCode, true, nil
|
||||
return storefrontMapping{}, fmt.Errorf("store front mapping for country code (%s) was not found", country)
|
||||
}
|
||||
|
||||
func (t *appstore) discoverAvailableStorefronts() error {
|
||||
t.storefrontsMu.Lock()
|
||||
defer t.storefrontsMu.Unlock()
|
||||
|
||||
if t.storefrontCountryCodes != nil {
|
||||
// Called with storefrontsMu held. Partial mappings from scoped bags do not mean
|
||||
// the full list has been loaded, and loading it must preserve those mappings.
|
||||
func (t *appstore) discoverAvailableStorefronts(endpoint string) error {
|
||||
if t.storefrontListLoaded {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -239,10 +146,15 @@ func (t *appstore) discoverAvailableStorefronts() error {
|
||||
return errors.New("storefront client is not configured")
|
||||
}
|
||||
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.User != nil || u.Fragment != "" || (u.Port() != "" && u.Port() != "443") ||
|
||||
(!strings.EqualFold(u.Hostname(), "apple.com") && !strings.HasSuffix(strings.ToLower(u.Hostname()), ".apple.com")) {
|
||||
return errors.New("invalid available-storefronts endpoint in bag")
|
||||
}
|
||||
|
||||
res, err := t.storefrontClient.Send(http.Request{
|
||||
URL: availableStorefrontsURL,
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatRaw,
|
||||
URL: endpoint, Method: http.MethodGET, ResponseFormat: http.ResponseFormatRaw,
|
||||
Headers: map[string]string{"Accept": "application/xml", "User-Agent": storeAuthenticationUserAgent},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("available storefronts request failed: %w", err)
|
||||
@@ -260,23 +172,59 @@ func (t *appstore) discoverAvailableStorefronts() error {
|
||||
countryCodes := make(map[string]string, len(result.Storefronts))
|
||||
|
||||
for _, storefront := range result.Storefronts {
|
||||
countryCode := strings.ToUpper(strings.TrimSpace(storefront.CountryCode))
|
||||
if storefront.ID <= 0 || countryCode == "" {
|
||||
continue
|
||||
code := strings.ToUpper(strings.TrimSpace(storefront.CountryCode))
|
||||
if storefront.ID > 0 && validStorefrontCountry(code) {
|
||||
countryCodes[strconv.FormatInt(storefront.ID, 10)] = code
|
||||
}
|
||||
|
||||
countryCodes[strconv.FormatInt(storefront.ID, 10)] = countryCode
|
||||
}
|
||||
|
||||
if len(countryCodes) == 0 {
|
||||
return errors.New("available storefronts response contains no storefronts")
|
||||
}
|
||||
|
||||
t.storefrontCountryCodes = countryCodes
|
||||
if t.storefrontCountryCodes == nil {
|
||||
t.storefrontCountryCodes = make(map[string]string)
|
||||
}
|
||||
|
||||
for id, code := range countryCodes {
|
||||
if t.storefrontCountryCodes[id] == "" {
|
||||
t.storefrontCountryCodes[id] = code
|
||||
}
|
||||
}
|
||||
|
||||
t.storefrontListLoaded = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func findStorefrontMapping(countryCodes map[string]string, identifier, country string) storefrontMapping {
|
||||
if identifier != "" {
|
||||
if code := countryCodes[identifier]; code != "" {
|
||||
return storefrontMapping{id: identifier, country: code}
|
||||
}
|
||||
|
||||
return storefrontMapping{}
|
||||
}
|
||||
|
||||
for id, code := range countryCodes {
|
||||
if code == country {
|
||||
return storefrontMapping{id: id, country: code}
|
||||
}
|
||||
}
|
||||
|
||||
return storefrontMapping{}
|
||||
}
|
||||
|
||||
func validStorefrontIdentifier(value string) bool {
|
||||
identifier, err := strconv.ParseInt(value, 10, 64)
|
||||
|
||||
return err == nil && identifier > 0 && strconv.FormatInt(identifier, 10) == value
|
||||
}
|
||||
|
||||
func validStorefrontCountry(value string) bool {
|
||||
return len(value) == 2 && value[0] >= 'A' && value[0] <= 'Z' && value[1] >= 'A' && value[1] <= 'Z'
|
||||
}
|
||||
|
||||
func countryCodeFromStoreFront(storeFront string, countryCodes map[string]string) (string, error) {
|
||||
identifier := storefrontIdentifier(storeFront)
|
||||
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
const discoveredStorefrontListURL = "https://itunes.apple.com/discovered/storefronts?revision=fixture"
|
||||
|
||||
func scopedStorefrontBag(identifier any, country string) http.Result[storefrontBagResult] {
|
||||
return http.Result[storefrontBagResult]{StatusCode: 200, Data: storefrontBagResult{StorefrontID: identifier, CountryCode: country, AvailableStorefrontsURL: discoveredStorefrontListURL}}
|
||||
}
|
||||
|
||||
var _ = Describe("Dynamic storefront discovery", func() {
|
||||
var store *appstore
|
||||
var bags *http.MockClient[storefrontBagResult]
|
||||
var lists *http.MockClient[[]byte]
|
||||
BeforeEach(func() {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
bags = http.NewMockClient[storefrontBagResult](ctrl)
|
||||
lists = http.NewMockClient[[]byte](ctrl)
|
||||
store = &appstore{storefrontBagClient: bags, storefrontClient: lists}
|
||||
})
|
||||
|
||||
DescribeTable("resolves and caches a scoped bag without requesting the unstable global list", func(identifier, country, suffix string) {
|
||||
bags.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[storefrontBagResult], error) {
|
||||
Expect(request.URL).To(Equal("https://init.itunes.apple.com/bag.xml?ix=6"))
|
||||
Expect(request.Headers["User-Agent"]).To(Equal(storeAuthenticationUserAgent))
|
||||
Expect(request.Headers["X-Apple-Store-Front"]).To(Equal(identifier + suffix))
|
||||
Expect(request.ResponseFormat).To(Equal(http.ResponseFormatXML))
|
||||
|
||||
return scopedStorefrontBag(identifier, country), nil
|
||||
}).Times(1)
|
||||
lists.EXPECT().Send(gomock.Any()).Times(0)
|
||||
Expect(store.countryCodeFromStoreFront(identifier + suffix)).To(Equal(country))
|
||||
Expect(store.countryCodeFromStoreFront(identifier)).To(Equal(country))
|
||||
Expect(store.discoverStorefrontID(country)).To(Equal(identifier))
|
||||
}, Entry("Vietnam, issue 670", "143471", "VN", "-1,34"), Entry("Japan", "143462", "JP", "-1,34"), Entry("bare ID", "143469", "RU", ""), Entry("new server-provided country mapping", "987654", "ZZ", "-1,34"))
|
||||
|
||||
It("resolves a phone account's country directly, including countries omitted from the global list", func() {
|
||||
bags.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[storefrontBagResult], error) {
|
||||
endpoint, err := url.Parse(request.URL)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(endpoint.Query().Get("cc")).To(Equal("CN"))
|
||||
Expect(request.Headers).NotTo(HaveKey("X-Apple-Store-Front"))
|
||||
|
||||
return scopedStorefrontBag("143465", "CN"), nil
|
||||
}).Times(1)
|
||||
Expect(store.discoverStorefrontID(" cn ")).To(Equal("143465"))
|
||||
Expect(store.countryCodeFromStoreFront("143465-19,29")).To(Equal("CN"))
|
||||
})
|
||||
|
||||
DescribeTable("uses the endpoint advertised by bags without storefront metadata", func(nested bool) {
|
||||
bag := scopedStorefrontBag(nil, "")
|
||||
if nested {
|
||||
bag.Data.URLBag.AvailableStorefrontsURL = discoveredStorefrontListURL + "&nested=true"
|
||||
}
|
||||
endpoint := discoveredStorefrontListURL
|
||||
if nested {
|
||||
endpoint += "&nested=true"
|
||||
}
|
||||
bags.EXPECT().Send(gomock.Any()).Return(bag, nil).Times(1)
|
||||
lists.EXPECT().Send(gomock.Any()).DoAndReturn(func(request http.Request) (http.Result[[]byte], error) {
|
||||
Expect(request.URL).To(Equal(endpoint))
|
||||
Expect(request.Headers["User-Agent"]).To(Equal(storeAuthenticationUserAgent))
|
||||
|
||||
return http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil
|
||||
}).Times(1)
|
||||
Expect(store.countryCodeFromStoreFront("143441-1,34")).To(Equal("US"))
|
||||
Expect(store.countryCodeFromStoreFront("143443")).To(Equal("DE"))
|
||||
}, Entry("top-level bag", false), Entry("nested URL bag", true))
|
||||
|
||||
It("does not mistake a partially populated cache for the complete list", func() {
|
||||
gomock.InOrder(bags.EXPECT().Send(gomock.Any()).Return(scopedStorefrontBag("143471", "VN"), nil), bags.EXPECT().Send(gomock.Any()).Return(scopedStorefrontBag(nil, ""), nil))
|
||||
lists.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil).Times(1)
|
||||
Expect(store.countryCodeFromStoreFront("143471")).To(Equal("VN"))
|
||||
Expect(store.countryCodeFromStoreFront("143443")).To(Equal("DE"))
|
||||
Expect(store.countryCodeFromStoreFront("143471")).To(Equal("VN"))
|
||||
Expect(store.countryCodeFromStoreFront("143441")).To(Equal("US"))
|
||||
})
|
||||
|
||||
DescribeTable("does not accept Apple's default storefront for an unmatched request", func(byCountry bool) {
|
||||
bags.EXPECT().Send(gomock.Any()).Return(scopedStorefrontBag("143441", "US"), nil)
|
||||
lists.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil)
|
||||
if byCountry {
|
||||
_, err := store.discoverStorefrontID("ZZ")
|
||||
Expect(err).To(MatchError(ContainSubstring("mapping for country code (ZZ) was not found")))
|
||||
} else {
|
||||
_, err := store.countryCodeFromStoreFront("999999")
|
||||
Expect(err).To(MatchError("country code mapping for store front (999999) was not found"))
|
||||
Expect(store.storefrontCountryCodes).NotTo(HaveKey("999999"))
|
||||
}
|
||||
}, Entry("unknown ID", false), Entry("unknown country", true))
|
||||
|
||||
It("does not poison discovery after a transient list 404", func() {
|
||||
gomock.InOrder(bags.EXPECT().Send(gomock.Any()).Return(scopedStorefrontBag(nil, ""), nil), bags.EXPECT().Send(gomock.Any()).Return(scopedStorefrontBag("143471", "VN"), nil))
|
||||
lists.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 404}, nil).Times(1)
|
||||
_, err := store.countryCodeFromStoreFront("143471")
|
||||
Expect(err).To(MatchError(ContainSubstring("available storefronts request failed")))
|
||||
Expect(store.storefrontListLoaded).To(BeFalse())
|
||||
Expect(store.countryCodeFromStoreFront("143471")).To(Equal("VN"))
|
||||
})
|
||||
|
||||
It("retries bag discovery on a later call after a transport failure", func() {
|
||||
failure := errors.New("connection reset")
|
||||
gomock.InOrder(bags.EXPECT().Send(gomock.Any()).Return(http.Result[storefrontBagResult]{}, failure), bags.EXPECT().Send(gomock.Any()).Return(scopedStorefrontBag("143471", "VN"), nil))
|
||||
_, err := store.countryCodeFromStoreFront("143471")
|
||||
Expect(errors.Is(err, failure)).To(BeTrue())
|
||||
Expect(store.countryCodeFromStoreFront("143471")).To(Equal("VN"))
|
||||
})
|
||||
|
||||
DescribeTable("rejects unusable list responses without caching them", func(status int, body []byte, message string) {
|
||||
bags.EXPECT().Send(gomock.Any()).Return(scopedStorefrontBag(nil, ""), nil)
|
||||
lists.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: status, Data: body}, nil)
|
||||
_, err := store.countryCodeFromStoreFront("143441")
|
||||
Expect(err).To(MatchError(ContainSubstring(message)))
|
||||
Expect(store.storefrontListLoaded).To(BeFalse())
|
||||
}, Entry("HTTP error", 503, nil, "available storefronts request failed"), Entry("invalid plist", 200, []byte("not plist"), "failed to decode available storefronts"), Entry("empty list", 200, []byte(`<plist><dict><key>storefronts</key><array/></dict></plist>`), "contains no storefronts"), Entry("invalid countries", 200, []byte(`<plist><dict><key>storefronts</key><array><dict><key>id</key><integer>1</integer><key>country-code</key><string>bad</string></dict></array></dict></plist>`), "contains no storefronts"))
|
||||
|
||||
DescribeTable("rejects untrusted list endpoints without contacting them", func(endpoint string) {
|
||||
bag := scopedStorefrontBag(nil, "")
|
||||
bag.Data.AvailableStorefrontsURL = endpoint
|
||||
bags.EXPECT().Send(gomock.Any()).Return(bag, nil)
|
||||
_, err := store.countryCodeFromStoreFront("143441")
|
||||
Expect(err).To(MatchError("invalid available-storefronts endpoint in bag"))
|
||||
}, Entry("absent", ""), Entry("HTTP", "http://itunes.apple.com/storefronts"), Entry("credentials", "https://user@itunes.apple.com/storefronts"), Entry("foreign host", "https://apple.com.example.com/storefronts"), Entry("fragment", "https://itunes.apple.com/storefronts#other"), Entry("custom port", "https://itunes.apple.com:8080/storefronts"))
|
||||
|
||||
DescribeTable("rejects malformed storefront identifiers before network access", func(value string) {
|
||||
_, err := store.countryCodeFromStoreFront(value)
|
||||
Expect(err).To(HaveOccurred())
|
||||
}, Entry("empty", ""), Entry("zero", "0"), Entry("negative", "-1"), Entry("text", "invalid"), Entry("overflow", "99999999999999999999"))
|
||||
|
||||
DescribeTable("decodes both numeric and string bag identifiers", func(encoded string) {
|
||||
var bag storefrontBagResult
|
||||
_, err := plist.Unmarshal([]byte(fmt.Sprintf(`<plist><dict><key>storeFrontId</key>%s<key>currentStorefrontCountryCodeISO2A</key><string>VN</string></dict></plist>`, encoded)), &bag)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[storefrontBagResult]{StatusCode: 200, Data: bag}, nil)
|
||||
Expect(store.countryCodeFromStoreFront("143471")).To(Equal("VN"))
|
||||
}, Entry("string", "<string>143471</string>"), Entry("integer", "<integer>143471</integer>"))
|
||||
})
|
||||
Reference in new issue
Block a user