AWS S3 presigned PUT URL from aws-php-sdk returns malformed or otherwise invalid token

105 views Asked by At

I am using Laravel v8 to craft a pre-signed upload url to s3 private bucket. The API itself runs on an EC2 instance with role set for full bucket access. When logged into the ec2 instance and using aws s3 ls command the associated buckets are displayed so role is set.

The API returns a signed URL to the frontend app by using following function:

    public function getPresignedPutUrl(string $diskName, string $bucketName, string $filePath) {
        $client = Storage::disk($diskName)->getDriver()->getAdapter()->getClient();
        $expiry = '+10 minutes';
        $contentType = 'video/' . explode('.', $filePath)[1];
        $cmd = $client->getCommand('PutObject', [
            'Bucket' => $bucketName,
            'Key' => $filePath,
            'Expires' => 300,
            'ContentType' => $contentType,
        ]);
        $request = $client->createPresignedRequest($cmd, $expiry);
        return $request->getUri();
    }

When calling the returned URL the following ambiguous error is returned: The provided token is malformed or otherwise invalid

Disk configuration is managed as follows:

        env('PRIVATE_DISK_NAME') => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET_PRIVATE'),
            'url' => env('AWS_URL'),
            'endpoint' => env('AWS_ENDPOINT'),
        ],

Here ENV values for AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are left out blank as suggested for security reasons. Credentials are provided by the EC2 instance metadata.This is confirmed by uploading files directly from the API successfully to s3 bucket via the Storage.

The s3 driver itself should check down the chain for access/authorization metadata and find it in the ec2 instance, however maybe the SDK itself looks in the wrong place for amazon auth details and therefore signs a malformed token?

Many similar topics have accepted answers that suggest to configure the secret key and access id within the ec2 instance or save them in .env files. This option is not possible as is marked as bad security practice in Amazon docs and is already working for regular file uploads via the s3 filesystem manager.

Do you have any ideas what could cause this behavior and what would be the potential fixes? Much appreciated!

0

There are 0 answers