Compare commits

...
18 Commits
Author SHA1 Message Date
Majd Alfhaily 4484b55d36 feat: add watchos platform support 2026-10-09 23:22:25 +02:00
Majd Alfhaily e3932cec31 fix: resolve apple arcade versions through the catalog api 2026-10-08 01:02:30 +02:00
Majd Alfhaily cde7d00355 feat: add version metadata mcp tool 2026-10-06 19:43:42 +02:00
Majd Alfhaily 93b527a839 fix: support phone-number apple account login 2026-10-06 19:24:05 +02:00
Majd Alfhaily ed45c02852 fix: read version metadata for legacy macos apps 2026-10-06 00:35:10 +02:00
Majd Alfhaily f11d9abafe feat: add mcp support 2026-10-05 23:47:57 +02:00
Majd Alfhaily f9aa6536cd fix: normalize the initial authentication url path 2026-10-05 23:39:41 +02:00
Majd Alfhaily 3411d57f45 fix: improve download reliability with kbsync 2026-10-01 21:57:13 +02:00
Majd Alfhaily 0cc226a3d7 fix: select a stable machine identity from network adapters 2026-10-01 20:32:44 +02:00
Majd Alfhaily e258fed14a fix: bound authentication requests and retry transport failures 2026-10-01 19:54:32 +02:00
Majd Alfhaily 1ec8b3e5dc fix: preserve signed authentication requests across redirects 2026-10-01 18:40:36 +02:00
Majd Alfhaily 387d1a4f47 fix: allow downloads of delisted tvos apps 2026-09-30 00:00:53 +02:00
Majd Alfhaily 294488012f fix: reuse credentials across download retries 2026-09-29 23:54:41 +02:00
Majd Alfhaily 5deb9b521b test: cover tvos update fallback safeguards 2026-09-29 23:47:03 +02:00
zebrapurring acd9e7a972 fix: enable update fallback for tvos downloads 2026-09-29 23:47:03 +02:00
Majd Alfhaily 50312a928b fix: recover redacted mac addresses on macos 27 2026-09-29 23:33:35 +02:00
Majd Alfhaily 735b689ac3 fix: normalize 2fa input and clarify verification errors 2026-09-19 19:13:27 +02:00
Majd Alfhaily e5211d6fd9 fix: fall back to consumer catalogs for ios version lookup 2026-09-18 23:13:53 +02:00
77 changed files with 5762 additions and 301 deletions

No files matched your search

+3 -3
View File
@@ -5,7 +5,7 @@
</p>
<p align="center">
<code>ipatool</code> is a command line tool that allows you to search for iOS, iPadOS, tvOS, visionOS, and macOS apps on the <a href="https://apps.apple.com">App Store</a>, and download <code>.ipa</code> or macOS <code>.pkg</code> app packages.
<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>
<p align="center">
@@ -45,13 +45,13 @@ Usage:
Available Commands:
auth Authenticate with the App Store
completion Generate the autocompletion script for the specified shell
download Download iOS, iPadOS, tvOS, visionOS, and macOS app packages from the App Store
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, visionOS, and macOS apps available on the App Store
search Search for iOS, iPadOS, tvOS, watchOS, visionOS, and macOS apps available on the App Store
Flags:
--format format sets output format for command; can be 'text', 'json' (default text)
+4 -4
View File
@@ -33,13 +33,13 @@ func loginCmd() *cobra.Command {
interactive := cmd.Context().Value(interactiveKey).(bool)
if email == "" && !interactive {
return errors.New("email is required when not running in interactive mode; use the \"--email\" flag")
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 email: ", false)
value, err := readPrompt("enter Apple ID (email address or phone number): ", false)
if err != nil {
return fmt.Errorf("failed to read email: %w", err)
return fmt.Errorf("failed to read Apple ID: %w", err)
}
email = value
}
@@ -111,7 +111,7 @@ 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")
+16 -11
View File
@@ -30,24 +30,28 @@ var _ = Describe("Login command", func() {
Expect(cmd.Execute()).To(MatchError(message))
Expect(store.loginCalls).To(BeZero())
},
Entry("missing email", []string{"--password", "secret"}, "email is required when not running in interactive mode; use the \"--email\" flag"),
Entry("missing 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) {
DescribeTable("uses supplied credentials", func(interactive bool, appleID string) {
cmd := loginCmd()
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, interactive))
cmd.SetArgs([]string{"--email", "user@example.com", "--password", "secret"})
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: "user@example.com", Password: "secret"}))
Expect(store.input).To(Equal(appstore.LoginInput{Email: appleID, Password: "secret"}))
},
Entry("interactive", true),
Entry("non-interactive", false),
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 email", func(input, message string) {
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())
@@ -72,7 +76,7 @@ var _ = Describe("Login command", func() {
if message == "" {
Expect(err).NotTo(HaveOccurred())
Expect(store.loginCalls).To(Equal(1))
Expect(store.input).To(Equal(appstore.LoginInput{Email: "user@example.com", Password: "secret"}))
Expect(store.input).To(Equal(appstore.LoginInput{Email: appleID, Password: "secret"}))
} else {
Expect(err).To(MatchError(message))
Expect(store.loginCalls).To(BeZero())
@@ -80,10 +84,11 @@ var _ = Describe("Login command", func() {
prompt, err := os.ReadFile(stderr.Name())
Expect(err).NotTo(HaveOccurred())
Expect(string(prompt)).To(Equal("enter email: "))
Expect(string(prompt)).To(Equal("enter Apple ID (email address or phone number): "))
},
Entry("reads unmasked input without requiring a terminal", "user@example.com\n", ""),
Entry("reports input errors", "", "failed to read email: failed to read input: EOF"),
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"),
)
})
+4
View File
@@ -101,6 +101,10 @@ 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})
stateDirectory := util.Must(prepareStateDirectory(dependencies.OS, dependencies.Machine.HomeDirectory()))
+16 -15
View File
@@ -29,7 +29,7 @@ func downloadCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
cmd := &cobra.Command{
Use: "download",
Short: "Download iOS, iPadOS, tvOS, visionOS, and macOS 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")
@@ -40,20 +40,18 @@ func downloadCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
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 {
store := appStore()
infoResult, err := store.AccountInfo()
if err != nil {
return err
}
acc = infoResult.Account
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
loginResult, err := store.Login(appstore.LoginInput{
Email: acc.Email,
@@ -66,7 +64,7 @@ func downloadCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
acc = loginResult.Account
}
app := appstore.App{ID: appID}
app := appstore.App{ID: appID, BundleID: bundleID}
if bundleID != "" {
lookupResult, err := store.Lookup(appstore.LookupInput{
@@ -74,11 +72,14 @@ func downloadCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
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) {
@@ -167,10 +168,10 @@ func downloadCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
}
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(&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 app (defaults to latest version when not specified)")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
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
+157 -16
View File
@@ -3,6 +3,7 @@ package cmd
import (
"context"
"errors"
"fmt"
"github.com/majd/ipatool/v2/pkg/appstore"
"github.com/majd/ipatool/v2/pkg/log"
@@ -11,6 +12,69 @@ import (
)
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"))
@@ -66,24 +130,28 @@ var _ = Describe("Download command", func() {
Expect(err).To(MatchError("replication failed"))
})
It("propagates macOS when automatic purchase retries the download", func() {
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", "macos", "--purchase"})
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(appstore.PlatformMacOS))
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(appstore.PlatformMacOS))
Expect(store.downloadInputs[1].Platform).To(Equal(appstore.PlatformMacOS))
})
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{
@@ -99,12 +167,74 @@ var _ = Describe("Download command", func() {
cmd.SetContext(context.WithValue(context.Background(), interactiveKey, false))
Expect(cmd.Execute()).To(Succeed())
Expect(store.accountInfoCalls).To(Equal(1))
Expect(store.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 {
@@ -121,27 +251,38 @@ func (f *fakeSinfReplicator) ReplicateSinf(input appstore.ReplicateSinfInput) er
}
type fakeDownloadAppStore struct {
downloadErrors []error
downloadInputs []appstore.DownloadInput
loginInputs []appstore.LoginInput
purchaseErrors []error
purchaseInputs []appstore.PurchaseInput
account appstore.Account
accountInfoCalls int
accountInfoError error
downloadErrors []error
downloadInputs []appstore.DownloadInput
loginAccount appstore.Account
loginInputs []appstore.LoginInput
lookupInputs []appstore.LookupInput
lookupOutput appstore.LookupOutput
lookupError error
purchaseErrors []error
purchaseInputs []appstore.PurchaseInput
}
func (f *fakeDownloadAppStore) Login(input appstore.LoginInput) (appstore.LoginOutput, error) {
f.loginInputs = append(f.loginInputs, input)
return appstore.LoginOutput{Account: appstore.Account{StoreFront: "143441"}}, nil
return appstore.LoginOutput{Account: f.loginAccount}, nil
}
func (*fakeDownloadAppStore) AccountInfo() (appstore.AccountInfoOutput, error) {
return appstore.AccountInfoOutput{Account: appstore.Account{StoreFront: "143441"}}, 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 (*fakeDownloadAppStore) Lookup(input appstore.LookupInput) (appstore.LookupOutput, error) {
return appstore.LookupOutput{}, 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) {
+1 -1
View File
@@ -101,7 +101,7 @@ func getVersionMetadataCmd() *cobra.Command {
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target app (required)")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to retrieve metadata for: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to retrieve metadata for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
_ = cmd.MarkFlagRequired("external-version-id")
+2 -2
View File
@@ -63,7 +63,7 @@ func ListVersionsCmd() *cobra.Command {
app = lookupResult.App
}
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Account: acc, App: app, Platform: platform})
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Context: cmd.Context(), Account: acc, App: app, Platform: platform})
if err != nil {
return err
}
@@ -92,7 +92,7 @@ func ListVersionsCmd() *cobra.Command {
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app (required)")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to list versions for: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to list versions for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
return cmd
}
+87
View File
@@ -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
})
}
+93
View File
@@ -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}
}
+32
View File
@@ -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
View File
@@ -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)
}
+358
View File
@@ -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
})
}
+1 -1
View File
@@ -104,7 +104,7 @@ func purchaseCmdWithAppStore(appStore func() appstore.AppStore) *cobra.Command {
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target app")
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target app (overrides the app ID)")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to purchase for: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to purchase for: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
return cmd
}
+1
View File
@@ -52,6 +52,7 @@ func rootCmd() *cobra.Command {
cmd.AddCommand(searchCmd())
cmd.AddCommand(ListVersionsCmd())
cmd.AddCommand(getVersionMetadataCmd())
cmd.AddCommand(mcpCmd())
return cmd
}
+2 -2
View File
@@ -14,7 +14,7 @@ func searchCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "search <term>",
Short: "Search for iOS, iPadOS, tvOS, visionOS, and macOS 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()
@@ -47,7 +47,7 @@ func searchCmd() *cobra.Command {
}
cmd.Flags().Int64VarP(&limit, "limit", "l", 5, "maximum amount of search results to retrieve; visionOS supports up to 12")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), visionos, or macos")
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone (iOS), ipad (iPadOS), appletv (tvOS), watchos, visionos, or macos")
return cmd
}
+8 -1
View File
@@ -11,6 +11,7 @@ require (
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
@@ -18,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
@@ -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
+16
View File
@@ -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=
+75
View File
@@ -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
}
+91
View File
@@ -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"),
)
})
+50 -43
View File
@@ -13,6 +13,7 @@ import (
const (
storeAgentBase = uint64(0x00001000c0000000)
storeAgentGlobalInit = storeAgentBase + 0x0c5fc0
storeAgentKBSyncEntry = storeAgentBase + 0x0c93c0
storeAgentSessionInit = storeAgentBase + 0x0debd0
storeAgentDecryptEntry = storeAgentBase + 0x0ee700
storeAgentSessionClose = storeAgentBase + 0x1212d0
@@ -55,65 +56,71 @@ func OpenStoreAgent(ctx context.Context, bundle assets.Bundle, hardwareID, dpInf
}
func openStoreAgent(ctx context.Context, bundle assets.Bundle, image, hardwareID, dpInfo []byte) (*StoreAgent, error) {
if ctx == nil {
return nil, errors.New("StoreAgent context is nil")
}
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("open StoreAgent runtime: %w", err)
}
if len(dpInfo) == 0 {
return nil, errors.New("StoreAgent dpInfo is empty")
}
if err := assets.VerifyStoreAgent(image); err != nil {
return nil, fmt.Errorf("verify Apple StoreAgent profile: %w", err)
}
hardware, err := hardwareBlock(hardwareID)
if err != nil {
return nil, err
}
guest, _, err := openRuntime(ctx, bundle, runtimeOptions{
extraImages: []imageSpec{{name: "storeagent", data: image, base: storeAgentBase}},
shims: shimOptions{
zeroReturnAliases: storeAgentZeroReturnAliases,
},
})
if err != nil {
return nil, fmt.Errorf("start StoreAgent runtime: %w", err)
}
agent := &StoreAgent{
guest: guest,
decryptEntry: storeAgentDecryptEntry,
closeEntry: storeAgentSessionClose,
}
complete := false
defer func() {
if !complete {
_ = agent.Close()
}
}()
globalContext, err := agent.initializeGlobal(hardware)
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
}
complete = true
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()
+5 -2
View File
@@ -16,7 +16,7 @@ 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)
@@ -43,6 +43,8 @@ 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]
@@ -79,9 +81,10 @@ func NewAppStore(args Args) AppStore {
searchClient: http.NewClient[searchResult](clientArgs),
purchaseClient: http.NewClient[purchaseResult](clientArgs),
downloadClient: http.NewClient[downloadResult](clientArgs),
kbsyncGenerator: defaultKBSyncGenerator,
platformClient: http.NewClient[platformVersionLookupResult](clientArgs),
storefrontClient: http.NewClient[[]byte](clientArgs),
bagClient: http.NewClient[bagResult](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,
+19 -6
View File
@@ -1,6 +1,7 @@
package appstore
import (
"errors"
"fmt"
gohttp "net/http"
"net/url"
@@ -53,6 +54,16 @@ func (t *appstore) bag(guid string) (BagOutput, error) {
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
}
@@ -76,6 +87,7 @@ type bagResult struct {
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"`
@@ -111,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
+39 -1
View File
@@ -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,
+15 -8
View File
@@ -52,14 +52,18 @@ func (t *appstore) Download(input DownloadInput) (DownloadOutput, error) {
}
externalVersionID := input.ExternalVersionID
if externalVersionID == "" && (input.Platform == PlatformAppleTV || input.Platform == PlatformVisionOS) {
if externalVersionID == "" && (input.Platform == PlatformAppleTV || input.Platform == PlatformWatchOS || input.Platform == PlatformVisionOS) {
externalVersionID, err = t.lookupLatestExternalVersionID(input.Account, input.App, input.Platform)
if err != nil {
// 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)
}
}
res, resolvedPlatform, err := t.sendDownloadProduct(input.Account, input.App, guid, externalVersionID, input.Platform)
res, resolvedPlatform, err := t.sendDownloadProduct(input.Context, input.Account, input.App, guid, externalVersionID, input.Platform)
if err != nil {
return DownloadOutput{}, err
}
@@ -155,6 +159,8 @@ func (*appstore) validatePackagePlatform(path string, platform Platform) error {
expectedPlatform = "iPhoneOS"
case PlatformAppleTV:
expectedPlatform = "AppleTVOS"
case PlatformWatchOS:
expectedPlatform = "WatchOS"
case PlatformVisionOS:
expectedPlatform = "XROS"
default:
@@ -212,11 +218,12 @@ func isTopLevelAppInfoPlist(path string) bool {
}
type downloadItemResult struct {
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"`
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 {
+52 -13
View File
@@ -1,6 +1,7 @@
package appstore
import (
"context"
"errors"
"fmt"
gohttp "net/http"
@@ -23,7 +24,15 @@ type downloadProductEndpoint struct {
versionKey string
}
func (t *appstore) sendDownloadProduct(acc Account, app App, guid, externalVersionID string, platform Platform) (http.Result[downloadResult], Platform, error) {
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 {
@@ -35,6 +44,28 @@ func (t *appstore) sendDownloadProduct(acc Account, app App, guid, externalVersi
}
}
// 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))
@@ -48,9 +79,13 @@ func (t *appstore) sendDownloadProduct(acc Account, app App, guid, externalVersi
// Try redownload when volumeStore returns no items, either silently or
// with the message-only "No Longer Available" response.
bag, err := t.fetchURLBag(guid)
if err != nil {
return res, platform, fmt.Errorf("failed to get bag for redownload fallback: %w", err)
if bag == 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 == "" {
@@ -77,7 +112,7 @@ func (t *appstore) sendDownloadProduct(acc Account, app App, guid, externalVersi
redownloadRes, err := t.downloadClient.Send(t.downloadProductRequest(redownload, acc, app, guid, externalVersionID))
if bag.UpdateEndpoint != "" && externalVersionID != "" &&
(platform == "" || platform == PlatformIPhone || platform == PlatformIPad || platform == PlatformMacOS) &&
(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)
@@ -108,7 +143,7 @@ func (t *appstore) sendUpdateProduct(endpoint string, acc Account, app App, guid
return http.Result[downloadResult]{}, err
}
// The bag's updateProduct can serve pinned iOS and macOS versions when redownload
// 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))
@@ -116,34 +151,38 @@ func (t *appstore) sendUpdateProduct(endpoint string, acc Account, app App, guid
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 res, nil
return nil
}
if res.Data.CustomerMessage != "" {
return res, NewErrorWithMetadata(fmt.Errorf("received update error: %s", res.Data.CustomerMessage), res)
return NewErrorWithMetadata(fmt.Errorf("received %s error: %s", source, res.Data.CustomerMessage), res)
}
if res.StatusCode != gohttp.StatusOK {
return res, fmt.Errorf("received unexpected update status code: %d", res.StatusCode)
return fmt.Errorf("received unexpected %s status code: %d", source, res.StatusCode)
}
if len(res.Data.Items) != 1 {
return res, errors.New("update response must contain exactly one item")
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 res, errors.New("update response does not match the requested app or version")
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 res, errors.New("update response does not match the requested bundle identifier")
return fmt.Errorf("%s response does not match the requested bundle identifier", source)
}
return res, nil
return nil
}
func newDownloadEndpoint(endpoint, path string) (downloadProductEndpoint, error) {
+30 -17
View File
@@ -1,6 +1,7 @@
package appstore
import (
"context"
"errors"
"fmt"
gohttp "net/http"
@@ -56,7 +57,7 @@ var _ = Describe("AppStore (Download Product)", func() {
ctrl.Finish()
})
It("uses volumeStore as the primary endpoint", func() {
It("uses volumeStore when kbsync generation is unavailable", func() {
expected := http.Result[downloadResult]{
StatusCode: gohttp.StatusOK,
Data: downloadResult{
@@ -78,7 +79,7 @@ var _ = Describe("AppStore (Download Product)", func() {
}).
Return(expected, nil)
actual, platform, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
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))
@@ -97,7 +98,7 @@ var _ = Describe("AppStore (Download Product)", func() {
Send(gomock.Any()).
Return(expected, nil)
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, PlatformIPhone)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(expected))
})
@@ -137,7 +138,7 @@ var _ = Describe("AppStore (Download Product)", func() {
Return(expected, nil),
)
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, PlatformIPhone)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(expected))
})
@@ -152,7 +153,7 @@ var _ = Describe("AppStore (Download Product)", func() {
Send(gomock.Any()).
Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: validBagResult()}, nil)
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, PlatformIPhone)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(expected))
})
@@ -165,7 +166,7 @@ var _ = Describe("AppStore (Download Product)", func() {
Send(gomock.Any()).
Return(http.Result[bagResult]{}, errors.New("bag request failed"))
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
_, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, PlatformIPhone)
Expect(err).To(MatchError(ContainSubstring("failed to get bag for redownload fallback")))
})
@@ -185,7 +186,7 @@ var _ = Describe("AppStore (Download Product)", func() {
Return(http.Result[downloadResult]{}, errors.New("redownload failed")),
)
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
_, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, PlatformIPhone)
Expect(err).To(MatchError(ContainSubstring("failed to send redownload request")))
})
@@ -197,7 +198,7 @@ var _ = Describe("AppStore (Download Product)", func() {
}
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil)
actual, resolvedPlatform, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, platform)
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))
@@ -265,7 +266,7 @@ var _ = Describe("AppStore (Download Product)", func() {
Expect(payload).ToNot(HaveKey("pricingParameters"))
}).Return(expected, nil),
)
actual, resolvedPlatform, err := store.sendDownloadProduct(account, app, testGUID, "", platform)
actual, resolvedPlatform, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, "", platform)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(expected))
if platform == "" {
@@ -280,6 +281,18 @@ var _ = Describe("AppStore (Download Product)", func() {
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(
@@ -290,7 +303,7 @@ var _ = Describe("AppStore (Download Product)", func() {
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", testVersionID))
}).Return(http.Result[downloadResult]{}, original),
)
_, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
_, _, 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})),
@@ -316,7 +329,7 @@ var _ = Describe("AppStore (Download Product)", func() {
Expect(payload).To(HaveKeyWithValue("appExtVrsId", versionID))
}
}).Return(expected, nil)
actual, resolvedPlatform, err := store.sendDownloadProduct(account, app, testGUID, versionID, platform)
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))
@@ -337,7 +350,7 @@ var _ = Describe("AppStore (Download Product)", func() {
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: latestVersion}, nil),
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil),
)
actual, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, "", PlatformIPhone)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(expected))
})
@@ -346,7 +359,7 @@ var _ = Describe("AppStore (Download Product)", func() {
lookupErr := errors.New("catalog unavailable")
mockPlatformClient.EXPECT().Send(gomock.Any()).Return(http.Result[platformVersionLookupResult]{}, lookupErr)
actual, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
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")))
@@ -354,9 +367,9 @@ var _ = Describe("AppStore (Download Product)", func() {
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)
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK}, nil).Times(4)
_, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
_, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, "", PlatformIPhone)
Expect(err).To(MatchError(ContainSubstring("platform version lookup returned no app")))
})
@@ -367,7 +380,7 @@ var _ = Describe("AppStore (Download Product)", func() {
mockPlatformClient.EXPECT().Send(gomock.Any()).
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: latestVersion}, nil)
_, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
_, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, "", PlatformIPhone)
Expect(err).To(MatchError(ContainSubstring("platform version lookup returned no external version id")))
})
@@ -378,7 +391,7 @@ var _ = Describe("AppStore (Download Product)", func() {
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK, Data: latestVersion}, nil),
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(expected, nil),
)
actual, _, err := store.sendDownloadProduct(account, app, testGUID, "", PlatformIPhone)
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, "", PlatformIPhone)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(expected))
})
+189
View File
@@ -196,6 +196,29 @@ 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().
@@ -828,6 +851,16 @@ var _ = Describe("AppStore (Download)", func() {
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() {
@@ -1140,6 +1173,17 @@ var _ = Describe("AppStore (Download)", func() {
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)
@@ -1170,3 +1214,148 @@ var _ = Describe("AppStore (Download)", func() {
})
})
})
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))
})
})
+12 -2
View File
@@ -28,7 +28,7 @@ func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersion
}
switch platform {
case PlatformIPhone, PlatformIPad, PlatformAppleTV, PlatformVisionOS, PlatformMacOS:
case PlatformIPhone, PlatformIPad, PlatformAppleTV, PlatformWatchOS, PlatformVisionOS, PlatformMacOS:
default:
return GetVersionMetadataOutput{}, fmt.Errorf("invalid platform %q", platform)
}
@@ -40,7 +40,7 @@ func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersion
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
res, _, err := t.sendDownloadProduct(input.Account, input.App, guid, input.VersionID, platform)
res, _, err := t.sendDownloadProduct(input.Context, input.Account, input.App, guid, input.VersionID, platform)
if err != nil {
return GetVersionMetadataOutput{}, err
}
@@ -66,6 +66,16 @@ 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 {
@@ -549,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",
@@ -558,6 +558,7 @@ var _ = Describe("AppStore (GetVersionMetadata)", func() {
ID: 1234567890,
},
VersionID: "test-version",
Platform: platform,
})
Expect(err).NotTo(HaveOccurred())
@@ -565,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),
)
})
+151
View File
@@ -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
}
+127
View File
@@ -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)
}
}
+157
View File
@@ -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))
})
})
+633
View File
@@ -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())
})
})
})
+5 -3
View File
@@ -1,12 +1,14 @@
package appstore
import (
"context"
"errors"
"fmt"
"strings"
)
type ListVersionsInput struct {
Context context.Context
Account Account
App App
Platform Platform
@@ -24,7 +26,7 @@ func (t *appstore) ListVersions(input ListVersionsInput) (ListVersionsOutput, er
}
switch platform {
case PlatformIPhone, PlatformIPad, PlatformAppleTV, PlatformVisionOS, PlatformMacOS:
case PlatformIPhone, PlatformIPad, PlatformAppleTV, PlatformWatchOS, PlatformVisionOS, PlatformMacOS:
default:
return ListVersionsOutput{}, fmt.Errorf("invalid platform %q", platform)
}
@@ -41,7 +43,7 @@ func (t *appstore) ListVersions(input ListVersionsInput) (ListVersionsOutput, er
switch platform {
case PlatformMacOS:
externalVersionID, err = t.lookupLatestMacOSExternalVersionID(input.Account, input.App)
case PlatformAppleTV, PlatformVisionOS:
case PlatformAppleTV, PlatformWatchOS, PlatformVisionOS:
externalVersionID, err = t.lookupLatestExternalVersionID(input.Account, input.App, platform)
}
@@ -49,7 +51,7 @@ func (t *appstore) ListVersions(input ListVersionsInput) (ListVersionsOutput, er
return ListVersionsOutput{}, fmt.Errorf("failed to resolve platform version: %w", err)
}
res, _, err := t.sendDownloadProduct(input.Account, input.App, guid, externalVersionID, platform)
res, _, err := t.sendDownloadProduct(input.Context, input.Account, input.App, guid, externalVersionID, platform)
if err != nil {
return ListVersionsOutput{}, err
}
@@ -70,6 +70,28 @@ var _ = Describe("AppStore (ListVersions)", func() {
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"`))
+173 -40
View File
@@ -1,16 +1,21 @@
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 (
@@ -19,6 +24,7 @@ var (
const (
maxAuthenticationRequestAttempts = 3
maxAuthenticationRedirects = 4
authenticationRetryDelay = 10 * time.Second
maxAuthenticationRetryDelay = 30 * time.Second
)
@@ -37,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)
@@ -65,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 {
@@ -88,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"`
@@ -107,25 +144,15 @@ 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), ""
for attempt := 1; ; {
res, err = t.sendAuthenticationRequest(request)
if err != nil {
@@ -134,20 +161,37 @@ func (t *appstore) login(email, password, authCode, guid, endpoint string, signe
stage = "2FA verification"
}
if redirect != "" {
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)
@@ -186,6 +230,7 @@ func (t *appstore) login(email, password, authCode, guid, endpoint string, signe
func (t *appstore) sendAuthenticationRequest(request http.Request) (http.Result[loginResult], error) {
statuses := make([]string, 0, maxAuthenticationRequestAttempts)
onlyHTTP := true
sleep := t.authRetrySleep
if sleep == nil {
@@ -204,27 +249,48 @@ func (t *appstore) sendAuthenticationRequest(request http.Request) (http.Result[
return result, nil
}
statuses = append(statuses, strconv.Itoa(status))
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 (HTTP %s): %w",
maxAuthenticationRequestAttempts, strings.Join(statuses, ", "), authenticationRequestError(err),
"authentication request failed after %d attempts (%s): %w",
maxAuthenticationRequestAttempts, summary, authenticationRequestError(err),
)
}
delay := min(authenticationRetryDelay<<(attempt-1), maxAuthenticationRetryDelay)
var responseErr *http.UnexpectedResponseError
if errors.As(err, &responseErr) {
if requested, ok := authenticationRetryAfter(responseErr.RetryAfter, time.Now()); ok {
if requested > maxAuthenticationRetryDelay {
return result, fmt.Errorf("apple requested a wait longer than %s; try again later: %w", maxAuthenticationRetryDelay, err)
}
var (
responseErr *http.UnexpectedResponseError
transportErr *http.TransportError
retryAfter string
)
// Retry-After takes precedence over the fallback backoff.
delay = max(requested, time.Second)
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)
@@ -234,11 +300,28 @@ func (t *appstore) sendAuthenticationRequest(request http.Request) (http.Result[
func retryableAuthenticationError(err error) (int, bool) {
var responseErr *http.UnexpectedResponseError
if !errors.As(err, &responseErr) {
return 0, false
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
@@ -246,25 +329,37 @@ func retryableAuthenticationError(err error) (int, bool) {
return status, retry
}
func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int, authCode string) (bool, string, error) {
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 != "" {
@@ -280,8 +375,41 @@ func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int
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,
@@ -300,6 +428,11 @@ 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 {
+54
View File
@@ -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", ""),
)
})
+62 -7
View File
@@ -60,9 +60,25 @@ 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() {
It("retries the same request until it succeeds", func() {
request := as.loginRequest(testEmail, testPassword, "", "guid", testAuthEndpoint, 1, signer)
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
@@ -76,6 +92,8 @@ var _ = Describe("AppStore (Login)", func() {
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++
@@ -88,7 +106,11 @@ var _ = Describe("AppStore (Login)", func() {
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) {
@@ -109,7 +131,8 @@ var _ = Describe("AppStore (Login)", func() {
},
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),
Entry("retries and then stops for non-plist HTTP 403", 403, maxAuthenticationRequestAttempts),
Entry("does not retry HTTP 401", 401, 1),
)
})
@@ -144,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
@@ -152,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)
@@ -259,6 +303,7 @@ var _ = Describe("AppStore (Login)", func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[loginResult]{
StatusCode: 200,
Data: loginResult{
FailureType: "",
CustomerMessage: CustomerMessageBadLogin,
@@ -272,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() {
@@ -283,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)
@@ -409,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
}
+17 -2
View File
@@ -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{
+50 -1
View File
@@ -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())
})
})
@@ -132,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)),
)
})
@@ -1,6 +1,7 @@
package appstore
import (
"context"
"errors"
gohttp "net/http"
@@ -54,7 +55,7 @@ var _ = Describe("Mac purchase version selection", func() {
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("externalVersionId", "876660716"))
}).Return(expected, downloadErr),
)
output, platform, err := store.sendDownloadProduct(Account{StoreFront: "143443-2,34"}, app, "001122334455", "", PlatformMacOS)
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 {
@@ -88,7 +89,7 @@ var _ = Describe("Mac purchase version selection", func() {
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", "876660716"))
}).Return(expected, nil),
)
output, platform, err := store.sendDownloadProduct(Account{StoreFront: "143443-2,34"}, app, "001122334455", "", PlatformMacOS)
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))
@@ -103,7 +104,7 @@ var _ = Describe("Mac purchase version selection", func() {
pages := http.NewMockClient[[]byte](ctrl)
store := &appstore{storefrontClient: pages, downloadClient: http.NewMockClient[downloadResult](ctrl)}
pages.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: status, Data: body}, requestErr)
_, _, err := store.sendDownloadProduct(Account{StoreFront: "143443-2,34"}, app, "001122334455", "", PlatformMacOS)
_, _, err := store.sendDownloadProduct(context.Background(), Account{StoreFront: "143443-2,34"}, app, "001122334455", "", PlatformMacOS)
Expect(err).To(HaveOccurred())
},
Entry("HTTP failure", 500, nil, nil),
@@ -24,7 +24,14 @@ func (t *appstore) readVersionMetadataFromMacPackage(ctx context.Context, item d
defer os.RemoveAll(directory)
destination := filepath.Join(directory, "app.pkg")
if _, err := t.downloadMacPackage(ctx, item, destination, hardwareID, nil); err != nil {
// 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
}
@@ -39,6 +46,10 @@ func (t *appstore) readVersionMetadataFromMacPackage(ctx context.Context, item d
defer archive.Close()
if preflight {
return macPreflightVersionMetadata(&archive.Reader, bundleID)
}
return macPackageVersionMetadata(&archive.Reader, bundleID)
}
@@ -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 {
@@ -70,44 +76,74 @@ func (t *appstore) lookupLatestExternalVersionID(acc Account, app App, platform
return t.lookupLatestVisionOSExternalVersionID(app.ID, countryCode)
}
request, err := t.platformVersionLookupRequest(app.ID, countryCode, platform)
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)
if err != nil {
return "", fmt.Errorf("platform version lookup request failed: %w", err)
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")
}
if res.StatusCode != gohttp.StatusOK {
return "", NewErrorWithMetadata(errors.New("platform version lookup request failed"), res)
}
var lastErr error
item, ok := res.Data.Results[strconv.FormatInt(app.ID, 10)]
if !ok {
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no app"), res)
}
for _, catalog := range catalogs {
request := t.platformVersionLookupRequest(app.ID, countryCode, catalog)
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)
res, err := t.platformClient.Send(request)
if err != nil {
return "", fmt.Errorf("failed to parse buy params: %w", err)
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 externalVersionID == "" {
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no external version id"), res)
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 externalVersionID, nil
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) {
@@ -134,12 +170,7 @@ func (t *appstore) lookupLatestVisionOSExternalVersionID(appID int64, countryCod
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))
@@ -153,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")))
})
})
+20 -4
View File
@@ -1,14 +1,30 @@
package appstore
import (
"errors"
"fmt"
"io/fs"
"github.com/byteness/keyring"
)
func (t *appstore) Revoke() error {
err := t.keychain.Remove("account")
if err != nil {
return fmt.Errorf("failed to remove account from keychain: %w", err)
accountErr := t.keychain.Remove("account")
if accountErr != nil {
accountErr = fmt.Errorf("failed to remove account from keychain: %w", accountErr)
}
return nil
t.kbsyncCache.mu.Lock()
defer t.kbsyncCache.mu.Unlock()
t.kbsyncCache.entry = kbsyncCacheEntry{}
cacheErr := t.keychain.Remove(kbsyncCacheKey)
if errors.Is(cacheErr, keyring.ErrKeyNotFound) || errors.Is(cacheErr, fs.ErrNotExist) {
cacheErr = nil
} else if cacheErr != nil {
cacheErr = fmt.Errorf("failed to remove kbsync cache from keychain: %w", cacheErr)
}
return errors.Join(accountErr, cacheErr)
}
+19
View File
@@ -2,7 +2,9 @@ package appstore
import (
"errors"
"io/fs"
"github.com/byteness/keyring"
"github.com/majd/ipatool/v2/pkg/keychain"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
@@ -33,6 +35,7 @@ var _ = Describe("AppStore (Revoke)", func() {
mockKeychain.EXPECT().
Remove("account").
Return(nil)
mockKeychain.EXPECT().Remove(kbsyncCacheKey).Return(nil)
})
It("returns data", func() {
@@ -41,11 +44,27 @@ var _ = Describe("AppStore (Revoke)", func() {
})
})
DescribeTable("revokes accounts saved before a kbsync cache existed", func(missing error) {
mockKeychain.EXPECT().Remove("account").Return(nil)
mockKeychain.EXPECT().Remove(kbsyncCacheKey).Return(missing)
Expect(appstore.Revoke()).To(Succeed())
},
Entry("native keychain", keyring.ErrKeyNotFound),
Entry("file keychain", &fs.PathError{Op: "remove", Path: "cache", Err: fs.ErrNotExist}),
)
It("reports a cache removal failure after removing the account", func() {
mockKeychain.EXPECT().Remove("account").Return(nil)
mockKeychain.EXPECT().Remove(kbsyncCacheKey).Return(errors.New("cache unavailable"))
Expect(appstore.Revoke()).To(MatchError("failed to remove kbsync cache from keychain: cache unavailable"))
})
When("keychain returns error", func() {
BeforeEach(func() {
mockKeychain.EXPECT().
Remove("account").
Return(errors.New(""))
mockKeychain.EXPECT().Remove(kbsyncCacheKey).Return(nil)
})
It("returns wrapped error", func() {
+9
View File
@@ -49,6 +49,14 @@ func (t *appstore) Search(input SearchInput) (SearchOutput, error) {
return SearchOutput{}, NewErrorWithMetadata(errors.New("request failed"), res)
}
if input.Platform == PlatformWatchOS {
// Watch apps share the software search catalog with iOS apps.
res.Data.Results = slices.DeleteFunc(res.Data.Results, func(app App) bool {
return !slices.Contains(app.Platforms, PlatformWatchOS)
})
res.Data.Count = len(res.Data.Results)
}
return SearchOutput{
Count: res.Data.Count,
Results: res.Data.Results,
@@ -164,6 +172,7 @@ func (r *searchResult) UnmarshalJSON(data []byte) error {
{"iPod", PlatformIPhone},
{"iPad", PlatformIPad},
{"AppleTV", PlatformAppleTV},
{"Watch", PlatformWatchOS},
{"RealityDevice", PlatformVisionOS},
{"Mac", PlatformMacOS},
} {
+23
View File
@@ -47,6 +47,8 @@ var _ = Describe("AppStore (Search)", func() {
Entry("iPad only", `"supportedDevices":["iPadAir-iPadAir"]`, []Platform{PlatformIPad}),
Entry("iPod", `"supportedDevices":["iPodTouchSixthGen-iPodTouchSixthGen"]`, []Platform{PlatformIPhone}),
Entry("TV", `"supportedDevices":["AppleTV4-AppleTV4"]`, []Platform{PlatformAppleTV}),
Entry("Watch", `"supportedDevices":["Watch4-Watch4","Watch5-Watch5"]`, []Platform{PlatformWatchOS}),
Entry("iPhone with Watch", `"supportedDevices":["Watch4-Watch4","iPhone6-iPhone6"]`, []Platform{PlatformIPhone, PlatformWatchOS}),
Entry("vision", `"supportedDevices":["RealityDevice-RealityDevice"]`, []Platform{PlatformVisionOS}),
Entry("Mac", `"kind":"mac-software"`, []Platform{PlatformMacOS}),
Entry("multiple families", `"supportedDevices":["MacDesktop-MacDesktop","RealityDevice-RealityDevice","iPadAir-iPadAir"]`, []Platform{PlatformIPad, PlatformVisionOS, PlatformMacOS}),
@@ -54,6 +56,27 @@ var _ = Describe("AppStore (Search)", func() {
Entry("unrecognized devices", `"supportedDevices":["FutureDevice"]`, []Platform{PlatformUnknown}),
)
It("filters watchOS searches to apps supporting Apple Watch", 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("software,watchSoftware"))
}).Return(http.Result[searchResult]{StatusCode: 200, Data: searchResult{
Count: 3,
Results: []App{
{ID: 1, Platforms: []Platform{PlatformIPhone}},
{ID: 2, Platforms: []Platform{PlatformWatchOS}},
{ID: 3, Platforms: []Platform{PlatformIPhone, PlatformWatchOS}},
},
}}, nil)
out, err := as.Search(SearchInput{Account: Account{StoreFront: "143441"}, Platform: PlatformWatchOS})
Expect(err).ToNot(HaveOccurred())
Expect(out.Count).To(Equal(2))
Expect(out.Results).To(HaveLen(2))
Expect(out.Results[0].ID).To(Equal(int64(2)))
Expect(out.Results[1].ID).To(Equal(int64(3)))
})
When("request is successful", func() {
const (
testID = 0
+39 -17
View File
@@ -1,6 +1,7 @@
package appstore
import (
"context"
"errors"
"fmt"
gohttp "net/http"
@@ -102,7 +103,7 @@ var _ = Describe("AppStore (Update Product)", func() {
}).Return(expected, nil),
)
actual, resolvedPlatform, err := store.sendDownloadProduct(account, app, testGUID, versionID, platform)
actual, resolvedPlatform, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, versionID, platform)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(expected))
if platform == "" {
@@ -116,11 +117,13 @@ var _ = Describe("AppStore (Update Product)", func() {
Entry("latest iPad", "", PlatformIPad),
Entry("explicit historical version", testVersionID, PlatformIPhone),
Entry("explicit macOS version", testVersionID, PlatformMacOS),
Entry("explicit tvOS version", testVersionID, PlatformAppleTV),
Entry("explicit watchOS version", testVersionID, PlatformWatchOS),
Entry("explicit version without a platform", testVersionID, Platform("")),
)
DescribeTable("tries update once for a message-only availability response",
func(primaryUnavailable, updateUnavailable bool) {
func(platform Platform, primaryUnavailable, updateUnavailable bool) {
unavailable := http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
Data: downloadResult{CustomerMessage: "“Messenger” No Longer Available"}}
primary := http.Result[downloadResult]{StatusCode: gohttp.StatusOK}
@@ -132,20 +135,25 @@ var _ = Describe("AppStore (Update Product)", func() {
update = unavailable
}
var redownloadRequest http.Request
gomock.InOrder(
mockDownloadClient.EXPECT().Send(gomock.Any()).Return(primary, nil),
mockBagClient.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{StatusCode: gohttp.StatusOK, Data: bag}, nil),
mockDownloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
Expect(req.URL).To(Equal(testRedownloadEndpoint + "?guid=" + testGUID))
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", testVersionID))
redownloadRequest = req
}).Return(unavailable, nil),
mockDownloadClient.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
Expect(req.URL).To(Equal(testUpdateEndpoint + "?guid=" + testGUID))
Expect(req.Headers).To(Equal(redownloadRequest.Headers))
Expect(req.Payload).To(Equal(redownloadRequest.Payload))
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", testVersionID))
}).Return(update, nil),
)
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
actual, resolvedPlatform, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, platform)
Expect(resolvedPlatform).To(Equal(platform))
Expect(actual).To(Equal(update))
if updateUnavailable {
Expect(err).To(MatchError(ContainSubstring(unavailable.Data.CustomerMessage)))
@@ -153,9 +161,12 @@ var _ = Describe("AppStore (Update Product)", func() {
Expect(err).ToNot(HaveOccurred())
}
},
Entry("redownload unavailable", false, false),
Entry("both initial endpoints unavailable", true, false),
Entry("update also unavailable", false, true),
Entry("redownload unavailable", PlatformIPhone, false, false),
Entry("both initial endpoints unavailable", PlatformIPhone, true, false),
Entry("update also unavailable", PlatformIPhone, false, true),
Entry("tvOS redownload unavailable", PlatformAppleTV, false, false),
Entry("tvOS both initial endpoints unavailable", PlatformAppleTV, true, false),
Entry("tvOS update also unavailable", PlatformAppleTV, false, true),
)
DescribeTable("keeps TestFlight's Mac offer pinned through update fallback",
@@ -203,7 +214,7 @@ var _ = Describe("AppStore (Update Product)", func() {
Expect(req.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appExtVrsId", testVersionID))
}).Return(update, nil),
)
actual, platform, err := store.sendDownloadProduct(account, app, testGUID, versionID, PlatformMacOS)
actual, platform, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, versionID, PlatformMacOS)
Expect(platform).To(Equal(PlatformMacOS))
Expect(actual).To(Equal(update))
if updateUnavailable {
@@ -226,12 +237,11 @@ var _ = Describe("AppStore (Update Product)", func() {
Data: downloadResult{FailureType: failureType, CustomerMessage: message}}
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).Return(response, nil)
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, platform)
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, platform)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(response))
},
Entry("missing endpoint", PlatformIPhone, "", "", "“Messenger” No Longer Available", 200),
Entry("tvOS", PlatformAppleTV, testUpdateEndpoint, "", "“Messenger” No Longer Available", 200),
Entry("visionOS", PlatformVisionOS, testUpdateEndpoint, "", "“Messenger” No Longer Available", 200),
Entry("license failure", PlatformIPhone, testUpdateEndpoint, FailureTypeLicenseNotFound, "“Messenger” No Longer Available", 200),
Entry("other message", PlatformIPhone, testUpdateEndpoint, "", "Sign in required", 200),
@@ -244,7 +254,7 @@ var _ = Describe("AppStore (Update Product)", func() {
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
Return(http.Result[downloadResult]{}, original)
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
_, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, PlatformIPhone)
Expect(errors.Is(err, original)).To(BeTrue())
},
Entry("authentication", &http.UnexpectedResponseError{StatusCode: gohttp.StatusForbidden}),
@@ -259,7 +269,7 @@ var _ = Describe("AppStore (Update Product)", func() {
previous := expectPrimary()
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).Return(response, nil)
actual, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
actual, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, PlatformIPhone)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(response))
},
@@ -277,7 +287,7 @@ var _ = Describe("AppStore (Update Product)", func() {
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
Return(http.Result[downloadResult]{}, redownloadErr)
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
_, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, PlatformIPhone)
Expect(errors.Is(err, redownloadErr)).To(BeTrue())
})
@@ -287,24 +297,36 @@ var _ = Describe("AppStore (Update Product)", func() {
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
Return(http.Result[downloadResult]{}, redownloadErr)
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
_, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, PlatformIPhone)
Expect(err).To(MatchError("invalid download endpoint in bag"))
})
DescribeTable("does not extend the fallback to unverified platforms",
DescribeTable("does not update unpinned tvOS or unverified platforms",
func(versionID string, platform Platform) {
previous := expectPrimary()
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).
Return(http.Result[downloadResult]{}, redownloadErr)
_, resolvedPlatform, err := store.sendDownloadProduct(account, app, testGUID, versionID, platform)
_, resolvedPlatform, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, versionID, platform)
Expect(errors.Is(err, redownloadErr)).To(BeTrue())
Expect(resolvedPlatform).To(Equal(platform))
},
Entry("pinned tvOS", testVersionID, PlatformAppleTV),
Entry("unpinned tvOS", "", PlatformAppleTV),
Entry("pinned visionOS", testVersionID, PlatformVisionOS),
)
It("preserves an unpinned tvOS availability response without updating", func() {
previous := expectPrimary()
response := http.Result[downloadResult]{StatusCode: gohttp.StatusOK,
Data: downloadResult{CustomerMessage: "No Longer Available"}}
mockDownloadClient.EXPECT().Send(gomock.Any()).After(previous).Return(response, nil)
actual, platform, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, "", PlatformAppleTV)
Expect(err).ToNot(HaveOccurred())
Expect(actual).To(Equal(response))
Expect(platform).To(Equal(PlatformAppleTV))
})
It("propagates an update error without retrying again", func() {
previous := expectPrimary()
gomock.InOrder(
@@ -314,7 +336,7 @@ var _ = Describe("AppStore (Update Product)", func() {
Return(http.Result[downloadResult]{}, redownloadErr),
)
_, _, err := store.sendDownloadProduct(account, app, testGUID, testVersionID, PlatformIPhone)
_, _, err := store.sendDownloadProduct(context.Background(), account, app, testGUID, testVersionID, PlatformIPhone)
Expect(errors.Is(err, redownloadErr)).To(BeTrue())
Expect(err).To(MatchError(ContainSubstring("failed to send update request")))
})
@@ -0,0 +1,213 @@
package appstore
import (
"encoding/base64"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"time"
apphttp "github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/keychain"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
"howett.net/plist"
)
var _ = Describe("Authentication redirects", func() {
DescribeTable("preserves a signed POST, cookies, credentials and storefront after a credential retry",
func(status int, suffix, appleID, storefront, authCode string) {
ctrl := gomock.NewController(GinkgoT())
jar, err := cookiejar.New(nil)
Expect(err).NotTo(HaveOccurred())
client := apphttp.NewClient[loginResult](apphttp.Args{CookieJar: loginSessionJar{jar}, Authentication: true})
adapter := apphttp.NewMockClient[loginResult](ctrl)
chain := keychain.NewMockKeychain(ctrl)
chain.EXPECT().Set("account", gomock.Any()).Return(nil)
sut := &appstore{loginClient: adapter, keychain: chain, authRetrySleep: func(time.Duration) { Fail("must not sleep") }}
podURL := "https://p7-buy.itunes.apple.com" + PrivateAppStoreAPIPathAuth + suffix + "?routing=opaque"
calls := 0
var originalBody []byte
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer GinkgoRecover()
calls++
Expect(r.Method).To(Equal(http.MethodPost))
Expect(r.Header.Get("X-Apple-Store-Front")).To(Equal(storefront))
body, err := io.ReadAll(r.Body)
Expect(err).NotTo(HaveOccurred())
signature, err := base64.StdEncoding.DecodeString(r.Header.Get(apphttp.HeaderAppleActionSignature))
Expect(err).NotTo(HaveOccurred())
Expect(signature).To(Equal(body))
var payload map[string]string
_, err = plist.Unmarshal(body, &payload)
Expect(err).NotTo(HaveOccurred())
Expect(payload["appleId"]).To(Equal(appleID))
Expect(payload["password"]).To(Equal("password" + authCode))
if calls > 1 {
cookie, err := r.Cookie("session")
Expect(err).NotTo(HaveOccurred())
Expect(cookie.Value).To(Equal("retained"))
Expect(payload["attempt"]).To(Equal("2"))
}
switch calls {
case 1:
Expect(payload["attempt"]).To(Equal("1"))
http.SetCookie(w, &http.Cookie{Name: "session", Value: "retained", Path: "/"})
_, err = w.Write([]byte("<dict><key>failureType</key><string>-5000</string></dict>"))
Expect(err).NotTo(HaveOccurred())
case 2:
originalBody = body
w.Header().Set("Location", podURL)
w.WriteHeader(status)
case 3:
Expect(body).To(Equal(originalBody))
Expect(r.URL.Path).To(Equal(PrivateAppStoreAPIPathAuth + suffix))
Expect(r.URL.RawQuery).To(Equal("routing=opaque"))
w.Header().Set(HTTPHeaderStoreFront, "143441-1,29")
_, err = w.Write([]byte("<dict><key>passwordToken</key><string>token</string><key>dsPersonId</key><string>123</string></dict>"))
Expect(err).NotTo(HaveOccurred())
default:
Fail("unexpected request")
}
}))
DeferCleanup(srv.Close)
var destinations []string
adapter.EXPECT().Send(gomock.Any()).DoAndReturn(func(request apphttp.Request) (apphttp.Result[loginResult], error) {
destinations = append(destinations, request.URL)
parsed, err := url.Parse(request.URL)
Expect(err).NotTo(HaveOccurred())
request.URL = srv.URL + parsed.RequestURI()
return client.Send(request)
}).Times(3)
signer := &stubActionSigner{}
account, err := sut.login(appleID, "password", authCode, "guid", testAuthEndpoint+suffix, signer)
Expect(err).NotTo(HaveOccurred())
Expect(account.PasswordToken).To(Equal("token"))
Expect(account.StoreFront).To(Equal("143441-1,29"))
Expect(destinations).To(Equal([]string{testAuthEndpoint + suffix, testAuthEndpoint + suffix, podURL}))
Expect(signer.signCalls).To(Equal(3))
},
Entry("301, bare path", 301, "", "user@example.test", "", "123456"),
Entry("301, trailing slash", 301, "/", "user@example.test", "", "123456"),
Entry("302, bare path", 302, "", "user@example.test", "", "123456"),
Entry("302, trailing slash", 302, "/", "user@example.test", "", "123456"),
Entry("307, bare path", 307, "", "user@example.test", "", "123456"),
Entry("307, trailing slash", 307, "/", "user@example.test", "", "123456"),
Entry("308, bare path", 308, "", "user@example.test", "", "123456"),
Entry("308, trailing slash", 308, "/", "user@example.test", "", "123456"),
Entry("Chinese phone number before 2FA", 302, "/", "+86 139-1234-5678", "143465", ""),
Entry("Indian phone number with 2FA", 307, "/", "9123456789", "143467", "012345"),
)
It("follows relative and pod redirects within the redirect budget", func() {
ctrl := gomock.NewController(GinkgoT())
client := apphttp.NewMockClient[loginResult](ctrl)
chain := keychain.NewMockKeychain(ctrl)
chain.EXPECT().Set("account", gomock.Any()).Return(nil)
sut := &appstore{loginClient: client, keychain: chain}
pod := "https://p7-buy.itunes.apple.com" + PrivateAppStoreAPIPathAuth
urls := []string{testAuthEndpoint, testAuthEndpoint + "/", pod, pod + "/", pod + "/?routing=opaque"}
locations := []string{PrivateAppStoreAPIPathAuth + "/", "//p7-buy.itunes.apple.com" + PrivateAppStoreAPIPathAuth, "authenticate/", "?routing=opaque"}
statuses := []int{301, 302, 307, 308}
calls := 0
var original apphttp.Payload
client.EXPECT().Send(gomock.Any()).DoAndReturn(func(request apphttp.Request) (apphttp.Result[loginResult], error) {
Expect(request.URL).To(Equal(urls[calls]))
if calls == 0 {
original = request.Payload
}
Expect(request.Payload).To(BeIdenticalTo(original))
calls++
if calls <= len(locations) {
return apphttp.Result[loginResult]{StatusCode: statuses[calls-1], Headers: map[string]string{"Location": locations[calls-1]}}, nil
}
return apphttp.Result[loginResult]{StatusCode: 200, Headers: map[string]string{HTTPHeaderStoreFront: "storefront"}, Data: loginResult{PasswordToken: "token", DirectoryServicesID: "123"}}, nil
}).Times(5)
_, err := sut.login("email", "password", "", "guid", testAuthEndpoint, &stubActionSigner{})
Expect(err).NotTo(HaveOccurred())
})
It("stops a redirect loop without retaining response secrets", func() {
ctrl := gomock.NewController(GinkgoT())
client := apphttp.NewMockClient[loginResult](ctrl)
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{
StatusCode: 301,
Headers: map[string]string{"Location": testAuthEndpoint + "?token=secret-query", "Set-Cookie": "secret-cookie"},
Data: loginResult{PasswordToken: "secret-token"},
}, nil).Times(maxAuthenticationRedirects + 1)
sut := &appstore{loginClient: client}
_, err := sut.login("email", "password", "", "guid", testAuthEndpoint, &stubActionSigner{})
Expect(err).To(MatchError("too many authentication redirects (HTTP 301)"))
var authErr *Error
Expect(errors.As(err, &authErr)).To(BeTrue())
Expect(authErr.Metadata).To(Equal(map[string]interface{}{"statusCode": 301, "destination": testAuthEndpoint}))
})
It("retries the first credential failure at the assigned pod", func() {
ctrl := gomock.NewController(GinkgoT())
client := apphttp.NewMockClient[loginResult](ctrl)
sut := &appstore{loginClient: client}
pod := "https://p7-buy.itunes.apple.com" + PrivateAppStoreAPIPathAuth + "/"
calls := 0
client.EXPECT().Send(gomock.Any()).DoAndReturn(func(request apphttp.Request) (apphttp.Result[loginResult], error) {
calls++
if calls == 1 {
return apphttp.Result[loginResult]{StatusCode: 302, Headers: map[string]string{"Location": pod}}, nil
}
Expect(request.URL).To(Equal(pod))
if calls == 2 {
Expect(request.Payload.(*apphttp.XMLPayload).Content).To(HaveKeyWithValue("attempt", "1"))
return apphttp.Result[loginResult]{StatusCode: 200, Data: loginResult{FailureType: FailureTypeInvalidCredentials}}, nil
}
Expect(request.Payload.(*apphttp.XMLPayload).Content).To(HaveKeyWithValue("attempt", "2"))
return apphttp.Result[loginResult]{StatusCode: 200, Data: loginResult{FailureType: FailureTypeInvalidCredentials, CustomerMessage: "invalid credentials"}}, nil
}).Times(3)
_, err := sut.login("email", "password", "", "guid", testAuthEndpoint, &stubActionSigner{})
Expect(err).To(MatchError("invalid credentials"))
})
DescribeTable("rejects unsafe or unsupported redirects before reposting credentials",
func(status int, location string) {
ctrl := gomock.NewController(GinkgoT())
client := apphttp.NewMockClient[loginResult](ctrl)
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{
StatusCode: status,
Headers: map[string]string{"Location": location, "Set-Cookie": "secret-cookie"},
Data: loginResult{PasswordToken: "secret-token"},
}, nil).Times(1)
sut := &appstore{loginClient: client}
_, err := sut.login("email", "password", "", "guid", testAuthEndpoint, &stubActionSigner{})
Expect(err).To(HaveOccurred())
Expect(err.Error()).NotTo(ContainSubstring("secret"))
var authErr *Error
Expect(errors.As(err, &authErr)).To(BeTrue())
data, marshalErr := json.Marshal(authErr.Metadata)
Expect(marshalErr).NotTo(HaveOccurred())
Expect(string(data)).NotTo(ContainSubstring("secret"))
},
Entry("HTTP downgrade", 301, "http://buy.itunes.apple.com"+PrivateAppStoreAPIPathAuth),
Entry("foreign host", 302, "https://example.com"+PrivateAppStoreAPIPathAuth+"?token=secret-query"),
Entry("host suffix spoof", 307, "https://buy.itunes.apple.com.example.com"+PrivateAppStoreAPIPathAuth),
Entry("foreign protocol-relative host", 308, "//example.com"+PrivateAppStoreAPIPathAuth),
Entry("different path", 301, "https://buy.itunes.apple.com/other"),
Entry("userinfo", 302, "https://user:secret-password@buy.itunes.apple.com"+PrivateAppStoreAPIPathAuth),
Entry("different port", 307, "https://buy.itunes.apple.com:8443"+PrivateAppStoreAPIPathAuth),
Entry("encoded path", 308, "https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/%61uthenticate"),
Entry("fragment", 301, testAuthEndpoint+"#secret-fragment"),
Entry("fragment after query", 302, testAuthEndpoint+"?routing=opaque#secret-fragment"),
Entry("malformed URL", 302, "https://buy.itunes.apple.com/%secret"),
Entry("empty Location", 307, ""),
Entry("blank Location", 308, " \t"),
Entry("303 GET redirect", 303, testAuthEndpoint+"?token=secret-query"),
Entry("300 multiple choices", 300, testAuthEndpoint),
)
})
+156 -13
View File
@@ -1,12 +1,19 @@
package appstore
import (
"context"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"sync/atomic"
"syscall"
"time"
"github.com/majd/ipatool/v2/pkg/keychain"
@@ -19,6 +26,74 @@ import (
)
var _ = Describe("Authentication recovery", func() {
DescribeTable("bounds transport retries and preserves the underlying error", func(cause error, transportFailure bool, calls int) {
ctrl := gomock.NewController(GinkgoT())
client := apphttp.NewMockClient[loginResult](ctrl)
failure := cause
if transportFailure {
failure = &apphttp.TransportError{Err: cause}
}
failure = fmt.Errorf("request failed: %w", failure)
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{}, failure).Times(calls)
var waits []time.Duration
sut := &appstore{loginClient: client, authRetrySleep: func(delay time.Duration) { waits = append(waits, delay) }}
_, err := sut.sendAuthenticationRequest(apphttp.Request{})
Expect(errors.Is(err, cause)).To(BeTrue())
if calls == 1 {
Expect(waits).To(BeEmpty())
} else {
Expect(waits).To(Equal([]time.Duration{10 * time.Second, 20 * time.Second}))
Expect(err.Error()).To(ContainSubstring("after 3 attempts (transport error, transport error, transport error)"))
}
},
Entry("request deadline", context.DeadlineExceeded, true, 3),
Entry("request deadline wrapped by the header transport", &url.Error{Op: "Post", URL: testAuthEndpoint, Err: fmt.Errorf("failed to make round trip: %w", context.DeadlineExceeded)}, true, 3),
Entry("wrapped DNS timeout", &url.Error{Op: "Post", URL: testAuthEndpoint, Err: &net.DNSError{IsTimeout: true}}, true, 3),
Entry("DNS timeout wrapped by the header transport", &url.Error{Op: "Post", URL: testAuthEndpoint, Err: fmt.Errorf("failed to make round trip: %w", &net.DNSError{IsTimeout: true})}, true, 3),
Entry("connection closed", io.EOF, true, 3),
Entry("truncated response body", io.ErrUnexpectedEOF, true, 3),
Entry("connection reset", &net.OpError{Op: "read", Net: "tcp", Err: syscall.ECONNRESET}, true, 3),
Entry("broken pipe", &net.OpError{Op: "write", Net: "tcp", Err: syscall.EPIPE}, true, 3),
Entry("canceled request", context.Canceled, true, 1),
Entry("canceled request wrapped by the header transport", &url.Error{Op: "Post", URL: testAuthEndpoint, Err: fmt.Errorf("failed to make round trip: %w", context.Canceled)}, true, 1),
Entry("permanent DNS failure", &net.DNSError{IsNotFound: true}, true, 1),
Entry("certificate failure", &url.Error{Op: "Post", URL: testAuthEndpoint, Err: x509.UnknownAuthorityError{}}, true, 1),
Entry("signing or cookie storage timeout", context.DeadlineExceeded, false, 1),
Entry("local EOF", io.EOF, false, 1),
Entry("other transport failure", errors.New("unrecoverable transport error"), true, 1),
)
DescribeTable("shares the attempt budget with HTTP failures and still honors Retry-After", func(status int) {
ctrl := gomock.NewController(GinkgoT())
client := apphttp.NewMockClient[loginResult](ctrl)
last := &apphttp.TransportError{Err: context.DeadlineExceeded}
gomock.InOrder(
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{}, &apphttp.TransportError{Err: io.EOF}),
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{}, &apphttp.UnexpectedResponseError{StatusCode: status, RetryAfter: "2"}),
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{}, last),
)
var waits []time.Duration
sut := &appstore{loginClient: client, authRetrySleep: func(delay time.Duration) { waits = append(waits, delay) }}
_, err := sut.sendAuthenticationRequest(apphttp.Request{})
Expect(errors.Is(err, last)).To(BeTrue())
Expect(waits).To(Equal([]time.Duration{10 * time.Second, 2 * time.Second}))
Expect(err.Error()).To(ContainSubstring(fmt.Sprintf("after 3 attempts (transport error, HTTP %d, transport error)", status)))
},
Entry("non-plist 403", http.StatusForbidden),
Entry("503", http.StatusServiceUnavailable),
)
It("stops when an incomplete response requests a wait beyond the budget", func() {
ctrl := gomock.NewController(GinkgoT())
client := apphttp.NewMockClient[loginResult](ctrl)
failure := &apphttp.TransportError{Err: context.DeadlineExceeded, RetryAfter: "3600"}
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{}, failure).Times(1)
sut := &appstore{loginClient: client, authRetrySleep: func(time.Duration) { Fail("must not sleep") }}
_, err := sut.sendAuthenticationRequest(apphttp.Request{})
Expect(errors.Is(err, failure)).To(BeTrue())
Expect(err.Error()).To(ContainSubstring("apple requested a wait longer than 30s"))
})
DescribeTable("honors Retry-After without exceeding the wait budget",
func(status int, header string, calls int, expectedWaits []time.Duration) {
ctrl := gomock.NewController(GinkgoT())
@@ -44,7 +119,9 @@ var _ = Describe("Authentication recovery", func() {
Entry("404 without a deadline", 404, "", 3, []time.Duration{10 * time.Second, 20 * time.Second}),
Entry("Retry-After zero avoids a tight retry loop", 429, "0", 3, []time.Duration{time.Second, time.Second}),
Entry("503 with a long deadline", 503, "3600", 1, []time.Duration(nil)),
Entry("403 is not retried", 403, "1", 1, []time.Duration(nil)),
Entry("403 without a deadline", 403, "", 3, []time.Duration{10 * time.Second, 20 * time.Second}),
Entry("403 with a requested delay", 403, "1", 3, []time.Duration{time.Second, time.Second}),
Entry("403 with a long deadline", 403, "3600", 1, []time.Duration(nil)),
Entry("malformed redirect is not retried", 302, "", 1, []time.Duration(nil)),
)
@@ -66,7 +143,7 @@ var _ = Describe("Authentication recovery", func() {
}
})
It("does not retry populated Apple credential errors or 2FA challenges", func() {
DescribeTable("does not retry populated Apple credential errors or 2FA challenges", func(status int) {
ctrl := gomock.NewController(GinkgoT())
client := apphttp.NewMockClient[loginResult](ctrl)
sut := &appstore{loginClient: client, authRetrySleep: func(time.Duration) { Fail("must not sleep") }}
@@ -74,14 +151,17 @@ var _ = Describe("Authentication recovery", func() {
{FailureType: FailureTypeInvalidCredentials, CustomerMessage: "invalid credentials"},
{CustomerMessage: CustomerMessageBadLogin},
} {
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{StatusCode: 200, Data: data}, nil).Times(1)
client.EXPECT().Send(gomock.Any()).Return(apphttp.Result[loginResult]{StatusCode: status, Data: data}, nil).Times(1)
result, err := sut.sendAuthenticationRequest(apphttp.Request{})
Expect(err).NotTo(HaveOccurred())
_, _, err = sut.parseLoginResponse(&result, 2, "")
_, _, err = sut.parseLoginResponse(&result, 2, "", testAuthEndpoint)
Expect(err).To(HaveOccurred())
Expect(err.Error()).NotTo(ContainSubstring("another network"))
}
})
},
Entry("HTTP 200", http.StatusOK),
Entry("HTTP 403", http.StatusForbidden),
)
})
// The adapter only redirects network traffic to the local server; login still
@@ -91,7 +171,56 @@ type loginSessionJar struct{ *cookiejar.Jar }
func (loginSessionJar) Save() error { return nil }
var _ = Describe("Login session continuity", func() {
It("retains cookies and the signed payload through retries, a pod redirect and 2FA", func() {
It("recovers from a body timeout with cookies and a newly signed identical payload", func() {
jar, err := cookiejar.New(nil)
Expect(err).NotTo(HaveOccurred())
client := apphttp.NewClient[loginResult](apphttp.Args{CookieJar: loginSessionJar{jar}, Authentication: true, Timeout: 250 * time.Millisecond})
var calls atomic.Int32
bodies := make(chan []byte, 2)
releaseResponse := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer GinkgoRecover()
call := calls.Add(1)
Expect(r.Method).To(Equal(http.MethodPost))
body, err := io.ReadAll(r.Body)
Expect(err).NotTo(HaveOccurred())
bodies <- body
signature, err := base64.StdEncoding.DecodeString(r.Header.Get(apphttp.HeaderAppleActionSignature))
Expect(err).NotTo(HaveOccurred())
Expect(signature).To(Equal(body))
if call == 1 {
http.SetCookie(w, &http.Cookie{Name: "session", Value: "retained", Path: "/"})
w.Header().Set("Retry-After", "2")
w.WriteHeader(http.StatusTooManyRequests)
_, err = w.Write([]byte("<dict>"))
Expect(err).NotTo(HaveOccurred())
w.(http.Flusher).Flush()
<-releaseResponse
return
}
Expect(call).To(Equal(int32(2)))
cookie, err := r.Cookie("session")
Expect(err).NotTo(HaveOccurred())
Expect(cookie.Value).To(Equal("retained"))
_, err = w.Write([]byte("<dict><key>passwordToken</key><string>token</string><key>dsPersonId</key><string>123</string></dict>"))
Expect(err).NotTo(HaveOccurred())
}))
DeferCleanup(srv.Close)
DeferCleanup(func() { close(releaseResponse) })
var waits []time.Duration
sut := &appstore{loginClient: client, authRetrySleep: func(delay time.Duration) { waits = append(waits, delay) }}
signer := &stubActionSigner{}
request := sut.loginRequest("email", "password", "123456", "guid", srv.URL+PrivateAppStoreAPIPathAuth, 1, signer)
result, err := sut.sendAuthenticationRequest(request)
Expect(err).NotTo(HaveOccurred())
Expect(result.Data.PasswordToken).To(Equal("token"))
Expect(waits).To(Equal([]time.Duration{2 * time.Second}))
Expect(signer.signCalls).To(Equal(2))
Expect(<-bodies).To(Equal(<-bodies))
})
It("retains cookies and the signed payload through retries, a pod HTML 403 and 2FA", func() {
ctrl := gomock.NewController(GinkgoT())
jar, err := cookiejar.New(nil)
Expect(err).NotTo(HaveOccurred())
@@ -99,9 +228,11 @@ var _ = Describe("Login session continuity", func() {
adapter := apphttp.NewMockClient[loginResult](ctrl)
keychain := keychain.NewMockKeychain(ctrl)
keychain.EXPECT().Set("account", gomock.Any()).Return(nil).Times(1)
sut := &appstore{loginClient: adapter, keychain: keychain, authRetrySleep: func(time.Duration) {}}
connections := make(chan string, 4)
var waits []time.Duration
sut := &appstore{loginClient: adapter, keychain: keychain, authRetrySleep: func(delay time.Duration) { waits = append(waits, delay) }}
connections := make(chan string, 5)
calls := 0
var originalBody []byte
podURL := "https://p7-buy.itunes.apple.com" + PrivateAppStoreAPIPathAuth
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer GinkgoRecover()
@@ -110,6 +241,11 @@ var _ = Describe("Login session continuity", func() {
Expect(r.Method).To(Equal(http.MethodPost))
body, err := io.ReadAll(r.Body)
Expect(err).NotTo(HaveOccurred())
if calls == 1 {
originalBody = body
} else if calls <= 4 {
Expect(body).To(Equal(originalBody))
}
signature, err := base64.StdEncoding.DecodeString(r.Header.Get(apphttp.HeaderAppleActionSignature))
Expect(err).NotTo(HaveOccurred())
Expect(signature).To(Equal(body))
@@ -130,12 +266,17 @@ var _ = Describe("Login session continuity", func() {
w.Header().Set("Location", podURL)
w.WriteHeader(http.StatusFound)
case 3:
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusForbidden)
_, err = w.Write([]byte("<html><body>Access Denied</body></html>"))
Expect(err).NotTo(HaveOccurred())
case 4:
Expect(payload["password"]).To(Equal("password"))
data, err := plist.Marshal(map[string]string{"customerMessage": CustomerMessageBadLogin}, plist.XMLFormat)
Expect(err).NotTo(HaveOccurred())
_, err = w.Write(data)
Expect(err).NotTo(HaveOccurred())
case 4:
case 5:
Expect(payload["password"]).To(Equal("password123456"))
w.Header().Set(HTTPHeaderStoreFront, "143441-1,29")
_, err = w.Write([]byte("<dict><key>passwordToken</key><string>token</string><key>dsPersonId</key><string>123</string></dict>"))
@@ -148,23 +289,25 @@ var _ = Describe("Login session continuity", func() {
adapted := 0
adapter.EXPECT().Send(gomock.Any()).DoAndReturn(func(request apphttp.Request) (apphttp.Result[loginResult], error) {
adapted++
if adapted == 3 {
if adapted == 3 || adapted == 4 {
Expect(request.URL).To(Equal(podURL))
}
request.URL = srv.URL + PrivateAppStoreAPIPathAuth
return client.Send(request)
}).Times(4)
}).Times(5)
signer := &stubActionSigner{}
_, err = sut.login("email", "password", "", "guid", testAuthEndpoint, signer)
Expect(errors.Is(err, ErrAuthCodeRequired)).To(BeTrue())
account, err := sut.login("email", "password", "123456", "guid", testAuthEndpoint, signer)
Expect(err).NotTo(HaveOccurred())
Expect(account.PasswordToken).To(Equal("token"))
Expect(waits).To(Equal([]time.Duration{10 * time.Second, 10 * time.Second}))
Expect(signer.signCalls).To(Equal(5))
seen := map[string]bool{}
for range 4 {
for range 5 {
seen[<-connections] = true
}
Expect(seen).To(HaveLen(4))
Expect(seen).To(HaveLen(5))
})
})
+4
View File
@@ -9,6 +9,10 @@ func (t Error) Error() string {
return t.underlyingError.Error()
}
func (t Error) Unwrap() error {
return t.underlyingError
}
func NewErrorWithMetadata(err error, metadata interface{}) *Error {
return &Error{
underlyingError: err,
+8 -1
View File
@@ -13,6 +13,7 @@ const (
PlatformIPhone Platform = "iphone"
PlatformIPad Platform = "ipad"
PlatformAppleTV Platform = "appletv"
PlatformWatchOS Platform = "watchos"
PlatformVisionOS Platform = "visionos"
PlatformMacOS Platform = "macos"
)
@@ -27,6 +28,8 @@ func ParsePlatform(value string) (Platform, error) {
return PlatformIPad, nil
case "appletv", "apple-tv", "tvos":
return PlatformAppleTV, nil
case "watch", "watchos", "applewatch", "apple-watch":
return PlatformWatchOS, nil
case "vision", "visionos", "visionpro", "xros", "realitydevice":
return PlatformVisionOS, nil
case "mac", "macos", "osx":
@@ -46,6 +49,8 @@ func (p Platform) lookupEntity() (string, error) {
return "iPadSoftware", nil
case PlatformAppleTV:
return "tvSoftware", nil
case PlatformWatchOS:
return "watchSoftware", nil
case PlatformVisionOS:
return "xrosSoftware", nil
case PlatformMacOS:
@@ -65,6 +70,8 @@ func (p Platform) searchEntity() (string, error) {
return "iPadSoftware", nil
case PlatformAppleTV:
return "software,tvSoftware", nil
case PlatformWatchOS:
return "software,watchSoftware", nil
case PlatformVisionOS:
return "xrosSoftware", nil
case PlatformMacOS:
@@ -76,7 +83,7 @@ func (p Platform) searchEntity() (string, error) {
func (p Platform) metadataPlatform() (string, error) {
switch p {
case PlatformIPhone, PlatformIPad:
case PlatformIPhone, PlatformIPad, PlatformWatchOS:
return "enterprisestore", nil
case PlatformAppleTV:
return "atv9", nil
+9 -2
View File
@@ -19,6 +19,10 @@ var _ = Describe("Platform", func() {
Entry("iPadOS", "iPadOS", PlatformIPad),
Entry("AppleTV", "appletv", PlatformAppleTV),
Entry("tvOS", "tvos", PlatformAppleTV),
Entry("watchOS", "watchOS", PlatformWatchOS),
Entry("Watch", "watch", PlatformWatchOS),
Entry("Apple Watch", "applewatch", PlatformWatchOS),
Entry("Apple Watch hyphenated", "apple-watch", PlatformWatchOS),
Entry("visionOS", "visionOS", PlatformVisionOS),
Entry("Vision Pro", "visionpro", PlatformVisionOS),
Entry("xrOS", "xrOS", PlatformVisionOS),
@@ -38,6 +42,7 @@ var _ = Describe("Platform", func() {
Entry("iPhone", PlatformIPhone, "software"),
Entry("iPad", PlatformIPad, "iPadSoftware"),
Entry("Apple TV", PlatformAppleTV, "tvSoftware"),
Entry("watchOS", PlatformWatchOS, "watchSoftware"),
Entry("visionOS", PlatformVisionOS, "xrosSoftware"),
Entry("macOS", PlatformMacOS, "macSoftware"),
)
@@ -52,6 +57,7 @@ var _ = Describe("Platform", func() {
Entry("iPhone", PlatformIPhone, "software"),
Entry("iPad", PlatformIPad, "iPadSoftware"),
Entry("Apple TV", PlatformAppleTV, "software,tvSoftware"),
Entry("watchOS", PlatformWatchOS, "software,watchSoftware"),
Entry("visionOS", PlatformVisionOS, "xrosSoftware"),
Entry("macOS", PlatformMacOS, "macSoftware"),
)
@@ -65,16 +71,17 @@ var _ = Describe("Platform", func() {
Entry("iPhone", PlatformIPhone, "enterprisestore"),
Entry("iPad", PlatformIPad, "enterprisestore"),
Entry("Apple TV", PlatformAppleTV, "atv9"),
Entry("watchOS", PlatformWatchOS, "enterprisestore"),
Entry("visionOS", PlatformVisionOS, "realityDevice"),
)
It("returns an error for invalid platforms", func() {
_, err := ParsePlatform("watch")
_, err := ParsePlatform("unsupported")
Expect(err).To(HaveOccurred())
})
It("returns errors when an unknown platform is mapped", func() {
platform := Platform("watch")
platform := Platform("unsupported")
_, lookupErr := platform.lookupEntity()
_, searchErr := platform.searchEntity()
+46
View File
@@ -16,6 +16,49 @@ type sessionCookieJar struct{ *cookiejar.Jar }
func (sessionCookieJar) Save() error { return nil }
var _ = Describe("Authentication transport", func() {
DescribeTable("returns redirects for explicit validation without contacting their destination",
func(http2 bool, status int, suffix string) {
jar, err := cookiejar.New(nil)
Expect(err).NotTo(HaveOccurred())
calls := 0
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer GinkgoRecover()
calls++
Expect(r.Method).To(Equal(http.MethodPost))
Expect(r.URL.Path).To(Equal(appStoreAuthPath + suffix))
Expect(r.ProtoMajor).To(Equal(map[bool]int{false: 1, true: 2}[http2]))
if calls == 1 {
w.Header().Set("Location", "/must-not-follow?token=secret")
w.WriteHeader(status)
}
}))
srv.EnableHTTP2 = http2
srv.StartTLS()
DeferCleanup(srv.Close)
sut := NewClient[struct{}](Args{CookieJar: sessionCookieJar{jar}, Authentication: true}).(*client[struct{}])
transport := sut.internalClient.Transport.(*AddHeaderTransport).T.(*http.Transport)
transport.TLSClientConfig = srv.Client().Transport.(*http.Transport).TLSClientConfig.Clone()
DeferCleanup(transport.CloseIdleConnections)
result, err := sut.Send(Request{
URL: srv.URL + appStoreAuthPath + suffix, Method: MethodPOST, ResponseFormat: ResponseFormatXML,
Payload: &XMLPayload{Content: map[string]interface{}{"password": "secret"}},
})
Expect(err).NotTo(HaveOccurred())
Expect(result.StatusCode).To(Equal(status))
Expect(result.Headers).To(HaveKeyWithValue("Location", "/must-not-follow?token=secret"))
Expect(calls).To(Equal(1))
},
Entry("301, bare path, HTTP/1.1", false, 301, ""),
Entry("301, trailing slash, HTTP/2", true, 301, "/"),
Entry("302, trailing slash, HTTP/1.1", false, 302, "/"),
Entry("302, bare path, HTTP/2", true, 302, ""),
Entry("307, trailing slash, HTTP/1.1", false, 307, "/"),
Entry("307, bare path, HTTP/2", true, 307, ""),
Entry("308, bare path, HTTP/1.1", false, 308, ""),
Entry("308, trailing slash, HTTP/2", true, 308, "/"),
Entry("303 must also reach the caller for rejection", false, 303, "/"),
)
DescribeTable("preserves cookies and signed POSTs across fresh connections",
func(http2 bool) {
jar, err := cookiejar.New(nil)
@@ -146,6 +189,9 @@ var _ = Describe("Authentication transport", func() {
Entry("empty forbidden response", 403, "", "empty or non-plist authentication response"),
Entry("HTML failure", 500, "<html>secret-password</html>", "empty or non-plist authentication response"),
Entry("redirect without Location", 302, "secret-token", "authentication redirect is missing Location"),
Entry("permanent redirect without Location", 301, "secret-token", "authentication redirect is missing Location"),
Entry("temporary redirect without Location", 307, "secret-token", "authentication redirect is missing Location"),
Entry("permanent POST redirect without Location", 308, "secret-token", "authentication redirect is missing Location"),
Entry("rate limit", 429, "secret-token", "rate limited by Apple"),
Entry("malformed plist", 200, "<plist><dict>secret-token", "malformed authentication plist"),
)
+44 -8
View File
@@ -7,15 +7,30 @@ import (
"errors"
"fmt"
"io"
"net"
"net/http"
"regexp"
"strings"
"time"
"howett.net/plist"
)
const appStoreAuthPath = "/WebObjects/MZFinance.woa/wa/authenticate"
const DefaultAuthenticationTimeout = 30 * time.Second
// IsAuthenticationRedirect reports which Store redirects can replay a signed POST.
// A 303 explicitly requests a GET and is not part of this authentication flow.
func IsAuthenticationRedirect(status int) bool {
switch status {
case http.StatusMovedPermanently, http.StatusFound, http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
return true
default:
return false
}
}
var (
documentXMLPattern = regexp.MustCompile(`(?is)<Document\b[^>]*>(.*)</Document>`)
plistXMLPattern = regexp.MustCompile(`(?is)<plist\b[^>]*>.*?</plist>`)
@@ -40,6 +55,9 @@ type Args struct {
CookieJar CookieJar
// Authentication isolates login connections and reports only allowlisted response diagnostics.
Authentication bool
// Timeout covers the request and response body. Zero uses the authentication
// default for login clients and leaves other clients without an overall limit.
Timeout time.Duration
}
// UnexpectedResponseError preserves the HTTP status when Apple returns an
@@ -85,22 +103,31 @@ func (t *AddHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error
func NewClient[R interface{}](args Args) Client[R] {
transport := http.DefaultTransport
timeout := args.Timeout
if args.Authentication {
if timeout == 0 {
timeout = DefaultAuthenticationTimeout
}
// Keep the cookie jar, but do not share pooled connections with other
// Store operations or reuse a connection for the next login attempt.
isolated := http.DefaultTransport.(*http.Transport).Clone()
isolated.DisableKeepAlives = true
isolated.DialContext = (&net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}).DialContext
transport = isolated
}
return &client[R]{
authentication: args.Authentication,
internalClient: http.Client{
Timeout: 0,
Timeout: timeout,
Jar: args.CookieJar,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) > 0 && via[len(via)-1].URL.Path == appStoreAuthPath {
// Login validates destinations and replays the signed POST itself.
// Never let net/http turn an authentication redirect into a GET.
if args.Authentication || (len(via) > 0 &&
(via[len(via)-1].URL.Path == appStoreAuthPath || via[len(via)-1].URL.Path == appStoreAuthPath+"/")) {
return http.ErrUseLastResponse
}
@@ -130,6 +157,10 @@ func (c *client[R]) Send(req Request) (Result[R], error) {
return Result[R]{}, fmt.Errorf("failed to create request: %w", err)
}
if req.Context != nil {
request = request.WithContext(req.Context)
}
for key, val := range req.Headers {
request.Header.Set(key, val)
}
@@ -143,9 +174,14 @@ func (c *client[R]) Send(req Request) (Result[R], error) {
request.Header.Set(HeaderAppleActionSignature, base64.StdEncoding.EncodeToString(signature))
}
res, err := c.internalClient.Do(request)
client := c.internalClient
if req.NoRedirects {
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
}
res, err := client.Do(request)
if err != nil {
return Result[R]{}, fmt.Errorf("request failed: %w", err)
return Result[R]{}, fmt.Errorf("request failed: %w", &TransportError{Err: err})
}
defer res.Body.Close()
@@ -172,7 +208,7 @@ func (c *client[R]) Send(req Request) (Result[R], error) {
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)
return Result[R]{}, fmt.Errorf("failed to read response body: %w", &TransportError{Err: err, RetryAfter: res.Header.Get("Retry-After")})
}
data, ok := any(body).(R)
@@ -208,7 +244,7 @@ func (*client[R]) NewRequest(method, url string, body io.Reader) (*http.Request,
func (c *client[R]) handleJSONResponse(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)
return Result[R]{}, fmt.Errorf("failed to read response body: %w", &TransportError{Err: err, RetryAfter: res.Header.Get("Retry-After")})
}
var data R
@@ -227,10 +263,10 @@ func (c *client[R]) handleJSONResponse(res *http.Response) (Result[R], error) {
func (c *client[R]) handleXMLResponse(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)
return Result[R]{}, fmt.Errorf("failed to read response body: %w", &TransportError{Err: err, RetryAfter: res.Header.Get("Retry-After")})
}
if c.authentication && res.StatusCode == http.StatusFound && strings.TrimSpace(res.Header.Get("Location")) == "" {
if c.authentication && IsAuthenticationRedirect(res.StatusCode) && strings.TrimSpace(res.Header.Get("Location")) == "" {
return Result[R]{}, authenticationResponseError(res, body, "authentication redirect is missing Location")
}
+4
View File
@@ -1,6 +1,10 @@
package http
import "context"
type Request struct {
Context context.Context
NoRedirects bool
Method string
URL string
Headers map[string]string
+75
View File
@@ -0,0 +1,75 @@
package http
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
)
var _ = Describe("HTTP request options", func() {
var jar *MockCookieJar
BeforeEach(func() {
jar = NewMockCookieJar(gomock.NewController(GinkgoT()))
jar.EXPECT().Cookies(gomock.Any()).Return(nil).AnyTimes()
jar.EXPECT().Save().Return(nil).AnyTimes()
})
It("stops redirects for a token-bearing request without changing subsequent requests", func() {
var visited atomic.Int32
destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
visited.Add(1)
w.WriteHeader(http.StatusOK)
}))
defer destination.Close()
source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, destination.URL, http.StatusTemporaryRedirect)
}))
defer source.Close()
client := NewClient[[]byte](Args{CookieJar: jar})
request := Request{URL: source.URL, Method: MethodPOST, ResponseFormat: ResponseFormatRaw, NoRedirects: true, Headers: map[string]string{"X-Token": "test-token"}}
result, err := client.Send(request)
Expect(err).NotTo(HaveOccurred())
Expect(result.StatusCode).To(Equal(http.StatusTemporaryRedirect))
Expect(visited.Load()).To(BeZero())
result, err = client.Send(Request{URL: source.URL, Method: MethodGET, ResponseFormat: ResponseFormatRaw})
Expect(err).NotTo(HaveOccurred())
Expect(result.StatusCode).To(Equal(http.StatusOK))
Expect(visited.Load()).To(Equal(int32(1)))
})
It("honors a request deadline while reading the response body", func() {
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
<-release
}))
defer server.Close()
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
client := NewClient[[]byte](Args{CookieJar: jar})
_, err := client.Send(Request{Context: ctx, URL: server.URL, Method: MethodGET, ResponseFormat: ResponseFormatRaw})
Expect(errors.Is(err, context.DeadlineExceeded)).To(BeTrue())
})
It("does not send a canceled request", func() {
var visited atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { visited.Store(true) }))
defer server.Close()
ctx, cancel := context.WithCancel(context.Background())
cancel()
client := NewClient[[]byte](Args{CookieJar: jar})
_, err := client.Send(Request{Context: ctx, URL: server.URL, Method: MethodGET, ResponseFormat: ResponseFormatRaw})
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
Expect(visited.Load()).To(BeFalse())
})
})
+118
View File
@@ -0,0 +1,118 @@
package http
import (
"context"
"errors"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"strings"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type timeoutTestTransport func(*http.Request) (*http.Response, error)
func (t timeoutTestTransport) RoundTrip(request *http.Request) (*http.Response, error) {
return t(request)
}
type timeoutTestJar struct {
*cookiejar.Jar
saveErr error
}
func (j timeoutTestJar) Save() error { return j.saveErr }
var _ = Describe("Request timeouts", func() {
DescribeTable("applies deadlines to bounded clients without limiting downloads", func(args Args, want time.Duration) {
jar, err := cookiejar.New(nil)
Expect(err).NotTo(HaveOccurred())
args.CookieJar = sessionCookieJar{jar}
sut := NewClient[[]byte](args).(*client[[]byte])
sut.internalClient.Transport = timeoutTestTransport(func(request *http.Request) (*http.Response, error) {
deadline, ok := request.Context().Deadline()
Expect(ok).To(Equal(want > 0))
if ok {
Expect(time.Until(deadline)).To(BeNumerically(">", want-time.Second))
Expect(time.Until(deadline)).To(BeNumerically("<=", want))
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("body"))}, nil
})
result, err := sut.Send(Request{URL: "https://example.com", Method: MethodGET, ResponseFormat: ResponseFormatRaw})
Expect(err).NotTo(HaveOccurred())
Expect(result.Data).To(Equal([]byte("body")))
},
Entry("authentication default", Args{Authentication: true}, 30*time.Second),
Entry("authentication override", Args{Authentication: true, Timeout: 5 * time.Second}, 5*time.Second),
Entry("bounded bag client", Args{Timeout: DefaultAuthenticationTimeout}, 30*time.Second),
Entry("ordinary download client", Args{}, time.Duration(0)),
)
DescribeTable("interrupts stalled authentication responses", func(http2, bodyStarted bool) {
jar, err := cookiejar.New(nil)
Expect(err).NotTo(HaveOccurred())
releaseResponse := make(chan struct{})
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer GinkgoRecover()
Expect(r.ProtoMajor).To(Equal(map[bool]int{false: 1, true: 2}[http2]))
if bodyStarted {
_, err := w.Write([]byte("<dict><key>passwordToken</key>"))
Expect(err).NotTo(HaveOccurred())
w.(http.Flusher).Flush()
}
// Keep the response incomplete until Send returns; finishing on
// server-side cancellation can race with the client's body read.
<-releaseResponse
}))
srv.EnableHTTP2 = http2
srv.StartTLS()
DeferCleanup(srv.Close)
DeferCleanup(func() { close(releaseResponse) })
sut := NewClient[struct{}](Args{Authentication: true, CookieJar: sessionCookieJar{jar}, Timeout: 250 * time.Millisecond}).(*client[struct{}])
transport := sut.internalClient.Transport.(*AddHeaderTransport).T.(*http.Transport)
transport.TLSClientConfig = srv.Client().Transport.(*http.Transport).TLSClientConfig.Clone()
DeferCleanup(transport.CloseIdleConnections)
_, err = sut.Send(Request{URL: srv.URL + appStoreAuthPath, Method: MethodPOST, ResponseFormat: ResponseFormatXML})
Expect(err).To(HaveOccurred())
var transportErr *TransportError
Expect(errors.As(err, &transportErr)).To(BeTrue(), "expected a transport failure, got %v", err)
// A url.Error need not report Timeout when a transport wrapper sits
// between it and the deadline error. Assert the underlying cause.
Expect(errors.Is(err, context.DeadlineExceeded)).To(BeTrue(), "expected a deadline failure, got %v", err)
if bodyStarted {
Expect(err.Error()).To(HavePrefix("failed to read response body:"))
} else {
Expect(err.Error()).To(HavePrefix("request failed:"))
}
},
Entry("waiting for HTTP/1.1 headers", false, false),
Entry("reading an HTTP/1.1 body", false, true),
Entry("waiting for HTTP/2 headers", true, false),
Entry("reading an HTTP/2 body", true, true),
)
DescribeTable("keeps local timeouts distinct from transport failures", func(signing bool) {
jar, err := cookiejar.New(nil)
Expect(err).NotTo(HaveOccurred())
args := Args{Authentication: true, CookieJar: timeoutTestJar{Jar: jar, saveErr: context.DeadlineExceeded}}
sut := NewClient[struct{}](args).(*client[struct{}])
sut.internalClient.Transport = timeoutTestTransport(func(request *http.Request) (*http.Response, error) {
Expect(signing).To(BeFalse())
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("<dict/>"))}, nil
})
request := Request{URL: "https://example.com", Method: MethodPOST, ResponseFormat: ResponseFormatXML}
if signing {
request.ActionSigner = &recordingActionSigner{err: context.DeadlineExceeded}
}
_, err = sut.Send(request)
Expect(errors.Is(err, context.DeadlineExceeded)).To(BeTrue())
var transportErr *TransportError
Expect(errors.As(err, &transportErr)).To(BeFalse())
}, Entry("signing", true), Entry("saving cookies", false))
})
+18
View File
@@ -0,0 +1,18 @@
package http
// TransportError identifies Send failures while sending a request or reading
// its response, so callers can distinguish them from signing, encoding and
// storage failures before deciding whether to retry.
type TransportError struct {
Err error
// RetryAfter retains Apple's backoff even when reading the response fails.
RetryAfter string
}
func (e *TransportError) Error() string {
return e.Err.Error()
}
func (e *TransportError) Unwrap() error {
return e.Err
}
+66
View File
@@ -0,0 +1,66 @@
package machine
import (
"bytes"
"errors"
"fmt"
"net"
)
const (
macPriorityPrimary = iota
macPriorityPhysical
macPriorityFallback
)
type macAddressCandidate struct {
address net.HardwareAddr
priority int
}
func usableMacAddress(address net.HardwareAddr) bool {
return len(address) == 6 && address[0]&1 == 0 &&
!bytes.Equal(address, []byte{0, 0, 0, 0, 0, 0}) &&
!bytes.Equal(address, []byte{0x02, 0, 0, 0, 0, 0})
}
func selectMacAddress(interfaces []net.Interface, lookup func(net.Interface) (macAddressCandidate, error)) (string, error) {
var (
selected macAddressCandidate
lookupErr error
)
for _, networkInterface := range interfaces {
if networkInterface.Flags&(net.FlagLoopback|net.FlagPointToPoint) != 0 {
continue
}
candidate, err := lookup(networkInterface)
if err != nil {
lookupErr = errors.Join(lookupErr, err)
continue
}
if !usableMacAddress(candidate.address) {
continue
}
// Do not use enumeration order, interface index or link state as a
// tie-breaker: those can change without changing the machine.
if selected.address == nil || candidate.priority < selected.priority ||
(candidate.priority == selected.priority && bytes.Compare(candidate.address, selected.address) < 0) {
selected = candidate
}
}
if selected.address != nil {
return selected.address.String(), nil
}
if lookupErr != nil {
return "", fmt.Errorf("could not find network interfaces with a valid mac address: %w", lookupErr)
}
return "", errors.New("could not find network interfaces with a valid mac address")
}
+129
View File
@@ -0,0 +1,129 @@
//go:build darwin && !ios
package machine
import (
"errors"
"fmt"
"net"
"unsafe"
"github.com/ebitengine/purego"
)
func interfaceMacAddress(networkInterface net.Interface) (macAddressCandidate, error) {
return macAddressWithHardwareLookup(networkInterface, hardwareMacAddress)
}
func macAddressWithHardwareLookup(networkInterface net.Interface, lookup func(string) (net.HardwareAddr, error)) (macAddressCandidate, error) {
// IOKit supplies the hardware address even when the current network address
// is randomized or redacted. Prefer en0, then other hardware interfaces.
address, err := lookup(networkInterface.Name)
if err == nil && usableMacAddress(address) {
priority := macPriorityPhysical
if networkInterface.Name == "en0" {
priority = macPriorityPrimary
}
return macAddressCandidate{address: address, priority: priority}, nil
}
if usableMacAddress(networkInterface.HardwareAddr) {
return macAddressCandidate{address: networkInterface.HardwareAddr, priority: macPriorityFallback}, nil
}
if err != nil {
return macAddressCandidate{}, fmt.Errorf("failed to read hardware address for %q: %w", networkInterface.Name, err)
}
return macAddressCandidate{}, fmt.Errorf("IOKit returned no usable hardware address for %q", networkInterface.Name)
}
type macAddressAPI struct {
matching func(uint32, uint32, string) uintptr
service func(uint32, uintptr) uint32
searchProperty func(uint32, string, uintptr, uintptr, uint32) uintptr
releaseObject func(uint32) int32
createString func(uintptr, string, uint32) uintptr
release func(uintptr)
typeID func(uintptr) uintptr
dataTypeID func() uintptr
dataLength func(uintptr) int64
dataBytes func(uintptr) unsafe.Pointer
}
func hardwareMacAddress(name string) (net.HardwareAddr, error) {
iokit, err := purego.Dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", purego.RTLD_NOW|purego.RTLD_LOCAL)
if err != nil {
return nil, fmt.Errorf("load IOKit: %w", err)
}
defer func() { _ = purego.Dlclose(iokit) }()
coreFoundation, err := purego.Dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", purego.RTLD_NOW|purego.RTLD_LOCAL)
if err != nil {
return nil, fmt.Errorf("load CoreFoundation: %w", err)
}
defer func() { _ = purego.Dlclose(coreFoundation) }()
var api macAddressAPI
purego.RegisterLibFunc(&api.matching, iokit, "IOBSDNameMatching")
purego.RegisterLibFunc(&api.service, iokit, "IOServiceGetMatchingService")
purego.RegisterLibFunc(&api.searchProperty, iokit, "IORegistryEntrySearchCFProperty")
purego.RegisterLibFunc(&api.releaseObject, iokit, "IOObjectRelease")
purego.RegisterLibFunc(&api.createString, coreFoundation, "CFStringCreateWithCString")
purego.RegisterLibFunc(&api.release, coreFoundation, "CFRelease")
purego.RegisterLibFunc(&api.typeID, coreFoundation, "CFGetTypeID")
purego.RegisterLibFunc(&api.dataTypeID, coreFoundation, "CFDataGetTypeID")
purego.RegisterLibFunc(&api.dataLength, coreFoundation, "CFDataGetLength")
purego.RegisterLibFunc(&api.dataBytes, coreFoundation, "CFDataGetBytePtr")
return readHardwareMacAddress(name, api)
}
func readHardwareMacAddress(name string, api macAddressAPI) (net.HardwareAddr, error) {
matching := api.matching(0, 0, name)
if matching == 0 {
return nil, errors.New("could not create interface matching dictionary")
}
// IOServiceGetMatchingService consumes the matching dictionary.
service := api.service(0, matching)
if service == 0 {
return nil, errors.New("network interface was not found in IOKit")
}
defer api.releaseObject(service)
const utf8Encoding = 0x08000100
key := api.createString(0, "IOMACAddress", utf8Encoding)
if key == 0 {
return nil, errors.New("could not create hardware address property key")
}
defer api.release(key)
// Apple's receipt-validation guidance reads IOMACAddress from the interface
// or its parents in the IOService plane.
// https://developer.apple.com/documentation/appstorereceipts/validating-receipts-on-the-device
const iterateRecursivelyAndParents = 0x01 | 0x02
property := api.searchProperty(service, "IOService", key, 0, iterateRecursivelyAndParents)
if property == 0 {
return nil, errors.New("hardware address property was not found in IOKit")
}
defer api.release(property)
if api.typeID(property) != api.dataTypeID() || api.dataLength(property) != 6 {
return nil, errors.New("IOKit hardware address must contain six bytes")
}
data := api.dataBytes(property)
if data == nil {
return nil, errors.New("IOKit hardware address data is missing")
}
// Copy the bytes before releasing the CoreFoundation property.
return append(net.HardwareAddr(nil), unsafe.Slice((*byte)(data), 6)...), nil
}
+251
View File
@@ -0,0 +1,251 @@
//go:build darwin && !ios
package machine
import (
"errors"
"net"
"unsafe"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("macOS hardware address", func() {
var networkInterface net.Interface
BeforeEach(func() {
networkInterface = net.Interface{
Name: "en4",
HardwareAddr: net.HardwareAddr{0x02, 0, 0, 0, 0, 0},
}
})
It("falls back to an unredacted address when IOKit is unavailable", func() {
networkInterface.HardwareAddr = net.HardwareAddr{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}
address, err := macAddressWithHardwareLookup(networkInterface, func(string) (net.HardwareAddr, error) {
return nil, errors.New("IOKit unavailable")
})
Expect(err).ToNot(HaveOccurred())
Expect(address.address.String()).To(Equal("aa:bb:cc:dd:ee:ff"))
Expect(address.priority).To(Equal(macPriorityFallback))
})
It("recovers the hardware address of the selected interface when redacted", func() {
address, err := macAddressWithHardwareLookup(networkInterface, func(name string) (net.HardwareAddr, error) {
Expect(name).To(Equal("en4"))
return net.HardwareAddr{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, nil
})
Expect(err).ToNot(HaveOccurred())
Expect(address.address.String()).To(Equal("aa:bb:cc:dd:ee:ff"))
Expect(address.priority).To(Equal(macPriorityPhysical))
})
It("prefers en0's hardware address over its randomized network address", func() {
networkInterface.Name = "en0"
networkInterface.HardwareAddr = net.HardwareAddr{0x02, 1, 2, 3, 4, 5}
address, err := macAddressWithHardwareLookup(networkInterface, func(name string) (net.HardwareAddr, error) {
Expect(name).To(Equal("en0"))
return net.HardwareAddr{0x00, 1, 2, 3, 4, 5}, nil
})
Expect(err).NotTo(HaveOccurred())
Expect(address.address.String()).To(Equal("00:01:02:03:04:05"))
Expect(address.priority).To(Equal(macPriorityPrimary))
})
It("reports unavailable hardware information without returning the placeholder", func() {
lookupErr := errors.New("interface unavailable")
address, err := macAddressWithHardwareLookup(networkInterface, func(string) (net.HardwareAddr, error) {
return nil, lookupErr
})
Expect(address.address).To(BeEmpty())
Expect(errors.Is(err, lookupErr)).To(BeTrue())
Expect(err.Error()).To(ContainSubstring("failed to read hardware address for \"en4\""))
})
DescribeTable("rejects an unusable IOKit address", func(hardware net.HardwareAddr) {
address, err := macAddressWithHardwareLookup(networkInterface, func(string) (net.HardwareAddr, error) {
return hardware, nil
})
Expect(address.address).To(BeEmpty())
Expect(err).To(MatchError(ContainSubstring("IOKit returned no usable hardware address")))
},
Entry("missing", nil),
Entry("wrong length", net.HardwareAddr{0xaa, 0xbb}),
Entry("zero", net.HardwareAddr{0, 0, 0, 0, 0, 0}),
Entry("redacted", net.HardwareAddr{0x02, 0, 0, 0, 0, 0}),
Entry("broadcast", net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}),
Entry("multicast", net.HardwareAddr{0x01, 0, 0x5e, 0, 0, 1}),
)
})
var _ = Describe("IOKit hardware address lookup", func() {
const (
dictionary = uintptr(1)
service = uint32(2)
key = uintptr(3)
property = uintptr(4)
dataType = uintptr(5)
)
var (
api macAddressAPI
data []byte
released []uintptr
releasedObjects []uint32
)
BeforeEach(func() {
data = []byte{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}
released = nil
releasedObjects = nil
api = macAddressAPI{
matching: func(port, options uint32, name string) uintptr {
Expect(port).To(BeZero())
Expect(options).To(BeZero())
Expect(name).To(Equal("en4"))
return dictionary
},
service: func(port uint32, matching uintptr) uint32 {
Expect(port).To(BeZero())
Expect(matching).To(Equal(dictionary))
return service
},
searchProperty: func(object uint32, plane string, propertyKey, allocator uintptr, options uint32) uintptr {
Expect(object).To(Equal(service))
Expect(plane).To(Equal("IOService"))
Expect(propertyKey).To(Equal(key))
Expect(allocator).To(BeZero())
Expect(options).To(Equal(uint32(3)))
return property
},
releaseObject: func(object uint32) int32 {
releasedObjects = append(releasedObjects, object)
return 0
},
createString: func(allocator uintptr, value string, encoding uint32) uintptr {
Expect(allocator).To(BeZero())
Expect(value).To(Equal("IOMACAddress"))
Expect(encoding).To(Equal(uint32(0x08000100)))
return key
},
release: func(object uintptr) {
released = append(released, object)
if object == property {
clear(data)
}
},
typeID: func(object uintptr) uintptr {
Expect(object).To(Equal(property))
return dataType
},
dataTypeID: func() uintptr { return dataType },
dataLength: func(object uintptr) int64 {
Expect(object).To(Equal(property))
return int64(len(data))
},
dataBytes: func(object uintptr) unsafe.Pointer {
Expect(object).To(Equal(property))
return unsafe.Pointer(&data[0])
},
}
})
It("copies the address before releasing the property, key, and interface", func() {
address, err := readHardwareMacAddress("en4", api)
Expect(err).ToNot(HaveOccurred())
Expect(address.String()).To(Equal("aa:bb:cc:dd:ee:ff"))
Expect(released).To(Equal([]uintptr{property, key}))
Expect(releasedObjects).To(Equal([]uint32{service}))
})
It("handles a missing matching dictionary", func() {
api.matching = func(uint32, uint32, string) uintptr { return 0 }
_, err := readHardwareMacAddress("en4", api)
Expect(err).To(MatchError("could not create interface matching dictionary"))
Expect(released).To(BeEmpty())
Expect(releasedObjects).To(BeEmpty())
})
It("handles a missing interface without releasing the consumed dictionary twice", func() {
api.service = func(uint32, uintptr) uint32 { return 0 }
_, err := readHardwareMacAddress("en4", api)
Expect(err).To(MatchError("network interface was not found in IOKit"))
Expect(released).To(BeEmpty())
Expect(releasedObjects).To(BeEmpty())
})
It("releases the interface when the property key cannot be created", func() {
api.createString = func(uintptr, string, uint32) uintptr { return 0 }
_, err := readHardwareMacAddress("en4", api)
Expect(err).To(MatchError("could not create hardware address property key"))
Expect(released).To(BeEmpty())
Expect(releasedObjects).To(Equal([]uint32{service}))
})
It("releases the interface and key when the property is missing", func() {
api.searchProperty = func(uint32, string, uintptr, uintptr, uint32) uintptr { return 0 }
_, err := readHardwareMacAddress("en4", api)
Expect(err).To(MatchError("hardware address property was not found in IOKit"))
Expect(released).To(Equal([]uintptr{key}))
Expect(releasedObjects).To(Equal([]uint32{service}))
})
It("rejects a non-data property without accessing its bytes", func() {
api.typeID = func(uintptr) uintptr { return dataType + 1 }
api.dataLength = nil
api.dataBytes = nil
_, err := readHardwareMacAddress("en4", api)
Expect(err).To(MatchError("IOKit hardware address must contain six bytes"))
Expect(released).To(Equal([]uintptr{property, key}))
Expect(releasedObjects).To(Equal([]uint32{service}))
})
It("rejects an unexpected length without accessing the bytes", func() {
api.dataLength = func(uintptr) int64 { return 8 }
api.dataBytes = nil
_, err := readHardwareMacAddress("en4", api)
Expect(err).To(MatchError("IOKit hardware address must contain six bytes"))
Expect(released).To(Equal([]uintptr{property, key}))
Expect(releasedObjects).To(Equal([]uint32{service}))
})
It("handles missing data without dereferencing a null pointer", func() {
api.dataBytes = func(uintptr) unsafe.Pointer { return nil }
_, err := readHardwareMacAddress("en4", api)
Expect(err).To(MatchError("IOKit hardware address data is missing"))
Expect(released).To(Equal([]uintptr{property, key}))
Expect(releasedObjects).To(Equal([]uint32{service}))
})
})
+9
View File
@@ -0,0 +1,9 @@
//go:build (!darwin && !linux && !windows) || ios
package machine
import "net"
func interfaceMacAddress(networkInterface net.Interface) (macAddressCandidate, error) {
return macAddressCandidate{address: networkInterface.HardwareAddr, priority: macPriorityFallback}, nil
}
+22
View File
@@ -0,0 +1,22 @@
package machine
import (
"net"
"os"
"path/filepath"
)
func interfaceMacAddress(networkInterface net.Interface) (macAddressCandidate, error) {
return macAddressWithSysfs(networkInterface, "/sys/class/net"), nil
}
func macAddressWithSysfs(networkInterface net.Interface, root string) macAddressCandidate {
candidate := macAddressCandidate{address: networkInterface.HardwareAddr, priority: macPriorityFallback}
// Physical adapters have a backing device in sysfs. Keep a fallback for
// containers and systems where sysfs is unavailable.
if _, err := os.Stat(filepath.Join(root, networkInterface.Name, "device")); err == nil {
candidate.priority = macPriorityPhysical
}
return candidate
}
@@ -0,0 +1,24 @@
package machine
import (
"net"
"os"
"path/filepath"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Linux hardware address", func() {
It("prefers a sysfs backing device and preserves virtual adapters as fallbacks", func() {
root := GinkgoT().TempDir()
Expect(os.MkdirAll(filepath.Join(root, "eth0", "device"), 0o755)).To(Succeed())
Expect(os.MkdirAll(filepath.Join(root, "veth0"), 0o755)).To(Succeed())
for name, priority := range map[string]int{"eth0": macPriorityPhysical, "veth0": macPriorityFallback, "missing": macPriorityFallback} {
networkInterface := net.Interface{Name: name, HardwareAddr: net.HardwareAddr{2, 1, 2, 3, 4, 5}}
candidate := macAddressWithSysfs(networkInterface, root)
Expect(candidate.priority).To(Equal(priority))
Expect(candidate.address).To(Equal(networkInterface.HardwareAddr))
}
})
})
+142
View File
@@ -0,0 +1,142 @@
package machine
import (
"errors"
"net"
"slices"
"sync"
"sync/atomic"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Machine address selection", func() {
DescribeTable("validates hardware addresses", func(address net.HardwareAddr, valid bool) {
Expect(usableMacAddress(address)).To(Equal(valid))
},
Entry("missing", nil, false),
Entry("short", net.HardwareAddr{0, 1}, false),
Entry("EUI-64", net.HardwareAddr{0, 1, 2, 3, 4, 5, 6, 7}, false),
Entry("zero", net.HardwareAddr{0, 0, 0, 0, 0, 0}, false),
Entry("redacted", net.HardwareAddr{2, 0, 0, 0, 0, 0}, false),
Entry("broadcast", net.HardwareAddr{255, 255, 255, 255, 255, 255}, false),
Entry("multicast", net.HardwareAddr{1, 0, 0x5e, 0, 0, 1}, false),
Entry("unicast", net.HardwareAddr{0, 1, 2, 3, 4, 5}, true),
Entry("locally administered", net.HardwareAddr{2, 1, 2, 3, 4, 5}, true),
)
It("prefers physical adapters regardless of enumeration order, index or link state", func() {
interfaces := []net.Interface{
{Name: "virtual", Index: 1, Flags: net.FlagUp, HardwareAddr: net.HardwareAddr{0, 0, 0, 0, 0, 1}},
{Name: "wired", Index: 20, HardwareAddr: net.HardwareAddr{0, 0, 0, 0, 0, 3}},
{Name: "wireless", Index: 10, Flags: net.FlagUp, HardwareAddr: net.HardwareAddr{0, 0, 0, 0, 0, 2}},
}
lookup := func(networkInterface net.Interface) (macAddressCandidate, error) {
priority := macPriorityPhysical
if networkInterface.Name == "virtual" {
priority = macPriorityFallback
}
return macAddressCandidate{address: networkInterface.HardwareAddr, priority: priority}, nil
}
for range 3 {
for _, reversed := range []bool{false, true} {
input := slices.Clone(interfaces)
if reversed {
slices.Reverse(input)
}
address, err := selectMacAddress(input, lookup)
Expect(err).NotTo(HaveOccurred())
Expect(address).To(Equal("00:00:00:00:00:02"))
}
interfaces = append(interfaces[1:], interfaces[0])
for i := range interfaces {
interfaces[i].Index += 100
interfaces[i].Flags ^= net.FlagUp
}
}
})
It("prefers a primary hardware interface over other physical adapters", func() {
interfaces := []net.Interface{{Name: "other"}, {Name: "primary"}}
address, err := selectMacAddress(interfaces, func(networkInterface net.Interface) (macAddressCandidate, error) {
if networkInterface.Name == "primary" {
return macAddressCandidate{address: net.HardwareAddr{0, 0, 0, 0, 0, 2}, priority: macPriorityPrimary}, nil
}
return macAddressCandidate{address: net.HardwareAddr{0, 0, 0, 0, 0, 1}, priority: macPriorityPhysical}, nil
})
Expect(err).NotTo(HaveOccurred())
Expect(address).To(Equal("00:00:00:00:00:02"))
})
It("skips loopback, tunnels, failed lookups and unusable addresses before using a fallback", func() {
interfaces := []net.Interface{
{Name: "loopback", Flags: net.FlagLoopback},
{Name: "tunnel", Flags: net.FlagPointToPoint},
{Name: "unavailable"},
{Name: "redacted", HardwareAddr: net.HardwareAddr{2, 0, 0, 0, 0, 0}},
{Name: "virtual", HardwareAddr: net.HardwareAddr{2, 1, 2, 3, 4, 5}},
}
address, err := selectMacAddress(interfaces, func(networkInterface net.Interface) (macAddressCandidate, error) {
Expect(networkInterface.Flags & (net.FlagLoopback | net.FlagPointToPoint)).To(BeZero())
if networkInterface.Name == "unavailable" {
return macAddressCandidate{}, errors.New("hardware lookup failed")
}
return macAddressCandidate{address: networkInterface.HardwareAddr, priority: macPriorityFallback}, nil
})
Expect(err).NotTo(HaveOccurred())
Expect(address).To(Equal("02:01:02:03:04:05"))
})
It("reports missing usable addresses without wrapping a nil error", func() {
address, err := selectMacAddress(nil, nil)
Expect(address).To(BeEmpty())
Expect(err).To(MatchError("could not find network interfaces with a valid mac address"))
})
It("retains lookup failures if no usable adapter remains", func() {
lookupErr := errors.New("hardware unavailable")
address, err := selectMacAddress([]net.Interface{{Name: "en0"}}, func(net.Interface) (macAddressCandidate, error) {
return macAddressCandidate{}, lookupErr
})
Expect(address).To(BeEmpty())
Expect(errors.Is(err, lookupErr)).To(BeTrue())
})
It("keeps one identity across concurrent calls and subsequent interface changes", func() {
var calls atomic.Int32
sut := &machine{interfaces: func() ([]net.Interface, error) {
last := byte(calls.Add(1))
return []net.Interface{{Index: 2147483647, Name: "ipatool-test", HardwareAddr: net.HardwareAddr{2, 1, 2, 3, 4, last}}}, nil
}}
var wg sync.WaitGroup
for range 8 {
wg.Add(1)
go func() {
defer wg.Done()
defer GinkgoRecover()
address, err := sut.MacAddress()
Expect(err).NotTo(HaveOccurred())
Expect(address).To(Equal("02:01:02:03:04:01"))
}()
}
wg.Wait()
address, err := sut.MacAddress()
Expect(err).NotTo(HaveOccurred())
Expect(address).To(Equal("02:01:02:03:04:01"))
Expect(calls.Load()).To(Equal(int32(1)))
})
It("preserves interface enumeration errors", func() {
lookupErr := errors.New("interfaces unavailable")
sut := &machine{interfaces: func() ([]net.Interface, error) { return nil, lookupErr }}
address, err := sut.MacAddress()
Expect(address).To(BeEmpty())
Expect(errors.Is(err, lookupErr)).To(BeTrue())
Expect(err.Error()).To(HavePrefix("failed to get network interfaces:"))
})
})
+55
View File
@@ -0,0 +1,55 @@
package machine
import (
"net"
"golang.org/x/sys/windows"
)
var getIfEntry2Ex = windows.NewLazySystemDLL("iphlpapi.dll").NewProc("GetIfEntry2Ex")
func interfaceMacAddress(networkInterface net.Interface) (macAddressCandidate, error) {
// Older Windows 10 builds lack this entry point. Metadata is optional;
// preserve the validated network address as a fallback on those systems.
fallback := macAddressCandidate{address: networkInterface.HardwareAddr, priority: macPriorityFallback}
if err := getIfEntry2Ex.Find(); err != nil {
return fallback, nil
}
row := windows.MibIfRow2{InterfaceIndex: uint32(networkInterface.Index)}
if err := windows.GetIfEntry2Ex(windows.MibIfTableNormalWithoutStatistics, &row); err != nil {
return fallback, nil
}
return macAddressFromWindowsRow(row), nil
}
func macAddressFromWindowsRow(row windows.MibIfRow2) macAddressCandidate {
candidate := macAddressCandidate{priority: macPriorityFallback}
if row.PhysicalAddressLength != 6 {
return candidate
}
candidate.address = append(net.HardwareAddr(nil), row.PhysicalAddress[:6]...)
// Use the permanent address so Wi-Fi randomization does not change the
// identity. Virtual adapters remain available as a lower-priority fallback.
if usableMacAddress(row.PermanentPhysicalAddress[:6]) {
candidate.address = append(net.HardwareAddr(nil), row.PermanentPhysicalAddress[:6]...)
}
// MIB_IF_ROW2's first two status bits are HardwareInterface and
// FilterInterface. Bluetooth PAN can otherwise look like Ethernet.
const (
hardwareInterface = 1
filterInterface = 2
bluetoothMedium = 10
)
if row.InterfaceAndOperStatusFlags&(hardwareInterface|filterInterface) == hardwareInterface &&
row.PhysicalMediumType != bluetoothMedium &&
(row.Type == windows.IF_TYPE_ETHERNET_CSMACD || row.Type == windows.IF_TYPE_IEEE80211) {
candidate.priority = macPriorityPhysical
}
return candidate
}
@@ -0,0 +1,57 @@
package machine
import (
"net"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"golang.org/x/sys/windows"
)
var _ = Describe("Windows hardware address", func() {
var row windows.MibIfRow2
BeforeEach(func() {
row = windows.MibIfRow2{
PhysicalAddressLength: 6,
Type: windows.IF_TYPE_ETHERNET_CSMACD,
InterfaceAndOperStatusFlags: 1,
}
copy(row.PhysicalAddress[:], []byte{2, 1, 2, 3, 4, 5})
copy(row.PermanentPhysicalAddress[:], []byte{0, 1, 2, 3, 4, 5})
})
It("uses a physical adapter's permanent address regardless of connection state", func() {
for _, state := range []uint32{windows.IfOperStatusUp, windows.IfOperStatusDown} {
row.OperStatus = state
candidate := macAddressFromWindowsRow(row)
Expect(candidate.address.String()).To(Equal("00:01:02:03:04:05"))
Expect(candidate.priority).To(Equal(macPriorityPhysical))
}
})
It("uses the current address when the permanent address is unavailable", func() {
clear(row.PermanentPhysicalAddress[:])
candidate := macAddressFromWindowsRow(row)
Expect(candidate.address).To(Equal(net.HardwareAddr{2, 1, 2, 3, 4, 5}))
Expect(candidate.priority).To(Equal(macPriorityPhysical))
})
DescribeTable("classifies adapters", func(flags uint8, interfaceType, medium uint32, priority int) {
row.InterfaceAndOperStatusFlags = flags
row.Type = interfaceType
row.PhysicalMediumType = medium
Expect(macAddressFromWindowsRow(row).priority).To(Equal(priority))
},
Entry("Wi-Fi hardware", uint8(1), uint32(windows.IF_TYPE_IEEE80211), uint32(9), macPriorityPhysical),
Entry("virtual Ethernet", uint8(0), uint32(windows.IF_TYPE_ETHERNET_CSMACD), uint32(0), macPriorityFallback),
Entry("filter", uint8(3), uint32(windows.IF_TYPE_ETHERNET_CSMACD), uint32(0), macPriorityFallback),
Entry("Bluetooth PAN", uint8(1), uint32(windows.IF_TYPE_ETHERNET_CSMACD), uint32(10), macPriorityFallback),
Entry("tunnel", uint8(1), uint32(windows.IF_TYPE_TUNNEL), uint32(0), macPriorityFallback),
)
DescribeTable("rejects non-Ethernet address lengths without slicing past the buffer", func(length uint32) {
row.PhysicalAddressLength = length
Expect(macAddressFromWindowsRow(row).address).To(BeEmpty())
}, Entry("empty", uint32(0)), Entry("EUI-64", uint32(8)), Entry("oversized", uint32(100)))
})
+20 -17
View File
@@ -5,6 +5,7 @@ import (
"net"
"path/filepath"
"runtime"
"sync"
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
"golang.org/x/term"
@@ -18,7 +19,11 @@ type Machine interface {
}
type machine struct {
os operatingsystem.OperatingSystem
os operatingsystem.OperatingSystem
interfaces func() ([]net.Interface, error)
macAddressOnce sync.Once
macAddress string
macAddressErr error
}
type Args struct {
@@ -27,28 +32,26 @@ type Args struct {
func New(args Args) Machine {
return &machine{
os: args.OS,
os: args.OS,
interfaces: net.Interfaces,
}
}
func (*machine) MacAddress() (string, error) {
interfaces, err := net.Interfaces()
if err != nil {
return "", fmt.Errorf("failed to get network interfaces: %w", err)
}
// Resolve once so bag requests, authentication and downloads use the same
// identity even if an adapter is added or removed during this invocation.
func (m *machine) MacAddress() (string, error) {
m.macAddressOnce.Do(func() {
interfaces, err := m.interfaces()
if err != nil {
m.macAddressErr = fmt.Errorf("failed to get network interfaces: %w", err)
if len(interfaces) == 0 {
return "", fmt.Errorf("could not find network interfaces: %w", err)
}
for _, netInterface := range interfaces {
addr := netInterface.HardwareAddr.String()
if addr != "" {
return addr, nil
return
}
}
return "", fmt.Errorf("could not find network interfaces with a valid mac address: %w", err)
m.macAddress, m.macAddressErr = selectMacAddress(interfaces, interfaceMacAddress)
})
return m.macAddress, m.macAddressErr
}
func (m *machine) HomeDirectory() string {
+5 -1
View File
@@ -53,10 +53,14 @@ var _ = Describe("Machine", func() {
})
When("machine has network interfaces", func() {
It("returns MAC address of the first interface", func() {
It("returns a usable MAC address", func() {
res, err := machine.MacAddress()
Expect(err).ToNot(HaveOccurred())
Expect(res).To(ContainSubstring(":"))
if runtime.GOOS == "darwin" {
Expect(res).ToNot(Equal("02:00:00:00:00:00"))
}
})
})