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

feat: store audits on mongodb #427

Merged
merged 27 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
dcfce6c
feat: env var management
fredmaggiowski Jan 15, 2025
bd44cd4
refactor: unified mongodb type definition and simplified mongodb test…
fredmaggiowski Jan 17, 2025
e15fafb
feat: mongodb agent
fredmaggiowski Jan 17, 2025
7068397
compount agent poc + multiple modes support
fredmaggiowski Jan 17, 2025
f55c671
fix log agent log
fredmaggiowski Jan 17, 2025
9012caf
refactor: agent pool renaming
fredmaggiowski Jan 17, 2025
f033642
gosec notice
fredmaggiowski Jan 20, 2025
4590cca
Merge branch 'main' into feat/store-audits-on-mongodb
fredmaggiowski Jan 20, 2025
21c30c6
refactor
fredmaggiowski Jan 20, 2025
727b850
test: compound log agent tests
fredmaggiowski Jan 20, 2025
8e425a4
refactor: using const
fredmaggiowski Jan 20, 2025
7d951a2
refactor: using const
fredmaggiowski Jan 20, 2025
9db68fd
refactor: sorted main imports
fredmaggiowski Jan 20, 2025
16fc728
Update main.go
fredmaggiowski Jan 20, 2025
af49638
test builting
fredmaggiowski Jan 20, 2025
f882971
parse error config test
fredmaggiowski Jan 20, 2025
c6e5047
def conde
fredmaggiowski Jan 20, 2025
ecdf4eb
license comment
fredmaggiowski Jan 20, 2025
926e2b0
insert one error simulation
fredmaggiowski Jan 20, 2025
bfb5a62
fix typo
fredmaggiowski Jan 20, 2025
7132787
refactor: init ordre
fredmaggiowski Jan 20, 2025
7f1f85d
refactor: import order
fredmaggiowski Jan 20, 2025
ca6eae6
fix: CompoundAgent#Trace returns error if no agent is set
fredmaggiowski Jan 20, 2025
4458260
refactor: empty lines removed
fredmaggiowski Jan 20, 2025
3f64976
use math/rand instead of exp/rand
fredmaggiowski Jan 20, 2025
627e75d
use math/rand instead of exp/rand
fredmaggiowski Jan 20, 2025
1762dcf
math rand usage
fredmaggiowski Jan 20, 2025
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
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ all: test

.PHONY: mongo-start
mongo-start:
docker run --rm --name mongo -p 27017:27017 -d mongo
docker run --rm --name mongo -p 27017:27017 -d mongo:8

.PHONY: test
test: clean mongo-start
Expand All @@ -39,3 +39,7 @@ version:
git add "Dockerfile"
git commit -m "v${VERSION}"
git tag v${VERSION}

.PHONY: runlocal
runlocal:
@set -a && source ./default.env && go run .
22 changes: 8 additions & 14 deletions custom_builtins/mongoclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (

"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)

func TestNewMongoClient(t *testing.T) {
Expand Down Expand Up @@ -66,7 +67,7 @@ func TestGetMongoCollectionFromContext(t *testing.T) {

func TestMongoFindOne(t *testing.T) {
log := logging.NewNoOpLogger()
mongoDBURL, dbName := getMongoDBURL(t)
mongoDBURL := testutils.GetMongoDBURL(t)
client, err := mongoclient.NewMongoClient(log, mongoDBURL, mongoclient.ConnectionOpts{})
require.NoError(t, err)
defer client.Disconnect()
Expand All @@ -75,7 +76,7 @@ func TestMongoFindOne(t *testing.T) {
require.NoError(t, err)

collectionName := "my-collection"
populateCollection(t, dbName, collectionName)
populateCollection(t, client.Collection(collectionName))

t.Run("finds a document", func(t *testing.T) {
result, err := mongoClient.FindOne(context.Background(), collectionName, map[string]interface{}{
Expand Down Expand Up @@ -108,16 +109,14 @@ func TestMongoFindOne(t *testing.T) {

func TestMongoFindMany(t *testing.T) {
log := logging.NewNoOpLogger()
mongoDBURL, dbName := getMongoDBURL(t)
client, err := mongoclient.NewMongoClient(log, mongoDBURL, mongoclient.ConnectionOpts{})
require.NoError(t, err)
defer client.Disconnect()
client, dbName := testutils.GetAndDisposeMongoClient(t)

mongoClient, err := NewMongoClient(log, client)
clientWrapper := &testutils.MockMongoClient{ActualClient: client, DBName: dbName}
mongoClient, err := NewMongoClient(log, clientWrapper)
require.NoError(t, err)

collectionName := "my-collection"
populateCollection(t, dbName, collectionName)
populateCollection(t, client.Database(dbName).Collection(collectionName))

t.Run("finds multiple documents", func(t *testing.T) {
result, err := mongoClient.FindMany(context.Background(), collectionName, map[string]interface{}{
Expand Down Expand Up @@ -166,14 +165,10 @@ func TestMongoFindMany(t *testing.T) {
})
}

func populateCollection(t *testing.T, dbName string, collectionName string) {
func populateCollection(t *testing.T, collection *mongo.Collection) {
t.Helper()

client := testutils.GetMongoClient(t)
ctx := context.Background()

db := client.Database(dbName)
collection := db.Collection(collectionName)
_, err := collection.DeleteMany(ctx, bson.D{})
require.NoError(t, err)
_, err = collection.InsertMany(ctx, []interface{}{
Expand All @@ -198,7 +193,6 @@ func populateCollection(t *testing.T, dbName string, collectionName string) {

t.Cleanup(func() {
collection.Drop(ctx)
db.Drop(ctx)
})
}

Expand Down
3 changes: 3 additions & 0 deletions default.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
OPA_MODULES_DIRECTORY=./mocks/rego-policies
TARGET_SERVICE_HOST=localhost:9090
API_PERMISSIONS_FILE_PATH=./mocks/simplifiedMock.json
13 changes: 7 additions & 6 deletions internal/audit/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import "context"
type Labels = map[string]any

type Agent interface {
Trace(context.Context, Audit)
Trace(context.Context, Audit) error
Cache() AuditCache
}

Expand All @@ -28,13 +28,14 @@ type AgentPool interface {
}

// noopAgent is a lazy agent that does nothing :(
type noopAgent struct{}

func (a *noopAgent) Trace(context.Context, Audit) error { return nil }
func (a *noopAgent) Cache() AuditCache { return &SingleRecordCache{} }

// noopAgentPool is a lazy agent pool that returns noopAgent :D
type noopAgentPool struct{}

func (p *noopAgentPool) New() Agent { return &noopAgent{} }

func NewNoopAgentPool() AgentPool { return &noopAgentPool{} }

type noopAgent struct{}

func (a *noopAgent) Trace(context.Context, Audit) {}
func (a *noopAgent) Cache() AuditCache { return &SingleRecordCache{} }
83 changes: 83 additions & 0 deletions internal/audit/agent_compound.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// Copyright 2025 Mia srl
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package audit

import (
"context"
"fmt"
)

var ErrNoAgents = fmt.Errorf("no audit agents provided")

type compoundAgent struct {
agents []Agent
}

func newCompoundAgent(agents ...Agent) Agent {
return &compoundAgent{agents: agents}
}

func (c *compoundAgent) Trace(ctx context.Context, a Audit) error {
if len(c.agents) == 0 {
return ErrNoAgents
}

var errors []error
for _, agent := range c.agents {
if err := agent.Trace(ctx, a); err != nil {
errors = append(errors, err)
}
}

if len(errors) > 0 {
errString := ""
for i, err := range errors {
errString += err.Error()
if i < len(errors)-1 {
errString += "; "
}
}
return fmt.Errorf("%d/%d agents failed to trace: %s", len(errors), len(c.agents), errString)
}
return nil
}

func (c *compoundAgent) Cache() AuditCache {
return &compoundAuditCache{
agents: c.agents,
}
}

type compoundAuditCache struct {
agents []Agent
}

func (c *compoundAuditCache) Store(d Data) {
for _, agent := range c.agents {
agent.Cache().Store(d)
}
}

func (c *compoundAuditCache) Load() Data {
dataToReturn := make(Data)
for _, agent := range c.agents {
if data := agent.Cache().Load(); data != nil {
for k, v := range data {
dataToReturn[k] = v
}
}
}
return dataToReturn
}
Loading
Loading