Re: ERROR: unsupported Unicode escape sequence - in JSON-type column

From: Erik Wienhold <ewie(at)ewie(dot)name>
To: Laurenz Albe <laurenz(dot)albe(at)cybertec(dot)at>, Jan Bilek <jan(dot)bilek(at)eftlab(dot)com(dot)au>, "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: ERROR: unsupported Unicode escape sequence - in JSON-type column
Date: 2023-02-27 15:17:10
Message-ID: 1435849180.1100046.1677511030342@office.mailbox.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

> On 27/02/2023 13:13 CET Laurenz Albe <laurenz(dot)albe(at)cybertec(dot)at> wrote:
>
> I'd be curious to know how the customer managed to do that.
> Perhaps there is a loophole in PostgreSQL that needs to be fixed.

Probably via some data access layer and not directly via Postgres. It's easy
to reproduce with psycopg:

import psycopg

with psycopg.connect() as con:
con.execute('create temp table jsontab (jsoncol json)')
con.execute(
'insert into jsontab (jsoncol) values (%s)',
[psycopg.types.json.Json('\0')],
)

with con.execute('select jsoncol from jsontab') as cur:
print(cur.fetchall())

try:
with con.execute('select jsoncol::jsonb from jsontab') as cur:
pass
raise AssertionError("jsonb should fail")
except psycopg.errors.UntranslatableCharacter:
pass

Another reason to prefer jsonb over json to reject such inputs right away.
The documentation states that json does not validate inputs in constrast to
jsonb.

Of course the OP now has to deal with json. The data can be sanitized by
replacing all null character escape sequences:

update jsontab
set jsoncol = replace(jsoncol::text, '\u0000', '')::json
where strpos(jsoncol::text, '\u0000') > 0;

But the data access layer (or whatever got the json into the database) must be
fixed as well to reject or sanitize those inputs in the future.

--
Erik

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Dávid Suchan 2023-02-27 15:44:58 pg_upgradecluster transfering only a portion of the data
Previous Message Ron 2023-02-27 14:31:32 Re: Repear operations on 50 tables of the same schema?