Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support service account in backend (#3536)
ecmadao331a7c6925b7
diff --git a/api/principal.go b/api/principal.goindex d59deeb69e..f2b53581e1 100644--- a/api/principal.go+++ b/api/principal.go@@ -13,6 +13,8 @@ type PrincipalType stringconst (// EndUser is the principal type for END_USER.EndUser PrincipalType = "END_USER"+ // ServiceAccount is the principal type for SERVICE_ACCOUNT.+ ServiceAccount PrincipalType = "SERVICE_ACCOUNT"// BOT is the principal type for BOT.BOT PrincipalType = "BOT")@@ -48,31 +50,36 @@ type Principal struct {// Role is stored in the member table, but we include it when returning the principal.// This simplifies the client code where it won't require order dependency to fetch the related member info first.Role Role `jsonapi:"attr,role"`+ // The ServiceKey is the password, only used for SERVICE_ACCOUNT.+ // We only return the service key for the first time after the creation for SERVICE_ACCOUNT.+ ServiceKey string `jsonapi:"attr,serviceKey"`}// MarshalJSON customizes the Principal Marshal method so the returned object// can map directly to the frontend Principal object without any conversion.func (p *Principal) MarshalJSON() ([]byte, error) {return json.Marshal(&struct {- ID int `json:"id"`- CreatorID int `json:"creatorId"`- CreatedTs int64 `json:"createdTs"`- UpdaterID int `json:"updaterId"`- UpdatedTs int64 `json:"updatedTs"`- Type PrincipalType `json:"type"`- Name string `json:"name"`- Email string `json:"email"`- Role Role `json:"role"`+ ID int `json:"id"`+ CreatorID int `json:"creatorId"`+ CreatedTs int64 `json:"createdTs"`+ UpdaterID int `json:"updaterId"`+ UpdatedTs int64 `json:"updatedTs"`+ Type PrincipalType `json:"type"`+ Name string `json:"name"`+ Email string `json:"email"`+ Role Role `json:"role"`+ ServiceKey string `json:"serviceKey"`}{- ID: p.ID,- CreatorID: p.CreatorID,- CreatedTs: p.CreatedTs,- UpdaterID: p.UpdaterID,- UpdatedTs: p.UpdatedTs,- Type: p.Type,- Name: p.Name,- Email: p.Email,- Role: p.Role,+ ID: p.ID,+ CreatorID: p.CreatorID,+ CreatedTs: p.CreatedTs,+ UpdaterID: p.UpdaterID,+ UpdatedTs: p.UpdatedTs,+ Type: p.Type,+ Name: p.Name,+ Email: p.Email,+ Role: p.Role,+ ServiceKey: p.ServiceKey,})}@@ -84,10 +91,10 @@ type PrincipalCreate struct {CreatorID int// Domain specific fields- Type PrincipalType- Name string `jsonapi:"attr,name"`- Email string `jsonapi:"attr,email"`- Password string `jsonapi:"attr,password"`+ Type PrincipalType `jsonapi:"attr,type"`+ Name string `jsonapi:"attr,name"`+ Email string `jsonapi:"attr,email"`+ Password string `jsonapi:"attr,password"`PasswordHash string}@@ -116,8 +123,11 @@ type PrincipalPatch struct {UpdaterID int// Domain specific fields- Name *string `jsonapi:"attr,name"`- Email *string `jsonapi:"attr,email"`- Password *string `jsonapi:"attr,password"`+ Type PrincipalType `jsonapi:"attr,type"`+ Name *string `jsonapi:"attr,name"`+ Email *string `jsonapi:"attr,email"`+ Password *string `jsonapi:"attr,password"`PasswordHash *string+ // RefreshKey is used by SERVICE_ACCOUNT to refresh its password+ RefreshKey bool `jsonapi:"attr,refreshKey"`}diff --git a/server/jwt.go b/server/jwt.goindex d2a6e501d2..2c7f7f7d01 100644--- a/server/jwt.go+++ b/server/jwt.go@@ -33,6 +33,7 @@ const (// Expiration section.refreshThresholdDuration = 1 * time.HouraccessTokenDuration = 24 * time.Hour+ apiTokenDuration = 2 * time.HourrefreshTokenDuration = 7 * 24 * time.Hour// Make cookie expire slightly earlier than the jwt expiration. Client would be logged out if the user// cookie expires, thus the client would always logout first before attempting to make a request with the expired jwt.@@ -79,6 +80,11 @@ func GenerateTokensAndSetCookies(c echo.Context, user *api.Principal, mode commoreturn nil}+func generateAPIToken(user *api.Principal, mode common.ReleaseMode, secret string) (string, error) {+ expirationTime := time.Now().Add(apiTokenDuration)+ return generateToken(user, fmt.Sprintf(accessTokenAudienceFmt, mode), expirationTime, []byte(secret))+}+func generateAccessToken(user *api.Principal, mode common.ReleaseMode, secret string) (string, error) {expirationTime := time.Now().Add(accessTokenDuration)return generateToken(user, fmt.Sprintf(accessTokenAudienceFmt, mode), expirationTime, []byte(secret))diff --git a/server/openapi_auth.go b/server/openapi_auth.goindex b6a83ee27c..60e54ccfc6 100644--- a/server/openapi_auth.go+++ b/server/openapi_auth.go@@ -54,7 +54,7 @@ func (s *Server) openAPIUserLogin(c echo.Context) error {return echo.NewHTTPError(http.StatusUnauthorized, "This user has been deactivated by the admin")}- accessToken, err := generateAccessToken(user, s.profile.Mode, s.secret)+ accessToken, err := generateAPIToken(user, s.profile.Mode, s.secret)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token").SetInternal(err)}diff --git a/server/principal.go b/server/principal.goindex 996630c96b..d9f81ae411 100644--- a/server/principal.go+++ b/server/principal.go@@ -22,7 +22,15 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {}principalCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)- principalCreate.Type = api.EndUser++ if principalCreate.Type == api.ServiceAccount {+ pwd, err := common.RandomString(20)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access key for service account.").SetInternal(err)+ }+ principalCreate.Password = fmt.Sprintf("bbs_%s", pwd)+ }+passwordHash, err := bcrypt.GenerateFromPassword([]byte(principalCreate.Password), bcrypt.DefaultCost)if err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash").SetInternal(err)@@ -39,6 +47,11 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {// Assign Developer role to the just created principalprincipal.Role = api.Developer+ // Only return the token if the user is ServiceAccount+ if principal.Type == api.ServiceAccount {+ principal.ServiceKey = principalCreate.Password+ }+c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, principal); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal create principal response").SetInternal(err)@@ -96,6 +109,16 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {if err := jsonapi.UnmarshalPayload(c.Request().Body, principalPatch); err != nil {return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch principal request").SetInternal(err)}++ if principalPatch.Type == api.ServiceAccount && principalPatch.RefreshKey {+ val, err := common.RandomString(20)+ if err != nil {+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access key for service account.").SetInternal(err)+ }+ password := fmt.Sprintf("bbs_%s", val)+ principalPatch.Password = &password+ }+if principalPatch.Password != nil && *principalPatch.Password != "" {passwordHash, err := bcrypt.GenerateFromPassword([]byte(*principalPatch.Password), bcrypt.DefaultCost)if err != nil {@@ -113,6 +136,11 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to patch principal ID: %v", id)).SetInternal(err)}+ // Only return the token if the user is ServiceAccount+ if principal.Type == api.ServiceAccount && principalPatch.Password != nil {+ principal.ServiceKey = *principalPatch.Password+ }+c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)if err := jsonapi.MarshalPayload(c.Response().Writer, principal); err != nil {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to marshal principal ID response: %v", id)).SetInternal(err)diff --git a/store/migration/dev/20221126000000##principal_type.sql b/store/migration/dev/20221126000000##principal_type.sqlnew file mode 100644index 0000000000..5342038b9a--- /dev/null+++ b/store/migration/dev/20221126000000##principal_type.sql@@ -0,0 +1,2 @@+ALTER TABLE principal DROP CONSTRAINT principal_type_check;+ALTER TABLE principal ADD CONSTRAINT principal_type_check CHECK (type IN ('END_USER', 'SYSTEM_BOT', 'SERVICE_ACCOUNT'));diff --git a/store/migration/dev/LATEST.sql b/store/migration/dev/LATEST.sqlindex 39c707e5c8..bcaa7a7208 100644--- a/store/migration/dev/LATEST.sql+++ b/store/migration/dev/LATEST.sql@@ -18,7 +18,7 @@ CREATE TABLE principal (created_ts BIGINT NOT NULL DEFAULT extract(epoch from now()),updater_id INTEGER NOT NULL REFERENCES principal (id),updated_ts BIGINT NOT NULL DEFAULT extract(epoch from now()),- type TEXT NOT NULL CHECK (type IN ('END_USER', 'SYSTEM_BOT')),+ type TEXT NOT NULL CHECK (type IN ('END_USER', 'SYSTEM_BOT', 'SERVICE_ACCOUNT')),name TEXT NOT NULL,email TEXT NOT NULL,password_hash TEXT NOT NULLdiff --git a/store/principal.go b/store/principal.goindex db8e5e8a7e..0d67b6e432 100644--- a/store/principal.go+++ b/store/principal.go@@ -78,7 +78,9 @@ func (s *Store) GetPrincipalList(ctx context.Context) ([]*api.Principal, error)if err != nil {return nil, errors.Wrapf(err, "failed to compose Principal role with principalRaw[%+v]", raw)}- principalList = append(principalList, principal)+ if principal != nil {+ principalList = append(principalList, principal)+ }}return principalList, nil}