Skip to content
PHP

How to Fix 'ImagickException: not authorized'

3 min read

Earlier this week we hit an issue with some code that we use to convert the first page of a PDF document into a thumbnail image (in our case a PNG). We use ImageMagick for the conversion. The code had been working well until we deployed it to a new server and it started to throw ImagickException errors.

In our error logs we were seeing errors like this:

ImagickException: not authorized /path/to/a-pdf-file.pdf @ error/constitute.c/ReadImage/412

Thankfully, it turned out that the fix was simple.

Back in 2018, ImageMagick released a security update that disabled ghostscript handled types by default. This meant that ImageMagick could no longer read or write to PDF files without updating the ImageMagick policy settings. This also includes PS, EPS and XPS file types.

The security patch introduced the following lines to the policy.xml file that handles these settings:

<!-- disable ghostscript format types -->
<policy domain="coder" rights="none" pattern="PS" />
<policy domain="coder" rights="none" pattern="EPS" />
<policy domain="coder" rights="none" pattern="PDF" />
<policy domain="coder" rights="none" pattern="XPS" />

In order for our code to be able to convert a PDF file into a PNG (or any other image format) we needed to update the policy for the PDF pattern. To do this, we edited the policy.xml file; for us, this file was located in /etc/ImageMagick-6/, but it may also be in /etc/ImageMagick/ (i.e. without the version number).

This was the line we needed to update:

<policy domain="coder" rights="none" pattern="PDF" />

We changed this so that the PDF pattern had read rights:

<policy domain="coder" rights="read" pattern="PDF" />

We only ever read the PDF files as we only use ImageMagick to convert a PDF to another image format. If you need to also write to PDF files using ImageMagick then you can give it a read|write policy:

<policy domain="coder" rights="read|write" pattern="PDF" />

Finally, we need to restart PHP-FPM (or nginx/apache) for the policy change to be implemented:

sudo service php7.4-fpm restart

This resolved our issue. ImagickException was no longer being thrown and ImageMagick was generating our thumbnails once more.

© 2024 Andy Carter