Skip to content

Commit

Permalink
Applied Sergiusz suggestions
Browse files Browse the repository at this point in the history
Signed-off-by: jose.vazquez <jose.vazquez@mongodb.com>
  • Loading branch information
josvazg committed Jun 4, 2024
1 parent de8fccb commit d94928b
Show file tree
Hide file tree
Showing 9 changed files with 108 additions and 100 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -566,4 +566,4 @@ upload-sbom-to-silk: ## Upload a give SBOM (lite) to Silk
.PHONY: contract-tests
contract-tests: ## Run contract tests
go clean -testcache
AKO_CONTRACT_TEST=1 go test -race -cover ./test/contract/...
AKO_CONTRACT_TEST=1 go test -v -race -cover ./test/contract/...
54 changes: 54 additions & 0 deletions internal/translation/audit/audit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package audit

import (
"context"
"fmt"

"go.mongodb.org/atlas-sdk/v20231115008/admin"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/types"

"github.com/mongodb/mongodb-atlas-kubernetes/v2/internal/translation"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/pkg/controller/atlas"
)

// AuditLogService is the interface exposed by this translation layer over
// the Atlas AuditLog
type AuditLogService interface {
Get(ctx context.Context, projectID string) (*AuditConfig, error)
Set(ctx context.Context, projectID string, auditing *AuditConfig) error
}

// AuditLog is the default implementation of the AuditLogService using the Atlas SDK
type AuditLog struct {
auditAPI admin.AuditingApi
}

// NewAuditLogService creates an AuditLog from credentials and the atlas provider
func NewAuditLogService(ctx context.Context, provider atlas.Provider, secretRef *types.NamespacedName, log *zap.SugaredLogger) (*AuditLog, error) {
client, err := translation.NewVersionedClient(ctx, provider, secretRef, log)
if err != nil {
return nil, err
}
return NewAuditLog(client.AuditingApi), nil
}

// NewAuditLog wraps the SDK AuditingApi as an AuditLog
func NewAuditLog(api admin.AuditingApi) *AuditLog {
return &AuditLog{auditAPI: api}
}

// Get an Atlas Project audit log configuration
func (s *AuditLog) Get(ctx context.Context, projectID string) (*AuditConfig, error) {
auditLog, _, err := s.auditAPI.GetAuditingConfiguration(ctx, projectID).Execute()
if err != nil {
return nil, fmt.Errorf("failed to get audit log from Atlas: %w", err)
}
return fromAtlas(auditLog)
}

// Set an Atlas Project audit log configuration
func (s *AuditLog) Set(ctx context.Context, projectID string, auditing *AuditConfig) error {
_, _, err := s.auditAPI.UpdateAuditingConfiguration(ctx, projectID, toAtlas(auditing)).Execute()
return err
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package auditing
package audit

import (
"fmt"
Expand All @@ -16,14 +16,15 @@ const (
FilterJSON AuditingConfigType = "FILTER_JSON"
)

type Auditing struct {
// AuditConfig represents the Atlas Project audit log config
type AuditConfig struct {
Enabled bool
AuditAuthorizationSuccess bool
ConfigurationType AuditingConfigType
AuditFilter string
}

func toAtlas(auditing *Auditing) *admin.AuditLog {
func toAtlas(auditing *AuditConfig) *admin.AuditLog {
return &admin.AuditLog{
Enabled: pointer.MakePtr(auditing.Enabled),
AuditAuthorizationSuccess: pointer.MakePtr(auditing.AuditAuthorizationSuccess),
Expand All @@ -32,12 +33,12 @@ func toAtlas(auditing *Auditing) *admin.AuditLog {
}
}

func fromAtlas(auditLog *admin.AuditLog) (*Auditing, error) {
func fromAtlas(auditLog *admin.AuditLog) (*AuditConfig, error) {
cfgType, err := configTypeFromAtlas(auditLog.ConfigurationType)
if err != nil {
return nil, err
}
return &Auditing{
return &AuditConfig{
Enabled: pointer.GetOrDefault(auditLog.Enabled, false),
AuditAuthorizationSuccess: pointer.GetOrDefault(auditLog.AuditAuthorizationSuccess, false),
ConfigurationType: cfgType,
Expand Down
47 changes: 0 additions & 47 deletions internal/translation/auditing/auditing.go

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package auditing
package audit

import (
"context"
_ "embed"
"log"
"os"
"testing"
"time"

"github.com/mongodb/mongodb-atlas-kubernetes/v2/internal/translation/auditing"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/internal/translation/audit"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/test/helper/control"
"github.com/mongodb/mongodb-atlas-kubernetes/v2/test/helper/launcher"

Expand All @@ -30,19 +31,21 @@ func TestMain(m *testing.M) {
return
}
l := launcher.NewFromEnv(testVersion)
l.Launch(
if err := l.Launch(
testYml,
launcher.WaitReady("atlasprojects/my-project", 30*time.Second))
launcher.WaitReady("atlasprojects/my-project", time.Minute)); err != nil {
log.Fatalf("Failed to launch test bed: %v", err)
}
if !control.Enabled("SKIP_CLEANUP") { // allow to reuse Atlas resources for local tests
defer l.Cleanup()
}
m.Run()
os.Exit(m.Run())
}

func TestDefaultAuditingGet(t *testing.T) {
testProjectID := mustReadProjectID()
ctx := context.Background()
as := auditing.NewProductionAtlasAudit(contract.MustVersionedClient(t, ctx).AuditingApi)
as := audit.NewAuditLog(contract.MustVersionedClient(t, ctx).AuditingApi)

result, err := as.Get(ctx, testProjectID)

Expand All @@ -55,8 +58,8 @@ func TestDefaultAuditingGet(t *testing.T) {
assert.Equal(t, defaultAtlasAuditing(), result)
}

func defaultAtlasAuditing() *auditing.Auditing {
return &auditing.Auditing{
func defaultAtlasAuditing() *audit.AuditConfig {
return &audit.AuditConfig{
Enabled: false,
AuditAuthorizationSuccess: false,
AuditFilter: "",
Expand All @@ -66,51 +69,51 @@ func defaultAtlasAuditing() *auditing.Auditing {
func TestSyncs(t *testing.T) {
testCases := []struct {
title string
auditing *auditing.Auditing
auditing *audit.AuditConfig
}{
{
title: "Just enabled",
auditing: &auditing.Auditing{
auditing: &audit.AuditConfig{
Enabled: true,
AuditAuthorizationSuccess: false,
AuditFilter: "{}", // must sent empty JSON to overwrite previous state
},
},
{
title: "Auth success logs as well",
auditing: &auditing.Auditing{
auditing: &audit.AuditConfig{
Enabled: true,
AuditAuthorizationSuccess: true,
AuditFilter: "{}",
},
},
{
title: "With a filter",
auditing: &auditing.Auditing{
auditing: &audit.AuditConfig{
Enabled: true,
AuditAuthorizationSuccess: false,
AuditFilter: `{"atype":"authenticate"}`,
},
},
{
title: "With a filter and success logs",
auditing: &auditing.Auditing{
auditing: &audit.AuditConfig{
Enabled: true,
AuditAuthorizationSuccess: true,
AuditFilter: `{"atype":"authenticate"}`,
},
},
{
title: "All set but disabled",
auditing: &auditing.Auditing{
auditing: &audit.AuditConfig{
Enabled: false,
AuditAuthorizationSuccess: true,
AuditFilter: `{"atype":"authenticate"}`,
},
},
{
title: "Default (disabled) case",
auditing: &auditing.Auditing{
auditing: &audit.AuditConfig{
Enabled: false,
AuditAuthorizationSuccess: false,
AuditFilter: "{}",
Expand All @@ -119,7 +122,7 @@ func TestSyncs(t *testing.T) {
}
testProjectID := mustReadProjectID()
ctx := context.Background()
as := auditing.NewProductionAtlasAudit(contract.MustVersionedClient(t, ctx).AuditingApi)
as := audit.NewAuditLog(contract.MustVersionedClient(t, ctx).AuditingApi)

for _, tc := range testCases {
t.Run(tc.title, func(t *testing.T) {
Expand Down
File renamed without changes.
6 changes: 3 additions & 3 deletions test/helper/launcher/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ type AtlasCredentials struct {

func credentialsFromEnv() AtlasCredentials {
return AtlasCredentials{
OrgID: MustSetEnv("MCLI_ORG_ID"),
PublicKey: MustSetEnv("MCLI_PUBLIC_API_KEY"),
PrivateKey: MustSetEnv("MCLI_PRIVATE_API_KEY"),
OrgID: MustLookupEnv("MCLI_ORG_ID"),
PublicKey: MustLookupEnv("MCLI_PUBLIC_API_KEY"),
PrivateKey: MustLookupEnv("MCLI_PRIVATE_API_KEY"),
}
}
48 changes: 22 additions & 26 deletions test/helper/launcher/launcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,12 @@ import (
)

const (
ExpectedContext = "kind-kind"

ExpectedContext = "kind-kind"
LauncherTestInstall = "test-ako"

HelmRepoURL = "https://mongodb.github.io/helm-charts"

RepoRef = "mongodb"

OperatorChart = "mongodb-atlas-operator"

AtlasURI = "https://cloud-qa.mongodb.com"

HelmRepoURL = "https://mongodb.github.io/helm-charts"
RepoRef = "mongodb"
OperatorChart = "mongodb-atlas-operator"
AtlasURI = "https://cloud-qa.mongodb.com"
// #nosec G101 -- This is just a name
AtlasSecretName = "mongodb-atlas-operator-api-key"
)
Expand All @@ -47,8 +41,8 @@ func NewFromEnv(version string) *Launcher {
return NewLauncher(credentialsFromEnv(), version, true)
}

// MustSetEnv sets the env var value given, or panics if the env var is not set
func MustSetEnv(envvar string) string {
// MustLookupEnv sets the env var value given, or panics if the env var is not set
func MustLookupEnv(envvar string) string {
value, ok := os.LookupEnv(envvar)
if !ok {
panic(fmt.Errorf("environment variable %s not set", envvar))
Expand All @@ -59,16 +53,16 @@ func MustSetEnv(envvar string) string {
// Launch will try to launch the operator and apply the given YAML for it to handle
func (l *Launcher) Launch(yml string, waitCfg *WaitConfig) error {
if err := l.ensureK8sCluster(); err != nil {
return err
return fmt.Errorf("failed to setup Kubernetes cluster: %w", err)
}
if err := l.ensureOperator(); err != nil {
return err
return fmt.Errorf("failed to setup Atlas Kubernetes Operator: %w", err)
}
if err := l.ensureAtlasSecret(); err != nil {
return err
return fmt.Errorf("failed to setup Atlas Secrets: %w", err)
}
if err := l.kubeApply(yml); err != nil {
return err
return fmt.Errorf("failed to setup Kubernetes resources: %w", err)
}
l.appliedYAMLs = append(l.appliedYAMLs, yml)
return l.kubeWait(waitCfg)
Expand All @@ -85,12 +79,12 @@ func (l *Launcher) Cleanup() error {
}
if l.clearOperator {
if err := l.uninstall(); err != nil {
return err
return fmt.Errorf("failed to uninstall Atlas operator: %w", err)
}
}
if l.clearSecret {
if err := l.kubeDeleteAtlasSecret(); err != nil {
return err
return fmt.Errorf("failed to delete Atlas secrets: %w", err)
}
}
if l.clearKind {
Expand All @@ -113,10 +107,11 @@ func (l *Launcher) isKubeConfigAvailable() bool {

func (l *Launcher) startKind() error {
err := l.silentRun("kind", "create", "cluster")
if err == nil {
l.clearKind = true
if err != nil {
return fmt.Errorf("failed to start kind: %w", err)
}
return err
l.clearKind = true
return nil
}

func (l *Launcher) stopKind() error {
Expand Down Expand Up @@ -167,10 +162,11 @@ func (l *Launcher) install() error {
}
err = l.silentRun("helm", "install", LauncherTestInstall, path.Join(RepoRef, OperatorChart),
"--version", l.version, "--atomic", "--set", fmt.Sprintf("atlasURI=%s", AtlasURI))
if err == nil {
l.clearOperator = true
if err != nil {
return fmt.Errorf("failed to install operator: %w", err)
}
return err
l.clearOperator = true
return nil
}

func (l *Launcher) uninstall() error {
Expand All @@ -194,7 +190,7 @@ func (l *Launcher) kubeCreateAtlasSecret() error {
fmt.Sprintf("--from-literal=orgId=%s", l.credentials.OrgID),
fmt.Sprintf("--from-literal=publicApiKey=%s", l.credentials.PublicKey),
fmt.Sprintf("--from-literal=privateApiKey=%s", l.credentials.PrivateKey)); err != nil {
return err
return fmt.Errorf("failed to create secret: %w", err)
}
return l.silentRun("kubectl", "label", "secret", AtlasSecretName, "atlas.mongodb.com/type=credentials")
}
Expand Down
Loading

0 comments on commit d94928b

Please sign in to comment.