Search code examples
graphqlcorsauthorizationapollostrapi

Strapi Graphql Inconsistent 401 Authorization Errors Appearing


Hey guys I've been developing a site using Strapi v4.11.3 and I have this weird issue thats a bit hard to explain.

The thing is I gave permissions to the models that I want to get data from using the Public role. And when I send a query with apollo its working as expected but sometimes it just gives a plain 401 authorization error to the request. The weird stuff is when you refresh the page a couple of times (thus sending the query again) it works as expected.No errors. It's just working fine for a couple of hours. When you stop sending request from the react side for a couple of hours the error comes again and it just vanishes when you refresh the page.

The problem is it shouldn't even ask for any kind of authorization, Public role has the required permissions. I use a dockerized strapi on a remote machine and when you head to the /graphql instead of using the react/apollo and try to write some stuff in the playground same thing happens(I checked it from the network tab of devtools). You have to press the run query button a couple of times and it just gets fixed for some reason.

I think its about the cors middleware but I couldn't find a way to disable it because strapi says you can't remove it.

Here is my middlewares.ts file;

export default [
  "strapi::errors",
  "strapi::security",
  "strapi::poweredBy",
  "strapi::cors",
  "strapi::logger",
  "strapi::query",
  "strapi::body",
  "strapi::session",
  "strapi::favicon",
  "strapi::public",
];

Graphql plugin is using the default configuration so I have no files for that.

Also the error from Apollo has nothing useful in its stacktrace. It just says;

ApolloError: Response not successful: Received status "code 401"

The strapi container is running on dev mode. I have no problem accessing the admin panel.

There is also this error in the strapi logs when this happens;

[2023-07-31 22:59:04.226] http: POST /graphql (502 ms) 200
[2023-07-31 23:20:54.136] http: POST /graphql (51 ms) 401
Connection Error: Connection ended unexpectedly
[2023-07-31 23:20:57.969] http: POST /graphql (9 ms) 401
Connection Error: Connection ended unexpectedly
[2023-07-31 23:21:01.674] http: POST /graphql (766 ms) 200
[2023-07-31 23:21:02.050] http: POST /graphql (162 ms) 200
[2023-07-31 23:30:16.656] http: POST /graphql (656 ms) 200
[2023-07-31 23:30:17.043] http: POST /graphql (178 ms) 200
[2023-07-31 23:31:25.994] http: POST /graphql (527 ms) 200
[2023-07-31 23:31:26.322] http: POST /graphql (115 ms) 200

Solution

  • Hey guys I think I found the culprit. It's because of a bug on the knex library and postgres.

    If you have a minimum db pool size of 2 the remaining active pools doesn't get removed from the knex's pool even if the connection is closed by the postgresql.

    I added the following .env var to strapi in the compose and no problems so far;

    DATABASE_POOL_MIN: 0