From 83ba72ddc60916d2aa56932a3b47991f7b885a3d Mon Sep 17 00:00:00 2001 From: Paulo Castellano Date: Fri, 3 Jul 2026 11:07:54 -0300 Subject: [PATCH] Stop Meta rate-limit errors from disconnecting Instagram/Threads tokens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TokenRefreshClient classified every non-5xx/429 refresh failure as a dead token. Meta returns rate-limit (code 4/17) and transient (code 1/2) errors as HTTP 4xx with type OAuthException, so a throttled proactive refresh was disconnecting still-valid Instagram/Threads tokens — and the wider 24h/15-min refresh cadence raised the odds of hitting it. Classification now keys on error code 190 (the signal the publish exceptions already use): only a genuine 190 disconnects; every other Meta 4xx is treated as transient (PlatformUnavailable) and retried next cycle. The same over-broad type-based check in verifyInstagram/verifyFacebook/verifyThreads is replaced with the shared Meta\GraphError helper so verify and refresh agree. --- app/Services/Social/ConnectionVerifier.php | 54 +++++++--------- app/Services/Social/Meta/GraphError.php | 30 +++++++++ app/Services/Social/TokenRefreshClient.php | 24 +++++-- tests/Feature/Jobs/RefreshSocialTokenTest.php | 22 +++++++ .../Social/ConnectionVerifierTest.php | 62 +++++++++++++++++++ .../Services/Social/Meta/GraphErrorTest.php | 35 +++++++++++ 6 files changed, 192 insertions(+), 35 deletions(-) create mode 100644 app/Services/Social/Meta/GraphError.php create mode 100644 tests/Unit/Services/Social/Meta/GraphErrorTest.php diff --git a/app/Services/Social/ConnectionVerifier.php b/app/Services/Social/ConnectionVerifier.php index 60513199..b795eed0 100644 --- a/app/Services/Social/ConnectionVerifier.php +++ b/app/Services/Social/ConnectionVerifier.php @@ -9,6 +9,7 @@ use App\Exceptions\TokenExpiredException; use App\Models\SocialAccount; use App\Services\Social\Discord\DiscordClient; +use App\Services\Social\Meta\GraphError; use App\Services\Social\Telegram\TelegramApi; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; @@ -311,10 +312,13 @@ private function refreshPinterestToken(SocialAccount $account): void private function refreshThreadsToken(SocialAccount $account): void { // Threads uses long-lived tokens that can be refreshed - $response = TokenRefreshClient::for(Platform::Threads)->send(fn () => Http::get(config('trypost.platforms.threads.auth_api').'/refresh_access_token', [ - 'grant_type' => 'th_refresh_token', - 'access_token' => $account->access_token, - ])); + $response = TokenRefreshClient::for(Platform::Threads)->send( + fn () => Http::get(config('trypost.platforms.threads.auth_api').'/refresh_access_token', [ + 'grant_type' => 'th_refresh_token', + 'access_token' => $account->access_token, + ]), + GraphError::indicatesInvalidToken(...), + ); $data = $response->json(); $newToken = data_get($data, 'access_token'); @@ -322,7 +326,7 @@ private function refreshThreadsToken(SocialAccount $account): void $account->update([ 'access_token' => $newToken, 'refresh_token' => $newToken, - 'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', 5184000)), + 'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', Platform::LONG_LIVED_TOKEN_TTL_SECONDS)), ]); $account->refresh(); @@ -330,10 +334,13 @@ private function refreshThreadsToken(SocialAccount $account): void private function refreshInstagramToken(SocialAccount $account): void { - $response = TokenRefreshClient::for(Platform::Instagram)->send(fn () => Http::get(config('trypost.platforms.instagram.auth_api').'/refresh_access_token', [ - 'grant_type' => 'ig_refresh_token', - 'access_token' => $account->access_token, - ])); + $response = TokenRefreshClient::for(Platform::Instagram)->send( + fn () => Http::get(config('trypost.platforms.instagram.auth_api').'/refresh_access_token', [ + 'grant_type' => 'ig_refresh_token', + 'access_token' => $account->access_token, + ]), + GraphError::indicatesInvalidToken(...), + ); $data = $response->json(); $newToken = data_get($data, 'access_token'); @@ -341,7 +348,7 @@ private function refreshInstagramToken(SocialAccount $account): void $account->update([ 'access_token' => $newToken, 'refresh_token' => $newToken, - 'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', 5184000)), + 'token_expires_at' => now()->addSeconds(data_get($data, 'expires_in', Platform::LONG_LIVED_TOKEN_TTL_SECONDS)), ]); $account->refresh(); @@ -408,13 +415,8 @@ private function verifyInstagram(SocialAccount $account): bool $body = $response->json() ?? []; - if (isset($body['error'])) { - $errorCode = $body['error']['code'] ?? null; - $errorType = $body['error']['type'] ?? null; - - if ($errorType === 'OAuthException' || $errorCode === 190) { - throw new TokenExpiredException('Instagram access token is invalid or expired'); - } + if (GraphError::indicatesInvalidToken($body)) { + throw new TokenExpiredException('Instagram access token is invalid or expired'); } return $response->successful(); @@ -429,13 +431,8 @@ private function verifyFacebook(SocialAccount $account): bool $body = $response->json() ?? []; - if (isset($body['error'])) { - $errorCode = $body['error']['code'] ?? null; - $errorType = $body['error']['type'] ?? null; - - if ($errorType === 'OAuthException' || $errorCode === 190) { - throw new TokenExpiredException('Facebook access token is invalid or expired'); - } + if (GraphError::indicatesInvalidToken($body)) { + throw new TokenExpiredException('Facebook access token is invalid or expired'); } return $response->successful(); @@ -450,13 +447,8 @@ private function verifyThreads(SocialAccount $account): bool $body = $response->json() ?? []; - if (isset($body['error'])) { - $errorCode = $body['error']['code'] ?? null; - $errorType = $body['error']['type'] ?? null; - - if ($errorType === 'OAuthException' || $errorCode === 190) { - throw new TokenExpiredException('Threads access token is invalid or expired'); - } + if (GraphError::indicatesInvalidToken($body)) { + throw new TokenExpiredException('Threads access token is invalid or expired'); } return $response->successful(); diff --git a/app/Services/Social/Meta/GraphError.php b/app/Services/Social/Meta/GraphError.php new file mode 100644 index 00000000..e0097e5b --- /dev/null +++ b/app/Services/Social/Meta/GraphError.php @@ -0,0 +1,30 @@ +|null $body + */ + public static function indicatesInvalidToken(?array $body): bool + { + return data_get($body, 'error.code') === 190; + } +} diff --git a/app/Services/Social/TokenRefreshClient.php b/app/Services/Social/TokenRefreshClient.php index 70b023e2..d20839e4 100644 --- a/app/Services/Social/TokenRefreshClient.php +++ b/app/Services/Social/TokenRefreshClient.php @@ -16,13 +16,18 @@ * Normalizes the failure modes of an OAuth token-refresh request: * * - ConnectionException (timeout / DNS / refused) → PlatformUnavailableException - * - HTTP 5xx → PlatformUnavailableException - * - HTTP 4xx → TokenExpiredException + * - HTTP 5xx or 429 → PlatformUnavailableException + * - other HTTP 4xx → TokenExpiredException + * + * Providers that return rate-limit or transient errors as an ordinary 4xx + * (Meta: Instagram/Threads) can pass an `$isTokenInvalid` classifier to + * `send()`; only a genuinely dead token then disconnects, while every other + * 4xx is treated as transient (PlatformUnavailableException). * * Callers configure the actual HTTP call through the closure passed to * `send()`, so platform-specific quirks (form vs JSON body, auth headers, * basic auth, etc.) stay where they belong — in the per-platform refresh - * method — while the failure semantics are uniform across providers. + * method. */ class TokenRefreshClient { @@ -35,11 +40,14 @@ public static function for(Platform $platform): self /** * @param Closure():Response $request + * @param (Closure(array|null):bool)|null $isTokenInvalid Given the parsed + * response body, returns whether a non-5xx/429 failure means the token itself is dead. + * When it returns false, the failure is treated as transient (PlatformUnavailableException). * * @throws PlatformUnavailableException * @throws TokenExpiredException */ - public function send(Closure $request): Response + public function send(Closure $request, ?Closure $isTokenInvalid = null): Response { $name = $this->platform->label(); @@ -62,6 +70,14 @@ public function send(Closure $request): Response ]); $body = $response->json(); + + if ($isTokenInvalid !== null && ! $isTokenInvalid($body)) { + throw new PlatformUnavailableException( + "{$name} API returned {$response->status()} during token refresh", + $response->status(), + ); + } + $message = data_get($body, 'error_description') ?? data_get($body, 'error.message') ?? "Failed to refresh {$name} token"; diff --git a/tests/Feature/Jobs/RefreshSocialTokenTest.php b/tests/Feature/Jobs/RefreshSocialTokenTest.php index bf9d0269..898950c3 100644 --- a/tests/Feature/Jobs/RefreshSocialTokenTest.php +++ b/tests/Feature/Jobs/RefreshSocialTokenTest.php @@ -107,6 +107,28 @@ expect($account->fresh()->access_token)->toBe('extended-threads-token'); }); +test('proactive refresh does NOT disconnect Instagram on a Meta rate-limit (400 OAuthException code 4)', function () { + $account = SocialAccount::factory()->create([ + 'workspace_id' => $this->workspace->id, + 'platform' => Platform::Instagram, + 'status' => Status::Connected, + 'access_token' => 'valid-ig-token', + 'token_expires_at' => now()->addMinutes(20), + ]); + + Http::fake([ + config('trypost.platforms.instagram.auth_api').'/refresh_access_token*' => Http::response([ + 'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4], + ], 400), + ]); + + (new RefreshSocialToken($account))->handle(app(ConnectionVerifier::class)); + + // A rate-limit is transient — the still-valid token must stay Connected. + expect($account->fresh()->status)->toBe(Status::Connected); + expect($account->fresh()->access_token)->toBe('valid-ig-token'); +}); + test('refresh job marks account as TokenExpired when refresh_token is rejected', function () { Queue::fake(); diff --git a/tests/Feature/Services/Social/ConnectionVerifierTest.php b/tests/Feature/Services/Social/ConnectionVerifierTest.php index e5472b44..29a38b99 100644 --- a/tests/Feature/Services/Social/ConnectionVerifierTest.php +++ b/tests/Feature/Services/Social/ConnectionVerifierTest.php @@ -561,3 +561,65 @@ expect((new ConnectionVerifier)->verify($account))->toBeFalse(); }); + +test('instagram refresh treats a Meta rate-limit (400 OAuthException code 4) as transient, not a dead token', function () { + Http::fake([ + config('trypost.platforms.instagram.auth_api').'/refresh_access_token*' => Http::response([ + 'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4], + ], 400), + ]); + + $account = SocialAccount::factory()->instagram()->create([ + 'token_expires_at' => now()->subHour(), + ]); + + expect(fn () => (new ConnectionVerifier)->refreshToken($account)) + ->toThrow(PlatformUnavailableException::class); +}); + +test('threads refresh treats a Meta rate-limit (400 OAuthException code 17) as transient, not a dead token', function () { + Http::fake([ + config('trypost.platforms.threads.auth_api').'/refresh_access_token*' => Http::response([ + 'error' => ['message' => 'User request limit reached', 'type' => 'OAuthException', 'code' => 17], + ], 400), + ]); + + $account = SocialAccount::factory()->threads()->create([ + 'token_expires_at' => now()->subHour(), + ]); + + expect(fn () => (new ConnectionVerifier)->refreshToken($account)) + ->toThrow(PlatformUnavailableException::class); +}); + +test('instagram refresh treats code 190 as a genuinely expired token', function () { + Http::fake([ + config('trypost.platforms.instagram.auth_api').'/refresh_access_token*' => Http::response([ + 'error' => ['message' => 'Access token has expired', 'type' => 'OAuthException', 'code' => 190], + ], 400), + ]); + + $account = SocialAccount::factory()->instagram()->create([ + 'token_expires_at' => now()->subHour(), + ]); + + expect(fn () => (new ConnectionVerifier)->refreshToken($account)) + ->toThrow(TokenExpiredException::class); +}); + +test('instagram verify treats a Meta rate-limit (OAuthException code 4) as still-valid, not a disconnect', function () { + Http::fake([ + config('trypost.platforms.instagram.graph_api').'/me*' => Http::response([ + 'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4], + ], 400), + ]); + + // Not expired, so verify hits the endpoint directly (no refresh). + $account = SocialAccount::factory()->instagram()->create([ + 'token_expires_at' => now()->addDays(30), + ]); + + // A rate-limit must NOT raise TokenExpiredException (which would disconnect); + // verify returns false and the caller leaves the account connected. + expect((new ConnectionVerifier)->verify($account))->toBeFalse(); +}); diff --git a/tests/Unit/Services/Social/Meta/GraphErrorTest.php b/tests/Unit/Services/Social/Meta/GraphErrorTest.php new file mode 100644 index 00000000..f1d79931 --- /dev/null +++ b/tests/Unit/Services/Social/Meta/GraphErrorTest.php @@ -0,0 +1,35 @@ + ['message' => 'Access token has expired', 'type' => 'OAuthException', 'code' => 190], + ]))->toBeTrue(); +}); + +test('rate-limit codes carried as OAuthException do NOT indicate an invalid token', function () { + // Meta returns rate limits as HTTP 4xx with type OAuthException — they must + // stay transient so a throttle never disconnects a still-valid token. + expect(GraphError::indicatesInvalidToken([ + 'error' => ['message' => 'Application request limit reached', 'type' => 'OAuthException', 'code' => 4], + ]))->toBeFalse(); + + expect(GraphError::indicatesInvalidToken([ + 'error' => ['message' => 'User request limit reached', 'type' => 'OAuthException', 'code' => 17], + ]))->toBeFalse(); +}); + +test('transient codes do NOT indicate an invalid token', function () { + expect(GraphError::indicatesInvalidToken([ + 'error' => ['message' => 'Service temporarily unavailable', 'code' => 2], + ]))->toBeFalse(); +}); + +test('a body with no error, or a null body, does not indicate an invalid token', function () { + expect(GraphError::indicatesInvalidToken(null))->toBeFalse(); + expect(GraphError::indicatesInvalidToken([]))->toBeFalse(); + expect(GraphError::indicatesInvalidToken(['data' => ['id' => '123']]))->toBeFalse(); +});