Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

Implement policy service for upserting and finding policies in an environment.

spinningbote7c9912201c0
diff --git a/api/policy.go b/api/policy.go
new file mode 100644
index 0000000000..5f5de1b03d
--- /dev/null
+++ b/api/policy.go
@@ -0,0 +1,61 @@
+package api
+
+import (
+ "context"
+)
+
+type Policy struct {
+ ID int `jsonapi:"primary,environment"`
+
+ // Standard fields
+ RowStatus RowStatus `jsonapi:"attr,rowStatus"`
+ CreatorId int
+ Creator *Principal `jsonapi:"attr,creator"`
+ CreatedTs int64 `jsonapi:"attr,createdTs"`
+ UpdaterId int
+ Updater *Principal `jsonapi:"attr,updater"`
+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`
+
+ // Related fields
+ EnvironmentId int `jsonapi:"attr,environmentId"`
+ // Do not return this to the client since the client always has the database context and fetching the
+ // database object and all its own related objects is a bit expensive.
+ Environment *Environment
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ Payload string `jsonapi:"attr,payload"`
+}
+
+// PolicyFind is the message to get a policy.
+type PolicyFind struct {
+ ID *int
+
+ // Related fields
+ EnvironmentId *int
+
+ // Domain specific fields
+ Name *string `jsonapi:"attr,name"`
+}
+
+// PolicyUpsert is the message to upsert a policy.
+// NOTE: We use PATCH for Upsert, this is inspired by https://google.aip.dev/134#patch-and-put
+type PolicyUpsert struct {
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ // CreatorId is the ID of the creator.
+ UpdaterId int
+
+ // Related fields
+ EnvironmentId int `jsonapi:"attr,environmentId"`
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ Payload string `jsonapi:"attr,payload"`
+}
+
+// PolicyService is the backend for policies.
+type PolicyService interface {
+ FindPolicy(ctx context.Context, find *PolicyFind) (*Policy, error)
+ UpsertPolicy(ctx context.Context, upsert *PolicyUpsert) (*Policy, error)
+}
diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sql
index daa2b506ae..a1cf540806 100644
--- a/store/migration/10001__init_schema.sql
+++ b/store/migration/10001__init_schema.sql
@@ -177,12 +177,14 @@ CREATE TABLE policy (
updater_id INTEGER NOT NULL REFERENCES principal (id),
updated_ts BIGINT NOT NULL DEFAULT (strftime('%s', 'now')),
environment_id INTEGER NOT NULL REFERENCES environment (id),
- type TEXT NOT NULL,
+ name TEXT NOT NULL,
payload TEXT NOT NULL
);
CREATE INDEX idx_policy_environment_id ON policy(environment_id);
+CREATE UNIQUE INDEX idx_policy_environment_id_name ON policy(environment_id, name);
+
INSERT INTO
sqlite_sequence (name, seq)
VALUES
diff --git a/store/policy.go b/store/policy.go
new file mode 100644
index 0000000000..0f1b2a6b1f
--- /dev/null
+++ b/store/policy.go
@@ -0,0 +1,175 @@
+package store
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/common"
+ "go.uber.org/zap"
+)
+
+var (
+ _ api.EnvironmentService = (*EnvironmentService)(nil)
+)
+
+// PolicyService represents a service for managing environment based policies.
+type PolicyService struct {
+ l *zap.Logger
+ db *DB
+
+ cache api.CacheService
+}
+
+// NewPolicyService returns a new instance of PolicyService.
+func NewPolicyService(logger *zap.Logger, db *DB, cache api.CacheService) *PolicyService {
+ return &PolicyService{l: logger, db: db, cache: cache}
+}
+
+// FindPolicy finds the policy for an environment.
+// Returns ENOTFOUND if no matching record.
+// Returns ECONFLICT if finding more than 1 matching records.
+func (s *PolicyService) FindPolicy(ctx context.Context, find *api.PolicyFind) (*api.Policy, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ list, err := s.findPolicy(ctx, tx, find)
+ if err != nil {
+ return nil, err
+ } else if len(list) == 0 {
+ return nil, &common.Error{Code: common.ENOTFOUND, Message: fmt.Sprintf("policy not found: %+v", find)}
+ } else if len(list) > 1 {
+ return nil, &common.Error{Code: common.ECONFLICT, Message: fmt.Sprintf("found %d policy with filter %+v, expect 1. ", len(list), find)}
+ }
+
+ return list[0], nil
+}
+
+func (s *PolicyService) findPolicy(ctx context.Context, tx *Tx, find *api.PolicyFind) (_ []*api.Policy, err error) {
+ // Build WHERE clause.
+ where, args := []string{"1 = 1"}, []interface{}{}
+ if v := find.ID; v != nil {
+ where, args = append(where, "id = ?"), append(args, *v)
+ }
+ if v := find.EnvironmentId; v != nil {
+ where, args = append(where, "environment_id = ?"), append(args, *v)
+ }
+ if v := find.Name; v != nil {
+ where, args = append(where, "name = ?"), append(args, *v)
+ }
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT
+ id,
+ creator_id,
+ created_ts,
+ updater_id,
+ updated_ts,
+ environment_id,
+ name,
+ payload
+ FROM policy
+ WHERE `+strings.Join(where, " AND "),
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+
+ // Iterate over result set and deserialize rows into list.
+ list := make([]*api.Policy, 0)
+ for rows.Next() {
+ var policy api.Policy
+ if err := rows.Scan(
+ &policy.ID,
+ &policy.CreatorId,
+ &policy.CreatedTs,
+ &policy.UpdaterId,
+ &policy.UpdatedTs,
+ &policy.Environment,
+ &policy.Name,
+ &policy.Payload,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ list = append(list, &policy)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return list, nil
+}
+
+// UpsertPolicy sets a policy for an environment.
+func (s *PolicyService) UpsertPolicy(ctx context.Context, upsert *api.PolicyUpsert) (*api.Policy, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer tx.Rollback()
+
+ policy, err := s.upsertPolicy(ctx, tx, upsert)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return policy, nil
+}
+
+// upsertPolicy updates an existing policy.
+func (s *PolicyService) upsertPolicy(ctx context.Context, tx *Tx, upsert *api.PolicyUpsert) (*api.Policy, error) {
+ // Upsert row into policy.
+ // TODO(spinningbot): fix the query.
+ row, err := tx.QueryContext(ctx, `
+ INSERT INTO policy (
+ creator_id,
+ updater_id,
+ environment_id,
+ name,
+ payload
+ )
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(environment_id, name) DO UPDATE SET
+ payload = excluded.payload
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, environment_id, name, payload
+ `,
+ upsert.UpdaterId,
+ upsert.UpdaterId,
+ upsert.EnvironmentId,
+ upsert.Name,
+ upsert.Payload,
+ )
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var policy api.Policy
+ if err := row.Scan(
+ &policy.ID,
+ &policy.CreatorId,
+ &policy.CreatedTs,
+ &policy.UpdaterId,
+ &policy.UpdatedTs,
+ &policy.EnvironmentId,
+ &policy.Name,
+ &policy.Payload,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &policy, nil
+}
diff --git a/store/seed/test/10050__environment.sql b/store/seed/test/10050__environment.sql
index 9b158e2c1d..d34ec55989 100644
--- a/store/seed/test/10050__environment.sql
+++ b/store/seed/test/10050__environment.sql
@@ -101,7 +101,7 @@ INSERT INTO
creator_id,
updater_id,
environment_id,
- type,
+ name,
payload
)
VALUES
@@ -111,5 +111,26 @@ VALUES
101,
5004,
'approval_policy',
- 'MANUAL_APPROVAL_ALWAYS'
+ 'MANUAL_APPROVAL_NEVER'
);
+
+INSERT INTO
+ policy (
+ id,
+ creator_id,
+ updater_id,
+ environment_id,
+ name,
+ payload
+ )
+VALUES
+ (
+ 1001,
+ 101,
+ 101,
+ 5004,
+ 'approval_policy',
+ 'MANUAL_APPROVAL_ALWAYS'
+ )
+ ON CONFLICT(environment_id, name) DO UPDATE SET
+ payload = excluded.payload;