mirror of
https://github.com/majd/ipatool
synced 2026-11-28 18:27:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
747d66fc0a | ||
|
|
1ed3bf94dd | ||
|
|
fb1ca3521b | ||
|
|
ad88910ad6 | ||
|
|
c66d6537f4 | ||
|
|
7b4913a71c | ||
|
|
c4323e4c55 | ||
|
|
2aaf18b832 | ||
|
|
e3dea14461 | ||
|
|
dd28a3a9d8 | ||
|
|
5a47056bc3 | ||
|
|
ba85241c88 | ||
|
|
394cd643de | ||
|
|
62f1c8b435 | ||
|
|
5c522b685d | ||
|
|
ba180d741d | ||
|
|
d1845ba678 | ||
|
|
a814a71a9f | ||
|
|
843f5c6c29 | ||
|
|
b8bac296b8 | ||
|
|
24f93d332f | ||
|
|
e6acb9c3c2 | ||
|
|
abdb5902cb | ||
|
|
91d4294085 | ||
|
|
73fabcc283 | ||
|
|
30b2909231 | ||
|
|
a9bd16c9a2 | ||
|
|
cee3674258 | ||
|
|
8f9748fa51 |
No files matched your search
@@ -0,0 +1 @@
|
||||
github: majd
|
||||
@@ -63,3 +63,14 @@ jobs:
|
||||
CGO_ENABLED: 1
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
build_ios:
|
||||
name: Build for iOS
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: brew install ldid cmake
|
||||
- run: ./tools/build-ios.sh
|
||||
@@ -108,6 +108,48 @@ jobs:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
if-no-files-found: error
|
||||
build_ios:
|
||||
name: Build for iOS
|
||||
runs-on: macos-latest
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: brew install ldid cmake
|
||||
- run: ./tools/build-ios.sh "ipatool-$VERSION-ios-arm64"
|
||||
env:
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
if-no-files-found: error
|
||||
release_ios:
|
||||
name: Release for iOS
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build_ios, release_windows]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
path: bin
|
||||
- run: chmod +x "bin/$FILE" && tar -czvf "$FILE.tar.gz" "bin/$FILE"
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64
|
||||
- run: ./tools/sha256sum.sh "$TARBALL" > "$TARBALL.sha256sum"
|
||||
env:
|
||||
TARBALL: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64.tar.gz
|
||||
- uses: svenstaro/upload-release-action@v2
|
||||
with:
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
file: ipatool-${{ needs.get_version.outputs.version }}-ios-arm64.*
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
release_windows:
|
||||
name: Release for Windows
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -1,34 +1,29 @@
|
||||
# IPATool
|
||||
<p align="center">
|
||||
<a href="https://GitHub.com/majd/ipatool/releases/"><img src="https://img.shields.io/github/release/majd/ipatool.svg?label=Release" alt="Release"></a>
|
||||
<a href="https://github.com/majd/ipatool/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License"></a>
|
||||
<a href="https://github.com/sponsors/majd"><img src="https://img.shields.io/badge/Sponsor-%E2%9D%A4-pink.svg" alt="Sponsor"></a>
|
||||
</p>
|
||||
|
||||
[](https://GitHub.com/majd/ipatool/releases/)
|
||||
[](https://github.com/majd/ipatool/blob/main/LICENSE)
|
||||
<p align="center">
|
||||
<code>ipatool</code> is a command line tool that allows you to search for iOS, iPadOS, tvOS, visionOS, and macOS apps on the <a href="https://apps.apple.com">App Store</a>, and download <code>.ipa</code> or macOS <code>.pkg</code> app packages.
|
||||
</p>
|
||||
|
||||
`ipatool` is a command line tool that allows you to search for iOS, iPadOS, tvOS, and visionOS apps on the [App Store](https://apps.apple.com) and download a copy of the app package, known as an _ipa_ file.
|
||||
|
||||

|
||||
|
||||
- [Requirements](#requirements)
|
||||
- [Installation](#installation)
|
||||
- [Manual](#manual)
|
||||
- [Package Manager (macOS)](#package-manager-macos)
|
||||
- [Usage](#usage)
|
||||
- [Compiling](#compiling)
|
||||
- [License](#license)
|
||||
- [Releases](https://github.com/majd/ipatool/releases)
|
||||
- [FAQ](https://github.com/majd/ipatool/wiki/FAQ)
|
||||
<p align="center">
|
||||
<img src="./resources/demo.gif" alt="Demo">
|
||||
</p>
|
||||
|
||||
## Requirements
|
||||
|
||||
- Supported operating system (Windows, Linux or macOS).
|
||||
- Apple ID set up to use the App Store.
|
||||
- A supported operating system (macOS, Linux, Windows or iOS).
|
||||
- An Apple Account already configured to use the App Store.
|
||||
|
||||
## Installation
|
||||
|
||||
### Manual
|
||||
### Linux and Windows
|
||||
|
||||
You can grab the latest version of `ipatool` from [GitHub releases](https://github.com/majd/ipatool/releases).
|
||||
|
||||
### Package Manager (macOS)
|
||||
### macOS
|
||||
|
||||
You can install `ipatool` using [Homebrew](https://brew.sh).
|
||||
|
||||
@@ -38,150 +33,35 @@ $ brew install ipatool
|
||||
|
||||
## Usage
|
||||
|
||||
To authenticate with the App Store, use the `auth` command.
|
||||
To get started, run the following command.
|
||||
|
||||
```
|
||||
Authenticate with the App Store
|
||||
```text
|
||||
$ ipatool --help
|
||||
A cli tool for interacting with Apple's ipa files
|
||||
|
||||
Usage:
|
||||
ipatool auth [command]
|
||||
ipatool [command]
|
||||
|
||||
Available Commands:
|
||||
info Show current account info
|
||||
login Login to the App Store
|
||||
revoke Revoke your App Store credentials
|
||||
auth Authenticate with the App Store
|
||||
completion Generate the autocompletion script for the specified shell
|
||||
download Download iOS, iPadOS, tvOS, visionOS, and macOS app packages from the App Store
|
||||
get-version-metadata Retrieves the metadata for a specific version of an app
|
||||
help Help about any command
|
||||
list-purchases List apps owned by the authenticated App Store account
|
||||
list-versions List the available versions of an App Store app
|
||||
purchase Obtain a license for the app from the App Store
|
||||
search Search for iOS, iPadOS, tvOS, visionOS, and macOS apps available on the App Store
|
||||
|
||||
Flags:
|
||||
-h, --help help for auth
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
|
||||
Use "ipatool auth [command] --help" for more information about a command.
|
||||
```
|
||||
|
||||
To search for apps on the App Store, use the `search` command.
|
||||
|
||||
```
|
||||
Search for iOS, iPadOS, tvOS, and visionOS apps available on the App Store
|
||||
|
||||
Usage:
|
||||
ipatool search <term> [flags]
|
||||
|
||||
Flags:
|
||||
-h, --help help for search
|
||||
-l, --limit int maximum amount of search results to retrieve; visionOS supports up to 12 (default 5)
|
||||
--platform string Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), or visionos
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To obtain a license for an app, use the `purchase` command.
|
||||
|
||||
```
|
||||
Obtain a license for the app from the App Store
|
||||
|
||||
Usage:
|
||||
ipatool purchase [flags]
|
||||
|
||||
Flags:
|
||||
-b, --bundle-identifier string Bundle identifier of the target iOS app (required)
|
||||
-h, --help help for purchase
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To list apps owned by the authenticated account, use the `list-purchases` command. Results are ordered by purchase date, newest first.
|
||||
|
||||
```
|
||||
List apps owned by the authenticated App Store account
|
||||
|
||||
Usage:
|
||||
ipatool list-purchases [flags]
|
||||
|
||||
Flags:
|
||||
-h, --help help for list-purchases
|
||||
-l, --max-results int maximum number of apps to return per page (default 10)
|
||||
-p, --page int page of owned apps to return (default 1)
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
-h, --help help for ipatool
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
-v, --version version for ipatool
|
||||
|
||||
To obtain a list of availble app versions to download, use the `list-versions` command.
|
||||
|
||||
```
|
||||
List the available versions of an iOS app
|
||||
|
||||
Usage:
|
||||
ipatool list-versions [flags]
|
||||
|
||||
Flags:
|
||||
-i, --app-id int ID of the target iOS app (required)
|
||||
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
|
||||
-h, --help help for list-versions
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To download a copy of the ipa file, use the `download` command.
|
||||
|
||||
```
|
||||
Download (encrypted) iOS, iPadOS, tvOS, and visionOS app packages from the App Store
|
||||
|
||||
Usage:
|
||||
ipatool download [flags]
|
||||
|
||||
Flags:
|
||||
-i, --app-id int ID of the target app (required)
|
||||
-b, --bundle-identifier string The bundle identifier of the target app (overrides the app ID)
|
||||
--external-version-id string External version identifier of the target app (defaults to latest version when not specified)
|
||||
-h, --help help for download
|
||||
-o, --output string The destination path of the downloaded app package
|
||||
--platform string Platform to download for: iphone (iOS), ipad (iPadOS), appletv (tvOS), or visionos
|
||||
--purchase Obtain a license for the app if needed
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To resolve an external version identifier, returned by the `list-versions` command, use the `get-version-metadata` command.
|
||||
|
||||
```
|
||||
Retrieves the metadata for a specific version of an app
|
||||
|
||||
Usage:
|
||||
ipatool get-version-metadata [flags]
|
||||
|
||||
Flags:
|
||||
-i, --app-id int ID of the target iOS app (required)
|
||||
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
|
||||
--external-version-id string External version identifier of the target iOS app (required)
|
||||
-h, --help help for get-version-metadata
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
Use "ipatool [command] --help" for more information about a command.
|
||||
```
|
||||
|
||||
**Note:** the tool runs in interactive mode by default. Use the `--non-interactive` flag
|
||||
@@ -204,4 +84,4 @@ $ go test -v ./...
|
||||
|
||||
## License
|
||||
|
||||
IPATool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
|
||||
ipatool is released under the [MIT license](https://github.com/majd/ipatool/blob/main/LICENSE).
|
||||
+15
-25
@@ -1,17 +1,13 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func authCmd() *cobra.Command {
|
||||
@@ -28,18 +24,6 @@ func authCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
func loginCmd() *cobra.Command {
|
||||
promptForAuthCode := func() (string, error) {
|
||||
authCode, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read string: %w", err)
|
||||
}
|
||||
|
||||
authCode = strings.Trim(authCode, "\n")
|
||||
authCode = strings.Trim(authCode, "\r")
|
||||
|
||||
return authCode, nil
|
||||
}
|
||||
|
||||
var email, password, authCode string
|
||||
|
||||
cmd := &cobra.Command{
|
||||
@@ -48,18 +32,28 @@ func loginCmd() *cobra.Command {
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
interactive := cmd.Context().Value(interactiveKey).(bool)
|
||||
|
||||
if email == "" && !interactive {
|
||||
return errors.New("email is required when not running in interactive mode; use the \"--email\" flag")
|
||||
}
|
||||
|
||||
if email == "" && interactive {
|
||||
value, err := readPrompt("enter email: ", false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read email: %w", err)
|
||||
}
|
||||
email = value
|
||||
}
|
||||
|
||||
if password == "" && !interactive {
|
||||
return errors.New("password is required when not running in interactive mode; use the \"--password\" flag")
|
||||
}
|
||||
|
||||
if password == "" && interactive {
|
||||
dependencies.Logger.Log().Msg("enter password:")
|
||||
|
||||
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
value, err := readPrompt("enter password: ", true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read password: %w", err)
|
||||
}
|
||||
password = string(bytes)
|
||||
password = value
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().Msg("preparing authentication; the first login may take a few minutes")
|
||||
@@ -69,10 +63,8 @@ func loginCmd() *cobra.Command {
|
||||
// nolint:wrapcheck
|
||||
return retry.Do(func() error {
|
||||
if errors.Is(lastErr, appstore.ErrAuthCodeRequired) && interactive {
|
||||
dependencies.Logger.Log().Msg("enter 2FA code:")
|
||||
|
||||
var err error
|
||||
authCode, err = promptForAuthCode()
|
||||
authCode, err = readPrompt("enter 2FA code: ", false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read auth code: %w", err)
|
||||
}
|
||||
@@ -123,8 +115,6 @@ func loginCmd() *cobra.Command {
|
||||
cmd.Flags().StringVarP(&password, "password", "p", "", "password for the Apple ID (required)")
|
||||
cmd.Flags().StringVar(&authCode, "auth-code", "", "2FA code for the Apple ID")
|
||||
|
||||
_ = cmd.MarkFlagRequired("email")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Login command", func() {
|
||||
var store *fakeLoginAppStore
|
||||
|
||||
BeforeEach(func() {
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
store = &fakeLoginAppStore{}
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
})
|
||||
|
||||
DescribeTable("requires credentials in non-interactive mode", func(args []string, message string) {
|
||||
cmd := loginCmd()
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
cmd.SetArgs(args)
|
||||
|
||||
Expect(cmd.Execute()).To(MatchError(message))
|
||||
Expect(store.loginCalls).To(BeZero())
|
||||
},
|
||||
Entry("missing email", []string{"--password", "secret"}, "email is required when not running in interactive mode; use the \"--email\" flag"),
|
||||
Entry("missing password", []string{"--email", "user@example.com"}, "password is required when not running in interactive mode; use the \"--password\" flag"),
|
||||
)
|
||||
|
||||
DescribeTable("uses supplied credentials", func(interactive bool) {
|
||||
cmd := loginCmd()
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, interactive))
|
||||
cmd.SetArgs([]string{"--email", "user@example.com", "--password", "secret"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.loginCalls).To(Equal(1))
|
||||
Expect(store.input).To(Equal(appstore.LoginInput{Email: "user@example.com", Password: "secret"}))
|
||||
},
|
||||
Entry("interactive", true),
|
||||
Entry("non-interactive", false),
|
||||
)
|
||||
|
||||
DescribeTable("prompts for email", func(input, message string) {
|
||||
dir := GinkgoT().TempDir()
|
||||
inputPath := filepath.Join(dir, "stdin")
|
||||
Expect(os.WriteFile(inputPath, []byte(input), 0o600)).To(Succeed())
|
||||
stdin, err := os.Open(inputPath)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(stdin.Close)
|
||||
stderr, err := os.Create(filepath.Join(dir, "stderr"))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(stderr.Close)
|
||||
|
||||
previousStdin, previousStderr := os.Stdin, os.Stderr
|
||||
os.Stdin, os.Stderr = stdin, stderr
|
||||
DeferCleanup(func() { os.Stdin, os.Stderr = previousStdin, previousStderr })
|
||||
|
||||
cmd := loginCmd()
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, true))
|
||||
cmd.SetArgs([]string{"--password", "secret"})
|
||||
cmd.SilenceErrors = true
|
||||
cmd.SilenceUsage = true
|
||||
|
||||
err = cmd.Execute()
|
||||
if message == "" {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(store.loginCalls).To(Equal(1))
|
||||
Expect(store.input).To(Equal(appstore.LoginInput{Email: "user@example.com", Password: "secret"}))
|
||||
} else {
|
||||
Expect(err).To(MatchError(message))
|
||||
Expect(store.loginCalls).To(BeZero())
|
||||
}
|
||||
|
||||
prompt, err := os.ReadFile(stderr.Name())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(prompt)).To(Equal("enter email: "))
|
||||
},
|
||||
Entry("reads unmasked input without requiring a terminal", "user@example.com\n", ""),
|
||||
Entry("reports input errors", "", "failed to read email: failed to read input: EOF"),
|
||||
)
|
||||
})
|
||||
|
||||
type fakeLoginAppStore struct {
|
||||
appstore.AppStore
|
||||
input appstore.LoginInput
|
||||
loginCalls int
|
||||
}
|
||||
|
||||
func (f *fakeLoginAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
f.input = input
|
||||
f.loginCalls++
|
||||
|
||||
return appstore.LoginOutput{}, nil
|
||||
}
|
||||
+9
-33
@@ -19,7 +19,6 @@ import (
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
var dependencies = Dependencies{}
|
||||
@@ -53,15 +52,15 @@ func newLogger(format OutputFormat, verbose bool) log.Logger {
|
||||
}
|
||||
|
||||
// newCookieJar returns a new cookie jar instance.
|
||||
func newCookieJar(machine machine.Machine) http.CookieJar {
|
||||
func newCookieJar(stateDirectory string) http.CookieJar {
|
||||
return util.Must(cookiejar.New(&cookiejar.Options{
|
||||
Filename: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName, CookieJarFileName),
|
||||
Filename: filepath.Join(stateDirectory, CookieJarFileName),
|
||||
}))
|
||||
}
|
||||
|
||||
// newKeychain returns a new keychain instance.
|
||||
func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) keychain.Keychain {
|
||||
ring := util.Must(keyring.Open(keyring.Config{
|
||||
func newKeychain(stateDirectory string, interactive bool) keychain.Keychain {
|
||||
ring := util.Must(openKeyring(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{
|
||||
keyring.KeychainBackend,
|
||||
keyring.SecretServiceBackend,
|
||||
@@ -69,7 +68,7 @@ func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) k
|
||||
},
|
||||
ServiceName: KeychainServiceName,
|
||||
KeychainTrustApplication: true,
|
||||
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
|
||||
FileDir: stateDirectory,
|
||||
FilePasswordFunc: func(s string) (string, error) {
|
||||
if keychainPassphrase == "" && !interactive {
|
||||
return "", errors.New("keychain passphrase is required when not running in interactive mode; use the \"--keychain-passphrase\" flag")
|
||||
@@ -80,16 +79,11 @@ func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) k
|
||||
}
|
||||
|
||||
path := strings.Split(s, " unlock ")[1]
|
||||
logger.Log().Msgf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path)
|
||||
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
password, err := readPrompt(fmt.Sprintf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path), true)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read password: %w", err)
|
||||
}
|
||||
|
||||
password := string(bytes)
|
||||
password = strings.Trim(password, "\n")
|
||||
password = strings.Trim(password, "\r")
|
||||
|
||||
return password, nil
|
||||
},
|
||||
}))
|
||||
@@ -109,31 +103,13 @@ func initWithCommand(cmd *cobra.Command) {
|
||||
dependencies.Logger = newLogger(format, verbose)
|
||||
dependencies.OS = operatingsystem.New()
|
||||
dependencies.Machine = machine.New(machine.Args{OS: dependencies.OS})
|
||||
dependencies.CookieJar = newCookieJar(dependencies.Machine)
|
||||
dependencies.Keychain = newKeychain(dependencies.Machine, dependencies.Logger, interactive)
|
||||
stateDirectory := util.Must(prepareStateDirectory(dependencies.OS, dependencies.Machine.HomeDirectory()))
|
||||
dependencies.CookieJar = newCookieJar(stateDirectory)
|
||||
dependencies.Keychain = newKeychain(stateDirectory, interactive)
|
||||
dependencies.AppStore = appstore.NewAppStore(appstore.Args{
|
||||
CookieJar: dependencies.CookieJar,
|
||||
OperatingSystem: dependencies.OS,
|
||||
Keychain: dependencies.Keychain,
|
||||
Machine: dependencies.Machine,
|
||||
})
|
||||
|
||||
util.Must("", createConfigDirectory(dependencies.OS, dependencies.Machine))
|
||||
}
|
||||
|
||||
// createConfigDirectory creates the configuration directory for the CLI tool, if needed.
|
||||
func createConfigDirectory(os operatingsystem.OperatingSystem, machine machine.Machine) error {
|
||||
configDirectoryPath := filepath.Join(machine.HomeDirectory(), ConfigDirectoryName)
|
||||
_, err := os.Stat(configDirectoryPath)
|
||||
|
||||
if err != nil && os.IsNotExist(err) {
|
||||
err = os.MkdirAll(configDirectoryPath, 0700)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("could not read metadata: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+43
-13
@@ -13,6 +13,11 @@ import (
|
||||
|
||||
// nolint:wrapcheck
|
||||
func downloadCmd() *cobra.Command {
|
||||
return downloadCmdWithAppStore(func() appstore.AppStore { return dependencies.AppStore })
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func downloadCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
|
||||
var (
|
||||
acquireLicense bool
|
||||
outputPath string
|
||||
@@ -24,18 +29,25 @@ func downloadCmd() *cobra.Command {
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "download",
|
||||
Short: "Download (encrypted) iOS, iPadOS, tvOS, and visionOS app packages from the App Store",
|
||||
Short: "Download iOS, iPadOS, tvOS, visionOS, and macOS app packages from the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
purchaseRequired := false
|
||||
purchased := false
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
store := appStore()
|
||||
infoResult, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -43,7 +55,7 @@ func downloadCmd() *cobra.Command {
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
loginResult, err := store.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
@@ -55,13 +67,9 @@ func downloadCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{
|
||||
lookupResult, err := store.Lookup(appstore.LookupInput{
|
||||
Account: acc,
|
||||
BundleID: bundleID,
|
||||
Platform: platform,
|
||||
@@ -74,10 +82,19 @@ func downloadCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrLicenseRequired) {
|
||||
err := dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: app})
|
||||
purchaseRequired = true
|
||||
}
|
||||
|
||||
if purchaseRequired {
|
||||
err := store.Purchase(appstore.PurchaseInput{
|
||||
Account: acc,
|
||||
App: app,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return err
|
||||
}
|
||||
purchaseRequired = false
|
||||
purchased = true
|
||||
dependencies.Logger.Verbose().
|
||||
Bool("success", true).
|
||||
@@ -103,7 +120,8 @@ func downloadCmd() *cobra.Command {
|
||||
)
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.Download(appstore.DownloadInput{
|
||||
out, err := store.Download(appstore.DownloadInput{
|
||||
Context: cmd.Context(),
|
||||
Account: acc,
|
||||
App: app,
|
||||
OutputPath: outputPath,
|
||||
@@ -115,8 +133,7 @@ func downloadCmd() *cobra.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
err = dependencies.AppStore.ReplicateSinf(appstore.ReplicateSinfInput{Sinfs: out.Sinfs, PackagePath: out.DestinationPath})
|
||||
if err != nil {
|
||||
if err := replicateDownloadSinf(store, platform, out); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -153,8 +170,21 @@ func downloadCmd() *cobra.Command {
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
|
||||
cmd.Flags().StringVarP(&outputPath, "output", "o", "", "The destination path of the downloaded app package")
|
||||
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target app (defaults to latest version when not specified)")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone (iOS), ipad (iPadOS), appletv (tvOS), or visionos")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
|
||||
cmd.Flags().BoolVar(&acquireLicense, "purchase", false, "Obtain a license for the app if needed")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
type sinfReplicator interface {
|
||||
ReplicateSinf(input appstore.ReplicateSinfInput) error
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func replicateDownloadSinf(store sinfReplicator, platform appstore.Platform, out appstore.DownloadOutput) error {
|
||||
if platform == appstore.PlatformMacOS && len(out.Sinfs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return store.ReplicateSinf(appstore.ReplicateSinfInput{Sinfs: out.Sinfs, PackagePath: out.DestinationPath})
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Download command", func() {
|
||||
It("exposes macOS in platform help", func() {
|
||||
cmd := downloadCmd()
|
||||
Expect(cmd.Flag("platform").Usage).To(ContainSubstring("macos"))
|
||||
})
|
||||
|
||||
It("skips sinf replication for macOS packages", func() {
|
||||
replicator := &fakeSinfReplicator{}
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformMacOS, appstore.DownloadOutput{
|
||||
DestinationPath: "app.pkg",
|
||||
})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(replicator.called).To(BeFalse())
|
||||
})
|
||||
|
||||
It("replicates sinf for mobile packages downloaded for macOS", func() {
|
||||
replicator := &fakeSinfReplicator{}
|
||||
out := appstore.DownloadOutput{
|
||||
DestinationPath: "app.ipa",
|
||||
Sinfs: []appstore.Sinf{{Data: []byte("sinf")}},
|
||||
}
|
||||
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformMacOS, out)
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(replicator.called).To(BeTrue())
|
||||
Expect(replicator.input).To(Equal(appstore.ReplicateSinfInput{
|
||||
PackagePath: out.DestinationPath,
|
||||
Sinfs: out.Sinfs,
|
||||
}))
|
||||
})
|
||||
|
||||
It("replicates sinf for non-macOS packages", func() {
|
||||
replicator := &fakeSinfReplicator{}
|
||||
out := appstore.DownloadOutput{
|
||||
DestinationPath: "app.ipa",
|
||||
Sinfs: []appstore.Sinf{{Data: []byte("sinf")}},
|
||||
}
|
||||
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformIPhone, out)
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(replicator.called).To(BeTrue())
|
||||
Expect(replicator.input).To(Equal(appstore.ReplicateSinfInput{
|
||||
PackagePath: out.DestinationPath,
|
||||
Sinfs: out.Sinfs,
|
||||
}))
|
||||
})
|
||||
|
||||
It("returns sinf replication errors for non-macOS packages", func() {
|
||||
replicator := &fakeSinfReplicator{err: errors.New("replication failed")}
|
||||
err := replicateDownloadSinf(replicator, appstore.PlatformIPhone, appstore.DownloadOutput{})
|
||||
Expect(err).To(MatchError("replication failed"))
|
||||
})
|
||||
|
||||
It("propagates macOS when automatic purchase retries the download", func() {
|
||||
store := &fakeDownloadAppStore{downloadErrors: []error{appstore.ErrLicenseRequired, nil}}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--app-id", "42", "--platform", "macos", "--purchase"})
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.purchaseInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs[0].Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.purchaseInputs[0].App).To(Equal(appstore.App{ID: 42}))
|
||||
Expect(store.downloadInputs).To(HaveLen(2))
|
||||
Expect(store.downloadInputs[0].Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.downloadInputs[1].Platform).To(Equal(appstore.PlatformMacOS))
|
||||
})
|
||||
|
||||
It("retains the pending automatic purchase after refreshing authentication", func() {
|
||||
store := &fakeDownloadAppStore{
|
||||
downloadErrors: []error{appstore.ErrLicenseRequired, nil},
|
||||
purchaseErrors: []error{appstore.ErrPasswordTokenExpired, nil},
|
||||
}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--app-id", "42", "--platform", "macos", "--purchase"})
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.loginInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs).To(HaveLen(2))
|
||||
Expect(store.purchaseInputs[0].Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.purchaseInputs[1].Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.downloadInputs).To(HaveLen(2))
|
||||
})
|
||||
})
|
||||
|
||||
type fakeSinfReplicator struct {
|
||||
called bool
|
||||
input appstore.ReplicateSinfInput
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeSinfReplicator) ReplicateSinf(input appstore.ReplicateSinfInput) error {
|
||||
f.called = true
|
||||
f.input = input
|
||||
|
||||
return f.err
|
||||
}
|
||||
|
||||
type fakeDownloadAppStore struct {
|
||||
downloadErrors []error
|
||||
downloadInputs []appstore.DownloadInput
|
||||
loginInputs []appstore.LoginInput
|
||||
purchaseErrors []error
|
||||
purchaseInputs []appstore.PurchaseInput
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
f.loginInputs = append(f.loginInputs, input)
|
||||
|
||||
return appstore.LoginOutput{Account: appstore.Account{StoreFront: "143441"}}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{Account: appstore.Account{StoreFront: "143441"}}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) Revoke() error { return nil }
|
||||
|
||||
func (*fakeDownloadAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return appstore.LookupOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Purchase(input appstore.PurchaseInput) error {
|
||||
f.purchaseInputs = append(f.purchaseInputs, input)
|
||||
index := len(f.purchaseInputs) - 1
|
||||
|
||||
if index < len(f.purchaseErrors) && f.purchaseErrors[index] != nil {
|
||||
return f.purchaseErrors[index]
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
f.downloadInputs = append(f.downloadInputs, input)
|
||||
index := len(f.downloadInputs) - 1
|
||||
|
||||
if index < len(f.downloadErrors) && f.downloadErrors[index] != nil {
|
||||
return appstore.DownloadOutput{}, f.downloadErrors[index]
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "app.pkg"}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error { return nil }
|
||||
|
||||
func (*fakeDownloadAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) Bag(input appstore.BagInput) (appstore.BagOutput, error) {
|
||||
return appstore.BagOutput{}, nil
|
||||
}
|
||||
@@ -15,6 +15,7 @@ func getVersionMetadataCmd() *cobra.Command {
|
||||
appID int64
|
||||
bundleID string
|
||||
externalVersionID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
@@ -25,6 +26,11 @@ func getVersionMetadataCmd() *cobra.Command {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
@@ -50,7 +56,7 @@ func getVersionMetadataCmd() *cobra.Command {
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID, Platform: platform})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -59,9 +65,11 @@ func getVersionMetadataCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.GetVersionMetadata(appstore.GetVersionMetadataInput{
|
||||
Context: cmd.Context(),
|
||||
Account: acc,
|
||||
App: app,
|
||||
VersionID: externalVersionID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -89,9 +97,11 @@ func getVersionMetadataCmd() *cobra.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
|
||||
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target iOS app (required)")
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
|
||||
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target app (required)")
|
||||
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to retrieve metadata for: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
|
||||
|
||||
_ = cmd.MarkFlagRequired("external-version-id")
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Get Version Metadata command", func() {
|
||||
DescribeTable("passes the platform and exact version to metadata lookup", func(args []string, platform appstore.Platform, lookup bool) {
|
||||
store := &fakeVersionMetadataAppStore{}
|
||||
previous := dependencies
|
||||
DeferCleanup(func() { dependencies = previous })
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
cmd := getVersionMetadataCmd()
|
||||
cmd.SetArgs(append(args, "--external-version-id", "876660716"))
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.input.Platform).To(Equal(platform))
|
||||
Expect(store.input.VersionID).To(Equal("876660716"))
|
||||
Expect(store.input.App.ID).To(Equal(int64(42)))
|
||||
Expect(store.lookupCalled).To(Equal(lookup))
|
||||
if lookup {
|
||||
Expect(store.lookupInput.Platform).To(Equal(platform))
|
||||
}
|
||||
},
|
||||
Entry("Mac bundle", []string{"-b", "com.example.mac", "--platform", "macos"}, appstore.PlatformMacOS, true),
|
||||
Entry("Mac ID alias", []string{"-i", "42", "--platform", "mac"}, appstore.PlatformMacOS, false),
|
||||
Entry("default", []string{"-i", "42"}, appstore.Platform(""), false),
|
||||
)
|
||||
It("rejects unknown as a filter", func() {
|
||||
cmd := getVersionMetadataCmd()
|
||||
cmd.SetArgs([]string{"-i", "42", "--external-version-id", "123", "--platform", "unknown"})
|
||||
Expect(cmd.Execute()).To(MatchError(`invalid platform "unknown"`))
|
||||
})
|
||||
})
|
||||
|
||||
type fakeVersionMetadataAppStore struct {
|
||||
fakeListVersionsAppStore
|
||||
input appstore.GetVersionMetadataInput
|
||||
}
|
||||
|
||||
func (s *fakeVersionMetadataAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
s.input = input
|
||||
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !ios
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
)
|
||||
|
||||
func openKeyring(config keyring.Config) (keychain.Keyring, error) {
|
||||
return keyring.Open(config) //nolint:wrapcheck
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
gokeychain "github.com/byteness/go-keychain"
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
)
|
||||
|
||||
// iosKeyring fixes the update query in keyring v1.9.0, which includes attributes
|
||||
// that SecItemUpdate rejects on iOS (kSecMatchLimit and kSecReturnAttributes).
|
||||
type iosKeyring struct {
|
||||
keyring.Keyring
|
||||
service string
|
||||
}
|
||||
|
||||
func openKeyring(config keyring.Config) (keychain.Keyring, error) {
|
||||
ring, err := keyring.Open(config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open iOS keyring: %w", err)
|
||||
}
|
||||
|
||||
return &iosKeyring{Keyring: ring, service: config.ServiceName}, nil
|
||||
}
|
||||
|
||||
func (k *iosKeyring) Set(item keyring.Item) error {
|
||||
query := gokeychain.NewItem()
|
||||
query.SetSecClass(gokeychain.SecClassGenericPassword)
|
||||
query.SetService(k.service)
|
||||
query.SetAccount(item.Key)
|
||||
|
||||
attributes := gokeychain.NewItem()
|
||||
attributes.SetData(item.Data)
|
||||
attributes.SetLabel(item.Label)
|
||||
attributes.SetDescription(item.Description)
|
||||
|
||||
err := gokeychain.UpdateItem(query, attributes)
|
||||
if err == gokeychain.ErrorItemNotFound {
|
||||
return k.Keyring.Set(item) //nolint:wrapcheck
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("update iOS keyring item: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("iOS keyring", func() {
|
||||
It("persists and updates credentials without invalid SecItemUpdate parameters", func() {
|
||||
ring, err := openKeyring(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{keyring.KeychainBackend},
|
||||
ServiceName: fmt.Sprintf("ipatool-test-%d", time.Now().UnixNano()),
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(func() { Expect(ring.Remove("account")).To(Succeed()) })
|
||||
Expect(ring.Set(keyring.Item{Key: "account", Data: []byte("first"), Label: "ipatool"})).To(Succeed())
|
||||
Expect(ring.Set(keyring.Item{Key: "account", Data: []byte("updated"), Label: "ipatool"})).To(Succeed())
|
||||
item, err := ring.Get("account")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(item.Data).To(Equal([]byte("updated")))
|
||||
Expect(item.Label).To(Equal("ipatool"))
|
||||
})
|
||||
})
|
||||
+15
-7
@@ -12,18 +12,24 @@ import (
|
||||
// nolint:wrapcheck
|
||||
func ListVersionsCmd() *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
appID int64
|
||||
bundleID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "list-versions",
|
||||
Short: "List the available versions of an iOS app",
|
||||
Short: "List the available versions of an App Store app",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
@@ -49,7 +55,7 @@ func ListVersionsCmd() *cobra.Command {
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID, Platform: platform})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -57,7 +63,7 @@ func ListVersionsCmd() *cobra.Command {
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Account: acc, App: app})
|
||||
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Account: acc, App: app, Platform: platform})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -83,8 +89,10 @@ func ListVersionsCmd() *cobra.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
|
||||
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to list versions for: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("List Versions command", func() {
|
||||
DescribeTable("passes the selected platform to lookup and version listing", func(args []string, expected appstore.Platform, lookup bool) {
|
||||
store := &fakeListVersionsAppStore{}
|
||||
previous := dependencies
|
||||
DeferCleanup(func() { dependencies = previous })
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
cmd := ListVersionsCmd()
|
||||
cmd.SetArgs(args)
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.input.Platform).To(Equal(expected))
|
||||
Expect(store.input.App.ID).To(Equal(int64(42)))
|
||||
Expect(store.lookupCalled).To(Equal(lookup))
|
||||
if lookup {
|
||||
Expect(store.lookupInput.Platform).To(Equal(expected))
|
||||
}
|
||||
},
|
||||
Entry("Mac bundle ID", []string{"-b", "com.example.mac", "--platform", "macos"}, appstore.PlatformMacOS, true),
|
||||
Entry("Mac app ID alias", []string{"-i", "42", "--platform", "mac"}, appstore.PlatformMacOS, false),
|
||||
Entry("default platform", []string{"-i", "42"}, appstore.Platform(""), false),
|
||||
Entry("iOS alias", []string{"-i", "42", "--platform", "ios"}, appstore.PlatformIPhone, false),
|
||||
)
|
||||
|
||||
It("rejects unknown as a platform before accessing the account", func() {
|
||||
cmd := ListVersionsCmd()
|
||||
cmd.SetArgs([]string{"-i", "42", "--platform", "unknown"})
|
||||
Expect(cmd.Execute()).To(MatchError(`invalid platform "unknown"`))
|
||||
})
|
||||
})
|
||||
|
||||
type fakeListVersionsAppStore struct {
|
||||
appstore.AppStore
|
||||
input appstore.ListVersionsInput
|
||||
lookupInput appstore.LookupInput
|
||||
lookupCalled bool
|
||||
}
|
||||
|
||||
func (*fakeListVersionsAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, nil
|
||||
}
|
||||
func (s *fakeListVersionsAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
s.lookupCalled = true
|
||||
s.lookupInput = input
|
||||
|
||||
return appstore.LookupOutput{App: appstore.App{ID: 42, BundleID: input.BundleID}}, nil
|
||||
}
|
||||
func (s *fakeListVersionsAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
s.input = input
|
||||
|
||||
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"123"}}, nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func readPrompt(prompt string, masked bool) (string, error) {
|
||||
if masked {
|
||||
state, err := term.MakeRaw(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to configure terminal: %w", err)
|
||||
}
|
||||
defer term.Restore(int(os.Stdin.Fd()), state) //nolint:errcheck
|
||||
}
|
||||
|
||||
// Prompts belong on stderr so structured output on stdout stays valid.
|
||||
if _, err := io.WriteString(os.Stderr, prompt); err != nil {
|
||||
return "", fmt.Errorf("failed to write prompt: %w", err)
|
||||
}
|
||||
|
||||
if masked {
|
||||
defer fmt.Fprint(os.Stderr, "\r\n")
|
||||
|
||||
return readMaskedInput(os.Stdin, os.Stderr)
|
||||
}
|
||||
|
||||
line, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read input: %w", err)
|
||||
}
|
||||
|
||||
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
|
||||
}
|
||||
|
||||
func readMaskedInput(input io.Reader, output io.Writer) (string, error) {
|
||||
reader := bufio.NewReader(input)
|
||||
|
||||
var (
|
||||
password []rune
|
||||
escape int
|
||||
)
|
||||
|
||||
for {
|
||||
key, _, err := reader.ReadRune()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read input: %w", err)
|
||||
}
|
||||
|
||||
// Ignore terminal escape sequences (for example, arrow keys).
|
||||
if escape != 0 {
|
||||
if escape == 1 && (key == '[' || key == 'O') {
|
||||
escape = 2
|
||||
} else if escape == 1 || (key >= 0x40 && key <= 0x7e) {
|
||||
escape = 0
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
var echo string
|
||||
|
||||
switch key {
|
||||
case '\r', '\n':
|
||||
return string(password), nil
|
||||
case 3:
|
||||
return "", errors.New("input interrupted")
|
||||
case 4:
|
||||
return "", io.EOF
|
||||
case 27:
|
||||
escape = 1
|
||||
case '\b', 127:
|
||||
if len(password) > 0 {
|
||||
password = password[:len(password)-1]
|
||||
echo = "\b \b"
|
||||
}
|
||||
case 21:
|
||||
echo = strings.Repeat("\b \b", len(password))
|
||||
password = password[:0]
|
||||
default:
|
||||
if unicode.IsPrint(key) {
|
||||
password = append(password, key)
|
||||
echo = "*"
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := io.WriteString(output, echo); err != nil {
|
||||
return "", fmt.Errorf("failed to echo input: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Masked input", func() {
|
||||
DescribeTable("echoes masks while preserving the entered password", func(input, password, echo string) {
|
||||
var output bytes.Buffer
|
||||
value, err := readMaskedInput(strings.NewReader(input), &output)
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(value).To(Equal(password))
|
||||
Expect(output.String()).To(Equal(echo))
|
||||
},
|
||||
Entry("enter", "secret\r", "secret", "******"),
|
||||
Entry("newline", "secret\n", "secret", "******"),
|
||||
Entry("unicode", "pä密🔑\r", "pä密🔑", "****"),
|
||||
Entry("delete", "ab\x7fc\r", "ac", "**\b \b*"),
|
||||
Entry("unicode backspace", "a密\bc\r", "ac", "**\b \b*"),
|
||||
Entry("backspace on empty input", "\b\x7fa\r", "a", "*"),
|
||||
Entry("clear line", "ab\x15c\r", "c", "**\b \b\b \b*"),
|
||||
Entry("arrow keys", "ab\x1b[D\x1bOCc\r", "abc", "***"),
|
||||
Entry("empty input", "\r", "", ""),
|
||||
)
|
||||
|
||||
It("cancels without returning the password on Ctrl-C", func() {
|
||||
value, err := readMaskedInput(strings.NewReader("secret\x03"), io.Discard)
|
||||
|
||||
Expect(err).To(MatchError("input interrupted"))
|
||||
Expect(value).To(BeEmpty())
|
||||
})
|
||||
|
||||
DescribeTable("discards incomplete input", func(input string) {
|
||||
value, err := readMaskedInput(strings.NewReader(input), io.Discard)
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("EOF")))
|
||||
Expect(value).To(BeEmpty())
|
||||
},
|
||||
Entry("end of stream", "secret"),
|
||||
Entry("Ctrl-D", "secret\x04"),
|
||||
)
|
||||
})
|
||||
+42
-9
@@ -11,17 +11,36 @@ import (
|
||||
|
||||
// nolint:wrapcheck
|
||||
func purchaseCmd() *cobra.Command {
|
||||
var bundleID string
|
||||
return purchaseCmdWithAppStore(func() appstore.AppStore { return dependencies.AppStore })
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func purchaseCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "purchase",
|
||||
Short: "Obtain a license for the app from the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
store := appStore()
|
||||
infoResult, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -29,7 +48,7 @@ func purchaseCmd() *cobra.Command {
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
loginResult, err := store.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
@@ -40,12 +59,25 @@ func purchaseCmd() *cobra.Command {
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
|
||||
if err != nil {
|
||||
return err
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := store.Lookup(appstore.LookupInput{
|
||||
Account: acc,
|
||||
BundleID: bundleID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
err = dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: lookupResult.App})
|
||||
err = store.Purchase(appstore.PurchaseInput{
|
||||
Account: acc,
|
||||
App: app,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return err
|
||||
}
|
||||
@@ -70,8 +102,9 @@ func purchaseCmd() *cobra.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "Bundle identifier of the target iOS app (required)")
|
||||
_ = cmd.MarkFlagRequired("bundle-identifier")
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to purchase for: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Purchase command", func() {
|
||||
It("accepts a platform flag with macOS help", func() {
|
||||
cmd := purchaseCmd()
|
||||
platform, err := cmd.Flags().GetString("platform")
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(platform).To(BeEmpty())
|
||||
Expect(cmd.Flag("platform").Usage).To(ContainSubstring("macos"))
|
||||
})
|
||||
|
||||
DescribeTable("purchasing by app ID", func(flag string) {
|
||||
store := &fakePurchaseAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{flag, "123456789", "--platform", "macos"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.lookupCalls).To(BeZero())
|
||||
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 123456789}))
|
||||
Expect(store.purchaseInput.Platform).To(Equal(appstore.PlatformMacOS))
|
||||
},
|
||||
Entry("accepts the long flag", "--app-id"),
|
||||
Entry("accepts the short flag", "-i"),
|
||||
)
|
||||
|
||||
It("requires an app ID or bundle identifier before accessing the account", func() {
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore {
|
||||
Fail("must not access the app store without a target")
|
||||
|
||||
return nil
|
||||
})
|
||||
cmd.SetArgs([]string{})
|
||||
|
||||
Expect(cmd.Execute()).To(MatchError("either the app ID or the bundle identifier must be specified"))
|
||||
})
|
||||
|
||||
It("lets the bundle identifier override the app ID", func() {
|
||||
store := &fakePurchaseAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"-i", "123456789", "-b", "com.example.app"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.lookupCalls).To(Equal(1))
|
||||
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.app"}))
|
||||
})
|
||||
|
||||
It("propagates macOS to lookup and purchase", func() {
|
||||
store := &fakePurchaseAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := purchaseCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--bundle-identifier", "com.example.mac", "--platform", "macos"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.lookupInput.BundleID).To(Equal("com.example.mac"))
|
||||
Expect(store.lookupInput.Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.purchaseInput.Platform).To(Equal(appstore.PlatformMacOS))
|
||||
Expect(store.purchaseInput.App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.mac"}))
|
||||
})
|
||||
})
|
||||
|
||||
type fakePurchaseAppStore struct {
|
||||
lookupCalls int
|
||||
lookupInput appstore.LookupInput
|
||||
purchaseInput appstore.PurchaseInput
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
return appstore.LoginOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{Account: appstore.Account{StoreFront: "143441"}}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Revoke() error { return nil }
|
||||
|
||||
func (f *fakePurchaseAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
f.lookupCalls++
|
||||
f.lookupInput = input
|
||||
|
||||
return appstore.LookupOutput{App: appstore.App{ID: 42, BundleID: input.BundleID}}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{}, nil
|
||||
}
|
||||
|
||||
func (f *fakePurchaseAppStore) Purchase(input appstore.PurchaseInput) error {
|
||||
f.purchaseInput = input
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error { return nil }
|
||||
|
||||
func (*fakePurchaseAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
|
||||
func (*fakePurchaseAppStore) Bag(input appstore.BagInput) (appstore.BagOutput, error) {
|
||||
return appstore.BagOutput{}, nil
|
||||
}
|
||||
+13
-4
@@ -14,6 +14,10 @@ import (
|
||||
func listPurchasesCmd() *cobra.Command {
|
||||
var page, maxResults int
|
||||
|
||||
var platformValue string
|
||||
|
||||
var platform appstore.Platform
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "list-purchases",
|
||||
Short: "List apps owned by the authenticated App Store account",
|
||||
@@ -29,7 +33,10 @@ func listPurchasesCmd() *cobra.Command {
|
||||
return fmt.Errorf("max results must not exceed %d", appstore.MaxOwnedAppsLimit)
|
||||
}
|
||||
|
||||
return nil
|
||||
var err error
|
||||
platform, err = appstore.ParsePlatform(platformValue)
|
||||
|
||||
return err
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
var lastErr error
|
||||
@@ -54,9 +61,10 @@ func listPurchasesCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
output, err := dependencies.AppStore.OwnedApps(appstore.OwnedAppsInput{
|
||||
Account: acc,
|
||||
Page: page,
|
||||
Limit: maxResults,
|
||||
Account: acc,
|
||||
Page: page,
|
||||
Limit: maxResults,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -86,6 +94,7 @@ func listPurchasesCmd() *cobra.Command {
|
||||
|
||||
cmd.Flags().IntVarP(&maxResults, "max-results", "l", appstore.DefaultOwnedAppsLimit, "maximum number of apps to return per page")
|
||||
cmd.Flags().IntVarP(&page, "page", "p", 1, "page of owned apps to return")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Filter by platform: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -2,11 +2,43 @@ package cmd
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("List Purchases command", func() {
|
||||
DescribeTable("passes the platform filter to owned apps",
|
||||
func(value string, expected appstore.Platform) {
|
||||
store := &fakePurchasesAppStore{}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.AppStore = store
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
cmd := listPurchasesCmd()
|
||||
cmd.SetArgs([]string{"--platform", value})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.input.Platform).To(Equal(expected))
|
||||
},
|
||||
Entry("all platforms by default", "", appstore.Platform("")),
|
||||
Entry("iOS alias", "ios", appstore.PlatformIPhone),
|
||||
Entry("iPadOS alias", "ipados", appstore.PlatformIPad),
|
||||
Entry("tvOS alias", "tvos", appstore.PlatformAppleTV),
|
||||
Entry("visionOS", "visionos", appstore.PlatformVisionOS),
|
||||
Entry("macOS", "macos", appstore.PlatformMacOS),
|
||||
)
|
||||
|
||||
DescribeTable("rejects an invalid platform before accessing the account", func(value string) {
|
||||
cmd := listPurchasesCmd()
|
||||
Expect(cmd.Flags().Set("platform", value)).To(Succeed())
|
||||
Expect(cmd.PreRunE(cmd, nil)).To(MatchError(ContainSubstring("invalid platform")))
|
||||
},
|
||||
Entry("invalid value", "invalid"),
|
||||
Entry("unknown is output only", "unknown"),
|
||||
Entry("uppercase unknown", "UNKNOWN"),
|
||||
)
|
||||
|
||||
It("uses the pagination defaults", func() {
|
||||
cmd := listPurchasesCmd()
|
||||
|
||||
@@ -39,3 +71,18 @@ var _ = Describe("List Purchases command", func() {
|
||||
Expect(cmd.Name()).To(Equal("list-purchases"))
|
||||
})
|
||||
})
|
||||
|
||||
type fakePurchasesAppStore struct {
|
||||
appstore.AppStore
|
||||
input appstore.OwnedAppsInput
|
||||
}
|
||||
|
||||
func (*fakePurchasesAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, nil
|
||||
}
|
||||
|
||||
func (s *fakePurchasesAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
s.input = input
|
||||
|
||||
return appstore.OwnedAppsOutput{}, nil
|
||||
}
|
||||
+2
-2
@@ -14,7 +14,7 @@ func searchCmd() *cobra.Command {
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "search <term>",
|
||||
Short: "Search for iOS, iPadOS, tvOS, and visionOS apps available on the App Store",
|
||||
Short: "Search for iOS, iPadOS, tvOS, visionOS, and macOS apps available on the App Store",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
@@ -47,7 +47,7 @@ func searchCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&limit, "limit", "l", 5, "maximum amount of search results to retrieve; visionOS supports up to 12")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), or visionos")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
)
|
||||
|
||||
// prepareStateDirectory resolves and migrates session storage before it is opened.
|
||||
func prepareStateDirectory(os operatingsystem.OperatingSystem, homeDirectory string) (string, error) {
|
||||
legacyDirectory := filepath.Join(homeDirectory, ConfigDirectoryName)
|
||||
stateDirectory := legacyDirectory
|
||||
|
||||
for _, variable := range []string{"XDG_STATE_HOME", "XDG_DATA_HOME"} {
|
||||
if base := os.Getenv(variable); filepath.IsAbs(base) {
|
||||
stateDirectory = filepath.Join(base, "ipatool")
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
info, err := os.Stat(legacyDirectory)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return "", fmt.Errorf("could not read legacy state directory metadata: %w", err)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
if !info.IsDir() {
|
||||
return "", fmt.Errorf("legacy state path is not a directory: %s", legacyDirectory)
|
||||
}
|
||||
// Never merge sessions or move a directory into itself. Keeping the legacy
|
||||
// directory also preserves authentication when migration is unavailable.
|
||||
relative, err := filepath.Rel(legacyDirectory, stateDirectory)
|
||||
if err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
|
||||
if _, err := os.Stat(stateDirectory); err == nil || !os.IsNotExist(err) {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(stateDirectory), 0700); err != nil {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
// Rename keeps cookies and encrypted credentials together, with their
|
||||
// existing permissions. Cross-filesystem moves fall back to legacy storage.
|
||||
if err := os.Rename(legacyDirectory, stateDirectory); err != nil {
|
||||
return legacyDirectory, nil
|
||||
}
|
||||
|
||||
return stateDirectory, nil
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(stateDirectory, 0700); err != nil {
|
||||
return "", fmt.Errorf("failed to create state directory: %w", err)
|
||||
}
|
||||
|
||||
return stateDirectory, nil
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("State directory", func() {
|
||||
var home, legacy, target string
|
||||
|
||||
BeforeEach(func() {
|
||||
home = GinkgoT().TempDir()
|
||||
legacy = filepath.Join(home, ConfigDirectoryName)
|
||||
target = filepath.Join(home, "state", "ipatool")
|
||||
GinkgoT().Setenv("XDG_STATE_HOME", filepath.Dir(target))
|
||||
GinkgoT().Setenv("XDG_DATA_HOME", "")
|
||||
})
|
||||
|
||||
DescribeTable("selects the session directory", func(state, data, want string) {
|
||||
for variable, value := range map[string]string{"XDG_STATE_HOME": state, "XDG_DATA_HOME": data} {
|
||||
if value != "" && value != "relative" {
|
||||
value = filepath.Join(home, value)
|
||||
}
|
||||
|
||||
GinkgoT().Setenv(variable, value)
|
||||
}
|
||||
|
||||
got, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(filepath.Join(home, want)))
|
||||
Expect(got).To(BeADirectory())
|
||||
|
||||
if got != legacy {
|
||||
Expect(legacy).ToNot(BeAnExistingFile())
|
||||
}
|
||||
},
|
||||
Entry("defaults to legacy storage", "", "", ConfigDirectoryName),
|
||||
Entry("prefers state storage", "state", "data", "state/ipatool"),
|
||||
Entry("falls back to data storage", "", "data", "data/ipatool"),
|
||||
Entry("ignores a relative state path", "relative", "data", "data/ipatool"),
|
||||
Entry("ignores relative paths", "relative", "relative", ConfigDirectoryName),
|
||||
)
|
||||
|
||||
It("preserves authentication after migration and subsequent startup", func() {
|
||||
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
|
||||
|
||||
openKeyring := func(directory string) keyring.Keyring {
|
||||
ring, err := keyring.Open(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{keyring.FileBackend},
|
||||
ServiceName: KeychainServiceName,
|
||||
FileDir: directory,
|
||||
FilePasswordFunc: keyring.FixedStringPrompt("test-passphrase"),
|
||||
})
|
||||
ExpectWithOffset(1, err).ToNot(HaveOccurred())
|
||||
|
||||
return ring
|
||||
}
|
||||
item := keyring.Item{Key: "account", Data: []byte("existing-session"), Label: KeychainServiceName}
|
||||
Expect(openKeyring(legacy).Set(item)).To(Succeed())
|
||||
|
||||
cookieURL, err := url.Parse("https://apps.apple.com/")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
jar := newCookieJar(legacy)
|
||||
jar.SetCookies(cookieURL, []*http.Cookie{{Name: "session", Value: "existing-cookie", Path: "/", Expires: time.Now().Add(time.Hour)}})
|
||||
Expect(jar.Save()).To(Succeed())
|
||||
|
||||
before, err := os.ReadFile(filepath.Join(legacy, item.Key))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
directory, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(directory).To(Equal(target))
|
||||
|
||||
got, err := openKeyring(directory).Get(item.Key)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got.Data).To(Equal(item.Data))
|
||||
|
||||
after, err := os.ReadFile(filepath.Join(directory, item.Key))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(after).To(Equal(before), "encrypted credentials must remain unchanged")
|
||||
|
||||
cookies := newCookieJar(directory).Cookies(cookieURL)
|
||||
Expect(cookies).To(HaveLen(1))
|
||||
Expect(cookies[0].Name).To(Equal("session"))
|
||||
Expect(cookies[0].Value).To(Equal("existing-cookie"))
|
||||
}
|
||||
|
||||
Expect(legacy).ToNot(BeAnExistingFile())
|
||||
})
|
||||
|
||||
DescribeTable("preserves legacy storage when migration fails", func(mkdirErr, renameErr error) {
|
||||
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(legacy, CookieJarFileName), []byte("session"), 0600)).To(Succeed())
|
||||
|
||||
got, err := prepareStateDirectory(migrationFailureOS{operatingsystem.New(), mkdirErr, renameErr}, home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(legacy))
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(got, CookieJarFileName))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(string(data)).To(Equal("session"))
|
||||
},
|
||||
Entry("parent creation denied", os.ErrPermission, nil),
|
||||
Entry("rename denied", nil, os.ErrPermission),
|
||||
Entry("cross filesystem", nil, errors.New("cross-device link")),
|
||||
)
|
||||
|
||||
It("preserves conflicting sessions and uses legacy storage", func() {
|
||||
for _, directory := range []string{legacy, target} {
|
||||
Expect(os.MkdirAll(directory, 0700)).To(Succeed())
|
||||
Expect(os.WriteFile(filepath.Join(directory, "account"), []byte(directory), 0600)).To(Succeed())
|
||||
}
|
||||
|
||||
got, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(legacy))
|
||||
|
||||
for _, directory := range []string{legacy, target} {
|
||||
data, err := os.ReadFile(filepath.Join(directory, "account"))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(string(data)).To(Equal(directory))
|
||||
}
|
||||
})
|
||||
|
||||
DescribeTable("rejects files at directory paths", func(useLegacy bool) {
|
||||
path := target
|
||||
if useLegacy {
|
||||
path = legacy
|
||||
}
|
||||
|
||||
Expect(os.MkdirAll(filepath.Dir(path), 0700)).To(Succeed())
|
||||
Expect(os.WriteFile(path, []byte("existing file"), 0600)).To(Succeed())
|
||||
|
||||
_, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).To(HaveOccurred())
|
||||
},
|
||||
Entry("legacy", true),
|
||||
Entry("destination", false),
|
||||
)
|
||||
|
||||
It("preserves legacy storage for a nested destination", func() {
|
||||
GinkgoT().Setenv("XDG_STATE_HOME", filepath.Join(legacy, "state"))
|
||||
Expect(os.MkdirAll(legacy, 0700)).To(Succeed())
|
||||
|
||||
got, err := prepareStateDirectory(operatingsystem.New(), home)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(legacy))
|
||||
|
||||
entries, err := os.ReadDir(legacy)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(entries).To(BeEmpty(), "migration must not create directories inside legacy storage")
|
||||
})
|
||||
})
|
||||
|
||||
type migrationFailureOS struct {
|
||||
operatingsystem.OperatingSystem
|
||||
mkdirErr, renameErr error
|
||||
}
|
||||
|
||||
// nolint:wrapcheck
|
||||
func (o migrationFailureOS) MkdirAll(path string, mode os.FileMode) error {
|
||||
if o.mkdirErr != nil {
|
||||
return o.mkdirErr
|
||||
}
|
||||
|
||||
return o.OperatingSystem.MkdirAll(path, mode)
|
||||
}
|
||||
|
||||
func (o migrationFailureOS) Rename(from, to string) error {
|
||||
return o.renameErr
|
||||
}
|
||||
@@ -6,6 +6,7 @@ require (
|
||||
github.com/avast/retry-go v3.0.0+incompatible
|
||||
github.com/blacktop/go-macho v1.1.282
|
||||
github.com/bodgit/sevenzip v1.6.3
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4
|
||||
github.com/byteness/keyring v1.9.0
|
||||
github.com/ebitengine/purego v0.10.2
|
||||
github.com/juju/persistent-cookiejar v1.0.0
|
||||
@@ -29,7 +30,6 @@ require (
|
||||
github.com/blacktop/go-dwarf v1.0.14 // indirect
|
||||
github.com/bodgit/plumbing v1.3.0 // indirect
|
||||
github.com/bodgit/windows v1.0.1 // indirect
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 // indirect
|
||||
github.com/byteness/percent v0.2.2 // indirect
|
||||
github.com/danieljoos/wincred v1.2.3 // indirect
|
||||
|
||||
@@ -93,9 +93,23 @@ func Load(ctx context.Context) (Bundle, error) {
|
||||
}
|
||||
|
||||
func download(ctx context.Context) (Bundle, error) {
|
||||
found, err := downloadFiles(ctx, requiredFiles, "download Apple SAP assets")
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
bundle := bundleFrom(found)
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func downloadFiles(ctx context.Context, specs []fileSpec, operation string) (map[string][]byte, error) {
|
||||
parsed, err := url.Parse(updateURL)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("parse Apple software update URL: %w", err)
|
||||
return nil, fmt.Errorf("parse Apple software update URL: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
@@ -105,17 +119,17 @@ func download(ctx context.Context) (Bundle, error) {
|
||||
|
||||
remote, err := ranger.NewReader(&ranger.HTTPRanger{Client: client, URL: parsed})
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("open Apple software update: %w", err)
|
||||
return nil, fmt.Errorf("open Apple software update: %w", err)
|
||||
}
|
||||
|
||||
length, err := remote.Length()
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("measure Apple software update: %w", err)
|
||||
return nil, fmt.Errorf("measure Apple software update: %w", err)
|
||||
}
|
||||
|
||||
container, err := xar.NewReader(remote, length)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read Apple software update: %w", err)
|
||||
return nil, fmt.Errorf("read Apple software update: %w", err)
|
||||
}
|
||||
|
||||
var payload *xar.File
|
||||
@@ -129,32 +143,32 @@ func download(ctx context.Context) (Bundle, error) {
|
||||
}
|
||||
|
||||
if payload == nil {
|
||||
return Bundle{}, &fs.PathError{Op: "open", Path: payloadName, Err: fs.ErrNotExist}
|
||||
return nil, &fs.PathError{Op: "open", Path: payloadName, Err: fs.ErrNotExist}
|
||||
}
|
||||
|
||||
raw := payload.OpenRaw()
|
||||
if _, err := raw.Seek(payloadBZOffset, io.SeekStart); err != nil {
|
||||
return Bundle{}, fmt.Errorf("seek Apple update payload: %w", err)
|
||||
return nil, fmt.Errorf("seek Apple update payload: %w", err)
|
||||
}
|
||||
|
||||
compressed := io.MultiReader(bytes.NewReader([]byte{'B', 'Z', 'h', '9'}), raw)
|
||||
|
||||
archive := bzip2.NewReader(compressed)
|
||||
if _, err := io.CopyN(io.Discard, archive, payloadCPIO); err != nil {
|
||||
return Bundle{}, fmt.Errorf("seek Apple payload archive: %w", err)
|
||||
return nil, fmt.Errorf("seek Apple payload archive: %w", err)
|
||||
}
|
||||
|
||||
wanted := make(map[string]fileSpec, len(requiredFiles))
|
||||
for _, spec := range requiredFiles {
|
||||
wanted := make(map[string]fileSpec, len(specs))
|
||||
for _, spec := range specs {
|
||||
wanted[spec.path] = spec
|
||||
}
|
||||
|
||||
found := make(map[string][]byte, len(requiredFiles))
|
||||
found := make(map[string][]byte, len(specs))
|
||||
reader := cpio.NewReader(archive)
|
||||
|
||||
for len(found) != len(wanted) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("download Apple SAP assets: %w", err)
|
||||
return nil, fmt.Errorf("%s: %w", operation, err)
|
||||
}
|
||||
|
||||
path, body, err := reader.Next()
|
||||
@@ -163,7 +177,7 @@ func download(ctx context.Context) (Bundle, error) {
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read Apple payload archive: %w", err)
|
||||
return nil, fmt.Errorf("read Apple payload archive: %w", err)
|
||||
}
|
||||
|
||||
spec, ok := wanted[path]
|
||||
@@ -173,18 +187,13 @@ func download(ctx context.Context) (Bundle, error) {
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(body, int64(spec.size)+1))
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read %s: %w", spec.name, err)
|
||||
return nil, fmt.Errorf("read %s: %w", spec.name, err)
|
||||
}
|
||||
|
||||
found[spec.name] = data
|
||||
}
|
||||
|
||||
bundle := bundleFrom(found)
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
return found, nil
|
||||
}
|
||||
|
||||
func cacheDirectory() (string, error) {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestAssetsGinkgo(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "SAP Assets Suite")
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const storeAgentCacheDirectory = "apple-storeagent-v1"
|
||||
|
||||
var storeAgentSpec = fileSpec{
|
||||
name: "storeagent",
|
||||
path: "./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Resources/storeagent",
|
||||
size: 2580176,
|
||||
digest: mustDigest("70ce036f9dbcbc04db9511ebd08de0dd3cbc35ccc9d44b089c90170cb5453c59"),
|
||||
}
|
||||
|
||||
// LoadStoreAgent loads the pinned StoreAgent image from its separate cache or Apple payload.
|
||||
func LoadStoreAgent(ctx context.Context) ([]byte, error) {
|
||||
directory, err := storeAgentDirectory()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
path := filepath.Join(directory, storeAgentSpec.name)
|
||||
if data, err := readStoreAgent(path); err == nil {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
files, err := downloadFiles(ctx, []fileSpec{storeAgentSpec}, "download Apple StoreAgent asset")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data := files[storeAgentSpec.name]
|
||||
if err := VerifyStoreAgent(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
return nil, fmt.Errorf("create StoreAgent asset cache: %w", err)
|
||||
}
|
||||
|
||||
if err := replaceFile(path, data); err != nil {
|
||||
return nil, fmt.Errorf("cache Apple StoreAgent asset: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func storeAgentDirectory() (string, error) {
|
||||
root, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("find user cache directory: %w", err)
|
||||
}
|
||||
|
||||
return filepath.Join(root, "ipatool", "sap", storeAgentCacheDirectory), nil
|
||||
}
|
||||
|
||||
func readStoreAgent(path string) ([]byte, error) {
|
||||
data, err := readCacheFile(path, storeAgentSpec.size)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read cached Apple StoreAgent asset: %w", err)
|
||||
}
|
||||
|
||||
if err := VerifyStoreAgent(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// VerifyStoreAgent verifies the image profile required by the StoreAgent runtime.
|
||||
func VerifyStoreAgent(data []byte) error {
|
||||
if len(data) != storeAgentSpec.size {
|
||||
return fmt.Errorf("apple StoreAgent asset has size %d, expected %d", len(data), storeAgentSpec.size)
|
||||
}
|
||||
|
||||
if sha256.Sum256(data) != storeAgentSpec.digest {
|
||||
return fmt.Errorf("apple StoreAgent asset failed integrity verification")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("StoreAgent asset profile", func() {
|
||||
It("pins the verified Apple payload asset", func() {
|
||||
Expect(storeAgentSpec.name).To(Equal("storeagent"))
|
||||
Expect(storeAgentSpec.path).To(Equal("./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Resources/storeagent"))
|
||||
Expect(storeAgentSpec.size).To(Equal(2580176))
|
||||
Expect(storeAgentSpec.digest).To(Equal(mustDigest("70ce036f9dbcbc04db9511ebd08de0dd3cbc35ccc9d44b089c90170cb5453c59")))
|
||||
})
|
||||
|
||||
It("rejects an asset with the wrong size", func() {
|
||||
Expect(VerifyStoreAgent(nil)).To(MatchError(ContainSubstring("has size 0, expected 2580176")))
|
||||
})
|
||||
|
||||
It("rejects an asset with the wrong digest", func() {
|
||||
data := bytes.Repeat([]byte{0xa5}, storeAgentSpec.size)
|
||||
Expect(sha256.Sum256(data)).NotTo(Equal(storeAgentSpec.digest))
|
||||
Expect(VerifyStoreAgent(data)).To(MatchError("apple StoreAgent asset failed integrity verification"))
|
||||
})
|
||||
|
||||
It("uses a cache namespace separate from ordinary SAP assets", func() {
|
||||
Expect(storeAgentCacheDirectory).NotTo(Equal("apple-assets-v2"))
|
||||
})
|
||||
})
|
||||
@@ -56,76 +56,108 @@ type Machine struct {
|
||||
closed bool
|
||||
}
|
||||
|
||||
type imageSpec struct {
|
||||
name string
|
||||
data []byte
|
||||
base uint64
|
||||
}
|
||||
|
||||
type runtimeOptions struct {
|
||||
extraImages []imageSpec
|
||||
shims shimOptions
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, bundle assets.Bundle) (*Machine, error) {
|
||||
machine, exports, err := openRuntime(ctx, bundle, runtimeOptions{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
machine.entry = entryPoints{
|
||||
initialize: exports["_cp2g1b9ro"],
|
||||
exchange: exports["_Mib5yocT"],
|
||||
sign: exports["_Fc3vhtJDvr"],
|
||||
teardown: exports["_IPaI1oem5iL"],
|
||||
dispose: exports["_jEHf8Xzsv8K"],
|
||||
}
|
||||
|
||||
return machine, nil
|
||||
}
|
||||
|
||||
func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptions) (*Machine, map[string]uint64, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("SAP runtime context is nil")
|
||||
return nil, nil, errors.New("SAP runtime context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
return nil, nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
}
|
||||
|
||||
coreFP, err := machimage.Open("CoreFP", bundle.CoreFP)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open CoreFP image: %w", err)
|
||||
}
|
||||
imageSpecs := make([]imageSpec, 0, 3+len(options.extraImages))
|
||||
imageSpecs = append(imageSpecs,
|
||||
imageSpec{name: "CoreFP", data: bundle.CoreFP, base: coreFPBase},
|
||||
imageSpec{name: "CommerceCore", data: bundle.CommerceCore, base: commerceBase},
|
||||
imageSpec{name: "CommerceKit", data: bundle.CommerceKit, base: kitBase},
|
||||
)
|
||||
imageSpecs = append(imageSpecs, options.extraImages...)
|
||||
|
||||
commerceCore, err := machimage.Open("CommerceCore", bundle.CommerceCore)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open CommerceCore image: %w", err)
|
||||
}
|
||||
images := make(map[string]*machimage.Image, len(imageSpecs))
|
||||
|
||||
commerceKit, err := machimage.Open("CommerceKit", bundle.CommerceKit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open CommerceKit image: %w", err)
|
||||
for _, spec := range imageSpecs {
|
||||
image, err := machimage.Open(spec.name, spec.data)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("open %s image: %w", spec.name, err)
|
||||
}
|
||||
|
||||
images[spec.name] = image
|
||||
}
|
||||
|
||||
exports := make(map[string]uint64)
|
||||
coreExports := make(map[string]uint64, len(coreExportNames))
|
||||
coreFP := images["CoreFP"]
|
||||
|
||||
for _, name := range coreExportNames {
|
||||
address, err := coreFP.Export(name, coreFPBase)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve CoreFP export %s: %w", name, err)
|
||||
return nil, nil, fmt.Errorf("resolve CoreFP export %s: %w", name, err)
|
||||
}
|
||||
|
||||
exports[name] = address
|
||||
coreExports[name] = address
|
||||
}
|
||||
|
||||
commerceCore := images["CommerceCore"]
|
||||
macAddress, err := commerceCore.Export("_get_mac_address", commerceBase)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve CommerceCore MAC address export: %w", err)
|
||||
return nil, nil, fmt.Errorf("resolve CommerceCore MAC address export: %w", err)
|
||||
}
|
||||
|
||||
exports["_get_mac_address"] = macAddress
|
||||
|
||||
entryNames := []string{
|
||||
commerceKit := images["CommerceKit"]
|
||||
for _, name := range []string{
|
||||
"_cp2g1b9ro",
|
||||
"_Mib5yocT",
|
||||
"_Fc3vhtJDvr",
|
||||
"_IPaI1oem5iL",
|
||||
"_jEHf8Xzsv8K",
|
||||
}
|
||||
resolvedEntries := make(map[string]uint64, len(entryNames))
|
||||
|
||||
for _, name := range entryNames {
|
||||
} {
|
||||
address, err := commerceKit.Export(name, kitBase)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve CommerceKit export %s: %w", name, err)
|
||||
return nil, nil, fmt.Errorf("resolve CommerceKit export %s: %w", name, err)
|
||||
}
|
||||
|
||||
exports[name] = address
|
||||
resolvedEntries[name] = address
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
return nil, nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
}
|
||||
|
||||
engine, err := unicorn.New(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create Unicorn engine: %w", err)
|
||||
return nil, nil, fmt.Errorf("create Unicorn engine: %w", err)
|
||||
}
|
||||
|
||||
machine := &Machine{engine: engine}
|
||||
@@ -147,17 +179,17 @@ func Open(ctx context.Context, bundle assets.Bundle) (*Machine, error) {
|
||||
{stackBase, stackSize},
|
||||
} {
|
||||
if err := engine.MemMap(region.address, region.size); err != nil {
|
||||
return nil, fmt.Errorf("map SAP guest memory at %#x: %w", region.address, err)
|
||||
return nil, nil, fmt.Errorf("map SAP guest memory at %#x: %w", region.address, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := engine.MemWrite(returnAddress, []byte{0xF4}); err != nil {
|
||||
return nil, fmt.Errorf("write SAP guest return instruction: %w", err)
|
||||
return nil, nil, fmt.Errorf("write SAP guest return instruction: %w", err)
|
||||
}
|
||||
|
||||
machine.services, err = newShims(engine, coreExports, bundle.CoreFPICXS)
|
||||
machine.services, err = newShimsWithOptions(engine, coreExports, bundle.CoreFPICXS, options.shims)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
resolver := func(name string) (uint64, error) {
|
||||
@@ -167,33 +199,21 @@ func Open(ctx context.Context, bundle assets.Bundle) (*Machine, error) {
|
||||
|
||||
return machine.services.resolve(name)
|
||||
}
|
||||
for _, item := range []struct {
|
||||
image *machimage.Image
|
||||
base uint64
|
||||
}{
|
||||
{coreFP, coreFPBase},
|
||||
{commerceCore, commerceBase},
|
||||
{commerceKit, kitBase},
|
||||
} {
|
||||
if err := item.image.Relocate(item.base, resolver); err != nil {
|
||||
return nil, fmt.Errorf("relocate SAP guest image: %w", err)
|
||||
|
||||
for _, spec := range imageSpecs {
|
||||
image := images[spec.name]
|
||||
if err := image.Relocate(spec.base, resolver); err != nil {
|
||||
return nil, nil, fmt.Errorf("relocate SAP guest image: %w", err)
|
||||
}
|
||||
|
||||
if err := item.image.Load(engine); err != nil {
|
||||
return nil, fmt.Errorf("load SAP guest image: %w", err)
|
||||
if err := image.Load(engine); err != nil {
|
||||
return nil, nil, fmt.Errorf("load SAP guest image: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
machine.entry = entryPoints{
|
||||
initialize: resolvedEntries["_cp2g1b9ro"],
|
||||
exchange: resolvedEntries["_Mib5yocT"],
|
||||
sign: resolvedEntries["_Fc3vhtJDvr"],
|
||||
teardown: resolvedEntries["_IPaI1oem5iL"],
|
||||
dispose: resolvedEntries["_jEHf8Xzsv8K"],
|
||||
}
|
||||
ready = true
|
||||
|
||||
return machine, nil
|
||||
return machine, exports, nil
|
||||
}
|
||||
|
||||
func (m *Machine) Initialize(hardwareID []byte) (uint64, error) {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestMachineGinkgo(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "SAP Machine Suite")
|
||||
}
|
||||
@@ -33,6 +33,10 @@ type freeBlock struct {
|
||||
size uint64
|
||||
}
|
||||
|
||||
type shimOptions struct {
|
||||
zeroReturnAliases []string
|
||||
}
|
||||
|
||||
type shims struct {
|
||||
engine *unicorn.Engine
|
||||
hook *unicorn.Hook
|
||||
@@ -52,6 +56,10 @@ type shims struct {
|
||||
}
|
||||
|
||||
func newShims(engine *unicorn.Engine, coreExports map[string]uint64, icxs []byte) (*shims, error) {
|
||||
return newShimsWithOptions(engine, coreExports, icxs, shimOptions{})
|
||||
}
|
||||
|
||||
func newShimsWithOptions(engine *unicorn.Engine, coreExports map[string]uint64, icxs []byte, options shimOptions) (*shims, error) {
|
||||
if err := engine.MemMap(shimBase, shimSize); err != nil {
|
||||
return nil, fmt.Errorf("map guest service area: %w", err)
|
||||
}
|
||||
@@ -74,6 +82,10 @@ func newShims(engine *unicorn.Engine, coreExports map[string]uint64, icxs []byte
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.addAliases(options.zeroReturnAliases, s.returnZero); err != nil {
|
||||
return nil, fmt.Errorf("register profile guest services: %w", err)
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
s.hook, err = engine.AddCodeHook(shimBase, shimBase+shimCodeSize-1, s.dispatch)
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
)
|
||||
|
||||
const (
|
||||
storeAgentBase = uint64(0x00001000c0000000)
|
||||
storeAgentGlobalInit = storeAgentBase + 0x0c5fc0
|
||||
storeAgentSessionInit = storeAgentBase + 0x0debd0
|
||||
storeAgentDecryptEntry = storeAgentBase + 0x0ee700
|
||||
storeAgentSessionClose = storeAgentBase + 0x1212d0
|
||||
storeAgentChunkSize = 0x8000
|
||||
storeAgentSCInfoPath = "/Users/Shared/SC Info"
|
||||
)
|
||||
|
||||
var storeAgentZeroReturnAliases = []string{
|
||||
"_pthread_rwlock_rdlock",
|
||||
"_pthread_rwlock_rdlock$UNIX2003",
|
||||
"_pthread_mutex_init",
|
||||
"_pthread_mutex_destroy",
|
||||
"_pthread_rwlock_destroy",
|
||||
}
|
||||
|
||||
type StoreAgent struct {
|
||||
mu sync.Mutex
|
||||
guest *Machine
|
||||
session uint64
|
||||
decryptEntry uint64
|
||||
closeEntry uint64
|
||||
closed bool
|
||||
}
|
||||
|
||||
func OpenStoreAgent(ctx context.Context, bundle assets.Bundle, hardwareID, dpInfo []byte) (*StoreAgent, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("StoreAgent context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("open StoreAgent runtime: %w", err)
|
||||
}
|
||||
|
||||
image, err := assets.LoadStoreAgent(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load Apple StoreAgent asset: %w", err)
|
||||
}
|
||||
|
||||
return openStoreAgent(ctx, bundle, image, hardwareID, dpInfo)
|
||||
}
|
||||
|
||||
func openStoreAgent(ctx context.Context, bundle assets.Bundle, image, hardwareID, dpInfo []byte) (*StoreAgent, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("StoreAgent context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("open StoreAgent runtime: %w", err)
|
||||
}
|
||||
|
||||
if len(dpInfo) == 0 {
|
||||
return nil, errors.New("StoreAgent dpInfo is empty")
|
||||
}
|
||||
|
||||
if err := assets.VerifyStoreAgent(image); err != nil {
|
||||
return nil, fmt.Errorf("verify Apple StoreAgent profile: %w", err)
|
||||
}
|
||||
|
||||
hardware, err := hardwareBlock(hardwareID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
guest, _, err := openRuntime(ctx, bundle, runtimeOptions{
|
||||
extraImages: []imageSpec{{name: "storeagent", data: image, base: storeAgentBase}},
|
||||
shims: shimOptions{
|
||||
zeroReturnAliases: storeAgentZeroReturnAliases,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("start StoreAgent runtime: %w", err)
|
||||
}
|
||||
|
||||
agent := &StoreAgent{
|
||||
guest: guest,
|
||||
decryptEntry: storeAgentDecryptEntry,
|
||||
closeEntry: storeAgentSessionClose,
|
||||
}
|
||||
complete := false
|
||||
|
||||
defer func() {
|
||||
if !complete {
|
||||
_ = agent.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
globalContext, err := agent.initializeGlobal(hardware)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
agent.session, err = agent.initializeSession(globalContext, dpInfo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
complete = true
|
||||
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
func (s *StoreAgent) initializeGlobal(hardware []byte) (uint32, error) {
|
||||
s.guest.beginCall()
|
||||
defer s.guest.clearScratch()
|
||||
|
||||
hardwareAddress, err := s.guest.scratch(hardware, uint64(len(hardware)))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
path := append([]byte(storeAgentSCInfoPath), 0)
|
||||
pathAddress, err := s.guest.scratch(path, uint64(len(path)))
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
contextField, err := s.guest.scratch(nil, 4)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
status, err := s.guest.invoke(storeAgentGlobalInit, 0, hardwareAddress, pathAddress, contextField)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("initialize StoreAgent global context: %w", err)
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return 0, fmt.Errorf("StoreAgent global initialization returned %d", int32(status))
|
||||
}
|
||||
|
||||
value, err := s.guest.readUint32(contextField)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if value == 0 {
|
||||
return 0, errors.New("StoreAgent global initialization returned a null context")
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (s *StoreAgent) initializeSession(globalContext uint32, dpInfo []byte) (uint64, error) {
|
||||
s.guest.beginCall()
|
||||
defer s.guest.clearScratch()
|
||||
|
||||
dpInfoAddress, err := s.guest.scratch(dpInfo, uint64(len(dpInfo)))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
sessionField, err := s.guest.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
status, err := s.guest.invoke(
|
||||
storeAgentSessionInit,
|
||||
uint64(globalContext),
|
||||
dpInfoAddress,
|
||||
uint64(len(dpInfo)),
|
||||
sessionField,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("initialize StoreAgent session: %w", err)
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return 0, fmt.Errorf("StoreAgent session initialization returned %d", int32(status))
|
||||
}
|
||||
|
||||
session, err := s.guest.readUint64(sessionField)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if session == 0 {
|
||||
return 0, errors.New("StoreAgent session initialization returned a null session")
|
||||
}
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *StoreAgent) Decrypt(ctx context.Context, dst io.Writer, src io.Reader) (int64, error) {
|
||||
if s == nil {
|
||||
return 0, errors.New("StoreAgent is nil")
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.closed {
|
||||
return 0, errors.New("StoreAgent is closed")
|
||||
}
|
||||
|
||||
if ctx == nil {
|
||||
return 0, errors.New("StoreAgent decryption context is nil")
|
||||
}
|
||||
|
||||
if dst == nil {
|
||||
return 0, errors.New("StoreAgent decryption destination is nil")
|
||||
}
|
||||
|
||||
if src == nil {
|
||||
return 0, errors.New("StoreAgent decryption source is nil")
|
||||
}
|
||||
|
||||
return decryptStream(ctx, dst, src, s.decryptChunk)
|
||||
}
|
||||
|
||||
func (s *StoreAgent) decryptChunk(data []byte) error {
|
||||
s.guest.beginCall()
|
||||
defer s.guest.clearScratch()
|
||||
|
||||
address, err := s.guest.scratch(data, uint64(len(data)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
status, err := s.guest.invoke(
|
||||
s.decryptEntry,
|
||||
s.session,
|
||||
address,
|
||||
uint64(len(data)),
|
||||
address,
|
||||
0,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decrypt StoreAgent chunk: %w", err)
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return fmt.Errorf("StoreAgent decryption returned %d", int32(status))
|
||||
}
|
||||
|
||||
if err := s.guest.engine.MemReadInto(data, address); err != nil {
|
||||
return fmt.Errorf("read decrypted StoreAgent chunk: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func decryptStream(ctx context.Context, dst io.Writer, src io.Reader, decrypt func([]byte) error) (int64, error) {
|
||||
buffer := make([]byte, storeAgentChunkSize)
|
||||
|
||||
var written int64
|
||||
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return written, fmt.Errorf("decrypt StoreAgent stream: %w", err)
|
||||
}
|
||||
|
||||
count, readErr := io.ReadFull(src, buffer)
|
||||
if count != 0 {
|
||||
chunk := buffer[:count]
|
||||
if err := decrypt(chunk); err != nil {
|
||||
return written, err
|
||||
}
|
||||
|
||||
n, err := dst.Write(chunk)
|
||||
written += int64(n)
|
||||
|
||||
if err != nil {
|
||||
return written, fmt.Errorf("write decrypted StoreAgent stream: %w", err)
|
||||
}
|
||||
|
||||
if n != len(chunk) {
|
||||
return written, fmt.Errorf("write decrypted StoreAgent stream: %w", io.ErrShortWrite)
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case readErr == nil:
|
||||
continue
|
||||
case errors.Is(readErr, io.EOF), errors.Is(readErr, io.ErrUnexpectedEOF):
|
||||
return written, nil
|
||||
default:
|
||||
return written, fmt.Errorf("read encrypted StoreAgent stream: %w", readErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StoreAgent) Close() error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.closed = true
|
||||
|
||||
var errs []error
|
||||
|
||||
if s.guest != nil && s.session != 0 {
|
||||
session := s.session
|
||||
s.session = 0
|
||||
|
||||
status, err := s.guest.invoke(s.closeEntry, session)
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Errorf("close StoreAgent session: %w", err))
|
||||
} else if int32(status) != 0 {
|
||||
errs = append(errs, fmt.Errorf("StoreAgent session close returned %d", int32(status)))
|
||||
}
|
||||
}
|
||||
|
||||
if s.guest != nil {
|
||||
errs = append(errs, s.guest.Close())
|
||||
s.guest = nil
|
||||
}
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("StoreAgent", func() {
|
||||
Describe("profile", func() {
|
||||
It("pins the verified image base and entry offsets", func() {
|
||||
Expect(storeAgentBase).To(Equal(uint64(0x00001000c0000000)))
|
||||
Expect(storeAgentGlobalInit).To(Equal(storeAgentBase + 0x0c5fc0))
|
||||
Expect(storeAgentSessionInit).To(Equal(storeAgentBase + 0x0debd0))
|
||||
Expect(storeAgentDecryptEntry).To(Equal(storeAgentBase + 0x0ee700))
|
||||
Expect(storeAgentSessionClose).To(Equal(storeAgentBase + 0x1212d0))
|
||||
})
|
||||
|
||||
It("re-verifies the pinned image before opening the runtime", func() {
|
||||
_, err := openStoreAgent(context.Background(), assets.Bundle{}, []byte("wrong image"), []byte{1}, []byte{1})
|
||||
Expect(err).To(MatchError(ContainSubstring("verify Apple StoreAgent profile")))
|
||||
Expect(err).To(MatchError(ContainSubstring("has size")))
|
||||
})
|
||||
|
||||
It("adds only the StoreAgent synchronization aliases", func() {
|
||||
machine := newGinkgoServiceMachine(shimOptions{zeroReturnAliases: storeAgentZeroReturnAliases})
|
||||
|
||||
for _, name := range storeAgentZeroReturnAliases {
|
||||
address, ok := machine.services.symbols[name]
|
||||
Expect(ok).To(BeTrue(), name)
|
||||
Expect(machine.invoke(address)).To(Equal(uint64(0)))
|
||||
}
|
||||
})
|
||||
|
||||
It("does not add StoreAgent aliases to the default SAP profile", func() {
|
||||
machine := newGinkgoServiceMachine(shimOptions{})
|
||||
address, err := machine.services.resolve("_pthread_mutex_init")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
_, err = machine.invoke(address)
|
||||
Expect(err).To(MatchError(ContainSubstring("unsupported import _pthread_mutex_init")))
|
||||
})
|
||||
})
|
||||
|
||||
Describe("streaming decryption", func() {
|
||||
It("uses full 0x8000 chunks and a final partial chunk", func() {
|
||||
input := bytes.Repeat([]byte{0x3c}, 2*storeAgentChunkSize+17)
|
||||
var output bytes.Buffer
|
||||
var sizes []int
|
||||
|
||||
written, err := decryptStream(context.Background(), &output, bytes.NewReader(input), func(chunk []byte) error {
|
||||
sizes = append(sizes, len(chunk))
|
||||
for index := range chunk {
|
||||
chunk[index] ^= 0xff
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(written).To(Equal(int64(len(input))))
|
||||
Expect(sizes).To(Equal([]int{storeAgentChunkSize, storeAgentChunkSize, 17}))
|
||||
Expect(output.Bytes()).To(Equal(bytes.Repeat([]byte{0xc3}, len(input))))
|
||||
})
|
||||
|
||||
It("does not invoke the decryptor for an empty stream", func() {
|
||||
called := false
|
||||
written, err := decryptStream(context.Background(), io.Discard, bytes.NewReader(nil), func([]byte) error {
|
||||
called = true
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(written).To(BeZero())
|
||||
Expect(called).To(BeFalse())
|
||||
})
|
||||
|
||||
It("writes a partial read before returning its source error", func() {
|
||||
sourceErr := errors.New("source failed")
|
||||
source := io.MultiReader(bytes.NewReader([]byte("partial")), errorReader{err: sourceErr})
|
||||
var output bytes.Buffer
|
||||
|
||||
written, err := decryptStream(context.Background(), &output, source, func(chunk []byte) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
Expect(written).To(Equal(int64(len("partial"))))
|
||||
Expect(output.String()).To(Equal("partial"))
|
||||
Expect(err).To(MatchError(ContainSubstring(sourceErr.Error())))
|
||||
})
|
||||
|
||||
It("stops before the next chunk when the context is canceled", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
input := bytes.Repeat([]byte{1}, 2*storeAgentChunkSize)
|
||||
calls := 0
|
||||
|
||||
written, err := decryptStream(ctx, io.Discard, bytes.NewReader(input), func([]byte) error {
|
||||
calls++
|
||||
cancel()
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
Expect(calls).To(Equal(1))
|
||||
Expect(written).To(Equal(int64(storeAgentChunkSize)))
|
||||
Expect(err).To(MatchError(ContainSubstring(context.Canceled.Error())))
|
||||
})
|
||||
|
||||
It("returns decryptor errors without writing the failed chunk", func() {
|
||||
decryptErr := errors.New("decrypt failed")
|
||||
var output bytes.Buffer
|
||||
|
||||
written, err := decryptStream(context.Background(), &output, bytes.NewReader([]byte("encrypted")), func([]byte) error {
|
||||
return decryptErr
|
||||
})
|
||||
|
||||
Expect(written).To(BeZero())
|
||||
Expect(output.Len()).To(BeZero())
|
||||
Expect(err).To(MatchError(decryptErr))
|
||||
})
|
||||
|
||||
It("reports short writes", func() {
|
||||
written, err := decryptStream(context.Background(), shortWriter{}, bytes.NewReader([]byte("encrypted")), func([]byte) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
Expect(written).To(Equal(int64(1)))
|
||||
Expect(err).To(MatchError(ContainSubstring(io.ErrShortWrite.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
It("closes the session and machine idempotently", func() {
|
||||
machine := newGinkgoServiceMachine(shimOptions{})
|
||||
var closedSession uint64
|
||||
closeEntry, err := machine.services.addFunction("test.storeagent.close", func() error {
|
||||
value, argumentErr := machine.services.argument(0)
|
||||
if argumentErr != nil {
|
||||
return argumentErr
|
||||
}
|
||||
|
||||
closedSession = value
|
||||
|
||||
return machine.services.setResult(0)
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
agent := &StoreAgent{guest: machine, session: 0x1234, closeEntry: closeEntry}
|
||||
Expect(agent.Close()).To(Succeed())
|
||||
Expect(closedSession).To(Equal(uint64(0x1234)))
|
||||
Expect(agent.session).To(BeZero())
|
||||
Expect(agent.guest).To(BeNil())
|
||||
Expect(agent.Close()).To(Succeed())
|
||||
})
|
||||
})
|
||||
|
||||
type errorReader struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (r errorReader) Read([]byte) (int, error) {
|
||||
return 0, r.err
|
||||
}
|
||||
|
||||
type shortWriter struct{}
|
||||
|
||||
func (shortWriter) Write([]byte) (int, error) {
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
func newGinkgoServiceMachine(options shimOptions) *Machine {
|
||||
engine, err := unicorn.New(context.Background())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
for _, region := range []struct {
|
||||
address uint64
|
||||
size uint64
|
||||
}{
|
||||
{returnAddress, pageSize},
|
||||
{scratchBase, scratchSize},
|
||||
{heapBase, heapSize},
|
||||
{stackBase, stackSize},
|
||||
} {
|
||||
Expect(engine.MemMap(region.address, region.size)).To(Succeed())
|
||||
}
|
||||
|
||||
Expect(engine.MemWrite(returnAddress, []byte{0xF4})).To(Succeed())
|
||||
|
||||
services, err := newShimsWithOptions(engine, map[string]uint64{}, nil, options)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
machine := &Machine{engine: engine, services: services}
|
||||
|
||||
DeferCleanup(func() {
|
||||
Expect(machine.Close()).To(Succeed())
|
||||
})
|
||||
|
||||
return machine
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"debug/elf"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -10,61 +12,57 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"time"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maxArtifactSize = 64 << 20
|
||||
|
||||
var artifactHTTPClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
type runtimePaths struct {
|
||||
library string
|
||||
dependencies []string
|
||||
func linuxUsesMusl() bool {
|
||||
return linuxUsesMuslFor("/proc/self/exe", muslLoaderInstalled)
|
||||
}
|
||||
|
||||
func cachedRuntimePaths(ctx context.Context) (runtimePaths, error) {
|
||||
goos := runtime.GOOS
|
||||
if goos == "linux" && linuxUsesMusl() {
|
||||
goos = "linux-musl"
|
||||
func linuxUsesMuslFor(executable string, loaderInstalled func() bool) bool {
|
||||
if interpreter, ok := executableInterpreter(executable); ok {
|
||||
return interpreterUsesMusl(interpreter)
|
||||
}
|
||||
|
||||
selected, err := artifactFor(goos, runtime.GOARCH)
|
||||
return loaderInstalled()
|
||||
}
|
||||
|
||||
// executableInterpreter reads the loader recorded in the executable. Missing PT_INTERP or
|
||||
// an unreadable executable leaves the caller to fall back to the host filesystem heuristic.
|
||||
func executableInterpreter(path string) (string, bool) {
|
||||
file, err := elf.Open(path)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
return "", false
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return runtimePaths{}, fmt.Errorf("locate user cache: %w", err)
|
||||
}
|
||||
|
||||
root := filepath.Join(cache, "ipatool", "unicorn", unicornVersion)
|
||||
paths := runtimePaths{dependencies: make([]string, 0, len(selected.dependencies))}
|
||||
|
||||
for _, dependency := range selected.dependencies {
|
||||
path, err := ensureLibrary(ctx, root, dependency, artifactHTTPClient)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
for _, program := range file.Progs {
|
||||
if program.Type != elf.PT_INTERP {
|
||||
continue
|
||||
}
|
||||
|
||||
paths.dependencies = append(paths.dependencies, path)
|
||||
interpreter, err := io.ReadAll(program.Open())
|
||||
if err != nil || uint64(len(interpreter)) != program.Filesz {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return string(bytes.TrimRight(interpreter, "\x00")), true
|
||||
}
|
||||
|
||||
paths.library, err = ensureLibrary(ctx, root, selected, artifactHTTPClient)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
paths.library, err = prepareRuntimeLibrary(paths.library)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
return paths, nil
|
||||
return "", false
|
||||
}
|
||||
|
||||
func linuxUsesMusl() bool {
|
||||
func interpreterUsesMusl(interpreter string) bool {
|
||||
return strings.HasPrefix(filepath.Base(interpreter), "ld-musl-")
|
||||
}
|
||||
|
||||
// muslLoaderInstalled reports whether a musl loader exists on the host. That only says musl is
|
||||
// available, not that this process uses it, so it is a last resort when the interpreter is
|
||||
// unavailable. glibc distributions package musl for cross compilation, and selecting the
|
||||
// musllinux artifact there loads a second libc into the process.
|
||||
func muslLoaderInstalled() bool {
|
||||
loaders, _ := filepath.Glob("/lib/ld-musl-*.so.1")
|
||||
if len(loaders) != 0 {
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"debug/elf"
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestLibcDetection(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Unicorn Libc Detection Suite")
|
||||
}
|
||||
|
||||
var _ = Describe("Linux libc detection", func() {
|
||||
DescribeTable("classifies interpreter names", func(interpreter string, expected bool) {
|
||||
Expect(interpreterUsesMusl(interpreter)).To(Equal(expected))
|
||||
},
|
||||
Entry("musl amd64", "/lib/ld-musl-x86_64.so.1", true),
|
||||
Entry("musl arm64", "/lib/ld-musl-aarch64.so.1", true),
|
||||
Entry("glibc amd64", "/lib64/ld-linux-x86-64.so.2", false),
|
||||
Entry("glibc arm64", "/lib/ld-linux-aarch64.so.1", false),
|
||||
Entry("glibc under usr", "/usr/lib/ld-linux-x86-64.so.2", false),
|
||||
Entry("empty", "", false),
|
||||
)
|
||||
|
||||
DescribeTable("prefers the executable over installed loaders", func(interpreter string, installed, expected bool) {
|
||||
path := filepath.Join(GinkgoT().TempDir(), "exe")
|
||||
Expect(os.WriteFile(path, libcTestELF(interpreter), 0o600)).To(Succeed())
|
||||
|
||||
actual, ok := executableInterpreter(path)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(actual).To(Equal(interpreter))
|
||||
|
||||
fallbackCalled := false
|
||||
Expect(linuxUsesMuslFor(path, func() bool {
|
||||
fallbackCalled = true
|
||||
|
||||
return installed
|
||||
})).To(Equal(expected))
|
||||
Expect(fallbackCalled).To(BeFalse())
|
||||
},
|
||||
Entry("glibc with musl installed", "/lib64/ld-linux-x86-64.so.2", true, false),
|
||||
Entry("glibc arm64 with musl installed", "/lib/ld-linux-aarch64.so.1", true, false),
|
||||
Entry("musl without a standard loader path", "/custom/ld-musl-x86_64.so.1", false, true),
|
||||
Entry("musl arm64", "/lib/ld-musl-aarch64.so.1", true, true),
|
||||
)
|
||||
|
||||
DescribeTable("falls back when the interpreter is unavailable", func(kind string) {
|
||||
path := filepath.Join(GinkgoT().TempDir(), "exe")
|
||||
switch kind {
|
||||
case "static":
|
||||
Expect(os.WriteFile(path, libcTestELF(""), 0o600)).To(Succeed())
|
||||
case "invalid":
|
||||
Expect(os.WriteFile(path, []byte("not an ELF executable"), 0o600)).To(Succeed())
|
||||
case "truncated":
|
||||
data := libcTestELF("/lib/ld-musl-x86_64.so.1")
|
||||
Expect(os.WriteFile(path, data[:len(data)-4], 0o600)).To(Succeed())
|
||||
}
|
||||
|
||||
interpreter, ok := executableInterpreter(path)
|
||||
Expect(ok).To(BeFalse())
|
||||
Expect(interpreter).To(BeEmpty())
|
||||
for _, installed := range []bool{false, true} {
|
||||
fallbackCalled := false
|
||||
Expect(linuxUsesMuslFor(path, func() bool {
|
||||
fallbackCalled = true
|
||||
|
||||
return installed
|
||||
})).To(Equal(installed))
|
||||
Expect(fallbackCalled).To(BeTrue())
|
||||
}
|
||||
},
|
||||
Entry("no PT_INTERP", "static"),
|
||||
Entry("executable cannot be opened", "missing"),
|
||||
Entry("invalid ELF", "invalid"),
|
||||
Entry("interpreter cannot be read", "truncated"),
|
||||
)
|
||||
|
||||
It("reads the running Linux executable", func() {
|
||||
if runtime.GOOS != "linux" {
|
||||
Skip("/proc/self/exe is Linux-specific")
|
||||
}
|
||||
interpreter, ok := executableInterpreter("/proc/self/exe")
|
||||
if !ok {
|
||||
Skip("running executable has no readable PT_INTERP")
|
||||
}
|
||||
Expect(filepath.IsAbs(interpreter)).To(BeTrue())
|
||||
Expect(linuxUsesMusl()).To(Equal(interpreterUsesMusl(interpreter)))
|
||||
})
|
||||
})
|
||||
|
||||
// libcTestELF builds an ELF64 executable with one program header. An empty
|
||||
// interpreter uses PT_NULL to model a static executable without PT_INTERP.
|
||||
func libcTestELF(interpreter string) []byte {
|
||||
const headerSize, programSize = 64, 56
|
||||
data := make([]byte, headerSize+programSize)
|
||||
copy(data, "\x7fELF")
|
||||
data[elf.EI_CLASS] = byte(elf.ELFCLASS64)
|
||||
data[elf.EI_DATA] = byte(elf.ELFDATA2LSB)
|
||||
data[elf.EI_VERSION] = byte(elf.EV_CURRENT)
|
||||
binary.LittleEndian.PutUint16(data[16:], uint16(elf.ET_EXEC))
|
||||
binary.LittleEndian.PutUint16(data[18:], uint16(elf.EM_X86_64))
|
||||
binary.LittleEndian.PutUint32(data[20:], uint32(elf.EV_CURRENT))
|
||||
binary.LittleEndian.PutUint64(data[32:], headerSize) // e_phoff
|
||||
binary.LittleEndian.PutUint16(data[52:], headerSize) // e_ehsize
|
||||
binary.LittleEndian.PutUint16(data[54:], programSize) // e_phentsize
|
||||
binary.LittleEndian.PutUint16(data[56:], 1) // e_phnum
|
||||
|
||||
if interpreter != "" {
|
||||
binary.LittleEndian.PutUint32(data[headerSize:], uint32(elf.PT_INTERP))
|
||||
binary.LittleEndian.PutUint64(data[headerSize+8:], headerSize+programSize) // p_offset
|
||||
binary.LittleEndian.PutUint64(data[headerSize+32:], uint64(len(interpreter)+1)) // p_filesz
|
||||
data = append(data, interpreter...)
|
||||
data = append(data, 0)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//go:build !ios
|
||||
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
var artifactHTTPClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
type runtimePaths struct {
|
||||
library string
|
||||
dependencies []string
|
||||
}
|
||||
|
||||
func cachedRuntimePaths(ctx context.Context) (runtimePaths, error) {
|
||||
goos := runtime.GOOS
|
||||
if goos == "linux" && linuxUsesMusl() {
|
||||
goos = "linux-musl"
|
||||
}
|
||||
|
||||
selected, err := artifactFor(goos, runtime.GOARCH)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return runtimePaths{}, fmt.Errorf("locate user cache: %w", err)
|
||||
}
|
||||
|
||||
root := filepath.Join(cache, "ipatool", "unicorn", unicornVersion)
|
||||
paths := runtimePaths{dependencies: make([]string, 0, len(selected.dependencies))}
|
||||
|
||||
for _, dependency := range selected.dependencies {
|
||||
path, err := ensureLibrary(ctx, root, dependency, artifactHTTPClient)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
paths.dependencies = append(paths.dependencies, path)
|
||||
}
|
||||
|
||||
paths.library, err = ensureLibrary(ctx, root, selected, artifactHTTPClient)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
paths.library, err = prepareRuntimeLibrary(paths.library)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
return paths, nil
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// iOS builds statically link Unicorn because the desktop runtime artifacts
|
||||
// cannot be loaded on iOS. tools/build-ios.sh exports its symbols for purego.
|
||||
func openLibrary(ctx context.Context) (library, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return library{}, fmt.Errorf("load Unicorn library: %w", err)
|
||||
}
|
||||
|
||||
if _, err := purego.Dlsym(purego.RTLD_DEFAULT, "uc_version"); err != nil {
|
||||
return library{}, fmt.Errorf("unicorn is not linked; build with tools/build-ios.sh: %w", err)
|
||||
}
|
||||
|
||||
return library{handle: purego.RTLD_DEFAULT, close: func() error { return nil }}, nil
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build darwin || linux
|
||||
//go:build (darwin && !ios) || linux
|
||||
|
||||
package unicorn
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build !windows || !arm64
|
||||
//go:build !ios && (!windows || !arm64)
|
||||
|
||||
package unicorn
|
||||
|
||||
|
||||
+16
-6
@@ -7,12 +7,13 @@ import (
|
||||
)
|
||||
|
||||
type App struct {
|
||||
ID int64 `json:"trackId,omitempty"`
|
||||
BundleID string `json:"bundleId,omitempty"`
|
||||
Name string `json:"trackName,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Price float64 `json:"price,omitempty"`
|
||||
PurchaseDate time.Time `json:"purchaseDate,omitzero"`
|
||||
ID int64 `json:"trackId,omitempty"`
|
||||
BundleID string `json:"bundleId,omitempty"`
|
||||
Name string `json:"trackName,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Price float64 `json:"price,omitempty"`
|
||||
PurchaseDate time.Time `json:"purchaseDate,omitzero"`
|
||||
Platforms []Platform `json:"platforms,omitzero"`
|
||||
}
|
||||
|
||||
type VersionHistoryInfo struct {
|
||||
@@ -47,4 +48,13 @@ func (a App) MarshalZerologObject(event *zerolog.Event) {
|
||||
if !a.PurchaseDate.IsZero() {
|
||||
event.Time("purchaseDate", a.PurchaseDate)
|
||||
}
|
||||
|
||||
if a.Platforms != nil {
|
||||
platforms := make([]string, len(a.Platforms))
|
||||
for index, platform := range a.Platforms {
|
||||
platforms[index] = string(platform)
|
||||
}
|
||||
|
||||
event.Strs("platforms", platforms)
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,22 @@ var _ = Describe("App", func() {
|
||||
Expect(out).ToNot(HaveKey("purchaseDate"))
|
||||
})
|
||||
|
||||
DescribeTable("serializes purchase platforms as an array",
|
||||
func(platforms []Platform, expected string) {
|
||||
app := App{ID: 42, Platforms: platforms}
|
||||
data, err := json.Marshal(app)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(string(data)).To(ContainSubstring(`"platforms":` + expected))
|
||||
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
logger := zerolog.New(buffer)
|
||||
logger.Log().Object("app", app).Send()
|
||||
Expect(buffer.String()).To(ContainSubstring(`"platforms":` + expected))
|
||||
},
|
||||
Entry("multiple platforms", []Platform{PlatformIPhone, PlatformIPad, PlatformMacOS}, `["iphone","ipad","macos"]`),
|
||||
Entry("unknown platforms", []Platform{PlatformUnknown}, `["unknown"]`),
|
||||
)
|
||||
|
||||
It("formats ipa name correctly", func() {
|
||||
app := App{
|
||||
ID: 42,
|
||||
@@ -94,5 +110,6 @@ var _ = Describe("App", func() {
|
||||
}
|
||||
|
||||
Expect(fileName(app, "1.0")).To(Equal("app.bundle-id1_42_1.0.ipa"))
|
||||
Expect(packageFileName(app, "1.0", PlatformMacOS)).To(Equal("app.bundle-id1_42_1.0.pkg"))
|
||||
})
|
||||
})
|
||||
@@ -25,7 +25,7 @@ type AppStore interface {
|
||||
// Purchase acquires a license for the desired app.
|
||||
// Note: only free apps are supported.
|
||||
Purchase(input PurchaseInput) error
|
||||
// Download downloads the IPA package from the App Store to the desired location.
|
||||
// Download downloads the app package from the App Store to the desired location.
|
||||
Download(input DownloadInput) (DownloadOutput, error)
|
||||
// ReplicateSinf replicates the sinf for the IPA package.
|
||||
ReplicateSinf(input ReplicateSinfInput) error
|
||||
@@ -48,6 +48,7 @@ type appstore struct {
|
||||
bagClient http.Client[bagResult]
|
||||
ownedAppsClient http.Client[[]byte]
|
||||
httpClient http.Client[interface{}]
|
||||
macDecrypterFactory macPackageDecrypterFactory
|
||||
actionSignerFactory ActionSignerFactory
|
||||
authRetrySleep func(time.Duration)
|
||||
machine machine.Machine
|
||||
@@ -74,7 +75,7 @@ func NewAppStore(args Args) AppStore {
|
||||
|
||||
return &appstore{
|
||||
keychain: args.Keychain,
|
||||
loginClient: http.NewClient[loginResult](clientArgs),
|
||||
loginClient: http.NewClient[loginResult](http.Args{CookieJar: args.CookieJar, Authentication: true}),
|
||||
searchClient: http.NewClient[searchResult](clientArgs),
|
||||
purchaseClient: http.NewClient[purchaseResult](clientArgs),
|
||||
downloadClient: http.NewClient[downloadResult](clientArgs),
|
||||
@@ -83,6 +84,7 @@ func NewAppStore(args Args) AppStore {
|
||||
bagClient: http.NewClient[bagResult](clientArgs),
|
||||
ownedAppsClient: http.NewClient[[]byte](clientArgs),
|
||||
httpClient: http.NewClient[interface{}](clientArgs),
|
||||
macDecrypterFactory: defaultMacPackageDecrypterFactory,
|
||||
actionSignerFactory: actionSignerFactory,
|
||||
authRetrySleep: time.Sleep,
|
||||
machine: args.Machine,
|
||||
|
||||
@@ -33,26 +33,20 @@ func (t *appstore) Bag(input BagInput) (BagOutput, error) {
|
||||
}
|
||||
|
||||
func (t *appstore) bag(guid string) (BagOutput, error) {
|
||||
req := t.bagRequest(guid)
|
||||
|
||||
res, err := t.bagClient.Send(req)
|
||||
bag, err := t.fetchURLBag(guid)
|
||||
if err != nil {
|
||||
return BagOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
return BagOutput{}, err
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return BagOutput{}, fmt.Errorf("received unexpected status code: %d", res.StatusCode)
|
||||
}
|
||||
|
||||
version, err := strconv.ParseUint(res.Data.URLBag.SAPVersion, 10, 32)
|
||||
version, err := strconv.ParseUint(bag.SAPVersion, 10, 32)
|
||||
if err != nil {
|
||||
return BagOutput{}, fmt.Errorf("invalid SAP version %q in bag: %w", res.Data.URLBag.SAPVersion, err)
|
||||
return BagOutput{}, fmt.Errorf("invalid SAP version %q in bag: %w", bag.SAPVersion, err)
|
||||
}
|
||||
|
||||
config := SAPConfig{
|
||||
AuthEndpoint: res.Data.URLBag.AuthEndpoint,
|
||||
SetupURL: res.Data.URLBag.SAPSetupEndpoint,
|
||||
CertificateURL: res.Data.URLBag.SAPSetupCertEndpoint,
|
||||
AuthEndpoint: bag.AuthEndpoint,
|
||||
SetupURL: bag.SAPSetupEndpoint,
|
||||
CertificateURL: bag.SAPSetupCertEndpoint,
|
||||
Version: uint32(version),
|
||||
}
|
||||
if err := validateSAPConfig(config); err != nil {
|
||||
@@ -62,12 +56,28 @@ 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.
|
||||
func (t *appstore) fetchURLBag(guid string) (urlBag, error) {
|
||||
res, err := t.bagClient.Send(t.bagRequest(guid))
|
||||
if err != nil {
|
||||
return urlBag{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return urlBag{}, fmt.Errorf("received unexpected status code: %d", res.StatusCode)
|
||||
}
|
||||
|
||||
return res.Data.URLBag, nil
|
||||
}
|
||||
|
||||
type bagResult struct {
|
||||
URLBag urlBag `plist:"urlBag,omitempty"`
|
||||
}
|
||||
|
||||
type urlBag struct {
|
||||
AuthEndpoint string `plist:"authenticateAccount,omitempty"`
|
||||
RedownloadEndpoint string `plist:"redownloadProduct,omitempty"`
|
||||
UpdateEndpoint string `plist:"updateProduct,omitempty"`
|
||||
SAPSetupEndpoint string `plist:"sign-sap-setup,omitempty"`
|
||||
SAPSetupCertEndpoint string `plist:"sign-sap-setup-cert,omitempty"`
|
||||
SAPVersion string `plist:"sign-sap-version,omitempty"`
|
||||
|
||||
@@ -2,14 +2,16 @@ package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
gohttp "net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"howett.net/plist"
|
||||
)
|
||||
@@ -19,6 +21,7 @@ var (
|
||||
)
|
||||
|
||||
type DownloadInput struct {
|
||||
Context context.Context
|
||||
Account Account
|
||||
App App
|
||||
OutputPath string
|
||||
@@ -40,6 +43,14 @@ func (t *appstore) Download(input DownloadInput) (DownloadOutput, error) {
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
var machineGUID []byte
|
||||
if input.Platform == PlatformMacOS {
|
||||
guid, machineGUID, err = machineIdentity(macAddr)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to resolve machine identity: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
externalVersionID := input.ExternalVersionID
|
||||
if externalVersionID == "" && (input.Platform == PlatformAppleTV || input.Platform == PlatformVisionOS) {
|
||||
externalVersionID, err = t.lookupLatestExternalVersionID(input.Account, input.App, input.Platform)
|
||||
@@ -48,11 +59,9 @@ func (t *appstore) Download(input DownloadInput) (DownloadOutput, error) {
|
||||
}
|
||||
}
|
||||
|
||||
req := t.downloadRequest(input.Account, input.App, guid, externalVersionID)
|
||||
|
||||
res, err := t.downloadClient.Send(req)
|
||||
res, resolvedPlatform, err := t.sendDownloadProduct(input.Account, input.App, guid, externalVersionID, input.Platform)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
return DownloadOutput{}, err
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired ||
|
||||
@@ -66,7 +75,7 @@ func (t *appstore) Download(input DownloadInput) (DownloadOutput, error) {
|
||||
return DownloadOutput{}, ErrLicenseRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
if res.Data.CustomerMessage != "" && (res.Data.FailureType != "" || len(res.Data.Items) == 0) {
|
||||
return DownloadOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
@@ -87,30 +96,44 @@ func (t *appstore) Download(input DownloadInput) (DownloadOutput, error) {
|
||||
version = fmt.Sprintf("%v", itemVersion)
|
||||
}
|
||||
|
||||
destination, err := t.resolveDestinationPath(input.App, version, input.OutputPath)
|
||||
packagePlatform, err := downloadPackagePlatform(input.Platform, item)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, err
|
||||
}
|
||||
|
||||
destination, err := t.resolveDestinationPath(input.App, version, input.OutputPath, packagePlatform)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to resolve destination path: %w", err)
|
||||
}
|
||||
|
||||
if packagePlatform == PlatformMacOS {
|
||||
return t.downloadMacPackage(input.Context, item, destination, machineGUID, input.Progress)
|
||||
}
|
||||
|
||||
tmpPath := fmt.Sprintf("%s.tmp", destination)
|
||||
|
||||
err = t.downloadFile(item.URL, tmpPath, input.Progress)
|
||||
if err != nil {
|
||||
if err := t.downloadFile(input.Context, item.URL, tmpPath, input.Progress); err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to download file: %w", err)
|
||||
}
|
||||
|
||||
err = t.applyPatches(item, input.Account, tmpPath, destination)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to apply patches: %w", err)
|
||||
}
|
||||
if err := t.validatePackagePlatform(tmpPath, resolvedPlatform); err != nil {
|
||||
if removeErr := t.os.Remove(tmpPath); removeErr != nil {
|
||||
err = errors.Join(err, fmt.Errorf("failed to remove invalid package: %w", removeErr))
|
||||
}
|
||||
|
||||
err = t.validatePackagePlatform(destination, input.Platform)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to validate package platform: %w", err)
|
||||
}
|
||||
|
||||
err = t.os.Remove(fmt.Sprintf("%s.tmp", destination))
|
||||
artwork, err := t.downloadArtwork(input.Context, item.ArtworkURL)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to download artwork: %w", err)
|
||||
}
|
||||
|
||||
if err := t.applyPatches(item, input.Account, tmpPath, destination, artwork); err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to apply patches: %w", err)
|
||||
}
|
||||
|
||||
if err := t.os.Remove(tmpPath); err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to remove file: %w", err)
|
||||
}
|
||||
|
||||
@@ -128,6 +151,8 @@ func (*appstore) validatePackagePlatform(path string, platform Platform) error {
|
||||
var expectedPlatform string
|
||||
|
||||
switch platform {
|
||||
case PlatformIPhone, PlatformIPad:
|
||||
expectedPlatform = "iPhoneOS"
|
||||
case PlatformAppleTV:
|
||||
expectedPlatform = "AppleTVOS"
|
||||
case PlatformVisionOS:
|
||||
@@ -187,10 +212,11 @@ func isTopLevelAppInfoPlist(path string) bool {
|
||||
}
|
||||
|
||||
type downloadItemResult struct {
|
||||
HashMD5 string `plist:"md5,omitempty"`
|
||||
URL string `plist:"URL,omitempty"`
|
||||
Sinfs []Sinf `plist:"sinfs,omitempty"`
|
||||
Metadata map[string]interface{} `plist:"metadata,omitempty"`
|
||||
ArtworkURL string `plist:"artworkURL,omitempty"`
|
||||
HashMD5 string `plist:"md5,omitempty"`
|
||||
URL string `plist:"URL,omitempty"`
|
||||
Sinfs []Sinf `plist:"sinfs,omitempty"`
|
||||
Metadata map[string]interface{} `plist:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type downloadResult struct {
|
||||
@@ -199,18 +225,31 @@ type downloadResult struct {
|
||||
Items []downloadItemResult `plist:"songList,omitempty"`
|
||||
}
|
||||
|
||||
func (t *appstore) downloadFile(src, dst string, progress *progressbar.ProgressBar) error {
|
||||
//nolint:nonamedreturns // Deferred close errors must propagate to callers.
|
||||
func (t *appstore) downloadFile(ctx context.Context, src, dst string, progress *progressbar.ProgressBar) (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()
|
||||
}
|
||||
|
||||
if req != nil {
|
||||
req = req.WithContext(ctx)
|
||||
}
|
||||
|
||||
file, err := t.os.OpenFile(dst, os.O_CREATE|os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
defer func() {
|
||||
if closeErr := file.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close downloaded file", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
stat, err := t.os.Stat(dst)
|
||||
if err != nil {
|
||||
@@ -227,64 +266,59 @@ func (t *appstore) downloadFile(src, dst string, progress *progressbar.ProgressB
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if progress != nil {
|
||||
progress.ChangeMax64(res.ContentLength + stat.Size())
|
||||
err = progress.Set64(stat.Size())
|
||||
offset, remaining, total, complete, err := downloadResponseRange(res, stat.Size())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if complete {
|
||||
return nil
|
||||
}
|
||||
|
||||
if res.StatusCode == gohttp.StatusOK {
|
||||
if err := file.Truncate(0); err != nil {
|
||||
return fmt.Errorf("failed to restart download: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := file.Seek(offset, io.SeekStart); err != nil {
|
||||
return fmt.Errorf("can not seek file: %w", err)
|
||||
}
|
||||
|
||||
var writer io.Writer = file
|
||||
|
||||
if progress != nil {
|
||||
progress.ChangeMax64(total)
|
||||
|
||||
if err := progress.Set64(offset); err != nil {
|
||||
return fmt.Errorf("can not set bar progress: %w", err)
|
||||
}
|
||||
|
||||
_, err = file.Seek(0, io.SeekEnd)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can not seek file: %w", err)
|
||||
}
|
||||
|
||||
_, err = io.Copy(io.MultiWriter(file, progress), res.Body)
|
||||
} else {
|
||||
_, err = io.Copy(file, res.Body)
|
||||
writer = io.MultiWriter(file, progress)
|
||||
}
|
||||
|
||||
var body io.Reader = res.Body
|
||||
if remaining >= 0 {
|
||||
body = io.LimitReader(body, remaining)
|
||||
}
|
||||
|
||||
written, err := io.Copy(writer, body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write file: %w", err)
|
||||
}
|
||||
|
||||
if remaining >= 0 && written != remaining || total >= 0 && offset+written != total {
|
||||
return fmt.Errorf("download is incomplete: %w", io.ErrUnexpectedEOF)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*appstore) downloadRequest(acc Account, app App, guid string, externalVersionID string) http.Request {
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
"serialNumber": "0",
|
||||
}
|
||||
|
||||
if externalVersionID != "" {
|
||||
payload["externalVersionId"] = externalVersionID
|
||||
}
|
||||
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: payload,
|
||||
},
|
||||
}
|
||||
func fileName(app App, version string) string {
|
||||
return packageFileName(app, version, "")
|
||||
}
|
||||
|
||||
func fileName(app App, version string) string {
|
||||
func packageFileName(app App, version string, platform Platform) string {
|
||||
var parts []string
|
||||
|
||||
if app.BundleID != "" {
|
||||
@@ -299,11 +333,16 @@ func fileName(app App, version string) string {
|
||||
parts = append(parts, version)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s.ipa", strings.Join(parts, "_"))
|
||||
extension := "ipa"
|
||||
if platform == PlatformMacOS {
|
||||
extension = "pkg"
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s.%s", strings.Join(parts, "_"), extension)
|
||||
}
|
||||
|
||||
func (t *appstore) resolveDestinationPath(app App, version string, path string) (string, error) {
|
||||
file := fileName(app, version)
|
||||
func (t *appstore) resolveDestinationPath(app App, version string, path string, platform Platform) (string, error) {
|
||||
file := packageFileName(app, version, platform)
|
||||
|
||||
if path == "" {
|
||||
workdir, err := t.os.Getwd()
|
||||
@@ -320,7 +359,7 @@ func (t *appstore) resolveDestinationPath(app App, version string, path string)
|
||||
}
|
||||
|
||||
if isDir {
|
||||
return fmt.Sprintf("%s/%s", path, file), nil
|
||||
return filepath.Join(path, file), nil
|
||||
}
|
||||
|
||||
return path, nil
|
||||
@@ -339,7 +378,8 @@ func (t *appstore) isDirectory(path string) (bool, error) {
|
||||
return info.IsDir(), nil
|
||||
}
|
||||
|
||||
func (t *appstore) applyPatches(item downloadItemResult, acc Account, src, dst string) error {
|
||||
//nolint:nonamedreturns // Deferred close errors must propagate to callers.
|
||||
func (t *appstore) applyPatches(item downloadItemResult, acc Account, src, dst string, artwork []byte) (err error) {
|
||||
srcZip, err := zip.OpenReader(src)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open zip reader: %w", err)
|
||||
@@ -350,16 +390,36 @@ func (t *appstore) applyPatches(item downloadItemResult, acc Account, src, dst s
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer dstFile.Close()
|
||||
|
||||
defer func() {
|
||||
if closeErr := dstFile.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close patched file", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
dstZip := zip.NewWriter(dstFile)
|
||||
defer dstZip.Close()
|
||||
defer func() {
|
||||
if closeErr := dstZip.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close zip writer", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
err = t.replicateZip(srcZip, dstZip)
|
||||
err = t.replicateZip(srcZip, dstZip, src)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to replicate zip: %w", err)
|
||||
}
|
||||
|
||||
if len(artwork) != 0 {
|
||||
file, err := dstZip.Create("iTunesArtwork")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create artwork: %w", err)
|
||||
}
|
||||
|
||||
if _, err := file.Write(artwork); err != nil {
|
||||
return fmt.Errorf("failed to write artwork: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
err = t.writeMetadata(item.Metadata, acc, dstZip)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write metadata: %w", err)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (t *appstore) downloadArtwork(ctx context.Context, url string) ([]byte, error) {
|
||||
if url == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
req, err := t.httpClient.NewRequest(http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
res, err := t.httpClient.Do(req.WithContext(ctx))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("unexpected artwork response status: %d", res.StatusCode)
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read artwork: %w", err)
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
return nil, errors.New("artwork response is empty")
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
)
|
||||
|
||||
func TestDownloadArtworkAndIncludeInIPA(t *testing.T) {
|
||||
requests := 0
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
_, _ = io.WriteString(w, "artwork bytes")
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
store := &appstore{httpClient: apphttp.NewClient[interface{}](apphttp.Args{}), os: operatingsystem.New()}
|
||||
for _, url := range []string{"", server.URL} {
|
||||
data, err := store.downloadArtwork(context.Background(), url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if url == "" && (len(data) != 0 || requests != 0) {
|
||||
t.Fatal("artwork was downloaded without a URL")
|
||||
}
|
||||
|
||||
if url != "" && string(data) != "artwork bytes" {
|
||||
t.Fatal("artwork missing")
|
||||
}
|
||||
|
||||
path := filepath.Join(t.TempDir(), "source.zip")
|
||||
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
writer := zip.NewWriter(file)
|
||||
if _, err := writer.Create("Payload/App.app/"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := file.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := store.applyPatches(downloadItemResult{Metadata: map[string]interface{}{}}, Account{}, path, path+".ipa", data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reader, err := zip.OpenReader(path + ".ipa")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
found := false
|
||||
|
||||
for _, entry := range reader.File {
|
||||
if entry.Name != "iTunesArtwork" {
|
||||
continue
|
||||
}
|
||||
|
||||
found = true
|
||||
|
||||
r, err := entry.Open()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
actual, err := io.ReadAll(r)
|
||||
r.Close()
|
||||
|
||||
if err != nil || string(actual) != "artwork bytes" {
|
||||
t.Fatalf("artwork = %q; %v", actual, err)
|
||||
}
|
||||
}
|
||||
|
||||
reader.Close()
|
||||
|
||||
if found != (url != "") {
|
||||
t.Fatal("incorrect artwork presence")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadArtworkRejectsFailedResponse(t *testing.T) {
|
||||
server := httptest.NewServer(http.NotFoundHandler())
|
||||
defer server.Close()
|
||||
|
||||
store := &appstore{httpClient: apphttp.NewClient[interface{}](apphttp.Args{})}
|
||||
if _, err := store.downloadArtwork(context.Background(), server.URL); err == nil {
|
||||
t.Fatal("accepted error page as artwork")
|
||||
}
|
||||
|
||||
if data, err := store.downloadArtwork(context.Background(), ""); err != nil || len(data) != 0 {
|
||||
t.Fatal("missing artwork URL should be skipped")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/blacktop/go-macho/pkg/xar"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
)
|
||||
|
||||
const (
|
||||
macDPInfoSuffix = ".dpInfo"
|
||||
macHWInfoSuffix = ".hwInfo"
|
||||
macEncryptedStageSuffix = ".ipatool-encrypted"
|
||||
macDecryptedStageSuffix = ".ipatool-decrypted"
|
||||
)
|
||||
|
||||
type macPackageDecrypter interface {
|
||||
Decrypt(ctx context.Context, dst io.Writer, src io.Reader) (int64, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
type macPackageDecrypterFactory func(ctx context.Context, hardwareID, dpInfo []byte) (macPackageDecrypter, error)
|
||||
|
||||
func (t *appstore) downloadMacPackage(
|
||||
ctx context.Context,
|
||||
item downloadItemResult,
|
||||
destination string,
|
||||
hardwareID []byte,
|
||||
progress *progressbar.ProgressBar,
|
||||
) (_ DownloadOutput, err error) {
|
||||
dpInfo, err := macDPInfo(item.Sinfs)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, err
|
||||
}
|
||||
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
encryptedPath := destination + macEncryptedStageSuffix
|
||||
decryptedPath := destination + macDecryptedStageSuffix
|
||||
stagePaths := []string{encryptedPath, decryptedPath}
|
||||
published := false
|
||||
|
||||
if err := t.cleanupMacPaths(stagePaths...); err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to prepare macOS download staging: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
cleanupErr := t.cleanupMacPaths(stagePaths...)
|
||||
if !published && cleanupErr != nil {
|
||||
err = joinCleanupError(err, "failed to clean up macOS download staging", cleanupErr)
|
||||
}
|
||||
}()
|
||||
|
||||
if err := t.downloadFile(ctx, item.URL, encryptedPath, progress); err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to download file: %w", err)
|
||||
}
|
||||
|
||||
factory := t.macDecrypterFactory
|
||||
if factory == nil {
|
||||
factory = defaultMacPackageDecrypterFactory
|
||||
}
|
||||
|
||||
decrypter, err := factory(ctx, append([]byte(nil), hardwareID...), append([]byte(nil), dpInfo...))
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to initialize macOS package decrypter: %w", err)
|
||||
}
|
||||
|
||||
if err := t.decryptMacPackage(ctx, decrypter, encryptedPath, decryptedPath); err != nil {
|
||||
return DownloadOutput{}, err
|
||||
}
|
||||
|
||||
if err := t.validateMacPackage(decryptedPath); err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to validate decrypted macOS package: %w", err)
|
||||
}
|
||||
|
||||
if err := t.publishMacPackage(decryptedPath, destination); err != nil {
|
||||
return DownloadOutput{}, err
|
||||
}
|
||||
|
||||
published = true
|
||||
|
||||
// The validated package is already published at this point. Legacy sidecars
|
||||
// are obsolete metadata, so their cleanup must not turn a successful package
|
||||
// replacement into an error.
|
||||
_ = t.removeLegacyMacSidecars(destination)
|
||||
|
||||
return DownloadOutput{DestinationPath: destination}, nil
|
||||
}
|
||||
|
||||
func (t *appstore) decryptMacPackage(ctx context.Context, decrypter macPackageDecrypter, encryptedPath, decryptedPath string) (err error) {
|
||||
decrypterClosed := false
|
||||
|
||||
var source *os.File
|
||||
|
||||
var destination *os.File
|
||||
|
||||
defer func() {
|
||||
if destination != nil {
|
||||
if closeErr := destination.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close decrypted macOS package staging", closeErr)
|
||||
}
|
||||
}
|
||||
|
||||
if source != nil {
|
||||
if closeErr := source.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close encrypted macOS package", closeErr)
|
||||
}
|
||||
}
|
||||
|
||||
if !decrypterClosed {
|
||||
if closeErr := decrypter.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close macOS package decrypter", closeErr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
source, err = t.os.OpenFile(encryptedPath, os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open encrypted macOS package: %w", err)
|
||||
}
|
||||
|
||||
destination, err = t.os.OpenFile(decryptedPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open decrypted macOS package staging: %w", err)
|
||||
}
|
||||
|
||||
_, decryptErr := decrypter.Decrypt(ctx, destination, source)
|
||||
destinationCloseErr := destination.Close()
|
||||
destination = nil
|
||||
sourceCloseErr := source.Close()
|
||||
source = nil
|
||||
decrypterCloseErr := decrypter.Close()
|
||||
decrypterClosed = true
|
||||
|
||||
if decryptErr != nil {
|
||||
err = fmt.Errorf("failed to decrypt macOS package: %w", decryptErr)
|
||||
}
|
||||
|
||||
if destinationCloseErr != nil {
|
||||
err = joinCleanupError(err, "failed to close decrypted macOS package staging", destinationCloseErr)
|
||||
}
|
||||
|
||||
if sourceCloseErr != nil {
|
||||
err = joinCleanupError(err, "failed to close encrypted macOS package", sourceCloseErr)
|
||||
}
|
||||
|
||||
if decrypterCloseErr != nil {
|
||||
err = joinCleanupError(err, "failed to close macOS package decrypter", decrypterCloseErr)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (t *appstore) validateMacPackage(path string) (err error) {
|
||||
file, err := t.os.OpenFile(path, os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open decrypted macOS package: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if closeErr := file.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close decrypted macOS package", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to inspect decrypted macOS package: %w", err)
|
||||
}
|
||||
|
||||
if info.Size() == 0 {
|
||||
return errors.New("decrypted package is empty")
|
||||
}
|
||||
|
||||
archive, err := xar.NewReader(file, info.Size())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse XAR archive: %w", err)
|
||||
}
|
||||
|
||||
if len(archive.Files) == 0 {
|
||||
return errors.New("XAR archive does not contain files")
|
||||
}
|
||||
|
||||
for _, entry := range archive.Files {
|
||||
if !entry.VerifyChecksum() {
|
||||
return fmt.Errorf("XAR entry %q failed checksum validation", entry.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func macDPInfo(sinfs []Sinf) ([]byte, error) {
|
||||
var dpInfo []byte
|
||||
|
||||
for _, sinf := range sinfs {
|
||||
if len(sinf.DPInfo) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if dpInfo != nil && !bytes.Equal(dpInfo, sinf.DPInfo) {
|
||||
return nil, errors.New("download response contains conflicting dpInfo values")
|
||||
}
|
||||
|
||||
dpInfo = sinf.DPInfo
|
||||
}
|
||||
|
||||
if len(dpInfo) == 0 {
|
||||
return nil, errors.New("download response does not contain dpInfo")
|
||||
}
|
||||
|
||||
return append([]byte(nil), dpInfo...), nil
|
||||
}
|
||||
|
||||
func (t *appstore) cleanupMacPaths(paths ...string) error {
|
||||
var cleanupErr error
|
||||
|
||||
for _, path := range paths {
|
||||
if err := t.os.Remove(path); err != nil && !t.os.IsNotExist(err) {
|
||||
cleanupErr = errors.Join(cleanupErr, fmt.Errorf("failed to remove %s: %w", path, err))
|
||||
}
|
||||
}
|
||||
|
||||
return cleanupErr
|
||||
}
|
||||
|
||||
func (t *appstore) removeLegacyMacSidecars(destination string) error {
|
||||
return t.cleanupMacPaths(destination+macDPInfoSuffix, destination+macHWInfoSuffix)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/sap/machine"
|
||||
)
|
||||
|
||||
type storeAgentDecrypter struct {
|
||||
agent *machine.StoreAgent
|
||||
}
|
||||
|
||||
func defaultMacPackageDecrypterFactory(ctx context.Context, hardwareID, dpInfo []byte) (macPackageDecrypter, error) {
|
||||
bundle, err := assets.Load(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to load SAP assets: %w", err)
|
||||
}
|
||||
|
||||
agent, err := machine.OpenStoreAgent(ctx, bundle, hardwareID, dpInfo)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open StoreAgent: %w", err)
|
||||
}
|
||||
|
||||
return &storeAgentDecrypter{agent: agent}, nil
|
||||
}
|
||||
|
||||
func (d *storeAgentDecrypter) Decrypt(ctx context.Context, dst io.Writer, src io.Reader) (int64, error) {
|
||||
written, err := d.agent.Decrypt(ctx, dst, src)
|
||||
if err != nil {
|
||||
return written, fmt.Errorf("failed to decrypt with StoreAgent: %w", err)
|
||||
}
|
||||
|
||||
return written, nil
|
||||
}
|
||||
|
||||
func (d *storeAgentDecrypter) Close() error {
|
||||
if err := d.agent.Close(); err != nil {
|
||||
return fmt.Errorf("failed to close StoreAgent: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const macBackupSuffix = ".ipatool-backup"
|
||||
|
||||
func (t *appstore) publishMacPackage(stagedPath, destination string) error {
|
||||
backupPath, err := t.backupMacFile(destination)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to preserve existing package: %w", err)
|
||||
}
|
||||
|
||||
if err := t.os.Rename(stagedPath, destination); err != nil {
|
||||
publishErr := fmt.Errorf("failed to publish package: %w", err)
|
||||
|
||||
return joinMacRollbackError(publishErr, t.restoreMacPackage(destination, backupPath))
|
||||
}
|
||||
|
||||
if backupPath != "" {
|
||||
_ = t.os.Remove(backupPath)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *appstore) backupMacFile(path string) (string, error) {
|
||||
_, err := t.os.Stat(path)
|
||||
if err != nil {
|
||||
if t.os.IsNotExist(err) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("failed to inspect destination package: %w", err)
|
||||
}
|
||||
|
||||
backupPath, err := t.macBackupPath(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if err := t.os.Rename(path, backupPath); err != nil {
|
||||
return "", fmt.Errorf("failed to back up destination package: %w", err)
|
||||
}
|
||||
|
||||
return backupPath, nil
|
||||
}
|
||||
|
||||
func (t *appstore) macBackupPath(path string) (string, error) {
|
||||
for index := 0; ; index++ {
|
||||
backupPath := path + macBackupSuffix
|
||||
if index > 0 {
|
||||
backupPath = fmt.Sprintf("%s.%d", backupPath, index)
|
||||
}
|
||||
|
||||
_, err := t.os.Stat(backupPath)
|
||||
if err != nil {
|
||||
if t.os.IsNotExist(err) {
|
||||
return backupPath, nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("failed to inspect package backup path: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *appstore) restoreMacPackage(destination, backupPath string) error {
|
||||
var rollbackErr error
|
||||
|
||||
if err := t.os.Remove(destination); err != nil && !t.os.IsNotExist(err) {
|
||||
rollbackErr = errors.Join(rollbackErr, fmt.Errorf("failed to remove partially published package: %w", err))
|
||||
}
|
||||
|
||||
if backupPath != "" {
|
||||
if err := t.os.Rename(backupPath, destination); err != nil {
|
||||
rollbackErr = errors.Join(rollbackErr, fmt.Errorf("failed to restore package: %w", err))
|
||||
}
|
||||
}
|
||||
|
||||
return rollbackErr
|
||||
}
|
||||
|
||||
func joinMacRollbackError(err, rollbackErr error) error {
|
||||
if rollbackErr == nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return joinCleanupError(err, "failed to restore existing macOS download", rollbackErr)
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"context"
|
||||
"crypto/sha1" // #nosec G505 -- XAR uses SHA-1 for archive checksums.
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
gohttp "net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (macOS download)", func() {
|
||||
var (
|
||||
server *httptest.Server
|
||||
destination string
|
||||
encrypted []byte
|
||||
decrypted []byte
|
||||
dpInfo []byte
|
||||
hardwareID []byte
|
||||
decrypter *fakeMacPackageDecrypter
|
||||
factory macPackageDecrypterFactory
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
encrypted = []byte("encrypted package")
|
||||
decrypted = makeTestXAR([]byte("decrypted payload"), false)
|
||||
dpInfo = []byte("dp info")
|
||||
hardwareID = []byte("hardware")
|
||||
|
||||
server = httptest.NewServer(gohttp.HandlerFunc(func(writer gohttp.ResponseWriter, _ *gohttp.Request) {
|
||||
_, _ = writer.Write(encrypted)
|
||||
}))
|
||||
DeferCleanup(server.Close)
|
||||
|
||||
destination = filepath.Join(GinkgoT().TempDir(), "app.pkg")
|
||||
decrypter = &fakeMacPackageDecrypter{output: decrypted}
|
||||
factory = func(ctx context.Context, gotHardwareID, gotDPInfo []byte) (macPackageDecrypter, error) {
|
||||
Expect(ctx).ToNot(BeNil())
|
||||
Expect(gotHardwareID).To(Equal(hardwareID))
|
||||
Expect(gotDPInfo).To(Equal(dpInfo))
|
||||
|
||||
return decrypter, nil
|
||||
}
|
||||
})
|
||||
|
||||
download := func(operatingSystem operatingsystem.OperatingSystem) (DownloadOutput, error) {
|
||||
store := &appstore{
|
||||
httpClient: apphttp.NewClient[interface{}](apphttp.Args{}),
|
||||
macDecrypterFactory: factory,
|
||||
os: operatingSystem,
|
||||
}
|
||||
|
||||
return store.downloadMacPackage(context.Background(), downloadItemResult{
|
||||
URL: server.URL,
|
||||
Sinfs: []Sinf{{DPInfo: dpInfo}},
|
||||
}, destination, hardwareID, nil)
|
||||
}
|
||||
|
||||
expectNoStaging := func() {
|
||||
Expect(destination + macEncryptedStageSuffix).ToNot(BeAnExistingFile())
|
||||
Expect(destination + macDecryptedStageSuffix).ToNot(BeAnExistingFile())
|
||||
Expect(destination + macBackupSuffix).ToNot(BeAnExistingFile())
|
||||
}
|
||||
|
||||
It("publishes only the decrypted validated package", func() {
|
||||
out, err := download(operatingsystem.New())
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out).To(Equal(DownloadOutput{DestinationPath: destination}))
|
||||
Expect(os.ReadFile(destination)).To(Equal(decrypted))
|
||||
Expect(decrypter.input).To(Equal(encrypted))
|
||||
Expect(decrypter.closed).To(BeTrue())
|
||||
Expect(destination + macDPInfoSuffix).ToNot(BeAnExistingFile())
|
||||
Expect(destination + macHWInfoSuffix).ToNot(BeAnExistingFile())
|
||||
expectNoStaging()
|
||||
})
|
||||
|
||||
It("replaces an existing package and removes legacy sidecars after success", func() {
|
||||
Expect(os.WriteFile(destination, []byte("old package"), 0644)).To(Succeed())
|
||||
Expect(os.WriteFile(destination+macDPInfoSuffix, []byte("old dp"), 0644)).To(Succeed())
|
||||
Expect(os.WriteFile(destination+macHWInfoSuffix, []byte("old hw"), 0644)).To(Succeed())
|
||||
|
||||
_, err := download(operatingsystem.New())
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(os.ReadFile(destination)).To(Equal(decrypted))
|
||||
Expect(destination + macDPInfoSuffix).ToNot(BeAnExistingFile())
|
||||
Expect(destination + macHWInfoSuffix).ToNot(BeAnExistingFile())
|
||||
expectNoStaging()
|
||||
})
|
||||
|
||||
It("succeeds when legacy sidecar cleanup fails after publication", func() {
|
||||
Expect(os.WriteFile(destination+macDPInfoSuffix, []byte("old dp"), 0644)).To(Succeed())
|
||||
operatingSystem := &macDownloadFailureOS{
|
||||
OperatingSystem: operatingsystem.New(),
|
||||
removeErrorPath: destination + macDPInfoSuffix,
|
||||
}
|
||||
|
||||
out, err := download(operatingSystem)
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out).To(Equal(DownloadOutput{DestinationPath: destination}))
|
||||
Expect(os.ReadFile(destination)).To(Equal(decrypted))
|
||||
Expect(os.ReadFile(destination + macDPInfoSuffix)).To(Equal([]byte("old dp")))
|
||||
expectNoStaging()
|
||||
})
|
||||
|
||||
It("preserves the existing package when decryption fails", func() {
|
||||
Expect(os.WriteFile(destination, []byte("old package"), 0644)).To(Succeed())
|
||||
decrypter.err = errors.New("decrypt failed")
|
||||
|
||||
_, err := download(operatingsystem.New())
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("decrypt failed")))
|
||||
Expect(os.ReadFile(destination)).To(Equal([]byte("old package")))
|
||||
expectNoStaging()
|
||||
})
|
||||
|
||||
It("cancels the package request and cleans staging", func() {
|
||||
started := make(chan struct{})
|
||||
cancelServer := httptest.NewServer(gohttp.HandlerFunc(func(writer gohttp.ResponseWriter, request *gohttp.Request) {
|
||||
close(started)
|
||||
<-request.Context().Done()
|
||||
}))
|
||||
DeferCleanup(cancelServer.Close)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
store := &appstore{
|
||||
httpClient: apphttp.NewClient[interface{}](apphttp.Args{}),
|
||||
macDecrypterFactory: factory,
|
||||
os: operatingsystem.New(),
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := store.downloadMacPackage(ctx, downloadItemResult{
|
||||
URL: cancelServer.URL,
|
||||
Sinfs: []Sinf{{DPInfo: dpInfo}},
|
||||
}, destination, hardwareID, nil)
|
||||
done <- err
|
||||
}()
|
||||
|
||||
<-started
|
||||
cancel()
|
||||
|
||||
Eventually(done).Should(Receive(MatchError(ContainSubstring(context.Canceled.Error()))))
|
||||
Expect(destination).ToNot(BeAnExistingFile())
|
||||
expectNoStaging()
|
||||
})
|
||||
|
||||
It("preserves the existing package when decrypted output is not XAR", func() {
|
||||
Expect(os.WriteFile(destination, []byte("old package"), 0644)).To(Succeed())
|
||||
decrypter.output = []byte("not xar")
|
||||
|
||||
_, err := download(operatingsystem.New())
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to parse XAR archive")))
|
||||
Expect(os.ReadFile(destination)).To(Equal([]byte("old package")))
|
||||
expectNoStaging()
|
||||
})
|
||||
|
||||
It("rejects a XAR without files", func() {
|
||||
Expect(os.WriteFile(destination, []byte("old package"), 0644)).To(Succeed())
|
||||
decrypter.output = makeEmptyTestXAR()
|
||||
|
||||
_, err := download(operatingsystem.New())
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("does not contain files")))
|
||||
Expect(os.ReadFile(destination)).To(Equal([]byte("old package")))
|
||||
expectNoStaging()
|
||||
})
|
||||
|
||||
It("rejects a XAR entry with an invalid checksum", func() {
|
||||
Expect(os.WriteFile(destination, []byte("old package"), 0644)).To(Succeed())
|
||||
decrypter.output = makeTestXAR([]byte("decrypted payload"), true)
|
||||
|
||||
_, err := download(operatingsystem.New())
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("failed checksum validation")))
|
||||
Expect(os.ReadFile(destination)).To(Equal([]byte("old package")))
|
||||
expectNoStaging()
|
||||
})
|
||||
|
||||
It("restores the existing package when publication fails", func() {
|
||||
Expect(os.WriteFile(destination, []byte("old package"), 0644)).To(Succeed())
|
||||
operatingSystem := &macDownloadFailureOS{
|
||||
OperatingSystem: operatingsystem.New(),
|
||||
renameErrorOld: destination + macDecryptedStageSuffix,
|
||||
}
|
||||
|
||||
_, err := download(operatingSystem)
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to publish package")))
|
||||
Expect(os.ReadFile(destination)).To(Equal([]byte("old package")))
|
||||
expectNoStaging()
|
||||
})
|
||||
|
||||
It("does not replace an unrelated existing backup", func() {
|
||||
Expect(os.WriteFile(destination, []byte("old package"), 0644)).To(Succeed())
|
||||
backupPath := destination + macBackupSuffix
|
||||
Expect(os.WriteFile(backupPath, []byte("unrelated backup"), 0644)).To(Succeed())
|
||||
|
||||
_, err := download(operatingsystem.New())
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(os.ReadFile(destination)).To(Equal(decrypted))
|
||||
Expect(os.ReadFile(backupPath)).To(Equal([]byte("unrelated backup")))
|
||||
Expect(destination + macBackupSuffix + ".1").ToNot(BeAnExistingFile())
|
||||
})
|
||||
|
||||
It("rejects a download response without dpInfo before downloading", func() {
|
||||
factoryCalled := false
|
||||
factory = func(context.Context, []byte, []byte) (macPackageDecrypter, error) {
|
||||
factoryCalled = true
|
||||
|
||||
return decrypter, nil
|
||||
}
|
||||
store := &appstore{
|
||||
httpClient: apphttp.NewClient[interface{}](apphttp.Args{}),
|
||||
macDecrypterFactory: factory,
|
||||
os: operatingsystem.New(),
|
||||
}
|
||||
|
||||
_, err := store.downloadMacPackage(context.Background(), downloadItemResult{URL: server.URL}, destination, hardwareID, nil)
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("dpInfo")))
|
||||
Expect(factoryCalled).To(BeFalse())
|
||||
Expect(destination).ToNot(BeAnExistingFile())
|
||||
})
|
||||
|
||||
It("rejects conflicting dpInfo values", func() {
|
||||
_, err := macDPInfo([]Sinf{{DPInfo: []byte("one")}, {DPInfo: []byte("two")}})
|
||||
Expect(err).To(MatchError(ContainSubstring("conflicting")))
|
||||
})
|
||||
})
|
||||
|
||||
type fakeMacPackageDecrypter struct {
|
||||
output []byte
|
||||
input []byte
|
||||
err error
|
||||
closed bool
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (f *fakeMacPackageDecrypter) Decrypt(_ context.Context, dst io.Writer, src io.Reader) (int64, error) {
|
||||
input, err := io.ReadAll(src)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
f.input = input
|
||||
if f.err != nil {
|
||||
return 0, f.err
|
||||
}
|
||||
|
||||
n, err := dst.Write(f.output)
|
||||
|
||||
return int64(n), err
|
||||
}
|
||||
|
||||
func (f *fakeMacPackageDecrypter) Close() error {
|
||||
f.closed = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type macDownloadFailureOS struct {
|
||||
operatingsystem.OperatingSystem
|
||||
renameErrorOld string
|
||||
removeErrorPath string
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (o *macDownloadFailureOS) Remove(path string) error {
|
||||
if path == o.removeErrorPath {
|
||||
return errors.New("remove failed")
|
||||
}
|
||||
|
||||
return o.OperatingSystem.Remove(path)
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (o *macDownloadFailureOS) Rename(oldPath, newPath string) error {
|
||||
if oldPath == o.renameErrorOld {
|
||||
return errors.New("rename failed")
|
||||
}
|
||||
|
||||
return o.OperatingSystem.Rename(oldPath, newPath)
|
||||
}
|
||||
|
||||
func makeEmptyTestXAR() []byte {
|
||||
return makeTestXARArchive("")
|
||||
}
|
||||
|
||||
func makeTestXAR(payload []byte, corruptFileChecksum bool) []byte {
|
||||
payloadChecksum := sha1.Sum(payload) // #nosec G401 -- XAR uses SHA-1 for archive checksums.
|
||||
checksum := payloadChecksum[:]
|
||||
|
||||
if corruptFileChecksum {
|
||||
checksum = bytes.Repeat([]byte{0xff}, sha1.Size)
|
||||
}
|
||||
|
||||
const tocChecksumSize = sha1.Size
|
||||
fileXML := fmt.Sprintf(`<file id="1"><type>file</type><name>Payload</name><data><length>%d</length><offset>%d</offset><size>%d</size><encoding style="application/octet-stream"/><archived-checksum style="sha1">%s</archived-checksum><extracted-checksum style="sha1">%s</extracted-checksum></data></file>`,
|
||||
len(payload),
|
||||
tocChecksumSize,
|
||||
len(payload),
|
||||
hex.EncodeToString(checksum),
|
||||
hex.EncodeToString(payloadChecksum[:]),
|
||||
)
|
||||
|
||||
return makeTestXARArchive(fileXML, payload...)
|
||||
}
|
||||
|
||||
func makeTestXARArchive(fileXML string, payload ...byte) []byte {
|
||||
const tocChecksumSize = sha1.Size
|
||||
toc := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
|
||||
<xar><toc><checksum style="sha1"><offset>0</offset><size>%d</size></checksum>%s</toc></xar>`, tocChecksumSize, fileXML)
|
||||
|
||||
var compressed bytes.Buffer
|
||||
writer := zlib.NewWriter(&compressed)
|
||||
_, err := writer.Write([]byte(toc))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(writer.Close()).To(Succeed())
|
||||
|
||||
compressedTOC := compressed.Bytes()
|
||||
tocChecksum := sha1.Sum(compressedTOC) // #nosec G401 -- XAR uses SHA-1 for archive checksums.
|
||||
|
||||
archive := make([]byte, 28+len(compressedTOC)+tocChecksumSize+len(payload))
|
||||
binary.BigEndian.PutUint32(archive[0:4], 0x78617221)
|
||||
binary.BigEndian.PutUint16(archive[4:6], 28)
|
||||
binary.BigEndian.PutUint16(archive[6:8], 1)
|
||||
binary.BigEndian.PutUint64(archive[8:16], uint64(len(compressedTOC)))
|
||||
binary.BigEndian.PutUint64(archive[16:24], uint64(len(toc)))
|
||||
binary.BigEndian.PutUint32(archive[24:28], 1)
|
||||
copy(archive[28:], compressedTOC)
|
||||
copy(archive[28+len(compressedTOC):], tocChecksum[:])
|
||||
copy(archive[28+len(compressedTOC)+tocChecksumSize:], payload)
|
||||
|
||||
return archive
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func downloadPackagePlatform(platform Platform, item downloadItemResult) (Platform, error) {
|
||||
if platform != PlatformMacOS {
|
||||
return platform, nil
|
||||
}
|
||||
|
||||
softwarePlatform := downloadMetadataString(item.Metadata, "software-platform")
|
||||
productType := downloadMetadataString(item.Metadata, "product-type")
|
||||
// Universal Mac apps can retain product-type=ios-app. Prefer the
|
||||
// package's explicit software platform over that catalog classification.
|
||||
mobileMetadata := strings.EqualFold(softwarePlatform, "ios")
|
||||
macMetadata := strings.EqualFold(softwarePlatform, "macos")
|
||||
|
||||
if softwarePlatform == "" {
|
||||
mobileMetadata = strings.EqualFold(productType, "ios-app")
|
||||
macMetadata = strings.EqualFold(productType, "mac-os-app")
|
||||
}
|
||||
|
||||
mobileSinf := hasMobileSinf(item.Sinfs)
|
||||
mobileSinfEvidence := hasMobileSinfEvidence(item.Sinfs)
|
||||
macDPInfo := hasMacDPInfo(item.Sinfs)
|
||||
|
||||
if (mobileMetadata && macDPInfo) || (macMetadata && mobileSinfEvidence) || (mobileSinfEvidence && macDPInfo) {
|
||||
return "", errors.New("download response contains conflicting package metadata")
|
||||
}
|
||||
|
||||
if mobileMetadata || mobileSinfEvidence {
|
||||
if !mobileSinf {
|
||||
return "", errors.New("download response does not contain mobile sinf data")
|
||||
}
|
||||
|
||||
return PlatformIPhone, nil
|
||||
}
|
||||
|
||||
return PlatformMacOS, nil
|
||||
}
|
||||
|
||||
func downloadMetadataString(metadata map[string]interface{}, key string) string {
|
||||
value, _ := metadata[key].(string)
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
func hasMobileSinf(sinfs []Sinf) bool {
|
||||
if len(sinfs) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, sinf := range sinfs {
|
||||
if len(sinf.Data) == 0 || len(sinf.DPInfo) > 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func hasMobileSinfEvidence(sinfs []Sinf) bool {
|
||||
for _, sinf := range sinfs {
|
||||
if len(sinf.Data) > 0 && len(sinf.DPInfo) == 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func hasMacDPInfo(sinfs []Sinf) bool {
|
||||
for _, sinf := range sinfs {
|
||||
if len(sinf.DPInfo) > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Download package platform", func() {
|
||||
It("uses the requested platform for native macOS packages", func() {
|
||||
item := downloadItemResult{
|
||||
Metadata: map[string]interface{}{
|
||||
"software-platform": "macos",
|
||||
"product-type": "mac-os-app",
|
||||
},
|
||||
Sinfs: []Sinf{{DPInfo: []byte("dp info")}},
|
||||
}
|
||||
|
||||
platform, err := downloadPackagePlatform(PlatformMacOS, item)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(platform).To(Equal(PlatformMacOS))
|
||||
})
|
||||
|
||||
It("recognizes universal Mac packages with an iOS product type", func() {
|
||||
platform, err := downloadPackagePlatform(PlatformMacOS, downloadItemResult{
|
||||
Metadata: map[string]interface{}{
|
||||
"software-platform": "macos",
|
||||
"product-type": "ios-app",
|
||||
},
|
||||
Sinfs: []Sinf{{DPInfo: make([]byte, 88)}},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(platform).To(Equal(PlatformMacOS))
|
||||
})
|
||||
|
||||
It("accepts native authorization data that also contains sinf data", func() {
|
||||
item := downloadItemResult{
|
||||
Metadata: map[string]interface{}{
|
||||
"software-platform": "macos",
|
||||
"product-type": "mac-os-app",
|
||||
},
|
||||
Sinfs: []Sinf{{Data: []byte("sinf"), DPInfo: []byte("dp info")}},
|
||||
}
|
||||
|
||||
platform, err := downloadPackagePlatform(PlatformMacOS, item)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(platform).To(Equal(PlatformMacOS))
|
||||
})
|
||||
|
||||
It("recognizes iOS apps made available on macOS", func() {
|
||||
item := downloadItemResult{
|
||||
Metadata: map[string]interface{}{
|
||||
"software-platform": "ios",
|
||||
"product-type": "ios-app",
|
||||
},
|
||||
Sinfs: []Sinf{{Data: []byte("sinf")}},
|
||||
}
|
||||
|
||||
platform, err := downloadPackagePlatform(PlatformMacOS, item)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(platform).To(Equal(PlatformIPhone))
|
||||
})
|
||||
|
||||
It("uses mobile sinf data when platform metadata is absent", func() {
|
||||
platform, err := downloadPackagePlatform(PlatformMacOS, downloadItemResult{
|
||||
Sinfs: []Sinf{{Data: []byte("sinf")}},
|
||||
})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(platform).To(Equal(PlatformIPhone))
|
||||
})
|
||||
|
||||
It("rejects mobile metadata without usable sinf data", func() {
|
||||
_, err := downloadPackagePlatform(PlatformMacOS, downloadItemResult{
|
||||
Metadata: map[string]interface{}{"software-platform": "ios"},
|
||||
})
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("mobile sinf")))
|
||||
})
|
||||
|
||||
It("rejects conflicting platform metadata", func() {
|
||||
_, err := downloadPackagePlatform(PlatformMacOS, downloadItemResult{
|
||||
Metadata: map[string]interface{}{
|
||||
"software-platform": "macos",
|
||||
"product-type": "ios-app",
|
||||
},
|
||||
Sinfs: []Sinf{{Data: []byte("sinf")}},
|
||||
})
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("conflicting")))
|
||||
})
|
||||
|
||||
It("rejects conflicting authorization data", func() {
|
||||
_, err := downloadPackagePlatform(PlatformMacOS, downloadItemResult{
|
||||
Sinfs: []Sinf{
|
||||
{Data: []byte("sinf")},
|
||||
{DPInfo: []byte("dp info")},
|
||||
},
|
||||
})
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("conflicting")))
|
||||
})
|
||||
|
||||
It("does not override non-macOS requests", func() {
|
||||
platform, err := downloadPackagePlatform(PlatformIPad, downloadItemResult{
|
||||
Metadata: map[string]interface{}{
|
||||
"software-platform": "macos",
|
||||
"product-type": "mac-os-app",
|
||||
},
|
||||
})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(platform).To(Equal(PlatformIPad))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,66 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
type readOnlyDestinationOS struct {
|
||||
operatingsystem.OperatingSystem
|
||||
destination string
|
||||
}
|
||||
|
||||
func (o readOnlyDestinationOS) OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
|
||||
if name != o.destination {
|
||||
file, err := o.OperatingSystem.OpenFile(name, flag, perm)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
return file, nil
|
||||
}
|
||||
|
||||
if err := os.WriteFile(name, nil, perm); err != nil {
|
||||
return nil, fmt.Errorf("failed to create destination: %w", err)
|
||||
}
|
||||
|
||||
// Hand back a read-only descriptor so every write to the archive fails.
|
||||
file, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open destination: %w", err)
|
||||
}
|
||||
|
||||
return file, nil
|
||||
}
|
||||
|
||||
var _ = Describe("AppStore (patch finalization)", func() {
|
||||
It("reports buffered writes that fail when closing the ZIP writer", func() {
|
||||
dir := GinkgoT().TempDir()
|
||||
src, dst := filepath.Join(dir, "source.zip"), filepath.Join(dir, "patched.ipa")
|
||||
|
||||
var source bytes.Buffer
|
||||
writer := zip.NewWriter(&source)
|
||||
_, err := writer.Create("Payload/App.app/")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(writer.Close()).To(Succeed())
|
||||
Expect(os.WriteFile(src, source.Bytes(), 0600)).To(Succeed())
|
||||
|
||||
// The patched archive stays buffered until Close, where the read-only
|
||||
// destination descriptor rejects the write.
|
||||
store := &appstore{os: readOnlyDestinationOS{OperatingSystem: operatingsystem.New(), destination: dst}}
|
||||
err = store.applyPatches(downloadItemResult{Metadata: map[string]interface{}{}}, Account{}, src, dst, nil)
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to close zip writer")))
|
||||
var pathErr *os.PathError
|
||||
Expect(errors.As(err, &pathErr)).To(BeTrue())
|
||||
Expect(pathErr.Op).To(Equal("write"))
|
||||
Expect(pathErr.Path).To(Equal(dst))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,217 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
const (
|
||||
downloadDispatchDomain = "downloaddispatch." + iTunesAPIDomain
|
||||
redownloadProductPath = "/r/redownload"
|
||||
updateProductPath = "/up/updateProduct"
|
||||
downloadVersionKeyVolumeStore = "externalVersionId"
|
||||
downloadVersionKeyRedownload = "appExtVrsId"
|
||||
)
|
||||
|
||||
type downloadProductEndpoint struct {
|
||||
baseURL string
|
||||
versionKey string
|
||||
}
|
||||
|
||||
func (t *appstore) sendDownloadProduct(acc Account, app App, guid, externalVersionID string, platform Platform) (http.Result[downloadResult], Platform, error) {
|
||||
// An unpinned request can return the iOS build of a universal app.
|
||||
// Select the Mac offer before accepting any download response.
|
||||
if externalVersionID == "" && platform == PlatformMacOS {
|
||||
var err error
|
||||
|
||||
externalVersionID, err = t.lookupLatestMacOSExternalVersionID(acc, app)
|
||||
if err != nil {
|
||||
return http.Result[downloadResult]{}, platform, fmt.Errorf("failed to resolve latest macOS version for download: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
volumeStore := t.volumeStoreEndpoint(acc)
|
||||
|
||||
res, err := t.downloadClient.Send(t.downloadProductRequest(volumeStore, acc, app, guid, externalVersionID))
|
||||
if err != nil {
|
||||
return res, platform, fmt.Errorf("failed to send http request: %w", err)
|
||||
}
|
||||
|
||||
if !isEmptyDownloadProductResponse(res) && !isUnavailableDownloadProductResponse(res) {
|
||||
return res, platform, nil
|
||||
}
|
||||
|
||||
// Try redownload when volumeStore returns no items, either silently or
|
||||
// with the message-only "No Longer Available" response.
|
||||
bag, err := t.fetchURLBag(guid)
|
||||
if err != nil {
|
||||
return res, platform, fmt.Errorf("failed to get bag for redownload fallback: %w", err)
|
||||
}
|
||||
|
||||
if bag.RedownloadEndpoint == "" {
|
||||
return res, platform, nil
|
||||
}
|
||||
|
||||
redownload, err := newDownloadEndpoint(bag.RedownloadEndpoint, redownloadProductPath)
|
||||
if err != nil {
|
||||
return res, platform, err
|
||||
}
|
||||
|
||||
if externalVersionID == "" && (platform == "" || platform == PlatformIPhone || platform == PlatformIPad) {
|
||||
// Unpinned redownloads can fail or return a tvOS package. Select
|
||||
// the current iOS build before sending.
|
||||
if platform == "" {
|
||||
platform = PlatformIPhone
|
||||
}
|
||||
|
||||
externalVersionID, err = t.lookupLatestExternalVersionID(acc, app, platform)
|
||||
if err != nil {
|
||||
return res, platform, fmt.Errorf("failed to resolve latest iOS version for redownload: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
redownloadRes, err := t.downloadClient.Send(t.downloadProductRequest(redownload, acc, app, guid, externalVersionID))
|
||||
if bag.UpdateEndpoint != "" && externalVersionID != "" &&
|
||||
(platform == "" || platform == PlatformIPhone || platform == PlatformIPad || platform == PlatformMacOS) &&
|
||||
(isEmptyRedownloadError(err) || (err == nil && isUnavailableDownloadProductResponse(redownloadRes))) {
|
||||
updateRes, updateErr := t.sendUpdateProduct(bag.UpdateEndpoint, acc, app, guid, externalVersionID)
|
||||
|
||||
if updateErr == nil && platform == "" {
|
||||
platform = PlatformIPhone
|
||||
}
|
||||
|
||||
return updateRes, platform, updateErr
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return redownloadRes, platform, fmt.Errorf("failed to send redownload request: %w", err)
|
||||
}
|
||||
|
||||
return redownloadRes, platform, nil
|
||||
}
|
||||
|
||||
func isEmptyRedownloadError(err error) bool {
|
||||
var unexpected *http.UnexpectedResponseError
|
||||
|
||||
return errors.As(err, &unexpected) &&
|
||||
unexpected.StatusCode == gohttp.StatusInternalServerError && unexpected.Snippet == ""
|
||||
}
|
||||
|
||||
func (t *appstore) sendUpdateProduct(endpoint string, acc Account, app App, guid, externalVersionID string) (http.Result[downloadResult], error) {
|
||||
update, err := newDownloadEndpoint(endpoint, updateProductPath)
|
||||
if err != nil {
|
||||
return http.Result[downloadResult]{}, err
|
||||
}
|
||||
|
||||
// The bag's updateProduct can serve pinned iOS and macOS versions when redownload
|
||||
// returns an empty HTTP 500 or a message-only availability error. Keep
|
||||
// the same session and version selection.
|
||||
res, err := t.downloadClient.Send(t.downloadProductRequest(update, acc, app, guid, externalVersionID))
|
||||
if err != nil {
|
||||
return res, fmt.Errorf("failed to send update request: %w", err)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
if res.Data.CustomerMessage != "" {
|
||||
return res, NewErrorWithMetadata(fmt.Errorf("received update error: %s", res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return res, fmt.Errorf("received unexpected update status code: %d", res.StatusCode)
|
||||
}
|
||||
|
||||
if len(res.Data.Items) != 1 {
|
||||
return res, errors.New("update response must contain exactly one item")
|
||||
}
|
||||
|
||||
metadata := res.Data.Items[0].Metadata
|
||||
if fmt.Sprint(metadata["itemId"]) != fmt.Sprint(app.ID) ||
|
||||
fmt.Sprint(metadata["softwareVersionExternalIdentifier"]) != externalVersionID {
|
||||
return res, errors.New("update response does not match the requested app or version")
|
||||
}
|
||||
|
||||
bundleID, ok := metadata["softwareVersionBundleId"].(string)
|
||||
if !ok || bundleID == "" || (app.BundleID != "" && bundleID != app.BundleID) {
|
||||
return res, errors.New("update response does not match the requested bundle identifier")
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func newDownloadEndpoint(endpoint, path string) (downloadProductEndpoint, error) {
|
||||
parsed, err := url.ParseRequestURI(endpoint)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Host != downloadDispatchDomain ||
|
||||
parsed.Path != path || parsed.RawPath != "" || parsed.RawQuery != "" ||
|
||||
parsed.ForceQuery || parsed.Fragment != "" || parsed.User != nil {
|
||||
return downloadProductEndpoint{}, errors.New("invalid download endpoint in bag")
|
||||
}
|
||||
|
||||
return downloadProductEndpoint{
|
||||
baseURL: endpoint,
|
||||
versionKey: downloadVersionKeyRedownload,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Limit recovery to the observed availability response; other customer messages
|
||||
// and structured failures must retain their normal error handling.
|
||||
func isUnavailableDownloadProductResponse(res http.Result[downloadResult]) bool {
|
||||
message := strings.ToLower(strings.TrimSpace(res.Data.CustomerMessage))
|
||||
|
||||
return res.StatusCode == gohttp.StatusOK &&
|
||||
res.Data.FailureType == "" && len(res.Data.Items) == 0 &&
|
||||
(message == "no longer available" || strings.HasSuffix(message, " no longer available"))
|
||||
}
|
||||
|
||||
func isEmptyDownloadProductResponse(res http.Result[downloadResult]) bool {
|
||||
return res.StatusCode == gohttp.StatusOK &&
|
||||
res.Data.FailureType == "" &&
|
||||
res.Data.CustomerMessage == "" &&
|
||||
len(res.Data.Items) == 0
|
||||
}
|
||||
|
||||
func (*appstore) volumeStoreEndpoint(acc Account) downloadProductEndpoint {
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return downloadProductEndpoint{
|
||||
baseURL: fmt.Sprintf("https://%s%s%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload),
|
||||
versionKey: downloadVersionKeyVolumeStore,
|
||||
}
|
||||
}
|
||||
|
||||
func (*appstore) downloadProductRequest(endpoint downloadProductEndpoint, acc Account, app App, guid, externalVersionID string) http.Request {
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
"serialNumber": "0",
|
||||
}
|
||||
|
||||
if externalVersionID != "" {
|
||||
payload[endpoint.versionKey] = externalVersionID
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("%s?guid=%s", endpoint.baseURL, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
const (
|
||||
testRedownloadEndpoint = "https://downloaddispatch.itunes.apple.com/r/redownload"
|
||||
testUpdateEndpoint = "https://downloaddispatch.itunes.apple.com/up/updateProduct"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Download Product)", func() {
|
||||
const (
|
||||
testGUID = "001122334455"
|
||||
testVersionID = "123456789"
|
||||
)
|
||||
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockBagClient *http.MockClient[bagResult]
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockPlatformClient *http.MockClient[platformVersionLookupResult]
|
||||
store *appstore
|
||||
account Account
|
||||
app App
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockBagClient = http.NewMockClient[bagResult](ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
store = &appstore{
|
||||
bagClient: mockBagClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
}
|
||||
account = Account{
|
||||
DirectoryServicesID: "test-dsid",
|
||||
Pod: "42",
|
||||
}
|
||||
app = App{ID: 987654321}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
It("uses volumeStore as the primary endpoint", func() {
|
||||
expected := http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{{URL: "https://example.com/app.ipa"}},
|
||||
},
|
||||
}
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal("https://p42-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct?guid=" + testGUID))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("iCloud-DSID", account.DirectoryServicesID))
|
||||
|
||||
payload, ok := req.Payload.(*http.XMLPayload)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(payload.Content).To(HaveKeyWithValue("externalVersionId", testVersionID))
|
||||
Expect(payload.Content).To(HaveKeyWithValue("serialNumber", "0"))
|
||||
Expect(payload.Content).ToNot(HaveKey("appExtVrsId"))
|
||||
}).
|
||||
Return(expected, nil)
|
||||
|
||||
actual, platform, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
Expect(platform).To(Equal(PlatformIPhone))
|
||||
})
|
||||
|
||||
It("does not fall back for an App Store error response", func() {
|
||||
expected := http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeLicenseNotFound,
|
||||
CustomerMessage: "License not found",
|
||||
},
|
||||
}
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(expected, nil)
|
||||
|
||||
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
})
|
||||
|
||||
It("falls back to redownloadProduct without requiring SAP configuration", func() {
|
||||
primary := http.Result[downloadResult]{StatusCode: gohttp.StatusOK}
|
||||
expected := http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{{URL: "https://example.com/redownload.ipa"}},
|
||||
},
|
||||
}
|
||||
bag := bagResult{}
|
||||
bag.URLBag.RedownloadEndpoint = testRedownloadEndpoint
|
||||
|
||||
gomock.InOrder(
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(primary, nil),
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal("https://init.itunes.apple.com/bag.xml?guid=" + testGUID))
|
||||
}).
|
||||
Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testRedownloadEndpoint + "?guid=" + testGUID))
|
||||
|
||||
payload, ok := req.Payload.(*http.XMLPayload)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(payload.Content).To(HaveKeyWithValue("appExtVrsId", testVersionID))
|
||||
Expect(payload.Content).To(HaveKeyWithValue("serialNumber", "0"))
|
||||
Expect(payload.Content).ToNot(HaveKey("externalVersionId"))
|
||||
}).
|
||||
Return(expected, nil),
|
||||
)
|
||||
|
||||
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
})
|
||||
|
||||
It("preserves the empty response when the bag has no redownload endpoint", func() {
|
||||
expected := http.Result[downloadResult]{StatusCode: gohttp.StatusOK}
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(expected, nil)
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: validBagResult()}, nil)
|
||||
|
||||
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
})
|
||||
|
||||
It("returns an error when the fallback bag request fails", func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK}, nil)
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{}, errors.New("bag request failed"))
|
||||
|
||||
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to get bag for redownload fallback")))
|
||||
})
|
||||
|
||||
It("returns an error when the redownload request fails", func() {
|
||||
bag := validBagResult()
|
||||
bag.URLBag.RedownloadEndpoint = testRedownloadEndpoint
|
||||
|
||||
gomock.InOrder(
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK}, nil),
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{}, errors.New("redownload failed")),
|
||||
)
|
||||
|
||||
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to send redownload request")))
|
||||
})
|
||||
|
||||
DescribeTable("preserves platform selection on the normal volumeStore path",
|
||||
func(platform Platform) {
|
||||
expected := http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{Items: []downloadItemResult{{URL: "https://example.com/app.ipa"}}},
|
||||
}
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil)
|
||||
|
||||
actual, resolvedPlatform, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, platform)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
Expect(resolvedPlatform).To(Equal(platform))
|
||||
},
|
||||
Entry("unspecified", Platform("")),
|
||||
Entry("iPhone", PlatformIPhone),
|
||||
Entry("iPad", PlatformIPad),
|
||||
Entry("macOS", PlatformMacOS),
|
||||
)
|
||||
|
||||
Describe("version-pinned redownload", func() {
|
||||
var latestVersion platformVersionLookupResult
|
||||
|
||||
BeforeEach(func() {
|
||||
account.StoreFront = "143441-1,34"
|
||||
latestVersion = platformVersionLookupResult{
|
||||
Results: map[string]platformVersionLookupItem{
|
||||
strconv.FormatInt(app.ID, 10): {
|
||||
Offers: []platformVersionLookupOffer{
|
||||
{Version: platformVersionLookupVersion{ExternalID: platformVersionExternalID(testVersionID)}},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
bag := validBagResult()
|
||||
bag.URLBag.RedownloadEndpoint = testRedownloadEndpoint
|
||||
first := mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK}, nil)
|
||||
mockBagClient.EXPECT().Send(gomock.Any()).After(first).
|
||||
Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil)
|
||||
})
|
||||
|
||||
DescribeTable("pins the latest iOS version before the first redownload",
|
||||
func(platform Platform, storefront, country string) {
|
||||
account.StoreFront = storefront
|
||||
expected := http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{Items: []downloadItemResult{{
|
||||
URL: "https://example.com/ios.ipa",
|
||||
Metadata: map[string]interface{}{
|
||||
"softwareVersionExternalIdentifiers": []interface{}{"123", testVersionID},
|
||||
},
|
||||
}}},
|
||||
}
|
||||
gomock.InOrder(
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
u, err := url.Parse(req.URL)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(u.Host).To(Equal("uclient-api.itunes.apple.com"))
|
||||
Expect(u.Query().Get("id")).To(Equal(strconv.FormatInt(app.ID, 10)))
|
||||
Expect(u.Query().Get("cc")).To(Equal(country))
|
||||
Expect(u.Query().Get("platform")).To(Equal("enterprisestore"))
|
||||
}).
|
||||
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: latestVersion}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testRedownloadEndpoint + "?guid=" + testGUID))
|
||||
Expect(req.Method).To(Equal(http.MethodPOST))
|
||||
payload := req.Payload.(*http.XMLPayload).Content
|
||||
Expect(payload).To(HaveKeyWithValue("salableAdamId", app.ID))
|
||||
Expect(payload).To(HaveKeyWithValue("guid", testGUID))
|
||||
Expect(payload).To(HaveKeyWithValue("appExtVrsId", testVersionID))
|
||||
Expect(payload).ToNot(HaveKey("externalVersionId"))
|
||||
Expect(payload).ToNot(HaveKey("pricingParameters"))
|
||||
}).Return(expected, nil),
|
||||
)
|
||||
actual, resolvedPlatform, err := store.sendDownloadProduct(account, app, testGUID, "", platform)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
if platform == "" {
|
||||
Expect(resolvedPlatform).To(Equal(PlatformIPhone))
|
||||
} else {
|
||||
Expect(resolvedPlatform).To(Equal(platform))
|
||||
}
|
||||
},
|
||||
Entry("unspecified platform", Platform(""), "143441-1,34", "us"),
|
||||
Entry("iPhone", PlatformIPhone, "143441-1,34", "us"),
|
||||
Entry("iPad", PlatformIPad, "143441-1,34", "us"),
|
||||
Entry("account storefront", PlatformIPhone, "143444-2,29", "gb"),
|
||||
)
|
||||
|
||||
DescribeTable("does not retry or remove the version pin after a redownload error",
|
||||
func(original error) {
|
||||
gomock.InOrder(
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: latestVersion}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", testVersionID))
|
||||
}).Return(http.Result[downloadResult]{}, original),
|
||||
)
|
||||
_, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
|
||||
Expect(errors.Is(err, original)).To(BeTrue())
|
||||
},
|
||||
Entry("empty HTTP 500", fmt.Errorf("wrapped: %w", &http.UnexpectedResponseError{StatusCode: gohttp.StatusInternalServerError})),
|
||||
Entry("authentication", &http.UnexpectedResponseError{StatusCode: gohttp.StatusForbidden}),
|
||||
Entry("rate limit", &http.UnexpectedResponseError{StatusCode: gohttp.StatusTooManyRequests}),
|
||||
Entry("service unavailable", &http.UnexpectedResponseError{StatusCode: gohttp.StatusServiceUnavailable}),
|
||||
Entry("nonempty 500 message", &http.UnexpectedResponseError{StatusCode: gohttp.StatusInternalServerError, Snippet: "maintenance"}),
|
||||
Entry("network failure", errors.New("connection reset")),
|
||||
)
|
||||
|
||||
DescribeTable("does not resolve an iOS version for pinned or other-platform requests",
|
||||
func(versionID string, platform Platform) {
|
||||
expected := http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{Items: []downloadItemResult{{URL: "https://example.com/app.ipa"}}},
|
||||
}
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
payload := req.Payload.(*http.XMLPayload).Content
|
||||
if versionID == "" {
|
||||
Expect(payload).ToNot(HaveKey("appExtVrsId"))
|
||||
} else {
|
||||
Expect(payload).To(HaveKeyWithValue("appExtVrsId", versionID))
|
||||
}
|
||||
}).Return(expected, nil)
|
||||
actual, resolvedPlatform, err := store.sendDownloadProduct(account, app, testGUID, versionID, platform)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
Expect(resolvedPlatform).To(Equal(platform))
|
||||
},
|
||||
Entry("explicit iOS version", testVersionID, PlatformIPhone),
|
||||
Entry("explicit version without a platform", "818970197", Platform("")),
|
||||
Entry("explicit tvOS version", "818970197", PlatformAppleTV),
|
||||
Entry("explicit macOS version", testVersionID, PlatformMacOS),
|
||||
Entry("tvOS", "", PlatformAppleTV),
|
||||
Entry("visionOS", "", PlatformVisionOS),
|
||||
)
|
||||
|
||||
It("preserves an actionable failure from the pinned request", func() {
|
||||
expected := http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{FailureType: FailureTypeLicenseNotFound}}
|
||||
gomock.InOrder(
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: latestVersion}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
})
|
||||
|
||||
It("stops before redownload when catalog lookup fails", func() {
|
||||
lookupErr := errors.New("catalog unavailable")
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{}, lookupErr)
|
||||
|
||||
actual, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
|
||||
Expect(isEmptyDownloadProductResponse(actual)).To(BeTrue())
|
||||
Expect(errors.Is(err, lookupErr)).To(BeTrue())
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to resolve latest iOS version for redownload")))
|
||||
})
|
||||
|
||||
It("does not send an unpinned request when the app is absent from the catalog", func() {
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK}, nil)
|
||||
|
||||
_, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
|
||||
Expect(err).To(MatchError(ContainSubstring("platform version lookup returned no app")))
|
||||
})
|
||||
|
||||
It("does not send an unpinned request when the catalog version is missing", func() {
|
||||
latestVersion.Results[strconv.FormatInt(app.ID, 10)] = platformVersionLookupItem{
|
||||
Offers: []platformVersionLookupOffer{{}},
|
||||
}
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: latestVersion}, nil)
|
||||
|
||||
_, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
|
||||
Expect(err).To(MatchError(ContainSubstring("platform version lookup returned no external version id")))
|
||||
})
|
||||
|
||||
It("does not retry a plist error response", func() {
|
||||
expected := http.Result[downloadResult]{StatusCode: gohttp.StatusInternalServerError}
|
||||
gomock.InOrder(
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: latestVersion}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
var _ = Describe("AppStore (Download Customer Messages)", func() {
|
||||
DescribeTable("preserves Apple's message and response metadata when fallback is unavailable",
|
||||
func(call func(*appstore) error) {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
defer ctrl.Finish()
|
||||
mockMachine := machine.NewMockMachine(ctrl)
|
||||
mockDownloadClient := http.NewMockClient[downloadResult](ctrl)
|
||||
mockBagClient := http.NewMockClient[bagResult](ctrl)
|
||||
store := &appstore{machine: mockMachine, downloadClient: mockDownloadClient, bagClient: mockBagClient}
|
||||
response := http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{CustomerMessage: "“Messenger” No Longer Available"}}
|
||||
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(response, nil)
|
||||
mockBagClient.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK, Data: validBagResult(),
|
||||
}, nil)
|
||||
|
||||
err := call(store)
|
||||
Expect(err).To(MatchError("received error: " + response.Data.CustomerMessage))
|
||||
Expect(err).To(BeAssignableToTypeOf(&Error{}))
|
||||
Expect(err.(*Error).Metadata).To(Equal(response))
|
||||
},
|
||||
Entry("download", func(store *appstore) error {
|
||||
_, err := store.Download(DownloadInput{})
|
||||
|
||||
return err
|
||||
}),
|
||||
Entry("version list", func(store *appstore) error {
|
||||
_, err := store.ListVersions(ListVersionsInput{})
|
||||
|
||||
return err
|
||||
}),
|
||||
Entry("version metadata", func(store *appstore) error {
|
||||
_, err := store.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
|
||||
return err
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
var _ = Describe("AppStore (Download Endpoints)", func() {
|
||||
for _, path := range []string{redownloadProductPath, updateProductPath} {
|
||||
endpoint := "https://downloaddispatch.itunes.apple.com" + path
|
||||
DescribeTable(path,
|
||||
func(value string, valid bool) {
|
||||
_, err := newDownloadEndpoint(value, path)
|
||||
if valid {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
} else {
|
||||
Expect(err).To(MatchError("invalid download endpoint in bag"))
|
||||
}
|
||||
},
|
||||
Entry("Apple endpoint", endpoint, true),
|
||||
Entry("empty", "", false),
|
||||
Entry("non-HTTPS", "http://downloaddispatch.itunes.apple.com"+path, false),
|
||||
Entry("foreign host", "https://example.com"+path, false),
|
||||
Entry("wrong path", endpoint+"/other", false),
|
||||
Entry("userinfo", "https://user@downloaddispatch.itunes.apple.com"+path, false),
|
||||
Entry("explicit port", "https://downloaddispatch.itunes.apple.com:443"+path, false),
|
||||
Entry("query", endpoint+"?guid=other", false),
|
||||
Entry("empty query", endpoint+"?", false),
|
||||
Entry("fragment", endpoint+"#fragment", false),
|
||||
Entry("escaped path", fmt.Sprintf("https://downloaddispatch.itunes.apple.com/%%%02x%s", path[1], path[2:]), false),
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// downloadResponseRange validates the response before any partial bytes change.
|
||||
// It returns the write offset, remaining bytes, total size, and completion state.
|
||||
func downloadResponseRange(res *http.Response, localSize int64) (int64, int64, int64, bool, error) {
|
||||
switch res.StatusCode {
|
||||
case http.StatusOK:
|
||||
return 0, res.ContentLength, res.ContentLength, false, nil
|
||||
case http.StatusRequestedRangeNotSatisfiable:
|
||||
value, found := strings.CutPrefix(res.Header.Get("Content-Range"), "bytes */")
|
||||
size, parseErr := strconv.ParseInt(value, 10, 64)
|
||||
|
||||
if found && parseErr == nil && size >= 0 && size == localSize {
|
||||
return localSize, 0, size, true, nil
|
||||
}
|
||||
|
||||
return 0, 0, 0, false, fmt.Errorf("download range rejected: local size %d does not match server range %q", localSize, res.Header.Get("Content-Range"))
|
||||
case http.StatusPartialContent:
|
||||
header := res.Header.Get("Content-Range")
|
||||
value, found := strings.CutPrefix(header, "bytes ")
|
||||
bounds, totalText, hasTotal := strings.Cut(value, "/")
|
||||
startText, endText, hasEnd := strings.Cut(bounds, "-")
|
||||
start, startErr := strconv.ParseInt(startText, 10, 64)
|
||||
end, endErr := strconv.ParseInt(endText, 10, 64)
|
||||
size, sizeErr := strconv.ParseInt(totalText, 10, 64)
|
||||
|
||||
if !found || !hasTotal || !hasEnd || startErr != nil || endErr != nil || sizeErr != nil || start != localSize || start < 0 || end < start || size <= end {
|
||||
return 0, 0, 0, false, fmt.Errorf("invalid download content range %q for local size %d", header, localSize)
|
||||
}
|
||||
|
||||
length := end - start + 1
|
||||
if res.ContentLength >= 0 && res.ContentLength != length {
|
||||
return 0, 0, 0, false, fmt.Errorf("download content length %d does not match range length %d", res.ContentLength, length)
|
||||
}
|
||||
|
||||
return start, length, size, false, nil
|
||||
default:
|
||||
return 0, 0, 0, false, fmt.Errorf("unexpected download response status: %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
)
|
||||
|
||||
func TestDownloadFileResumesWithAndWithoutProgress(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("Range"); got != "bytes=7-" {
|
||||
t.Errorf("range = %q", got)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Range", "bytes 7-14/15")
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
_, _ = io.WriteString(w, "download")
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
for _, interactive := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "non-interactive", true: "interactive"}[interactive], func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "app.tmp")
|
||||
if err := os.WriteFile(path, []byte("partial"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
store := &appstore{httpClient: apphttp.NewClient[interface{}](apphttp.Args{}), os: operatingsystem.New()}
|
||||
|
||||
var progress *progressbar.ProgressBar
|
||||
if interactive {
|
||||
progress = progressbar.NewOptions64(15, progressbar.OptionSetWriter(io.Discard))
|
||||
}
|
||||
|
||||
if err := store.downloadFile(context.Background(), server.URL, path, progress); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if string(data) != "partialdownload" {
|
||||
t.Fatalf("download = %q", data)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadFileValidatesResumeResponses(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
status int
|
||||
rangeHeader string
|
||||
body string
|
||||
want string
|
||||
wantError bool
|
||||
chunked bool
|
||||
}{
|
||||
{name: "range ignored", status: http.StatusOK, body: "new", want: "new"},
|
||||
{name: "already complete", status: http.StatusRequestedRangeNotSatisfiable, rangeHeader: "bytes */7", body: "error page", want: "partial"},
|
||||
{name: "stale oversized partial", status: http.StatusRequestedRangeNotSatisfiable, rangeHeader: "bytes */3", body: "error page", want: "partial", wantError: true},
|
||||
{name: "incomplete rejected partial", status: http.StatusRequestedRangeNotSatisfiable, rangeHeader: "bytes */15", want: "partial", wantError: true},
|
||||
{name: "malformed unsatisfied range", status: http.StatusRequestedRangeNotSatisfiable, rangeHeader: "7", want: "partial", wantError: true},
|
||||
{name: "http error", status: http.StatusForbidden, body: "error page", want: "partial", wantError: true},
|
||||
{name: "wrong offset", status: http.StatusPartialContent, rangeHeader: "bytes 0-7/15", body: "download", want: "partial", wantError: true},
|
||||
{name: "missing range", status: http.StatusPartialContent, body: "download", want: "partial", wantError: true},
|
||||
{name: "malformed range", status: http.StatusPartialContent, rangeHeader: "bytes 7-x/15", body: "download", want: "partial", wantError: true},
|
||||
{name: "invalid total", status: http.StatusPartialContent, rangeHeader: "bytes 7-14/14", body: "download", want: "partial", wantError: true},
|
||||
{name: "length mismatch", status: http.StatusPartialContent, rangeHeader: "bytes 7-14/15", body: "bad", want: "partial", wantError: true},
|
||||
{name: "truncated chunked response", status: http.StatusPartialContent, rangeHeader: "bytes 7-14/15", body: "dow", want: "partialdow", wantError: true, chunked: true},
|
||||
} {
|
||||
for _, interactive := range []bool{false, true} {
|
||||
t.Run(test.name+map[bool]string{false: "/non-interactive", true: "/interactive"}[interactive], func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "app.tmp")
|
||||
if err := os.WriteFile(path, []byte("partial"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Range") != "bytes=7-" {
|
||||
t.Errorf("range = %q", r.Header.Get("Range"))
|
||||
}
|
||||
|
||||
if test.rangeHeader != "" {
|
||||
w.Header().Set("Content-Range", test.rangeHeader)
|
||||
}
|
||||
|
||||
w.WriteHeader(test.status)
|
||||
|
||||
if test.chunked {
|
||||
w.(http.Flusher).Flush()
|
||||
}
|
||||
|
||||
_, _ = io.WriteString(w, test.body)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
store := &appstore{httpClient: apphttp.NewClient[interface{}](apphttp.Args{}), os: operatingsystem.New()}
|
||||
|
||||
var progress *progressbar.ProgressBar
|
||||
if interactive {
|
||||
progress = progressbar.NewOptions64(1, progressbar.OptionSetWriter(io.Discard))
|
||||
}
|
||||
|
||||
err := store.downloadFile(context.Background(), server.URL, path, progress)
|
||||
if (err != nil) != test.wantError {
|
||||
t.Fatalf("download error = %v", err)
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if string(data) != test.want {
|
||||
t.Fatalf("file = %q, want %q", data, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -9,6 +11,7 @@ import (
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -35,6 +38,7 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockBagClient *http.MockClient[bagResult]
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockPlatformClient *http.MockClient[platformVersionLookupResult]
|
||||
mockStorefrontClient *http.MockClient[[]byte]
|
||||
@@ -49,6 +53,7 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockBagClient = http.NewMockClient[bagResult](ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
mockStorefrontClient = http.NewMockClient[[]byte](ctrl)
|
||||
@@ -59,6 +64,7 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
bagClient: mockBagClient,
|
||||
loginClient: mockLoginClient,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
@@ -403,10 +409,18 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: validBagResult(),
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
@@ -556,7 +570,9 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(&gohttp.Response{
|
||||
Body: io.NopCloser(strings.NewReader("ping")),
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Body: io.NopCloser(strings.NewReader("ping")),
|
||||
ContentLength: 4,
|
||||
}, nil)
|
||||
|
||||
})
|
||||
@@ -616,7 +632,9 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(&gohttp.Response{
|
||||
Body: io.NopCloser(strings.NewReader("ping")),
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Body: io.NopCloser(strings.NewReader("ping")),
|
||||
ContentLength: 4,
|
||||
}, nil)
|
||||
})
|
||||
|
||||
@@ -658,7 +676,7 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
|
||||
mockOS.EXPECT().
|
||||
Stat(gomock.Any()).
|
||||
Return(nil, nil)
|
||||
Return(&dummyFileInfo{}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Remove(tmpFile.Name()).
|
||||
@@ -698,6 +716,353 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
})
|
||||
})
|
||||
|
||||
DescribeTable("validates explicit or catalog-resolved platforms before replacing the output",
|
||||
func(platform Platform, versionID string, fallback string, supportedPlatform string, succeeds bool) {
|
||||
tempDir := GinkgoT().TempDir()
|
||||
outputPath := filepath.Join(tempDir, "app.ipa")
|
||||
previousOutput := []byte("previous output")
|
||||
Expect(os.WriteFile(outputPath, previousOutput, 0600)).To(Succeed())
|
||||
|
||||
packageBuffer := new(bytes.Buffer)
|
||||
packageWriter := zip.NewWriter(packageBuffer)
|
||||
infoWriter, err := packageWriter.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleSupportedPlatforms": []string{supportedPlatform},
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = infoWriter.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(packageWriter.Close()).To(Succeed())
|
||||
|
||||
response := http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{Items: []downloadItemResult{{
|
||||
URL: "https://example.test/app.ipa",
|
||||
Metadata: map[string]interface{}{"bundleShortVersionString": "1.0"},
|
||||
}}},
|
||||
}
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
if fallback != "" {
|
||||
bag := bagResult{URLBag: urlBag{RedownloadEndpoint: testRedownloadEndpoint, UpdateEndpoint: testUpdateEndpoint}}
|
||||
first := mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK}, nil)
|
||||
previous := mockBagClient.EXPECT().Send(gomock.Any()).After(first).
|
||||
Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil)
|
||||
resolvedVersion := versionID
|
||||
if resolvedVersion == "" {
|
||||
resolvedVersion = "890598805"
|
||||
previous = mockPlatformClient.EXPECT().Send(gomock.Any()).After(previous).
|
||||
Return(http.Result[platformVersionLookupResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: platformVersionLookupResult{Results: map[string]platformVersionLookupItem{
|
||||
"42": {Offers: []platformVersionLookupOffer{
|
||||
{Version: platformVersionLookupVersion{ExternalID: platformVersionExternalID(resolvedVersion)}},
|
||||
}},
|
||||
}},
|
||||
}, nil)
|
||||
}
|
||||
if fallback == "update" {
|
||||
previous = mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{CustomerMessage: "“Messenger” No Longer Available"}}, nil)
|
||||
response.Data.Items[0].Metadata["itemId"] = uint64(42)
|
||||
response.Data.Items[0].Metadata["softwareVersionExternalIdentifier"] = resolvedVersion
|
||||
response.Data.Items[0].Metadata["softwareVersionBundleId"] = "com.example.app"
|
||||
}
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", resolvedVersion))
|
||||
}).Return(response, nil)
|
||||
} else {
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(response, nil)
|
||||
}
|
||||
mockHTTPClient.EXPECT().NewRequest("GET", "https://example.test/app.ipa", nil).
|
||||
Return(&gohttp.Request{Header: gohttp.Header{}}, nil)
|
||||
mockHTTPClient.EXPECT().Do(gomock.Any()).Return(&gohttp.Response{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Body: io.NopCloser(bytes.NewReader(packageBuffer.Bytes())),
|
||||
ContentLength: int64(packageBuffer.Len()),
|
||||
}, nil)
|
||||
|
||||
store := &appstore{
|
||||
downloadClient: mockDownloadClient,
|
||||
bagClient: mockBagClient,
|
||||
platformClient: mockPlatformClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: operatingsystem.New(),
|
||||
}
|
||||
out, err := store.Download(DownloadInput{
|
||||
Account: Account{StoreFront: "143441", Email: "test@example.com"},
|
||||
App: App{ID: 42},
|
||||
OutputPath: outputPath,
|
||||
Platform: platform,
|
||||
ExternalVersionID: versionID,
|
||||
})
|
||||
if succeeds {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.DestinationPath).To(Equal(outputPath))
|
||||
actual, readErr := os.ReadFile(outputPath)
|
||||
Expect(readErr).ToNot(HaveOccurred())
|
||||
Expect(actual).ToNot(Equal(previousOutput))
|
||||
} else {
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to validate package platform")))
|
||||
Expect(out.DestinationPath).To(BeEmpty())
|
||||
Expect(os.ReadFile(outputPath)).To(Equal(previousOutput))
|
||||
}
|
||||
Expect(outputPath + ".tmp").ToNot(BeAnExistingFile())
|
||||
},
|
||||
Entry("iPhone accepts iOS", PlatformIPhone, "", "", "iPhoneOS", true),
|
||||
Entry("iPad accepts iOS", PlatformIPad, "", "", "iPhoneOS", true),
|
||||
Entry("iPhone rejects tvOS", PlatformIPhone, "", "", "AppleTVOS", false),
|
||||
Entry("iPad rejects tvOS", PlatformIPad, "", "", "AppleTVOS", false),
|
||||
Entry("iPhone rejects visionOS", PlatformIPhone, "", "", "XROS", false),
|
||||
Entry("a conflicting explicit version is rejected, not replaced", PlatformIPhone, "818970197", "", "AppleTVOS", false),
|
||||
Entry("default iOS fallback accepts iOS", Platform(""), "", "redownload", "iPhoneOS", true),
|
||||
Entry("default iOS fallback rejects tvOS", Platform(""), "", "redownload", "AppleTVOS", false),
|
||||
Entry("latest update accepts iOS", Platform(""), "", "update", "iPhoneOS", true),
|
||||
Entry("pinned update accepts iOS", Platform(""), "818970197", "update", "iPhoneOS", true),
|
||||
Entry("pinned update rejects tvOS", Platform(""), "818970197", "update", "AppleTVOS", false),
|
||||
Entry("pinned redownload preserves an unspecified platform", Platform(""), "818970197", "redownload", "AppleTVOS", true),
|
||||
Entry("normal unspecified-platform behavior is preserved", Platform(""), "", "", "AppleTVOS", true),
|
||||
Entry("an explicit tvOS version without a platform is preserved", Platform(""), "818970197", "", "AppleTVOS", true),
|
||||
Entry("explicit tvOS downloads still work", PlatformAppleTV, "818970197", "", "AppleTVOS", true),
|
||||
)
|
||||
|
||||
Describe("macOS packages", func() {
|
||||
It("decrypts the downloaded package with in-memory machine identity and dpInfo", func() {
|
||||
tempDir := GinkgoT().TempDir()
|
||||
requestedPath := filepath.Join(tempDir, "custom-output.pkg")
|
||||
packageData := []byte("encrypted package")
|
||||
decryptedData := makeTestXAR([]byte("decrypted payload"), false)
|
||||
dpInfo := bytes.Repeat([]byte{0x42}, 88)
|
||||
decrypter := &fakeMacPackageDecrypter{output: decryptedData}
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:aa:bb:cc", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
payload := req.Payload.(*http.XMLPayload)
|
||||
Expect(payload.Content["guid"]).To(Equal("001122AABBCC"))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{
|
||||
StatusCode: 200,
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{{
|
||||
URL: "https://example.test/app.pkg",
|
||||
Sinfs: []Sinf{{DPInfo: dpInfo}},
|
||||
Metadata: map[string]interface{}{
|
||||
"bundleShortVersionString": "1.2.3",
|
||||
"software-platform": "macos",
|
||||
"product-type": "ios-app",
|
||||
},
|
||||
}},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", "https://example.test/app.pkg", nil).
|
||||
Return(&gohttp.Request{Header: gohttp.Header{}}, nil)
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(&gohttp.Response{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Body: io.NopCloser(bytes.NewReader(packageData)),
|
||||
ContentLength: int64(len(packageData)),
|
||||
}, nil)
|
||||
|
||||
store := &appstore{
|
||||
downloadClient: mockDownloadClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: operatingsystem.New(),
|
||||
macDecrypterFactory: func(ctx context.Context, hardwareID, gotDPInfo []byte) (macPackageDecrypter, error) {
|
||||
Expect(ctx).ToNot(BeNil())
|
||||
Expect(hardwareID).To(Equal([]byte{0x00, 0x11, 0x22, 0xaa, 0xbb, 0xcc}))
|
||||
Expect(gotDPInfo).To(Equal(dpInfo))
|
||||
|
||||
return decrypter, nil
|
||||
},
|
||||
}
|
||||
out, err := store.Download(DownloadInput{
|
||||
Context: context.Background(),
|
||||
App: App{ID: 42, BundleID: "com.example.mac"},
|
||||
OutputPath: requestedPath,
|
||||
Platform: PlatformMacOS,
|
||||
ExternalVersionID: "123456789",
|
||||
})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out).To(Equal(DownloadOutput{DestinationPath: requestedPath}))
|
||||
Expect(decrypter.input).To(Equal(packageData))
|
||||
Expect(os.ReadFile(requestedPath)).To(Equal(decryptedData))
|
||||
Expect(requestedPath + macDPInfoSuffix).ToNot(BeAnExistingFile())
|
||||
Expect(requestedPath + macHWInfoSuffix).ToNot(BeAnExistingFile())
|
||||
})
|
||||
|
||||
It("downloads an iOS app available on macOS through the mobile package pipeline", func() {
|
||||
tempDir := GinkgoT().TempDir()
|
||||
requestedPath := filepath.Join(tempDir, "developer.apple.wwdc-Release_640199958_11.0.2.ipa")
|
||||
packageBuffer := new(bytes.Buffer)
|
||||
packageWriter := zip.NewWriter(packageBuffer)
|
||||
infoWriter, err := packageWriter.Create("Payload/Developer.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleExecutable": "Developer",
|
||||
"CFBundleSupportedPlatforms": []string{"iPhoneOS"},
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = infoWriter.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(packageWriter.Close()).To(Succeed())
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:aa:bb:cc", nil)
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
StatusCode: 200,
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{{
|
||||
URL: "https://example.test/developer.ipa",
|
||||
Sinfs: []Sinf{{
|
||||
ID: 0,
|
||||
Data: []byte("mobile sinf"),
|
||||
}},
|
||||
Metadata: map[string]interface{}{
|
||||
"bundleShortVersionString": "11.0.2",
|
||||
"software-platform": "ios",
|
||||
"product-type": "ios-app",
|
||||
},
|
||||
}},
|
||||
},
|
||||
}, nil)
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", "https://example.test/developer.ipa", nil).
|
||||
Return(&gohttp.Request{Header: gohttp.Header{}}, nil)
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(gomock.Any()).
|
||||
Return(&gohttp.Response{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Body: io.NopCloser(bytes.NewReader(packageBuffer.Bytes())),
|
||||
ContentLength: int64(packageBuffer.Len()),
|
||||
}, nil)
|
||||
|
||||
store := &appstore{
|
||||
downloadClient: mockDownloadClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: operatingsystem.New(),
|
||||
macDecrypterFactory: func(context.Context, []byte, []byte) (macPackageDecrypter, error) {
|
||||
Fail("mobile packages must not initialize the macOS package decrypter")
|
||||
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
|
||||
out, err := store.Download(DownloadInput{
|
||||
Context: context.Background(),
|
||||
Account: Account{Email: "test@example.com"},
|
||||
App: App{ID: 640199958, BundleID: "developer.apple.wwdc-Release"},
|
||||
OutputPath: tempDir,
|
||||
Platform: PlatformMacOS,
|
||||
ExternalVersionID: "123456789",
|
||||
})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.DestinationPath).To(Equal(requestedPath))
|
||||
Expect(out.Sinfs).To(Equal([]Sinf{{ID: 0, Data: []byte("mobile sinf")}}))
|
||||
Expect(requestedPath).To(BeAnExistingFile())
|
||||
Expect(requestedPath + macEncryptedStageSuffix).ToNot(BeAnExistingFile())
|
||||
Expect(requestedPath + macDecryptedStageSuffix).ToNot(BeAnExistingFile())
|
||||
})
|
||||
|
||||
It("uses a pkg name derived from the generated package name", func() {
|
||||
store := &appstore{os: operatingsystem.New()}
|
||||
tempDir := GinkgoT().TempDir()
|
||||
|
||||
packagePath, err := store.resolveDestinationPath(
|
||||
App{ID: 42, BundleID: "com.example.mac"},
|
||||
"1.2.3",
|
||||
tempDir,
|
||||
PlatformMacOS,
|
||||
)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(packagePath).To(Equal(filepath.Join(tempDir, "com.example.mac_42_1.2.3.pkg")))
|
||||
})
|
||||
|
||||
It("preserves an explicit output path", func() {
|
||||
store := &appstore{os: operatingsystem.New()}
|
||||
tempDir := GinkgoT().TempDir()
|
||||
requestedPath := filepath.Join(tempDir, "custom-output")
|
||||
|
||||
packagePath, err := store.resolveDestinationPath(App{}, "1.2.3", requestedPath, PlatformMacOS)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(packagePath).To(Equal(requestedPath))
|
||||
})
|
||||
|
||||
It("rejects a download response without dpInfo", func() {
|
||||
_, err := macDPInfo(nil)
|
||||
Expect(err).To(MatchError(ContainSubstring("dpInfo")))
|
||||
})
|
||||
|
||||
It("rejects conflicting dpInfo values", func() {
|
||||
_, err := macDPInfo([]Sinf{{DPInfo: []byte("one")}, {DPInfo: []byte("two")}})
|
||||
Expect(err).To(MatchError(ContainSubstring("conflicting")))
|
||||
})
|
||||
})
|
||||
|
||||
When("resuming a download without a progress bar", func() {
|
||||
It("appends the ranged response to the partial file", func() {
|
||||
testFile, err := os.CreateTemp("", "ipatool-download-*")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
defer os.Remove(testFile.Name())
|
||||
|
||||
_, err = testFile.WriteString("partial-")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = testFile.Seek(0, io.SeekStart)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
request := &gohttp.Request{Header: make(gohttp.Header)}
|
||||
info, err := testFile.Stat()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
mockHTTPClient.EXPECT().
|
||||
NewRequest("GET", "https://example.com/app.ipa", nil).
|
||||
Return(request, nil)
|
||||
mockOS.EXPECT().
|
||||
OpenFile(testFile.Name(), os.O_CREATE|os.O_RDWR, os.FileMode(0644)).
|
||||
Return(testFile, nil)
|
||||
mockOS.EXPECT().
|
||||
Stat(testFile.Name()).
|
||||
Return(info, nil)
|
||||
mockHTTPClient.EXPECT().
|
||||
Do(request.WithContext(context.Background())).
|
||||
DoAndReturn(func(request *gohttp.Request) (*gohttp.Response, error) {
|
||||
Expect(request.Header.Get("range")).To(Equal("bytes=8-"))
|
||||
|
||||
return &gohttp.Response{
|
||||
StatusCode: gohttp.StatusPartialContent,
|
||||
Header: gohttp.Header{"Content-Range": []string{"bytes 8-16/17"}},
|
||||
ContentLength: 9,
|
||||
Body: io.NopCloser(strings.NewReader("remainder")),
|
||||
}, nil
|
||||
})
|
||||
|
||||
err = as.(*appstore).downloadFile(context.Background(), "https://example.com/app.ipa", testFile.Name(), nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
data, err := os.ReadFile(testFile.Name())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(string(data)).To(Equal("partial-remainder"))
|
||||
})
|
||||
})
|
||||
|
||||
Describe("package platform validation", func() {
|
||||
writePackageWithInfoPlists := func(infoPlists map[string][]string) string {
|
||||
file, err := os.CreateTemp("", "ipatool-platform-*.ipa")
|
||||
@@ -736,6 +1101,36 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
DescribeTable("validates iOS packages",
|
||||
func(platform Platform, supportedPlatforms []string, succeeds bool) {
|
||||
path := writePackage(supportedPlatforms)
|
||||
defer os.Remove(path)
|
||||
|
||||
err := (&appstore{}).validatePackagePlatform(path, platform)
|
||||
if succeeds {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
} else {
|
||||
Expect(err).To(MatchError(ContainSubstring("iPhoneOS")))
|
||||
}
|
||||
},
|
||||
Entry("iPhone accepts iPhoneOS", PlatformIPhone, []string{"iPhoneOS"}, true),
|
||||
Entry("iPad accepts iPhoneOS", PlatformIPad, []string{"iPhoneOS"}, true),
|
||||
Entry("iPhone rejects AppleTVOS", PlatformIPhone, []string{"AppleTVOS"}, false),
|
||||
Entry("iPad rejects XROS", PlatformIPad, []string{"XROS"}, false),
|
||||
Entry("missing platform declaration", PlatformIPhone, []string{}, false),
|
||||
)
|
||||
|
||||
It("does not accept iOS support declared only by an embedded app", func() {
|
||||
path := writePackageWithInfoPlists(map[string][]string{
|
||||
"Payload/Test.app/Info.plist": {"AppleTVOS"},
|
||||
"Payload/Test.app/PlugIns/iOS.app/Info.plist": {"iPhoneOS"},
|
||||
})
|
||||
defer os.Remove(path)
|
||||
|
||||
err := (&appstore{}).validatePackagePlatform(path, PlatformIPhone)
|
||||
Expect(err).To(MatchError(ContainSubstring("iPhoneOS")))
|
||||
})
|
||||
|
||||
It("returns an error for packages without AppleTVOS support", func() {
|
||||
path := writePackage([]string{"iPhoneOS"})
|
||||
defer os.Remove(path)
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type GetVersionMetadataInput struct {
|
||||
Context context.Context
|
||||
Account Account
|
||||
App App
|
||||
VersionID string
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
type GetVersionMetadataOutput struct {
|
||||
@@ -21,6 +22,17 @@ type GetVersionMetadataOutput struct {
|
||||
}
|
||||
|
||||
func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersionMetadataOutput, error) {
|
||||
platform := input.Platform
|
||||
if platform == "" {
|
||||
platform = PlatformIPhone
|
||||
}
|
||||
|
||||
switch platform {
|
||||
case PlatformIPhone, PlatformIPad, PlatformAppleTV, PlatformVisionOS, PlatformMacOS:
|
||||
default:
|
||||
return GetVersionMetadataOutput{}, fmt.Errorf("invalid platform %q", platform)
|
||||
}
|
||||
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
@@ -28,11 +40,9 @@ func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersion
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
req := t.getVersionMetadataRequest(input.Account, input.App, guid, input.VersionID)
|
||||
res, err := t.downloadClient.Send(req)
|
||||
|
||||
res, _, err := t.sendDownloadProduct(input.Account, input.App, guid, input.VersionID, platform)
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
return GetVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired || res.Data.FailureType == FailureTypeSignInRequired {
|
||||
@@ -43,7 +53,7 @@ func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersion
|
||||
return GetVersionMetadataOutput{}, ErrLicenseRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
if res.Data.CustomerMessage != "" && (res.Data.FailureType != "" || len(res.Data.Items) == 0) {
|
||||
return GetVersionMetadataOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
@@ -56,6 +66,26 @@ func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersion
|
||||
}
|
||||
|
||||
item := res.Data.Items[0]
|
||||
if platform == PlatformMacOS {
|
||||
packagePlatform, err := downloadPackagePlatform(platform, item)
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
if packagePlatform == PlatformMacOS {
|
||||
_, hardwareID, err := machineIdentity(macAddr)
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
metadata, err := t.readVersionMetadataFromMacPackage(input.Context, item, hardwareID, input.App.BundleID)
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, fmt.Errorf("failed to read macOS version metadata: %w", err)
|
||||
}
|
||||
|
||||
return GetVersionMetadataOutput(metadata), nil
|
||||
}
|
||||
}
|
||||
|
||||
// Do not fall back to item.Metadata here. The App Store download API can
|
||||
// return stale version and release date values, so the IPA Info.plist is the
|
||||
@@ -67,32 +97,3 @@ func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersion
|
||||
|
||||
return GetVersionMetadataOutput(metadata), nil
|
||||
}
|
||||
|
||||
func (t *appstore) getVersionMetadataRequest(acc Account, app App, guid string, version string) http.Request {
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
"externalVersionId": version,
|
||||
"serialNumber": "0",
|
||||
}
|
||||
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,7 @@ var _ = Describe("AppStore (GetVersionMetadata)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockMachine *machine.MockMachine
|
||||
mockBagClient *http.MockClient[bagResult]
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
as AppStore
|
||||
)
|
||||
@@ -178,9 +179,11 @@ var _ = Describe("AppStore (GetVersionMetadata)", func() {
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
mockBagClient = http.NewMockClient[bagResult](ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
as = &appstore{
|
||||
machine: mockMachine,
|
||||
bagClient: mockBagClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
httpClient: http.NewClient[interface{}](http.Args{}),
|
||||
}
|
||||
@@ -370,10 +373,18 @@ var _ = Describe("AppStore (GetVersionMetadata)", func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: validBagResult(),
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
@@ -462,6 +473,41 @@ var _ = Describe("AppStore (GetVersionMetadata)", func() {
|
||||
})
|
||||
})
|
||||
|
||||
It("preserves the requested historical version through the redownload fallback", func() {
|
||||
const versionID = "818970197"
|
||||
releaseDate := time.Date(2016, 12, 15, 12, 0, 0, 0, time.UTC)
|
||||
server, _, _ := testIPAServer(testIPA("1.0", releaseDate.Format(time.RFC3339), releaseDate))
|
||||
defer server.Close()
|
||||
|
||||
bag := validBagResult()
|
||||
bag.URLBag.RedownloadEndpoint = testRedownloadEndpoint
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
gomock.InOrder(
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", versionID))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK}, nil),
|
||||
mockBagClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
payload := req.Payload.(*http.XMLPayload).Content
|
||||
Expect(payload).To(HaveKeyWithValue("appExtVrsId", versionID))
|
||||
Expect(payload).ToNot(HaveKey("externalVersionId"))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{Items: []downloadItemResult{{URL: server.URL}}}}, nil),
|
||||
)
|
||||
|
||||
output, err := as.GetVersionMetadata(GetVersionMetadataInput{
|
||||
App: App{ID: 547702041}, VersionID: versionID,
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(output.DisplayVersion).To(Equal("1.0"))
|
||||
Expect(output.ReleaseDate).To(Equal(releaseDate))
|
||||
})
|
||||
|
||||
When("successfully gets version metadata", func() {
|
||||
var (
|
||||
server *httptest.Server
|
||||
|
||||
@@ -4,13 +4,12 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type ListVersionsInput struct {
|
||||
Account Account
|
||||
App App
|
||||
Account Account
|
||||
App App
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
type ListVersionsOutput struct {
|
||||
@@ -19,6 +18,17 @@ type ListVersionsOutput struct {
|
||||
}
|
||||
|
||||
func (t *appstore) ListVersions(input ListVersionsInput) (ListVersionsOutput, error) {
|
||||
platform := input.Platform
|
||||
if platform == "" {
|
||||
platform = PlatformIPhone
|
||||
}
|
||||
|
||||
switch platform {
|
||||
case PlatformIPhone, PlatformIPad, PlatformAppleTV, PlatformVisionOS, PlatformMacOS:
|
||||
default:
|
||||
return ListVersionsOutput{}, fmt.Errorf("invalid platform %q", platform)
|
||||
}
|
||||
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return ListVersionsOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
@@ -26,11 +36,22 @@ func (t *appstore) ListVersions(input ListVersionsInput) (ListVersionsOutput, er
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
req := t.listVersionsRequest(input.Account, input.App, guid)
|
||||
res, err := t.downloadClient.Send(req)
|
||||
var externalVersionID string
|
||||
|
||||
switch platform {
|
||||
case PlatformMacOS:
|
||||
externalVersionID, err = t.lookupLatestMacOSExternalVersionID(input.Account, input.App)
|
||||
case PlatformAppleTV, PlatformVisionOS:
|
||||
externalVersionID, err = t.lookupLatestExternalVersionID(input.Account, input.App, platform)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return ListVersionsOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
return ListVersionsOutput{}, fmt.Errorf("failed to resolve platform version: %w", err)
|
||||
}
|
||||
|
||||
res, _, err := t.sendDownloadProduct(input.Account, input.App, guid, externalVersionID, platform)
|
||||
if err != nil {
|
||||
return ListVersionsOutput{}, err
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired || res.Data.FailureType == FailureTypeSignInRequired {
|
||||
@@ -41,7 +62,7 @@ func (t *appstore) ListVersions(input ListVersionsInput) (ListVersionsOutput, er
|
||||
return ListVersionsOutput{}, ErrLicenseRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
if res.Data.CustomerMessage != "" && (res.Data.FailureType != "" || len(res.Data.Items) == 0) {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
@@ -75,31 +96,3 @@ func (t *appstore) ListVersions(input ListVersionsInput) (ListVersionsOutput, er
|
||||
LatestExternalVersionID: fmt.Sprintf("%v", latestExternalVersionID),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *appstore) listVersionsRequest(acc Account, app App, guid string) http.Request {
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
"serialNumber": "0",
|
||||
}
|
||||
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
gohttp "net/http"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
@@ -13,17 +14,23 @@ import (
|
||||
var _ = Describe("AppStore (ListVersions)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockBagClient *http.MockClient[bagResult]
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockPlatformClient *http.MockClient[platformVersionLookupResult]
|
||||
mockMachine *machine.MockMachine
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockBagClient = http.NewMockClient[bagResult](ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
bagClient: mockBagClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
machine: mockMachine,
|
||||
}
|
||||
})
|
||||
@@ -32,6 +39,42 @@ var _ = Describe("AppStore (ListVersions)", func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
It("pins the Mac offer before requesting a universal app's version history", func() {
|
||||
pages := http.NewMockClient[[]byte](ctrl)
|
||||
as.(*appstore).storefrontClient = pages
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
gomock.InOrder(
|
||||
pages.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal("https://apps.apple.com/de/app/id6472431552?platform=mac"))
|
||||
}).Return(http.Result[[]byte]{StatusCode: gohttp.StatusOK, Data: macVersionPage(karingMacConfiguration)}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(ContainSubstring("volumeStoreDownloadProduct"))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", "876660716"))
|
||||
}).Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{Items: []downloadItemResult{{Metadata: map[string]interface{}{
|
||||
"softwareVersionExternalIdentifiers": []interface{}{uint64(876660700), uint64(876660716)},
|
||||
"softwareVersionExternalIdentifier": uint64(876660716),
|
||||
}}}}}, nil),
|
||||
)
|
||||
out, err := as.ListVersions(ListVersionsInput{Account: Account{StoreFront: "143443-2,34"}, App: App{ID: 6472431552, BundleID: "com.nebula.karing"}, Platform: PlatformMacOS})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.ExternalVersionIdentifiers).To(Equal([]string{"876660700", "876660716"}))
|
||||
Expect(out.LatestExternalVersionID).To(Equal("876660716"))
|
||||
})
|
||||
|
||||
It("does not fall back to iOS when the Mac version cannot be resolved", func() {
|
||||
pages := http.NewMockClient[[]byte](ctrl)
|
||||
as.(*appstore).storefrontClient = pages
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
pages.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: gohttp.StatusOK, Data: macVersionPage(`{}`)}, nil)
|
||||
_, err := as.ListVersions(ListVersionsInput{Account: Account{StoreFront: "143443-2,34"}, App: App{ID: 42}, Platform: PlatformMacOS})
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to resolve platform version")))
|
||||
})
|
||||
|
||||
It("rejects unsupported platforms before making requests", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{Platform: PlatformUnknown})
|
||||
Expect(err).To(MatchError(`invalid platform "unknown"`))
|
||||
})
|
||||
|
||||
When("fails to get MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
@@ -209,10 +252,18 @@ var _ = Describe("AppStore (ListVersions)", func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: validBagResult(),
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
@@ -277,6 +328,44 @@ var _ = Describe("AppStore (ListVersions)", func() {
|
||||
})
|
||||
})
|
||||
|
||||
It("lists the iOS history from a version-pinned fallback", func() {
|
||||
const latest = "890598805"
|
||||
bag := validBagResult()
|
||||
bag.URLBag.RedownloadEndpoint = testRedownloadEndpoint
|
||||
catalog := platformVersionLookupResult{Results: map[string]platformVersionLookupItem{
|
||||
"547702041": {Offers: []platformVersionLookupOffer{
|
||||
{Version: platformVersionLookupVersion{ExternalID: platformVersionExternalID(latest)}},
|
||||
}},
|
||||
}}
|
||||
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
gomock.InOrder(
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK}, nil),
|
||||
mockBagClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: catalog}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", latest))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{Items: []downloadItemResult{{Metadata: map[string]interface{}{
|
||||
"softwareVersionExternalIdentifiers": []interface{}{"9660833", latest},
|
||||
"softwareVersionExternalIdentifier": latest,
|
||||
}}}}}, nil),
|
||||
)
|
||||
|
||||
out, err := as.ListVersions(ListVersionsInput{
|
||||
Account: Account{StoreFront: "143441-1,34"},
|
||||
App: App{ID: 547702041},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.ExternalVersionIdentifiers).To(Equal([]string{"9660833", latest}))
|
||||
Expect(out.LatestExternalVersionID).To(Equal(latest))
|
||||
})
|
||||
|
||||
When("successfully lists versions", func() {
|
||||
const (
|
||||
testVersion1 = "12345678"
|
||||
|
||||
@@ -19,7 +19,8 @@ var (
|
||||
|
||||
const (
|
||||
maxAuthenticationRequestAttempts = 3
|
||||
authenticationRetryDelay = 250 * time.Millisecond
|
||||
authenticationRetryDelay = 10 * time.Second
|
||||
maxAuthenticationRetryDelay = 30 * time.Second
|
||||
)
|
||||
|
||||
type LoginInput struct {
|
||||
@@ -128,7 +129,16 @@ func (t *appstore) login(email, password, authCode, guid, endpoint string, signe
|
||||
res, err = t.sendAuthenticationRequest(request)
|
||||
|
||||
if err != nil {
|
||||
return Account{}, fmt.Errorf("request failed: %w", err)
|
||||
stage := "sign-in"
|
||||
if authCode != "" {
|
||||
stage = "2FA verification"
|
||||
}
|
||||
|
||||
if redirect != "" {
|
||||
stage += " at Store pod"
|
||||
}
|
||||
|
||||
return Account{}, fmt.Errorf("%s request failed: %w", stage, err)
|
||||
}
|
||||
|
||||
if retry, redirect, err = t.parseLoginResponse(&res, attempt, authCode); err != nil {
|
||||
@@ -188,7 +198,7 @@ func (t *appstore) sendAuthenticationRequest(request http.Request) (http.Result[
|
||||
status, retry := retryableAuthenticationError(err)
|
||||
if !retry {
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("%w", err)
|
||||
return result, authenticationRequestError(err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
@@ -199,11 +209,25 @@ func (t *appstore) sendAuthenticationRequest(request http.Request) (http.Result[
|
||||
if attempt == maxAuthenticationRequestAttempts {
|
||||
return result, fmt.Errorf(
|
||||
"authentication request failed after %d attempts (HTTP %s): %w",
|
||||
maxAuthenticationRequestAttempts, strings.Join(statuses, ", "), err,
|
||||
maxAuthenticationRequestAttempts, strings.Join(statuses, ", "), authenticationRequestError(err),
|
||||
)
|
||||
}
|
||||
|
||||
sleep(time.Duration(attempt) * authenticationRetryDelay)
|
||||
delay := min(authenticationRetryDelay<<(attempt-1), maxAuthenticationRetryDelay)
|
||||
|
||||
var responseErr *http.UnexpectedResponseError
|
||||
if errors.As(err, &responseErr) {
|
||||
if requested, ok := authenticationRetryAfter(responseErr.RetryAfter, time.Now()); ok {
|
||||
if requested > maxAuthenticationRetryDelay {
|
||||
return result, fmt.Errorf("apple requested a wait longer than %s; try again later: %w", maxAuthenticationRetryDelay, err)
|
||||
}
|
||||
|
||||
// Retry-After takes precedence over the fallback backoff.
|
||||
delay = max(requested, time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
sleep(delay)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,6 +240,7 @@ func retryableAuthenticationError(err error) (int, bool) {
|
||||
status := responseErr.StatusCode
|
||||
retry := status == gohttp.StatusNoContent ||
|
||||
status == gohttp.StatusNotFound ||
|
||||
status == gohttp.StatusTooManyRequests ||
|
||||
status/100 == 5
|
||||
|
||||
return status, retry
|
||||
@@ -249,7 +274,7 @@ func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int
|
||||
err = NewErrorWithMetadata(errors.New("something went wrong"), res)
|
||||
}
|
||||
} else if res.StatusCode != gohttp.StatusOK || res.Data.PasswordToken == "" || res.Data.DirectoryServicesID == "" {
|
||||
err = NewErrorWithMetadata(errors.New("something went wrong"), res)
|
||||
err = fmt.Errorf("apple returned no usable authentication response (HTTP %d): missing account credentials or unexpected status; try again later or from another network", res.StatusCode)
|
||||
}
|
||||
|
||||
return retry, redirect, err
|
||||
@@ -276,3 +301,35 @@ func (t *appstore) loginRequest(email, password, authCode, guid, endpoint string
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func authenticationRequestError(err error) error {
|
||||
var responseErr *http.UnexpectedResponseError
|
||||
if !errors.As(err, &responseErr) {
|
||||
return err
|
||||
}
|
||||
|
||||
if responseErr.StatusCode == gohttp.StatusTooManyRequests {
|
||||
return fmt.Errorf("apple rate limited authentication; try again later: %w", err)
|
||||
}
|
||||
|
||||
return fmt.Errorf("apple returned no usable authentication response; try again later or from another network: %w", err)
|
||||
}
|
||||
|
||||
func authenticationRetryAfter(value string, now time.Time) (time.Duration, bool) {
|
||||
value = strings.TrimSpace(value)
|
||||
if seconds, err := strconv.ParseUint(value, 10, 64); err == nil {
|
||||
// Saturate before converting to Duration to avoid overflow. A wait over
|
||||
// the budget ends this login rather than retrying before Apple's deadline.
|
||||
if seconds > uint64(maxAuthenticationRetryDelay/time.Second) {
|
||||
return maxAuthenticationRetryDelay + time.Second, true
|
||||
}
|
||||
|
||||
return time.Duration(seconds) * time.Second, true
|
||||
}
|
||||
|
||||
if date, err := gohttp.ParseTime(value); err == nil {
|
||||
return max(time.Duration(0), date.Sub(now)), true
|
||||
}
|
||||
|
||||
return 0, false
|
||||
}
|
||||
@@ -310,7 +310,7 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(MatchError("request failed: test complete"))
|
||||
Expect(err).To(MatchError("sign-in at Store pod request failed: test complete"))
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -86,6 +86,29 @@ var _ = Describe("AppStore (Lookup)", func() {
|
||||
})
|
||||
})
|
||||
|
||||
When("platform is macOS", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
parsedURL, err := url.Parse(req.URL)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(parsedURL.Query().Get("entity")).To(Equal("macSoftware"))
|
||||
}).
|
||||
Return(http.Result[searchResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("uses the macOS lookup entity", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
Platform: PlatformMacOS,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("platform is AppleTV", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
func (t *appstore) lookupLatestMacOSExternalVersionID(acc Account, app App) (string, error) {
|
||||
countryCode, err := countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve the country code: %w", err)
|
||||
}
|
||||
|
||||
// The legacy MDM lookup can return an iOS offer even with platform=osx.
|
||||
// Use the Mac product page to select the native Mac offer instead.
|
||||
res, err := t.storefrontClient.Send(http.Request{
|
||||
URL: fmt.Sprintf("https://apps.apple.com/%s/app/id%d?platform=mac", strings.ToLower(countryCode), app.ID),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatRaw,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("macOS version lookup request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return "", fmt.Errorf("macOS version lookup returned HTTP %d", res.StatusCode)
|
||||
}
|
||||
|
||||
return macOSExternalVersionID(res.Data, app)
|
||||
}
|
||||
|
||||
func macOSExternalVersionID(body []byte, app App) (string, error) {
|
||||
data, err := serializedServerData(body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var value interface{}
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
return "", fmt.Errorf("failed to decode Mac product page: %w", err)
|
||||
}
|
||||
|
||||
versions := make(map[string]struct{})
|
||||
collectMacOSExternalVersions(value, app, versions)
|
||||
|
||||
if len(versions) == 0 {
|
||||
return "", errors.New("macOS purchase configuration has no external version id for the requested app")
|
||||
}
|
||||
|
||||
if len(versions) != 1 {
|
||||
return "", errors.New("macOS purchase configurations contain conflicting external version ids")
|
||||
}
|
||||
|
||||
for version := range versions {
|
||||
return version, nil
|
||||
}
|
||||
|
||||
return "", errors.New("macOS external version id was not found")
|
||||
}
|
||||
|
||||
func collectMacOSExternalVersions(value interface{}, app App, versions map[string]struct{}) {
|
||||
switch value := value.(type) {
|
||||
case []interface{}:
|
||||
for _, child := range value {
|
||||
collectMacOSExternalVersions(child, app, versions)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
if configuration, ok := value["purchaseConfiguration"].(map[string]interface{}); ok {
|
||||
platforms, _ := configuration["appPlatforms"].([]interface{})
|
||||
bundleID, _ := configuration["bundleId"].(string)
|
||||
buyParams, _ := configuration["buyParams"].(string)
|
||||
|
||||
params, err := url.ParseQuery(buyParams)
|
||||
if err == nil && slices.Contains(platforms, interface{}("mac")) &&
|
||||
params.Get("salableAdamId") == strconv.FormatInt(app.ID, 10) &&
|
||||
(app.BundleID == "" || app.BundleID == bundleID) {
|
||||
version := params.Get("appExtVrsId")
|
||||
if id, err := strconv.ParseUint(version, 10, 64); err == nil && id != 0 {
|
||||
versions[version] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, child := range value {
|
||||
collectMacOSExternalVersions(child, app, versions)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
gohttp "net/http"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
const karingMacConfiguration = `{"purchaseConfiguration":{"bundleId":"com.nebula.karing","appPlatforms":["mac","tv","phone","pad"],"metricsPlatformDisplayStyle":"ios","buyParams":"salableAdamId=6472431552&appExtVrsId=876660716"}}`
|
||||
|
||||
func macVersionPage(configuration string) []byte {
|
||||
return []byte(`<script id="serialized-server-data">` + configuration + `</script>`)
|
||||
}
|
||||
|
||||
var _ = Describe("Mac purchase version selection", func() {
|
||||
app := App{ID: 6472431552, BundleID: "com.nebula.karing"}
|
||||
|
||||
It("selects Karing's Mac offer and ignores unrelated and iOS offers", func() {
|
||||
body := macVersionPage(`[{"purchaseConfiguration":{"bundleId":"com.nebula.karing","appPlatforms":["phone","pad"],"buyParams":"salableAdamId=6472431552&appExtVrsId=891116578"}}, {"purchaseConfiguration":{"appPlatforms":["mac"],"buyParams":"salableAdamId=100&appExtVrsId=123"}}, ` + karingMacConfiguration + `]`)
|
||||
version, err := macOSExternalVersionID(body, app)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(version).To(Equal("876660716"))
|
||||
})
|
||||
|
||||
DescribeTable("rejects invalid catalog metadata", func(configuration string) {
|
||||
_, err := macOSExternalVersionID(macVersionPage(configuration), app)
|
||||
Expect(err).To(HaveOccurred())
|
||||
},
|
||||
Entry("invalid JSON", `{`),
|
||||
Entry("no offer", `{}`),
|
||||
Entry("iOS only", `{"purchaseConfiguration":{"bundleId":"com.nebula.karing","appPlatforms":["phone","pad"],"buyParams":"salableAdamId=6472431552&appExtVrsId=891116578"}}`),
|
||||
Entry("wrong bundle", `{"purchaseConfiguration":{"bundleId":"other","appPlatforms":["mac"],"buyParams":"salableAdamId=6472431552&appExtVrsId=123"}}`),
|
||||
Entry("invalid version", `{"purchaseConfiguration":{"bundleId":"com.nebula.karing","appPlatforms":["mac"],"buyParams":"salableAdamId=6472431552&appExtVrsId=invalid"}}`),
|
||||
Entry("conflicting offers", `[`+karingMacConfiguration+`,{"purchaseConfiguration":{"bundleId":"com.nebula.karing","appPlatforms":["mac"],"buyParams":"salableAdamId=6472431552&appExtVrsId=123"}}]`),
|
||||
)
|
||||
|
||||
DescribeTable("pins the Mac offer before requesting a package", func(downloadErr error) {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
defer ctrl.Finish()
|
||||
downloads := http.NewMockClient[downloadResult](ctrl)
|
||||
pages := http.NewMockClient[[]byte](ctrl)
|
||||
store := &appstore{downloadClient: downloads, storefrontClient: pages}
|
||||
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) {
|
||||
Expect(req.URL).To(Equal("https://apps.apple.com/de/app/id6472431552?platform=mac"))
|
||||
}).Return(http.Result[[]byte]{StatusCode: gohttp.StatusOK, Data: macVersionPage(karingMacConfiguration)}, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(store.volumeStoreEndpoint(Account{}).baseURL + "?guid=001122334455"))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", "876660716"))
|
||||
}).Return(expected, downloadErr),
|
||||
)
|
||||
output, platform, err := store.sendDownloadProduct(Account{StoreFront: "143443-2,34"}, app, "001122334455", "", PlatformMacOS)
|
||||
Expect(output).To(Equal(expected))
|
||||
Expect(platform).To(Equal(PlatformMacOS))
|
||||
if downloadErr == nil {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
} else {
|
||||
Expect(errors.Is(err, downloadErr)).To(BeTrue())
|
||||
}
|
||||
},
|
||||
Entry("successful primary response", nil),
|
||||
Entry("propagates pinned download failure", &http.UnexpectedResponseError{StatusCode: gohttp.StatusInternalServerError}),
|
||||
)
|
||||
|
||||
DescribeTable("keeps the Mac version pinned through redownload fallback", func(message string) {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
defer ctrl.Finish()
|
||||
downloads := http.NewMockClient[downloadResult](ctrl)
|
||||
pages := http.NewMockClient[[]byte](ctrl)
|
||||
bags := http.NewMockClient[bagResult](ctrl)
|
||||
store := &appstore{downloadClient: downloads, storefrontClient: pages, bagClient: bags}
|
||||
bag := validBagResult()
|
||||
bag.URLBag.RedownloadEndpoint = testRedownloadEndpoint
|
||||
expected := http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{Items: []downloadItemResult{{URL: "https://example.test/mac.pkg"}}}}
|
||||
gomock.InOrder(
|
||||
pages.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: gohttp.StatusOK, Data: macVersionPage(karingMacConfiguration)}, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", "876660716"))
|
||||
}).Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{CustomerMessage: message}}, nil),
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testRedownloadEndpoint + "?guid=001122334455"))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", "876660716"))
|
||||
}).Return(expected, nil),
|
||||
)
|
||||
output, platform, err := store.sendDownloadProduct(Account{StoreFront: "143443-2,34"}, app, "001122334455", "", PlatformMacOS)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(output).To(Equal(expected))
|
||||
Expect(platform).To(Equal(PlatformMacOS))
|
||||
},
|
||||
Entry("empty response", ""),
|
||||
Entry("unavailable response", "No Longer Available"),
|
||||
)
|
||||
|
||||
DescribeTable("propagates lookup failures", func(status int, body []byte, requestErr error) {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
defer ctrl.Finish()
|
||||
pages := http.NewMockClient[[]byte](ctrl)
|
||||
store := &appstore{storefrontClient: pages, downloadClient: http.NewMockClient[downloadResult](ctrl)}
|
||||
pages.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: status, Data: body}, requestErr)
|
||||
_, _, err := store.sendDownloadProduct(Account{StoreFront: "143443-2,34"}, app, "001122334455", "", PlatformMacOS)
|
||||
Expect(err).To(HaveOccurred())
|
||||
},
|
||||
Entry("HTTP failure", 500, nil, nil),
|
||||
Entry("network failure", 0, nil, errors.New("connection reset")),
|
||||
Entry("missing Mac offer", 200, macVersionPage(`{}`), nil),
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,114 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/blacktop/go-macho/pkg/xar"
|
||||
)
|
||||
|
||||
func (t *appstore) readVersionMetadataFromMacPackage(ctx context.Context, item downloadItemResult, hardwareID []byte, bundleID string) (versionMetadata, error) {
|
||||
directory, err := os.MkdirTemp("", "ipatool-version-metadata-*")
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to create metadata staging: %w", err)
|
||||
}
|
||||
|
||||
defer os.RemoveAll(directory)
|
||||
|
||||
destination := filepath.Join(directory, "app.pkg")
|
||||
if _, err := t.downloadMacPackage(ctx, item, destination, hardwareID, nil); err != nil {
|
||||
return versionMetadata{}, err
|
||||
}
|
||||
|
||||
if bundleID == "" {
|
||||
bundleID = downloadMetadataString(item.Metadata, "softwareVersionBundleId")
|
||||
}
|
||||
|
||||
archive, err := xar.Open(destination)
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to open Mac package: %w", err)
|
||||
}
|
||||
|
||||
defer archive.Close()
|
||||
|
||||
return macPackageVersionMetadata(&archive.Reader, bundleID)
|
||||
}
|
||||
|
||||
func macPackageVersionMetadata(archive *xar.Reader, bundleID string) (versionMetadata, error) {
|
||||
var result *versionMetadata
|
||||
|
||||
for _, file := range archive.Files {
|
||||
if path.Base(file.Name) != "PackageInfo" {
|
||||
continue
|
||||
}
|
||||
|
||||
source, err := file.Open()
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to open PackageInfo: %w", err)
|
||||
}
|
||||
|
||||
data, readErr := io.ReadAll(source)
|
||||
closeErr := source.Close()
|
||||
|
||||
if err := errors.Join(readErr, closeErr); err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to read PackageInfo: %w", err)
|
||||
}
|
||||
|
||||
var info struct {
|
||||
Bundles []struct {
|
||||
ID string `xml:"id,attr"`
|
||||
Version string `xml:"CFBundleShortVersionString,attr"`
|
||||
} `xml:"bundle"`
|
||||
}
|
||||
|
||||
if err := xml.Unmarshal(data, &info); err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to parse PackageInfo: %w", err)
|
||||
}
|
||||
|
||||
for _, bundle := range info.Bundles {
|
||||
if bundleID != "" && bundle.ID != bundleID {
|
||||
continue
|
||||
}
|
||||
|
||||
version := strings.TrimSpace(bundle.Version)
|
||||
if version == "" {
|
||||
return versionMetadata{}, errors.New("macOS package does not contain a display version")
|
||||
}
|
||||
|
||||
if result != nil {
|
||||
return versionMetadata{}, errors.New("macOS package contains multiple matching bundles")
|
||||
}
|
||||
// Like the IPA Info.plist timestamp fallback, use the selected build's
|
||||
// archived payload timestamp, not the API's app-level release date.
|
||||
var modified int64
|
||||
|
||||
for _, payload := range archive.Files {
|
||||
if payload.Name == path.Join(path.Dir(file.Name), "Payload") {
|
||||
modified = payload.Info.Mtime
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if modified <= 0 {
|
||||
return versionMetadata{}, errors.New("macOS package does not contain a payload timestamp")
|
||||
}
|
||||
|
||||
result = &versionMetadata{DisplayVersion: version, ReleaseDate: time.Unix(modified, 0).UTC()}
|
||||
}
|
||||
}
|
||||
|
||||
if result == nil {
|
||||
return versionMetadata{}, errors.New("macOS package does not contain metadata for the requested bundle")
|
||||
}
|
||||
|
||||
return *result, nil
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha1" // #nosec G505 -- XAR uses SHA-1 for archive checksums.
|
||||
"fmt"
|
||||
"io"
|
||||
gohttp "net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/blacktop/go-macho/pkg/xar"
|
||||
"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"
|
||||
)
|
||||
|
||||
func macMetadataXAR(info, modified string) []byte {
|
||||
payload := []byte("app payload")
|
||||
|
||||
var entries string
|
||||
|
||||
offset := sha1.Size
|
||||
|
||||
for index, entry := range []struct {
|
||||
name string
|
||||
data []byte
|
||||
}{{"PackageInfo", []byte(info)}, {"Payload", payload}} {
|
||||
checksum := sha1.Sum(entry.data) // #nosec G401 -- XAR uses SHA-1 for archive checksums.
|
||||
entries += fmt.Sprintf(`<file id="%d"><type>file</type><name>%s</name><mtime>%s</mtime><data><length>%d</length><offset>%d</offset><size>%d</size><encoding style="application/octet-stream"/><archived-checksum style="sha1">%x</archived-checksum><extracted-checksum style="sha1">%x</extracted-checksum></data></file>`, index+1, entry.name, modified, len(entry.data), offset, len(entry.data), checksum, checksum)
|
||||
offset += len(entry.data)
|
||||
}
|
||||
|
||||
return makeTestXARArchive(entries, append([]byte(info), payload...)...)
|
||||
}
|
||||
|
||||
var _ = Describe("Mac version metadata", func() {
|
||||
const info = `<pkg-info><bundle id="com.example.mac" CFBundleShortVersionString="1.2.1"/></pkg-info>`
|
||||
const modified = "2025-07-24T08:38:42Z"
|
||||
|
||||
DescribeTable("validates package metadata", func(contents, bundle, stamp string, success bool) {
|
||||
data := macMetadataXAR(contents, stamp)
|
||||
archive, err := xar.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
metadata, err := macPackageVersionMetadata(archive, bundle)
|
||||
if success {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(metadata.DisplayVersion).To(Equal("1.2.1"))
|
||||
Expect(metadata.ReleaseDate).To(Equal(time.Date(2025, 7, 24, 8, 38, 42, 0, time.UTC)))
|
||||
} else {
|
||||
Expect(err).To(HaveOccurred())
|
||||
}
|
||||
},
|
||||
Entry("matching bundle", info, "com.example.mac", modified, true),
|
||||
Entry("ID-only lookup with a unique bundle", info, "", modified, true),
|
||||
Entry("wrong bundle", info, "com.other.mac", modified, false),
|
||||
Entry("missing version", `<pkg-info><bundle id="com.example.mac"/></pkg-info>`, "com.example.mac", modified, false),
|
||||
Entry("missing timestamp", info, "com.example.mac", "", false),
|
||||
Entry("ambiguous bundles", `<pkg-info><bundle id="a" CFBundleShortVersionString="1"/><bundle id="b" CFBundleShortVersionString="2"/></pkg-info>`, "", modified, false),
|
||||
Entry("invalid XML", "<", "com.example.mac", modified, false),
|
||||
)
|
||||
|
||||
It("reads Mac-compatible IPA metadata with the existing IPA reader", func() {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
defer ctrl.Finish()
|
||||
date := time.Date(2025, 7, 24, 8, 38, 42, 0, time.UTC)
|
||||
server, _, _ := testIPAServer(testIPA("2.0", date, date))
|
||||
defer server.Close()
|
||||
downloads := http.NewMockClient[downloadResult](ctrl)
|
||||
machines := machine.NewMockMachine(ctrl)
|
||||
store := &appstore{downloadClient: downloads, machine: machines, httpClient: http.NewClient[interface{}](http.Args{})}
|
||||
machines.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
downloads.EXPECT().Send(gomock.Any()).Return(http.Result[downloadResult]{StatusCode: 200, Data: downloadResult{Items: []downloadItemResult{{
|
||||
URL: server.URL, Sinfs: []Sinf{{Data: []byte("sinf")}}, Metadata: map[string]interface{}{"software-platform": "ios"},
|
||||
}}}}, nil)
|
||||
out, err := store.GetVersionMetadata(GetVersionMetadataInput{App: App{ID: 42}, Platform: PlatformMacOS, VersionID: "123"})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.DisplayVersion).To(Equal("2.0"))
|
||||
Expect(out.ReleaseDate).To(Equal(date))
|
||||
})
|
||||
|
||||
It("decrypts the selected Mac version and ignores stale API metadata", func() {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
defer ctrl.Finish()
|
||||
tempRoot := GinkgoT().TempDir()
|
||||
GinkgoT().Setenv("TMPDIR", tempRoot)
|
||||
GinkgoT().Setenv("TMP", tempRoot)
|
||||
GinkgoT().Setenv("TEMP", tempRoot)
|
||||
server := httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, r *gohttp.Request) { _, _ = io.WriteString(w, "encrypted") }))
|
||||
defer server.Close()
|
||||
downloads := http.NewMockClient[downloadResult](ctrl)
|
||||
machines := machine.NewMockMachine(ctrl)
|
||||
decrypter := &fakeMacPackageDecrypter{output: macMetadataXAR(info, modified)}
|
||||
store := &appstore{downloadClient: downloads, machine: machines, os: operatingsystem.New(), httpClient: http.NewClient[interface{}](http.Args{}), macDecrypterFactory: func(ctx context.Context, hw, dp []byte) (macPackageDecrypter, error) {
|
||||
Expect(hw).To(Equal([]byte{0, 17, 34, 51, 68, 85}))
|
||||
Expect(dp).To(Equal([]byte("dpInfo")))
|
||||
|
||||
return decrypter, nil
|
||||
}}
|
||||
machines.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", "876660716"))
|
||||
}).Return(http.Result[downloadResult]{StatusCode: 200, Data: downloadResult{Items: []downloadItemResult{{URL: server.URL, Sinfs: []Sinf{{DPInfo: []byte("dpInfo")}}, Metadata: map[string]interface{}{"software-platform": "macos", "bundleShortVersionString": "9.9", "releaseDate": "2023-12-26T08:00:00Z"}}}}}, nil)
|
||||
out, err := store.GetVersionMetadata(GetVersionMetadataInput{App: App{ID: 42, BundleID: "com.example.mac"}, Platform: PlatformMacOS, VersionID: "876660716"})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.DisplayVersion).To(Equal("1.2.1"))
|
||||
Expect(out.ReleaseDate).To(Equal(time.Date(2025, 7, 24, 8, 38, 42, 0, time.UTC)))
|
||||
entries, err := os.ReadDir(tempRoot)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(entries).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
@@ -6,8 +6,10 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
gohttp "net/http"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
@@ -17,13 +19,16 @@ const (
|
||||
DefaultOwnedAppsLimit = 10
|
||||
MaxOwnedAppsLimit = 100
|
||||
|
||||
ownedAppsMediaKind = 131072
|
||||
ownedAppsMediaKind = 131072
|
||||
ownedArcadeAppsMediaKind = 262144
|
||||
ownedMacAppsMediaKind = 67108864
|
||||
)
|
||||
|
||||
type OwnedAppsInput struct {
|
||||
Account Account
|
||||
Page int
|
||||
Limit int
|
||||
Account Account
|
||||
Page int
|
||||
Limit int
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
type OwnedAppsOutput struct {
|
||||
@@ -68,6 +73,12 @@ func (t *appstore) OwnedApps(input OwnedAppsInput) (OwnedAppsOutput, error) {
|
||||
}
|
||||
|
||||
apps, fetchErr := t.fetchOwnedApps(input.Account, guid, signer)
|
||||
if input.Platform != "" {
|
||||
apps = slices.DeleteFunc(apps, func(app App) bool {
|
||||
return !slices.Contains(app.Platforms, input.Platform)
|
||||
})
|
||||
}
|
||||
|
||||
apps = ownedAppsSortedByPurchaseDate(apps)
|
||||
pageApps := ownedAppsPage(apps, input.Page, input.Limit)
|
||||
output := OwnedAppsOutput{
|
||||
@@ -98,6 +109,12 @@ func (t *appstore) OwnedApps(input OwnedAppsInput) (OwnedAppsOutput, error) {
|
||||
}
|
||||
|
||||
func normalizeOwnedAppsInput(input OwnedAppsInput) (OwnedAppsInput, error) {
|
||||
switch input.Platform {
|
||||
case "", PlatformIPhone, PlatformIPad, PlatformAppleTV, PlatformVisionOS, PlatformMacOS:
|
||||
default:
|
||||
return OwnedAppsInput{}, fmt.Errorf("invalid platform %q", input.Platform)
|
||||
}
|
||||
|
||||
if input.Page == 0 {
|
||||
input.Page = 1
|
||||
}
|
||||
@@ -122,6 +139,26 @@ func normalizeOwnedAppsInput(input OwnedAppsInput) (OwnedAppsInput, error) {
|
||||
}
|
||||
|
||||
func (t *appstore) fetchOwnedApps(acc Account, guid string, signer ActionSigner) ([]App, error) {
|
||||
var apps []App
|
||||
|
||||
storeFront, _, _ := strings.Cut(acc.StoreFront, ",")
|
||||
// Configurator (34) lists mobile apps, while the Mac App Store (13)
|
||||
// also lists Mac software and mobile apps available on Apple silicon.
|
||||
for _, store := range []string{"34", "13"} {
|
||||
acc.StoreFront = storeFront + "," + store
|
||||
|
||||
results, err := t.fetchOwnedAppsForStorefront(acc, guid, signer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
apps = append(apps, results...)
|
||||
}
|
||||
|
||||
return mergeOwnedApps(apps), nil
|
||||
}
|
||||
|
||||
func (t *appstore) fetchOwnedAppsForStorefront(acc Account, guid string, signer ActionSigner) ([]App, error) {
|
||||
loginResult, err := t.ownedAppsClient.Send(t.ownedAppsLoginRequest(acc, guid))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open purchase history session: %w", err)
|
||||
@@ -144,7 +181,7 @@ func (t *appstore) fetchOwnedApps(acc Account, guid string, signer ActionSigner)
|
||||
return nil, errors.New("purchase history login response did not contain a valid session ID")
|
||||
}
|
||||
|
||||
query := fmt.Sprintf("('com.apple.itunes.extended\\-media\\-kind:%d')", ownedAppsMediaKind)
|
||||
query := fmt.Sprintf("('com.apple.itunes.extended\\-media\\-kind:%d','com.apple.itunes.extended\\-media\\-kind:%d','com.apple.itunes.extended\\-media\\-kind:%d')", ownedAppsMediaKind, ownedArcadeAppsMediaKind, ownedMacAppsMediaKind)
|
||||
|
||||
updateResult, err := t.ownedAppsClient.Send(t.ownedAppsUpdateRequest(acc, guid, uint32(sessionID), query, signer))
|
||||
if err != nil {
|
||||
@@ -359,7 +396,6 @@ func firstDMAPUint(data []byte, target string) (uint64, bool, error) {
|
||||
|
||||
func parseOwnedApps(data []byte) ([]App, error) {
|
||||
apps := make([]App, 0)
|
||||
seen := make(map[int64]struct{})
|
||||
|
||||
err := walkDMAP(data, 0, func(tag string, payload []byte) error {
|
||||
if tag != "mlit" {
|
||||
@@ -375,12 +411,6 @@ func parseOwnedApps(data []byte) ([]App, error) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, ok := seen[app.ID]; ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
seen[app.ID] = struct{}{}
|
||||
|
||||
apps = append(apps, app)
|
||||
|
||||
return nil
|
||||
@@ -389,14 +419,71 @@ func parseOwnedApps(data []byte) ([]App, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return apps, nil
|
||||
return mergeOwnedApps(apps), nil
|
||||
}
|
||||
|
||||
func mergeOwnedApps(apps []App) []App {
|
||||
merged := make([]App, 0, len(apps))
|
||||
|
||||
seen := make(map[int64]int)
|
||||
for _, app := range apps {
|
||||
if index, ok := seen[app.ID]; ok {
|
||||
for _, platform := range app.Platforms {
|
||||
if !slices.Contains(merged[index].Platforms, platform) {
|
||||
merged[index].Platforms = append(merged[index].Platforms, platform)
|
||||
}
|
||||
}
|
||||
|
||||
if app.PurchaseDate.After(merged[index].PurchaseDate) {
|
||||
merged[index].PurchaseDate = app.PurchaseDate
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
seen[app.ID] = len(merged)
|
||||
merged = append(merged, app)
|
||||
}
|
||||
|
||||
for index := range merged {
|
||||
if len(merged[index].Platforms) > 1 {
|
||||
merged[index].Platforms = slices.DeleteFunc(merged[index].Platforms, func(platform Platform) bool {
|
||||
return platform == PlatformUnknown
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return merged
|
||||
}
|
||||
|
||||
func parseOwnedApp(data []byte) (App, error) {
|
||||
var app App
|
||||
app := App{Platforms: []Platform{}}
|
||||
|
||||
var mediaKind, supportedProducts uint64
|
||||
|
||||
err := walkDMAP(data, 0, func(tag string, payload []byte) error {
|
||||
switch tag {
|
||||
case "aeMk", "aeSS":
|
||||
var value uint64
|
||||
|
||||
switch len(payload) {
|
||||
case 1:
|
||||
value = uint64(payload[0])
|
||||
case 2:
|
||||
value = uint64(binary.BigEndian.Uint16(payload))
|
||||
case 4:
|
||||
value = uint64(binary.BigEndian.Uint32(payload))
|
||||
case 8:
|
||||
value = binary.BigEndian.Uint64(payload)
|
||||
default:
|
||||
return fmt.Errorf("owned app %s has invalid integer length %d", tag, len(payload))
|
||||
}
|
||||
|
||||
if tag == "aeMk" {
|
||||
mediaKind = value
|
||||
} else {
|
||||
supportedProducts = value
|
||||
}
|
||||
case "aeSI":
|
||||
id, err := dmapInt64(payload)
|
||||
if err != nil {
|
||||
@@ -425,6 +512,33 @@ func parseOwnedApp(data []byte) (App, error) {
|
||||
return nil
|
||||
})
|
||||
|
||||
// Mac software uses a separate media kind; its supported-products bits
|
||||
// do not describe mobile device support.
|
||||
switch mediaKind {
|
||||
case ownedMacAppsMediaKind:
|
||||
app.Platforms = append(app.Platforms, PlatformMacOS)
|
||||
case ownedAppsMediaKind, ownedArcadeAppsMediaKind:
|
||||
// The purchase-history mask uses 8 for Mac and 16 for visionOS.
|
||||
// It does not encode Apple TV support.
|
||||
for _, product := range []struct {
|
||||
mask uint64
|
||||
platform Platform
|
||||
}{
|
||||
{1, PlatformIPhone},
|
||||
{2, PlatformIPad},
|
||||
{16, PlatformVisionOS},
|
||||
{8, PlatformMacOS},
|
||||
} {
|
||||
if supportedProducts&product.mask != 0 {
|
||||
app.Platforms = append(app.Platforms, product.platform)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(app.Platforms) == 0 {
|
||||
app.Platforms = []Platform{PlatformUnknown}
|
||||
}
|
||||
|
||||
return app, err
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ var _ = Describe("AppStore (OwnedApps)", func() {
|
||||
const (
|
||||
testDSID = "123456789"
|
||||
testGUID = "AABBCCDDEEFF"
|
||||
testStoreFront = "143441"
|
||||
testStoreFront = "143441-1,34"
|
||||
testToken = "password-token"
|
||||
testSessionID = uint32(42)
|
||||
testRevision = uint32(99)
|
||||
@@ -77,6 +77,115 @@ var _ = Describe("AppStore (OwnedApps)", func() {
|
||||
}, nil)
|
||||
}
|
||||
|
||||
expectStorefront := func(storefront string, data []byte) {
|
||||
responses := []http.Result[[]byte]{
|
||||
{StatusCode: gohttp.StatusOK, Data: dmapTag("mlog", dmapUint32("mlid", testSessionID))},
|
||||
{StatusCode: gohttp.StatusOK, Data: dmapTag("mupd", dmapUint32("musr", testRevision))},
|
||||
{StatusCode: gohttp.StatusOK, Data: data},
|
||||
}
|
||||
calls := make([]*gomock.Call, 0, len(responses))
|
||||
for _, response := range responses {
|
||||
calls = append(calls, mockOwnedClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.Headers).To(HaveKeyWithValue("X-Apple-Store-Front", storefront))
|
||||
}).Return(response, nil))
|
||||
}
|
||||
gomock.InOrder(calls[0], calls[1], calls[2])
|
||||
}
|
||||
|
||||
DescribeTable("filters merged purchases before sorting and pagination",
|
||||
func(platform Platform, page, total int, ids []int64) {
|
||||
expectSignerSetup()
|
||||
item := func(id, kind, products, date uint32) []byte {
|
||||
data := append(dmapUint32("aeSI", id), dmapUint32("aeMk", kind)...)
|
||||
data = append(data, dmapUint32("aeSS", products)...)
|
||||
data = append(data, dmapUint32("asdp", date)...)
|
||||
|
||||
return dmapTag("mlit", data)
|
||||
}
|
||||
mobile := append(item(1, 131072, 1, 300), item(2, 131072, 19, 200)...)
|
||||
mobile = append(mobile, item(3, 131072, 0, 100)...)
|
||||
mac := append(item(2, 67108864, 0, 200), item(4, 67108864, 0, 400)...)
|
||||
expectStorefront("143441-1,34", dmapTag("adbs", dmapTag("mlcl", mobile)))
|
||||
expectStorefront("143441-1,13", dmapTag("adbs", dmapTag("mlcl", mac)))
|
||||
|
||||
output, err := as.OwnedApps(OwnedAppsInput{Account: account, Platform: platform, Page: page, Limit: 1})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(output.TotalCount).To(Equal(total))
|
||||
Expect(output.Count).To(Equal(len(ids)))
|
||||
Expect(output.Page).To(Equal(page))
|
||||
actualIDs := make([]int64, 0, len(output.Results))
|
||||
for _, app := range output.Results {
|
||||
actualIDs = append(actualIDs, app.ID)
|
||||
}
|
||||
Expect(actualIDs).To(Equal(ids))
|
||||
if len(ids) == 1 && ids[0] == 2 {
|
||||
Expect(output.Results[0].Platforms).To(Equal([]Platform{PlatformIPhone, PlatformIPad, PlatformVisionOS, PlatformMacOS}))
|
||||
}
|
||||
},
|
||||
Entry("no filter", Platform(""), 1, 4, []int64{4}),
|
||||
Entry("iPhone", PlatformIPhone, 1, 2, []int64{1}),
|
||||
Entry("iPad", PlatformIPad, 1, 1, []int64{2}),
|
||||
Entry("visionOS", PlatformVisionOS, 1, 1, []int64{2}),
|
||||
Entry("Mac second page includes merged platform", PlatformMacOS, 2, 2, []int64{2}),
|
||||
Entry("no matching Apple TV apps", PlatformAppleTV, 1, 0, []int64{}),
|
||||
Entry("page past filtered results", PlatformVisionOS, 2, 1, []int64{}),
|
||||
)
|
||||
|
||||
It("puts a new Mac purchase first and merges apps from both storefronts", func() {
|
||||
expectSignerSetup()
|
||||
mobile := append(dmapUint32("aeSI", 123), dmapUint32("aeSS", 3)...)
|
||||
mobile = append(mobile, dmapUint32("aeMk", 131072)...)
|
||||
mobile = append(mobile, dmapUint32("asdp", 100)...)
|
||||
arcade := append(dmapUint32("aeSI", 456), dmapUint32("aeMk", 262144)...)
|
||||
arcade = append(arcade, dmapUint32("aeSS", 3)...)
|
||||
mobileListing := append(dmapTag("mlit", mobile), dmapTag("mlit", arcade)...)
|
||||
expectStorefront("143441-1,34", dmapTag("adbs", dmapTag("mlcl", mobileListing)))
|
||||
|
||||
// SnippetsLab's Mac media kind and empty supported-products field
|
||||
// reproduce the fields that were previously missing from the results.
|
||||
mac := append(dmapUint32("aeSI", 1006087419), dmapUint32("aeMk", 67108864)...)
|
||||
mac = append(mac, dmapTag("aeSS", []byte{0, 0})...)
|
||||
mac = append(mac, dmapString("aeLN", "SnippetsLab")...)
|
||||
mac = append(mac, dmapUint32("asdp", 300)...)
|
||||
macListing := append(dmapTag("mlit", mobile), dmapTag("mlit", mac)...)
|
||||
expectStorefront("143441-1,13", dmapTag("adbs", dmapTag("mlcl", macListing)))
|
||||
|
||||
output, err := as.OwnedApps(OwnedAppsInput{Account: account, Limit: 2})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(output.TotalCount).To(Equal(3))
|
||||
Expect(output.Count).To(Equal(2))
|
||||
Expect(output.Results[0].Name).To(Equal("SnippetsLab"))
|
||||
Expect(output.Results[0].Platforms).To(Equal([]Platform{PlatformMacOS}))
|
||||
Expect(output.Results[1].ID).To(Equal(int64(123)))
|
||||
Expect(output.Results[1].Platforms).To(Equal([]Platform{PlatformIPhone, PlatformIPad}))
|
||||
Expect(signer.closeCalls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("does not infer a platform from the storefront or app name", func() {
|
||||
expectSignerSetup()
|
||||
expectStorefront("143441-1,34", dmapTag("adbs", nil))
|
||||
item := append(dmapUint32("aeSI", 123), dmapString("aeLN", "Example for Mac")...)
|
||||
expectStorefront("143441-1,13", dmapTag("adbs", dmapTag("mlcl", dmapTag("mlit", item))))
|
||||
|
||||
output, err := as.OwnedApps(OwnedAppsInput{Account: account})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(output.Results).To(HaveLen(1))
|
||||
Expect(output.Results[0].Platforms).To(Equal([]Platform{PlatformUnknown}))
|
||||
})
|
||||
|
||||
It("does not return an incomplete list if the Mac storefront fails", func() {
|
||||
expectSignerSetup()
|
||||
expectStorefront("143441-1,34", ownedAppsDMAPResponse([]App{{ID: 123}}))
|
||||
mockOwnedClient.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: gohttp.StatusUnauthorized}, nil)
|
||||
|
||||
output, err := as.OwnedApps(OwnedAppsInput{Account: account})
|
||||
Expect(errors.Is(err, ErrPasswordTokenExpired)).To(BeTrue())
|
||||
Expect(output.Results).To(BeEmpty())
|
||||
Expect(signer.closeCalls).To(Equal(1))
|
||||
})
|
||||
|
||||
When("the account has more than one page of apps", func() {
|
||||
It("sorts all apps by descending purchase date before returning the requested partial page", func() {
|
||||
expectSignerSetup()
|
||||
@@ -118,7 +227,7 @@ var _ = Describe("AppStore (OwnedApps)", func() {
|
||||
|
||||
payload, ok := req.Payload.(*http.RawPayload)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(string(payload.Content)).To(Equal("session-id=42&revision-number=(null)&query=('com.apple.itunes.extended\\-media\\-kind:131072')"))
|
||||
Expect(string(payload.Content)).To(Equal("session-id=42&revision-number=(null)&query=('com.apple.itunes.extended\\-media\\-kind:131072','com.apple.itunes.extended\\-media\\-kind:262144','com.apple.itunes.extended\\-media\\-kind:67108864')"))
|
||||
}).
|
||||
Return(http.Result[[]byte]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
@@ -144,6 +253,14 @@ var _ = Describe("AppStore (OwnedApps)", func() {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(revision).To(Equal(uint64(testRevision)))
|
||||
err = walkDMAP(payload.Content, 0, func(tag string, data []byte) error {
|
||||
if tag == "mque" {
|
||||
Expect(string(data)).To(Equal("('com.apple.itunes.extended\\-media\\-kind:131072','com.apple.itunes.extended\\-media\\-kind:262144','com.apple.itunes.extended\\-media\\-kind:67108864')"))
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
}).
|
||||
Return(http.Result[[]byte]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
@@ -151,6 +268,7 @@ var _ = Describe("AppStore (OwnedApps)", func() {
|
||||
}, nil)
|
||||
|
||||
gomock.InOrder(loginCall, updateCall, itemsCall)
|
||||
expectStorefront("143441-1,13", ownedAppsDMAPResponse(nil))
|
||||
|
||||
output, err := as.OwnedApps(OwnedAppsInput{
|
||||
Account: account,
|
||||
@@ -190,6 +308,8 @@ var _ = Describe("AppStore (OwnedApps)", func() {
|
||||
}, nil),
|
||||
)
|
||||
|
||||
expectStorefront("143441-1,13", ownedAppsDMAPResponse(nil))
|
||||
|
||||
output, err := as.OwnedApps(OwnedAppsInput{Account: account, Page: 2, Limit: 10})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
@@ -259,6 +379,8 @@ var _ = Describe("AppStore (OwnedApps)", func() {
|
||||
Entry("rejects a negative page", OwnedAppsInput{Page: -1, Limit: 10}, OwnedAppsInput{}, "page"),
|
||||
Entry("rejects a negative limit", OwnedAppsInput{Page: 1, Limit: -1}, OwnedAppsInput{}, "limit"),
|
||||
Entry("rejects a limit over 100", OwnedAppsInput{Page: 1, Limit: 101}, OwnedAppsInput{}, "100"),
|
||||
Entry("rejects an invalid platform", OwnedAppsInput{Platform: "invalid"}, OwnedAppsInput{}, "invalid platform"),
|
||||
Entry("rejects unknown as a filter", OwnedAppsInput{Platform: PlatformUnknown}, OwnedAppsInput{}, "invalid platform"),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -266,7 +388,7 @@ var _ = Describe("owned-app DMAP parsing", func() {
|
||||
It("parses app fields, ignores unknown fields, and removes duplicate IDs", func() {
|
||||
item := make([]byte, 0, 128)
|
||||
item = append(item, dmapString("zzzz", "unknown")...)
|
||||
item = append(item, dmapUint64ForTest("aeSI", 123)...)
|
||||
item = append(item, dmapAppIDForTest(123)...)
|
||||
item = append(item, dmapString("aeBI", "com.example.app")...)
|
||||
item = append(item, dmapString("aeLN", "Example")...)
|
||||
item = append(item, dmapString("aePd", "1.2.3")...)
|
||||
@@ -283,11 +405,104 @@ var _ = Describe("owned-app DMAP parsing", func() {
|
||||
Name: "Example",
|
||||
Version: "1.2.3",
|
||||
PurchaseDate: time.Unix(1_700_000_000, 0).UTC(),
|
||||
Platforms: []Platform{PlatformUnknown},
|
||||
}}))
|
||||
})
|
||||
|
||||
DescribeTable("decodes supported platforms",
|
||||
func(kind uint32, products []byte, expected []Platform) {
|
||||
item := append(dmapUint32("aeMk", kind), dmapTag("aeSS", products)...)
|
||||
app, err := parseOwnedApp(item)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(app.Platforms).To(Equal(expected))
|
||||
},
|
||||
Entry("iPhone", uint32(131072), []byte{0, 1}, []Platform{PlatformIPhone}),
|
||||
Entry("iPad", uint32(131072), []byte{0, 2}, []Platform{PlatformIPad}),
|
||||
Entry("Mac universal purchase", uint32(131072), []byte{0, 8}, []Platform{PlatformMacOS}),
|
||||
Entry("visionOS", uint32(131072), []byte{0, 16}, []Platform{PlatformVisionOS}),
|
||||
Entry("Arcade does not imply Mac support", uint32(262144), []byte{0, 3}, []Platform{PlatformIPhone, PlatformIPad}),
|
||||
Entry("universal app", uint32(131072), []byte{0, 27}, []Platform{PlatformIPhone, PlatformIPad, PlatformVisionOS, PlatformMacOS}),
|
||||
Entry("Mac ignores mobile product bits", uint32(67108864), []byte{0, 7}, []Platform{PlatformMacOS}),
|
||||
Entry("iPod touch only", uint32(131072), []byte{0, 4}, []Platform{PlatformUnknown}),
|
||||
Entry("unknown product bit does not imply visionOS", uint32(131072), []byte{0, 32}, []Platform{PlatformUnknown}),
|
||||
Entry("empty products", uint32(131072), []byte{0, 0}, []Platform{PlatformUnknown}),
|
||||
Entry("unknown media kind", uint32(999), []byte{0, 31}, []Platform{PlatformUnknown}),
|
||||
Entry("unknown products", uint32(131072), []byte{128, 0}, []Platform{PlatformUnknown}),
|
||||
Entry("one-byte products", uint32(131072), []byte{3}, []Platform{PlatformIPhone, PlatformIPad}),
|
||||
Entry("four-byte products", uint32(131072), []byte{0, 0, 0, 3}, []Platform{PlatformIPhone, PlatformIPad}),
|
||||
Entry("eight-byte products", uint32(131072), []byte{0, 0, 0, 0, 0, 0, 0, 3}, []Platform{PlatformIPhone, PlatformIPad}),
|
||||
)
|
||||
|
||||
DescribeTable("returns unknown for missing platform metadata",
|
||||
func(item []byte) {
|
||||
app, err := parseOwnedApp(item)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(app.Platforms).To(Equal([]Platform{PlatformUnknown}))
|
||||
},
|
||||
Entry("missing products", dmapUint32("aeMk", 131072)),
|
||||
Entry("missing media kind", dmapUint32("aeSS", 31)),
|
||||
)
|
||||
|
||||
DescribeTable("replaces unknown when another record identifies the platform",
|
||||
func(platforms ...[]Platform) {
|
||||
records := make([]App, 0, len(platforms))
|
||||
for _, value := range platforms {
|
||||
records = append(records, App{ID: 123, Platforms: value})
|
||||
}
|
||||
apps := mergeOwnedApps(records)
|
||||
Expect(apps).To(HaveLen(1))
|
||||
Expect(apps[0].Platforms).To(Equal([]Platform{PlatformMacOS}))
|
||||
},
|
||||
Entry("unknown first", []Platform{PlatformUnknown}, []Platform{PlatformMacOS}),
|
||||
Entry("unknown last", []Platform{PlatformMacOS}, []Platform{PlatformUnknown}),
|
||||
)
|
||||
|
||||
It("identifies YouTube for visionOS as visionOS only", func() {
|
||||
item := dmapAppIDForTest(6745572359)
|
||||
item = append(item, dmapString("aeBI", "com.google.visionosyoutube")...)
|
||||
item = append(item, dmapString("aeLN", "YouTube for visionOS")...)
|
||||
item = append(item, dmapUint32("aeMk", 131072)...)
|
||||
item = append(item, dmapTag("aeSS", []byte{0, 16})...)
|
||||
|
||||
apps, err := parseOwnedApps(dmapTag("adbs", dmapTag("mlcl", dmapTag("mlit", item))))
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(apps).To(HaveLen(1))
|
||||
Expect(apps[0].ID).To(Equal(int64(6745572359)))
|
||||
Expect(apps[0].Platforms).To(Equal([]Platform{PlatformVisionOS}))
|
||||
})
|
||||
|
||||
It("merges platforms and keeps the latest purchase date before pagination", func() {
|
||||
mobile := append(dmapUint32("aeSI", 123), dmapUint32("aeSS", 3)...)
|
||||
mobile = append(mobile, dmapUint32("aeMk", 131072)...)
|
||||
mobile = append(mobile, dmapUint32("asdp", 100)...)
|
||||
mac := append(dmapUint32("aeSI", 123), dmapUint32("aeMk", 67108864)...)
|
||||
mac = append(mac, dmapUint32("asdp", 300)...)
|
||||
other := append(dmapUint32("aeSI", 456), dmapUint32("asdp", 200)...)
|
||||
listing := append(dmapTag("mlit", mobile), dmapTag("mlit", other)...)
|
||||
listing = append(listing, dmapTag("mlit", mac)...)
|
||||
listing = append(listing, dmapTag("mlit", mobile)...)
|
||||
|
||||
apps, err := parseOwnedApps(dmapTag("adbs", dmapTag("mlcl", listing)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(apps).To(HaveLen(2))
|
||||
page := ownedAppsPage(ownedAppsSortedByPurchaseDate(apps), 1, 1)
|
||||
Expect(page[0].ID).To(Equal(int64(123)))
|
||||
Expect(page[0].Platforms).To(Equal([]Platform{PlatformIPhone, PlatformIPad, PlatformMacOS}))
|
||||
Expect(page[0].PurchaseDate).To(Equal(time.Unix(300, 0).UTC()))
|
||||
})
|
||||
|
||||
DescribeTable("rejects malformed platform metadata",
|
||||
func(tag string) {
|
||||
_, err := parseOwnedApp(dmapTag(tag, []byte{1, 2, 3}))
|
||||
Expect(err).To(MatchError(ContainSubstring("invalid integer length 3")))
|
||||
},
|
||||
Entry("media kind", "aeMk"),
|
||||
Entry("supported products", "aeSS"),
|
||||
)
|
||||
|
||||
It("rejects a malformed purchase date", func() {
|
||||
item := append(dmapUint64ForTest("aeSI", 123), dmapTag("asdp", []byte{1, 2, 3})...)
|
||||
item := append(dmapAppIDForTest(123), dmapTag("asdp", []byte{1, 2, 3})...)
|
||||
response := dmapTag("adbs", dmapTag("mlcl", dmapTag("mlit", item)))
|
||||
|
||||
_, err := parseOwnedApps(response)
|
||||
@@ -373,7 +588,7 @@ func ownedAppsDMAPResponse(apps []App) []byte {
|
||||
|
||||
for _, app := range apps {
|
||||
item := make([]byte, 0, 128)
|
||||
item = append(item, dmapUint64ForTest("aeSI", uint64(app.ID))...)
|
||||
item = append(item, dmapAppIDForTest(uint64(app.ID))...)
|
||||
item = append(item, dmapString("aeBI", app.BundleID)...)
|
||||
item = append(item, dmapString("aeLN", app.Name)...)
|
||||
item = append(item, dmapString("aePd", app.Version)...)
|
||||
@@ -388,9 +603,9 @@ func ownedAppsDMAPResponse(apps []App) []byte {
|
||||
return dmapTag("adbs", dmapTag("mlcl", listing))
|
||||
}
|
||||
|
||||
func dmapUint64ForTest(name string, value uint64) []byte {
|
||||
func dmapAppIDForTest(value uint64) []byte {
|
||||
payload := make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(payload, value)
|
||||
|
||||
return dmapTag(name, payload)
|
||||
return dmapTag("aeSI", payload)
|
||||
}
|
||||
@@ -17,8 +17,9 @@ var (
|
||||
)
|
||||
|
||||
type PurchaseInput struct {
|
||||
Account Account
|
||||
App App
|
||||
Account Account
|
||||
App App
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
func (t *appstore) Purchase(input PurchaseInput) error {
|
||||
@@ -35,7 +36,7 @@ func (t *appstore) Purchase(input PurchaseInput) error {
|
||||
|
||||
err = t.purchaseWithParams(input.Account, input.App, guid, PricingParameterAppStore)
|
||||
if err != nil {
|
||||
if err == ErrTemporarilyUnavailable {
|
||||
if input.Platform != PlatformMacOS && err == ErrTemporarilyUnavailable {
|
||||
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)
|
||||
|
||||
@@ -368,6 +368,96 @@ var _ = Describe("AppStore (Purchase)", func() {
|
||||
})
|
||||
})
|
||||
|
||||
When("purchasing a macOS app", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{PricingParameterAppStore}).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
JingleDocType: "purchaseSuccess",
|
||||
Status: 0,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("uses the standard acquisition pricing parameter", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{StoreFront: "143441"},
|
||||
App: App{ID: 42},
|
||||
Platform: PlatformMacOS,
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("macOS purchase is temporarily unavailable", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{PricingParameterAppStore}).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
FailureType: FailureTypeTemporarilyUnavailable,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("does not fall back to the GAME pricing parameter", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{StoreFront: "143441"},
|
||||
App: App{ID: 42},
|
||||
Platform: PlatformMacOS,
|
||||
})
|
||||
Expect(err).To(MatchError(ContainSubstring(PricingParameterAppStore)))
|
||||
})
|
||||
})
|
||||
|
||||
DescribeTable("falls back to the GAME pricing parameter for non-macOS platforms",
|
||||
func(platform Platform) {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{PricingParameterAppStore}).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
FailureType: FailureTypeTemporarilyUnavailable,
|
||||
},
|
||||
}, nil)
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{PricingParameterAppleArcade}).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
JingleDocType: "purchaseSuccess",
|
||||
Status: 0,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{StoreFront: "143441"},
|
||||
App: App{ID: 42},
|
||||
Platform: platform,
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
},
|
||||
Entry("iPhone", PlatformIPhone),
|
||||
Entry("iPad", PlatformIPad),
|
||||
Entry("Apple TV", PlatformAppleTV),
|
||||
Entry("visionOS", PlatformVisionOS),
|
||||
)
|
||||
|
||||
When("successfully purchases the app", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
|
||||
@@ -15,8 +15,9 @@ import (
|
||||
)
|
||||
|
||||
type Sinf struct {
|
||||
ID int64 `plist:"id,omitempty"`
|
||||
Data []byte `plist:"sinf,omitempty"`
|
||||
ID int64 `plist:"id,omitempty"`
|
||||
Data []byte `plist:"sinf,omitempty"`
|
||||
DPInfo []byte `plist:"dpInfo,omitempty"`
|
||||
}
|
||||
|
||||
type ReplicateSinfInput struct {
|
||||
@@ -72,11 +73,17 @@ func (t *appstore) writeReplicatedZip(input ReplicateSinfInput, tmpPath string)
|
||||
}
|
||||
}()
|
||||
|
||||
err = t.replicateZip(zipReader, zipWriter)
|
||||
err = t.replicateZip(zipReader, zipWriter, input.PackagePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to replicate zip: %w", err)
|
||||
}
|
||||
|
||||
// Device-based downloads can omit sinfs even when the package has a
|
||||
// manifest. Preserve the archive rewrite, but only inject supplied data.
|
||||
if len(input.Sinfs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
bundleName, err := t.readBundleName(zipReader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read bundle name: %w", err)
|
||||
@@ -161,30 +168,59 @@ func (t *appstore) replicateSinfFromInfo(info packageInfo, zip *zip.Writer, sinf
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *appstore) replicateZip(src *zip.ReadCloser, dst *zip.Writer) error {
|
||||
func (t *appstore) replicateZip(src *zip.ReadCloser, dst *zip.Writer, sourcePath string) error {
|
||||
source, err := os.Open(sourcePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open zip headers: %w", err)
|
||||
}
|
||||
|
||||
defer source.Close()
|
||||
|
||||
info, err := source.Stat()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to stat zip: %w", err)
|
||||
}
|
||||
|
||||
headers, err := newZIPLocalHeaders(source, info.Size())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read zip directory: %w", err)
|
||||
}
|
||||
|
||||
for _, file := range src.File {
|
||||
err := func() error {
|
||||
srcFile, err := file.OpenRaw()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
header := file.FileHeader
|
||||
dstFile, err := dst.CreateRaw(&header)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to copy file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}()
|
||||
srcFile, err := file.OpenRaw()
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
header := file.FileHeader
|
||||
|
||||
localExtra, err := headers.extra(file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read local metadata for %q: %w", file.Name, err)
|
||||
}
|
||||
|
||||
header.Extra = zipStoredExtra(&header, localExtra)
|
||||
// Frame deflated files with a trailing descriptor for streaming
|
||||
// installers, without changing their compressed data or timestamps.
|
||||
// Stored files need inline sizes because they have no stream terminator.
|
||||
if strings.HasSuffix(header.Name, "/") || header.Method == zip.Store {
|
||||
header.Flags &^= 0x8
|
||||
} else if header.Method == zip.Deflate {
|
||||
header.Flags |= 0x8
|
||||
}
|
||||
|
||||
dstFile, err := dst.CreateRaw(&header)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
|
||||
// CreateRaw writes the local header immediately and retains this pointer
|
||||
// for the central directory written by Close. Keep the two extras distinct.
|
||||
header.Extra = zipExtraWithoutZIP64(file.Extra)
|
||||
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to copy file: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@ import (
|
||||
"archive/zip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
@@ -199,3 +201,56 @@ var _ = Describe("AppStore (ReplicateSinf)", func() {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("SINF replication with optional license data", func() {
|
||||
DescribeTable("preserves package contents when Apple supplies no sinfs", func(withManifest bool, sinfs []Sinf) {
|
||||
packagePath := filepath.Join(GinkgoT().TempDir(), "app.ipa")
|
||||
file, err := os.Create(packagePath)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
writer := zip.NewWriter(file)
|
||||
info, err := plist.Marshal(packageInfo{BundleExecutable: "Test"}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
contents := map[string][]byte{
|
||||
"Payload/Test.app/Info.plist": info,
|
||||
"Payload/Test.app/Test": []byte("executable"),
|
||||
"Payload/Test.app/SC_Info/Test.supf": []byte("existing protection data"),
|
||||
}
|
||||
if withManifest {
|
||||
manifest, err := plist.Marshal(packageManifest{SinfPaths: []string{"SC_Info/Test.sinf"}}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
contents["Payload/Test.app/SC_Info/Manifest.plist"] = manifest
|
||||
}
|
||||
for name, data := range contents {
|
||||
entry, err := writer.Create(name)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = entry.Write(data)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
}
|
||||
Expect(writer.Close()).To(Succeed())
|
||||
Expect(file.Close()).To(Succeed())
|
||||
|
||||
store := &appstore{os: operatingsystem.New()}
|
||||
Expect(store.ReplicateSinf(ReplicateSinfInput{PackagePath: packagePath, Sinfs: sinfs})).To(Succeed())
|
||||
|
||||
reader, err := zip.OpenReader(packagePath)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(reader.Close)
|
||||
Expect(reader.File).To(HaveLen(len(contents)))
|
||||
for _, entry := range reader.File {
|
||||
Expect(contents).To(HaveKey(entry.Name))
|
||||
src, err := entry.Open()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
data, err := io.ReadAll(src)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(src.Close()).To(Succeed())
|
||||
Expect(data).To(Equal(contents[entry.Name]))
|
||||
}
|
||||
_, err = os.Stat(packagePath + ".tmp")
|
||||
Expect(os.IsNotExist(err)).To(BeTrue())
|
||||
},
|
||||
Entry("with a manifest and omitted sinfs", true, []Sinf(nil)),
|
||||
Entry("with a manifest and empty sinfs", true, []Sinf{}),
|
||||
Entry("without a manifest and omitted sinfs", false, []Sinf(nil)),
|
||||
Entry("without a manifest and empty sinfs", false, []Sinf{}),
|
||||
)
|
||||
})
|
||||
@@ -1,10 +1,12 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -106,6 +108,15 @@ func (t *appstore) searchVisionOS(input SearchInput, countryCode string) (Search
|
||||
if metadata, ok := hydrated[app.ID]; ok {
|
||||
storefrontApps[index] = metadata
|
||||
}
|
||||
|
||||
platforms := slices.DeleteFunc(storefrontApps[index].Platforms, func(platform Platform) bool {
|
||||
return platform == PlatformUnknown
|
||||
})
|
||||
if !slices.Contains(platforms, PlatformVisionOS) {
|
||||
platforms = append(platforms, PlatformVisionOS)
|
||||
}
|
||||
|
||||
storefrontApps[index].Platforms = platforms
|
||||
}
|
||||
|
||||
return SearchOutput{
|
||||
@@ -119,6 +130,65 @@ type searchResult struct {
|
||||
Results []App `json:"results,omitempty"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON derives platforms from catalog metadata without exposing the
|
||||
// catalog's device list in app output.
|
||||
func (r *searchResult) UnmarshalJSON(data []byte) error {
|
||||
var result struct {
|
||||
Count int `json:"resultCount"`
|
||||
Results []struct {
|
||||
App
|
||||
Kind string `json:"kind"`
|
||||
SupportedDevices []string `json:"supportedDevices"`
|
||||
} `json:"results"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(data, &result); err != nil {
|
||||
return fmt.Errorf("failed to decode search results: %w", err)
|
||||
}
|
||||
|
||||
r.Count = result.Count
|
||||
r.Results = nil
|
||||
|
||||
if result.Results != nil {
|
||||
r.Results = make([]App, 0, len(result.Results))
|
||||
}
|
||||
|
||||
for _, item := range result.Results {
|
||||
platforms := item.Platforms
|
||||
|
||||
for _, family := range []struct {
|
||||
prefix string
|
||||
platform Platform
|
||||
}{
|
||||
{"iPhone", PlatformIPhone},
|
||||
{"iPod", PlatformIPhone},
|
||||
{"iPad", PlatformIPad},
|
||||
{"AppleTV", PlatformAppleTV},
|
||||
{"RealityDevice", PlatformVisionOS},
|
||||
{"Mac", PlatformMacOS},
|
||||
} {
|
||||
for _, device := range item.SupportedDevices {
|
||||
if strings.HasPrefix(device, family.prefix) && !slices.Contains(platforms, family.platform) {
|
||||
platforms = append(platforms, family.platform)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if item.Kind == "mac-software" && !slices.Contains(platforms, PlatformMacOS) {
|
||||
platforms = append(platforms, PlatformMacOS)
|
||||
}
|
||||
|
||||
if len(platforms) == 0 {
|
||||
platforms = []Platform{PlatformUnknown}
|
||||
}
|
||||
|
||||
item.Platforms = platforms
|
||||
r.Results = append(r.Results, item.App)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *appstore) searchRequest(term, countryCode string, limit int64, platform Platform) (http.Request, error) {
|
||||
url, err := t.searchURL(term, countryCode, limit, platform)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/url"
|
||||
|
||||
@@ -32,6 +33,27 @@ var _ = Describe("AppStore (Search)", func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
DescribeTable("decodes catalog platforms",
|
||||
func(metadata string, expected []Platform) {
|
||||
var result searchResult
|
||||
Expect(json.Unmarshal([]byte(`{"resultCount":1,"results":[{"trackId":42,`+metadata+`}]}`), &result)).To(Succeed())
|
||||
mockClient.EXPECT().Send(gomock.Any()).Return(http.Result[searchResult]{StatusCode: 200, Data: result}, nil)
|
||||
out, err := as.Search(SearchInput{Account: Account{StoreFront: "143441"}})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.Count).To(Equal(1))
|
||||
Expect(out.Results).To(Equal([]App{{ID: 42, Platforms: expected}}))
|
||||
},
|
||||
Entry("universal app with duplicate devices", `"supportedDevices":["iPadAir-iPadAir","iPhone5s-iPhone5s","iPhone6-iPhone6","iPodTouchSixthGen-iPodTouchSixthGen"]`, []Platform{PlatformIPhone, PlatformIPad}),
|
||||
Entry("iPad only", `"supportedDevices":["iPadAir-iPadAir"]`, []Platform{PlatformIPad}),
|
||||
Entry("iPod", `"supportedDevices":["iPodTouchSixthGen-iPodTouchSixthGen"]`, []Platform{PlatformIPhone}),
|
||||
Entry("TV", `"supportedDevices":["AppleTV4-AppleTV4"]`, []Platform{PlatformAppleTV}),
|
||||
Entry("vision", `"supportedDevices":["RealityDevice-RealityDevice"]`, []Platform{PlatformVisionOS}),
|
||||
Entry("Mac", `"kind":"mac-software"`, []Platform{PlatformMacOS}),
|
||||
Entry("multiple families", `"supportedDevices":["MacDesktop-MacDesktop","RealityDevice-RealityDevice","iPadAir-iPadAir"]`, []Platform{PlatformIPad, PlatformVisionOS, PlatformMacOS}),
|
||||
Entry("missing metadata", `"kind":"software"`, []Platform{PlatformUnknown}),
|
||||
Entry("unrecognized devices", `"supportedDevices":["FutureDevice"]`, []Platform{PlatformUnknown}),
|
||||
)
|
||||
|
||||
When("request is successful", func() {
|
||||
const (
|
||||
testID = 0
|
||||
@@ -80,6 +102,29 @@ var _ = Describe("AppStore (Search)", func() {
|
||||
})
|
||||
})
|
||||
|
||||
When("platform is macOS", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
parsedURL, err := url.Parse(req.URL)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(parsedURL.Query().Get("entity")).To(Equal("macSoftware"))
|
||||
}).
|
||||
Return(http.Result[searchResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("uses the macOS search entity", func() {
|
||||
_, err := as.Search(SearchInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
Platform: PlatformMacOS,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("platform is AppleTV", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
@@ -161,12 +206,28 @@ var _ = Describe("AppStore (Search)", func() {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.Count).To(Equal(2))
|
||||
Expect(out.Results).To(Equal([]App{
|
||||
{ID: 200, BundleID: "hydrated.two", Name: "Hydrated Two", Version: "2.0"},
|
||||
{ID: 100, BundleID: "hydrated.one", Name: "Hydrated One", Version: "1.0"},
|
||||
{ID: 200, BundleID: "hydrated.two", Name: "Hydrated Two", Version: "2.0", Platforms: []Platform{PlatformVisionOS}},
|
||||
{ID: 100, BundleID: "hydrated.one", Name: "Hydrated One", Version: "1.0", Platforms: []Platform{PlatformVisionOS}},
|
||||
}))
|
||||
})
|
||||
})
|
||||
|
||||
DescribeTable("preserves confirmed visionOS support",
|
||||
func(metadata []App, expected []Platform) {
|
||||
page := `<script type="application/json" id="serialized-server-data">{"data":[{"data":{"shelves":[{"items":[{"$kind":"AppSearchResult","lockup":{"adamId":"42"},"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=42&appExtVrsId=420"}}]}]}}]}</script>`
|
||||
mockStorefrontClient.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: []byte(page)}, nil)
|
||||
mockClient.EXPECT().Send(gomock.Any()).Return(http.Result[searchResult]{StatusCode: 200, Data: searchResult{Results: metadata}}, nil)
|
||||
out, err := as.Search(SearchInput{Account: Account{StoreFront: "143441"}, Platform: PlatformVisionOS, Limit: 1})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.Results).To(HaveLen(1))
|
||||
Expect(out.Results[0].Platforms).To(Equal(expected))
|
||||
},
|
||||
Entry("missing lookup result", nil, []Platform{PlatformVisionOS}),
|
||||
Entry("unknown lookup platforms", []App{{ID: 42, Platforms: []Platform{PlatformUnknown}}}, []Platform{PlatformVisionOS}),
|
||||
Entry("additional lookup platforms", []App{{ID: 42, Platforms: []Platform{PlatformIPhone, PlatformIPad}}}, []Platform{PlatformIPhone, PlatformIPad, PlatformVisionOS}),
|
||||
Entry("vision already present", []App{{ID: 42, Platforms: []Platform{PlatformVisionOS}}}, []Platform{PlatformVisionOS}),
|
||||
)
|
||||
|
||||
When("store front is invalid", func() {
|
||||
It("returns error", func() {
|
||||
_, err := as.Search(SearchInput{
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Update Product)", func() {
|
||||
const (
|
||||
testGUID = "001122334455"
|
||||
testVersionID = "123456789"
|
||||
)
|
||||
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockBagClient *http.MockClient[bagResult]
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockPlatformClient *http.MockClient[platformVersionLookupResult]
|
||||
store *appstore
|
||||
account Account
|
||||
app App
|
||||
bag bagResult
|
||||
expected http.Result[downloadResult]
|
||||
redownloadErr error
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockBagClient = http.NewMockClient[bagResult](ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
store = &appstore{bagClient: mockBagClient, downloadClient: mockDownloadClient, platformClient: mockPlatformClient}
|
||||
account = Account{DirectoryServicesID: "test-dsid", Pod: "42", StoreFront: "143441-1,34"}
|
||||
app = App{ID: 987654321, BundleID: "com.example.app"}
|
||||
bag = bagResult{}
|
||||
bag.URLBag.RedownloadEndpoint = testRedownloadEndpoint
|
||||
bag.URLBag.UpdateEndpoint = testUpdateEndpoint
|
||||
redownloadErr = fmt.Errorf("wrapped: %w", &http.UnexpectedResponseError{StatusCode: gohttp.StatusInternalServerError})
|
||||
expected = http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{Items: []downloadItemResult{{
|
||||
URL: "https://example.com/ios.ipa",
|
||||
Metadata: map[string]interface{}{
|
||||
"itemId": uint64(app.ID),
|
||||
"softwareVersionExternalIdentifier": uint64(123456789),
|
||||
"softwareVersionBundleId": app.BundleID,
|
||||
},
|
||||
}}},
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
expectPrimary := func() *gomock.Call {
|
||||
first := mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK}, nil)
|
||||
|
||||
return mockBagClient.EXPECT().Send(gomock.Any()).After(first).
|
||||
Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil)
|
||||
}
|
||||
|
||||
DescribeTable("retries once with the same pinned request",
|
||||
func(versionID string, platform Platform) {
|
||||
previous := expectPrimary()
|
||||
if versionID == "" {
|
||||
previous = mockPlatformClient.EXPECT().Send(gomock.Any()).After(previous).
|
||||
Return(http.Result[platformVersionLookupResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: platformVersionLookupResult{Results: map[string]platformVersionLookupItem{
|
||||
strconv.FormatInt(app.ID, 10): {Offers: []platformVersionLookupOffer{
|
||||
{Version: platformVersionLookupVersion{ExternalID: platformVersionExternalID(testVersionID)}},
|
||||
}},
|
||||
}},
|
||||
}, nil)
|
||||
}
|
||||
|
||||
var redownloadRequest http.Request
|
||||
|
||||
gomock.InOrder(
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testRedownloadEndpoint + "?guid=" + testGUID))
|
||||
redownloadRequest = req
|
||||
}).Return(http.Result[downloadResult]{}, redownloadErr),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testUpdateEndpoint + "?guid=" + testGUID))
|
||||
Expect(req.Method).To(Equal(http.MethodPOST))
|
||||
Expect(req.Headers).To(Equal(redownloadRequest.Headers))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("Content-Type", "application/x-apple-plist"))
|
||||
Expect(req.Payload).To(Equal(redownloadRequest.Payload))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", testVersionID))
|
||||
}).Return(expected, nil),
|
||||
)
|
||||
|
||||
actual, resolvedPlatform, err := store.sendDownloadProduct(account, app, testGUID, versionID, platform)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
if platform == "" {
|
||||
Expect(resolvedPlatform).To(Equal(PlatformIPhone))
|
||||
} else {
|
||||
Expect(resolvedPlatform).To(Equal(platform))
|
||||
}
|
||||
},
|
||||
Entry("default iOS", "", Platform("")),
|
||||
Entry("latest iPhone", "", PlatformIPhone),
|
||||
Entry("latest iPad", "", PlatformIPad),
|
||||
Entry("explicit historical version", testVersionID, PlatformIPhone),
|
||||
Entry("explicit macOS version", testVersionID, PlatformMacOS),
|
||||
Entry("explicit version without a platform", testVersionID, Platform("")),
|
||||
)
|
||||
|
||||
DescribeTable("tries update once for a message-only availability response",
|
||||
func(primaryUnavailable, updateUnavailable bool) {
|
||||
unavailable := http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{CustomerMessage: "“Messenger” No Longer Available"}}
|
||||
primary := http.Result[downloadResult]{StatusCode: gohttp.StatusOK}
|
||||
if primaryUnavailable {
|
||||
primary = unavailable
|
||||
}
|
||||
update := expected
|
||||
if updateUnavailable {
|
||||
update = unavailable
|
||||
}
|
||||
|
||||
gomock.InOrder(
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(primary, nil),
|
||||
mockBagClient.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testRedownloadEndpoint + "?guid=" + testGUID))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", testVersionID))
|
||||
}).Return(unavailable, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testUpdateEndpoint + "?guid=" + testGUID))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", testVersionID))
|
||||
}).Return(update, nil),
|
||||
)
|
||||
|
||||
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(actual).To(Equal(update))
|
||||
if updateUnavailable {
|
||||
Expect(err).To(MatchError(ContainSubstring(unavailable.Data.CustomerMessage)))
|
||||
} else {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
}
|
||||
},
|
||||
Entry("redownload unavailable", false, false),
|
||||
Entry("both initial endpoints unavailable", true, false),
|
||||
Entry("update also unavailable", false, true),
|
||||
)
|
||||
|
||||
DescribeTable("keeps TestFlight's Mac offer pinned through update fallback",
|
||||
func(versionID string, emptyRedownload bool, updateUnavailable bool) {
|
||||
app = App{ID: 899247664, BundleID: "com.apple.TestFlight"}
|
||||
expected.Data.Items[0].URL = "https://example.com/TestFlight.pkg"
|
||||
expected.Data.Items[0].Metadata["itemId"] = uint64(app.ID)
|
||||
expected.Data.Items[0].Metadata["softwareVersionBundleId"] = app.BundleID
|
||||
expected.Data.Items[0].Metadata["software-platform"] = "macos"
|
||||
if versionID == "" {
|
||||
pages := http.NewMockClient[[]byte](ctrl)
|
||||
store.storefrontClient = pages
|
||||
pages.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal("https://apps.apple.com/us/app/id899247664?platform=mac"))
|
||||
}).Return(http.Result[[]byte]{StatusCode: gohttp.StatusOK, Data: macVersionPage(
|
||||
`{"purchaseConfiguration":{"bundleId":"com.apple.TestFlight","appPlatforms":["mac"],"buyParams":"salableAdamId=899247664&appExtVrsId=123456789"}}`,
|
||||
)}, nil)
|
||||
}
|
||||
unavailable := http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{CustomerMessage: "“TestFlight” No Longer Available"}}
|
||||
redownload := unavailable
|
||||
var requestErr error
|
||||
if emptyRedownload {
|
||||
redownload = http.Result[downloadResult]{}
|
||||
requestErr = redownloadErr
|
||||
}
|
||||
update := expected
|
||||
if updateUnavailable {
|
||||
update = unavailable
|
||||
}
|
||||
var redownloadRequest http.Request
|
||||
gomock.InOrder(
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", testVersionID))
|
||||
}).Return(unavailable, nil),
|
||||
mockBagClient.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testRedownloadEndpoint + "?guid=" + testGUID))
|
||||
redownloadRequest = req
|
||||
}).Return(redownload, requestErr),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testUpdateEndpoint + "?guid=" + testGUID))
|
||||
Expect(req.Headers).To(Equal(redownloadRequest.Headers))
|
||||
Expect(req.Payload).To(Equal(redownloadRequest.Payload))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", testVersionID))
|
||||
}).Return(update, nil),
|
||||
)
|
||||
actual, platform, err := store.sendDownloadProduct(account, app, testGUID, versionID, PlatformMacOS)
|
||||
Expect(platform).To(Equal(PlatformMacOS))
|
||||
Expect(actual).To(Equal(update))
|
||||
if updateUnavailable {
|
||||
Expect(err).To(MatchError(ContainSubstring(unavailable.Data.CustomerMessage)))
|
||||
} else {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
}
|
||||
},
|
||||
Entry("latest Mac offer after availability errors", "", false, false),
|
||||
Entry("explicit Mac version after availability errors", testVersionID, false, false),
|
||||
Entry("latest Mac offer after empty HTTP 500", "", true, false),
|
||||
Entry("update also unavailable", "", false, true),
|
||||
)
|
||||
|
||||
DescribeTable("preserves availability responses when update is ineligible",
|
||||
func(platform Platform, updateEndpoint, failureType, message string, status int) {
|
||||
bag.URLBag.UpdateEndpoint = updateEndpoint
|
||||
previous := expectPrimary()
|
||||
response := http.Result[downloadResult]{StatusCode: status,
|
||||
Data: downloadResult{FailureType: failureType, CustomerMessage: message}}
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).Return(response, nil)
|
||||
|
||||
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, platform)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(response))
|
||||
},
|
||||
Entry("missing endpoint", PlatformIPhone, "", "", "“Messenger” No Longer Available", 200),
|
||||
Entry("tvOS", PlatformAppleTV, testUpdateEndpoint, "", "“Messenger” No Longer Available", 200),
|
||||
Entry("visionOS", PlatformVisionOS, testUpdateEndpoint, "", "“Messenger” No Longer Available", 200),
|
||||
Entry("license failure", PlatformIPhone, testUpdateEndpoint, FailureTypeLicenseNotFound, "“Messenger” No Longer Available", 200),
|
||||
Entry("other message", PlatformIPhone, testUpdateEndpoint, "", "Sign in required", 200),
|
||||
Entry("HTTP failure", PlatformIPhone, testUpdateEndpoint, "", "“Messenger” No Longer Available", 403),
|
||||
)
|
||||
|
||||
DescribeTable("preserves other redownload errors without retrying",
|
||||
func(original error) {
|
||||
previous := expectPrimary()
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
|
||||
Return(http.Result[downloadResult]{}, original)
|
||||
|
||||
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(errors.Is(err, original)).To(BeTrue())
|
||||
},
|
||||
Entry("authentication", &http.UnexpectedResponseError{StatusCode: gohttp.StatusForbidden}),
|
||||
Entry("rate limit", &http.UnexpectedResponseError{StatusCode: gohttp.StatusTooManyRequests}),
|
||||
Entry("service unavailable", &http.UnexpectedResponseError{StatusCode: gohttp.StatusServiceUnavailable}),
|
||||
Entry("nonempty 500", &http.UnexpectedResponseError{StatusCode: gohttp.StatusInternalServerError, Snippet: "maintenance"}),
|
||||
Entry("transport failure", errors.New("connection reset")),
|
||||
)
|
||||
|
||||
DescribeTable("does not retry a decoded redownload response",
|
||||
func(response http.Result[downloadResult]) {
|
||||
previous := expectPrimary()
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).Return(response, nil)
|
||||
|
||||
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(response))
|
||||
},
|
||||
Entry("successful download", http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{Items: []downloadItemResult{{URL: "https://example.com/app.ipa"}}}}),
|
||||
Entry("license error", http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{FailureType: FailureTypeLicenseNotFound}}),
|
||||
Entry("empty HTTP 200", http.Result[downloadResult]{StatusCode: gohttp.StatusOK}),
|
||||
Entry("decoded HTTP 500", http.Result[downloadResult]{StatusCode: gohttp.StatusInternalServerError}),
|
||||
)
|
||||
|
||||
It("preserves the redownload error when the update endpoint is missing", func() {
|
||||
bag.URLBag.UpdateEndpoint = ""
|
||||
previous := expectPrimary()
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
|
||||
Return(http.Result[downloadResult]{}, redownloadErr)
|
||||
|
||||
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(errors.Is(err, redownloadErr)).To(BeTrue())
|
||||
})
|
||||
|
||||
It("rejects an invalid bag endpoint before sending an update request", func() {
|
||||
bag.URLBag.UpdateEndpoint = "https://example.com/up/updateProduct"
|
||||
previous := expectPrimary()
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
|
||||
Return(http.Result[downloadResult]{}, redownloadErr)
|
||||
|
||||
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(err).To(MatchError("invalid download endpoint in bag"))
|
||||
})
|
||||
|
||||
DescribeTable("does not extend the fallback to unverified platforms",
|
||||
func(versionID string, platform Platform) {
|
||||
previous := expectPrimary()
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
|
||||
Return(http.Result[downloadResult]{}, redownloadErr)
|
||||
|
||||
_, resolvedPlatform, err := store.sendDownloadProduct(account, app, testGUID, versionID, platform)
|
||||
Expect(errors.Is(err, redownloadErr)).To(BeTrue())
|
||||
Expect(resolvedPlatform).To(Equal(platform))
|
||||
},
|
||||
Entry("pinned tvOS", testVersionID, PlatformAppleTV),
|
||||
Entry("pinned visionOS", testVersionID, PlatformVisionOS),
|
||||
)
|
||||
|
||||
It("propagates an update error without retrying again", func() {
|
||||
previous := expectPrimary()
|
||||
gomock.InOrder(
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
|
||||
Return(http.Result[downloadResult]{}, redownloadErr),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{}, redownloadErr),
|
||||
)
|
||||
|
||||
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
|
||||
Expect(errors.Is(err, redownloadErr)).To(BeTrue())
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to send update request")))
|
||||
})
|
||||
|
||||
DescribeTable("preserves structured update failures for the caller",
|
||||
func(failure string) {
|
||||
expected.Data = downloadResult{FailureType: failure, CustomerMessage: "App Store error"}
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil)
|
||||
|
||||
actual, err := store.sendUpdateProduct(testUpdateEndpoint, account, app, testGUID, testVersionID)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
},
|
||||
Entry("license required", FailureTypeLicenseNotFound),
|
||||
Entry("expired session", FailureTypePasswordTokenExpired),
|
||||
Entry("sign in required", FailureTypeSignInRequired),
|
||||
)
|
||||
|
||||
It("rejects a non-200 update response", func() {
|
||||
expected.StatusCode = gohttp.StatusInternalServerError
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil)
|
||||
|
||||
_, err := store.sendUpdateProduct(testUpdateEndpoint, account, app, testGUID, testVersionID)
|
||||
Expect(err).To(MatchError("received unexpected update status code: 500"))
|
||||
})
|
||||
|
||||
It("does not accept items when an update response contains only a customer error", func() {
|
||||
expected.Data.CustomerMessage = "Unable to process your request"
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil)
|
||||
|
||||
_, err := store.sendUpdateProduct(testUpdateEndpoint, account, app, testGUID, testVersionID)
|
||||
Expect(err).To(MatchError("received update error: Unable to process your request"))
|
||||
})
|
||||
|
||||
DescribeTable("requires exactly one update item",
|
||||
func(count int) {
|
||||
expected.Data.Items = make([]downloadItemResult, count)
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil)
|
||||
|
||||
_, err := store.sendUpdateProduct(testUpdateEndpoint, account, app, testGUID, testVersionID)
|
||||
Expect(err).To(MatchError("update response must contain exactly one item"))
|
||||
},
|
||||
Entry("empty", 0),
|
||||
Entry("ambiguous", 2),
|
||||
)
|
||||
|
||||
DescribeTable("rejects mismatched or missing update identity",
|
||||
func(field string, value interface{}) {
|
||||
expected.Data.Items[0].Metadata[field] = value
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil)
|
||||
|
||||
_, err := store.sendUpdateProduct(testUpdateEndpoint, account, app, testGUID, testVersionID)
|
||||
Expect(err).To(MatchError(ContainSubstring("update response does not match")))
|
||||
},
|
||||
Entry("wrong app", "itemId", uint64(42)),
|
||||
Entry("missing app", "itemId", nil),
|
||||
Entry("different version", "softwareVersionExternalIdentifier", uint64(987654321)),
|
||||
Entry("missing version", "softwareVersionExternalIdentifier", nil),
|
||||
Entry("wrong bundle", "softwareVersionBundleId", "com.example.other"),
|
||||
Entry("missing bundle", "softwareVersionBundleId", nil),
|
||||
Entry("empty bundle", "softwareVersionBundleId", ""),
|
||||
)
|
||||
|
||||
It("accepts string identifiers for an ID-only caller", func() {
|
||||
app.BundleID = ""
|
||||
expected.Data.Items[0].Metadata["itemId"] = strconv.FormatInt(app.ID, 10)
|
||||
expected.Data.Items[0].Metadata["softwareVersionExternalIdentifier"] = testVersionID
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil)
|
||||
|
||||
actual, err := store.sendUpdateProduct(testUpdateEndpoint, account, app, testGUID, testVersionID)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
})
|
||||
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"compress/flate"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (ZIP streaming framing)", func() {
|
||||
DescribeTable("preserves entry data and metadata with streaming-compatible framing",
|
||||
func(name string, method, sourceFlags uint16) {
|
||||
payload := []byte("streaming archive test payload")
|
||||
if strings.HasSuffix(name, "/") {
|
||||
payload = []byte{}
|
||||
}
|
||||
raw := payload
|
||||
if method == zip.Deflate {
|
||||
var compressed bytes.Buffer
|
||||
compressor, err := flate.NewWriter(&compressed, flate.HuffmanOnly)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = compressor.Write(payload)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(compressor.Close()).To(Succeed())
|
||||
raw = compressed.Bytes()
|
||||
}
|
||||
|
||||
By("creating an archive with the requested source framing")
|
||||
var source bytes.Buffer
|
||||
sourceWriter := zip.NewWriter(&source)
|
||||
writer, err := sourceWriter.CreateRaw(&zip.FileHeader{
|
||||
Name: name,
|
||||
Method: method,
|
||||
Flags: sourceFlags,
|
||||
CRC32: crc32.ChecksumIEEE(payload),
|
||||
CompressedSize64: uint64(len(raw)),
|
||||
UncompressedSize64: uint64(len(payload)),
|
||||
ModifiedDate: 0x5821,
|
||||
ModifiedTime: 0x1234,
|
||||
ExternalAttrs: 0x81a40000,
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = writer.Write(raw)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(sourceWriter.Close()).To(Succeed())
|
||||
|
||||
directory, err := os.MkdirTemp("", "ipatool-zip-framing-*")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(os.RemoveAll, directory)
|
||||
path := filepath.Join(directory, "source.zip")
|
||||
Expect(os.WriteFile(path, source.Bytes(), 0600)).To(Succeed())
|
||||
src, err := zip.OpenReader(path)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(src.Close)
|
||||
|
||||
var output bytes.Buffer
|
||||
dst := zip.NewWriter(&output)
|
||||
Expect((&appstore{}).replicateZip(src, dst, path)).To(Succeed())
|
||||
Expect(dst.Close()).To(Succeed())
|
||||
result, err := zip.NewReader(bytes.NewReader(output.Bytes()), int64(output.Len()))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(result.File).To(HaveLen(1))
|
||||
file := result.File[0]
|
||||
original := src.File[0]
|
||||
|
||||
By("checking local framing independently of the central directory")
|
||||
offset, err := file.DataOffset()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
local := output.Bytes()[:offset]
|
||||
flags := binary.LittleEndian.Uint16(local[6:8])
|
||||
Expect(flags).To(Equal(file.Flags))
|
||||
end := offset + int64(file.CompressedSize64)
|
||||
if method == zip.Deflate {
|
||||
Expect(flags & 8).To(Equal(uint16(8)))
|
||||
Expect(local[14:26]).To(Equal(make([]byte, 12)))
|
||||
descriptor := output.Bytes()[end : end+16]
|
||||
Expect(binary.LittleEndian.Uint32(descriptor)).To(Equal(uint32(0x08074b50)))
|
||||
Expect(binary.LittleEndian.Uint32(descriptor[4:])).To(Equal(file.CRC32))
|
||||
Expect(binary.LittleEndian.Uint32(descriptor[8:])).To(Equal(uint32(file.CompressedSize64)))
|
||||
Expect(binary.LittleEndian.Uint32(descriptor[12:])).To(Equal(uint32(file.UncompressedSize64)))
|
||||
} else {
|
||||
Expect(flags & 8).To(BeZero())
|
||||
Expect(binary.LittleEndian.Uint32(local[14:])).To(Equal(file.CRC32))
|
||||
Expect(binary.LittleEndian.Uint32(local[18:])).To(Equal(uint32(file.CompressedSize64)))
|
||||
Expect(binary.LittleEndian.Uint32(local[22:])).To(Equal(uint32(file.UncompressedSize64)))
|
||||
Expect(binary.LittleEndian.Uint32(output.Bytes()[end:])).To(Equal(uint32(0x02014b50)))
|
||||
}
|
||||
|
||||
By("preserving the compressed bytes and metadata")
|
||||
reader, err := file.OpenRaw()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
copied, err := io.ReadAll(reader)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(copied).To(Equal(raw))
|
||||
Expect(file.Name).To(Equal(original.Name))
|
||||
Expect(file.Method).To(Equal(original.Method))
|
||||
Expect(file.ModifiedDate).To(Equal(original.ModifiedDate))
|
||||
Expect(file.ModifiedTime).To(Equal(original.ModifiedTime))
|
||||
Expect(file.ExternalAttrs).To(Equal(original.ExternalAttrs))
|
||||
Expect(file.Extra).To(Equal(original.Extra))
|
||||
|
||||
By("reading the content back with CRC verification")
|
||||
contentReader, err := file.Open()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(contentReader.Close)
|
||||
content, err := io.ReadAll(contentReader)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(content).To(Equal(payload))
|
||||
},
|
||||
Entry("directory", "Payload/", zip.Store, uint16(0)),
|
||||
Entry("stored file without a descriptor", "stored", zip.Store, uint16(0)),
|
||||
Entry("stored file with an existing descriptor", "stored-descriptor", zip.Store, uint16(8)),
|
||||
Entry("deflated file without a descriptor", "deflated", zip.Deflate, uint16(0)),
|
||||
Entry("deflated file with an existing descriptor", "deflated-descriptor", zip.Deflate, uint16(8)),
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,289 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
)
|
||||
|
||||
const (
|
||||
zipLocalHeaderSignature = 0x04034b50
|
||||
zipCentralHeaderSignature = 0x02014b50
|
||||
zipDirectoryEndSignature = 0x06054b50
|
||||
zip64DirectoryEndSignature = 0x06064b50
|
||||
zip64LocatorSignature = 0x07064b50
|
||||
zip64ExtraID = 0x0001
|
||||
|
||||
zipLocalHeaderLen = 30
|
||||
zipCentralHeaderLen = 46
|
||||
zipDirectoryEndLen = 22
|
||||
zip64DirectoryEndLen = 56
|
||||
zip64LocatorLen = 20
|
||||
)
|
||||
|
||||
// zipLocalHeaders reads the local metadata that archive/zip's FileHeader omits.
|
||||
// The central directory provides offsets rather than relying on entry order or
|
||||
// searching compressed data for local-header signatures.
|
||||
type zipLocalHeaders struct {
|
||||
source io.ReaderAt
|
||||
directory *io.SectionReader
|
||||
base int64
|
||||
}
|
||||
|
||||
func newZIPLocalHeaders(source io.ReaderAt, size int64) (*zipLocalHeaders, error) {
|
||||
directory, err := readZIPDirectoryEnd(source, size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if directory.size > uint64(directory.endOffset) || directory.offset > math.MaxInt64 {
|
||||
return nil, zip.ErrFormat
|
||||
}
|
||||
|
||||
base := directory.endOffset - int64(directory.size) - int64(directory.offset)
|
||||
// Match archive/zip's handling of prefixed archives and inaccurate directory
|
||||
// sizes: prefer the declared offset if it already points to a central header.
|
||||
var signature [4]byte
|
||||
if base > 0 {
|
||||
if _, err := source.ReadAt(signature[:], int64(directory.offset)); err == nil && binary.LittleEndian.Uint32(signature[:]) == zipCentralHeaderSignature {
|
||||
base = 0
|
||||
}
|
||||
}
|
||||
|
||||
if base < 0 || base > size-int64(directory.offset) {
|
||||
return nil, zip.ErrFormat
|
||||
}
|
||||
|
||||
start := base + int64(directory.offset)
|
||||
|
||||
return &zipLocalHeaders{
|
||||
source: source,
|
||||
directory: io.NewSectionReader(source, start, size-start),
|
||||
base: base,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type zipDirectoryEnd struct {
|
||||
offset uint64
|
||||
size uint64
|
||||
endOffset int64
|
||||
}
|
||||
|
||||
func readZIPDirectoryEnd(source io.ReaderAt, size int64) (zipDirectoryEnd, error) {
|
||||
// The end record can be followed by a comment of up to 65535 bytes.
|
||||
tail := make([]byte, min(size, zipDirectoryEndLen+math.MaxUint16))
|
||||
if _, err := source.ReadAt(tail, size-int64(len(tail))); err != nil {
|
||||
return zipDirectoryEnd{}, fmt.Errorf("failed to read zip trailer: %w", err)
|
||||
}
|
||||
|
||||
for i := len(tail) - zipDirectoryEndLen; i >= 0; i-- {
|
||||
if binary.LittleEndian.Uint32(tail[i:]) != zipDirectoryEndSignature {
|
||||
continue
|
||||
}
|
||||
|
||||
commentLen := int(binary.LittleEndian.Uint16(tail[i+20:]))
|
||||
if i+zipDirectoryEndLen+commentLen > len(tail) {
|
||||
continue
|
||||
}
|
||||
|
||||
directory := zipDirectoryEnd{
|
||||
size: uint64(binary.LittleEndian.Uint32(tail[i+12:])),
|
||||
offset: uint64(binary.LittleEndian.Uint32(tail[i+16:])),
|
||||
endOffset: size - int64(len(tail)) + int64(i),
|
||||
}
|
||||
|
||||
return readZIP64DirectoryEnd(source, size, directory)
|
||||
}
|
||||
|
||||
return zipDirectoryEnd{}, zip.ErrFormat
|
||||
}
|
||||
|
||||
func readZIP64DirectoryEnd(source io.ReaderAt, size int64, directory zipDirectoryEnd) (zipDirectoryEnd, error) {
|
||||
// A ZIP64 locator, when present, immediately precedes the ordinary end record.
|
||||
if directory.endOffset < zip64LocatorLen {
|
||||
return directory, nil
|
||||
}
|
||||
|
||||
var locator [zip64LocatorLen]byte
|
||||
if _, err := source.ReadAt(locator[:], directory.endOffset-zip64LocatorLen); err != nil {
|
||||
return zipDirectoryEnd{}, fmt.Errorf("failed to read zip64 locator: %w", err)
|
||||
}
|
||||
|
||||
if binary.LittleEndian.Uint32(locator[:]) != zip64LocatorSignature {
|
||||
return directory, nil
|
||||
}
|
||||
|
||||
offset := binary.LittleEndian.Uint64(locator[8:])
|
||||
disk := binary.LittleEndian.Uint32(locator[4:])
|
||||
diskCount := binary.LittleEndian.Uint32(locator[16:])
|
||||
|
||||
if offset > uint64(size) || disk != 0 || diskCount != 1 {
|
||||
return zipDirectoryEnd{}, zip.ErrFormat
|
||||
}
|
||||
|
||||
var end [zip64DirectoryEndLen]byte
|
||||
if _, err := source.ReadAt(end[:], int64(offset)); err != nil {
|
||||
return zipDirectoryEnd{}, fmt.Errorf("failed to read zip64 trailer: %w", err)
|
||||
}
|
||||
|
||||
if binary.LittleEndian.Uint32(end[:]) != zip64DirectoryEndSignature {
|
||||
return zipDirectoryEnd{}, zip.ErrFormat
|
||||
}
|
||||
|
||||
return zipDirectoryEnd{
|
||||
size: binary.LittleEndian.Uint64(end[40:]),
|
||||
offset: binary.LittleEndian.Uint64(end[48:]),
|
||||
endOffset: int64(offset),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *zipLocalHeaders) extra(file *zip.File) ([]byte, error) {
|
||||
var central [zipCentralHeaderLen]byte
|
||||
if _, err := io.ReadFull(r.directory, central[:]); err != nil {
|
||||
return nil, fmt.Errorf("failed to read central header: %w", err)
|
||||
}
|
||||
|
||||
if binary.LittleEndian.Uint32(central[:]) != zipCentralHeaderSignature {
|
||||
return nil, zip.ErrFormat
|
||||
}
|
||||
|
||||
nameLen := int(binary.LittleEndian.Uint16(central[28:]))
|
||||
extraLen := int(binary.LittleEndian.Uint16(central[30:]))
|
||||
commentLen := int(binary.LittleEndian.Uint16(central[32:]))
|
||||
|
||||
metadata := make([]byte, nameLen+extraLen+commentLen)
|
||||
if _, err := io.ReadFull(r.directory, metadata); err != nil {
|
||||
return nil, fmt.Errorf("failed to read central metadata: %w", err)
|
||||
}
|
||||
|
||||
if string(metadata[:nameLen]) != file.Name {
|
||||
return nil, zip.ErrFormat
|
||||
}
|
||||
|
||||
offset, err := zipLocalHeaderOffset(central[:], metadata[nameLen:nameLen+extraLen])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if offset > uint64(math.MaxInt64-r.base) {
|
||||
return nil, zip.ErrFormat
|
||||
}
|
||||
|
||||
localOffset := r.base + int64(offset)
|
||||
|
||||
var local [zipLocalHeaderLen]byte
|
||||
|
||||
if _, err := r.source.ReadAt(local[:], localOffset); err != nil {
|
||||
return nil, fmt.Errorf("failed to read local header: %w", err)
|
||||
}
|
||||
|
||||
if binary.LittleEndian.Uint32(local[:]) != zipLocalHeaderSignature {
|
||||
return nil, zip.ErrFormat
|
||||
}
|
||||
|
||||
localNameLen := int(binary.LittleEndian.Uint16(local[26:]))
|
||||
localExtraLen := int(binary.LittleEndian.Uint16(local[28:]))
|
||||
|
||||
dataOffset, err := file.DataOffset()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to locate entry data: %w", err)
|
||||
}
|
||||
|
||||
if dataOffset-localOffset != int64(zipLocalHeaderLen+localNameLen+localExtraLen) {
|
||||
return nil, zip.ErrFormat
|
||||
}
|
||||
|
||||
localMetadata := make([]byte, localNameLen+localExtraLen)
|
||||
if _, err := r.source.ReadAt(localMetadata, localOffset+zipLocalHeaderLen); err != nil {
|
||||
return nil, fmt.Errorf("failed to read local metadata: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(localMetadata[:localNameLen], metadata[:nameLen]) {
|
||||
return nil, zip.ErrFormat
|
||||
}
|
||||
|
||||
return localMetadata[localNameLen:], nil
|
||||
}
|
||||
|
||||
// ZIP64 central-directory offsets belong to the source archive. Let zip.Writer
|
||||
// regenerate structural ZIP64 values for the output instead of leaving an old
|
||||
// block ahead of the one it appends. Preserve all other extra bytes verbatim.
|
||||
func zipExtraWithoutZIP64(extra []byte) []byte {
|
||||
result := make([]byte, 0, len(extra))
|
||||
|
||||
for len(extra) >= 4 {
|
||||
length := int(binary.LittleEndian.Uint16(extra[2:])) + 4
|
||||
if length > len(extra) {
|
||||
break
|
||||
}
|
||||
|
||||
if binary.LittleEndian.Uint16(extra) != zip64ExtraID {
|
||||
result = append(result, extra[:length]...)
|
||||
}
|
||||
|
||||
extra = extra[length:]
|
||||
}
|
||||
|
||||
return append(result, extra...)
|
||||
}
|
||||
|
||||
// Stored ZIP64 entries have no descriptor after framing normalization, so their
|
||||
// local ZIP64 sizes must be authoritative even if the source used placeholders.
|
||||
func zipStoredExtra(header *zip.FileHeader, extra []byte) []byte {
|
||||
if header.Method != zip.Store || (header.CompressedSize64 < math.MaxUint32 && header.UncompressedSize64 < math.MaxUint32) {
|
||||
return extra
|
||||
}
|
||||
|
||||
result := zipExtraWithoutZIP64(extra)
|
||||
|
||||
var sizes [20]byte
|
||||
|
||||
binary.LittleEndian.PutUint16(sizes[:], zip64ExtraID)
|
||||
binary.LittleEndian.PutUint16(sizes[2:], 16)
|
||||
binary.LittleEndian.PutUint64(sizes[4:], header.UncompressedSize64)
|
||||
binary.LittleEndian.PutUint64(sizes[12:], header.CompressedSize64)
|
||||
|
||||
return append(result, sizes[:]...)
|
||||
}
|
||||
|
||||
// ZIP64 values appear only for saturated fields, in this order:
|
||||
// uncompressed size, compressed size, local-header offset, disk number.
|
||||
func zipLocalHeaderOffset(central, extra []byte) (uint64, error) {
|
||||
offset := binary.LittleEndian.Uint32(central[42:])
|
||||
if offset != math.MaxUint32 {
|
||||
return uint64(offset), nil
|
||||
}
|
||||
|
||||
skip := 0
|
||||
if binary.LittleEndian.Uint32(central[24:]) == math.MaxUint32 {
|
||||
skip += 8
|
||||
}
|
||||
|
||||
if binary.LittleEndian.Uint32(central[20:]) == math.MaxUint32 {
|
||||
skip += 8
|
||||
}
|
||||
|
||||
for len(extra) >= 4 {
|
||||
tag := binary.LittleEndian.Uint16(extra)
|
||||
|
||||
length := int(binary.LittleEndian.Uint16(extra[2:]))
|
||||
if length > len(extra)-4 {
|
||||
return 0, zip.ErrFormat
|
||||
}
|
||||
|
||||
if tag == zip64ExtraID {
|
||||
if length < skip+8 {
|
||||
return 0, zip.ErrFormat
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint64(extra[4+skip:]), nil
|
||||
}
|
||||
|
||||
extra = extra[4+length:]
|
||||
}
|
||||
|
||||
return 0, zip.ErrFormat
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (ZIP local metadata)", func() {
|
||||
// Local Unix timestamp field captured from the affected United Airlines IPA.
|
||||
unixTimestamp := []byte{0x55, 0x58, 12, 0, 0xb1, 0x24, 0x51, 0x6a, 0xb1, 0x24, 0x51, 0x6a, 0xcb, 0, 0xc8, 0}
|
||||
localTimestamp := []byte{0x55, 0x54, 9, 0, 3, 0xb2, 0x27, 0x51, 0x6a, 0xb2, 0x27, 0x51, 0x6a}
|
||||
centralTimestamp := []byte{0x55, 0x54, 5, 0, 1, 0xb2, 0x27, 0x51, 0x6a}
|
||||
DescribeTable("preserves independent extra fields through metadata and SINF patches",
|
||||
func(local, central []byte) {
|
||||
source := timestampZIP(local, central)
|
||||
dir, err := os.MkdirTemp("", "ipatool-zip-timestamps-*")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(os.RemoveAll, dir)
|
||||
original, patched := filepath.Join(dir, "original.ipa"), filepath.Join(dir, "patched.ipa")
|
||||
Expect(os.WriteFile(original, source, 0600)).To(Succeed())
|
||||
store := &appstore{os: operatingsystem.New()}
|
||||
Expect(store.applyPatches(downloadItemResult{Metadata: map[string]interface{}{}}, Account{}, original, patched, nil)).To(Succeed())
|
||||
checkTimestampZIP(patched, local, central)
|
||||
Expect(store.ReplicateSinf(ReplicateSinfInput{PackagePath: patched, Sinfs: []Sinf{{Data: []byte("sinf")}}})).To(Succeed())
|
||||
checkTimestampZIP(patched, local, central)
|
||||
},
|
||||
Entry("United Airlines local-only Unix timestamp", unixTimestamp, []byte{}),
|
||||
Entry("identical local and central timestamps", centralTimestamp, centralTimestamp),
|
||||
Entry("local-only extended timestamp", localTimestamp, []byte{}),
|
||||
Entry("different local and central timestamps", localTimestamp, centralTimestamp),
|
||||
Entry("central-only extended timestamp", []byte{}, centralTimestamp),
|
||||
Entry("no extended timestamps", []byte{}, []byte{}),
|
||||
Entry("unknown local field", []byte{0xfe, 0xca, 3, 0, 1, 2, 3}, []byte{}),
|
||||
)
|
||||
|
||||
It("reads local extras in central-directory order, including prefixed archives", func() {
|
||||
data := timestampZIP(localTimestamp, nil)
|
||||
end := len(data) - 22
|
||||
start := int(binary.LittleEndian.Uint32(data[end+16:]))
|
||||
firstLen := 46 + int(binary.LittleEndian.Uint16(data[start+28:])) + int(binary.LittleEndian.Uint16(data[start+30:]))
|
||||
reordered := append([]byte{}, data[:start]...)
|
||||
reordered = append(reordered, data[start+firstLen:end]...)
|
||||
reordered = append(reordered, data[start:start+firstLen]...)
|
||||
reordered = append(reordered, data[end:]...)
|
||||
reordered = append([]byte("archive prefix"), reordered...)
|
||||
reader, err := zip.NewReader(bytes.NewReader(reordered), int64(len(reordered)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
headers, err := newZIPLocalHeaders(bytes.NewReader(reordered), int64(len(reordered)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
for _, file := range reader.File {
|
||||
extra, err := headers.extra(file)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
if file.Name == "Payload/Test.app/_CodeSignature/CodeResources" {
|
||||
Expect(extra).To(Equal(localTimestamp))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
It("reads ZIP64 entry offsets and a ZIP64 end record", func() {
|
||||
out := zip64TimestampZIP(localTimestamp)
|
||||
reader, err := zip.NewReader(bytes.NewReader(out), int64(len(out)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
headers, err := newZIPLocalHeaders(bytes.NewReader(out), int64(len(out)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
extra, err := headers.extra(reader.File[0])
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(extra).To(Equal(localTimestamp))
|
||||
|
||||
By("rewriting the ZIP64 archive without retaining stale central offsets")
|
||||
dir, err := os.MkdirTemp("", "ipatool-zip64-*")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(os.RemoveAll, dir)
|
||||
path := filepath.Join(dir, "source.zip")
|
||||
Expect(os.WriteFile(path, out, 0600)).To(Succeed())
|
||||
src, err := zip.OpenReader(path)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
DeferCleanup(src.Close)
|
||||
var output bytes.Buffer
|
||||
dst := zip.NewWriter(&output)
|
||||
Expect((&appstore{}).replicateZip(src, dst, path)).To(Succeed())
|
||||
Expect(dst.Close()).To(Succeed())
|
||||
resultPath := filepath.Join(dir, "result.zip")
|
||||
Expect(os.WriteFile(resultPath, output.Bytes(), 0600)).To(Succeed())
|
||||
checkTimestampZIP(resultPath, localTimestamp, []byte{})
|
||||
})
|
||||
|
||||
It("replaces local ZIP64 placeholder sizes when removing a stored entry's descriptor", func() {
|
||||
extra := append([]byte{}, unixTimestamp...)
|
||||
placeholder := make([]byte, 20)
|
||||
binary.LittleEndian.PutUint16(placeholder, 1)
|
||||
binary.LittleEndian.PutUint16(placeholder[2:], 16)
|
||||
extra = append(extra, placeholder...)
|
||||
size := uint64(math.MaxUint32) + 10
|
||||
result := zipStoredExtra(&zip.FileHeader{Method: zip.Store, CompressedSize64: size, UncompressedSize64: size}, extra)
|
||||
Expect(result[:len(unixTimestamp)]).To(Equal(unixTimestamp))
|
||||
Expect(result).To(HaveLen(len(unixTimestamp) + 20))
|
||||
Expect(binary.LittleEndian.Uint64(result[len(unixTimestamp)+4:])).To(Equal(size))
|
||||
Expect(binary.LittleEndian.Uint64(result[len(unixTimestamp)+12:])).To(Equal(size))
|
||||
})
|
||||
|
||||
It("rejects a truncated local extra field", func() {
|
||||
data := timestampZIP(localTimestamp, nil)
|
||||
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
binary.LittleEndian.PutUint16(data[28:], 0xffff)
|
||||
headers, err := newZIPLocalHeaders(bytes.NewReader(data), int64(len(data)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = headers.extra(reader.File[0])
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
// Build distinct local/central metadata without using the production helper.
|
||||
func timestampZIP(local, central []byte) []byte {
|
||||
var output bytes.Buffer
|
||||
writer := zip.NewWriter(&output)
|
||||
payload := []byte("signature")
|
||||
header := &zip.FileHeader{
|
||||
Name: "Payload/Test.app/_CodeSignature/CodeResources",
|
||||
Method: zip.Store,
|
||||
ModifiedDate: 0x5cea,
|
||||
ModifiedTime: 0x874d,
|
||||
Extra: local,
|
||||
CRC32: crc32.ChecksumIEEE(payload),
|
||||
CompressedSize64: uint64(len(payload)),
|
||||
UncompressedSize64: uint64(len(payload)),
|
||||
}
|
||||
entry, err := writer.CreateRaw(header)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = entry.Write(payload)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
header.Extra = central
|
||||
info, err := writer.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = io.WriteString(info, `<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleExecutable</key><string>Test</string></dict></plist>`)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(writer.Close()).To(Succeed())
|
||||
|
||||
return output.Bytes()
|
||||
}
|
||||
|
||||
func checkTimestampZIP(path string, local, central []byte) {
|
||||
data, err := os.ReadFile(path)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
// This fixture's CodeResources is the first entry. Inspect its local bytes
|
||||
// independently of the production reader and Go's central-only FileHeader.
|
||||
nameLen := int(binary.LittleEndian.Uint16(data[26:]))
|
||||
extraLen := int(binary.LittleEndian.Uint16(data[28:]))
|
||||
Expect(data[30+nameLen : 30+nameLen+extraLen]).To(Equal(local))
|
||||
Expect(binary.LittleEndian.Uint16(data[10:])).To(Equal(uint16(0x874d)))
|
||||
Expect(binary.LittleEndian.Uint16(data[12:])).To(Equal(uint16(0x5cea)))
|
||||
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(reader.File[0].Extra).To(BeEquivalentTo(central))
|
||||
entry, err := reader.File[0].Open()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
payload, err := io.ReadAll(entry)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(entry.Close()).To(Succeed())
|
||||
Expect(string(payload)).To(Equal("signature"))
|
||||
}
|
||||
|
||||
// Force ZIP64 offsets and end records without allocating a multi-gigabyte fixture.
|
||||
func zip64TimestampZIP(local []byte) []byte {
|
||||
data := timestampZIP(local, nil)
|
||||
end := len(data) - 22
|
||||
start := int(binary.LittleEndian.Uint32(data[end+16:]))
|
||||
nameLen := int(binary.LittleEndian.Uint16(data[start+28:]))
|
||||
offsetExtra := make([]byte, 12)
|
||||
binary.LittleEndian.PutUint16(offsetExtra, 1)
|
||||
binary.LittleEndian.PutUint16(offsetExtra[2:], 8)
|
||||
binary.LittleEndian.PutUint32(data[start+42:], 0xffffffff)
|
||||
binary.LittleEndian.PutUint16(data[start+30:], 12)
|
||||
out := append([]byte{}, data[:start+46+nameLen]...)
|
||||
out = append(out, offsetExtra...)
|
||||
out = append(out, data[start+46+nameLen:end]...)
|
||||
zip64Offset := len(out)
|
||||
end64 := make([]byte, 56)
|
||||
binary.LittleEndian.PutUint32(end64, 0x06064b50)
|
||||
binary.LittleEndian.PutUint64(end64[4:], 44)
|
||||
binary.LittleEndian.PutUint64(end64[24:], 2)
|
||||
binary.LittleEndian.PutUint64(end64[32:], 2)
|
||||
binary.LittleEndian.PutUint64(end64[40:], uint64(zip64Offset-start))
|
||||
binary.LittleEndian.PutUint64(end64[48:], uint64(start))
|
||||
out = append(out, end64...)
|
||||
locator := make([]byte, 20)
|
||||
binary.LittleEndian.PutUint32(locator, 0x07064b50)
|
||||
binary.LittleEndian.PutUint64(locator[8:], uint64(zip64Offset))
|
||||
binary.LittleEndian.PutUint32(locator[16:], 1)
|
||||
out = append(out, locator...)
|
||||
eocd := append([]byte{}, data[end:]...)
|
||||
binary.LittleEndian.PutUint16(eocd[10:], 0xffff)
|
||||
binary.LittleEndian.PutUint32(eocd[12:], 0xffffffff)
|
||||
binary.LittleEndian.PutUint32(eocd[16:], 0xffffffff)
|
||||
out = append(out, eocd...)
|
||||
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"howett.net/plist"
|
||||
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("Authentication recovery", func() {
|
||||
DescribeTable("honors Retry-After without exceeding the wait budget",
|
||||
func(status int, header string, calls int, expectedWaits []time.Duration) {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
client := apphttp.NewMockClient[loginResult](ctrl)
|
||||
responseErr := &apphttp.UnexpectedResponseError{StatusCode: status, RetryAfter: header}
|
||||
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{}, responseErr).Times(calls)
|
||||
var waits []time.Duration
|
||||
sut := &appstore{loginClient: client, authRetrySleep: func(delay time.Duration) { waits = append(waits, delay) }}
|
||||
_, err := sut.sendAuthenticationRequest(apphttp.Request{})
|
||||
Expect(errors.Is(err, responseErr)).To(BeTrue())
|
||||
if calls == 1 {
|
||||
Expect(waits).To(BeEmpty())
|
||||
} else {
|
||||
Expect(waits).To(Equal(expectedWaits))
|
||||
}
|
||||
},
|
||||
Entry("503 with a requested delay", 503, "5", 3, []time.Duration{5 * time.Second, 5 * time.Second}),
|
||||
Entry("429 with a requested delay", 429, "3", 3, []time.Duration{3 * time.Second, 3 * time.Second}),
|
||||
Entry("429 without a deadline", 429, "", 3, []time.Duration{10 * time.Second, 20 * time.Second}),
|
||||
Entry("429 with an invalid deadline", 429, "invalid", 3, []time.Duration{10 * time.Second, 20 * time.Second}),
|
||||
Entry("503 without a deadline", 503, "", 3, []time.Duration{10 * time.Second, 20 * time.Second}),
|
||||
Entry("204 without a deadline", 204, "", 3, []time.Duration{10 * time.Second, 20 * time.Second}),
|
||||
Entry("404 without a deadline", 404, "", 3, []time.Duration{10 * time.Second, 20 * time.Second}),
|
||||
Entry("Retry-After zero avoids a tight retry loop", 429, "0", 3, []time.Duration{time.Second, time.Second}),
|
||||
Entry("503 with a long deadline", 503, "3600", 1, []time.Duration(nil)),
|
||||
Entry("403 is not retried", 403, "1", 1, []time.Duration(nil)),
|
||||
Entry("malformed redirect is not retried", 302, "", 1, []time.Duration(nil)),
|
||||
)
|
||||
|
||||
It("parses dates and seconds without overflow or negative waits", func() {
|
||||
now := time.Date(2026, 9, 13, 12, 0, 0, 0, time.UTC)
|
||||
for value, want := range map[string]time.Duration{
|
||||
now.Add(5 * time.Second).Format(http.TimeFormat): 5 * time.Second,
|
||||
now.Add(-time.Second).Format(http.TimeFormat): 0,
|
||||
"0": 0, " 5 ": 5 * time.Second,
|
||||
"18446744073709551615": maxAuthenticationRetryDelay + time.Second,
|
||||
} {
|
||||
delay, ok := authenticationRetryAfter(value, now)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(delay).To(Equal(want))
|
||||
}
|
||||
for _, value := range []string{"", "-1", "invalid"} {
|
||||
_, ok := authenticationRetryAfter(value, now)
|
||||
Expect(ok).To(BeFalse())
|
||||
}
|
||||
})
|
||||
|
||||
It("does not retry populated Apple credential errors or 2FA challenges", func() {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
client := apphttp.NewMockClient[loginResult](ctrl)
|
||||
sut := &appstore{loginClient: client, authRetrySleep: func(time.Duration) { Fail("must not sleep") }}
|
||||
for _, data := range []loginResult{
|
||||
{FailureType: FailureTypeInvalidCredentials, CustomerMessage: "invalid credentials"},
|
||||
{CustomerMessage: CustomerMessageBadLogin},
|
||||
} {
|
||||
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{StatusCode: 200, Data: data}, nil).Times(1)
|
||||
result, err := sut.sendAuthenticationRequest(apphttp.Request{})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
_, _, err = sut.parseLoginResponse(&result, 2, "")
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).NotTo(ContainSubstring("another network"))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// The adapter only redirects network traffic to the local server; login still
|
||||
// validates Apple's advertised pod URL before this adapter receives a request.
|
||||
type loginSessionJar struct{ *cookiejar.Jar }
|
||||
|
||||
func (loginSessionJar) Save() error { return nil }
|
||||
|
||||
var _ = Describe("Login session continuity", func() {
|
||||
It("retains cookies and the signed payload through retries, a pod redirect and 2FA", func() {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
jar, err := cookiejar.New(nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
client := apphttp.NewClient[loginResult](apphttp.Args{CookieJar: loginSessionJar{jar}, Authentication: true})
|
||||
adapter := apphttp.NewMockClient[loginResult](ctrl)
|
||||
keychain := keychain.NewMockKeychain(ctrl)
|
||||
keychain.EXPECT().Set("account", gomock.Any()).Return(nil).Times(1)
|
||||
sut := &appstore{loginClient: adapter, keychain: keychain, authRetrySleep: func(time.Duration) {}}
|
||||
connections := make(chan string, 4)
|
||||
calls := 0
|
||||
podURL := "https://p7-buy.itunes.apple.com" + PrivateAppStoreAPIPathAuth
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer GinkgoRecover()
|
||||
calls++
|
||||
connections <- r.RemoteAddr
|
||||
Expect(r.Method).To(Equal(http.MethodPost))
|
||||
body, err := io.ReadAll(r.Body)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
signature, err := base64.StdEncoding.DecodeString(r.Header.Get(apphttp.HeaderAppleActionSignature))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(signature).To(Equal(body))
|
||||
var payload map[string]string
|
||||
_, err = plist.Unmarshal(body, &payload)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(payload["attempt"]).To(Equal("1"))
|
||||
if calls > 1 {
|
||||
cookie, err := r.Cookie("session")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(cookie.Value).To(Equal("retained"))
|
||||
}
|
||||
switch calls {
|
||||
case 1:
|
||||
http.SetCookie(w, &http.Cookie{Name: "session", Value: "retained", Path: "/"})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case 2:
|
||||
w.Header().Set("Location", podURL)
|
||||
w.WriteHeader(http.StatusFound)
|
||||
case 3:
|
||||
Expect(payload["password"]).To(Equal("password"))
|
||||
data, err := plist.Marshal(map[string]string{"customerMessage": CustomerMessageBadLogin}, plist.XMLFormat)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
_, err = w.Write(data)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
case 4:
|
||||
Expect(payload["password"]).To(Equal("password123456"))
|
||||
w.Header().Set(HTTPHeaderStoreFront, "143441-1,29")
|
||||
_, err = w.Write([]byte("<dict><key>passwordToken</key><string>token</string><key>dsPersonId</key><string>123</string></dict>"))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
default:
|
||||
Fail("unexpected request")
|
||||
}
|
||||
}))
|
||||
DeferCleanup(srv.Close)
|
||||
adapted := 0
|
||||
adapter.EXPECT().Send(gomock.Any()).DoAndReturn(func(request apphttp.Request) (apphttp.Result[loginResult], error) {
|
||||
adapted++
|
||||
if adapted == 3 {
|
||||
Expect(request.URL).To(Equal(podURL))
|
||||
}
|
||||
request.URL = srv.URL + PrivateAppStoreAPIPathAuth
|
||||
|
||||
return client.Send(request)
|
||||
}).Times(4)
|
||||
signer := &stubActionSigner{}
|
||||
_, err = sut.login("email", "password", "", "guid", testAuthEndpoint, signer)
|
||||
Expect(errors.Is(err, ErrAuthCodeRequired)).To(BeTrue())
|
||||
account, err := sut.login("email", "password", "123456", "guid", testAuthEndpoint, signer)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(account.PasswordToken).To(Equal("token"))
|
||||
seen := map[string]bool{}
|
||||
for range 4 {
|
||||
seen[<-connections] = true
|
||||
}
|
||||
Expect(seen).To(HaveLen(4))
|
||||
})
|
||||
})
|
||||
@@ -8,10 +8,13 @@ import (
|
||||
type Platform string
|
||||
|
||||
const (
|
||||
// PlatformUnknown is an output value, not a selectable store platform.
|
||||
PlatformUnknown Platform = "unknown"
|
||||
PlatformIPhone Platform = "iphone"
|
||||
PlatformIPad Platform = "ipad"
|
||||
PlatformAppleTV Platform = "appletv"
|
||||
PlatformVisionOS Platform = "visionos"
|
||||
PlatformMacOS Platform = "macos"
|
||||
)
|
||||
|
||||
func ParsePlatform(value string) (Platform, error) {
|
||||
@@ -26,6 +29,8 @@ func ParsePlatform(value string) (Platform, error) {
|
||||
return PlatformAppleTV, nil
|
||||
case "vision", "visionos", "visionpro", "xros", "realitydevice":
|
||||
return PlatformVisionOS, nil
|
||||
case "mac", "macos", "osx":
|
||||
return PlatformMacOS, nil
|
||||
default:
|
||||
return "", fmt.Errorf("invalid platform %q", value)
|
||||
}
|
||||
@@ -43,6 +48,8 @@ func (p Platform) lookupEntity() (string, error) {
|
||||
return "tvSoftware", nil
|
||||
case PlatformVisionOS:
|
||||
return "xrosSoftware", nil
|
||||
case PlatformMacOS:
|
||||
return "macSoftware", nil
|
||||
default:
|
||||
return "", fmt.Errorf("invalid platform %q", p)
|
||||
}
|
||||
@@ -60,6 +67,8 @@ func (p Platform) searchEntity() (string, error) {
|
||||
return "software,tvSoftware", nil
|
||||
case PlatformVisionOS:
|
||||
return "xrosSoftware", nil
|
||||
case PlatformMacOS:
|
||||
return "macSoftware", nil
|
||||
default:
|
||||
return "", fmt.Errorf("invalid platform %q", p)
|
||||
}
|
||||
|
||||
@@ -23,6 +23,9 @@ var _ = Describe("Platform", func() {
|
||||
Entry("Vision Pro", "visionpro", PlatformVisionOS),
|
||||
Entry("xrOS", "xrOS", PlatformVisionOS),
|
||||
Entry("realityDevice", "realityDevice", PlatformVisionOS),
|
||||
Entry("Mac", "mac", PlatformMacOS),
|
||||
Entry("macOS", "macOS", PlatformMacOS),
|
||||
Entry("OS X", "osx", PlatformMacOS),
|
||||
)
|
||||
|
||||
DescribeTable("maps platforms to lookup entities",
|
||||
@@ -36,6 +39,7 @@ var _ = Describe("Platform", func() {
|
||||
Entry("iPad", PlatformIPad, "iPadSoftware"),
|
||||
Entry("Apple TV", PlatformAppleTV, "tvSoftware"),
|
||||
Entry("visionOS", PlatformVisionOS, "xrosSoftware"),
|
||||
Entry("macOS", PlatformMacOS, "macSoftware"),
|
||||
)
|
||||
|
||||
DescribeTable("maps platforms to search entities",
|
||||
@@ -49,6 +53,7 @@ var _ = Describe("Platform", func() {
|
||||
Entry("iPad", PlatformIPad, "iPadSoftware"),
|
||||
Entry("Apple TV", PlatformAppleTV, "software,tvSoftware"),
|
||||
Entry("visionOS", PlatformVisionOS, "xrosSoftware"),
|
||||
Entry("macOS", PlatformMacOS, "macSoftware"),
|
||||
)
|
||||
|
||||
DescribeTable("maps platforms to metadata platforms",
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
type sessionCookieJar struct{ *cookiejar.Jar }
|
||||
|
||||
func (sessionCookieJar) Save() error { return nil }
|
||||
|
||||
var _ = Describe("Authentication transport", func() {
|
||||
DescribeTable("preserves cookies and signed POSTs across fresh connections",
|
||||
func(http2 bool) {
|
||||
jar, err := cookiejar.New(nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
signer := &recordingActionSigner{signature: []byte("signature")}
|
||||
addresses := make(chan string, 4)
|
||||
calls := 0
|
||||
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer GinkgoRecover()
|
||||
calls++
|
||||
addresses <- r.RemoteAddr
|
||||
Expect(r.ProtoMajor).To(Equal(map[bool]int{false: 1, true: 2}[http2]))
|
||||
Expect(r.Method).To(Equal(http.MethodPost))
|
||||
data, err := io.ReadAll(r.Body)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(data).To(Equal(signer.data))
|
||||
Expect(r.Header.Get(HeaderAppleActionSignature)).To(Equal(base64.StdEncoding.EncodeToString(signer.signature)))
|
||||
if calls > 1 {
|
||||
cookie, err := r.Cookie("session")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(cookie.Value).To(Equal("retained"))
|
||||
}
|
||||
switch calls {
|
||||
case 1:
|
||||
http.SetCookie(w, &http.Cookie{Name: "session", Value: "retained", Path: "/"})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case 2:
|
||||
w.Header().Set("Location", "https://p7-buy.itunes.apple.com"+appStoreAuthPath)
|
||||
w.WriteHeader(http.StatusFound)
|
||||
default:
|
||||
_, err = w.Write([]byte("<dict><key>foo</key><string>ok</string></dict>"))
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
}
|
||||
}))
|
||||
srv.EnableHTTP2 = http2
|
||||
srv.StartTLS()
|
||||
DeferCleanup(srv.Close)
|
||||
|
||||
original := http.DefaultTransport.(*http.Transport).DisableKeepAlives
|
||||
sut := NewClient[struct {
|
||||
Foo string `plist:"foo"`
|
||||
}](Args{CookieJar: sessionCookieJar{jar}, Authentication: true}).(*client[struct {
|
||||
Foo string `plist:"foo"`
|
||||
}])
|
||||
transport := sut.internalClient.Transport.(*AddHeaderTransport).T.(*http.Transport)
|
||||
// Trust only the test server's certificate; retain the production transport settings.
|
||||
transport.TLSClientConfig = srv.Client().Transport.(*http.Transport).TLSClientConfig.Clone()
|
||||
DeferCleanup(transport.CloseIdleConnections)
|
||||
request := Request{URL: srv.URL + appStoreAuthPath, Method: MethodPOST, ResponseFormat: ResponseFormatXML, ActionSigner: signer, Payload: &XMLPayload{Content: map[string]interface{}{"password": "password", "attempt": "1"}}}
|
||||
_, err = sut.Send(request)
|
||||
Expect(err).To(HaveOccurred())
|
||||
redirect, err := sut.Send(request)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(redirect.StatusCode).To(Equal(http.StatusFound))
|
||||
Expect(redirect.Headers).To(HaveKey("Location"))
|
||||
// The appstore layer validates the pod URL and explicitly repeats the POST.
|
||||
// Route that POST to this server to inspect it without contacting Apple.
|
||||
_, err = sut.Send(request)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
request.Payload = &XMLPayload{Content: map[string]interface{}{"password": "password123456", "attempt": "1"}}
|
||||
_, err = sut.Send(request)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(signer.calls).To(Equal(4))
|
||||
seen := map[string]bool{}
|
||||
for range 4 {
|
||||
seen[<-addresses] = true
|
||||
}
|
||||
Expect(seen).To(HaveLen(4))
|
||||
Expect(http.DefaultTransport.(*http.Transport).DisableKeepAlives).To(Equal(original))
|
||||
}, Entry("HTTP/1.1", false), Entry("HTTP/2", true),
|
||||
)
|
||||
|
||||
It("preserves a populated Apple error even with HTTP 429", func() {
|
||||
recorder := httptest.NewRecorder()
|
||||
recorder.Header().Set("Retry-After", "5")
|
||||
recorder.WriteHeader(http.StatusTooManyRequests)
|
||||
_, err := recorder.WriteString("<dict><key>failureType</key><string>badCredentials</string></dict>")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
sut := &client[map[string]string]{authentication: true}
|
||||
result, err := sut.handleXMLResponse(recorder.Result())
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(result.Data).To(HaveKeyWithValue("failureType", "badCredentials"))
|
||||
Expect(result.StatusCode).To(Equal(http.StatusTooManyRequests))
|
||||
})
|
||||
|
||||
It("retains pooling for ordinary clients", func() {
|
||||
addresses := make(chan string, 2)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
addresses <- r.RemoteAddr
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
DeferCleanup(srv.Close)
|
||||
sut := NewClient[struct{}](Args{})
|
||||
for range 2 {
|
||||
request, err := http.NewRequest(http.MethodGet, srv.URL, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
response, err := sut.Do(request)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(response.Body.Close()).To(Succeed())
|
||||
}
|
||||
Expect(<-addresses).To(Equal(<-addresses))
|
||||
})
|
||||
|
||||
DescribeTable("reports malformed responses without retaining credentials",
|
||||
func(status int, body, reason string) {
|
||||
recorder := httptest.NewRecorder()
|
||||
recorder.Header().Set("Content-Type", "text/html")
|
||||
recorder.Header().Set("X-Apple-Jingle-Correlation-Key", "correlation-123")
|
||||
recorder.Header().Set("Set-Cookie", "secret-cookie")
|
||||
recorder.Header().Set("Retry-After", "5")
|
||||
recorder.WriteHeader(status)
|
||||
_, err := recorder.WriteString(body)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
sut := &client[struct{}]{authentication: true}
|
||||
_, err = sut.handleXMLResponse(recorder.Result())
|
||||
Expect(err).To(HaveOccurred())
|
||||
responseErr, ok := err.(*UnexpectedResponseError)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(responseErr.StatusCode).To(Equal(status))
|
||||
Expect(responseErr.BodyLength).To(Equal(len(body)))
|
||||
Expect(responseErr.ContentType).To(Equal("text/html"))
|
||||
Expect(responseErr.CorrelationID).To(Equal("correlation-123"))
|
||||
Expect(responseErr.RetryAfter).To(Equal("5"))
|
||||
Expect(responseErr.Reason).To(Equal(reason))
|
||||
Expect(responseErr.Snippet).To(BeEmpty())
|
||||
Expect(err.Error()).NotTo(ContainSubstring("secret"))
|
||||
},
|
||||
Entry("empty forbidden response", 403, "", "empty or non-plist authentication response"),
|
||||
Entry("HTML failure", 500, "<html>secret-password</html>", "empty or non-plist authentication response"),
|
||||
Entry("redirect without Location", 302, "secret-token", "authentication redirect is missing Location"),
|
||||
Entry("rate limit", 429, "secret-token", "rate limited by Apple"),
|
||||
Entry("malformed plist", 200, "<plist><dict>secret-token", "malformed authentication plist"),
|
||||
)
|
||||
})
|
||||
+56
-4
@@ -33,20 +33,32 @@ type Client[R interface{}] interface {
|
||||
type client[R interface{}] struct {
|
||||
internalClient http.Client
|
||||
cookieJar CookieJar
|
||||
authentication bool
|
||||
}
|
||||
|
||||
type Args struct {
|
||||
CookieJar CookieJar
|
||||
// Authentication isolates login connections and reports only allowlisted response diagnostics.
|
||||
Authentication bool
|
||||
}
|
||||
|
||||
// UnexpectedResponseError preserves the HTTP status when Apple returns an
|
||||
// HTML or empty response where an XML plist was expected.
|
||||
type UnexpectedResponseError struct {
|
||||
StatusCode int
|
||||
Snippet string
|
||||
StatusCode int
|
||||
Snippet string
|
||||
Reason string
|
||||
BodyLength int
|
||||
ContentType string
|
||||
CorrelationID string
|
||||
RetryAfter string
|
||||
}
|
||||
|
||||
func (e *UnexpectedResponseError) Error() string {
|
||||
if e.Reason != "" {
|
||||
return fmt.Sprintf("unexpected response from Apple (HTTP %d): %s (body length=%d, content type=%q, correlation ID=%q)", e.StatusCode, e.Reason, e.BodyLength, e.ContentType, e.CorrelationID)
|
||||
}
|
||||
|
||||
if e.Snippet == "" {
|
||||
return fmt.Sprintf("unexpected response from Apple (HTTP %d): empty or non-plist body", e.StatusCode)
|
||||
}
|
||||
@@ -72,7 +84,18 @@ func (t *AddHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error
|
||||
}
|
||||
|
||||
func NewClient[R interface{}](args Args) Client[R] {
|
||||
transport := http.DefaultTransport
|
||||
|
||||
if args.Authentication {
|
||||
// Keep the cookie jar, but do not share pooled connections with other
|
||||
// Store operations or reuse a connection for the next login attempt.
|
||||
isolated := http.DefaultTransport.(*http.Transport).Clone()
|
||||
isolated.DisableKeepAlives = true
|
||||
transport = isolated
|
||||
}
|
||||
|
||||
return &client[R]{
|
||||
authentication: args.Authentication,
|
||||
internalClient: http.Client{
|
||||
Timeout: 0,
|
||||
Jar: args.CookieJar,
|
||||
@@ -83,7 +106,7 @@ func NewClient[R interface{}](args Args) Client[R] {
|
||||
|
||||
return nil
|
||||
},
|
||||
Transport: &AddHeaderTransport{http.DefaultTransport},
|
||||
Transport: &AddHeaderTransport{transport},
|
||||
},
|
||||
cookieJar: args.CookieJar,
|
||||
}
|
||||
@@ -207,7 +230,11 @@ func (c *client[R]) handleXMLResponse(res *http.Response) (Result[R], error) {
|
||||
return Result[R]{}, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode == http.StatusTooManyRequests {
|
||||
if c.authentication && res.StatusCode == http.StatusFound && strings.TrimSpace(res.Header.Get("Location")) == "" {
|
||||
return Result[R]{}, authenticationResponseError(res, body, "authentication redirect is missing Location")
|
||||
}
|
||||
|
||||
if !c.authentication && res.StatusCode == http.StatusTooManyRequests {
|
||||
return Result[R]{}, fmt.Errorf("rate limited by Apple (HTTP %d): %s", res.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
|
||||
@@ -226,6 +253,14 @@ func (c *client[R]) handleXMLResponse(res *http.Response) (Result[R], error) {
|
||||
normalizedBody := normalizeXMLPlistBody(body)
|
||||
|
||||
if !looksLikePropertyList(normalizedBody) {
|
||||
if c.authentication {
|
||||
if res.StatusCode == http.StatusTooManyRequests {
|
||||
return Result[R]{}, authenticationResponseError(res, body, "rate limited by Apple")
|
||||
}
|
||||
|
||||
return Result[R]{}, authenticationResponseError(res, body, "empty or non-plist authentication response")
|
||||
}
|
||||
|
||||
snippet := bodySnippet(body)
|
||||
|
||||
return Result[R]{}, &UnexpectedResponseError{
|
||||
@@ -236,6 +271,10 @@ func (c *client[R]) handleXMLResponse(res *http.Response) (Result[R], error) {
|
||||
|
||||
_, err = plist.Unmarshal(normalizedBody, &data)
|
||||
if err != nil {
|
||||
if c.authentication {
|
||||
return Result[R]{}, authenticationResponseError(res, body, "malformed authentication plist")
|
||||
}
|
||||
|
||||
return Result[R]{}, fmt.Errorf("failed to unmarshal xml: %w", err)
|
||||
}
|
||||
|
||||
@@ -356,3 +395,16 @@ func extractDocumentInnerBody(body []byte) []byte {
|
||||
|
||||
return documentBody
|
||||
}
|
||||
|
||||
// Do not retain bodies or arbitrary response headers: authentication responses
|
||||
// can contain credentials, tokens and cookies, including on failure.
|
||||
func authenticationResponseError(res *http.Response, body []byte, reason string) *UnexpectedResponseError {
|
||||
return &UnexpectedResponseError{
|
||||
StatusCode: res.StatusCode,
|
||||
Reason: reason,
|
||||
BodyLength: len(body),
|
||||
ContentType: bodySnippet([]byte(res.Header.Get("Content-Type"))),
|
||||
CorrelationID: bodySnippet([]byte(res.Header.Get("X-Apple-Jingle-Correlation-Key"))),
|
||||
RetryAfter: res.Header.Get("Retry-After"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>application-identifier</key>
|
||||
<string>dev.majd.ipatool</string>
|
||||
<key>com.apple.private.security.no-container</key>
|
||||
<true/>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>dev.majd.ipatool</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
# Build a standalone executable for jailbroken arm64 devices running iOS 15+.
|
||||
ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
OUTPUT=${1:-ipatool-ios-arm64}
|
||||
VERSION=${VERSION:-dev}
|
||||
|
||||
for TOOL in ldid cmake; do
|
||||
command -v "$TOOL" >/dev/null 2>&1 || {
|
||||
echo "$TOOL is required; install it with 'brew install ldid cmake'." >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
|
||||
SDKROOT=$(xcrun --sdk iphoneos --show-sdk-path)
|
||||
CC=$(xcrun --sdk iphoneos --find clang)
|
||||
export SDKROOT CC
|
||||
export IPHONEOS_DEPLOYMENT_TARGET=15.0
|
||||
export GOOS=ios GOARCH=arm64 CGO_ENABLED=1
|
||||
|
||||
BUILD_DIR=$(mktemp -d /tmp/ipatool-ios.XXXXXX)
|
||||
trap 'rm -rf "$BUILD_DIR"' EXIT HUP INT TERM
|
||||
|
||||
# Keep this version in sync with internal/sap/unicorn/artifact.go.
|
||||
curl -fL --retry 3 https://github.com/unicorn-engine/unicorn/archive/refs/tags/2.1.4.tar.gz -o "$BUILD_DIR/unicorn.tar.gz"
|
||||
echo "ea8863f095a0136388694e5a6063afd9bb7650e30243dd6251af59c5ce5601f4 $BUILD_DIR/unicorn.tar.gz" | shasum -a 256 -c -
|
||||
tar -xzf "$BUILD_DIR/unicorn.tar.gz" -C "$BUILD_DIR"
|
||||
# Use iOS W^X memory protection for Unicorn, including nested Go callbacks.
|
||||
patch -d "$BUILD_DIR/unicorn-2.1.4" -p1 < "$ROOT/tools/patches/unicorn-ios.patch"
|
||||
ARCHFLAGS='-arch arm64' cmake -S "$BUILD_DIR/unicorn-2.1.4" -B "$BUILD_DIR/build" \
|
||||
-DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_SYSROOT="$SDKROOT" \
|
||||
-DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=15.0 \
|
||||
-DCMAKE_C_FLAGS='-target arm64-apple-ios15.0' -DCMAKE_BUILD_TYPE=Release \
|
||||
-DBUILD_SHARED_LIBS=OFF -DUNICORN_ARCH=x86 -DUNICORN_BUILD_TESTS=OFF -DUNICORN_INSTALL=OFF
|
||||
cmake --build "$BUILD_DIR/build" --parallel "$(sysctl -n hw.ncpu)"
|
||||
|
||||
# purego resolves the statically linked Unicorn API through dlsym.
|
||||
export CGO_LDFLAGS="${CGO_LDFLAGS:-} -Wl,-force_load,$BUILD_DIR/build/libunicorn.a -Wl,-export_dynamic"
|
||||
cd "$ROOT"
|
||||
go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o "$OUTPUT" .
|
||||
ldid -S"$ROOT/resources/ios-entitlements.plist" "$OUTPUT"
|
||||
@@ -0,0 +1,76 @@
|
||||
--- a/qemu/configure
|
||||
+++ b/qemu/configure
|
||||
@@ -2152,7 +2152,7 @@
|
||||
if [ "$darwin" = "yes" ] ; then
|
||||
cat > $TMPC << EOF
|
||||
#include <pthread.h>
|
||||
-int main() { pthread_jit_write_protect_supported_np(); return 0;}
|
||||
+int main() { pthread_jit_write_protect_supported_np(); pthread_jit_write_protect_np(0); return 0;}
|
||||
EOF
|
||||
if ! compile_prog ""; then
|
||||
have_pthread_jit_protect='no'
|
||||
--- a/qemu/include/tcg/tcg-apple-jit.h
|
||||
+++ b/qemu/include/tcg/tcg-apple-jit.h
|
||||
@@ -104,13 +104,11 @@
|
||||
#endif
|
||||
|
||||
|
||||
-#if defined(__APPLE__) && defined(HAVE_PTHREAD_JIT_PROTECT) && (defined(__arm__) || defined(__aarch64__))
|
||||
+#if defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__)
|
||||
|
||||
-/* write protect enable = write disable */
|
||||
-static inline void jit_write_protect(int enabled)
|
||||
-{
|
||||
- return pthread_jit_write_protect_np(enabled);
|
||||
-}
|
||||
+struct uc_struct;
|
||||
+void ipatool_jit_write_protect(struct uc_struct *uc, int enabled);
|
||||
+#define jit_write_protect(enabled) ipatool_jit_write_protect(uc, enabled)
|
||||
|
||||
#define JIT_CALLBACK_GUARD(x) \
|
||||
{ \
|
||||
--- a/qemu/accel/tcg/translate-all.c
|
||||
+++ b/qemu/accel/tcg/translate-all.c
|
||||
@@ -1019,7 +1019,7 @@
|
||||
static inline void *alloc_code_gen_buffer(struct uc_struct *uc)
|
||||
{
|
||||
TCGContext *tcg_ctx = uc->tcg_ctx;
|
||||
- int prot = PROT_WRITE | PROT_READ | PROT_EXEC;
|
||||
+ int prot = PROT_WRITE | PROT_READ;
|
||||
int flags = MAP_PRIVATE | MAP_ANONYMOUS;
|
||||
size_t size = tcg_ctx->code_gen_buffer_size;
|
||||
void *buf;
|
||||
@@ -2172,7 +2172,20 @@
|
||||
}
|
||||
|
||||
|
||||
-#if defined(__APPLE__) && defined(HAVE_PTHREAD_JIT_PROTECT) && (defined(__arm__) || defined(__aarch64__))
|
||||
+/* iOS CLI processes cannot use MAP_JIT outside an app sandbox. Toggle the
|
||||
+ * translation buffer between writable and executable instead of using RWX. */
|
||||
+void ipatool_jit_write_protect(struct uc_struct *uc, int enabled)
|
||||
+{
|
||||
+ TCGContext *ctx = uc->tcg_ctx;
|
||||
+ if (ctx && ctx->initial_buffer &&
|
||||
+ mprotect(ctx->initial_buffer, ctx->initial_buffer_size,
|
||||
+ PROT_READ | (enabled ? PROT_EXEC : PROT_WRITE)) != 0) {
|
||||
+ perror("protect Unicorn translation buffer");
|
||||
+ abort();
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+#if defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__)
|
||||
static bool tb_exec_is_locked(struct uc_struct *uc)
|
||||
{
|
||||
return uc->current_executable;
|
||||
--- a/uc.c
|
||||
+++ b/uc.c
|
||||
@@ -35,8 +35,7 @@
|
||||
static uc_err uc_snapshot(uc_engine *uc);
|
||||
static uc_err uc_restore_latest_snapshot(uc_engine *uc);
|
||||
|
||||
-#if defined(__APPLE__) && defined(HAVE_PTHREAD_JIT_PROTECT) && \
|
||||
- (defined(__arm__) || defined(__aarch64__))
|
||||
+#if defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__)
|
||||
static void save_jit_state(uc_engine *uc)
|
||||
{
|
||||
if (!uc->nested) {
|
||||
Reference in new issue
Block a user