How to Fix Disk Named `r2` Cannot Be Accessed Error

After a totally random solopreneur style composer update command, my media library file uploads ended up generating the error:

Spatie\MediaLibrary\MediaCollections\Exceptions\DiskCannotBeAccessed
Disk named `r2` cannot be accessed

After setting throw to true in my previously working fine-filesystems like this:

'r2' => [
    'driver' => 's3',
    'key' => env('CLOUDFLARE_R2_ACCESS_KEY_ID'),
    'secret' => env('CLOUDFLARE_R2_SECRET_ACCESS_KEY'),
    'region' => 'us-east-1',
    'bucket' => env('CLOUDFLARE_R2_BUCKET'),
    'url' => env('CLOUDFLARE_R2_URL'),
    'visibility' => 'private',
    'endpoint' => env('CLOUDFLARE_R2_ENDPOINT'),
    'use_path_style_endpoint' => env('CLOUDFLARE_R2_USE_PATH_STYLE_ENDPOINT', false),
    'throw' => true, // Changed to true
],

The error was this:

Unable to write file at location: *.png.

Error executing "PutObject" on "https://*.r2.cloudflarestorage.com/*.png";
AWS HTTP error: Server error: `PUT https://*.r2.cloudflarestorage.com/*.png`
resulted in a `501 Not Implemented` response:

<?xml version="1.0" encoding="UTF-8"?>
<Error>
    <Code>NotImplemented</Code>
    <Message>Header 'x-amz-checksum-crc32' (truncated...)
</Error>

NotImplemented (server): Header 'x-amz-checksum-crc32' with value 'tBHiWQ==' not implemented -

<?xml version="1.0" encoding="UTF-8"?>
<Error>
    <Code>NotImplemented</Code>
    <Message>Header 'x-amz-checksum-crc32' with value 'tBHiWQ==' not implemented</Message>
</Error>

After a quick look to the updated packages, I found the culprit: aws/aws-sdk-php update from 3.334.1 to 3.337.2, which led me to this issue [cloudflare r2] S3 default integrity change.

Fix

As mentioned in this issue the quick fix is to add these to lines to the disk config as below:

'r2' => [
    'driver' => 's3',
    'key' => env('CLOUDFLARE_R2_ACCESS_KEY_ID'),
    'secret' => env('CLOUDFLARE_R2_SECRET_ACCESS_KEY'),
    'region' => 'us-east-1',
    'bucket' => env('CLOUDFLARE_R2_BUCKET'),
    'url' => env('CLOUDFLARE_R2_URL'),
    'visibility' => 'private',
    'endpoint' => env('CLOUDFLARE_R2_ENDPOINT'),
    'use_path_style_endpoint' => env('CLOUDFLARE_R2_USE_PATH_STYLE_ENDPOINT', false),
    'throw' => false,
    'request_checksum_calculation' => 'when_required', // Add these
    'response_checksum_validation' => 'when_required', // two lines
],

Or downgrade aws/aws-sdk-php to 3.336.15 version.

Cloudflare Update

Compatibility

Client version 3.337.0 introduced a modification to the default checksum behavior from the client that is currently incompatible with R2 APIs.

To mitigate, users can use 3.336.15 or add the following to their $options:

'request_checksum_calculation' => 'when_required', 'response_checksum_validation' => 'when_required'