Repository: jchambers/pushy (java)

Issue:
"TooManyProviderTokenUpdates"  received when sent a push notification to apns using .p8
I was using the pushy library.

"TooManyProviderTokenUpdates"  received when sent a push notification to apns using .p8 file.

[https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html#//apple_ref/doc/uid/TP40008194-CH11-SW1]
This document indicates that "TooManyProviderTokenUpdates" means The provider token is being updated too often.

But i am still confused,What does that mean ?
The provider token is being updated by what ?

What's right solution? Any reply is appreciated,Thanks very much.

Pull request description:
Treat token expirations as fatal errors
As a spiritual follow-on to #747, this fixes #568 by simply closing connections when the server thinks tokens have expired.

My best idea right now is that the server simply doesn't let connections use new tokens after one has actually expired and continues to respond to all subsequent notifications with an "expired token" response. If that's the case, our best recourse is to just close the connection and open a new one.

Patch:
diff --git a/pushy/src/main/java/com/eatthepath/pushy/apns/ApnsClientHandler.java b/pushy/src/main/java/com/eatthepath/pushy/apns/ApnsClientHandler.java
index 3767997d..f1a3cafd 100644
--- a/pushy/src/main/java/com/eatthepath/pushy/apns/ApnsClientHandler.java
+++ b/pushy/src/main/java/com/eatthepath/pushy/apns/ApnsClientHandler.java
@@ -180,7 +180,7 @@ class ApnsClientHandler extends Http2ConnectionHandler implements Http2FrameList
         }
     }
 
-    void retryPushNotificationFromStream(final ChannelHandlerContext context, final int streamId) {
+    private void retryPushNotificationFromStream(final ChannelHandlerContext context, final int streamId) {
         final Http2Stream stream = this.connection().stream(streamId);
 
         final PushNotificationFuture<?, ?> responseFuture = stream.removeProperty(this.responsePromisePropertyKey);
diff --git a/pushy/src/main/java/com/eatthepath/pushy/apns/TokenAuthenticationApnsClientHandler.java b/pushy/src/main/java/com/eatthepath/pushy/apns/TokenAuthenticationApnsClientHandler.java
index 783f632b..3f231309 100644
--- a/pushy/src/main/java/com/eatthepath/pushy/apns/TokenAuthenticationApnsClientHandler.java
+++ b/pushy/src/main/java/com/eatthepath/pushy/apns/TokenAuthenticationApnsClientHandler.java
@@ -47,7 +47,6 @@ class TokenAuthenticationApnsClientHandler extends ApnsClientHandler {
     private final ApnsSigningKey signingKey;
 
     private AuthenticationToken authenticationToken;
-    private int mostRecentStreamWithNewToken = 0;
 
     private final Duration tokenExpiration;
     private ScheduledFuture<?> expireTokenFuture;
@@ -109,7 +108,6 @@ class TokenAuthenticationApnsClientHandler extends ApnsClientHandler {
                 log.debug("Generating new token for stream {}.", streamId);
 
                 this.authenticationToken = new AuthenticationToken(signingKey, Instant.now());
-                this.mostRecentStreamWithNewToken = streamId;
 
                 this.expireTokenFuture = context.executor().schedule(() -> {
                     log.debug("Proactively expiring authentication token.");
@@ -129,18 +127,14 @@ class TokenAuthenticationApnsClientHandler extends ApnsClientHandler {
 
     @Override
     protected void handleErrorResponse(final ChannelHandlerContext context, final int streamId, final Http2Headers headers, final ApnsPushNotification pushNotification, final ErrorResponse errorResponse) {
-        if (TokenAuthenticationApnsClientHandler.EXPIRED_AUTH_TOKEN_REASON.equals(errorResponse.getReason())) {
-            log.warn("APNs server reports token has expired.");
+        super.handleErrorResponse(context, streamId, headers, pushNotification, errorResponse);
 
-            if (streamId >= this.mostRecentStreamWithNewToken) {
-                this.authenticationToken = null;
-            }
+        if (EXPIRED_AUTH_TOKEN_REASON.equals(errorResponse.getReason())) {
+            log.warn("APNs server reports token has expired.");
 
-            // Once we've invalidated an expired token, it's reasonable to expect that re-sending the notification might
-            // succeed.
-            this.retryPushNotificationFromStream(context, streamId);
-        } else {
-            super.handleErrorResponse(context, streamId, headers, pushNotification, errorResponse);
+            // Once the server thinks our token has expired, it will "wedge" the connection. There's no way to recover
+            // from this situation, and all we can do is close the connection and create a new one.
+            context.close();
         }
     }
 


Test patch:
diff --git a/pushy/src/test/java/com/eatthepath/pushy/apns/ApnsClientTest.java b/pushy/src/test/java/com/eatthepath/pushy/apns/ApnsClientTest.java
index 8745ffa2..f42143c5 100644
--- a/pushy/src/test/java/com/eatthepath/pushy/apns/ApnsClientTest.java
+++ b/pushy/src/test/java/com/eatthepath/pushy/apns/ApnsClientTest.java
@@ -332,7 +332,9 @@ public class ApnsClientTest extends AbstractClientServerTest {
     @Test
     void testSendNotificationWithExpiredAuthenticationToken() throws Exception {
         final PushNotificationHandlerFactory expireFirstTokenHandlerFactory =
-                sslSession -> new ExpireFirstTokenPushNotificationHandler();
+                sslSession -> (PushNotificationHandler) (headers, payload) -> {
+                    throw new RejectedNotificationException(RejectionReason.EXPIRED_PROVIDER_TOKEN);
+                };
 
         final MockApnsServer server = this.buildServer(expireFirstTokenHandlerFactory);
 
@@ -348,20 +350,8 @@ public class ApnsClientTest extends AbstractClientServerTest {
             final PushNotificationResponse<SimpleApnsPushNotification> response =
                     client.sendNotification(pushNotification).get();
 
-            assertTrue(response.isAccepted(),
-                    "Client should automatically re-send notifications with expired authentication tokens.");
-
-            metricsListener.waitForNonZeroAcceptedNotifications();
-
-            // See https://github.com/jchambers/pushy/issues/448
-            assertEquals(1, metricsListener.getSentNotifications().size(),
-                    "Re-sent notifications with expired tokens must not be double-counted.");
-
-            assertEquals(1, metricsListener.getAcceptedNotifications().size(),
-                    "Re-sent notifications should be counted as accepted exactly once.");
-
-            assertTrue(metricsListener.getRejectedNotifications().isEmpty(),
-                    "Notifications with expired authentication tokens should not count as rejections.");
+            assertFalse(response.isAccepted(),
+                    "Expired token failures should be fatal.");
         } finally {
             client.close().get();
             server.shutdown().get();
diff --git a/pushy/src/test/java/com/eatthepath/pushy/apns/ExpireFirstTokenPushNotificationHandler.java b/pushy/src/test/java/com/eatthepath/pushy/apns/ExpireFirstTokenPushNotificationHandler.java
deleted file mode 100644
index afcabc1b..00000000
--- a/pushy/src/test/java/com/eatthepath/pushy/apns/ExpireFirstTokenPushNotificationHandler.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2020 Jon Chambers
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-
-package com.eatthepath.pushy.apns;
-
-import com.eatthepath.pushy.apns.server.PushNotificationHandler;
-import com.eatthepath.pushy.apns.server.RejectedNotificationException;
-import com.eatthepath.pushy.apns.server.RejectionReason;
-import io.netty.buffer.ByteBuf;
-import io.netty.handler.codec.http2.Http2Headers;
-import io.netty.util.AsciiString;
-
-class ExpireFirstTokenPushNotificationHandler implements PushNotificationHandler {
-
-    private String rejectedAuthorizationHeader;
-
-    private static final AsciiString APNS_AUTHORIZATION_HEADER = new AsciiString("authorization");
-
-    @Override
-    public void handlePushNotification(final Http2Headers headers, final ByteBuf payload) throws RejectedNotificationException {
-        final CharSequence authorizationSequence = headers.get(APNS_AUTHORIZATION_HEADER);
-
-        if (authorizationSequence != null) {
-            final String authorizationHeader = authorizationSequence.toString();
-
-            if (this.rejectedAuthorizationHeader == null) {
-                this.rejectedAuthorizationHeader = authorizationHeader;
-            }
-
-            if (this.rejectedAuthorizationHeader.equals(authorizationHeader)) {
-                throw new RejectedNotificationException(RejectionReason.EXPIRED_PROVIDER_TOKEN);
-            }
-        }
-    }
-}