contrib/opa

OPA

Release Discord Test

Open Policy Agent support for Fiber.

Compatible with Fiber v3.

Go version support

We only support the latest two versions of Go. Visit https://go.dev/doc/devel/release for more information.

Install

go get -u github.com/gofiber/fiber/v3
go get -u github.com/gofiber/contrib/v3/opa

Signature

opa.New(config opa.Config) fiber.Handler

Config

PropertyTypeDescriptionDefault
RegoQuerystringRequired - Rego query-
RegoPolicyio.ReaderRequired - Rego policy-
IncludeQueryStringboolInclude query string as input to rego policyfalse
DeniedStatusCodeintHttp status code to return when policy denies request400
DeniedResponseMessagestringHttp response body text to return when policy denies request""
IncludeHeaders[]stringInclude headers as input to rego policy-
InputCreationMethodInputCreationFuncUse your own function to provide input for OPAfunc defaultInput(ctx fiber.Ctx) (map[string]interface{}, error)

Types

type InputCreationFunc func(c fiber.Ctx) (map[string]interface{}, error)

Usage

OPA Fiber middleware sends the following example data to the policy engine as input:

{
  "method": "GET",
  "path": "/somePath",
  "query": {
    "name": ["John Doe"]
  },
  "headers": {
    "Accept": "application/json",
    "Content-Type": "application/json"
  }
}

path is the path as the client sent it. Unless fiber.Config.CaseSensitive and StrictRouting are set, the router matches routes on the lower-cased path without trailing slashes, while route params are cut from the path without trailing slashes in the client's letter case; the policy is evaluated again with each of these forms that differs from path and has to allow all of them. Write policy paths lower-case and without trailing slashes. An InputCreationMethod that sets path to ctx.Path() gets the same check. Unless DisableHeadAutoRegister is set, the router answers HEAD with the handlers of GET routes, so a HEAD request is evaluated again with method set to GET and needs both allowed, even on a route with its own HEAD handler; this applies when method is ctx.Method(). Clients that only send HEAD, such as health checks, need GET allowed too, or set DisableHeadAutoRegister.

A header listed in IncludeHeaders that the request carries on more than one line is refused with DeniedStatusCode, because handlers can read another line than the policy saw. The typical case is X-Forwarded-For behind a proxy that adds a line of its own instead of appending to the existing one. Cookie lines are joined with ; instead. A header the server keeps as one value, such as User-Agent (the last line) or two identical Content-Type lines, is not refused, since the policy and handlers read that value.

When the policy cannot be evaluated, the client gets a 500 with Error evaluating rego policy and the ErrorHandler gets a *fiber.Error with the same text. OPA's error can quote values the policy computed, so it is only logged.

package main

import (
    "bytes"

    "github.com/gofiber/fiber/v3"
    "github.com/gofiber/contrib/v3/opa"
)

func main() {
    app := fiber.New()
    module := `
package example.authz

default allow := false

allow if {
    input.method == "GET"
}
`

    cfg := opa.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(opa.New(cfg))

    app.Get("/", func(ctx fiber.Ctx) error {
        return ctx.SendStatus(200)
    })

    app.Listen(":8080")
}