Skip to content

Commit

Permalink
changes to make apisix work as pep
Browse files Browse the repository at this point in the history
  • Loading branch information
gerardsn committed Jun 12, 2024
1 parent a6fabf1 commit bf59bd3
Show file tree
Hide file tree
Showing 10 changed files with 500 additions and 87 deletions.
91 changes: 83 additions & 8 deletions api/opa/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,110 @@ package opa

import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/nuts-foundation/nuts-pxp/policy"
http2 "net/http"
"net/http/httputil"
"strings"

"github.com/nuts-foundation/nuts-pxp/http"
"github.com/nuts-foundation/nuts-pxp/policy"
)

var _ StrictServerInterface = (*Wrapper)(nil)
var _ http.Router = (*Wrapper)(nil)

type Wrapper struct {
DecisionMaker policy.DecisionMaker
}

func (w Wrapper) Routes(router *http2.ServeMux) {
handler := NewStrictHandlerWithOptions(w, []StrictMiddlewareFunc{}, StrictHTTPServerOptions{
RequestErrorHandlerFunc: http.ErrorHandlerFunc,
ResponseErrorHandlerFunc: http.ErrorHandlerFunc,
})
HandlerFromMux(handler, router)
router.HandleFunc("POST /v1/data/*", func(writer http2.ResponseWriter, request *http2.Request) {
req, _ := httputil.DumpRequest(request, true)
fmt.Printf("REQUEST DUMP START: %s\n", req)
fmt.Println("REQUEST DUMP END")
// we validate the path and if valid we route it to /v1/data
if err := validatePath(request.URL.Path); err != nil {
http.ErrorHandlerFunc(writer, request, err)
// MUST return here if the path is invalid
return
}
request.URL.Path = "/v1/data"

wrapper := ServerInterfaceWrapper{
Handler: handler,
HandlerMiddlewares: []MiddlewareFunc{},
ErrorHandlerFunc: http.ErrorHandlerFunc,
}
wrapper.EvaluateDocument(writer, request)
})
}

func validatePath(path string) error {
// path matches /v1/data/*, we validate *
// /v1/data/{package}/{decision}
// OPA 'package' contains 1 or more path elements.
// If there is more than 1 element, replace '/' with '.' for the package name. This value is currently not validated.
// 'decision' is the variable name of the boolean in the result containing the OPA policy decision.
// If * contains more than 1 path element we assume the last element is the decision value, which MUST be equal to 'allow'
parts := strings.Split(path, "/") // ["", "v1", "data", ...]
if len(parts) > 4 && parts[len(parts)-1] != "allow" {
return errors.New("invalid OPA request")
}
return nil
}

func (w Wrapper) EvaluateDocument(ctx context.Context, request EvaluateDocumentRequestObject) (EvaluateDocumentResponseObject, error) {
// parse the requestLine and extract the method and path
// the requestLine is formatted as an HTTP request line
// e.g. "GET /api/v1/resource HTTP/1.1"
// we are only interested in the method and path
method, path, err := parseRequestLine(request.Params.Request)
//method, path, err := parseRequestLine(request.Params.Request)
//if err != nil {
// return nil, err
//}
//httpRequest := map[string]interface{}{}
//httpRequest["method"] = method
//httpRequest["path"] = path

// request.Body =:
// {
// "input": {
// "request": {
// "method": ...,
// "path": ...,
// }, {
// "headers": {
// "X-Userinfo": ...,
// },
// },
// }
httpRequest := (*request.Body)["input"].(map[string]interface{})["request"].(map[string]interface{})
httpHeaders := httpRequest["headers"].(map[string]interface{})
xUserinfoBase64 := httpHeaders["X-Userinfo"].(string)
xUserinfoJSON, err := base64.URLEncoding.DecodeString(xUserinfoBase64)
if err != nil {
return nil, err
panic(err)
}
xUserinfo := map[string]interface{}{}
err = json.Unmarshal(xUserinfoJSON, &xUserinfo)
if err != nil {
panic(err)
}
httpRequest := map[string]interface{}{}
httpRequest["method"] = method
httpRequest["path"] = path

descision, err := w.DecisionMaker.Query(ctx, httpRequest, request.Params.XUserinfo)
descision, err := w.DecisionMaker.Query(ctx, httpRequest, xUserinfo)
if err != nil {
return nil, err
}
return EvaluateDocument200JSONResponse{Allow: descision}, nil
result := map[string]interface{}{"allow": descision}
return EvaluateDocument200JSONResponse{Result: result}, nil
}

// parseRequestLine parses the request line and extracts the method and path
Expand Down
54 changes: 18 additions & 36 deletions api/opa/generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions api/pip/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,26 @@ package pip
import (
"context"
"encoding/json"
http2 "net/http"

"github.com/nuts-foundation/nuts-pxp/db"
"github.com/nuts-foundation/nuts-pxp/http"
)

var _ StrictServerInterface = (*Wrapper)(nil)
var _ http.Router = (*Wrapper)(nil)

type Wrapper struct {
DB db.DB
}

func (w Wrapper) Routes(router *http2.ServeMux) {
HandlerFromMux(NewStrictHandlerWithOptions(w, []StrictMiddlewareFunc{}, StrictHTTPServerOptions{
RequestErrorHandlerFunc: http.ErrorHandlerFunc,
ResponseErrorHandlerFunc: http.ErrorHandlerFunc,
}), router)
}

func (w Wrapper) CreateData(_ context.Context, request CreateDataRequestObject) (CreateDataResponseObject, error) {
// serialize authInput for storage
authInput, _ := json.Marshal(request.Body.AuthInput)
Expand Down
5 changes: 0 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ require (
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/microsoft/go-mssqldb v1.7.0 // indirect
Expand All @@ -61,8 +59,6 @@ require (
github.com/sethvargo/go-retry v0.2.4 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/tchap/go-patricia/v2 v2.3.1 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/yashtewari/glob-intersection v0.2.0 // indirect
Expand All @@ -72,7 +68,6 @@ require (
go.opentelemetry.io/otel/trace v1.21.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
Expand Down
Loading

0 comments on commit bf59bd3

Please sign in to comment.