跳到主要内容
版本: websocket_v1.x.x

Opafiber

Release Discord Test

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

配置

属性类型描述默认值
RegoQuerystring必需 - Rego 查询-
RegoPolicyio.Reader必需 - Rego 策略-
IncludeQueryStringbool将查询字符串包含作为 Rego 策略的输入false
DeniedStatusCodeint当策略拒绝请求时返回的 Http 状态码400
DeniedResponseMessagestring当策略拒绝请求时返回的 Http 响应正文文本""
IncludeHeaders[]string将请求头包含作为 Rego 策略的输入-
InputCreationMethodInputCreationFunc使用您自己的函数为 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")
}