Skip to content

Commit

Permalink
Add rego parsing capabilities
Browse files Browse the repository at this point in the history
Signed-off-by: David Son <[email protected]>
  • Loading branch information
sondavidb committed Sep 10, 2024
1 parent 5d9b1e0 commit b847fed
Show file tree
Hide file tree
Showing 4 changed files with 252 additions and 82 deletions.
59 changes: 59 additions & 0 deletions api/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package router

import (
"context"
"errors"
"fmt"
"net/http"
"os"
Expand All @@ -14,6 +15,7 @@ import (
"github.com/gorilla/mux"
"github.com/moby/moby/api/server/httputils"
"github.com/moby/moby/api/types/versions"
"github.com/open-policy-agent/opa/rego"

"github.com/runfinch/finch-daemon/api/handlers/builder"
"github.com/runfinch/finch-daemon/api/handlers/container"
Expand All @@ -29,6 +31,8 @@ import (
"github.com/runfinch/finch-daemon/version"
)

var BadRegoError = errors.New("internal server error: bad rego policy")

// Options defines the router options to be passed into the handlers.
type Options struct {
Config *config.Config
Expand All @@ -40,15 +44,25 @@ type Options struct {
VolumeService volume.Service
ExecService exec.Service

// RegoPath points to a rego file used to parse allowlist/denylist policies
// Ignored if empty
RegoPath string

// NerdctlWrapper wraps the interactions with nerdctl to build
NerdctlWrapper *backend.NerdctlWrapper
}

type RegoInput struct {
Method string
Path string
}

// New creates a new router and registers the handlers to it. Returns a handler object
// The struct definitions of the HTTP responses come from https://github.com/moby/moby/tree/master/api/types.
func New(opts *Options) http.Handler {
r := mux.NewRouter()
r.Use(VersionMiddleware)
r.Use(CreateRegoMiddleware(opts))
vr := types.VersionedRouter{Router: r}

logger := flog.NewLogrus()
Expand Down Expand Up @@ -87,3 +101,48 @@ func VersionMiddleware(next http.Handler) http.Handler {
next.ServeHTTP(w, newReq)
})
}

// CreateRegoMiddleware dynamically parses the rego file at the path specified in options
// and allows or denies the request based on the policy
func CreateRegoMiddleware(opts *Options) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
regoPath := opts.RegoPath

// Ignore if regoPath is blank
if regoPath != "" {
query := "data.docker.authz.allow"

input := RegoInput{
Method: r.Method,
Path: r.URL.Path,
}

newRego := rego.New(
rego.Load([]string{regoPath}, nil),
rego.Query(query),
)

preppedQuery, err := newRego.PrepareForEval(context.Background())
if err != nil {
response.SendErrorResponse(w, http.StatusInternalServerError, BadRegoError)
return
}

rs, err := preppedQuery.Eval(context.Background(), rego.EvalInput(input))
if err != nil {
response.SendErrorResponse(w, http.StatusInternalServerError, BadRegoError)
return
}

if !rs.Allowed() {
response.SendErrorResponse(w, http.StatusBadRequest,
fmt.Errorf("method %s not allowed for path %s", r.Method, r.URL.Path))
return
}
}
newReq := r.WithContext(r.Context())
next.ServeHTTP(w, newReq)
})
}
}
9 changes: 6 additions & 3 deletions cmd/finch-daemon/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ type DaemonOptions struct {
debug bool
socketAddr string
socketOwner int
regoPath string
}

var options = new(DaemonOptions)
Expand All @@ -66,6 +67,7 @@ func main() {
" For macOS, the socket has to be owned by the lima user to make port forwarding work"+
" (more info: https://github.com/lima-vm/lima/blob/5a9bca3d09481ed7109b14f8d3f0074816731f43/examples/default.yaml#L340)."+
" -1 means no-op.")
rootCmd.Flags().StringVar(&options.regoPath, "rego-path", "", "Optional path to a rego policy. Currently only allowlist/denylist options are available")
if err := rootCmd.Execute(); err != nil {
log.Printf("got error: %v", err)
log.Fatal(err)
Expand All @@ -83,7 +85,7 @@ func run(options *DaemonOptions) error {
}

logger := flog.NewLogrus()
r, err := newRouter(options.debug, logger)
r, err := newRouter(options, logger)
if err != nil {
return fmt.Errorf("failed to create a router: %w", err)
}
Expand Down Expand Up @@ -122,9 +124,9 @@ func run(options *DaemonOptions) error {
return nil
}

func newRouter(debug bool, logger *flog.Logrus) (http.Handler, error) {
func newRouter(options *DaemonOptions, logger *flog.Logrus) (http.Handler, error) {
conf := config.New()
conf.Debug = debug
conf.Debug = options.debug
conf.Namespace = defaultNamespace
client, err := containerd.New(conf.Address, containerd.WithDefaultNamespace(conf.Namespace))
if err != nil {
Expand All @@ -151,6 +153,7 @@ func newRouter(debug bool, logger *flog.Logrus) (http.Handler, error) {
BuilderService: builder.NewService(clientWrapper, ncWrapper, logger, tarExtractor),
VolumeService: volume.NewService(ncWrapper, logger),
ExecService: exec.NewService(clientWrapper, logger),
RegoPath: options.regoPath,
NerdctlWrapper: ncWrapper,
}
return router.New(opts), nil
Expand Down
71 changes: 48 additions & 23 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ go 1.22.7

require (
github.com/containerd/cgroups/v3 v3.0.3
github.com/containerd/containerd v1.7.14
github.com/containerd/containerd v1.7.21
github.com/containerd/containerd/api v1.7.19
github.com/containerd/go-cni v1.1.9
github.com/containerd/nerdctl v1.7.5
github.com/containerd/typeurl/v2 v2.1.1
Expand All @@ -20,29 +21,34 @@ require (
github.com/moby/moby v26.0.0+incompatible
github.com/onsi/ginkgo/v2 v2.17.1
github.com/onsi/gomega v1.32.0
github.com/open-policy-agent/opa v0.68.0
github.com/opencontainers/go-digest v1.0.0
github.com/opencontainers/image-spec v1.1.0
github.com/opencontainers/runtime-spec v1.2.0
github.com/pkg/errors v0.9.1
github.com/runfinch/common-tests v0.7.21
github.com/sirupsen/logrus v1.9.3
github.com/spf13/afero v1.11.0
github.com/spf13/cobra v1.8.0
github.com/spf13/cobra v1.8.1
github.com/vishvananda/netlink v1.2.1-beta.2
github.com/vishvananda/netns v0.0.4
golang.org/x/net v0.23.0
golang.org/x/sys v0.20.0
google.golang.org/protobuf v1.33.0
golang.org/x/net v0.28.0
golang.org/x/sys v0.23.0
google.golang.org/protobuf v1.34.2
)

require (
github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 // indirect
github.com/AdamKorcz/go-118-fuzz-build v0.0.0-20231105174938-2b5cbb29f3e2 // indirect
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect
github.com/Masterminds/semver/v3 v3.2.1 // indirect
github.com/Microsoft/go-winio v0.6.1 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/Microsoft/hcsshim v0.12.2 // indirect
github.com/OneOfOne/xxhash v1.2.8 // indirect
github.com/agnivade/levenshtein v1.1.1 // indirect
github.com/awslabs/soci-snapshotter v0.5.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cilium/ebpf v0.14.0 // indirect
github.com/containerd/accelerated-container-image v1.0.4 // indirect
github.com/containerd/console v1.0.4 // indirect
Expand All @@ -53,15 +59,17 @@ require (
github.com/containerd/imgcrypt v1.1.10 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/containerd/nydus-snapshotter v0.13.11 // indirect
github.com/containerd/platforms v0.2.1 // indirect
github.com/containerd/stargz-snapshotter v0.15.1 // indirect
github.com/containerd/stargz-snapshotter/estargz v0.15.1 // indirect
github.com/containerd/stargz-snapshotter/ipfs v0.15.1 // indirect
github.com/containerd/ttrpc v1.2.3 // indirect
github.com/containerd/ttrpc v1.2.5 // indirect
github.com/containerd/typeurl v1.0.3-0.20220422153119-7f6e6d160d67 // indirect
github.com/containernetworking/plugins v1.4.1 // indirect
github.com/containers/ocicrypt v1.1.10 // indirect
github.com/coreos/go-iptables v0.7.0 // indirect
github.com/cyphar/filepath-securejoin v0.2.4 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/djherbis/times v1.6.0 // indirect
github.com/docker/docker-credential-helpers v0.8.1 // indirect
Expand All @@ -71,10 +79,12 @@ require (
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fluent/fluent-logger-golang v1.9.0 // indirect
github.com/getlantern/mockconn v0.0.0-20200818071412-cb30d065a848 // indirect
github.com/go-ini/ini v1.67.0 // indirect
github.com/go-jose/go-jose/v3 v3.0.3 // indirect
github.com/go-logr/logr v1.4.1 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
Expand All @@ -88,7 +98,7 @@ require (
github.com/hashicorp/go-retryablehttp v0.7.7 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/ipfs/go-cid v0.4.1 // indirect
github.com/klauspost/compress v1.17.7 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/miekg/pkcs11 v1.1.1 // indirect
github.com/minio/sha256-simd v1.0.1 // indirect
Expand All @@ -102,7 +112,8 @@ require (
github.com/moby/sys/sequential v0.5.0 // indirect
github.com/moby/sys/signal v0.7.0 // indirect
github.com/moby/sys/symlink v0.2.0 // indirect
github.com/moby/sys/user v0.1.0 // indirect
github.com/moby/sys/user v0.3.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/moby/term v0.5.0 // indirect
github.com/morikuni/aec v1.0.0 // indirect
github.com/mr-tron/base58 v1.2.0 // indirect
Expand All @@ -113,38 +124,52 @@ require (
github.com/multiformats/go-multibase v0.2.0 // indirect
github.com/multiformats/go-multihash v0.2.3 // indirect
github.com/multiformats/go-varint v0.0.7 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/opencontainers/selinux v1.11.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/philhofer/fwd v1.1.2 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_golang v1.20.2 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.55.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 // indirect
github.com/rootless-containers/bypass4netns v0.4.0 // indirect
github.com/rootless-containers/rootlesskit v1.1.1 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 // indirect
github.com/tchap/go-patricia/v2 v2.3.1 // indirect
github.com/tidwall/gjson v1.17.1 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tinylib/msgp v1.1.9 // indirect
github.com/vbatts/tar-split v0.11.5 // 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
github.com/yuchanns/srslog v1.1.0 // indirect
go.mozilla.org/pkcs7 v0.0.0-20210826202110-33d05740a352 // indirect
go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect
go.opentelemetry.io/otel v1.24.0 // indirect
go.opentelemetry.io/otel/metric v1.24.0 // indirect
go.opentelemetry.io/otel/trace v1.24.0 // indirect
golang.org/x/crypto v0.21.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.53.0 // indirect
go.opentelemetry.io/otel v1.28.0 // indirect
go.opentelemetry.io/otel/metric v1.28.0 // indirect
go.opentelemetry.io/otel/sdk v1.28.0 // indirect
go.opentelemetry.io/otel/trace v1.28.0 // indirect
go.uber.org/goleak v1.3.0 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/exp v0.0.0-20240325151524-a685a6edb6d8 // indirect
golang.org/x/mod v0.16.0 // indirect
golang.org/x/sync v0.6.0 // indirect
golang.org/x/term v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.5.0 // indirect
golang.org/x/tools v0.19.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/term v0.23.0 // indirect
golang.org/x/text v0.17.0 // indirect
golang.org/x/time v0.6.0 // indirect
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
google.golang.org/genproto v0.0.0-20240401170217-c3f982113cda // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240401170217-c3f982113cda // indirect
google.golang.org/grpc v1.62.1 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240701130421-f6361c86f094 // indirect
google.golang.org/grpc v1.66.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/cri-api v0.29.3 // indirect
lukechampine.com/blake3 v1.2.1 // indirect
sigs.k8s.io/yaml v1.4.0 // indirect
)
Loading

0 comments on commit b847fed

Please sign in to comment.