Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce query engine and schema generation #55

Merged
merged 5 commits into from
Mar 29, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@

# Dependency directories (remove the comment below to include it)
# vendor/

# Emacs stuff
*~
36 changes: 24 additions & 12 deletions cmd/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package cmd

import (
"context"
"fmt"

v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"
"github.com/spf13/cobra"
Expand All @@ -26,19 +27,32 @@ import (
"go.infratographer.com/permissions-api/internal/spicedbx"
)

var schemaCmd = &cobra.Command{
Use: "schema",
Short: "write the schema into SpiceDB",
Run: func(cmd *cobra.Command, args []string) {
writeSchema(cmd.Context(), globalCfg)
},
}
var (
schemaCmd = &cobra.Command{
Use: "schema",
Short: "write the schema into SpiceDB",
Run: func(cmd *cobra.Command, args []string) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

total nit but I prefer RunE over a bunch of logger.Fatal - not sure how you feel about that (yes, i know you didn't really change this 😆 )

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's a good suggestion for a subsequent PR. Can you open a GH issue? Would be a nice low hanging fruit.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done! See #57.

writeSchema(cmd.Context(), dryRun, globalCfg)
},
}

dryRun bool
)

func init() {
rootCmd.AddCommand(schemaCmd)

schemaCmd.Flags().BoolVar(&dryRun, "dry-run", false, "dry run: print the schema instead of applying it")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❤️

}

func writeSchema(ctx context.Context, cfg *config.AppConfig) {
func writeSchema(ctx context.Context, dryRun bool, cfg *config.AppConfig) {
schemaStr := spicedbx.GeneratedSchema("infratographer")

if dryRun {
fmt.Printf("%s", schemaStr)
return
}

err := otelx.InitTracer(cfg.Tracing, appName, logger)
if err != nil {
logger.Fatalw("unable to initialize tracing system", "error", err)
Expand All @@ -49,11 +63,9 @@ func writeSchema(ctx context.Context, cfg *config.AppConfig) {
logger.Fatalw("unable to initialize spicedb client", "error", err)
}

schema := spicedbx.GeneratedSchema(cfg.SpiceDB.Prefix)

logger.Debugw("Writing schema to DB", "schema", schema)
logger.Debugw("Writing schema to DB", "schema", schemaStr)

_, err = client.WriteSchema(context.Background(), &v1.WriteSchemaRequest{Schema: schema})
_, err = client.WriteSchema(context.Background(), &v1.WriteSchemaRequest{Schema: schemaStr})
if err != nil {
logger.Fatalw("error writing schema to SpiceDB", "error", err)
}
Expand Down
5 changes: 4 additions & 1 deletion cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (

"go.infratographer.com/permissions-api/internal/api"
"go.infratographer.com/permissions-api/internal/config"
"go.infratographer.com/permissions-api/internal/query"
"go.infratographer.com/permissions-api/internal/spicedbx"
)

Expand Down Expand Up @@ -64,9 +65,11 @@ func serve(ctx context.Context, cfg *config.AppConfig) {
logger.Fatalw("unable to initialize spicedb client", "error", err)
}

engine := query.NewEngine("infratographer", spiceClient)

s := ginx.NewServer(logger.Desugar(), cfg.Server, versionx.BuildDetails())

r, err := api.NewRouter(cfg.OIDC, spiceClient, logger)
r, err := api.NewRouter(cfg.OIDC, engine, logger)
if err != nil {
logger.Fatalw("unable to initialize router", "error", err)
}
Expand Down
65 changes: 0 additions & 65 deletions cmd/worker.go

This file was deleted.

6 changes: 3 additions & 3 deletions internal/api/permissions.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func (r *Router) checkAction(c *gin.Context) {
return
}

resource, err := query.NewResourceFromURN(resourceURN)
resource, err := r.engine.NewResourceFromURN(resourceURN)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "error processing resource URN", "error": err.Error()})
return
Expand All @@ -34,13 +34,13 @@ func (r *Router) checkAction(c *gin.Context) {
return
}

subjectResource, err := query.NewResourceFromURN(subject)
subjectResource, err := r.engine.NewResourceFromURN(subject)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "error processing subject URN", "error": err.Error()})
return
}

err = query.SubjectHasPermission(ctx, r.authzedClient, subjectResource, action, resource, "")
err = r.engine.SubjectHasPermission(ctx, subjectResource, action, resource, "")
if err != nil {
if errors.Is(err, query.ErrActionNotAssigned) {
c.JSON(http.StatusForbidden, gin.H{"message": "subject does not have requested action"})
Expand Down
29 changes: 19 additions & 10 deletions internal/api/resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"net/http"

"github.com/gin-gonic/gin"
"go.infratographer.com/permissions-api/internal/query"
"go.infratographer.com/x/urnx"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
Expand All @@ -18,39 +17,49 @@ func (r *Router) resourceCreate(c *gin.Context) {

resourceURN, err := urnx.Parse(resourceURNStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "error processing resource URN", "error": err.Error()})
c.JSON(http.StatusBadRequest, gin.H{"message": "error parsing resource URN", "error": err.Error()})
return
}

resource, err := query.NewResourceFromURN(resourceURN)
resource, err := r.engine.NewResourceFromURN(resourceURN)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "error processing resource URN", "error": err.Error()})
return
}

if err := c.ShouldBindJSON(&resource.Fields); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}

subject, err := currentSubject(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "message": "failed to get the subject"})
return
}

subjectResource, err := query.NewResourceFromURN(subject)
subjectResource, err := r.engine.NewResourceFromURN(subject)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": "error processing subject URN", "error": err.Error()})
return
}

zedToken, err := query.CreateSpiceDBRelationships(ctx, r.authzedClient, resource, subjectResource)
if resource.Type != "tenant" {
c.JSON(http.StatusBadRequest, gin.H{"message": "failed to create relationship", "error": "only tenants can be created"})
return
}

roles, _, err := r.engine.CreateBuiltInRoles(ctx, resource)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "failed to create relationship", "error": err.Error()})
return
}

var zedToken string
for _, role := range roles {
zedToken, err = r.engine.AssignSubjectRole(ctx, subjectResource, role)

if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "failed to create relationship", "error": err.Error()})
return
}
}

c.JSON(http.StatusCreated, gin.H{"token": zedToken})
}

Expand Down
16 changes: 8 additions & 8 deletions internal/api/router.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package api

import (
"github.com/authzed/authzed-go/v1"
"github.com/gin-gonic/gin"
"go.hollow.sh/toolbox/ginjwt"
"go.infratographer.com/permissions-api/internal/query"
"go.infratographer.com/x/urnx"
"go.opentelemetry.io/otel"
"go.uber.org/zap"
Expand All @@ -13,21 +13,21 @@ var tracer = otel.Tracer("go.infratographer.com/permissions-api/internal/api")

// Router provides a router for the API
type Router struct {
authMW func(*gin.Context)
authzedClient *authzed.Client
logger *zap.SugaredLogger
authMW func(*gin.Context)
engine *query.Engine
logger *zap.SugaredLogger
}

func NewRouter(authCfg ginjwt.AuthConfig, authzedClient *authzed.Client, l *zap.SugaredLogger) (*Router, error) {
func NewRouter(authCfg ginjwt.AuthConfig, engine *query.Engine, l *zap.SugaredLogger) (*Router, error) {
authMW, err := newAuthMiddleware(authCfg)
if err != nil {
return nil, err
}

out := &Router{
authMW: authMW,
authzedClient: authzedClient,
logger: l.Named("api"),
authMW: authMW,
engine: engine,
logger: l.Named("api"),
}

return out, nil
Expand Down
15 changes: 15 additions & 0 deletions internal/query/roles.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package query

import (
"github.com/google/uuid"
"go.infratographer.com/permissions-api/internal/types"
)

func newRoleFromTemplate(t types.RoleTemplate) types.Role {
out := types.Role{
ID: uuid.New(),
Actions: t.Actions,
}

return out
jnschaeffer marked this conversation as resolved.
Show resolved Hide resolved
}
16 changes: 16 additions & 0 deletions internal/query/service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package query

import "github.com/authzed/authzed-go/v1"

// Engine represents a client for making permissions queries.
type Engine struct {
namespace string
client *authzed.Client
}

func NewEngine(namespace string, client *authzed.Client) *Engine {
jnschaeffer marked this conversation as resolved.
Show resolved Hide resolved
return &Engine{
namespace: namespace,
client: client,
}
}
Loading