Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat(serviceaccount): domain changes for service account (#10568)

Vikrant Gupta92d220c4d914
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index 1b2100b904..30e0707b0a 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -1768,19 +1768,19 @@ components:
createdAt:
format: date-time
type: string
- expires_at:
+ expiresAt:
minimum: 0
type: integer
id:
type: string
key:
type: string
- last_used:
+ lastObservedAt:
format: date-time
type: string
name:
type: string
- service_account_id:
+ serviceAccountId:
type: string
updatedAt:
format: date-time
@@ -1788,9 +1788,9 @@ components:
required:
- id
- key
- - expires_at
- - last_used
- - service_account_id
+ - expiresAt
+ - lastObservedAt
+ - serviceAccountId
type: object
ServiceaccounttypesGettableFactorAPIKeyWithKey:
properties:
@@ -1804,14 +1804,14 @@ components:
type: object
ServiceaccounttypesPostableFactorAPIKey:
properties:
- expires_at:
+ expiresAt:
minimum: 0
type: integer
name:
type: string
required:
- name
- - expires_at
+ - expiresAt
type: object
ServiceaccounttypesPostableServiceAccount:
properties:
@@ -1833,13 +1833,16 @@ components:
createdAt:
format: date-time
type: string
+ deletedAt:
+ format: date-time
+ type: string
email:
type: string
id:
type: string
name:
type: string
- orgID:
+ orgId:
type: string
roles:
items:
@@ -1856,18 +1859,19 @@ components:
- email
- roles
- status
- - orgID
+ - orgId
+ - deletedAt
type: object
ServiceaccounttypesUpdatableFactorAPIKey:
properties:
- expires_at:
+ expiresAt:
minimum: 0
type: integer
name:
type: string
required:
- name
- - expires_at
+ - expiresAt
type: object
ServiceaccounttypesUpdatableServiceAccount:
properties:
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index 1db2243316..56d6953e87 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -2100,7 +2100,7 @@ export interface ServiceaccounttypesFactorAPIKeyDTO {
* @type integer
* @minimum 0
*/
- expires_at: number;
+ expiresAt: number;
/**
* @type string
*/
@@ -2113,7 +2113,7 @@ export interface ServiceaccounttypesFactorAPIKeyDTO {
* @type string
* @format date-time
*/
- last_used: Date;
+ lastObservedAt: Date;
/**
* @type string
*/
@@ -2121,7 +2121,7 @@ export interface ServiceaccounttypesFactorAPIKeyDTO {
/**
* @type string
*/
- service_account_id: string;
+ serviceAccountId: string;
/**
* @type string
* @format date-time
@@ -2145,7 +2145,7 @@ export interface ServiceaccounttypesPostableFactorAPIKeyDTO {
* @type integer
* @minimum 0
*/
- expires_at: number;
+ expiresAt: number;
/**
* @type string
*/
@@ -2173,6 +2173,11 @@ export interface ServiceaccounttypesServiceAccountDTO {
* @format date-time
*/
createdAt?: Date;
+ /**
+ * @type string
+ * @format date-time
+ */
+ deletedAt: Date;
/**
* @type string
*/
@@ -2188,7 +2193,7 @@ export interface ServiceaccounttypesServiceAccountDTO {
/**
* @type string
*/
- orgID: string;
+ orgId: string;
/**
* @type array
*/
@@ -2209,7 +2214,7 @@ export interface ServiceaccounttypesUpdatableFactorAPIKeyDTO {
* @type integer
* @minimum 0
*/
- expires_at: number;
+ expiresAt: number;
/**
* @type string
*/
diff --git a/pkg/modules/serviceaccount/implserviceaccount/handler.go b/pkg/modules/serviceaccount/implserviceaccount/handler.go
index 51973dbdf2..38b2db0683 100644
--- a/pkg/modules/serviceaccount/implserviceaccount/handler.go
+++ b/pkg/modules/serviceaccount/implserviceaccount/handler.go
@@ -111,7 +111,12 @@ func (handler *handler) Update(rw http.ResponseWriter, r *http.Request) {
return
}
- serviceAccount.Update(req.Name, req.Email, req.Roles)
+ err = serviceAccount.Update(req.Name, req.Email, req.Roles)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
err = handler.module.Update(ctx, valuer.MustNewUUID(claims.OrgID), serviceAccount)
if err != nil {
render.Error(rw, err)
@@ -147,7 +152,12 @@ func (handler *handler) UpdateStatus(rw http.ResponseWriter, r *http.Request) {
return
}
- serviceAccount.UpdateStatus(req.Status)
+ err = serviceAccount.UpdateStatus(req.Status)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
err = handler.module.UpdateStatus(ctx, valuer.MustNewUUID(claims.OrgID), serviceAccount)
if err != nil {
render.Error(rw, err)
@@ -290,7 +300,7 @@ func (handler *handler) UpdateFactorAPIKey(rw http.ResponseWriter, r *http.Reque
}
factorAPIKey.Update(req.Name, req.ExpiresAt)
- err = handler.module.UpdateFactorAPIKey(ctx, serviceAccount.ID, factorAPIKey)
+ err = handler.module.UpdateFactorAPIKey(ctx, valuer.MustNewUUID(claims.OrgID), serviceAccount.ID, factorAPIKey)
if err != nil {
render.Error(rw, err)
return
diff --git a/pkg/modules/serviceaccount/implserviceaccount/module.go b/pkg/modules/serviceaccount/implserviceaccount/module.go
index 7cde1e0765..d07fdcde08 100644
--- a/pkg/modules/serviceaccount/implserviceaccount/module.go
+++ b/pkg/modules/serviceaccount/implserviceaccount/module.go
@@ -5,6 +5,7 @@ import (
"github.com/SigNoz/signoz/pkg/authz"
"github.com/SigNoz/signoz/pkg/emailing"
+ "github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/modules/serviceaccount"
"github.com/SigNoz/signoz/pkg/types/authtypes"
@@ -60,6 +61,24 @@ func (module *module) Create(ctx context.Context, orgID valuer.UUID, serviceAcco
return nil
}
+func (module *module) GetOrCreate(ctx context.Context, serviceAccount *serviceaccounttypes.ServiceAccount) (*serviceaccounttypes.ServiceAccount, error) {
+ existingServiceAccount, err := module.store.GetActiveByOrgIDAndName(ctx, serviceAccount.OrgID, serviceAccount.Name)
+ if err != nil && !errors.Ast(err, errors.TypeNotFound) {
+ return nil, err
+ }
+
+ if existingServiceAccount != nil {
+ return serviceAccount, nil
+ }
+
+ err = module.Create(ctx, serviceAccount.OrgID, serviceAccount)
+ if err != nil {
+ return nil, err
+ }
+
+ return serviceAccount, nil
+}
+
func (module *module) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*serviceaccounttypes.ServiceAccount, error) {
storableServiceAccount, err := module.store.Get(ctx, orgID, id)
if err != nil {
@@ -171,26 +190,28 @@ func (module *module) Update(ctx context.Context, orgID valuer.UUID, input *serv
}
func (module *module) UpdateStatus(ctx context.Context, orgID valuer.UUID, input *serviceaccounttypes.ServiceAccount) error {
- serviceAccount, err := module.Get(ctx, orgID, input.ID)
+ err := module.authz.Revoke(ctx, orgID, input.Roles, authtypes.MustNewSubject(authtypes.TypeableServiceAccount, input.ID.String(), orgID, nil))
if err != nil {
return err
}
- if input.Status == serviceAccount.Status {
- return nil
- }
-
- switch input.Status {
- case serviceaccounttypes.StatusActive:
- err := module.activateServiceAccount(ctx, orgID, input)
+ err = module.store.RunInTx(ctx, func(ctx context.Context) error {
+ // revoke all the API keys on disable
+ err := module.store.RevokeAllFactorAPIKeys(ctx, input.ID)
if err != nil {
return err
}
- case serviceaccounttypes.StatusDisabled:
- err := module.disableServiceAccount(ctx, orgID, input)
+
+ // update the status but do not delete the role mappings as we will use them for audits
+ err = module.store.Update(ctx, orgID, serviceaccounttypes.NewStorableServiceAccount(input))
if err != nil {
return err
}
+
+ return nil
+ })
+ if err != nil {
+ return err
}
return nil
@@ -276,8 +297,13 @@ func (module *module) ListFactorAPIKey(ctx context.Context, serviceAccountID val
return serviceaccounttypes.NewFactorAPIKeyFromStorables(storables), nil
}
-func (module *module) UpdateFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID, factorAPIKey *serviceaccounttypes.FactorAPIKey) error {
- return module.store.UpdateFactorAPIKey(ctx, serviceAccountID, serviceaccounttypes.NewStorableFactorAPIKey(factorAPIKey))
+func (module *module) UpdateFactorAPIKey(ctx context.Context, _ valuer.UUID, serviceAccountID valuer.UUID, factorAPIKey *serviceaccounttypes.FactorAPIKey) error {
+ err := module.store.UpdateFactorAPIKey(ctx, serviceAccountID, serviceaccounttypes.NewStorableFactorAPIKey(factorAPIKey))
+ if err != nil {
+ return err
+ }
+
+ return nil
}
func (module *module) RevokeFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID, id valuer.UUID) error {
@@ -307,45 +333,3 @@ func (module *module) RevokeFactorAPIKey(ctx context.Context, serviceAccountID v
return nil
}
-
-func (module *module) disableServiceAccount(ctx context.Context, orgID valuer.UUID, input *serviceaccounttypes.ServiceAccount) error {
- err := module.authz.Revoke(ctx, orgID, input.Roles, authtypes.MustNewSubject(authtypes.TypeableServiceAccount, input.ID.String(), orgID, nil))
- if err != nil {
- return err
- }
-
- err = module.store.RunInTx(ctx, func(ctx context.Context) error {
- // revoke all the API keys on disable
- err := module.store.RevokeAllFactorAPIKeys(ctx, input.ID)
- if err != nil {
- return err
- }
-
- // update the status but do not delete the role mappings as we will reuse them on activation.
- err = module.Update(ctx, orgID, input)
- if err != nil {
- return err
- }
-
- return nil
- })
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (module *module) activateServiceAccount(ctx context.Context, orgID valuer.UUID, input *serviceaccounttypes.ServiceAccount) error {
- err := module.authz.Grant(ctx, orgID, input.Roles, authtypes.MustNewSubject(authtypes.TypeableServiceAccount, input.ID.String(), orgID, nil))
- if err != nil {
- return err
- }
-
- err = module.Update(ctx, orgID, input)
- if err != nil {
- return err
- }
-
- return nil
-}
diff --git a/pkg/modules/serviceaccount/implserviceaccount/store.go b/pkg/modules/serviceaccount/implserviceaccount/store.go
index 3362d30222..82244a0512 100644
--- a/pkg/modules/serviceaccount/implserviceaccount/store.go
+++ b/pkg/modules/serviceaccount/implserviceaccount/store.go
@@ -48,6 +48,25 @@ func (store *store) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID)
return storable, nil
}
+func (store *store) GetActiveByOrgIDAndName(ctx context.Context, orgID valuer.UUID, name string) (*serviceaccounttypes.StorableServiceAccount, error) {
+ storable := new(serviceaccounttypes.StorableServiceAccount)
+
+ err := store.
+ sqlstore.
+ BunDBCtx(ctx).
+ NewSelect().
+ Model(storable).
+ Where("org_id = ?", orgID).
+ Where("name = ?", name).
+ Where("status = ?", serviceaccounttypes.StatusActive).
+ Scan(ctx)
+ if err != nil {
+ return nil, store.sqlstore.WrapNotFoundErrf(err, serviceaccounttypes.ErrCodeServiceAccountNotFound, "service account with name: %s doesn't exist in org: %s", name, orgID.String())
+ }
+
+ return storable, nil
+}
+
func (store *store) GetByID(ctx context.Context, id valuer.UUID) (*serviceaccounttypes.StorableServiceAccount, error) {
storable := new(serviceaccounttypes.StorableServiceAccount)
@@ -188,7 +207,7 @@ func (store *store) CreateFactorAPIKey(ctx context.Context, storable *serviceacc
Model(storable).
Exec(ctx)
if err != nil {
- return store.sqlstore.WrapAlreadyExistsErrf(err, serviceaccounttypes.ErrCodeServiceAccountFactorAPIKeyAlreadyExists, "api key with name: %s already exists for service account: %s", storable.Name, storable.ServiceAccountID)
+ return store.sqlstore.WrapAlreadyExistsErrf(err, serviceaccounttypes.ErrCodeAPIKeyAlreadyExists, "api key with name: %s already exists for service account: %s", storable.Name, storable.ServiceAccountID)
}
return nil
@@ -206,7 +225,7 @@ func (store *store) GetFactorAPIKey(ctx context.Context, serviceAccountID valuer
Where("service_account_id = ?", serviceAccountID).
Scan(ctx)
if err != nil {
- return nil, store.sqlstore.WrapNotFoundErrf(err, serviceaccounttypes.ErrCodeServiceAccounFactorAPIKeytNotFound, "api key with id: %s doesn't exist for service account: %s", id, serviceAccountID)
+ return nil, store.sqlstore.WrapNotFoundErrf(err, serviceaccounttypes.ErrCodeAPIKeytNotFound, "api key with id: %s doesn't exist for service account: %s", id, serviceAccountID)
}
return storable, nil
diff --git a/pkg/modules/serviceaccount/serviceaccount.go b/pkg/modules/serviceaccount/serviceaccount.go
index 73cc54711b..f1083e6851 100644
--- a/pkg/modules/serviceaccount/serviceaccount.go
+++ b/pkg/modules/serviceaccount/serviceaccount.go
@@ -15,6 +15,9 @@ type Module interface {
// Gets a service account by id.
Get(context.Context, valuer.UUID, valuer.UUID) (*serviceaccounttypes.ServiceAccount, error)
+ // Gets or creates a service account by name
+ GetOrCreate(context.Context, *serviceaccounttypes.ServiceAccount) (*serviceaccounttypes.ServiceAccount, error)
+
// Gets a service account by id without fetching roles.
GetWithoutRoles(context.Context, valuer.UUID, valuer.UUID) (*serviceaccounttypes.ServiceAccount, error)
@@ -40,7 +43,7 @@ type Module interface {
ListFactorAPIKey(context.Context, valuer.UUID) ([]*serviceaccounttypes.FactorAPIKey, error)
// Updates an existing API key for a service account
- UpdateFactorAPIKey(context.Context, valuer.UUID, *serviceaccounttypes.FactorAPIKey) error
+ UpdateFactorAPIKey(context.Context, valuer.UUID, valuer.UUID, *serviceaccounttypes.FactorAPIKey) error
// Revokes an existing API key for a service account
RevokeFactorAPIKey(context.Context, valuer.UUID, valuer.UUID) error
diff --git a/pkg/types/serviceaccounttypes/factor_api_key.go b/pkg/types/serviceaccounttypes/factor_api_key.go
index 6c18ef5039..05c4de74d2 100644
--- a/pkg/types/serviceaccounttypes/factor_api_key.go
+++ b/pkg/types/serviceaccounttypes/factor_api_key.go
@@ -11,20 +11,22 @@ import (
)
var (
- ErrCodeServiceAccountFactorAPIkeyInvalidInput = errors.MustNewCode("service_account_factor_api_key_invalid_input")
- ErrCodeServiceAccountFactorAPIKeyAlreadyExists = errors.MustNewCode("service_account_factor_api_key_already_exists")
- ErrCodeServiceAccounFactorAPIKeytNotFound = errors.MustNewCode("service_account_factor_api_key_not_found")
+ ErrCodeAPIkeyInvalidInput = errors.MustNewCode("service_account_factor_api_key_invalid_input")
+ ErrCodeAPIKeyAlreadyExists = errors.MustNewCode("service_account_factor_api_key_already_exists")
+ ErrCodeAPIKeytNotFound = errors.MustNewCode("service_account_factor_api_key_not_found")
+ ErrCodeAPIKeyExpired = errors.MustNewCode("api_key_expired")
+ ErrCodeAPIkeyOlderLastObservedAt = errors.MustNewCode("api_key_older_last_observed_at")
)
type StorableFactorAPIKey struct {
- bun.BaseModel `bun:"table:factor_api_key"`
+ bun.BaseModel `bun:"table:factor_api_key,alias:factor_api_key"`
types.Identifiable
types.TimeAuditable
Name string `bun:"name"`
Key string `bun:"key"`
ExpiresAt uint64 `bun:"expires_at"`
- LastUsed time.Time `bun:"last_used"`
+ LastObservedAt time.Time `bun:"last_observed_at"`
ServiceAccountID string `bun:"service_account_id"`
}
@@ -33,9 +35,9 @@ type FactorAPIKey struct {
types.TimeAuditable
Name string `json:"name" requrired:"true"`
Key string `json:"key" required:"true"`
- ExpiresAt uint64 `json:"expires_at" required:"true"`
- LastUsed time.Time `json:"last_used" required:"true"`
- ServiceAccountID valuer.UUID `json:"service_account_id" required:"true"`
+ ExpiresAt uint64 `json:"expiresAt" required:"true"`
+ LastObservedAt time.Time `json:"lastObservedAt" required:"true"`
+ ServiceAccountID valuer.UUID `json:"serviceAccountId" required:"true"`
}
type GettableFactorAPIKeyWithKey struct {
@@ -47,19 +49,19 @@ type GettableFactorAPIKey struct {
types.Identifiable
types.TimeAuditable
Name string `json:"name" requrired:"true"`
- ExpiresAt uint64 `json:"expires_at" required:"true"`
- LastUsed time.Time `json:"last_used" required:"true"`
- ServiceAccountID valuer.UUID `json:"service_account_id" required:"true"`
+ ExpiresAt uint64 `json:"expiresAt" required:"true"`
+ LastObservedAt time.Time `json:"lastObservedAt" required:"true"`
+ ServiceAccountID valuer.UUID `json:"serviceAccountId" required:"true"`
}
type PostableFactorAPIKey struct {
Name string `json:"name" required:"true"`
- ExpiresAt uint64 `json:"expires_at" required:"true"`
+ ExpiresAt uint64 `json:"expiresAt" required:"true"`
}
type UpdatableFactorAPIKey struct {
Name string `json:"name" required:"true"`
- ExpiresAt uint64 `json:"expires_at" required:"true"`
+ ExpiresAt uint64 `json:"expiresAt" required:"true"`
}
func NewFactorAPIKeyFromStorable(storable *StorableFactorAPIKey) *FactorAPIKey {
@@ -69,7 +71,7 @@ func NewFactorAPIKeyFromStorable(storable *StorableFactorAPIKey) *FactorAPIKey {
Name: storable.Name,
Key: storable.Key,
ExpiresAt: storable.ExpiresAt,
- LastUsed: storable.LastUsed,
+ LastObservedAt: storable.LastObservedAt,
ServiceAccountID: valuer.MustNewUUID(storable.ServiceAccountID),
}
}
@@ -91,7 +93,7 @@ func NewStorableFactorAPIKey(factorAPIKey *FactorAPIKey) *StorableFactorAPIKey {
Name: factorAPIKey.Name,
Key: factorAPIKey.Key,
ExpiresAt: factorAPIKey.ExpiresAt,
- LastUsed: factorAPIKey.LastUsed,
+ LastObservedAt: factorAPIKey.LastObservedAt,
ServiceAccountID: factorAPIKey.ServiceAccountID.String(),
}
}
@@ -105,7 +107,7 @@ func NewGettableFactorAPIKeys(keys []*FactorAPIKey) []*GettableFactorAPIKey {
TimeAuditable: key.TimeAuditable,
Name: key.Name,
ExpiresAt: key.ExpiresAt,
- LastUsed: key.LastUsed,
+ LastObservedAt: key.LastObservedAt,
ServiceAccountID: key.ServiceAccountID,
}
}
@@ -128,6 +130,29 @@ func (apiKey *FactorAPIKey) Update(name string, expiresAt uint64) {
apiKey.UpdatedAt = time.Now()
}
+func (apiKey *FactorAPIKey) IsExpired() error {
+ if apiKey.ExpiresAt == 0 {
+ return nil
+ }
+
+ if time.Now().After(time.Unix(int64(apiKey.ExpiresAt), 0)) {
+ return errors.New(errors.TypeUnauthenticated, ErrCodeAPIKeyExpired, "api key has been expired")
+ }
+
+ return nil
+}
+
+func (apiKey *FactorAPIKey) UpdateLastObservedAt(lastObservedAt time.Time) error {
+ if lastObservedAt.Before(apiKey.LastObservedAt) {
+ return errors.New(errors.TypeInvalidInput, ErrCodeAPIkeyOlderLastObservedAt, "last observed at is before the current last observed at")
+ }
+
+ apiKey.LastObservedAt = lastObservedAt
+ apiKey.UpdatedAt = time.Now()
+
+ return nil
+}
+
func (key *PostableFactorAPIKey) UnmarshalJSON(data []byte) error {
type Alias PostableFactorAPIKey
@@ -137,7 +162,7 @@ func (key *PostableFactorAPIKey) UnmarshalJSON(data []byte) error {
}
if temp.Name == "" {
- return errors.New(errors.TypeInvalidInput, ErrCodeServiceAccountFactorAPIkeyInvalidInput, "name cannot be empty")
+ return errors.New(errors.TypeInvalidInput, ErrCodeAPIkeyInvalidInput, "name cannot be empty")
}
*key = PostableFactorAPIKey(temp)
@@ -153,7 +178,7 @@ func (key *UpdatableFactorAPIKey) UnmarshalJSON(data []byte) error {
}
if temp.Name == "" {
- return errors.New(errors.TypeInvalidInput, ErrCodeServiceAccountFactorAPIkeyInvalidInput, "name cannot be empty")
+ return errors.New(errors.TypeInvalidInput, ErrCodeAPIkeyInvalidInput, "name cannot be empty")
}
*key = UpdatableFactorAPIKey(temp)
diff --git a/pkg/types/serviceaccounttypes/service_acccount.go b/pkg/types/serviceaccounttypes/service_acccount.go
index fd77b3692e..67af813a5e 100644
--- a/pkg/types/serviceaccounttypes/service_acccount.go
+++ b/pkg/types/serviceaccounttypes/service_acccount.go
@@ -4,7 +4,7 @@ import (
"crypto/rand"
"encoding/base64"
"encoding/json"
- "slices"
+ "regexp"
"time"
"github.com/SigNoz/signoz/pkg/errors"
@@ -15,10 +15,11 @@ import (
)
var (
- ErrCodeServiceAccountInvalidInput = errors.MustNewCode("service_account_invalid_input")
- ErrCodeServiceAccountAlreadyExists = errors.MustNewCode("service_account_already_exists")
- ErrCodeServiceAccountNotFound = errors.MustNewCode("service_account_not_found")
- ErrCodeServiceAccountRoleAlreadyExists = errors.MustNewCode("service_account_role_already_exists")
+ ErrCodeServiceAccountInvalidInput = errors.MustNewCode("service_account_invalid_input")
+ ErrCodeServiceAccountAlreadyExists = errors.MustNewCode("service_account_already_exists")
+ ErrCodeServiceAccountNotFound = errors.MustNewCode("service_account_not_found")
+ ErrCodeServiceAccountRoleAlreadyExists = errors.MustNewCode("service_account_role_already_exists")
+ ErrCodeServiceAccountOperationUnsupported = errors.MustNewCode("service_account_operation_unsupported")
)
var (
@@ -27,25 +28,31 @@ var (
ValidStatus = []valuer.String{StatusActive, StatusDisabled}
)
+var (
+ serviceAccountNameRegex = regexp.MustCompile("^[a-z-]{1,50}$")
+)
+
type StorableServiceAccount struct {
bun.BaseModel `bun:"table:service_account,alias:service_account"`
types.Identifiable
types.TimeAuditable
- Name string `bun:"name"`
- Email string `bun:"email"`
- Status valuer.String `bun:"status"`
- OrgID string `bun:"org_id"`
+ Name string `bun:"name"`
+ Email string `bun:"email"`
+ Status valuer.String `bun:"status"`
+ OrgID string `bun:"org_id"`
+ DeletedAt time.Time `bun:"deleted_at"`
}
type ServiceAccount struct {
types.Identifiable
types.TimeAuditable
- Name string `json:"name" required:"true"`
- Email valuer.Email `json:"email" required:"true"`
- Roles []string `json:"roles" required:"true" nullable:"false"`
- Status valuer.String `json:"status" required:"true"`
- OrgID valuer.UUID `json:"orgID" required:"true"`
+ Name string `json:"name" required:"true"`
+ Email valuer.Email `json:"email" required:"true"`
+ Roles []string `json:"roles" required:"true" nullable:"false"`
+ Status valuer.String `json:"status" required:"true"`
+ OrgID valuer.UUID `json:"orgId" required:"true"`
+ DeletedAt time.Time `json:"deletedAt" required:"true"`
}
type PostableServiceAccount struct {
@@ -73,11 +80,12 @@ func NewServiceAccount(name string, email valuer.Email, roles []string, status v
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
},
- Name: name,
- Email: email,
- Roles: roles,
- Status: status,
- OrgID: orgID,
+ Name: name,
+ Email: email,
+ Roles: roles,
+ Status: status,
+ OrgID: orgID,
+ DeletedAt: time.Time{},
}
}
@@ -90,6 +98,7 @@ func NewServiceAccountFromStorables(storableServiceAccount *StorableServiceAccou
Roles: roles,
Status: storableServiceAccount.Status,
OrgID: valuer.MustNewUUID(storableServiceAccount.OrgID),
+ DeletedAt: storableServiceAccount.DeletedAt,
}
}
@@ -126,22 +135,46 @@ func NewStorableServiceAccount(serviceAccount *ServiceAccount) *StorableServiceA
Email: serviceAccount.Email.String(),
Status: serviceAccount.Status,
OrgID: serviceAccount.OrgID.String(),
+ DeletedAt: serviceAccount.DeletedAt,
}
}
-func (sa *ServiceAccount) Update(name string, email valuer.Email, roles []string) {
+func (sa *ServiceAccount) Update(name string, email valuer.Email, roles []string) error {
+ if err := sa.ErrIfDisabled(); err != nil {
+ return err
+ }
+
sa.Name = name
sa.Email = email
sa.Roles = roles
sa.UpdatedAt = time.Now()
+ return nil
}
-func (sa *ServiceAccount) UpdateStatus(status valuer.String) {
+func (sa *ServiceAccount) UpdateStatus(status valuer.String) error {
+ if err := sa.ErrIfDisabled(); err != nil {
+ return err
+ }
+
sa.Status = status
sa.UpdatedAt = time.Now()
+ sa.DeletedAt = time.Now()
+ return nil
+}
+
+func (sa *ServiceAccount) ErrIfDisabled() error {
+ if sa.Status == StatusDisabled {
+ return errors.New(errors.TypeUnsupported, ErrCodeServiceAccountOperationUnsupported, "this operation is not supported for disabled service account")
+ }
+
+ return nil
}
func (sa *ServiceAccount) NewFactorAPIKey(name string, expiresAt uint64) (*FactorAPIKey, error) {
+ if err := sa.ErrIfDisabled(); err != nil {
+ return nil, err
+ }
+
key := make([]byte, 32)
_, err := rand.Read(key)
if err != nil {
@@ -161,7 +194,7 @@ func (sa *ServiceAccount) NewFactorAPIKey(name string, expiresAt uint64) (*Facto
Name: name,
Key: encodedKey,
ExpiresAt: expiresAt,
- LastUsed: time.Now(),
+ LastObservedAt: time.Now(),
ServiceAccountID: sa.ID,
}, nil
}
@@ -204,8 +237,8 @@ func (sa *PostableServiceAccount) UnmarshalJSON(data []byte) error {
return err
}
- if temp.Name == "" {
- return errors.New(errors.TypeInvalidInput, ErrCodeServiceAccountInvalidInput, "name cannot be empty")
+ if match := serviceAccountNameRegex.MatchString(temp.Name); !match {
+ return errors.Newf(errors.TypeInvalidInput, ErrCodeServiceAccountInvalidInput, "name must conform to the regex: %s", serviceAccountNameRegex.String())
}
if len(temp.Roles) == 0 {
@@ -224,8 +257,8 @@ func (sa *UpdatableServiceAccount) UnmarshalJSON(data []byte) error {
return err
}
- if temp.Name == "" {
- return errors.New(errors.TypeInvalidInput, ErrCodeServiceAccountInvalidInput, "name cannot be empty")
+ if match := serviceAccountNameRegex.MatchString(temp.Name); !match {
+ return errors.Newf(errors.TypeInvalidInput, ErrCodeServiceAccountInvalidInput, "name must conform to the regex: %s", serviceAccountNameRegex.String())
}
if len(temp.Roles) == 0 {
@@ -244,8 +277,8 @@ func (sa *UpdatableServiceAccountStatus) UnmarshalJSON(data []byte) error {
return err
}
- if !slices.Contains(ValidStatus, temp.Status) {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeServiceAccountInvalidInput, "invalid status: %s, allowed status are: %v", temp.Status, ValidStatus)
+ if temp.Status != StatusDisabled {
+ return errors.Newf(errors.TypeInvalidInput, ErrCodeServiceAccountInvalidInput, "invalid status: %s, allowed status are: %v", temp.Status, StatusDisabled)
}
*sa = UpdatableServiceAccountStatus(temp)
diff --git a/pkg/types/serviceaccounttypes/store.go b/pkg/types/serviceaccounttypes/store.go
index 2e8cf9e728..64d9b9f108 100644
--- a/pkg/types/serviceaccounttypes/store.go
+++ b/pkg/types/serviceaccounttypes/store.go
@@ -10,6 +10,7 @@ type Store interface {
// Service Account
Create(context.Context, *StorableServiceAccount) error
Get(context.Context, valuer.UUID, valuer.UUID) (*StorableServiceAccount, error)
+ GetActiveByOrgIDAndName(context.Context, valuer.UUID, string) (*StorableServiceAccount, error)
GetByID(context.Context, valuer.UUID) (*StorableServiceAccount, error)
List(context.Context, valuer.UUID) ([]*StorableServiceAccount, error)
Update(context.Context, valuer.UUID, *StorableServiceAccount) error