GraphQL 关系泄漏数据,即使已经设置了 context.user 解析器。如何防止通过关系暴露数据?

Posted

技术标签:

【中文标题】GraphQL 关系泄漏数据,即使已经设置了 context.user 解析器。如何防止通过关系暴露数据?【英文标题】:GraphQL relations leaking data, even with context.user resolver already set. How to prevent data exposure via relations? 【发布时间】:2018-03-04 00:06:31 【问题描述】:

每个人如何跨关系进行身份验证以防止数据通过关系被遍历?

例如,我们有一个拥有用户的商店。

// Returns error as i've set custom resolver to allow only context.user.is_shop_owner

  shops 
    name
    users 
      email
      ...
    
  

此查询通常会被 context.user.is_shop_owner 等自定义解析程序阻止,因此您无法从根查询执行此操作。

但是,如果恶意人员遍历关系到达用户对象,他就能够获取敏感的用户数据。

// Data exposed un-intendedly due to relation traversal. How to prevent this?

  products 
    name
    price
    shop 
      users  ...  // boom, exposed
    
  

这是 graphql 的缺陷吗? 你们是如何解决这个问题的

顺便说一句,这是在 python-石墨烯堆栈上。

编辑:顺便说一句,我知道我们可以做exclude_fields,但是我将无法从 ShopNode 访问用户,这是查询 ShopNode 的重要信息,因此限制字段可能不是一个好主意。 (已编辑)

【问题讨论】:

你是用 Django 做这个的吗,你能在返回用户时展示你的视图吗? @MauricioCortazar 我不使用 Django 视图,抱歉! 架构* 我的意思是 * 【参考方案1】:

这可能应该控制在Shop 类型中,当用户没有正确的权限时返回null。否则,如果从第二个字段访问 Shop,您将不得不重复检查。

【讨论】:

你将如何实现它?【参考方案2】:

我最终为每个节点设置了自定义解析器,以根据context.user 阻止您想要限制访问的关系。请参考下面的代码来回答我上面的问题。

class ProductNode(DjangoObjectType):
    class Meta:
        model = Product
        interfaces = (graphene.relay.Node)
        # Exclude nodes where you do not need any access at all
        exclude_fields = ['users']

    # For nodes where you need specific/limited access, define custom resolvers.
    # This prevents the relation traversal loophole
    def resolve_shop(self, args, context, info):
        """ Allow access to nodes only for staff or shop owner and manager """
        if get_is_staff_user(context.user, self):
            return self.shop

        Operations.raise_forbidden_access_error()

【讨论】:

以上是关于GraphQL 关系泄漏数据,即使已经设置了 context.user 解析器。如何防止通过关系暴露数据?的主要内容,如果未能解决你的问题,请参考以下文章

使用 NestJS、TypeORM、GraphQL 更新具有实体之间关系的 PSQL 表

API 平台 GraphQL 关系中的安全性

无法在 GraphQL 中返回关系数据

为啥在使用 Prisma 时需要使用 GraphQL 关系?

使用 graphql 和 apollo 客户端刷新 Angular 令牌

c ++ Opengl,Win内存泄漏