与 GraphQL API 交互
与 GraphQL API 交互安全性:避免泄露 Query 中使用的认证信息

安全性:避免泄露 Query 中使用的认证信息

除非 GraphQL API 未公开(例如构建静态站点时),否则必须确保 GraphQL Query 不会泄露私密数据:

  • 包含在 Query 的响应中
  • 包含在发生错误时的输出中
  • 包含在日志中

例如,以下 Query 使用了 Environment Fields 模块提供的字段 _env

{
  githubAccessToken: _env(name: "GITHUB_ACCESS_TOKEN")
}

...会直接在响应中输出认证信息:

{
  "data": {
    "githubAccessToken": "{some access token}"
  }
}

可以使用插件中的若干功能来保证 GraphQL Query 的安全性:

  • Field to Input:通过动态变量将环境变量的值注入到另一个字段中
  • @remove Directive:避免将环境变量的值打印到输出中
  • Send HTTP Request Fields:直接在 GraphQL Query 内部连接外部服务

例如,以下 Query 使用私有访问令牌连接到 GitHub REST API:

{
  githubAccessToken: _env(name: "GITHUB_ACCESS_TOKEN")
    # This directive will remove this entry from the output
    @remove
 
  # Create the authorization header to send to GitHub
  authorizationHeader: _sprintf(
    string: "Bearer %s",
    # "Field to Input" feature to access value from the field above
    values: [$__githubAccessToken]
  )
    # Do not print in output
    @remove
  
  # Use the field from "Send HTTP Request Fields" to connect to GitHub
  gitHubArtifactData: _sendJSONObjectCollectionHTTPRequest(
    input: {
      url: "https://api.github.com/repos/GatoGraphQL/GatoGraphQL/actions/artifacts",
      options: {
        headers: [
          {
            name: "Accept"
            value: "application/vnd.github+json"
          },
          {
            name: "Authorization"
            # "Field to Input" feature to access value from the field above
            value: $__authorizationHeader
          },
        ]
      }
    }
  )
}

在此 Query 中,包含敏感数据的字段 githubAccessTokenauthorizationHeader 均已从输出中删除,字段 gitHubArtifactData 仅打印 API 调用的结果,不会泄露任何输入值(例如:发生错误时将打印字符串 "$__authorizationHeader" 而非变量的实际值)。