Skip to content

Commit

Permalink
Add example
Browse files Browse the repository at this point in the history
Signed-off-by: Charith Ellawala <charith@cerbos.dev>
  • Loading branch information
charithe committed Sep 22, 2023
1 parent 1f8050b commit 657a296
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 1 deletion.
4 changes: 4 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,7 @@ issues:
- goconst
- gomnd
- govet
- path: example_test\.go
linters:
- gocritic
- errcheck
65 changes: 65 additions & 0 deletions testutil/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2021-2023 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0

package testutil_test

import (
"context"
"fmt"
"log"
"time"

"github.com/cerbos/cerbos-sdk-go/cerbos"
"github.com/cerbos/cerbos-sdk-go/testutil"
)

func ExampleLaunchCerbosServer() {
// Configure Cerbos with the SQLite storage driver
conf := testutil.LaunchConf{
Cmd: []string{
"server",
"--set=storage.driver=sqlite3",
"--set=storage.sqlite3.dsn=:mem:?_fk=true",
},
Env: []string{
"CERBOS_LOG_LEVEL=error",
},
}

// Set timeout for launching the server
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

s, err := testutil.LaunchCerbosServer(ctx, conf)
if err != nil {
log.Fatalf("Failed to launch Cerbos server: %v", err)
}

defer s.Stop()

c, err := cerbos.New(s.GRPCAddr(), cerbos.WithPlaintext())
if err != nil {
log.Fatalf("Failed to create Cerbos client: %v", err)
}

allowed, err := c.IsAllowed(context.TODO(),
cerbos.NewPrincipal("john").
WithRoles("employee", "manager").
WithAttr("department", "marketing").
WithAttr("geography", "GB"),
cerbos.NewResource("leave_request", "XX125").
WithAttributes(map[string]any{
"department": "marketing",
"geography": "GB",
"owner": "harry",
"status": "DRAFT",
}),
"view",
)
if err != nil {
log.Fatalf("API request failed: %v", err)
}

fmt.Println(allowed)
// Output: false
}
3 changes: 2 additions & 1 deletion testutil/testutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ type LaunchConf struct {
PolicyDirMountPoint string
AdditionalMounts []string
Cmd []string
Env []string
}

// NewCerbosServerLauncher creates a launcher for Cerbos containers.
Expand Down Expand Up @@ -130,7 +131,7 @@ func (csl *CerbosServerLauncher) Launch(conf LaunchConf) (*CerbosServerInstance,
Repository: csl.repo,
Tag: csl.tag,
Cmd: conf.Cmd,
Env: []string{"CERBOS_NO_TELEMETRY=1"},
Env: append([]string{"CERBOS_NO_TELEMETRY=1"}, conf.Env...),
}

if conf.ConfFilePath != "" {
Expand Down

0 comments on commit 657a296

Please sign in to comment.