GraphQL联邦架构安全边界与策略执行最佳实践概述联邦将多个子图聚合成一个网关API,需在网关与子图层同时执行授权与复杂度治理,确保边界安全与一致性。子图授权指令directive @auth(role: String, permission: String) on FIELD_DEFINITION | OBJECT type User @auth(role: "admin") { id: ID! email: String } 网关策略执行type Context = { userId: string; roles: string[]; permissions: string[] } function guard(ctx: Context, args: { role?: string; permission?: string }): boolean { const hasRole = args.role ? ctx.roles.includes(args.role) : true const hasPerm = args.permission ? ctx.permissions.includes(args.permission) : true return hasRole && hasPerm } function wrapResolver(resolver: Function, args: { role?: string; permission?: string }): Function { return async (p: any, a: any, ctx: Context, i: any) => { if (!guard(ctx, args)) throw new Error('forbidden') return resolver(p, a, ctx, i) } } 查询规划与复杂度type CostRule = { field: string; cost: number } function computeCost(ast: any, rules: CostRule[]): number { let c = 0 const stack = [ast] while (stack.length) { const cur = stack.pop()! const name = cur.name?.value const r = rules.find(x => x.field === name) if (r) c += r.cost const sels = cur.selectionSet?.selections || [] for (const s of sels) stack.push(s) } return c } function limitComplexity(cost: number, max: number) { if (cost > max) throw new Error('complexity_exceeded') } 运维要点在子图以指令标注授权需求,并在网关统一执行对联邦查询进行复杂度评估与阈值限制,避免资源枯竭记录网关与子图的授权拒绝与复杂度超限事件通过子图边界与统一策略执行,可在联邦架构下实现一致且可验证的安全治理。

发表评论 取消回复