mirror of
https://github.com/majd/ipatool
synced 2026-11-28 10:17:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b02b4c555 | ||
|
|
d69faf83c8 | ||
|
|
5a6dfe0582 | ||
|
|
b352566155 | ||
|
|
6194bf4ecd | ||
|
|
20290220cd | ||
|
|
3e84853e2e | ||
|
|
2cfd33fa45 | ||
|
|
e4b0aaee61 | ||
|
|
9df35a6d84 | ||
|
|
8771e57445 | ||
|
|
e0e2908dc8 | ||
|
|
f137223276 | ||
|
|
536d7bacc1 | ||
|
|
856323251a | ||
|
|
0d99fc2d96 |
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)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/majd/go-apfs/pkg/disk"
|
||||
"github.com/majd/go-apfs/pkg/disk/dmg"
|
||||
"github.com/majd/go-apfs/types"
|
||||
"github.com/majd/ipatool/v2/internal/sap/machimage"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -74,7 +75,7 @@ func extractAPFSFiles(ctx context.Context, source io.ReaderAt, size int64, paths
|
||||
if err := ctx.Err(); err != nil {
|
||||
return fmt.Errorf("extract Apple filesystem files: %w", err)
|
||||
}
|
||||
if err := extractor.extractFile(ctx, path, destination); err != nil {
|
||||
if err := extractor.extractImageFile(ctx, path, destination, filepath.Ext(path) != ".icxs"); err != nil {
|
||||
return fmt.Errorf("extract %s from Apple filesystem: %w", path, err)
|
||||
}
|
||||
}
|
||||
@@ -129,7 +130,7 @@ func newAPFSExtractor(source io.ReaderAt, size int64) (*apfsExtractor, func() er
|
||||
return extractor, closeExtractor, nil
|
||||
}
|
||||
|
||||
func (e *apfsExtractor) extractFile(ctx context.Context, path, destination string) (err error) {
|
||||
func (e *apfsExtractor) extractImageFile(ctx context.Context, path, destination string, thin bool) (err error) {
|
||||
file, err := e.openFile(ctx, path)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -150,8 +151,15 @@ func (e *apfsExtractor) extractFile(ctx context.Context, path, destination strin
|
||||
}
|
||||
}()
|
||||
|
||||
reader := &contextReader{ctx: ctx, reader: io.NewSectionReader(file, 0, file.size)}
|
||||
if _, err := io.CopyN(output, reader, file.size); err != nil {
|
||||
offset, size := int64(0), file.size
|
||||
if thin {
|
||||
offset, size, err = machimage.ARM64Range(file, file.size)
|
||||
if err != nil {
|
||||
return fmt.Errorf("select runtime image architecture: %w", err)
|
||||
}
|
||||
}
|
||||
reader := &contextReader{ctx: ctx, reader: io.NewSectionReader(file, offset, size)}
|
||||
if _, err := io.CopyN(output, reader, size); err != nil {
|
||||
return fmt.Errorf("copy file data: %w", err)
|
||||
}
|
||||
|
||||
|
||||
+173
-25
@@ -1,22 +1,27 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/machimage"
|
||||
)
|
||||
|
||||
const (
|
||||
macOSVersion = "27.0.1"
|
||||
macOSBuild = "26A434"
|
||||
macOSRestoreURL = "https://updates.cdn-apple.com/2026FallFCS/59241290-5d51-4ca8-9df4-31624b9a4eac/UniversalMac_27.0.1_26A434_Restore.ipsw"
|
||||
assetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v4"
|
||||
macOSVersion = "27.0.1"
|
||||
macOSBuild = "26A434"
|
||||
macOSRestoreURL = "https://updates.cdn-apple.com/2026FallFCS/59241290-5d51-4ca8-9df4-31624b9a4eac/UniversalMac_27.0.1_26A434_Restore.ipsw"
|
||||
assetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v5"
|
||||
legacyAssetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v4"
|
||||
)
|
||||
|
||||
type Bundle struct {
|
||||
@@ -36,6 +41,16 @@ type fileSpec struct {
|
||||
}
|
||||
|
||||
var requiredFiles = []fileSpec{
|
||||
{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
|
||||
{name: "commerce", size: 2735088, digest: mustDigest("c4b2088dd39aeb353f59cb57597902e8317aec66ae7da0414b03c5f932771343")},
|
||||
{name: "adid", size: 3047808, digest: mustDigest("43419a206c28bc93ecb8884256088d18306a0a462350f83adbced8e60a94e390")},
|
||||
{name: "CoreFP", size: 30764976, digest: mustDigest("afbc123e688a822d980d5816cc2b52f69fde669d1dca92cf85627e1cbee587f6")},
|
||||
{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
|
||||
{name: "fairplayd", size: 17389744, digest: mustDigest("1e58d37e9602dd0ca5e24b14762063b6c310248b4d3a94272771d815e4ea1784")},
|
||||
{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
|
||||
}
|
||||
|
||||
var legacyFiles = []fileSpec{
|
||||
{
|
||||
name: "AppleMediaServices",
|
||||
size: 14813888,
|
||||
@@ -73,9 +88,21 @@ var requiredFiles = []fileSpec{
|
||||
},
|
||||
}
|
||||
|
||||
// Load resolves and caches the pinned macOS framework profile used by SAP,
|
||||
// kbsync generation, and package decryption.
|
||||
type bundleLoader struct {
|
||||
gate chan struct{}
|
||||
installed *Bundle
|
||||
resolve func(context.Context) (Bundle, error)
|
||||
}
|
||||
|
||||
var defaultLoader = bundleLoader{gate: make(chan struct{}, 1), resolve: loadBundle}
|
||||
|
||||
// Load resolves and verifies the pinned macOS framework profile once per process.
|
||||
// The returned slices are shared and must not be modified by callers.
|
||||
func Load(ctx context.Context) (Bundle, error) {
|
||||
return defaultLoader.load(ctx)
|
||||
}
|
||||
|
||||
func (l *bundleLoader) load(ctx context.Context) (Bundle, error) {
|
||||
if ctx == nil {
|
||||
return Bundle{}, errors.New("apple asset context is nil")
|
||||
}
|
||||
@@ -84,12 +111,43 @@ func Load(ctx context.Context) (Bundle, error) {
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case l.gate <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", ctx.Err())
|
||||
}
|
||||
|
||||
defer func() { <-l.gate }()
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
|
||||
}
|
||||
|
||||
if l.installed != nil {
|
||||
return *l.installed, nil
|
||||
}
|
||||
|
||||
bundle, err := l.resolve(ctx)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
|
||||
}
|
||||
|
||||
l.installed = &bundle
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func loadBundle(ctx context.Context) (Bundle, error) {
|
||||
directory, err := cacheDirectory()
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if bundle, err := readCache(directory); err == nil {
|
||||
if bundle, found := loadCachedBundle(directory); found {
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
@@ -105,6 +163,44 @@ func Load(ctx context.Context) (Bundle, error) {
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
// Keep only the architecture used by the emulator after verifying and caching
|
||||
// the original files. Cloning releases the unused slices of universal binaries.
|
||||
func compactBundle(bundle Bundle) (Bundle, error) {
|
||||
for _, image := range []struct {
|
||||
name string
|
||||
data *[]byte
|
||||
}{
|
||||
{"AppleMediaServices", &bundle.AppleMediaServices},
|
||||
{"commerce", &bundle.Commerce},
|
||||
{"adid", &bundle.ADID},
|
||||
{"CoreFP", &bundle.CoreFP},
|
||||
{"fairplayd", &bundle.FairPlayD},
|
||||
{"FairPlayIOKit", &bundle.FairPlayKext},
|
||||
} {
|
||||
data, err := compactImage(image.name, *image.data)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
*image.data = data
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func compactImage(name string, input []byte) ([]byte, error) {
|
||||
data, err := machimage.ARM64Slice(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("select %s architecture: %w", name, err)
|
||||
}
|
||||
|
||||
if len(data) != len(input) {
|
||||
return bytes.Clone(data), nil
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func cacheDirectory() (string, error) {
|
||||
root, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
@@ -114,11 +210,38 @@ func cacheDirectory() (string, error) {
|
||||
return filepath.Join(root, "ipatool", "sap", assetCacheDirectory), nil
|
||||
}
|
||||
|
||||
func readCache(directory string) (Bundle, error) {
|
||||
files := make(map[string][]byte, len(requiredFiles))
|
||||
func loadCachedBundle(directory string) (Bundle, bool) {
|
||||
if bundle, err := readCache(directory); err == nil {
|
||||
return bundle, true
|
||||
}
|
||||
|
||||
for _, spec := range requiredFiles {
|
||||
data, err := readCacheFile(filepath.Join(directory, spec.name), spec.size)
|
||||
legacyDirectory := filepath.Join(filepath.Dir(directory), legacyAssetCacheDirectory)
|
||||
|
||||
bundle, err := readCacheSpecs(legacyDirectory, legacyFiles)
|
||||
if err != nil {
|
||||
return Bundle{}, false
|
||||
}
|
||||
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, false
|
||||
}
|
||||
|
||||
// A verified legacy cache remains usable on read-only mounts. Persist the
|
||||
// smaller representation when possible without requiring a new download.
|
||||
_ = writeCache(directory, bundle)
|
||||
|
||||
return bundle, true
|
||||
}
|
||||
|
||||
func readCache(directory string) (Bundle, error) {
|
||||
return readCacheSpecs(directory, requiredFiles)
|
||||
}
|
||||
|
||||
func readCacheSpecs(directory string, specs []fileSpec) (Bundle, error) {
|
||||
files := make(map[string][]byte, len(specs))
|
||||
|
||||
for _, spec := range specs {
|
||||
data, err := readCacheData(filepath.Join(directory, spec.name), spec.size, &spec)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read cached Apple SAP asset %s: %w", spec.name, err)
|
||||
}
|
||||
@@ -126,15 +249,14 @@ func readCache(directory string) (Bundle, error) {
|
||||
files[spec.name] = data
|
||||
}
|
||||
|
||||
bundle := bundleFrom(files)
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
return bundleFrom(files), nil
|
||||
}
|
||||
|
||||
func readCacheFile(path string, expectedSize int) ([]byte, error) {
|
||||
return readCacheData(path, expectedSize, nil)
|
||||
}
|
||||
|
||||
func readCacheData(path string, expectedSize int, spec *fileSpec) ([]byte, error) {
|
||||
if expectedSize < 0 {
|
||||
return nil, errors.New("invalid expected size")
|
||||
}
|
||||
@@ -155,8 +277,23 @@ func readCacheFile(path string, expectedSize int) ([]byte, error) {
|
||||
return nil, fmt.Errorf("has size %d, expected %d", info.Size(), expectedSize)
|
||||
}
|
||||
|
||||
data := make([]byte, expectedSize)
|
||||
if _, err := io.ReadFull(file, data); err != nil {
|
||||
var reader io.Reader = file
|
||||
|
||||
var digest hash.Hash
|
||||
if spec != nil {
|
||||
digest = sha256.New()
|
||||
reader = io.TeeReader(file, digest)
|
||||
}
|
||||
|
||||
var data []byte
|
||||
if spec != nil && spec.name != "CoreFP.icxs" {
|
||||
data, err = machimage.ReadARM64(reader, expectedSize)
|
||||
} else {
|
||||
data = make([]byte, expectedSize)
|
||||
_, err = io.ReadFull(reader, data)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read cached asset: %w", err)
|
||||
}
|
||||
|
||||
@@ -167,6 +304,10 @@ func readCacheFile(path string, expectedSize int) ([]byte, error) {
|
||||
return nil, fmt.Errorf("verify cached asset length: %w", err)
|
||||
}
|
||||
|
||||
if spec != nil && !bytes.Equal(digest.Sum(nil), spec.digest[:]) {
|
||||
return nil, fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
@@ -232,14 +373,21 @@ func replaceFile(path string, data []byte) error {
|
||||
func validate(bundle Bundle) error {
|
||||
files := bundleFiles(bundle)
|
||||
for _, spec := range requiredFiles {
|
||||
data := files[spec.name]
|
||||
if len(data) != spec.size {
|
||||
return fmt.Errorf("apple SAP asset %s has size %d, expected %d", spec.name, len(data), spec.size)
|
||||
if err := validateFile(spec, files[spec.name]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if sha256.Sum256(data) != spec.digest {
|
||||
return fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateFile(spec fileSpec, data []byte) error {
|
||||
if len(data) != spec.size {
|
||||
return fmt.Errorf("apple SAP asset %s has size %d, expected %d", spec.name, len(data), spec.size)
|
||||
}
|
||||
|
||||
if sha256.Sum256(data) != spec.digest {
|
||||
return fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Verified bundle cache", func() {
|
||||
It("shares one successful load across concurrent callers", func() {
|
||||
var calls atomic.Int32
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
data := []byte("verified bundle")
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls.Add(1)
|
||||
close(entered)
|
||||
<-release
|
||||
|
||||
return Bundle{CoreFP: data}, nil
|
||||
}}
|
||||
var workers sync.WaitGroup
|
||||
results := make(chan Bundle, 8)
|
||||
failures := make(chan error, 8)
|
||||
for range 8 {
|
||||
workers.Go(func() {
|
||||
bundle, err := loader.load(context.Background())
|
||||
results <- bundle
|
||||
failures <- err
|
||||
})
|
||||
}
|
||||
Eventually(entered).Should(BeClosed())
|
||||
close(release)
|
||||
workers.Wait()
|
||||
Expect(calls.Load()).To(Equal(int32(1)))
|
||||
for range 8 {
|
||||
Expect(<-failures).NotTo(HaveOccurred())
|
||||
Expect(&(<-results).CoreFP[0]).To(BeIdenticalTo(&data[0]))
|
||||
}
|
||||
})
|
||||
|
||||
It("lets a waiting caller cancel without interrupting the load", func() {
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
close(entered)
|
||||
<-release
|
||||
|
||||
return Bundle{CoreFP: []byte("ready")}, nil
|
||||
}}
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := loader.load(context.Background()); done <- err }()
|
||||
Eventually(entered).Should(BeClosed())
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err := loader.load(ctx)
|
||||
Expect(errors.Is(err, context.DeadlineExceeded)).To(BeTrue())
|
||||
close(release)
|
||||
Eventually(done).Should(Receive(BeNil()))
|
||||
bundle, err := loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(bundle.CoreFP)).To(Equal("ready"))
|
||||
})
|
||||
|
||||
It("retries failed loads", func() {
|
||||
calls := 0
|
||||
failed := errors.New("temporary failure")
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return Bundle{}, failed
|
||||
}
|
||||
|
||||
return Bundle{CoreFP: []byte("ready")}, nil
|
||||
}}
|
||||
_, err := loader.load(context.Background())
|
||||
Expect(err).To(MatchError(failed))
|
||||
bundle, err := loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(bundle.CoreFP)).To(Equal("ready"))
|
||||
Expect(calls).To(Equal(2))
|
||||
})
|
||||
|
||||
It("does not publish a load canceled before completion", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
calls := 0
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls++
|
||||
cancel()
|
||||
|
||||
return Bundle{CoreFP: []byte("ready")}, nil
|
||||
}}
|
||||
_, err := loader.load(ctx)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(loader.installed).To(BeNil())
|
||||
_, err = loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(calls).To(Equal(2))
|
||||
})
|
||||
|
||||
It("rejects nil and canceled contexts even after a successful load", func() {
|
||||
calls := 0
|
||||
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
|
||||
calls++
|
||||
|
||||
return Bundle{}, nil
|
||||
}}
|
||||
_, err := loader.load(nil) //nolint:staticcheck // Verify invalid caller input.
|
||||
Expect(err).To(MatchError(ContainSubstring("context is nil")))
|
||||
_, err = loader.load(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err = loader.load(ctx)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(calls).To(Equal(1))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Runtime bundle compaction", func() {
|
||||
It("retains independent arm64e images and preserves thin images and ICXS", func() {
|
||||
fat := make([]byte, 32)
|
||||
for i, value := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
|
||||
binary.BigEndian.PutUint32(fat[i*4:], value)
|
||||
}
|
||||
copy(fat[28:], "arm!")
|
||||
thin, icxs := []byte("thin"), []byte("ICXS")
|
||||
bundle := Bundle{CoreFP: fat, Commerce: fat, ADID: fat, FairPlayD: fat, AppleMediaServices: thin, FairPlayKext: thin, CoreFPICXS: icxs}
|
||||
original := bytes.Clone(fat)
|
||||
compact, err := compactBundle(bundle)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
for _, data := range [][]byte{compact.CoreFP, compact.Commerce, compact.ADID, compact.FairPlayD} {
|
||||
Expect(string(data)).To(Equal("arm!"))
|
||||
Expect(&data[0]).NotTo(BeIdenticalTo(&fat[28]))
|
||||
Expect(cap(data)).To(BeNumerically("<", len(fat)))
|
||||
}
|
||||
Expect(&compact.AppleMediaServices[0]).To(BeIdenticalTo(&thin[0]))
|
||||
Expect(&compact.FairPlayKext[0]).To(BeIdenticalTo(&thin[0]))
|
||||
Expect(&compact.CoreFPICXS[0]).To(BeIdenticalTo(&icxs[0]))
|
||||
Expect(fat).To(Equal(original))
|
||||
Expect(bundle.CoreFP).To(HaveLen(32))
|
||||
})
|
||||
It("verifies the entire cached file before discarding unused architectures", func() {
|
||||
fat := make([]byte, 40)
|
||||
for i, value := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
|
||||
binary.BigEndian.PutUint32(fat[i*4:], value)
|
||||
}
|
||||
copy(fat[28:], "arm!unused!!")
|
||||
originalSpecs := requiredFiles
|
||||
DeferCleanup(func() { requiredFiles = originalSpecs })
|
||||
requiredFiles = []fileSpec{{name: "CoreFP", size: len(fat), digest: sha256.Sum256(fat)}}
|
||||
directory := GinkgoT().TempDir()
|
||||
path := filepath.Join(directory, "CoreFP")
|
||||
Expect(os.WriteFile(path, fat, 0o600)).To(Succeed())
|
||||
bundle, err := readCache(directory)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(bundle.CoreFP)).To(Equal("arm!"))
|
||||
cached, err := os.ReadFile(path)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(cached).To(Equal(fat))
|
||||
fat[len(fat)-1] ^= 0xff
|
||||
Expect(os.WriteFile(path, fat, 0o600)).To(Succeed())
|
||||
_, err = readCache(directory)
|
||||
Expect(err).To(MatchError(ContainSubstring("failed integrity verification")))
|
||||
})
|
||||
|
||||
It("rejects invalid universal images", func() {
|
||||
fat := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(fat, types.MagicFat.Int())
|
||||
_, err := compactBundle(Bundle{CoreFP: fat})
|
||||
Expect(err).To(MatchError(ContainSubstring("select CoreFP architecture")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Buffered remote ranges", func() {
|
||||
var source []byte
|
||||
var remote *remoteFile
|
||||
var requests []string
|
||||
var mu sync.Mutex
|
||||
BeforeEach(func() {
|
||||
source = make([]byte, 1<<20)
|
||||
for n := range source {
|
||||
source[n] = byte(n % 251)
|
||||
}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
requests = append(requests, r.Header.Get("Range"))
|
||||
mu.Unlock()
|
||||
http.ServeContent(w, r, "image", time.Time{}, bytes.NewReader(source))
|
||||
}))
|
||||
DeferCleanup(server.Close)
|
||||
requests = nil
|
||||
remote = &remoteFile{ctx: context.Background(), client: server.Client(), url: server.URL, size: int64(len(source))}
|
||||
})
|
||||
It("serves a small sequential stream in bounded larger transfers", func() {
|
||||
output := make([]byte, len(source))
|
||||
for offset := 0; offset < len(output); offset += 4096 {
|
||||
count, err := remote.ReadAt(output[offset:offset+4096], int64(offset))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(4096))
|
||||
}
|
||||
Expect(output).To(Equal(source))
|
||||
mu.Lock()
|
||||
count := len(requests)
|
||||
mu.Unlock()
|
||||
Expect(count).To(Equal(5))
|
||||
Expect(len(remote.cache)).To(BeNumerically("<=", remoteReadAheadSize))
|
||||
})
|
||||
It("keeps sparse metadata requests exact", func() {
|
||||
for _, offset := range []int64{0, 500000, 900000} {
|
||||
output := make([]byte, 8)
|
||||
_, err := remote.ReadAt(output, offset)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(output).To(Equal(source[offset : offset+8]))
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
Expect(requests).To(Equal([]string{"bytes=0-7", "bytes=500000-500007", "bytes=900000-900007"}))
|
||||
})
|
||||
It("isolates cached bytes from caller mutation and reports EOF correctly", func() {
|
||||
data := make([]byte, 4096)
|
||||
_, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
clear(data)
|
||||
_, err = remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(data).To(Equal(source[:4096]))
|
||||
tail := make([]byte, 32)
|
||||
count, err := remote.ReadAt(tail, int64(len(source)-16))
|
||||
Expect(err).To(MatchError(io.EOF))
|
||||
Expect(count).To(Equal(16))
|
||||
Expect(tail[:count]).To(Equal(source[len(source)-16:]))
|
||||
})
|
||||
It("honors cancellation even when data is buffered", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
remote.ctx = ctx
|
||||
data := make([]byte, 32)
|
||||
_, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
cancel()
|
||||
_, err = remote.ReadAt(data, 0)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
})
|
||||
It("supports concurrent independent reads", func() {
|
||||
finished := make(chan error, 8)
|
||||
for n := range 8 {
|
||||
go func() {
|
||||
offset := int64(n * 40000)
|
||||
output := make([]byte, 4096)
|
||||
_, err := remote.ReadAt(output, offset)
|
||||
if err == nil && !bytes.Equal(output, source[offset:offset+4096]) {
|
||||
err = errors.New("incorrect concurrent range")
|
||||
}
|
||||
finished <- err
|
||||
}()
|
||||
}
|
||||
for range 8 {
|
||||
Eventually(finished).Should(Receive(BeNil()))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Interrupted remote responses", func() {
|
||||
It("resumes a short response at the first unread byte", func() {
|
||||
var ranges []string
|
||||
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 8, client: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
ranges = append(ranges, r.Header.Get("Range"))
|
||||
if len(ranges) == 1 {
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-7/8"}}, Body: io.NopCloser(strings.NewReader("abcd"))}, nil
|
||||
}
|
||||
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 4-7/8"}}, Body: io.NopCloser(strings.NewReader("efgh"))}, nil
|
||||
})}}
|
||||
data := make([]byte, 8)
|
||||
count, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(8))
|
||||
Expect(string(data)).To(Equal("abcdefgh"))
|
||||
Expect(ranges).To(Equal([]string{"bytes=0-7", "bytes=4-7"}))
|
||||
})
|
||||
It("rejects incorrect response ranges without caching them", func() {
|
||||
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 8, client: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 1-7/8"}}, Body: io.NopCloser(strings.NewReader("1234567"))}, nil
|
||||
})}}
|
||||
_, err := remote.ReadAt(make([]byte, 8), 0)
|
||||
Expect(err).To(MatchError(ContainSubstring("server returned bytes")))
|
||||
Expect(remote.cache).To(BeEmpty())
|
||||
})
|
||||
It("does not fail a completed requested prefix when speculative tail reads fail", func() {
|
||||
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 1 << 20}
|
||||
calls := 0
|
||||
remote.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
switch calls {
|
||||
case 1:
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-3/1048576"}}, Body: io.NopCloser(strings.NewReader("abcd"))}, nil
|
||||
case 2:
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{fmt.Sprintf("bytes 4-%d/1048576", 4+remoteReadAheadSize-1)}}, Body: io.NopCloser(strings.NewReader("efgh"))}, nil
|
||||
default:
|
||||
return nil, errors.New("connection interrupted")
|
||||
}
|
||||
})}
|
||||
data := make([]byte, 4)
|
||||
_, err := remote.ReadAt(data, 0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
count, err := remote.ReadAt(data, 4)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(4))
|
||||
Expect(string(data)).To(Equal("efgh"))
|
||||
Expect(remote.cacheOffset).To(BeZero())
|
||||
Expect(remote.cache).To(HaveLen(4))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Remote image size probes", func() {
|
||||
DescribeTable("requires exactly the requested byte", func(body string, valid bool) {
|
||||
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-0/123"}}, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
remote, err := openRemoteFile(context.Background(), client)
|
||||
if valid {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(remote.size).To(Equal(int64(123)))
|
||||
} else {
|
||||
Expect(err).To(MatchError(ContainSubstring("probe has an invalid length")))
|
||||
}
|
||||
}, Entry("one byte", "x", true), Entry("empty body", "", false), Entry("too much data", "xx", false))
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -8,15 +9,26 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const remoteReadAttempts = 3
|
||||
const (
|
||||
remoteReadAttempts = 3
|
||||
restoreImageUserAgent = "Mozilla/5.0"
|
||||
remoteSmallReadSize = 32 << 10
|
||||
remoteReadAheadSize = 256 << 10
|
||||
)
|
||||
|
||||
type remoteFile struct {
|
||||
ctx context.Context
|
||||
client *http.Client
|
||||
url string
|
||||
size int64
|
||||
ctx context.Context
|
||||
client *http.Client
|
||||
url string
|
||||
size int64
|
||||
mu sync.Mutex
|
||||
cache []byte
|
||||
cacheOffset int64
|
||||
previous bool
|
||||
lastEnd int64
|
||||
}
|
||||
|
||||
//nolint:wsl // Request construction and validation are clearer in protocol order.
|
||||
@@ -26,6 +38,7 @@ func openRemoteFile(ctx context.Context, client *http.Client) (*remoteFile, erro
|
||||
return nil, fmt.Errorf("create remote image request: %w", err)
|
||||
}
|
||||
|
||||
request.Header.Set("User-Agent", restoreImageUserAgent)
|
||||
request.Header.Set("Range", "bytes=0-0")
|
||||
response, err := client.Do(request)
|
||||
|
||||
@@ -47,6 +60,14 @@ func openRemoteFile(ctx context.Context, client *http.Client) (*remoteFile, erro
|
||||
return nil, fmt.Errorf("open remote image: server returned unexpected byte range %d-%d", start, end)
|
||||
}
|
||||
|
||||
probe, err := io.ReadAll(io.LimitReader(response.Body, 2))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read remote image probe: %w", err)
|
||||
}
|
||||
if len(probe) != 1 {
|
||||
return nil, errors.New("remote image probe has an invalid length")
|
||||
}
|
||||
|
||||
return &remoteFile{ctx: ctx, client: client, url: macOSRestoreURL, size: size}, nil
|
||||
}
|
||||
|
||||
@@ -97,6 +118,60 @@ func (r *remoteFile) ReadAt(data []byte, offset int64) (int, error) {
|
||||
wanted = int(remaining)
|
||||
}
|
||||
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, fmt.Errorf("read remote image: %w", err)
|
||||
}
|
||||
r.mu.Lock()
|
||||
if offset >= r.cacheOffset && offset+int64(wanted) <= r.cacheOffset+int64(len(r.cache)) {
|
||||
copy(data[:wanted], r.cache[offset-r.cacheOffset:offset-r.cacheOffset+int64(wanted)])
|
||||
r.previous, r.lastEnd = true, offset+int64(wanted)
|
||||
r.mu.Unlock()
|
||||
if wanted != len(data) {
|
||||
return wanted, io.EOF
|
||||
}
|
||||
|
||||
return wanted, nil
|
||||
}
|
||||
// Sparse metadata reads stay exact; only a sequential small-read stream
|
||||
// earns read-ahead. This avoids fetching large unused image regions.
|
||||
ahead := r.previous && offset == r.lastEnd && wanted <= remoteSmallReadSize
|
||||
r.previous, r.lastEnd = true, offset+int64(wanted)
|
||||
r.mu.Unlock()
|
||||
fetchSize := wanted
|
||||
if ahead {
|
||||
fetchSize = int(min(int64(remoteReadAheadSize), r.size-offset))
|
||||
}
|
||||
buffer := data[:wanted]
|
||||
if fetchSize > wanted {
|
||||
buffer = make([]byte, fetchSize)
|
||||
}
|
||||
count, err := r.readRange(buffer, offset)
|
||||
if count == fetchSize && err == nil && fetchSize <= remoteReadAheadSize {
|
||||
cached := buffer
|
||||
if fetchSize == wanted {
|
||||
cached = bytes.Clone(buffer)
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.cacheOffset, r.cache = offset, cached
|
||||
r.mu.Unlock()
|
||||
}
|
||||
if fetchSize > wanted {
|
||||
copy(data[:wanted], buffer[:min(count, wanted)])
|
||||
}
|
||||
if count < wanted {
|
||||
return count, err
|
||||
}
|
||||
if wanted != len(data) {
|
||||
return wanted, io.EOF
|
||||
}
|
||||
|
||||
return wanted, nil
|
||||
}
|
||||
|
||||
// Read and validate one wire range, resuming interrupted bodies as needed.
|
||||
func (r *remoteFile) readRange(data []byte, offset int64) (int, error) {
|
||||
wanted := len(data)
|
||||
|
||||
total := 0
|
||||
|
||||
var lastErr error
|
||||
@@ -110,7 +185,9 @@ func (r *remoteFile) ReadAt(data []byte, offset int64) (int, error) {
|
||||
return total, fmt.Errorf("create remote range request: %w", err)
|
||||
}
|
||||
|
||||
request.Header.Set("User-Agent", restoreImageUserAgent)
|
||||
request.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end))
|
||||
|
||||
response, err := r.client.Do(request)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
@@ -123,10 +200,12 @@ func (r *remoteFile) ReadAt(data []byte, offset int64) (int, error) {
|
||||
|
||||
return total, fmt.Errorf("read remote image range: server returned %s", response.Status)
|
||||
}
|
||||
|
||||
actualStart, actualEnd, actualSize, err := parseContentRange(response.Header.Get("Content-Range"))
|
||||
|
||||
if err != nil || actualStart != start || actualEnd != end || actualSize != r.size {
|
||||
response.Body.Close()
|
||||
|
||||
if err != nil {
|
||||
return total, fmt.Errorf("read remote image range: %w", err)
|
||||
}
|
||||
@@ -155,9 +234,5 @@ func (r *remoteFile) ReadAt(data []byte, offset int64) (int, error) {
|
||||
return total, fmt.Errorf("read remote image at offset %d: %w", offset+int64(total), lastErr)
|
||||
}
|
||||
|
||||
if wanted != len(data) {
|
||||
return total, io.EOF
|
||||
}
|
||||
|
||||
return total, nil
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
return function(request)
|
||||
}
|
||||
|
||||
var _ = Describe("remote image HTTP requests", func() {
|
||||
It("reads image ranges from a server requiring a browser-compatible user agent", func() {
|
||||
const content = "restore image"
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
if request.UserAgent() != "Mozilla/5.0" {
|
||||
http.Error(response, "unsupported user agent", http.StatusForbidden)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
http.ServeContent(response, request, "restore.ipsw", time.Time{}, strings.NewReader(content))
|
||||
}))
|
||||
DeferCleanup(server.Close)
|
||||
|
||||
transport := &http.Transport{}
|
||||
DeferCleanup(transport.CloseIdleConnections)
|
||||
|
||||
client := &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
request = request.Clone(request.Context())
|
||||
request.URL.Scheme = "http"
|
||||
request.URL.Host = server.Listener.Addr().String()
|
||||
|
||||
return transport.RoundTrip(request)
|
||||
})}
|
||||
|
||||
remote, err := openRemoteFile(context.Background(), client)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(remote.size).To(Equal(int64(len(content))))
|
||||
|
||||
data := make([]byte, len(content)-1)
|
||||
count, err := remote.ReadAt(data, 1)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(len(data)))
|
||||
Expect(string(data)).To(Equal(content[1:]))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Compact asset cache migration", func() {
|
||||
var directory, legacyDirectory string
|
||||
var source, selected []byte
|
||||
BeforeEach(func() {
|
||||
root := GinkgoT().TempDir()
|
||||
directory = filepath.Join(root, assetCacheDirectory)
|
||||
legacyDirectory = filepath.Join(root, legacyAssetCacheDirectory)
|
||||
source = make([]byte, 40)
|
||||
for n, v := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
|
||||
binary.BigEndian.PutUint32(source[n*4:], v)
|
||||
}
|
||||
copy(source[28:], "arm!unused!")
|
||||
selected = []byte("arm!")
|
||||
originalRequired, originalLegacy := requiredFiles, legacyFiles
|
||||
DeferCleanup(func() { requiredFiles, legacyFiles = originalRequired, originalLegacy })
|
||||
requiredFiles = []fileSpec{{name: "CoreFP", size: len(selected), digest: sha256.Sum256(selected)}}
|
||||
legacyFiles = []fileSpec{{name: "CoreFP", size: len(source), digest: sha256.Sum256(source)}}
|
||||
Expect(os.MkdirAll(legacyDirectory, 0o700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(legacyDirectory, "CoreFP"), source, 0o600)).To(Succeed())
|
||||
})
|
||||
It("verifies legacy files and writes only the selected architecture", func() {
|
||||
bundle, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(bundle.CoreFP).To(Equal(selected))
|
||||
migrated, err := os.ReadFile(filepath.Join(directory, "CoreFP"))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(migrated).To(Equal(selected))
|
||||
old, err := os.ReadFile(filepath.Join(legacyDirectory, "CoreFP"))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(old).To(Equal(source))
|
||||
})
|
||||
It("uses a compact cache without requiring the old files", func() {
|
||||
Expect(writeCache(directory, Bundle{CoreFP: selected})).To(Succeed())
|
||||
Expect(os.RemoveAll(legacyDirectory)).To(Succeed())
|
||||
bundle, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(bundle.CoreFP).To(Equal(selected))
|
||||
})
|
||||
It("rejects corrupt discarded legacy bytes", func() {
|
||||
corrupt := bytes.Clone(source)
|
||||
corrupt[len(corrupt)-1] ^= 0xff
|
||||
Expect(os.WriteFile(filepath.Join(legacyDirectory, "CoreFP"), corrupt, 0o600)).To(Succeed())
|
||||
_, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeFalse())
|
||||
})
|
||||
It("repairs corrupt compact data from a valid old cache", func() {
|
||||
Expect(os.MkdirAll(directory, 0o700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(directory, "CoreFP"), []byte("bad!"), 0o600)).To(Succeed())
|
||||
bundle, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(bundle.CoreFP).To(Equal(selected))
|
||||
})
|
||||
It("keeps valid legacy data usable when the compact cache cannot be written", func() {
|
||||
Expect(os.WriteFile(directory, []byte("not a directory"), 0o600)).To(Succeed())
|
||||
bundle, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(bundle.CoreFP).To(Equal(selected))
|
||||
})
|
||||
It("rejects a legacy slice that does not match the new pin", func() {
|
||||
requiredFiles[0].digest = sha256.Sum256([]byte("bad!"))
|
||||
_, found := loadCachedBundle(directory)
|
||||
Expect(found).To(BeFalse())
|
||||
})
|
||||
|
||||
})
|
||||
@@ -82,7 +82,10 @@ func resolveRemoteImage(ctx context.Context) (Bundle, error) {
|
||||
files[spec.name] = data
|
||||
}
|
||||
|
||||
bundle := bundleFrom(files)
|
||||
bundle, err := compactBundle(bundleFrom(files))
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@ var _ = Describe("macOS 27 asset profile", func() {
|
||||
Expect(assetCacheDirectory).To(ContainSubstring("macos-27-26A434"))
|
||||
})
|
||||
|
||||
It("pins every runtime artifact by size and digest", func() {
|
||||
Expect(requiredFiles).To(ConsistOf(
|
||||
It("preserves the pinned legacy artifacts for migration", func() {
|
||||
Expect(legacyFiles).To(ConsistOf(
|
||||
fileSpec{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
|
||||
fileSpec{name: "commerce", size: 8092640, digest: mustDigest("76de40a4a32f691947cb926ce3b128d2fc446f7cac9755f831c406cf5a316ac9")},
|
||||
fileSpec{name: "adid", size: 9797952, digest: mustDigest("1fec225b6917206e3d9b00fe636c04878f82bfd06a87a4b6941711de60efab5b")},
|
||||
@@ -27,6 +27,18 @@ var _ = Describe("macOS 27 asset profile", func() {
|
||||
))
|
||||
})
|
||||
|
||||
It("pins compact runtime artifacts by size and digest", func() {
|
||||
Expect(requiredFiles).To(ConsistOf(
|
||||
fileSpec{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
|
||||
fileSpec{name: "commerce", size: 2735088, digest: mustDigest("c4b2088dd39aeb353f59cb57597902e8317aec66ae7da0414b03c5f932771343")},
|
||||
fileSpec{name: "adid", size: 3047808, digest: mustDigest("43419a206c28bc93ecb8884256088d18306a0a462350f83adbced8e60a94e390")},
|
||||
fileSpec{name: "CoreFP", size: 30764976, digest: mustDigest("afbc123e688a822d980d5816cc2b52f69fde669d1dca92cf85627e1cbee587f6")},
|
||||
fileSpec{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
|
||||
fileSpec{name: "fairplayd", size: 17389744, digest: mustDigest("1e58d37e9602dd0ca5e24b14762063b6c310248b4d3a94272771d815e4ea1784")},
|
||||
fileSpec{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
|
||||
))
|
||||
})
|
||||
|
||||
It("pins the CoreADI path and deflated kernel entry", func() {
|
||||
Expect(frameworkImagePaths).To(ContainElement("/System/Library/PrivateFrameworks/CoreADI.framework/Versions/A/adid"))
|
||||
archive := &zip.Reader{File: []*zip.File{{FileHeader: zip.FileHeader{
|
||||
|
||||
+200
-61
@@ -2,9 +2,11 @@ package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"sort"
|
||||
|
||||
@@ -33,16 +35,19 @@ type segment struct {
|
||||
}
|
||||
|
||||
type Image struct {
|
||||
name string
|
||||
data []byte
|
||||
file *macho.File
|
||||
base uint64
|
||||
segments []segment
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
chained *fixupchains.DyldChainedFixups
|
||||
relocated bool
|
||||
loadedBase uint64
|
||||
name string
|
||||
data []byte
|
||||
modified map[uint64][]byte
|
||||
instructions map[uint64][]instructionPatch
|
||||
file *macho.File
|
||||
base uint64
|
||||
segments []segment
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
chained *fixupchains.DyldChainedFixups
|
||||
fixups []chainedRelocation
|
||||
relocated bool
|
||||
loadedBase uint64
|
||||
}
|
||||
|
||||
func (i *Image) Base() uint64 {
|
||||
@@ -56,7 +61,41 @@ func Open(name string, input []byte) (*Image, error) {
|
||||
return nil, fmt.Errorf("open %s: %w", name, err)
|
||||
}
|
||||
|
||||
file, err := macho.NewFile(bytes.NewReader(data))
|
||||
return openImage(name, data, nil)
|
||||
}
|
||||
|
||||
func openImage(name string, data []byte, modified map[uint64][]byte) (*Image, error) {
|
||||
image := &Image{name: name, data: data, modified: modified}
|
||||
|
||||
var reader io.ReaderAt = bytes.NewReader(data)
|
||||
|
||||
if modified != nil {
|
||||
reader = imageInput{image}
|
||||
}
|
||||
|
||||
var key [sha256.Size]byte
|
||||
|
||||
var preparation imagePreparation
|
||||
|
||||
var cached bool
|
||||
|
||||
if modified != nil {
|
||||
key = sha256.Sum256(data)
|
||||
preparation, cached = imagePreparations.get(key)
|
||||
}
|
||||
|
||||
var file *macho.File
|
||||
|
||||
var err error
|
||||
if cached {
|
||||
file, err = macho.NewFile(reader, macho.FileConfig{LoadExcluding: []types.LoadCmd{types.LC_SYMTAB, types.LC_DYSYMTAB, types.LC_CODE_SIGNATURE}})
|
||||
if err == nil {
|
||||
file.Symtab, file.Dysymtab = preparation.symtab, preparation.dysymtab
|
||||
}
|
||||
} else {
|
||||
file, err = macho.NewFile(reader)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s Mach-O: %w", name, err)
|
||||
}
|
||||
@@ -65,12 +104,9 @@ func Open(name string, input []byte) (*Image, error) {
|
||||
return nil, fmt.Errorf("open %s: expected arm64 Mach-O, found %s", name, file.CPU)
|
||||
}
|
||||
|
||||
image := &Image{
|
||||
name: name,
|
||||
data: data,
|
||||
file: file,
|
||||
base: file.GetBaseAddress(),
|
||||
}
|
||||
image.file = file
|
||||
image.base = file.GetBaseAddress()
|
||||
|
||||
for _, item := range file.Segments() {
|
||||
image.segments = append(image.segments, segment{
|
||||
name: item.Name,
|
||||
@@ -84,6 +120,14 @@ func Open(name string, input []byte) (*Image, error) {
|
||||
if err := image.validateSegments(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cached {
|
||||
image.instructions, image.fixups = preparation.instructions, preparation.fixups
|
||||
image.binds, image.rebases = preparation.binds, preparation.rebases
|
||||
|
||||
return image, nil
|
||||
}
|
||||
|
||||
if err := image.removePointerAuthentication(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -109,26 +153,50 @@ func Open(name string, input []byte) (*Image, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if modified != nil {
|
||||
if image.chained != nil {
|
||||
image.fixups, err = image.decodeChainedRelocations()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
image.chained = nil
|
||||
}
|
||||
|
||||
imagePreparations.put(key, imagePreparation{instructions: image.instructions, fixups: image.fixups, binds: image.binds, rebases: image.rebases, symtab: file.Symtab, dysymtab: file.Dysymtab})
|
||||
}
|
||||
|
||||
return image, nil
|
||||
}
|
||||
|
||||
//nolint:wsl // Instruction decoding is clearer when related operations stay together.
|
||||
func (i *Image) removePointerAuthentication() error {
|
||||
var ranges [][2]uint64
|
||||
|
||||
for _, section := range i.file.Sections {
|
||||
if !section.Flags.IsPureInstructions() && !section.Flags.IsSomeInstructions() {
|
||||
continue
|
||||
}
|
||||
|
||||
start := uint64(section.Offset)
|
||||
|
||||
end, overflow := add(start, section.Size)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("instruction section %s exceeds %s", section.Name, i.name)
|
||||
}
|
||||
for offset := start; offset+4 <= end; offset += 4 {
|
||||
|
||||
ranges = append(ranges, [2]uint64{start, end})
|
||||
}
|
||||
|
||||
for _, region := range ranges {
|
||||
for offset := region[0]; offset+4 <= region[1]; offset += 4 {
|
||||
instruction := binary.LittleEndian.Uint32(i.data[offset:])
|
||||
replacement := WithoutPointerAuthentication(instruction)
|
||||
if replacement != instruction {
|
||||
binary.LittleEndian.PutUint32(i.data[offset:], replacement)
|
||||
|
||||
if replacement == instruction {
|
||||
continue
|
||||
}
|
||||
|
||||
i.writeInstruction(offset, replacement)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,28 +245,55 @@ func WithoutPointerAuthentication(instruction uint32) uint32 {
|
||||
return replacement
|
||||
}
|
||||
|
||||
func arm64Slice(input []byte) ([]byte, error) {
|
||||
fat, err := macho.NewFatFile(bytes.NewReader(input))
|
||||
if err != nil {
|
||||
return bytes.Clone(input), nil
|
||||
// ARM64Slice selects the arm64e image without parsing the other architectures.
|
||||
// The returned view aliases input and must not be modified by the caller.
|
||||
func ARM64Slice(input []byte) ([]byte, error) {
|
||||
if len(input) < 4 || binary.BigEndian.Uint32(input) != types.MagicFat.Int() {
|
||||
return input, nil
|
||||
}
|
||||
|
||||
for _, architecture := range fat.Arches {
|
||||
if architecture.CPU != types.CPUArm64 || architecture.SubCPU&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
|
||||
const headerSize, architectureSize = 8, 20
|
||||
if len(input) < headerSize {
|
||||
return nil, errors.New("truncated universal binary header")
|
||||
}
|
||||
|
||||
count := uint64(binary.BigEndian.Uint32(input[4:]))
|
||||
if count == 0 || count > uint64(len(input)-headerSize)/architectureSize {
|
||||
return nil, errors.New("invalid universal binary architecture count")
|
||||
}
|
||||
|
||||
for index := uint64(0); index < count; index++ {
|
||||
header := input[headerSize+index*architectureSize:]
|
||||
cpu := types.CPU(binary.BigEndian.Uint32(header))
|
||||
subtype := types.CPUSubtype(binary.BigEndian.Uint32(header[4:]))
|
||||
|
||||
if cpu != types.CPUArm64 || subtype&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
|
||||
continue
|
||||
}
|
||||
|
||||
end, overflow := add(uint64(architecture.Offset), uint64(architecture.Size))
|
||||
if overflow || end > uint64(len(input)) {
|
||||
return nil, errors.New("arm64e slice exceeds input size")
|
||||
offset := uint64(binary.BigEndian.Uint32(header[8:]))
|
||||
size := uint64(binary.BigEndian.Uint32(header[12:]))
|
||||
end, overflow := add(offset, size)
|
||||
|
||||
if size == 0 || offset < headerSize+count*architectureSize || overflow || end > uint64(len(input)) {
|
||||
return nil, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
|
||||
}
|
||||
|
||||
return bytes.Clone(input[architecture.Offset:end]), nil
|
||||
return input[offset:end], nil
|
||||
}
|
||||
|
||||
return nil, errors.New("universal binary has no arm64e slice")
|
||||
}
|
||||
|
||||
func arm64Slice(input []byte) ([]byte, error) {
|
||||
data, err := ARM64Slice(input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return bytes.Clone(data), nil
|
||||
}
|
||||
|
||||
func (i *Image) Export(name string, loadBase uint64) (uint64, error) {
|
||||
address, err := i.file.FindSymbolAddress(name)
|
||||
if err != nil {
|
||||
@@ -313,7 +408,7 @@ func (i *Image) RelocateKernelCachePointers(loadBase, kernelBase uint64, resolve
|
||||
|
||||
end := item.fileOff + item.fileSize
|
||||
for offset := start; offset <= end-pointerSize; offset += kernelFixupStride {
|
||||
raw := binary.LittleEndian.Uint64(i.data[offset : offset+pointerSize])
|
||||
raw := i.pointerAt(offset)
|
||||
|
||||
pointer := fixupchains.DyldChainedPtr64KernelCacheRebase{Pointer: raw}
|
||||
if pointer.CacheLevel() != 0 || pointer.Target() == 0 {
|
||||
@@ -362,19 +457,20 @@ func (i *Image) containsAddress(address uint64) bool {
|
||||
}
|
||||
|
||||
//nolint:wsl // Chained-fixup decoding is clearer when related operations stay together.
|
||||
func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, error)) error {
|
||||
func (i *Image) decodeChainedRelocations() ([]chainedRelocation, error) {
|
||||
if i.chained == nil {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var relocations []chainedRelocation
|
||||
for _, start := range i.chained.Starts {
|
||||
for _, fixup := range start.Fixups {
|
||||
offset := fixup.Offset()
|
||||
if offset > uint64(len(i.data)) || pointerSize > uint64(len(i.data))-offset {
|
||||
return fmt.Errorf("chained fixup at %#x exceeds %s", offset, i.name)
|
||||
return nil, fmt.Errorf("chained fixup at %#x exceeds %s", offset, i.name)
|
||||
}
|
||||
|
||||
var address uint64
|
||||
relocation := chainedRelocation{offset: offset}
|
||||
|
||||
switch {
|
||||
case fixup.IsRebase():
|
||||
@@ -391,7 +487,7 @@ func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, e
|
||||
if i.chained.PointerFormat == fixupchains.DYLD_CHAINED_PTR_ARM64E {
|
||||
absolute := rebase.UnpackTarget() & 0x00ffffffffffffff
|
||||
if absolute < i.base {
|
||||
return fmt.Errorf("chained rebase at %#x precedes the base of %s", offset, i.name)
|
||||
return nil, fmt.Errorf("chained rebase at %#x precedes the base of %s", offset, i.name)
|
||||
}
|
||||
target = absolute - i.base
|
||||
}
|
||||
@@ -402,28 +498,19 @@ func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, e
|
||||
|
||||
target, err = i.chained.Rebase(offset, i.base)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decode chained rebase at %#x in %s: %w", offset, i.name, err)
|
||||
return nil, fmt.Errorf("decode chained rebase at %#x in %s: %w", offset, i.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
var overflow bool
|
||||
|
||||
address, overflow = add(loadBase, target)
|
||||
if overflow {
|
||||
return fmt.Errorf("chained rebase at %#x with target %#x, image base %#x, load base %#x, format %s, and type %T overflows in %s", offset, target, i.base, loadBase, i.chained.PointerFormat, fixup, i.name)
|
||||
}
|
||||
relocation.target = target
|
||||
case fixup.IsBind():
|
||||
binding, ok := fixup.(fixupchains.Bind)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid chained bind at %#x in %s", offset, i.name)
|
||||
return nil, fmt.Errorf("invalid chained bind at %#x in %s", offset, i.name)
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
address, err = resolve(binding.Name())
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve %s for %s: %w", binding.Name(), i.name, err)
|
||||
}
|
||||
relocation.isBind = true
|
||||
relocation.symbol = binding.Name()
|
||||
|
||||
addend := int64(binding.Addend())
|
||||
switch arm64e := fixup.(type) {
|
||||
@@ -436,17 +523,54 @@ func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, e
|
||||
addend += int64(i.chained.Imports[ordinal].Addend())
|
||||
}
|
||||
|
||||
address, err = addSigned(address, addend)
|
||||
if err != nil {
|
||||
return fmt.Errorf("apply chained addend for %s in %s: %w", binding.Name(), i.name, err)
|
||||
}
|
||||
relocation.addend = addend
|
||||
default:
|
||||
return fmt.Errorf("unknown chained fixup at %#x in %s", offset, i.name)
|
||||
return nil, fmt.Errorf("unknown chained fixup at %#x in %s", offset, i.name)
|
||||
}
|
||||
|
||||
if err := i.putPointer(offset, address); err != nil {
|
||||
return err
|
||||
relocations = append(relocations, relocation)
|
||||
}
|
||||
}
|
||||
|
||||
return relocations, nil
|
||||
}
|
||||
|
||||
func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, error)) error {
|
||||
relocations := i.fixups
|
||||
|
||||
if i.chained != nil {
|
||||
var err error
|
||||
|
||||
relocations, err = i.decodeChainedRelocations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, relocation := range relocations {
|
||||
var address uint64
|
||||
|
||||
if relocation.isBind {
|
||||
value, err := resolve(relocation.symbol)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve %s for %s: %w", relocation.symbol, i.name, err)
|
||||
}
|
||||
|
||||
address, err = addSigned(value, relocation.addend)
|
||||
if err != nil {
|
||||
return fmt.Errorf("apply chained addend for %s in %s: %w", relocation.symbol, i.name, err)
|
||||
}
|
||||
} else {
|
||||
var overflow bool
|
||||
|
||||
address, overflow = add(loadBase, relocation.target)
|
||||
if overflow {
|
||||
return fmt.Errorf("chained rebase at %#x with target %#x overflows in %s", relocation.offset, relocation.target, i.name)
|
||||
}
|
||||
}
|
||||
|
||||
if err := i.putPointer(relocation.offset, address); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,6 +597,13 @@ func (i *Image) PreparePrelinked(external map[uint64]string, resolve func(string
|
||||
patched[address] = value
|
||||
}
|
||||
|
||||
if len(patched) == 0 {
|
||||
i.relocated = true
|
||||
i.loadedBase = i.base
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, item := range i.segments {
|
||||
if item.name == "__TEXT" || item.name == "__LINKEDIT" || item.fileSize < pointerSize {
|
||||
continue
|
||||
@@ -485,7 +616,7 @@ func (i *Image) PreparePrelinked(external map[uint64]string, resolve func(string
|
||||
|
||||
end := item.fileOff + item.fileSize
|
||||
for offset := start; offset <= end-pointerSize; offset += pointerSize {
|
||||
current := binary.LittleEndian.Uint64(i.data[offset : offset+pointerSize])
|
||||
current := i.pointerAt(offset)
|
||||
|
||||
value, ok := patched[current]
|
||||
if !ok {
|
||||
@@ -571,6 +702,11 @@ func (i *Image) Load(memory Memory) error {
|
||||
}
|
||||
}
|
||||
|
||||
var buffer []byte
|
||||
if len(i.modified) > 0 || len(i.instructions) > 0 {
|
||||
buffer = make([]byte, min(128<<10, len(i.data)))
|
||||
}
|
||||
|
||||
for _, item := range i.segments {
|
||||
if item.name == "__PAGEZERO" || item.fileSize == 0 {
|
||||
continue
|
||||
@@ -586,7 +722,7 @@ func (i *Image) Load(memory Memory) error {
|
||||
return fmt.Errorf("segment %s address overflows in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
if err := memory.MemWrite(address, i.data[item.fileOff:end]); err != nil {
|
||||
if err := i.writeSegment(memory, address, item.fileOff, end, buffer); err != nil {
|
||||
return fmt.Errorf("write segment %s from %s: %w", item.name, i.name, err)
|
||||
}
|
||||
}
|
||||
@@ -650,7 +786,10 @@ func (i *Image) putPointer(offset, value uint64) error {
|
||||
return fmt.Errorf("fixup at %#x exceeds %s", offset, i.name)
|
||||
}
|
||||
|
||||
binary.LittleEndian.PutUint64(i.data[offset:end], value)
|
||||
var data [8]byte
|
||||
|
||||
binary.LittleEndian.PutUint64(data[:], value)
|
||||
i.writeAt(offset, data[:])
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package machimage
|
||||
|
||||
import "github.com/blacktop/go-macho"
|
||||
|
||||
// Symbols returns the immutable symbol table used for guest exports and ivars.
|
||||
// Callers must not modify the returned slice.
|
||||
func (i *Image) Symbols() []macho.Symbol {
|
||||
if i.file.Symtab == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return i.file.Symtab.Syms
|
||||
}
|
||||
|
||||
// InstructionRanges returns the guest's executable section address ranges.
|
||||
func (i *Image) InstructionRanges() [][2]uint64 {
|
||||
var ranges [][2]uint64
|
||||
|
||||
for _, section := range i.file.Sections {
|
||||
if section.Flags.IsPureInstructions() || section.Flags.IsSomeInstructions() {
|
||||
ranges = append(ranges, [2]uint64{section.Addr, section.Addr + section.Size})
|
||||
}
|
||||
}
|
||||
|
||||
return ranges
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
const (
|
||||
maxImagePreparations = 8
|
||||
maxPreparationBytes = 64 << 20
|
||||
)
|
||||
|
||||
type chainedRelocation struct {
|
||||
offset, target uint64
|
||||
addend int64
|
||||
symbol string
|
||||
isBind bool
|
||||
}
|
||||
|
||||
type instructionPatch struct {
|
||||
offset uint64
|
||||
value uint32
|
||||
}
|
||||
|
||||
type imagePreparation struct {
|
||||
instructions map[uint64][]instructionPatch
|
||||
fixups []chainedRelocation
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
symtab *macho.Symtab
|
||||
dysymtab *macho.Dysymtab
|
||||
}
|
||||
|
||||
func (p imagePreparation) size() int {
|
||||
size := cap(p.fixups)*int(unsafe.Sizeof(chainedRelocation{})) + cap(p.binds)*int(unsafe.Sizeof(types.Bind{})) + cap(p.rebases)*int(unsafe.Sizeof(types.Rebase{}))
|
||||
for _, patches := range p.instructions {
|
||||
size += cap(patches) * int(unsafe.Sizeof(instructionPatch{}))
|
||||
}
|
||||
|
||||
for _, fixup := range p.fixups {
|
||||
size += len(fixup.symbol)
|
||||
}
|
||||
|
||||
for _, bind := range p.binds {
|
||||
size += len(bind.Name)
|
||||
}
|
||||
|
||||
if p.symtab != nil {
|
||||
size += cap(p.symtab.Syms)*int(unsafe.Sizeof(macho.Symbol{})) + cap(p.symtab.LoadBytes)
|
||||
for _, symbol := range p.symtab.Syms {
|
||||
size += len(symbol.Name) + len(symbol.IndirectName)
|
||||
}
|
||||
}
|
||||
|
||||
if p.dysymtab != nil {
|
||||
size += cap(p.dysymtab.IndirectSyms)*4 + cap(p.dysymtab.LoadBytes)
|
||||
}
|
||||
|
||||
return size
|
||||
}
|
||||
|
||||
type imagePreparationCache struct {
|
||||
mu sync.Mutex
|
||||
entries map[[sha256.Size]byte]imagePreparation
|
||||
order [][sha256.Size]byte
|
||||
bytes int
|
||||
}
|
||||
|
||||
// Cache only immutable instruction patches, symbol tables and decoded relocations. Every guest
|
||||
// supplies its own load bases, import addresses and mutable memory.
|
||||
var imagePreparations imagePreparationCache
|
||||
|
||||
func (c *imagePreparationCache) get(key [sha256.Size]byte) (imagePreparation, bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
prepared, ok := c.entries[key]
|
||||
|
||||
return prepared, ok
|
||||
}
|
||||
|
||||
func (c *imagePreparationCache) put(key [sha256.Size]byte, prepared imagePreparation) {
|
||||
size := prepared.size()
|
||||
if size > maxPreparationBytes {
|
||||
return
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if _, exists := c.entries[key]; exists {
|
||||
return
|
||||
}
|
||||
|
||||
if c.entries == nil {
|
||||
c.entries = make(map[[sha256.Size]byte]imagePreparation)
|
||||
}
|
||||
|
||||
for len(c.order) >= maxImagePreparations || c.bytes+size > maxPreparationBytes {
|
||||
oldest := c.order[0]
|
||||
c.bytes -= c.entries[oldest].size()
|
||||
delete(c.entries, oldest)
|
||||
c.order = c.order[1:]
|
||||
}
|
||||
|
||||
c.order = append(c.order, key)
|
||||
c.entries[key] = prepared
|
||||
c.bytes += size
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
// ARM64Range locates a thin image or the arm64e slice using only its headers.
|
||||
// It leaves unselected architectures unread for range-backed remote sources.
|
||||
func ARM64Range(source io.ReaderAt, size int64) (int64, int64, error) {
|
||||
if size < 0 {
|
||||
return 0, 0, errors.New("invalid image size")
|
||||
}
|
||||
|
||||
var header [8]byte
|
||||
|
||||
if size < 4 {
|
||||
return 0, size, nil
|
||||
}
|
||||
|
||||
if _, err := source.ReadAt(header[:4], 0); err != nil {
|
||||
return 0, 0, fmt.Errorf("read image magic: %w", err)
|
||||
}
|
||||
|
||||
if binary.BigEndian.Uint32(header[:]) != types.MagicFat.Int() {
|
||||
return 0, size, nil
|
||||
}
|
||||
|
||||
if size < 8 {
|
||||
return 0, 0, errors.New("truncated universal binary header")
|
||||
}
|
||||
|
||||
if _, err := source.ReadAt(header[4:], 4); err != nil {
|
||||
return 0, 0, fmt.Errorf("read universal binary header: %w", err)
|
||||
}
|
||||
|
||||
count := int64(binary.BigEndian.Uint32(header[4:]))
|
||||
if count == 0 || count > (size-8)/20 {
|
||||
return 0, 0, errors.New("invalid universal binary architecture count")
|
||||
}
|
||||
|
||||
var architecture [20]byte
|
||||
for index := int64(0); index < count; index++ {
|
||||
if _, err := source.ReadAt(architecture[:], 8+index*20); err != nil {
|
||||
return 0, 0, fmt.Errorf("read universal binary architecture: %w", err)
|
||||
}
|
||||
|
||||
cpu := types.CPU(binary.BigEndian.Uint32(architecture[:]))
|
||||
subtype := types.CPUSubtype(binary.BigEndian.Uint32(architecture[4:]))
|
||||
|
||||
if cpu != types.CPUArm64 || subtype&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
|
||||
continue
|
||||
}
|
||||
|
||||
offset, length := int64(binary.BigEndian.Uint32(architecture[8:])), int64(binary.BigEndian.Uint32(architecture[12:]))
|
||||
if length == 0 || offset < 8+count*20 || offset > size || length > size-offset {
|
||||
return 0, 0, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
|
||||
}
|
||||
|
||||
return offset, length, nil
|
||||
}
|
||||
|
||||
return 0, 0, errors.New("universal binary has no arm64e slice")
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
type headerReader struct {
|
||||
input []byte
|
||||
read int
|
||||
end int64
|
||||
}
|
||||
|
||||
func (r *headerReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||
r.read += len(data)
|
||||
r.end = max(r.end, offset+int64(len(data)))
|
||||
|
||||
return bytes.NewReader(r.input).ReadAt(data, offset) //nolint:wrapcheck // ReaderAt adapters preserve io.EOF.
|
||||
}
|
||||
|
||||
var _ = Describe("Remote architecture selection", func() {
|
||||
It("reads only the architecture headers", func() {
|
||||
input := universalImage()
|
||||
reader := &headerReader{input: input}
|
||||
offset, size, err := ARM64Range(reader, int64(len(input)))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(offset).To(Equal(int64(52)))
|
||||
Expect(size).To(Equal(int64(4)))
|
||||
Expect(reader.end).To(BeNumerically("<=", 48))
|
||||
Expect(reader.read).To(BeNumerically("<=", 48))
|
||||
})
|
||||
It("keeps thin images whole", func() {
|
||||
data := []byte("thin image")
|
||||
reader := &headerReader{input: data}
|
||||
offset, size, err := ARM64Range(reader, int64(len(data)))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(offset).To(BeZero())
|
||||
Expect(size).To(Equal(int64(len(data))))
|
||||
Expect(reader.read).To(Equal(4))
|
||||
})
|
||||
It("rejects invalid counts and out-of-bounds slices", func() {
|
||||
for _, index := range []int{4, 36, 40} {
|
||||
data := universalImage()
|
||||
binary.BigEndian.PutUint32(data[index:], ^uint32(0))
|
||||
_, _, err := ARM64Range(bytes.NewReader(data), int64(len(data)))
|
||||
Expect(err).To(HaveOccurred())
|
||||
}
|
||||
})
|
||||
It("reports truncated headers and missing arm64e slices", func() {
|
||||
data := universalImage()
|
||||
_, _, err := ARM64Range(bytes.NewReader(data[:10]), int64(len(data)))
|
||||
Expect(err).To(HaveOccurred())
|
||||
binary.BigEndian.PutUint32(data[32:], 0)
|
||||
_, _, err = ARM64Range(bytes.NewReader(data), int64(len(data)))
|
||||
Expect(err).To(MatchError(ContainSubstring("no arm64e slice")))
|
||||
})
|
||||
It("handles tiny files and rejects a negative declared size", func() {
|
||||
_, size, err := ARM64Range(bytes.NewReader([]byte{1}), 1)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(size).To(Equal(int64(1)))
|
||||
_, _, err = ARM64Range(bytes.NewReader(nil), -1)
|
||||
Expect(err).To(HaveOccurred())
|
||||
_, _, err = ARM64Range(io.NewSectionReader(bytes.NewReader(nil), 0, 4), 4)
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,103 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
// ReadARM64 consumes exactly size bytes, retaining only the arm64e image of a
|
||||
// universal binary. A caller can hash the entire input with an io.TeeReader.
|
||||
func ReadARM64(input io.Reader, size int) ([]byte, error) {
|
||||
if size < 0 {
|
||||
return nil, errors.New("invalid image size")
|
||||
}
|
||||
|
||||
var header [8]byte
|
||||
|
||||
prefix := min(size, 4)
|
||||
if _, err := io.ReadFull(input, header[:prefix]); err != nil {
|
||||
return nil, fmt.Errorf("read image magic: %w", err)
|
||||
}
|
||||
|
||||
if prefix < 4 || binary.BigEndian.Uint32(header[:]) != types.MagicFat.Int() {
|
||||
data := make([]byte, size)
|
||||
copy(data, header[:prefix])
|
||||
|
||||
if _, err := io.ReadFull(input, data[prefix:]); err != nil {
|
||||
return nil, fmt.Errorf("read thin image: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
if size < 8 {
|
||||
return nil, errors.New("truncated universal binary header")
|
||||
}
|
||||
|
||||
if _, err := io.ReadFull(input, header[4:]); err != nil {
|
||||
return nil, fmt.Errorf("read universal binary header: %w", err)
|
||||
}
|
||||
|
||||
count := uint64(binary.BigEndian.Uint32(header[4:]))
|
||||
if count == 0 || count > uint64(size-8)/20 {
|
||||
return nil, errors.New("invalid universal binary architecture count")
|
||||
}
|
||||
|
||||
var offset, length uint64
|
||||
|
||||
var arch [20]byte
|
||||
for range count {
|
||||
if _, err := io.ReadFull(input, arch[:]); err != nil {
|
||||
return nil, fmt.Errorf("read universal binary architecture: %w", err)
|
||||
}
|
||||
|
||||
cpu := types.CPU(binary.BigEndian.Uint32(arch[:]))
|
||||
subtype := types.CPUSubtype(binary.BigEndian.Uint32(arch[4:]))
|
||||
|
||||
if length == 0 && cpu == types.CPUArm64 && subtype&types.CpuSubtypeMask == types.CPUSubtypeArm64E {
|
||||
offset = uint64(binary.BigEndian.Uint32(arch[8:]))
|
||||
length = uint64(binary.BigEndian.Uint32(arch[12:]))
|
||||
|
||||
if length == 0 || offset < 8+count*20 || offset+length > uint64(size) {
|
||||
return nil, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if length == 0 {
|
||||
return nil, errors.New("universal binary has no arm64e slice")
|
||||
}
|
||||
|
||||
buffer := make([]byte, 256<<10)
|
||||
if err := discardImageBytes(input, offset-(8+count*20), buffer); err != nil {
|
||||
return nil, fmt.Errorf("read universal binary prefix: %w", err)
|
||||
}
|
||||
|
||||
data := make([]byte, int(length))
|
||||
if _, err := io.ReadFull(input, data); err != nil {
|
||||
return nil, fmt.Errorf("read arm64e image: %w", err)
|
||||
}
|
||||
|
||||
if err := discardImageBytes(input, uint64(size)-offset-length, buffer); err != nil {
|
||||
return nil, fmt.Errorf("read universal binary suffix: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func discardImageBytes(input io.Reader, count uint64, buffer []byte) error {
|
||||
for count > 0 {
|
||||
size := min(count, uint64(len(buffer)))
|
||||
if _, err := io.ReadFull(input, buffer[:size]); err != nil {
|
||||
return fmt.Errorf("consume image bytes: %w", err)
|
||||
}
|
||||
|
||||
count -= size
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Streaming ARM64 extraction", func() {
|
||||
It("hashes discarded bytes and stops at the declared size", func() {
|
||||
fat := append(universalImage(), []byte("unused suffix")...)
|
||||
reader := bytes.NewReader(append(bytes.Clone(fat), []byte("trailer")...))
|
||||
digest := sha256.New()
|
||||
data, err := ReadARM64(io.TeeReader(reader, digest), len(fat))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).To(Equal("arm!"))
|
||||
expected := sha256.Sum256(fat)
|
||||
Expect(digest.Sum(nil)).To(Equal(expected[:]))
|
||||
trailing, err := io.ReadAll(reader)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(trailing)).To(Equal("trailer"))
|
||||
})
|
||||
It("preserves thin and short input", func() {
|
||||
for _, input := range [][]byte{nil, {1}, {1, 2, 3}, []byte("thin image")} {
|
||||
data, err := ReadARM64(bytes.NewReader(input), len(input))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(bytes.Equal(data, input)).To(BeTrue())
|
||||
}
|
||||
})
|
||||
It("rejects a negative size", func() {
|
||||
_, err := ReadARM64(bytes.NewReader(nil), -1)
|
||||
Expect(err).To(MatchError(ContainSubstring("invalid image size")))
|
||||
})
|
||||
It("rejects truncation before, inside, and after the selected slice", func() {
|
||||
input := append(universalImage(), []byte("suffix")...)
|
||||
for _, length := range []int{0, 4, 7, 20, 48, 53, 55, 59} {
|
||||
_, err := ReadARM64(bytes.NewReader(input[:length]), len(input))
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)).To(BeTrue())
|
||||
}
|
||||
})
|
||||
It("rejects invalid architecture ranges before allocating their data", func() {
|
||||
input := universalImage()
|
||||
input[40] = 0xff
|
||||
_, err := ReadARM64(bytes.NewReader(input), len(input))
|
||||
Expect(err).To(MatchError(ContainSubstring("exceeds input size")))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,159 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// OpenShared borrows immutable image bytes and copies only pages changed by
|
||||
// relocation. Instruction patches are applied while loading into guest memory.
|
||||
// Input must remain unchanged while the Image is used.
|
||||
func OpenShared(name string, input []byte) (*Image, error) {
|
||||
data, err := ARM64Slice(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s: %w", name, err)
|
||||
}
|
||||
|
||||
return openImage(name, data, make(map[uint64][]byte))
|
||||
}
|
||||
|
||||
func (i *Image) writeAt(offset uint64, data []byte) {
|
||||
if i.modified == nil {
|
||||
copy(i.data[offset:], data)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for len(data) > 0 {
|
||||
page := offset &^ (pageSize - 1)
|
||||
buffer := i.modified[page]
|
||||
|
||||
if buffer == nil {
|
||||
buffer = bytes.Clone(i.data[page:min(page+pageSize, uint64(len(i.data)))])
|
||||
i.overlay(buffer, page)
|
||||
i.modified[page] = buffer
|
||||
}
|
||||
|
||||
count := copy(buffer[offset-page:], data)
|
||||
offset += uint64(count)
|
||||
data = data[count:]
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Image) pointerAt(offset uint64) uint64 {
|
||||
pageStart := offset &^ (pageSize - 1)
|
||||
if offset+pointerSize <= pageStart+pageSize {
|
||||
if page := i.modified[pageStart]; page != nil {
|
||||
return binary.LittleEndian.Uint64(page[offset-pageStart:])
|
||||
}
|
||||
|
||||
if len(i.instructions[pageStart]) == 0 {
|
||||
return binary.LittleEndian.Uint64(i.data[offset:])
|
||||
}
|
||||
}
|
||||
|
||||
var value [8]byte
|
||||
|
||||
copy(value[:], i.data[offset:offset+8])
|
||||
i.overlay(value[:], offset)
|
||||
|
||||
return binary.LittleEndian.Uint64(value[:])
|
||||
}
|
||||
|
||||
func (i *Image) writeInstruction(offset uint64, value uint32) {
|
||||
if i.modified != nil {
|
||||
if i.instructions == nil {
|
||||
i.instructions = make(map[uint64][]instructionPatch)
|
||||
}
|
||||
|
||||
for page := offset &^ (pageSize - 1); page < offset+4; page += pageSize {
|
||||
i.instructions[page] = append(i.instructions[page], instructionPatch{offset, value})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var data [4]byte
|
||||
|
||||
binary.LittleEndian.PutUint32(data[:], value)
|
||||
i.writeAt(offset, data[:])
|
||||
}
|
||||
|
||||
// Overlay private relocations and immutable instruction patches. Clip each page
|
||||
// and patch to the destination, including unaligned segment and chunk boundaries.
|
||||
func (i *Image) overlay(data []byte, offset uint64) {
|
||||
end := offset + uint64(len(data))
|
||||
for page := offset &^ (pageSize - 1); page < end; page += pageSize {
|
||||
first, last := max(page, offset), min(page+pageSize, end)
|
||||
if modified := i.modified[page]; modified != nil {
|
||||
copy(data[first-offset:last-offset], modified[first-page:last-page])
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
for _, patch := range i.instructions[page] {
|
||||
start, stop := max(first, patch.offset), min(last, patch.offset+4)
|
||||
if start >= stop {
|
||||
continue
|
||||
}
|
||||
|
||||
var encoded [4]byte
|
||||
|
||||
binary.LittleEndian.PutUint32(encoded[:], patch.value)
|
||||
copy(data[start-offset:stop-offset], encoded[start-patch.offset:stop-patch.offset])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep staging memory bounded regardless of image size and guest count.
|
||||
func (i *Image) writeSegment(memory Memory, address, start, end uint64, buffer []byte) error {
|
||||
if len(i.modified) == 0 && len(i.instructions) == 0 {
|
||||
if err := memory.MemWrite(address, i.data[start:end]); err != nil {
|
||||
return fmt.Errorf("write image data: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
for position := start; position < end; {
|
||||
stop := min(position+uint64(len(buffer)), end)
|
||||
data := buffer[:stop-position]
|
||||
copy(data, i.data[position:stop])
|
||||
i.overlay(data, position)
|
||||
|
||||
if err := memory.MemWrite(address+position-start, data); err != nil {
|
||||
return fmt.Errorf("write image chunk: %w", err)
|
||||
}
|
||||
|
||||
position = stop
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Mach-O fixup parsing must observe the same rewritten bytes that will be loaded
|
||||
// into the guest, including instruction patches in mixed code/data sections.
|
||||
type imageInput struct{ image *Image }
|
||||
|
||||
func (r imageInput) ReadAt(data []byte, offset int64) (int, error) {
|
||||
if offset < 0 {
|
||||
return 0, fmt.Errorf("invalid image offset %d", offset)
|
||||
}
|
||||
|
||||
if offset >= int64(len(r.image.data)) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
count := copy(data, r.image.data[offset:])
|
||||
if len(r.image.instructions) > 0 || len(r.image.modified) > 0 {
|
||||
r.image.overlay(data[:count], uint64(offset))
|
||||
}
|
||||
|
||||
if count < len(data) {
|
||||
return count, io.EOF
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
// One instruction page and one data page following the Mach-O headers.
|
||||
func sharedFixture() []byte {
|
||||
data := make([]byte, 3*pageSize)
|
||||
for n, v := range []uint32{0xfeedfacf, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 6, 2, 176, 0, 0} {
|
||||
binary.LittleEndian.PutUint32(data[n*4:], v)
|
||||
}
|
||||
|
||||
binary.LittleEndian.PutUint32(data[32:], 25)
|
||||
binary.LittleEndian.PutUint32(data[36:], 152)
|
||||
copy(data[40:], "__TEXT")
|
||||
|
||||
for n, v := range []uint64{0x100000000, uint64(len(data)), 0, uint64(len(data))} {
|
||||
binary.LittleEndian.PutUint64(data[56+n*8:], v)
|
||||
}
|
||||
|
||||
for n, v := range []uint32{7, 7, 1, 0} {
|
||||
binary.LittleEndian.PutUint32(data[88+n*4:], v)
|
||||
}
|
||||
|
||||
copy(data[104:], "__text")
|
||||
copy(data[120:], "__TEXT")
|
||||
binary.LittleEndian.PutUint64(data[136:], 0x100001000)
|
||||
binary.LittleEndian.PutUint64(data[144:], pageSize)
|
||||
binary.LittleEndian.PutUint32(data[152:], uint32(pageSize))
|
||||
binary.LittleEndian.PutUint32(data[156:], 2)
|
||||
binary.LittleEndian.PutUint32(data[168:], 0x80000400)
|
||||
|
||||
for n, v := range []uint32{2, 24, 512, 1, 528, 8} {
|
||||
binary.LittleEndian.PutUint32(data[184+n*4:], v)
|
||||
}
|
||||
|
||||
binary.LittleEndian.PutUint32(data[512:], 1)
|
||||
data[516], data[517] = 0x0f, 1
|
||||
binary.LittleEndian.PutUint64(data[520:], 0x100001000)
|
||||
copy(data[528:], []byte{0, 't', 'a', 'r', 'g', 'e', 't', 0})
|
||||
binary.LittleEndian.PutUint32(data[4096:], 0xd503233f)
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
type imageMemory struct {
|
||||
data []byte
|
||||
base uint64
|
||||
fail error
|
||||
}
|
||||
|
||||
func (m *imageMemory) MemMap(uint64, uint64) error { return nil }
|
||||
func (m *imageMemory) MemWrite(address uint64, data []byte) error {
|
||||
if m.fail != nil {
|
||||
return m.fail
|
||||
}
|
||||
|
||||
copy(m.data[address-m.base:], data)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ = Describe("Shared image preparation", func() {
|
||||
It("shares instruction patches and isolates relocation and source bytes", func() {
|
||||
source := sharedFixture()
|
||||
original := bytes.Clone(source)
|
||||
first, err := OpenShared("first", source)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
second, err := OpenShared("second", source)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(&first.data[0]).To(BeIdenticalTo(&source[0]))
|
||||
Expect(&first.instructions[4096][0]).To(BeIdenticalTo(&second.instructions[4096][0]))
|
||||
Expect(first.modified).To(BeEmpty())
|
||||
Expect(first.file.Symtab).To(BeIdenticalTo(second.file.Symtab))
|
||||
exported, err := second.Export("target", 0x300000000)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(exported).To(Equal(uint64(0x300001000)))
|
||||
Expect(second.InstructionRanges()).To(Equal([][2]uint64{{0x100001000, 0x100002000}}))
|
||||
Expect(second.Symbols()).To(HaveLen(1))
|
||||
first.binds = []types.Bind{{Name: "target", Segment: "__TEXT", SegOffset: 8192, Type: types.BIND_TYPE_POINTER}}
|
||||
second.binds = first.binds
|
||||
Expect(first.Relocate(0x200000000, func(string) (uint64, error) { return 0x1111, nil })).To(Succeed())
|
||||
Expect(second.Relocate(0x300000000, func(string) (uint64, error) { return 0x2222, nil })).To(Succeed())
|
||||
Expect(second.putPointer(4092, 0x8877665544332211)).To(Succeed())
|
||||
Expect(second.pointerAt(4092)).To(Equal(uint64(0x8877665544332211)))
|
||||
Expect(first.pointerAt(4092)).To(Equal(uint64(0xd503201f00000000)))
|
||||
for _, test := range []struct {
|
||||
image *Image
|
||||
base, value uint64
|
||||
}{{first, 0x200000000, 0x1111}, {second, 0x300000000, 0x2222}} {
|
||||
memory := &imageMemory{base: test.base, data: make([]byte, len(source))}
|
||||
Expect(test.image.Load(memory)).To(Succeed())
|
||||
Expect(binary.LittleEndian.Uint64(memory.data[8192:])).To(Equal(test.value))
|
||||
if test.image == first {
|
||||
Expect(binary.LittleEndian.Uint32(memory.data[4096:])).To(Equal(uint32(0xd503201f)))
|
||||
}
|
||||
}
|
||||
Expect(source).To(Equal(original))
|
||||
})
|
||||
It("keeps concurrent guests independent while sharing preparation", func() {
|
||||
source := sharedFixture()
|
||||
source[len(source)-2] = 77
|
||||
finished := make(chan error, 8)
|
||||
for n := range 8 {
|
||||
go func() {
|
||||
image, err := OpenShared("concurrent", source)
|
||||
if err == nil {
|
||||
image.binds = []types.Bind{{Name: "target", Segment: "__TEXT", SegOffset: 8192, Type: types.BIND_TYPE_POINTER}}
|
||||
expected := uint64(n+1) * 4096
|
||||
err = image.Relocate(uint64(n+1)<<32, func(string) (uint64, error) { return expected, nil })
|
||||
if err == nil && image.pointerAt(8192) != expected {
|
||||
err = fmt.Errorf("guest %d has another guest's binding", n)
|
||||
}
|
||||
}
|
||||
finished <- err
|
||||
}()
|
||||
}
|
||||
for range 8 {
|
||||
Eventually(finished).Should(Receive(BeNil()))
|
||||
}
|
||||
})
|
||||
|
||||
It("applies cached chained relocations with each guest's own addresses", func() {
|
||||
source := make([]byte, 4096)
|
||||
plan := []chainedRelocation{{offset: 0, target: 0x80}, {offset: 8, isBind: true, symbol: "target", addend: -4}}
|
||||
for _, base := range []uint64{0x1000, 0x2000} {
|
||||
image := &Image{data: source, modified: map[uint64][]byte{}, fixups: plan}
|
||||
Expect(image.relocateChained(base, func(string) (uint64, error) { return base + 0x404, nil })).To(Succeed())
|
||||
Expect(image.pointerAt(0)).To(Equal(base + 0x80))
|
||||
Expect(image.pointerAt(8)).To(Equal(base + 0x400))
|
||||
}
|
||||
Expect(source).To(Equal(make([]byte, 4096)))
|
||||
})
|
||||
It("overlays patches across unaligned page, segment, and chunk boundaries", func() {
|
||||
source := make([]byte, 3*pageSize+13)
|
||||
image := &Image{data: source, modified: map[uint64][]byte{}}
|
||||
image.writeInstruction(4094, 0x11223344)
|
||||
Expect(image.pointerAt(4092)).To(Equal(uint64(0x112233440000)))
|
||||
var decoded [8]byte
|
||||
count, err := (imageInput{image}).ReadAt(decoded[:], 4092)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(count).To(Equal(8))
|
||||
Expect(binary.LittleEndian.Uint64(decoded[:])).To(Equal(uint64(0x112233440000)))
|
||||
Expect(image.putPointer(4095, 0xaabbccddeeff0011)).To(Succeed())
|
||||
expected := bytes.Clone(source)
|
||||
binary.LittleEndian.PutUint32(expected[4094:], 0x11223344)
|
||||
binary.LittleEndian.PutUint64(expected[4095:], 0xaabbccddeeff0011)
|
||||
memory := &imageMemory{data: make([]byte, len(source))}
|
||||
Expect(image.writeSegment(memory, 0, 3, uint64(len(source)), make([]byte, 4093))).To(Succeed())
|
||||
Expect(memory.data[:len(source)-3]).To(Equal(expected[3:]))
|
||||
})
|
||||
It("invalidates preparation when any source byte changes", func() {
|
||||
source := sharedFixture()
|
||||
first, err := OpenShared("first", source)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
changed := bytes.Clone(source)
|
||||
changed[len(changed)-1] = 1
|
||||
second, err := OpenShared("second", changed)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(&first.instructions[4096][0]).NotTo(BeIdenticalTo(&second.instructions[4096][0]))
|
||||
})
|
||||
It("preserves write errors and rejects fixups outside the image", func() {
|
||||
image, err := OpenShared("image", sharedFixture())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(image.Relocate(image.Base(), nil)).To(Succeed())
|
||||
failed := errors.New("write failure")
|
||||
Expect(errors.Is(image.Load(&imageMemory{fail: failed}), failed)).To(BeTrue())
|
||||
Expect(image.putPointer(uint64(len(image.data)-7), 1)).NotTo(Succeed())
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Image preparation cache bounds", func() {
|
||||
It("evicts old preparations when the image count is exceeded", func() {
|
||||
var cache imagePreparationCache
|
||||
first := sha256.Sum256([]byte{0})
|
||||
for n := 0; n <= maxImagePreparations; n++ {
|
||||
cache.put(sha256.Sum256([]byte{byte(n)}), imagePreparation{})
|
||||
}
|
||||
_, ok := cache.get(first)
|
||||
Expect(ok).To(BeFalse())
|
||||
Expect(cache.entries).To(HaveLen(maxImagePreparations))
|
||||
})
|
||||
It("bounds retained patch and fixup storage", func() {
|
||||
var cache imagePreparationCache
|
||||
key := sha256.Sum256([]byte("first"))
|
||||
large := imagePreparation{instructions: map[uint64][]instructionPatch{0: make([]instructionPatch, 0, maxPreparationBytes/16+1)}}
|
||||
cache.put(key, large)
|
||||
_, ok := cache.get(key)
|
||||
Expect(ok).To(BeFalse())
|
||||
half := imagePreparation{instructions: map[uint64][]instructionPatch{0: large.instructions[0][: 0 : maxPreparationBytes/32+1]}}
|
||||
cache.put(key, half)
|
||||
second := sha256.Sum256([]byte("second"))
|
||||
cache.put(second, half)
|
||||
_, ok = cache.get(key)
|
||||
Expect(ok).To(BeFalse())
|
||||
Expect(cache.bytes).To(BeNumerically("<=", maxPreparationBytes))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"testing"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestImageGinkgo(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Mach-O Image Suite")
|
||||
}
|
||||
|
||||
func universalImage() []byte {
|
||||
data := make([]byte, 56)
|
||||
for index, value := range []uint32{
|
||||
types.MagicFat.Int(), 2,
|
||||
uint32(types.CPUAmd64), 3, 48, 4, 0,
|
||||
uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 52, 4, 0,
|
||||
} {
|
||||
binary.BigEndian.PutUint32(data[index*4:], value)
|
||||
}
|
||||
|
||||
copy(data[48:], []byte("x86!arm!"))
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
var _ = Describe("ARM64 image selection", func() {
|
||||
It("selects arm64e without parsing unused architectures", func() {
|
||||
input := universalImage()
|
||||
data, err := ARM64Slice(input)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).To(Equal("arm!"))
|
||||
Expect(&data[0]).To(BeIdenticalTo(&input[52]))
|
||||
})
|
||||
It("preserves thin image data", func() {
|
||||
input := []byte("thin image")
|
||||
data, err := ARM64Slice(input)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(&data[0]).To(BeIdenticalTo(&input[0]))
|
||||
})
|
||||
It("isolates mutable relocation data from the source bundle", func() {
|
||||
for _, input := range [][]byte{universalImage(), []byte("thin image")} {
|
||||
original := bytes.Clone(input)
|
||||
data, err := arm64Slice(input)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
data[0] ^= 0xff
|
||||
Expect(input).To(Equal(original))
|
||||
}
|
||||
})
|
||||
DescribeTable("rejects malformed universal images", func(mutate func([]byte) []byte, message string) {
|
||||
_, err := ARM64Slice(mutate(universalImage()))
|
||||
Expect(err).To(MatchError(ContainSubstring(message)))
|
||||
},
|
||||
Entry("truncated header", func(b []byte) []byte { return b[:4] }, "header"),
|
||||
Entry("truncated architecture table", func(b []byte) []byte { return b[:47] }, "architecture count"),
|
||||
Entry("no architectures", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[4:], 0)
|
||||
|
||||
return b
|
||||
}, "architecture count"),
|
||||
Entry("excessive count", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[4:], ^uint32(0))
|
||||
|
||||
return b
|
||||
}, "architecture count"),
|
||||
Entry("no arm64e image", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[32:], 0)
|
||||
|
||||
return b
|
||||
}, "no arm64e slice"),
|
||||
Entry("slice past the end", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[40:], 5)
|
||||
|
||||
return b
|
||||
}, "exceeds input size"),
|
||||
Entry("empty slice", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[40:], 0)
|
||||
|
||||
return b
|
||||
}, "exceeds input size"),
|
||||
Entry("overlapping header", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[36:], 8)
|
||||
|
||||
return b
|
||||
}, "overlaps"),
|
||||
Entry("large offset", func(b []byte) []byte {
|
||||
binary.BigEndian.PutUint32(b[36:], ^uint32(0))
|
||||
|
||||
return b
|
||||
}, "exceeds input size"),
|
||||
)
|
||||
})
|
||||
@@ -112,7 +112,7 @@ func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptio
|
||||
images := make(map[string]*machimage.Image, len(imageSpecs))
|
||||
|
||||
for _, spec := range imageSpecs {
|
||||
image, err := machimage.Open(spec.name, spec.data)
|
||||
image, err := machimage.OpenShared(spec.name, spec.data)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("open %s image: %w", spec.name, err)
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
@@ -154,7 +168,20 @@ func (e *Engine) register(handle uintptr) {
|
||||
purego.RegisterLibFunc(&e.api.open, handle, "uc_open")
|
||||
purego.RegisterLibFunc(&e.api.close, handle, "uc_close")
|
||||
purego.RegisterLibFunc(&e.api.query, handle, "uc_query")
|
||||
purego.RegisterLibFunc(&e.api.ctl, handle, "uc_ctl")
|
||||
// Darwin ARM64 passes C variadic arguments on the stack. Fill the six
|
||||
// remaining integer registers so purego places uc_ctl's value there.
|
||||
if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" {
|
||||
var control func(uintptr, uint32, uintptr, uintptr, uintptr, uintptr, uintptr, uintptr, uint32) int32
|
||||
|
||||
purego.RegisterLibFunc(&control, handle, "uc_ctl")
|
||||
|
||||
e.api.ctl = func(engine uintptr, command, value uint32) int32 {
|
||||
return control(engine, command, 0, 0, 0, 0, 0, 0, value)
|
||||
}
|
||||
} else {
|
||||
purego.RegisterLibFunc(&e.api.ctl, handle, "uc_ctl")
|
||||
}
|
||||
|
||||
purego.RegisterLibFunc(&e.api.strerror, handle, "uc_strerror")
|
||||
purego.RegisterLibFunc(&e.api.memMap, handle, "uc_mem_map")
|
||||
purego.RegisterLibFunc(&e.api.memUnmap, handle, "uc_mem_unmap")
|
||||
@@ -306,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)))
|
||||
}
|
||||
|
||||
@@ -330,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
|
||||
}
|
||||
|
||||
+4
-3
@@ -6,17 +6,18 @@ const (
|
||||
ucCtlTCGBufferSize = 13
|
||||
ucCtlIOWrite = 1
|
||||
ucCtlArgumentCount = 1
|
||||
tcgBufferSize = 64 << 20
|
||||
tcgBufferSize = 4 << 20
|
||||
)
|
||||
|
||||
func configureEngine(engine *Engine) error {
|
||||
// The VirtualAlloc compatibility hook commits this buffer eagerly, so keep
|
||||
// its upper bound modest instead of using Unicorn's much larger default.
|
||||
// Bound native JIT memory on every host, including memory-limited Linux
|
||||
// containers. Unicorn flushes translated blocks when the buffer fills.
|
||||
control := uint32(ucCtlTCGBufferSize |
|
||||
ucCtlArgumentCount<<26 |
|
||||
ucCtlIOWrite<<30)
|
||||
if err := engine.err(engine.api.ctl(engine.handle, control, tcgBufferSize)); err != nil {
|
||||
return fmt.Errorf("configure Unicorn translation buffer: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package unicorn
|
||||
|
||||
func configureEngine(*Engine) error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Translation buffer limit", func() {
|
||||
It("sets the native buffer size before guest memory is mapped", func() {
|
||||
called := false
|
||||
engine := &Engine{handle: 123, api: api{ctl: func(handle uintptr, control, value uint32) int32 {
|
||||
called = true
|
||||
Expect(handle).To(Equal(uintptr(123)))
|
||||
Expect(control).To(Equal(uint32(13 | 1<<26 | 1<<30)))
|
||||
Expect(value).To(Equal(uint32(tcgBufferSize)))
|
||||
|
||||
return 0
|
||||
}}}
|
||||
Expect(configureEngine(engine)).To(Succeed())
|
||||
Expect(called).To(BeTrue())
|
||||
})
|
||||
It("applies the limit to a real engine before native initialization", func() {
|
||||
engine, err := New(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(engine.Close)
|
||||
Expect(engine.MemMap(0x1000, 0x1000)).To(Succeed())
|
||||
var readBufferSize func(uintptr, uint32, *uint32) int32
|
||||
if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" {
|
||||
var control func(uintptr, uint32, uintptr, uintptr, uintptr, uintptr, uintptr, uintptr, *uint32) int32
|
||||
purego.RegisterLibFunc(&control, engine.library.handle, "uc_ctl")
|
||||
readBufferSize = func(engine uintptr, command uint32, value *uint32) int32 {
|
||||
return control(engine, command, 0, 0, 0, 0, 0, 0, value)
|
||||
}
|
||||
} else {
|
||||
purego.RegisterLibFunc(&readBufferSize, engine.library.handle, "uc_ctl")
|
||||
}
|
||||
var size uint32
|
||||
Expect(engine.err(readBufferSize(engine.handle, 13|1<<26|2<<30, &size))).To(Succeed())
|
||||
Expect(size).To(Equal(uint32(tcgBufferSize)))
|
||||
Expect(engine.err(readBufferSize(engine.handle, 7|1<<26|2<<30, &size))).To(Succeed())
|
||||
Expect(size).To(Equal(arm64CPUModelMax))
|
||||
})
|
||||
|
||||
It("reports failure to set the native buffer size", func() {
|
||||
engine := &Engine{api: api{
|
||||
ctl: func(uintptr, uint32, uint32) int32 { return 15 },
|
||||
strerror: func(int32) string { return "invalid argument" },
|
||||
}}
|
||||
Expect(configureEngine(engine)).To(MatchError(ContainSubstring("configure Unicorn translation buffer")))
|
||||
})
|
||||
})
|
||||
@@ -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())
|
||||
|
||||
@@ -26,6 +26,29 @@ func (r *Runtime) symbol(name string) {
|
||||
}
|
||||
|
||||
switch name {
|
||||
case "AMSError":
|
||||
// AMSAccountAuthenticationPlugin uses this factory when Apple returns a
|
||||
// server dialog and native presentation is disabled. Preserve the error
|
||||
// as an NSError so the framework can finish the request and the caller can
|
||||
// inspect the original response instead of aborting the guest.
|
||||
info := map[string]uint64{}
|
||||
if description := r.arg(1); description != 0 {
|
||||
info["NSLocalizedDescription"] = description
|
||||
}
|
||||
|
||||
if reason := r.arg(2); reason != 0 {
|
||||
info["NSLocalizedFailureReason"] = reason
|
||||
}
|
||||
|
||||
if underlying := r.arg(3); underlying != 0 {
|
||||
info["NSUnderlyingError"] = underlying
|
||||
}
|
||||
|
||||
r.set(r.New("NSError", map[string]uint64{
|
||||
"domain": r.New("NSString", "AMSErrorDomain"),
|
||||
"code": r.New("NSNumber", int64(r.arg(0))),
|
||||
"userInfo": r.New("NSDictionary", info),
|
||||
}))
|
||||
case "xpc_get_type":
|
||||
object := r.objects[r.arg(0)]
|
||||
if object != nil && object.Class == "HostXPCDictionary" {
|
||||
@@ -745,6 +768,29 @@ func (r *Runtime) message(receiver uint64, selector string, super bool) {
|
||||
|
||||
return
|
||||
}
|
||||
// Store tasks use keep-alives to request host process assertions. The guest
|
||||
// runs synchronously inside the CLI, so retaining a scoped token is enough.
|
||||
if class == "AMSKeepAlive" {
|
||||
switch selector {
|
||||
case "keepAliveWithName:style:", "rbs_keepAliveWithName:style:":
|
||||
if meta {
|
||||
value := r.New("AMSKeepAlive", nil)
|
||||
r.objects[value].Properties["name"] = r.arg(2)
|
||||
r.objects[value].Properties["style"] = r.arg(3)
|
||||
r.set(value)
|
||||
|
||||
return
|
||||
}
|
||||
case "invalidate", "rbs_invalidate":
|
||||
r.set(0)
|
||||
|
||||
return
|
||||
case "name", "style":
|
||||
r.set(object.Properties[selector])
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if entry := r.lookup(class, selector, meta); !super && entry != 0 {
|
||||
r.jump(entry, receiver, selector)
|
||||
@@ -1961,6 +2007,12 @@ func (r *Runtime) formatAt(format string, sp uint64) string {
|
||||
} else {
|
||||
obj := r.objects[value]
|
||||
if obj == nil {
|
||||
if class := r.classNames[value]; class != "" {
|
||||
result.WriteString(class)
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
panic(fmt.Sprintf("unknown format object %#x", value))
|
||||
}
|
||||
|
||||
|
||||
@@ -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" {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
@@ -89,10 +90,58 @@ var _ = Describe("Generated profile response branches", func() {
|
||||
Entry("version lookup GET", "lookup", http.MethodGet, "application/json", `{"results":{"fixture-value":{"offers":[]}}}`, http.StatusOK, false),
|
||||
Entry("streamed package range", "download", http.MethodGet, "application/octet-stream", "fixture-value\x00\xff", http.StatusPartialContent, true),
|
||||
Entry("authentication failure", "authenticate", http.MethodPost, "application/x-apple-plist", `<plist version="1.0"><dict><key>failureType</key><string>2034</string><key>customerMessage</key><string>fixture-value</string></dict></plist>`, http.StatusOK, false),
|
||||
Entry("authentication server dialog", "authenticate", http.MethodPost, "application/x-apple-plist", `<plist version="1.0"><dict><key>customerMessage</key><string>fixture-value</string><key>dialog</key><dict><key>message</key><string>Account locked</string><key>explanation</key><string>Reset the account to continue.</string><key>okButtonString</key><string>Reset</string><key>okButtonAction</key><dict><key>kind</key><string>OpenURL</string><key>url</key><string>https://iforgot.apple.com/cgi-bin/iforgot.cgi</string></dict></dict></dict></plist>`, http.StatusOK, false),
|
||||
Entry("purchase failure", "purchase", http.MethodPost, "application/x-apple-plist", `<plist version="1.0"><dict><key>failureType</key><string>9610</string><key>customerMessage</key><string>fixture-value</string></dict></plist>`, http.StatusOK, false),
|
||||
)
|
||||
})
|
||||
|
||||
var _ = Describe("URL component query setters", func() {
|
||||
DescribeTable("preserves query values through the runtime bridge", func(selector string, value any, encoded, decoded string) {
|
||||
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)
|
||||
u, err := url.Parse("https://example.com/path?old=value#fragment")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
components := guest.New("NSURLComponents", u)
|
||||
_, err = guest.Invoke(components, "setQuery:", guest.New("NSString", "old=value"))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
_, err = guest.Invoke(components, selector, guest.importValue(value))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
encodedQuery, err := guest.Invoke(components, "percentEncodedQuery")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
query, err := guest.Invoke(components, "query")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
expectedURL := "https://example.com/path"
|
||||
if value == nil {
|
||||
Expect(encodedQuery).To(BeZero())
|
||||
Expect(query).To(BeZero())
|
||||
} else {
|
||||
Expect(encodedQuery).NotTo(BeZero())
|
||||
Expect(query).NotTo(BeZero())
|
||||
Expect(guest.String(encodedQuery)).To(Equal(encoded))
|
||||
Expect(guest.String(query)).To(Equal(decoded))
|
||||
expectedURL += "?" + encoded
|
||||
}
|
||||
|
||||
result, err := guest.Invoke(components, "URL")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(guest.String(result)).To(Equal(expectedURL + "#fragment"))
|
||||
},
|
||||
Entry("clears an encoded query", "setPercentEncodedQuery:", nil, "", ""),
|
||||
Entry("keeps an empty encoded query delimiter", "setPercentEncodedQuery:", "", "", ""),
|
||||
Entry("preserves percent escapes and literal plus signs", "setPercentEncodedQuery:", "q=a%20b%2Bc+%26%3D%25%23&symbol=%e2%9c%93", "q=a%20b%2Bc+%26%3D%25%23&symbol=%e2%9c%93", "q=a b+c+&=%#&symbol=✓"),
|
||||
Entry("preserves query delimiters", "setPercentEncodedQuery:", "q=/?@!$&'()*+,;=:", "q=/?@!$&'()*+,;=:", "q=/?@!$&'()*+,;=:"),
|
||||
Entry("clears a decoded query", "setQuery:", nil, "", ""),
|
||||
Entry("keeps an empty decoded query delimiter", "setQuery:", "", "", ""),
|
||||
Entry("encodes decoded query values", "setQuery:", "q=a b+%&symbol=✓", "q=a%20b+%25&symbol=%E2%9C%93", "q=a b+%&symbol=✓"),
|
||||
)
|
||||
})
|
||||
|
||||
var _ = Describe("Missing profile snapshots", func() {
|
||||
It("rejects an omitted page even though its neighbors share a grouped mapping", func() {
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -534,12 +534,15 @@ func (r *Runtime) networkMessage(receiver uint64, class, selector string, meta b
|
||||
u := object.Value.(*url.URL)
|
||||
|
||||
switch selector {
|
||||
case "setQuery:":
|
||||
case "setQuery:", "setPercentEncodedQuery:":
|
||||
u.RawQuery = ""
|
||||
u.ForceQuery = r.arg(2) != 0
|
||||
|
||||
if r.arg(2) != 0 {
|
||||
u.RawQuery = encodeComponentQuery(r.String(r.arg(2)))
|
||||
u.RawQuery = r.String(r.arg(2))
|
||||
if selector == "setQuery:" {
|
||||
u.RawQuery = encodeComponentQuery(u.RawQuery)
|
||||
}
|
||||
}
|
||||
|
||||
r.set(0)
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package emulator
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type profileMemory interface{ MemWrite(uint64, []byte) error }
|
||||
|
||||
// Batch consecutive guest pages whose source bytes are also consecutive. Gaps
|
||||
// remain separate writes, so strict profile validation covers the same pages.
|
||||
func writeProfilePages(memory profileMemory, pages []Page, data []byte) error {
|
||||
for first := 0; first < len(pages); {
|
||||
page := pages[first]
|
||||
if page.Offset > uint64(len(data)) || profilePageSize > uint64(len(data))-page.Offset {
|
||||
return errors.New("profile page exceeds data")
|
||||
}
|
||||
|
||||
last := first + 1
|
||||
for last < len(pages) {
|
||||
next, previous := pages[last], pages[last-1]
|
||||
if previous.Address > ^uint64(0)-profilePageSize || next.Address != previous.Address+profilePageSize || next.Offset != previous.Offset+profilePageSize {
|
||||
break
|
||||
}
|
||||
|
||||
if next.Offset > uint64(len(data)) || profilePageSize > uint64(len(data))-next.Offset {
|
||||
return errors.New("profile page exceeds data")
|
||||
}
|
||||
|
||||
last++
|
||||
}
|
||||
|
||||
end := page.Offset + uint64(last-first)*profilePageSize
|
||||
if err := memory.MemWrite(page.Address, data[page.Offset:end]); err != nil {
|
||||
return fmt.Errorf("write Store profile pages: %w", err)
|
||||
}
|
||||
|
||||
first = last
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package emulator
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
type pageWrite struct {
|
||||
address uint64
|
||||
data []byte
|
||||
}
|
||||
type pageMemory struct {
|
||||
writes []pageWrite
|
||||
fail error
|
||||
}
|
||||
|
||||
func (m *pageMemory) MemWrite(address uint64, data []byte) error {
|
||||
if m.fail != nil {
|
||||
return m.fail
|
||||
}
|
||||
|
||||
m.writes = append(m.writes, pageWrite{address, bytes.Clone(data)})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ = Describe("Store profile page transfers", func() {
|
||||
It("batches consecutive source and guest pages without writing gaps", func() {
|
||||
data := make([]byte, 3*profilePageSize)
|
||||
for n := range data {
|
||||
data[n] = byte(n/4096 + 1)
|
||||
}
|
||||
memory := &pageMemory{}
|
||||
Expect(writeProfilePages(memory, []Page{{Address: 0x1000, Offset: 0}, {Address: 0x2000, Offset: 4096}, {Address: 0x9000, Offset: 8192}}, data)).To(Succeed())
|
||||
Expect(memory.writes).To(HaveLen(2))
|
||||
Expect(memory.writes[0]).To(Equal(pageWrite{0x1000, data[:8192]}))
|
||||
Expect(memory.writes[1]).To(Equal(pageWrite{0x9000, data[8192:]}))
|
||||
})
|
||||
It("preserves writes when source pages or guest addresses are out of order", func() {
|
||||
data := make([]byte, 3*profilePageSize)
|
||||
memory := &pageMemory{}
|
||||
pages := []Page{{Address: 0x2000, Offset: 0}, {Address: 0x1000, Offset: 8192}, {Address: 0x2000, Offset: 4096}}
|
||||
Expect(writeProfilePages(memory, pages, data)).To(Succeed())
|
||||
Expect(memory.writes).To(HaveLen(3))
|
||||
for n, page := range pages {
|
||||
Expect(memory.writes[n]).To(Equal(pageWrite{page.Address, data[page.Offset : page.Offset+4096]}))
|
||||
}
|
||||
})
|
||||
It("rejects truncated and wrapping source ranges", func() {
|
||||
for _, offset := range []uint64{1, 4096, ^uint64(0) - 4095} {
|
||||
memory := &pageMemory{}
|
||||
Expect(writeProfilePages(memory, []Page{{Address: 0x1000, Offset: offset}}, make([]byte, 4096))).To(MatchError("profile page exceeds data"))
|
||||
Expect(memory.writes).To(BeEmpty())
|
||||
}
|
||||
})
|
||||
It("does not merge across a wrapping guest address", func() {
|
||||
memory := &pageMemory{}
|
||||
Expect(writeProfilePages(memory, []Page{{Address: ^uint64(0) - 4095, Offset: 0}, {Address: 0, Offset: 4096}}, make([]byte, 8192))).To(Succeed())
|
||||
Expect(memory.writes).To(HaveLen(2))
|
||||
})
|
||||
It("preserves memory write errors", func() {
|
||||
failed := errors.New("write failure")
|
||||
err := writeProfilePages(&pageMemory{fail: failed}, []Page{{Address: 0x1000}}, make([]byte, 4096))
|
||||
Expect(errors.Is(err, failed)).To(BeTrue())
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,6 @@
|
||||
package emulator
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
@@ -13,7 +12,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
"github.com/majd/ipatool/v2/internal/sap/machimage"
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
storeprofile "github.com/majd/ipatool/v2/internal/store/profile"
|
||||
@@ -46,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)
|
||||
@@ -151,8 +150,10 @@ func open(ctx context.Context, imageData []byte, prepared storeprofile.Data, str
|
||||
}
|
||||
}
|
||||
|
||||
images := make([]*machimage.Image, 0, len(imageInputs))
|
||||
|
||||
for name, data := range imageInputs {
|
||||
image, e := machimage.Open(name, data)
|
||||
image, e := machimage.OpenShared(name, data)
|
||||
if e != nil {
|
||||
return nil, fmt.Errorf("prepare store runtime: %w", e)
|
||||
}
|
||||
@@ -164,6 +165,8 @@ func open(ctx context.Context, imageData []byte, prepared storeprofile.Data, str
|
||||
if e = image.Load(r); e != nil {
|
||||
return nil, fmt.Errorf("prepare store runtime: %w", e)
|
||||
}
|
||||
|
||||
images = append(images, image)
|
||||
}
|
||||
|
||||
pageData := prepared.Pages
|
||||
@@ -210,14 +213,8 @@ func open(ctx context.Context, imageData []byte, prepared storeprofile.Data, str
|
||||
}
|
||||
}
|
||||
|
||||
for _, page := range profile.Pages {
|
||||
if page.Offset+4096 > uint64(len(pageData)) {
|
||||
return nil, errors.New("profile page exceeds data")
|
||||
}
|
||||
|
||||
if err = r.MemWrite(page.Address, pageData[page.Offset:page.Offset+4096]); err != nil {
|
||||
return nil, fmt.Errorf("prepare store runtime: %w", err)
|
||||
}
|
||||
if err = writeProfilePages(r, profile.Pages, pageData); err != nil {
|
||||
return nil, fmt.Errorf("prepare store runtime: %w", err)
|
||||
}
|
||||
|
||||
for _, call := range profile.Calls {
|
||||
@@ -233,39 +230,26 @@ func open(ctx context.Context, imageData []byte, prepared storeprofile.Data, str
|
||||
}
|
||||
}
|
||||
// Non-fragile ivar offsets are fixed by the Objective-C loader on macOS.
|
||||
for _, imageBytes := range imageInputs {
|
||||
file, err := macho.NewFile(bytes.NewReader(imageBytes))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("prepare store runtime: %w", err)
|
||||
}
|
||||
for _, image := range images {
|
||||
r.codeRanges = append(r.codeRanges, image.InstructionRanges()...)
|
||||
|
||||
defer file.Close()
|
||||
|
||||
for _, section := range file.Sections {
|
||||
if section.Flags.IsPureInstructions() || section.Flags.IsSomeInstructions() {
|
||||
r.codeRanges = append(r.codeRanges, [2]uint64{section.Addr, section.Addr + section.Size})
|
||||
for _, sym := range image.Symbols() {
|
||||
if !strings.HasPrefix(sym.Name, "_OBJC_IVAR_$_") {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if file.Symtab != nil {
|
||||
for _, sym := range file.Symtab.Syms {
|
||||
if !strings.HasPrefix(sym.Name, "_OBJC_IVAR_$_") {
|
||||
continue
|
||||
}
|
||||
parts := strings.SplitN(strings.TrimPrefix(sym.Name, "_OBJC_IVAR_$_"), ".", 2)
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
parts := strings.SplitN(strings.TrimPrefix(sym.Name, "_OBJC_IVAR_$_"), ".", 2)
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
}
|
||||
if c := r.classes[parts[0]]; c != nil {
|
||||
if offset, ok := c.Ivars[parts[1]]; ok {
|
||||
data := make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(data, uint32(offset))
|
||||
|
||||
if c := r.classes[parts[0]]; c != nil {
|
||||
if offset, ok := c.Ivars[parts[1]]; ok {
|
||||
data := make([]byte, 4)
|
||||
binary.LittleEndian.PutUint32(data, uint32(offset))
|
||||
|
||||
if err = r.MemWrite(sym.Value, data); err != nil {
|
||||
return nil, fmt.Errorf("prepare store runtime: %w", err)
|
||||
}
|
||||
if err = r.MemWrite(sym.Value, data); err != nil {
|
||||
return nil, fmt.Errorf("prepare store runtime: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -25,7 +25,7 @@ func StoreAMDHeaders(ctx context.Context, encoded []byte, endpoint string, hardw
|
||||
}
|
||||
|
||||
if len(state.Provisioning) == 0 {
|
||||
return nil, nil, errors.New("store AMD state is not provisioned")
|
||||
return nil, nil, errors.New("store AMD state is not provisioned; run 'ipatool auth login' to authenticate")
|
||||
}
|
||||
|
||||
bundle, err := assets.Load(ctx)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+29
-22
@@ -43,28 +43,33 @@ type AppStore interface {
|
||||
}
|
||||
|
||||
type appstore struct {
|
||||
keychain keychain.Keychain
|
||||
loginClient http.Client[loginResult]
|
||||
searchClient http.Client[searchResult]
|
||||
purchaseClient http.Client[purchaseResult]
|
||||
downloadClient http.Client[downloadResult]
|
||||
kbsyncGenerator kbsyncGenerator
|
||||
kbsyncCache kbsyncCache
|
||||
platformClient http.Client[platformVersionLookupResult]
|
||||
storefrontClient http.Client[[]byte]
|
||||
bagClient http.Client[bagResult]
|
||||
ownedAppsClient http.Client[[]byte]
|
||||
httpClient http.Client[interface{}]
|
||||
macDecrypterFactory macPackageDecrypterFactory
|
||||
actionSignerFactory ActionSignerFactory
|
||||
authRetrySleep func(time.Duration)
|
||||
machine machine.Machine
|
||||
os operatingsystem.OperatingSystem
|
||||
authBackend *store.Backend
|
||||
authHTTP *gohttp.Client
|
||||
authStateMu sync.Mutex
|
||||
anisetteState []byte
|
||||
authenticationHeaders gohttp.Header
|
||||
keychain keychain.Keychain
|
||||
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{}]
|
||||
macDecrypterFactory macPackageDecrypterFactory
|
||||
actionSignerFactory ActionSignerFactory
|
||||
authRetrySleep func(time.Duration)
|
||||
machine machine.Machine
|
||||
os operatingsystem.OperatingSystem
|
||||
authBackend *store.Backend
|
||||
authHTTP *gohttp.Client
|
||||
authStateMu sync.Mutex
|
||||
anisetteState []byte
|
||||
authenticationHeaders gohttp.Header
|
||||
}
|
||||
|
||||
type Args struct {
|
||||
@@ -99,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{
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
gohttp "net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
var _ = Describe("Delisted app kbsync recovery", func() {
|
||||
const guid = "001122334455"
|
||||
var (
|
||||
store *appstore
|
||||
downloads *http.MockClient[downloadResult]
|
||||
account Account
|
||||
app App
|
||||
redownload downloadProductEndpoint
|
||||
success http.Result[downloadResult]
|
||||
forbidden error
|
||||
generated int
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
downloads = http.NewMockClient[downloadResult](gomock.NewController(GinkgoT()))
|
||||
generated = 0
|
||||
store = &appstore{
|
||||
downloadClient: downloads,
|
||||
kbsyncGenerator: func(ctx context.Context, hardwareID []byte, dsid uint64) ([]byte, error) {
|
||||
Expect(ctx.Err()).NotTo(HaveOccurred())
|
||||
deadline, ok := ctx.Deadline()
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(time.Until(deadline)).To(BeNumerically("<=", 2*time.Minute))
|
||||
Expect(hardwareID).To(Equal([]byte{0, 0x11, 0x22, 0x33, 0x44, 0x55}))
|
||||
Expect(dsid).To(Equal(uint64(1234)))
|
||||
generated++
|
||||
|
||||
return []byte("kbsync blob"), nil
|
||||
},
|
||||
}
|
||||
account = Account{DirectoryServicesID: "1234", PasswordToken: "token", StoreFront: "143469-2,29"}
|
||||
app = App{ID: 42, BundleID: "com.example.app"}
|
||||
var err error
|
||||
redownload, err = newDownloadEndpoint(testRedownloadEndpoint, redownloadProductPath)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
success = http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{
|
||||
Items: []downloadItemResult{{URL: "https://example.test/app.ipa", Metadata: map[string]interface{}{
|
||||
"itemId": app.ID, "softwareVersionBundleId": app.BundleID,
|
||||
"softwareVersionExternalIdentifier": uint64(1001),
|
||||
}}},
|
||||
}}
|
||||
forbidden = &http.UnexpectedResponseError{StatusCode: gohttp.StatusForbidden}
|
||||
})
|
||||
|
||||
expectRedownload := func(response http.Result[downloadResult], err error) *gomock.Call {
|
||||
return downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testRedownloadEndpoint + "?guid=" + guid))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).NotTo(HaveKey("appExtVrsId"))
|
||||
}).Return(response, err)
|
||||
}
|
||||
|
||||
expectCatalog404Recovery := func() *gomock.Call {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
bags := http.NewMockClient[bagResult](ctrl)
|
||||
catalogs := http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
store.bagClient = bags
|
||||
store.platformClient = catalogs
|
||||
store.storefrontCountryCodes = testStorefrontCountryCodes()
|
||||
last := bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK, Data: bagResult{URLBag: urlBag{
|
||||
EntDownloadEndpoint: testEntDownloadEndpoint, RedownloadEndpoint: testRedownloadEndpoint,
|
||||
}},
|
||||
}, nil)
|
||||
// The preferred request and legacy fallback both discover the missing offer.
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
for _, catalog := range []string{"enterprisestore", "iphone", "ipad"} {
|
||||
last = catalogs.EXPECT().Send(store.platformVersionLookupRequest(app.ID, "RU", catalog)).After(last).
|
||||
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK}, nil)
|
||||
}
|
||||
last = catalogs.EXPECT().Send(http.Request{
|
||||
URL: "https://apps.apple.com/api/apps/v1/catalog/ru/apps/42?platform=iphone",
|
||||
Method: http.MethodGET, ResponseFormat: http.ResponseFormatJSON,
|
||||
}).After(last).Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusNotFound}, nil)
|
||||
if attempt == 0 {
|
||||
last = downloads.EXPECT().Send(store.downloadProductRequest(store.volumeStoreEndpoint(account), account, app, guid, "")).After(last).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK}, nil)
|
||||
}
|
||||
}
|
||||
|
||||
return expectRedownload(http.Result[downloadResult]{}, forbidden).After(last)
|
||||
}
|
||||
|
||||
It("recovers an opaque redownload 403 without consulting the catalog or pinning a version", func() {
|
||||
first := expectRedownload(http.Result[downloadResult]{}, forbidden)
|
||||
downloads.EXPECT().Send(gomock.Any()).After(first).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testEntDownloadEndpoint + "?guid=" + guid))
|
||||
Expect(req.NoRedirects).To(BeTrue())
|
||||
Expect(req.Headers).To(HaveKeyWithValue("X-Token", account.PasswordToken))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("X-Apple-Store-Front", account.StoreFront))
|
||||
payload := req.Payload.(*http.XMLPayload).Content
|
||||
Expect(payload).To(HaveKey("kbsync"))
|
||||
Expect(payload).NotTo(HaveKey("externalVersionId"))
|
||||
}).Return(success, nil)
|
||||
|
||||
actual, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(Equal(1))
|
||||
})
|
||||
|
||||
It("keeps a successful redownload without generating kbsync", func() {
|
||||
expectRedownload(success, nil)
|
||||
actual, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(BeZero())
|
||||
})
|
||||
|
||||
It("lists versions through the complete catalog-404 and redownload-403 recovery chain", func() {
|
||||
device := machine.NewMockMachine(gomock.NewController(GinkgoT()))
|
||||
device.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
store.machine = device
|
||||
success.Data.Items[0].Metadata["softwareVersionExternalIdentifiers"] = []interface{}{"1000", "1001"}
|
||||
last := expectCatalog404Recovery()
|
||||
downloads.EXPECT().Send(gomock.Any()).After(last).Return(success, nil)
|
||||
out, err := store.ListVersions(ListVersionsInput{Account: account, App: app})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(out.ExternalVersionIdentifiers).To(Equal([]string{"1000", "1001"}))
|
||||
Expect(out.LatestExternalVersionID).To(Equal("1001"))
|
||||
Expect(generated).To(Equal(1))
|
||||
})
|
||||
|
||||
DescribeTable("validates recovered packages before replacing the destination", func(supportedPlatform string) {
|
||||
device := machine.NewMockMachine(gomock.NewController(GinkgoT()))
|
||||
device.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
store.machine = device
|
||||
store.os = operatingsystem.New()
|
||||
store.httpClient = newDownloadTestClient()
|
||||
packageBuffer := new(bytes.Buffer)
|
||||
writer := zip.NewWriter(packageBuffer)
|
||||
infoWriter, err := writer.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleSupportedPlatforms": []string{supportedPlatform},
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
_, err = infoWriter.Write(info)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(writer.Close()).To(Succeed())
|
||||
server := httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, _ *gohttp.Request) {
|
||||
_, _ = w.Write(packageBuffer.Bytes())
|
||||
}))
|
||||
DeferCleanup(server.Close)
|
||||
success.Data.Items[0].URL = server.URL + "/app.ipa"
|
||||
last := expectCatalog404Recovery()
|
||||
downloads.EXPECT().Send(gomock.Any()).After(last).Return(success, nil)
|
||||
destination := filepath.Join(GinkgoT().TempDir(), "app.ipa")
|
||||
Expect(os.WriteFile(destination, []byte("previous package"), 0600)).To(Succeed())
|
||||
out, err := store.Download(DownloadInput{Account: account, App: app, OutputPath: destination})
|
||||
if supportedPlatform == "iPhoneOS" {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(out.DestinationPath).To(Equal(destination))
|
||||
Expect(store.validatePackagePlatform(destination, PlatformIPhone)).To(Succeed())
|
||||
} else {
|
||||
Expect(err).To(MatchError(ContainSubstring("does not declare iPhoneOS support")))
|
||||
Expect(os.ReadFile(destination)).To(Equal([]byte("previous package")))
|
||||
}
|
||||
Expect(destination + ".tmp").NotTo(BeAnExistingFile())
|
||||
},
|
||||
Entry("iOS", "iPhoneOS"),
|
||||
Entry("tvOS", "AppleTVOS"),
|
||||
)
|
||||
|
||||
It("preserves authentication recovery without trying another endpoint", func() {
|
||||
expectRedownload(http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{
|
||||
Dialog: map[string]interface{}{"kind": "authorization"},
|
||||
Metrics: map[string]interface{}{"messageCode": uint64(2042)},
|
||||
}}, nil)
|
||||
actual, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual.Data.FailureType).To(Equal(FailureTypePasswordTokenExpired))
|
||||
Expect(generated).To(BeZero())
|
||||
})
|
||||
|
||||
DescribeTable("preserves actionable errors from ent/download", func(failure, expected string) {
|
||||
first := expectRedownload(http.Result[downloadResult]{}, forbidden)
|
||||
downloads.EXPECT().Send(gomock.Any()).After(first).Return(http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK, Data: downloadResult{FailureType: failure},
|
||||
}, nil)
|
||||
actual, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual.Data.FailureType).To(Equal(expected))
|
||||
},
|
||||
Entry("expired token", FailureTypePasswordTokenExpired, FailureTypePasswordTokenExpired),
|
||||
Entry("sign-in required", FailureTypeSignInRequired, FailureTypePasswordTokenExpired),
|
||||
Entry("missing license", FailureTypeLicenseNotFound, FailureTypeLicenseNotFound),
|
||||
)
|
||||
|
||||
It("tries ent/download after an unavailable dialog and retains the missing-license result if it fails", func() {
|
||||
expectRedownload(http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{
|
||||
CustomerMessage: "Redownload Unavailable with This Apple Account",
|
||||
}}, nil)
|
||||
downloads.EXPECT().Send(gomock.Any()).Return(http.Result[downloadResult]{}, forbidden)
|
||||
actual, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual.Data.FailureType).To(Equal(FailureTypeLicenseNotFound))
|
||||
})
|
||||
|
||||
DescribeTable("retains the original error when kbsync recovery is unavailable", func(generatorAvailable bool, endpoint string) {
|
||||
if !generatorAvailable {
|
||||
store.kbsyncGenerator = nil
|
||||
}
|
||||
expectRedownload(http.Result[downloadResult]{}, forbidden)
|
||||
_, err := store.sendDelistedDownload(context.Background(), redownload, endpoint, account, app, guid)
|
||||
Expect(errors.Is(err, forbidden)).To(BeTrue())
|
||||
Expect(generated).To(BeZero())
|
||||
},
|
||||
Entry("no generator", false, testEntDownloadEndpoint),
|
||||
Entry("no endpoint", true, ""),
|
||||
)
|
||||
|
||||
It("reports both endpoint failures and the missing catalog offer", func() {
|
||||
failed := errors.New("kbsync endpoint failed")
|
||||
first := expectRedownload(http.Result[downloadResult]{}, forbidden)
|
||||
downloads.EXPECT().Send(gomock.Any()).After(first).Return(http.Result[downloadResult]{}, failed)
|
||||
_, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
|
||||
Expect(err).To(MatchError(ContainSubstring("app 42 has no offer")))
|
||||
Expect(errors.Is(err, forbidden)).To(BeTrue())
|
||||
Expect(errors.Is(err, failed)).To(BeTrue())
|
||||
})
|
||||
|
||||
It("rejects an invalid ent/download destination before generating or sending credentials", func() {
|
||||
expectRedownload(http.Result[downloadResult]{}, forbidden)
|
||||
_, err := store.sendDelistedDownload(context.Background(), redownload, "https://example.test/ent/download", account, app, guid)
|
||||
Expect(err).To(MatchError(ContainSubstring("invalid download endpoint in bag")))
|
||||
Expect(generated).To(BeZero())
|
||||
})
|
||||
|
||||
It("does not start kbsync recovery after cancellation", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
expectRedownload(http.Result[downloadResult]{}, forbidden).Do(func(http.Request) { cancel() })
|
||||
_, err := store.sendDelistedDownload(ctx, redownload, testEntDownloadEndpoint, account, app, guid)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(generated).To(BeZero())
|
||||
})
|
||||
|
||||
DescribeTable("validates the unpinned ent/download response", func(field string, value interface{}) {
|
||||
success.Data.Items[0].Metadata[field] = value
|
||||
first := expectRedownload(http.Result[downloadResult]{}, forbidden)
|
||||
downloads.EXPECT().Send(gomock.Any()).After(first).Return(success, nil)
|
||||
_, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err).To(MatchError(ContainSubstring("does not match the requested")))
|
||||
},
|
||||
Entry("wrong app", "itemId", int64(43)),
|
||||
Entry("wrong bundle", "softwareVersionBundleId", "com.other.app"),
|
||||
Entry("missing bundle", "softwareVersionBundleId", nil),
|
||||
)
|
||||
})
|
||||
|
||||
var _ = Describe("Download failure dialogs", func() {
|
||||
It("does not reinterpret successful items using metric codes", func() {
|
||||
result := downloadResult{
|
||||
Items: []downloadItemResult{{URL: "https://example.test/app.ipa"}},
|
||||
Metrics: map[string]interface{}{"messageCode": uint64(0)},
|
||||
}
|
||||
Expect(normalizeDownloadFailure(result).FailureType).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("keeps authentication recovery when an error response also contains items", func() {
|
||||
result := downloadResult{FailureType: FailureTypeDeviceVerificationFailed, Items: []downloadItemResult{{}}}
|
||||
Expect(normalizeDownloadFailure(result).FailureType).To(Equal(FailureTypePasswordTokenExpired))
|
||||
})
|
||||
|
||||
DescribeTable("normalizes plist dialogs and metric codes", func(body, expected string) {
|
||||
var result downloadResult
|
||||
_, err := plist.Unmarshal([]byte(`<plist version="1.0"><dict>`+body+`</dict></plist>`), &result)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(normalizeDownloadFailure(result).FailureType).To(Equal(expected))
|
||||
},
|
||||
Entry("numeric sign-in metric", `<key>metrics</key><dict><key>messageCode</key><integer>2042</integer></dict>`, FailureTypePasswordTokenExpired),
|
||||
Entry("string expired-token metric", `<key>metrics</key><dict><key>messageCode</key><string>2034</string></dict>`, FailureTypePasswordTokenExpired),
|
||||
Entry("existing failure", `<key>failureType</key><string>9610</string><key>metrics</key><dict><key>messageCode</key><integer>2042</integer></dict>`, FailureTypeLicenseNotFound),
|
||||
Entry("sign-in message", `<key>customerMessage</key><string>Sign in to the iTunes Store</string>`, FailureTypePasswordTokenExpired),
|
||||
Entry("unavailable dialog with Apple spaces", `<key>dialog</key><dict><key>message</key><string>Redownload Unavailable with This Apple Account</string><key>explanation</key><string>This redownload is not available for this Apple Account either because it was bought by a different user or the item was refunded or cancelled.</string></dict>`, FailureTypeLicenseNotFound),
|
||||
Entry("unavailable with a metric code", `<key>customerMessage</key><string>Redownload Unavailable with This Apple Account</string><key>metrics</key><dict><key>messageCode</key><integer>2059</integer></dict>`, FailureTypeLicenseNotFound),
|
||||
)
|
||||
})
|
||||
@@ -233,24 +233,54 @@ type downloadItemResult struct {
|
||||
}
|
||||
|
||||
type downloadResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
Items []downloadItemResult `plist:"songList,omitempty"`
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
Dialog map[string]interface{} `plist:"dialog,omitempty"`
|
||||
Metrics map[string]interface{} `plist:"metrics,omitempty"`
|
||||
Items []downloadItemResult `plist:"songList,omitempty"`
|
||||
}
|
||||
|
||||
func (t *appstore) downloadFile(ctx context.Context, src, dst string, progress *progressbar.ProgressBar) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
err := t.downloadFileAttempt(ctx, src, dst, progress, true, "")
|
||||
|
||||
var parallelErr *parallelDownloadError
|
||||
if !errors.As(err, ¶llelErr) || ctx.Err() != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if fallbackErr := t.downloadFileAttempt(ctx, src, dst, progress, false, parallelErr.validator); fallbackErr != nil {
|
||||
return errors.Join(err, fmt.Errorf("single-connection fallback failed: %w", fallbackErr))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
//nolint:nonamedreturns // Deferred close errors must propagate to callers.
|
||||
func (t *appstore) downloadFile(ctx context.Context, src, dst string, progress *progressbar.ProgressBar) (err error) {
|
||||
func (t *appstore) downloadFileAttempt(ctx context.Context, src, dst string, progress *progressbar.ProgressBar, parallel bool, validator string) (err error) {
|
||||
req, err := t.httpClient.NewRequest("GET", src, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
// Staged ranges are expendable; only the contiguous destination is resumed.
|
||||
if err := os.RemoveAll(downloadPartsPath(dst)); err != nil {
|
||||
return fmt.Errorf("failed to remove stale download parts: %w", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
if req != nil {
|
||||
req = req.WithContext(ctx)
|
||||
req.Header.Set("Accept-Encoding", "identity")
|
||||
|
||||
if validator != "" {
|
||||
req.Header.Set("If-Range", validator)
|
||||
}
|
||||
}
|
||||
|
||||
file, err := t.os.OpenFile(dst, os.O_CREATE|os.O_RDWR, 0644)
|
||||
@@ -310,6 +340,17 @@ func (t *appstore) downloadFile(ctx context.Context, src, dst string, progress *
|
||||
writer = io.MultiWriter(file, progress)
|
||||
}
|
||||
|
||||
// Combining responses requires a strong validator to keep all ranges on
|
||||
// the same representation. Servers without one retain the single stream.
|
||||
if parallel && res.StatusCode == gohttp.StatusPartialContent &&
|
||||
remaining == total-offset && remaining >= parallelDownloadThreshold && downloadValidator(res) != "" {
|
||||
if err := t.downloadFileParallel(ctx, cancel, src, dst, file, writer, res, offset, total, progress); err != nil {
|
||||
return ¶llelDownloadError{err: err, validator: downloadValidator(res)}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var body io.Reader = res.Body
|
||||
if remaining >= 0 {
|
||||
body = io.LimitReader(body, remaining)
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/schollz/progressbar/v3"
|
||||
)
|
||||
|
||||
const (
|
||||
parallelDownloadThreshold = 128 << 20
|
||||
parallelDownloadCount = 4
|
||||
)
|
||||
|
||||
type parallelDownloadError struct {
|
||||
err error
|
||||
validator string
|
||||
}
|
||||
|
||||
func (e *parallelDownloadError) Error() string {
|
||||
return fmt.Sprintf("parallel download failed: %s", e.err)
|
||||
}
|
||||
|
||||
func (e *parallelDownloadError) Unwrap() error {
|
||||
return e.err
|
||||
}
|
||||
|
||||
func downloadPartsPath(destination string) string {
|
||||
return destination + ".ipatool-parts"
|
||||
}
|
||||
|
||||
func downloadValidator(response *http.Response) string {
|
||||
etag := response.Header.Get("ETag")
|
||||
if strings.HasPrefix(etag, `"`) && strings.HasSuffix(etag, `"`) {
|
||||
return etag
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// Keep out-of-order bytes out of the main file, so even an unclean process exit
|
||||
// leaves its length describing a valid contiguous prefix for the next attempt.
|
||||
//
|
||||
//nolint:nonamedreturns // Staging cleanup errors must propagate to callers.
|
||||
func (t *appstore) downloadFileParallel(
|
||||
ctx context.Context,
|
||||
cancel context.CancelFunc,
|
||||
src, dst string,
|
||||
file *os.File,
|
||||
writer io.Writer,
|
||||
response *http.Response,
|
||||
offset, total int64,
|
||||
progress *progressbar.ProgressBar,
|
||||
) (err error) {
|
||||
directory := downloadPartsPath(dst)
|
||||
if err := os.Mkdir(directory, 0700); err != nil {
|
||||
return fmt.Errorf("failed to create download staging directory: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if cleanupErr := os.RemoveAll(directory); cleanupErr != nil {
|
||||
err = joinCleanupError(err, "failed to remove download staging directory", cleanupErr)
|
||||
}
|
||||
}()
|
||||
|
||||
chunkSize := (total - offset) / parallelDownloadCount
|
||||
validator := downloadValidator(response)
|
||||
|
||||
var (
|
||||
workers sync.WaitGroup
|
||||
failures [parallelDownloadCount - 1]error
|
||||
)
|
||||
|
||||
for index := range parallelDownloadCount - 1 {
|
||||
workers.Add(1)
|
||||
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
|
||||
start := offset + chunkSize*int64(index+1)
|
||||
end := start + chunkSize - 1
|
||||
|
||||
if index == parallelDownloadCount-2 {
|
||||
end = total - 1
|
||||
}
|
||||
|
||||
path := filepath.Join(directory, fmt.Sprintf("%d", index))
|
||||
failures[index] = t.downloadFileRange(ctx, src, path, start, end, total, validator, progress)
|
||||
|
||||
if failures[index] != nil {
|
||||
cancel()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
_, copyErr := io.CopyN(writer, response.Body, chunkSize)
|
||||
// The initial request covers the entire remainder. Stop reading it once its
|
||||
// first quarter is written; the other requests supply the remaining ranges.
|
||||
_ = response.Body.Close()
|
||||
|
||||
if copyErr != nil {
|
||||
cancel()
|
||||
}
|
||||
|
||||
workers.Wait()
|
||||
|
||||
for _, failure := range failures {
|
||||
if failure != nil {
|
||||
return failure
|
||||
}
|
||||
}
|
||||
|
||||
if copyErr != nil {
|
||||
return fmt.Errorf("failed to download first range: %w", copyErr)
|
||||
}
|
||||
|
||||
for index := range parallelDownloadCount - 1 {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return fmt.Errorf("download canceled: %w", err)
|
||||
}
|
||||
|
||||
path := filepath.Join(directory, fmt.Sprintf("%d", index))
|
||||
if err := appendDownloadPart(file, path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
//nolint:nonamedreturns // Deferred close errors must propagate to callers.
|
||||
func (t *appstore) downloadFileRange(ctx context.Context, src, dst string, start, end, total int64, validator string, progress *progressbar.ProgressBar) (err error) {
|
||||
req, err := t.httpClient.NewRequest(http.MethodGet, src, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create range request: %w", err)
|
||||
}
|
||||
|
||||
req = req.WithContext(ctx)
|
||||
req.Header.Set("Accept-Encoding", "identity")
|
||||
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end))
|
||||
|
||||
if validator != "" {
|
||||
req.Header.Set("If-Range", validator)
|
||||
}
|
||||
|
||||
response, err := t.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("range request failed: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
_, length, size, _, err := downloadResponseRange(response, start)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if response.StatusCode != http.StatusPartialContent || length != end-start+1 || size != total {
|
||||
return fmt.Errorf("unexpected download range %q", response.Header.Get("Content-Range"))
|
||||
}
|
||||
|
||||
if encoding := response.Header.Get("Content-Encoding"); encoding != "" && !strings.EqualFold(encoding, "identity") {
|
||||
return fmt.Errorf("unexpected download content encoding %q", encoding)
|
||||
}
|
||||
|
||||
if etag := response.Header.Get("ETag"); validator != "" && etag != "" && etag != validator {
|
||||
return fmt.Errorf("download validator changed from %q to %q", validator, etag)
|
||||
}
|
||||
|
||||
file, err := os.OpenFile(dst, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create download part: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if closeErr := file.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close download part", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
var writer io.Writer = file
|
||||
if progress != nil {
|
||||
writer = io.MultiWriter(file, progress)
|
||||
}
|
||||
|
||||
written, err := io.Copy(writer, io.LimitReader(response.Body, length+1))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write download part: %w", err)
|
||||
}
|
||||
|
||||
if written != length {
|
||||
return fmt.Errorf("download part is incomplete: %w", io.ErrUnexpectedEOF)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func appendDownloadPart(destination io.Writer, path string) error {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open download part: %w", err)
|
||||
}
|
||||
|
||||
_, copyErr := io.Copy(destination, file)
|
||||
closeErr := file.Close()
|
||||
|
||||
if copyErr != nil {
|
||||
return fmt.Errorf("failed to append download part: %w", copyErr)
|
||||
}
|
||||
|
||||
if closeErr != nil {
|
||||
return fmt.Errorf("failed to close download part: %w", closeErr)
|
||||
}
|
||||
|
||||
if err := os.Remove(path); err != nil {
|
||||
return fmt.Errorf("failed to remove download part: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
)
|
||||
|
||||
type downloadFixtureData byte
|
||||
|
||||
func (seed downloadFixtureData) ReadAt(buffer []byte, offset int64) (int, error) {
|
||||
for index := range buffer {
|
||||
buffer[index] = byte((offset+int64(index))%251) + byte(seed)
|
||||
}
|
||||
|
||||
return len(buffer), nil
|
||||
}
|
||||
|
||||
type downloadFixtureRequest struct {
|
||||
rangeHeader string
|
||||
validator string
|
||||
}
|
||||
|
||||
type parallelDownloadFixture struct {
|
||||
size int64
|
||||
path string
|
||||
store *appstore
|
||||
server *httptest.Server
|
||||
mu sync.Mutex
|
||||
requests []downloadFixtureRequest
|
||||
active atomic.Int64
|
||||
maximum atomic.Int64
|
||||
handler http.HandlerFunc
|
||||
}
|
||||
|
||||
func newParallelDownloadFixture(size int64) *parallelDownloadFixture {
|
||||
fixture := ¶llelDownloadFixture{
|
||||
size: size,
|
||||
path: filepath.Join(GinkgoT().TempDir(), "app.ipa.tmp"),
|
||||
store: &appstore{httpClient: newDownloadTestClient(), os: operatingsystem.New()},
|
||||
}
|
||||
|
||||
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
fixture.serve(writer, request, 1, `"fixture"`)
|
||||
}
|
||||
fixture.server = httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
defer GinkgoRecover()
|
||||
|
||||
active := fixture.active.Add(1)
|
||||
defer fixture.active.Add(-1)
|
||||
|
||||
for maximum := fixture.maximum.Load(); active > maximum; maximum = fixture.maximum.Load() {
|
||||
if fixture.maximum.CompareAndSwap(maximum, active) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
fixture.mu.Lock()
|
||||
fixture.requests = append(fixture.requests, downloadFixtureRequest{
|
||||
rangeHeader: request.Header.Get("Range"),
|
||||
validator: request.Header.Get("If-Range"),
|
||||
})
|
||||
fixture.mu.Unlock()
|
||||
|
||||
fixture.handler(writer, request)
|
||||
}))
|
||||
DeferCleanup(fixture.server.Close)
|
||||
|
||||
return fixture
|
||||
}
|
||||
|
||||
func (fixture *parallelDownloadFixture) serve(writer http.ResponseWriter, request *http.Request, seed downloadFixtureData, validator string) {
|
||||
if validator != "" {
|
||||
writer.Header().Set("ETag", validator)
|
||||
}
|
||||
|
||||
http.ServeContent(writer, request, "app.ipa", time.Time{}, io.NewSectionReader(seed, 0, fixture.size))
|
||||
}
|
||||
|
||||
func (fixture *parallelDownloadFixture) recordedRequests() []downloadFixtureRequest {
|
||||
fixture.mu.Lock()
|
||||
defer fixture.mu.Unlock()
|
||||
|
||||
return append([]downloadFixtureRequest(nil), fixture.requests...)
|
||||
}
|
||||
|
||||
func (fixture *parallelDownloadFixture) writePrefix(size int64) {
|
||||
file, err := os.Create(fixture.path)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
_, err = io.Copy(file, io.NewSectionReader(downloadFixtureData(1), 0, size))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(file.Close()).To(Succeed())
|
||||
}
|
||||
|
||||
func (fixture *parallelDownloadFixture) expectContents(seed downloadFixtureData) {
|
||||
file, err := os.Open(fixture.path)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(info.Size()).To(Equal(fixture.size))
|
||||
|
||||
actual, expected := sha256.New(), sha256.New()
|
||||
_, err = io.Copy(actual, file)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
_, err = io.Copy(expected, io.NewSectionReader(seed, 0, fixture.size))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual.Sum(nil)).To(Equal(expected.Sum(nil)))
|
||||
Expect(downloadPartsPath(fixture.path)).NotTo(BeAnExistingFile())
|
||||
Expect(downloadPartsPath(fixture.path)).NotTo(BeADirectory())
|
||||
}
|
||||
|
||||
var _ = Describe("automatic parallel downloads", func() {
|
||||
It("uses four requests when exactly 128 MiB remains and counts progress once", func() {
|
||||
const prefix = int64(4096)
|
||||
|
||||
fixture := newParallelDownloadFixture(parallelDownloadThreshold + prefix)
|
||||
fixture.writePrefix(prefix)
|
||||
progress := progressbar.NewOptions64(1, progressbar.OptionSetWriter(io.Discard))
|
||||
|
||||
err := fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, progress)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
fixture.expectContents(1)
|
||||
|
||||
requests := fixture.recordedRequests()
|
||||
Expect(requests).To(HaveLen(parallelDownloadCount))
|
||||
Expect(requests[0].rangeHeader).To(Equal("bytes=4096-"))
|
||||
for _, request := range requests[1:] {
|
||||
Expect(request.validator).To(Equal(`"fixture"`))
|
||||
Expect(request.rangeHeader).NotTo(HaveSuffix("-"))
|
||||
}
|
||||
|
||||
Expect(fixture.maximum.Load()).To(Equal(int64(parallelDownloadCount)))
|
||||
Expect(progress.State().CurrentNum).To(Equal(fixture.size))
|
||||
})
|
||||
|
||||
It("uses one request when one byte less than 128 MiB remains", func() {
|
||||
const prefix = int64(4097)
|
||||
|
||||
fixture := newParallelDownloadFixture(parallelDownloadThreshold + prefix - 1)
|
||||
fixture.writePrefix(prefix)
|
||||
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
|
||||
fixture.expectContents(1)
|
||||
Expect(fixture.recordedRequests()).To(HaveLen(1))
|
||||
})
|
||||
|
||||
It("uses one request for a small file", func() {
|
||||
fixture := newParallelDownloadFixture(64 << 10)
|
||||
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
|
||||
fixture.expectContents(1)
|
||||
Expect(fixture.recordedRequests()).To(HaveLen(1))
|
||||
})
|
||||
|
||||
It("keeps one stream when the server ignores the initial range", func() {
|
||||
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
|
||||
fixture.writePrefix(4096)
|
||||
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
request.Header.Del("Range")
|
||||
fixture.serve(writer, request, 1, `"fixture"`)
|
||||
}
|
||||
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
|
||||
fixture.expectContents(1)
|
||||
Expect(fixture.recordedRequests()).To(HaveLen(1))
|
||||
})
|
||||
|
||||
DescribeTable("falls back to one stream without appending invalid staged bytes", func(status int, contentRange string, body string) {
|
||||
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
|
||||
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
if strings.HasSuffix(request.Header.Get("Range"), "-") {
|
||||
fixture.serve(writer, request, 1, `"fixture"`)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
writer.Header().Set("Content-Range", contentRange)
|
||||
writer.WriteHeader(status)
|
||||
_, _ = io.WriteString(writer, body)
|
||||
}
|
||||
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
|
||||
fixture.expectContents(1)
|
||||
|
||||
requests := fixture.recordedRequests()
|
||||
Expect(len(requests)).To(BeNumerically(">", 1))
|
||||
Expect(requests[len(requests)-1].rangeHeader).To(HaveSuffix("-"))
|
||||
Expect(requests[len(requests)-1].validator).To(Equal(`"fixture"`))
|
||||
},
|
||||
Entry("ignored bounded ranges", http.StatusOK, "", "a whole response"),
|
||||
Entry("wrong offsets", http.StatusPartialContent, "bytes 1-3/134217728", "bad"),
|
||||
Entry("content-length mismatch", http.StatusPartialContent, "bytes 33554432-67108863/134217728", "bad"),
|
||||
Entry("server errors", http.StatusServiceUnavailable, "", "unavailable"),
|
||||
)
|
||||
|
||||
It("restarts the fallback when If-Range detects a changed representation", func() {
|
||||
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
|
||||
var requests atomic.Int64
|
||||
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
if requests.Add(1) == 1 {
|
||||
fixture.serve(writer, request, 1, `"old"`)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
fixture.serve(writer, request, 2, `"new"`)
|
||||
}
|
||||
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
|
||||
fixture.expectContents(2)
|
||||
})
|
||||
|
||||
DescribeTable("keeps a single stream without a strong validator", func(validator string) {
|
||||
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
|
||||
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
fixture.serve(writer, request, 1, validator)
|
||||
}
|
||||
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
|
||||
fixture.expectContents(1)
|
||||
Expect(fixture.recordedRequests()).To(HaveLen(1))
|
||||
},
|
||||
Entry("missing ETag", ""),
|
||||
Entry("weak ETag", `W/"fixture"`),
|
||||
)
|
||||
|
||||
It("falls back when a valid range response is truncated mid-body", func() {
|
||||
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
|
||||
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
value := request.Header.Get("Range")
|
||||
if strings.HasSuffix(value, "-") {
|
||||
fixture.serve(writer, request, 1, `"fixture"`)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
writer.Header().Set("Content-Range", strings.Replace(value, "=", " ", 1)+fmt.Sprintf("/%d", fixture.size))
|
||||
writer.Header().Set("ETag", `"fixture"`)
|
||||
writer.WriteHeader(http.StatusPartialContent)
|
||||
writer.(http.Flusher).Flush()
|
||||
_, _ = io.WriteString(writer, "truncated")
|
||||
}
|
||||
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
|
||||
fixture.expectContents(1)
|
||||
requests := fixture.recordedRequests()
|
||||
Expect(len(requests)).To(BeNumerically(">", 1))
|
||||
Expect(requests[len(requests)-1].rangeHeader).To(HaveSuffix("-"))
|
||||
})
|
||||
|
||||
It("resumes the first stream after a disconnect and resets staged progress", func() {
|
||||
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
|
||||
var first atomic.Bool
|
||||
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
if first.CompareAndSwap(false, true) {
|
||||
writer.Header().Set("ETag", `"fixture"`)
|
||||
writer.Header().Set("Content-Length", fmt.Sprint(fixture.size))
|
||||
writer.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", fixture.size-1, fixture.size))
|
||||
writer.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = io.Copy(writer, io.NewSectionReader(downloadFixtureData(1), 0, 4096))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
fixture.serve(writer, request, 1, `"fixture"`)
|
||||
}
|
||||
|
||||
progress := progressbar.NewOptions64(1, progressbar.OptionSetWriter(io.Discard))
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, progress)).To(Succeed())
|
||||
fixture.expectContents(1)
|
||||
requests := fixture.recordedRequests()
|
||||
Expect(len(requests)).To(BeNumerically(">", 1))
|
||||
Expect(requests[len(requests)-1].rangeHeader).To(Equal("bytes=4096-"))
|
||||
Expect(progress.State().CurrentNum).To(Equal(fixture.size))
|
||||
})
|
||||
|
||||
It("preserves a contiguous prefix on interruption and resumes with one request below the threshold", func() {
|
||||
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
|
||||
var interrupted atomic.Bool
|
||||
interrupted.Store(true)
|
||||
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
if interrupted.Load() && strings.HasSuffix(request.Header.Get("Range"), "-") {
|
||||
writer.Header().Set("ETag", `"fixture"`)
|
||||
writer.Header().Set("Content-Length", fmt.Sprint(fixture.size))
|
||||
writer.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", fixture.size-1, fixture.size))
|
||||
writer.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = io.Copy(writer, io.NewSectionReader(downloadFixtureData(1), 0, 4096))
|
||||
writer.(http.Flusher).Flush()
|
||||
<-request.Context().Done()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
fixture.serve(writer, request, 1, `"fixture"`)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
DeferCleanup(cancel)
|
||||
finished := make(chan error, 1)
|
||||
go func() {
|
||||
finished <- fixture.store.downloadFile(ctx, fixture.server.URL, fixture.path, nil)
|
||||
}()
|
||||
|
||||
Eventually(func() int64 {
|
||||
var staged int64
|
||||
for index := range parallelDownloadCount - 1 {
|
||||
info, err := os.Stat(filepath.Join(downloadPartsPath(fixture.path), fmt.Sprint(index)))
|
||||
if err == nil {
|
||||
staged += info.Size()
|
||||
}
|
||||
}
|
||||
|
||||
return staged
|
||||
}, 10*time.Second).Should(Equal(int64(parallelDownloadThreshold / 4 * 3)))
|
||||
Eventually(func() int64 {
|
||||
info, err := os.Stat(fixture.path)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
return info.Size()
|
||||
}).Should(Equal(int64(4096)))
|
||||
cancel()
|
||||
|
||||
var downloadErr error
|
||||
Eventually(finished).Should(Receive(&downloadErr))
|
||||
Expect(errors.Is(downloadErr, context.Canceled)).To(BeTrue())
|
||||
info, err := os.Stat(fixture.path)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(info.Size()).To(Equal(int64(4096)))
|
||||
Expect(downloadPartsPath(fixture.path)).NotTo(BeADirectory())
|
||||
|
||||
interrupted.Store(false)
|
||||
before := len(fixture.recordedRequests())
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
|
||||
fixture.expectContents(1)
|
||||
requests := fixture.recordedRequests()
|
||||
Expect(requests).To(HaveLen(before + 1))
|
||||
Expect(requests[before].rangeHeader).To(Equal("bytes=4096-"))
|
||||
})
|
||||
|
||||
It("discards orphaned parts after an unclean exit and resumes only the main file", func() {
|
||||
fixture := newParallelDownloadFixture(64 << 10)
|
||||
fixture.writePrefix(4096)
|
||||
directory := downloadPartsPath(fixture.path)
|
||||
Expect(os.Mkdir(directory, 0700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(directory, "0"), []byte("out-of-order bytes"), 0600)).To(Succeed())
|
||||
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
|
||||
fixture.expectContents(1)
|
||||
requests := fixture.recordedRequests()
|
||||
Expect(requests).To(HaveLen(1))
|
||||
Expect(requests[0].rangeHeader).To(Equal("bytes=4096-"))
|
||||
})
|
||||
|
||||
It("resumes safely after the downloading process is killed", func() {
|
||||
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
|
||||
var interrupted atomic.Bool
|
||||
interrupted.Store(true)
|
||||
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
if interrupted.Load() && strings.HasSuffix(request.Header.Get("Range"), "-") {
|
||||
writer.Header().Set("ETag", `"fixture"`)
|
||||
writer.Header().Set("Content-Length", fmt.Sprint(fixture.size))
|
||||
writer.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", fixture.size-1, fixture.size))
|
||||
writer.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = io.Copy(writer, io.NewSectionReader(downloadFixtureData(1), 0, 4096))
|
||||
writer.(http.Flusher).Flush()
|
||||
<-request.Context().Done()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
fixture.serve(writer, request, 1, `"fixture"`)
|
||||
}
|
||||
|
||||
executable, err := os.Executable()
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
child := exec.Command(executable, "-test.run=^TestAppStore$", "-ginkgo.focus=download subprocess helper")
|
||||
child.Env = append(os.Environ(), "IPATOOL_DOWNLOAD_TEST_URL="+fixture.server.URL, "IPATOOL_DOWNLOAD_TEST_PATH="+fixture.path)
|
||||
Expect(child.Start()).To(Succeed())
|
||||
DeferCleanup(func() {
|
||||
_ = child.Process.Kill()
|
||||
_ = child.Wait()
|
||||
})
|
||||
|
||||
Eventually(func() int64 {
|
||||
var size int64
|
||||
for index := range parallelDownloadCount - 1 {
|
||||
info, err := os.Stat(filepath.Join(downloadPartsPath(fixture.path), fmt.Sprint(index)))
|
||||
if err == nil {
|
||||
size += info.Size()
|
||||
}
|
||||
}
|
||||
|
||||
return size
|
||||
}, 15*time.Second).Should(Equal(int64(parallelDownloadThreshold / 4 * 3)))
|
||||
Eventually(func() int64 {
|
||||
info, err := os.Stat(fixture.path)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
return info.Size()
|
||||
}).Should(Equal(int64(4096)))
|
||||
Expect(child.Process.Kill()).To(Succeed())
|
||||
Expect(child.Wait()).To(HaveOccurred())
|
||||
Expect(downloadPartsPath(fixture.path)).To(BeADirectory())
|
||||
|
||||
interrupted.Store(false)
|
||||
before := len(fixture.recordedRequests())
|
||||
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
|
||||
fixture.expectContents(1)
|
||||
requests := fixture.recordedRequests()
|
||||
Expect(requests).To(HaveLen(before + 1))
|
||||
Expect(requests[before].rangeHeader).To(Equal("bytes=4096-"))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("download subprocess helper", func() {
|
||||
It("downloads the subprocess fixture", func() {
|
||||
url := os.Getenv("IPATOOL_DOWNLOAD_TEST_URL")
|
||||
if url == "" {
|
||||
Skip("only executed by the process-interruption test")
|
||||
}
|
||||
|
||||
store := &appstore{httpClient: newDownloadTestClient(), os: operatingsystem.New()}
|
||||
Expect(store.downloadFile(context.Background(), url, os.Getenv("IPATOOL_DOWNLOAD_TEST_PATH"), nil)).To(Succeed())
|
||||
})
|
||||
})
|
||||
@@ -107,9 +107,9 @@ func (t *appstore) sendDownloadProduct(ctx context.Context, acc Account, app App
|
||||
|
||||
externalVersionID, err = t.lookupLatestExternalVersionID(acc, app, platform)
|
||||
if errors.Is(err, errIOSCatalogAppNotFound) {
|
||||
// A delisted app can still be available to this account. Try once
|
||||
// without a version; Download validates the returned package's platform.
|
||||
res, err := t.sendUnpinnedRedownload(ctx, redownload, acc, app, guid)
|
||||
// A delisted app can still be available to this account. Neither
|
||||
// recovery endpoint needs a catalog version to select its entitled build.
|
||||
res, err := t.sendDelistedDownload(ctx, redownload, bag.EntDownloadEndpoint, acc, app, guid)
|
||||
|
||||
return res, platform, err
|
||||
}
|
||||
@@ -139,6 +139,40 @@ func (t *appstore) sendDownloadProduct(ctx context.Context, acc Account, app App
|
||||
return redownloadRes, platform, nil
|
||||
}
|
||||
|
||||
func (t *appstore) sendDelistedDownload(ctx context.Context, redownload downloadProductEndpoint, entEndpoint string, acc Account, app App, guid string) (http.Result[downloadResult], error) {
|
||||
res, err := t.sendUnpinnedRedownload(ctx, redownload, acc, app, guid)
|
||||
if err == nil && res.Data.FailureType != FailureTypeLicenseNotFound {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
||||
return res, errors.Join(err, ctxErr)
|
||||
}
|
||||
|
||||
if t.kbsyncGenerator == nil || entEndpoint == "" {
|
||||
return res, err
|
||||
}
|
||||
|
||||
endpoint, endpointErr := newDownloadEndpoint(entEndpoint, entDownloadPath)
|
||||
if endpointErr != nil {
|
||||
return res, errors.Join(err, endpointErr)
|
||||
}
|
||||
|
||||
// Bypass catalog discovery: it already confirmed that there is no offer.
|
||||
// Download still checks the returned package's platform before publishing it.
|
||||
entRes, entErr := t.sendEntDownload(ctx, endpoint, acc, app, guid, "")
|
||||
if entErr == nil || entRes.Data.FailureType == FailureTypePasswordTokenExpired ||
|
||||
entRes.Data.FailureType == FailureTypeLicenseNotFound {
|
||||
return entRes, nil
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseNotFound {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
return entRes, fmt.Errorf("app %d has no offer in the account's App Store catalog and the kbsync fallback failed: %w", app.ID, errors.Join(err, entErr))
|
||||
}
|
||||
|
||||
func (t *appstore) sendUnpinnedRedownload(ctx context.Context, endpoint downloadProductEndpoint, acc Account, app App, guid string) (http.Result[downloadResult], error) {
|
||||
requestContext, cancel := context.WithTimeout(ctx, http.DefaultAuthenticationTimeout)
|
||||
defer cancel()
|
||||
@@ -155,6 +189,8 @@ func (t *appstore) sendUnpinnedRedownload(ctx context.Context, endpoint download
|
||||
return res, fmt.Errorf("failed to send redownload request: %w", err)
|
||||
}
|
||||
|
||||
res.Data = normalizeDownloadFailure(res.Data)
|
||||
|
||||
if err := validateDownloadResponse(res, app, "", "redownload"); err != nil {
|
||||
return res, err
|
||||
}
|
||||
@@ -166,6 +202,42 @@ func (t *appstore) sendUnpinnedRedownload(ctx context.Context, endpoint download
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func normalizeDownloadFailure(data downloadResult) downloadResult {
|
||||
if len(data.Items) == 0 && data.FailureType == "" && data.Metrics["messageCode"] != nil {
|
||||
data.FailureType = strings.TrimSpace(fmt.Sprint(data.Metrics["messageCode"]))
|
||||
}
|
||||
|
||||
if data.FailureType == FailureTypeSignInRequired || data.FailureType == FailureTypeDeviceVerificationFailed {
|
||||
data.FailureType = FailureTypePasswordTokenExpired
|
||||
}
|
||||
|
||||
if len(data.Items) > 0 {
|
||||
return data
|
||||
}
|
||||
|
||||
message := strings.Join(strings.Fields(data.CustomerMessage), " ")
|
||||
if strings.EqualFold(message, "sign in to the itunes store") || strings.EqualFold(message, "sign-in required") {
|
||||
data.FailureType = FailureTypePasswordTokenExpired
|
||||
}
|
||||
|
||||
if data.FailureType == FailureTypePasswordTokenExpired {
|
||||
return data
|
||||
}
|
||||
|
||||
const unavailable = "Redownload Unavailable with This Apple Account"
|
||||
|
||||
dialogMessage, _ := data.Dialog["message"].(string)
|
||||
dialogExplanation, _ := data.Dialog["explanation"].(string)
|
||||
|
||||
if message == unavailable ||
|
||||
(strings.Join(strings.Fields(dialogMessage), " ") == unavailable &&
|
||||
strings.Join(strings.Fields(dialogExplanation), " ") == "This redownload is not available for this Apple Account either because it was bought by a different user or the item was refunded or cancelled.") {
|
||||
data.FailureType = FailureTypeLicenseNotFound
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
func isEmptyRedownloadError(err error) bool {
|
||||
var unexpected *http.UnexpectedResponseError
|
||||
|
||||
|
||||
@@ -42,9 +42,10 @@ var _ = Describe("AppStore (Download Product)", func() {
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
store = &appstore{
|
||||
bagClient: mockBagClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
bagClient: mockBagClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
storefrontCountryCodes: testStorefrontCountryCodes(),
|
||||
}
|
||||
account = Account{
|
||||
DirectoryServicesID: "test-dsid",
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/store"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
@@ -63,16 +64,17 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
mockOS = operatingsystem.NewMockOperatingSystem(ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
bagClient: mockBagClient,
|
||||
loginClient: mockLoginClient,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
storefrontClient: mockStorefrontClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: mockOS,
|
||||
keychain: mockKeychain,
|
||||
bagClient: mockBagClient,
|
||||
loginClient: mockLoginClient,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
storefrontClient: mockStorefrontClient,
|
||||
storefrontCountryCodes: testStorefrontCountryCodes(),
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: mockOS,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -110,6 +112,19 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
})
|
||||
})
|
||||
|
||||
DescribeTable("suggests logging in when Store AMD state is not provisioned",
|
||||
func(state []byte) {
|
||||
as.(*appstore).authBackend = store.New(nil, nil)
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
mockKeychain.EXPECT().Get(anisetteKeychainKey).Return(state, nil)
|
||||
|
||||
_, err := as.Download(DownloadInput{App: App{ID: 1641486558}})
|
||||
Expect(err).To(MatchError("failed to send http request: generate Store AMD proof: store AMD state is not provisioned; run 'ipatool auth login' to authenticate"))
|
||||
},
|
||||
Entry("missing state", nil),
|
||||
Entry("persisted identity without provisioning", []byte(`{"Identifier":"AAECAwQFBgcICQoLDA0ODw=="}`)),
|
||||
)
|
||||
|
||||
When("request uses a custom pod", func() {
|
||||
const (
|
||||
testPod = "42"
|
||||
@@ -811,12 +826,13 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
}, nil)
|
||||
|
||||
store := &appstore{
|
||||
downloadClient: mockDownloadClient,
|
||||
bagClient: mockBagClient,
|
||||
platformClient: mockPlatformClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: operatingsystem.New(),
|
||||
downloadClient: mockDownloadClient,
|
||||
bagClient: mockBagClient,
|
||||
platformClient: mockPlatformClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: operatingsystem.New(),
|
||||
storefrontCountryCodes: testStorefrontCountryCodes(),
|
||||
}
|
||||
out, err := store.Download(DownloadInput{
|
||||
Account: Account{StoreFront: "143441", Email: "test@example.com"},
|
||||
@@ -1082,7 +1098,7 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
Stat(testFile.Name()).
|
||||
Return(info, nil)
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(request.WithContext(context.Background())).
|
||||
Do(gomock.AssignableToTypeOf(request)).
|
||||
DoAndReturn(func(request *gohttp.Request) (*gohttp.Response, error) {
|
||||
Expect(request.Header.Get("range")).To(Equal("bytes=8-"))
|
||||
|
||||
@@ -1292,12 +1308,13 @@ var _ = Describe("Downloading delisted tvOS apps", func() {
|
||||
mockMachine := machine.NewMockMachine(ctrl)
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
store = &appstore{
|
||||
platformClient: platformClient,
|
||||
downloadClient: downloadClient,
|
||||
bagClient: bagClient,
|
||||
httpClient: httpClient,
|
||||
machine: mockMachine,
|
||||
os: operatingsystem.New(),
|
||||
platformClient: platformClient,
|
||||
downloadClient: downloadClient,
|
||||
bagClient: bagClient,
|
||||
httpClient: httpClient,
|
||||
machine: mockMachine,
|
||||
os: operatingsystem.New(),
|
||||
storefrontCountryCodes: testStorefrontCountryCodes(),
|
||||
}
|
||||
input = DownloadInput{
|
||||
Account: Account{StoreFront: "143441"},
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -31,7 +31,7 @@ var _ = Describe("iOS catalog version fallback", func() {
|
||||
|
||||
BeforeEach(func() {
|
||||
client = http.NewMockClient[platformVersionLookupResult](gomock.NewController(GinkgoT()))
|
||||
store = &appstore{platformClient: client}
|
||||
store = &appstore{platformClient: client, storefrontCountryCodes: testStorefrontCountryCodes()}
|
||||
})
|
||||
|
||||
DescribeTable("resolves Arcade versions after exhausting the MDM catalogs", func(platform Platform, noOffers bool, quotedVersion bool) {
|
||||
@@ -115,7 +115,7 @@ var _ = Describe("ListVersions for apps missing from the MDM catalogs", func() {
|
||||
downloads := http.NewMockClient[downloadResult](ctrl)
|
||||
bags := http.NewMockClient[bagResult](ctrl)
|
||||
device := machine.NewMockMachine(ctrl)
|
||||
store := &appstore{platformClient: catalog, downloadClient: downloads, bagClient: bags, machine: device}
|
||||
store := &appstore{platformClient: catalog, downloadClient: downloads, bagClient: bags, machine: device, storefrontCountryCodes: testStorefrontCountryCodes()}
|
||||
device.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
result := downloadResult{FailureType: FailureTypeLicenseNotFound}
|
||||
if licensed {
|
||||
|
||||
@@ -133,20 +133,26 @@ func (t *appstore) sendEntDownloadRequest(ctx context.Context, endpoint download
|
||||
}
|
||||
}
|
||||
|
||||
request.Payload = &http.XMLPayload{Content: map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"kbsync": blob,
|
||||
"salableAdamId": strconv.FormatInt(app.ID, 10),
|
||||
"serialNumber": base64.StdEncoding.EncodeToString(serial),
|
||||
"externalVersionId": versionID,
|
||||
}}
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"kbsync": blob,
|
||||
"salableAdamId": strconv.FormatInt(app.ID, 10),
|
||||
"serialNumber": base64.StdEncoding.EncodeToString(serial),
|
||||
}
|
||||
if versionID != "" {
|
||||
payload["externalVersionId"] = versionID
|
||||
}
|
||||
|
||||
request.Payload = &http.XMLPayload{Content: payload}
|
||||
|
||||
res, err := t.downloadClient.Send(request)
|
||||
if err != nil {
|
||||
return res, fmt.Errorf("send ent/download request: %w", err)
|
||||
}
|
||||
|
||||
res.Data = normalizeDownloadFailure(res.Data)
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
return res, NewErrorWithMetadata(fmt.Errorf("received ent/download error: %s", res.Data.FailureType), res)
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ var _ = Describe("AppStore (preferred kbsync download)", func() {
|
||||
generated = 0
|
||||
store = &appstore{
|
||||
downloadClient: downloads, bagClient: bags, platformClient: platforms,
|
||||
storefrontCountryCodes: testStorefrontCountryCodes(),
|
||||
kbsyncGenerator: func(ctx context.Context, hardwareID []byte, dsid uint64) ([]byte, error) {
|
||||
Expect(ctx.Err()).NotTo(HaveOccurred())
|
||||
deadline, ok := ctx.Deadline()
|
||||
|
||||
@@ -28,10 +28,11 @@ var _ = Describe("AppStore (ListVersions)", func() {
|
||||
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
bagClient: mockBagClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
machine: mockMachine,
|
||||
bagClient: mockBagClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
machine: mockMachine,
|
||||
storefrontCountryCodes: testStorefrontCountryCodes(),
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -66,6 +66,12 @@ func (t *appstore) legacyLogin(input LoginInput) (LoginOutput, error) {
|
||||
return LoginOutput{}, err
|
||||
}
|
||||
|
||||
if countryCode := phoneNumberStorefrontCountryCode(input.Email); countryCode != "" {
|
||||
if _, err = t.discoverStorefrontID(countryCode); err != nil {
|
||||
return LoginOutput{}, fmt.Errorf("failed to discover storefronts: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return LoginOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
@@ -153,10 +159,24 @@ type loginAccountResult struct {
|
||||
Address loginAddressResult `plist:"address,omitempty"`
|
||||
}
|
||||
|
||||
type loginDialogActionResult struct {
|
||||
Kind string `plist:"kind,omitempty"`
|
||||
URL string `plist:"url,omitempty"`
|
||||
}
|
||||
|
||||
type loginDialogResult struct {
|
||||
Message string `plist:"message,omitempty"`
|
||||
Explanation string `plist:"explanation,omitempty"`
|
||||
OKButtonString string `plist:"okButtonString,omitempty"`
|
||||
OKButtonAction loginDialogActionResult `plist:"okButtonAction,omitempty"`
|
||||
CancelButtonString string `plist:"cancelButtonString,omitempty"`
|
||||
}
|
||||
|
||||
type loginResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
Account loginAccountResult `plist:"accountInfo,omitempty"`
|
||||
Dialog loginDialogResult `plist:"dialog,omitempty"`
|
||||
DirectoryServicesID string `plist:"dsPersonId,omitempty"`
|
||||
PasswordToken string `plist:"passwordToken,omitempty"`
|
||||
}
|
||||
@@ -214,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)
|
||||
@@ -239,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
|
||||
@@ -377,6 +393,8 @@ func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int
|
||||
|
||||
if action := authenticationMachineAction(res.Headers); action != nil {
|
||||
err = action
|
||||
} else if dialogErr := authenticationDialogError(res.Data); dialogErr != nil {
|
||||
err = NewErrorWithMetadata(dialogErr, res)
|
||||
} else if res.StatusCode >= gohttp.StatusMultipleChoices && res.StatusCode < gohttp.StatusBadRequest {
|
||||
if redirect, err = res.GetHeader("location"); err != nil {
|
||||
err = fmt.Errorf("failed to retrieve redirect location: %w", err)
|
||||
@@ -416,6 +434,70 @@ func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int
|
||||
return retry, redirect, err
|
||||
}
|
||||
|
||||
func authenticationDialogError(result loginResult) error {
|
||||
dialog := result.Dialog
|
||||
if strings.TrimSpace(dialog.Message) == "" && strings.TrimSpace(dialog.Explanation) == "" &&
|
||||
strings.TrimSpace(dialog.OKButtonString) == "" && strings.TrimSpace(dialog.CancelButtonString) == "" &&
|
||||
strings.TrimSpace(dialog.OKButtonAction.Kind) == "" && strings.TrimSpace(dialog.OKButtonAction.URL) == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
message := strings.TrimSpace(dialog.Message)
|
||||
explanation := strings.TrimSpace(dialog.Explanation)
|
||||
|
||||
if message == "" {
|
||||
message = strings.TrimSpace(result.CustomerMessage)
|
||||
}
|
||||
|
||||
actionURL := trustedAuthenticationDialogURL(dialog.OKButtonAction)
|
||||
if message == "" && explanation == "" && actionURL == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
parts := make([]string, 0, 2)
|
||||
if message != "" {
|
||||
parts = append(parts, message)
|
||||
}
|
||||
|
||||
if explanation != "" && explanation != message {
|
||||
parts = append(parts, explanation)
|
||||
}
|
||||
|
||||
detail := strings.Join(parts, ": ")
|
||||
if detail == "" {
|
||||
detail = "Apple requires action before sign-in can continue"
|
||||
}
|
||||
|
||||
if actionURL != "" {
|
||||
label := strings.TrimSpace(dialog.OKButtonString)
|
||||
if label == "" {
|
||||
label = "Continue"
|
||||
}
|
||||
|
||||
detail += fmt.Sprintf(" (%s: %s)", label, actionURL)
|
||||
}
|
||||
|
||||
return errors.New(detail)
|
||||
}
|
||||
|
||||
func trustedAuthenticationDialogURL(action loginDialogActionResult) string {
|
||||
if !strings.EqualFold(strings.TrimSpace(action.Kind), "OpenURL") {
|
||||
return ""
|
||||
}
|
||||
|
||||
value, err := url.Parse(strings.TrimSpace(action.URL))
|
||||
if err != nil || value.Scheme != "https" || value.User != nil || value.Fragment != "" || value.Port() != "" && value.Port() != "443" {
|
||||
return ""
|
||||
}
|
||||
|
||||
host := strings.ToLower(value.Hostname())
|
||||
if host != "apple.com" && !strings.HasSuffix(host, ".apple.com") {
|
||||
return ""
|
||||
}
|
||||
|
||||
return value.String()
|
||||
}
|
||||
|
||||
func authenticationMachineAction(headers map[string]string) *authenticationMachineActionError {
|
||||
var action, data string
|
||||
|
||||
@@ -529,7 +611,7 @@ func (t *appstore) loginRequest(email, password, authCode, guid, endpoint string
|
||||
},
|
||||
},
|
||||
}
|
||||
if storefront := phoneNumberStorefront(email); storefront != "" {
|
||||
if storefront := t.storefrontID(phoneNumberStorefrontCountryCode(email)); storefront != "" {
|
||||
request.Headers["X-Apple-Store-Front"] = storefront
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,10 @@ package appstore
|
||||
|
||||
import "strings"
|
||||
|
||||
// phoneNumberStorefront supplies a routing hint for phone-based Apple Accounts
|
||||
// in mainland China and India. It does not change the Apple ID sent to Apple.
|
||||
func phoneNumberStorefront(appleID string) string {
|
||||
// phoneNumberStorefrontCountryCode identifies the storefront routing hint for
|
||||
// phone-based Apple Accounts in mainland China and India. It does not change
|
||||
// the Apple ID sent to Apple.
|
||||
func phoneNumberStorefrontCountryCode(appleID string) string {
|
||||
number := strings.ReplaceAll(strings.TrimSpace(appleID), " ", "")
|
||||
number = strings.ReplaceAll(number, "-", "")
|
||||
|
||||
@@ -30,7 +31,7 @@ func phoneNumberStorefront(appleID string) string {
|
||||
// match a supported country code and cannot fall back to a local format.
|
||||
switch {
|
||||
case len(number) == 13 && strings.HasPrefix(number, "861"):
|
||||
return storeFronts["CN"]
|
||||
return "CN"
|
||||
case len(number) == 12 && strings.HasPrefix(number, "91"):
|
||||
number = number[2:]
|
||||
case international:
|
||||
@@ -38,7 +39,7 @@ func phoneNumberStorefront(appleID string) string {
|
||||
}
|
||||
|
||||
if len(number) == 11 && number[0] == '1' {
|
||||
return storeFronts["CN"]
|
||||
return "CN"
|
||||
}
|
||||
|
||||
// India also permits a trunk prefix when writing a national number.
|
||||
@@ -47,7 +48,7 @@ func phoneNumberStorefront(appleID string) string {
|
||||
}
|
||||
|
||||
if len(number) == 10 && number[0] >= '6' && number[0] <= '9' {
|
||||
return storeFronts["IN"]
|
||||
return "IN"
|
||||
}
|
||||
|
||||
return ""
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
var _ = Describe("Phone account login routing", func() {
|
||||
DescribeTable("sets a storefront hint without rewriting the Apple ID", func(appleID, storefront string) {
|
||||
request := (&appstore{}).loginRequest(appleID, "password", "", "guid", testAuthEndpoint, 1, &stubActionSigner{})
|
||||
request := (&appstore{storefrontCountryCodes: testStorefrontCountryCodes()}).loginRequest(appleID, "password", "", "guid", testAuthEndpoint, 1, &stubActionSigner{})
|
||||
|
||||
Expect(request.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appleId", appleID))
|
||||
if storefront == "" {
|
||||
|
||||
@@ -42,11 +42,12 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
signer = &stubActionSigner{}
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockClient,
|
||||
bagClient: mockBagClient,
|
||||
machine: mockMachine,
|
||||
authRetrySleep: func(time.Duration) {},
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockClient,
|
||||
bagClient: mockBagClient,
|
||||
machine: mockMachine,
|
||||
authRetrySleep: func(time.Duration) {},
|
||||
storefrontCountryCodes: testStorefrontCountryCodes(),
|
||||
actionSignerFactory: func(config SAPConfig, machineID []byte) (ActionSigner, error) {
|
||||
Expect(config).To(Equal(validSAPConfig()))
|
||||
Expect(machineID).To(Equal([]byte{0, 0, 0, 0, 0, 0}))
|
||||
@@ -136,6 +137,20 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
)
|
||||
})
|
||||
|
||||
DescribeTable("does not expose untrusted dialog actions", func(action loginDialogActionResult) {
|
||||
result := loginResult{Dialog: loginDialogResult{Message: "Account action required", OKButtonString: "Continue", OKButtonAction: action}}
|
||||
err := authenticationDialogError(result)
|
||||
|
||||
Expect(err).To(MatchError("Account action required"))
|
||||
},
|
||||
Entry("non-Apple URL", loginDialogActionResult{Kind: "OpenURL", URL: "https://example.com/reset"}),
|
||||
Entry("insecure URL", loginDialogActionResult{Kind: "OpenURL", URL: "http://iforgot.apple.com/reset"}),
|
||||
Entry("embedded credentials", loginDialogActionResult{Kind: "OpenURL", URL: "https://user@iforgot.apple.com/reset"}),
|
||||
Entry("nonstandard port", loginDialogActionResult{Kind: "OpenURL", URL: "https://iforgot.apple.com:8443/reset"}),
|
||||
Entry("fragment", loginDialogActionResult{Kind: "OpenURL", URL: "https://iforgot.apple.com/reset#token"}),
|
||||
Entry("non-navigation action", loginDialogActionResult{Kind: "Buy", URL: "https://iforgot.apple.com/reset"}),
|
||||
)
|
||||
|
||||
When("fails to read Machine's MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
@@ -298,6 +313,36 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns an account recovery dialog", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{
|
||||
StatusCode: 200,
|
||||
Data: loginResult{
|
||||
CustomerMessage: CustomerMessageAccountDisabled,
|
||||
Dialog: loginDialogResult{
|
||||
Message: "This Apple Account has been locked for security reasons.",
|
||||
Explanation: "Reset your password to continue.",
|
||||
OKButtonString: "Reset",
|
||||
OKButtonAction: loginDialogActionResult{
|
||||
Kind: "OpenURL",
|
||||
URL: "https://iforgot.apple.com/cgi-bin/iforgot.cgi",
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("surfaces the dialog and trusted recovery URL", func() {
|
||||
_, err := as.Login(LoginInput{Password: testPassword})
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("This Apple Account has been locked for security reasons.")))
|
||||
Expect(err).To(MatchError(ContainSubstring("Reset your password to continue.")))
|
||||
Expect(err).To(MatchError(ContainSubstring("Reset: https://iforgot.apple.com/cgi-bin/iforgot.cgi")))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API requires 2FA code", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
|
||||
@@ -25,7 +25,7 @@ type LookupOutput struct {
|
||||
}
|
||||
|
||||
func (t *appstore) Lookup(input LookupInput) (LookupOutput, error) {
|
||||
countryCode, err := countryCodeFromStoreFront(input.Account.StoreFront)
|
||||
countryCode, err := t.countryCodeFromStoreFront(input.Account.StoreFront)
|
||||
if err != nil {
|
||||
return LookupOutput{}, fmt.Errorf("failed to resolve the country code: %w", err)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,8 @@ var _ = Describe("AppStore (Lookup)", func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockClient = http.NewMockClient[searchResult](ctrl)
|
||||
as = &appstore{
|
||||
searchClient: mockClient,
|
||||
searchClient: mockClient,
|
||||
storefrontCountryCodes: testStorefrontCountryCodes(),
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
)
|
||||
|
||||
func (t *appstore) lookupLatestMacOSExternalVersionID(acc Account, app App) (string, error) {
|
||||
countryCode, err := countryCodeFromStoreFront(acc.StoreFront)
|
||||
countryCode, err := t.countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve the country code: %w", err)
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ var _ = Describe("Mac purchase version selection", func() {
|
||||
defer ctrl.Finish()
|
||||
downloads := http.NewMockClient[downloadResult](ctrl)
|
||||
pages := http.NewMockClient[[]byte](ctrl)
|
||||
store := &appstore{downloadClient: downloads, storefrontClient: pages}
|
||||
store := &appstore{downloadClient: downloads, storefrontClient: pages, storefrontCountryCodes: testStorefrontCountryCodes()}
|
||||
expected := http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{Items: []downloadItemResult{{URL: "https://example.test/mac.pkg"}}}}
|
||||
gomock.InOrder(
|
||||
pages.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
@@ -74,7 +74,7 @@ var _ = Describe("Mac purchase version selection", func() {
|
||||
downloads := http.NewMockClient[downloadResult](ctrl)
|
||||
pages := http.NewMockClient[[]byte](ctrl)
|
||||
bags := http.NewMockClient[bagResult](ctrl)
|
||||
store := &appstore{downloadClient: downloads, storefrontClient: pages, bagClient: bags}
|
||||
store := &appstore{downloadClient: downloads, storefrontClient: pages, bagClient: bags, storefrontCountryCodes: testStorefrontCountryCodes()}
|
||||
bag := validBagResult()
|
||||
bag.URLBag.RedownloadEndpoint = testRedownloadEndpoint
|
||||
expected := http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{Items: []downloadItemResult{{URL: "https://example.test/mac.pkg"}}}}
|
||||
@@ -102,7 +102,7 @@ var _ = Describe("Mac purchase version selection", func() {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
defer ctrl.Finish()
|
||||
pages := http.NewMockClient[[]byte](ctrl)
|
||||
store := &appstore{storefrontClient: pages, downloadClient: http.NewMockClient[downloadResult](ctrl)}
|
||||
store := &appstore{storefrontClient: pages, downloadClient: http.NewMockClient[downloadResult](ctrl), storefrontCountryCodes: testStorefrontCountryCodes()}
|
||||
pages.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: status, Data: body}, requestErr)
|
||||
_, _, err := store.sendDownloadProduct(context.Background(), Account{StoreFront: "143443-2,34"}, app, "001122334455", "", PlatformMacOS)
|
||||
Expect(err).To(HaveOccurred())
|
||||
|
||||
@@ -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"))
|
||||
})
|
||||
})
|
||||
@@ -67,7 +67,7 @@ func (t *appstore) lookupLatestExternalVersionID(acc Account, app App, platform
|
||||
return "", errors.New("app ID is required for platform version lookup")
|
||||
}
|
||||
|
||||
countryCode, err := countryCodeFromStoreFront(acc.StoreFront)
|
||||
countryCode, err := t.countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve the country code: %w", err)
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ var _ = Describe("Platform version catalog fallback", func() {
|
||||
|
||||
BeforeEach(func() {
|
||||
client = http.NewMockClient[platformVersionLookupResult](gomock.NewController(GinkgoT()))
|
||||
store = &appstore{platformClient: client}
|
||||
store = &appstore{platformClient: client, storefrontCountryCodes: testStorefrontCountryCodes()}
|
||||
})
|
||||
|
||||
expectLookup := func(catalog string, status int, data platformVersionLookupResult, sendErr error) *gomock.Call {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -44,6 +44,7 @@ var _ = Describe("Redownloading delisted iOS apps", func() {
|
||||
store = &appstore{
|
||||
platformClient: catalogs, downloadClient: downloads, bagClient: bags,
|
||||
httpClient: assets, machine: device, os: operatingsystem.New(),
|
||||
storefrontCountryCodes: testStorefrontCountryCodes(),
|
||||
}
|
||||
input = DownloadInput{
|
||||
Context: context.Background(),
|
||||
|
||||
@@ -26,7 +26,7 @@ type SearchOutput struct {
|
||||
}
|
||||
|
||||
func (t *appstore) Search(input SearchInput) (SearchOutput, error) {
|
||||
countryCode, err := countryCodeFromStoreFront(input.Account.StoreFront)
|
||||
countryCode, err := t.countryCodeFromStoreFront(input.Account.StoreFront)
|
||||
if err != nil {
|
||||
return SearchOutput{}, fmt.Errorf("country code is invalid: %w", err)
|
||||
}
|
||||
|
||||
@@ -24,8 +24,9 @@ var _ = Describe("AppStore (Search)", func() {
|
||||
mockClient = http.NewMockClient[searchResult](ctrl)
|
||||
mockStorefrontClient = http.NewMockClient[[]byte](ctrl)
|
||||
as = &appstore{
|
||||
searchClient: mockClient,
|
||||
storefrontClient: mockStorefrontClient,
|
||||
searchClient: mockClient,
|
||||
storefrontClient: mockStorefrontClient,
|
||||
storefrontCountryCodes: testStorefrontCountryCodes(),
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -8,6 +8,25 @@ import (
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func testStorefrontCountryCodes() map[string]string {
|
||||
return map[string]string{
|
||||
"143441": "US",
|
||||
"143443": "DE",
|
||||
"143444": "GB",
|
||||
"143465": "CN",
|
||||
"143467": "IN",
|
||||
"143469": "RU",
|
||||
}
|
||||
}
|
||||
|
||||
func availableStorefrontsFixture() []byte {
|
||||
return []byte(`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<plist version="1.0"><dict><key>storefronts</key><array>
|
||||
<dict><key>country-code</key><string>US</string><key>id</key><integer>143441</integer></dict>
|
||||
<dict><key>country-code</key><string>DE</string><key>id</key><integer>143443</integer></dict>
|
||||
</array></dict></plist>`)
|
||||
}
|
||||
|
||||
func storefrontSearchItemFixture(kind, adamID, platform, salableAdamID, externalVersionID string) string {
|
||||
return fmt.Sprintf(`{
|
||||
"$kind":%q,
|
||||
@@ -38,7 +57,7 @@ func storefrontPageFixture(items ...string) []byte {
|
||||
|
||||
var _ = Describe("App Store storefront data", func() {
|
||||
DescribeTable("resolves storefront response suffixes", func(storefront, country string) {
|
||||
Expect(countryCodeFromStoreFront(storefront)).To(Equal(country))
|
||||
Expect(countryCodeFromStoreFront(storefront, testStorefrontCountryCodes())).To(Equal(country))
|
||||
},
|
||||
Entry("comma suffix", "143441,34", "US"),
|
||||
Entry("dash and comma suffixes", "143441-1,34", "US"),
|
||||
|
||||
@@ -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"),
|
||||
)
|
||||
})
|
||||
@@ -37,7 +37,7 @@ var _ = Describe("AppStore (Update Product)", func() {
|
||||
mockBagClient = http.NewMockClient[bagResult](ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
store = &appstore{bagClient: mockBagClient, downloadClient: mockDownloadClient, platformClient: mockPlatformClient}
|
||||
store = &appstore{bagClient: mockBagClient, downloadClient: mockDownloadClient, platformClient: mockPlatformClient, storefrontCountryCodes: testStorefrontCountryCodes()}
|
||||
account = Account{DirectoryServicesID: "test-dsid", Pod: "42", StoreFront: "143441-1,34"}
|
||||
app = App{ID: 987654321, BundleID: "com.example.app"}
|
||||
bag = bagResult{}
|
||||
|
||||
+233
-142
@@ -1,156 +1,247 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
func countryCodeFromStoreFront(storeFront string) (string, error) {
|
||||
identifier, _, _ := strings.Cut(strings.TrimSpace(storeFront), ",")
|
||||
identifier, _, _ = strings.Cut(identifier, "-")
|
||||
type availableStorefrontsResult struct {
|
||||
Storefronts []availableStorefront `plist:"storefronts"`
|
||||
}
|
||||
|
||||
for key, val := range storeFronts {
|
||||
if identifier == val {
|
||||
return key, nil
|
||||
type availableStorefront struct {
|
||||
CountryCode string `plist:"country-code"`
|
||||
ID int64 `plist:"id"`
|
||||
}
|
||||
|
||||
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 !validStorefrontIdentifier(storefrontIdentifier(storeFront)) {
|
||||
return "", storefrontMappingError(storeFront)
|
||||
}
|
||||
|
||||
mapping, err := t.discoverStorefront(storeFront, "")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return mapping.country, nil
|
||||
}
|
||||
|
||||
func (t *appstore) storefrontID(countryCode string) string {
|
||||
t.storefrontsMu.Lock()
|
||||
defer t.storefrontsMu.Unlock()
|
||||
|
||||
return findStorefrontMapping(t.storefrontCountryCodes, "", countryCode).id
|
||||
}
|
||||
|
||||
func (t *appstore) discoverStorefrontID(countryCode string) (string, error) {
|
||||
countryCode = strings.ToUpper(strings.TrimSpace(countryCode))
|
||||
if !validStorefrontCountry(countryCode) {
|
||||
return "", fmt.Errorf("invalid storefront country code (%s)", countryCode)
|
||||
}
|
||||
|
||||
mapping, err := t.discoverStorefront("", countryCode)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return mapping.id, nil
|
||||
}
|
||||
|
||||
// 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()
|
||||
|
||||
identifier := storefrontIdentifier(storeFront)
|
||||
if mapping := findStorefrontMapping(t.storefrontCountryCodes, identifier, country); mapping.id != "" {
|
||||
return mapping, nil
|
||||
}
|
||||
|
||||
if t.storefrontBagClient == nil {
|
||||
return storefrontMapping{}, errors.New("storefront bag client is not configured")
|
||||
}
|
||||
|
||||
request := t.bagRequest("")
|
||||
if identifier != "" {
|
||||
request.Headers["X-Apple-Store-Front"] = strings.TrimSpace(storeFront)
|
||||
} else {
|
||||
request.URL += "&cc=" + url.QueryEscape(country)
|
||||
}
|
||||
|
||||
response, err := t.storefrontBagClient.Send(request)
|
||||
if err != nil {
|
||||
return storefrontMapping{}, fmt.Errorf("storefront bag request failed: %w", err)
|
||||
}
|
||||
|
||||
if response.StatusCode != gohttp.StatusOK {
|
||||
return storefrontMapping{}, NewErrorWithMetadata(errors.New("storefront bag request failed"), response)
|
||||
}
|
||||
|
||||
bag := response.Data
|
||||
id := fmt.Sprint(bag.StorefrontID)
|
||||
code := strings.ToUpper(strings.TrimSpace(bag.CountryCode))
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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 err := t.discoverAvailableStorefronts(endpoint); err != nil {
|
||||
return storefrontMapping{}, err
|
||||
}
|
||||
|
||||
if mapping := findStorefrontMapping(t.storefrontCountryCodes, identifier, country); mapping.id != "" {
|
||||
return mapping, nil
|
||||
}
|
||||
|
||||
if identifier != "" {
|
||||
return storefrontMapping{}, storefrontMappingError(storeFront)
|
||||
}
|
||||
|
||||
return storefrontMapping{}, fmt.Errorf("store front mapping for country code (%s) was not found", country)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
if t.storefrontClient == nil {
|
||||
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: 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)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return NewErrorWithMetadata(errors.New("available storefronts request failed"), res)
|
||||
}
|
||||
|
||||
var result availableStorefrontsResult
|
||||
if _, err = plist.Unmarshal(res.Data, &result); err != nil {
|
||||
return fmt.Errorf("failed to decode available storefronts: %w", err)
|
||||
}
|
||||
|
||||
countryCodes := make(map[string]string, len(result.Storefronts))
|
||||
|
||||
for _, storefront := range result.Storefronts {
|
||||
code := strings.ToUpper(strings.TrimSpace(storefront.CountryCode))
|
||||
if storefront.ID > 0 && validStorefrontCountry(code) {
|
||||
countryCodes[strconv.FormatInt(storefront.ID, 10)] = code
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("country code mapping for store front (%s) was not found", storeFront)
|
||||
if len(countryCodes) == 0 {
|
||||
return errors.New("available storefronts response contains no storefronts")
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
var storeFronts = map[string]string{
|
||||
"AE": "143481",
|
||||
"AG": "143540",
|
||||
"AI": "143538",
|
||||
"AL": "143575",
|
||||
"AM": "143524",
|
||||
"AO": "143564",
|
||||
"AR": "143505",
|
||||
"AT": "143445",
|
||||
"AU": "143460",
|
||||
"AZ": "143568",
|
||||
"BB": "143541",
|
||||
"BD": "143490",
|
||||
"BE": "143446",
|
||||
"BG": "143526",
|
||||
"BH": "143559",
|
||||
"BM": "143542",
|
||||
"BN": "143560",
|
||||
"BO": "143556",
|
||||
"BR": "143503",
|
||||
"BS": "143539",
|
||||
"BW": "143525",
|
||||
"BY": "143565",
|
||||
"BZ": "143555",
|
||||
"CA": "143455",
|
||||
"CH": "143459",
|
||||
"CI": "143527",
|
||||
"CL": "143483",
|
||||
"CN": "143465",
|
||||
"CO": "143501",
|
||||
"CR": "143495",
|
||||
"CY": "143557",
|
||||
"CZ": "143489",
|
||||
"DE": "143443",
|
||||
"DK": "143458",
|
||||
"DM": "143545",
|
||||
"DO": "143508",
|
||||
"DZ": "143563",
|
||||
"EC": "143509",
|
||||
"EE": "143518",
|
||||
"EG": "143516",
|
||||
"ES": "143454",
|
||||
"FI": "143447",
|
||||
"FR": "143442",
|
||||
"GB": "143444",
|
||||
"GD": "143546",
|
||||
"GE": "143615",
|
||||
"GH": "143573",
|
||||
"GR": "143448",
|
||||
"GT": "143504",
|
||||
"GY": "143553",
|
||||
"HK": "143463",
|
||||
"HN": "143510",
|
||||
"HR": "143494",
|
||||
"HU": "143482",
|
||||
"ID": "143476",
|
||||
"IE": "143449",
|
||||
"IL": "143491",
|
||||
"IN": "143467",
|
||||
"IS": "143558",
|
||||
"IT": "143450",
|
||||
"IQ": "143617",
|
||||
"JM": "143511",
|
||||
"JO": "143528",
|
||||
"JP": "143462",
|
||||
"KE": "143529",
|
||||
"KN": "143548",
|
||||
"KR": "143466",
|
||||
"KW": "143493",
|
||||
"KY": "143544",
|
||||
"KZ": "143517",
|
||||
"LB": "143497",
|
||||
"LC": "143549",
|
||||
"LI": "143522",
|
||||
"LK": "143486",
|
||||
"LT": "143520",
|
||||
"LU": "143451",
|
||||
"LV": "143519",
|
||||
"MD": "143523",
|
||||
"MG": "143531",
|
||||
"MK": "143530",
|
||||
"ML": "143532",
|
||||
"MN": "143592",
|
||||
"MO": "143515",
|
||||
"MS": "143547",
|
||||
"MT": "143521",
|
||||
"MU": "143533",
|
||||
"MV": "143488",
|
||||
"MX": "143468",
|
||||
"MY": "143473",
|
||||
"NE": "143534",
|
||||
"NG": "143561",
|
||||
"NI": "143512",
|
||||
"NL": "143452",
|
||||
"NO": "143457",
|
||||
"NP": "143484",
|
||||
"NZ": "143461",
|
||||
"OM": "143562",
|
||||
"PA": "143485",
|
||||
"PE": "143507",
|
||||
"PH": "143474",
|
||||
"PK": "143477",
|
||||
"PL": "143478",
|
||||
"PT": "143453",
|
||||
"PY": "143513",
|
||||
"QA": "143498",
|
||||
"RO": "143487",
|
||||
"RS": "143500",
|
||||
"RU": "143469",
|
||||
"SA": "143479",
|
||||
"SE": "143456",
|
||||
"SG": "143464",
|
||||
"SI": "143499",
|
||||
"SK": "143496",
|
||||
"SN": "143535",
|
||||
"SR": "143554",
|
||||
"SV": "143506",
|
||||
"TC": "143552",
|
||||
"TH": "143475",
|
||||
"TN": "143536",
|
||||
"TR": "143480",
|
||||
"TT": "143551",
|
||||
"TW": "143470",
|
||||
"TZ": "143572",
|
||||
"UA": "143492",
|
||||
"UG": "143537",
|
||||
"US": "143441",
|
||||
"UY": "143514",
|
||||
"UZ": "143566",
|
||||
"VC": "143550",
|
||||
"VE": "143502",
|
||||
"VG": "143543",
|
||||
"VN": "143471",
|
||||
"YE": "143571",
|
||||
"ZA": "143472",
|
||||
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)
|
||||
|
||||
if countryCode, ok := countryCodes[identifier]; ok {
|
||||
return countryCode, nil
|
||||
}
|
||||
|
||||
return "", storefrontMappingError(storeFront)
|
||||
}
|
||||
|
||||
func storefrontIdentifier(storeFront string) string {
|
||||
identifier, _, _ := strings.Cut(strings.TrimSpace(storeFront), ",")
|
||||
identifier, _, _ = strings.Cut(identifier, "-")
|
||||
|
||||
return identifier
|
||||
}
|
||||
|
||||
func storefrontMappingError(storeFront string) error {
|
||||
return fmt.Errorf("country code mapping for store front (%s) was not found", 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