pothos icon indicating copy to clipboard operation
pothos copied to clipboard

Pitfall when calling a schema locally from another schema using auth scopes

Open macrozone opened this issue 1 year ago • 0 comments

this is a funky one.

i have this scenario:

  • i have 2 schemas A and B created by pothos , both with auth rules using the auth scope plugin. the auth rules currently are different
  • in one resolver of schemaA i am using a function that calls the other schema without a graphql server (because reasons):

// this is a function that is called in schemaA
export const myFunc = async (userId: string, ctx: Context) => {
  return await graphql({
    schema: schemaB
    source: `
        query GetUserInfo($userId: String!) {
            user(userId: $userId) {
                id
                firstName
                lastName
            }
        }
        `,
    variableValues: {
      userId,
    },
    contextValue: ctx,
  });
};

the ctx here is the context from the graphql server

So the funky bit is this:

** the auth scopes of schemaB are now resolved with a cached version of schemaA's scope values.**

the reason is that there is a global cache in pothos which uses the context object as key:

https://github.com/hayes/pothos/blob/main/packages/plugin-scope-auth/src/request-cache.ts#L21

since i pass the same context object to schemaB using the graphql function above, it will reuse the cache, but now with a different schema.

The workaround is to make sure to pass a new context object:


export const getUserInfo = async (userId: string, ctx: Context) => {
  return await graphql({
    schema,
    source: `
        query GetUserInfo($userId: String!) {
            user(userId: $userId) {
                id
                firstName
                lastName
            }
        }
        `,
    variableValues: {
      userId,
    },
    contextValue: {
      ...ctx, // important to create a new one!
    },
  });
};

Possible fix:

this is certainly an edge case, but one that is very hard to find with very weird consequences (i spent nearly an afternoon and had to fire up the node debugger to find it)

I am not totally sure how to fix it correctly, but i guess the builder or schema "instance" (if something like this exists) should be part of the cache key here: https://github.com/hayes/pothos/blob/main/packages/core/src/utils/context-cache.ts#L20

macrozone avatar May 24 '24 12:05 macrozone