mirror of
https://github.com/majd/ipatool
synced 2026-11-28 02:07:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4484b55d36 | ||
|
|
e3932cec31 | ||
|
|
cde7d00355 | ||
|
|
93b527a839 | ||
|
|
ed45c02852 | ||
|
|
f11d9abafe | ||
|
|
f9aa6536cd | ||
|
|
3411d57f45 | ||
|
|
0cc226a3d7 | ||
|
|
e258fed14a | ||
|
|
1ec8b3e5dc | ||
|
|
387d1a4f47 | ||
|
|
294488012f | ||
|
|
5deb9b521b | ||
|
|
acd9e7a972 | ||
|
|
50312a928b | ||
|
|
735b689ac3 | ||
|
|
e5211d6fd9 | ||
|
|
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 | ||
|
|
d5d0b56faf | ||
|
|
30d19a6859 | ||
|
|
27e8902d7e | ||
|
|
acaf6c566e | ||
|
|
652b9d0083 | ||
|
|
a53550f9c4 | ||
|
|
161888d240 |
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 +0,0 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance for coding agents working in this repository.
|
||||
|
||||
## Repository overview
|
||||
- Project: `ipatool`
|
||||
- Language: Go
|
||||
- Entry point: `main.go`
|
||||
- CLI command implementations: `cmd/`
|
||||
|
||||
## Development workflow
|
||||
1. Keep changes focused and minimal.
|
||||
2. Prefer idiomatic Go and keep command behavior consistent with existing commands in `cmd/`.
|
||||
3. Run formatting and tests before finalizing changes.
|
||||
|
||||
## Local checks
|
||||
Use these commands from the repository root:
|
||||
|
||||
```bash
|
||||
go generate ./...
|
||||
go test ./...
|
||||
go build ./...
|
||||
```
|
||||
|
||||
## Coding conventions
|
||||
- Follow standard Go formatting (`gofmt`).
|
||||
- Avoid introducing new dependencies unless necessary.
|
||||
- Keep user-facing text consistent with existing CLI help/output tone.
|
||||
- Preserve backward compatibility for CLI flags and output formats unless explicitly asked to change them.
|
||||
|
||||
## Commit/PR guidance
|
||||
- Write clear, scoped commit messages.
|
||||
- Summarize what changed and why in PR descriptions.
|
||||
- Include test/build results in your handoff.
|
||||
@@ -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, watchOS, 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 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,130 +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, watchOS, 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, watchOS, 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 and tvOS 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 (default 5)
|
||||
--platform string Platform to search: iphone, ipad, or appletv
|
||||
|
||||
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 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)
|
||||
-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 download a copy of the ipa file, use the `download` command.
|
||||
|
||||
```
|
||||
Download (encrypted) iOS and tvOS app packages from the App Store
|
||||
|
||||
Usage:
|
||||
ipatool download [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 (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, ipad, or appletv
|
||||
--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
|
||||
@@ -184,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).
|
||||
+18
-26
@@ -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,29 +32,39 @@ func loginCmd() *cobra.Command {
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
interactive := cmd.Context().Value(interactiveKey).(bool)
|
||||
|
||||
if email == "" && !interactive {
|
||||
return errors.New("an Apple ID is required when not running in interactive mode; use the \"--email\" flag")
|
||||
}
|
||||
|
||||
if email == "" && interactive {
|
||||
value, err := readPrompt("enter Apple ID (email address or phone number): ", false)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read Apple ID: %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")
|
||||
|
||||
var lastErr error
|
||||
|
||||
// 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)
|
||||
}
|
||||
@@ -117,12 +111,10 @@ func loginCmd() *cobra.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&email, "email", "e", "", "email address for the Apple ID (required)")
|
||||
cmd.Flags().StringVarP(&email, "email", "e", "", "Apple ID email address or phone number (required)")
|
||||
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,106 @@
|
||||
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 Apple ID", []string{"--password", "secret"}, "an Apple ID 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, appleID string) {
|
||||
cmd := loginCmd()
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, interactive))
|
||||
cmd.SetArgs([]string{"--email", appleID, "--password", "secret"})
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.loginCalls).To(Equal(1))
|
||||
Expect(store.input).To(Equal(appstore.LoginInput{Email: appleID, Password: "secret"}))
|
||||
},
|
||||
Entry("interactive email", true, "user@example.com"),
|
||||
Entry("non-interactive email", false, "user@example.com"),
|
||||
Entry("interactive Chinese phone number", true, "+8613912345678"),
|
||||
Entry("non-interactive Chinese phone number", false, "+8613912345678"),
|
||||
Entry("interactive Indian phone number", true, "9123456789"),
|
||||
Entry("non-interactive Indian phone number", false, "9123456789"),
|
||||
)
|
||||
|
||||
DescribeTable("prompts for an Apple ID", func(input, appleID, 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: appleID, 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 Apple ID (email address or phone number): "))
|
||||
},
|
||||
Entry("reads email without requiring a terminal", "user@example.com\n", "user@example.com", ""),
|
||||
Entry("reads a phone number without requiring a terminal", "+91 91234-56789\n", "+91 91234-56789", ""),
|
||||
Entry("reports input errors", "", "", "failed to read Apple ID: 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
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestCmd(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Command Suite")
|
||||
}
|
||||
+19
-35
@@ -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,22 +52,23 @@ 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,
|
||||
keyring.FileBackend,
|
||||
},
|
||||
ServiceName: KeychainServiceName,
|
||||
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
|
||||
ServiceName: KeychainServiceName,
|
||||
KeychainTrustApplication: true,
|
||||
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")
|
||||
@@ -79,21 +79,19 @@ 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
|
||||
},
|
||||
}))
|
||||
|
||||
return keychain.New(keychain.Args{Keyring: ring})
|
||||
return keychain.New(keychain.Args{
|
||||
Keyring: ring,
|
||||
Label: KeychainServiceName,
|
||||
})
|
||||
}
|
||||
|
||||
// initWithCommand initializes the dependencies of the command.
|
||||
@@ -103,33 +101,19 @@ func initWithCommand(cmd *cobra.Command) {
|
||||
format := util.Must(OutputFormatFromString(cmd.Flag("format").Value.String()))
|
||||
|
||||
dependencies.Logger = newLogger(format, verbose)
|
||||
if cmd.Name() == "mcp" {
|
||||
dependencies.Logger = log.NewLogger(log.Args{Verbose: verbose, Writer: zerolog.SyncWriter(os.Stderr)})
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
+57
-26
@@ -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,26 +29,31 @@ func downloadCmd() *cobra.Command {
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "download",
|
||||
Short: "Download (encrypted) iOS and tvOS app packages from the App Store",
|
||||
Short: "Download iOS, iPadOS, tvOS, watchOS, 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
|
||||
}
|
||||
|
||||
store := appStore()
|
||||
infoResult, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc := infoResult.Account
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
purchaseRequired := false
|
||||
purchased := false
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
@@ -54,30 +64,38 @@ func downloadCmd() *cobra.Command {
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
app := appstore.App{ID: appID, BundleID: bundleID}
|
||||
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{
|
||||
lookupResult, err := store.Lookup(appstore.LookupInput{
|
||||
Account: acc,
|
||||
BundleID: bundleID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
if err != nil && (appID == 0 || !errors.Is(err, appstore.ErrAppNotFound)) {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
// Delisted apps may still be downloadable by their numeric ID.
|
||||
if err == nil {
|
||||
app = lookupResult.App
|
||||
}
|
||||
}
|
||||
|
||||
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 +121,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 +134,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
|
||||
}
|
||||
|
||||
@@ -149,12 +167,25 @@ func downloadCmd() *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 when found)")
|
||||
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 iOS app (defaults to latest version when not specified)")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone, ipad, or appletv")
|
||||
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), watchos, 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,330 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"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() {
|
||||
Describe("app resolution", func() {
|
||||
var store *fakeDownloadAppStore
|
||||
|
||||
BeforeEach(func() {
|
||||
store = &fakeDownloadAppStore{account: appstore.Account{StoreFront: "143441"}}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
})
|
||||
|
||||
execute := func(args ...string) error {
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs(args)
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
return cmd.Execute()
|
||||
}
|
||||
|
||||
It("uses the app ID when the bundle is absent from the catalog", func() {
|
||||
store.lookupError = fmt.Errorf("lookup: %w", appstore.ErrAppNotFound)
|
||||
Expect(execute("-i", "42", "-b", "com.example.delisted", "--platform", "appletv")).To(Succeed())
|
||||
Expect(store.lookupInputs).To(Equal([]appstore.LookupInput{{
|
||||
Account: appstore.Account{StoreFront: "143441"},
|
||||
BundleID: "com.example.delisted",
|
||||
Platform: appstore.PlatformAppleTV,
|
||||
}}))
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(appstore.App{ID: 42, BundleID: "com.example.delisted"}))
|
||||
Expect(store.downloadInputs[0].Platform).To(Equal(appstore.PlatformAppleTV))
|
||||
})
|
||||
|
||||
It("preserves bundle identifier precedence when lookup succeeds", func() {
|
||||
store.lookupOutput.App = appstore.App{ID: 43, BundleID: "com.example.listed"}
|
||||
Expect(execute("-i", "42", "-b", "com.example.listed")).To(Succeed())
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(store.lookupOutput.App))
|
||||
})
|
||||
|
||||
It("resolves a bundle identifier without an app ID", func() {
|
||||
store.lookupOutput.App = appstore.App{ID: 43, BundleID: "com.example.listed"}
|
||||
Expect(execute("-b", "com.example.listed")).To(Succeed())
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(store.lookupOutput.App))
|
||||
})
|
||||
|
||||
It("does not look up the bundle for an explicit app ID and version", func() {
|
||||
Expect(execute("-i", "42", "--platform", "appletv", "--external-version-id", "123456")).To(Succeed())
|
||||
Expect(store.lookupInputs).To(BeEmpty())
|
||||
Expect(store.downloadInputs).To(HaveLen(1))
|
||||
Expect(store.downloadInputs[0].App).To(Equal(appstore.App{ID: 42}))
|
||||
Expect(store.downloadInputs[0].ExternalVersionID).To(Equal("123456"))
|
||||
})
|
||||
|
||||
DescribeTable("preserves lookup errors", func(args []string, lookupError error) {
|
||||
store.lookupError = lookupError
|
||||
Expect(execute(args...)).To(MatchError(lookupError))
|
||||
Expect(store.downloadInputs).To(BeEmpty())
|
||||
},
|
||||
Entry("missing bundle without an app ID", []string{"-b", "com.example.delisted"}, appstore.ErrAppNotFound),
|
||||
Entry("request failure with an app ID", []string{"-i", "42", "-b", "com.example.app"}, errors.New("request failed")),
|
||||
)
|
||||
})
|
||||
|
||||
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"))
|
||||
})
|
||||
|
||||
DescribeTable("preserves the platform when automatic purchase retries the download", func(platform appstore.Platform) {
|
||||
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", string(platform), "--purchase"})
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.purchaseInputs).To(HaveLen(1))
|
||||
Expect(store.purchaseInputs[0].Platform).To(Equal(platform))
|
||||
Expect(store.purchaseInputs[0].App).To(Equal(appstore.App{ID: 42}))
|
||||
Expect(store.downloadInputs).To(HaveLen(2))
|
||||
Expect(store.downloadInputs[0].Platform).To(Equal(platform))
|
||||
Expect(store.downloadInputs[1].Platform).To(Equal(platform))
|
||||
},
|
||||
Entry("macOS", appstore.PlatformMacOS),
|
||||
Entry("watchOS", appstore.PlatformWatchOS),
|
||||
)
|
||||
|
||||
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.accountInfoCalls).To(Equal(1))
|
||||
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))
|
||||
})
|
||||
|
||||
DescribeTable("reuses the account throughout download retries", func(downloadErrors []error, purchaseCount int) {
|
||||
account := appstore.Account{
|
||||
Email: "user@example.com",
|
||||
Password: "password",
|
||||
PasswordToken: "expired-token",
|
||||
StoreFront: "143441",
|
||||
}
|
||||
refreshedAccount := account
|
||||
refreshedAccount.PasswordToken = "refreshed-token"
|
||||
store := &fakeDownloadAppStore{
|
||||
account: account,
|
||||
loginAccount: refreshedAccount,
|
||||
downloadErrors: downloadErrors,
|
||||
}
|
||||
previousDependencies := dependencies
|
||||
DeferCleanup(func() { dependencies = previousDependencies })
|
||||
dependencies.Logger = log.NewLogger(log.Args{})
|
||||
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--bundle-identifier", "com.example.app", "--purchase"})
|
||||
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
|
||||
|
||||
Expect(cmd.Execute()).To(Succeed())
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.loginInputs).To(Equal([]appstore.LoginInput{{Email: account.Email, Password: account.Password}}))
|
||||
Expect(store.lookupInputs).To(HaveLen(len(downloadErrors)))
|
||||
Expect(store.lookupInputs[0].Account).To(Equal(account))
|
||||
Expect(store.downloadInputs).To(HaveLen(len(downloadErrors)))
|
||||
Expect(store.downloadInputs[0].Account).To(Equal(account))
|
||||
|
||||
for _, input := range store.lookupInputs[1:] {
|
||||
Expect(input.Account).To(Equal(refreshedAccount))
|
||||
}
|
||||
|
||||
for _, input := range store.downloadInputs[1:] {
|
||||
Expect(input.Account).To(Equal(refreshedAccount))
|
||||
}
|
||||
|
||||
Expect(store.purchaseInputs).To(HaveLen(purchaseCount))
|
||||
|
||||
for _, input := range store.purchaseInputs {
|
||||
Expect(input.Account).To(Equal(refreshedAccount))
|
||||
}
|
||||
},
|
||||
Entry("refreshes an expired token", []error{appstore.ErrPasswordTokenExpired, nil}, 0),
|
||||
Entry("retains the refreshed token for a subsequent purchase", []error{appstore.ErrPasswordTokenExpired, appstore.ErrLicenseRequired, nil}, 1),
|
||||
)
|
||||
|
||||
It("returns an account read error before attempting a download", func() {
|
||||
store := &fakeDownloadAppStore{accountInfoError: errors.New("account unavailable")}
|
||||
cmd := downloadCmdWithAppStore(func() appstore.AppStore { return store })
|
||||
cmd.SetArgs([]string{"--app-id", "42"})
|
||||
|
||||
Expect(cmd.Execute()).To(MatchError(store.accountInfoError))
|
||||
Expect(store.accountInfoCalls).To(Equal(1))
|
||||
Expect(store.loginInputs).To(BeEmpty())
|
||||
Expect(store.lookupInputs).To(BeEmpty())
|
||||
Expect(store.purchaseInputs).To(BeEmpty())
|
||||
Expect(store.downloadInputs).To(BeEmpty())
|
||||
})
|
||||
})
|
||||
|
||||
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 {
|
||||
account appstore.Account
|
||||
accountInfoCalls int
|
||||
accountInfoError error
|
||||
downloadErrors []error
|
||||
downloadInputs []appstore.DownloadInput
|
||||
loginAccount appstore.Account
|
||||
loginInputs []appstore.LoginInput
|
||||
lookupInputs []appstore.LookupInput
|
||||
lookupOutput appstore.LookupOutput
|
||||
lookupError error
|
||||
purchaseErrors []error
|
||||
purchaseInputs []appstore.PurchaseInput
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
f.loginInputs = append(f.loginInputs, input)
|
||||
|
||||
return appstore.LoginOutput{Account: f.loginAccount}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDownloadAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
f.accountInfoCalls++
|
||||
|
||||
return appstore.AccountInfoOutput{Account: f.account}, f.accountInfoError
|
||||
}
|
||||
|
||||
func (*fakeDownloadAppStore) Revoke() error { return nil }
|
||||
|
||||
func (f *fakeDownloadAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
f.lookupInputs = append(f.lookupInputs, input)
|
||||
|
||||
return f.lookupOutput, f.lookupError
|
||||
}
|
||||
|
||||
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), watchos, 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{Context: cmd.Context(), 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), watchos, 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
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func mcpCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "mcp",
|
||||
Short: "Serve App Store tools over MCP using stdio",
|
||||
Long: "Serve App Store tools over the Model Context Protocol using stdio.\n" +
|
||||
"Authenticate with 'ipatool auth login' before using the tools.\n" +
|
||||
"Runs non-interactively; authentication tools are not exposed.",
|
||||
Args: cobra.NoArgs,
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
cmd.SetContext(context.WithValue(cmd.Context(), interactiveKey, false))
|
||||
initWithCommand(cmd)
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt)
|
||||
defer stop()
|
||||
|
||||
server := newMCPServer(dependencies.AppStore)
|
||||
if err := server.Run(ctx, &mcp.StdioTransport{}); err != nil {
|
||||
return fmt.Errorf("MCP server failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type mcpTools struct {
|
||||
store appstore.AppStore
|
||||
gate chan struct{}
|
||||
}
|
||||
|
||||
func newMCPServer(store appstore.AppStore) *mcp.Server {
|
||||
server := mcp.NewServer(&mcp.Implementation{Name: "ipatool", Version: version}, &mcp.ServerOptions{
|
||||
Instructions: "Use the existing ipatool account. If authentication is required, ask the user to run ipatool auth login outside MCP. Purchases support free apps only.",
|
||||
})
|
||||
tools := &mcpTools{store: store, gate: make(chan struct{}, 1)}
|
||||
addMCPTool(server, tools, "search_apps", "Search for apps on the App Store.", true, tools.search)
|
||||
addMCPTool(server, tools, "download_app", "Download an app package to the local filesystem. Optionally acquire a free license if purchase is true.", false, tools.download)
|
||||
addMCPTool(server, tools, "list_app_versions", "List available external version identifiers for an app.", true, tools.listVersions)
|
||||
addMCPTool(server, tools, "get_version_metadata", "Retrieve the display version and release date for a specific external version identifier of an app.", true, tools.getVersionMetadata)
|
||||
addMCPTool(server, tools, "list_purchases", "List apps owned by the authenticated account, with pagination.", true, tools.listPurchases)
|
||||
addMCPTool(server, tools, "purchase_app", "Obtain a license for a free app. Paid apps are not supported.", false, tools.purchase)
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
func addMCPTool[In, Out any](server *mcp.Server, tools *mcpTools, name, description string, readOnly bool, handler func(context.Context, In) (Out, error)) {
|
||||
mcp.AddTool(server, &mcp.Tool{
|
||||
Name: name,
|
||||
Description: description,
|
||||
Annotations: &mcp.ToolAnnotations{ReadOnlyHint: readOnly},
|
||||
}, func(ctx context.Context, _ *mcp.CallToolRequest, input In) (*mcp.CallToolResult, Out, error) {
|
||||
var zero Out
|
||||
|
||||
// The App Store client shares account state and caches across calls.
|
||||
select {
|
||||
case tools.gate <- struct{}{}:
|
||||
defer func() { <-tools.gate }()
|
||||
case <-ctx.Done():
|
||||
return nil, zero, fmt.Errorf("tool call canceled: %w", ctx.Err())
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, zero, fmt.Errorf("tool call canceled: %w", err)
|
||||
}
|
||||
|
||||
output, err := handler(ctx, input)
|
||||
if err != nil {
|
||||
return nil, zero, fmt.Errorf("%s failed: %w", name, err)
|
||||
}
|
||||
|
||||
return nil, output, nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
)
|
||||
|
||||
// mcpApp keeps every metadata field in the MCP response, including zero values.
|
||||
// The App Store's JSON representation is also used by other callers, so its
|
||||
// omission rules are left unchanged.
|
||||
type mcpApp struct {
|
||||
ID int64 `json:"trackId"`
|
||||
BundleID string `json:"bundleId"`
|
||||
Name string `json:"trackName"`
|
||||
Version string `json:"version"`
|
||||
Price float64 `json:"price"`
|
||||
PurchaseDate *time.Time `json:"purchaseDate"`
|
||||
Platforms []appstore.Platform `json:"platforms"`
|
||||
}
|
||||
|
||||
func newMCPApp(app appstore.App) mcpApp {
|
||||
output := mcpApp{
|
||||
ID: app.ID, BundleID: app.BundleID, Name: app.Name, Version: app.Version, Price: app.Price,
|
||||
Platforms: append([]appstore.Platform{}, app.Platforms...),
|
||||
}
|
||||
if !app.PurchaseDate.IsZero() {
|
||||
output.PurchaseDate = &app.PurchaseDate
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
// completeApp supplements sparse metadata without making catalog availability a
|
||||
// prerequisite for operating on owned or delisted apps.
|
||||
func (t *mcpTools) completeApp(acc appstore.Account, app appstore.App, platform appstore.Platform) appstore.App {
|
||||
knownPlatforms := len(app.Platforms) > 0 && app.Platforms[0] != appstore.PlatformUnknown
|
||||
if app.ID <= 0 || (app.BundleID != "" && app.Name != "" && app.Version != "" && knownPlatforms) {
|
||||
return app
|
||||
}
|
||||
|
||||
// Purchase history can contain several platforms when no filter was supplied.
|
||||
// Use an app's known platform for its catalog lookup in that case.
|
||||
if platform == "" && len(app.Platforms) > 0 && app.Platforms[0] != appstore.PlatformUnknown {
|
||||
platform = app.Platforms[0]
|
||||
}
|
||||
|
||||
out, err := t.store.Lookup(appstore.LookupInput{Account: acc, AppID: app.ID, Platform: platform})
|
||||
if err != nil || out.App.ID != app.ID {
|
||||
return app
|
||||
}
|
||||
|
||||
if app.BundleID == "" {
|
||||
app.BundleID = out.App.BundleID
|
||||
}
|
||||
|
||||
if app.Name == "" {
|
||||
app.Name = out.App.Name
|
||||
}
|
||||
|
||||
if app.Version == "" {
|
||||
app.Version = out.App.Version
|
||||
}
|
||||
|
||||
if len(out.App.Platforms) > 0 && (len(app.Platforms) == 0 || (len(app.Platforms) == 1 && app.Platforms[0] == appstore.PlatformUnknown)) {
|
||||
app.Platforms = out.App.Platforms
|
||||
}
|
||||
|
||||
if app.Price == 0 {
|
||||
app.Price = out.App.Price
|
||||
}
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
func (t *mcpTools) appResults(acc appstore.Account, apps []appstore.App, platform appstore.Platform) []mcpApp {
|
||||
results := make([]mcpApp, 0, len(apps))
|
||||
for _, app := range apps {
|
||||
results = append(results, newMCPApp(t.completeApp(acc, app, platform)))
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
type mcpAppParameters struct {
|
||||
AppID int64 `json:"app_id"`
|
||||
BundleIdentifier string `json:"bundle_identifier"`
|
||||
Platform appstore.Platform `json:"platform"`
|
||||
}
|
||||
|
||||
func appParameters(app appstore.App, platform appstore.Platform) mcpAppParameters {
|
||||
return mcpAppParameters{AppID: app.ID, BundleIdentifier: app.BundleID, Platform: platform}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("MCP app metadata", func() {
|
||||
DescribeTable("preserves source data when catalog metadata cannot be used", func(catalog appstore.App, lookupErr error) {
|
||||
original := appstore.App{ID: 123, Name: "Original name", Price: 2.99, Platforms: []appstore.Platform{appstore.PlatformUnknown}}
|
||||
store := &fakeMCPAppStore{lookup: func(appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return appstore.LookupOutput{App: catalog}, lookupErr
|
||||
}}
|
||||
tools := &mcpTools{store: store}
|
||||
|
||||
Expect(tools.completeApp(appstore.Account{}, original, "")).To(Equal(original))
|
||||
},
|
||||
Entry("delisted app", appstore.App{}, appstore.ErrAppNotFound),
|
||||
Entry("network failure", appstore.App{}, errors.New("network failure")),
|
||||
Entry("wrong app ID", appstore.App{ID: 999, BundleID: "wrong.bundle"}, nil),
|
||||
Entry("missing catalog values", appstore.App{ID: 123}, nil),
|
||||
)
|
||||
|
||||
It("avoids catalog lookups when app metadata is already complete", func() {
|
||||
tools := &mcpTools{store: &fakeMCPAppStore{}}
|
||||
app := appstore.App{ID: 123, BundleID: "com.example.app", Name: "Example", Version: "1.0", Platforms: []appstore.Platform{appstore.PlatformIPhone}}
|
||||
Expect(tools.completeApp(appstore.Account{}, app, "")).To(Equal(app))
|
||||
})
|
||||
})
|
||||
+603
@@ -0,0 +1,603 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("MCP server", func() {
|
||||
var (
|
||||
ctx context.Context
|
||||
store *fakeMCPAppStore
|
||||
session *mcp.ClientSession
|
||||
account appstore.Account
|
||||
app appstore.App
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
var cancel context.CancelFunc
|
||||
|
||||
ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
|
||||
DeferCleanup(cancel)
|
||||
account = appstore.Account{Email: "private-email", Password: "private-password", PasswordToken: "private-token"}
|
||||
app = appstore.App{ID: 123, BundleID: "com.example.app", Name: "Example"}
|
||||
store = &fakeMCPAppStore{}
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{Account: account}, nil
|
||||
}
|
||||
store.lookup = func(appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return appstore.LookupOutput{}, appstore.ErrAppNotFound
|
||||
}
|
||||
clientTransport, serverTransport := mcp.NewInMemoryTransports()
|
||||
serverSession, err := newMCPServer(store).Connect(ctx, serverTransport, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(func() { Expect(serverSession.Close()).To(Succeed()) })
|
||||
session, err = mcp.NewClient(&mcp.Implementation{Name: "test", Version: "1"}, nil).Connect(ctx, clientTransport, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
DeferCleanup(func() { Expect(session.Close()).To(Succeed()) })
|
||||
})
|
||||
|
||||
call := func(name string, args map[string]any) *mcp.CallToolResult {
|
||||
result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
It("registers the mcp subcommand", func() {
|
||||
command, _, err := rootCmd().Find([]string{"mcp"})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(command.Name()).To(Equal("mcp"))
|
||||
Expect(command.Args(command, []string{"unexpected"})).NotTo(Succeed())
|
||||
})
|
||||
|
||||
It("advertises exactly six tools and their schemas without auth functions", func() {
|
||||
result, err := session.ListTools(ctx, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
names := make([]string, 0, len(result.Tools))
|
||||
for _, tool := range result.Tools {
|
||||
names = append(names, tool.Name)
|
||||
Expect(tool.InputSchema).NotTo(BeNil())
|
||||
Expect(tool.OutputSchema).NotTo(BeNil())
|
||||
Expect(tool.Annotations.ReadOnlyHint).To(Equal(tool.Name != "download_app" && tool.Name != "purchase_app"))
|
||||
}
|
||||
Expect(names).To(ConsistOf("search_apps", "download_app", "list_app_versions", "get_version_metadata", "list_purchases", "purchase_app"))
|
||||
})
|
||||
|
||||
It("searches with CLI defaults and returns structured app data without credentials", func() {
|
||||
var input appstore.SearchInput
|
||||
|
||||
store.search = func(in appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.SearchOutput{Count: 1, Results: []appstore.App{app}}, nil
|
||||
}
|
||||
result := call("search_apps", map[string]any{"term": "example"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input).To(Equal(appstore.SearchInput{Account: account, Term: "example", Limit: 5}))
|
||||
data, err := json.Marshal(result.StructuredContent)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).To(ContainSubstring("com.example.app"))
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
Expect(result.Content).To(HaveLen(1))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("term", "example"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("limit", float64(5)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", ""))
|
||||
})
|
||||
|
||||
DescribeTable("passes search platform aliases and limits to the App Store", func(value string, platform appstore.Platform) {
|
||||
var input appstore.SearchInput
|
||||
|
||||
store.search = func(in appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.SearchOutput{}, nil
|
||||
}
|
||||
Expect(call("search_apps", map[string]any{"term": "example", "platform": value, "limit": 7}).IsError).To(BeFalse())
|
||||
Expect(input.Platform).To(Equal(platform))
|
||||
Expect(input.Limit).To(Equal(int64(7)))
|
||||
},
|
||||
Entry("tvOS", "tvos", appstore.PlatformAppleTV),
|
||||
Entry("watchOS", "watch", appstore.PlatformWatchOS),
|
||||
)
|
||||
|
||||
DescribeTable("rejects invalid inputs before accessing the account", func(name string, args map[string]any) {
|
||||
accountCalls := 0
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
accountCalls++
|
||||
|
||||
return appstore.AccountInfoOutput{}, errors.New("unexpected account access")
|
||||
}
|
||||
result, err := session.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
|
||||
Expect(err != nil || (result != nil && result.IsError)).To(BeTrue())
|
||||
Expect(accountCalls).To(BeZero())
|
||||
},
|
||||
Entry("missing search term", "search_apps", map[string]any{}),
|
||||
Entry("blank search term", "search_apps", map[string]any{"term": " "}),
|
||||
Entry("invalid search limit", "search_apps", map[string]any{"term": "app", "limit": 0}),
|
||||
Entry("wrong argument type", "search_apps", map[string]any{"term": 123}),
|
||||
Entry("credentials are not arguments", "search_apps", map[string]any{"term": "app", "password": "secret"}),
|
||||
Entry("invalid platform", "search_apps", map[string]any{"term": "app", "platform": "unknown"}),
|
||||
Entry("missing download app", "download_app", map[string]any{}),
|
||||
Entry("negative app ID", "purchase_app", map[string]any{"app_id": -1}),
|
||||
Entry("missing versions app", "list_app_versions", map[string]any{}),
|
||||
Entry("missing metadata app", "get_version_metadata", map[string]any{"external_version_id": "200"}),
|
||||
Entry("missing metadata version", "get_version_metadata", map[string]any{"app_id": 123}),
|
||||
Entry("empty metadata version", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": ""}),
|
||||
Entry("blank metadata version", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": " "}),
|
||||
Entry("invalid metadata version type", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": 200}),
|
||||
Entry("invalid metadata platform", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200", "platform": "unknown"}),
|
||||
Entry("invalid page", "list_purchases", map[string]any{"page": 0}),
|
||||
Entry("invalid page size", "list_purchases", map[string]any{"max_results": 101}),
|
||||
)
|
||||
|
||||
It("returns actionable account errors and keeps serving requests", func() {
|
||||
store.accountInfo = func() (appstore.AccountInfoOutput, error) {
|
||||
return appstore.AccountInfoOutput{}, errors.New("account not found")
|
||||
}
|
||||
result := call("list_purchases", map[string]any{})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("ipatool auth login"))
|
||||
_, err := session.ListTools(ctx, nil)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
})
|
||||
|
||||
DescribeTable("lists purchases with pagination", func(args map[string]any, page, limit int, platform appstore.Platform) {
|
||||
var input appstore.OwnedAppsInput
|
||||
|
||||
store.ownedApps = func(in appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 11, Page: in.Page, Results: []appstore.App{app}}, nil
|
||||
}
|
||||
result := call("list_purchases", args)
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input).To(Equal(appstore.OwnedAppsInput{Account: account, Page: page, Limit: limit, Platform: platform}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("totalCount", float64(11)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("page", float64(page)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("max_results", float64(limit)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", string(platform)))
|
||||
},
|
||||
Entry("defaults", map[string]any{}, 1, 10, appstore.Platform("")),
|
||||
Entry("explicit values", map[string]any{"page": 2, "max_results": 5, "platform": "macos"}, 2, 5, appstore.PlatformMacOS),
|
||||
)
|
||||
|
||||
It("resolves bundle identifiers and lists versions", func() {
|
||||
var lookup appstore.LookupInput
|
||||
var input appstore.ListVersionsInput
|
||||
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: app}, nil
|
||||
}
|
||||
store.listVersions = func(in appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"100", "200"}, LatestExternalVersionID: "200"}, nil
|
||||
}
|
||||
result := call("list_app_versions", map[string]any{"app_id": 999, "bundle_identifier": app.BundleID, "platform": "ipados"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, BundleID: app.BundleID, Platform: appstore.PlatformIPad}))
|
||||
Expect(input.App).To(Equal(app))
|
||||
Expect(input.Context).NotTo(BeNil())
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("externalVersionIdentifiers", []any{"100", "200"}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(app.ID)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", "ipad"))
|
||||
})
|
||||
|
||||
It("resolves a bundle identifier and returns metadata for the requested version", func() {
|
||||
var lookup appstore.LookupInput
|
||||
var input appstore.GetVersionMetadataInput
|
||||
|
||||
app.Version = "2.0"
|
||||
releasedAt := time.Date(2025, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: app}, nil
|
||||
}
|
||||
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3", ReleaseDate: releasedAt}, nil
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 999, "bundle_identifier": app.BundleID, "external_version_id": "200", "platform": "ipados"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, BundleID: app.BundleID, Platform: appstore.PlatformIPad}))
|
||||
Expect(input.Context).NotTo(BeNil())
|
||||
Expect(input.Account).To(Equal(account))
|
||||
Expect(input.App).To(Equal(app))
|
||||
Expect(input.VersionID).To(Equal("200"))
|
||||
Expect(input.Platform).To(Equal(appstore.PlatformIPad))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(app.ID)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("platform", "ipad"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("external_version_id", "200"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("displayVersion", "1.2.3"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("releaseDate", releasedAt.Format(time.RFC3339)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("success", true))
|
||||
Expect(result.StructuredContent.(map[string]any)["app"]).To(HaveKeyWithValue("version", "2.0"))
|
||||
data, err := json.Marshal(result.StructuredContent)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(MatchJSON(string(data)))
|
||||
})
|
||||
|
||||
DescribeTable("retrieves version metadata by app ID when catalog metadata is unavailable", func(platform string, expected appstore.Platform) {
|
||||
var input appstore.GetVersionMetadataInput
|
||||
|
||||
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3"}, nil
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200", "platform": platform})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input.App).To(Equal(appstore.App{ID: 123}))
|
||||
Expect(input.VersionID).To(Equal("200"))
|
||||
Expect(input.Platform).To(Equal(expected))
|
||||
},
|
||||
Entry("CLI default", "", appstore.Platform("")),
|
||||
Entry("iOS alias", "ios", appstore.PlatformIPhone),
|
||||
Entry("macOS", "macos", appstore.PlatformMacOS),
|
||||
)
|
||||
|
||||
It("returns bundle lookup failures as metadata tool errors", func() {
|
||||
result := call("get_version_metadata", map[string]any{"bundle_identifier": app.BundleID, "external_version_id": "200"})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(appstore.ErrAppNotFound.Error()))
|
||||
})
|
||||
|
||||
DescribeTable("returns metadata failures as tool errors without acquiring a license", func(metadataErr error) {
|
||||
store.getVersionMetadata = func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, appstore.NewErrorWithMetadata(metadataErr, account)
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring(metadataErr.Error()))
|
||||
data, err := json.Marshal(result)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
},
|
||||
Entry("missing license", appstore.ErrLicenseRequired),
|
||||
Entry("metadata unavailable", errors.New("metadata unavailable")),
|
||||
)
|
||||
|
||||
It("refreshes an expired session when retrieving version metadata", func() {
|
||||
var login appstore.LoginInput
|
||||
var accounts []appstore.Account
|
||||
|
||||
refreshed := appstore.Account{PasswordToken: "refreshed-private-token"}
|
||||
store.getVersionMetadata = func(in appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
accounts = append(accounts, in.Account)
|
||||
if len(accounts) == 1 {
|
||||
return appstore.GetVersionMetadataOutput{}, appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
return appstore.GetVersionMetadataOutput{DisplayVersion: "1.2.3"}, nil
|
||||
}
|
||||
store.login = func(in appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
login = in
|
||||
|
||||
return appstore.LoginOutput{Account: refreshed}, nil
|
||||
}
|
||||
result := call("get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(login).To(Equal(appstore.LoginInput{Email: account.Email, Password: account.Password}))
|
||||
Expect(accounts).To(Equal([]appstore.Account{account, refreshed}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("displayVersion", "1.2.3"))
|
||||
})
|
||||
|
||||
DescribeTable("purchases a free license", func(purchaseErr error, alreadyOwned bool) {
|
||||
var input appstore.PurchaseInput
|
||||
|
||||
store.purchase = func(in appstore.PurchaseInput) error {
|
||||
input = in
|
||||
|
||||
return purchaseErr
|
||||
}
|
||||
result := call("purchase_app", map[string]any{"app_id": 123, "platform": "visionos"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input).To(Equal(appstore.PurchaseInput{Account: account, App: appstore.App{ID: 123}, Platform: appstore.PlatformVisionOS}))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("alreadyOwned", alreadyOwned))
|
||||
},
|
||||
Entry("new license", nil, false),
|
||||
Entry("existing license", appstore.ErrLicenseAlreadyExists, true),
|
||||
)
|
||||
|
||||
It("downloads a selected version and finalizes the package without a progress bar", func() {
|
||||
var input appstore.DownloadInput
|
||||
var sinfInput appstore.ReplicateSinfInput
|
||||
|
||||
store.download = func(in appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(in appstore.ReplicateSinfInput) error {
|
||||
sinfInput = in
|
||||
|
||||
return nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "output": "/tmp/example.ipa", "external_version_id": "200", "platform": "ios"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input.App.ID).To(Equal(int64(123)))
|
||||
Expect(input.OutputPath).To(Equal("/tmp/example.ipa"))
|
||||
Expect(input.ExternalVersionID).To(Equal("200"))
|
||||
Expect(input.Platform).To(Equal(appstore.PlatformIPhone))
|
||||
Expect(input.Context).NotTo(BeNil())
|
||||
Expect(input.Progress).To(BeNil())
|
||||
Expect(sinfInput.PackagePath).To(Equal(input.OutputPath))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("output", input.OutputPath))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("external_version_id", "200"))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("purchase", false))
|
||||
})
|
||||
|
||||
It("downloads delisted macOS apps by ID without attempting IPA finalization", func() {
|
||||
var input appstore.DownloadInput
|
||||
|
||||
store.lookup = func(appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return appstore.LookupOutput{}, appstore.ErrAppNotFound
|
||||
}
|
||||
store.download = func(in appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
input = in
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "bundle_identifier": app.BundleID, "platform": "macos"})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(input.App.ID).To(Equal(int64(123)))
|
||||
})
|
||||
|
||||
DescribeTable("only acquires a license during download when requested", func(purchase bool) {
|
||||
downloads, purchases := 0, 0
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
downloads++
|
||||
if downloads == 1 {
|
||||
return appstore.DownloadOutput{}, appstore.ErrLicenseRequired
|
||||
}
|
||||
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.pkg"}, nil
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error {
|
||||
purchases++
|
||||
|
||||
return nil
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123, "platform": "macos", "purchase": purchase})
|
||||
Expect(result.IsError).To(Equal(!purchase))
|
||||
if purchase {
|
||||
Expect(purchases).To(Equal(1))
|
||||
Expect(downloads).To(Equal(2))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("purchased", true))
|
||||
} else {
|
||||
Expect(purchases).To(BeZero())
|
||||
Expect(downloads).To(Equal(1))
|
||||
}
|
||||
}, Entry("explicit opt in", true), Entry("no opt in", false))
|
||||
|
||||
It("refreshes an expired session using saved credentials", func() {
|
||||
var login appstore.LoginInput
|
||||
var accounts []appstore.Account
|
||||
|
||||
refreshed := appstore.Account{PasswordToken: "refreshed-private-token"}
|
||||
store.purchase = func(in appstore.PurchaseInput) error {
|
||||
accounts = append(accounts, in.Account)
|
||||
if len(accounts) == 1 {
|
||||
return appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
store.login = func(in appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
login = in
|
||||
|
||||
return appstore.LoginOutput{Account: refreshed}, nil
|
||||
}
|
||||
Expect(call("purchase_app", map[string]any{"app_id": 123}).IsError).To(BeFalse())
|
||||
Expect(login).To(Equal(appstore.LoginInput{Email: account.Email, Password: account.Password}))
|
||||
Expect(accounts).To(Equal([]appstore.Account{account, refreshed}))
|
||||
})
|
||||
|
||||
It("reports two-factor requirements as tool errors without requesting credentials", func() {
|
||||
store.purchase = func(appstore.PurchaseInput) error {
|
||||
return appstore.ErrPasswordTokenExpired
|
||||
}
|
||||
store.login = func(appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
return appstore.LoginOutput{}, appstore.ErrAuthCodeRequired
|
||||
}
|
||||
result := call("purchase_app", map[string]any{"app_id": 123})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("ipatool auth login"))
|
||||
})
|
||||
|
||||
It("does not expose App Store error metadata", func() {
|
||||
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{}, appstore.NewErrorWithMetadata(errors.New("request failed"), account)
|
||||
}
|
||||
result := call("search_apps", map[string]any{"term": "example"})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
data, err := json.Marshal(result)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(string(data)).To(ContainSubstring("request failed"))
|
||||
Expect(string(data)).NotTo(ContainSubstring("private-"))
|
||||
})
|
||||
|
||||
It("reports package finalization failures as tool errors", func() {
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(appstore.ReplicateSinfInput) error {
|
||||
return errors.New("finalization failed")
|
||||
}
|
||||
result := call("download_app", map[string]any{"app_id": 123})
|
||||
Expect(result.IsError).To(BeTrue())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(ContainSubstring("finalization failed"))
|
||||
})
|
||||
|
||||
DescribeTable("returns every parameter and app field even when metadata is unavailable", func(name string, args map[string]any, expectedKeys []string) {
|
||||
partial := appstore.App{ID: 123}
|
||||
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{Count: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
store.ownedApps = func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 1, Page: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
store.listVersions = func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{ExternalVersionIdentifiers: []string{"200"}}, nil
|
||||
}
|
||||
store.getVersionMetadata = func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return appstore.GetVersionMetadataOutput{}, nil
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error { return nil }
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(appstore.ReplicateSinfInput) error { return nil }
|
||||
result := call(name, args)
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
output := result.StructuredContent.(map[string]any)
|
||||
for _, key := range expectedKeys {
|
||||
Expect(output).To(HaveKey(key))
|
||||
}
|
||||
|
||||
metadata := output["app"]
|
||||
if metadata == nil {
|
||||
metadata = output["apps"].([]any)[0]
|
||||
}
|
||||
Expect(metadata).To(Equal(map[string]any{
|
||||
"trackId": float64(123), "bundleId": "", "trackName": "", "version": "",
|
||||
"price": float64(0), "purchaseDate": nil, "platforms": []any{},
|
||||
}))
|
||||
textJSON, err := json.Marshal(result.StructuredContent)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(result.Content[0].(*mcp.TextContent).Text).To(MatchJSON(string(textJSON)))
|
||||
},
|
||||
Entry("search", "search_apps", map[string]any{"term": "example"}, []string{"term", "limit", "platform", "count", "apps"}),
|
||||
Entry("purchases", "list_purchases", map[string]any{}, []string{"page", "max_results", "platform", "count", "totalCount", "apps"}),
|
||||
Entry("versions", "list_app_versions", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "bundleID", "app", "externalVersionIdentifiers", "latestExternalVersionID", "success"}),
|
||||
Entry("version metadata", "get_version_metadata", map[string]any{"app_id": 123, "external_version_id": "200"}, []string{"app_id", "bundle_identifier", "platform", "app", "external_version_id", "displayVersion", "releaseDate", "success"}),
|
||||
Entry("purchase", "purchase_app", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "app", "alreadyOwned", "success"}),
|
||||
Entry("download", "download_app", map[string]any{"app_id": 123}, []string{"app_id", "bundle_identifier", "platform", "app", "output", "external_version_id", "purchase", "purchased", "success"}),
|
||||
)
|
||||
|
||||
DescribeTable("fills missing bundle identifiers in app lists without losing purchase metadata", func(name string, args map[string]any) {
|
||||
purchasedAt := time.Date(2025, time.January, 2, 3, 4, 5, 0, time.UTC)
|
||||
partial := appstore.App{ID: 123, Name: "Original name", PurchaseDate: purchasedAt, Platforms: []appstore.Platform{appstore.PlatformMacOS}}
|
||||
var lookup appstore.LookupInput
|
||||
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: appstore.App{ID: 123, BundleID: app.BundleID, Name: "Catalog name", Version: "2.0", Price: 4.99}}, nil
|
||||
}
|
||||
store.search = func(appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return appstore.SearchOutput{Count: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
store.ownedApps = func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return appstore.OwnedAppsOutput{Count: 1, TotalCount: 1, Page: 1, Results: []appstore.App{partial}}, nil
|
||||
}
|
||||
result := call(name, args)
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup).To(Equal(appstore.LookupInput{Account: account, AppID: 123, Platform: appstore.PlatformMacOS}))
|
||||
metadata := result.StructuredContent.(map[string]any)["apps"].([]any)[0]
|
||||
Expect(metadata).To(Equal(map[string]any{
|
||||
"trackId": float64(123), "bundleId": app.BundleID, "trackName": "Original name", "version": "2.0",
|
||||
"price": 4.99, "purchaseDate": purchasedAt.Format(time.RFC3339), "platforms": []any{"macos"},
|
||||
}))
|
||||
},
|
||||
Entry("search", "search_apps", map[string]any{"term": "example"}),
|
||||
Entry("purchases", "list_purchases", map[string]any{}),
|
||||
)
|
||||
|
||||
DescribeTable("resolves bundle identifiers for numeric app IDs", func(name string) {
|
||||
var lookup appstore.LookupInput
|
||||
|
||||
store.lookup = func(in appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
lookup = in
|
||||
|
||||
return appstore.LookupOutput{App: app}, nil
|
||||
}
|
||||
store.purchase = func(appstore.PurchaseInput) error { return nil }
|
||||
store.listVersions = func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return appstore.ListVersionsOutput{}, nil
|
||||
}
|
||||
store.download = func(appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return appstore.DownloadOutput{DestinationPath: "/tmp/example.ipa"}, nil
|
||||
}
|
||||
store.replicateSinf = func(appstore.ReplicateSinfInput) error { return nil }
|
||||
result := call(name, map[string]any{"app_id": 123})
|
||||
Expect(result.IsError).To(BeFalse())
|
||||
Expect(lookup.AppID).To(Equal(int64(123)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("app_id", float64(123)))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundle_identifier", app.BundleID))
|
||||
Expect(result.StructuredContent.(map[string]any)["app"]).To(HaveKeyWithValue("bundleId", app.BundleID))
|
||||
if name == "list_app_versions" {
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("bundleID", app.BundleID))
|
||||
Expect(result.StructuredContent).To(HaveKeyWithValue("externalVersionIdentifiers", []any{}))
|
||||
}
|
||||
}, Entry("purchase", "purchase_app"), Entry("download", "download_app"), Entry("versions", "list_app_versions"))
|
||||
})
|
||||
|
||||
type fakeMCPAppStore struct {
|
||||
appstore.AppStore
|
||||
accountInfo func() (appstore.AccountInfoOutput, error)
|
||||
search func(appstore.SearchInput) (appstore.SearchOutput, error)
|
||||
lookup func(appstore.LookupInput) (appstore.LookupOutput, error)
|
||||
ownedApps func(appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error)
|
||||
listVersions func(appstore.ListVersionsInput) (appstore.ListVersionsOutput, error)
|
||||
getVersionMetadata func(appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error)
|
||||
purchase func(appstore.PurchaseInput) error
|
||||
download func(appstore.DownloadInput) (appstore.DownloadOutput, error)
|
||||
replicateSinf func(appstore.ReplicateSinfInput) error
|
||||
login func(appstore.LoginInput) (appstore.LoginOutput, error)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
|
||||
return s.accountInfo()
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Search(input appstore.SearchInput) (appstore.SearchOutput, error) {
|
||||
return s.search(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
|
||||
return s.lookup(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) OwnedApps(input appstore.OwnedAppsInput) (appstore.OwnedAppsOutput, error) {
|
||||
return s.ownedApps(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) ListVersions(input appstore.ListVersionsInput) (appstore.ListVersionsOutput, error) {
|
||||
return s.listVersions(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) GetVersionMetadata(input appstore.GetVersionMetadataInput) (appstore.GetVersionMetadataOutput, error) {
|
||||
return s.getVersionMetadata(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Purchase(input appstore.PurchaseInput) error {
|
||||
return s.purchase(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Download(input appstore.DownloadInput) (appstore.DownloadOutput, error) {
|
||||
return s.download(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) ReplicateSinf(input appstore.ReplicateSinfInput) error {
|
||||
return s.replicateSinf(input)
|
||||
}
|
||||
|
||||
func (s *fakeMCPAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
|
||||
return s.login(input)
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
)
|
||||
|
||||
type mcpSearchInput struct {
|
||||
Term string `json:"term" jsonschema:"Search term"`
|
||||
Limit *int64 `json:"limit,omitempty" jsonschema:"Maximum results; defaults to 5. visionOS supports up to 12."`
|
||||
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), watchos, visionos, or macos; defaults to iOS and iPadOS"`
|
||||
}
|
||||
|
||||
type mcpSearchOutput struct {
|
||||
Term string `json:"term"`
|
||||
Limit int64 `json:"limit"`
|
||||
Platform appstore.Platform `json:"platform"`
|
||||
Count int `json:"count"`
|
||||
Apps []mcpApp `json:"apps"`
|
||||
}
|
||||
|
||||
type mcpAppInput struct {
|
||||
AppID int64 `json:"app_id,omitempty" jsonschema:"Numeric app ID; required unless bundle_identifier is provided"`
|
||||
BundleID string `json:"bundle_identifier,omitempty" jsonschema:"Bundle identifier; overrides app_id when found"`
|
||||
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), watchos, visionos, or macos; uses the CLI default when omitted"`
|
||||
}
|
||||
|
||||
type mcpDownloadInput struct {
|
||||
mcpAppInput
|
||||
Output string `json:"output,omitempty" jsonschema:"Destination file or directory; defaults to the server's working directory"`
|
||||
ExternalVersionID string `json:"external_version_id,omitempty" jsonschema:"External version identifier; defaults to the latest version"`
|
||||
Purchase bool `json:"purchase,omitempty" jsonschema:"Acquire a free license if needed; defaults to false"`
|
||||
}
|
||||
|
||||
type mcpDownloadOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
Output string `json:"output"`
|
||||
ExternalVersionID string `json:"external_version_id"`
|
||||
Purchase bool `json:"purchase"`
|
||||
Purchased bool `json:"purchased"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type mcpVersionsOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
ExternalVersionIdentifiers []string `json:"externalVersionIdentifiers"`
|
||||
LatestExternalVersionID string `json:"latestExternalVersionID"`
|
||||
BundleID string `json:"bundleID"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type mcpVersionMetadataInput struct {
|
||||
mcpAppInput
|
||||
ExternalVersionID string `json:"external_version_id" jsonschema:"External version identifier of the target app (required)"`
|
||||
}
|
||||
|
||||
type mcpVersionMetadataOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
ExternalVersionID string `json:"external_version_id"`
|
||||
DisplayVersion string `json:"displayVersion" jsonschema:"Display version of the requested external version identifier"`
|
||||
ReleaseDate time.Time `json:"releaseDate"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
type mcpPurchasesInput struct {
|
||||
Page *int `json:"page,omitempty" jsonschema:"Page number starting at 1; defaults to 1"`
|
||||
MaxResults *int `json:"max_results,omitempty" jsonschema:"Apps per page from 1 to 100; defaults to 10"`
|
||||
Platform string `json:"platform,omitempty" jsonschema:"iphone (ios), ipad (ipados), appletv (tvos), visionos, or macos; defaults to all platforms"`
|
||||
}
|
||||
|
||||
type mcpPurchasesOutput struct {
|
||||
Count int `json:"count"`
|
||||
TotalCount int `json:"totalCount"`
|
||||
Page int `json:"page"`
|
||||
MaxResults int `json:"max_results"`
|
||||
Platform appstore.Platform `json:"platform"`
|
||||
Apps []mcpApp `json:"apps"`
|
||||
}
|
||||
|
||||
type mcpPurchaseOutput struct {
|
||||
mcpAppParameters
|
||||
App mcpApp `json:"app"`
|
||||
AlreadyOwned bool `json:"alreadyOwned"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// withMCPAccount refreshes expired tokens using the saved credentials, as the CLI does.
|
||||
// Authentication and account details are never included in tool results.
|
||||
func withMCPAccount[Out any](ctx context.Context, store appstore.AppStore, operation func(appstore.Account) (Out, error)) (Out, error) {
|
||||
var zero Out
|
||||
|
||||
info, err := store.AccountInfo()
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("account unavailable; run 'ipatool auth login' before using MCP: %w", err)
|
||||
}
|
||||
|
||||
output, err := operation(info.Account)
|
||||
if !errors.Is(err, appstore.ErrPasswordTokenExpired) {
|
||||
return output, err
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return zero, fmt.Errorf("tool call canceled: %w", err)
|
||||
}
|
||||
|
||||
login, err := store.Login(appstore.LoginInput{Email: info.Account.Email, Password: info.Account.Password})
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("session refresh failed; run 'ipatool auth login' outside MCP: %w", err)
|
||||
}
|
||||
|
||||
output, err = operation(login.Account)
|
||||
if err != nil {
|
||||
return zero, fmt.Errorf("operation failed after session refresh: %w", err)
|
||||
}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) search(ctx context.Context, input mcpSearchInput) (mcpSearchOutput, error) {
|
||||
if strings.TrimSpace(input.Term) == "" {
|
||||
return mcpSearchOutput{}, errors.New("search term must not be empty")
|
||||
}
|
||||
|
||||
limit := int64(5)
|
||||
if input.Limit != nil {
|
||||
limit = *input.Limit
|
||||
}
|
||||
|
||||
if limit < 1 {
|
||||
return mcpSearchOutput{}, errors.New("limit must be greater than 0")
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(input.Platform)
|
||||
if err != nil {
|
||||
return mcpSearchOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpSearchOutput, error) {
|
||||
out, err := t.store.Search(appstore.SearchInput{Account: acc, Term: input.Term, Limit: limit, Platform: platform})
|
||||
if err != nil {
|
||||
return mcpSearchOutput{}, err
|
||||
}
|
||||
|
||||
return mcpSearchOutput{
|
||||
Term: input.Term, Limit: limit, Platform: platform,
|
||||
Count: out.Count, Apps: t.appResults(acc, out.Results, platform),
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (input mcpAppInput) validate() (appstore.Platform, error) {
|
||||
if input.AppID < 0 || (input.AppID == 0 && strings.TrimSpace(input.BundleID) == "") {
|
||||
return "", errors.New("a positive app ID or a bundle identifier must be specified")
|
||||
}
|
||||
|
||||
return appstore.ParsePlatform(input.Platform)
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) resolveApp(acc appstore.Account, input mcpAppInput, platform appstore.Platform, allowDelisted bool) (appstore.App, error) {
|
||||
app := appstore.App{ID: input.AppID, BundleID: input.BundleID}
|
||||
if input.BundleID == "" {
|
||||
return t.completeApp(acc, app, platform), nil
|
||||
}
|
||||
|
||||
out, err := t.store.Lookup(appstore.LookupInput{Account: acc, BundleID: input.BundleID, Platform: platform})
|
||||
if allowDelisted && input.AppID > 0 && errors.Is(err, appstore.ErrAppNotFound) {
|
||||
return app, nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return appstore.App{}, err
|
||||
}
|
||||
|
||||
// Preserve a known bundle identifier even if the catalog omits it.
|
||||
if out.App.BundleID == "" {
|
||||
out.App.BundleID = input.BundleID
|
||||
}
|
||||
|
||||
return out.App, nil
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) download(ctx context.Context, input mcpDownloadInput) (mcpDownloadOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
purchased := false
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpDownloadOutput, error) {
|
||||
app, err := t.resolveApp(acc, input.mcpAppInput, platform, true)
|
||||
if err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
downloadInput := appstore.DownloadInput{
|
||||
Context: ctx, Account: acc, App: app, OutputPath: input.Output,
|
||||
ExternalVersionID: input.ExternalVersionID, Platform: platform,
|
||||
}
|
||||
|
||||
out, err := t.store.Download(downloadInput)
|
||||
if errors.Is(err, appstore.ErrLicenseRequired) && input.Purchase && !purchased {
|
||||
err = t.store.Purchase(appstore.PurchaseInput{Account: acc, App: app, Platform: platform})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
purchased = true
|
||||
out, err = t.store.Download(downloadInput)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
if err := replicateDownloadSinf(t.store, platform, out); err != nil {
|
||||
return mcpDownloadOutput{}, err
|
||||
}
|
||||
|
||||
return mcpDownloadOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
Output: out.DestinationPath, ExternalVersionID: input.ExternalVersionID,
|
||||
Purchase: input.Purchase, Purchased: purchased, Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) listVersions(ctx context.Context, input mcpAppInput) (mcpVersionsOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpVersionsOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpVersionsOutput, error) {
|
||||
app, err := t.resolveApp(acc, input, platform, false)
|
||||
if err != nil {
|
||||
return mcpVersionsOutput{}, err
|
||||
}
|
||||
|
||||
out, err := t.store.ListVersions(appstore.ListVersionsInput{Context: ctx, Account: acc, App: app, Platform: platform})
|
||||
if err != nil {
|
||||
return mcpVersionsOutput{}, err
|
||||
}
|
||||
|
||||
return mcpVersionsOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
ExternalVersionIdentifiers: append([]string{}, out.ExternalVersionIdentifiers...),
|
||||
LatestExternalVersionID: out.LatestExternalVersionID, BundleID: app.BundleID, Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) getVersionMetadata(ctx context.Context, input mcpVersionMetadataInput) (mcpVersionMetadataOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
if strings.TrimSpace(input.ExternalVersionID) == "" {
|
||||
return mcpVersionMetadataOutput{}, errors.New("external version identifier must not be empty")
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpVersionMetadataOutput, error) {
|
||||
app, err := t.resolveApp(acc, input.mcpAppInput, platform, false)
|
||||
if err != nil {
|
||||
return mcpVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
out, err := t.store.GetVersionMetadata(appstore.GetVersionMetadataInput{
|
||||
Context: ctx, Account: acc, App: app, VersionID: input.ExternalVersionID, Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return mcpVersionMetadataOutput{}, err
|
||||
}
|
||||
|
||||
return mcpVersionMetadataOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
ExternalVersionID: input.ExternalVersionID, DisplayVersion: out.DisplayVersion,
|
||||
ReleaseDate: out.ReleaseDate, Success: true,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) listPurchases(ctx context.Context, input mcpPurchasesInput) (mcpPurchasesOutput, error) {
|
||||
page, limit := 1, appstore.DefaultOwnedAppsLimit
|
||||
if input.Page != nil {
|
||||
page = *input.Page
|
||||
}
|
||||
|
||||
if input.MaxResults != nil {
|
||||
limit = *input.MaxResults
|
||||
}
|
||||
|
||||
if page < 1 {
|
||||
return mcpPurchasesOutput{}, errors.New("page must be greater than 0")
|
||||
}
|
||||
|
||||
if limit < 1 || limit > appstore.MaxOwnedAppsLimit {
|
||||
return mcpPurchasesOutput{}, fmt.Errorf("max results must be between 1 and %d", appstore.MaxOwnedAppsLimit)
|
||||
}
|
||||
|
||||
platform, err := appstore.ParsePlatform(input.Platform)
|
||||
if err != nil {
|
||||
return mcpPurchasesOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpPurchasesOutput, error) {
|
||||
out, err := t.store.OwnedApps(appstore.OwnedAppsInput{Account: acc, Page: page, Limit: limit, Platform: platform})
|
||||
if err != nil {
|
||||
return mcpPurchasesOutput{}, err
|
||||
}
|
||||
|
||||
return mcpPurchasesOutput{
|
||||
Count: out.Count, TotalCount: out.TotalCount, Page: out.Page, MaxResults: limit, Platform: platform,
|
||||
Apps: t.appResults(acc, out.Results, platform),
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:wrapcheck
|
||||
func (t *mcpTools) purchase(ctx context.Context, input mcpAppInput) (mcpPurchaseOutput, error) {
|
||||
platform, err := input.validate()
|
||||
if err != nil {
|
||||
return mcpPurchaseOutput{}, err
|
||||
}
|
||||
|
||||
return withMCPAccount(ctx, t.store, func(acc appstore.Account) (mcpPurchaseOutput, error) {
|
||||
app, err := t.resolveApp(acc, input, platform, false)
|
||||
if err != nil {
|
||||
return mcpPurchaseOutput{}, err
|
||||
}
|
||||
|
||||
err = t.store.Purchase(appstore.PurchaseInput{Account: acc, App: app, Platform: platform})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return mcpPurchaseOutput{}, err
|
||||
}
|
||||
|
||||
return mcpPurchaseOutput{
|
||||
mcpAppParameters: appParameters(app, platform), App: newMCPApp(app),
|
||||
AlreadyOwned: errors.Is(err, appstore.ErrLicenseAlreadyExists), Success: true,
|
||||
}, 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), watchos, 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
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
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",
|
||||
Args: cobra.NoArgs,
|
||||
PreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
if page < 1 {
|
||||
return errors.New("page must be greater than 0")
|
||||
}
|
||||
if maxResults < 1 {
|
||||
return errors.New("max results must be greater than 0")
|
||||
}
|
||||
if maxResults > appstore.MaxOwnedAppsLimit {
|
||||
return fmt.Errorf("max results must not exceed %d", appstore.MaxOwnedAppsLimit)
|
||||
}
|
||||
|
||||
var err error
|
||||
platform, err = appstore.ParsePlatform(platformValue)
|
||||
|
||||
return err
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
var lastErr error
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc := infoResult.Account
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
output, err := dependencies.AppStore.OwnedApps(appstore.OwnedAppsInput{
|
||||
Account: acc,
|
||||
Page: page,
|
||||
Limit: maxResults,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Int("count", output.Count).
|
||||
Int("totalCount", output.TotalCount).
|
||||
Int("page", output.Page).
|
||||
Array("apps", appstore.Apps(output.Results)).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
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()
|
||||
|
||||
page, err := cmd.Flags().GetInt("page")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(page).To(Equal(1))
|
||||
|
||||
maxResults, err := cmd.Flags().GetInt("max-results")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(maxResults).To(Equal(appstore.DefaultOwnedAppsLimit))
|
||||
})
|
||||
|
||||
DescribeTable("rejects invalid pagination",
|
||||
func(flag, value, errorText string) {
|
||||
cmd := listPurchasesCmd()
|
||||
Expect(cmd.Flags().Set(flag, value)).To(Succeed())
|
||||
|
||||
err := cmd.PreRunE(cmd, nil)
|
||||
Expect(err).To(MatchError(ContainSubstring(errorText)))
|
||||
},
|
||||
Entry("page below one", "page", "0", "page"),
|
||||
Entry("max results below one", "max-results", "0", "max results"),
|
||||
Entry("max results over limit", "max-results", "101", "100"),
|
||||
)
|
||||
|
||||
It("is registered on the root command", func() {
|
||||
cmd, _, err := rootCmd().Find([]string{"list-purchases"})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
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
|
||||
}
|
||||
@@ -47,10 +47,12 @@ func rootCmd() *cobra.Command {
|
||||
|
||||
cmd.AddCommand(authCmd())
|
||||
cmd.AddCommand(downloadCmd())
|
||||
cmd.AddCommand(listPurchasesCmd())
|
||||
cmd.AddCommand(purchaseCmd())
|
||||
cmd.AddCommand(searchCmd())
|
||||
cmd.AddCommand(ListVersionsCmd())
|
||||
cmd.AddCommand(getVersionMetadataCmd())
|
||||
cmd.AddCommand(mcpCmd())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
+3
-3
@@ -14,7 +14,7 @@ func searchCmd() *cobra.Command {
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "search <term>",
|
||||
Short: "Search for iOS and tvOS apps available on the App Store",
|
||||
Short: "Search for iOS, iPadOS, tvOS, watchOS, 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()
|
||||
@@ -46,8 +46,8 @@ func searchCmd() *cobra.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&limit, "limit", "l", 5, "maximum amount of search results to retrieve")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone, ipad, or appletv")
|
||||
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), watchos, 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,10 +6,12 @@ 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
|
||||
github.com/klauspost/compress v1.18.6
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0
|
||||
github.com/onsi/ginkgo/v2 v2.5.0
|
||||
github.com/onsi/gomega v1.24.0
|
||||
github.com/rs/zerolog v1.28.0
|
||||
@@ -17,6 +19,7 @@ require (
|
||||
github.com/spf13/cobra v1.6.1
|
||||
github.com/thediveo/enumflag/v2 v2.0.1
|
||||
go.uber.org/mock v0.4.0
|
||||
golang.org/x/sys v0.45.0
|
||||
golang.org/x/term v0.43.0
|
||||
howett.net/plist v1.0.0
|
||||
howett.net/ranger v0.0.0-20171016084633-e2e137620847
|
||||
@@ -29,7 +32,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
|
||||
@@ -40,6 +42,7 @@ require (
|
||||
github.com/gobwas/glob v0.2.3 // indirect
|
||||
github.com/godbus/dbus/v5 v5.2.2 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/jsonschema-go v0.4.3 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.1 // indirect
|
||||
@@ -53,6 +56,8 @@ require (
|
||||
github.com/pierrec/lz4/v4 v4.1.26 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/segmentio/asm v1.1.3 // indirect
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/stangelandcl/ppmd v0.1.0 // indirect
|
||||
@@ -61,6 +66,7 @@ require (
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible // indirect
|
||||
github.com/ulikunitz/xz v0.5.15 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f // indirect
|
||||
@@ -68,9 +74,10 @@ require (
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
|
||||
golang.org/x/mod v0.35.0 // indirect
|
||||
golang.org/x/net v0.55.0 // indirect
|
||||
golang.org/x/oauth2 v0.35.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.45.0 // indirect
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
golang.org/x/tools v0.44.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/errgo.v1 v1.0.1 // indirect
|
||||
|
||||
@@ -50,11 +50,15 @@ github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJA
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
|
||||
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
|
||||
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
@@ -87,6 +91,8 @@ github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWV
|
||||
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/noamcohen97/touchid-go v0.3.0 h1:fcXxVCizysD7KHRR6hrURt3nyNIs5JBGSbOIidD/3wo=
|
||||
@@ -113,6 +119,10 @@ github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6us
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/schollz/progressbar/v3 v3.13.1 h1:o8rySDYiQ59Mwzy2FELeHY5ZARXZTVJC7iHD6PEFUiE=
|
||||
github.com/schollz/progressbar/v3 v3.13.1/go.mod h1:xvrbki8kfT1fzWzBT/UZd9L6GA+jdL7HAgq2RFnO6fQ=
|
||||
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
|
||||
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
|
||||
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
|
||||
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
||||
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
@@ -148,6 +158,8 @@ github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
|
||||
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
@@ -164,6 +176,8 @@ golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
|
||||
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
|
||||
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
@@ -177,6 +191,8 @@ golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
|
||||
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
|
||||
@@ -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"))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
)
|
||||
|
||||
// GenerateKBSync creates the account and hardware bound FairPlay data required
|
||||
// by the bag's ent/download endpoint, without opening a decryption session.
|
||||
func GenerateKBSync(ctx context.Context, bundle assets.Bundle, hardwareID []byte, dsid uint64) ([]byte, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("StoreAgent context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("generate kbsync: %w", err)
|
||||
}
|
||||
|
||||
if dsid == 0 {
|
||||
return nil, errors.New("kbsync requires a nonzero account DSID")
|
||||
}
|
||||
|
||||
image, err := assets.LoadStoreAgent(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load Apple StoreAgent asset: %w", err)
|
||||
}
|
||||
|
||||
agent, globalContext, err := openStoreAgentGlobal(ctx, bundle, image, hardwareID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer agent.Close()
|
||||
|
||||
return agent.guest.generateKBSync(storeAgentKBSyncEntry, globalContext, dsid)
|
||||
}
|
||||
|
||||
func (m *Machine) generateKBSync(entry uint64, globalContext uint32, dsid uint64) ([]byte, error) {
|
||||
m.beginCall()
|
||||
defer m.clearScratch()
|
||||
|
||||
pointerField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// StoreAgent writes a uint32 length. Zero the upper half so consumeOutput
|
||||
// can share the SAP buffer bounds checking and storage disposal.
|
||||
lengthField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
status, err := m.invoke(entry, uint64(globalContext), dsid, 0, 1, pointerField, lengthField)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate StoreAgent kbsync: %w", err)
|
||||
}
|
||||
|
||||
output, outputErr := m.consumeOutput(pointerField, lengthField)
|
||||
if int32(status) != 0 {
|
||||
return nil, errors.Join(fmt.Errorf("StoreAgent kbsync returned %d", int32(status)), outputErr)
|
||||
}
|
||||
|
||||
if outputErr != nil {
|
||||
return nil, outputErr
|
||||
}
|
||||
|
||||
if len(output) == 0 {
|
||||
return nil, errors.New("StoreAgent kbsync returned an empty buffer")
|
||||
}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("StoreAgent kbsync", func() {
|
||||
It("pins the kbsync entry in the verified StoreAgent image", func() {
|
||||
Expect(storeAgentKBSyncEntry).To(Equal(storeAgentBase + 0x0c93c0))
|
||||
})
|
||||
|
||||
It("rejects a canceled context before loading assets", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := GenerateKBSync(ctx, assets.Bundle{}, []byte{1}, 123)
|
||||
Expect(err).To(MatchError(ContainSubstring(context.Canceled.Error())))
|
||||
})
|
||||
|
||||
It("rejects missing context or account identity before loading assets", func() {
|
||||
var missingContext context.Context
|
||||
_, err := GenerateKBSync(missingContext, assets.Bundle{}, nil, 123)
|
||||
Expect(err).To(MatchError("StoreAgent context is nil"))
|
||||
_, err = GenerateKBSync(context.Background(), assets.Bundle{}, nil, 0)
|
||||
Expect(err).To(MatchError("kbsync requires a nonzero account DSID"))
|
||||
})
|
||||
|
||||
DescribeTable("copies and disposes guest output with the StoreAgent ABI",
|
||||
func(pointer, length uint64, status uint32, wantError string) {
|
||||
guest := newGinkgoServiceMachine(shimOptions{})
|
||||
data := []byte{0, 4, 0, 1, 42}
|
||||
Expect(guest.engine.MemWrite(heapBase, data)).To(Succeed())
|
||||
var disposed []uint64
|
||||
|
||||
dispose, err := guest.services.addFunction("test.kbsync.dispose", func() error {
|
||||
address, err := guest.services.argument(0)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
disposed = append(disposed, address)
|
||||
|
||||
return guest.services.setResult(0)
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
guest.entry.dispose = dispose
|
||||
|
||||
entry, err := guest.services.addFunction("test.kbsync.generate", func() error {
|
||||
for index, expected := range []uint64{0x1234, 0x123456789abcdef0, 0, 1} {
|
||||
argument, err := guest.services.argument(index)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(argument).To(Equal(expected))
|
||||
}
|
||||
|
||||
pointerField, err := guest.services.argument(4)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(guest.writeUint64(pointerField, pointer)).To(Succeed())
|
||||
lengthField, err := guest.services.argument(5)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
// Only the low 32 bits are written by the real entry point.
|
||||
Expect(guest.engine.MemWrite(lengthField, binary.LittleEndian.AppendUint32(nil, uint32(length)))).To(Succeed())
|
||||
|
||||
return guest.services.setResult(uint64(status))
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
|
||||
output, err := guest.generateKBSync(entry, 0x1234, 0x123456789abcdef0)
|
||||
if wantError == "" {
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(output).To(Equal(data))
|
||||
} else {
|
||||
Expect(err).To(MatchError(ContainSubstring(wantError)))
|
||||
Expect(output).To(BeNil())
|
||||
}
|
||||
|
||||
if pointer != 0 {
|
||||
Expect(disposed).To(Equal([]uint64{pointer}))
|
||||
} else {
|
||||
Expect(disposed).To(BeEmpty())
|
||||
}
|
||||
Expect(guest.scratchCursor).To(BeZero())
|
||||
Expect(guest.engine.MemRead(scratchBase, 32)).To(Equal(make([]byte, 32)))
|
||||
},
|
||||
Entry("valid blob", heapBase, uint64(5), uint32(0), ""),
|
||||
Entry("guest error still releases storage", heapBase, uint64(5), ^uint32(41), "kbsync returned -42"),
|
||||
Entry("oversized blob", heapBase, maxOutputSize+1, uint32(0), "maximum is"),
|
||||
Entry("null pointer", uint64(0), uint64(5), uint32(0), "null output pointer"),
|
||||
Entry("empty blob", heapBase, uint64(0), uint32(0), "empty buffer"),
|
||||
)
|
||||
})
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
)
|
||||
|
||||
const sapGuestTimeout = time.Minute
|
||||
|
||||
const (
|
||||
returnAddress = uint64(0x0000000100000000)
|
||||
coreFPBase = uint64(0x0000100000000000)
|
||||
@@ -54,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}
|
||||
@@ -145,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) {
|
||||
@@ -165,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) {
|
||||
@@ -431,7 +453,10 @@ func (m *Machine) invoke(function uint64, arguments ...uint64) (uint64, error) {
|
||||
|
||||
m.services.resetFault()
|
||||
|
||||
if err := m.engine.StartBounded(function, returnAddress, 10*time.Second, 100_000_000); err != nil {
|
||||
// SAP's cryptographic routines have input- and host-dependent instruction
|
||||
// counts. Bound execution by wall time without rejecting legitimate work on
|
||||
// slower machines for crossing a fixed instruction limit.
|
||||
if err := m.engine.StartBounded(function, returnAddress, sapGuestTimeout, 0); err != nil {
|
||||
if m.services.fault != nil {
|
||||
return 0, m.services.fault
|
||||
}
|
||||
|
||||
@@ -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,340 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
)
|
||||
|
||||
const (
|
||||
storeAgentBase = uint64(0x00001000c0000000)
|
||||
storeAgentGlobalInit = storeAgentBase + 0x0c5fc0
|
||||
storeAgentKBSyncEntry = storeAgentBase + 0x0c93c0
|
||||
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 len(dpInfo) == 0 {
|
||||
return nil, errors.New("StoreAgent dpInfo is empty")
|
||||
}
|
||||
|
||||
agent, globalContext, err := openStoreAgentGlobal(ctx, bundle, image, hardwareID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
agent.session, err = agent.initializeSession(globalContext, dpInfo)
|
||||
if err != nil {
|
||||
_ = agent.Close()
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return agent, nil
|
||||
}
|
||||
|
||||
func openStoreAgentGlobal(ctx context.Context, bundle assets.Bundle, image, hardwareID []byte) (*StoreAgent, uint32, error) {
|
||||
if ctx == nil {
|
||||
return nil, 0, errors.New("StoreAgent context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, 0, fmt.Errorf("open StoreAgent runtime: %w", err)
|
||||
}
|
||||
|
||||
if err := assets.VerifyStoreAgent(image); err != nil {
|
||||
return nil, 0, fmt.Errorf("verify Apple StoreAgent profile: %w", err)
|
||||
}
|
||||
|
||||
hardware, err := hardwareBlock(hardwareID)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
guest, exports, err := openRuntime(ctx, bundle, runtimeOptions{
|
||||
extraImages: []imageSpec{{name: "storeagent", data: image, base: storeAgentBase}},
|
||||
shims: shimOptions{
|
||||
zeroReturnAliases: storeAgentZeroReturnAliases,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("start StoreAgent runtime: %w", err)
|
||||
}
|
||||
|
||||
guest.entry.dispose = exports["_jEHf8Xzsv8K"]
|
||||
|
||||
agent := &StoreAgent{
|
||||
guest: guest,
|
||||
decryptEntry: storeAgentDecryptEntry,
|
||||
closeEntry: storeAgentSessionClose,
|
||||
}
|
||||
|
||||
globalContext, err := agent.initializeGlobal(hardware)
|
||||
if err != nil {
|
||||
_ = agent.Close()
|
||||
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return agent, globalContext, 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
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
const queryTimeout = 4
|
||||
|
||||
const (
|
||||
archX86 = 4
|
||||
mode64 = 8
|
||||
@@ -28,12 +30,16 @@ const (
|
||||
RegR9 = 107
|
||||
)
|
||||
|
||||
var errEngineClosed = errors.New("unicorn engine is closed")
|
||||
var (
|
||||
errTimeout = errors.New("unicorn emulation timed out")
|
||||
errEngineClosed = errors.New("unicorn engine is closed")
|
||||
)
|
||||
|
||||
type api struct {
|
||||
version func(*uint32, *uint32) uint32
|
||||
open func(int32, int32, *uintptr) int32
|
||||
close func(uintptr) int32
|
||||
query func(uintptr, int32, *uint64) int32
|
||||
ctl func(uintptr, uint32, uint32) int32
|
||||
strerror func(int32) string
|
||||
memMap func(uintptr, uint64, uint64, uint32) int32
|
||||
@@ -126,6 +132,7 @@ func (e *Engine) register(handle uintptr) {
|
||||
purego.RegisterLibFunc(&e.api.version, handle, "uc_version")
|
||||
purego.RegisterLibFunc(&e.api.open, handle, "uc_open")
|
||||
purego.RegisterLibFunc(&e.api.close, handle, "uc_close")
|
||||
purego.RegisterLibFunc(&e.api.query, handle, "uc_query")
|
||||
purego.RegisterLibFunc(&e.api.ctl, handle, "uc_ctl")
|
||||
purego.RegisterLibFunc(&e.api.strerror, handle, "uc_strerror")
|
||||
purego.RegisterLibFunc(&e.api.memMap, handle, "uc_mem_map")
|
||||
@@ -259,7 +266,20 @@ func (e *Engine) StartBounded(begin, end uint64, timeout time.Duration, instruct
|
||||
|
||||
defer done()
|
||||
|
||||
return e.err(e.api.emuStart(handle, begin, end, microseconds, instructionLimit))
|
||||
if err := e.err(e.api.emuStart(handle, begin, end, microseconds, instructionLimit)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var timedOut uint64
|
||||
if err := e.err(e.api.query(handle, queryTimeout, &timedOut)); err != nil {
|
||||
return fmt.Errorf("query Unicorn timeout: %w", err)
|
||||
}
|
||||
|
||||
if timedOut != 0 {
|
||||
return fmt.Errorf("%w after %s", errTimeout, timeout)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Engine) Stop() error {
|
||||
|
||||
@@ -242,3 +242,32 @@ func TestEngineExecutesX8664(t *testing.T) {
|
||||
t.Fatalf("RAX = %#x, want %#x", value, uint64(0x1234))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartBoundedReportsTimeout(t *testing.T) {
|
||||
engine := newTestEngine(t)
|
||||
defer engine.Close()
|
||||
|
||||
const address = uint64(0x1100000)
|
||||
if err := engine.MemMap(address, 0x1000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// jmp $-2
|
||||
if err := engine.MemWrite(address, []byte{0xeb, 0xfe}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := engine.StartBounded(address, address+2, 10*time.Millisecond, 0)
|
||||
if !errors.Is(err, errTimeout) {
|
||||
t.Fatalf("StartBounded error = %v, want %v", err, errTimeout)
|
||||
}
|
||||
|
||||
const completionAddress = address + 0x10
|
||||
if err := engine.MemWrite(completionAddress, []byte{0xf4}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := engine.StartBounded(completionAddress, completionAddress+1, time.Second, 0); err != nil {
|
||||
t.Fatalf("StartBounded after timeout: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
+22
-5
@@ -1,15 +1,19 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
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"`
|
||||
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 {
|
||||
@@ -40,4 +44,17 @@ func (a App) MarshalZerologObject(event *zerolog.Event) {
|
||||
Str("name", a.Name).
|
||||
Str("version", a.Version).
|
||||
Float64("price", a.Price)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package appstore
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
@@ -40,12 +41,14 @@ var _ = Describe("App", func() {
|
||||
})
|
||||
|
||||
It("marshalls app object", func() {
|
||||
purchaseDate := time.Unix(1_700_000_000, 0).UTC()
|
||||
app := App{
|
||||
ID: 42,
|
||||
BundleID: "app.bundle.id",
|
||||
Name: "app name",
|
||||
Version: "1.0",
|
||||
Price: 0,
|
||||
ID: 42,
|
||||
BundleID: "app.bundle.id",
|
||||
Name: "app name",
|
||||
Version: "1.0",
|
||||
Price: 0,
|
||||
PurchaseDate: purchaseDate,
|
||||
}
|
||||
|
||||
buffer := bytes.NewBuffer([]byte{})
|
||||
@@ -63,8 +66,40 @@ var _ = Describe("App", func() {
|
||||
Expect(out["name"]).To(Equal("app name"))
|
||||
Expect(out["version"]).To(Equal("1.0"))
|
||||
Expect(out["price"]).To(Equal(float64(0)))
|
||||
Expect(out["purchaseDate"]).To(Equal(purchaseDate.Format(time.RFC3339)))
|
||||
})
|
||||
|
||||
It("omits an unknown purchase date", func() {
|
||||
buffer := bytes.NewBuffer([]byte{})
|
||||
logger := zerolog.New(buffer)
|
||||
app := App{ID: 42}
|
||||
|
||||
event := logger.Log()
|
||||
app.MarshalZerologObject(event)
|
||||
event.Send()
|
||||
|
||||
var out map[string]interface{}
|
||||
err := json.Unmarshal(buffer.Bytes(), &out)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
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,
|
||||
@@ -75,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"))
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,8 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
@@ -14,14 +16,16 @@ type AppStore interface {
|
||||
AccountInfo() (AccountInfoOutput, error)
|
||||
// Revoke revokes the active credentials.
|
||||
Revoke() error
|
||||
// Lookup looks apps up based on the specified bundle identifier.
|
||||
// Lookup looks apps up by bundle identifier or numeric app ID.
|
||||
Lookup(input LookupInput) (LookupOutput, error)
|
||||
// Search searches the App Store for apps matching the specified term.
|
||||
Search(input SearchInput) (SearchOutput, error)
|
||||
// OwnedApps lists apps owned by the authenticated account.
|
||||
OwnedApps(input OwnedAppsInput) (OwnedAppsOutput, error)
|
||||
// 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
|
||||
@@ -39,10 +43,16 @@ type appstore struct {
|
||||
searchClient http.Client[searchResult]
|
||||
purchaseClient http.Client[purchaseResult]
|
||||
downloadClient http.Client[downloadResult]
|
||||
kbsyncGenerator kbsyncGenerator
|
||||
kbsyncCache kbsyncCache
|
||||
platformClient http.Client[platformVersionLookupResult]
|
||||
storefrontClient http.Client[[]byte]
|
||||
bagClient http.Client[bagResult]
|
||||
ownedAppsClient http.Client[[]byte]
|
||||
httpClient http.Client[interface{}]
|
||||
macDecrypterFactory macPackageDecrypterFactory
|
||||
actionSignerFactory ActionSignerFactory
|
||||
authRetrySleep func(time.Duration)
|
||||
machine machine.Machine
|
||||
os operatingsystem.OperatingSystem
|
||||
}
|
||||
@@ -67,14 +77,19 @@ 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),
|
||||
kbsyncGenerator: defaultKBSyncGenerator,
|
||||
platformClient: http.NewClient[platformVersionLookupResult](clientArgs),
|
||||
bagClient: http.NewClient[bagResult](clientArgs),
|
||||
storefrontClient: http.NewClient[[]byte](clientArgs),
|
||||
bagClient: http.NewClient[bagResult](http.Args{CookieJar: args.CookieJar, Timeout: http.DefaultAuthenticationTimeout}),
|
||||
ownedAppsClient: http.NewClient[[]byte](clientArgs),
|
||||
httpClient: http.NewClient[interface{}](clientArgs),
|
||||
macDecrypterFactory: defaultMacPackageDecrypterFactory,
|
||||
actionSignerFactory: actionSignerFactory,
|
||||
authRetrySleep: time.Sleep,
|
||||
machine: args.Machine,
|
||||
os: args.OperatingSystem,
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
@@ -33,41 +34,62 @@ 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 {
|
||||
return BagOutput{}, err
|
||||
}
|
||||
|
||||
authURL, err := url.Parse(config.AuthEndpoint)
|
||||
if err != nil {
|
||||
return BagOutput{}, fmt.Errorf("failed to parse authentication endpoint: %w", err)
|
||||
}
|
||||
|
||||
// The bare path can return unusable responses, including a 301 without
|
||||
// Location. Normalize only the validated bag URL, retaining its host and query.
|
||||
authURL.Path = PrivateAppStoreAPIPathAuth + "/"
|
||||
config.AuthEndpoint = authURL.String()
|
||||
|
||||
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"`
|
||||
EntDownloadEndpoint string `plist:"volumeStoreDownloadProduct,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"`
|
||||
@@ -101,18 +123,19 @@ func validateSAPConfig(config SAPConfig) error {
|
||||
}
|
||||
|
||||
func validateAuthenticationEndpoint(endpoint string) error {
|
||||
parsed, err := url.ParseRequestURI(endpoint)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Host == "" {
|
||||
return fmt.Errorf("invalid authentication endpoint %q", endpoint)
|
||||
parsed, err := url.Parse(endpoint)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.User != nil ||
|
||||
parsed.Fragment != "" || parsed.RawPath != "" || (parsed.Port() != "" && parsed.Port() != "443") {
|
||||
return errors.New("invalid authentication endpoint")
|
||||
}
|
||||
|
||||
host := strings.ToLower(parsed.Hostname())
|
||||
if host != PrivateAppStoreAPIDomain && !strings.HasSuffix(host, "-buy.itunes.apple.com") {
|
||||
return fmt.Errorf("unsupported authentication endpoint %q", endpoint)
|
||||
return errors.New("unsupported authentication endpoint")
|
||||
}
|
||||
|
||||
if parsed.Path != PrivateAppStoreAPIPathAuth {
|
||||
return fmt.Errorf("unsupported authentication endpoint %q", endpoint)
|
||||
if parsed.Path != PrivateAppStoreAPIPathAuth && parsed.Path != PrivateAppStoreAPIPathAuth+"/" {
|
||||
return errors.New("unsupported authentication endpoint")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -33,6 +33,44 @@ var _ = Describe("AppStore (Bag)", func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
DescribeTable("normalizes the authentication path while preserving the bag host and query", func(endpoint, expected string) {
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
result := validBagResult()
|
||||
result.URLBag.AuthEndpoint = endpoint
|
||||
mockBagClient.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: result}, nil)
|
||||
out, err := as.Bag(BagInput{})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(out.AuthEndpoint).To(Equal(expected))
|
||||
Expect(out.SAPConfig.AuthEndpoint).To(Equal(expected))
|
||||
},
|
||||
Entry("bare path", testAuthEndpoint, testAuthEndpoint+"/"),
|
||||
Entry("trailing slash", testAuthEndpoint+"/", testAuthEndpoint+"/"),
|
||||
Entry("bare path with routing query", testAuthEndpoint+"?Pod=7&routing=a%2Fb+c", testAuthEndpoint+"/?Pod=7&routing=a%2Fb+c"),
|
||||
Entry("bare pod URL with routing query", "https://p7-buy.itunes.apple.com"+PrivateAppStoreAPIPathAuth+"?Pod=7&PRH=7", "https://p7-buy.itunes.apple.com"+PrivateAppStoreAPIPathAuth+"/?Pod=7&PRH=7"),
|
||||
Entry("slashed pod URL with routing query", "https://p7-buy.itunes.apple.com"+PrivateAppStoreAPIPathAuth+"/?routing=opaque", "https://p7-buy.itunes.apple.com"+PrivateAppStoreAPIPathAuth+"/?routing=opaque"),
|
||||
Entry("explicit HTTPS port", "https://buy.itunes.apple.com:443"+PrivateAppStoreAPIPathAuth, "https://buy.itunes.apple.com:443"+PrivateAppStoreAPIPathAuth+"/"),
|
||||
)
|
||||
|
||||
DescribeTable("rejects invalid authentication URLs before normalizing the path", func(endpoint string) {
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
result := validBagResult()
|
||||
result.URLBag.AuthEndpoint = endpoint
|
||||
mockBagClient.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: result}, nil)
|
||||
_, err := as.Bag(BagInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
},
|
||||
Entry("double slash", testAuthEndpoint+"//"),
|
||||
Entry("extra path", testAuthEndpoint+"/extra"),
|
||||
Entry("encoded slash", testAuthEndpoint+"%2f"),
|
||||
Entry("different path", "https://buy.itunes.apple.com/other"),
|
||||
Entry("foreign host", "https://example.com"+PrivateAppStoreAPIPathAuth),
|
||||
Entry("HTTP", "http://buy.itunes.apple.com"+PrivateAppStoreAPIPathAuth),
|
||||
Entry("userinfo", "https://user@buy.itunes.apple.com"+PrivateAppStoreAPIPathAuth),
|
||||
Entry("unsupported port", "https://buy.itunes.apple.com:8443"+PrivateAppStoreAPIPathAuth),
|
||||
Entry("fragment", testAuthEndpoint+"#fragment"),
|
||||
Entry("malformed URL", testAuthEndpoint+"%zz"),
|
||||
)
|
||||
|
||||
When("fails to read machine MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
@@ -177,7 +215,7 @@ func validBagResult() bagResult {
|
||||
|
||||
func validSAPConfig() SAPConfig {
|
||||
return SAPConfig{
|
||||
AuthEndpoint: testAuthEndpoint,
|
||||
AuthEndpoint: testAuthEndpoint + "/",
|
||||
SetupURL: testSAPSetupEndpoint,
|
||||
CertificateURL: testSAPSetupCertEndpoint,
|
||||
Version: 200,
|
||||
|
||||
@@ -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,19 +43,29 @@ func (t *appstore) Download(input DownloadInput) (DownloadOutput, error) {
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
externalVersionID := input.ExternalVersionID
|
||||
if externalVersionID == "" && input.Platform == PlatformAppleTV {
|
||||
externalVersionID, err = t.lookupLatestExternalVersionID(input.Account, input.App, input.Platform)
|
||||
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 == PlatformWatchOS || input.Platform == PlatformVisionOS) {
|
||||
externalVersionID, err = t.lookupLatestExternalVersionID(input.Account, input.App, input.Platform)
|
||||
// Delisted tvOS apps may have no catalog offer but still be available
|
||||
// for redownload. Validate the returned package's platform below.
|
||||
missingTVOffer := input.Platform == PlatformAppleTV &&
|
||||
(errors.Is(err, errPlatformAppNotFound) || errors.Is(err, errPlatformOffersNotFound))
|
||||
if err != nil && !missingTVOffer {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to resolve platform version: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
req := t.downloadRequest(input.Account, input.App, guid, externalVersionID)
|
||||
|
||||
res, err := t.downloadClient.Send(req)
|
||||
res, resolvedPlatform, err := t.sendDownloadProduct(input.Context, 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 +79,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 +100,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)
|
||||
}
|
||||
|
||||
@@ -125,7 +152,18 @@ type platformPackageInfo struct {
|
||||
}
|
||||
|
||||
func (*appstore) validatePackagePlatform(path string, platform Platform) error {
|
||||
if platform != PlatformAppleTV {
|
||||
var expectedPlatform string
|
||||
|
||||
switch platform {
|
||||
case PlatformIPhone, PlatformIPad:
|
||||
expectedPlatform = "iPhoneOS"
|
||||
case PlatformAppleTV:
|
||||
expectedPlatform = "AppleTVOS"
|
||||
case PlatformWatchOS:
|
||||
expectedPlatform = "WatchOS"
|
||||
case PlatformVisionOS:
|
||||
expectedPlatform = "XROS"
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -136,7 +174,7 @@ func (*appstore) validatePackagePlatform(path string, platform Platform) error {
|
||||
defer reader.Close()
|
||||
|
||||
for _, file := range reader.File {
|
||||
if !strings.HasPrefix(file.Name, "Payload/") || !strings.HasSuffix(file.Name, ".app/Info.plist") {
|
||||
if !isTopLevelAppInfoPlist(file.Name) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -164,20 +202,28 @@ func (*appstore) validatePackagePlatform(path string, platform Platform) error {
|
||||
}
|
||||
|
||||
for _, supportedPlatform := range info.SupportedPlatforms {
|
||||
if supportedPlatform == "AppleTVOS" {
|
||||
if supportedPlatform == expectedPlatform {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return errors.New("downloaded package does not declare AppleTVOS support")
|
||||
return fmt.Errorf("downloaded package does not declare %s support", expectedPlatform)
|
||||
}
|
||||
|
||||
func isTopLevelAppInfoPlist(path string) bool {
|
||||
parts := strings.Split(path, "/")
|
||||
|
||||
return len(parts) == 3 && parts[0] == "Payload" && strings.HasSuffix(parts[1], ".app") && parts[2] == "Info.plist"
|
||||
}
|
||||
|
||||
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"`
|
||||
PreflightPackageURL string `plist:"preflightPackageURL,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 {
|
||||
@@ -186,18 +232,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 {
|
||||
@@ -214,64 +273,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 != "" {
|
||||
@@ -286,11 +340,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()
|
||||
@@ -307,7 +366,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
|
||||
@@ -326,7 +385,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)
|
||||
@@ -337,16 +397,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,256 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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(ctx context.Context, acc Account, app App, guid, externalVersionID string, platform Platform) (http.Result[downloadResult], Platform, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return http.Result[downloadResult]{}, platform, fmt.Errorf("download request canceled: %w", err)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// Prefer ent/download when its generator and bag endpoint are available.
|
||||
// Keep the fetched bag for the legacy chain if this attempt cannot serve
|
||||
// the requested app; asset, network, and response failures can fall back.
|
||||
var bag *urlBag
|
||||
|
||||
if t.kbsyncGenerator != nil {
|
||||
fetched, err := t.fetchURLBag(guid)
|
||||
if err == nil {
|
||||
bag = &fetched
|
||||
if bag.EntDownloadEndpoint != "" {
|
||||
res, resolvedPlatform, err := t.sendPreferredDownload(ctx, bag.EntDownloadEndpoint, acc, app, guid, externalVersionID, platform)
|
||||
if err == nil {
|
||||
return res, resolvedPlatform, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return http.Result[downloadResult]{}, platform, fmt.Errorf("download request canceled: %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.
|
||||
if bag == nil {
|
||||
fetched, err := t.fetchURLBag(guid)
|
||||
if err != nil {
|
||||
return res, platform, fmt.Errorf("failed to get bag for redownload fallback: %w", err)
|
||||
}
|
||||
|
||||
bag = &fetched
|
||||
}
|
||||
|
||||
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 || platform == PlatformAppleTV || platform == PlatformWatchOS) &&
|
||||
(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 app 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)
|
||||
}
|
||||
|
||||
return res, validateVersionedDownloadResponse(res, app, externalVersionID, "update")
|
||||
}
|
||||
|
||||
func validateVersionedDownloadResponse(res http.Result[downloadResult], app App, externalVersionID, source string) error {
|
||||
if res.Data.FailureType != "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
if res.Data.CustomerMessage != "" {
|
||||
return NewErrorWithMetadata(fmt.Errorf("received %s error: %s", source, res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return fmt.Errorf("received unexpected %s status code: %d", source, res.StatusCode)
|
||||
}
|
||||
|
||||
if len(res.Data.Items) != 1 {
|
||||
return fmt.Errorf("%s response must contain exactly one item", source)
|
||||
}
|
||||
|
||||
metadata := res.Data.Items[0].Metadata
|
||||
if fmt.Sprint(metadata["itemId"]) != fmt.Sprint(app.ID) ||
|
||||
fmt.Sprint(metadata["softwareVersionExternalIdentifier"]) != externalVersionID {
|
||||
return fmt.Errorf("%s response does not match the requested app or version", source)
|
||||
}
|
||||
|
||||
bundleID, ok := metadata["softwareVersionBundleId"].(string)
|
||||
if !ok || bundleID == "" || (app.BundleID != "" && bundleID != app.BundleID) {
|
||||
return fmt.Errorf("%s response does not match the requested bundle identifier", source)
|
||||
}
|
||||
|
||||
return 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,468 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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 when kbsync generation is unavailable", 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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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"),
|
||||
)
|
||||
|
||||
It("pins the consumer catalog version on redownload", func() {
|
||||
gomock.InOrder(
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK}, nil),
|
||||
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]{StatusCode: gohttp.StatusOK}, nil),
|
||||
)
|
||||
_, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, "", PlatformIPhone)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
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(context.Background(), 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(context.Background(), 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(context.Background(), 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(context.Background(), 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).Times(4)
|
||||
|
||||
_, _, err := store.sendDownloadProduct(context.Background(), 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(context.Background(), 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(context.Background(), 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"
|
||||
|
||||
@@ -33,37 +36,43 @@ func (d *dummyFileInfo) Sys() interface{} { return nil }
|
||||
|
||||
var _ = Describe("AppStore (Download)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockPlatformClient *http.MockClient[platformVersionLookupResult]
|
||||
mockPurchaseClient *http.MockClient[purchaseResult]
|
||||
mockLoginClient *http.MockClient[loginResult]
|
||||
mockHTTPClient *http.MockClient[interface{}]
|
||||
mockOS *operatingsystem.MockOperatingSystem
|
||||
mockMachine *machine.MockMachine
|
||||
as AppStore
|
||||
ctrl *gomock.Controller
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockBagClient *http.MockClient[bagResult]
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockPlatformClient *http.MockClient[platformVersionLookupResult]
|
||||
mockStorefrontClient *http.MockClient[[]byte]
|
||||
mockPurchaseClient *http.MockClient[purchaseResult]
|
||||
mockLoginClient *http.MockClient[loginResult]
|
||||
mockHTTPClient *http.MockClient[interface{}]
|
||||
mockOS *operatingsystem.MockOperatingSystem
|
||||
mockMachine *machine.MockMachine
|
||||
as AppStore
|
||||
)
|
||||
|
||||
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)
|
||||
mockLoginClient = http.NewMockClient[loginResult](ctrl)
|
||||
mockPurchaseClient = http.NewMockClient[purchaseResult](ctrl)
|
||||
mockHTTPClient = http.NewMockClient[interface{}](ctrl)
|
||||
mockOS = operatingsystem.NewMockOperatingSystem(ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockLoginClient,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: mockOS,
|
||||
keychain: mockKeychain,
|
||||
bagClient: mockBagClient,
|
||||
loginClient: mockLoginClient,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
platformClient: mockPlatformClient,
|
||||
storefrontClient: mockStorefrontClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: mockOS,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -187,6 +196,97 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
})
|
||||
})
|
||||
|
||||
It("pins the latest watchOS version before downloading", func() {
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
gomock.InOrder(
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
parsedURL, err := url.Parse(req.URL)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(parsedURL.Query().Get("platform")).To(Equal("enterprisestore"))
|
||||
Expect(parsedURL.Query().Get("id")).To(Equal("6764448634"))
|
||||
}).Return(http.Result[platformVersionLookupResult]{StatusCode: 200, Data: platformVersionLookupResult{
|
||||
Results: map[string]platformVersionLookupItem{"6764448634": {Offers: []platformVersionLookupOffer{
|
||||
{Version: platformVersionLookupVersion{ExternalID: "885050618"}},
|
||||
}}},
|
||||
}}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", "885050618"))
|
||||
}).Return(http.Result[downloadResult]{Data: downloadResult{FailureType: FailureTypeLicenseNotFound}}, nil),
|
||||
)
|
||||
_, err := as.Download(DownloadInput{
|
||||
Account: Account{StoreFront: "143441"}, App: App{ID: 6764448634}, Platform: PlatformWatchOS,
|
||||
})
|
||||
Expect(err).To(MatchError(ErrLicenseRequired))
|
||||
})
|
||||
|
||||
When("platform is visionOS", func() {
|
||||
It("resolves and sends the visionOS external version id", func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockStorefrontClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
parsedURL, err := url.Parse(req.URL)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(parsedURL.Host).To(Equal("apps.apple.com"))
|
||||
Expect(parsedURL.Path).To(Equal("/us/app/id42"))
|
||||
Expect(parsedURL.Query().Get("platform")).To(Equal("vision"))
|
||||
Expect(req.Method).To(Equal(http.MethodGET))
|
||||
Expect(req.ResponseFormat).To(Equal(http.ResponseFormatRaw))
|
||||
}).
|
||||
Return(http.Result[[]byte]{
|
||||
StatusCode: 200,
|
||||
Data: []byte(`<script type="application/json" id="serialized-server-data">[{"data":{"app":{"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=42&appExtVrsId=987654"}}}}]</script>`),
|
||||
}, nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
payload, ok := req.Payload.(*http.XMLPayload)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(payload.Content["externalVersionId"]).To(Equal("987654"))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{}, errors.New("request error"))
|
||||
|
||||
_, err := as.Download(DownloadInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
App: App{
|
||||
ID: 42,
|
||||
},
|
||||
Platform: PlatformVisionOS,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
|
||||
It("uses an explicit external version id without a storefront lookup", func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
payload, ok := req.Payload.(*http.XMLPayload)
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(payload.Content["externalVersionId"]).To(Equal("123456"))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{}, errors.New("request error"))
|
||||
|
||||
_, err := as.Download(DownloadInput{
|
||||
App: App{
|
||||
ID: 42,
|
||||
},
|
||||
Platform: PlatformVisionOS,
|
||||
ExternalVersionID: "123456",
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
DescribeTable("platform uses the standard download request",
|
||||
func(platform Platform) {
|
||||
mockMachine.EXPECT().
|
||||
@@ -332,10 +432,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() {
|
||||
@@ -485,7 +593,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)
|
||||
|
||||
})
|
||||
@@ -545,7 +655,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)
|
||||
})
|
||||
|
||||
@@ -587,7 +699,7 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
|
||||
mockOS.EXPECT().
|
||||
Stat(gomock.Any()).
|
||||
Return(nil, nil)
|
||||
Return(&dummyFileInfo{}, nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Remove(tmpFile.Name()).
|
||||
@@ -627,27 +739,392 @@ 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),
|
||||
Entry("tvOS update accepts tvOS", PlatformAppleTV, "818970197", "update", "AppleTVOS", true),
|
||||
Entry("tvOS update rejects iOS", PlatformAppleTV, "818970197", "update", "iPhoneOS", false),
|
||||
Entry("tvOS update rejects visionOS", PlatformAppleTV, "818970197", "update", "XROS", false),
|
||||
Entry("watchOS accepts WatchOS", PlatformWatchOS, "818970197", "", "WatchOS", true),
|
||||
Entry("watchOS rejects iOS", PlatformWatchOS, "818970197", "", "iPhoneOS", false),
|
||||
Entry("watchOS rejects tvOS", PlatformWatchOS, "818970197", "", "AppleTVOS", false),
|
||||
Entry("watchOS redownload preserves the platform", PlatformWatchOS, "818970197", "redownload", "WatchOS", true),
|
||||
Entry("watchOS update accepts WatchOS", PlatformWatchOS, "818970197", "update", "WatchOS", true),
|
||||
Entry("watchOS update rejects iOS", PlatformWatchOS, "818970197", "update", "iPhoneOS", false),
|
||||
Entry("iPhone still rejects WatchOS", PlatformIPhone, "", "", "WatchOS", false),
|
||||
)
|
||||
|
||||
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() {
|
||||
writePackage := func(platforms []string) string {
|
||||
writePackageWithInfoPlists := func(infoPlists map[string][]string) string {
|
||||
file, err := os.CreateTemp("", "ipatool-platform-*.ipa")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
defer file.Close()
|
||||
|
||||
zipFile := zip.NewWriter(file)
|
||||
w, err := zipFile.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
for path, platforms := range infoPlists {
|
||||
w, err := zipFile.Create(path)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleSupportedPlatforms": platforms,
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleSupportedPlatforms": platforms,
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
}
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(zipFile.Close()).To(Succeed())
|
||||
|
||||
return file.Name()
|
||||
}
|
||||
writePackage := func(platforms []string) string {
|
||||
return writePackageWithInfoPlists(map[string][]string{
|
||||
"Payload/Test.app/Info.plist": platforms,
|
||||
})
|
||||
}
|
||||
|
||||
It("accepts AppleTVOS packages", func() {
|
||||
path := writePackage([]string{"AppleTVOS"})
|
||||
@@ -657,6 +1134,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)
|
||||
@@ -665,5 +1172,190 @@ var _ = Describe("AppStore (Download)", func() {
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("AppleTVOS"))
|
||||
})
|
||||
|
||||
It("does not accept watchOS support declared only by an embedded app", func() {
|
||||
path := writePackageWithInfoPlists(map[string][]string{
|
||||
"Payload/Test.app/Info.plist": {"iPhoneOS"},
|
||||
"Payload/Test.app/Watch/Watch.app/Info.plist": {"WatchOS"},
|
||||
})
|
||||
defer os.Remove(path)
|
||||
|
||||
err := (&appstore{}).validatePackagePlatform(path, PlatformWatchOS)
|
||||
Expect(err).To(MatchError("downloaded package does not declare WatchOS support"))
|
||||
})
|
||||
|
||||
It("accepts XROS packages", func() {
|
||||
path := writePackage([]string{"XROS"})
|
||||
defer os.Remove(path)
|
||||
|
||||
err := (&appstore{}).validatePackagePlatform(path, PlatformVisionOS)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("returns an error for packages without XROS support", func() {
|
||||
path := writePackage([]string{"iPhoneOS"})
|
||||
defer os.Remove(path)
|
||||
|
||||
err := (&appstore{}).validatePackagePlatform(path, PlatformVisionOS)
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("XROS"))
|
||||
})
|
||||
|
||||
It("ignores supported platforms declared only by an embedded app", func() {
|
||||
path := writePackageWithInfoPlists(map[string][]string{
|
||||
"Payload/Test.app/Info.plist": {"iPhoneOS"},
|
||||
"Payload/Test.app/PlugIns/Vision.app/Info.plist": {"XROS"},
|
||||
})
|
||||
defer os.Remove(path)
|
||||
|
||||
err := (&appstore{}).validatePackagePlatform(path, PlatformVisionOS)
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("XROS"))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("Downloading delisted tvOS apps", func() {
|
||||
var (
|
||||
platformClient *http.MockClient[platformVersionLookupResult]
|
||||
downloadClient *http.MockClient[downloadResult]
|
||||
bagClient *http.MockClient[bagResult]
|
||||
httpClient *http.MockClient[interface{}]
|
||||
store *appstore
|
||||
input DownloadInput
|
||||
)
|
||||
|
||||
missingApp := platformVersionLookupResult{}
|
||||
missingOffers := platformVersionLookupResult{Results: map[string]platformVersionLookupItem{"42": {}}}
|
||||
missingVersion := platformVersionLookupResult{Results: map[string]platformVersionLookupItem{
|
||||
"42": {Offers: []platformVersionLookupOffer{{}}},
|
||||
}}
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
platformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
downloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
bagClient = http.NewMockClient[bagResult](ctrl)
|
||||
httpClient = http.NewMockClient[interface{}](ctrl)
|
||||
mockMachine := machine.NewMockMachine(ctrl)
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
store = &appstore{
|
||||
platformClient: platformClient,
|
||||
downloadClient: downloadClient,
|
||||
bagClient: bagClient,
|
||||
httpClient: httpClient,
|
||||
machine: mockMachine,
|
||||
os: operatingsystem.New(),
|
||||
}
|
||||
input = DownloadInput{
|
||||
Account: Account{StoreFront: "143441"},
|
||||
App: App{ID: 42},
|
||||
Platform: PlatformAppleTV,
|
||||
OutputPath: filepath.Join(GinkgoT().TempDir(), "app.ipa"),
|
||||
}
|
||||
})
|
||||
|
||||
DescribeTable("attempts downloads without a catalog offer and validates the package",
|
||||
func(catalog platformVersionLookupResult, redownload bool, supportedPlatform string) {
|
||||
previousOutput := []byte("previous output")
|
||||
Expect(os.WriteFile(input.OutputPath, previousOutput, 0600)).To(Succeed())
|
||||
packageBuffer := new(bytes.Buffer)
|
||||
writer := zip.NewWriter(packageBuffer)
|
||||
infoWriter, err := writer.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(writer.Close()).To(Succeed())
|
||||
|
||||
previous := platformClient.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{
|
||||
StatusCode: gohttp.StatusOK, Data: catalog,
|
||||
}, nil)
|
||||
checkRequest := func(req http.Request) {
|
||||
payload := req.Payload.(*http.XMLPayload).Content
|
||||
Expect(payload).To(HaveKeyWithValue("salableAdamId", input.App.ID))
|
||||
Expect(payload).ToNot(HaveKey("externalVersionId"))
|
||||
Expect(payload).ToNot(HaveKey("appExtVrsId"))
|
||||
}
|
||||
if redownload {
|
||||
previous = downloadClient.EXPECT().Send(gomock.Any()).After(previous).Do(checkRequest).
|
||||
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK}, nil)
|
||||
previous = bagClient.EXPECT().Send(gomock.Any()).After(previous).Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: bagResult{URLBag: urlBag{RedownloadEndpoint: testRedownloadEndpoint}},
|
||||
}, nil)
|
||||
}
|
||||
downloadClient.EXPECT().Send(gomock.Any()).After(previous).Do(checkRequest).Return(http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{Items: []downloadItemResult{{
|
||||
URL: "https://example.test/app.ipa",
|
||||
Metadata: map[string]interface{}{"bundleShortVersionString": "1.0"},
|
||||
}}},
|
||||
}, nil)
|
||||
httpClient.EXPECT().NewRequest("GET", "https://example.test/app.ipa", nil).
|
||||
Return(&gohttp.Request{Header: gohttp.Header{}}, nil)
|
||||
httpClient.EXPECT().Do(gomock.Any()).Return(&gohttp.Response{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Body: io.NopCloser(bytes.NewReader(packageBuffer.Bytes())),
|
||||
ContentLength: int64(packageBuffer.Len()),
|
||||
}, nil)
|
||||
|
||||
out, err := store.Download(input)
|
||||
if supportedPlatform == "AppleTVOS" {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.DestinationPath).To(Equal(input.OutputPath))
|
||||
Expect(store.validatePackagePlatform(out.DestinationPath, PlatformAppleTV)).To(Succeed())
|
||||
} else {
|
||||
Expect(err).To(MatchError(ContainSubstring("does not declare AppleTVOS support")))
|
||||
Expect(os.ReadFile(input.OutputPath)).To(Equal(previousOutput))
|
||||
}
|
||||
Expect(input.OutputPath + ".tmp").ToNot(BeAnExistingFile())
|
||||
},
|
||||
Entry("missing app", missingApp, false, "AppleTVOS"),
|
||||
Entry("missing offers", missingOffers, false, "AppleTVOS"),
|
||||
Entry("missing app with redownload", missingApp, true, "AppleTVOS"),
|
||||
Entry("wrong platform from volumeStore", missingApp, false, "iPhoneOS"),
|
||||
Entry("wrong platform from redownload", missingApp, true, "iPhoneOS"),
|
||||
)
|
||||
|
||||
DescribeTable("preserves catalog failures", func(status int, catalog platformVersionLookupResult, sendErr error, message string) {
|
||||
platformClient.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{
|
||||
StatusCode: status, Data: catalog,
|
||||
}, sendErr)
|
||||
|
||||
_, err := store.Download(input)
|
||||
Expect(err).To(MatchError(ContainSubstring(message)))
|
||||
},
|
||||
Entry("network failure", 0, missingApp, errors.New("connection reset"), "connection reset"),
|
||||
Entry("invalid response", 200, missingApp, errors.New("invalid JSON"), "invalid JSON"),
|
||||
Entry("HTTP failure", 503, missingApp, nil, "platform version lookup request failed"),
|
||||
Entry("offer without version", 200, missingVersion, nil, "no external version id"),
|
||||
)
|
||||
|
||||
It("preserves license errors after a missing catalog entry", func() {
|
||||
platformClient.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK}, nil)
|
||||
downloadClient.EXPECT().Send(gomock.Any()).Return(http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{FailureType: FailureTypeLicenseNotFound},
|
||||
}, nil)
|
||||
|
||||
_, err := store.Download(input)
|
||||
Expect(err).To(MatchError(ErrLicenseRequired))
|
||||
})
|
||||
|
||||
It("uses an explicit tvOS version without consulting the catalog", func() {
|
||||
input.ExternalVersionID = "123456"
|
||||
downloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", input.ExternalVersionID))
|
||||
}).Return(http.Result[downloadResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: downloadResult{FailureType: FailureTypeLicenseNotFound},
|
||||
}, nil)
|
||||
|
||||
_, err := store.Download(input)
|
||||
Expect(err).To(MatchError(ErrLicenseRequired))
|
||||
})
|
||||
})
|
||||
@@ -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, PlatformWatchOS, 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.Context, 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,36 @@ func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersion
|
||||
}
|
||||
|
||||
item := res.Data.Items[0]
|
||||
// A pinned Mac version can be returned even when no platform was supplied.
|
||||
// Use the response's package type instead of passing it to the IPA reader.
|
||||
if input.Platform == "" {
|
||||
softwarePlatform := downloadMetadataString(item.Metadata, "software-platform")
|
||||
if strings.EqualFold(softwarePlatform, "macos") ||
|
||||
(softwarePlatform == "" && strings.EqualFold(downloadMetadataString(item.Metadata, "product-type"), "mac-os-app")) {
|
||||
platform = PlatformMacOS
|
||||
}
|
||||
}
|
||||
|
||||
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 +107,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
|
||||
@@ -503,7 +549,7 @@ var _ = Describe("AppStore (GetVersionMetadata)", func() {
|
||||
server.Close()
|
||||
})
|
||||
|
||||
It("returns version metadata", func() {
|
||||
DescribeTable("returns version metadata", func(platform Platform) {
|
||||
output, err := as.GetVersionMetadata(GetVersionMetadataInput{
|
||||
Account: Account{
|
||||
DirectoryServicesID: "test-dsid",
|
||||
@@ -512,6 +558,7 @@ var _ = Describe("AppStore (GetVersionMetadata)", func() {
|
||||
ID: 1234567890,
|
||||
},
|
||||
VersionID: "test-version",
|
||||
Platform: platform,
|
||||
})
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
@@ -519,6 +566,9 @@ var _ = Describe("AppStore (GetVersionMetadata)", func() {
|
||||
Expect(output.ReleaseDate).To(Equal(releaseDate))
|
||||
Expect(atomic.LoadInt64(wholeGetCount)).To(BeZero())
|
||||
Expect(atomic.LoadInt64(servedBytes)).To(BeNumerically("<", int64(len(ipa)/2)))
|
||||
})
|
||||
},
|
||||
Entry("default platform", Platform("")),
|
||||
Entry("watchOS", PlatformWatchOS),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type catalogVersionLookupItem struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Attributes struct {
|
||||
DeviceFamilies []string `json:"deviceFamilies,omitempty"`
|
||||
PlatformAttributes map[string]catalogVersionPlatformAttributes `json:"platformAttributes,omitempty"`
|
||||
} `json:"attributes,omitempty"`
|
||||
}
|
||||
|
||||
type catalogVersionPlatformAttributes struct {
|
||||
BundleID string `json:"bundleId,omitempty"`
|
||||
ExternalVersionID platformVersionExternalID `json:"externalVersionId,omitempty"`
|
||||
}
|
||||
|
||||
func (t *appstore) lookupLatestIOSExternalVersionID(app App, countryCode string, platform Platform) (string, error) {
|
||||
// This is the JSON catalog API used by the public App Store client.
|
||||
res, err := t.platformClient.Send(http.Request{
|
||||
URL: fmt.Sprintf("https://apps.apple.com/api/apps/v1/catalog/%s/apps/%d?platform=%s", strings.ToLower(countryCode), app.ID, platform),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatJSON,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("iOS catalog lookup request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return "", fmt.Errorf("iOS catalog lookup returned HTTP %d", res.StatusCode)
|
||||
}
|
||||
|
||||
if len(res.Data.Data) != 1 {
|
||||
return "", errors.New("iOS catalog lookup must return exactly one app")
|
||||
}
|
||||
|
||||
item := res.Data.Data[0]
|
||||
if item.ID != strconv.FormatInt(app.ID, 10) || item.Type != "apps" {
|
||||
return "", errors.New("iOS catalog lookup returned a different app")
|
||||
}
|
||||
|
||||
attributes, ok := item.Attributes.PlatformAttributes["ios"]
|
||||
if !ok || !slices.Contains(item.Attributes.DeviceFamilies, string(platform)) {
|
||||
return "", errors.New("iOS catalog lookup returned no metadata for the requested platform")
|
||||
}
|
||||
|
||||
if app.BundleID != "" && attributes.BundleID != app.BundleID {
|
||||
return "", errors.New("iOS catalog lookup returned a different bundle identifier")
|
||||
}
|
||||
|
||||
version := string(attributes.ExternalVersionID)
|
||||
if id, err := strconv.ParseUint(version, 10, 64); err != nil || id == 0 {
|
||||
return "", errors.New("iOS catalog lookup returned no valid external version id")
|
||||
}
|
||||
|
||||
return version, nil
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
// Synthetic catalog API response for an example app.
|
||||
const arcadeCatalogResponse = `{"data":[{"id":"42","type":"apps","attributes":{"deviceFamilies":["tvos","iphone","ipad","ipod"],"platformAttributes":{"ios":{"bundleId":"com.example.arcade","externalVersionId":1002}}}}]}`
|
||||
|
||||
func decodeCatalogResponse(body string) platformVersionLookupResult {
|
||||
var result platformVersionLookupResult
|
||||
|
||||
Expect(json.Unmarshal([]byte(body), &result)).To(Succeed())
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
var _ = Describe("iOS catalog version fallback", func() {
|
||||
var client *http.MockClient[platformVersionLookupResult]
|
||||
var store *appstore
|
||||
app := App{ID: 42, BundleID: "com.example.arcade"}
|
||||
account := Account{StoreFront: "143443-2,34"}
|
||||
|
||||
BeforeEach(func() {
|
||||
client = http.NewMockClient[platformVersionLookupResult](gomock.NewController(GinkgoT()))
|
||||
store = &appstore{platformClient: client}
|
||||
})
|
||||
|
||||
DescribeTable("resolves Arcade versions after exhausting the MDM catalogs", func(platform Platform, noOffers bool, quotedVersion bool) {
|
||||
empty := platformVersionLookupResult{}
|
||||
if noOffers {
|
||||
empty.Results = map[string]platformVersionLookupItem{"42": {}}
|
||||
}
|
||||
body := arcadeCatalogResponse
|
||||
if quotedVersion {
|
||||
body = strings.ReplaceAll(body, "1002", `"1002"`)
|
||||
}
|
||||
calls := make([]any, 0, 4)
|
||||
for _, catalog := range []string{"enterprisestore", "iphone", "ipad"} {
|
||||
calls = append(calls, client.EXPECT().Send(store.platformVersionLookupRequest(app.ID, "DE", catalog)).Return(http.Result[platformVersionLookupResult]{StatusCode: 200, Data: empty}, nil))
|
||||
}
|
||||
calls = append(calls, client.EXPECT().Send(http.Request{
|
||||
URL: "https://apps.apple.com/api/apps/v1/catalog/de/apps/42?platform=" + string(platform),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatJSON,
|
||||
}).Return(http.Result[platformVersionLookupResult]{StatusCode: 200, Data: decodeCatalogResponse(body)}, nil))
|
||||
gomock.InOrder(calls...)
|
||||
version, err := store.lookupLatestExternalVersionID(account, app, platform)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(version).To(Equal("1002"))
|
||||
},
|
||||
Entry("missing iPhone app", PlatformIPhone, false, false),
|
||||
Entry("missing iPad offers", PlatformIPad, true, false),
|
||||
Entry("string version identifier", PlatformIPhone, false, true),
|
||||
)
|
||||
|
||||
DescribeTable("preserves catalog and API failures", func(status int, requestErr error, message string) {
|
||||
gomock.InOrder(
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: 200}, nil).Times(3),
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: status}, requestErr),
|
||||
)
|
||||
_, err := store.lookupLatestExternalVersionID(account, app, PlatformIPhone)
|
||||
Expect(err).To(MatchError(And(ContainSubstring("iOS catalog fallback failed"), ContainSubstring(message), ContainSubstring("storefront DE"))))
|
||||
Expect(errors.Is(err, errPlatformAppNotFound)).To(BeTrue())
|
||||
if requestErr != nil {
|
||||
Expect(errors.Is(err, requestErr)).To(BeTrue())
|
||||
}
|
||||
},
|
||||
Entry("HTTP failure", 503, nil, "HTTP 503"),
|
||||
Entry("network failure", 0, errors.New("connection reset"), "connection reset"),
|
||||
Entry("decoding failure", 200, errors.New("invalid JSON"), "invalid JSON"),
|
||||
Entry("empty response", 200, nil, "exactly one app"),
|
||||
)
|
||||
|
||||
DescribeTable("rejects unusable API metadata", func(body string, message string) {
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: 200, Data: decodeCatalogResponse(body)}, nil)
|
||||
_, err := store.lookupLatestIOSExternalVersionID(app, "US", PlatformIPhone)
|
||||
Expect(err).To(MatchError(ContainSubstring(message)))
|
||||
},
|
||||
Entry("no app", `{"data":[]}`, "exactly one app"),
|
||||
Entry("wrong app", strings.ReplaceAll(arcadeCatalogResponse, "42", "1"), "different app"),
|
||||
Entry("wrong resource type", strings.ReplaceAll(arcadeCatalogResponse, `"apps"`, `"app-bundles"`), "different app"),
|
||||
Entry("wrong bundle", strings.ReplaceAll(arcadeCatalogResponse, "com.example.arcade", "other"), "different bundle"),
|
||||
Entry("Mac version only", strings.ReplaceAll(arcadeCatalogResponse, `"ios"`, `"macos"`), "requested platform"),
|
||||
Entry("TV version only", strings.ReplaceAll(arcadeCatalogResponse, `"ios"`, `"tvos"`), "requested platform"),
|
||||
Entry("iPad only", strings.ReplaceAll(arcadeCatalogResponse, `"iphone",`, ""), "requested platform"),
|
||||
Entry("missing version", strings.ReplaceAll(arcadeCatalogResponse, "1002", "null"), "no valid external version id"),
|
||||
Entry("zero version", strings.ReplaceAll(arcadeCatalogResponse, "1002", "0"), "no valid external version id"),
|
||||
Entry("negative version", strings.ReplaceAll(arcadeCatalogResponse, "1002", "-1"), "no valid external version id"),
|
||||
Entry("fractional version", strings.ReplaceAll(arcadeCatalogResponse, "1002", "1.5"), "no valid external version id"),
|
||||
Entry("nonnumeric version", strings.ReplaceAll(arcadeCatalogResponse, "1002", `"invalid"`), "no valid external version id"),
|
||||
)
|
||||
|
||||
It("supports requests made with only an app ID", func() {
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: 200, Data: decodeCatalogResponse(arcadeCatalogResponse)}, nil)
|
||||
version, err := store.lookupLatestIOSExternalVersionID(App{ID: app.ID}, "US", PlatformIPhone)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(version).To(Equal("1002"))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("ListVersions for apps missing from the MDM catalogs", func() {
|
||||
DescribeTable("uses the API version for redownload and retains license handling", func(licensed bool) {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
defer ctrl.Finish()
|
||||
catalog := http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
downloads := http.NewMockClient[downloadResult](ctrl)
|
||||
bags := http.NewMockClient[bagResult](ctrl)
|
||||
device := machine.NewMockMachine(ctrl)
|
||||
store := &appstore{platformClient: catalog, downloadClient: downloads, bagClient: bags, machine: device}
|
||||
device.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
result := downloadResult{FailureType: FailureTypeLicenseNotFound}
|
||||
if licensed {
|
||||
result = downloadResult{Items: []downloadItemResult{{Metadata: map[string]interface{}{
|
||||
"softwareVersionExternalIdentifiers": []interface{}{uint64(1001), uint64(1002)},
|
||||
"softwareVersionExternalIdentifier": uint64(1002),
|
||||
}}}}
|
||||
}
|
||||
gomock.InOrder(
|
||||
downloads.EXPECT().Send(gomock.Any()).Return(http.Result[downloadResult]{StatusCode: 200}, nil),
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: 200, Data: bagResult{URLBag: urlBag{RedownloadEndpoint: testRedownloadEndpoint}}}, nil),
|
||||
catalog.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: 200}, nil).Times(3),
|
||||
catalog.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: 200, Data: decodeCatalogResponse(arcadeCatalogResponse)}, 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", "1002"))
|
||||
}).Return(http.Result[downloadResult]{StatusCode: 200, Data: result}, nil),
|
||||
)
|
||||
out, err := store.ListVersions(ListVersionsInput{
|
||||
Account: Account{StoreFront: "143441-1,34"},
|
||||
App: App{ID: 42, BundleID: "com.example.arcade"},
|
||||
})
|
||||
if licensed {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.LatestExternalVersionID).To(Equal("1002"))
|
||||
Expect(out.ExternalVersionIdentifiers).To(Equal([]string{"1001", "1002"}))
|
||||
} else {
|
||||
Expect(err).To(MatchError(ErrLicenseRequired))
|
||||
}
|
||||
},
|
||||
Entry("licensed app", true),
|
||||
Entry("missing license", false),
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/sap/machine"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
const entDownloadPath = "/WebObjects/DownloadDispatch.woa/wa/ent/download"
|
||||
|
||||
type kbsyncGenerator func(context.Context, []byte, uint64) ([]byte, error)
|
||||
|
||||
func defaultKBSyncGenerator(ctx context.Context, hardwareID []byte, dsid uint64) ([]byte, error) {
|
||||
bundle, err := assets.Load(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load SAP assets for kbsync: %w", err)
|
||||
}
|
||||
|
||||
data, err := machine.GenerateKBSync(ctx, bundle, hardwareID, dsid)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate kbsync: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (t *appstore) sendPreferredDownload(ctx context.Context, endpointURL string, acc Account, app App, guid, versionID string, platform Platform) (http.Result[downloadResult], Platform, error) {
|
||||
endpoint, err := newDownloadEndpoint(endpointURL, entDownloadPath)
|
||||
if err != nil {
|
||||
return http.Result[downloadResult]{}, platform, err
|
||||
}
|
||||
|
||||
if platform == "" {
|
||||
platform = PlatformIPhone
|
||||
}
|
||||
|
||||
if versionID == "" {
|
||||
versionID, err = t.lookupLatestExternalVersionID(acc, app, platform)
|
||||
if err != nil {
|
||||
return http.Result[downloadResult]{}, platform, fmt.Errorf("failed to resolve platform version for ent/download: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
res, err := t.sendEntDownload(ctx, endpoint, acc, app, guid, versionID)
|
||||
|
||||
return res, platform, err
|
||||
}
|
||||
|
||||
func (t *appstore) sendEntDownload(ctx context.Context, endpoint downloadProductEndpoint, acc Account, app App, guid, versionID string) (http.Result[downloadResult], error) {
|
||||
hardwareID, err := hex.DecodeString(guid)
|
||||
if err != nil || len(hardwareID) != 6 {
|
||||
return http.Result[downloadResult]{}, errors.New("ent/download requires a six-byte device GUID")
|
||||
}
|
||||
|
||||
dsid, err := strconv.ParseUint(acc.DirectoryServicesID, 10, 64)
|
||||
if err != nil || dsid == 0 {
|
||||
return http.Result[downloadResult]{}, errors.New("ent/download requires a nonzero numeric account DSID")
|
||||
}
|
||||
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
// Asset loading and guest execution also honor this deadline. Each guest
|
||||
// call retains the emulator's existing one-minute execution bound.
|
||||
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return http.Result[downloadResult]{}, fmt.Errorf("ent/download canceled: %w", err)
|
||||
}
|
||||
|
||||
if cached := t.cachedKBSync(dsid, guid); cached != "" {
|
||||
res, err := t.sendEntDownloadRequest(ctx, endpoint, acc, app, guid, versionID, hardwareID, cached)
|
||||
if err == nil {
|
||||
return res, nil
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return res, fmt.Errorf("ent/download canceled: %w", ctx.Err())
|
||||
}
|
||||
|
||||
// Retry a rejected cached blob once, bypassing the cache even if its
|
||||
// persistent entry could not be removed. Fresh blobs are never retried.
|
||||
t.invalidateKBSync(dsid, guid, cached)
|
||||
}
|
||||
|
||||
blob, err := t.generateKBSync(ctx, hardwareID, dsid)
|
||||
if err != nil {
|
||||
return http.Result[downloadResult]{}, err
|
||||
}
|
||||
|
||||
res, err := t.sendEntDownloadRequest(ctx, endpoint, acc, app, guid, versionID, hardwareID, blob)
|
||||
if err == nil {
|
||||
t.storeKBSync(dsid, guid, blob)
|
||||
}
|
||||
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (t *appstore) sendEntDownloadRequest(ctx context.Context, endpoint downloadProductEndpoint, acc Account, app App, guid, versionID string, hardwareID []byte, blob string) (http.Result[downloadResult], error) {
|
||||
serial := append([]byte{0x54, 0xc8, 0xb0, 0xa9, 0x88}, hardwareID[2:]...)
|
||||
request := t.downloadProductRequest(endpoint, acc, app, guid, "")
|
||||
|
||||
requestContext, cancelRequest := context.WithTimeout(ctx, http.DefaultAuthenticationTimeout)
|
||||
defer cancelRequest()
|
||||
|
||||
request.Context = requestContext
|
||||
|
||||
// X-Token must not be forwarded to redirect destinations.
|
||||
request.NoRedirects = true
|
||||
request.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8"
|
||||
request.Headers["User-Agent"] = "Configurator/2.18 (Macintosh; OS X 15.3.2; 24D81) AppleWebKit/0620.2.4.11.6"
|
||||
request.Headers["X-Apple-Store-Front"] = acc.StoreFront
|
||||
request.Headers["X-Token"] = acc.PasswordToken
|
||||
request.Payload = &http.XMLPayload{Content: map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"kbsync": blob,
|
||||
"salableAdamId": strconv.FormatInt(app.ID, 10),
|
||||
"serialNumber": base64.StdEncoding.EncodeToString(serial),
|
||||
"externalVersionId": versionID,
|
||||
}}
|
||||
|
||||
res, err := t.downloadClient.Send(request)
|
||||
if err != nil {
|
||||
return res, fmt.Errorf("send ent/download request: %w", err)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
return res, NewErrorWithMetadata(fmt.Errorf("received ent/download error: %s", res.Data.FailureType), res)
|
||||
}
|
||||
|
||||
if err := validateVersionedDownloadResponse(res, app, versionID, "ent/download"); err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
if res.Data.Items[0].URL == "" {
|
||||
return res, errors.New("ent/download response has no package URL")
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Version the key when the pinned StoreAgent profile or cache format changes.
|
||||
const kbsyncCacheKey = "kbsync-v1"
|
||||
|
||||
type kbsyncCacheEntry struct {
|
||||
DSID uint64 `json:"dsid"`
|
||||
GUID string `json:"guid"`
|
||||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
// Cache a single account/device pair, separately from Account so the blob is
|
||||
// neither exposed in account output nor overwritten by a token refresh.
|
||||
type kbsyncCache struct {
|
||||
mu sync.Mutex
|
||||
entry kbsyncCacheEntry
|
||||
}
|
||||
|
||||
func (t *appstore) generateKBSync(ctx context.Context, hardwareID []byte, dsid uint64) (string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", fmt.Errorf("generate kbsync: %w", err)
|
||||
}
|
||||
|
||||
if t.kbsyncGenerator == nil {
|
||||
return "", errors.New("kbsync generator is unavailable")
|
||||
}
|
||||
|
||||
data, err := t.kbsyncGenerator(ctx, hardwareID, dsid)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generate download kbsync: %w", err)
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", fmt.Errorf("generate kbsync: %w", err)
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
return "", errors.New("generated download kbsync is empty")
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
// Store only blobs that have served a valid ent/download response.
|
||||
func (t *appstore) storeKBSync(dsid uint64, guid, data string) {
|
||||
entry := kbsyncCacheEntry{DSID: dsid, GUID: guid, Data: data}
|
||||
|
||||
t.kbsyncCache.mu.Lock()
|
||||
defer t.kbsyncCache.mu.Unlock()
|
||||
|
||||
t.kbsyncCache.entry = entry
|
||||
if t.keychain != nil {
|
||||
// Cache storage is best effort: an unavailable keychain must not turn
|
||||
// successful generation into a failed download.
|
||||
if encoded, err := json.Marshal(entry); err == nil {
|
||||
_ = t.keychain.Set(kbsyncCacheKey, encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *appstore) cachedKBSync(dsid uint64, guid string) string {
|
||||
t.kbsyncCache.mu.Lock()
|
||||
defer t.kbsyncCache.mu.Unlock()
|
||||
|
||||
entry := t.kbsyncCache.entry
|
||||
if entry.DSID == dsid && entry.GUID == guid && entry.Data != "" {
|
||||
return entry.Data
|
||||
}
|
||||
|
||||
if t.keychain == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
encoded, err := t.keychain.Get(kbsyncCacheKey)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
entry = kbsyncCacheEntry{}
|
||||
if json.Unmarshal(encoded, &entry) != nil || entry.DSID != dsid || entry.GUID != guid {
|
||||
return ""
|
||||
}
|
||||
|
||||
data, err := base64.StdEncoding.DecodeString(entry.Data)
|
||||
if err != nil || len(data) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
t.kbsyncCache.entry = entry
|
||||
|
||||
return entry.Data
|
||||
}
|
||||
|
||||
func (t *appstore) invalidateKBSync(dsid uint64, guid, data string) {
|
||||
t.kbsyncCache.mu.Lock()
|
||||
defer t.kbsyncCache.mu.Unlock()
|
||||
|
||||
rejected := kbsyncCacheEntry{DSID: dsid, GUID: guid, Data: data}
|
||||
if t.kbsyncCache.entry == rejected {
|
||||
t.kbsyncCache.entry = kbsyncCacheEntry{}
|
||||
}
|
||||
|
||||
if t.keychain == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// A concurrent request may have cached a different account or a newer
|
||||
// blob. Only remove the exact entry used by the failed request.
|
||||
encoded, err := t.keychain.Get(kbsyncCacheKey)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var entry kbsyncCacheEntry
|
||||
if json.Unmarshal(encoded, &entry) == nil && entry == rejected {
|
||||
_ = t.keychain.Remove(kbsyncCacheKey)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("Persistent kbsync cache", func() {
|
||||
const guid = "001122334455"
|
||||
const dsid = uint64(123456789)
|
||||
var (
|
||||
chain *keychain.MockKeychain
|
||||
stored []byte
|
||||
readErr, writeErr error
|
||||
removed int
|
||||
blob string
|
||||
newStore func() *appstore
|
||||
)
|
||||
BeforeEach(func() {
|
||||
chain = keychain.NewMockKeychain(gomock.NewController(GinkgoT()))
|
||||
stored = nil
|
||||
readErr, writeErr = nil, nil
|
||||
removed = 0
|
||||
blob = base64.StdEncoding.EncodeToString([]byte("working blob"))
|
||||
chain.EXPECT().Get(kbsyncCacheKey).DoAndReturn(func(string) ([]byte, error) {
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
if stored == nil {
|
||||
return nil, keyring.ErrKeyNotFound
|
||||
}
|
||||
|
||||
return bytes.Clone(stored), nil
|
||||
}).AnyTimes()
|
||||
chain.EXPECT().Set(kbsyncCacheKey, gomock.Any()).DoAndReturn(func(_ string, data []byte) error {
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
stored = bytes.Clone(data)
|
||||
|
||||
return nil
|
||||
}).AnyTimes()
|
||||
chain.EXPECT().Remove(kbsyncCacheKey).DoAndReturn(func(string) error {
|
||||
removed++
|
||||
stored = nil
|
||||
|
||||
return nil
|
||||
}).AnyTimes()
|
||||
newStore = func() *appstore { return &appstore{keychain: chain} }
|
||||
})
|
||||
|
||||
It("reuses a keychain blob in a fresh client with the same account and device", func() {
|
||||
newStore().storeKBSync(dsid, guid, blob)
|
||||
var entry kbsyncCacheEntry
|
||||
Expect(json.Unmarshal(stored, &entry)).To(Succeed())
|
||||
Expect(entry).To(Equal(kbsyncCacheEntry{DSID: dsid, GUID: guid, Data: blob}))
|
||||
Expect(newStore().cachedKBSync(dsid, guid)).To(Equal(blob))
|
||||
})
|
||||
|
||||
DescribeTable("misses for a different account or device", func(nextDSID uint64, nextGUID string) {
|
||||
store := newStore()
|
||||
store.storeKBSync(dsid, guid, blob)
|
||||
Expect(store.cachedKBSync(nextDSID, nextGUID)).To(BeEmpty())
|
||||
Expect(newStore().cachedKBSync(nextDSID, nextGUID)).To(BeEmpty())
|
||||
}, Entry("account changed", dsid+1, guid), Entry("device changed", dsid, "001122334466"))
|
||||
|
||||
DescribeTable("ignores an unusable persistent entry", func(record string) {
|
||||
stored = []byte(record)
|
||||
Expect(newStore().cachedKBSync(dsid, guid)).To(BeEmpty())
|
||||
},
|
||||
Entry("malformed JSON", "{"), Entry("missing identity", `{"data":"YmxvYg=="}`),
|
||||
Entry("invalid base64", `{"dsid":123456789,"guid":"001122334455","data":"!"}`),
|
||||
Entry("empty data", `{"dsid":123456789,"guid":"001122334455","data":""}`),
|
||||
)
|
||||
|
||||
It("does not borrow data from another account when a persistent entry is incomplete", func() {
|
||||
store := newStore()
|
||||
store.storeKBSync(dsid, guid, blob)
|
||||
stored = []byte(`{"dsid":987654321,"guid":"001122334455"}`)
|
||||
Expect(store.cachedKBSync(987654321, guid)).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("keeps the memory cache usable when keychain reads or writes fail", func() {
|
||||
readErr = errors.New("cache read failed")
|
||||
writeErr = errors.New("cache write failed")
|
||||
store := newStore()
|
||||
Expect(store.cachedKBSync(dsid, guid)).To(BeEmpty())
|
||||
store.storeKBSync(dsid, guid, blob)
|
||||
Expect(store.cachedKBSync(dsid, guid)).To(Equal(blob))
|
||||
Expect(stored).To(BeNil())
|
||||
})
|
||||
|
||||
It("does not cache a generated blob before it has been used", func() {
|
||||
store := newStore()
|
||||
store.kbsyncGenerator = func(context.Context, []byte, uint64) ([]byte, error) { return []byte("new blob"), nil }
|
||||
generated, err := store.generateKBSync(context.Background(), nil, dsid)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(generated).NotTo(BeEmpty())
|
||||
Expect(store.cachedKBSync(dsid, guid)).To(BeEmpty())
|
||||
Expect(stored).To(BeNil())
|
||||
})
|
||||
|
||||
It("rejects failed generation and empty blobs", func() {
|
||||
store := newStore()
|
||||
failure := errors.New("guest failed")
|
||||
store.kbsyncGenerator = func(context.Context, []byte, uint64) ([]byte, error) { return nil, failure }
|
||||
_, err := store.generateKBSync(context.Background(), nil, dsid)
|
||||
Expect(errors.Is(err, failure)).To(BeTrue())
|
||||
store.kbsyncGenerator = func(context.Context, []byte, uint64) ([]byte, error) { return nil, nil }
|
||||
_, err = store.generateKBSync(context.Background(), nil, dsid)
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(stored).To(BeNil())
|
||||
})
|
||||
|
||||
It("removes a rejected blob from both caches", func() {
|
||||
store := newStore()
|
||||
store.storeKBSync(dsid, guid, blob)
|
||||
store.invalidateKBSync(dsid, guid, blob)
|
||||
Expect(removed).To(Equal(1))
|
||||
Expect(stored).To(BeNil())
|
||||
Expect(store.cachedKBSync(dsid, guid)).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("clears persistent and in-memory blobs when revoking the account", func() {
|
||||
store := newStore()
|
||||
store.storeKBSync(dsid, guid, blob)
|
||||
chain.EXPECT().Remove("account").Return(nil)
|
||||
Expect(store.Revoke()).To(Succeed())
|
||||
Expect(stored).To(BeNil())
|
||||
Expect(removed).To(Equal(1))
|
||||
Expect(store.cachedKBSync(dsid, guid)).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("does not evict a different account or a newer persisted blob", func() {
|
||||
first := newStore()
|
||||
first.storeKBSync(dsid, guid, blob)
|
||||
newStore().storeKBSync(dsid+1, guid, blob)
|
||||
first.invalidateKBSync(dsid, guid, blob)
|
||||
Expect(removed).To(BeZero())
|
||||
Expect(newStore().cachedKBSync(dsid+1, guid)).To(Equal(blob))
|
||||
|
||||
newer := base64.StdEncoding.EncodeToString([]byte("newer"))
|
||||
newStore().storeKBSync(dsid, guid, newer)
|
||||
first.invalidateKBSync(dsid, guid, blob)
|
||||
Expect(removed).To(BeZero())
|
||||
Expect(newStore().cachedKBSync(dsid, guid)).To(Equal(newer))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,633 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
gohttp "net/http"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
const testEntDownloadEndpoint = "https://downloaddispatch.itunes.apple.com/WebObjects/DownloadDispatch.woa/wa/ent/download"
|
||||
|
||||
var _ = Describe("AppStore (preferred kbsync download)", func() {
|
||||
const guid = "001122334455"
|
||||
const versionID = "123456789"
|
||||
var (
|
||||
store *appstore
|
||||
downloads *http.MockClient[downloadResult]
|
||||
bags *http.MockClient[bagResult]
|
||||
platforms *http.MockClient[platformVersionLookupResult]
|
||||
account Account
|
||||
app App
|
||||
bag bagResult
|
||||
empty, unavailable, success http.Result[downloadResult]
|
||||
generated int
|
||||
)
|
||||
BeforeEach(func() {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
downloads = http.NewMockClient[downloadResult](ctrl)
|
||||
bags = http.NewMockClient[bagResult](ctrl)
|
||||
platforms = http.NewMockClient[platformVersionLookupResult](ctrl)
|
||||
generated = 0
|
||||
store = &appstore{
|
||||
downloadClient: downloads, bagClient: bags, platformClient: platforms,
|
||||
kbsyncGenerator: func(ctx context.Context, hardwareID []byte, dsid uint64) ([]byte, error) {
|
||||
Expect(ctx.Err()).NotTo(HaveOccurred())
|
||||
deadline, ok := ctx.Deadline()
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(time.Until(deadline)).To(BeNumerically("<=", 2*time.Minute))
|
||||
Expect(hardwareID).To(Equal([]byte{0, 0x11, 0x22, 0x33, 0x44, 0x55}))
|
||||
Expect(dsid).To(Equal(uint64(123456789012)))
|
||||
generated++
|
||||
|
||||
return []byte("kbsync blob"), nil
|
||||
},
|
||||
}
|
||||
account = Account{DirectoryServicesID: "123456789012", PasswordToken: "test-token", StoreFront: "143441-1,29"}
|
||||
app = App{ID: 42, BundleID: "com.example.app"}
|
||||
bag = bagResult{URLBag: urlBag{EntDownloadEndpoint: testEntDownloadEndpoint}}
|
||||
empty = http.Result[downloadResult]{StatusCode: gohttp.StatusOK}
|
||||
unavailable = http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{CustomerMessage: "App No Longer Available"}}
|
||||
success = http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{Items: []downloadItemResult{{
|
||||
URL: "https://example.com/app.ipa",
|
||||
Metadata: map[string]interface{}{"itemId": int64(42), "softwareVersionExternalIdentifier": versionID, "softwareVersionBundleId": app.BundleID},
|
||||
}}}}
|
||||
})
|
||||
|
||||
It("sends kbsync to the full ent endpoint advertised in Apple's bag", func() {
|
||||
var decoded bagResult
|
||||
_, err := plist.Unmarshal([]byte(`<?xml version="1.0"?><plist version="1.0"><dict><key>urlBag</key><dict><key>volumeStoreDownloadProduct</key><string>`+testEntDownloadEndpoint+`</string></dict></dict></plist>`), &decoded)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(decoded.URLBag.EntDownloadEndpoint).To(Equal(testEntDownloadEndpoint))
|
||||
gomock.InOrder(
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: decoded}, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testEntDownloadEndpoint + "?guid=" + guid))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("kbsync", base64.StdEncoding.EncodeToString([]byte("kbsync blob"))))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(Equal(1))
|
||||
})
|
||||
|
||||
It("enables kbsync generation for normal clients", func() {
|
||||
Expect(NewAppStore(Args{}).(*appstore).kbsyncGenerator).NotTo(BeNil())
|
||||
})
|
||||
|
||||
It("uses volumeStore when the bag omits ent/download", func() {
|
||||
bag.URLBag.EntDownloadEndpoint = ""
|
||||
gomock.InOrder(
|
||||
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(ContainSubstring("volumeStoreDownloadProduct"))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(BeZero())
|
||||
})
|
||||
|
||||
It("keeps volumeStore usable when the initial bag request fails", func() {
|
||||
gomock.InOrder(
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{}, errors.New("bag unavailable")),
|
||||
downloads.EXPECT().Send(gomock.Any()).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(BeZero())
|
||||
})
|
||||
|
||||
It("falls back when generation is unavailable", func() {
|
||||
store.kbsyncGenerator = func(context.Context, []byte, uint64) ([]byte, error) {
|
||||
return nil, errors.New("guest unavailable")
|
||||
}
|
||||
gomock.InOrder(
|
||||
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(ContainSubstring("volumeStoreDownloadProduct"))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
})
|
||||
|
||||
DescribeTable("falls back from unusable ent/download responses", func(outcome string) {
|
||||
response := empty
|
||||
var responseErr error
|
||||
switch outcome {
|
||||
case "unavailable":
|
||||
response = unavailable
|
||||
case "HTML 403":
|
||||
responseErr = &http.UnexpectedResponseError{StatusCode: gohttp.StatusForbidden}
|
||||
case "HTTP 500":
|
||||
responseErr = &http.UnexpectedResponseError{StatusCode: gohttp.StatusInternalServerError}
|
||||
case "timeout":
|
||||
responseErr = &http.TransportError{Err: context.DeadlineExceeded}
|
||||
case "wrong app", "wrong version", "missing URL":
|
||||
response = http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{Items: []downloadItemResult{{
|
||||
URL: "https://example.com/wrong.ipa", Metadata: map[string]interface{}{
|
||||
"itemId": int64(42), "softwareVersionExternalIdentifier": versionID, "softwareVersionBundleId": app.BundleID,
|
||||
},
|
||||
}}}}
|
||||
switch outcome {
|
||||
case "wrong app":
|
||||
response.Data.Items[0].Metadata["itemId"] = int64(99)
|
||||
case "wrong version":
|
||||
response.Data.Items[0].Metadata["softwareVersionExternalIdentifier"] = "other"
|
||||
default:
|
||||
response.Data.Items[0].URL = ""
|
||||
}
|
||||
}
|
||||
|
||||
gomock.InOrder(
|
||||
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(testEntDownloadEndpoint + "?guid=" + guid))
|
||||
}).Return(response, responseErr),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(ContainSubstring("volumeStoreDownloadProduct"))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", versionID))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(Equal(1))
|
||||
},
|
||||
Entry("empty song list", "empty"), Entry("unavailable", "unavailable"), Entry("HTML 403", "HTML 403"),
|
||||
Entry("HTTP 500", "HTTP 500"), Entry("timeout", "timeout"), Entry("wrong app", "wrong app"),
|
||||
Entry("wrong version", "wrong version"), Entry("missing package URL", "missing URL"),
|
||||
)
|
||||
|
||||
It("retains the complete legacy chain and reuses the bag after an ent/download miss", func() {
|
||||
bag.URLBag.RedownloadEndpoint = testRedownloadEndpoint
|
||||
bag.URLBag.UpdateEndpoint = testUpdateEndpoint
|
||||
gomock.InOrder(
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Return(unavailable, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(ContainSubstring("volumeStoreDownloadProduct"))
|
||||
}).Return(empty, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testRedownloadEndpoint + "?guid=" + guid))
|
||||
}).Return(unavailable, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testUpdateEndpoint + "?guid=" + guid))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(Equal(1))
|
||||
})
|
||||
|
||||
DescribeTable("tries ent/download first for a pinned version",
|
||||
func(platform Platform) {
|
||||
fetched := bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil)
|
||||
downloads.EXPECT().Send(gomock.Any()).After(fetched).Do(func(req http.Request) {
|
||||
Expect(generated).To(Equal(1))
|
||||
Expect(req.URL).To(Equal(testEntDownloadEndpoint + "?guid=" + guid))
|
||||
Expect(req.Method).To(Equal(http.MethodPOST))
|
||||
Expect(req.NoRedirects).To(BeTrue())
|
||||
Expect(req.Context.Err()).NotTo(HaveOccurred())
|
||||
deadline, ok := req.Context.Deadline()
|
||||
Expect(ok).To(BeTrue())
|
||||
Expect(time.Until(deadline)).To(BeNumerically("<=", 30*time.Second))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("X-Token", account.PasswordToken))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("X-Dsid", account.DirectoryServicesID))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("iCloud-DSID", account.DirectoryServicesID))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("X-Apple-Store-Front", account.StoreFront))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"))
|
||||
Expect(req.Headers["User-Agent"]).To(HavePrefix("Configurator/2.18 "))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(Equal(map[string]interface{}{
|
||||
"creditDisplay": "", "guid": guid, "salableAdamId": "42", "externalVersionId": versionID,
|
||||
"serialNumber": base64.StdEncoding.EncodeToString([]byte{0x54, 0xc8, 0xb0, 0xa9, 0x88, 0x22, 0x33, 0x44, 0x55}),
|
||||
"kbsync": base64.StdEncoding.EncodeToString([]byte("kbsync blob")),
|
||||
}))
|
||||
}).Return(success, nil)
|
||||
actual, resolved, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, platform)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(resolved).To(Equal(platform))
|
||||
},
|
||||
Entry("iPhone", PlatformIPhone), Entry("iPad", PlatformIPad), Entry("macOS", PlatformMacOS),
|
||||
Entry("tvOS", PlatformAppleTV), Entry("visionOS", PlatformVisionOS),
|
||||
Entry("watchOS", PlatformWatchOS),
|
||||
)
|
||||
|
||||
It("pins the iOS offer before trying ent/download", func() {
|
||||
gomock.InOrder(
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
platforms.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: platformVersionLookupResult{
|
||||
Results: map[string]platformVersionLookupItem{"42": {Offers: []platformVersionLookupOffer{{Version: platformVersionLookupVersion{ExternalID: platformVersionExternalID(versionID)}}}}},
|
||||
}}, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", versionID))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, platform, err := store.sendDownloadProduct(context.Background(), account, app, guid, "", "")
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(platform).To(Equal(PlatformIPhone))
|
||||
})
|
||||
|
||||
It("pins the native Mac offer before trying ent/download for a universal app", func() {
|
||||
pages := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
|
||||
store.storefrontClient = pages
|
||||
account.StoreFront = "143443-2,34"
|
||||
app = App{ID: 6472431552, BundleID: "com.nebula.karing"}
|
||||
success.Data.Items[0].Metadata = map[string]interface{}{
|
||||
"itemId": app.ID, "softwareVersionExternalIdentifier": "876660716", "softwareVersionBundleId": app.BundleID,
|
||||
}
|
||||
gomock.InOrder(
|
||||
pages.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: gohttp.StatusOK, Data: macVersionPage(karingMacConfiguration)}, 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(testEntDownloadEndpoint + "?guid=" + guid))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", "876660716"))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, platform, err := store.sendDownloadProduct(context.Background(), account, app, guid, "", PlatformMacOS)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(platform).To(Equal(PlatformMacOS))
|
||||
})
|
||||
|
||||
It("uses ent/download when listing versions", func() {
|
||||
device := machine.NewMockMachine(gomock.NewController(GinkgoT()))
|
||||
store.machine = device
|
||||
device.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
success.Data.Items[0].Metadata["softwareVersionExternalIdentifiers"] = []interface{}{"123456788", versionID}
|
||||
gomock.InOrder(
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
platforms.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: platformVersionLookupResult{
|
||||
Results: map[string]platformVersionLookupItem{"42": {Offers: []platformVersionLookupOffer{{Version: platformVersionLookupVersion{ExternalID: platformVersionExternalID(versionID)}}}}},
|
||||
}}, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testEntDownloadEndpoint + "?guid=" + guid))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
result, err := store.ListVersions(ListVersionsInput{Account: account, App: app})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(result.ExternalVersionIdentifiers).To(Equal([]string{"123456788", versionID}))
|
||||
Expect(result.LatestExternalVersionID).To(Equal(versionID))
|
||||
})
|
||||
|
||||
DescribeTable("rejects invalid bag destinations before generating or sending credentials", func(endpoint string) {
|
||||
bag.URLBag.EntDownloadEndpoint = endpoint
|
||||
_, _, err := store.sendPreferredDownload(context.Background(), bag.URLBag.EntDownloadEndpoint, account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).To(MatchError("invalid download endpoint in bag"))
|
||||
Expect(generated).To(BeZero())
|
||||
},
|
||||
Entry("HTTP", "http://downloaddispatch.itunes.apple.com/WebObjects/DownloadDispatch.woa/wa/ent/download"),
|
||||
Entry("foreign host", "https://example.com/WebObjects/DownloadDispatch.woa/wa/ent/download"),
|
||||
Entry("lookalike host", "https://downloaddispatch.itunes.apple.com.example.com/WebObjects/DownloadDispatch.woa/wa/ent/download"),
|
||||
Entry("credentials", "https://user@downloaddispatch.itunes.apple.com/WebObjects/DownloadDispatch.woa/wa/ent/download"),
|
||||
Entry("query", testEntDownloadEndpoint+"?guid=other"), Entry("fragment", testEntDownloadEndpoint+"#fragment"),
|
||||
Entry("wrong path", testUpdateEndpoint),
|
||||
Entry("abbreviated path", "https://downloaddispatch.itunes.apple.com/ent/download"),
|
||||
Entry("encoded path", "https://downloaddispatch.itunes.apple.com/WebObjects/DownloadDispatch.woa/wa/ent/%64ownload"),
|
||||
)
|
||||
|
||||
DescribeTable("validates the app, version and bundle before accepting ent/download", func(field string, value interface{}, expected string) {
|
||||
success.Data.Items[0].Metadata[field] = value
|
||||
downloads.EXPECT().Send(gomock.Any()).Return(success, nil)
|
||||
_, _, err := store.sendPreferredDownload(context.Background(), bag.URLBag.EntDownloadEndpoint, account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).To(MatchError(ContainSubstring(expected)))
|
||||
},
|
||||
Entry("wrong app", "itemId", int64(99), "requested app or version"),
|
||||
Entry("wrong version", "softwareVersionExternalIdentifier", "987654321", "requested app or version"),
|
||||
Entry("wrong bundle", "softwareVersionBundleId", "com.other.app", "requested bundle identifier"),
|
||||
Entry("missing bundle", "softwareVersionBundleId", nil, "requested bundle identifier"),
|
||||
)
|
||||
|
||||
DescribeTable("preserves authentication and license failures from the fallback", func(failure string) {
|
||||
response := http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{FailureType: failure}}
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil)
|
||||
gomock.InOrder(
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testEntDownloadEndpoint + "?guid=" + guid))
|
||||
}).Return(response, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(ContainSubstring("volumeStoreDownloadProduct"))
|
||||
}).Return(response, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(response))
|
||||
}, Entry("expired token", FailureTypePasswordTokenExpired), Entry("missing license", FailureTypeLicenseNotFound))
|
||||
|
||||
It("stops before generating when canceled", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, _, err := store.sendDownloadProduct(ctx, account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(generated).To(BeZero())
|
||||
})
|
||||
|
||||
It("reports generation failures without sending the token", func() {
|
||||
failure := errors.New("guest failed")
|
||||
store.kbsyncGenerator = func(context.Context, []byte, uint64) ([]byte, error) { return nil, failure }
|
||||
_, _, err := store.sendPreferredDownload(context.Background(), bag.URLBag.EntDownloadEndpoint, account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(errors.Is(err, failure)).To(BeTrue())
|
||||
})
|
||||
|
||||
It("does not start the legacy chain after cancellation during generation", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil)
|
||||
store.kbsyncGenerator = func(context.Context, []byte, uint64) ([]byte, error) {
|
||||
cancel()
|
||||
|
||||
return nil, context.Canceled
|
||||
}
|
||||
_, _, err := store.sendDownloadProduct(ctx, account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
})
|
||||
|
||||
It("preserves unpinned legacy downloads when the preferred offer lookup fails", func() {
|
||||
gomock.InOrder(
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
|
||||
platforms.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{}, errors.New("catalog unavailable")),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(ContainSubstring("volumeStoreDownloadProduct"))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).NotTo(HaveKey("externalVersionId"))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, "", PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(BeZero())
|
||||
})
|
||||
|
||||
It("does not send credentials to an invalid preferred endpoint and falls back", func() {
|
||||
bag.URLBag.EntDownloadEndpoint = "https://example.com/WebObjects/DownloadDispatch.woa/wa/ent/download"
|
||||
gomock.InOrder(
|
||||
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(ContainSubstring("volumeStoreDownloadProduct"))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(BeZero())
|
||||
})
|
||||
|
||||
Describe("retrying cached kbsync", func() {
|
||||
const dsid = uint64(123456789012)
|
||||
var (
|
||||
stored []byte
|
||||
cachedBlob, freshBlob string
|
||||
removed, saved int
|
||||
removeErr error
|
||||
request func(string) *gomock.Call
|
||||
failure func(string) (http.Result[downloadResult], error)
|
||||
)
|
||||
BeforeEach(func() {
|
||||
cachedBlob = base64.StdEncoding.EncodeToString([]byte("cached blob"))
|
||||
freshBlob = base64.StdEncoding.EncodeToString([]byte("kbsync blob"))
|
||||
var err error
|
||||
stored, err = json.Marshal(kbsyncCacheEntry{DSID: dsid, GUID: guid, Data: cachedBlob})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
removed, saved = 0, 0
|
||||
removeErr = nil
|
||||
chain := keychain.NewMockKeychain(gomock.NewController(GinkgoT()))
|
||||
store.keychain = chain
|
||||
chain.EXPECT().Get(kbsyncCacheKey).DoAndReturn(func(string) ([]byte, error) {
|
||||
return bytes.Clone(stored), nil
|
||||
}).AnyTimes()
|
||||
chain.EXPECT().Remove(kbsyncCacheKey).DoAndReturn(func(string) error {
|
||||
removed++
|
||||
if removeErr != nil {
|
||||
return removeErr
|
||||
}
|
||||
stored = nil
|
||||
|
||||
return nil
|
||||
}).AnyTimes()
|
||||
chain.EXPECT().Set(kbsyncCacheKey, gomock.Any()).DoAndReturn(func(_ string, data []byte) error {
|
||||
saved++
|
||||
stored = bytes.Clone(data)
|
||||
|
||||
return nil
|
||||
}).AnyTimes()
|
||||
bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil).AnyTimes()
|
||||
request = func(blob string) *gomock.Call {
|
||||
return downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testEntDownloadEndpoint + "?guid=" + guid))
|
||||
Expect(req.NoRedirects).To(BeTrue())
|
||||
Expect(req.Context.Err()).NotTo(HaveOccurred())
|
||||
Expect(req.Headers).To(HaveKeyWithValue("X-Token", account.PasswordToken))
|
||||
payload := req.Payload.(*http.XMLPayload).Content
|
||||
Expect(payload).To(HaveKeyWithValue("kbsync", blob))
|
||||
Expect(payload).To(HaveKeyWithValue("externalVersionId", versionID))
|
||||
})
|
||||
}
|
||||
failure = func(outcome string) (http.Result[downloadResult], error) {
|
||||
switch outcome {
|
||||
case "HTTP 500":
|
||||
return http.Result[downloadResult]{StatusCode: gohttp.StatusInternalServerError}, nil
|
||||
case "HTML 403":
|
||||
return http.Result[downloadResult]{}, &http.UnexpectedResponseError{StatusCode: gohttp.StatusForbidden}
|
||||
case "timeout":
|
||||
return http.Result[downloadResult]{}, &http.TransportError{Err: context.DeadlineExceeded}
|
||||
case "unavailable":
|
||||
return unavailable, nil
|
||||
case "structured failure":
|
||||
return http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{FailureType: FailureTypePasswordTokenExpired}}, nil
|
||||
case "missing URL", "wrong version":
|
||||
response := http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{Items: []downloadItemResult{{
|
||||
Metadata: map[string]interface{}{"itemId": app.ID, "softwareVersionExternalIdentifier": versionID, "softwareVersionBundleId": app.BundleID},
|
||||
}}}}
|
||||
if outcome == "wrong version" {
|
||||
response.Data.Items[0].URL = "https://example.com/wrong.ipa"
|
||||
response.Data.Items[0].Metadata["softwareVersionExternalIdentifier"] = "other"
|
||||
}
|
||||
|
||||
return response, nil
|
||||
default:
|
||||
return empty, nil
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
It("uses a working persistent blob without generating or rewriting it", func() {
|
||||
request(cachedBlob).Return(success, nil)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(BeZero())
|
||||
Expect(removed).To(BeZero())
|
||||
Expect(saved).To(BeZero())
|
||||
})
|
||||
|
||||
It("saves an uncached blob only after success and reuses it in a new client", func() {
|
||||
stored = nil
|
||||
request(freshBlob).Do(func(http.Request) {
|
||||
Expect(stored).To(BeNil())
|
||||
Expect(saved).To(BeZero())
|
||||
}).Return(success, nil)
|
||||
_, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(saved).To(Equal(1))
|
||||
restarted := &appstore{
|
||||
keychain: store.keychain, downloadClient: downloads, bagClient: bags,
|
||||
kbsyncGenerator: func(context.Context, []byte, uint64) ([]byte, error) {
|
||||
Fail("the new client must reuse the successful blob")
|
||||
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
request(freshBlob).Return(success, nil)
|
||||
_, _, err = restarted.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(generated).To(Equal(1))
|
||||
Expect(saved).To(Equal(1))
|
||||
})
|
||||
|
||||
DescribeTable("retries a failed cached blob and saves a successful replacement", func(outcome string) {
|
||||
response, responseErr := failure(outcome)
|
||||
var firstContext context.Context
|
||||
gomock.InOrder(
|
||||
request(cachedBlob).Do(func(req http.Request) { firstContext = req.Context }).Return(response, responseErr),
|
||||
request(freshBlob).Do(func(req http.Request) {
|
||||
Expect(removed).To(Equal(1))
|
||||
Expect(stored).To(BeNil())
|
||||
Expect(saved).To(BeZero())
|
||||
Expect(firstContext.Err()).To(HaveOccurred())
|
||||
Expect(req.Context).NotTo(Equal(firstContext))
|
||||
Expect(store.cachedKBSync(dsid, guid)).To(BeEmpty())
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(Equal(1))
|
||||
Expect(saved).To(Equal(1))
|
||||
var entry kbsyncCacheEntry
|
||||
Expect(json.Unmarshal(stored, &entry)).To(Succeed())
|
||||
Expect(entry).To(Equal(kbsyncCacheEntry{DSID: dsid, GUID: guid, Data: freshBlob}))
|
||||
Expect(store.cachedKBSync(dsid, guid)).To(Equal(freshBlob))
|
||||
request(freshBlob).Return(success, nil)
|
||||
_, _, err = store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(generated).To(Equal(1))
|
||||
Expect(saved).To(Equal(1))
|
||||
},
|
||||
Entry("server error", "HTTP 500"), Entry("non-plist error", "HTML 403"), Entry("request timeout", "timeout"),
|
||||
Entry("empty response", "empty"), Entry("availability error", "unavailable"), Entry("Apple failure", "structured failure"),
|
||||
Entry("missing URL", "missing URL"), Entry("wrong version", "wrong version"),
|
||||
)
|
||||
|
||||
DescribeTable("falls back without caching or retrying a failed fresh blob", func(outcome string, hasCache bool) {
|
||||
if hasCache {
|
||||
request(cachedBlob).Return(empty, nil)
|
||||
} else {
|
||||
stored = nil
|
||||
}
|
||||
response, responseErr := failure(outcome)
|
||||
gomock.InOrder(
|
||||
request(freshBlob).Return(response, responseErr),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(ContainSubstring("volumeStoreDownloadProduct"))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(Equal(1))
|
||||
Expect(saved).To(BeZero())
|
||||
Expect(stored).To(BeNil())
|
||||
Expect(store.cachedKBSync(dsid, guid)).To(BeEmpty())
|
||||
},
|
||||
Entry("server error", "HTTP 500", true), Entry("non-plist error", "HTML 403", true), Entry("timeout", "timeout", true),
|
||||
Entry("empty response", "empty", true), Entry("availability error", "unavailable", true),
|
||||
Entry("Apple failure", "structured failure", true), Entry("missing URL", "missing URL", true), Entry("wrong version", "wrong version", true),
|
||||
Entry("no existing cache", "HTTP 500", false), Entry("uncached Apple failure", "structured failure", false),
|
||||
)
|
||||
|
||||
It("falls back when regeneration fails", func() {
|
||||
store.kbsyncGenerator = func(context.Context, []byte, uint64) ([]byte, error) {
|
||||
Expect(removed).To(Equal(1))
|
||||
|
||||
return nil, errors.New("guest failed")
|
||||
}
|
||||
gomock.InOrder(
|
||||
request(cachedBlob).Return(empty, nil),
|
||||
downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.URL).To(ContainSubstring("volumeStoreDownloadProduct"))
|
||||
}).Return(success, nil),
|
||||
)
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(saved).To(BeZero())
|
||||
Expect(stored).To(BeNil())
|
||||
})
|
||||
|
||||
It("bypasses the old blob even if its keychain entry cannot be removed", func() {
|
||||
removeErr = errors.New("keychain unavailable")
|
||||
gomock.InOrder(request(cachedBlob).Return(empty, nil), request(freshBlob).Return(success, nil))
|
||||
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(actual).To(Equal(success))
|
||||
Expect(generated).To(Equal(1))
|
||||
Expect(removed).To(Equal(1))
|
||||
Expect(saved).To(Equal(1))
|
||||
Expect(store.cachedKBSync(dsid, guid)).To(Equal(freshBlob))
|
||||
})
|
||||
|
||||
It("does not regenerate or fall back when the cached request is canceled", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
request(cachedBlob).Do(func(http.Request) { cancel() }).Return(http.Result[downloadResult]{}, context.Canceled)
|
||||
_, _, err := store.sendDownloadProduct(ctx, account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(generated).To(BeZero())
|
||||
Expect(removed).To(BeZero())
|
||||
Expect(saved).To(BeZero())
|
||||
})
|
||||
|
||||
It("does not use the cached blob when already canceled", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, _, err := store.sendPreferredDownload(ctx, testEntDownloadEndpoint, account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(generated).To(BeZero())
|
||||
Expect(removed).To(BeZero())
|
||||
})
|
||||
|
||||
It("stops without saving or falling back when regeneration is canceled", func() {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
request(cachedBlob).Return(empty, nil)
|
||||
store.kbsyncGenerator = func(context.Context, []byte, uint64) ([]byte, error) {
|
||||
cancel()
|
||||
|
||||
return []byte("canceled blob"), nil
|
||||
}
|
||||
_, _, err := store.sendDownloadProduct(ctx, account, app, guid, versionID, PlatformIPhone)
|
||||
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
|
||||
Expect(removed).To(Equal(1))
|
||||
Expect(saved).To(BeZero())
|
||||
Expect(stored).To(BeNil())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,16 +1,17 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type ListVersionsInput struct {
|
||||
Account Account
|
||||
App App
|
||||
Context context.Context
|
||||
Account Account
|
||||
App App
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
type ListVersionsOutput struct {
|
||||
@@ -19,6 +20,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, PlatformWatchOS, 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 +38,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, PlatformWatchOS, 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.Context, input.Account, input.App, guid, externalVersionID, platform)
|
||||
if err != nil {
|
||||
return ListVersionsOutput{}, err
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired || res.Data.FailureType == FailureTypeSignInRequired {
|
||||
@@ -41,7 +64,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 +98,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,64 @@ 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("pins the watchOS version before requesting version history", func() {
|
||||
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
|
||||
gomock.InOrder(
|
||||
mockPlatformClient.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: platformVersionLookupResult{Results: map[string]platformVersionLookupItem{
|
||||
"42": {Offers: []platformVersionLookupOffer{{Version: platformVersionLookupVersion{ExternalID: "123456"}}}},
|
||||
}},
|
||||
}, nil),
|
||||
mockDownloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", "123456"))
|
||||
}).Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{Items: []downloadItemResult{{Metadata: map[string]interface{}{
|
||||
"softwareVersionExternalIdentifiers": []interface{}{uint64(123455), uint64(123456)},
|
||||
"softwareVersionExternalIdentifier": uint64(123456),
|
||||
}}}}}, nil),
|
||||
)
|
||||
out, err := as.ListVersions(ListVersionsInput{Account: Account{StoreFront: "143441"}, App: App{ID: 42}, Platform: PlatformWatchOS})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.ExternalVersionIdentifiers).To(Equal([]string{"123455", "123456"}))
|
||||
Expect(out.LatestExternalVersionID).To(Equal("123456"))
|
||||
})
|
||||
|
||||
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 +274,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 +350,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"
|
||||
|
||||
+273
-30
@@ -1,21 +1,34 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAuthCodeRequired = errors.New("auth code is required")
|
||||
)
|
||||
|
||||
const (
|
||||
maxAuthenticationRequestAttempts = 3
|
||||
maxAuthenticationRedirects = 4
|
||||
authenticationRetryDelay = 10 * time.Second
|
||||
maxAuthenticationRetryDelay = 30 * time.Second
|
||||
)
|
||||
|
||||
type LoginInput struct {
|
||||
Email string
|
||||
Password string
|
||||
@@ -30,6 +43,11 @@ type LoginOutput struct {
|
||||
}
|
||||
|
||||
func (t *appstore) Login(input LoginInput) (LoginOutput, error) {
|
||||
authCode, err := normalizeAuthCode(input.AuthCode)
|
||||
if err != nil {
|
||||
return LoginOutput{}, err
|
||||
}
|
||||
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return LoginOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
@@ -58,7 +76,7 @@ func (t *appstore) Login(input LoginInput) (LoginOutput, error) {
|
||||
return LoginOutput{}, errors.New("SAP action signer factory returned nil")
|
||||
}
|
||||
|
||||
acc, loginErr := t.login(input.Email, input.Password, input.AuthCode, guid, bag.SAPConfig.AuthEndpoint, signer)
|
||||
acc, loginErr := t.login(input.Email, input.Password, authCode, guid, bag.SAPConfig.AuthEndpoint, signer)
|
||||
closeErr := signer.Close()
|
||||
|
||||
if closeErr != nil {
|
||||
@@ -81,6 +99,32 @@ func (t *appstore) Login(input LoginInput) (LoginOutput, error) {
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func normalizeAuthCode(code string) (string, error) {
|
||||
if code == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// Terminals may wrap pasted input in bracketed-paste markers. Strip only
|
||||
// a matched outer pair; other escape sequences are invalid input.
|
||||
code = strings.TrimSpace(code)
|
||||
if strings.HasPrefix(code, "\x1b[200~") && strings.HasSuffix(code, "\x1b[201~") {
|
||||
code = strings.TrimSuffix(strings.TrimPrefix(code, "\x1b[200~"), "\x1b[201~")
|
||||
}
|
||||
|
||||
code = strings.Map(func(r rune) rune {
|
||||
if unicode.IsSpace(r) {
|
||||
return -1
|
||||
}
|
||||
|
||||
return r
|
||||
}, code)
|
||||
if len(code) != 6 || strings.IndexFunc(code, func(r rune) bool { return r < '0' || r > '9' }) != -1 {
|
||||
return "", errors.New("2FA code must contain exactly six digits")
|
||||
}
|
||||
|
||||
return code, nil
|
||||
}
|
||||
|
||||
type loginAddressResult struct {
|
||||
FirstName string `plist:"firstName,omitempty"`
|
||||
LastName string `plist:"lastName,omitempty"`
|
||||
@@ -100,38 +144,54 @@ type loginResult struct {
|
||||
}
|
||||
|
||||
func (t *appstore) login(email, password, authCode, guid, endpoint string, signer ActionSigner) (Account, error) {
|
||||
redirect := ""
|
||||
request := t.loginRequest(email, password, authCode, guid, endpoint, 1, signer)
|
||||
redirects := 0
|
||||
|
||||
var (
|
||||
err error
|
||||
res http.Result[loginResult]
|
||||
)
|
||||
|
||||
retry := true
|
||||
|
||||
for attempt := 1; retry && attempt <= 4; attempt++ {
|
||||
requestAttempt := attempt
|
||||
if redirect != "" {
|
||||
// The pod redirect is part of the same authentication attempt. Apple
|
||||
// expects the original XML plist body, including its attempt value.
|
||||
requestAttempt = 1
|
||||
}
|
||||
|
||||
request := t.loginRequest(email, password, authCode, guid, endpoint, requestAttempt, signer)
|
||||
request.URL, _ = util.IfEmpty(redirect, request.URL), ""
|
||||
res, err = t.loginClient.Send(request)
|
||||
for attempt := 1; ; {
|
||||
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 redirects > 0 {
|
||||
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 {
|
||||
retry, redirect, err := t.parseLoginResponse(&res, attempt, authCode, request.URL)
|
||||
if err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if retry {
|
||||
return Account{}, NewErrorWithMetadata(errors.New("too many attempts"), res)
|
||||
if !retry {
|
||||
break
|
||||
}
|
||||
|
||||
if redirect != "" {
|
||||
if redirects == maxAuthenticationRedirects {
|
||||
return Account{}, authenticationRedirectError(errors.New("too many authentication redirects"), res.StatusCode, redirect)
|
||||
}
|
||||
|
||||
redirects++
|
||||
// Only the destination changes: redirects belong to the same login
|
||||
// attempt and must retain its payload, including the attempt value.
|
||||
request.URL = redirect
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
attempt++
|
||||
request = t.loginRequest(email, password, authCode, guid, request.URL, attempt, signer)
|
||||
}
|
||||
|
||||
sf, err := res.GetHeader(HTTPHeaderStoreFront)
|
||||
@@ -168,25 +228,138 @@ func (t *appstore) login(email, password, authCode, guid, endpoint string, signe
|
||||
return acc, nil
|
||||
}
|
||||
|
||||
func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int, authCode string) (bool, string, error) {
|
||||
func (t *appstore) sendAuthenticationRequest(request http.Request) (http.Result[loginResult], error) {
|
||||
statuses := make([]string, 0, maxAuthenticationRequestAttempts)
|
||||
onlyHTTP := true
|
||||
|
||||
sleep := t.authRetrySleep
|
||||
if sleep == nil {
|
||||
sleep = time.Sleep
|
||||
}
|
||||
|
||||
for attempt := 1; ; attempt++ {
|
||||
result, err := t.loginClient.Send(request)
|
||||
|
||||
status, retry := retryableAuthenticationError(err)
|
||||
if !retry {
|
||||
if err != nil {
|
||||
return result, authenticationRequestError(err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
outcome := fmt.Sprintf("HTTP %d", status)
|
||||
if status == 0 {
|
||||
outcome = "transport error"
|
||||
onlyHTTP = false
|
||||
}
|
||||
|
||||
statuses = append(statuses, outcome)
|
||||
|
||||
if attempt == maxAuthenticationRequestAttempts {
|
||||
summary := strings.Join(statuses, ", ")
|
||||
if onlyHTTP {
|
||||
// Preserve the existing diagnostic format for HTTP-only failures.
|
||||
summary = strings.ReplaceAll(summary, ", HTTP ", ", ")
|
||||
}
|
||||
|
||||
return result, fmt.Errorf(
|
||||
"authentication request failed after %d attempts (%s): %w",
|
||||
maxAuthenticationRequestAttempts, summary, authenticationRequestError(err),
|
||||
)
|
||||
}
|
||||
|
||||
delay := min(authenticationRetryDelay<<(attempt-1), maxAuthenticationRetryDelay)
|
||||
|
||||
var (
|
||||
responseErr *http.UnexpectedResponseError
|
||||
transportErr *http.TransportError
|
||||
retryAfter string
|
||||
)
|
||||
|
||||
if errors.As(err, &responseErr) {
|
||||
retryAfter = responseErr.RetryAfter
|
||||
} else if errors.As(err, &transportErr) {
|
||||
retryAfter = transportErr.RetryAfter
|
||||
}
|
||||
|
||||
if requested, ok := authenticationRetryAfter(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)
|
||||
}
|
||||
}
|
||||
|
||||
func retryableAuthenticationError(err error) (int, bool) {
|
||||
var responseErr *http.UnexpectedResponseError
|
||||
if !errors.As(err, &responseErr) {
|
||||
var transportErr *http.TransportError
|
||||
if !errors.As(err, &transportErr) || errors.Is(err, context.Canceled) {
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// A url.Error can report Timeout false when its cause is wrapped by
|
||||
// AddHeaderTransport, so inspect each underlying error as well.
|
||||
for cause := transportErr.Err; cause != nil; cause = errors.Unwrap(cause) {
|
||||
if networkErr, ok := cause.(net.Error); ok && networkErr.Timeout() {
|
||||
return 0, true
|
||||
}
|
||||
}
|
||||
|
||||
return 0, errors.Is(transportErr, io.EOF) || errors.Is(transportErr, io.ErrUnexpectedEOF) ||
|
||||
errors.Is(transportErr, syscall.ECONNRESET) || errors.Is(transportErr, syscall.EPIPE)
|
||||
}
|
||||
|
||||
status := responseErr.StatusCode
|
||||
// A Store pod can transiently return an HTML 403 page. Populated Apple
|
||||
// credential errors are decoded normally and never reach this branch.
|
||||
retry := status == gohttp.StatusNoContent ||
|
||||
status == gohttp.StatusForbidden ||
|
||||
status == gohttp.StatusNotFound ||
|
||||
status == gohttp.StatusTooManyRequests ||
|
||||
status/100 == 5
|
||||
|
||||
return status, retry
|
||||
}
|
||||
|
||||
func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int, authCode, endpoint string) (bool, string, error) {
|
||||
var (
|
||||
retry bool
|
||||
redirect string
|
||||
err error
|
||||
)
|
||||
|
||||
if res.StatusCode == gohttp.StatusFound {
|
||||
if res.StatusCode >= gohttp.StatusMultipleChoices && res.StatusCode < gohttp.StatusBadRequest {
|
||||
if redirect, err = res.GetHeader("location"); err != nil {
|
||||
err = fmt.Errorf("failed to retrieve redirect location: %w", err)
|
||||
} else if err = validateAuthenticationEndpoint(redirect); err != nil {
|
||||
err = fmt.Errorf("invalid authentication redirect: %w", err)
|
||||
} else if !http.IsAuthenticationRedirect(res.StatusCode) {
|
||||
err = errors.New("unsupported authentication redirect status")
|
||||
} else {
|
||||
retry = true
|
||||
redirect, err = resolveAuthenticationRedirect(endpoint, redirect)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
location, _ := res.GetHeader("location")
|
||||
|
||||
return false, "", authenticationRedirectError(err, res.StatusCode, location)
|
||||
}
|
||||
|
||||
retry = true
|
||||
} else if attempt == 1 && res.Data.FailureType == FailureTypeInvalidCredentials {
|
||||
retry = true
|
||||
} else if res.Data.FailureType == "" && authCode == "" && res.Data.CustomerMessage == CustomerMessageBadLogin {
|
||||
err = ErrAuthCodeRequired
|
||||
} else if res.Data.FailureType == "" && res.Data.CustomerMessage == CustomerMessageBadLogin {
|
||||
if authCode == "" {
|
||||
err = ErrAuthCodeRequired
|
||||
} else {
|
||||
err = errors.New("apple did not complete verification; try a fresh 2FA code")
|
||||
}
|
||||
} else if res.Data.FailureType == "" && res.Data.CustomerMessage == CustomerMessageAccountDisabled {
|
||||
err = NewErrorWithMetadata(errors.New("account is disabled"), res)
|
||||
} else if res.Data.FailureType != "" {
|
||||
@@ -196,14 +369,47 @@ 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
|
||||
}
|
||||
|
||||
func resolveAuthenticationRedirect(endpoint, location string) (string, error) {
|
||||
base, err := url.Parse(endpoint)
|
||||
if err != nil {
|
||||
return "", errors.New("invalid authentication redirect base URL")
|
||||
}
|
||||
|
||||
reference, err := url.Parse(strings.TrimSpace(location))
|
||||
if err != nil || strings.TrimSpace(location) == "" {
|
||||
return "", errors.New("invalid authentication redirect location")
|
||||
}
|
||||
|
||||
destination := base.ResolveReference(reference).String()
|
||||
if err := validateAuthenticationEndpoint(destination); err != nil {
|
||||
return "", fmt.Errorf("invalid authentication redirect: %w", err)
|
||||
}
|
||||
|
||||
return destination, nil
|
||||
}
|
||||
|
||||
func authenticationRedirectError(err error, status int, location string) error {
|
||||
// Keep useful routing diagnostics without retaining URL credentials, query
|
||||
// parameters, fragments, response bodies or arbitrary response headers.
|
||||
destination := "invalid URL"
|
||||
if parsed, parseErr := url.Parse(location); parseErr == nil {
|
||||
destination = (&url.URL{Scheme: parsed.Scheme, Host: parsed.Host, Path: parsed.Path}).String()
|
||||
}
|
||||
|
||||
return NewErrorWithMetadata(fmt.Errorf("%w (HTTP %d)", err, status), map[string]interface{}{
|
||||
"statusCode": status,
|
||||
"destination": destination,
|
||||
})
|
||||
}
|
||||
|
||||
func (t *appstore) loginRequest(email, password, authCode, guid, endpoint string, attempt int, signer ActionSigner) http.Request {
|
||||
return http.Request{
|
||||
request := http.Request{
|
||||
Method: http.MethodPOST,
|
||||
URL: endpoint,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
@@ -222,4 +428,41 @@ func (t *appstore) loginRequest(email, password, authCode, guid, endpoint string
|
||||
},
|
||||
},
|
||||
}
|
||||
if storefront := phoneNumberStorefront(email); storefront != "" {
|
||||
request.Headers["X-Apple-Store-Front"] = storefront
|
||||
}
|
||||
|
||||
return request
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package appstore
|
||||
|
||||
import "strings"
|
||||
|
||||
// phoneNumberStorefront supplies a routing hint for phone-based Apple Accounts
|
||||
// in mainland China and India. It does not change the Apple ID sent to Apple.
|
||||
func phoneNumberStorefront(appleID string) string {
|
||||
number := strings.ReplaceAll(strings.TrimSpace(appleID), " ", "")
|
||||
number = strings.ReplaceAll(number, "-", "")
|
||||
|
||||
international := false
|
||||
|
||||
switch {
|
||||
case strings.HasPrefix(number, "+"):
|
||||
international = true
|
||||
number = number[1:]
|
||||
case strings.HasPrefix(number, "00"):
|
||||
international = true
|
||||
number = number[2:]
|
||||
}
|
||||
|
||||
for _, digit := range number {
|
||||
if digit < '0' || digit > '9' {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// Check the full length before removing a country code: a local Indian
|
||||
// number can itself start with 91. Explicit international numbers must
|
||||
// match a supported country code and cannot fall back to a local format.
|
||||
switch {
|
||||
case len(number) == 13 && strings.HasPrefix(number, "861"):
|
||||
return storeFronts["CN"]
|
||||
case len(number) == 12 && strings.HasPrefix(number, "91"):
|
||||
number = number[2:]
|
||||
case international:
|
||||
return ""
|
||||
}
|
||||
|
||||
if len(number) == 11 && number[0] == '1' {
|
||||
return storeFronts["CN"]
|
||||
}
|
||||
|
||||
// India also permits a trunk prefix when writing a national number.
|
||||
if !international && len(number) == 11 && number[0] == '0' {
|
||||
number = number[1:]
|
||||
}
|
||||
|
||||
if len(number) == 10 && number[0] >= '6' && number[0] <= '9' {
|
||||
return storeFronts["IN"]
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
var _ = Describe("Phone account login routing", func() {
|
||||
DescribeTable("sets a storefront hint without rewriting the Apple ID", func(appleID, storefront string) {
|
||||
request := (&appstore{}).loginRequest(appleID, "password", "", "guid", testAuthEndpoint, 1, &stubActionSigner{})
|
||||
|
||||
Expect(request.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appleId", appleID))
|
||||
if storefront == "" {
|
||||
Expect(request.Headers).NotTo(HaveKey("X-Apple-Store-Front"))
|
||||
} else {
|
||||
Expect(request.Headers).To(HaveKeyWithValue("X-Apple-Store-Front", storefront))
|
||||
}
|
||||
},
|
||||
Entry("Chinese national number", "13912345678", "143465"),
|
||||
Entry("Chinese number with a plus prefix", "+8613912345678", "143465"),
|
||||
Entry("Chinese number with a 00 prefix", "008613912345678", "143465"),
|
||||
Entry("Chinese number with a bare country code", "8613912345678", "143465"),
|
||||
Entry("Chinese number with spaces and hyphens", " +86 139-1234-5678 ", "143465"),
|
||||
Entry("Indian national number beginning with 91", "9123456789", "143467"),
|
||||
Entry("Indian national number beginning with 86", "8612345678", "143467"),
|
||||
Entry("Indian national number beginning with 6", "6123456789", "143467"),
|
||||
Entry("Indian number with a trunk prefix", "09123456789", "143467"),
|
||||
Entry("Indian number with a plus prefix", "+919123456789", "143467"),
|
||||
Entry("Indian number with a 00 prefix", "00919123456789", "143467"),
|
||||
Entry("Indian number with a bare country code", "919123456789", "143467"),
|
||||
Entry("Indian number with spaces and hyphens", "+91 91234-56789", "143467"),
|
||||
Entry("email", "person@example.test", ""),
|
||||
Entry("numeric email", "13912345678@example.test", ""),
|
||||
Entry("legacy username", "some-account", ""),
|
||||
Entry("empty input", "", ""),
|
||||
Entry("formatting only", " -- ", ""),
|
||||
Entry("plus only", "+", ""),
|
||||
Entry("international access code only", "00", ""),
|
||||
Entry("letters within a number", "139x12345678", ""),
|
||||
Entry("unsupported punctuation", "139/1234/5678", ""),
|
||||
Entry("non-ASCII digits", "+8613912345678", ""),
|
||||
Entry("non-ASCII plus", "+8613912345678", ""),
|
||||
Entry("embedded control character", "139\n12345678", ""),
|
||||
Entry("misplaced plus", "139+12345678", ""),
|
||||
Entry("repeated plus", "++8613912345678", ""),
|
||||
Entry("mixed international prefixes", "+008613912345678", ""),
|
||||
Entry("unsupported country with a Chinese-looking local format", "+13912345678", ""),
|
||||
Entry("unsupported country with a 00 prefix", "0013912345678", ""),
|
||||
Entry("unsupported country with an Indian-looking local format", "+8612345678", ""),
|
||||
Entry("explicit country code missing national digits", "+9123456789", ""),
|
||||
Entry("short Chinese number", "+861391234567", ""),
|
||||
Entry("long Chinese number", "+86139123456789", ""),
|
||||
Entry("Chinese country code with an Indian trunk number", "8609123456789", ""),
|
||||
Entry("invalid Chinese national prefix", "+8623912345678", ""),
|
||||
Entry("short Indian number", "+91912345678", ""),
|
||||
Entry("long Indian number", "+9191234567890", ""),
|
||||
Entry("invalid Indian national prefix", "+915123456789", ""),
|
||||
Entry("trunk prefix after an international code", "+9109123456789", ""),
|
||||
)
|
||||
})
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
@@ -41,10 +42,11 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
signer = &stubActionSigner{}
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockClient,
|
||||
bagClient: mockBagClient,
|
||||
machine: mockMachine,
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockClient,
|
||||
bagClient: mockBagClient,
|
||||
machine: mockMachine,
|
||||
authRetrySleep: func(time.Duration) {},
|
||||
actionSignerFactory: func(config SAPConfig, machineID []byte) (ActionSigner, error) {
|
||||
Expect(config).To(Equal(validSAPConfig()))
|
||||
Expect(machineID).To(Equal([]byte{0, 0, 0, 0, 0, 0}))
|
||||
@@ -58,6 +60,82 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
DescribeTable("rejects malformed 2FA codes before preparing authentication", func(code string) {
|
||||
_, err := as.Login(LoginInput{AuthCode: code})
|
||||
|
||||
Expect(err).To(MatchError("2FA code must contain exactly six digits"))
|
||||
},
|
||||
Entry("whitespace only", " \t\r\n"),
|
||||
Entry("too short", "12345"),
|
||||
Entry("too long", "1234567"),
|
||||
Entry("letters", "12345a"),
|
||||
Entry("non-ASCII digits", "123456"),
|
||||
Entry("other escape sequences", "\x1b[31m123456"),
|
||||
Entry("unmatched paste marker", "\x1b[200~123456"),
|
||||
Entry("empty paste", "\x1b[200~\x1b[201~"),
|
||||
Entry("embedded paste markers", "123\x1b[200~456\x1b[201~"),
|
||||
)
|
||||
|
||||
Describe("transient authentication responses", func() {
|
||||
DescribeTable("retries the same request until it succeeds", func(appleID, storefront string) {
|
||||
request := as.loginRequest(appleID, testPassword, "", "guid", testAuthEndpoint, 1, signer)
|
||||
responses := []struct {
|
||||
result http.Result[loginResult]
|
||||
err error
|
||||
}{
|
||||
{err: &http.UnexpectedResponseError{StatusCode: 204}},
|
||||
{err: &http.UnexpectedResponseError{StatusCode: 404}},
|
||||
{result: http.Result[loginResult]{StatusCode: 200}},
|
||||
}
|
||||
call := 0
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
DoAndReturn(func(actual http.Request) (http.Result[loginResult], error) {
|
||||
Expect(actual.URL).To(Equal(request.URL))
|
||||
Expect(actual.Headers["X-Apple-Store-Front"]).To(Equal(storefront))
|
||||
Expect(actual.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appleId", appleID))
|
||||
Expect(actual.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("attempt", "1"))
|
||||
response := responses[call]
|
||||
call++
|
||||
|
||||
return response.result, response.err
|
||||
}).
|
||||
Times(3)
|
||||
|
||||
result, err := as.sendAuthenticationRequest(request)
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(result.StatusCode).To(Equal(200))
|
||||
},
|
||||
Entry("email account", testEmail, ""),
|
||||
Entry("Chinese phone account", "+8613912345678", "143465"),
|
||||
Entry("Indian phone account", "9123456789", "143467"),
|
||||
)
|
||||
|
||||
DescribeTable("bounds retries to transient statuses",
|
||||
func(status, expectedCalls int) {
|
||||
request := as.loginRequest(testEmail, testPassword, "", "guid", testAuthEndpoint, 1, signer)
|
||||
responseErr := &http.UnexpectedResponseError{StatusCode: status}
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{}, responseErr).
|
||||
Times(expectedCalls)
|
||||
|
||||
_, err := as.sendAuthenticationRequest(request)
|
||||
|
||||
Expect(errors.Is(err, responseErr)).To(BeTrue())
|
||||
if expectedCalls == maxAuthenticationRequestAttempts {
|
||||
Expect(err.Error()).To(ContainSubstring("after 3 attempts"))
|
||||
Expect(err.Error()).To(ContainSubstring(fmt.Sprintf("HTTP %d, %d, %d", status, status, status)))
|
||||
}
|
||||
},
|
||||
Entry("retries and then stops for HTTP 204", 204, maxAuthenticationRequestAttempts),
|
||||
Entry("retries and then stops for HTTP 503", 503, maxAuthenticationRequestAttempts),
|
||||
Entry("retries and then stops for non-plist HTTP 403", 403, maxAuthenticationRequestAttempts),
|
||||
Entry("does not retry HTTP 401", 401, 1),
|
||||
)
|
||||
})
|
||||
|
||||
When("fails to read Machine's MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
@@ -89,6 +167,27 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
}, nil)
|
||||
})
|
||||
|
||||
DescribeTable("normalizes 2FA codes without changing the password", func(code, suffix string) {
|
||||
const password = " \tpäss word\n"
|
||||
mockClient.EXPECT().Send(gomock.Any()).DoAndReturn(func(req http.Request) (http.Result[loginResult], error) {
|
||||
Expect(req.URL).To(Equal(testAuthEndpoint + "/"))
|
||||
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("password", password+suffix))
|
||||
|
||||
return http.Result[loginResult]{}, errors.New("test complete")
|
||||
})
|
||||
|
||||
_, err := as.Login(LoginInput{Password: password, AuthCode: code})
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("test complete")))
|
||||
},
|
||||
Entry("no code on initial login", "", ""),
|
||||
Entry("plain code with leading zero", "012345", "012345"),
|
||||
Entry("spaces", "123 456", "123456"),
|
||||
Entry("Unicode whitespace", "\t123\u00a0456\r\n", "123456"),
|
||||
Entry("bracketed paste", "\x1b[200~123456\x1b[201~", "123456"),
|
||||
Entry("bracketed paste with whitespace", " \x1b[200~123 456\n\x1b[201~\r\n", "123456"),
|
||||
)
|
||||
|
||||
When("client returns error", func() {
|
||||
var clientErr error
|
||||
|
||||
@@ -97,7 +196,7 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testAuthEndpoint))
|
||||
Expect(req.URL).To(Equal(testAuthEndpoint + "/"))
|
||||
Expect(req.ActionSigner).To(BeIdenticalTo(signer))
|
||||
}).
|
||||
Return(http.Result[loginResult]{}, clientErr)
|
||||
@@ -204,6 +303,7 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{
|
||||
StatusCode: 200,
|
||||
Data: loginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
@@ -217,6 +317,13 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
})
|
||||
Expect(err).To(Equal(ErrAuthCodeRequired))
|
||||
})
|
||||
|
||||
It("reports an incomplete verification when a code was already supplied", func() {
|
||||
_, err := as.Login(LoginInput{Password: testPassword, AuthCode: "123456"})
|
||||
|
||||
Expect(err).To(MatchError("apple did not complete verification; try a fresh 2FA code"))
|
||||
Expect(errors.Is(err, ErrAuthCodeRequired)).To(BeFalse())
|
||||
})
|
||||
})
|
||||
|
||||
When("store API redirects", func() {
|
||||
@@ -228,7 +335,7 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
firstCall := mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testAuthEndpoint))
|
||||
Expect(req.URL).To(Equal(testAuthEndpoint + "/"))
|
||||
Expect(req.ActionSigner).To(BeIdenticalTo(signer))
|
||||
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
|
||||
x := req.Payload.(*http.XMLPayload)
|
||||
@@ -255,7 +362,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"))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -354,9 +461,12 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
type stubActionSigner struct {
|
||||
closeCalls int
|
||||
closeErr error
|
||||
signCalls int
|
||||
}
|
||||
|
||||
func (*stubActionSigner) Sign(data []byte) ([]byte, error) {
|
||||
func (s *stubActionSigner) Sign(data []byte) ([]byte, error) {
|
||||
s.signCalls++
|
||||
|
||||
return append([]byte(nil), data...), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,17 @@ import (
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
var ErrAppNotFound = errors.New("app not found")
|
||||
|
||||
type LookupInput struct {
|
||||
Account Account
|
||||
AppID int64
|
||||
BundleID string
|
||||
Platform Platform
|
||||
}
|
||||
@@ -25,7 +30,13 @@ func (t *appstore) Lookup(input LookupInput) (LookupOutput, error) {
|
||||
return LookupOutput{}, fmt.Errorf("failed to resolve the country code: %w", err)
|
||||
}
|
||||
|
||||
request, err := t.lookupRequest(input.BundleID, countryCode, input.Platform)
|
||||
var request http.Request
|
||||
if input.BundleID == "" && input.AppID > 0 {
|
||||
request, err = t.lookupIDsRequest([]string{strconv.FormatInt(input.AppID, 10)}, countryCode, input.Platform)
|
||||
} else {
|
||||
request, err = t.lookupRequest(input.BundleID, countryCode, input.Platform)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return LookupOutput{}, fmt.Errorf("failed to create lookup request: %w", err)
|
||||
}
|
||||
@@ -40,7 +51,11 @@ func (t *appstore) Lookup(input LookupInput) (LookupOutput, error) {
|
||||
}
|
||||
|
||||
if len(res.Data.Results) == 0 {
|
||||
return LookupOutput{}, errors.New("app not found")
|
||||
return LookupOutput{}, ErrAppNotFound
|
||||
}
|
||||
|
||||
if input.Platform == PlatformWatchOS && !slices.Contains(res.Data.Results[0].Platforms, PlatformWatchOS) {
|
||||
return LookupOutput{}, ErrAppNotFound
|
||||
}
|
||||
|
||||
return LookupOutput{
|
||||
|
||||
@@ -29,6 +29,33 @@ var _ = Describe("AppStore (Lookup)", func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
DescribeTable("looks up an app by ID or bundle identifier", func(appID int64, bundleID, key, value string) {
|
||||
mockClient.EXPECT().Send(gomock.Any()).DoAndReturn(func(req http.Request) (http.Result[searchResult], error) {
|
||||
parsed, err := url.Parse(req.URL)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(parsed.Query().Get(key)).To(Equal(value))
|
||||
Expect(parsed.Query().Get("entity")).To(Equal("macSoftware"))
|
||||
Expect(parsed.Query().Get("country")).To(Equal("US"))
|
||||
if key == "bundleId" {
|
||||
Expect(parsed.Query().Has("id")).To(BeFalse())
|
||||
} else {
|
||||
Expect(parsed.Query().Has("bundleId")).To(BeFalse())
|
||||
}
|
||||
|
||||
return http.Result[searchResult]{
|
||||
StatusCode: 200, Data: searchResult{Results: []App{{ID: 123, BundleID: "com.example.app"}}},
|
||||
}, nil
|
||||
})
|
||||
output, err := as.Lookup(LookupInput{
|
||||
Account: Account{StoreFront: "143441"}, AppID: appID, BundleID: bundleID, Platform: PlatformMacOS,
|
||||
})
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(output.App.BundleID).To(Equal("com.example.app"))
|
||||
},
|
||||
Entry("numeric ID", int64(123), "", "id", "123"),
|
||||
Entry("bundle identifier overrides ID", int64(999), "com.example.app", "bundleId", "com.example.app"),
|
||||
)
|
||||
|
||||
When("request is successful", func() {
|
||||
When("does not find app", func() {
|
||||
BeforeEach(func() {
|
||||
@@ -49,7 +76,7 @@ var _ = Describe("AppStore (Lookup)", func() {
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(errors.Is(err, ErrAppNotFound)).To(BeTrue())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -86,6 +113,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().
|
||||
@@ -109,6 +159,28 @@ var _ = Describe("AppStore (Lookup)", func() {
|
||||
})
|
||||
})
|
||||
|
||||
DescribeTable("checks watchOS support in lookup results", func(platforms []Platform, found bool) {
|
||||
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("watchSoftware"))
|
||||
}).Return(http.Result[searchResult]{StatusCode: 200, Data: searchResult{
|
||||
Count: 1, Results: []App{{ID: 42, Platforms: platforms}},
|
||||
}}, nil)
|
||||
out, err := as.Lookup(LookupInput{Account: Account{StoreFront: "143441"}, AppID: 42, Platform: PlatformWatchOS})
|
||||
if found {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.App.ID).To(Equal(int64(42)))
|
||||
} else {
|
||||
Expect(err).To(MatchError(ErrAppNotFound))
|
||||
}
|
||||
},
|
||||
Entry("Watch app", []Platform{PlatformWatchOS}, true),
|
||||
Entry("iPhone app with Watch support", []Platform{PlatformIPhone, PlatformWatchOS}, true),
|
||||
Entry("iPhone only", []Platform{PlatformIPhone}, false),
|
||||
Entry("unknown platforms", []Platform{PlatformUnknown}, false),
|
||||
)
|
||||
|
||||
When("store front is invalid", func() {
|
||||
It("returns error", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/blacktop/go-macho/pkg/xar"
|
||||
)
|
||||
|
||||
type macPreflightDistributionInfo struct {
|
||||
XMLName xml.Name `xml:"installer-gui-script"`
|
||||
Products []struct {
|
||||
ID string `xml:"id,attr"`
|
||||
Version string `xml:"version,attr"`
|
||||
} `xml:"product"`
|
||||
Packages []struct {
|
||||
ID string `xml:"id,attr"`
|
||||
Version string `xml:"version,attr"`
|
||||
Bundles []struct {
|
||||
ID string `xml:"id,attr"`
|
||||
} `xml:"relocate>bundle"`
|
||||
} `xml:"pkg-ref"`
|
||||
}
|
||||
|
||||
func macPreflightVersionMetadata(archive *xar.Reader, bundleID string) (versionMetadata, error) {
|
||||
var distribution *xar.File
|
||||
|
||||
for _, file := range archive.Files {
|
||||
if file.Name != "Distribution" {
|
||||
continue
|
||||
}
|
||||
|
||||
if distribution != nil {
|
||||
return versionMetadata{}, errors.New("macOS preflight package contains multiple Distribution files")
|
||||
}
|
||||
|
||||
distribution = file
|
||||
}
|
||||
|
||||
if distribution == nil {
|
||||
return versionMetadata{}, errors.New("macOS preflight package does not contain Distribution")
|
||||
}
|
||||
|
||||
if !distribution.VerifyChecksum() {
|
||||
return versionMetadata{}, errors.New("macOS preflight Distribution checksum mismatch")
|
||||
}
|
||||
|
||||
source, err := distribution.Open()
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to open Mac preflight Distribution: %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 Mac preflight Distribution: %w", err)
|
||||
}
|
||||
|
||||
var info macPreflightDistributionInfo
|
||||
if err := xml.Unmarshal(data, &info); err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to parse Mac preflight Distribution: %w", err)
|
||||
}
|
||||
|
||||
if len(info.Products) != 1 || info.Products[0].ID == "" || (bundleID != "" && info.Products[0].ID != bundleID) {
|
||||
return versionMetadata{}, errors.New("macOS preflight package does not contain a unique product for the requested bundle")
|
||||
}
|
||||
|
||||
product := info.Products[0]
|
||||
version := strings.TrimSpace(product.Version)
|
||||
|
||||
if version == "" {
|
||||
return versionMetadata{}, errors.New("macOS preflight package does not contain a display version")
|
||||
}
|
||||
|
||||
// References to the same package can be split across several pkg-ref
|
||||
// elements. Only use versions belonging to the requested product's bundle.
|
||||
packageIDs := make(map[string]bool)
|
||||
|
||||
for _, pkg := range info.Packages {
|
||||
for _, bundle := range pkg.Bundles {
|
||||
if bundle.ID == product.ID && pkg.ID != "" {
|
||||
packageIDs[pkg.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var built time.Time
|
||||
|
||||
for _, pkg := range info.Packages {
|
||||
if !packageIDs[pkg.ID] || pkg.Version == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
timestamp, err := legacyMacPackageBuildTime(version, pkg.Version)
|
||||
if err != nil {
|
||||
return versionMetadata{}, err
|
||||
}
|
||||
|
||||
if !built.IsZero() && !built.Equal(timestamp) {
|
||||
return versionMetadata{}, errors.New("macOS preflight package contains conflicting build timestamps")
|
||||
}
|
||||
|
||||
built = timestamp
|
||||
}
|
||||
|
||||
if built.IsZero() {
|
||||
return versionMetadata{}, errors.New("macOS preflight package does not contain a build timestamp for the requested bundle")
|
||||
}
|
||||
|
||||
// As with the payload timestamp fallback, this is the build time, not an
|
||||
// exact store release date. The API date is app-level, and the preflight
|
||||
// archive's creation time can reflect a much later repackaging date.
|
||||
return versionMetadata{DisplayVersion: version, ReleaseDate: built}, nil
|
||||
}
|
||||
|
||||
func legacyMacPackageBuildTime(displayVersion, packageVersion string) (time.Time, error) {
|
||||
// Legacy Apple installers use major.minor.patch.0.1.<Unix build time>.
|
||||
// Do not interpret arbitrary dotted versions as timestamps.
|
||||
parts := strings.Split(packageVersion, ".")
|
||||
version := strings.Split(displayVersion, ".")
|
||||
|
||||
for len(version) < 3 {
|
||||
version = append(version, "0")
|
||||
}
|
||||
|
||||
if len(parts) != 6 || len(version) != 3 || strings.Join(parts[:3], ".") != strings.Join(version, ".") ||
|
||||
parts[3] != "0" || parts[4] != "1" || len(parts[5]) != 10 {
|
||||
return time.Time{}, errors.New("macOS preflight package does not contain a supported build timestamp")
|
||||
}
|
||||
|
||||
for _, part := range parts {
|
||||
if part == "" || strings.Trim(part, "0123456789") != "" {
|
||||
return time.Time{}, errors.New("macOS preflight package contains an invalid installer version")
|
||||
}
|
||||
}
|
||||
|
||||
seconds, err := strconv.ParseInt(parts[5], 10, 64)
|
||||
if err != nil || seconds <= 0 {
|
||||
return time.Time{}, errors.New("macOS preflight package contains an invalid build timestamp")
|
||||
}
|
||||
|
||||
return time.Unix(seconds, 0).UTC(), nil
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha1" // #nosec G505 -- XAR uses SHA-1 for archive checksums.
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"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 macPreflightXAR(distribution string) []byte {
|
||||
data := []byte(distribution)
|
||||
checksum := sha1.Sum(data) // #nosec G401 -- XAR uses SHA-1 for archive checksums.
|
||||
entry := fmt.Sprintf(`<file id="1"><type>file</type><name>Distribution</name><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>`, len(data), sha1.Size, len(data), checksum, checksum)
|
||||
|
||||
// The live preflight packages were repacked in 2023. Their creation time
|
||||
// must not replace the original build timestamp in the installer version.
|
||||
return makeTestXARArchive(`<creation-time>2023-01-04T22:53:15</creation-time>`+entry, data...)
|
||||
}
|
||||
|
||||
func macPreflightDistribution(version, packageVersion string) string {
|
||||
return fmt.Sprintf(`<installer-gui-script><product id="com.example.mac" version="%s"/>
|
||||
<pkg-ref id="com.example.pkg"><relocate><bundle id="com.example.mac"/></relocate></pkg-ref>
|
||||
<pkg-ref id="com.unrelated.pkg" version="9.9.9.0.1.1700000000"/>
|
||||
<pkg-ref id="com.example.pkg" version="%s"/>
|
||||
<pkg-ref id="com.example.pkg" version="%s"/></installer-gui-script>`, version, packageVersion, packageVersion)
|
||||
}
|
||||
|
||||
var _ = Describe("Mac preflight version metadata", func() {
|
||||
DescribeTable("validates the selected product and its build timestamp", func(distribution, bundle, expectedError string) {
|
||||
data := macPreflightXAR(distribution)
|
||||
archive, err := xar.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
metadata, err := macPreflightVersionMetadata(archive, bundle)
|
||||
if expectedError != "" {
|
||||
Expect(err).To(MatchError(ContainSubstring(expectedError)))
|
||||
} else {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(metadata.DisplayVersion).To(Equal("4.2"))
|
||||
Expect(metadata.ReleaseDate).To(Equal(time.Unix(1341568473, 0).UTC()))
|
||||
}
|
||||
},
|
||||
Entry("unique product without a bundle filter", macPreflightDistribution("4.2", "4.2.0.0.1.1341568473"), "", ""),
|
||||
Entry("wrong bundle", macPreflightDistribution("4.2", "4.2.0.0.1.1341568473"), "com.other.mac", "requested bundle"),
|
||||
Entry("missing version", macPreflightDistribution("", "4.2.0.0.1.1341568473"), "", "display version"),
|
||||
Entry("missing timestamp", macPreflightDistribution("4.2", ""), "", "build timestamp"),
|
||||
Entry("ordinary dotted version", macPreflightDistribution("4.2", "4.2.0"), "", "supported build timestamp"),
|
||||
Entry("different package version", macPreflightDistribution("4.2", "4.3.0.0.1.1341568473"), "", "supported build timestamp"),
|
||||
Entry("invalid timestamp", macPreflightDistribution("4.2", "4.2.0.0.1.abcdefghij"), "", "invalid installer version"),
|
||||
Entry("zero timestamp", macPreflightDistribution("4.2", "4.2.0.0.1.0000000000"), "", "invalid build timestamp"),
|
||||
Entry("unrelated package", strings.ReplaceAll(macPreflightDistribution("4.2", "4.2.0.0.1.1341568473"), `<bundle id="com.example.mac"`, `<bundle id="com.other.mac"`), "", "requested bundle"),
|
||||
Entry("conflicting timestamps", strings.Replace(macPreflightDistribution("4.2", "4.2.0.0.1.1341568473"), "1341568473", "1341568474", 1), "", "conflicting build timestamps"),
|
||||
Entry("ambiguous products", strings.Replace(macPreflightDistribution("4.2", "4.2.0.0.1.1341568473"), "</installer-gui-script>", `<product id="com.other.mac" version="4.2"/></installer-gui-script>`, 1), "", "unique product"),
|
||||
Entry("malformed XML", "<", "", "failed to parse"),
|
||||
)
|
||||
|
||||
It("rejects corrupted installer metadata", func() {
|
||||
data := macPreflightXAR(macPreflightDistribution("4.2", "4.2.0.0.1.1341568473"))
|
||||
data[len(data)-1] ^= 1
|
||||
archive, err := xar.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err = macPreflightVersionMetadata(archive, "com.example.mac")
|
||||
Expect(err).To(MatchError(ContainSubstring("checksum mismatch")))
|
||||
})
|
||||
|
||||
DescribeTable("reads the selected legacy version without downloading the encrypted app", func(platform Platform, softwarePlatform, versionID, displayVersion, packageVersion string, timestamp int64) {
|
||||
ctrl := gomock.NewController(GinkgoT())
|
||||
defer ctrl.Finish()
|
||||
tempRoot := GinkgoT().TempDir()
|
||||
GinkgoT().Setenv("TMPDIR", tempRoot)
|
||||
GinkgoT().Setenv("TMP", tempRoot)
|
||||
GinkgoT().Setenv("TEMP", tempRoot)
|
||||
data := macPreflightXAR(macPreflightDistribution(displayVersion, packageVersion))
|
||||
var encryptedRequests atomic.Int64
|
||||
server := httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, r *gohttp.Request) {
|
||||
if r.URL.Path != "/preflight.pkg" {
|
||||
encryptedRequests.Add(1)
|
||||
w.WriteHeader(gohttp.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(data)
|
||||
}))
|
||||
defer server.Close()
|
||||
downloads := http.NewMockClient[downloadResult](ctrl)
|
||||
machines := machine.NewMockMachine(ctrl)
|
||||
store := &appstore{downloadClient: downloads, machine: machines, os: operatingsystem.New(), httpClient: http.NewClient[interface{}](http.Args{})}
|
||||
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", versionID))
|
||||
}).Return(http.Result[downloadResult]{StatusCode: 200, Data: downloadResult{Items: []downloadItemResult{{
|
||||
URL: server.URL + "/encrypted.pkg", PreflightPackageURL: server.URL + "/preflight.pkg",
|
||||
Metadata: map[string]interface{}{
|
||||
"software-platform": softwarePlatform, "product-type": "mac-os-app", "softwareVersionBundleId": "com.example.mac",
|
||||
"bundleShortVersionString": "4.3", "releaseDate": "2011-01-03T08:00:00Z",
|
||||
},
|
||||
}}}}, nil)
|
||||
|
||||
out, err := store.GetVersionMetadata(GetVersionMetadataInput{App: App{ID: 409201541}, VersionID: versionID, Platform: platform})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.DisplayVersion).To(Equal(displayVersion))
|
||||
Expect(out.ReleaseDate).To(Equal(time.Unix(timestamp, 0).UTC()))
|
||||
Expect(encryptedRequests.Load()).To(BeZero())
|
||||
entries, err := os.ReadDir(tempRoot)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(entries).To(BeEmpty())
|
||||
},
|
||||
Entry("4.0.5 without a platform", Platform(""), "macos", "3235485", "4.0.5", "4.0.5.0.1.1292967101", int64(1292967101)),
|
||||
Entry("4.0.5 with macOS", PlatformMacOS, "macos", "3235485", "4.0.5", "4.0.5.0.1.1292967101", int64(1292967101)),
|
||||
Entry("4.2 without a platform", Platform(""), "macos", "12013122", "4.2", "4.2.0.0.1.1341568473", int64(1341568473)),
|
||||
Entry("4.2 with macOS", PlatformMacOS, "macos", "12013122", "4.2", "4.2.0.0.1.1341568473", int64(1341568473)),
|
||||
Entry("product type without platform metadata", Platform(""), "", "12013122", "4.2", "4.2.0.0.1.1341568473", int64(1341568473)),
|
||||
)
|
||||
})
|
||||
@@ -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,114 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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(context.Background(), 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(context.Background(), 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(context.Background(), 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,125 @@
|
||||
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")
|
||||
// Older device-based downloads omit dpInfo but include a small, readable
|
||||
// preflight archive containing the selected build's installer metadata.
|
||||
preflight := !hasMacDPInfo(item.Sinfs) && item.PreflightPackageURL != ""
|
||||
if preflight {
|
||||
if err := t.downloadFile(ctx, item.PreflightPackageURL, destination, nil); err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to download Mac preflight package: %w", err)
|
||||
}
|
||||
} else 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()
|
||||
|
||||
if preflight {
|
||||
return macPreflightVersionMetadata(&archive.Reader, bundleID)
|
||||
}
|
||||
|
||||
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())
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,666 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
gohttp "net/http"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultOwnedAppsLimit = 10
|
||||
MaxOwnedAppsLimit = 100
|
||||
|
||||
ownedAppsMediaKind = 131072
|
||||
ownedArcadeAppsMediaKind = 262144
|
||||
ownedMacAppsMediaKind = 67108864
|
||||
)
|
||||
|
||||
type OwnedAppsInput struct {
|
||||
Account Account
|
||||
Page int
|
||||
Limit int
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
type OwnedAppsOutput struct {
|
||||
Count int
|
||||
TotalCount int
|
||||
Page int
|
||||
Results []App
|
||||
}
|
||||
|
||||
func (t *appstore) OwnedApps(input OwnedAppsInput) (OwnedAppsOutput, error) {
|
||||
input, err := normalizeOwnedAppsInput(input)
|
||||
if err != nil {
|
||||
return OwnedAppsOutput{}, err
|
||||
}
|
||||
|
||||
macAddress, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return OwnedAppsOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid, machineID, err := machineIdentity(macAddress)
|
||||
if err != nil {
|
||||
return OwnedAppsOutput{}, err
|
||||
}
|
||||
|
||||
bag, err := t.bag(guid)
|
||||
if err != nil {
|
||||
return OwnedAppsOutput{}, fmt.Errorf("failed to get bag: %w", err)
|
||||
}
|
||||
|
||||
if t.actionSignerFactory == nil {
|
||||
return OwnedAppsOutput{}, errors.New("SAP action signer is not configured")
|
||||
}
|
||||
|
||||
signer, err := t.actionSignerFactory(bag.SAPConfig, machineID)
|
||||
if err != nil {
|
||||
return OwnedAppsOutput{}, fmt.Errorf("failed to initialize SAP action signer: %w", err)
|
||||
}
|
||||
|
||||
if signer == nil {
|
||||
return OwnedAppsOutput{}, errors.New("SAP action signer factory returned nil")
|
||||
}
|
||||
|
||||
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{
|
||||
Count: len(pageApps),
|
||||
TotalCount: len(apps),
|
||||
Page: input.Page,
|
||||
Results: pageApps,
|
||||
}
|
||||
closeErr := signer.Close()
|
||||
|
||||
if closeErr != nil {
|
||||
closeErr = fmt.Errorf("failed to close SAP action signer: %w", closeErr)
|
||||
}
|
||||
|
||||
if fetchErr != nil {
|
||||
if closeErr != nil {
|
||||
return OwnedAppsOutput{}, errors.Join(fetchErr, closeErr)
|
||||
}
|
||||
|
||||
return OwnedAppsOutput{}, fetchErr
|
||||
}
|
||||
|
||||
if closeErr != nil {
|
||||
return output, closeErr
|
||||
}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
if input.Limit == 0 {
|
||||
input.Limit = DefaultOwnedAppsLimit
|
||||
}
|
||||
|
||||
if input.Page < 1 {
|
||||
return OwnedAppsInput{}, errors.New("page must be greater than 0")
|
||||
}
|
||||
|
||||
if input.Limit < 1 {
|
||||
return OwnedAppsInput{}, errors.New("limit must be greater than 0")
|
||||
}
|
||||
|
||||
if input.Limit > MaxOwnedAppsLimit {
|
||||
return OwnedAppsInput{}, fmt.Errorf("limit must not exceed %d", MaxOwnedAppsLimit)
|
||||
}
|
||||
|
||||
return input, nil
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
if err := ownedAppsResponseError("purchase history login", loginResult); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := ownedAppsDMAPStatusError("purchase history login", loginResult.Data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sessionID, ok, err := firstDMAPUint(loginResult.Data, "mlid")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse purchase history login response: %w", err)
|
||||
}
|
||||
|
||||
if !ok || sessionID > math.MaxUint32 {
|
||||
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','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 {
|
||||
return nil, fmt.Errorf("failed to update purchase history: %w", err)
|
||||
}
|
||||
|
||||
if err := ownedAppsResponseError("purchase history update", updateResult); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := ownedAppsDMAPStatusError("purchase history update", updateResult.Data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
latestVersion, ok, err := firstDMAPUint(updateResult.Data, "musr")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse purchase history update response: %w", err)
|
||||
}
|
||||
|
||||
if !ok || latestVersion > math.MaxUint32 {
|
||||
return nil, errors.New("purchase history update response did not contain a valid revision")
|
||||
}
|
||||
|
||||
itemsResult, err := t.ownedAppsClient.Send(t.ownedAppsItemsRequest(
|
||||
acc,
|
||||
guid,
|
||||
uint32(sessionID),
|
||||
uint32(latestVersion),
|
||||
query,
|
||||
time.Now(),
|
||||
signer,
|
||||
))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to retrieve purchase history items: %w", err)
|
||||
}
|
||||
|
||||
if err := ownedAppsResponseError("purchase history items", itemsResult); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := ownedAppsDMAPStatusError("purchase history items", itemsResult.Data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
apps, err := parseOwnedApps(itemsResult.Data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse purchase history items response: %w", err)
|
||||
}
|
||||
|
||||
return apps, nil
|
||||
}
|
||||
|
||||
func (t *appstore) ownedAppsLoginRequest(acc Account, guid string) http.Request {
|
||||
return http.Request{
|
||||
URL: PrivatePurchaseDAAPBaseURL + "/login",
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatRaw,
|
||||
Headers: ownedAppsHeaders(acc, guid, time.Now()),
|
||||
}
|
||||
}
|
||||
|
||||
func (t *appstore) ownedAppsUpdateRequest(acc Account, guid string, sessionID uint32, query string, signer ActionSigner) http.Request {
|
||||
body := []byte(fmt.Sprintf("session-id=%d&revision-number=(null)&query=%s", sessionID, query))
|
||||
headers := ownedAppsHeaders(acc, guid, time.Now())
|
||||
headers["Content-Type"] = "application/x-www-form-urlencoded"
|
||||
|
||||
return http.Request{
|
||||
URL: PrivatePurchaseDAAPBaseURL + "/update",
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatRaw,
|
||||
ActionSigner: signer,
|
||||
Headers: headers,
|
||||
Payload: &http.RawPayload{Content: body},
|
||||
}
|
||||
}
|
||||
|
||||
func (t *appstore) ownedAppsItemsRequest(acc Account, guid string, sessionID, latestVersion uint32, query string, now time.Time, signer ActionSigner) http.Request {
|
||||
headers := ownedAppsHeaders(acc, guid, now)
|
||||
headers["Content-Type"] = "application/x-dmap-tagged"
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("%s/databases/%d/items", PrivatePurchaseDAAPBaseURL, latestVersion),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatRaw,
|
||||
ActionSigner: signer,
|
||||
Headers: headers,
|
||||
Payload: &http.RawPayload{Content: ownedAppsItemsBody(
|
||||
sessionID,
|
||||
latestVersion,
|
||||
query,
|
||||
now,
|
||||
)},
|
||||
}
|
||||
}
|
||||
|
||||
func ownedAppsHeaders(acc Account, guid string, now time.Time) map[string]string {
|
||||
utc := now.UTC()
|
||||
_, offsetSeconds := now.Zone()
|
||||
|
||||
return map[string]string{
|
||||
"Accept": "*/*",
|
||||
"Accept-Language": "en-us",
|
||||
"Client-Cloud-DAAP-Request-Reason": "5",
|
||||
"Client-Cloud-Purchase-Daap-Version": "1.1/Configurator-2.0",
|
||||
"Client-DAAP-Version": "3.12",
|
||||
"Date": utc.Format(gohttp.TimeFormat),
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Apple-I-Client-Time": utc.Format("2006-01-02T15:04:05Z"),
|
||||
"X-Apple-I-Locale": "en_US",
|
||||
"X-Apple-I-TimeZone": now.Location().String(),
|
||||
"X-Apple-Store-Front": acc.StoreFront,
|
||||
"X-Apple-TZ": strconv.Itoa(offsetSeconds / 60),
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
"X-Guid": guid,
|
||||
"X-Token": acc.PasswordToken,
|
||||
}
|
||||
}
|
||||
|
||||
func ownedAppsItemsBody(sessionID, latestVersion uint32, query string, now time.Time) []byte {
|
||||
payload := make([]byte, 0, 73+len(query))
|
||||
payload = append(payload, dmapUint32("mstc", uint32(now.Unix()))...)
|
||||
payload = append(payload, dmapUint32("mlid", sessionID)...)
|
||||
payload = append(payload, dmapUint8("mikd", 2)...)
|
||||
payload = append(payload, dmapUint32("musr", latestVersion)...)
|
||||
payload = append(payload, dmapUint32("mder", 0)...)
|
||||
payload = append(payload, dmapString("mque", query)...)
|
||||
payload = append(payload, dmapTag("aetl", nil)...)
|
||||
|
||||
return dmapTag("adsr", payload)
|
||||
}
|
||||
|
||||
func dmapTag(name string, payload []byte) []byte {
|
||||
result := make([]byte, 8+len(payload))
|
||||
copy(result[:4], name)
|
||||
binary.BigEndian.PutUint32(result[4:8], uint32(len(payload)))
|
||||
copy(result[8:], payload)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func dmapUint8(name string, value uint8) []byte {
|
||||
return dmapTag(name, []byte{value})
|
||||
}
|
||||
|
||||
func dmapUint32(name string, value uint32) []byte {
|
||||
payload := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(payload, value)
|
||||
|
||||
return dmapTag(name, payload)
|
||||
}
|
||||
|
||||
func dmapString(name, value string) []byte {
|
||||
return dmapTag(name, []byte(value))
|
||||
}
|
||||
|
||||
func ownedAppsResponseError(label string, result http.Result[[]byte]) error {
|
||||
if result.StatusCode == gohttp.StatusUnauthorized || result.StatusCode == gohttp.StatusForbidden {
|
||||
return fmt.Errorf("%w: %s request returned HTTP %d", ErrPasswordTokenExpired, label, result.StatusCode)
|
||||
}
|
||||
|
||||
if result.StatusCode != gohttp.StatusOK {
|
||||
return fmt.Errorf("%s request returned HTTP %d", label, result.StatusCode)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ownedAppsDMAPStatusError(label string, data []byte) error {
|
||||
status, found, err := firstDMAPUint(data, "mstt")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse %s response: %w", label, err)
|
||||
}
|
||||
|
||||
if found && (status == gohttp.StatusUnauthorized || status == gohttp.StatusForbidden) {
|
||||
return fmt.Errorf("%w: %s response returned DAAP status %d", ErrPasswordTokenExpired, label, status)
|
||||
}
|
||||
|
||||
if found && status != gohttp.StatusOK {
|
||||
return fmt.Errorf("%s response returned DAAP status %d", label, status)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func firstDMAPUint(data []byte, target string) (uint64, bool, error) {
|
||||
var (
|
||||
result uint64
|
||||
found bool
|
||||
)
|
||||
|
||||
err := walkDMAP(data, 0, func(tag string, payload []byte) error {
|
||||
if found || tag != target {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch len(payload) {
|
||||
case 4:
|
||||
result = uint64(binary.BigEndian.Uint32(payload))
|
||||
case 8:
|
||||
result = binary.BigEndian.Uint64(payload)
|
||||
default:
|
||||
return fmt.Errorf("tag %s has invalid integer length %d", target, len(payload))
|
||||
}
|
||||
|
||||
found = true
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
return result, found, err
|
||||
}
|
||||
|
||||
func parseOwnedApps(data []byte) ([]App, error) {
|
||||
apps := make([]App, 0)
|
||||
|
||||
err := walkDMAP(data, 0, func(tag string, payload []byte) error {
|
||||
if tag != "mlit" {
|
||||
return nil
|
||||
}
|
||||
|
||||
app, err := parseOwnedApp(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if app.ID == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
apps = append(apps, app)
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
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) {
|
||||
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 {
|
||||
return fmt.Errorf("failed to parse owned app ID: %w", err)
|
||||
}
|
||||
|
||||
app.ID = id
|
||||
case "aeBI":
|
||||
app.BundleID = string(payload)
|
||||
case "aeLN":
|
||||
app.Name = string(payload)
|
||||
case "minm":
|
||||
if app.Name == "" {
|
||||
app.Name = string(payload)
|
||||
}
|
||||
case "aePd":
|
||||
app.Version = string(payload)
|
||||
case "asdp":
|
||||
if len(payload) != 4 {
|
||||
return fmt.Errorf("owned app purchase date has invalid length %d", len(payload))
|
||||
}
|
||||
|
||||
app.PurchaseDate = time.Unix(int64(binary.BigEndian.Uint32(payload)), 0).UTC()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func ownedAppsSortedByPurchaseDate(apps []App) []App {
|
||||
sorted := append([]App(nil), apps...)
|
||||
sort.SliceStable(sorted, func(left, right int) bool {
|
||||
leftDate, rightDate := sorted[left].PurchaseDate, sorted[right].PurchaseDate
|
||||
if leftDate.IsZero() {
|
||||
return false
|
||||
}
|
||||
|
||||
if rightDate.IsZero() {
|
||||
return true
|
||||
}
|
||||
|
||||
return leftDate.After(rightDate)
|
||||
})
|
||||
|
||||
return sorted
|
||||
}
|
||||
|
||||
func dmapInt64(payload []byte) (int64, error) {
|
||||
switch len(payload) {
|
||||
case 4:
|
||||
return int64(binary.BigEndian.Uint32(payload)), nil
|
||||
case 8:
|
||||
value := binary.BigEndian.Uint64(payload)
|
||||
if value > math.MaxInt64 {
|
||||
return 0, errors.New("integer exceeds int64")
|
||||
}
|
||||
|
||||
return int64(value), nil
|
||||
default:
|
||||
return 0, fmt.Errorf("invalid integer length %d", len(payload))
|
||||
}
|
||||
}
|
||||
|
||||
func walkDMAP(data []byte, depth int, visit func(tag string, payload []byte) error) error {
|
||||
if depth > 16 {
|
||||
return errors.New("DMAP nesting is too deep")
|
||||
}
|
||||
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
for offset := 0; offset < len(data); {
|
||||
if len(data)-offset < 8 {
|
||||
return fmt.Errorf("truncated DMAP tag header at byte %d", offset)
|
||||
}
|
||||
|
||||
tagBytes := data[offset : offset+4]
|
||||
if !validDMAPTag(tagBytes) {
|
||||
return fmt.Errorf("invalid DMAP tag at byte %d", offset)
|
||||
}
|
||||
|
||||
length, remaining := uint64(binary.BigEndian.Uint32(data[offset+4:offset+8])), uint64(len(data)-offset-8)
|
||||
if length > remaining {
|
||||
return fmt.Errorf("DMAP tag %s length %d exceeds remaining response length %d", string(tagBytes), length, remaining)
|
||||
}
|
||||
|
||||
end := offset + 8 + int(length)
|
||||
|
||||
tag, payload := string(tagBytes), data[offset+8:end]
|
||||
if err := visit(tag, payload); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if isDMAPContainer(tag) {
|
||||
if err := walkDMAP(payload, depth+1, visit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
offset = end
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validDMAPTag(tag []byte) bool {
|
||||
if len(tag) != 4 {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, character := range tag {
|
||||
if character < 0x20 || character > 0x7e {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func isDMAPContainer(tag string) bool {
|
||||
switch tag {
|
||||
case "adbs", "adsr", "aply", "avdb", "mbcl", "mccr", "mcty", "mdcl", "mlcl", "mlit", "mlog", "msrv", "mupd":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func ownedAppsPage(apps []App, page, limit int) []App {
|
||||
if page < 1 || limit < 1 {
|
||||
return []App{}
|
||||
}
|
||||
|
||||
pageIndex, pageSize := uint64(page-1), uint64(limit)
|
||||
if pageIndex > uint64(len(apps))/pageSize {
|
||||
return []App{}
|
||||
}
|
||||
|
||||
start := pageIndex * pageSize
|
||||
if start >= uint64(len(apps)) {
|
||||
return []App{}
|
||||
}
|
||||
|
||||
end := start + pageSize
|
||||
if end > uint64(len(apps)) {
|
||||
end = uint64(len(apps))
|
||||
}
|
||||
|
||||
return append([]App(nil), apps[int(start):int(end)]...)
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math"
|
||||
gohttp "net/http"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (OwnedApps)", func() {
|
||||
const (
|
||||
testDSID = "123456789"
|
||||
testGUID = "AABBCCDDEEFF"
|
||||
testStoreFront = "143441-1,34"
|
||||
testToken = "password-token"
|
||||
testSessionID = uint32(42)
|
||||
testRevision = uint32(99)
|
||||
)
|
||||
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockBagClient *http.MockClient[bagResult]
|
||||
mockOwnedClient *http.MockClient[[]byte]
|
||||
mockMachine *machine.MockMachine
|
||||
signer *stubActionSigner
|
||||
as *appstore
|
||||
)
|
||||
|
||||
account := Account{
|
||||
DirectoryServicesID: testDSID,
|
||||
PasswordToken: testToken,
|
||||
StoreFront: testStoreFront,
|
||||
}
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockBagClient = http.NewMockClient[bagResult](ctrl)
|
||||
mockOwnedClient = http.NewMockClient[[]byte](ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
signer = &stubActionSigner{}
|
||||
as = &appstore{
|
||||
bagClient: mockBagClient,
|
||||
ownedAppsClient: mockOwnedClient,
|
||||
machine: mockMachine,
|
||||
actionSignerFactory: func(config SAPConfig, machineID []byte) (ActionSigner, error) {
|
||||
Expect(config).To(Equal(validSAPConfig()))
|
||||
Expect(machineID).To(Equal([]byte{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}))
|
||||
|
||||
return signer, nil
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
expectSignerSetup := func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("aa:bb:cc:dd:ee:ff", 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: validBagResult(),
|
||||
}, 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()
|
||||
|
||||
responseOrder := []int{5, 12, 1, 9, 3, 11, 2, 8, 4, 10, 6, 7}
|
||||
apps := make([]App, 0, 12)
|
||||
for _, index := range responseOrder {
|
||||
apps = append(apps, App{
|
||||
ID: int64(1000 + index),
|
||||
BundleID: "com.example.app" + string(rune('a'+index-1)),
|
||||
Name: "DAAP app",
|
||||
Version: "1.0",
|
||||
PurchaseDate: time.Unix(1_700_000_000+int64(index*60), 0).UTC(),
|
||||
})
|
||||
}
|
||||
|
||||
loginCall := mockOwnedClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.Method).To(Equal(http.MethodPOST))
|
||||
Expect(req.URL).To(Equal(PrivatePurchaseDAAPBaseURL + "/login"))
|
||||
Expect(req.ActionSigner).To(BeNil())
|
||||
Expect(req.Payload).To(BeNil())
|
||||
expectOwnedAppsHeaders(req.Headers, account, testGUID)
|
||||
}).
|
||||
Return(http.Result[[]byte]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: dmapTag("mlog", dmapUint32("mlid", testSessionID)),
|
||||
}, nil)
|
||||
|
||||
updateCall := mockOwnedClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.Method).To(Equal(http.MethodPOST))
|
||||
Expect(req.URL).To(Equal(PrivatePurchaseDAAPBaseURL + "/update"))
|
||||
Expect(req.ActionSigner).To(BeIdenticalTo(signer))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("Content-Type", "application/x-www-form-urlencoded"))
|
||||
expectOwnedAppsHeaders(req.Headers, account, testGUID)
|
||||
|
||||
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','com.apple.itunes.extended\\-media\\-kind:262144','com.apple.itunes.extended\\-media\\-kind:67108864')"))
|
||||
}).
|
||||
Return(http.Result[[]byte]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: dmapTag("mupd", dmapUint32("musr", testRevision)),
|
||||
}, nil)
|
||||
|
||||
itemsCall := mockOwnedClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.Method).To(Equal(http.MethodPOST))
|
||||
Expect(req.URL).To(Equal(PrivatePurchaseDAAPBaseURL + "/databases/99/items"))
|
||||
Expect(req.ActionSigner).To(BeIdenticalTo(signer))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("Content-Type", "application/x-dmap-tagged"))
|
||||
expectOwnedAppsHeaders(req.Headers, account, testGUID)
|
||||
|
||||
payload, ok := req.Payload.(*http.RawPayload)
|
||||
Expect(ok).To(BeTrue())
|
||||
sessionID, found, err := firstDMAPUint(payload.Content, "mlid")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(sessionID).To(Equal(uint64(testSessionID)))
|
||||
revision, found, err := firstDMAPUint(payload.Content, "musr")
|
||||
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,
|
||||
Data: ownedAppsDMAPResponse(apps),
|
||||
}, nil)
|
||||
|
||||
gomock.InOrder(loginCall, updateCall, itemsCall)
|
||||
expectStorefront("143441-1,13", ownedAppsDMAPResponse(nil))
|
||||
|
||||
output, err := as.OwnedApps(OwnedAppsInput{
|
||||
Account: account,
|
||||
Page: 2,
|
||||
Limit: 10,
|
||||
})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(output.Count).To(Equal(2))
|
||||
Expect(output.TotalCount).To(Equal(12))
|
||||
Expect(output.Page).To(Equal(2))
|
||||
Expect(output.Results).To(HaveLen(2))
|
||||
Expect(output.Results[0].ID).To(Equal(int64(1002)))
|
||||
Expect(output.Results[0].PurchaseDate).To(Equal(time.Unix(1_700_000_120, 0).UTC()))
|
||||
Expect(output.Results[1].ID).To(Equal(int64(1001)))
|
||||
Expect(output.Results[1].PurchaseDate).To(Equal(time.Unix(1_700_000_060, 0).UTC()))
|
||||
Expect(signer.closeCalls).To(Equal(1))
|
||||
})
|
||||
})
|
||||
|
||||
When("the requested page is past the end", func() {
|
||||
It("returns an empty page without a metadata lookup", func() {
|
||||
expectSignerSetup()
|
||||
|
||||
gomock.InOrder(
|
||||
mockOwnedClient.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: dmapTag("mlog", dmapUint32("mlid", testSessionID)),
|
||||
}, nil),
|
||||
mockOwnedClient.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: dmapTag("mupd", dmapUint32("musr", testRevision)),
|
||||
}, nil),
|
||||
mockOwnedClient.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: ownedAppsDMAPResponse([]App{{ID: 1}}),
|
||||
}, nil),
|
||||
)
|
||||
|
||||
expectStorefront("143441-1,13", ownedAppsDMAPResponse(nil))
|
||||
|
||||
output, err := as.OwnedApps(OwnedAppsInput{Account: account, Page: 2, Limit: 10})
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(output.Count).To(Equal(0))
|
||||
Expect(output.TotalCount).To(Equal(1))
|
||||
Expect(output.Results).To(BeEmpty())
|
||||
Expect(signer.closeCalls).To(Equal(1))
|
||||
})
|
||||
})
|
||||
|
||||
When("the authenticated session is rejected", func() {
|
||||
It("returns the password-token-expired error and closes the signer", func() {
|
||||
expectSignerSetup()
|
||||
mockOwnedClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[[]byte]{StatusCode: gohttp.StatusUnauthorized}, nil)
|
||||
|
||||
_, err := as.OwnedApps(OwnedAppsInput{Account: account})
|
||||
|
||||
Expect(errors.Is(err, ErrPasswordTokenExpired)).To(BeTrue())
|
||||
Expect(signer.closeCalls).To(Equal(1))
|
||||
})
|
||||
})
|
||||
|
||||
When("the purchase history request and signer cleanup both fail", func() {
|
||||
It("preserves both errors", func() {
|
||||
expectSignerSetup()
|
||||
requestErr := errors.New("request error")
|
||||
cleanupErr := errors.New("cleanup error")
|
||||
signer.closeErr = cleanupErr
|
||||
mockOwnedClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[[]byte]{}, requestErr)
|
||||
|
||||
_, err := as.OwnedApps(OwnedAppsInput{Account: account})
|
||||
|
||||
Expect(errors.Is(err, requestErr)).To(BeTrue())
|
||||
Expect(errors.Is(err, cleanupErr)).To(BeTrue())
|
||||
Expect(signer.closeCalls).To(Equal(1))
|
||||
})
|
||||
})
|
||||
|
||||
When("the machine address cannot be read", func() {
|
||||
It("returns an error before creating a signer", func() {
|
||||
mockMachine.EXPECT().MacAddress().Return("", errors.New("machine error"))
|
||||
|
||||
_, err := as.OwnedApps(OwnedAppsInput{Account: account})
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("failed to get mac address")))
|
||||
})
|
||||
})
|
||||
|
||||
DescribeTable("validates and defaults pagination",
|
||||
func(input OwnedAppsInput, expected OwnedAppsInput, errorText string) {
|
||||
actual, err := normalizeOwnedAppsInput(input)
|
||||
if errorText != "" {
|
||||
Expect(err).To(MatchError(ContainSubstring(errorText)))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(actual).To(Equal(expected))
|
||||
},
|
||||
Entry("defaults page and limit", OwnedAppsInput{}, OwnedAppsInput{Page: 1, Limit: 10}, ""),
|
||||
Entry("accepts the maximum limit", OwnedAppsInput{Page: 3, Limit: 100}, OwnedAppsInput{Page: 3, Limit: 100}, ""),
|
||||
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"),
|
||||
)
|
||||
})
|
||||
|
||||
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, dmapAppIDForTest(123)...)
|
||||
item = append(item, dmapString("aeBI", "com.example.app")...)
|
||||
item = append(item, dmapString("aeLN", "Example")...)
|
||||
item = append(item, dmapString("aePd", "1.2.3")...)
|
||||
item = append(item, dmapUint32("asdp", 1_700_000_000)...)
|
||||
listing := append(dmapTag("mlit", item), dmapTag("mlit", item)...)
|
||||
response := dmapTag("adbs", dmapTag("mlcl", listing))
|
||||
|
||||
apps, err := parseOwnedApps(response)
|
||||
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(apps).To(Equal([]App{{
|
||||
ID: 123,
|
||||
BundleID: "com.example.app",
|
||||
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(dmapAppIDForTest(123), dmapTag("asdp", []byte{1, 2, 3})...)
|
||||
response := dmapTag("adbs", dmapTag("mlcl", dmapTag("mlit", item)))
|
||||
|
||||
_, err := parseOwnedApps(response)
|
||||
|
||||
Expect(err).To(MatchError(ContainSubstring("purchase date has invalid length 3")))
|
||||
})
|
||||
|
||||
It("rejects a truncated tag", func() {
|
||||
_, err := parseOwnedApps([]byte("adbs\x00\x00\x00\x10short"))
|
||||
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("exceeds remaining response length"))
|
||||
})
|
||||
|
||||
It("rejects a protocol-level error status", func() {
|
||||
response := dmapTag("mlog", dmapUint32("mstt", gohttp.StatusForbidden))
|
||||
|
||||
err := ownedAppsDMAPStatusError("purchase history login", response)
|
||||
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(errors.Is(err, ErrPasswordTokenExpired)).To(BeTrue())
|
||||
Expect(err.Error()).To(ContainSubstring("DAAP status 403"))
|
||||
})
|
||||
|
||||
It("preserves a partial last page", func() {
|
||||
apps := []App{{ID: 1}, {ID: 2}, {ID: 3}}
|
||||
|
||||
Expect(ownedAppsPage(apps, 2, 2)).To(Equal([]App{{ID: 3}}))
|
||||
Expect(ownedAppsPage(apps, 3, 2)).To(BeEmpty())
|
||||
Expect(ownedAppsPage(apps, math.MaxInt, 100)).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("sorts missing dates last and preserves response order for ties", func() {
|
||||
date := time.Unix(1_700_000_000, 0).UTC()
|
||||
apps := []App{
|
||||
{ID: 1},
|
||||
{ID: 2, PurchaseDate: date},
|
||||
{ID: 3, PurchaseDate: date.Add(time.Hour)},
|
||||
{ID: 4, PurchaseDate: date},
|
||||
{ID: 5},
|
||||
}
|
||||
|
||||
sorted := ownedAppsSortedByPurchaseDate(apps)
|
||||
|
||||
Expect(sorted).To(Equal([]App{
|
||||
{ID: 3, PurchaseDate: date.Add(time.Hour)},
|
||||
{ID: 2, PurchaseDate: date},
|
||||
{ID: 4, PurchaseDate: date},
|
||||
{ID: 1},
|
||||
{ID: 5},
|
||||
}))
|
||||
Expect(apps[0].ID).To(Equal(int64(1)))
|
||||
})
|
||||
|
||||
It("builds the dynamic DMAP item request body", func() {
|
||||
now := time.Unix(1_700_000_000, 0)
|
||||
query := "('com.apple.itunes.extended\\-media\\-kind:131072')"
|
||||
body := ownedAppsItemsBody(42, 99, query, now)
|
||||
|
||||
timestamp, found, err := firstDMAPUint(body, "mstc")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(timestamp).To(Equal(uint64(1_700_000_000)))
|
||||
sessionID, found, err := firstDMAPUint(body, "mlid")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(found).To(BeTrue())
|
||||
Expect(sessionID).To(Equal(uint64(42)))
|
||||
})
|
||||
})
|
||||
|
||||
func expectOwnedAppsHeaders(headers map[string]string, account Account, guid string) {
|
||||
Expect(headers).To(HaveKeyWithValue("X-Dsid", account.DirectoryServicesID))
|
||||
Expect(headers).To(HaveKeyWithValue("iCloud-DSID", account.DirectoryServicesID))
|
||||
Expect(headers).To(HaveKeyWithValue("X-Token", account.PasswordToken))
|
||||
Expect(headers).To(HaveKeyWithValue("X-Apple-Store-Front", account.StoreFront))
|
||||
Expect(headers).To(HaveKeyWithValue("X-Guid", guid))
|
||||
Expect(headers).To(HaveKeyWithValue("Client-DAAP-Version", "3.12"))
|
||||
Expect(headers).To(HaveKeyWithValue("Client-Cloud-Purchase-Daap-Version", "1.1/Configurator-2.0"))
|
||||
}
|
||||
|
||||
func ownedAppsDMAPResponse(apps []App) []byte {
|
||||
listing := make([]byte, 0, len(apps)*128)
|
||||
|
||||
for _, app := range apps {
|
||||
item := make([]byte, 0, 128)
|
||||
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)...)
|
||||
|
||||
if !app.PurchaseDate.IsZero() {
|
||||
item = append(item, dmapUint32("asdp", uint32(app.PurchaseDate.Unix()))...)
|
||||
}
|
||||
|
||||
listing = append(listing, dmapTag("mlit", item)...)
|
||||
}
|
||||
|
||||
return dmapTag("adbs", dmapTag("mlcl", listing))
|
||||
}
|
||||
|
||||
func dmapAppIDForTest(value uint64) []byte {
|
||||
payload := make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(payload, value)
|
||||
|
||||
return dmapTag("aeSI", payload)
|
||||
}
|
||||
@@ -12,8 +12,14 @@ import (
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
var (
|
||||
errPlatformAppNotFound = errors.New("platform version lookup returned no app")
|
||||
errPlatformOffersNotFound = errors.New("platform version lookup returned no offers")
|
||||
)
|
||||
|
||||
type platformVersionLookupResult struct {
|
||||
Results map[string]platformVersionLookupItem `json:"results,omitempty"`
|
||||
Data []catalogVersionLookupItem `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
type platformVersionLookupItem struct {
|
||||
@@ -66,52 +72,105 @@ func (t *appstore) lookupLatestExternalVersionID(acc Account, app App, platform
|
||||
return "", fmt.Errorf("failed to resolve the country code: %w", err)
|
||||
}
|
||||
|
||||
request, err := t.platformVersionLookupRequest(app.ID, countryCode, platform)
|
||||
if platform == PlatformVisionOS {
|
||||
return t.lookupLatestVisionOSExternalVersionID(app.ID, countryCode)
|
||||
}
|
||||
|
||||
metadataPlatform, err := platform.metadataPlatform()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create platform version lookup request: %w", err)
|
||||
}
|
||||
|
||||
res, err := t.platformClient.Send(request)
|
||||
catalogs := []string{metadataPlatform}
|
||||
if platform == PlatformIPhone || platform == PlatformIPad || platform == PlatformWatchOS {
|
||||
// Some storefronts have no enterprise listing even when the consumer
|
||||
// catalogs contain the app. Keep the account's country for each lookup.
|
||||
catalogs = append(catalogs, "iphone", "ipad")
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
|
||||
for _, catalog := range catalogs {
|
||||
request := t.platformVersionLookupRequest(app.ID, countryCode, catalog)
|
||||
|
||||
res, err := t.platformClient.Send(request)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("platform version lookup request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup request failed"), res)
|
||||
}
|
||||
|
||||
item, ok := res.Data.Results[strconv.FormatInt(app.ID, 10)]
|
||||
if !ok {
|
||||
lastErr = NewErrorWithMetadata(errPlatformAppNotFound, res)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if len(item.Offers) == 0 {
|
||||
lastErr = NewErrorWithMetadata(errPlatformOffersNotFound, res)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
offer := item.Offers[0]
|
||||
externalVersionID := string(offer.Version.ExternalID)
|
||||
|
||||
if externalVersionID == "" {
|
||||
externalVersionID, err = externalVersionIDFromBuyParams(offer.BuyParams)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse buy params: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if externalVersionID == "" {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no external version id"), res)
|
||||
}
|
||||
|
||||
return externalVersionID, nil
|
||||
}
|
||||
|
||||
if platform == PlatformIPhone || platform == PlatformIPad {
|
||||
// Apple Arcade apps can be absent from every MDM catalog. The App
|
||||
// Store's catalog API still exposes their current iOS version.
|
||||
version, err := t.lookupLatestIOSExternalVersionID(app, countryCode, platform)
|
||||
if err == nil {
|
||||
return version, nil
|
||||
}
|
||||
|
||||
lastErr = fmt.Errorf("%w; iOS catalog fallback failed: %w", lastErr, err)
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("app %d in storefront %s (catalogs: %s): %w", app.ID, countryCode, strings.Join(catalogs, ", "), lastErr)
|
||||
}
|
||||
|
||||
func (t *appstore) lookupLatestVisionOSExternalVersionID(appID int64, countryCode string) (string, error) {
|
||||
request := http.Request{
|
||||
URL: visionProductURL(appID, countryCode),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatRaw,
|
||||
}
|
||||
|
||||
res, err := t.storefrontClient.Send(request)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("platform version lookup request failed: %w", err)
|
||||
return "", fmt.Errorf("visionOS version lookup request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup request failed"), res)
|
||||
return "", NewErrorWithMetadata(errors.New("visionOS version lookup request failed"), res)
|
||||
}
|
||||
|
||||
item, ok := res.Data.Results[strconv.FormatInt(app.ID, 10)]
|
||||
if !ok {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no app"), res)
|
||||
}
|
||||
|
||||
if len(item.Offers) == 0 {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no offers"), res)
|
||||
}
|
||||
|
||||
offer := item.Offers[0]
|
||||
externalVersionID := string(offer.Version.ExternalID)
|
||||
|
||||
if externalVersionID == "" {
|
||||
externalVersionID, err = externalVersionIDFromBuyParams(offer.BuyParams)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse buy params: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if externalVersionID == "" {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no external version id"), res)
|
||||
externalVersionID, err := visionExternalVersionID(res.Data, appID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse visionOS version lookup response: %w", err)
|
||||
}
|
||||
|
||||
return externalVersionID, nil
|
||||
}
|
||||
|
||||
func (*appstore) platformVersionLookupRequest(appID int64, countryCode string, platform Platform) (http.Request, error) {
|
||||
metadataPlatform, err := platform.metadataPlatform()
|
||||
if err != nil {
|
||||
return http.Request{}, err
|
||||
}
|
||||
|
||||
func (*appstore) platformVersionLookupRequest(appID int64, countryCode, metadataPlatform string) http.Request {
|
||||
params := url.Values{}
|
||||
params.Add("version", "2")
|
||||
params.Add("id", strconv.FormatInt(appID, 10))
|
||||
@@ -125,7 +184,7 @@ func (*appstore) platformVersionLookupRequest(appID int64, countryCode string, p
|
||||
URL: fmt.Sprintf("https://uclient-api.itunes.apple.com/WebObjects/MZStorePlatform.woa/wa/lookup?%s", params.Encode()),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatJSON,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func externalVersionIDFromBuyParams(buyParams string) (string, error) {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("Platform version catalog fallback", func() {
|
||||
var client *http.MockClient[platformVersionLookupResult]
|
||||
var store *appstore
|
||||
account := Account{StoreFront: "143469-1,34"}
|
||||
app := App{ID: 6472431552}
|
||||
missing := platformVersionLookupResult{}
|
||||
noOffers := platformVersionLookupResult{Results: map[string]platformVersionLookupItem{"6472431552": {}}}
|
||||
withOffer := func(offer platformVersionLookupOffer) platformVersionLookupResult {
|
||||
return platformVersionLookupResult{Results: map[string]platformVersionLookupItem{"6472431552": {Offers: []platformVersionLookupOffer{offer}}}}
|
||||
}
|
||||
valid := withOffer(platformVersionLookupOffer{Version: platformVersionLookupVersion{ExternalID: "891116578"}})
|
||||
|
||||
BeforeEach(func() {
|
||||
client = http.NewMockClient[platformVersionLookupResult](gomock.NewController(GinkgoT()))
|
||||
store = &appstore{platformClient: client}
|
||||
})
|
||||
|
||||
expectLookup := func(catalog string, status int, data platformVersionLookupResult, sendErr error) *gomock.Call {
|
||||
return client.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
|
||||
u, err := url.Parse(req.URL)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(u.Query().Get("platform")).To(Equal(catalog))
|
||||
Expect(u.Query().Get("cc")).To(Equal("ru"))
|
||||
Expect(u.Query().Get("id")).To(Equal("6472431552"))
|
||||
}).Return(http.Result[platformVersionLookupResult]{StatusCode: status, Data: data}, sendErr)
|
||||
}
|
||||
|
||||
DescribeTable("stops at the first available iOS catalog", func(platform Platform, empty platformVersionLookupResult, successIndex int, offer platformVersionLookupResult) {
|
||||
var calls []any
|
||||
for i, catalog := range []string{"enterprisestore", "iphone", "ipad"} {
|
||||
data := empty
|
||||
if i == successIndex {
|
||||
data = offer
|
||||
}
|
||||
calls = append(calls, expectLookup(catalog, 200, data, nil))
|
||||
if i == successIndex {
|
||||
break
|
||||
}
|
||||
}
|
||||
gomock.InOrder(calls...)
|
||||
version, err := store.lookupLatestExternalVersionID(account, app, platform)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(version).To(Equal("891116578"))
|
||||
},
|
||||
Entry("enterprise succeeds", PlatformIPhone, missing, 0, valid),
|
||||
Entry("missing enterprise app", PlatformIPhone, missing, 1, valid),
|
||||
Entry("empty enterprise offers", PlatformIPhone, noOffers, 1, valid),
|
||||
Entry("only iPad catalog succeeds", PlatformIPhone, missing, 2, valid),
|
||||
Entry("empty offers until iPad", PlatformIPad, noOffers, 2, valid),
|
||||
Entry("iPad request uses iPhone fallback first", PlatformIPad, missing, 1, valid),
|
||||
Entry("consumer buy params version", PlatformIPhone, missing, 1, withOffer(platformVersionLookupOffer{BuyParams: "appExtVrsId=891116578"})),
|
||||
Entry("watchOS shares the enterprise catalog", PlatformWatchOS, missing, 0, valid),
|
||||
Entry("watchOS falls back to the consumer catalog", PlatformWatchOS, missing, 1, valid),
|
||||
)
|
||||
|
||||
DescribeTable("reports exhausted catalogs", func(empty platformVersionLookupResult, message string) {
|
||||
gomock.InOrder(
|
||||
expectLookup("enterprisestore", 200, empty, nil),
|
||||
expectLookup("iphone", 200, empty, nil),
|
||||
expectLookup("ipad", 200, empty, nil),
|
||||
client.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{StatusCode: 200}, nil),
|
||||
)
|
||||
version, err := store.lookupLatestExternalVersionID(account, app, PlatformIPhone)
|
||||
Expect(version).To(BeEmpty())
|
||||
Expect(err).To(MatchError(And(ContainSubstring(message), ContainSubstring("6472431552"), ContainSubstring("RU"), ContainSubstring("enterprisestore, iphone, ipad"))))
|
||||
}, Entry("missing apps", missing, "returned no app"), Entry("empty offers", noOffers, "returned no offers"))
|
||||
|
||||
DescribeTable("does not fall back after a request or offer error", func(status int, data platformVersionLookupResult, sendErr error, message string) {
|
||||
expectLookup("enterprisestore", status, data, sendErr)
|
||||
_, err := store.lookupLatestExternalVersionID(account, app, PlatformIPhone)
|
||||
Expect(err).To(MatchError(ContainSubstring(message)))
|
||||
if sendErr != nil {
|
||||
Expect(errors.Is(err, sendErr)).To(BeTrue())
|
||||
}
|
||||
},
|
||||
Entry("transport failure", 0, missing, errors.New("connection reset"), "request failed"),
|
||||
Entry("decoding failure", 200, missing, errors.New("invalid JSON"), "request failed"),
|
||||
Entry("HTTP failure", 503, missing, nil, "request failed"),
|
||||
Entry("missing version", 200, withOffer(platformVersionLookupOffer{}), nil, "no external version id"),
|
||||
Entry("malformed buy params", 200, withOffer(platformVersionLookupOffer{BuyParams: "appExtVrsId=%zz"}), nil, "failed to parse buy params"),
|
||||
)
|
||||
|
||||
It("stops on an HTTP error in a consumer catalog", func() {
|
||||
gomock.InOrder(expectLookup("enterprisestore", 200, missing, nil), expectLookup("iphone", 503, missing, nil))
|
||||
_, err := store.lookupLatestExternalVersionID(account, app, PlatformIPhone)
|
||||
Expect(err).To(MatchError(ContainSubstring("request failed")))
|
||||
})
|
||||
|
||||
It("does not use iOS catalogs for Apple TV", func() {
|
||||
expectLookup("atv9", 200, missing, nil)
|
||||
_, err := store.lookupLatestExternalVersionID(account, app, PlatformAppleTV)
|
||||
Expect(err).To(MatchError(ContainSubstring("returned no app")))
|
||||
})
|
||||
})
|
||||
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user