Skip to main content

Production Considerations

When it comes time to deploy your PostGraphile application to production, there's a few things you'll want to think about including topics such as logging, security and stability. This article outlines some of the issues you might face, and how to solve them.

准备将 PostGraphile 应用部署到生产环境时,有几个关键方面需要重点考虑,包括日志记录、安全性以及稳定性等。本文梳理了一些常见的问题及对应的解决方案。

Database Access Considerations数据库访问安全​

PostGraphile is just a node app / middleware, so you can deploy it to any number of places: Heroku, Now.sh, a VM, a container such as Docker, or of course onto bare metal. Typically you won't run PostGraphile on the same hardware/container/VM as the database, so PostGraphile needs to be able to connect to your database without you putting your DB at risk.

PostGraphile 本质上只是一个 Node.js 应用或中间件,因此可以部署到任意环境中,例如 Heroku、Now.sh、虚拟机、Docker 容器乃至物理机。通常 PostGraphile 不会与数据库运行在同一台硬件、容器或虚拟机上,因此你需要确保它在能连通数据库的同时,不会将数据库暴露在安全风险之中。

A standard way of doing this is to put the DB behind a firewall. However, if you're using a system like Heroku or Now.sh you probably can't do that, so instead you must make your DB accessible to the internet. When doing so here are a few things we recommend:

常规做法是将数据库置于防火墙之后。但如果使用 Heroku 或 Now.sh 等托管平台,往往无法配置内网隔离,不得不让数据库暴露在公网上。在这种情况下,建议采取以下安全措施:

  1. Only allow connections over SSL (force_ssl setting)

    仅允许通过 SSL 建立连接(开启 force_ssl 配置)

  2. Use a secure username (not root, admin, postgres, etc which are all fairly commonly used)

    使用高安全性用户名(避免使用 root、admin、postgres 等常见默认名称)

  3. Use a super secure password; you can use a command like this to generate one: openssl rand -base64 30 | tr '+/' '-_'

    使用高强度密码;可以通过类似如下命令生成:openssl rand -base64 30 | tr '+/' '-_'

  4. Use a non-standard port for your PostgreSQL server if you can (pick a random port number)

    条件允许时,为 PostgreSQL 服务器更换非标准端口(选择一个随机端口号)

  5. Use a hard-to-guess hostname, and never reveal the hostname to anyone who doesn't need to know it

    使用难以猜测的主机名,且切勿向无关人员泄露该主机名

  6. If possible, limit the IP addresses that can connect to your DB to be just those of your hosting provider.

    如条件允许,限制仅允许托管服务商的 IP 地址连接数据库。

Heroku have some instructions on making RDS available for use under Heroku which should also work for Now.sh or any other service: https://devcenter.heroku.com/articles/amazon-rds

Heroku 官方提供了在 Heroku 中安全连接 Amazon RDS 的说明文档,同样适用于 Now.sh 或其他托管平台:https://devcenter.heroku.com/articles/amazon-rds

By default PgRBACPlugin is enabled which inspects the RBAC (GRANT / REVOKE) privileges in the database and reflects these in your GraphQL schema. As is GraphQL best practices, this still only results in one GraphQL schema (not one per user), so it takes the user account you connect to PostgreSQL with (from your connection string) and walks all the roles that this user can become within the database, and uses the union of all these permissions. Using this plugin is recommended, as it results in a much leaner schema that doesn't contain functionality that you can't actually use. You can, however, disable it via disablePlugins: ['PgRBACPlugin'].

默认情况下,PgRBACPlugin 处于启用状态,它会检查数据库中的 RBAC(GRANT / REVOKE)权限,并将其映射到生成的 GraphQL schema 中。遵循 GraphQL 最佳实践,系统依然只生成一份统一的 GraphQL schema(而非为每个用户单独生成):它会根据连接字符串中指定的 PostgreSQL 用户账号,遍历该账号在数据库中有权切换的所有角色,并取这些角色权限的并集。建议保留启用该插件,这样生成的 schema 更加精简,不会包含实际无法调用的功能。当然,你也可以通过 disablePlugins: ['PgRBACPlugin'] 将其禁用。

Database Latency数据库网络延迟​

PostGraphile needs to issue queries to your database. For a transaction this might be multiple statements (begin, set local ..., select ..., commit) and each of these requires a roundtrip to the database. Thus the latency between your database and your PostGraphile server can easily be multiplied. If your database is in London but your PostGraphile server is in Tokyo then the ~300ms roundtrip time times 4 is a base latency that users will see of 1.2 seconds, no matter how fast your queries actually are.

PostGraphile 需要向数据库发送查询请求。单次事务可能包含多条语句(如 begin、set local ...、select ...、commit),而每条语句都需要一次数据库网络往返。因此,数据库与 PostGraphile 服务器之间的网络延迟会被成倍放大。举个例子,如果你的数据库位于伦敦,而 PostGraphile 服务器部署在东京,单次往返延迟约 300ms,乘以 4 次往返后,用户感知到的基础延迟就会高达 1.2 秒——无论查询本身执行得多快都无法回避。

Run PostGraphile in the same city as your database, preferably in the same data centre.

请务必将 PostGraphile 部署在与数据库相同的城市,最好是同一数据中心内。

Grafast ConsiderationsGrafast 相关注意事项​

Since PostGraphile uses Grafast under the hood, you should also familiarize yourself with Grafast's production considerations.

由于 PostGraphile 底层基于 Grafast 运行,建议同时熟悉 Grafast 生产环境注意事项。

Common Middleware Considerations常用中间件配置​

In a production app, you typically want to add a few common enhancements, e.g.

在生产环境应用中,通常需要叠加一些通用的增强能力,例如:

  • Logging

    日志记录

  • Gzip or similar compression

    Gzip 等响应压缩

  • Security protections

    安全防护

  • Rate limiting

    请求限流

Since there's already a lot of options and opinions in this space, and they're not directly related to the problem of serving GraphQL from your PostgreSQL database, PostGraphile does not include these things by default. We recommend that you use something like Express middleware to implement these common requirements. This is why we recommend using PostGraphile as a library for production usage.

由于这一领域已有大量成熟方案和不同偏好,且它们并不直接涉及“从 PostgreSQL 数据库提供 GraphQL 服务”这一核心职责,PostGraphile 默认并未内置这些功能。我们建议使用 Express 中间件等方式来实现这些通用需求——这也是我们推荐在生产环境中将 PostGraphile 作为库使用的原因。

Picking the Express (or similar) middleware that work for you is beyond the scope of this article; but you should ensure that they're installed before you add your PostGraphile server to the middleware stack.

具体挑选哪些适合项目的 Express(或同类框架)中间件已超出本文讨论范围;但请务必在将 PostGraphile 服务器挂载到中间件栈之前完成这些中间件的注册。

Denial of Service Considerations拒绝服务(DoS)防护​

When you run PostGraphile in production you'll want to ensure that people cannot easily trigger denial of service (DOS) attacks against you. Due to the nature of GraphQL it's easy to construct a small query that could be very expensive for the server to run, for example:

在生产环境中运行 PostGraphile 时,需要确保攻击者无法轻易发起拒绝服务(DoS)攻击。由于 GraphQL 的查询特性,攻击者很容易构造出一个体积很小、但服务器执行代价极高的查询,例如:

allUsers {
nodes {
postsByAuthorId {
nodes {
commentsByPostId {
userByAuthorId {
postsByAuthorId {
nodes {
commentsByPostId {
userByAuthorId {
postsByAuthorId {
nodes {
commentsByPostId {
userByAuthorId {
id
}
}
}
}
}
}
}
}
}
}
}
}
}
}

There's lots of techniques for protecting your server from these kinds of queries; a great introduction to this subject is this blog post from Apollo.

针对此类恶意查询有多种防护手段;Apollo 发布的这篇博客对此做了非常系统的入门介绍。

These techniques should be used in conjunction with common HTTP protection methods such as rate limiting which are typically better implemented at a separate layer; for example you could use Cloudflare rate limiting for this, or an Express.js middleware.

这些应用层防护措施还应与通用的 HTTP 防护手段(如请求限流)配合使用,后者通常更适合放在独立层处理——例如采用 Cloudflare 限流服务或 Express.js 限流中间件。

Statement Timeout语句超时限制(Statement Timeout)​

One simple solution to this issue is to place a timeout on the database operations via the statement_timeout PostgreSQL setting. This will halt any query that takes longer than the specified number of milliseconds to execute. This can still enable nefarious actors to have your database work hard for that duration, but it does prevent these malicious queries from running for an extended period, reducing the ease of a DoS (Denial of Service) attack. This solution is a good way to catch anything that may have slipped through the cracks of your other defences, or just to get you up and running while you work on more robust/lower level solutions, but when you expose your GraphQL endpoint to the world it's better to cut things off at the source before a query is ever sent to the database using one or more of the techniques detailed below.

一个简单直接的应对方式是通过 PostgreSQL 的 statement_timeout 参数为数据库操作设置超时时间。任何执行耗时超过指定毫秒数的查询都会被强制中止。虽然恶意请求在这段超时窗口内仍会消耗数据库资源,但至少能防止慢查询长期占满连接,从而大幅提高发起 DoS(拒绝服务)攻击的门槛。这项措施既适合作为其他防线的兜底保护,也适合在完善更底层防护期间快速上线使用;不过,若将 GraphQL 接口直接暴露给公网,更好的做法是采用下文介绍的方案,在查询发往数据库之前就从源头拦截。

Currently you can set this on a per-transaction basis using the pgSettings functionality in PostGraphile library mode, e.g.:

目前,在 PostGraphile 库模式下,可以通过 pgSettings 功能按事务粒度设置该超时,例如:

graphile.config.mjs
export default {
// ...
grafast: {
context(requestContext, args) {
return {
statement_timeout: "3000",
// ...
};
},
},
};

To be more efficient (only setting this once per database connection rather than once per GraphQL request) you can also set this up on a per connection basis if you pass a correctly configured pg.Pool instance to PostGraphile directly, e.g.:

为了获得更高效率(按数据库连接而非每次 GraphQL 请求设置一次),也可以直接向 PostGraphile 传入预先配置好的 pg.Pool 实例,在连接级别设置超时,例如:

graphile.config.mjs
import { Pool } from "pg";
import { makePgService } from "postgraphile/adaptors/pg";

/** does nothing */
function noop() {}

const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
pool.on("error", noop);
pool.on("connect", (client) => {
client.on("error", noop);
client.query("SET statement_timeout TO 3000");
});

export default {
// ...
pgServices: [
makePgService({
pool,
schemas: ["app_public"],
}),
],
};

Simple: Query Allowlist ("persisted queries" / "persisted operations")简便方案:查询白名单(“持久化查询” / “持久化操作”)​

If you do not intend to allow third parties to run arbitrary operations against your API then using persisted operations as a query allowlist is a highly recommended solution to protect your GraphQL endpoint. This technique ensures that only the operations you use in your own applications can be executed on the server, preventing malicious (or merely curious) actors from executing operations which may be more expensive than those you have written.

如果不打算允许第三方对你的 API 执行任意 GraphQL 操作,强烈建议使用持久化操作作为查询白名单来保护 GraphQL 端点。该机制确保服务器仅执行你自己应用中所使用的操作,从而彻底杜绝恶意攻击者(或仅仅出于好奇的用户)运行比预期更昂贵的查询。

This technique is suitable for the vast majority of use cases and supports many GraphQL clients, but it does have a few caveats:

该方案适用于绝大多数业务场景,也兼容众多 GraphQL 客户端,但使用时有几点需要注意:

  • Your API will only accept operations that you've approved, so it's not suitable if you want third parties to run arbitrary custom operations.

    API 只会接受预先批准的操作,因此不适合需要允许第三方自由编写任意查询的场景。

  • You must be able to generate a unique ID (e.g. a hash) from each operation at build time of your application/web page — your GraphQL operations must be "static". It's important to note this only applies to the operation document itself, the variables can of course change at runtime.

    必须在应用或前端页面构建阶段,就能为每个操作生成唯一 ID(例如哈希值)——也就是说 GraphQL 操作本身必须是“静态的”。注意这一限制仅针对操作文档本身,传入的变量在运行时依然可以动态变化。

  • You must have a way of sharing these static operations from the application build process to the server so that the server will know what operation the ID represents.

    必须有一种机制将构建产物中的这些静态操作同步给服务器,使服务器能够根据 ID 查找到对应的操作文档。

  • You must be careful not to use variables in dangerous places within your operation; for example if you were to use allUsers(first: $myVar) a malicious attacker could set $myVar to 2147483647 to cause your server to process as much data as possible. Use fixed limits, conditions and orders where possible, even if it means having additional static operations.

    切勿在操作中的危险位置使用变量;例如,若写成 allUsers(first: $myVar),恶意攻击者就可以将 $myVar 设为 2147483647,迫使服务器尽可能处理海量数据。应尽量对分页上限、过滤条件和排序方式使用固定值,即便这意味着需要多维护几个静态操作。

  • It does not protect you from writing expensive queries yourself; it may be wise to combine this technique with a cost estimation technique to help guide your developers and avoid accidentally writing expensive queries.

    白名单机制并不能阻止开发者自己写出高开销查询;建议将其与查询成本估算技术结合使用,引导开发团队避免无意间写出性能较差的查询。

PostGraphile has first-party support for persisted operations via the open source @grafserv/persisted plugin; we recommend its use to the vast majority of our users.

PostGraphile 通过开源的 @grafserv/persisted 插件为持久化操作提供了一等支持;我们向绝大多数用户推荐使用该插件。