Opafiber
Open Policy Agent 对 Fiber 的支持。
注意: 需要 Go 1.19 或更高版本
安装
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/contrib/opafiber/v2
签名
opafiber.New(config opafiber.Config) fiber.Handler
配置
属性 | 类型 | 描述 | 默认值 |
---|---|---|---|
RegoQuery | string | 必需 - Rego 查询 | - |
RegoPolicy | io.Reader | 必需 - Rego 策略 | - |
IncludeQueryString | bool | 将查询字符串包含作为 Rego 策略的输入 | false |
DeniedStatusCode | int | 当策略拒绝请求时返回的 Http 状态码 | 400 |
DeniedResponseMessage | string | 当策略拒绝请求时返回的 Http 响应正文文本 | "" |
IncludeHeaders | []string | 将请求头包含作为 Rego 策略的输入 | - |
InputCreationMethod | InputCreationFunc | 使用您自己的函数为 OPA 提供输入 | func defaultInput(ctx *fiber.Ctx) (map[string]interface{}, error) |
类型
type InputCreationFunc func(c *fiber.Ctx) (map[string]interface{}, error)
用法
OPA Fiber 中间件将以下示例数据作为输入发送到策略引擎
{
"method": "GET",
"path": "/somePath",
"query": {
"name": ["John Doe"]
},
"headers": {
"Accept": "application/json",
"Content-Type": "application/json"
}
}
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/contrib/opafiber/v2"
)
func main() {
app := fiber.New()
module := `
package example.authz
default allow := false
allow {
input.method == "GET"
}
`
cfg := opafiber.Config{
RegoQuery: "data.example.authz.allow",
RegoPolicy: bytes.NewBufferString(module),
IncludeQueryString: true,
DeniedStatusCode: fiber.StatusForbidden,
DeniedResponseMessage: "status forbidden",
IncludeHeaders: []string{"Authorization"},
InputCreationMethod: func (ctx *fiber.Ctx) (map[string]interface{}, error) {
return map[string]interface{}{
"method": ctx.Method(),
"path": ctx.Path(),
}, nil
},
}
app.Use(opafiber.New(cfg))
app.Get("/", func(ctx *fiber.Ctx) error {
return ctx.SendStatus(200)
})
app.Listen(":8080")
}