Compare commits

...
2 Commits
Author SHA1 Message Date
Majd Alfhailyandhorskin ab79e429d5 fix: fall back to legacy Store authentication (#514)
* fix: fall back to legacy Store authentication

* style: satisfy lint checks

---------

Co-authored-by: horskin <pkh_horskin@photons.com.tw>
2026-08-03 09:58:15 +02:00
dependabot[bot] 9032d4c192 Bump golang.org/x/crypto from 0.51.0 to 0.52.0 (#509)
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.51.0 to 0.52.0.
- [Commits](https://github.com/golang/crypto/compare/v0.51.0...v0.52.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.52.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-10 23:08:22 +02:00
6 changed files with 129 additions and 15 deletions

No files matched your search

+1 -1
View File
@@ -49,7 +49,7 @@ require (
github.com/uber/jaeger-lib v2.4.1+incompatible // indirect
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/crypto v0.51.0 // indirect
golang.org/x/crypto v0.52.0 // indirect
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
+2 -2
View File
@@ -121,8 +121,8 @@ go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
+32 -1
View File
@@ -16,6 +16,8 @@ var (
ErrAuthCodeRequired = errors.New("auth code is required")
)
const legacyAuthenticateEndpoint = "https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/authenticate"
type LoginInput struct {
Email string
Password string
@@ -74,11 +76,22 @@ func (t *appstore) login(email, password, authCode, guid, endpoint string) (Acco
retry := true
for attempt := 1; retry && attempt <= 4; attempt++ {
request := t.loginRequest(email, password, authCode, guid, endpoint, 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)
request.URL, _ = util.IfEmpty(redirect, request.URL), ""
res, err = t.loginClient.Send(request)
if err != nil {
if shouldRetryWithLegacyAuthenticate(endpoint, err) {
return t.login(email, password, authCode, guid, legacyAuthenticateEndpoint)
}
return Account{}, fmt.Errorf("request failed: %w", err)
}
@@ -125,6 +138,24 @@ func (t *appstore) login(email, password, authCode, guid, endpoint string) (Acco
return acc, nil
}
func shouldRetryWithLegacyAuthenticate(endpoint string, err error) bool {
if !strings.Contains(endpoint, "/native/") {
return false
}
var responseErr *http.UnexpectedResponseError
if !errors.As(err, &responseErr) {
return false
}
switch responseErr.StatusCode {
case gohttp.StatusNoContent, gohttp.StatusForbidden, gohttp.StatusNotFound, gohttp.StatusServiceUnavailable:
return true
default:
return false
}
}
func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int, authCode string) (bool, string, error) {
var (
retry bool
+43 -2
View File
@@ -103,6 +103,47 @@ var _ = Describe("AppStore (Login)", func() {
})
})
When("native authentication returns an empty response", func() {
const podURL = "https://p7-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/authenticate?Pod=7&PRH=7"
BeforeEach(func() {
native := mockClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
Expect(req.URL).To(Equal("https://auth.itunes.apple.com/auth/v1/native/fast/"))
}).
Return(http.Result[loginResult]{}, &http.UnexpectedResponseError{StatusCode: 204})
legacy := mockClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
Expect(req.URL).To(Equal(legacyAuthenticateEndpoint))
payload := req.Payload.(*http.XMLPayload)
Expect(payload.Content).To(HaveKeyWithValue("attempt", "1"))
}).
Return(http.Result[loginResult]{
StatusCode: 302,
Headers: map[string]string{"Location": podURL},
}, nil)
pod := mockClient.EXPECT().
Send(gomock.Any()).
Do(func(req http.Request) {
Expect(req.URL).To(Equal(podURL))
payload := req.Payload.(*http.XMLPayload)
Expect(payload.Content).To(HaveKeyWithValue("attempt", "1"))
}).
Return(http.Result[loginResult]{}, errors.New("stop after pod redirect"))
gomock.InOrder(native, legacy, pod)
})
It("falls back to legacy authentication and reposts the plist to the assigned pod", func() {
_, err := as.Login(LoginInput{
Password: testPassword,
Endpoint: "https://auth.itunes.apple.com/auth/v1/native/fast",
})
Expect(err).To(MatchError("request failed: stop after pod redirect"))
})
})
When("store API returns invalid credentials on first attempt", func() {
BeforeEach(func() {
mockClient.EXPECT().
@@ -205,13 +246,13 @@ var _ = Describe("AppStore (Login)", func() {
Expect(req.URL).To(Equal(testRedirectLocation))
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
x := req.Payload.(*http.XMLPayload)
Expect(x.Content).To(HaveKeyWithValue("attempt", "2"))
Expect(x.Content).To(HaveKeyWithValue("attempt", "1"))
}).
Return(http.Result[loginResult]{}, errors.New("test complete"))
gomock.InOrder(firstCall, secondCall)
})
It("follows the redirect and increments attempt", func() {
It("follows the redirect while preserving the original request body", func() {
_, err := as.Login(LoginInput{
Password: testPassword,
})
+38 -9
View File
@@ -39,6 +39,21 @@ type Args struct {
CookieJar CookieJar
}
// UnexpectedResponseError preserves the HTTP status when Apple returns an
// HTML or empty response where an XML plist was expected.
type UnexpectedResponseError struct {
StatusCode int
Snippet string
}
func (e *UnexpectedResponseError) Error() string {
if e.Snippet == "" {
return fmt.Sprintf("unexpected response from Apple (HTTP %d): empty or non-plist body", e.StatusCode)
}
return fmt.Sprintf("unexpected response from Apple (HTTP %d): %s", e.StatusCode, e.Snippet)
}
type AddHeaderTransport struct {
T http.RoundTripper
}
@@ -165,17 +180,27 @@ func (c *client[R]) handleXMLResponse(res *http.Response) (Result[R], error) {
return Result[R]{}, fmt.Errorf("rate limited by Apple (HTTP %d): %s", res.StatusCode, strings.TrimSpace(string(body)))
}
// The legacy authentication endpoint redirects to an assigned Store pod.
// Preserve the redirect response and its Location header so callers can
// repeat the original POST request at that pod.
if res.StatusCode >= http.StatusMultipleChoices && res.StatusCode < http.StatusBadRequest {
return Result[R]{
StatusCode: res.StatusCode,
Headers: responseHeaders(res),
}, nil
}
var data R
normalizedBody := normalizeXMLPlistBody(body)
if !looksLikePropertyList(normalizedBody) {
snippet := bodySnippet(body)
if snippet == "" {
return Result[R]{}, fmt.Errorf("unexpected response from Apple (HTTP %d): empty or non-plist body", res.StatusCode)
}
return Result[R]{}, fmt.Errorf("unexpected response from Apple (HTTP %d): %s", res.StatusCode, snippet)
return Result[R]{}, &UnexpectedResponseError{
StatusCode: res.StatusCode,
Snippet: snippet,
}
}
_, err = plist.Unmarshal(normalizedBody, &data)
@@ -183,16 +208,20 @@ func (c *client[R]) handleXMLResponse(res *http.Response) (Result[R], error) {
return Result[R]{}, fmt.Errorf("failed to unmarshal xml: %w", err)
}
return Result[R]{
StatusCode: res.StatusCode,
Headers: responseHeaders(res),
Data: data,
}, nil
}
func responseHeaders(res *http.Response) map[string]string {
headers := map[string]string{}
for key, val := range res.Header {
headers[key] = strings.Join(val, "; ")
}
return Result[R]{
StatusCode: res.StatusCode,
Headers: headers,
Data: data,
}, nil
return headers
}
func normalizeXMLPlistBody(body []byte) []byte {
+13
View File
@@ -224,6 +224,19 @@ var _ = Describe("Client", Ordered, func() {
})
})
It("preserves an XML redirect response and its location header", func() {
recorder := httptest.NewRecorder()
recorder.Header().Set("Location", "https://p7-buy.itunes.apple.com/authenticate")
recorder.WriteHeader(http.StatusFound)
sut := &client[xmlResult]{}
res, err := sut.handleXMLResponse(recorder.Result())
Expect(err).ToNot(HaveOccurred())
Expect(res.StatusCode).To(Equal(http.StatusFound))
Expect(res.Headers).To(HaveKeyWithValue("Location", "https://p7-buy.itunes.apple.com/authenticate"))
})
When("payload fails to decode", func() {
It("returns error", func() {
sut := NewClient[xmlResult](Args{