Compare commits

...
7 Commits
40 changed files with 2317 additions and 127 deletions

No files matched your search

-34
View File
@@ -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.
+29 -9
View File
@@ -3,7 +3,7 @@
[![Release](https://img.shields.io/github/release/majd/ipatool.svg?label=Release)](https://GitHub.com/majd/ipatool/releases/)
[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/majd/ipatool/blob/main/LICENSE)
`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.
`ipatool` is a command line tool that allows you to search for iOS, iPadOS, tvOS, and visionOS apps on the [App Store](https://apps.apple.com) and download a copy of the app package, known as an _ipa_ file.
![Demo](./resources/demo.gif)
@@ -65,15 +65,15 @@ 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
Search for iOS, iPadOS, tvOS, and visionOS apps available on the App Store
Usage:
ipatool search <term> [flags]
Flags:
-h, --help help for search
-l, --limit int maximum amount of search results to retrieve (default 5)
--platform string Platform to search: iphone, ipad, or appletv
-l, --limit int maximum amount of search results to retrieve; visionOS supports up to 12 (default 5)
--platform string Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), or visionos
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
@@ -99,6 +99,26 @@ Global Flags:
--verbose enables verbose logs
```
To list apps owned by the authenticated account, use the `list-purchases` command. Results are ordered by purchase date, newest first.
```
List apps owned by the authenticated App Store account
Usage:
ipatool list-purchases [flags]
Flags:
-h, --help help for list-purchases
-l, --max-results int maximum number of apps to return per page (default 10)
-p, --page int page of owned apps to return (default 1)
Global Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
--keychain-passphrase string passphrase for unlocking keychain
--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.
```
@@ -122,18 +142,18 @@ Global Flags:
To download a copy of the ipa file, use the `download` command.
```
Download (encrypted) iOS and tvOS app packages from the App Store
Download (encrypted) iOS, iPadOS, tvOS, and visionOS app packages from the App Store
Usage:
ipatool download [flags]
Flags:
-i, --app-id int ID of the target 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)
-i, --app-id int ID of the target app (required)
-b, --bundle-identifier string The bundle identifier of the target app (overrides the app ID)
--external-version-id string External version identifier of the target app (defaults to latest version when not specified)
-h, --help help for download
-o, --output string The destination path of the downloaded app package
--platform string Platform to download for: iphone, ipad, or appletv
--platform string Platform to download for: iphone (iOS), ipad (iPadOS), appletv (tvOS), or visionos
--purchase Obtain a license for the app if needed
Global Flags:
+2
View File
@@ -62,6 +62,8 @@ func loginCmd() *cobra.Command {
password = string(bytes)
}
dependencies.Logger.Log().Msg("preparing authentication; the first login may take a few minutes")
var lastErr error
// nolint:wrapcheck
+13
View File
@@ -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")
}
+7 -3
View File
@@ -67,8 +67,9 @@ func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) k
keyring.SecretServiceBackend,
keyring.FileBackend,
},
ServiceName: KeychainServiceName,
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
ServiceName: KeychainServiceName,
KeychainTrustApplication: true,
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
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")
@@ -93,7 +94,10 @@ func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) k
},
}))
return keychain.New(keychain.Args{Keyring: ring})
return keychain.New(keychain.Args{
Keyring: ring,
Label: KeychainServiceName,
})
}
// initWithCommand initializes the dependencies of the command.
+5 -5
View File
@@ -24,7 +24,7 @@ func downloadCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "download",
Short: "Download (encrypted) iOS and tvOS app packages from the App Store",
Short: "Download (encrypted) iOS, iPadOS, tvOS, and visionOS 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")
@@ -149,11 +149,11 @@ 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)")
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), or visionos")
cmd.Flags().BoolVar(&acquireLicense, "purchase", false, "Obtain a license for the app if needed")
return cmd
+91
View File
@@ -0,0 +1,91 @@
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
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)
}
return nil
},
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,
})
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")
return cmd
}
+41
View File
@@ -0,0 +1,41 @@
package cmd
import (
"github.com/majd/ipatool/v2/pkg/appstore"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("List Purchases command", func() {
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"))
})
})
+1
View File
@@ -47,6 +47,7 @@ func rootCmd() *cobra.Command {
cmd.AddCommand(authCmd())
cmd.AddCommand(downloadCmd())
cmd.AddCommand(listPurchasesCmd())
cmd.AddCommand(purchaseCmd())
cmd.AddCommand(searchCmd())
cmd.AddCommand(ListVersionsCmd())
+3 -3
View File
@@ -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, and visionOS 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), or visionos")
return cmd
}
+6 -1
View File
@@ -13,6 +13,8 @@ import (
"github.com/majd/ipatool/v2/internal/sap/unicorn"
)
const sapGuestTimeout = time.Minute
const (
returnAddress = uint64(0x0000000100000000)
coreFPBase = uint64(0x0000100000000000)
@@ -431,7 +433,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
}
+22 -2
View File
@@ -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 {
+29
View File
@@ -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)
}
}
+12 -5
View File
@@ -1,15 +1,18 @@
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"`
}
type VersionHistoryInfo struct {
@@ -40,4 +43,8 @@ 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)
}
}
+24 -5
View File
@@ -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,6 +66,22 @@ 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"))
})
It("formats ipa name correctly", func() {
+10
View File
@@ -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"
@@ -18,6 +20,8 @@ type AppStore interface {
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
@@ -40,9 +44,12 @@ type appstore struct {
purchaseClient http.Client[purchaseResult]
downloadClient http.Client[downloadResult]
platformClient http.Client[platformVersionLookupResult]
storefrontClient http.Client[[]byte]
bagClient http.Client[bagResult]
ownedAppsClient http.Client[[]byte]
httpClient http.Client[interface{}]
actionSignerFactory ActionSignerFactory
authRetrySleep func(time.Duration)
machine machine.Machine
os operatingsystem.OperatingSystem
}
@@ -72,9 +79,12 @@ func NewAppStore(args Args) AppStore {
purchaseClient: http.NewClient[purchaseResult](clientArgs),
downloadClient: http.NewClient[downloadResult](clientArgs),
platformClient: http.NewClient[platformVersionLookupResult](clientArgs),
storefrontClient: http.NewClient[[]byte](clientArgs),
bagClient: http.NewClient[bagResult](clientArgs),
ownedAppsClient: http.NewClient[[]byte](clientArgs),
httpClient: http.NewClient[interface{}](clientArgs),
actionSignerFactory: actionSignerFactory,
authRetrySleep: time.Sleep,
machine: args.Machine,
os: args.OperatingSystem,
}
+18 -5
View File
@@ -41,7 +41,7 @@ func (t *appstore) Download(input DownloadInput) (DownloadOutput, error) {
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
externalVersionID := input.ExternalVersionID
if externalVersionID == "" && input.Platform == PlatformAppleTV {
if externalVersionID == "" && (input.Platform == PlatformAppleTV || input.Platform == PlatformVisionOS) {
externalVersionID, err = t.lookupLatestExternalVersionID(input.Account, input.App, input.Platform)
if err != nil {
return DownloadOutput{}, fmt.Errorf("failed to resolve platform version: %w", err)
@@ -125,7 +125,14 @@ type platformPackageInfo struct {
}
func (*appstore) validatePackagePlatform(path string, platform Platform) error {
if platform != PlatformAppleTV {
var expectedPlatform string
switch platform {
case PlatformAppleTV:
expectedPlatform = "AppleTVOS"
case PlatformVisionOS:
expectedPlatform = "XROS"
default:
return nil
}
@@ -136,7 +143,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,13 +171,19 @@ 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 {
+135 -27
View File
@@ -33,16 +33,17 @@ 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
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() {
@@ -50,20 +51,22 @@ var _ = Describe("AppStore (Download)", func() {
mockKeychain = keychain.NewMockKeychain(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,
loginClient: mockLoginClient,
purchaseClient: mockPurchaseClient,
downloadClient: mockDownloadClient,
platformClient: mockPlatformClient,
storefrontClient: mockStorefrontClient,
httpClient: mockHTTPClient,
machine: mockMachine,
os: mockOS,
}
})
@@ -187,6 +190,74 @@ var _ = Describe("AppStore (Download)", func() {
})
})
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().
@@ -628,26 +699,34 @@ var _ = Describe("AppStore (Download)", func() {
})
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"})
@@ -665,5 +744,34 @@ var _ = Describe("AppStore (Download)", func() {
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("AppleTVOS"))
})
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"))
})
})
})
+54 -1
View File
@@ -7,6 +7,7 @@ import (
gohttp "net/http"
"strconv"
"strings"
"time"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/util"
@@ -16,6 +17,11 @@ var (
ErrAuthCodeRequired = errors.New("auth code is required")
)
const (
maxAuthenticationRequestAttempts = 3
authenticationRetryDelay = 250 * time.Millisecond
)
type LoginInput struct {
Email string
Password string
@@ -119,7 +125,7 @@ func (t *appstore) login(email, password, authCode, guid, endpoint string, signe
request := t.loginRequest(email, password, authCode, guid, endpoint, requestAttempt, signer)
request.URL, _ = util.IfEmpty(redirect, request.URL), ""
res, err = t.loginClient.Send(request)
res, err = t.sendAuthenticationRequest(request)
if err != nil {
return Account{}, fmt.Errorf("request failed: %w", err)
@@ -168,6 +174,53 @@ func (t *appstore) login(email, password, authCode, guid, endpoint string, signe
return acc, nil
}
func (t *appstore) sendAuthenticationRequest(request http.Request) (http.Result[loginResult], error) {
statuses := make([]string, 0, maxAuthenticationRequestAttempts)
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, fmt.Errorf("%w", err)
}
return result, nil
}
statuses = append(statuses, strconv.Itoa(status))
if attempt == maxAuthenticationRequestAttempts {
return result, fmt.Errorf(
"authentication request failed after %d attempts (HTTP %s): %w",
maxAuthenticationRequestAttempts, strings.Join(statuses, ", "), err,
)
}
sleep(time.Duration(attempt) * authenticationRetryDelay)
}
}
func retryableAuthenticationError(err error) (int, bool) {
var responseErr *http.UnexpectedResponseError
if !errors.As(err, &responseErr) {
return 0, false
}
status := responseErr.StatusCode
retry := status == gohttp.StatusNoContent ||
status == gohttp.StatusNotFound ||
status/100 == 5
return status, retry
}
func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int, authCode string) (bool, string, error) {
var (
retry bool
+59 -4
View File
@@ -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,59 @@ var _ = Describe("AppStore (Login)", func() {
ctrl.Finish()
})
Describe("transient authentication responses", func() {
It("retries the same request until it succeeds", func() {
request := as.loginRequest(testEmail, 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.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))
})
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("does not retry HTTP 403", 403, 1),
)
})
When("fails to read Machine's MAC address", func() {
BeforeEach(func() {
mockMachine.EXPECT().
+552
View File
@@ -0,0 +1,552 @@
package appstore
import (
"encoding/binary"
"errors"
"fmt"
"math"
gohttp "net/http"
"sort"
"strconv"
"time"
"github.com/majd/ipatool/v2/pkg/http"
)
const (
DefaultOwnedAppsLimit = 10
MaxOwnedAppsLimit = 100
ownedAppsMediaKind = 131072
)
type OwnedAppsInput struct {
Account Account
Page int
Limit int
}
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)
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) {
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) {
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')", ownedAppsMediaKind)
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)
seen := make(map[int64]struct{})
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
}
if _, ok := seen[app.ID]; ok {
return nil
}
seen[app.ID] = struct{}{}
apps = append(apps, app)
return nil
})
if err != nil {
return nil, err
}
return apps, nil
}
func parseOwnedApp(data []byte) (App, error) {
var app App
err := walkDMAP(data, 0, func(tag string, payload []byte) error {
switch tag {
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
})
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)]...)
}
+396
View File
@@ -0,0 +1,396 @@
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"
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)
}
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')"))
}).
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)))
}).
Return(http.Result[[]byte]{
StatusCode: gohttp.StatusOK,
Data: ownedAppsDMAPResponse(apps),
}, nil)
gomock.InOrder(loginCall, updateCall, itemsCall)
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),
)
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"),
)
})
var _ = Describe("owned-app DMAP parsing", func() {
It("parses app fields, ignores unknown fields, and removes duplicate IDs", func() {
item := make([]byte, 0, 128)
item = append(item, dmapString("zzzz", "unknown")...)
item = append(item, dmapUint64ForTest("aeSI", 123)...)
item = append(item, 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(),
}}))
})
It("rejects a malformed purchase date", func() {
item := append(dmapUint64ForTest("aeSI", 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, dmapUint64ForTest("aeSI", 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 dmapUint64ForTest(name string, value uint64) []byte {
payload := make([]byte, 8)
binary.BigEndian.PutUint64(payload, value)
return dmapTag(name, payload)
}
@@ -66,6 +66,10 @@ func (t *appstore) lookupLatestExternalVersionID(acc Account, app App, platform
return "", fmt.Errorf("failed to resolve the country code: %w", err)
}
if platform == PlatformVisionOS {
return t.lookupLatestVisionOSExternalVersionID(app.ID, countryCode)
}
request, err := t.platformVersionLookupRequest(app.ID, countryCode, platform)
if err != nil {
return "", fmt.Errorf("failed to create platform version lookup request: %w", err)
@@ -106,6 +110,30 @@ func (t *appstore) lookupLatestExternalVersionID(acc Account, app App, platform
return externalVersionID, nil
}
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("visionOS version lookup request failed: %w", err)
}
if res.StatusCode != gohttp.StatusOK {
return "", NewErrorWithMetadata(errors.New("visionOS version lookup request failed"), 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 {
+2 -3
View File
@@ -164,14 +164,13 @@ func (t *appstore) replicateSinfFromInfo(info packageInfo, zip *zip.Writer, sinf
func (t *appstore) replicateZip(src *zip.ReadCloser, dst *zip.Writer) error {
for _, file := range src.File {
err := func() error {
srcFile, err := file.Open()
srcFile, err := file.OpenRaw()
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer srcFile.Close()
header := file.FileHeader
dstFile, err := dst.CreateHeader(&header)
dstFile, err := dst.CreateRaw(&header)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
+84
View File
@@ -6,6 +6,7 @@ import (
gohttp "net/http"
"net/url"
"strconv"
"strings"
"github.com/majd/ipatool/v2/pkg/http"
)
@@ -28,6 +29,10 @@ func (t *appstore) Search(input SearchInput) (SearchOutput, error) {
return SearchOutput{}, fmt.Errorf("country code is invalid: %w", err)
}
if input.Platform == PlatformVisionOS {
return t.searchVisionOS(input, countryCode)
}
request, err := t.searchRequest(input.Term, countryCode, input.Limit, input.Platform)
if err != nil {
return SearchOutput{}, fmt.Errorf("failed to create search request: %w", err)
@@ -48,6 +53,67 @@ func (t *appstore) Search(input SearchInput) (SearchOutput, error) {
}, nil
}
func (t *appstore) searchVisionOS(input SearchInput, countryCode string) (SearchOutput, error) {
request := http.Request{
URL: visionSearchURL(input.Term, countryCode),
Method: http.MethodGET,
ResponseFormat: http.ResponseFormatRaw,
}
res, err := t.storefrontClient.Send(request)
if err != nil {
return SearchOutput{}, fmt.Errorf("visionOS search request failed: %w", err)
}
if res.StatusCode != gohttp.StatusOK {
return SearchOutput{}, NewErrorWithMetadata(errors.New("visionOS search request failed"), res)
}
storefrontApps, err := storefrontVisionApps(res.Data, input.Limit)
if err != nil {
return SearchOutput{}, fmt.Errorf("failed to parse visionOS search results: %w", err)
}
if len(storefrontApps) == 0 {
return SearchOutput{Results: []App{}}, nil
}
ids := make([]string, 0, len(storefrontApps))
for _, app := range storefrontApps {
ids = append(ids, strconv.FormatInt(app.ID, 10))
}
lookupRequest, err := t.lookupIDsRequest(ids, countryCode, PlatformVisionOS)
if err != nil {
return SearchOutput{}, fmt.Errorf("failed to create visionOS metadata request: %w", err)
}
lookupResponse, err := t.searchClient.Send(lookupRequest)
if err != nil {
return SearchOutput{}, fmt.Errorf("visionOS metadata request failed: %w", err)
}
if lookupResponse.StatusCode != gohttp.StatusOK {
return SearchOutput{}, NewErrorWithMetadata(errors.New("visionOS metadata request failed"), lookupResponse)
}
hydrated := make(map[int64]App, len(lookupResponse.Data.Results))
for _, app := range lookupResponse.Data.Results {
hydrated[app.ID] = app
}
for index, app := range storefrontApps {
if metadata, ok := hydrated[app.ID]; ok {
storefrontApps[index] = metadata
}
}
return SearchOutput{
Count: len(storefrontApps),
Results: storefrontApps,
}, nil
}
type searchResult struct {
Count int `json:"resultCount,omitempty"`
Results []App `json:"results,omitempty"`
@@ -81,3 +147,21 @@ func (t *appstore) searchURL(term, countryCode string, limit int64, platform Pla
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathSearch, params.Encode()), nil
}
func (*appstore) lookupIDsRequest(ids []string, countryCode string, platform Platform) (http.Request, error) {
entity, err := platform.lookupEntity()
if err != nil {
return http.Request{}, err
}
params := url.Values{}
params.Add("entity", entity)
params.Add("id", strings.Join(ids, ","))
params.Add("country", countryCode)
return http.Request{
URL: fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathLookup, params.Encode()),
Method: http.MethodGET,
ResponseFormat: http.ResponseFormatJSON,
}, nil
}
+71 -4
View File
@@ -12,16 +12,19 @@ import (
var _ = Describe("AppStore (Search)", func() {
var (
ctrl *gomock.Controller
mockClient *http.MockClient[searchResult]
as AppStore
ctrl *gomock.Controller
mockClient *http.MockClient[searchResult]
mockStorefrontClient *http.MockClient[[]byte]
as AppStore
)
BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())
mockClient = http.NewMockClient[searchResult](ctrl)
mockStorefrontClient = http.NewMockClient[[]byte](ctrl)
as = &appstore{
searchClient: mockClient,
searchClient: mockClient,
storefrontClient: mockStorefrontClient,
}
})
@@ -100,6 +103,70 @@ var _ = Describe("AppStore (Search)", func() {
})
})
When("platform is visionOS", func() {
const searchPage = `<html><script type="application/json" id="serialized-server-data">{
"data":[{"data":{"shelves":[{"items":[
{"$kind":"EditorialItem","lockup":{"adamId":"999"},"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=999&appExtVrsId=9990"}},
{"$kind":"AppSearchResult","lockup":{"adamId":"200","bundleId":"fallback.two","title":"Fallback Two"},"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=200&appExtVrsId=2000"}},
{"$kind":"AppSearchResult","lockup":{"adamId":"300","bundleId":"wrong.platform","title":"Wrong Platform"},"purchaseConfiguration":{"metricsPlatformDisplayStyle":"ios","appPlatforms":["iphone"],"buyParams":"salableAdamId=300&appExtVrsId=3000"}},
{"$kind":"AppSearchResult","lockup":{"adamId":"100","bundleId":"fallback.one","title":"Fallback One"},"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=100&appExtVrsId=1000"}},
{"$kind":"AppSearchResult","lockup":{"adamId":"400","bundleId":"limited.out","title":"Limited Out"},"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=400&appExtVrsId=4000"}}
] }]}}]}
</script></html>`
BeforeEach(func() {
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/vision/search"))
Expect(parsedURL.Query().Get("term")).To(Equal("spatial notes"))
Expect(req.Method).To(Equal(http.MethodGET))
Expect(req.ResponseFormat).To(Equal(http.ResponseFormatRaw))
}).
Return(http.Result[[]byte]{StatusCode: 200, Data: []byte(searchPage)}, nil)
mockClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
parsedURL, err := url.Parse(req.URL)
Expect(err).ToNot(HaveOccurred())
Expect(parsedURL.Path).To(Equal("/lookup"))
Expect(parsedURL.Query().Get("country")).To(Equal("US"))
Expect(parsedURL.Query().Get("entity")).To(Equal("xrosSoftware"))
Expect(parsedURL.Query().Get("id")).To(Equal("200,100"))
}).
Return(http.Result[searchResult]{
StatusCode: 200,
Data: searchResult{
Count: 2,
Results: []App{
{ID: 100, BundleID: "hydrated.one", Name: "Hydrated One", Version: "1.0"},
{ID: 200, BundleID: "hydrated.two", Name: "Hydrated Two", Version: "2.0"},
},
},
}, nil)
})
It("filters native results, applies the limit, hydrates metadata, and preserves storefront order", func() {
out, err := as.Search(SearchInput{
Account: Account{StoreFront: "143441"},
Term: "spatial notes",
Limit: 2,
Platform: PlatformVisionOS,
})
Expect(err).ToNot(HaveOccurred())
Expect(out.Count).To(Equal(2))
Expect(out.Results).To(Equal([]App{
{ID: 200, BundleID: "hydrated.two", Name: "Hydrated Two", Version: "2.0"},
{ID: 100, BundleID: "hydrated.one", Name: "Hydrated One", Version: "1.0"},
}))
})
})
When("store front is invalid", func() {
It("returns error", func() {
_, err := as.Search(SearchInput{
+255
View File
@@ -0,0 +1,255 @@
package appstore
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/url"
"strconv"
"strings"
)
const (
serializedServerDataID = "serialized-server-data"
maxVisionOSSearchResults = 12
)
type storefrontSearchPage struct {
Data []struct {
Data struct {
Shelves []struct {
Items []json.RawMessage `json:"items,omitempty"`
} `json:"shelves,omitempty"`
} `json:"data,omitempty"`
} `json:"data,omitempty"`
}
type storefrontSearchItem struct {
Kind string `json:"$kind,omitempty"`
Lockup json.RawMessage `json:"lockup,omitempty"`
}
type storefrontAppLockup struct {
AdamID string `json:"adamId,omitempty"`
BundleID string `json:"bundleId,omitempty"`
Title string `json:"title,omitempty"`
}
func serializedServerData(body []byte) ([]byte, error) {
markerIndex := bytes.Index(body, []byte(`id="`+serializedServerDataID+`"`))
if markerIndex == -1 {
markerIndex = bytes.Index(body, []byte(`id='`+serializedServerDataID+`'`))
}
if markerIndex == -1 {
return nil, errors.New("serialized server data was not found")
}
scriptStart := bytes.LastIndex(body[:markerIndex], []byte("<script"))
if scriptStart == -1 {
return nil, errors.New("serialized server data script was not found")
}
contentOffset := bytes.IndexByte(body[markerIndex:], '>')
if contentOffset == -1 {
return nil, errors.New("serialized server data script is malformed")
}
contentStart := markerIndex + contentOffset + 1
contentEndOffset := bytes.Index(body[contentStart:], []byte("</script>"))
if contentEndOffset == -1 {
return nil, errors.New("serialized server data script is not closed")
}
return bytes.TrimSpace(body[contentStart : contentStart+contentEndOffset]), nil
}
func storefrontVisionApps(body []byte, limit int64) ([]App, error) {
data, err := serializedServerData(body)
if err != nil {
return nil, err
}
var page storefrontSearchPage
if err := json.Unmarshal(data, &page); err != nil {
return nil, fmt.Errorf("failed to decode serialized server data: %w", err)
}
if limit <= 0 {
return []App{}, nil
}
limit = min(limit, maxVisionOSSearchResults)
apps := make([]App, 0, int(limit))
seen := make(map[int64]struct{})
for _, pageData := range page.Data {
for _, shelf := range pageData.Data.Shelves {
for _, rawItem := range shelf.Items {
var item storefrontSearchItem
if err := json.Unmarshal(rawItem, &item); err != nil || item.Kind != "AppSearchResult" {
continue
}
var lockup storefrontAppLockup
if err := json.Unmarshal(item.Lockup, &lockup); err != nil {
continue
}
appID, err := strconv.ParseInt(lockup.AdamID, 10, 64)
if err != nil || appID == 0 {
continue
}
if _, ok := seen[appID]; ok {
continue
}
if !containsVisionPurchaseConfiguration(rawItem, appID) {
continue
}
seen[appID] = struct{}{}
apps = append(apps, App{
ID: appID,
BundleID: lockup.BundleID,
Name: lockup.Title,
})
if int64(len(apps)) == limit {
return apps, nil
}
}
}
}
return apps, nil
}
func containsVisionPurchaseConfiguration(data []byte, appID int64) bool {
var value interface{}
if err := json.Unmarshal(data, &value); err != nil {
return false
}
_, found := findVisionExternalVersionID(value, appID)
return found
}
func visionExternalVersionID(body []byte, appID int64) (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 serialized server data: %w", err)
}
externalVersionID, found := findVisionExternalVersionID(value, appID)
if !found {
return "", errors.New("visionOS purchase configuration was not found")
}
if externalVersionID == "" {
return "", errors.New("visionOS purchase configuration has no external version id")
}
return externalVersionID, nil
}
func findVisionExternalVersionID(value interface{}, appID int64) (string, bool) {
matched := false
switch typedValue := value.(type) {
case []interface{}:
for _, item := range typedValue {
if externalVersionID, found := findVisionExternalVersionID(item, appID); found {
if externalVersionID != "" {
return externalVersionID, true
}
matched = true
}
}
case map[string]interface{}:
if configuration, ok := typedValue["purchaseConfiguration"].(map[string]interface{}); ok {
if externalVersionID, found := externalVersionIDFromVisionConfiguration(configuration, appID); found {
if externalVersionID != "" {
return externalVersionID, true
}
matched = true
}
}
for _, child := range typedValue {
if externalVersionID, found := findVisionExternalVersionID(child, appID); found {
if externalVersionID != "" {
return externalVersionID, true
}
matched = true
}
}
}
return "", matched
}
func externalVersionIDFromVisionConfiguration(configuration map[string]interface{}, appID int64) (string, bool) {
if configuration["metricsPlatformDisplayStyle"] != "vision" {
return "", false
}
platforms, ok := configuration["appPlatforms"].([]interface{})
if !ok {
return "", false
}
isVisionApp := false
for _, platform := range platforms {
if platform == "vision" {
isVisionApp = true
break
}
}
if !isVisionApp {
return "", false
}
buyParams, ok := configuration["buyParams"].(string)
if !ok || buyParams == "" {
return "", false
}
values, err := url.ParseQuery(buyParams)
if err != nil || values.Get("salableAdamId") != strconv.FormatInt(appID, 10) {
return "", false
}
return values.Get("appExtVrsId"), true
}
func visionSearchURL(term, countryCode string) string {
params := url.Values{}
params.Set("term", term)
return fmt.Sprintf("https://apps.apple.com/%s/vision/search?%s", strings.ToLower(countryCode), params.Encode())
}
func visionProductURL(appID int64, countryCode string) string {
params := url.Values{}
params.Set("platform", "vision")
return fmt.Sprintf("https://apps.apple.com/%s/app/id%d?%s", strings.ToLower(countryCode), appID, params.Encode())
}
+155
View File
@@ -0,0 +1,155 @@
package appstore
import (
"fmt"
"strings"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func storefrontSearchItemFixture(kind, adamID, platform, salableAdamID, externalVersionID string) string {
return fmt.Sprintf(`{
"$kind":%q,
"lockup":{"adamId":%q,"bundleId":%q,"title":%q},
"offer":{"purchaseConfiguration":{
"metricsPlatformDisplayStyle":%q,
"appPlatforms":[%q],
"buyParams":%q
}}
}`,
kind,
adamID,
"bundle."+adamID,
"App "+adamID,
platform,
platform,
"salableAdamId="+salableAdamID+"&appExtVrsId="+externalVersionID,
)
}
func storefrontPageFixture(items ...string) []byte {
return []byte(`<html><head></head><body><script data-test="value" id='serialized-server-data' type="application/json">{
"data":[{"data":{"shelves":[{"items":[` +
strings.Join(items, ",") +
`] }]}}]}
</script></body></html>`)
}
var _ = Describe("App Store storefront data", func() {
Describe("storefrontVisionApps", func() {
It("keeps unique native visionOS apps in storefront order and applies the limit", func() {
body := storefrontPageFixture(
storefrontSearchItemFixture("EditorialItem", "900", "vision", "900", "9000"),
storefrontSearchItemFixture("AppSearchResult", "200", "vision", "200", "2000"),
storefrontSearchItemFixture("AppSearchResult", "300", "ios", "300", "3000"),
storefrontSearchItemFixture("AppSearchResult", "not-an-id", "vision", "0", "4000"),
storefrontSearchItemFixture("AppSearchResult", "200", "vision", "200", "2000"),
storefrontSearchItemFixture("AppSearchResult", "100", "vision", "999", "1000"),
storefrontSearchItemFixture("AppSearchResult", "100", "vision", "100", "1000"),
storefrontSearchItemFixture("AppSearchResult", "400", "vision", "400", "4000"),
)
apps, err := storefrontVisionApps(body, 2)
Expect(err).ToNot(HaveOccurred())
Expect(apps).To(Equal([]App{
{ID: 200, BundleID: "bundle.200", Name: "App 200"},
{ID: 100, BundleID: "bundle.100", Name: "App 100"},
}))
})
It("returns an empty slice for a zero limit", func() {
body := storefrontPageFixture(
storefrontSearchItemFixture("AppSearchResult", "100", "vision", "100", "1000"),
)
apps, err := storefrontVisionApps(body, 0)
Expect(err).ToNot(HaveOccurred())
Expect(apps).To(BeEmpty())
})
It("caps oversized limits to the storefront result maximum", func() {
items := make([]string, 0, maxVisionOSSearchResults+1)
for index := 1; index <= maxVisionOSSearchResults+1; index++ {
appID := fmt.Sprintf("%d", index)
items = append(items, storefrontSearchItemFixture("AppSearchResult", appID, "vision", appID, appID+"0"))
}
apps, err := storefrontVisionApps(storefrontPageFixture(items...), 1<<62)
Expect(err).ToNot(HaveOccurred())
Expect(apps).To(HaveLen(maxVisionOSSearchResults))
})
It("returns an error when serialized data is absent", func() {
_, err := storefrontVisionApps([]byte("<html></html>"), 5)
Expect(err).To(MatchError("serialized server data was not found"))
})
It("returns an error when serialized data is invalid JSON", func() {
_, err := storefrontVisionApps([]byte(`<script id="serialized-server-data">not-json</script>`), 5)
Expect(err).To(MatchError(ContainSubstring("failed to decode serialized server data")))
})
})
Describe("visionExternalVersionID", func() {
It("selects the matching vision purchase configuration", func() {
body := []byte(`<script id="serialized-server-data">{
"data":[
{"purchaseConfiguration":{"metricsPlatformDisplayStyle":"ios","appPlatforms":["iphone"],"buyParams":"salableAdamId=100&appExtVrsId=ios-version"}},
{"nested":{"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=999&appExtVrsId=wrong-app"}}},
{"nested":{"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=100&appExtVrsId=vision-version"}}}
]}
</script>`)
externalVersionID, err := visionExternalVersionID(body, 100)
Expect(err).ToNot(HaveOccurred())
Expect(externalVersionID).To(Equal("vision-version"))
})
It("returns an error when no matching vision purchase configuration exists", func() {
body := []byte(`<script id="serialized-server-data">{
"purchaseConfiguration":{"metricsPlatformDisplayStyle":"ios","appPlatforms":["iphone"],"buyParams":"salableAdamId=100&appExtVrsId=ios-version"}
}</script>`)
_, err := visionExternalVersionID(body, 100)
Expect(err).To(MatchError("visionOS purchase configuration was not found"))
})
It("distinguishes a matching configuration with no external version id", func() {
body := []byte(`<script id="serialized-server-data">{
"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=100"}
}</script>`)
_, err := visionExternalVersionID(body, 100)
Expect(err).To(MatchError("visionOS purchase configuration has no external version id"))
})
It("prefers a populated matching configuration over an empty duplicate", func() {
body := []byte(`<script id="serialized-server-data">{
"data":[
{"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=100"}},
{"purchaseConfiguration":{"metricsPlatformDisplayStyle":"vision","appPlatforms":["vision"],"buyParams":"salableAdamId=100&appExtVrsId=vision-version"}}
]
}</script>`)
externalVersionID, err := visionExternalVersionID(body, 100)
Expect(err).ToNot(HaveOccurred())
Expect(externalVersionID).To(Equal("vision-version"))
})
It("returns an error when the serialized script is not closed", func() {
_, err := visionExternalVersionID([]byte(`<script id="serialized-server-data">{}`), 100)
Expect(err).To(MatchError("serialized server data script is not closed"))
})
})
})
+2
View File
@@ -26,6 +26,8 @@ const (
PrivateAppStoreAPIPathPurchase = "/WebObjects/MZFinance.woa/wa/buyProduct"
PrivateAppStoreAPIPathDownload = "/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct"
PrivatePurchaseDAAPBaseURL = "https://pd.itunes.apple.com/WebObjects/MZPurchaseDaap.woa/purchase"
HTTPHeaderStoreFront = "X-Set-Apple-Store-Front"
HTTPHeaderPod = "pod"
+20 -8
View File
@@ -1,25 +1,31 @@
package appstore
import "fmt"
import (
"fmt"
"strings"
)
type Platform string
const (
PlatformIPhone Platform = "iphone"
PlatformIPad Platform = "ipad"
PlatformAppleTV Platform = "appletv"
PlatformIPhone Platform = "iphone"
PlatformIPad Platform = "ipad"
PlatformAppleTV Platform = "appletv"
PlatformVisionOS Platform = "visionos"
)
func ParsePlatform(value string) (Platform, error) {
switch value {
switch strings.ToLower(value) {
case "":
return "", nil
case "iphone", "iPhone", "ios", "iOS":
case "iphone", "ios":
return PlatformIPhone, nil
case "ipad", "iPad":
case "ipad", "ipados":
return PlatformIPad, nil
case "appletv", "AppleTV", "apple-tv", "tvos", "tvOS":
case "appletv", "apple-tv", "tvos":
return PlatformAppleTV, nil
case "vision", "visionos", "visionpro", "xros", "realitydevice":
return PlatformVisionOS, nil
default:
return "", fmt.Errorf("invalid platform %q", value)
}
@@ -35,6 +41,8 @@ func (p Platform) lookupEntity() (string, error) {
return "iPadSoftware", nil
case PlatformAppleTV:
return "tvSoftware", nil
case PlatformVisionOS:
return "xrosSoftware", nil
default:
return "", fmt.Errorf("invalid platform %q", p)
}
@@ -50,6 +58,8 @@ func (p Platform) searchEntity() (string, error) {
return "iPadSoftware", nil
case PlatformAppleTV:
return "software,tvSoftware", nil
case PlatformVisionOS:
return "xrosSoftware", nil
default:
return "", fmt.Errorf("invalid platform %q", p)
}
@@ -61,6 +71,8 @@ func (p Platform) metadataPlatform() (string, error) {
return "enterprisestore", nil
case PlatformAppleTV:
return "atv9", nil
case PlatformVisionOS:
return "realityDevice", nil
default:
return "", fmt.Errorf("invalid platform %q", p)
}
+55
View File
@@ -16,12 +16,67 @@ var _ = Describe("Platform", func() {
Entry("iPhone", "iphone", PlatformIPhone),
Entry("iOS", "ios", PlatformIPhone),
Entry("iPad", "ipad", PlatformIPad),
Entry("iPadOS", "iPadOS", PlatformIPad),
Entry("AppleTV", "appletv", PlatformAppleTV),
Entry("tvOS", "tvos", PlatformAppleTV),
Entry("visionOS", "visionOS", PlatformVisionOS),
Entry("Vision Pro", "visionpro", PlatformVisionOS),
Entry("xrOS", "xrOS", PlatformVisionOS),
Entry("realityDevice", "realityDevice", PlatformVisionOS),
)
DescribeTable("maps platforms to lookup entities",
func(platform Platform, expected string) {
entity, err := platform.lookupEntity()
Expect(err).ToNot(HaveOccurred())
Expect(entity).To(Equal(expected))
},
Entry("default", Platform(""), "software,iPadSoftware"),
Entry("iPhone", PlatformIPhone, "software"),
Entry("iPad", PlatformIPad, "iPadSoftware"),
Entry("Apple TV", PlatformAppleTV, "tvSoftware"),
Entry("visionOS", PlatformVisionOS, "xrosSoftware"),
)
DescribeTable("maps platforms to search entities",
func(platform Platform, expected string) {
entity, err := platform.searchEntity()
Expect(err).ToNot(HaveOccurred())
Expect(entity).To(Equal(expected))
},
Entry("default", Platform(""), "software,iPadSoftware"),
Entry("iPhone", PlatformIPhone, "software"),
Entry("iPad", PlatformIPad, "iPadSoftware"),
Entry("Apple TV", PlatformAppleTV, "software,tvSoftware"),
Entry("visionOS", PlatformVisionOS, "xrosSoftware"),
)
DescribeTable("maps platforms to metadata platforms",
func(platform Platform, expected string) {
metadataPlatform, err := platform.metadataPlatform()
Expect(err).ToNot(HaveOccurred())
Expect(metadataPlatform).To(Equal(expected))
},
Entry("iPhone", PlatformIPhone, "enterprisestore"),
Entry("iPad", PlatformIPad, "enterprisestore"),
Entry("Apple TV", PlatformAppleTV, "atv9"),
Entry("visionOS", PlatformVisionOS, "realityDevice"),
)
It("returns an error for invalid platforms", func() {
_, err := ParsePlatform("watch")
Expect(err).To(HaveOccurred())
})
It("returns errors when an unknown platform is mapped", func() {
platform := Platform("watch")
_, lookupErr := platform.lookupEntity()
_, searchErr := platform.searchEntity()
_, metadataErr := platform.metadataPlatform()
Expect(lookupErr).To(HaveOccurred())
Expect(searchErr).To(HaveOccurred())
Expect(metadataErr).To(HaveOccurred())
})
})
+23
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@@ -134,6 +135,10 @@ func (c *client[R]) Send(req Request) (Result[R], error) {
return c.handleJSONResponse(res)
}
if req.ResponseFormat == ResponseFormatRaw {
return c.handleRawResponse(res)
}
if req.ResponseFormat == ResponseFormatXML {
return c.handleXMLResponse(res)
}
@@ -141,6 +146,24 @@ func (c *client[R]) Send(req Request) (Result[R], error) {
return Result[R]{}, fmt.Errorf("content type is not supported (%s)", req.ResponseFormat)
}
func (c *client[R]) handleRawResponse(res *http.Response) (Result[R], error) {
body, err := io.ReadAll(res.Body)
if err != nil {
return Result[R]{}, fmt.Errorf("failed to read response body: %w", err)
}
data, ok := any(body).(R)
if !ok {
return Result[R]{}, errors.New("raw response format requires a []byte result type")
}
return Result[R]{
StatusCode: res.StatusCode,
Headers: responseHeaders(res),
Data: data,
}, nil
}
func (c *client[R]) Do(req *http.Request) (*http.Response, error) {
res, err := c.internalClient.Do(req)
if err != nil {
+67
View File
@@ -125,6 +125,43 @@ var _ = Describe("Client", Ordered, func() {
Expect(res.Data.Foo).To(Equal("bar"))
})
It("returns a raw response body", func() {
body := []byte{0x00, 0x01, 0xff}
mockHandler = func(w http.ResponseWriter, _r *http.Request) {
w.Header().Set("X-Test", "raw")
_, err := w.Write(body)
Expect(err).ToNot(HaveOccurred())
}
sut := NewClient[[]byte](Args{CookieJar: mockCookieJar})
res, err := sut.Send(Request{
URL: srv.URL,
Method: MethodGET,
ResponseFormat: ResponseFormatRaw,
})
Expect(err).ToNot(HaveOccurred())
Expect(res.Data).To(Equal(body))
Expect(res.StatusCode).To(Equal(http.StatusOK))
Expect(res.Headers).To(HaveKeyWithValue("X-Test", "raw"))
})
It("rejects a raw response when the result type is not bytes", func() {
mockHandler = func(w http.ResponseWriter, _r *http.Request) {
_, err := w.Write([]byte("raw"))
Expect(err).ToNot(HaveOccurred())
}
sut := NewClient[struct{}](Args{CookieJar: mockCookieJar})
_, err := sut.Send(Request{
URL: srv.URL,
Method: MethodGET,
ResponseFormat: ResponseFormatRaw,
})
Expect(err).To(MatchError("raw response format requires a []byte result type"))
})
It("signs the exact serialized request body", func() {
signature := []byte("test-signature")
signer := &recordingActionSigner{signature: signature}
@@ -156,6 +193,36 @@ var _ = Describe("Client", Ordered, func() {
Expect(signer.calls).To(Equal(1))
})
It("signs an exact raw request body", func() {
body := []byte{0x61, 0x64, 0x73, 0x72, 0x00, 0x00, 0x00, 0x00}
signature := []byte("raw-signature")
signer := &recordingActionSigner{signature: signature}
mockHandler = func(w http.ResponseWriter, r *http.Request) {
defer GinkgoRecover()
actual, err := io.ReadAll(r.Body)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(body))
Expect(r.Header.Get(HeaderAppleActionSignature)).To(Equal(base64.StdEncoding.EncodeToString(signature)))
_, err = w.Write([]byte("response"))
Expect(err).ToNot(HaveOccurred())
}
sut := NewClient[[]byte](Args{CookieJar: mockCookieJar})
_, err := sut.Send(Request{
URL: srv.URL,
Method: MethodPOST,
ResponseFormat: ResponseFormatRaw,
ActionSigner: signer,
Payload: &RawPayload{Content: body},
})
Expect(err).ToNot(HaveOccurred())
Expect(signer.calls).To(Equal(1))
Expect(signer.data).To(Equal(body))
})
It("preserves an authentication pod redirect", func() {
podURL := srv.URL + "/pod"
mockHandler = func(w http.ResponseWriter, r *http.Request) {
+1
View File
@@ -4,6 +4,7 @@ type ResponseFormat string
const (
ResponseFormatJSON ResponseFormat = "json"
ResponseFormatRaw ResponseFormat = "raw"
ResponseFormatXML ResponseFormat = "xml"
)
+10
View File
@@ -21,6 +21,12 @@ type URLPayload struct {
Content map[string]interface{}
}
// RawPayload sends Content without applying an encoding. It is used by Apple
// services whose request body is already serialized, such as DAAP/DMAP.
type RawPayload struct {
Content []byte
}
func (p *XMLPayload) data() ([]byte, error) {
buffer := new(bytes.Buffer)
@@ -48,3 +54,7 @@ func (p *URLPayload) data() ([]byte, error) {
return []byte(params.Encode()), nil
}
func (p *RawPayload) data() ([]byte, error) {
return append([]byte(nil), p.Content...), nil
}
+14
View File
@@ -61,4 +61,18 @@ var _ = Describe("Payload", func() {
Expect(data).To(BeNil())
})
})
Context("Raw Payload", func() {
It("returns a copy of the data without encoding it", func() {
payload := &RawPayload{Content: []byte{0x00, 0x01, 0xff}}
sut = payload
data, err := sut.data()
Expect(err).ToNot(HaveOccurred())
Expect(data).To(Equal([]byte{0x00, 0x01, 0xff}))
data[0] = 0xff
Expect(payload.Content).To(Equal([]byte{0x00, 0x01, 0xff}))
})
})
})
+3
View File
@@ -9,14 +9,17 @@ type Keychain interface {
type keychain struct {
keyring Keyring
label string
}
type Args struct {
Keyring Keyring
Label string
}
func New(args Args) Keychain {
return &keychain{
keyring: args.Keyring,
label: args.Label,
}
}
+6 -2
View File
@@ -10,6 +10,8 @@ import (
)
var _ = Describe("Keychain (Get)", func() {
const testLabel = "test-label"
var (
ctrl *gomock.Controller
keychain Keychain
@@ -21,6 +23,7 @@ var _ = Describe("Keychain (Get)", func() {
mockKeyring = NewMockKeyring(ctrl)
keychain = New(Args{
Keyring: mockKeyring,
Label: testLabel,
})
})
@@ -44,7 +47,7 @@ var _ = Describe("Keychain (Get)", func() {
})
})
When("keyring returns item", func() {
When("keyring returns a legacy unlabeled item", func() {
const testKey = "test-key"
var testData = []byte("test")
@@ -52,7 +55,8 @@ var _ = Describe("Keychain (Get)", func() {
mockKeyring.EXPECT().
Get(testKey).
Return(keyring.Item{
Data: testData,
Data: testData,
Label: "",
}, nil)
})
+3 -2
View File
@@ -8,8 +8,9 @@ import (
func (k *keychain) Set(key string, data []byte) error {
err := k.keyring.Set(keyring.Item{
Key: key,
Data: data,
Key: key,
Data: data,
Label: k.label,
})
if err != nil {
return fmt.Errorf("failed to set item: %w", err)
+9 -4
View File
@@ -10,6 +10,8 @@ import (
)
var _ = Describe("Keychain (Set)", func() {
const testLabel = "test-label"
var (
ctrl *gomock.Controller
keychain Keychain
@@ -21,6 +23,7 @@ var _ = Describe("Keychain (Set)", func() {
mockKeyring = NewMockKeyring(ctrl)
keychain = New(Args{
Keyring: mockKeyring,
Label: testLabel,
})
})
@@ -35,8 +38,9 @@ var _ = Describe("Keychain (Set)", func() {
BeforeEach(func() {
mockKeyring.EXPECT().
Set(keyring.Item{
Key: testKey,
Data: testData,
Key: testKey,
Data: testData,
Label: testLabel,
}).
Return(errors.New(""))
})
@@ -54,8 +58,9 @@ var _ = Describe("Keychain (Set)", func() {
BeforeEach(func() {
mockKeyring.EXPECT().
Set(keyring.Item{
Key: testKey,
Data: testData,
Key: testKey,
Data: testData,
Label: testLabel,
}).
Return(nil)
})