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): integrate service account (#10681)

Vikrant Guptabad80399a6e4
diff --git a/.github/workflows/integrationci.yaml b/.github/workflows/integrationci.yaml
index 5046aa796f..59c0498696 100644
--- a/.github/workflows/integrationci.yaml
+++ b/.github/workflows/integrationci.yaml
@@ -51,6 +51,7 @@ jobs:
- alerts
- ingestionkeys
- rootuser
+ - serviceaccount
sqlstore-provider:
- postgres
- sqlite
diff --git a/conf/example.yaml b/conf/example.yaml
index db3436d655..77fe4fb885 100644
--- a/conf/example.yaml
+++ b/conf/example.yaml
@@ -354,3 +354,13 @@ identn:
impersonation:
# toggle impersonation identN, when enabled, all requests will impersonate the root user
enabled: false
+
+##################### Service Account #####################
+serviceaccount:
+ email:
+ # email domain for the service account principal
+ domain: signozserviceaccount.com
+
+ analytics:
+ # toggle service account analytics
+ enabled: true
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index b092e45a79..795175ba2c 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -2447,7 +2447,7 @@ components:
- start
- end
type: object
- ServiceaccounttypesFactorAPIKey:
+ ServiceaccounttypesGettableFactorAPIKey:
properties:
createdAt:
format: date-time
@@ -2457,8 +2457,6 @@ components:
type: integer
id:
type: string
- key:
- type: string
lastObservedAt:
format: date-time
type: string
@@ -2471,7 +2469,6 @@ components:
type: string
required:
- id
- - key
- expiresAt
- lastObservedAt
- serviceAccountId
@@ -2499,27 +2496,23 @@ components:
type: object
ServiceaccounttypesPostableServiceAccount:
properties:
- email:
- type: string
name:
type: string
- roles:
- items:
- type: string
- type: array
required:
- name
- - email
- - roles
+ type: object
+ ServiceaccounttypesPostableServiceAccountRole:
+ properties:
+ id:
+ type: string
+ required:
+ - id
type: object
ServiceaccounttypesServiceAccount:
properties:
createdAt:
format: date-time
type: string
- deletedAt:
- format: date-time
- type: string
email:
type: string
id:
@@ -2528,10 +2521,6 @@ components:
type: string
orgId:
type: string
- roles:
- items:
- type: string
- type: array
status:
type: string
updatedAt:
@@ -2541,43 +2530,72 @@ components:
- id
- name
- email
- - roles
- status
- orgId
- - deletedAt
type: object
- ServiceaccounttypesUpdatableFactorAPIKey:
+ ServiceaccounttypesServiceAccountRole:
properties:
- expiresAt:
- minimum: 0
- type: integer
- name:
+ createdAt:
+ format: date-time
+ type: string
+ id:
+ type: string
+ role:
+ $ref: '#/components/schemas/AuthtypesRole'
+ roleId:
+ type: string
+ serviceAccountId:
+ type: string
+ updatedAt:
+ format: date-time
type: string
required:
- - name
- - expiresAt
+ - id
+ - serviceAccountId
+ - roleId
+ - role
type: object
- ServiceaccounttypesUpdatableServiceAccount:
+ ServiceaccounttypesServiceAccountWithRoles:
properties:
+ createdAt:
+ format: date-time
+ type: string
email:
type: string
+ id:
+ type: string
name:
type: string
- roles:
+ orgId:
+ type: string
+ serviceAccountRoles:
items:
- type: string
+ $ref: '#/components/schemas/ServiceaccounttypesServiceAccountRole'
+ nullable: true
type: array
+ status:
+ type: string
+ updatedAt:
+ format: date-time
+ type: string
required:
+ - id
- name
- email
- - roles
+ - status
+ - orgId
+ - serviceAccountRoles
type: object
- ServiceaccounttypesUpdatableServiceAccountStatus:
+ ServiceaccounttypesUpdatableFactorAPIKey:
properties:
- status:
+ expiresAt:
+ minimum: 0
+ type: integer
+ name:
type: string
required:
- - status
+ - name
+ - expiresAt
type: object
TelemetrytypesFieldContext:
enum:
@@ -2702,43 +2720,6 @@ components:
required:
- id
type: object
- TypesGettableAPIKey:
- properties:
- createdAt:
- format: date-time
- type: string
- createdBy:
- type: string
- createdByUser:
- $ref: '#/components/schemas/TypesUser'
- expiresAt:
- format: int64
- type: integer
- id:
- type: string
- lastUsed:
- format: int64
- type: integer
- name:
- type: string
- revoked:
- type: boolean
- role:
- type: string
- token:
- type: string
- updatedAt:
- format: date-time
- type: string
- updatedBy:
- type: string
- updatedByUser:
- $ref: '#/components/schemas/TypesUser'
- userId:
- type: string
- required:
- - id
- type: object
TypesIdentifiable:
properties:
id:
@@ -2793,16 +2774,6 @@ components:
required:
- id
type: object
- TypesPostableAPIKey:
- properties:
- expiresInDays:
- format: int64
- type: integer
- name:
- type: string
- role:
- type: string
- type: object
TypesPostableBulkInviteRequest:
properties:
invites:
@@ -2863,33 +2834,6 @@ components:
required:
- id
type: object
- TypesStorableAPIKey:
- properties:
- createdAt:
- format: date-time
- type: string
- createdBy:
- type: string
- id:
- type: string
- name:
- type: string
- revoked:
- type: boolean
- role:
- type: string
- token:
- type: string
- updatedAt:
- format: date-time
- type: string
- updatedBy:
- type: string
- userId:
- type: string
- required:
- - id
- type: object
TypesUpdatableUser:
properties:
displayName:
@@ -4966,222 +4910,6 @@ paths:
summary: Update org preference
tags:
- preferences
- /api/v1/pats:
- get:
- deprecated: false
- description: This endpoint lists all api keys
- operationId: ListAPIKeys
- responses:
- "200":
- content:
- application/json:
- schema:
- properties:
- data:
- items:
- $ref: '#/components/schemas/TypesGettableAPIKey'
- type: array
- status:
- type: string
- required:
- - status
- - data
- type: object
- description: OK
- "401":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Unauthorized
- "403":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Forbidden
- "500":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Internal Server Error
- security:
- - api_key:
- - ADMIN
- - tokenizer:
- - ADMIN
- summary: List api keys
- tags:
- - users
- post:
- deprecated: false
- description: This endpoint creates an api key
- operationId: CreateAPIKey
- requestBody:
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/TypesPostableAPIKey'
- responses:
- "201":
- content:
- application/json:
- schema:
- properties:
- data:
- $ref: '#/components/schemas/TypesGettableAPIKey'
- status:
- type: string
- required:
- - status
- - data
- type: object
- description: Created
- "400":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Bad Request
- "401":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Unauthorized
- "403":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Forbidden
- "409":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Conflict
- "500":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Internal Server Error
- security:
- - api_key:
- - ADMIN
- - tokenizer:
- - ADMIN
- summary: Create api key
- tags:
- - users
- /api/v1/pats/{id}:
- delete:
- deprecated: false
- description: This endpoint revokes an api key
- operationId: RevokeAPIKey
- parameters:
- - in: path
- name: id
- required: true
- schema:
- type: string
- responses:
- "204":
- description: No Content
- "401":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Unauthorized
- "403":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Forbidden
- "404":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Not Found
- "500":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Internal Server Error
- security:
- - api_key:
- - ADMIN
- - tokenizer:
- - ADMIN
- summary: Revoke api key
- tags:
- - users
- put:
- deprecated: false
- description: This endpoint updates an api key
- operationId: UpdateAPIKey
- parameters:
- - in: path
- name: id
- required: true
- schema:
- type: string
- requestBody:
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/TypesStorableAPIKey'
- responses:
- "204":
- content:
- application/json:
- schema:
- type: string
- description: No Content
- "400":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Bad Request
- "401":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Unauthorized
- "403":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Forbidden
- "404":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Not Found
- "500":
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/RenderErrorResponse'
- description: Internal Server Error
- security:
- - api_key:
- - ADMIN
- - tokenizer:
- - ADMIN
- summary: Update api key
- tags:
- - users
/api/v1/public/dashboards/{id}:
get:
deprecated: false
@@ -5956,7 +5684,7 @@ paths:
schema:
properties:
data:
- $ref: '#/components/schemas/ServiceaccounttypesServiceAccount'
+ $ref: '#/components/schemas/ServiceaccounttypesServiceAccountWithRoles'
status:
type: string
required:
@@ -6010,7 +5738,7 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/ServiceaccounttypesUpdatableServiceAccount'
+ $ref: '#/components/schemas/ServiceaccounttypesPostableServiceAccount'
responses:
"204":
content:
@@ -6075,7 +5803,7 @@ paths:
properties:
data:
items:
- $ref: '#/components/schemas/ServiceaccounttypesFactorAPIKey'
+ $ref: '#/components/schemas/ServiceaccounttypesGettableFactorAPIKey'
type: array
status:
type: string
@@ -6298,11 +6026,71 @@ paths:
summary: Updates a service account key
tags:
- serviceaccount
- /api/v1/service_accounts/{id}/status:
- put:
+ /api/v1/service_accounts/{id}/roles:
+ get:
deprecated: false
- description: This endpoint updates an existing service account status
- operationId: UpdateServiceAccountStatus
+ description: This endpoint gets all the roles for the existing service account
+ operationId: GetServiceAccountRoles
+ parameters:
+ - in: path
+ name: id
+ required: true
+ schema:
+ type: string
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ items:
+ $ref: '#/components/schemas/AuthtypesRole'
+ nullable: true
+ type: array
+ status:
+ type: string
+ required:
+ - status
+ - data
+ type: object
+ description: OK
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Unauthorized
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Forbidden
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Not Found
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ security:
+ - api_key:
+ - ADMIN
+ - tokenizer:
+ - ADMIN
+ summary: Gets service account roles
+ tags:
+ - serviceaccount
+ post:
+ deprecated: false
+ description: This endpoint assigns a role to a service account
+ operationId: CreateServiceAccountRole
parameters:
- in: path
name: id
@@ -6313,14 +6101,22 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/ServiceaccounttypesUpdatableServiceAccountStatus'
+ $ref: '#/components/schemas/ServiceaccounttypesPostableServiceAccountRole'
responses:
- "204":
+ "201":
content:
application/json:
schema:
- type: string
- description: No Content
+ properties:
+ data:
+ $ref: '#/components/schemas/TypesIdentifiable'
+ status:
+ type: string
+ required:
+ - status
+ - data
+ type: object
+ description: Created
"400":
content:
application/json:
@@ -6339,12 +6135,55 @@ paths:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
description: Forbidden
- "404":
+ "500":
content:
application/json:
schema:
$ref: '#/components/schemas/RenderErrorResponse'
- description: Not Found
+ description: Internal Server Error
+ security:
+ - api_key:
+ - ADMIN
+ - tokenizer:
+ - ADMIN
+ summary: Create service account role
+ tags:
+ - serviceaccount
+ /api/v1/service_accounts/{id}/roles/{rid}:
+ delete:
+ deprecated: false
+ description: This endpoint revokes a role from service account
+ operationId: DeleteServiceAccountRole
+ parameters:
+ - in: path
+ name: id
+ required: true
+ schema:
+ type: string
+ - in: path
+ name: rid
+ required: true
+ schema:
+ type: string
+ responses:
+ "204":
+ content:
+ application/json:
+ schema:
+ type: string
+ description: No Content
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Unauthorized
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Forbidden
"500":
content:
application/json:
@@ -6356,7 +6195,73 @@ paths:
- ADMIN
- tokenizer:
- ADMIN
- summary: Updates a service account status
+ summary: Delete service account role
+ tags:
+ - serviceaccount
+ /api/v1/service_accounts/me:
+ get:
+ deprecated: false
+ description: This endpoint gets my service account
+ operationId: GetMyServiceAccount
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/ServiceaccounttypesServiceAccountWithRoles'
+ status:
+ type: string
+ required:
+ - status
+ - data
+ type: object
+ description: OK
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Not Found
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ summary: Gets my service account
+ tags:
+ - serviceaccount
+ put:
+ deprecated: false
+ description: This endpoint gets my service account
+ operationId: UpdateMyServiceAccount
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ServiceaccounttypesPostableServiceAccount'
+ responses:
+ "204":
+ content:
+ application/json:
+ schema:
+ type: string
+ description: No Content
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Not Found
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ summary: Updates my service account
tags:
- serviceaccount
/api/v1/user:
diff --git a/ee/authz/openfgaserver/server.go b/ee/authz/openfgaserver/server.go
index 97587abaa8..ff3ed39c4d 100644
--- a/ee/authz/openfgaserver/server.go
+++ b/ee/authz/openfgaserver/server.go
@@ -34,9 +34,22 @@ func (server *Server) Stop(ctx context.Context) error {
}
func (server *Server) CheckWithTupleCreation(ctx context.Context, claims authtypes.Claims, orgID valuer.UUID, relation authtypes.Relation, typeable authtypes.Typeable, selectors []authtypes.Selector, _ []authtypes.Selector) error {
- subject, err := authtypes.NewSubject(authtypes.TypeableUser, claims.UserID, orgID, nil)
- if err != nil {
- return err
+ subject := ""
+ switch claims.Principal {
+ case authtypes.PrincipalUser:
+ user, err := authtypes.NewSubject(authtypes.TypeableUser, claims.UserID, orgID, nil)
+ if err != nil {
+ return err
+ }
+
+ subject = user
+ case authtypes.PrincipalServiceAccount:
+ serviceAccount, err := authtypes.NewSubject(authtypes.TypeableServiceAccount, claims.ServiceAccountID, orgID, nil)
+ if err != nil {
+ return err
+ }
+
+ subject = serviceAccount
}
tupleSlice, err := typeable.Tuples(subject, relation, selectors, orgID)
diff --git a/ee/modules/dashboard/impldashboard/module.go b/ee/modules/dashboard/impldashboard/module.go
index 74aba8eec9..dfd96616eb 100644
--- a/ee/modules/dashboard/impldashboard/module.go
+++ b/ee/modules/dashboard/impldashboard/module.go
@@ -213,8 +213,8 @@ func (module *module) Update(ctx context.Context, orgID valuer.UUID, id valuer.U
return module.pkgDashboardModule.Update(ctx, orgID, id, updatedBy, data, diff)
}
-func (module *module) LockUnlock(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, role types.Role, lock bool) error {
- return module.pkgDashboardModule.LockUnlock(ctx, orgID, id, updatedBy, role, lock)
+func (module *module) LockUnlock(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, isAdmin bool, lock bool) error {
+ return module.pkgDashboardModule.LockUnlock(ctx, orgID, id, updatedBy, isAdmin, lock)
}
func (module *module) MustGetTypeables() []authtypes.Typeable {
diff --git a/ee/query-service/app/api/cloudIntegrations.go b/ee/query-service/app/api/cloudIntegrations.go
index 2f1473d12f..c0df93298a 100644
--- a/ee/query-service/app/api/cloudIntegrations.go
+++ b/ee/query-service/app/api/cloudIntegrations.go
@@ -14,10 +14,9 @@ import (
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/http/render"
- "github.com/SigNoz/signoz/pkg/modules/user"
basemodel "github.com/SigNoz/signoz/pkg/query-service/model"
- "github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
+ "github.com/SigNoz/signoz/pkg/types/serviceaccounttypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/gorilla/mux"
)
@@ -50,7 +49,7 @@ func (ah *APIHandler) CloudIntegrationsGenerateConnectionParams(w http.ResponseW
return
}
- apiKey, apiErr := ah.getOrCreateCloudIntegrationPAT(r.Context(), claims.OrgID, cloudProvider)
+ apiKey, apiErr := ah.getOrCreateCloudIntegrationFactorAPIKey(r.Context(), valuer.MustNewUUID(claims.OrgID), cloudProvider)
if apiErr != nil {
RespondError(w, basemodel.WrapApiError(
apiErr, "couldn't provision PAT for cloud integration:",
@@ -110,84 +109,44 @@ func (ah *APIHandler) CloudIntegrationsGenerateConnectionParams(w http.ResponseW
ah.Respond(w, result)
}
-func (ah *APIHandler) getOrCreateCloudIntegrationPAT(ctx context.Context, orgId string, cloudProvider string) (
+func (ah *APIHandler) getOrCreateCloudIntegrationFactorAPIKey(ctx context.Context, orgID valuer.UUID, cloudProvider string) (
string, *basemodel.ApiError,
) {
- integrationPATName := fmt.Sprintf("%s integration", cloudProvider)
-
- integrationUser, apiErr := ah.getOrCreateCloudIntegrationUser(ctx, orgId, cloudProvider)
+ integrationPATName := fmt.Sprintf("%s", cloudProvider)
+ serviceAccount, apiErr := ah.getOrCreateCloudIntegrationServiceAccount(ctx, orgID)
if apiErr != nil {
return "", apiErr
}
- orgIdUUID, err := valuer.NewUUID(orgId)
- if err != nil {
- return "", basemodel.InternalError(fmt.Errorf(
- "couldn't parse orgId: %w", err,
- ))
- }
-
- allPats, err := ah.Signoz.Modules.UserSetter.ListAPIKeys(ctx, orgIdUUID)
- if err != nil {
- return "", basemodel.InternalError(fmt.Errorf(
- "couldn't list PATs: %w", err,
- ))
- }
- for _, p := range allPats {
- if p.UserID == integrationUser.ID && p.Name == integrationPATName {
- return p.Token, nil
- }
- }
-
- slog.InfoContext(ctx, "no PAT found for cloud integration, creating a new one",
- "cloud_provider", cloudProvider,
- )
-
- newPAT, err := types.NewStorableAPIKey(
- integrationPATName,
- integrationUser.ID,
- types.RoleViewer,
- 0,
- )
+ factorAPIKey, err := serviceAccount.NewFactorAPIKey(integrationPATName, 0)
if err != nil {
return "", basemodel.InternalError(fmt.Errorf(
"couldn't create cloud integration PAT: %w", err,
))
}
- err = ah.Signoz.Modules.UserSetter.CreateAPIKey(ctx, newPAT)
+ factorAPIKey, err = ah.Signoz.Modules.ServiceAccount.GetOrCreateFactorAPIKey(ctx, factorAPIKey)
if err != nil {
return "", basemodel.InternalError(fmt.Errorf(
"couldn't create cloud integration PAT: %w", err,
))
}
- return newPAT.Token, nil
+ return factorAPIKey.Key, nil
}
-func (ah *APIHandler) getOrCreateCloudIntegrationUser(
- ctx context.Context, orgId string, cloudProvider string,
-) (*types.User, *basemodel.ApiError) {
- cloudIntegrationUserName := fmt.Sprintf("%s-integration", cloudProvider)
- email := valuer.MustNewEmail(fmt.Sprintf("%[email protected]", cloudIntegrationUserName))
-
- cloudIntegrationUser, err := types.NewUser(cloudIntegrationUserName, email, valuer.MustNewUUID(orgId), types.UserStatusActive)
+func (ah *APIHandler) getOrCreateCloudIntegrationServiceAccount(ctx context.Context, orgId valuer.UUID) (*serviceaccounttypes.ServiceAccount, *basemodel.ApiError) {
+ domain := ah.Signoz.Modules.ServiceAccount.Config().Email.Domain
+ cloudIntegrationServiceAccount := serviceaccounttypes.NewServiceAccount("integration", domain, serviceaccounttypes.ServiceAccountStatusActive, orgId)
+ cloudIntegrationServiceAccount, err := ah.Signoz.Modules.ServiceAccount.GetOrCreate(ctx, orgId, cloudIntegrationServiceAccount)
if err != nil {
- return nil, basemodel.InternalError(fmt.Errorf("couldn't create cloud integration user: %w", err))
+ return nil, basemodel.InternalError(fmt.Errorf("couldn't create cloud integration service account: %w", err))
}
-
- password := types.MustGenerateFactorPassword(cloudIntegrationUser.ID.StringValue())
-
- cloudIntegrationUser, err = ah.Signoz.Modules.UserSetter.GetOrCreateUser(
- ctx,
- cloudIntegrationUser,
- user.WithFactorPassword(password),
- user.WithRoleNames([]string{authtypes.SigNozViewerRoleName}),
- )
+ err = ah.Signoz.Modules.ServiceAccount.SetRoleByName(ctx, orgId, cloudIntegrationServiceAccount.ID, authtypes.SigNozViewerRoleName)
if err != nil {
- return nil, basemodel.InternalError(fmt.Errorf("couldn't look for integration user: %w", err))
+ return nil, basemodel.InternalError(fmt.Errorf("couldn't create cloud integration service account: %w", err))
}
- return cloudIntegrationUser, nil
+ return cloudIntegrationServiceAccount, nil
}
func (ah *APIHandler) getIngestionUrlAndSigNozAPIUrl(ctx context.Context, licenseKey string) (
diff --git a/frontend/src/AppRoutes/__tests__/Private.test.tsx b/frontend/src/AppRoutes/__tests__/Private.test.tsx
index a3c010c165..9ec68b3fbb 100644
--- a/frontend/src/AppRoutes/__tests__/Private.test.tsx
+++ b/frontend/src/AppRoutes/__tests__/Private.test.tsx
@@ -306,11 +306,19 @@ describe('PrivateRoute', () => {
);
});
- it('should redirect /settings/access-tokens to /settings/api-keys', () => {
+ it('should redirect /settings/access-tokens to /settings/service-accounts', () => {
renderPrivateRoute({ initialRoute: '/settings/access-tokens' });
expect(screen.getByTestId('location-display')).toHaveTextContent(
- '/settings/api-keys',
+ '/settings/service-accounts',
+ );
+ });
+
+ it('should redirect /settings/api-keys to /settings/service-accounts', () => {
+ renderPrivateRoute({ initialRoute: '/settings/api-keys' });
+
+ expect(screen.getByTestId('location-display')).toHaveTextContent(
+ '/settings/service-accounts',
);
});
diff --git a/frontend/src/AppRoutes/pageComponents.ts b/frontend/src/AppRoutes/pageComponents.ts
index d03d09e3cb..c3026e4e7a 100644
--- a/frontend/src/AppRoutes/pageComponents.ts
+++ b/frontend/src/AppRoutes/pageComponents.ts
@@ -157,10 +157,6 @@ export const IngestionSettings = Loadable(
() => import(/* webpackChunkName: "Ingestion Settings" */ 'pages/Settings'),
);
-export const APIKeys = Loadable(
- () => import(/* webpackChunkName: "All Settings" */ 'pages/Settings'),
-);
-
export const MySettings = Loadable(
() => import(/* webpackChunkName: "All MySettings" */ 'pages/Settings'),
);
diff --git a/frontend/src/AppRoutes/routes.ts b/frontend/src/AppRoutes/routes.ts
index da6f5aaafc..18b3d0e1ac 100644
--- a/frontend/src/AppRoutes/routes.ts
+++ b/frontend/src/AppRoutes/routes.ts
@@ -513,6 +513,7 @@ export const oldRoutes = [
'/logs-save-views',
'/traces-save-views',
'/settings/access-tokens',
+ '/settings/api-keys',
'/messaging-queues',
'/alerts/edit',
];
@@ -523,7 +524,8 @@ export const oldNewRoutesMapping: Record<string, string> = {
'/logs-explorer/live': '/logs/logs-explorer/live',
'/logs-save-views': '/logs/saved-views',
'/traces-save-views': '/traces/saved-views',
- '/settings/access-tokens': '/settings/api-keys',
+ '/settings/access-tokens': '/settings/service-accounts',
+ '/settings/api-keys': '/settings/service-accounts',
'/messaging-queues': '/messaging-queues/overview',
'/alerts/edit': '/alerts/overview',
};
diff --git a/frontend/src/api/generated/services/serviceaccount/index.ts b/frontend/src/api/generated/services/serviceaccount/index.ts
index 0d1114b074..4470d92875 100644
--- a/frontend/src/api/generated/services/serviceaccount/index.ts
+++ b/frontend/src/api/generated/services/serviceaccount/index.ts
@@ -23,9 +23,15 @@ import type {
CreateServiceAccount201,
CreateServiceAccountKey201,
CreateServiceAccountKeyPathParameters,
+ CreateServiceAccountRole201,
+ CreateServiceAccountRolePathParameters,
DeleteServiceAccountPathParameters,
+ DeleteServiceAccountRolePathParameters,
+ GetMyServiceAccount200,
GetServiceAccount200,
GetServiceAccountPathParameters,
+ GetServiceAccountRoles200,
+ GetServiceAccountRolesPathParameters,
ListServiceAccountKeys200,
ListServiceAccountKeysPathParameters,
ListServiceAccounts200,
@@ -33,12 +39,10 @@ import type {
RevokeServiceAccountKeyPathParameters,
ServiceaccounttypesPostableFactorAPIKeyDTO,
ServiceaccounttypesPostableServiceAccountDTO,
+ ServiceaccounttypesPostableServiceAccountRoleDTO,
ServiceaccounttypesUpdatableFactorAPIKeyDTO,
- ServiceaccounttypesUpdatableServiceAccountDTO,
- ServiceaccounttypesUpdatableServiceAccountStatusDTO,
UpdateServiceAccountKeyPathParameters,
UpdateServiceAccountPathParameters,
- UpdateServiceAccountStatusPathParameters,
} from '../sigNoz.schemas';
/**
@@ -399,13 +403,13 @@ export const invalidateGetServiceAccount = async (
*/
export const updateServiceAccount = (
{ id }: UpdateServiceAccountPathParameters,
- serviceaccounttypesUpdatableServiceAccountDTO: BodyType<ServiceaccounttypesUpdatableServiceAccountDTO>,
+ serviceaccounttypesPostableServiceAccountDTO: BodyType<ServiceaccounttypesPostableServiceAccountDTO>,
) => {
return GeneratedAPIInstance<string>({
url: `/api/v1/service_accounts/${id}`,
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- data: serviceaccounttypesUpdatableServiceAccountDTO,
+ data: serviceaccounttypesPostableServiceAccountDTO,
});
};
@@ -418,7 +422,7 @@ export const getUpdateServiceAccountMutationOptions = <
TError,
{
pathParams: UpdateServiceAccountPathParameters;
- data: BodyType<ServiceaccounttypesUpdatableServiceAccountDTO>;
+ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
},
TContext
>;
@@ -427,7 +431,7 @@ export const getUpdateServiceAccountMutationOptions = <
TError,
{
pathParams: UpdateServiceAccountPathParameters;
- data: BodyType<ServiceaccounttypesUpdatableServiceAccountDTO>;
+ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
},
TContext
> => {
@@ -444,7 +448,7 @@ export const getUpdateServiceAccountMutationOptions = <
Awaited<ReturnType<typeof updateServiceAccount>>,
{
pathParams: UpdateServiceAccountPathParameters;
- data: BodyType<ServiceaccounttypesUpdatableServiceAccountDTO>;
+ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
@@ -458,7 +462,7 @@ export const getUpdateServiceAccountMutationOptions = <
export type UpdateServiceAccountMutationResult = NonNullable<
Awaited<ReturnType<typeof updateServiceAccount>>
>;
-export type UpdateServiceAccountMutationBody = BodyType<ServiceaccounttypesUpdatableServiceAccountDTO>;
+export type UpdateServiceAccountMutationBody = BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
export type UpdateServiceAccountMutationError = ErrorType<RenderErrorResponseDTO>;
/**
@@ -473,7 +477,7 @@ export const useUpdateServiceAccount = <
TError,
{
pathParams: UpdateServiceAccountPathParameters;
- data: BodyType<ServiceaccounttypesUpdatableServiceAccountDTO>;
+ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
},
TContext
>;
@@ -482,7 +486,7 @@ export const useUpdateServiceAccount = <
TError,
{
pathParams: UpdateServiceAccountPathParameters;
- data: BodyType<ServiceaccounttypesUpdatableServiceAccountDTO>;
+ data: BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
},
TContext
> => {
@@ -871,44 +875,150 @@ export const useUpdateServiceAccountKey = <
return useMutation(mutationOptions);
};
/**
- * This endpoint updates an existing service account status
- * @summary Updates a service account status
+ * This endpoint gets all the roles for the existing service account
+ * @summary Gets service account roles
*/
-export const updateServiceAccountStatus = (
- { id }: UpdateServiceAccountStatusPathParameters,
- serviceaccounttypesUpdatableServiceAccountStatusDTO: BodyType<ServiceaccounttypesUpdatableServiceAccountStatusDTO>,
+export const getServiceAccountRoles = (
+ { id }: GetServiceAccountRolesPathParameters,
+ signal?: AbortSignal,
) => {
- return GeneratedAPIInstance<string>({
- url: `/api/v1/service_accounts/${id}/status`,
- method: 'PUT',
+ return GeneratedAPIInstance<GetServiceAccountRoles200>({
+ url: `/api/v1/service_accounts/${id}/roles`,
+ method: 'GET',
+ signal,
+ });
+};
+
+export const getGetServiceAccountRolesQueryKey = ({
+ id,
+}: GetServiceAccountRolesPathParameters) => {
+ return [`/api/v1/service_accounts/${id}/roles`] as const;
+};
+
+export const getGetServiceAccountRolesQueryOptions = <
+ TData = Awaited<ReturnType<typeof getServiceAccountRoles>>,
+ TError = ErrorType<RenderErrorResponseDTO>
+>(
+ { id }: GetServiceAccountRolesPathParameters,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getServiceAccountRoles>>,
+ TError,
+ TData
+ >;
+ },
+) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey =
+ queryOptions?.queryKey ?? getGetServiceAccountRolesQueryKey({ id });
+
+ const queryFn: QueryFunction<
+ Awaited<ReturnType<typeof getServiceAccountRoles>>
+ > = ({ signal }) => getServiceAccountRoles({ id }, signal);
+
+ return {
+ queryKey,
+ queryFn,
+ enabled: !!id,
+ ...queryOptions,
+ } as UseQueryOptions<
+ Awaited<ReturnType<typeof getServiceAccountRoles>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type GetServiceAccountRolesQueryResult = NonNullable<
+ Awaited<ReturnType<typeof getServiceAccountRoles>>
+>;
+export type GetServiceAccountRolesQueryError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Gets service account roles
+ */
+
+export function useGetServiceAccountRoles<
+ TData = Awaited<ReturnType<typeof getServiceAccountRoles>>,
+ TError = ErrorType<RenderErrorResponseDTO>
+>(
+ { id }: GetServiceAccountRolesPathParameters,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getServiceAccountRoles>>,
+ TError,
+ TData
+ >;
+ },
+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getGetServiceAccountRolesQueryOptions({ id }, options);
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ query.queryKey = queryOptions.queryKey;
+
+ return query;
+}
+
+/**
+ * @summary Gets service account roles
+ */
+export const invalidateGetServiceAccountRoles = async (
+ queryClient: QueryClient,
+ { id }: GetServiceAccountRolesPathParameters,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getGetServiceAccountRolesQueryKey({ id }) },
+ options,
+ );
+
+ return queryClient;
+};
+
+/**
+ * This endpoint assigns a role to a service account
+ * @summary Create service account role
+ */
+export const createServiceAccountRole = (
+ { id }: CreateServiceAccountRolePathParameters,
+ serviceaccounttypesPostableServiceAccountRoleDTO: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<CreateServiceAccountRole201>({
+ url: `/api/v1/service_accounts/${id}/roles`,
+ method: 'POST',
headers: { 'Content-Type': 'application/json' },
- data: serviceaccounttypesUpdatableServiceAccountStatusDTO,
+ data: serviceaccounttypesPostableServiceAccountRoleDTO,
+ signal,
});
};
-export const getUpdateServiceAccountStatusMutationOptions = <
+export const getCreateServiceAccountRoleMutationOptions = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
- Awaited<ReturnType<typeof updateServiceAccountStatus>>,
+ Awaited<ReturnType<typeof createServiceAccountRole>>,
TError,
{
- pathParams: UpdateServiceAccountStatusPathParameters;
- data: BodyType<ServiceaccounttypesUpdatableServiceAccountStatusDTO>;
+ pathParams: CreateServiceAccountRolePathParameters;
+ data: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
},
TContext
>;
}): UseMutationOptions<
- Awaited<ReturnType<typeof updateServiceAccountStatus>>,
+ Awaited<ReturnType<typeof createServiceAccountRole>>,
TError,
{
- pathParams: UpdateServiceAccountStatusPathParameters;
- data: BodyType<ServiceaccounttypesUpdatableServiceAccountStatusDTO>;
+ pathParams: CreateServiceAccountRolePathParameters;
+ data: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
},
TContext
> => {
- const mutationKey = ['updateServiceAccountStatus'];
+ const mutationKey = ['createServiceAccountRole'];
const { mutation: mutationOptions } = options
? options.mutation &&
'mutationKey' in options.mutation &&
@@ -918,52 +1028,299 @@ export const getUpdateServiceAccountStatusMutationOptions = <
: { mutation: { mutationKey } };
const mutationFn: MutationFunction<
- Awaited<ReturnType<typeof updateServiceAccountStatus>>,
+ Awaited<ReturnType<typeof createServiceAccountRole>>,
{
- pathParams: UpdateServiceAccountStatusPathParameters;
- data: BodyType<ServiceaccounttypesUpdatableServiceAccountStatusDTO>;
+ pathParams: CreateServiceAccountRolePathParameters;
+ data: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
}
> = (props) => {
const { pathParams, data } = props ?? {};
- return updateServiceAccountStatus(pathParams, data);
+ return createServiceAccountRole(pathParams, data);
};
return { mutationFn, ...mutationOptions };
};
-export type UpdateServiceAccountStatusMutationResult = NonNullable<
- Awaited<ReturnType<typeof updateServiceAccountStatus>>
+export type CreateServiceAccountRoleMutationResult = NonNullable<
+ Awaited<ReturnType<typeof createServiceAccountRole>>
>;
-export type UpdateServiceAccountStatusMutationBody = BodyType<ServiceaccounttypesUpdatableServiceAccountStatusDTO>;
-export type UpdateServiceAccountStatusMutationError = ErrorType<RenderErrorResponseDTO>;
+export type CreateServiceAccountRoleMutationBody = BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
+export type CreateServiceAccountRoleMutationError = ErrorType<RenderErrorResponseDTO>;
/**
- * @summary Updates a service account status
+ * @summary Create service account role
*/
-export const useUpdateServiceAccountStatus = <
+export const useCreateServiceAccountRole = <
TError = ErrorType<RenderErrorResponseDTO>,
TContext = unknown
>(options?: {
mutation?: UseMutationOptions<
- Awaited<ReturnType<typeof updateServiceAccountStatus>>,
+ Awaited<ReturnType<typeof createServiceAccountRole>>,
TError,
{
- pathParams: UpdateServiceAccountStatusPathParameters;
- data: BodyType<ServiceaccounttypesUpdatableServiceAccountStatusDTO>;
+ pathParams: CreateServiceAccountRolePathParameters;
+ data: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
},
TContext
>;
}): UseMutationResult<
- Awaited<ReturnType<typeof updateServiceAccountStatus>>,
+ Awaited<ReturnType<typeof createServiceAccountRole>>,
TError,
{
- pathParams: UpdateServiceAccountStatusPathParameters;
- data: BodyType<ServiceaccounttypesUpdatableServiceAccountStatusDTO>;
+ pathParams: CreateServiceAccountRolePathParameters;
+ data: BodyType<ServiceaccounttypesPostableServiceAccountRoleDTO>;
},
TContext
> => {
- const mutationOptions = getUpdateServiceAccountStatusMutationOptions(options);
+ const mutationOptions = getCreateServiceAccountRoleMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * This endpoint revokes a role from service account
+ * @summary Delete service account role
+ */
+export const deleteServiceAccountRole = ({
+ id,
+ rid,
+}: DeleteServiceAccountRolePathParameters) => {
+ return GeneratedAPIInstance<string>({
+ url: `/api/v1/service_accounts/${id}/roles/${rid}`,
+ method: 'DELETE',
+ });
+};
+
+export const getDeleteServiceAccountRoleMutationOptions = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof deleteServiceAccountRole>>,
+ TError,
+ { pathParams: DeleteServiceAccountRolePathParameters },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof deleteServiceAccountRole>>,
+ TError,
+ { pathParams: DeleteServiceAccountRolePathParameters },
+ TContext
+> => {
+ const mutationKey = ['deleteServiceAccountRole'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof deleteServiceAccountRole>>,
+ { pathParams: DeleteServiceAccountRolePathParameters }
+ > = (props) => {
+ const { pathParams } = props ?? {};
+
+ return deleteServiceAccountRole(pathParams);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type DeleteServiceAccountRoleMutationResult = NonNullable<
+ Awaited<ReturnType<typeof deleteServiceAccountRole>>
+>;
+
+export type DeleteServiceAccountRoleMutationError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Delete service account role
+ */
+export const useDeleteServiceAccountRole = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof deleteServiceAccountRole>>,
+ TError,
+ { pathParams: DeleteServiceAccountRolePathParameters },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof deleteServiceAccountRole>>,
+ TError,
+ { pathParams: DeleteServiceAccountRolePathParameters },
+ TContext
+> => {
+ const mutationOptions = getDeleteServiceAccountRoleMutationOptions(options);
+
+ return useMutation(mutationOptions);
+};
+/**
+ * This endpoint gets my service account
+ * @summary Gets my service account
+ */
+export const getMyServiceAccount = (signal?: AbortSignal) => {
+ return GeneratedAPIInstance<GetMyServiceAccount200>({
+ url: `/api/v1/service_accounts/me`,
+ method: 'GET',
+ signal,
+ });
+};
+
+export const getGetMyServiceAccountQueryKey = () => {
+ return [`/api/v1/service_accounts/me`] as const;
+};
+
+export const getGetMyServiceAccountQueryOptions = <
+ TData = Awaited<ReturnType<typeof getMyServiceAccount>>,
+ TError = ErrorType<RenderErrorResponseDTO>
+>(options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getMyServiceAccount>>,
+ TError,
+ TData
+ >;
+}) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey = queryOptions?.queryKey ?? getGetMyServiceAccountQueryKey();
+
+ const queryFn: QueryFunction<
+ Awaited<ReturnType<typeof getMyServiceAccount>>
+ > = ({ signal }) => getMyServiceAccount(signal);
+
+ return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
+ Awaited<ReturnType<typeof getMyServiceAccount>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type GetMyServiceAccountQueryResult = NonNullable<
+ Awaited<ReturnType<typeof getMyServiceAccount>>
+>;
+export type GetMyServiceAccountQueryError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Gets my service account
+ */
+
+export function useGetMyServiceAccount<
+ TData = Awaited<ReturnType<typeof getMyServiceAccount>>,
+ TError = ErrorType<RenderErrorResponseDTO>
+>(options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getMyServiceAccount>>,
+ TError,
+ TData
+ >;
+}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getGetMyServiceAccountQueryOptions(options);
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ query.queryKey = queryOptions.queryKey;
+
+ return query;
+}
+
+/**
+ * @summary Gets my service account
+ */
+export const invalidateGetMyServiceAccount = async (
+ queryClient: QueryClient,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getGetMyServiceAccountQueryKey() },
+ options,
+ );
+
+ return queryClient;
+};
+
+/**
+ * This endpoint gets my service account
+ * @summary Updates my service account
+ */
+export const updateMyServiceAccount = (
+ serviceaccounttypesPostableServiceAccountDTO: BodyType<ServiceaccounttypesPostableServiceAccountDTO>,
+) => {
+ return GeneratedAPIInstance<string>({
+ url: `/api/v1/service_accounts/me`,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ data: serviceaccounttypesPostableServiceAccountDTO,
+ });
+};
+
+export const getUpdateMyServiceAccountMutationOptions = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof updateMyServiceAccount>>,
+ TError,
+ { data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof updateMyServiceAccount>>,
+ TError,
+ { data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
+ TContext
+> => {
+ const mutationKey = ['updateMyServiceAccount'];
+ const { mutation: mutationOptions } = options
+ ? options.mutation &&
+ 'mutationKey' in options.mutation &&
+ options.mutation.mutationKey
+ ? options
+ : { ...options, mutation: { ...options.mutation, mutationKey } }
+ : { mutation: { mutationKey } };
+
+ const mutationFn: MutationFunction<
+ Awaited<ReturnType<typeof updateMyServiceAccount>>,
+ { data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> }
+ > = (props) => {
+ const { data } = props ?? {};
+
+ return updateMyServiceAccount(data);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type UpdateMyServiceAccountMutationResult = NonNullable<
+ Awaited<ReturnType<typeof updateMyServiceAccount>>
+>;
+export type UpdateMyServiceAccountMutationBody = BodyType<ServiceaccounttypesPostableServiceAccountDTO>;
+export type UpdateMyServiceAccountMutationError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Updates my service account
+ */
+export const useUpdateMyServiceAccount = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof updateMyServiceAccount>>,
+ TError,
+ { data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof updateMyServiceAccount>>,
+ TError,
+ { data: BodyType<ServiceaccounttypesPostableServiceAccountDTO> },
+ TContext
+> => {
+ const mutationOptions = getUpdateMyServiceAccountMutationOptions(options);
return useMutation(mutationOptions);
};
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index 2dc46a406e..b87c32cfe8 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -2843,7 +2843,7 @@ export interface RulestatehistorytypesGettableRuleStateWindowDTO {
state: RulestatehistorytypesAlertStateDTO;
}
-export interface ServiceaccounttypesFactorAPIKeyDTO {
+export interface ServiceaccounttypesGettableFactorAPIKeyDTO {
/**
* @type string
* @format date-time
@@ -2858,10 +2858,6 @@ export interface ServiceaccounttypesFactorAPIKeyDTO {
* @type string
*/
id: string;
- /**
- * @type string
- */
- key: string;
/**
* @type string
* @format date-time
@@ -2906,18 +2902,17 @@ export interface ServiceaccounttypesPostableFactorAPIKeyDTO {
}
export interface ServiceaccounttypesPostableServiceAccountDTO {
- /**
- * @type string
- */
- email: string;
/**
* @type string
*/
name: string;
+}
+
+export interface ServiceaccounttypesPostableServiceAccountRoleDTO {
/**
- * @type array
+ * @type string
*/
- roles: string[];
+ id: string;
}
export interface ServiceaccounttypesServiceAccountDTO {
@@ -2926,11 +2921,6 @@ export interface ServiceaccounttypesServiceAccountDTO {
* @format date-time
*/
createdAt?: Date;
- /**
- * @type string
- * @format date-time
- */
- deletedAt: Date;
/**
* @type string
*/
@@ -2947,10 +2937,6 @@ export interface ServiceaccounttypesServiceAccountDTO {
* @type string
*/
orgId: string;
- /**
- * @type array
- */
- roles: string[];
/**
* @type string
*/
@@ -2962,38 +2948,80 @@ export interface ServiceaccounttypesServiceAccountDTO {
updatedAt?: Date;
}
-export interface ServiceaccounttypesUpdatableFactorAPIKeyDTO {
+export interface ServiceaccounttypesServiceAccountRoleDTO {
/**
- * @type integer
- * @minimum 0
+ * @type string
+ * @format date-time
*/
- expiresAt: number;
+ createdAt?: Date;
/**
* @type string
*/
- name: string;
+ id: string;
+ role: AuthtypesRoleDTO;
+ /**
+ * @type string
+ */
+ roleId: string;
+ /**
+ * @type string
+ */
+ serviceAccountId: string;
+ /**
+ * @type string
+ * @format date-time
+ */
+ updatedAt?: Date;
}
-export interface ServiceaccounttypesUpdatableServiceAccountDTO {
+export interface ServiceaccounttypesServiceAccountWithRolesDTO {
+ /**
+ * @type string
+ * @format date-time
+ */
+ createdAt?: Date;
/**
* @type string
*/
email: string;
+ /**
+ * @type string
+ */
+ id: string;
/**
* @type string
*/
name: string;
+ /**
+ * @type string
+ */
+ orgId: string;
/**
* @type array
+ * @nullable true
+ */
+ serviceAccountRoles: ServiceaccounttypesServiceAccountRoleDTO[] | null;
+ /**
+ * @type string
+ */
+ status: string;
+ /**
+ * @type string
+ * @format date-time
*/
- roles: string[];
+ updatedAt?: Date;
}
-export interface ServiceaccounttypesUpdatableServiceAccountStatusDTO {
+export interface ServiceaccounttypesUpdatableFactorAPIKeyDTO {
+ /**
+ * @type integer
+ * @minimum 0
+ */
+ expiresAt: number;
/**
* @type string
*/
- status: string;
+ name: string;
}
export enum TelemetrytypesFieldContextDTO {
@@ -3139,63 +3167,6 @@ export interface TypesDeprecatedUserDTO {
updatedAt?: Date;
}
-export interface TypesGettableAPIKeyDTO {
- /**
- * @type string
- * @format date-time
- */
- createdAt?: Date;
- /**
- * @type string
- */
- createdBy?: string;
- createdByUser?: TypesUserDTO;
- /**
- * @type integer
- * @format int64
- */
- expiresAt?: number;
- /**
- * @type string
- */
- id: string;
- /**
- * @type integer
- * @format int64
- */
- lastUsed?: number;
- /**
- * @type string
- */
- name?: string;
- /**
- * @type boolean
- */
- revoked?: boolean;
- /**
- * @type string
- */
- role?: string;
- /**
- * @type string
- */
- token?: string;
- /**
- * @type string
- * @format date-time
- */
- updatedAt?: Date;
- /**
- * @type string
- */
- updatedBy?: string;
- updatedByUser?: TypesUserDTO;
- /**
- * @type string
- */
- userId?: string;
-}
-
export interface TypesIdentifiableDTO {
/**
* @type string
@@ -3278,22 +3249,6 @@ export interface TypesOrganizationDTO {
updatedAt?: Date;
}
-export interface TypesPostableAPIKeyDTO {
- /**
- * @type integer
- * @format int64
- */
- expiresInDays?: number;
- /**
- * @type string
- */
- name?: string;
- /**
- * @type string
- */
- role?: string;
-}
-
export interface TypesPostableBulkInviteRequestDTO {
/**
* @type array
@@ -3373,51 +3328,6 @@ export interface TypesResetPasswordTokenDTO {
token?: string;
}
-export interface TypesStorableAPIKeyDTO {
- /**
- * @type string
- * @format date-time
- */
- createdAt?: Date;
- /**
- * @type string
- */
- createdBy?: string;
- /**
- * @type string
- */
- id: string;
- /**
- * @type string
- */
- name?: string;
- /**
- * @type boolean
- */
- revoked?: boolean;
- /**
- * @type string
- */
- role?: string;
- /**
- * @type string
- */
- token?: string;
- /**
- * @type string
- * @format date-time
- */
- updatedAt?: Date;
- /**
- * @type string
- */
- updatedBy?: string;
- /**
- * @type string
- */
- userId?: string;
-}
-
export interface TypesUpdatableUserDTO {
/**
* @type string
@@ -3956,31 +3866,6 @@ export type GetOrgPreference200 = {
export type UpdateOrgPreferencePathParameters = {
name: string;
};
-export type ListAPIKeys200 = {
- /**
- * @type array
- */
- data: TypesGettableAPIKeyDTO[];
- /**
- * @type string
- */
- status: string;
-};
-
-export type CreateAPIKey201 = {
- data: TypesGettableAPIKeyDTO;
- /**
- * @type string
- */
- status: string;
-};
-
-export type RevokeAPIKeyPathParameters = {
- id: string;
-};
-export type UpdateAPIKeyPathParameters = {
- id: string;
-};
export type GetPublicDashboardDataPathParameters = {
id: string;
};
@@ -4085,7 +3970,7 @@ export type GetServiceAccountPathParameters = {
id: string;
};
export type GetServiceAccount200 = {
- data: ServiceaccounttypesServiceAccountDTO;
+ data: ServiceaccounttypesServiceAccountWithRolesDTO;
/**
* @type string
*/
@@ -4102,7 +3987,7 @@ export type ListServiceAccountKeys200 = {
/**
* @type array
*/
- data: ServiceaccounttypesFactorAPIKeyDTO[];
+ data: ServiceaccounttypesGettableFactorAPIKeyDTO[];
/**
* @type string
*/
@@ -4128,9 +4013,44 @@ export type UpdateServiceAccountKeyPathParameters = {
id: string;
fid: string;
};
-export type UpdateServiceAccountStatusPathParameters = {
+export type GetServiceAccountRolesPathParameters = {
+ id: string;
+};
+export type GetServiceAccountRoles200 = {
+ /**
+ * @type array
+ * @nullable true
+ */
+ data: AuthtypesRoleDTO[] | null;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
+export type CreateServiceAccountRolePathParameters = {
+ id: string;
+};
+export type CreateServiceAccountRole201 = {
+ data: TypesIdentifiableDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
+export type DeleteServiceAccountRolePathParameters = {
id: string;
+ rid: string;
};
+export type GetMyServiceAccount200 = {
+ data: ServiceaccounttypesServiceAccountWithRolesDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
export type ListUsersDeprecated200 = {
/**
* @type array
diff --git a/frontend/src/api/generated/services/users/index.ts b/frontend/src/api/generated/services/users/index.ts
index c68e317c4e..bf110e7bde 100644
--- a/frontend/src/api/generated/services/users/index.ts
+++ b/frontend/src/api/generated/services/users/index.ts
@@ -21,7 +21,6 @@ import type { BodyType, ErrorType } from '../../../generatedAPIInstance';
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
import type {
ChangePasswordPathParameters,
- CreateAPIKey201,
CreateInvite201,
DeleteUserPathParameters,
GetMyUser200,
@@ -36,24 +35,19 @@ import type {
GetUserPathParameters,
GetUsersByRoleID200,
GetUsersByRoleIDPathParameters,
- ListAPIKeys200,
ListUsers200,
ListUsersDeprecated200,
RemoveUserRoleByUserIDAndRoleIDPathParameters,
RenderErrorResponseDTO,
- RevokeAPIKeyPathParameters,
SetRoleByUserIDPathParameters,
TypesChangePasswordRequestDTO,
TypesDeprecatedUserDTO,
- TypesPostableAPIKeyDTO,
TypesPostableBulkInviteRequestDTO,
TypesPostableForgotPasswordDTO,
TypesPostableInviteDTO,
TypesPostableResetPasswordDTO,
TypesPostableRoleDTO,
- TypesStorableAPIKeyDTO,
TypesUpdatableUserDTO,
- UpdateAPIKeyPathParameters,
UpdateUserDeprecated200,
UpdateUserDeprecatedPathParameters,
UpdateUserPathParameters,
@@ -428,349 +422,6 @@ export const useCreateBulkInvite = <
return useMutation(mutationOptions);
};
-/**
- * This endpoint lists all api keys
- * @summary List api keys
- */
-export const listAPIKeys = (signal?: AbortSignal) => {
- return GeneratedAPIInstance<ListAPIKeys200>({
- url: `/api/v1/pats`,
- method: 'GET',
- signal,
- });
-};
-
-export const getListAPIKeysQueryKey = () => {
- return [`/api/v1/pats`] as const;
-};
-
-export const getListAPIKeysQueryOptions = <
- TData = Awaited<ReturnType<typeof listAPIKeys>>,
- TError = ErrorType<RenderErrorResponseDTO>
->(options?: {
- query?: UseQueryOptions<
- Awaited<ReturnType<typeof listAPIKeys>>,
- TError,
- TData
- >;
-}) => {
- const { query: queryOptions } = options ?? {};
-
- const queryKey = queryOptions?.queryKey ?? getListAPIKeysQueryKey();
-
- const queryFn: QueryFunction<Awaited<ReturnType<typeof listAPIKeys>>> = ({
- signal,
- }) => listAPIKeys(signal);
-
- return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
- Awaited<ReturnType<typeof listAPIKeys>>,
- TError,
- TData
- > & { queryKey: QueryKey };
-};
-
-export type ListAPIKeysQueryResult = NonNullable<
- Awaited<ReturnType<typeof listAPIKeys>>
->;
-export type ListAPIKeysQueryError = ErrorType<RenderErrorResponseDTO>;
-
-/**
- * @summary List api keys
- */
-
-export function useListAPIKeys<
- TData = Awaited<ReturnType<typeof listAPIKeys>>,
- TError = ErrorType<RenderErrorResponseDTO>
->(options?: {
- query?: UseQueryOptions<
- Awaited<ReturnType<typeof listAPIKeys>>,
- TError,
- TData
- >;
-}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
- const queryOptions = getListAPIKeysQueryOptions(options);
-
- const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
- queryKey: QueryKey;
- };
-
- query.queryKey = queryOptions.queryKey;
-
- return query;
-}
-
-/**
- * @summary List api keys
- */
-export const invalidateListAPIKeys = async (
- queryClient: QueryClient,
- options?: InvalidateOptions,
-): Promise<QueryClient> => {
- await queryClient.invalidateQueries(
- { queryKey: getListAPIKeysQueryKey() },
- options,
- );
-
- return queryClient;
-};
-
-/**
- * This endpoint creates an api key
- * @summary Create api key
- */
-export const createAPIKey = (
- typesPostableAPIKeyDTO: BodyType<TypesPostableAPIKeyDTO>,
- signal?: AbortSignal,
-) => {
- return GeneratedAPIInstance<CreateAPIKey201>({
- url: `/api/v1/pats`,
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- data: typesPostableAPIKeyDTO,
- signal,
- });
-};
-
-export const getCreateAPIKeyMutationOptions = <
- TError = ErrorType<RenderErrorResponseDTO>,
- TContext = unknown
->(options?: {
- mutation?: UseMutationOptions<
- Awaited<ReturnType<typeof createAPIKey>>,
- TError,
- { data: BodyType<TypesPostableAPIKeyDTO> },
- TContext
- >;
-}): UseMutationOptions<
- Awaited<ReturnType<typeof createAPIKey>>,
- TError,
- { data: BodyType<TypesPostableAPIKeyDTO> },
- TContext
-> => {
- const mutationKey = ['createAPIKey'];
- const { mutation: mutationOptions } = options
- ? options.mutation &&
- 'mutationKey' in options.mutation &&
- options.mutation.mutationKey
- ? options
- : { ...options, mutation: { ...options.mutation, mutationKey } }
- : { mutation: { mutationKey } };
-
- const mutationFn: MutationFunction<
- Awaited<ReturnType<typeof createAPIKey>>,
- { data: BodyType<TypesPostableAPIKeyDTO> }
- > = (props) => {
- const { data } = props ?? {};
-
- return createAPIKey(data);
- };
-
- return { mutationFn, ...mutationOptions };
-};
-
-export type CreateAPIKeyMutationResult = NonNullable<
- Awaited<ReturnType<typeof createAPIKey>>
->;
-export type CreateAPIKeyMutationBody = BodyType<TypesPostableAPIKeyDTO>;
-export type CreateAPIKeyMutationError = ErrorType<RenderErrorResponseDTO>;
-
-/**
- * @summary Create api key
- */
-export const useCreateAPIKey = <
- TError = ErrorType<RenderErrorResponseDTO>,
- TContext = unknown
->(options?: {
- mutation?: UseMutationOptions<
- Awaited<ReturnType<typeof createAPIKey>>,
- TError,
- { data: BodyType<TypesPostableAPIKeyDTO> },
- TContext
- >;
-}): UseMutationResult<
- Awaited<ReturnType<typeof createAPIKey>>,
- TError,
- { data: BodyType<TypesPostableAPIKeyDTO> },
- TContext
-> => {
- const mutationOptions = getCreateAPIKeyMutationOptions(options);
-
- return useMutation(mutationOptions);
-};
-/**
- * This endpoint revokes an api key
- * @summary Revoke api key
- */
-export const revokeAPIKey = ({ id }: RevokeAPIKeyPathParameters) => {
- return GeneratedAPIInstance<void>({
- url: `/api/v1/pats/${id}`,
- method: 'DELETE',
- });
-};
-
-export const getRevokeAPIKeyMutationOptions = <
- TError = ErrorType<RenderErrorResponseDTO>,
- TContext = unknown
->(options?: {
- mutation?: UseMutationOptions<
- Awaited<ReturnType<typeof revokeAPIKey>>,
- TError,
- { pathParams: RevokeAPIKeyPathParameters },
- TContext
- >;
-}): UseMutationOptions<
- Awaited<ReturnType<typeof revokeAPIKey>>,
- TError,
- { pathParams: RevokeAPIKeyPathParameters },
- TContext
-> => {
- const mutationKey = ['revokeAPIKey'];
- const { mutation: mutationOptions } = options
- ? options.mutation &&
- 'mutationKey' in options.mutation &&
- options.mutation.mutationKey
- ? options
- : { ...options, mutation: { ...options.mutation, mutationKey } }
- : { mutation: { mutationKey } };
-
- const mutationFn: MutationFunction<
- Awaited<ReturnType<typeof revokeAPIKey>>,
- { pathParams: RevokeAPIKeyPathParameters }
- > = (props) => {
- const { pathParams } = props ?? {};
-
- return revokeAPIKey(pathParams);
- };
-
- return { mutationFn, ...mutationOptions };
-};
-
-export type RevokeAPIKeyMutationResult = NonNullable<
- Awaited<ReturnType<typeof revokeAPIKey>>
->;
-
-export type RevokeAPIKeyMutationError = ErrorType<RenderErrorResponseDTO>;
-
-/**
- * @summary Revoke api key
- */
-export const useRevokeAPIKey = <
- TError = ErrorType<RenderErrorResponseDTO>,
- TContext = unknown
->(options?: {
- mutation?: UseMutationOptions<
- Awaited<ReturnType<typeof revokeAPIKey>>,
- TError,
- { pathParams: RevokeAPIKeyPathParameters },
- TContext
- >;
-}): UseMutationResult<
- Awaited<ReturnType<typeof revokeAPIKey>>,
- TError,
- { pathParams: RevokeAPIKeyPathParameters },
- TContext
-> => {
- const mutationOptions = getRevokeAPIKeyMutationOptions(options);
-
- return useMutation(mutationOptions);
-};
-/**
- * This endpoint updates an api key
- * @summary Update api key
- */
-export const updateAPIKey = (
- { id }: UpdateAPIKeyPathParameters,
- typesStorableAPIKeyDTO: BodyType<TypesStorableAPIKeyDTO>,
-) => {
- return GeneratedAPIInstance<string>({
- url: `/api/v1/pats/${id}`,
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- data: typesStorableAPIKeyDTO,
- });
-};
-
-export const getUpdateAPIKeyMutationOptions = <
- TError = ErrorType<RenderErrorResponseDTO>,
- TContext = unknown
->(options?: {
- mutation?: UseMutationOptions<
- Awaited<ReturnType<typeof updateAPIKey>>,
- TError,
- {
- pathParams: UpdateAPIKeyPathParameters;
- data: BodyType<TypesStorableAPIKeyDTO>;
- },
- TContext
- >;
-}): UseMutationOptions<
- Awaited<ReturnType<typeof updateAPIKey>>,
- TError,
- {
- pathParams: UpdateAPIKeyPathParameters;
- data: BodyType<TypesStorableAPIKeyDTO>;
- },
- TContext
-> => {
- const mutationKey = ['updateAPIKey'];
- const { mutation: mutationOptions } = options
- ? options.mutation &&
- 'mutationKey' in options.mutation &&
- options.mutation.mutationKey
- ? options
- : { ...options, mutation: { ...options.mutation, mutationKey } }
- : { mutation: { mutationKey } };
-
- const mutationFn: MutationFunction<
- Awaited<ReturnType<typeof updateAPIKey>>,
- {
- pathParams: UpdateAPIKeyPathParameters;
- data: BodyType<TypesStorableAPIKeyDTO>;
- }
- > = (props) => {
- const { pathParams, data } = props ?? {};
-
- return updateAPIKey(pathParams, data);
- };
-
- return { mutationFn, ...mutationOptions };
-};
-
-export type UpdateAPIKeyMutationResult = NonNullable<
- Awaited<ReturnType<typeof updateAPIKey>>
->;
-export type UpdateAPIKeyMutationBody = BodyType<TypesStorableAPIKeyDTO>;
-export type UpdateAPIKeyMutationError = ErrorType<RenderErrorResponseDTO>;
-
-/**
- * @summary Update api key
- */
-export const useUpdateAPIKey = <
- TError = ErrorType<RenderErrorResponseDTO>,
- TContext = unknown
->(options?: {
- mutation?: UseMutationOptions<
- Awaited<ReturnType<typeof updateAPIKey>>,
- TError,
- {
- pathParams: UpdateAPIKeyPathParameters;
- data: BodyType<TypesStorableAPIKeyDTO>;
- },
- TContext
- >;
-}): UseMutationResult<
- Awaited<ReturnType<typeof updateAPIKey>>,
- TError,
- {
- pathParams: UpdateAPIKeyPathParameters;
- data: BodyType<TypesStorableAPIKeyDTO>;
- },
- TContext
-> => {
- const mutationOptions = getUpdateAPIKeyMutationOptions(options);
-
- return useMutation(mutationOptions);
-};
/**
* This endpoint resets the password by token
* @summary Reset password
diff --git a/frontend/src/api/v1/pats/create.ts b/frontend/src/api/v1/pats/create.ts
deleted file mode 100644
index c487a91bb3..0000000000
--- a/frontend/src/api/v1/pats/create.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import axios from 'api';
-import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
-import { AxiosError } from 'axios';
-import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
-import {
- APIKeyProps,
- CreateAPIKeyProps,
- CreatePayloadProps,
-} from 'types/api/pat/types';
-
-const create = async (
- props: CreateAPIKeyProps,
-): Promise<SuccessResponseV2<APIKeyProps>> => {
- try {
- const response = await axios.post<CreatePayloadProps>('/pats', {
- ...props,
- });
-
- return {
- httpStatusCode: response.status,
- data: response.data.data,
- };
- } catch (error) {
- ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
- }
-};
-
-export default create;
diff --git a/frontend/src/api/v1/pats/delete.ts b/frontend/src/api/v1/pats/delete.ts
deleted file mode 100644
index 716bdffc19..0000000000
--- a/frontend/src/api/v1/pats/delete.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import axios from 'api';
-import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
-import { AxiosError } from 'axios';
-import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
-
-const deleteAPIKey = async (id: string): Promise<SuccessResponseV2<null>> => {
- try {
- const response = await axios.delete(`/pats/${id}`);
-
- return {
- httpStatusCode: response.status,
- data: null,
- };
- } catch (error) {
- ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
- }
-};
-
-export default deleteAPIKey;
diff --git a/frontend/src/api/v1/pats/list.ts b/frontend/src/api/v1/pats/list.ts
deleted file mode 100644
index bc4833af51..0000000000
--- a/frontend/src/api/v1/pats/list.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import axios from 'api';
-import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
-import { AxiosError } from 'axios';
-import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
-import { AllAPIKeyProps, APIKeyProps } from 'types/api/pat/types';
-
-const list = async (): Promise<SuccessResponseV2<APIKeyProps[]>> => {
- try {
- const response = await axios.get<AllAPIKeyProps>('/pats');
-
- return {
- httpStatusCode: response.status,
- data: response.data.data,
- };
- } catch (error) {
- ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
- }
-};
-
-export default list;
diff --git a/frontend/src/api/v1/pats/update.ts b/frontend/src/api/v1/pats/update.ts
deleted file mode 100644
index b7c1e016c8..0000000000
--- a/frontend/src/api/v1/pats/update.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import axios from 'api';
-import { ErrorResponseHandlerV2 } from 'api/ErrorResponseHandlerV2';
-import { AxiosError } from 'axios';
-import { ErrorV2Resp, SuccessResponseV2 } from 'types/api';
-import { UpdateAPIKeyProps } from 'types/api/pat/types';
-
-const updateAPIKey = async (
- props: UpdateAPIKeyProps,
-): Promise<SuccessResponseV2<null>> => {
- try {
- const response = await axios.put(`/pats/${props.id}`, {
- ...props.data,
- });
-
- return {
- httpStatusCode: response.status,
- data: null,
- };
- } catch (error) {
- ErrorResponseHandlerV2(error as AxiosError<ErrorV2Resp>);
- }
-};
-
-export default updateAPIKey;
diff --git a/frontend/src/components/CreateServiceAccountModal/CreateServiceAccountModal.tsx b/frontend/src/components/CreateServiceAccountModal/CreateServiceAccountModal.tsx
index 1b8c6c78c4..617328d4e3 100644
--- a/frontend/src/components/CreateServiceAccountModal/CreateServiceAccountModal.tsx
+++ b/frontend/src/components/CreateServiceAccountModal/CreateServiceAccountModal.tsx
@@ -12,17 +12,13 @@ import {
} from 'api/generated/services/serviceaccount';
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
import { AxiosError } from 'axios';
-import RolesSelect, { useRoles } from 'components/RolesSelect';
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
import { parseAsBoolean, useQueryState } from 'nuqs';
-import { EMAIL_REGEX } from 'utils/app';
import './CreateServiceAccountModal.styles.scss';
interface FormValues {
name: string;
- email: string;
- roles: string[];
}
function CreateServiceAccountModal(): JSX.Element {
@@ -41,8 +37,6 @@ function CreateServiceAccountModal(): JSX.Element {
mode: 'onChange',
defaultValues: {
name: '',
- email: '',
- roles: [],
},
});
@@ -70,13 +64,6 @@ function CreateServiceAccountModal(): JSX.Element {
},
},
});
- const {
- roles,
- isLoading: rolesLoading,
- isError: rolesError,
- error: rolesErrorObj,
- refetch: refetchRoles,
- } = useRoles();
function handleClose(): void {
reset();
@@ -87,8 +74,6 @@ function CreateServiceAccountModal(): JSX.Element {
createServiceAccount({
data: {
name: values.name.trim(),
- email: values.email.trim(),
- roles: values.roles,
},
});
}
@@ -134,68 +119,6 @@ function CreateServiceAccountModal(): JSX.Element {
<p className="create-sa-form__error">{errors.name.message}</p>
)}
</div>
-
- <div className="create-sa-form__item">
- <label htmlFor="sa-email">Email Address</label>
- <Controller
- name="email"
- control={control}
- rules={{
- required: 'Email Address is required',
- pattern: {
- value: EMAIL_REGEX,
- message: 'Please enter a valid email address',
- },
- }}
- render={({ field }): JSX.Element => (
- <Input
- id="sa-email"
- type="email"
- placeholder="[email protected]"
- className="create-sa-form__input"
- value={field.value}
- onChange={field.onChange}
- onBlur={field.onBlur}
- />
- )}
- />
- {errors.email && (
- <p className="create-sa-form__error">{errors.email.message}</p>
- )}
- </div>
- <p className="create-sa-form__helper">
- Used only for notifications about this service account. It is not used for
- authentication.
- </p>
-
- <div className="create-sa-form__item">
- <label htmlFor="sa-roles">Roles</label>
- <Controller
- name="roles"
- control={control}
- rules={{
- validate: (value): string | true =>
- value.length > 0 || 'At least one role is required',
- }}
- render={({ field }): JSX.Element => (
- <RolesSelect
- id="sa-roles"
- mode="multiple"
- roles={roles}
- loading={rolesLoading}
- isError={rolesError}
- error={rolesErrorObj}
- onRefetch={refetchRoles}
- placeholder="Select roles"
- value={field.value}
- onChange={field.onChange}
- />
- )}
- />
- {errors.roles && (
- <p className="create-sa-form__error">{errors.roles.message}</p>
- )}
- </div>
</form>
</div>
diff --git a/frontend/src/components/CreateServiceAccountModal/__tests__/CreateServiceAccountModal.test.tsx b/frontend/src/components/CreateServiceAccountModal/__tests__/CreateServiceAccountModal.test.tsx
index 8dea4e2d3c..a9d0ab9440 100644
--- a/frontend/src/components/CreateServiceAccountModal/__tests__/CreateServiceAccountModal.test.tsx
+++ b/frontend/src/components/CreateServiceAccountModal/__tests__/CreateServiceAccountModal.test.tsx
@@ -1,5 +1,4 @@
import { toast } from '@signozhq/sonner';
-import { listRolesSuccessResponse } from 'mocks-server/__mockdata__/roles';
import { rest, server } from 'mocks-server/server';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
@@ -12,7 +11,6 @@ jest.mock('@signozhq/sonner', () => ({
const mockToast = jest.mocked(toast);
-const ROLES_ENDPOINT = '*/api/v1/roles';
const SERVICE_ACCOUNTS_ENDPOINT = '*/api/v1/service_accounts';
function renderModal(): ReturnType<typeof render> {
@@ -27,9 +25,6 @@ describe('CreateServiceAccountModal', () => {
beforeEach(() => {
jest.clearAllMocks();
server.use(
- rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
- res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
- ),
rest.post(SERVICE_ACCOUNTS_ENDPOINT, (_, res, ctx) =>
res(ctx.status(201), ctx.json({ status: 'success', data: {} })),
),
@@ -48,38 +43,11 @@ describe('CreateServiceAccountModal', () => {
).toBeDisabled();
});
- it('submit button remains disabled when email is invalid', async () => {
- const user = userEvent.setup({ pointerEventsCheck: 0 });
- renderModal();
-
- await user.type(screen.getByPlaceholderText('Enter a name'), 'My Bot');
- await user.type(
- screen.getByPlaceholderText('[email protected]'),
- 'not-an-email',
- );
-
- await user.click(screen.getByText('Select roles'));
- await user.click(await screen.findByTitle('signoz-admin'));
-
- await waitFor(() =>
- expect(
- screen.getByRole('button', { name: /Create Service Account/i }),
- ).toBeDisabled(),
- );
- });
-
it('successful submit shows toast.success and closes modal', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
await user.type(screen.getByPlaceholderText('Enter a name'), 'Deploy Bot');
- await user.type(
- screen.getByPlaceholderText('[email protected]'),
- );
-
- await user.click(screen.getByText('Select roles'));
- await user.click(await screen.findByTitle('signoz-admin'));
const submitBtn = screen.getByRole('button', {
name: /Create Service Account/i,
@@ -116,13 +84,6 @@ describe('CreateServiceAccountModal', () => {
renderModal();
await user.type(screen.getByPlaceholderText('Enter a name'), 'Dupe Bot');
- await user.type(
- screen.getByPlaceholderText('[email protected]'),
- );
-
- await user.click(screen.getByText('Select roles'));
- await user.click(await screen.findByTitle('signoz-admin'));
const submitBtn = screen.getByRole('button', {
name: /Create Service Account/i,
@@ -164,16 +125,4 @@ describe('CreateServiceAccountModal', () => {
await screen.findByText('Name is required');
});
-
- it('shows "Please enter a valid email address" for a malformed email', async () => {
- const user = userEvent.setup({ pointerEventsCheck: 0 });
- renderModal();
-
- await user.type(
- screen.getByPlaceholderText('[email protected]'),
- 'not-an-email',
- );
-
- await screen.findByText('Please enter a valid email address');
- });
});
diff --git a/frontend/src/components/RolesSelect/RolesSelect.tsx b/frontend/src/components/RolesSelect/RolesSelect.tsx
index b0f8c4c6e0..12d2ea3bc3 100644
--- a/frontend/src/components/RolesSelect/RolesSelect.tsx
+++ b/frontend/src/components/RolesSelect/RolesSelect.tsx
@@ -34,7 +34,7 @@ export function useRoles(): {
export function getRoleOptions(roles: AuthtypesRoleDTO[]): RoleOption[] {
return roles.map((role) => ({
label: role.name ?? '',
- value: role.name ?? '',
+ value: role.id ?? '',
}));
}
diff --git a/frontend/src/components/ServiceAccountDrawer/DisableAccountModal.tsx b/frontend/src/components/ServiceAccountDrawer/DeleteAccountModal.tsx
similarity index 66%
rename from frontend/src/components/ServiceAccountDrawer/DisableAccountModal.tsx
rename to frontend/src/components/ServiceAccountDrawer/DeleteAccountModal.tsx
index 32deed1068..6eba2a2d6d 100644
--- a/frontend/src/components/ServiceAccountDrawer/DisableAccountModal.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/DeleteAccountModal.tsx
@@ -1,13 +1,13 @@
import { useQueryClient } from 'react-query';
import { Button } from '@signozhq/button';
import { DialogFooter, DialogWrapper } from '@signozhq/dialog';
-import { PowerOff, X } from '@signozhq/icons';
+import { Trash2, X } from '@signozhq/icons';
import { toast } from '@signozhq/sonner';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import {
getGetServiceAccountQueryKey,
invalidateListServiceAccounts,
- useUpdateServiceAccountStatus,
+ useDeleteServiceAccount,
} from 'api/generated/services/serviceaccount';
import type {
RenderErrorResponseDTO,
@@ -17,14 +17,14 @@ import { AxiosError } from 'axios';
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
import { parseAsBoolean, useQueryState } from 'nuqs';
-function DisableAccountModal(): JSX.Element {
+function DeleteAccountModal(): JSX.Element {
const queryClient = useQueryClient();
const [accountId, setAccountId] = useQueryState(SA_QUERY_PARAMS.ACCOUNT);
- const [isDisableOpen, setIsDisableOpen] = useQueryState(
- SA_QUERY_PARAMS.DISABLE_SA,
+ const [isDeleteOpen, setIsDeleteOpen] = useQueryState(
+ SA_QUERY_PARAMS.DELETE_SA,
parseAsBoolean.withDefault(false),
);
- const open = !!isDisableOpen && !!accountId;
+ const open = !!isDeleteOpen && !!accountId;
const cachedAccount = accountId
? queryClient.getQueryData<{
@@ -34,13 +34,13 @@ function DisableAccountModal(): JSX.Element {
const accountName = cachedAccount?.data?.name;
const {
- mutate: updateStatus,
- isLoading: isDisabling,
- } = useUpdateServiceAccountStatus({
+ mutate: deleteAccount,
+ isLoading: isDeleting,
+ } = useDeleteServiceAccount({
mutation: {
onSuccess: async () => {
- toast.success('Service account disabled', { richColors: true });
- await setIsDisableOpen(null);
+ toast.success('Service account deleted', { richColors: true });
+ await setIsDeleteOpen(null);
await setAccountId(null);
await invalidateListServiceAccounts(queryClient);
},
@@ -48,7 +48,7 @@ function DisableAccountModal(): JSX.Element {
const errMessage =
convertToApiError(
error as AxiosError<RenderErrorResponseDTO, unknown> | null,
- )?.getErrorMessage() || 'Failed to disable service account';
+ )?.getErrorMessage() || 'Failed to delete service account';
toast.error(errMessage, { richColors: true });
},
},
@@ -58,14 +58,13 @@ function DisableAccountModal(): JSX.Element {
if (!accountId) {
return;
}
- updateStatus({
+ deleteAccount({
pathParams: { id: accountId },
- data: { status: 'DISABLED' },
});
}
function handleCancel(): void {
- setIsDisableOpen(null);
+ setIsDeleteOpen(null);
}
return (
@@ -76,17 +75,18 @@ function DisableAccountModal(): JSX.Element {
handleCancel();
}
}}
- title={`Disable service account ${accountName ?? ''}?`}
+ title={`Delete service account ${accountName ?? ''}?`}
width="narrow"
- className="alert-dialog sa-disable-dialog"
+ className="alert-dialog sa-delete-dialog"
showCloseButton={false}
disableOutsideClick={false}
>
- <p className="sa-disable-dialog__body">
- Disabling this service account will revoke access for all its keys. Any
- systems using this account will lose access immediately.
+ <p className="sa-delete-dialog__body">
+ Are you sure you want to delete <strong>{accountName}</strong>? This action
+ cannot be undone. All keys associated with this service account will be
+ permanently removed.
</p>
- <DialogFooter className="sa-disable-dialog__footer">
+ <DialogFooter className="sa-delete-dialog__footer">
<Button variant="solid" color="secondary" size="sm" onClick={handleCancel}>
<X size={12} />
Cancel
@@ -95,15 +95,15 @@ function DisableAccountModal(): JSX.Element {
variant="solid"
color="destructive"
size="sm"
- loading={isDisabling}
+ loading={isDeleting}
onClick={handleConfirm}
>
- <PowerOff size={12} />
- Disable
+ <Trash2 size={12} />
+ Delete
</Button>
</DialogFooter>
</DialogWrapper>
);
}
-export default DisableAccountModal;
+export default DeleteAccountModal;
diff --git a/frontend/src/components/ServiceAccountDrawer/EditKeyModal/EditKeyForm.tsx b/frontend/src/components/ServiceAccountDrawer/EditKeyModal/EditKeyForm.tsx
index a05277b8de..55510a36a1 100644
--- a/frontend/src/components/ServiceAccountDrawer/EditKeyModal/EditKeyForm.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/EditKeyModal/EditKeyForm.tsx
@@ -6,7 +6,7 @@ import { LockKeyhole, Trash2, X } from '@signozhq/icons';
import { Input } from '@signozhq/input';
import { ToggleGroup, ToggleGroupItem } from '@signozhq/toggle-group';
import { DatePicker } from 'antd';
-import type { ServiceaccounttypesFactorAPIKeyDTO } from 'api/generated/services/sigNoz.schemas';
+import type { ServiceaccounttypesGettableFactorAPIKeyDTO } from 'api/generated/services/sigNoz.schemas';
import { popupContainer } from 'utils/selectPopupContainer';
import { disabledDate, formatLastObservedAt } from '../utils';
@@ -17,7 +17,7 @@ export interface EditKeyFormProps {
register: UseFormRegister<FormValues>;
control: Control<FormValues>;
expiryMode: ExpiryMode;
- keyItem: ServiceaccounttypesFactorAPIKeyDTO | null;
+ keyItem: ServiceaccounttypesGettableFactorAPIKeyDTO | null;
isSaving: boolean;
isDirty: boolean;
onSubmit: () => void;
diff --git a/frontend/src/components/ServiceAccountDrawer/EditKeyModal/index.tsx b/frontend/src/components/ServiceAccountDrawer/EditKeyModal/index.tsx
index e03c6fb421..c2d0c1b2eb 100644
--- a/frontend/src/components/ServiceAccountDrawer/EditKeyModal/index.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/EditKeyModal/index.tsx
@@ -11,7 +11,7 @@ import {
} from 'api/generated/services/serviceaccount';
import type {
RenderErrorResponseDTO,
- ServiceaccounttypesFactorAPIKeyDTO,
+ ServiceaccounttypesGettableFactorAPIKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import { AxiosError } from 'axios';
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
@@ -27,7 +27,7 @@ import { DEFAULT_FORM_VALUES, ExpiryMode } from './types';
import './EditKeyModal.styles.scss';
export interface EditKeyModalProps {
- keyItem: ServiceaccounttypesFactorAPIKeyDTO | null;
+ keyItem: ServiceaccounttypesGettableFactorAPIKeyDTO | null;
}
function EditKeyModal({ keyItem }: EditKeyModalProps): JSX.Element {
diff --git a/frontend/src/components/ServiceAccountDrawer/KeysTab.tsx b/frontend/src/components/ServiceAccountDrawer/KeysTab.tsx
index f33966f72b..1aacbc52dd 100644
--- a/frontend/src/components/ServiceAccountDrawer/KeysTab.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/KeysTab.tsx
@@ -3,7 +3,7 @@ import { Button } from '@signozhq/button';
import { KeyRound, X } from '@signozhq/icons';
import { Skeleton, Table, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table/interface';
-import type { ServiceaccounttypesFactorAPIKeyDTO } from 'api/generated/services/sigNoz.schemas';
+import type { ServiceaccounttypesGettableFactorAPIKeyDTO } from 'api/generated/services/sigNoz.schemas';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import dayjs from 'dayjs';
import { parseAsBoolean, parseAsString, useQueryState } from 'nuqs';
@@ -14,7 +14,7 @@ import RevokeKeyModal from './RevokeKeyModal';
import { formatLastObservedAt } from './utils';
interface KeysTabProps {
- keys: ServiceaccounttypesFactorAPIKeyDTO[];
+ keys: ServiceaccounttypesGettableFactorAPIKeyDTO[];
isLoading: boolean;
isDisabled?: boolean;
currentPage: number;
@@ -44,7 +44,7 @@ function buildColumns({
isDisabled,
onRevokeClick,
handleformatLastObservedAt,
-}: BuildColumnsParams): ColumnsType<ServiceaccounttypesFactorAPIKeyDTO> {
+}: BuildColumnsParams): ColumnsType<ServiceaccounttypesGettableFactorAPIKeyDTO> {
return [
{
title: 'Name',
@@ -183,7 +183,7 @@ function KeysTab({
return (
<>
{/* Todo: use new table component from periscope when ready */}
- <Table<ServiceaccounttypesFactorAPIKeyDTO>
+ <Table<ServiceaccounttypesGettableFactorAPIKeyDTO>
columns={columns}
dataSource={keys}
rowKey="id"
diff --git a/frontend/src/components/ServiceAccountDrawer/OverviewTab.tsx b/frontend/src/components/ServiceAccountDrawer/OverviewTab.tsx
index 98b3e968f5..1fc7df75c0 100644
--- a/frontend/src/components/ServiceAccountDrawer/OverviewTab.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/OverviewTab.tsx
@@ -9,6 +9,9 @@ import { ServiceAccountRow } from 'container/ServiceAccountsSettings/utils';
import { useTimezone } from 'providers/Timezone';
import APIError from 'types/api/error';
+import SaveErrorItem from './SaveErrorItem';
+import type { SaveError } from './utils';
+
interface OverviewTabProps {
account: ServiceAccountRow;
localName: string;
@@ -21,6 +24,7 @@ interface OverviewTabProps {
rolesError?: boolean;
rolesErrorObj?: APIError | undefined;
onRefetchRoles?: () => void;
+ saveErrors?: SaveError[];
}
function OverviewTab({
@@ -35,6 +39,7 @@ function OverviewTab({
rolesError,
rolesErrorObj,
onRefetchRoles,
+ saveErrors = [],
}: OverviewTabProps): JSX.Element {
const { formatTimezoneAdjustedTimestamp } = useTimezone();
@@ -92,11 +97,14 @@ function OverviewTab({
<div className="sa-drawer__input-wrapper sa-drawer__input-wrapper--disabled">
<div className="sa-drawer__disabled-roles">
{localRoles.length > 0 ? (
- localRoles.map((r) => (
- <Badge key={r} color="vanilla">
- {r}
- </Badge>
- ))
+ localRoles.map((roleId) => {
+ const role = availableRoles.find((r) => r.id === roleId);
+ return (
+ <Badge key={roleId} color="vanilla">
+ {role?.name ?? roleId}
+ </Badge>
+ );
+ })
) : (
<span className="sa-drawer__input-text">—</span>
)}
@@ -126,9 +134,13 @@ function OverviewTab({
<Badge color="forest" variant="outline">
ACTIVE
</Badge>
+ ) : account.status?.toUpperCase() === 'DELETED' ? (
+ <Badge color="cherry" variant="outline">
+ DELETED
+ </Badge>
) : (
<Badge color="vanilla" variant="outline" className="sa-status-badge">
- DISABLED
+ {account.status ? account.status.toUpperCase() : 'UNKNOWN'}
</Badge>
)}
</div>
@@ -143,6 +155,19 @@ function OverviewTab({
<Badge color="vanilla">{formatTimestamp(account.updatedAt)}</Badge>
</div>
</div>
+
+ {saveErrors.length > 0 && (
+ <div className="sa-drawer__save-errors">
+ {saveErrors.map(({ context, apiError, onRetry }) => (
+ <SaveErrorItem
+ key={context}
+ context={context}
+ apiError={apiError}
+ onRetry={onRetry}
+ />
+ ))}
+ </div>
+ )}
</>
);
}
diff --git a/frontend/src/components/ServiceAccountDrawer/RevokeKeyModal.tsx b/frontend/src/components/ServiceAccountDrawer/RevokeKeyModal.tsx
index 40ad15baca..690a020d6e 100644
--- a/frontend/src/components/ServiceAccountDrawer/RevokeKeyModal.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/RevokeKeyModal.tsx
@@ -11,7 +11,7 @@ import {
} from 'api/generated/services/serviceaccount';
import type {
RenderErrorResponseDTO,
- ServiceaccounttypesFactorAPIKeyDTO,
+ ServiceaccounttypesGettableFactorAPIKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import { AxiosError } from 'axios';
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
@@ -64,9 +64,9 @@ function RevokeKeyModal(): JSX.Element {
const open = !!revokeKeyId && !!accountId;
const cachedKeys = accountId
- ? queryClient.getQueryData<{ data: ServiceaccounttypesFactorAPIKeyDTO[] }>(
- getListServiceAccountKeysQueryKey({ id: accountId }),
- )
+ ? queryClient.getQueryData<{
+ data: ServiceaccounttypesGettableFactorAPIKeyDTO[];
+ }>(getListServiceAccountKeysQueryKey({ id: accountId }))
: null;
const keyName = cachedKeys?.data?.find((k) => k.id === revokeKeyId)?.name;
diff --git a/frontend/src/components/ServiceAccountDrawer/SaveErrorItem.tsx b/frontend/src/components/ServiceAccountDrawer/SaveErrorItem.tsx
new file mode 100644
index 0000000000..bb7eb19175
--- /dev/null
+++ b/frontend/src/components/ServiceAccountDrawer/SaveErrorItem.tsx
@@ -0,0 +1,74 @@
+import { useState } from 'react';
+import { Button } from '@signozhq/button';
+import { Color } from '@signozhq/design-tokens';
+import { ChevronDown, ChevronUp, CircleAlert, RotateCw } from '@signozhq/icons';
+import ErrorContent from 'components/ErrorModal/components/ErrorContent';
+import APIError from 'types/api/error';
+
+interface SaveErrorItemProps {
+ context: string;
+ apiError: APIError;
+ onRetry?: () => void | Promise<void>;
+}
+
+function SaveErrorItem({
+ context,
+ apiError,
+ onRetry,
+}: SaveErrorItemProps): JSX.Element {
+ const [expanded, setExpanded] = useState(false);
+ const [isRetrying, setIsRetrying] = useState(false);
+
+ const ChevronIcon = expanded ? ChevronUp : ChevronDown;
+
+ return (
+ <div className="sa-error-item">
+ <div
+ role="button"
+ tabIndex={0}
+ className="sa-error-item__header"
+ aria-disabled={isRetrying}
+ onClick={(): void => {
+ if (!isRetrying) {
+ setExpanded((prev) => !prev);
+ }
+ }}
+ >
+ <CircleAlert size={12} className="sa-error-item__icon" />
+ <span className="sa-error-item__title">
+ {isRetrying ? 'Retrying...' : `${context}: ${apiError.getErrorMessage()}`}
+ </span>
+ {onRetry && !isRetrying && (
+ <Button
+ type="button"
+ aria-label="Retry"
+ size="xs"
+ onClick={async (e): Promise<void> => {
+ e.stopPropagation();
+ setIsRetrying(true);
+ setExpanded(false);
+ try {
+ await onRetry();
+ } finally {
+ setIsRetrying(false);
+ }
+ }}
+ >
+ <RotateCw size={12} color={Color.BG_CHERRY_400} />
+ </Button>
+ )}
+ {!isRetrying && (
+ <ChevronIcon size={14} className="sa-error-item__chevron" />
+ )}
+ </div>
+
+ {expanded && !isRetrying && (
+ <div className="sa-error-item__body">
+ <ErrorContent error={apiError} />
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default SaveErrorItem;
diff --git a/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.styles.scss b/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.styles.scss
index a6804dffee..9d12ff0747 100644
--- a/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.styles.scss
+++ b/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.styles.scss
@@ -92,6 +92,23 @@
display: flex;
flex-direction: column;
gap: var(--spacing-8);
+
+ &::-webkit-scrollbar {
+ width: 0.25rem;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: rgba(136, 136, 136, 0.4);
+ border-radius: 0.125rem;
+
+ &:hover {
+ background: rgba(136, 136, 136, 0.7);
+ }
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
}
&__footer {
@@ -239,6 +256,113 @@
letter-spacing: 0.48px;
text-transform: uppercase;
}
+
+ &__save-errors {
+ display: flex;
+ flex-direction: column;
+ gap: var(--spacing-2);
+ }
+}
+
+.sa-error-item {
+ border: 1px solid var(--l1-border);
+ border-radius: 4px;
+ overflow: hidden;
+
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: var(--spacing-3);
+ width: 100%;
+ padding: var(--padding-2) var(--padding-4);
+ background: transparent;
+ border: none;
+ cursor: pointer;
+ text-align: left;
+ outline: none;
+
+ &:hover {
+ background: rgba(229, 72, 77, 0.08);
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--primary);
+ outline-offset: -2px;
+ }
+
+ &[aria-disabled='true'] {
+ cursor: default;
+ pointer-events: none;
+ }
+ }
+
+ &:hover {
+ border-color: var(--callout-error-border);
+ }
+
+ &__icon {
+ flex-shrink: 0;
+ color: var(--bg-cherry-500);
+ }
+
+ &__title {
+ flex: 1;
+ min-width: 0;
+ font-size: var(--font-size-xs);
+ font-weight: var(--font-weight-medium);
+ color: var(--bg-cherry-500);
+ line-height: var(--line-height-18);
+ letter-spacing: -0.06px;
+ text-align: left;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ &__chevron {
+ flex-shrink: 0;
+ color: var(--l2-foreground);
+ }
+
+ &__body {
+ border-top: 1px solid var(--l1-border);
+
+ .error-content {
+ &__summary {
+ padding: 10px 12px;
+ }
+
+ &__summary-left {
+ gap: 6px;
+ }
+
+ &__error-code {
+ font-size: 12px;
+ line-height: 18px;
+ }
+
+ &__error-message {
+ font-size: 11px;
+ line-height: 16px;
+ }
+
+ &__docs-button {
+ font-size: 11px;
+ padding: 5px 8px;
+ }
+
+ &__message-badge {
+ padding: 0 12px 10px;
+ gap: 8px;
+ }
+
+ &__message-item {
+ font-size: 11px;
+ padding: 2px 12px 2px 22px;
+ margin-bottom: 2px;
+ }
+ }
+ }
}
.keys-tab {
@@ -429,7 +553,7 @@
}
}
-.sa-disable-dialog {
+.sa-delete-dialog {
background: var(--l2-background);
border: 1px solid var(--l2-border);
diff --git a/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx b/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx
index a801e4df54..afad688d42 100644
--- a/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx
@@ -1,25 +1,29 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useQueryClient } from 'react-query';
import { Button } from '@signozhq/button';
import { DrawerWrapper } from '@signozhq/drawer';
-import { Key, LayoutGrid, Plus, PowerOff, X } from '@signozhq/icons';
+import { Key, LayoutGrid, Plus, Trash2, X } from '@signozhq/icons';
import { toast } from '@signozhq/sonner';
import { ToggleGroup, ToggleGroupItem } from '@signozhq/toggle-group';
import { Pagination, Skeleton } from 'antd';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import {
+ getListServiceAccountsQueryKey,
useGetServiceAccount,
useListServiceAccountKeys,
useUpdateServiceAccount,
} from 'api/generated/services/serviceaccount';
-import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
+import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
import { AxiosError } from 'axios';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import { useRoles } from 'components/RolesSelect';
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
import {
ServiceAccountRow,
+ ServiceAccountStatus,
toServiceAccountRow,
} from 'container/ServiceAccountsSettings/utils';
+import { useServiceAccountRoleManager } from 'hooks/serviceAccount/useServiceAccountRoleManager';
import {
parseAsBoolean,
parseAsInteger,
@@ -27,12 +31,14 @@ import {
parseAsStringEnum,
useQueryState,
} from 'nuqs';
+import APIError from 'types/api/error';
import { toAPIError } from 'utils/errorUtils';
import AddKeyModal from './AddKeyModal';
-import DisableAccountModal from './DisableAccountModal';
+import DeleteAccountModal from './DeleteAccountModal';
import KeysTab from './KeysTab';
import OverviewTab from './OverviewTab';
+import type { SaveError } from './utils';
import { ServiceAccountDrawerTab } from './utils';
import './ServiceAccountDrawer.styles.scss';
@@ -69,12 +75,16 @@ function ServiceAccountDrawer({
SA_QUERY_PARAMS.ADD_KEY,
parseAsBoolean.withDefault(false),
);
- const [, setIsDisableOpen] = useQueryState(
- SA_QUERY_PARAMS.DISABLE_SA,
+ const [, setIsDeleteOpen] = useQueryState(
+ SA_QUERY_PARAMS.DELETE_SA,
parseAsBoolean.withDefault(false),
);
const [localName, setLocalName] = useState('');
const [localRoles, setLocalRoles] = useState<string[]>([]);
+ const [isSaving, setIsSaving] = useState(false);
+ const [saveErrors, setSaveErrors] = useState<SaveError[]>([]);
+
+ const queryClient = useQueryClient();
const {
data: accountData,
@@ -93,21 +103,30 @@ function ServiceAccountDrawer({
[accountData],
);
+ const { currentRoles, applyDiff } = useServiceAccountRoleManager(
+ selectedAccountId ?? '',
+ );
+
useEffect(() => {
- if (account) {
- setLocalName(account.name ?? '');
- setLocalRoles(account.roles ?? []);
+ if (account?.id) {
+ setLocalName(account?.name ?? '');
setKeysPage(1);
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [account?.id]);
+ setSaveErrors([]);
+ }, [account?.id, account?.name, setKeysPage]);
+
+ useEffect(() => {
+ setLocalRoles(currentRoles.map((r) => r.id).filter(Boolean) as string[]);
+ }, [currentRoles]);
- const isDisabled = account?.status?.toUpperCase() !== 'ACTIVE';
+ const isDeleted =
+ account?.status?.toUpperCase() === ServiceAccountStatus.Deleted;
const isDirty =
account !== null &&
(localName !== (account.name ?? '') ||
- JSON.stringify(localRoles) !== JSON.stringify(account.roles ?? []));
+ JSON.stringify([...localRoles].sort()) !==
+ JSON.stringify([...currentRoles.map((r) => r.id).filter(Boolean)].sort()));
const {
roles: availableRoles,
@@ -133,51 +152,189 @@ function ServiceAccountDrawer({
}
}, [keysLoading, keys.length, keysPage, setKeysPage]);
- const { mutate: updateAccount, isLoading: isSaving } = useUpdateServiceAccount(
- {
- mutation: {
- onSuccess: () => {
- toast.success('Service account updated successfully', {
- richColors: true,
- });
- refetchAccount();
- onSuccess({ closeDrawer: false });
- },
- onError: (error) => {
- const errMessage =
- convertToApiError(
- error as AxiosError<RenderErrorResponseDTO, unknown> | null,
- )?.getErrorMessage() || 'Failed to update service account';
- toast.error(errMessage, { richColors: true });
- },
- },
+ // the retry for this mutation is safe due to the api being idempotent on backend
+ const { mutateAsync: updateMutateAsync } = useUpdateServiceAccount();
+
+ const toSaveApiError = useCallback(
+ (err: unknown): APIError =>
+ convertToApiError(err as AxiosError<RenderErrorResponseDTO>) ??
+ toAPIError(err as AxiosError<RenderErrorResponseDTO>),
+ [],
+ );
+
+ const retryNameUpdate = useCallback(async (): Promise<void> => {
+ if (!account) {
+ return;
+ }
+ try {
+ await updateMutateAsync({
+ pathParams: { id: account.id },
+ data: { name: localName },
+ });
+ setSaveErrors((prev) => prev.filter((e) => e.context !== 'Name update'));
+ refetchAccount();
+ queryClient.invalidateQueries(getListServiceAccountsQueryKey());
+ } catch (err) {
+ setSaveErrors((prev) =>
+ prev.map((e) =>
+ e.context === 'Name update' ? { ...e, apiError: toSaveApiError(err) } : e,
+ ),
+ );
+ }
+ }, [
+ account,
+ localName,
+ updateMutateAsync,
+ refetchAccount,
+ queryClient,
+ toSaveApiError,
+ ]);
+
+ const handleNameChange = useCallback((name: string): void => {
+ setLocalName(name);
+ setSaveErrors((prev) => prev.filter((e) => e.context !== 'Name update'));
+ }, []);
+
+ const makeRoleRetry = useCallback(
+ (
+ context: string,
+ rawRetry: () => Promise<void>,
+ ) => async (): Promise<void> => {
+ try {
+ await rawRetry();
+ setSaveErrors((prev) => prev.filter((e) => e.context !== context));
+ } catch (err) {
+ setSaveErrors((prev) =>
+ prev.map((e) =>
+ e.context === context ? { ...e, apiError: toSaveApiError(err) } : e,
+ ),
+ );
+ }
},
+ [toSaveApiError],
);
- function handleSave(): void {
+ const retryRolesUpdate = useCallback(async (): Promise<void> => {
+ try {
+ const failures = await applyDiff(localRoles, availableRoles);
+ if (failures.length === 0) {
+ setSaveErrors((prev) => prev.filter((e) => e.context !== 'Roles update'));
+ } else {
+ setSaveErrors((prev) => {
+ const rest = prev.filter((e) => e.context !== 'Roles update');
+ const roleErrors = failures.map((f) => {
+ const ctx = `Role '${f.roleName}'`;
+ return {
+ context: ctx,
+ apiError: toSaveApiError(f.error),
+ onRetry: makeRoleRetry(ctx, f.onRetry),
+ };
+ });
+ return [...rest, ...roleErrors];
+ });
+ }
+ } catch (err) {
+ setSaveErrors((prev) =>
+ prev.map((e) =>
+ e.context === 'Roles update' ? { ...e, apiError: toSaveApiError(err) } : e,
+ ),
+ );
+ }
+ }, [localRoles, availableRoles, applyDiff, toSaveApiError, makeRoleRetry]);
+
+ const handleSave = useCallback(async (): Promise<void> => {
if (!account || !isDirty) {
return;
}
- updateAccount({
- pathParams: { id: account.id },
- data: { name: localName, email: account.email, roles: localRoles },
- });
- }
+ setSaveErrors([]);
+ setIsSaving(true);
+ try {
+ const namePromise =
+ localName !== (account.name ?? '')
+ ? updateMutateAsync({
+ pathParams: { id: account.id },
+ data: { name: localName },
+ })
+ : Promise.resolve();
+
+ const [nameResult, rolesResult] = await Promise.allSettled([
+ namePromise,
+ applyDiff(localRoles, availableRoles),
+ ]);
+
+ const errors: SaveError[] = [];
+
+ if (nameResult.status === 'rejected') {
+ errors.push({
+ context: 'Name update',
+ apiError: toSaveApiError(nameResult.reason),
+ onRetry: retryNameUpdate,
+ });
+ }
+
+ if (rolesResult.status === 'rejected') {
+ errors.push({
+ context: 'Roles update',
+ apiError: toSaveApiError(rolesResult.reason),
+ onRetry: retryRolesUpdate,
+ });
+ } else {
+ for (const failure of rolesResult.value) {
+ const context = `Role '${failure.roleName}'`;
+ errors.push({
+ context,
+ apiError: toSaveApiError(failure.error),
+ onRetry: makeRoleRetry(context, failure.onRetry),
+ });
+ }
+ }
+
+ if (errors.length > 0) {
+ setSaveErrors(errors);
+ } else {
+ toast.success('Service account updated successfully', {
+ richColors: true,
+ });
+ onSuccess({ closeDrawer: false });
+ }
+
+ refetchAccount();
+ queryClient.invalidateQueries(getListServiceAccountsQueryKey());
+ } finally {
+ setIsSaving(false);
+ }
+ }, [
+ account,
+ isDirty,
+ localName,
+ localRoles,
+ availableRoles,
+ updateMutateAsync,
+ applyDiff,
+ refetchAccount,
+ onSuccess,
+ queryClient,
+ toSaveApiError,
+ retryNameUpdate,
+ makeRoleRetry,
+ retryRolesUpdate,
+ ]);
const handleClose = useCallback((): void => {
- setIsDisableOpen(null);
+ setIsDeleteOpen(null);
setIsAddKeyOpen(null);
setSelectedAccountId(null);
setActiveTab(null);
setKeysPage(null);
setEditKeyId(null);
+ setSaveErrors([]);
}, [
setSelectedAccountId,
setActiveTab,
setKeysPage,
setEditKeyId,
setIsAddKeyOpen,
- setIsDisableOpen,
+ setIsDeleteOpen,
]);
const drawerContent = (
@@ -220,7 +377,7 @@ function ServiceAccountDrawer({
variant="outlined"
size="sm"
color="secondary"
- disabled={isDisabled}
+ disabled={isDeleted}
onClick={(): void => {
setIsAddKeyOpen(true);
}}
@@ -251,22 +408,23 @@ function ServiceAccountDrawer({
<OverviewTab
account={account}
localName={localName}
- onNameChange={setLocalName}
+ onNameChange={handleNameChange}
localRoles={localRoles}
onRolesChange={setLocalRoles}
- isDisabled={isDisabled}
+ isDisabled={isDeleted}
availableRoles={availableRoles}
rolesLoading={rolesLoading}
rolesError={rolesError}
rolesErrorObj={rolesErrorObj}
onRefetchRoles={refetchRoles}
+ saveErrors={saveErrors}
/>
)}
{activeTab === ServiceAccountDrawerTab.Keys && (
<KeysTab
keys={keys}
isLoading={keysLoading}
- isDisabled={isDisabled}
+ isDisabled={isDeleted}
currentPage={keysPage}
pageSize={PAGE_SIZE}
/>
@@ -298,20 +456,20 @@ function ServiceAccountDrawer({
/>
) : (
<>
- {!isDisabled && (
+ {!isDeleted && (
<Button
variant="ghost"
color="destructive"
className="sa-drawer__footer-btn"
onClick={(): void => {
- setIsDisableOpen(true);
+ setIsDeleteOpen(true);
}}
>
- <PowerOff size={12} />
- Disable Service Account
+ <Trash2 size={12} />
+ Delete Service Account
</Button>
)}
- {!isDisabled && (
+ {!isDeleted && (
<div className="sa-drawer__footer-right">
<Button
variant="solid"
@@ -359,7 +517,7 @@ function ServiceAccountDrawer({
className="sa-drawer"
/>
- <DisableAccountModal />
+ <DeleteAccountModal />
<AddKeyModal />
</>
diff --git a/frontend/src/components/ServiceAccountDrawer/__tests__/EditKeyModal.test.tsx b/frontend/src/components/ServiceAccountDrawer/__tests__/EditKeyModal.test.tsx
index 00887da0ed..79685b5a14 100644
--- a/frontend/src/components/ServiceAccountDrawer/__tests__/EditKeyModal.test.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/__tests__/EditKeyModal.test.tsx
@@ -1,5 +1,5 @@
import { toast } from '@signozhq/sonner';
-import type { ServiceaccounttypesFactorAPIKeyDTO } from 'api/generated/services/sigNoz.schemas';
+import type { ServiceaccounttypesGettableFactorAPIKeyDTO } from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
@@ -14,17 +14,16 @@ const mockToast = jest.mocked(toast);
const SA_KEY_ENDPOINT = '*/api/v1/service_accounts/sa-1/keys/key-1';
-const mockKey: ServiceaccounttypesFactorAPIKeyDTO = {
+const mockKey: ServiceaccounttypesGettableFactorAPIKeyDTO = {
id: 'key-1',
name: 'Original Key Name',
expiresAt: 0,
lastObservedAt: null as any,
- key: 'snz_abc123',
serviceAccountId: 'sa-1',
};
function renderModal(
- keyItem: ServiceaccounttypesFactorAPIKeyDTO | null = mockKey,
+ keyItem: ServiceaccounttypesGettableFactorAPIKeyDTO | null = mockKey,
searchParams: Record<string, string> = {
account: 'sa-1',
'edit-key': 'key-1',
diff --git a/frontend/src/components/ServiceAccountDrawer/__tests__/KeysTab.test.tsx b/frontend/src/components/ServiceAccountDrawer/__tests__/KeysTab.test.tsx
index ecd8c625b8..5d4f129637 100644
--- a/frontend/src/components/ServiceAccountDrawer/__tests__/KeysTab.test.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/__tests__/KeysTab.test.tsx
@@ -1,5 +1,5 @@
import { toast } from '@signozhq/sonner';
-import { ServiceaccounttypesFactorAPIKeyDTO } from 'api/generated/services/sigNoz.schemas';
+import { ServiceaccounttypesGettableFactorAPIKeyDTO } from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
@@ -14,13 +14,12 @@ const mockToast = jest.mocked(toast);
const SA_KEY_ENDPOINT = '*/api/v1/service_accounts/sa-1/keys/:fid';
-const keys: ServiceaccounttypesFactorAPIKeyDTO[] = [
+const keys: ServiceaccounttypesGettableFactorAPIKeyDTO[] = [
{
id: 'key-1',
name: 'Production Key',
expiresAt: 0,
lastObservedAt: null as any,
- key: 'snz_prod_123',
serviceAccountId: 'sa-1',
},
{
@@ -28,7 +27,6 @@ const keys: ServiceaccounttypesFactorAPIKeyDTO[] = [
name: 'Staging Key',
expiresAt: 1924905600, // 2030-12-31
lastObservedAt: new Date('2026-03-10T10:00:00Z'),
- key: 'snz_stag_456',
serviceAccountId: 'sa-1',
},
];
diff --git a/frontend/src/components/ServiceAccountDrawer/__tests__/ServiceAccountDrawer.test.tsx b/frontend/src/components/ServiceAccountDrawer/__tests__/ServiceAccountDrawer.test.tsx
index e99961ceae..eef57ef2cd 100644
--- a/frontend/src/components/ServiceAccountDrawer/__tests__/ServiceAccountDrawer.test.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/__tests__/ServiceAccountDrawer.test.tsx
@@ -23,7 +23,9 @@ jest.mock('@signozhq/sonner', () => ({
const ROLES_ENDPOINT = '*/api/v1/roles';
const SA_KEYS_ENDPOINT = '*/api/v1/service_accounts/:id/keys';
const SA_ENDPOINT = '*/api/v1/service_accounts/sa-1';
-const SA_STATUS_ENDPOINT = '*/api/v1/service_accounts/sa-1/status';
+const SA_DELETE_ENDPOINT = '*/api/v1/service_accounts/sa-1';
+const SA_ROLES_ENDPOINT = '*/api/v1/service_accounts/:id/roles';
+const SA_ROLE_DELETE_ENDPOINT = '*/api/v1/service_accounts/:id/roles/:rid';
const activeAccountResponse = {
id: 'sa-1',
@@ -35,10 +37,10 @@ const activeAccountResponse = {
updatedAt: '2026-01-02T00:00:00Z',
};
-const disabledAccountResponse = {
+const deletedAccountResponse = {
...activeAccountResponse,
id: 'sa-2',
- status: 'DISABLED',
+ status: 'DELETED',
};
function renderDrawer(
@@ -67,7 +69,23 @@ describe('ServiceAccountDrawer', () => {
rest.put(SA_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
),
- rest.put(SA_STATUS_ENDPOINT, (_, res, ctx) =>
+ rest.delete(SA_DELETE_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
+ ),
+ rest.get(SA_ROLES_ENDPOINT, (_, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json({
+ data: listRolesSuccessResponse.data.filter(
+ (r) => r.name === 'signoz-admin',
+ ),
+ }),
+ ),
+ ),
+ rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
+ ),
+ rest.delete(SA_ROLE_DELETE_ENDPOINT, (_, res, ctx) =>
res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
),
);
@@ -115,8 +133,6 @@ describe('ServiceAccountDrawer', () => {
expect(updateSpy).toHaveBeenCalledWith(
expect.objectContaining({
name: 'CI Bot Updated',
- email: '[email protected]',
- roles: ['signoz-admin'],
}),
);
expect(onSuccess).toHaveBeenCalledWith({ closeDrawer: false });
@@ -125,6 +141,7 @@ describe('ServiceAccountDrawer', () => {
it('changing roles enables Save; clicking Save sends updated roles in payload', async () => {
const updateSpy = jest.fn();
+ const roleSpy = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
@@ -132,6 +149,10 @@ describe('ServiceAccountDrawer', () => {
updateSpy(await req.json());
return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
}),
+ rest.post(SA_ROLES_ENDPOINT, async (req, res, ctx) => {
+ roleSpy(await req.json());
+ return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
+ }),
);
renderDrawer();
@@ -146,21 +167,22 @@ describe('ServiceAccountDrawer', () => {
await user.click(saveBtn);
await waitFor(() => {
- expect(updateSpy).toHaveBeenCalledWith(
+ expect(updateSpy).not.toHaveBeenCalled();
+ expect(roleSpy).toHaveBeenCalledWith(
expect.objectContaining({
- roles: expect.arrayContaining(['signoz-admin', 'signoz-viewer']),
+ id: '019c24aa-2248-7585-a129-4188b3473c27',
}),
);
});
});
- it('"Disable Service Account" opens confirm dialog; confirming sends correct status payload', async () => {
- const statusSpy = jest.fn();
+ it('"Delete Service Account" opens confirm dialog; confirming sends delete request', async () => {
+ const deleteSpy = jest.fn();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
- rest.put(SA_STATUS_ENDPOINT, async (req, res, ctx) => {
- statusSpy(await req.json());
+ rest.delete(SA_DELETE_ENDPOINT, (_, res, ctx) => {
+ deleteSpy();
return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
}),
);
@@ -170,19 +192,19 @@ describe('ServiceAccountDrawer', () => {
await screen.findByDisplayValue('CI Bot');
await user.click(
- screen.getByRole('button', { name: /Disable Service Account/i }),
+ screen.getByRole('button', { name: /Delete Service Account/i }),
);
const dialog = await screen.findByRole('dialog', {
- name: /Disable service account CI Bot/i,
+ name: /Delete service account CI Bot/i,
});
expect(dialog).toBeInTheDocument();
- const confirmBtns = screen.getAllByRole('button', { name: /^Disable$/i });
+ const confirmBtns = screen.getAllByRole('button', { name: /^Delete$/i });
await user.click(confirmBtns[confirmBtns.length - 1]);
await waitFor(() => {
- expect(statusSpy).toHaveBeenCalledWith({ status: 'DISABLED' });
+ expect(deleteSpy).toHaveBeenCalled();
});
await waitFor(() => {
@@ -190,14 +212,17 @@ describe('ServiceAccountDrawer', () => {
});
});
- it('disabled account shows read-only name, no Save button, no Disable button', async () => {
+ it('deleted account shows read-only name, no Save button, no Delete button', async () => {
server.use(
rest.get('*/api/v1/service_accounts/sa-2', (_, res, ctx) =>
- res(ctx.status(200), ctx.json({ data: disabledAccountResponse })),
+ res(ctx.status(200), ctx.json({ data: deletedAccountResponse })),
),
rest.get('*/api/v1/service_accounts/sa-2/keys', (_, res, ctx) =>
res(ctx.status(200), ctx.json({ data: [] })),
),
+ rest.get('*/api/v1/service_accounts/sa-2/roles', (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ data: [] })),
+ ),
);
renderDrawer({ account: 'sa-2' });
@@ -208,7 +233,7 @@ describe('ServiceAccountDrawer', () => {
screen.queryByRole('button', { name: /Save Changes/i }),
).not.toBeInTheDocument();
expect(
- screen.queryByRole('button', { name: /Disable Service Account/i }),
+ screen.queryByRole('button', { name: /Delete Service Account/i }),
).not.toBeInTheDocument();
expect(screen.queryByDisplayValue('CI Bot')).not.toBeInTheDocument();
});
@@ -248,3 +273,169 @@ describe('ServiceAccountDrawer', () => {
).toBeInTheDocument();
});
});
+
+describe('ServiceAccountDrawer – save-error UX', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ server.use(
+ rest.get(ROLES_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json(listRolesSuccessResponse)),
+ ),
+ rest.get(SA_KEYS_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ data: [] })),
+ ),
+ rest.get(SA_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ data: activeAccountResponse })),
+ ),
+ rest.put(SA_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
+ ),
+ rest.delete(SA_DELETE_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
+ ),
+ rest.get(SA_ROLES_ENDPOINT, (_, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json({
+ data: listRolesSuccessResponse.data.filter(
+ (r) => r.name === 'signoz-admin',
+ ),
+ }),
+ ),
+ ),
+ rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
+ ),
+ rest.delete(SA_ROLE_DELETE_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
+ ),
+ );
+ });
+
+ afterEach(() => {
+ server.resetHandlers();
+ });
+
+ it('name update failure shows SaveErrorItem with "Name update" context', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ server.use(
+ rest.put(SA_ENDPOINT, (_, res, ctx) =>
+ res(
+ ctx.status(500),
+ ctx.json({
+ error: {
+ code: 'INTERNAL_ERROR',
+ message: 'name update failed',
+ },
+ }),
+ ),
+ ),
+ );
+
+ renderDrawer();
+
+ const nameInput = await screen.findByDisplayValue('CI Bot');
+ await user.clear(nameInput);
+ await user.type(nameInput, 'New Name');
+
+ const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
+ await waitFor(() => expect(saveBtn).not.toBeDisabled());
+ await user.click(saveBtn);
+
+ expect(
+ await screen.findByText(/Name update.*name update failed/i, undefined, {
+ timeout: 5000,
+ }),
+ ).toBeInTheDocument();
+ });
+
+ it('role update failure shows SaveErrorItem with the role name context', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ server.use(
+ rest.post(SA_ROLES_ENDPOINT, (_, res, ctx) =>
+ res(
+ ctx.status(500),
+ ctx.json({
+ error: {
+ code: 'INTERNAL_ERROR',
+ message: 'role assign failed',
+ },
+ }),
+ ),
+ ),
+ );
+
+ renderDrawer();
+
+ await screen.findByDisplayValue('CI Bot');
+
+ // Add the signoz-viewer role (which is not currently assigned)
+ await user.click(screen.getByLabelText('Roles'));
+ await user.click(await screen.findByTitle('signoz-viewer'));
+
+ const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
+ await waitFor(() => expect(saveBtn).not.toBeDisabled());
+ await user.click(saveBtn);
+
+ expect(
+ await screen.findByText(
+ /Role 'signoz-viewer'.*role assign failed/i,
+ undefined,
+ {
+ timeout: 5000,
+ },
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it('clicking Retry on a name-update error re-triggers the request; on success the error item is removed', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ // First: PUT always fails so the error appears
+ server.use(
+ rest.put(SA_ENDPOINT, (_, res, ctx) =>
+ res(
+ ctx.status(500),
+ ctx.json({
+ error: {
+ code: 'INTERNAL_ERROR',
+ message: 'name update failed',
+ },
+ }),
+ ),
+ ),
+ );
+
+ renderDrawer();
+
+ const nameInput = await screen.findByDisplayValue('CI Bot');
+ await user.clear(nameInput);
+ await user.type(nameInput, 'Retry Test');
+
+ const saveBtn = screen.getByRole('button', { name: /Save Changes/i });
+ await waitFor(() => expect(saveBtn).not.toBeDisabled());
+ await user.click(saveBtn);
+
+ await screen.findByText(/Name update.*name update failed/i, undefined, {
+ timeout: 5000,
+ });
+
+ server.use(
+ rest.put(SA_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ status: 'success', data: {} })),
+ ),
+ );
+
+ const retryBtn = screen.getByRole('button', { name: /Retry/i });
+ await user.click(retryBtn);
+
+ // Error item should be removed after successful retry
+ await waitFor(() => {
+ expect(
+ screen.queryByText(/Name update.*name update failed/i),
+ ).not.toBeInTheDocument();
+ });
+ });
+});
diff --git a/frontend/src/components/ServiceAccountDrawer/utils.ts b/frontend/src/components/ServiceAccountDrawer/utils.ts
index 547a4976e0..7cf093415f 100644
--- a/frontend/src/components/ServiceAccountDrawer/utils.ts
+++ b/frontend/src/components/ServiceAccountDrawer/utils.ts
@@ -1,6 +1,13 @@
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
+import APIError from 'types/api/error';
+
+export interface SaveError {
+ context: string;
+ apiError: APIError;
+ onRetry: () => Promise<void>;
+}
export enum ServiceAccountDrawerTab {
Overview = 'overview',
diff --git a/frontend/src/components/ServiceAccountsTable/__tests__/ServiceAccountsTable.test.tsx b/frontend/src/components/ServiceAccountsTable/__tests__/ServiceAccountsTable.test.tsx
index 89912cd04d..32ce62b46c 100644
--- a/frontend/src/components/ServiceAccountsTable/__tests__/ServiceAccountsTable.test.tsx
+++ b/frontend/src/components/ServiceAccountsTable/__tests__/ServiceAccountsTable.test.tsx
@@ -8,7 +8,6 @@ const mockActiveAccount: ServiceAccountRow = {
id: 'sa-1',
name: 'CI Bot',
- roles: ['signoz-admin'],
status: 'ACTIVE',
createdAt: '2026-01-01T00:00:00Z',
updatedAt: '2026-01-02T00:00:00Z',
@@ -18,7 +17,6 @@ const mockDisabledAccount: ServiceAccountRow = {
id: 'sa-2',
name: 'Legacy Bot',
- roles: ['signoz-viewer', 'signoz-editor', 'billing-manager'],
status: 'DISABLED',
createdAt: '2025-06-01T00:00:00Z',
updatedAt: '2025-12-01T00:00:00Z',
@@ -39,7 +37,6 @@ describe('ServiceAccountsTable', () => {
expect(screen.getByText('CI Bot')).toBeInTheDocument();
expect(screen.getByText('[email protected]')).toBeInTheDocument();
- expect(screen.getByText('signoz-admin')).toBeInTheDocument();
expect(screen.getByText('ACTIVE')).toBeInTheDocument();
});
@@ -49,8 +46,6 @@ describe('ServiceAccountsTable', () => {
);
expect(screen.getByText('DISABLED')).toBeInTheDocument();
- expect(screen.getByText('signoz-viewer')).toBeInTheDocument();
- expect(screen.getByText('+2')).toBeInTheDocument();
});
it('calls onRowClick with the correct account when a row is clicked', async () => {
diff --git a/frontend/src/components/ServiceAccountsTable/utils.tsx b/frontend/src/components/ServiceAccountsTable/utils.tsx
index 2168b4e56f..a894806ec9 100644
--- a/frontend/src/components/ServiceAccountsTable/utils.tsx
+++ b/frontend/src/components/ServiceAccountsTable/utils.tsx
@@ -25,32 +25,6 @@ export function NameEmailCell({
);
}
-export function RolesCell({ roles }: { roles: string[] }): JSX.Element {
- if (!roles || roles.length === 0) {
- return <span className="sa-dash">—</span>;
- }
- const first = roles[0];
- const overflow = roles.length - 1;
- const tooltipContent = roles.slice(1).join(', ');
-
- return (
- <div className="sa-roles-cell">
- <Badge color="vanilla">{first}</Badge>
- {overflow > 0 && (
- <Tooltip
- title={tooltipContent}
- overlayClassName="sa-tooltip"
- overlayStyle={{ maxWidth: '600px' }}
- >
- <Badge color="vanilla" variant="outline" className="sa-status-badge">
- +{overflow}
- </Badge>
- </Tooltip>
- )}
- </div>
- );
-}
-
export function StatusBadge({ status }: { status: string }): JSX.Element {
if (status?.toUpperCase() === 'ACTIVE') {
return (
@@ -59,9 +33,16 @@ export function StatusBadge({ status }: { status: string }): JSX.Element {
</Badge>
);
}
+ if (status?.toUpperCase() === 'DELETED') {
+ return (
+ <Badge color="cherry" variant="outline">
+ DELETED
+ </Badge>
+ );
+ }
return (
<Badge color="vanilla" variant="outline" className="sa-status-badge">
- DISABLED
+ {status ? status.toUpperCase() : 'UNKNOWN'}
</Badge>
);
}
@@ -98,13 +79,6 @@ export const columns: ColumnsType<ServiceAccountRow> = [
<NameEmailCell name={record.name} email={record.email} />
),
},
- {
- title: 'Roles',
- dataIndex: 'roles',
- key: 'roles',
- width: 420,
- render: (roles: string[]): JSX.Element => <RolesCell roles={roles} />,
- },
{
title: 'Status',
dataIndex: 'status',
diff --git a/frontend/src/constants/routes.ts b/frontend/src/constants/routes.ts
index 49523f82bf..ece76e30df 100644
--- a/frontend/src/constants/routes.ts
+++ b/frontend/src/constants/routes.ts
@@ -38,7 +38,6 @@ const ROUTES = {
SETTINGS: '/settings',
MY_SETTINGS: '/settings/my-settings',
ORG_SETTINGS: '/settings/org-settings',
- API_KEYS: '/settings/api-keys',
INGESTION_SETTINGS: '/settings/ingestion-settings',
SOMETHING_WENT_WRONG: '/something-went-wrong',
UN_AUTHORIZED: '/un-authorized',
diff --git a/frontend/src/constants/shortcutActions.tsx b/frontend/src/constants/shortcutActions.tsx
index 7530612a96..3db1eed162 100644
--- a/frontend/src/constants/shortcutActions.tsx
+++ b/frontend/src/constants/shortcutActions.tsx
@@ -248,15 +248,5 @@ export function createShortcutActions(deps: ActionDeps): CmdAction[] {
roles: ['ADMIN', 'EDITOR'],
perform: (): void => navigate(ROUTES.BILLING),
},
- {
- id: 'my-settings-api-keys',
- name: 'Go to Account Settings API Keys',
- shortcut: [GlobalShortcutsName.NavigateToSettingsAPIKeys],
- keywords: 'account settings api keys',
- section: 'Settings',
- icon: <Settings size={14} />,
- roles: ['ADMIN', 'EDITOR'],
- perform: (): void => navigate(ROUTES.API_KEYS),
- },
];
}
diff --git a/frontend/src/constants/shortcuts/globalShortcuts.ts b/frontend/src/constants/shortcuts/globalShortcuts.ts
index b9b497bf1a..23ac597933 100644
--- a/frontend/src/constants/shortcuts/globalShortcuts.ts
+++ b/frontend/src/constants/shortcuts/globalShortcuts.ts
@@ -26,7 +26,6 @@ export const GlobalShortcuts = {
NavigateToSettings: 'shift+g',
NavigateToSettingsIngestion: 'shift+g+i',
NavigateToSettingsBilling: 'shift+g+b',
- NavigateToSettingsAPIKeys: 'shift+g+k',
NavigateToSettingsNotificationChannels: 'shift+g+n',
};
@@ -47,7 +46,6 @@ export const GlobalShortcutsName = {
NavigateToSettings: 'shift+g',
NavigateToSettingsIngestion: 'shift+g+i',
NavigateToSettingsBilling: 'shift+g+b',
- NavigateToSettingsAPIKeys: 'shift+g+k',
NavigateToSettingsNotificationChannels: 'shift+g+n',
NavigateToLogs: 'shift+l',
NavigateToLogsPipelines: 'shift+l+p',
@@ -72,7 +70,6 @@ export const GlobalShortcutsDescription = {
NavigateToSettings: 'Navigate to Settings',
NavigateToSettingsIngestion: 'Navigate to Ingestion Settings',
NavigateToSettingsBilling: 'Navigate to Billing Settings',
- NavigateToSettingsAPIKeys: 'Navigate to API Keys Settings',
NavigateToSettingsNotificationChannels:
'Navigate to Notification Channels Settings',
NavigateToLogsPipelines: 'Navigate to Logs Pipelines',
diff --git a/frontend/src/container/APIKeys/APIKeys.styles.scss b/frontend/src/container/APIKeys/APIKeys.styles.scss
deleted file mode 100644
index c0aeec0cac..0000000000
--- a/frontend/src/container/APIKeys/APIKeys.styles.scss
+++ /dev/null
@@ -1,685 +0,0 @@
-.api-key-container {
- margin-top: 24px;
- display: flex;
- justify-content: center;
- width: 100%;
-
- .api-key-content {
- width: calc(100% - 30px);
- max-width: 736px;
-
- .title {
- color: var(--bg-vanilla-100);
- font-size: var(--font-size-lg);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- line-height: 28px; /* 155.556% */
- letter-spacing: -0.09px;
- }
-
- .subtitle {
- color: var(--bg-vanilla-400);
- font-size: var(--font-size-sm);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- line-height: 20px; /* 142.857% */
- letter-spacing: -0.07px;
- }
-
- .api-keys-search-add-new {
- display: flex;
- align-items: center;
- gap: 12px;
-
- padding: 16px 0;
-
- .add-new-api-key-btn {
- display: flex;
- align-items: center;
- gap: 8px;
- }
- }
-
- .ant-table-row {
- .ant-table-cell {
- padding: 0;
- border: none;
- background: var(--bg-ink-500);
- }
- .column-render {
- margin: 8px 0 !important;
- border-radius: 6px;
- border: 1px solid var(--bg-slate-500);
- background: var(--bg-ink-400);
-
- .title-with-action {
- display: flex;
- justify-content: space-between;
-
- align-items: center;
- padding: 8px;
-
- .api-key-data {
- display: flex;
- gap: 8px;
- align-items: center;
-
- .api-key-title {
- display: flex;
- align-items: center;
- gap: 6px;
-
- .ant-typography {
- color: var(--bg-vanilla-400);
- font-size: var(--font-size-sm);
- font-style: normal;
- font-weight: var(--font-weight-medium);
- line-height: 20px;
- letter-spacing: -0.07px;
- }
- }
-
- .api-key-value {
- display: flex;
- align-items: center;
- gap: 12px;
-
- border-radius: 20px;
- padding: 0px 12px;
-
- background: var(--bg-ink-200);
-
- .ant-typography {
- color: var(--bg-vanilla-400);
- font-size: var(--font-size-xs);
- font-family: 'Space Mono', monospace;
- font-style: normal;
- font-weight: var(--font-weight-medium);
- line-height: 20px;
- letter-spacing: -0.07px;
- }
-
- .copy-key-btn {
- cursor: pointer;
- }
- }
- }
-
- .action-btn {
- display: flex;
- align-items: center;
- gap: 4px;
- cursor: pointer;
- }
-
- .visibility-btn {
- border: 1px solid rgba(113, 144, 249, 0.2);
- background: rgba(113, 144, 249, 0.1);
- }
- }
-
- .ant-collapse {
- border: none;
-
- .ant-collapse-header {
- padding: 0px 8px;
-
- display: flex;
- align-items: center;
- background-color: #121317;
- }
-
- .ant-collapse-content {
- border-top: 1px solid var(--bg-slate-500);
- }
-
- .ant-collapse-item {
- border-bottom: none;
- }
-
- .ant-collapse-expand-icon {
- padding-inline-end: 0px;
- }
- }
-
- .api-key-details {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 8px;
- border-top: 1px solid var(--bg-slate-500);
- padding: 8px;
-
- .api-key-tag {
- width: 14px;
- height: 14px;
- border-radius: 50px;
- background: var(--bg-slate-300);
- display: flex;
- justify-content: center;
- align-items: center;
-
- .tag-text {
- color: var(--bg-vanilla-400);
- leading-trim: both;
- text-edge: cap;
- font-size: 10px;
- font-style: normal;
- font-weight: var(--font-weight-normal);
- line-height: normal;
- letter-spacing: -0.05px;
- }
- }
-
- .api-key-created-by {
- margin-left: 8px;
- }
-
- .api-key-last-used-at {
- display: flex;
- align-items: center;
- gap: 8px;
-
- .ant-typography {
- color: var(--bg-vanilla-400);
- font-size: var(--font-size-sm);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- line-height: 18px; /* 128.571% */
- letter-spacing: -0.07px;
- font-variant-numeric: lining-nums tabular-nums stacked-fractions
- slashed-zero;
- font-feature-settings: 'dlig' on, 'salt' on, 'cpsp' on, 'case' on;
- }
- }
-
- .api-key-expires-in {
- font-style: normal;
- font-weight: 400;
- line-height: 18px;
-
- display: flex;
- align-items: center;
- gap: 8px;
-
- .dot {
- height: 6px;
- width: 6px;
- border-radius: 50%;
- }
-
- &.warning {
- color: var(--bg-amber-400);
-
- .dot {
- background: var(--bg-amber-400);
- box-shadow: 0px 0px 6px 0px var(--bg-amber-400);
- }
- }
-
- &.danger {
- color: var(--bg-cherry-400);
-
- .dot {
- background: var(--bg-cherry-400);
- box-shadow: 0px 0px 6px 0px var(--bg-cherry-400);
- }
- }
- }
- }
- }
- }
-
- .ant-pagination-item {
- display: flex;
- justify-content: center;
- align-items: center;
-
- > a {
- color: var(--bg-vanilla-400);
- font-variant-numeric: lining-nums tabular-nums slashed-zero;
- font-feature-settings: 'dlig' on, 'salt' on, 'case' on, 'cpsp' on;
- font-size: var(--font-size-sm);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- line-height: 20px; /* 142.857% */
- }
- }
-
- .ant-pagination-item-active {
- background-color: var(--bg-robin-500);
- > a {
- color: var(--bg-ink-500) !important;
- font-size: var(--font-size-sm);
- font-style: normal;
- font-weight: var(--font-weight-medium);
- line-height: 20px;
- }
- }
- }
-}
-
-.api-key-info-container {
- display: flex;
- gap: 12px;
- flex-direction: column;
-
- .user-info {
- display: flex;
- gap: 8px;
- align-items: center;
- flex-wrap: wrap;
-
- .user-avatar {
- background-color: lightslategray;
- vertical-align: middle;
- }
- }
-
- .user-email {
- display: inline-flex;
- align-items: center;
- gap: 12px;
- border-radius: 20px;
- padding: 0px 12px;
- background: var(--bg-ink-200);
-
- font-family: 'Space Mono', monospace;
- }
-
- .role {
- display: flex;
- align-items: center;
- gap: 12px;
- }
-}
-
-.api-key-modal {
- .ant-modal-content {
- border-radius: 4px;
- border: 1px solid var(--bg-slate-500);
- background: var(--bg-ink-400);
- box-shadow: 0px -4px 16px 2px rgba(0, 0, 0, 0.2);
- padding: 0;
-
- .ant-modal-header {
- background: none;
- border-bottom: 1px solid var(--bg-slate-500);
- padding: 16px;
- }
-
- .ant-modal-close-x {
- font-size: 12px;
- }
-
- .ant-modal-body {
- padding: 12px 16px;
- }
-
- .ant-modal-footer {
- padding: 16px;
- margin-top: 0;
-
- display: flex;
- justify-content: flex-end;
- }
- }
-}
-
-.api-key-access-role {
- display: flex;
-
- .ant-radio-button-wrapper {
- font-size: 12px;
- text-transform: capitalize;
-
- &.ant-radio-button-wrapper-checked {
- color: #fff;
- background: var(--bg-slate-400, #1d212d);
- border-color: var(--bg-slate-400, #1d212d);
-
- &:hover {
- color: #fff;
- background: var(--bg-slate-400, #1d212d);
- border-color: var(--bg-slate-400, #1d212d);
-
- &::before {
- background-color: var(--bg-slate-400, #1d212d);
- }
- }
-
- &:focus {
- color: #fff;
- background: var(--bg-slate-400, #1d212d);
- border-color: var(--bg-slate-400, #1d212d);
- }
- }
- }
-
- .tab {
- border: 1px solid var(--bg-slate-400);
-
- flex: 1;
-
- display: flex;
- justify-content: center;
-
- &::before {
- background: var(--bg-slate-400);
- }
-
- &.selected {
- background: var(--bg-slate-400, #1d212d);
- }
- }
-
- .role {
- display: flex;
- align-items: center;
- gap: 8px;
- }
-}
-
-.delete-api-key-modal {
- width: calc(100% - 30px) !important; /* Adjust the 20px as needed */
- max-width: 384px;
- .ant-modal-content {
- padding: 0;
- border-radius: 4px;
- border: 1px solid var(--bg-slate-500);
- background: var(--bg-ink-400);
- box-shadow: 0px -4px 16px 2px rgba(0, 0, 0, 0.2);
-
- .ant-modal-header {
- padding: 16px;
- background: var(--bg-ink-400);
- }
-
- .ant-modal-body {
- padding: 0px 16px 28px 16px;
-
- .ant-typography {
- color: var(--bg-vanilla-400);
- font-size: var(--font-size-sm);
- font-style: normal;
- font-weight: var(--font-weight-normal);
- line-height: 20px;
- letter-spacing: -0.07px;
- }
-
- .api-key-input {
- margin-top: 8px;
- display: flex;
- gap: 8px;
- }
-
- .ant-color-picker-trigger {
- padding: 6px;
- border-radius: 2px;
- border: 1px solid var(--bg-slate-400);
- background: var(--bg-ink-300);
- width: 32px;
- height: 32px;
-
- .ant-color-picker-color-block {
- border-radius: 50px;
- width: 16px;
- height: 16px;
- flex-shrink: 0;
-
- .ant-color-picker-color-block-inner {
- display: flex;
- justify-content: center;
- align-items: center;
- }
- }
- }
- }
-
- .ant-modal-footer {
- display: flex;
- justify-content: flex-end;
- padding: 16px 16px;
- margin: 0;
-
- .cancel-btn {
- display: flex;
- align-items: center;
- border: none;
- border-radius: 2px;
- background: var(--bg-slate-500);
- }
-
- .delete-btn {
- display: flex;
- align-items: center;
- border: none;
- border-radius: 2px;
- background: var(--bg-cherry-500);
- margin-left: 12px;
- }
-
- .delete-btn:hover {
- color: var(--bg-vanilla-100);
- background: var(--bg-cherry-600);
- }
- }
- }
-
- .title {
- color: var(--bg-vanilla-100);
- font-size: var(--font-size-sm);
- font-style: normal;
- font-weight: var(--font-weight-medium);
- line-height: 20px; /* 142.857% */
- }
-}
-
-.expiration-selector {
- .ant-select-selector {
- border: 1px solid var(--bg-slate-400) !important;
- }
-}
-
-.newAPIKeyDetails {
- display: flex;
- flex-direction: column;
- gap: 8px;
-}
-
-.copyable-text {
- display: inline-flex;
- align-items: center;
- gap: 12px;
- border-radius: 20px;
- padding: 0px 12px;
- background: var(--bg-ink-200, #23262e);
-
- .copy-key-btn {
- cursor: pointer;
- }
-}
-
-.lightMode {
- .api-key-container {
- .api-key-content {
- .title {
- color: var(--bg-ink-500);
- }
-
- .ant-table-row {
- .ant-table-cell {
- background: var(--bg-vanilla-200);
- }
-
- &:hover {
- .ant-table-cell {
- background: var(--bg-vanilla-200) !important;
- }
- }
-
- .column-render {
- border: 1px solid var(--bg-vanilla-200);
- background: var(--bg-vanilla-100);
-
- .ant-collapse {
- border: none;
-
- .ant-collapse-header {
- background: var(--bg-vanilla-100);
- }
-
- .ant-collapse-content {
- border-top: 1px solid var(--bg-vanilla-300);
- }
- }
-
- .title-with-action {
- .api-key-title {
- .ant-typography {
- color: var(--bg-ink-500);
- }
- }
-
- .api-key-value {
- background: var(--bg-vanilla-200);
-
- .ant-typography {
- color: var(--bg-slate-400);
- }
-
- .copy-key-btn {
- cursor: pointer;
- }
- }
-
- .action-btn {
- .ant-typography {
- color: var(--bg-ink-500);
- }
- }
- }
-
- .api-key-details {
- border-top: 1px solid var(--bg-vanilla-200);
- .api-key-tag {
- background: var(--bg-vanilla-200);
- .tag-text {
- color: var(--bg-ink-500);
- }
- }
-
- .api-key-created-by {
- color: var(--bg-ink-500);
- }
-
- .api-key-last-used-at {
- .ant-typography {
- color: var(--bg-ink-500);
- }
- }
- }
- }
- }
- }
- }
-
- .delete-api-key-modal {
- .ant-modal-content {
- border: 1px solid var(--bg-vanilla-200);
- background: var(--bg-vanilla-100);
-
- .ant-modal-header {
- background: var(--bg-vanilla-100);
-
- .title {
- color: var(--bg-ink-500);
- }
- }
-
- .ant-modal-body {
- .ant-typography {
- color: var(--bg-ink-500);
- }
-
- .api-key-input {
- .ant-input {
- background: var(--bg-vanilla-200);
- color: var(--bg-ink-500);
- }
- }
- }
-
- .ant-modal-footer {
- .cancel-btn {
- background: var(--bg-vanilla-300);
- color: var(--bg-ink-400);
- }
- }
- }
- }
-
- .api-key-info-container {
- .user-email {
- background: var(--bg-vanilla-200);
- }
- }
-
- .api-key-modal {
- .ant-modal-content {
- border-radius: 4px;
- border: 1px solid var(--bg-vanilla-200);
- background: var(--bg-vanilla-100);
- box-shadow: 0px -4px 16px 2px rgba(0, 0, 0, 0.2);
- padding: 0;
-
- .ant-modal-header {
- background: none;
- border-bottom: 1px solid var(--bg-vanilla-200);
- padding: 16px;
- }
- }
- }
-
- .api-key-access-role {
- .ant-radio-button-wrapper {
- &.ant-radio-button-wrapper-checked {
- color: var(--bg-ink-400);
- background: var(--bg-vanilla-300);
- border-color: var(--bg-vanilla-300);
-
- &:hover {
- color: var(--bg-ink-400);
- background: var(--bg-vanilla-300);
- border-color: var(--bg-vanilla-300);
-
- &::before {
- background-color: var(--bg-vanilla-300);
- }
- }
-
- &:focus {
- color: var(--bg-ink-400);
- background: var(--bg-vanilla-300);
- border-color: var(--bg-vanilla-300);
- }
- }
- }
-
- .tab {
- border: 1px solid var(--bg-vanilla-300);
-
- &::before {
- background: var(--bg-vanilla-300);
- }
-
- &.selected {
- background: var(--bg-vanilla-300);
- }
- }
- }
-
- .copyable-text {
- background: var(--bg-vanilla-200);
- }
-}
diff --git a/frontend/src/container/APIKeys/APIKeys.test.tsx b/frontend/src/container/APIKeys/APIKeys.test.tsx
deleted file mode 100644
index bb6b76f4ca..0000000000
--- a/frontend/src/container/APIKeys/APIKeys.test.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import {
- createAPIKeyResponse,
- getAPIKeysResponse,
-} from 'mocks-server/__mockdata__/apiKeys';
-import { server } from 'mocks-server/server';
-import { rest } from 'msw';
-import { act, fireEvent, render, screen, waitFor } from 'tests/test-utils';
-
-import APIKeys from './APIKeys';
-
-const apiKeysURL = 'http://localhost/api/v1/pats';
-
-describe('APIKeys component', () => {
- beforeEach(() => {
- server.use(
- rest.get(apiKeysURL, (req, res, ctx) =>
- res(ctx.status(200), ctx.json(getAPIKeysResponse)),
- ),
- );
-
- render(<APIKeys />);
- });
-
- afterEach(() => {
- jest.clearAllMocks();
- });
-
- it('renders APIKeys component without crashing', () => {
- expect(screen.getByText('API Keys')).toBeInTheDocument();
- expect(
- screen.getByText('Create and manage API keys for the SigNoz API'),
- ).toBeInTheDocument();
- });
-
- it('render list of Access Tokens', async () => {
- server.use(
- rest.get(apiKeysURL, (req, res, ctx) =>
- res(ctx.status(200), ctx.json(getAPIKeysResponse)),
- ),
- );
-
- await waitFor(() => {
- expect(screen.getByText('No Expiry Key')).toBeInTheDocument();
- expect(screen.getByText('1-5 of 18 keys')).toBeInTheDocument();
- });
- });
-
- it('opens add new key modal on button click', async () => {
- fireEvent.click(screen.getByText('New Key'));
- await waitFor(() => {
- const createNewKeyBtn = screen.getByRole('button', {
- name: /Create new key/i,
- });
-
- expect(createNewKeyBtn).toBeInTheDocument();
- });
- });
-
- it('closes add new key modal on cancel button click', async () => {
- fireEvent.click(screen.getByText('New Key'));
-
- const createNewKeyBtn = screen.getByRole('button', {
- name: /Create new key/i,
- });
-
- await waitFor(() => {
- expect(createNewKeyBtn).toBeInTheDocument();
- });
- fireEvent.click(screen.getByText('Cancel'));
- await waitFor(() => {
- expect(createNewKeyBtn).not.toBeInTheDocument();
- });
- });
-
- it('creates a new key on form submission', async () => {
- server.use(
- rest.post(apiKeysURL, (req, res, ctx) =>
- res(ctx.status(200), ctx.json(createAPIKeyResponse)),
- ),
- );
-
- fireEvent.click(screen.getByText('New Key'));
-
- const createNewKeyBtn = screen.getByRole('button', {
- name: /Create new key/i,
- });
-
- await waitFor(() => {
- expect(createNewKeyBtn).toBeInTheDocument();
- });
-
- act(() => {
- const inputElement = screen.getByPlaceholderText('Enter Key Name');
- fireEvent.change(inputElement, { target: { value: 'Top Secret' } });
- fireEvent.click(screen.getByTestId('create-form-admin-role-btn'));
- fireEvent.click(createNewKeyBtn);
- });
- });
-});
diff --git a/frontend/src/container/APIKeys/APIKeys.tsx b/frontend/src/container/APIKeys/APIKeys.tsx
deleted file mode 100644
index f1bb412a1b..0000000000
--- a/frontend/src/container/APIKeys/APIKeys.tsx
+++ /dev/null
@@ -1,874 +0,0 @@
-import { ChangeEvent, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { useMutation } from 'react-query';
-import { useCopyToClipboard } from 'react-use';
-import { Color } from '@signozhq/design-tokens';
-import {
- Avatar,
- Button,
- Col,
- Collapse,
- CollapseProps,
- Flex,
- Form,
- Input,
- Modal,
- Radio,
- Row,
- Select,
- Table,
- TableProps,
- Tooltip,
- Typography,
-} from 'antd';
-import type { NotificationInstance } from 'antd/es/notification/interface';
-import createAPIKeyApi from 'api/v1/pats/create';
-import deleteAPIKeyApi from 'api/v1/pats/delete';
-import updateAPIKeyApi from 'api/v1/pats/update';
-import cx from 'classnames';
-import dayjs from 'dayjs';
-import relativeTime from 'dayjs/plugin/relativeTime';
-import { useGetAllAPIKeys } from 'hooks/APIKeys/useGetAllAPIKeys';
-import { useNotifications } from 'hooks/useNotifications';
-import {
- CalendarClock,
- Check,
- ClipboardEdit,
- Contact2,
- Copy,
- Eye,
- Minus,
- PenLine,
- Plus,
- Search,
- Trash2,
- View,
- X,
-} from 'lucide-react';
-import { useAppContext } from 'providers/App/App';
-import APIError from 'types/api/error';
-import { APIKeyProps } from 'types/api/pat/types';
-import { USER_ROLES } from 'types/roles';
-
-import './APIKeys.styles.scss';
-
-dayjs.extend(relativeTime);
-
-export const showErrorNotification = (
- notifications: NotificationInstance,
- err: APIError,
-): void => {
- notifications.error({
- message: err.getErrorCode(),
- description: err.getErrorMessage(),
- });
-};
-
-type ExpiryOption = {
- value: string;
- label: string;
-};
-
-export const EXPIRATION_WITHIN_SEVEN_DAYS = 7;
-
-const API_KEY_EXPIRY_OPTIONS: ExpiryOption[] = [
- { value: '1', label: '1 day' },
- { value: '7', label: '1 week' },
- { value: '30', label: '1 month' },
- { value: '90', label: '3 months' },
- { value: '365', label: '1 year' },
- { value: '0', label: 'No Expiry' },
-];
-
-export const isExpiredToken = (expiryTimestamp: number): boolean => {
- if (expiryTimestamp === 0) {
- return false;
- }
- const currentTime = dayjs();
- const tokenExpiresAt = dayjs.unix(expiryTimestamp);
- return tokenExpiresAt.isBefore(currentTime);
-};
-
-export const getDateDifference = (
- createdTimestamp: number,
- expiryTimestamp: number,
-): number => {
- const differenceInSeconds = Math.abs(expiryTimestamp - createdTimestamp);
-
- // Convert seconds to days
- return differenceInSeconds / (60 * 60 * 24);
-};
-
-function APIKeys(): JSX.Element {
- const { user } = useAppContext();
- const { notifications } = useNotifications();
- const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
- const [isAddModalOpen, setIsAddModalOpen] = useState(false);
- const [showNewAPIKeyDetails, setShowNewAPIKeyDetails] = useState(false);
- const [, handleCopyToClipboard] = useCopyToClipboard();
-
- const [isEditModalOpen, setIsEditModalOpen] = useState(false);
- const [activeAPIKey, setActiveAPIKey] = useState<APIKeyProps | null>();
-
- const [searchValue, setSearchValue] = useState<string>('');
- const [dataSource, setDataSource] = useState<APIKeyProps[]>([]);
- const { t } = useTranslation(['apiKeys']);
-
- const [editForm] = Form.useForm();
- const [createForm] = Form.useForm();
-
- const handleFormReset = (): void => {
- editForm.resetFields();
- createForm.resetFields();
- };
-
- const hideDeleteViewModal = (): void => {
- handleFormReset();
- setActiveAPIKey(null);
- setIsDeleteModalOpen(false);
- };
-
- const showDeleteModal = (apiKey: APIKeyProps): void => {
- setActiveAPIKey(apiKey);
- setIsDeleteModalOpen(true);
- };
-
- const hideEditViewModal = (): void => {
- handleFormReset();
- setActiveAPIKey(null);
- setIsEditModalOpen(false);
- };
-
- const hideAddViewModal = (): void => {
- handleFormReset();
- setShowNewAPIKeyDetails(false);
- setActiveAPIKey(null);
- setIsAddModalOpen(false);
- };
-
- const showEditModal = (apiKey: APIKeyProps): void => {
- handleFormReset();
- setActiveAPIKey(apiKey);
-
- editForm.setFieldsValue({
- name: apiKey.name,
- role: apiKey.role || USER_ROLES.VIEWER,
- });
-
- setIsEditModalOpen(true);
- };
-
- const showAddModal = (): void => {
- setActiveAPIKey(null);
- setIsAddModalOpen(true);
- };
-
- const handleModalClose = (): void => {
- setActiveAPIKey(null);
- };
-
- const {
- data: APIKeys,
- isLoading,
- isRefetching,
- refetch: refetchAPIKeys,
- error,
- isError,
- } = useGetAllAPIKeys();
-
- useEffect(() => {
- setActiveAPIKey(APIKeys?.data?.[0]);
- }, [APIKeys]);
-
- useEffect(() => {
- setDataSource(APIKeys?.data || []);
- }, [APIKeys?.data]);
-
- useEffect(() => {
- if (isError) {
- showErrorNotification(notifications, error as APIError);
- }
- }, [error, isError, notifications]);
-
- const handleSearch = (e: ChangeEvent<HTMLInputElement>): void => {
- setSearchValue(e.target.value);
- const filteredData = APIKeys?.data?.filter(
- (key: APIKeyProps) =>
- key &&
- key.name &&
- key.name.toLowerCase().includes(e.target.value.toLowerCase()),
- );
- setDataSource(filteredData || []);
- };
-
- const clearSearch = (): void => {
- setSearchValue('');
- };
-
- const { mutate: createAPIKey, isLoading: isLoadingCreateAPIKey } = useMutation(
- createAPIKeyApi,
- {
- onSuccess: (data) => {
- setShowNewAPIKeyDetails(true);
- setActiveAPIKey(data.data);
-
- refetchAPIKeys();
- },
- onError: (error) => {
- showErrorNotification(notifications, error as APIError);
- },
- },
- );
-
- const { mutate: updateAPIKey, isLoading: isLoadingUpdateAPIKey } = useMutation(
- updateAPIKeyApi,
- {
- onSuccess: () => {
- refetchAPIKeys();
- setIsEditModalOpen(false);
- },
- onError: (error) => {
- showErrorNotification(notifications, error as APIError);
- },
- },
- );
-
- const { mutate: deleteAPIKey, isLoading: isDeleteingAPIKey } = useMutation(
- deleteAPIKeyApi,
- {
- onSuccess: () => {
- refetchAPIKeys();
- setIsDeleteModalOpen(false);
- },
- onError: (error) => {
- showErrorNotification(notifications, error as APIError);
- },
- },
- );
-
- const onDeleteHandler = (): void => {
- clearSearch();
-
- if (activeAPIKey) {
- deleteAPIKey(activeAPIKey.id);
- }
- };
-
- const onUpdateApiKey = (): void => {
- editForm
- .validateFields()
- .then((values) => {
- if (activeAPIKey) {
- updateAPIKey({
- id: activeAPIKey.id,
- data: {
- name: values.name,
- role: values.role,
- },
- });
- }
- })
- .catch((errorInfo) => {
- console.error('error info', errorInfo);
- });
- };
-
- const onCreateAPIKey = (): void => {
- createForm
- .validateFields()
- .then((values) => {
- if (user) {
- createAPIKey({
- name: values.name,
- expiresInDays: parseInt(values.expiration, 10),
- role: values.role,
- });
- }
- })
- .catch((errorInfo) => {
- console.error('error info', errorInfo);
- });
- };
-
- const handleCopyKey = (text: string): void => {
- handleCopyToClipboard(text);
- notifications.success({
- message: 'Copied to clipboard',
- });
- };
-
- const getFormattedTime = (epochTime: number): string => {
- const timeOptions: Intl.DateTimeFormatOptions = {
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit',
- hour12: false,
- };
- const formattedTime = new Date(epochTime * 1000).toLocaleTimeString(
- 'en-US',
- timeOptions,
- );
-
- const dateOptions: Intl.DateTimeFormatOptions = {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- };
-
- const formattedDate = new Date(epochTime * 1000).toLocaleDateString(
- 'en-US',
- dateOptions,
- );
-
- return `${formattedDate} ${formattedTime}`;
- };
-
- const handleCopyClose = (): void => {
- if (activeAPIKey) {
- handleCopyKey(activeAPIKey?.token);
- }
-
- hideAddViewModal();
- };
-
- const columns: TableProps<APIKeyProps>['columns'] = [
- {
- title: 'API Key',
- key: 'api-key',
- // eslint-disable-next-line sonarjs/cognitive-complexity
- render: (APIKey: APIKeyProps): JSX.Element => {
- const formattedDateAndTime =
- APIKey && APIKey?.lastUsed && APIKey?.lastUsed !== 0
- ? getFormattedTime(APIKey?.lastUsed)
- : 'Never';
-
- const createdOn = new Date(APIKey.createdAt).toLocaleString();
-
- const expiresIn =
- APIKey.expiresAt === 0
- ? Number.POSITIVE_INFINITY
- : getDateDifference(
- new Date(APIKey?.createdAt).getTime() / 1000,
- APIKey?.expiresAt,
- );
-
- const isExpired = isExpiredToken(APIKey.expiresAt);
-
- const expiresOn =
- !APIKey.expiresAt || APIKey.expiresAt === 0
- ? 'No Expiry'
- : getFormattedTime(APIKey.expiresAt);
-
- const updatedOn =
- !APIKey.updatedAt || APIKey.updatedAt === ''
- ? null
- : new Date(APIKey.updatedAt).toLocaleString();
-
- const items: CollapseProps['items'] = [
- {
- key: '1',
- label: (
- <div className="title-with-action">
- <div className="api-key-data">
- <div className="api-key-title">
- <Typography.Text>{APIKey?.name}</Typography.Text>
- </div>
-
- <div className="api-key-value">
- <Typography.Text>
- {APIKey?.token.substring(0, 2)}********
- {APIKey?.token.substring(APIKey.token.length - 2).trim()}
- </Typography.Text>
-
- <Copy
- className="copy-key-btn"
- size={12}
- onClick={(e): void => {
- e.stopPropagation();
- e.preventDefault();
- handleCopyKey(APIKey.token);
- }}
- />
- </div>
-
- {APIKey.role === USER_ROLES.ADMIN && (
- <Tooltip title={USER_ROLES.ADMIN}>
- <Contact2 size={14} color={Color.BG_ROBIN_400} />
- </Tooltip>
- )}
-
- {APIKey.role === USER_ROLES.EDITOR && (
- <Tooltip title={USER_ROLES.EDITOR}>
- <ClipboardEdit size={14} color={Color.BG_ROBIN_400} />
- </Tooltip>
- )}
-
- {APIKey.role === USER_ROLES.VIEWER && (
- <Tooltip title={USER_ROLES.VIEWER}>
- <View size={14} color={Color.BG_ROBIN_400} />
- </Tooltip>
- )}
-
- {!APIKey.role && (
- <Tooltip title={USER_ROLES.ADMIN}>
- <Contact2 size={14} color={Color.BG_ROBIN_400} />
- </Tooltip>
- )}
- </div>
- <div className="action-btn">
- <Button
- className="periscope-btn ghost"
- icon={<PenLine size={14} />}
- onClick={(e): void => {
- e.stopPropagation();
- e.preventDefault();
- showEditModal(APIKey);
- }}
- />
-
- <Button
- className="periscope-btn ghost"
- icon={<Trash2 color={Color.BG_CHERRY_500} size={14} />}
- onClick={(e): void => {
- e.stopPropagation();
- e.preventDefault();
- showDeleteModal(APIKey);
- }}
- />
- </div>
- </div>
- ),
- children: (
- <div className="api-key-info-container">
- {APIKey?.createdByUser && (
- <Row>
- <Col span={6}> Creator </Col>
- <Col span={12} className="user-info">
- <Avatar className="user-avatar" size="small">
- {APIKey?.createdByUser?.displayName?.substring(0, 1)}
- </Avatar>
-
- <Typography.Text>
- {APIKey.createdByUser?.displayName}
- </Typography.Text>
-
- <div className="user-email">{APIKey.createdByUser?.email}</div>
- </Col>
- </Row>
- )}
- <Row>
- <Col span={6}> Created on </Col>
- <Col span={12}>
- <Typography.Text>{createdOn}</Typography.Text>
- </Col>
- </Row>
- {updatedOn && (
- <Row>
- <Col span={6}> Updated on </Col>
- <Col span={12}>
- <Typography.Text>{updatedOn}</Typography.Text>
- </Col>
- </Row>
- )}
-
- <Row>
- <Col span={6}> Expires on </Col>
- <Col span={12}>
- <Typography.Text>{expiresOn}</Typography.Text>
- </Col>
- </Row>
- </div>
- ),
- },
- ];
-
- return (
- <div className="column-render">
- <Collapse items={items} />
-
- <div className="api-key-details">
- <div className="api-key-last-used-at">
- <CalendarClock size={14} />
- Last used <Minus size={12} />
- <Typography.Text>{formattedDateAndTime}</Typography.Text>
- </div>
-
- {!isExpired && expiresIn <= EXPIRATION_WITHIN_SEVEN_DAYS && (
- <div
- className={cx(
- 'api-key-expires-in',
- expiresIn <= 3 ? 'danger' : 'warning',
- )}
- >
- <span className="dot" /> Expires {dayjs().to(expiresOn)}
- </div>
- )}
-
- {isExpired && (
- <div className={cx('api-key-expires-in danger')}>
- <span className="dot" /> Expired
- </div>
- )}
- </div>
- </div>
- );
- },
- },
- ];
-
- return (
- <div className="api-key-container">
- <div className="api-key-content">
- <header>
- <Typography.Title className="title">API Keys</Typography.Title>
- <Typography.Text className="subtitle">
- Create and manage API keys for the SigNoz API
- </Typography.Text>
- </header>
-
- <div className="api-keys-search-add-new">
- <Input
- placeholder="Search for keys..."
- prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
- value={searchValue}
- onChange={handleSearch}
- />
-
- <Button
- className="add-new-api-key-btn"
- type="primary"
- onClick={showAddModal}
- >
- <Plus size={14} /> New Key
- </Button>
- </div>
-
- <Table
- columns={columns}
- dataSource={dataSource}
- loading={isLoading || isRefetching}
- showHeader={false}
- pagination={{
- pageSize: 5,
- hideOnSinglePage: true,
- showTotal: (total: number, range: number[]): string =>
- `${range[0]}-${range[1]} of ${total} keys`,
- }}
- />
- </div>
-
- {/* Delete Key Modal */}
- <Modal
- className="delete-api-key-modal"
- title={<span className="title">Delete Key</span>}
- open={isDeleteModalOpen}
- closable
- afterClose={handleModalClose}
- onCancel={hideDeleteViewModal}
- destroyOnClose
- footer={[
- <Button
- key="cancel"
- onClick={hideDeleteViewModal}
- className="cancel-btn"
- icon={<X size={16} />}
- >
- Cancel
- </Button>,
- <Button
- key="submit"
- icon={<Trash2 size={16} />}
- loading={isDeleteingAPIKey}
- onClick={onDeleteHandler}
- className="delete-btn"
- >
- Delete key
- </Button>,
- ]}
- >
- <Typography.Text className="delete-text">
- {t('delete_confirm_message', {
- keyName: activeAPIKey?.name,
- })}
- </Typography.Text>
- </Modal>
-
- {/* Edit Key Modal */}
- <Modal
- className="api-key-modal"
- title="Edit key"
- open={isEditModalOpen}
- key="edit-api-key-modal"
- afterClose={handleModalClose}
- // closable
- onCancel={hideEditViewModal}
- destroyOnClose
- footer={[
- <Button
- key="cancel"
- onClick={hideEditViewModal}
- className="periscope-btn cancel-btn"
- icon={<X size={16} />}
- >
- Cancel
- </Button>,
- <Button
- className="periscope-btn primary"
- key="submit"
- type="primary"
- loading={isLoadingUpdateAPIKey}
- icon={<Check size={14} />}
- onClick={onUpdateApiKey}
- >
- Update key
- </Button>,
- ]}
- >
- <Form
- name="edit-api-key-form"
- key={activeAPIKey?.id}
- form={editForm}
- layout="vertical"
- autoComplete="off"
- initialValues={{
- name: activeAPIKey?.name,
- role: activeAPIKey?.role,
- }}
- >
- <Form.Item
- name="name"
- label="Name"
- rules={[{ required: true }, { type: 'string', min: 6 }]}
- >
- <Input placeholder="Enter Key Name" autoFocus />
- </Form.Item>
-
- <Form.Item name="role" label="Role">
- <Flex vertical gap="middle">
- <Radio.Group
- buttonStyle="solid"
- className="api-key-access-role"
- defaultValue={activeAPIKey?.role}
- >
- <Radio.Button value={USER_ROLES.ADMIN} className={cx('tab')}>
- <div className="role">
- <Contact2 size={14} /> Admin
- </div>
- </Radio.Button>
- <Radio.Button value={USER_ROLES.EDITOR} className={cx('tab')}>
- <div className="role">
- <ClipboardEdit size={14} /> Editor
- </div>
- </Radio.Button>
- <Radio.Button value={USER_ROLES.VIEWER} className={cx('tab')}>
- <div className="role">
- <Eye size={14} /> Viewer
- </div>
- </Radio.Button>
- </Radio.Group>
- </Flex>
- </Form.Item>
- </Form>
- </Modal>
-
- {/* Create New Key Modal */}
- <Modal
- className="api-key-modal"
- title="Create new key"
- open={isAddModalOpen}
- key="create-api-key-modal"
- closable
- onCancel={hideAddViewModal}
- destroyOnClose
- footer={
- showNewAPIKeyDetails
- ? [
- <Button
- key="copy-key-close"
- className="periscope-btn primary"
- data-testid="copy-key-close-btn"
- type="primary"
- onClick={handleCopyClose}
- icon={<Check size={12} />}
- >
- Copy key and close
- </Button>,
- ]
- : [
- <Button
- key="cancel"
- onClick={hideAddViewModal}
- className="periscope-btn cancel-btn"
- icon={<X size={16} />}
- >
- Cancel
- </Button>,
- <Button
- className="periscope-btn primary"
- test-id="create-new-key"
- key="submit"
- type="primary"
- icon={<Check size={14} />}
- loading={isLoadingCreateAPIKey}
- onClick={onCreateAPIKey}
- >
- Create new key
- </Button>,
- ]
- }
- >
- {!showNewAPIKeyDetails && (
- <Form
- key="createForm"
- name="create-api-key-form"
- form={createForm}
- initialValues={{
- role: USER_ROLES.ADMIN,
- expiration: '1',
- name: '',
- }}
- layout="vertical"
- autoComplete="off"
- >
- <Form.Item
- name="name"
- label="Name"
- rules={[{ required: true }, { type: 'string', min: 6 }]}
- validateTrigger="onFinish"
- >
- <Input placeholder="Enter Key Name" autoFocus />
- </Form.Item>
-
- <Form.Item name="role" label="Role">
- <Flex vertical gap="middle">
- <Radio.Group
- buttonStyle="solid"
- className="api-key-access-role"
- defaultValue={USER_ROLES.ADMIN}
- >
- <Radio.Button value={USER_ROLES.ADMIN} className={cx('tab')}>
- <div className="role" data-testid="create-form-admin-role-btn">
- <Contact2 size={14} /> Admin
- </div>
- </Radio.Button>
- <Radio.Button value={USER_ROLES.EDITOR} className="tab">
- <div className="role" data-testid="create-form-editor-role-btn">
- <ClipboardEdit size={14} /> Editor
- </div>
- </Radio.Button>
- <Radio.Button value={USER_ROLES.VIEWER} className="tab">
- <div className="role" data-testid="create-form-viewer-role-btn">
- <Eye size={14} /> Viewer
- </div>
- </Radio.Button>
- </Radio.Group>
- </Flex>
- </Form.Item>
- <Form.Item name="expiration" label="Expiration">
- <Select
- className="expiration-selector"
- placeholder="Expiration"
- options={API_KEY_EXPIRY_OPTIONS}
- />
- </Form.Item>
- </Form>
- )}
-
- {showNewAPIKeyDetails && (
- <div className="api-key-info-container">
- <Row>
- <Col span={8}>Key</Col>
- <Col span={16}>
- <span className="copyable-text">
- <Typography.Text>
- {activeAPIKey?.token.substring(0, 2)}****************
- {activeAPIKey?.token.substring(activeAPIKey.token.length - 2).trim()}
- </Typography.Text>
-
- <Copy
- className="copy-key-btn"
- size={12}
- onClick={(): void => {
- if (activeAPIKey) {
- handleCopyKey(activeAPIKey.token);
- }
- }}
- />
- </span>
- </Col>
- </Row>
-
- <Row>
- <Col span={8}>Name</Col>
- <Col span={16}>{activeAPIKey?.name}</Col>
- </Row>
-
- <Row>
- <Col span={8}>Role</Col>
- <Col span={16}>
- {activeAPIKey?.role === USER_ROLES.ADMIN && (
- <div className="role">
- <Contact2 size={14} /> Admin
- </div>
- )}
- {activeAPIKey?.role === USER_ROLES.EDITOR && (
- <div className="role">
- {' '}
- <ClipboardEdit size={14} /> Editor
- </div>
- )}
- {activeAPIKey?.role === USER_ROLES.VIEWER && (
- <div className="role">
- {' '}
- <View size={14} /> Viewer
- </div>
- )}
- </Col>
- </Row>
-
- <Row>
- <Col span={8}>Creator</Col>
-
- <Col span={16} className="user-info">
- <Avatar className="user-avatar" size="small">
- {activeAPIKey?.createdByUser?.displayName?.substring(0, 1)}
- </Avatar>
-
- <Typography.Text>
- {activeAPIKey?.createdByUser?.displayName}
- </Typography.Text>
-
- <div className="user-email">{activeAPIKey?.createdByUser?.email}</div>
- </Col>
- </Row>
-
- {activeAPIKey?.createdAt && (
- <Row>
- <Col span={8}>Created on</Col>
- <Col span={16}>
- {new Date(activeAPIKey?.createdAt).toLocaleString()}
- </Col>
- </Row>
- )}
-
- {activeAPIKey?.expiresAt !== 0 && activeAPIKey?.expiresAt && (
- <Row>
- <Col span={8}>Expires on</Col>
- <Col span={16}>{getFormattedTime(activeAPIKey?.expiresAt)}</Col>
- </Row>
- )}
-
- {activeAPIKey?.expiresAt === 0 && (
- <Row>
- <Col span={8}>Expires on</Col>
- <Col span={16}> No Expiry </Col>
- </Row>
- )}
- </div>
- )}
- </Modal>
- </div>
- );
-}
-
-export default APIKeys;
diff --git a/frontend/src/container/Home/Home.tsx b/frontend/src/container/Home/Home.tsx
index 513cae2bb5..a5ea97047c 100644
--- a/frontend/src/container/Home/Home.tsx
+++ b/frontend/src/container/Home/Home.tsx
@@ -16,7 +16,6 @@ import { ORG_PREFERENCES } from 'constants/orgPreferences';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import ROUTES from 'constants/routes';
-import { IS_SERVICE_ACCOUNTS_ENABLED } from 'container/ServiceAccountsSettings/config';
import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { useIsDarkMode } from 'hooks/useDarkMode';
@@ -265,23 +264,21 @@ export default function Home(): JSX.Element {
return (
<div className="home-container">
- {IS_SERVICE_ACCOUNTS_ENABLED && (
- <PersistedAnnouncementBanner
- type="warning"
- storageKey={LOCALSTORAGE.DISMISSED_API_KEYS_DEPRECATION_BANNER}
- message={
- <>
- <strong>API Keys</strong> have been deprecated and replaced by{' '}
- <strong>Service Accounts</strong>. Please migrate to Service Accounts for
- programmatic API access.
- </>
- }
- action={{
- label: 'Go to Service Accounts',
- onClick: (): void => history.push(ROUTES.SERVICE_ACCOUNTS_SETTINGS),
- }}
- />
- )}
+ <PersistedAnnouncementBanner
+ type="warning"
+ storageKey={LOCALSTORAGE.DISMISSED_API_KEYS_DEPRECATION_BANNER}
+ message={
+ <>
+ <strong>API Keys</strong> have been deprecated and replaced by{' '}
+ <strong>Service Accounts</strong>. Please migrate to Service Accounts for
+ programmatic API access.
+ </>
+ }
+ action={{
+ label: 'Go to Service Accounts',
+ onClick: (): void => history.push(ROUTES.SERVICE_ACCOUNTS_SETTINGS),
+ }}
+ />
<div className="sticky-header">
<Header
diff --git a/frontend/src/container/ServiceAccountsSettings/ServiceAccountsSettings.tsx b/frontend/src/container/ServiceAccountsSettings/ServiceAccountsSettings.tsx
index d0f037b179..ef7082a45b 100644
--- a/frontend/src/container/ServiceAccountsSettings/ServiceAccountsSettings.tsx
+++ b/frontend/src/container/ServiceAccountsSettings/ServiceAccountsSettings.tsx
@@ -1,18 +1,10 @@
import { useCallback, useEffect, useMemo } from 'react';
-import { useQueryClient } from 'react-query';
import { Button } from '@signozhq/button';
import { Check, ChevronDown, Plus } from '@signozhq/icons';
import { Input } from '@signozhq/input';
import type { MenuProps } from 'antd';
import { Dropdown } from 'antd';
-import {
- getGetServiceAccountQueryKey,
- useListServiceAccounts,
-} from 'api/generated/services/serviceaccount';
-import type {
- GetServiceAccount200,
- ListServiceAccounts200,
-} from 'api/generated/services/sigNoz.schemas';
+import { useListServiceAccounts } from 'api/generated/services/serviceaccount';
import CreateServiceAccountModal from 'components/CreateServiceAccountModal/CreateServiceAccountModal';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import ServiceAccountDrawer from 'components/ServiceAccountDrawer/ServiceAccountDrawer';
@@ -59,29 +51,13 @@ function ServiceAccountsSettings(): JSX.Element {
parseAsBoolean.withDefault(false),
);
- const queryClient = useQueryClient();
-
- const seedAccountCache = useCallback(
- (data: ListServiceAccounts200) => {
- data.data.forEach((account) => {
- queryClient.setQueryData<GetServiceAccount200>(
- getGetServiceAccountQueryKey({ id: account.id }),
- (old) => old ?? { data: account, status: data.status },
- );
- });
- },
- [queryClient],
- );
-
const {
data: serviceAccountsData,
isLoading,
isError,
error,
refetch: handleCreateSuccess,
- } = useListServiceAccounts({
- query: { onSuccess: seedAccountCache },
- });
+ } = useListServiceAccounts();
const allAccounts = useMemo(
(): ServiceAccountRow[] =>
@@ -97,10 +73,10 @@ function ServiceAccountsSettings(): JSX.Element {
[allAccounts],
);
- const disabledCount = useMemo(
+ const deletedCount = useMemo(
() =>
allAccounts.filter(
- (a) => a.status?.toUpperCase() !== ServiceAccountStatus.Active,
+ (a) => a.status?.toUpperCase() === ServiceAccountStatus.Deleted,
).length,
[allAccounts],
);
@@ -112,9 +88,9 @@ function ServiceAccountsSettings(): JSX.Element {
result = result.filter(
(a) => a.status?.toUpperCase() === ServiceAccountStatus.Active,
);
- } else if (filterMode === FilterMode.Disabled) {
+ } else if (filterMode === FilterMode.Deleted) {
result = result.filter(
- (a) => a.status?.toUpperCase() !== ServiceAccountStatus.Active,
+ (a) => a.status?.toUpperCase() === ServiceAccountStatus.Deleted,
);
}
@@ -122,9 +98,7 @@ function ServiceAccountsSettings(): JSX.Element {
const q = searchQuery.trim().toLowerCase();
result = result.filter(
(a) =>
- a.name?.toLowerCase().includes(q) ||
- a.email?.toLowerCase().includes(q) ||
- a.roles?.some((role: string) => role.toLowerCase().includes(q)),
+ a.name?.toLowerCase().includes(q) || a.email?.toLowerCase().includes(q),
);
}
@@ -174,15 +148,15 @@ function ServiceAccountsSettings(): JSX.Element {
},
},
{
- key: FilterMode.Disabled,
+ key: FilterMode.Deleted,
label: (
<div className="sa-settings-filter-option">
- <span>Disabled ⎯ {disabledCount}</span>
- {filterMode === FilterMode.Disabled && <Check size={14} />}
+ <span>Deleted ⎯ {deletedCount}</span>
+ {filterMode === FilterMode.Deleted && <Check size={14} />}
</div>
),
onClick: (): void => {
- setFilterMode(FilterMode.Disabled);
+ setFilterMode(FilterMode.Deleted);
setPage(1);
},
},
@@ -192,8 +166,8 @@ function ServiceAccountsSettings(): JSX.Element {
switch (filterMode) {
case FilterMode.Active:
return `Active ⎯ ${activeCount}`;
- case FilterMode.Disabled:
- return `Disabled ⎯ ${disabledCount}`;
+ case FilterMode.Deleted:
+ return `Deleted ⎯ ${deletedCount}`;
default:
return `All accounts ⎯ ${totalCount}`;
}
diff --git a/frontend/src/container/ServiceAccountsSettings/__tests__/ServiceAccountsSettings.integration.test.tsx b/frontend/src/container/ServiceAccountsSettings/__tests__/ServiceAccountsSettings.integration.test.tsx
index 5070b4dc7a..5247f76919 100644
--- a/frontend/src/container/ServiceAccountsSettings/__tests__/ServiceAccountsSettings.integration.test.tsx
+++ b/frontend/src/container/ServiceAccountsSettings/__tests__/ServiceAccountsSettings.integration.test.tsx
@@ -2,7 +2,7 @@ import type { ReactNode } from 'react';
import { listRolesSuccessResponse } from 'mocks-server/__mockdata__/roles';
import { rest, server } from 'mocks-server/server';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
-import { render, screen, userEvent } from 'tests/test-utils';
+import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import ServiceAccountsSettings from '../ServiceAccountsSettings';
@@ -149,7 +149,7 @@ describe('ServiceAccountsSettings (integration)', () => {
);
expect(
- await screen.findByRole('button', { name: /Disable Service Account/i }),
+ await screen.findByRole('button', { name: /Delete Service Account/i }),
).toBeInTheDocument();
});
@@ -187,14 +187,16 @@ describe('ServiceAccountsSettings (integration)', () => {
await user.click(screen.getByRole('button', { name: /Save Changes/i }));
await screen.findByDisplayValue('CI Bot Updated');
- expect(listRefetchSpy).toHaveBeenCalled();
+ await waitFor(() => {
+ expect(listRefetchSpy).toHaveBeenCalled();
+ });
});
it('"New Service Account" button opens the Create Service Account modal', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
- <NuqsTestingAdapter>
+ <NuqsTestingAdapter hasMemory>
<ServiceAccountsSettings />
</NuqsTestingAdapter>,
);
diff --git a/frontend/src/container/ServiceAccountsSettings/config.ts b/frontend/src/container/ServiceAccountsSettings/config.ts
index f80be90597..e69de29bb2 100644
--- a/frontend/src/container/ServiceAccountsSettings/config.ts
+++ b/frontend/src/container/ServiceAccountsSettings/config.ts
@@ -1 +0,0 @@
-export const IS_SERVICE_ACCOUNTS_ENABLED = false;
diff --git a/frontend/src/container/ServiceAccountsSettings/constants.ts b/frontend/src/container/ServiceAccountsSettings/constants.ts
index a7c9014307..d7f937c6f8 100644
--- a/frontend/src/container/ServiceAccountsSettings/constants.ts
+++ b/frontend/src/container/ServiceAccountsSettings/constants.ts
@@ -9,5 +9,5 @@ export const SA_QUERY_PARAMS = {
ADD_KEY: 'add-key',
EDIT_KEY: 'edit-key',
REVOKE_KEY: 'revoke-key',
- DISABLE_SA: 'disable-sa',
+ DELETE_SA: 'delete-sa',
} as const;
diff --git a/frontend/src/container/ServiceAccountsSettings/utils.ts b/frontend/src/container/ServiceAccountsSettings/utils.ts
index 4e87ee264d..81f906eb74 100644
--- a/frontend/src/container/ServiceAccountsSettings/utils.ts
+++ b/frontend/src/container/ServiceAccountsSettings/utils.ts
@@ -8,7 +8,6 @@ export function toServiceAccountRow(
id: sa.id,
name: sa.name,
email: sa.email,
- roles: sa.roles,
status: sa.status,
createdAt: toISOString(sa.createdAt),
updatedAt: toISOString(sa.updatedAt),
@@ -18,19 +17,18 @@ export function toServiceAccountRow(
export enum FilterMode {
All = 'all',
Active = 'active',
- Disabled = 'disabled',
+ Deleted = 'deleted',
}
export enum ServiceAccountStatus {
Active = 'ACTIVE',
- Disabled = 'DISABLED',
+ Deleted = 'DELETED',
}
export interface ServiceAccountRow {
id: string;
name: string;
email: string;
- roles: string[];
status: string;
createdAt: string | null;
updatedAt: string | null;
diff --git a/frontend/src/container/SideNav/SideNav.tsx b/frontend/src/container/SideNav/SideNav.tsx
index e3c971fae0..afc8a2895b 100644
--- a/frontend/src/container/SideNav/SideNav.tsx
+++ b/frontend/src/container/SideNav/SideNav.tsx
@@ -692,9 +692,6 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
registerShortcut(GlobalShortcuts.NavigateToSettingsBilling, () =>
onClickHandler(ROUTES.BILLING, null),
);
- registerShortcut(GlobalShortcuts.NavigateToSettingsAPIKeys, () =>
- onClickHandler(ROUTES.API_KEYS, null),
- );
registerShortcut(GlobalShortcuts.NavigateToSettingsNotificationChannels, () =>
onClickHandler(ROUTES.ALL_CHANNELS, null),
);
@@ -720,7 +717,6 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
deregisterShortcut(GlobalShortcuts.NavigateToSettings);
deregisterShortcut(GlobalShortcuts.NavigateToSettingsIngestion);
deregisterShortcut(GlobalShortcuts.NavigateToSettingsBilling);
- deregisterShortcut(GlobalShortcuts.NavigateToSettingsAPIKeys);
deregisterShortcut(GlobalShortcuts.NavigateToSettingsNotificationChannels);
deregisterShortcut(GlobalShortcuts.NavigateToLogsPipelines);
deregisterShortcut(GlobalShortcuts.NavigateToLogsViews);
diff --git a/frontend/src/container/SideNav/menuItems.tsx b/frontend/src/container/SideNav/menuItems.tsx
index fefb99f896..df8556ec03 100644
--- a/frontend/src/container/SideNav/menuItems.tsx
+++ b/frontend/src/container/SideNav/menuItems.tsx
@@ -19,7 +19,6 @@ import {
Github,
HardDrive,
Home,
- Key,
Keyboard,
Layers2,
LayoutGrid,
@@ -366,13 +365,6 @@ export const settingsNavSections: SettingsNavSection[] = [
isEnabled: false,
itemKey: 'service-accounts',
},
- {
- key: ROUTES.API_KEYS,
- label: 'API Keys',
- icon: <Key size={16} />,
- isEnabled: false,
- itemKey: 'api-keys',
- },
{
key: ROUTES.INGESTION_SETTINGS,
label: 'Ingestion',
diff --git a/frontend/src/container/TopNav/DateTimeSelectionV2/constants.ts b/frontend/src/container/TopNav/DateTimeSelectionV2/constants.ts
index 418cbe506a..6668b17ee8 100644
--- a/frontend/src/container/TopNav/DateTimeSelectionV2/constants.ts
+++ b/frontend/src/container/TopNav/DateTimeSelectionV2/constants.ts
@@ -158,7 +158,6 @@ export const routesToSkip = [
ROUTES.MEMBERS_SETTINGS,
ROUTES.SERVICE_ACCOUNTS_SETTINGS,
ROUTES.INGESTION_SETTINGS,
- ROUTES.API_KEYS,
ROUTES.ERROR_DETAIL,
ROUTES.LOGS_PIPELINES,
ROUTES.BILLING,
diff --git a/frontend/src/hooks/APIKeys/useGetAllAPIKeys.ts b/frontend/src/hooks/APIKeys/useGetAllAPIKeys.ts
deleted file mode 100644
index 69a5cf3405..0000000000
--- a/frontend/src/hooks/APIKeys/useGetAllAPIKeys.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { useQuery, UseQueryResult } from 'react-query';
-import list from 'api/v1/pats/list';
-import { SuccessResponseV2 } from 'types/api';
-import APIError from 'types/api/error';
-import { APIKeyProps } from 'types/api/pat/types';
-
-export const useGetAllAPIKeys = (): UseQueryResult<
- SuccessResponseV2<APIKeyProps[]>,
- APIError
-> =>
- useQuery<SuccessResponseV2<APIKeyProps[]>, APIError>({
- queryKey: ['APIKeys'],
- queryFn: () => list(),
- });
diff --git a/frontend/src/hooks/serviceAccount/useServiceAccountRoleManager.ts b/frontend/src/hooks/serviceAccount/useServiceAccountRoleManager.ts
new file mode 100644
index 0000000000..73f8e9462c
--- /dev/null
+++ b/frontend/src/hooks/serviceAccount/useServiceAccountRoleManager.ts
@@ -0,0 +1,113 @@
+import { useCallback, useMemo } from 'react';
+import { useQueryClient } from 'react-query';
+import {
+ getGetServiceAccountRolesQueryKey,
+ useCreateServiceAccountRole,
+ useDeleteServiceAccountRole,
+ useGetServiceAccountRoles,
+} from 'api/generated/services/serviceaccount';
+import type { AuthtypesRoleDTO } from 'api/generated/services/sigNoz.schemas';
+
+export interface RoleUpdateFailure {
+ roleName: string;
+ error: unknown;
+ onRetry: () => Promise<void>;
+}
+
+interface UseServiceAccountRoleManagerResult {
+ currentRoles: AuthtypesRoleDTO[];
+ isLoading: boolean;
+ applyDiff: (
+ localRoleIds: string[],
+ availableRoles: AuthtypesRoleDTO[],
+ ) => Promise<RoleUpdateFailure[]>;
+}
+
+export function useServiceAccountRoleManager(
+ accountId: string,
+): UseServiceAccountRoleManagerResult {
+ const queryClient = useQueryClient();
+
+ const { data, isLoading } = useGetServiceAccountRoles({ id: accountId });
+
+ const currentRoles = useMemo<AuthtypesRoleDTO[]>(() => data?.data ?? [], [
+ data?.data,
+ ]);
+
+ // the retry for these mutations is safe due to being idempotent on backend
+ const { mutateAsync: createRole } = useCreateServiceAccountRole();
+ const { mutateAsync: deleteRole } = useDeleteServiceAccountRole();
+
+ const invalidateRoles = useCallback(
+ () =>
+ queryClient.invalidateQueries(
+ getGetServiceAccountRolesQueryKey({ id: accountId }),
+ ),
+ [accountId, queryClient],
+ );
+
+ const applyDiff = useCallback(
+ async (
+ localRoleIds: string[],
+ availableRoles: AuthtypesRoleDTO[],
+ ): Promise<RoleUpdateFailure[]> => {
+ const currentRoleIds = new Set(
+ currentRoles.map((r) => r.id).filter(Boolean),
+ );
+ const desiredRoleIds = new Set(
+ localRoleIds.filter((id) => id != null && id !== ''),
+ );
+
+ const addedRoles = availableRoles.filter(
+ (r) => r.id && desiredRoleIds.has(r.id) && !currentRoleIds.has(r.id),
+ );
+
+ const removedRoles = currentRoles.filter(
+ (r) => r.id && !desiredRoleIds.has(r.id),
+ );
+
+ const allOperations = [
+ ...addedRoles.map((role) => ({
+ role,
+ run: (): ReturnType<typeof createRole> =>
+ createRole({ pathParams: { id: accountId }, data: { id: role.id } }),
+ })),
+ ...removedRoles.map((role) => ({
+ role,
+ run: (): ReturnType<typeof deleteRole> =>
+ deleteRole({ pathParams: { id: accountId, rid: role.id } }),
+ })),
+ ];
+
+ const results = await Promise.allSettled(
+ allOperations.map((op) => op.run()),
+ );
+
+ await invalidateRoles();
+
+ const failures: RoleUpdateFailure[] = [];
+ results.forEach((result, index) => {
+ if (result.status === 'rejected') {
+ const { role, run } = allOperations[index];
+ failures.push({
+ roleName: role.name ?? 'unknown',
+ error: result.reason,
+ onRetry: async (): Promise<void> => {
+ await run();
+ await invalidateRoles();
+ },
+ });
+ }
+ });
+
+ return failures;
+ },
+ [accountId, currentRoles, createRole, deleteRole, invalidateRoles],
+ );
+
+ return {
+ currentRoles,
+ isLoading,
+ applyDiff,
+ };
+}
diff --git a/frontend/src/mocks-server/__mockdata__/apiKeys.ts b/frontend/src/mocks-server/__mockdata__/apiKeys.ts
deleted file mode 100644
index c5d3c0171a..0000000000
--- a/frontend/src/mocks-server/__mockdata__/apiKeys.ts
+++ /dev/null
@@ -1,541 +0,0 @@
-const createdByEmail = '[email protected]';
-
-export const getAPIKeysResponse = {
- status: 'success',
- data: [
- {
- id: '26',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '',
- name: '',
- email: '',
- createdAt: 0,
- profilePictureURL: '',
- notFound: true,
- },
- token: 'T2DuASwpuUx3wlYraFl5r7N9G1ikBhzGuy2ihcIKDMs=',
- role: 'ADMIN',
- name: '1 Day Old',
- createdAt: 1708010258,
- expiresAt: 1708096658,
- updatedAt: 1708010258,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: '',
- },
- {
- id: '24',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- token: 'EteVs77BA4FFLJD/TsFE9c+CLX4kXVmlx+0GGK7dpXY=',
- role: 'ADMIN',
- name: '1 year expiry - updated',
- createdAt: 1708008146,
- expiresAt: 1739544146,
- updatedAt: 1708008239,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: 'mandalorian',
- },
- {
- id: '25',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- token: '1udrUFmRI6gdb8r/hLabS7zRlgfMQlUw/tz9sac82pE=',
- role: 'ADMIN',
- name: 'No Expiry Key',
- createdAt: 1708008178,
- expiresAt: 0,
- updatedAt: 1708008190,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: 'mandalorian',
- },
- {
- id: '22',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- token: 'gtqKF7g7avoe+Yu2+WhyDDLQSr6IsVaR5xpby2XhLAY=',
- role: 'VIEWER',
- name: 'No Expiry',
- createdAt: 1708007395,
- expiresAt: 0,
- updatedAt: 1708007936,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: 'mandalorian',
- },
- {
- id: '23',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- token: 'GM/TqEID8N4ynlvQHK38ITEvRAcn5XkJZpmd11xT3OQ=',
- role: 'VIEWER',
- name: 'No Expiry - 2',
- createdAt: 1708007685,
- expiresAt: 0,
- updatedAt: 1708007786,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: 'mandalorian',
- },
- {
- id: '19',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- token: 'Oj75e6Zr7JmjFcWIo0UK/Nl06RdC2BKOr/QVHoBA0gM=',
- role: 'ADMIN',
- name: '7 Days',
- createdAt: 1708003326,
- expiresAt: 1708608126,
- updatedAt: 1708007380,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: 'mandalorian',
- },
- {
- id: '20',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- token: 'T+sNdYe6I74ya/9mEKqB3UTrFm8+jwI0DiirqEx3bsM=',
- role: 'EDITOR',
- name: '1 month',
- createdAt: 1708004012,
- expiresAt: 1710596012,
- updatedAt: 1708005206,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: 'mandalorian',
- },
- {
- id: '21',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- token: 'JWw26FuymeHq+fsfFcb+2+Ls/MdokmeXxXdZisuaVeI=',
- role: 'ADMIN',
- name: '3 Months',
- createdAt: 1708004755,
- expiresAt: 1715780755,
- updatedAt: 1708005197,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: 'mandalorian',
- },
- {
- id: '17',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '',
- name: '',
- email: '',
- createdAt: 0,
- profilePictureURL: '',
- notFound: true,
- },
- token: '2zDrYNr+IWXUyA14+afVvO6GI9dcHfEsOYxjA9mrprg=',
- role: 'ADMIN',
- name: 'New No Expiry',
- createdAt: 1708000444,
- expiresAt: 0,
- updatedAt: 1708000444,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: '',
- },
- {
- id: '14',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '',
- name: '',
- email: '',
- createdAt: 0,
- profilePictureURL: '',
- notFound: true,
- },
- token: 'Q+/+UB2OrDPcS9b0+5A1dDXYmWHz0abbVVidF48QCso=',
- role: 'EDITOR',
- name: 'Editor Token for user 1',
- createdAt: 1707997720,
- expiresAt: 1708170520,
- updatedAt: 1707997720,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: '',
- },
- {
- id: '13',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '',
- name: '',
- email: '',
- createdAt: 0,
- profilePictureURL: '',
- notFound: true,
- },
- token: '/X3OEaSOLrrJImvzIB3g5WGg+5831X89fZZQT1JaxvQ=',
- role: 'EDITOR',
- name: 'Editor Token for user 2',
- createdAt: 1707997603,
- expiresAt: 1708170403,
- updatedAt: 1707997603,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: '',
- },
- {
- id: '12',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '',
- name: '',
- email: '',
- createdAt: 0,
- profilePictureURL: '',
- notFound: true,
- },
- token: 'bTs+Q6waIiP4KJ8L5N58EQonuapWMXsfEra/cmMwmbE=',
- role: 'EDITOR',
- name: 'Editor Token for user 3',
- createdAt: 1707997539,
- expiresAt: 1708170339,
- updatedAt: 1707997539,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: '',
- },
- {
- id: '11',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '',
- name: '',
- email: '',
- createdAt: 0,
- profilePictureURL: '',
- notFound: true,
- },
- token: 'YaEqQHrH8KOnYFllor/8Tq653TgxPU1Z7ZDzY3+ETmI=',
- role: 'EDITOR',
- name: 'Editor Token for user',
- createdAt: 1707997537,
- expiresAt: 1708170337,
- updatedAt: 1707997537,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: '',
- },
- {
- id: '10',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '',
- name: '',
- email: '',
- createdAt: 0,
- profilePictureURL: '',
- notFound: true,
- },
- token: 'Hg/QpMU9VQyqIuzSh9ND2454IN5uOHzVkv7owEtBcPo=',
- role: 'EDITOR',
- name: 'test123',
- createdAt: 1707997288,
- expiresAt: 1708083688,
- updatedAt: 1707997288,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: '',
- },
- {
- id: '9',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '',
- name: '',
- email: '',
- createdAt: 0,
- profilePictureURL: '',
- notFound: true,
- },
- token: 'M5gMsccDthPTibquB7kR7ZSEI76y4endOxZPESZ9/po=',
- role: 'VIEWER',
- name: 'Viewer Token for user',
- createdAt: 1707996747,
- expiresAt: 1708255947,
- updatedAt: 1707996747,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: '',
- },
- {
- id: '8',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '',
- name: '',
- email: '',
- createdAt: 0,
- profilePictureURL: '',
- notFound: true,
- },
- token: 'H8NVlOD09IcMgQ/rzfVucb+4+jEcqZ4ZRx6n7QztMSc=',
- role: 'EDITOR',
- name: 'Editor Token for user',
- createdAt: 1707996736,
- expiresAt: 1708169536,
- updatedAt: 1707996736,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: '',
- },
- {
- id: '7',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '',
- name: '',
- email: '',
- createdAt: 0,
- profilePictureURL: '',
- notFound: true,
- },
- token: 'z24SswLmNlPVUgb1j6rfc2u4Kb4xSUolwb11cI8kbrs=',
- role: 'ADMIN',
- name: 'Admin Token for user',
- createdAt: 1707996719,
- expiresAt: 0,
- updatedAt: 1707996719,
- lastUsed: 0,
- revoked: false,
- updatedByUserId: '',
- },
- {
- id: '5',
- userId: 'mandalorian',
- createdByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- updatedByUser: {
- id: '001',
- name: 'Mando',
- email: createdByEmail,
- createdAt: 1707974098,
- profilePictureURL: '',
- notFound: false,
- },
- token: 'SWuNSF08EB6+VN05312QaAsPum2wkqIm+ujiWZKnm2Q=',
- role: 'EDITOR',
- name: 'Editor Token',
- createdAt: 1707992270,
- expiresAt: 1708165070,
- updatedAt: 1707995424,
- lastUsed: 1707992517,
- revoked: false,
- updatedByUserId: 'mandalorian',
- },
- ],
-};
-
-export const createAPIKeyResponse = {
- status: 'success',
- data: {
- id: '57',
- userId: 'mandalorian',
- token: 'pQ5kiHjcbQ2FbKlS14LQjA2RzXEBi/KvBfM7BRSwltI=',
- name: 'test1233',
- createdAt: 1707818550,
- expiresAt: 0,
- },
-};
diff --git a/frontend/src/pages/Settings/Settings.tsx b/frontend/src/pages/Settings/Settings.tsx
index 0c6d3e96f0..57611f5479 100644
--- a/frontend/src/pages/Settings/Settings.tsx
+++ b/frontend/src/pages/Settings/Settings.tsx
@@ -5,7 +5,6 @@ import logEvent from 'api/common/logEvent';
import RouteTab from 'components/RouteTab';
import { FeatureKeys } from 'constants/features';
import ROUTES from 'constants/routes';
-import { IS_SERVICE_ACCOUNTS_ENABLED } from 'container/ServiceAccountsSettings/config';
import { routeConfig } from 'container/SideNav/config';
import { getQueryString } from 'container/SideNav/helper';
import { settingsNavSections } from 'container/SideNav/menuItems';
@@ -84,12 +83,10 @@ function SettingsPage(): JSX.Element {
item.key === ROUTES.ROLES_SETTINGS ||
item.key === ROUTES.ROLE_DETAILS ||
item.key === ROUTES.INTEGRATIONS ||
- item.key === ROUTES.API_KEYS ||
item.key === ROUTES.INGESTION_SETTINGS ||
item.key === ROUTES.ORG_SETTINGS ||
item.key === ROUTES.MEMBERS_SETTINGS ||
- (IS_SERVICE_ACCOUNTS_ENABLED &&
- item.key === ROUTES.SERVICE_ACCOUNTS_SETTINGS) ||
+ item.key === ROUTES.SERVICE_ACCOUNTS_SETTINGS ||
item.key === ROUTES.SHORTCUTS
? true
: item.isEnabled,
@@ -118,11 +115,9 @@ function SettingsPage(): JSX.Element {
item.key === ROUTES.ROLES_SETTINGS ||
item.key === ROUTES.ROLE_DETAILS ||
item.key === ROUTES.INTEGRATIONS ||
- item.key === ROUTES.API_KEYS ||
item.key === ROUTES.ORG_SETTINGS ||
item.key === ROUTES.MEMBERS_SETTINGS ||
- (IS_SERVICE_ACCOUNTS_ENABLED &&
- item.key === ROUTES.SERVICE_ACCOUNTS_SETTINGS) ||
+ item.key === ROUTES.SERVICE_ACCOUNTS_SETTINGS ||
item.key === ROUTES.INGESTION_SETTINGS
? true
: item.isEnabled,
@@ -146,11 +141,9 @@ function SettingsPage(): JSX.Element {
updatedItems = updatedItems.map((item) => ({
...item,
isEnabled:
- item.key === ROUTES.API_KEYS ||
item.key === ROUTES.ORG_SETTINGS ||
item.key === ROUTES.MEMBERS_SETTINGS ||
- (IS_SERVICE_ACCOUNTS_ENABLED &&
- item.key === ROUTES.SERVICE_ACCOUNTS_SETTINGS)
+ item.key === ROUTES.SERVICE_ACCOUNTS_SETTINGS
? true
: item.isEnabled,
}));
diff --git a/frontend/src/pages/Settings/__tests__/Settings.test.tsx b/frontend/src/pages/Settings/__tests__/Settings.test.tsx
index ad12902031..c9b48224d1 100644
--- a/frontend/src/pages/Settings/__tests__/Settings.test.tsx
+++ b/frontend/src/pages/Settings/__tests__/Settings.test.tsx
@@ -53,7 +53,6 @@ describe('SettingsPage nav sections', () => {
'billing',
'roles',
'members',
- 'api-keys',
'sso',
'integrations',
'ingestion',
@@ -82,12 +81,9 @@ describe('SettingsPage nav sections', () => {
expect(screen.getByTestId(id)).toBeInTheDocument();
});
- it.each(['billing', 'roles', 'api-keys'])(
- 'does not render "%s" element',
- (id) => {
- expect(screen.queryByTestId(id)).not.toBeInTheDocument();
- },
- );
+ it.each(['billing', 'roles'])('does not render "%s" element', (id) => {
+ expect(screen.queryByTestId(id)).not.toBeInTheDocument();
+ });
});
describe('Self-hosted Admin', () => {
@@ -99,7 +95,7 @@ describe('SettingsPage nav sections', () => {
});
});
- it.each(['roles', 'members', 'api-keys', 'integrations', 'sso', 'ingestion'])(
+ it.each(['roles', 'members', 'integrations', 'sso', 'ingestion'])(
'renders "%s" element',
(id) => {
expect(screen.getByTestId(id)).toBeInTheDocument();
diff --git a/frontend/src/pages/Settings/config.tsx b/frontend/src/pages/Settings/config.tsx
index 3754cec44f..db3e1fb1bf 100644
--- a/frontend/src/pages/Settings/config.tsx
+++ b/frontend/src/pages/Settings/config.tsx
@@ -1,7 +1,6 @@
import { RouteTabProps } from 'components/RouteTab/types';
import ROUTES from 'constants/routes';
import AlertChannels from 'container/AllAlertChannels';
-import APIKeys from 'container/APIKeys/APIKeys';
import BillingContainer from 'container/BillingContainer/BillingContainer';
import CreateAlertChannels from 'container/CreateAlertChannels';
import { ChannelType } from 'container/CreateAlertChannels/config';
@@ -22,7 +21,6 @@ import {
Cpu,
CreditCard,
Keyboard,
- KeySquare,
Pencil,
Plus,
Shield,
@@ -114,19 +112,6 @@ export const generalSettingsCloud = (t: TFunction): RouteTabProps['routes'] => [
},
];
-export const apiKeys = (t: TFunction): RouteTabProps['routes'] => [
- {
- Component: APIKeys,
- name: (
- <div className="periscope-tab">
- <KeySquare size={16} /> {t('routes:api_keys').toString()}
- </div>
- ),
- route: ROUTES.API_KEYS,
- key: ROUTES.API_KEYS,
- },
-];
-
export const billingSettings = (t: TFunction): RouteTabProps['routes'] => [
{
Component: BillingContainer,
diff --git a/frontend/src/pages/Settings/utils.ts b/frontend/src/pages/Settings/utils.ts
index 82d2499c19..9521f95cc7 100644
--- a/frontend/src/pages/Settings/utils.ts
+++ b/frontend/src/pages/Settings/utils.ts
@@ -1,11 +1,9 @@
import { RouteTabProps } from 'components/RouteTab/types';
-import { IS_SERVICE_ACCOUNTS_ENABLED } from 'container/ServiceAccountsSettings/config';
import { TFunction } from 'i18next';
import { ROLES, USER_ROLES } from 'types/roles';
import {
alertChannels,
- apiKeys,
billingSettings,
createAlertChannels,
editAlertChannels,
@@ -64,11 +62,7 @@ export const getRoutes = (
settings.push(...alertChannels(t));
if (isAdmin) {
- settings.push(...apiKeys(t), ...membersSettings(t));
-
- if (IS_SERVICE_ACCOUNTS_ENABLED) {
- settings.push(...serviceAccountsSettings(t));
- }
+ settings.push(...membersSettings(t), ...serviceAccountsSettings(t));
}
// todo: Sagar - check the condition for role list and details page, to whom we want to serve
diff --git a/frontend/src/tests/test-utils.tsx b/frontend/src/tests/test-utils.tsx
index 9f03368629..c27b66b1d1 100644
--- a/frontend/src/tests/test-utils.tsx
+++ b/frontend/src/tests/test-utils.tsx
@@ -47,6 +47,9 @@ const queryClient = new QueryClient({
refetchOnWindowFocus: false,
retry: false,
},
+ mutations: {
+ retry: false,
+ },
},
});
diff --git a/frontend/src/types/api/pat/types.ts b/frontend/src/types/api/pat/types.ts
deleted file mode 100644
index 768ea44b43..0000000000
--- a/frontend/src/types/api/pat/types.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-export interface User {
- createdAt?: number;
- email?: string;
- id: string;
- displayName?: string;
-}
-
-export interface APIKeyProps {
- name: string;
- expiresAt: number;
- role: string;
- token: string;
- id: string;
- createdAt: string;
- createdByUser?: User;
- updatedAt?: string;
- updatedByUser?: User;
- lastUsed?: number;
-}
-
-export interface CreatePayloadProps {
- data: APIKeyProps;
- status: string;
-}
-
-export interface CreateAPIKeyProps {
- name: string;
- expiresInDays: number;
- role: string;
-}
-
-export interface AllAPIKeyProps {
- status: string;
- data: APIKeyProps[];
-}
-
-export interface CreateAPIKeyProp {
- data: APIKeyProps;
-}
-
-export interface DeleteAPIKeyPayloadProps {
- status: string;
-}
-
-export interface UpdateAPIKeyProps {
- id: string;
- data: {
- name: string;
- role: string;
- };
-}
-
-export type PayloadProps = {
- status: string;
- data: string;
-};
diff --git a/frontend/src/utils/permission/index.ts b/frontend/src/utils/permission/index.ts
index 9c7ae2b96d..08a6bcc040 100644
--- a/frontend/src/utils/permission/index.ts
+++ b/frontend/src/utils/permission/index.ts
@@ -108,7 +108,6 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
TRACES_SAVE_VIEWS: ['ADMIN', 'EDITOR', 'VIEWER'],
TRACES_FUNNELS: ['ADMIN', 'EDITOR', 'VIEWER'],
TRACES_FUNNELS_DETAIL: ['ADMIN', 'EDITOR', 'VIEWER'],
- API_KEYS: ['ADMIN'],
LOGS_BASE: ['ADMIN', 'EDITOR', 'VIEWER'],
OLD_LOGS_EXPLORER: ['ADMIN', 'EDITOR', 'VIEWER'],
SHORTCUTS: ['ADMIN', 'EDITOR', 'VIEWER'],
diff --git a/pkg/apiserver/signozapiserver/serviceaccount.go b/pkg/apiserver/signozapiserver/serviceaccount.go
index f1afe99611..085fdbbf53 100644
--- a/pkg/apiserver/signozapiserver/serviceaccount.go
+++ b/pkg/apiserver/signozapiserver/serviceaccount.go
@@ -5,6 +5,7 @@ import (
"github.com/SigNoz/signoz/pkg/http/handler"
"github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/serviceaccounttypes"
"github.com/gorilla/mux"
)
@@ -44,6 +45,23 @@ func (provider *provider) addServiceAccountRoutes(router *mux.Router) error {
return err
}
+ if err := router.Handle("/api/v1/service_accounts/me", handler.New(provider.authZ.OpenAccess(provider.serviceAccountHandler.GetMe), handler.OpenAPIDef{
+ ID: "GetMyServiceAccount",
+ Tags: []string{"serviceaccount"},
+ Summary: "Gets my service account",
+ Description: "This endpoint gets my service account",
+ Request: nil,
+ RequestContentType: "",
+ Response: new(serviceaccounttypes.ServiceAccountWithRoles),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusNotFound},
+ Deprecated: false,
+ SecuritySchemes: nil,
+ })).Methods(http.MethodGet).GetError(); err != nil {
+ return err
+ }
+
if err := router.Handle("/api/v1/service_accounts/{id}", handler.New(provider.authZ.AdminAccess(provider.serviceAccountHandler.Get), handler.OpenAPIDef{
ID: "GetServiceAccount",
Tags: []string{"serviceaccount"},
@@ -51,7 +69,7 @@ func (provider *provider) addServiceAccountRoutes(router *mux.Router) error {
Description: "This endpoint gets an existing service account",
Request: nil,
RequestContentType: "",
- Response: new(serviceaccounttypes.ServiceAccount),
+ Response: new(serviceaccounttypes.ServiceAccountWithRoles),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{http.StatusNotFound},
@@ -61,29 +79,80 @@ func (provider *provider) addServiceAccountRoutes(router *mux.Router) error {
return err
}
- if err := router.Handle("/api/v1/service_accounts/{id}", handler.New(provider.authZ.AdminAccess(provider.serviceAccountHandler.Update), handler.OpenAPIDef{
- ID: "UpdateServiceAccount",
+ if err := router.Handle("/api/v1/service_accounts/{id}/roles", handler.New(provider.authZ.AdminAccess(provider.serviceAccountHandler.GetRoles), handler.OpenAPIDef{
+ ID: "GetServiceAccountRoles",
Tags: []string{"serviceaccount"},
- Summary: "Updates a service account",
- Description: "This endpoint updates an existing service account",
- Request: new(serviceaccounttypes.UpdatableServiceAccount),
+ Summary: "Gets service account roles",
+ Description: "This endpoint gets all the roles for the existing service account",
+ Request: nil,
+ RequestContentType: "",
+ Response: new([]*authtypes.Role),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusNotFound},
+ Deprecated: false,
+ SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
+ })).Methods(http.MethodGet).GetError(); err != nil {
+ return err
+ }
+
+ if err := router.Handle("/api/v1/service_accounts/{id}/roles", handler.New(provider.authZ.AdminAccess(provider.serviceAccountHandler.SetRole), handler.OpenAPIDef{
+ ID: "CreateServiceAccountRole",
+ Tags: []string{"serviceaccount"},
+ Summary: "Create service account role",
+ Description: "This endpoint assigns a role to a service account",
+ Request: new(serviceaccounttypes.PostableServiceAccountRole),
+ RequestContentType: "",
+ Response: new(types.Identifiable),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusCreated,
+ ErrorStatusCodes: []int{http.StatusBadRequest},
+ Deprecated: false,
+ SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
+ })).Methods(http.MethodPost).GetError(); err != nil {
+ return err
+ }
+
+ if err := router.Handle("/api/v1/service_accounts/{id}/roles/{rid}", handler.New(provider.authZ.AdminAccess(provider.serviceAccountHandler.DeleteRole), handler.OpenAPIDef{
+ ID: "DeleteServiceAccountRole",
+ Tags: []string{"serviceaccount"},
+ Summary: "Delete service account role",
+ Description: "This endpoint revokes a role from service account",
+ Request: nil,
RequestContentType: "",
Response: nil,
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusNoContent,
- ErrorStatusCodes: []int{http.StatusNotFound, http.StatusBadRequest},
+ ErrorStatusCodes: []int{},
Deprecated: false,
SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
+ })).Methods(http.MethodDelete).GetError(); err != nil {
+ return err
+ }
+
+ if err := router.Handle("/api/v1/service_accounts/me", handler.New(provider.authZ.OpenAccess(provider.serviceAccountHandler.UpdateMe), handler.OpenAPIDef{
+ ID: "UpdateMyServiceAccount",
+ Tags: []string{"serviceaccount"},
+ Summary: "Updates my service account",
+ Description: "This endpoint gets my service account",
+ Request: new(serviceaccounttypes.UpdatableServiceAccount),
+ RequestContentType: "",
+ Response: nil,
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusNoContent,
+ ErrorStatusCodes: []int{http.StatusNotFound},
+ Deprecated: false,
+ SecuritySchemes: nil,
})).Methods(http.MethodPut).GetError(); err != nil {
return err
}
- if err := router.Handle("/api/v1/service_accounts/{id}/status", handler.New(provider.authZ.AdminAccess(provider.serviceAccountHandler.UpdateStatus), handler.OpenAPIDef{
- ID: "UpdateServiceAccountStatus",
+ if err := router.Handle("/api/v1/service_accounts/{id}", handler.New(provider.authZ.AdminAccess(provider.serviceAccountHandler.Update), handler.OpenAPIDef{
+ ID: "UpdateServiceAccount",
Tags: []string{"serviceaccount"},
- Summary: "Updates a service account status",
- Description: "This endpoint updates an existing service account status",
- Request: new(serviceaccounttypes.UpdatableServiceAccountStatus),
+ Summary: "Updates a service account",
+ Description: "This endpoint updates an existing service account",
+ Request: new(serviceaccounttypes.UpdatableServiceAccount),
RequestContentType: "",
Response: nil,
ResponseContentType: "application/json",
@@ -136,7 +205,7 @@ func (provider *provider) addServiceAccountRoutes(router *mux.Router) error {
Description: "This endpoint lists the service account keys",
Request: nil,
RequestContentType: "",
- Response: make([]*serviceaccounttypes.FactorAPIKey, 0),
+ Response: make([]*serviceaccounttypes.GettableFactorAPIKey, 0),
ResponseContentType: "application/json",
SuccessStatusCode: http.StatusOK,
ErrorStatusCodes: []int{},
diff --git a/pkg/apiserver/signozapiserver/user.go b/pkg/apiserver/signozapiserver/user.go
index 09f0269ca3..5127a7a9d1 100644
--- a/pkg/apiserver/signozapiserver/user.go
+++ b/pkg/apiserver/signozapiserver/user.go
@@ -43,74 +43,6 @@ func (provider *provider) addUserRoutes(router *mux.Router) error {
return err
}
- if err := router.Handle("/api/v1/pats", handler.New(provider.authZ.AdminAccess(provider.userHandler.CreateAPIKey), handler.OpenAPIDef{
- ID: "CreateAPIKey",
- Tags: []string{"users"},
- Summary: "Create api key",
- Description: "This endpoint creates an api key",
- Request: new(types.PostableAPIKey),
- RequestContentType: "application/json",
- Response: new(types.GettableAPIKey),
- ResponseContentType: "application/json",
- SuccessStatusCode: http.StatusCreated,
- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusConflict},
- Deprecated: false,
- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
- })).Methods(http.MethodPost).GetError(); err != nil {
- return err
- }
-
- if err := router.Handle("/api/v1/pats", handler.New(provider.authZ.AdminAccess(provider.userHandler.ListAPIKeys), handler.OpenAPIDef{
- ID: "ListAPIKeys",
- Tags: []string{"users"},
- Summary: "List api keys",
- Description: "This endpoint lists all api keys",
- Request: nil,
- RequestContentType: "",
- Response: make([]*types.GettableAPIKey, 0),
- ResponseContentType: "application/json",
- SuccessStatusCode: http.StatusOK,
- ErrorStatusCodes: []int{},
- Deprecated: false,
- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
- })).Methods(http.MethodGet).GetError(); err != nil {
- return err
- }
-
- if err := router.Handle("/api/v1/pats/{id}", handler.New(provider.authZ.AdminAccess(provider.userHandler.UpdateAPIKey), handler.OpenAPIDef{
- ID: "UpdateAPIKey",
- Tags: []string{"users"},
- Summary: "Update api key",
- Description: "This endpoint updates an api key",
- Request: new(types.StorableAPIKey),
- RequestContentType: "application/json",
- Response: nil,
- ResponseContentType: "application/json",
- SuccessStatusCode: http.StatusNoContent,
- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
- Deprecated: false,
- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
- })).Methods(http.MethodPut).GetError(); err != nil {
- return err
- }
-
- if err := router.Handle("/api/v1/pats/{id}", handler.New(provider.authZ.AdminAccess(provider.userHandler.RevokeAPIKey), handler.OpenAPIDef{
- ID: "RevokeAPIKey",
- Tags: []string{"users"},
- Summary: "Revoke api key",
- Description: "This endpoint revokes an api key",
- Request: nil,
- RequestContentType: "",
- Response: nil,
- ResponseContentType: "",
- SuccessStatusCode: http.StatusNoContent,
- ErrorStatusCodes: []int{http.StatusNotFound},
- Deprecated: false,
- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
- })).Methods(http.MethodDelete).GetError(); err != nil {
- return err
- }
-
if err := router.Handle("/api/v1/user", handler.New(provider.authZ.AdminAccess(provider.userHandler.ListUsersDeprecated), handler.OpenAPIDef{
ID: "ListUsersDeprecated",
Tags: []string{"users"},
diff --git a/pkg/authn/passwordauthn/emailpasswordauthn/authn.go b/pkg/authn/passwordauthn/emailpasswordauthn/authn.go
index b05fb49bee..9b5c137e4c 100644
--- a/pkg/authn/passwordauthn/emailpasswordauthn/authn.go
+++ b/pkg/authn/passwordauthn/emailpasswordauthn/authn.go
@@ -21,7 +21,7 @@ func New(store authtypes.AuthNStore) *AuthN {
}
func (a *AuthN) Authenticate(ctx context.Context, email string, password string, orgID valuer.UUID) (*authtypes.Identity, error) {
- user, factorPassword, userRoles, err := a.store.GetActiveUserAndFactorPasswordByEmailAndOrgID(ctx, email, orgID)
+ user, factorPassword, _, err := a.store.GetActiveUserAndFactorPasswordByEmailAndOrgID(ctx, email, orgID)
if err != nil {
return nil, err
}
@@ -30,11 +30,5 @@ func (a *AuthN) Authenticate(ctx context.Context, email string, password string,
return nil, errors.New(errors.TypeUnauthenticated, types.ErrCodeIncorrectPassword, "invalid email or password")
}
- if len(userRoles) == 0 {
- return nil, errors.New(errors.TypeUnexpected, authtypes.ErrCodeUserRolesNotFound, "no user roles entries found")
- }
-
- role := authtypes.SigNozManagedRoleToExistingLegacyRole[userRoles[0].Role.Name]
-
- return authtypes.NewIdentity(user.ID, orgID, user.Email, role, authtypes.IdentNProviderTokenizer), nil
+ return authtypes.NewPrincipalUserIdentity(user.ID, orgID, user.Email, authtypes.IdentNProviderTokenizer), nil
}
diff --git a/pkg/authz/authzstore/sqlauthzstore/store.go b/pkg/authz/authzstore/sqlauthzstore/store.go
index 7cf6206fe9..4412de8317 100644
--- a/pkg/authz/authzstore/sqlauthzstore/store.go
+++ b/pkg/authz/authzstore/sqlauthzstore/store.go
@@ -97,11 +97,7 @@ func (store *store) ListByOrgIDAndNames(ctx context.Context, orgID valuer.UUID,
}
if len(roles) != len(names) {
- return nil, store.sqlstore.WrapNotFoundErrf(
- nil,
- authtypes.ErrCodeRoleNotFound,
- "not all roles found for the provided names: %v", names,
- )
+ return nil, errors.Newf(errors.TypeInvalidInput, authtypes.ErrCodeRoleNotFound, "not all roles found for the provided names: %v", names)
}
return roles, nil
@@ -122,11 +118,7 @@ func (store *store) ListByOrgIDAndIDs(ctx context.Context, orgID valuer.UUID, id
}
if len(roles) != len(ids) {
- return nil, store.sqlstore.WrapNotFoundErrf(
- nil,
- authtypes.ErrCodeRoleNotFound,
- "not all roles found for the provided ids: %v", ids,
- )
+ return nil, errors.Newf(errors.TypeInvalidInput, authtypes.ErrCodeRoleNotFound, "not all roles found for the provided names: %v", ids)
}
return roles, nil
diff --git a/pkg/authz/openfgaauthz/provider.go b/pkg/authz/openfgaauthz/provider.go
index eb2306d7ee..9f70e94235 100644
--- a/pkg/authz/openfgaauthz/provider.go
+++ b/pkg/authz/openfgaauthz/provider.go
@@ -148,7 +148,12 @@ func (provider *provider) Grant(ctx context.Context, orgID valuer.UUID, names []
return err
}
- return provider.Write(ctx, tuples, nil)
+ err = provider.Write(ctx, tuples, nil)
+ if err != nil {
+ return errors.WrapInternalf(err, errors.CodeInternal, "failed to grant roles: %v to subject: %s", names, subject)
+ }
+
+ return nil
}
func (provider *provider) ModifyGrant(ctx context.Context, orgID valuer.UUID, existingRoleNames []string, updatedRoleNames []string, subject string) error {
@@ -180,7 +185,13 @@ func (provider *provider) Revoke(ctx context.Context, orgID valuer.UUID, names [
if err != nil {
return err
}
- return provider.Write(ctx, nil, tuples)
+
+ err = provider.Write(ctx, nil, tuples)
+ if err != nil {
+ return errors.WrapInternalf(err, errors.CodeInternal, "failed to revoke roles: %v to subject: %s", names, subject)
+ }
+
+ return nil
}
func (provider *provider) CreateManagedRoles(ctx context.Context, _ valuer.UUID, managedRoles []*authtypes.Role) error {
diff --git a/pkg/authz/openfgaserver/server.go b/pkg/authz/openfgaserver/server.go
index 538734b44c..fabc803a2a 100644
--- a/pkg/authz/openfgaserver/server.go
+++ b/pkg/authz/openfgaserver/server.go
@@ -140,9 +140,22 @@ func (server *Server) BatchCheck(ctx context.Context, tupleReq map[string]*openf
}
func (server *Server) CheckWithTupleCreation(ctx context.Context, claims authtypes.Claims, orgID valuer.UUID, _ authtypes.Relation, _ authtypes.Typeable, _ []authtypes.Selector, roleSelectors []authtypes.Selector) error {
- subject, err := authtypes.NewSubject(authtypes.TypeableUser, claims.UserID, orgID, nil)
- if err != nil {
- return err
+ subject := ""
+ switch claims.Principal {
+ case authtypes.PrincipalUser:
+ user, err := authtypes.NewSubject(authtypes.TypeableUser, claims.UserID, orgID, nil)
+ if err != nil {
+ return err
+ }
+
+ subject = user
+ case authtypes.PrincipalServiceAccount:
+ serviceAccount, err := authtypes.NewSubject(authtypes.TypeableServiceAccount, claims.ServiceAccountID, orgID, nil)
+ if err != nil {
+ return err
+ }
+
+ subject = serviceAccount
}
tupleSlice, err := authtypes.TypeableRole.Tuples(subject, authtypes.RelationAssignee, roleSelectors, orgID)
diff --git a/pkg/http/middleware/authz.go b/pkg/http/middleware/authz.go
index 9ec9bfaf8d..9b9a4a4dd9 100644
--- a/pkg/http/middleware/authz.go
+++ b/pkg/http/middleware/authz.go
@@ -40,17 +40,6 @@ func (middleware *AuthZ) ViewAccess(next http.HandlerFunc) http.HandlerFunc {
return
}
- if claims.IdentNProvider == authtypes.IdentNProviderAPIKey.StringValue() {
- if err := claims.IsViewer(); err != nil {
- middleware.logger.WarnContext(ctx, authzDeniedMessage, slog.Any("claims", claims))
- render.Error(rw, err)
- return
- }
-
- next(rw, req)
- return
- }
-
selectors := []authtypes.Selector{
authtypes.MustNewSelector(authtypes.TypeRole, authtypes.SigNozAdminRoleName),
authtypes.MustNewSelector(authtypes.TypeRole, authtypes.SigNozEditorRoleName),
@@ -90,17 +79,6 @@ func (middleware *AuthZ) EditAccess(next http.HandlerFunc) http.HandlerFunc {
return
}
- if claims.IdentNProvider == authtypes.IdentNProviderAPIKey.StringValue() {
- if err := claims.IsEditor(); err != nil {
- middleware.logger.WarnContext(ctx, authzDeniedMessage, slog.Any("claims", claims))
- render.Error(rw, err)
- return
- }
-
- next(rw, req)
- return
- }
-
selectors := []authtypes.Selector{
authtypes.MustNewSelector(authtypes.TypeRole, authtypes.SigNozAdminRoleName),
authtypes.MustNewSelector(authtypes.TypeRole, authtypes.SigNozEditorRoleName),
@@ -139,17 +117,6 @@ func (middleware *AuthZ) AdminAccess(next http.HandlerFunc) http.HandlerFunc {
return
}
- if claims.IdentNProvider == authtypes.IdentNProviderAPIKey.StringValue() {
- if err := claims.IsAdmin(); err != nil {
- middleware.logger.WarnContext(ctx, authzDeniedMessage, slog.Any("claims", claims))
- render.Error(rw, err)
- return
- }
-
- next(rw, req)
- return
- }
-
selectors := []authtypes.Selector{
authtypes.MustNewSelector(authtypes.TypeRole, authtypes.SigNozAdminRoleName),
}
@@ -186,13 +153,28 @@ func (middleware *AuthZ) SelfAccess(next http.HandlerFunc) http.HandlerFunc {
return
}
- id := mux.Vars(req)["id"]
- if err := claims.IsSelfAccess(id); err != nil {
- middleware.logger.WarnContext(req.Context(), authzDeniedMessage, slog.Any("claims", claims))
- render.Error(rw, err)
- return
+ selectors := []authtypes.Selector{
+ authtypes.MustNewSelector(authtypes.TypeRole, authtypes.SigNozAdminRoleName),
}
+ err = middleware.authzService.CheckWithTupleCreation(
+ req.Context(),
+ claims,
+ valuer.MustNewUUID(claims.OrgID),
+ authtypes.RelationAssignee,
+ authtypes.TypeableRole,
+ selectors,
+ selectors,
+ )
+
+ if err != nil {
+ id := mux.Vars(req)["id"]
+ if err := claims.IsSelfAccess(id); err != nil {
+ middleware.logger.WarnContext(req.Context(), authzDeniedMessage, slog.Any("claims", claims))
+ render.Error(rw, err)
+ return
+ }
+ }
next(rw, req)
})
}
diff --git a/pkg/http/middleware/identn.go b/pkg/http/middleware/identn.go
index 2f4474d487..5c146691f3 100644
--- a/pkg/http/middleware/identn.go
+++ b/pkg/http/middleware/identn.go
@@ -61,8 +61,10 @@ func (m *IdentN) Wrap(next http.Handler) http.Handler {
ctx = authtypes.NewContextWithClaims(ctx, claims)
comment := ctxtypes.CommentFromContext(ctx)
- comment.Set("identn_provider", claims.IdentNProvider)
+ comment.Set("identn_provider", claims.IdentNProvider.StringValue())
comment.Set("user_id", claims.UserID)
+ comment.Set("service_account_id", claims.ServiceAccountID)
+ comment.Set("principal", claims.Principal.StringValue())
comment.Set("org_id", claims.OrgID)
ctx = ctxtypes.NewContextWithComment(ctx, comment)
diff --git a/pkg/identn/apikeyidentn/provider.go b/pkg/identn/apikeyidentn/provider.go
index ba584a6d2a..fae98e65a6 100644
--- a/pkg/identn/apikeyidentn/provider.go
+++ b/pkg/identn/apikeyidentn/provider.go
@@ -10,33 +10,29 @@ import (
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/identn"
- "github.com/SigNoz/signoz/pkg/sqlstore"
- "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/modules/serviceaccount"
"github.com/SigNoz/signoz/pkg/types/authtypes"
)
-// todo: will move this in types layer with service account integration
-type apiKeyTokenKey struct{}
-
type provider struct {
- store sqlstore.SQLStore
- config identn.Config
- settings factory.ScopedProviderSettings
- sfGroup *singleflight.Group
+ serviceAccount serviceaccount.Module
+ config identn.Config
+ settings factory.ScopedProviderSettings
+ sfGroup *singleflight.Group
}
-func NewFactory(store sqlstore.SQLStore) factory.ProviderFactory[identn.IdentN, identn.Config] {
+func NewFactory(serviceAccount serviceaccount.Module) factory.ProviderFactory[identn.IdentN, identn.Config] {
return factory.NewProviderFactory(factory.MustNewName(authtypes.IdentNProviderAPIKey.StringValue()), func(ctx context.Context, providerSettings factory.ProviderSettings, config identn.Config) (identn.IdentN, error) {
- return New(providerSettings, store, config)
+ return New(serviceAccount, config, providerSettings)
})
}
-func New(providerSettings factory.ProviderSettings, store sqlstore.SQLStore, config identn.Config) (identn.IdentN, error) {
+func New(serviceAccount serviceaccount.Module, config identn.Config, providerSettings factory.ProviderSettings) (identn.IdentN, error) {
return &provider{
- store: store,
- config: config,
- settings: factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/pkg/identn/apikeyidentn"),
- sfGroup: &singleflight.Group{},
+ serviceAccount: serviceAccount,
+ config: config,
+ settings: factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/pkg/identn/apikeyidentn"),
+ sfGroup: &singleflight.Group{},
}, nil
}
@@ -54,75 +50,44 @@ func (provider *provider) Test(req *http.Request) bool {
}
func (provider *provider) Pre(req *http.Request) *http.Request {
- token := provider.extractToken(req)
- if token == "" {
+ apiKey := provider.extractToken(req)
+ if apiKey == "" {
return req
}
- ctx := context.WithValue(req.Context(), apiKeyTokenKey{}, token)
+ ctx := authtypes.NewContextWithAPIKey(req.Context(), apiKey)
return req.WithContext(ctx)
}
func (provider *provider) GetIdentity(req *http.Request) (*authtypes.Identity, error) {
ctx := req.Context()
- apiKeyToken, ok := ctx.Value(apiKeyTokenKey{}).(string)
- if !ok || apiKeyToken == "" {
- return nil, errors.New(errors.TypeUnauthenticated, errors.CodeUnauthenticated, "missing api key")
- }
-
- var apiKey types.StorableAPIKey
- err := provider.
- store.
- BunDB().
- NewSelect().
- Model(&apiKey).
- Where("token = ?", apiKeyToken).
- Scan(ctx)
+ apiKey, err := authtypes.APIKeyFromContext(ctx)
if err != nil {
return nil, err
}
- if apiKey.ExpiresAt.Before(time.Now()) && !apiKey.ExpiresAt.Equal(types.NEVER_EXPIRES) {
- return nil, errors.New(errors.TypeUnauthenticated, errors.CodeUnauthenticated, "api key has expired")
- }
-
- var user types.User
- err = provider.
- store.
- BunDB().
- NewSelect().
- Model(&user).
- Where("id = ?", apiKey.UserID).
- Scan(ctx)
+ identity, err := provider.serviceAccount.GetIdentity(ctx, apiKey)
if err != nil {
return nil, err
}
- identity := authtypes.NewIdentity(user.ID, user.OrgID, user.Email, apiKey.Role, provider.Name())
return identity, nil
}
func (provider *provider) Post(ctx context.Context, _ *http.Request, _ authtypes.Claims) {
- apiKeyToken, ok := ctx.Value(apiKeyTokenKey{}).(string)
- if !ok || apiKeyToken == "" {
+ apiKey, err := authtypes.APIKeyFromContext(ctx)
+ if err != nil {
return
}
- _, _, _ = provider.sfGroup.Do(apiKeyToken, func() (any, error) {
- _, err := provider.
- store.
- BunDB().
- NewUpdate().
- Model(new(types.StorableAPIKey)).
- Set("last_used = ?", time.Now()).
- Where("token = ?", apiKeyToken).
- Where("revoked = false").
- Exec(ctx)
- if err != nil {
- provider.settings.Logger().ErrorContext(ctx, "failed to update last used of api key", errors.Attr(err))
+ _, _, _ = provider.sfGroup.Do(apiKey, func() (any, error) {
+ if err := provider.serviceAccount.SetLastObservedAt(ctx, apiKey, time.Now()); err != nil {
+ provider.settings.Logger().ErrorContext(ctx, "failed to set last observed at", errors.Attr(err))
+ return false, err
}
return true, nil
})
+
}
func (provider *provider) extractToken(req *http.Request) string {
diff --git a/pkg/identn/impersonationidentn/provider.go b/pkg/identn/impersonationidentn/provider.go
index b8f50cb627..94a8669426 100644
--- a/pkg/identn/impersonationidentn/provider.go
+++ b/pkg/identn/impersonationidentn/provider.go
@@ -79,22 +79,15 @@ func (provider *provider) GetIdentity(req *http.Request) (*authtypes.Identity, e
return nil, err
}
- rootUser, userRoles, err := provider.userGetter.GetRootUserByOrgID(ctx, org.ID)
+ rootUser, _, err := provider.userGetter.GetRootUserByOrgID(ctx, org.ID)
if err != nil {
return nil, err
}
- if len(userRoles) == 0 {
- return nil, errors.New(errors.TypeUnexpected, authtypes.ErrCodeUserRolesNotFound, "no user roles entries found")
- }
-
- role := authtypes.SigNozManagedRoleToExistingLegacyRole[userRoles[0].Role.Name]
-
- provider.identity = authtypes.NewIdentity(
+ provider.identity = authtypes.NewPrincipalUserIdentity(
rootUser.ID,
rootUser.OrgID,
rootUser.Email,
- role,
authtypes.IdentNProviderImpersonation,
)
diff --git a/pkg/modules/dashboard/dashboard.go b/pkg/modules/dashboard/dashboard.go
index 78ef10d970..0261fa769b 100644
--- a/pkg/modules/dashboard/dashboard.go
+++ b/pkg/modules/dashboard/dashboard.go
@@ -43,7 +43,7 @@ type Module interface {
Update(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, data dashboardtypes.UpdatableDashboard, diff int) (*dashboardtypes.Dashboard, error)
- LockUnlock(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, role types.Role, lock bool) error
+ LockUnlock(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, isAdmin bool, lock bool) error
Delete(ctx context.Context, orgID valuer.UUID, id valuer.UUID) error
diff --git a/pkg/modules/dashboard/impldashboard/handler.go b/pkg/modules/dashboard/impldashboard/handler.go
index cf313236ae..6cac1785a7 100644
--- a/pkg/modules/dashboard/impldashboard/handler.go
+++ b/pkg/modules/dashboard/impldashboard/handler.go
@@ -7,6 +7,7 @@ import (
"strconv"
"time"
+ "github.com/SigNoz/signoz/pkg/authz"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/http/binding"
@@ -22,11 +23,12 @@ import (
type handler struct {
module dashboard.Module
+ authz authz.AuthZ
providerSettings factory.ProviderSettings
}
-func NewHandler(module dashboard.Module, providerSettings factory.ProviderSettings) dashboard.Handler {
- return &handler{module: module, providerSettings: providerSettings}
+func NewHandler(module dashboard.Module, providerSettings factory.ProviderSettings, authz authz.AuthZ) dashboard.Handler {
+ return &handler{module: module, providerSettings: providerSettings, authz: authz}
}
func (handler *handler) Create(rw http.ResponseWriter, r *http.Request) {
@@ -57,7 +59,7 @@ func (handler *handler) Create(rw http.ResponseWriter, r *http.Request) {
dashboardMigrator.Migrate(ctx, req)
}
- dashboard, err := handler.module.Create(ctx, orgID, claims.Email, valuer.MustNewUUID(claims.UserID), req)
+ dashboard, err := handler.module.Create(ctx, orgID, claims.Email, valuer.MustNewUUID(claims.IdentityID()), req)
if err != nil {
render.Error(rw, err)
return
@@ -108,7 +110,7 @@ func (handler *handler) Update(rw http.ResponseWriter, r *http.Request) {
diff := 0
// Allow multiple deletions for API key requests; enforce for others
- if claims.IdentNProvider == authtypes.IdentNProviderTokenizer.StringValue() {
+ if claims.IdentNProvider == authtypes.IdentNProviderTokenizer {
diff = 1
}
@@ -155,7 +157,24 @@ func (handler *handler) LockUnlock(rw http.ResponseWriter, r *http.Request) {
return
}
- err = handler.module.LockUnlock(ctx, orgID, dashboardID, claims.Email, claims.Role, *req.Locked)
+ isAdmin := false
+ selectors := []authtypes.Selector{
+ authtypes.MustNewSelector(authtypes.TypeRole, authtypes.SigNozAdminRoleName),
+ }
+ err = handler.authz.CheckWithTupleCreation(
+ ctx,
+ claims,
+ valuer.MustNewUUID(claims.OrgID),
+ authtypes.RelationAssignee,
+ authtypes.TypeableRole,
+ selectors,
+ selectors,
+ )
+ if err == nil {
+ isAdmin = true
+ }
+
+ err = handler.module.LockUnlock(ctx, orgID, dashboardID, claims.Email, isAdmin, *req.Locked)
if err != nil {
render.Error(rw, err)
return
diff --git a/pkg/modules/dashboard/impldashboard/module.go b/pkg/modules/dashboard/impldashboard/module.go
index 22f2ddc129..1732102a10 100644
--- a/pkg/modules/dashboard/impldashboard/module.go
+++ b/pkg/modules/dashboard/impldashboard/module.go
@@ -99,13 +99,13 @@ func (module *module) Update(ctx context.Context, orgID valuer.UUID, id valuer.U
return dashboard, nil
}
-func (module *module) LockUnlock(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, role types.Role, lock bool) error {
+func (module *module) LockUnlock(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updatedBy string, isAdmin bool, lock bool) error {
dashboard, err := module.Get(ctx, orgID, id)
if err != nil {
return err
}
- err = dashboard.LockUnlock(lock, role, updatedBy)
+ err = dashboard.LockUnlock(lock, isAdmin, updatedBy)
if err != nil {
return err
}
diff --git a/pkg/modules/serviceaccount/config.go b/pkg/modules/serviceaccount/config.go
new file mode 100644
index 0000000000..5630fcc786
--- /dev/null
+++ b/pkg/modules/serviceaccount/config.go
@@ -0,0 +1,46 @@
+package serviceaccount
+
+import (
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/factory"
+ "github.com/SigNoz/signoz/pkg/types/serviceaccounttypes"
+)
+
+type Config struct {
+ // Email config for service accounts
+ Email EmailConfig `mapstructure:"email"`
+
+ // Analytics collection config for service accounts
+ Analytics AnalyticsConfig `mapstructure:"analytics"`
+}
+
+type EmailConfig struct {
+ Domain string `mapstructure:"domain"`
+}
+
+type AnalyticsConfig struct {
+ Enabled bool `mapstructure:"enabled"`
+}
+
+func NewConfigFactory() factory.ConfigFactory {
+ return factory.NewConfigFactory(factory.MustNewName("serviceaccount"), newConfig)
+}
+
+func newConfig() factory.Config {
+ return &Config{
+ Email: EmailConfig{
+ Domain: "signozserviceaccount.com",
+ },
+ Analytics: AnalyticsConfig{
+ Enabled: true,
+ },
+ }
+}
+
+func (c Config) Validate() error {
+ if c.Email.Domain == "" {
+ return errors.New(errors.TypeInvalidInput, serviceaccounttypes.ErrCodeServiceAccountInvalidConfig, "email domain cannot be empty")
+ }
+
+ return nil
+}
diff --git a/pkg/modules/serviceaccount/implserviceaccount/handler.go b/pkg/modules/serviceaccount/implserviceaccount/handler.go
index 38b2db0683..503602b56d 100644
--- a/pkg/modules/serviceaccount/implserviceaccount/handler.go
+++ b/pkg/modules/serviceaccount/implserviceaccount/handler.go
@@ -35,7 +35,7 @@ func (handler *handler) Create(rw http.ResponseWriter, r *http.Request) {
return
}
- serviceAccount := serviceaccounttypes.NewServiceAccount(req.Name, req.Email, req.Roles, serviceaccounttypes.StatusActive, valuer.MustNewUUID(claims.OrgID))
+ serviceAccount := serviceaccounttypes.NewServiceAccount(req.Name, handler.module.Config().Email.Domain, serviceaccounttypes.ServiceAccountStatusActive, valuer.MustNewUUID(claims.OrgID))
err = handler.module.Create(ctx, valuer.MustNewUUID(claims.OrgID), serviceAccount)
if err != nil {
render.Error(rw, err)
@@ -59,13 +59,59 @@ func (handler *handler) Get(rw http.ResponseWriter, r *http.Request) {
return
}
- serviceAccount, err := handler.module.Get(ctx, valuer.MustNewUUID(claims.OrgID), id)
+ serviceAccountWithRoles, err := handler.module.GetWithRoles(ctx, valuer.MustNewUUID(claims.OrgID), id)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusOK, serviceAccountWithRoles)
+}
+
+func (handler *handler) GetMe(rw http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ id, err := valuer.NewUUID(claims.ServiceAccountID)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ serviceAccountWithRoles, err := handler.module.GetWithRoles(ctx, valuer.MustNewUUID(claims.OrgID), id)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusOK, serviceAccountWithRoles)
+}
+
+func (handler *handler) GetRoles(rw http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ id, err := valuer.NewUUID(mux.Vars(r)["id"])
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ serviceAccount, err := handler.module.GetWithRoles(ctx, valuer.MustNewUUID(claims.OrgID), id)
if err != nil {
render.Error(rw, err)
return
}
- render.Success(rw, http.StatusOK, serviceAccount)
+ render.Success(rw, http.StatusOK, serviceAccount.GetRoles())
}
func (handler *handler) List(rw http.ResponseWriter, r *http.Request) {
@@ -111,7 +157,7 @@ func (handler *handler) Update(rw http.ResponseWriter, r *http.Request) {
return
}
- err = serviceAccount.Update(req.Name, req.Email, req.Roles)
+ err = serviceAccount.Update(req.Name)
if err != nil {
render.Error(rw, err)
return
@@ -126,7 +172,7 @@ func (handler *handler) Update(rw http.ResponseWriter, r *http.Request) {
render.Success(rw, http.StatusNoContent, nil)
}
-func (handler *handler) UpdateStatus(rw http.ResponseWriter, r *http.Request) {
+func (handler *handler) UpdateMe(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
claims, err := authtypes.ClaimsFromContext(ctx)
if err != nil {
@@ -134,13 +180,13 @@ func (handler *handler) UpdateStatus(rw http.ResponseWriter, r *http.Request) {
return
}
- id, err := valuer.NewUUID(mux.Vars(r)["id"])
+ id, err := valuer.NewUUID(claims.ServiceAccountID)
if err != nil {
render.Error(rw, err)
return
}
- req := new(serviceaccounttypes.UpdatableServiceAccountStatus)
+ req := new(serviceaccounttypes.UpdatableServiceAccount)
if err := binding.JSON.BindBody(r.Body, req); err != nil {
render.Error(rw, err)
return
@@ -152,13 +198,71 @@ func (handler *handler) UpdateStatus(rw http.ResponseWriter, r *http.Request) {
return
}
- err = serviceAccount.UpdateStatus(req.Status)
+ err = serviceAccount.Update(req.Name)
+ 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)
+ return
+ }
+
+ render.Success(rw, http.StatusNoContent, nil)
+}
+
+func (handler *handler) SetRole(rw http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ id, err := valuer.NewUUID(mux.Vars(r)["id"])
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ req := new(serviceaccounttypes.PostableServiceAccountRole)
+ if err := binding.JSON.BindBody(r.Body, req); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ err = handler.module.SetRole(ctx, valuer.MustNewUUID(claims.OrgID), id, req.ID)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusNoContent, nil)
+}
+
+func (handler *handler) DeleteRole(rw http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ id, err := valuer.NewUUID(mux.Vars(r)["id"])
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ roleID, err := valuer.NewUUID(mux.Vars(r)["rid"])
if err != nil {
render.Error(rw, err)
return
}
- err = handler.module.UpdateStatus(ctx, valuer.MustNewUUID(claims.OrgID), serviceAccount)
+ err = handler.module.DeleteRole(ctx, valuer.MustNewUUID(claims.OrgID), id, roleID)
if err != nil {
render.Error(rw, err)
return
@@ -211,7 +315,7 @@ func (handler *handler) CreateFactorAPIKey(rw http.ResponseWriter, r *http.Reque
}
// this takes care of checking the existence of service account and the org constraint.
- serviceAccount, err := handler.module.GetWithoutRoles(ctx, valuer.MustNewUUID(claims.OrgID), id)
+ serviceAccount, err := handler.module.Get(ctx, valuer.MustNewUUID(claims.OrgID), id)
if err != nil {
render.Error(rw, err)
return
@@ -246,7 +350,7 @@ func (handler *handler) ListFactorAPIKey(rw http.ResponseWriter, r *http.Request
return
}
- serviceAccount, err := handler.module.GetWithoutRoles(ctx, valuer.MustNewUUID(claims.OrgID), id)
+ serviceAccount, err := handler.module.Get(ctx, valuer.MustNewUUID(claims.OrgID), id)
if err != nil {
render.Error(rw, err)
return
@@ -287,7 +391,7 @@ func (handler *handler) UpdateFactorAPIKey(rw http.ResponseWriter, r *http.Reque
return
}
- serviceAccount, err := handler.module.GetWithoutRoles(ctx, valuer.MustNewUUID(claims.OrgID), id)
+ serviceAccount, err := handler.module.Get(ctx, valuer.MustNewUUID(claims.OrgID), id)
if err != nil {
render.Error(rw, err)
return
@@ -299,7 +403,12 @@ func (handler *handler) UpdateFactorAPIKey(rw http.ResponseWriter, r *http.Reque
return
}
- factorAPIKey.Update(req.Name, req.ExpiresAt)
+ err = factorAPIKey.Update(req.Name, req.ExpiresAt)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
err = handler.module.UpdateFactorAPIKey(ctx, valuer.MustNewUUID(claims.OrgID), serviceAccount.ID, factorAPIKey)
if err != nil {
render.Error(rw, err)
@@ -329,7 +438,7 @@ func (handler *handler) RevokeFactorAPIKey(rw http.ResponseWriter, r *http.Reque
return
}
- serviceAccount, err := handler.module.GetWithoutRoles(ctx, valuer.MustNewUUID(claims.OrgID), id)
+ serviceAccount, err := handler.module.Get(ctx, valuer.MustNewUUID(claims.OrgID), id)
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 61e226216e..01e780190f 100644
--- a/pkg/modules/serviceaccount/implserviceaccount/module.go
+++ b/pkg/modules/serviceaccount/implserviceaccount/module.go
@@ -2,186 +2,154 @@ package implserviceaccount
import (
"context"
+ "time"
+ "github.com/SigNoz/signoz/pkg/analytics"
"github.com/SigNoz/signoz/pkg/authz"
- "github.com/SigNoz/signoz/pkg/emailing"
+ "github.com/SigNoz/signoz/pkg/cache"
"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"
- "github.com/SigNoz/signoz/pkg/types/emailtypes"
+ "github.com/SigNoz/signoz/pkg/types/cachetypes"
"github.com/SigNoz/signoz/pkg/types/serviceaccounttypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
+var (
+ emptyOrgID valuer.UUID = valuer.UUID{}
+)
+
type module struct {
- store serviceaccounttypes.Store
- authz authz.AuthZ
- emailing emailing.Emailing
- settings factory.ScopedProviderSettings
+ store serviceaccounttypes.Store
+ authz authz.AuthZ
+ cache cache.Cache
+ analytics analytics.Analytics
+ settings factory.ScopedProviderSettings
+ config serviceaccount.Config
}
-func NewModule(store serviceaccounttypes.Store, authz authz.AuthZ, emailing emailing.Emailing, providerSettings factory.ProviderSettings) serviceaccount.Module {
+func NewModule(store serviceaccounttypes.Store, authz authz.AuthZ, cache cache.Cache, analytics analytics.Analytics, providerSettings factory.ProviderSettings, config serviceaccount.Config) serviceaccount.Module {
settings := factory.NewScopedProviderSettings(providerSettings, "github.com/SigNoz/signoz/pkg/modules/serviceaccount/implserviceaccount")
- return &module{store: store, authz: authz, emailing: emailing, settings: settings}
+ return &module{store: store, authz: authz, cache: cache, analytics: analytics, settings: settings, config: config}
}
func (module *module) Create(ctx context.Context, orgID valuer.UUID, serviceAccount *serviceaccounttypes.ServiceAccount) error {
- // validates the presence of all roles passed in the create request
- roles, err := module.authz.ListByOrgIDAndNames(ctx, orgID, serviceAccount.Roles)
- if err != nil {
- return err
- }
-
- // authz actions cannot run in sql transactions
- err = module.authz.Grant(ctx, orgID, serviceAccount.Roles, authtypes.MustNewSubject(authtypes.TypeableServiceAccount, serviceAccount.ID.String(), orgID, nil))
- if err != nil {
- return err
- }
-
- storableServiceAccount := serviceaccounttypes.NewStorableServiceAccount(serviceAccount)
- storableServiceAccountRoles := serviceaccounttypes.NewStorableServiceAccountRoles(serviceAccount.ID, roles)
- err = module.store.RunInTx(ctx, func(ctx context.Context) error {
- err := module.store.Create(ctx, storableServiceAccount)
- if err != nil {
- return err
- }
-
- err = module.store.CreateServiceAccountRoles(ctx, storableServiceAccountRoles)
- if err != nil {
- return err
- }
-
- return nil
- })
+ err := module.store.Create(ctx, serviceAccount)
if err != nil {
return err
}
+ module.identifyUser(ctx, orgID.String(), serviceAccount.ID.String(), serviceAccount.Traits())
+ module.trackUser(ctx, orgID.String(), serviceAccount.ID.String(), "Service Account Created", serviceAccount.Traits())
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)
+func (module *module) GetOrCreate(ctx context.Context, orgID valuer.UUID, serviceAccountWithRoles *serviceaccounttypes.ServiceAccount) (*serviceaccounttypes.ServiceAccount, error) {
+ existingServiceAccount, err := module.GetActiveByOrgIDAndName(ctx, serviceAccountWithRoles.OrgID, serviceAccountWithRoles.Name)
if err != nil && !errors.Ast(err, errors.TypeNotFound) {
return nil, err
}
if existingServiceAccount != nil {
- return serviceAccount, nil
+ return existingServiceAccount, nil
}
- err = module.Create(ctx, serviceAccount.OrgID, serviceAccount)
+ err = module.Create(ctx, orgID, serviceAccountWithRoles)
if err != nil {
return nil, err
}
- return serviceAccount, nil
+ return serviceAccountWithRoles, 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)
+func (module *module) GetActiveByOrgIDAndName(ctx context.Context, orgID valuer.UUID, name string) (*serviceaccounttypes.ServiceAccount, error) {
+ serviceAccount, err := module.store.GetActiveByOrgIDAndName(ctx, orgID, name)
if err != nil {
return nil, err
}
- // did the orchestration on application layer instead of DB as the ORM also does it anyways for many to many tables.
- storableServiceAccountRoles, err := module.store.GetServiceAccountRoles(ctx, id)
+ return module.Get(ctx, orgID, serviceAccount.ID)
+}
+
+func (module *module) GetWithRoles(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*serviceaccounttypes.ServiceAccountWithRoles, error) {
+ serviceAccountWithRoles, err := module.store.GetWithRoles(ctx, orgID, id)
if err != nil {
return nil, err
}
- roleIDs := make([]valuer.UUID, len(storableServiceAccountRoles))
- for idx, sar := range storableServiceAccountRoles {
- roleIDs[idx] = valuer.MustNewUUID(sar.RoleID)
- }
+ return serviceAccountWithRoles, nil
+}
- roles, err := module.authz.ListByOrgIDAndIDs(ctx, orgID, roleIDs)
+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 {
return nil, err
}
- rolesNames, err := serviceaccounttypes.NewRolesFromStorableServiceAccountRoles(storableServiceAccountRoles, roles)
+ return storableServiceAccount, nil
+}
+
+func (module *module) List(ctx context.Context, orgID valuer.UUID) ([]*serviceaccounttypes.ServiceAccount, error) {
+ serviceAccounts, err := module.store.List(ctx, orgID)
if err != nil {
return nil, err
}
- serviceAccount := serviceaccounttypes.NewServiceAccountFromStorables(storableServiceAccount, rolesNames)
- return serviceAccount, nil
+ return serviceAccounts, nil
}
-func (module *module) GetWithoutRoles(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*serviceaccounttypes.ServiceAccount, error) {
- storableServiceAccount, err := module.store.Get(ctx, orgID, id)
+func (module *module) Update(ctx context.Context, orgID valuer.UUID, input *serviceaccounttypes.ServiceAccount) error {
+ err := module.store.Update(ctx, orgID, input)
if err != nil {
- return nil, err
+ return err
}
- // passing []string{} (not nil to prevent panics) roles as the function isn't supposed to put roles.
- serviceAccount := serviceaccounttypes.NewServiceAccountFromStorables(storableServiceAccount, []string{})
- return serviceAccount, nil
+ module.identifyUser(ctx, orgID.String(), input.ID.String(), input.Traits())
+ module.trackUser(ctx, orgID.String(), input.ID.String(), "Service Account Updated", input.Traits())
+ return nil
}
-func (module *module) List(ctx context.Context, orgID valuer.UUID) ([]*serviceaccounttypes.ServiceAccount, error) {
- storableServiceAccounts, err := module.store.List(ctx, orgID)
+func (module *module) SetRole(ctx context.Context, orgID valuer.UUID, id valuer.UUID, roleID valuer.UUID) error {
+ role, err := module.authz.Get(ctx, orgID, roleID)
if err != nil {
- return nil, err
+ return err
}
- storableServiceAccountRoles, err := module.store.ListServiceAccountRolesByOrgID(ctx, orgID)
- if err != nil {
- return nil, err
- }
+ return module.setRole(ctx, orgID, id, role)
+}
- // convert the service account roles to structured data
- saIDToRoleIDs, roleIDs := serviceaccounttypes.GetUniqueRolesAndServiceAccountMapping(storableServiceAccountRoles)
- roles, err := module.authz.ListByOrgIDAndIDs(ctx, orgID, roleIDs)
+func (module *module) SetRoleByName(ctx context.Context, orgID valuer.UUID, id valuer.UUID, name string) error {
+ role, err := module.authz.GetByOrgIDAndName(ctx, orgID, name)
if err != nil {
- return nil, err
+ return err
}
- // fill in the role fetched data back to service account
- serviceAccounts := serviceaccounttypes.NewServiceAccountsFromRoles(storableServiceAccounts, roles, saIDToRoleIDs)
- return serviceAccounts, nil
+ return module.setRole(ctx, orgID, id, role)
}
-func (module *module) Update(ctx context.Context, orgID valuer.UUID, input *serviceaccounttypes.ServiceAccount) error {
- serviceAccount, err := module.Get(ctx, orgID, input.ID)
+func (module *module) DeleteRole(ctx context.Context, orgID valuer.UUID, id valuer.UUID, roleID valuer.UUID) error {
+ role, err := module.authz.Get(ctx, orgID, roleID)
if err != nil {
return err
}
- roles, err := module.authz.ListByOrgIDAndNames(ctx, orgID, input.Roles)
+ serviceAccount, err := module.Get(ctx, orgID, id)
if err != nil {
return err
}
- // gets the role diff if any to modify grants.
- grants, revokes := serviceAccount.PatchRoles(input)
- err = module.authz.ModifyGrant(ctx, orgID, revokes, grants, authtypes.MustNewSubject(authtypes.TypeableServiceAccount, serviceAccount.ID.String(), orgID, nil))
+ err = serviceAccount.ErrIfDeleted()
if err != nil {
return err
}
- storableServiceAccountRoles := serviceaccounttypes.NewStorableServiceAccountRoles(serviceAccount.ID, roles)
- err = module.store.RunInTx(ctx, func(ctx context.Context) error {
- err := module.store.Update(ctx, orgID, serviceaccounttypes.NewStorableServiceAccount(input))
- if err != nil {
- return err
- }
-
- // delete all the service account roles and create new rather than diff here.
- err = module.store.DeleteServiceAccountRoles(ctx, input.ID)
- if err != nil {
- return err
- }
-
- err = module.store.CreateServiceAccountRoles(ctx, storableServiceAccountRoles)
- if err != nil {
- return err
- }
+ err = module.store.DeleteServiceAccountRole(ctx, serviceAccount.ID, roleID)
+ if err != nil {
+ return err
+ }
- return nil
- })
+ err = module.authz.Revoke(ctx, orgID, []string{role.Name}, authtypes.MustNewSubject(authtypes.TypeableServiceAccount, id.String(), orgID, nil))
if err != nil {
return err
}
@@ -189,21 +157,26 @@ func (module *module) Update(ctx context.Context, orgID valuer.UUID, input *serv
return nil
}
-func (module *module) UpdateStatus(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))
+func (module *module) Delete(ctx context.Context, orgID valuer.UUID, id valuer.UUID) error {
+ serviceAccount, err := module.GetWithRoles(ctx, orgID, id)
+ if err != nil {
+ return err
+ }
+
+ err = serviceAccount.UpdateStatus(serviceaccounttypes.ServiceAccountStatusDeleted)
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)
+ err := module.store.RevokeAllFactorAPIKeys(ctx, id)
if err != nil {
return err
}
// 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))
+ err = module.store.Update(ctx, orgID, serviceAccount.ServiceAccount)
if err != nil {
return err
}
@@ -214,122 +187,234 @@ func (module *module) UpdateStatus(ctx context.Context, orgID valuer.UUID, input
return err
}
+ err = module.authz.Revoke(ctx, orgID, serviceAccount.RoleNames(), authtypes.MustNewSubject(authtypes.TypeableServiceAccount, id.StringValue(), orgID, nil))
+ if err != nil {
+ return err
+ }
+
+ // delete the cache when updating status for service account
+ module.cache.Delete(ctx, emptyOrgID, identityCacheKey(id))
+
+ module.identifyUser(ctx, orgID.String(), id.String(), serviceAccount.Traits())
+ module.trackUser(ctx, orgID.String(), id.String(), "Service Account Deleted", map[string]any{})
return nil
}
-func (module *module) Delete(ctx context.Context, orgID valuer.UUID, id valuer.UUID) error {
- serviceAccount, err := module.Get(ctx, orgID, id)
+func (module *module) CreateFactorAPIKey(ctx context.Context, factorAPIKey *serviceaccounttypes.FactorAPIKey) error {
+ err := module.store.CreateFactorAPIKey(ctx, factorAPIKey)
if err != nil {
return err
}
- // revoke from authz first as this cannot run in sql transaction
- err = module.authz.Revoke(ctx, orgID, serviceAccount.Roles, authtypes.MustNewSubject(authtypes.TypeableServiceAccount, serviceAccount.ID.String(), orgID, nil))
+ serviceAccount, err := module.store.GetByID(ctx, factorAPIKey.ServiceAccountID)
+ if err == nil {
+ module.trackUser(ctx, serviceAccount.OrgID.StringValue(), serviceAccount.ID.String(), "API Key created", factorAPIKey.Traits())
+ }
+
+ return nil
+}
+
+func (module *module) GetOrCreateFactorAPIKey(ctx context.Context, factorAPIKey *serviceaccounttypes.FactorAPIKey) (*serviceaccounttypes.FactorAPIKey, error) {
+ existingFactorAPIKey, err := module.store.GetFactorAPIKeyByName(ctx, factorAPIKey.ServiceAccountID, factorAPIKey.Name)
+ if err != nil && !errors.Ast(err, errors.TypeNotFound) {
+ return nil, err
+ }
+
+ if existingFactorAPIKey != nil {
+ return existingFactorAPIKey, nil
+ }
+
+ err = module.CreateFactorAPIKey(ctx, factorAPIKey)
if err != nil {
- return err
+ return nil, err
}
- err = module.store.RunInTx(ctx, func(ctx context.Context) error {
- err := module.store.DeleteServiceAccountRoles(ctx, serviceAccount.ID)
- if err != nil {
- return err
- }
+ return factorAPIKey, nil
+}
- err = module.store.RevokeAllFactorAPIKeys(ctx, serviceAccount.ID)
- if err != nil {
- return err
- }
+func (module *module) GetFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID, id valuer.UUID) (*serviceaccounttypes.FactorAPIKey, error) {
+ factorAPIKey, err := module.store.GetFactorAPIKey(ctx, serviceAccountID, id)
+ if err != nil {
+ return nil, err
+ }
- err = module.store.Delete(ctx, serviceAccount.OrgID, serviceAccount.ID)
- if err != nil {
- return err
- }
+ return factorAPIKey, nil
+}
- return nil
- })
+func (module *module) ListFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID) ([]*serviceaccounttypes.FactorAPIKey, error) {
+ factorAPIKeys, err := module.store.ListFactorAPIKey(ctx, serviceAccountID)
+ if err != nil {
+ return nil, err
+ }
+
+ return factorAPIKeys, nil
+}
+
+func (module *module) UpdateFactorAPIKey(ctx context.Context, orgID valuer.UUID, serviceAccountID valuer.UUID, factorAPIKey *serviceaccounttypes.FactorAPIKey) error {
+ err := module.store.UpdateFactorAPIKey(ctx, serviceAccountID, factorAPIKey)
if err != nil {
return err
}
+ // delete the cache when updating the factor api key
+ module.cache.Delete(ctx, emptyOrgID, apiKeyCacheKey(factorAPIKey.Key))
+ module.trackUser(ctx, orgID.String(), serviceAccountID.String(), "API Key updated", factorAPIKey.Traits())
return nil
}
-func (module *module) CreateFactorAPIKey(ctx context.Context, factorAPIKey *serviceaccounttypes.FactorAPIKey) error {
- storableFactorAPIKey := serviceaccounttypes.NewStorableFactorAPIKey(factorAPIKey)
-
- err := module.store.CreateFactorAPIKey(ctx, storableFactorAPIKey)
+func (module *module) RevokeFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID, id valuer.UUID) error {
+ factorAPIKey, err := module.GetFactorAPIKey(ctx, serviceAccountID, id)
if err != nil {
return err
}
- serviceAccount, err := module.store.GetByID(ctx, factorAPIKey.ServiceAccountID)
+ err = module.store.RevokeFactorAPIKey(ctx, serviceAccountID, id)
if err != nil {
return err
}
- if err := module.emailing.SendHTML(ctx, serviceAccount.Email, "New API Key created for your SigNoz account", emailtypes.TemplateNameAPIKeyEvent, map[string]any{
- "Name": serviceAccount.Name,
- "KeyName": factorAPIKey.Name,
- "KeyID": factorAPIKey.ID.String(),
- "KeyCreatedAt": factorAPIKey.CreatedAt.String(),
- }); err != nil {
- module.settings.Logger().ErrorContext(ctx, "failed to send email", errors.Attr(err))
+ serviceAccount, err := module.store.GetByID(ctx, serviceAccountID)
+ if err != nil {
+ return err
}
+ // delete the cache when revoking the factor api key
+ module.cache.Delete(ctx, emptyOrgID, apiKeyCacheKey(factorAPIKey.Key))
+ module.trackUser(ctx, serviceAccount.OrgID.StringValue(), serviceAccountID.String(), "API Key revoked", factorAPIKey.Traits())
return nil
}
-func (module *module) GetFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID, id valuer.UUID) (*serviceaccounttypes.FactorAPIKey, error) {
- storableFactorAPIKey, err := module.store.GetFactorAPIKey(ctx, serviceAccountID, id)
+func (module *module) Config() serviceaccount.Config {
+ return module.config
+}
+
+func (module *module) Collect(ctx context.Context, orgID valuer.UUID) (map[string]any, error) {
+ stats := make(map[string]any)
+
+ count, err := module.store.CountByOrgID(ctx, orgID)
+ if err == nil {
+ stats["serviceaccount.count"] = count
+ }
+
+ count, err = module.store.CountFactorAPIKeysByOrgID(ctx, orgID)
+ if err == nil {
+ stats["serviceaccount.keys.count"] = count
+ }
+
+ return stats, nil
+}
+
+func (module *module) GetIdentity(ctx context.Context, key string) (*authtypes.Identity, error) {
+ apiKey, err := module.getOrGetSetAPIKey(ctx, key)
+ if err != nil {
+ return nil, err
+ }
+
+ if err := apiKey.IsExpired(); err != nil {
+ return nil, err
+ }
+
+ identity, err := module.getOrGetSetIdentity(ctx, apiKey.ServiceAccountID)
if err != nil {
return nil, err
}
- return serviceaccounttypes.NewFactorAPIKeyFromStorable(storableFactorAPIKey), nil
+ return identity, nil
}
-func (module *module) ListFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID) ([]*serviceaccounttypes.FactorAPIKey, error) {
- storables, err := module.store.ListFactorAPIKey(ctx, serviceAccountID)
+func (module *module) SetLastObservedAt(ctx context.Context, key string, lastObservedAt time.Time) error {
+ return module.store.UpdateLastObservedAt(ctx, key, lastObservedAt)
+}
+
+func (module *module) getOrGetSetAPIKey(ctx context.Context, key string) (*serviceaccounttypes.FactorAPIKey, error) {
+ factorAPIKey := new(serviceaccounttypes.FactorAPIKey)
+ err := module.cache.Get(ctx, emptyOrgID, apiKeyCacheKey(key), factorAPIKey)
+ if err != nil && !errors.Ast(err, errors.TypeNotFound) {
+ return nil, err
+ }
+
+ if err == nil {
+ return factorAPIKey, nil
+ }
+
+ factorAPIKey, err = module.store.GetFactorAPIKeyByKey(ctx, key)
+ if err != nil {
+ return nil, err
+ }
+
+ err = module.cache.Set(ctx, emptyOrgID, apiKeyCacheKey(key), factorAPIKey, time.Duration(factorAPIKey.ExpiresAt))
if err != nil {
return nil, err
}
- return serviceaccounttypes.NewFactorAPIKeyFromStorables(storables), nil
+ return factorAPIKey, nil
}
-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))
+func (module *module) getOrGetSetIdentity(ctx context.Context, serviceAccountID valuer.UUID) (*authtypes.Identity, error) {
+ identity := new(authtypes.Identity)
+ err := module.cache.Get(ctx, emptyOrgID, identityCacheKey(serviceAccountID), identity)
+ if err != nil && !errors.Ast(err, errors.TypeNotFound) {
+ return nil, err
+ }
+
+ if err == nil {
+ return identity, nil
+ }
+
+ storableServiceAccount, err := module.store.GetByID(ctx, serviceAccountID)
if err != nil {
- return err
+ return nil, err
}
- return nil
+ identity = storableServiceAccount.ToIdentity()
+ err = module.cache.Set(ctx, emptyOrgID, identityCacheKey(serviceAccountID), identity, 0)
+ if err != nil {
+ return nil, err
+ }
+
+ return identity, nil
}
-func (module *module) RevokeFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID, id valuer.UUID) error {
- factorAPIKey, err := module.GetFactorAPIKey(ctx, serviceAccountID, id)
+func (module *module) setRole(ctx context.Context, orgID valuer.UUID, id valuer.UUID, role *authtypes.Role) error {
+ serviceAccount, err := module.Get(ctx, orgID, id)
if err != nil {
return err
}
- err = module.store.RevokeFactorAPIKey(ctx, serviceAccountID, id)
+ serviceAccountRole, err := serviceAccount.AddRole(role)
if err != nil {
return err
}
- serviceAccount, err := module.store.GetByID(ctx, serviceAccountID)
+ err = module.store.CreateServiceAccountRole(ctx, serviceAccountRole)
if err != nil {
return err
}
- if err := module.emailing.SendHTML(ctx, serviceAccount.Email, "API Key revoked for your SigNoz account", emailtypes.TemplateNameAPIKeyEvent, map[string]any{
- "Name": serviceAccount.Name,
- "KeyName": factorAPIKey.Name,
- "KeyID": factorAPIKey.ID.String(),
- "KeyCreatedAt": factorAPIKey.CreatedAt.String(),
- }); err != nil {
- module.settings.Logger().ErrorContext(ctx, "failed to send email", errors.Attr(err))
+ err = module.authz.Grant(ctx, orgID, []string{role.Name}, authtypes.MustNewSubject(authtypes.TypeableServiceAccount, id.String(), orgID, nil))
+ if err != nil {
+ return err
}
return nil
}
+
+func (module *module) trackUser(ctx context.Context, orgID string, userID string, event string, attrs map[string]any) {
+ if module.config.Analytics.Enabled {
+ module.analytics.TrackUser(ctx, orgID, userID, event, attrs)
+ }
+}
+
+func (module *module) identifyUser(ctx context.Context, orgID string, userID string, traits map[string]any) {
+ if module.config.Analytics.Enabled {
+ module.analytics.IdentifyUser(ctx, orgID, userID, traits)
+ }
+}
+
+func apiKeyCacheKey(apiKey string) string {
+ return "api_key::" + cachetypes.NewSha1CacheKey(apiKey)
+}
+
+func identityCacheKey(serviceAccountID valuer.UUID) string {
+ return "identity::" + serviceAccountID.String()
+}
diff --git a/pkg/modules/serviceaccount/implserviceaccount/store.go b/pkg/modules/serviceaccount/implserviceaccount/store.go
index 82244a0512..36106d4736 100644
--- a/pkg/modules/serviceaccount/implserviceaccount/store.go
+++ b/pkg/modules/serviceaccount/implserviceaccount/store.go
@@ -2,6 +2,7 @@ package implserviceaccount
import (
"context"
+ "time"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/types/serviceaccounttypes"
@@ -16,7 +17,7 @@ func NewStore(sqlstore sqlstore.SQLStore) serviceaccounttypes.Store {
return &store{sqlstore: sqlstore}
}
-func (store *store) Create(ctx context.Context, storable *serviceaccounttypes.StorableServiceAccount) error {
+func (store *store) Create(ctx context.Context, storable *serviceaccounttypes.ServiceAccount) error {
_, err := store.
sqlstore.
BunDBCtx(ctx).
@@ -30,8 +31,8 @@ func (store *store) Create(ctx context.Context, storable *serviceaccounttypes.St
return nil
}
-func (store *store) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*serviceaccounttypes.StorableServiceAccount, error) {
- storable := new(serviceaccounttypes.StorableServiceAccount)
+func (store *store) Get(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*serviceaccounttypes.ServiceAccount, error) {
+ storable := new(serviceaccounttypes.ServiceAccount)
err := store.
sqlstore.
@@ -48,8 +49,28 @@ 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)
+func (store *store) GetWithRoles(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*serviceaccounttypes.ServiceAccountWithRoles, error) {
+ storable := new(serviceaccounttypes.ServiceAccountWithRoles)
+
+ err := store.
+ sqlstore.
+ BunDBCtx(ctx).
+ NewSelect().
+ Model(storable).
+ Relation("ServiceAccountRoles").
+ Relation("ServiceAccountRoles.Role").
+ Where("id = ?", id).
+ Where("org_id = ?", orgID).
+ Scan(ctx)
+ if err != nil {
+ return nil, store.sqlstore.WrapNotFoundErrf(err, serviceaccounttypes.ErrCodeServiceAccountNotFound, "service account with id: %s doesn't exist in org: %s", id, orgID)
+ }
+
+ return storable, nil
+}
+
+func (store *store) GetActiveByOrgIDAndName(ctx context.Context, orgID valuer.UUID, name string) (*serviceaccounttypes.ServiceAccount, error) {
+ storable := new(serviceaccounttypes.ServiceAccount)
err := store.
sqlstore.
@@ -58,17 +79,17 @@ func (store *store) GetActiveByOrgIDAndName(ctx context.Context, orgID valuer.UU
Model(storable).
Where("org_id = ?", orgID).
Where("name = ?", name).
- Where("status = ?", serviceaccounttypes.StatusActive).
+ Where("status = ?", serviceaccounttypes.ServiceAccountStatusActive).
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 nil, store.sqlstore.WrapNotFoundErrf(err, serviceaccounttypes.ErrCodeServiceAccountNotFound, "active 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)
+func (store *store) GetByID(ctx context.Context, id valuer.UUID) (*serviceaccounttypes.ServiceAccount, error) {
+ storable := new(serviceaccounttypes.ServiceAccount)
err := store.
sqlstore.
@@ -84,8 +105,25 @@ func (store *store) GetByID(ctx context.Context, id valuer.UUID) (*serviceaccoun
return storable, nil
}
-func (store *store) List(ctx context.Context, orgID valuer.UUID) ([]*serviceaccounttypes.StorableServiceAccount, error) {
- storables := make([]*serviceaccounttypes.StorableServiceAccount, 0)
+func (store *store) CountByOrgID(ctx context.Context, orgID valuer.UUID) (int64, error) {
+ storable := new(serviceaccounttypes.ServiceAccount)
+
+ count, err := store.
+ sqlstore.
+ BunDB().
+ NewSelect().
+ Model(storable).
+ Where("org_id = ?", orgID).
+ Count(ctx)
+ if err != nil {
+ return 0, err
+ }
+
+ return int64(count), nil
+}
+
+func (store *store) List(ctx context.Context, orgID valuer.UUID) ([]*serviceaccounttypes.ServiceAccount, error) {
+ storables := make([]*serviceaccounttypes.ServiceAccount, 0)
err := store.
sqlstore.
@@ -101,7 +139,7 @@ func (store *store) List(ctx context.Context, orgID valuer.UUID) ([]*serviceacco
return storables, nil
}
-func (store *store) Update(ctx context.Context, orgID valuer.UUID, storable *serviceaccounttypes.StorableServiceAccount) error {
+func (store *store) Update(ctx context.Context, orgID valuer.UUID, storable *serviceaccounttypes.ServiceAccount) error {
_, err := store.
sqlstore.
BunDBCtx(ctx).
@@ -110,6 +148,21 @@ func (store *store) Update(ctx context.Context, orgID valuer.UUID, storable *ser
WherePK().
Where("org_id = ?", orgID).
Exec(ctx)
+ if err != nil {
+ return store.sqlstore.WrapAlreadyExistsErrf(err, serviceaccounttypes.ErrCodeServiceAccountAlreadyExists, "service account with name: %s already exists", storable.Name)
+ }
+
+ return nil
+}
+
+func (store *store) CreateServiceAccountRole(ctx context.Context, serviceAccountRole *serviceaccounttypes.ServiceAccountRole) error {
+ _, err := store.
+ sqlstore.
+ BunDBCtx(ctx).
+ NewInsert().
+ Model(serviceAccountRole).
+ On("CONFLICT (service_account_id, role_id) DO NOTHING").
+ Exec(ctx)
if err != nil {
return err
}
@@ -117,14 +170,14 @@ func (store *store) Update(ctx context.Context, orgID valuer.UUID, storable *ser
return nil
}
-func (store *store) Delete(ctx context.Context, orgID valuer.UUID, id valuer.UUID) error {
+func (store *store) DeleteServiceAccountRole(ctx context.Context, serviceAccountID valuer.UUID, roleID valuer.UUID) error {
_, err := store.
sqlstore.
BunDBCtx(ctx).
NewDelete().
- Model(new(serviceaccounttypes.StorableServiceAccount)).
- Where("id = ?", id).
- Where("org_id = ?", orgID).
+ Model(new(serviceaccounttypes.ServiceAccountRole)).
+ Where("service_account_id = ?", serviceAccountID).
+ Where("role_id = ?", roleID).
Exec(ctx)
if err != nil {
return err
@@ -133,106 +186,94 @@ func (store *store) Delete(ctx context.Context, orgID valuer.UUID, id valuer.UUI
return nil
}
-func (store *store) CreateServiceAccountRoles(ctx context.Context, storables []*serviceaccounttypes.StorableServiceAccountRole) error {
+func (store *store) CreateFactorAPIKey(ctx context.Context, storable *serviceaccounttypes.FactorAPIKey) error {
_, err := store.
sqlstore.
BunDBCtx(ctx).
NewInsert().
- Model(&storables).
+ Model(storable).
Exec(ctx)
if err != nil {
- return store.sqlstore.WrapAlreadyExistsErrf(err, serviceaccounttypes.ErrCodeServiceAccountRoleAlreadyExists, "duplicate role assignments for service account")
+ return store.sqlstore.WrapAlreadyExistsErrf(err, serviceaccounttypes.ErrCodeAPIKeyAlreadyExists, "api key with name: %s already exists for service account: %s", storable.Name, storable.ServiceAccountID)
}
return nil
}
-func (store *store) GetServiceAccountRoles(ctx context.Context, id valuer.UUID) ([]*serviceaccounttypes.StorableServiceAccountRole, error) {
- storables := make([]*serviceaccounttypes.StorableServiceAccountRole, 0)
+func (store *store) GetFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID, id valuer.UUID) (*serviceaccounttypes.FactorAPIKey, error) {
+ storable := new(serviceaccounttypes.FactorAPIKey)
err := store.
sqlstore.
BunDBCtx(ctx).
NewSelect().
- Model(&storables).
- Where("service_account_id = ?", id).
+ Model(storable).
+ Where("id = ?", id).
+ Where("service_account_id = ?", serviceAccountID).
Scan(ctx)
if err != nil {
- // no need to wrap not found here as this is many to many table
- return nil, err
+ return nil, store.sqlstore.WrapNotFoundErrf(err, serviceaccounttypes.ErrCodeAPIKeytNotFound, "api key with id: %s doesn't exist for service account: %s", id, serviceAccountID)
}
- return storables, nil
+ return storable, nil
}
-func (store *store) ListServiceAccountRolesByOrgID(ctx context.Context, orgID valuer.UUID) ([]*serviceaccounttypes.StorableServiceAccountRole, error) {
- storables := make([]*serviceaccounttypes.StorableServiceAccountRole, 0)
+func (store *store) GetFactorAPIKeyByKey(ctx context.Context, key string) (*serviceaccounttypes.FactorAPIKey, error) {
+ storable := new(serviceaccounttypes.FactorAPIKey)
err := store.
sqlstore.
BunDBCtx(ctx).
NewSelect().
- Model(&storables).
- Join("JOIN service_account").
- JoinOn("service_account.id = service_account_role.service_account_id").
- Where("service_account.org_id = ?", orgID).
+ Model(storable).
+ Where("key = ?", key).
Scan(ctx)
if err != nil {
- return nil, err
+ return nil, store.sqlstore.WrapNotFoundErrf(err, serviceaccounttypes.ErrCodeAPIKeytNotFound, "api key with key: %s doesn't exist.", key)
}
- return storables, nil
+ return storable, nil
}
-func (store *store) DeleteServiceAccountRoles(ctx context.Context, id valuer.UUID) error {
- _, err := store.
- sqlstore.
- BunDBCtx(ctx).
- NewDelete().
- Model(new(serviceaccounttypes.StorableServiceAccountRole)).
- Where("service_account_id = ?", id).
- Exec(ctx)
- if err != nil {
- return err
- }
-
- return nil
-}
+func (store *store) GetFactorAPIKeyByName(ctx context.Context, serviceAccountID valuer.UUID, name string) (*serviceaccounttypes.FactorAPIKey, error) {
+ storable := new(serviceaccounttypes.FactorAPIKey)
-func (store *store) CreateFactorAPIKey(ctx context.Context, storable *serviceaccounttypes.StorableFactorAPIKey) error {
- _, err := store.
+ err := store.
sqlstore.
BunDBCtx(ctx).
- NewInsert().
+ NewSelect().
Model(storable).
- Exec(ctx)
+ Where("service_account_id = ?", serviceAccountID.String()).
+ Where("name = ?", name).
+ Scan(ctx)
if err != nil {
- return store.sqlstore.WrapAlreadyExistsErrf(err, serviceaccounttypes.ErrCodeAPIKeyAlreadyExists, "api key with name: %s already exists for service account: %s", storable.Name, storable.ServiceAccountID)
+ return nil, store.sqlstore.WrapNotFoundErrf(err, serviceaccounttypes.ErrCodeAPIKeytNotFound, "api key with name: %s doesn't exist in service account: %s", name, serviceAccountID.String())
}
- return nil
+ return storable, nil
}
-func (store *store) GetFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID, id valuer.UUID) (*serviceaccounttypes.StorableFactorAPIKey, error) {
- storable := new(serviceaccounttypes.StorableFactorAPIKey)
+func (store *store) CountFactorAPIKeysByOrgID(ctx context.Context, orgID valuer.UUID) (int64, error) {
+ storable := new(serviceaccounttypes.FactorAPIKey)
- err := store.
+ count, err := store.
sqlstore.
BunDBCtx(ctx).
NewSelect().
Model(storable).
- Where("id = ?", id).
- Where("service_account_id = ?", serviceAccountID).
- Scan(ctx)
+ Join("JOIN service_account").
+ JoinOn("service_account.id = factor_api_key.service_account_id").
+ Where("service_account.org_id = ?", orgID).
+ Count(ctx)
if err != nil {
- return nil, store.sqlstore.WrapNotFoundErrf(err, serviceaccounttypes.ErrCodeAPIKeytNotFound, "api key with id: %s doesn't exist for service account: %s", id, serviceAccountID)
+ return 0, err
}
- return storable, nil
+ return int64(count), nil
}
-func (store *store) ListFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID) ([]*serviceaccounttypes.StorableFactorAPIKey, error) {
- storables := make([]*serviceaccounttypes.StorableFactorAPIKey, 0)
+func (store *store) ListFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID) ([]*serviceaccounttypes.FactorAPIKey, error) {
+ storables := make([]*serviceaccounttypes.FactorAPIKey, 0)
err := store.
sqlstore.
@@ -248,14 +289,31 @@ func (store *store) ListFactorAPIKey(ctx context.Context, serviceAccountID value
return storables, nil
}
-func (store *store) UpdateFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID, storable *serviceaccounttypes.StorableFactorAPIKey) error {
+func (store *store) UpdateFactorAPIKey(ctx context.Context, serviceAccountID valuer.UUID, storable *serviceaccounttypes.FactorAPIKey) error {
_, err := store.
sqlstore.
BunDBCtx(ctx).
NewUpdate().
Model(storable).
+ WherePK().
Where("service_account_id = ?", serviceAccountID).
Exec(ctx)
+ if err != nil {
+ return store.sqlstore.WrapAlreadyExistsErrf(err, serviceaccounttypes.ErrCodeAPIKeyAlreadyExists, "api key with name: %s already exists in service account: %s", storable.Name, storable.ServiceAccountID)
+ }
+
+ return nil
+}
+
+func (store *store) UpdateLastObservedAt(ctx context.Context, key string, lastObservedAt time.Time) error {
+ _, err := store.
+ sqlstore.
+ BunDBCtx(ctx).
+ NewUpdate().
+ TableExpr("factor_api_key").
+ Set("last_observed_at = ?", lastObservedAt).
+ Where("key = ?", key).
+ Exec(ctx)
if err != nil {
return err
}
@@ -268,7 +326,7 @@ func (store *store) RevokeFactorAPIKey(ctx context.Context, serviceAccountID val
sqlstore.
BunDBCtx(ctx).
NewDelete().
- Model(new(serviceaccounttypes.StorableFactorAPIKey)).
+ Model(new(serviceaccounttypes.FactorAPIKey)).
Where("service_account_id = ?", serviceAccountID).
Where("id = ?", id).
Exec(ctx)
@@ -284,7 +342,7 @@ func (store *store) RevokeAllFactorAPIKeys(ctx context.Context, serviceAccountID
sqlstore.
BunDBCtx(ctx).
NewDelete().
- Model(new(serviceaccounttypes.StorableFactorAPIKey)).
+ Model(new(serviceaccounttypes.FactorAPIKey)).
Where("service_account_id = ?", serviceAccountID).
Exec(ctx)
if err != nil {
diff --git a/pkg/modules/serviceaccount/serviceaccount.go b/pkg/modules/serviceaccount/serviceaccount.go
index f1083e6851..a8d3214b41 100644
--- a/pkg/modules/serviceaccount/serviceaccount.go
+++ b/pkg/modules/serviceaccount/serviceaccount.go
@@ -3,7 +3,9 @@ package serviceaccount
import (
"context"
"net/http"
+ "time"
+ "github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/serviceaccounttypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
@@ -12,14 +14,14 @@ type Module interface {
// Creates a new service account for an organization.
Create(context.Context, valuer.UUID, *serviceaccounttypes.ServiceAccount) error
- // Gets a service account by id.
- Get(context.Context, valuer.UUID, valuer.UUID) (*serviceaccounttypes.ServiceAccount, error)
+ // Gets a service account with roles by id.
+ GetWithRoles(context.Context, valuer.UUID, valuer.UUID) (*serviceaccounttypes.ServiceAccountWithRoles, error)
// Gets or creates a service account by name
- GetOrCreate(context.Context, *serviceaccounttypes.ServiceAccount) (*serviceaccounttypes.ServiceAccount, error)
+ GetOrCreate(context.Context, valuer.UUID, *serviceaccounttypes.ServiceAccount) (*serviceaccounttypes.ServiceAccount, error)
- // Gets a service account by id without fetching roles.
- GetWithoutRoles(context.Context, valuer.UUID, valuer.UUID) (*serviceaccounttypes.ServiceAccount, error)
+ // Gets a service account by id
+ Get(context.Context, valuer.UUID, valuer.UUID) (*serviceaccounttypes.ServiceAccount, error)
// List all service accounts for an organization.
List(context.Context, valuer.UUID) ([]*serviceaccounttypes.ServiceAccount, error)
@@ -27,8 +29,14 @@ type Module interface {
// Updates an existing service account
Update(context.Context, valuer.UUID, *serviceaccounttypes.ServiceAccount) error
- // Updates an existing service account status
- UpdateStatus(context.Context, valuer.UUID, *serviceaccounttypes.ServiceAccount) error
+ // Assign a role to the service account. this is safe to retry
+ SetRole(context.Context, valuer.UUID, valuer.UUID, valuer.UUID) error
+
+ // Assigns a role by name to service account, this is safe to retry
+ SetRoleByName(context.Context, valuer.UUID, valuer.UUID, string) error
+
+ // Revokes a role from service account, this is safe to retry
+ DeleteRole(context.Context, valuer.UUID, valuer.UUID, valuer.UUID) error
// Deletes an existing service account by id
Delete(context.Context, valuer.UUID, valuer.UUID) error
@@ -39,14 +47,25 @@ type Module interface {
// Gets a factor API key by id
GetFactorAPIKey(context.Context, valuer.UUID, valuer.UUID) (*serviceaccounttypes.FactorAPIKey, error)
+ // Gets or creates a factor api key by name
+ GetOrCreateFactorAPIKey(context.Context, *serviceaccounttypes.FactorAPIKey) (*serviceaccounttypes.FactorAPIKey, error)
+
// Lists all the API keys for a service account
ListFactorAPIKey(context.Context, valuer.UUID) ([]*serviceaccounttypes.FactorAPIKey, error)
// Updates an existing API key for a service account
UpdateFactorAPIKey(context.Context, valuer.UUID, valuer.UUID, *serviceaccounttypes.FactorAPIKey) error
+ // Set the last observed at for an api key.
+ SetLastObservedAt(context.Context, string, time.Time) error
+
// Revokes an existing API key for a service account
RevokeFactorAPIKey(context.Context, valuer.UUID, valuer.UUID) error
+
+ // Gets the identity for service account based on the factor api key.
+ GetIdentity(context.Context, string) (*authtypes.Identity, error)
+
+ Config() Config
}
type Handler interface {
@@ -54,11 +73,19 @@ type Handler interface {
Get(http.ResponseWriter, *http.Request)
+ GetRoles(http.ResponseWriter, *http.Request)
+
+ GetMe(http.ResponseWriter, *http.Request)
+
List(http.ResponseWriter, *http.Request)
Update(http.ResponseWriter, *http.Request)
- UpdateStatus(http.ResponseWriter, *http.Request)
+ UpdateMe(http.ResponseWriter, *http.Request)
+
+ SetRole(http.ResponseWriter, *http.Request)
+
+ DeleteRole(http.ResponseWriter, *http.Request)
Delete(http.ResponseWriter, *http.Request)
diff --git a/pkg/modules/session/implsession/module.go b/pkg/modules/session/implsession/module.go
index d379baaa06..89eb3aed23 100644
--- a/pkg/modules/session/implsession/module.go
+++ b/pkg/modules/session/implsession/module.go
@@ -160,18 +160,7 @@ func (module *module) CreateCallbackAuthNSession(ctx context.Context, authNProvi
return "", errors.WithAdditionalf(err, "root user can only authenticate via password")
}
- userRoles, err := module.userGetter.GetRolesByUserID(ctx, newUser.ID)
- if err != nil {
- return "", err
- }
-
- if len(userRoles) == 0 {
- return "", errors.New(errors.TypeUnexpected, authtypes.ErrCodeUserRolesNotFound, "no user roles entries found")
- }
-
- finalRole := authtypes.SigNozManagedRoleToExistingLegacyRole[userRoles[0].Role.Name]
-
- token, err := module.tokenizer.CreateToken(ctx, authtypes.NewIdentity(newUser.ID, newUser.OrgID, newUser.Email, finalRole, authtypes.IdentNProviderTokenizer), map[string]string{})
+ token, err := module.tokenizer.CreateToken(ctx, authtypes.NewPrincipalUserIdentity(newUser.ID, newUser.OrgID, newUser.Email, authtypes.IdentNProviderTokenizer), map[string]string{})
if err != nil {
return "", err
}
diff --git a/pkg/modules/spanpercentile/implspanpercentile/handler.go b/pkg/modules/spanpercentile/implspanpercentile/handler.go
index fb6263886e..a5b50e20d9 100644
--- a/pkg/modules/spanpercentile/implspanpercentile/handler.go
+++ b/pkg/modules/spanpercentile/implspanpercentile/handler.go
@@ -35,7 +35,7 @@ func (h *handler) GetSpanPercentileDetails(w http.ResponseWriter, r *http.Reques
return
}
- result, err := h.module.GetSpanPercentile(r.Context(), valuer.MustNewUUID(claims.OrgID), valuer.MustNewUUID(claims.UserID), spanPercentileRequest)
+ result, err := h.module.GetSpanPercentile(r.Context(), valuer.MustNewUUID(claims.OrgID), spanPercentileRequest)
if err != nil {
render.Error(w, err)
return
diff --git a/pkg/modules/spanpercentile/implspanpercentile/module.go b/pkg/modules/spanpercentile/implspanpercentile/module.go
index b73e935761..f5ee853241 100644
--- a/pkg/modules/spanpercentile/implspanpercentile/module.go
+++ b/pkg/modules/spanpercentile/implspanpercentile/module.go
@@ -28,7 +28,7 @@ func NewModule(
}
}
-func (m *module) GetSpanPercentile(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, req *spanpercentiletypes.SpanPercentileRequest) (*spanpercentiletypes.SpanPercentileResponse, error) {
+func (m *module) GetSpanPercentile(ctx context.Context, orgID valuer.UUID, req *spanpercentiletypes.SpanPercentileRequest) (*spanpercentiletypes.SpanPercentileResponse, error) {
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
instrumentationtypes.CodeNamespace: "spanpercentile",
instrumentationtypes.CodeFunctionName: "GetSpanPercentile",
diff --git a/pkg/modules/spanpercentile/spanpercentile.go b/pkg/modules/spanpercentile/spanpercentile.go
index c1fd1b55c8..8030096de2 100644
--- a/pkg/modules/spanpercentile/spanpercentile.go
+++ b/pkg/modules/spanpercentile/spanpercentile.go
@@ -9,7 +9,7 @@ import (
)
type Module interface {
- GetSpanPercentile(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, req *spanpercentiletypes.SpanPercentileRequest) (*spanpercentiletypes.SpanPercentileResponse, error)
+ GetSpanPercentile(ctx context.Context, orgID valuer.UUID, req *spanpercentiletypes.SpanPercentileRequest) (*spanpercentiletypes.SpanPercentileResponse, error)
}
type Handler interface {
diff --git a/pkg/modules/user/impluser/handler.go b/pkg/modules/user/impluser/handler.go
index fbb2608c36..c2e2a03dc2 100644
--- a/pkg/modules/user/impluser/handler.go
+++ b/pkg/modules/user/impluser/handler.go
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"net/http"
- "slices"
"time"
"github.com/SigNoz/signoz/pkg/errors"
@@ -13,7 +12,6 @@ import (
root "github.com/SigNoz/signoz/pkg/modules/user"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
- "github.com/SigNoz/signoz/pkg/types/integrationtypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/gorilla/mux"
)
@@ -43,7 +41,7 @@ func (h *handler) CreateInvite(rw http.ResponseWriter, r *http.Request) {
return
}
- invites, err := h.setter.CreateBulkInvite(ctx, valuer.MustNewUUID(claims.OrgID), valuer.MustNewUUID(claims.UserID), &types.PostableBulkInviteRequest{
+ invites, err := h.setter.CreateBulkInvite(ctx, valuer.MustNewUUID(claims.OrgID), valuer.MustNewUUID(claims.IdentityID()), valuer.MustNewEmail(claims.Email), &types.PostableBulkInviteRequest{
Invites: []types.PostableInvite{req},
})
if err != nil {
@@ -76,7 +74,7 @@ func (h *handler) CreateBulkInvite(rw http.ResponseWriter, r *http.Request) {
return
}
- _, err = h.setter.CreateBulkInvite(ctx, valuer.MustNewUUID(claims.OrgID), valuer.MustNewUUID(claims.UserID), &req)
+ _, err = h.setter.CreateBulkInvite(ctx, valuer.MustNewUUID(claims.OrgID), valuer.MustNewUUID(claims.IdentityID()), valuer.MustNewEmail(claims.Email), &req)
if err != nil {
render.Error(rw, err)
return
@@ -268,7 +266,7 @@ func (h *handler) UpdateUserDeprecated(w http.ResponseWriter, r *http.Request) {
return
}
- updatedUser, err := h.setter.UpdateUserDeprecated(ctx, valuer.MustNewUUID(claims.OrgID), id, &user, claims.UserID)
+ updatedUser, err := h.setter.UpdateUserDeprecated(ctx, valuer.MustNewUUID(claims.OrgID), id, &user)
if err != nil {
render.Error(w, err)
return
@@ -321,7 +319,7 @@ func (h *handler) DeleteUser(w http.ResponseWriter, r *http.Request) {
return
}
- if err := h.setter.DeleteUser(ctx, valuer.MustNewUUID(claims.OrgID), id, claims.UserID); err != nil {
+ if err := h.setter.DeleteUser(ctx, valuer.MustNewUUID(claims.OrgID), id, claims.IdentityID()); err != nil {
render.Error(w, err)
return
}
@@ -413,175 +411,6 @@ func (h *handler) ForgotPassword(w http.ResponseWriter, r *http.Request) {
render.Success(w, http.StatusNoContent, nil)
}
-func (h *handler) CreateAPIKey(w http.ResponseWriter, r *http.Request) {
- ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
- defer cancel()
-
- claims, err := authtypes.ClaimsFromContext(ctx)
- if err != nil {
- render.Error(w, err)
- return
- }
-
- req := new(types.PostableAPIKey)
- if err := json.NewDecoder(r.Body).Decode(req); err != nil {
- render.Error(w, errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "failed to decode api key"))
- return
- }
-
- apiKey, err := types.NewStorableAPIKey(
- req.Name,
- valuer.MustNewUUID(claims.UserID),
- req.Role,
- req.ExpiresInDays,
- )
- if err != nil {
- render.Error(w, err)
- return
- }
-
- err = h.setter.CreateAPIKey(ctx, apiKey)
- if err != nil {
- render.Error(w, err)
- return
- }
-
- createdApiKey, err := h.setter.GetAPIKey(ctx, valuer.MustNewUUID(claims.OrgID), apiKey.ID)
- if err != nil {
- render.Error(w, err)
- return
- }
-
- // just corrected the status code, response is same,
- render.Success(w, http.StatusCreated, createdApiKey)
-}
-
-func (h *handler) ListAPIKeys(w http.ResponseWriter, r *http.Request) {
- ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
- defer cancel()
-
- claims, err := authtypes.ClaimsFromContext(ctx)
- if err != nil {
- render.Error(w, err)
- return
- }
-
- apiKeys, err := h.setter.ListAPIKeys(ctx, valuer.MustNewUUID(claims.OrgID))
- if err != nil {
- render.Error(w, err)
- return
- }
-
- // for backward compatibility
- if len(apiKeys) == 0 {
- render.Success(w, http.StatusOK, []types.GettableAPIKey{})
- return
- }
-
- result := make([]*types.GettableAPIKey, len(apiKeys))
- for i, apiKey := range apiKeys {
- result[i] = types.NewGettableAPIKeyFromStorableAPIKey(apiKey)
- }
-
- render.Success(w, http.StatusOK, result)
-
-}
-
-func (h *handler) UpdateAPIKey(w http.ResponseWriter, r *http.Request) {
- ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
- defer cancel()
-
- claims, err := authtypes.ClaimsFromContext(ctx)
- if err != nil {
- render.Error(w, err)
- return
- }
-
- req := types.StorableAPIKey{}
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- render.Error(w, errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "failed to decode api key"))
- return
- }
-
- idStr := mux.Vars(r)["id"]
- id, err := valuer.NewUUID(idStr)
- if err != nil {
- render.Error(w, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is not a valid uuid-v7"))
- return
- }
-
- //get the API Key
- existingAPIKey, err := h.setter.GetAPIKey(ctx, valuer.MustNewUUID(claims.OrgID), id)
- if err != nil {
- render.Error(w, err)
- return
- }
-
- // get the user
- createdByUser, err := h.getter.Get(ctx, existingAPIKey.UserID)
- if err != nil {
- render.Error(w, err)
- return
- }
-
- if slices.Contains(integrationtypes.AllIntegrationUserEmails, integrationtypes.IntegrationUserEmail(createdByUser.Email.String())) {
- render.Error(w, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "API Keys for integration users cannot be revoked"))
- return
- }
-
- err = h.setter.UpdateAPIKey(ctx, id, &req, valuer.MustNewUUID(claims.UserID))
- if err != nil {
- render.Error(w, err)
- return
- }
-
- render.Success(w, http.StatusNoContent, nil)
-}
-
-func (h *handler) RevokeAPIKey(w http.ResponseWriter, r *http.Request) {
- ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
- defer cancel()
-
- claims, err := authtypes.ClaimsFromContext(ctx)
- if err != nil {
- render.Error(w, err)
- return
- }
-
- idStr := mux.Vars(r)["id"]
- id, err := valuer.NewUUID(idStr)
- if err != nil {
- render.Error(w, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "id is not a valid uuid-v7"))
- return
- }
-
- //get the API Key
- existingAPIKey, err := h.setter.GetAPIKey(ctx, valuer.MustNewUUID(claims.OrgID), id)
- if err != nil {
- render.Error(w, err)
- return
- }
-
- // get the user
- createdByUser, err := h.getter.Get(ctx, existingAPIKey.UserID)
- if err != nil {
- render.Error(w, err)
- return
- }
-
- if slices.Contains(integrationtypes.AllIntegrationUserEmails, integrationtypes.IntegrationUserEmail(createdByUser.Email.String())) {
- render.Error(w, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "API Keys for integration users cannot be revoked"))
- return
- }
-
- if err := h.setter.RevokeAPIKey(ctx, id, valuer.MustNewUUID(claims.UserID)); err != nil {
- render.Error(w, err)
- return
- }
-
- render.Success(w, http.StatusNoContent, nil)
-}
-
func (h *handler) GetRolesByUserID(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
diff --git a/pkg/modules/user/impluser/setter.go b/pkg/modules/user/impluser/setter.go
index 99bbc836ed..648533962f 100644
--- a/pkg/modules/user/impluser/setter.go
+++ b/pkg/modules/user/impluser/setter.go
@@ -55,12 +55,7 @@ func NewSetter(store types.UserStore, tokenizer tokenizer.Tokenizer, emailing em
}
// CreateBulk implements invite.Module.
-func (module *setter) CreateBulkInvite(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, bulkInvites *types.PostableBulkInviteRequest) ([]*types.Invite, error) {
- creator, err := module.store.GetUser(ctx, userID)
- if err != nil {
- return nil, err
- }
-
+func (module *setter) CreateBulkInvite(ctx context.Context, orgID valuer.UUID, identityID valuer.UUID, identityEmail valuer.Email, bulkInvites *types.PostableBulkInviteRequest) ([]*types.Invite, error) {
// validate all emails to be invited
emails := make([]string, len(bulkInvites.Invites))
for idx, invite := range bulkInvites.Invites {
@@ -127,7 +122,7 @@ func (module *setter) CreateBulkInvite(ctx context.Context, orgID valuer.UUID, u
// send password reset emails to all the invited users
for idx, userWithToken := range newUsersWithResetToken {
- module.analytics.TrackUser(ctx, orgID.String(), creator.ID.String(), "Invite Sent", map[string]any{
+ module.analytics.TrackUser(ctx, orgID.String(), identityID.String(), "Invite Sent", map[string]any{
"invitee_email": userWithToken.User.Email,
"invitee_role": userWithToken.Role,
})
@@ -161,7 +156,7 @@ func (module *setter) CreateBulkInvite(ctx context.Context, orgID valuer.UUID, u
humanizedTokenLifetime := strings.TrimSpace(humanize.RelTime(time.Now(), time.Now().Add(tokenLifetime), "", ""))
if err := module.emailing.SendHTML(ctx, userWithToken.User.Email.String(), "You're Invited to Join SigNoz", emailtypes.TemplateNameInvitationEmail, map[string]any{
- "inviter_email": creator.Email,
+ "inviter_email": identityEmail.StringValue(),
"link": resetLink,
"Expiry": humanizedTokenLifetime,
}); err != nil {
@@ -219,7 +214,12 @@ func (module *setter) CreateUser(ctx context.Context, user *types.User, opts ...
return nil
}
-func (module *setter) UpdateUserDeprecated(ctx context.Context, orgID valuer.UUID, id string, user *types.DeprecatedUser, updatedBy string) (*types.DeprecatedUser, error) {
+func (module *setter) UpdateUserDeprecated(ctx context.Context, orgID valuer.UUID, id string, user *types.DeprecatedUser) (*types.DeprecatedUser, error) {
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ return nil, err
+ }
+
existingUser, err := module.getter.GetDeprecatedUserByOrgIDAndID(ctx, orgID, valuer.MustNewUUID(id))
if err != nil {
return nil, err
@@ -233,19 +233,29 @@ func (module *setter) UpdateUserDeprecated(ctx context.Context, orgID valuer.UUI
return nil, errors.WithAdditionalf(err, "cannot update deleted user")
}
- requestor, err := module.getter.GetDeprecatedUserByOrgIDAndID(ctx, orgID, valuer.MustNewUUID(updatedBy))
- if err != nil {
- return nil, err
- }
-
roleChange := user.Role != "" && user.Role != existingUser.Role
- if roleChange && requestor.Role != types.RoleAdmin {
- return nil, errors.New(errors.TypeForbidden, errors.CodeForbidden, "only admins can change roles")
+ if roleChange {
+ selectors := []authtypes.Selector{
+ authtypes.MustNewSelector(authtypes.TypeRole, authtypes.SigNozAdminRoleName),
+ }
+ err = module.authz.CheckWithTupleCreation(
+ ctx,
+ claims,
+ valuer.MustNewUUID(claims.OrgID),
+ authtypes.RelationAssignee,
+ authtypes.TypeableRole,
+ selectors,
+ selectors,
+ )
+
+ if err != nil {
+ return nil, errors.New(errors.TypeForbidden, errors.CodeForbidden, "only admins can change roles")
+ }
}
// make sure the user is not demoting self from admin
- if roleChange && existingUser.ID == requestor.ID && existingUser.Role == types.RoleAdmin && user.Role != types.RoleAdmin {
+ if roleChange && existingUser.ID == valuer.MustNewUUID(claims.IdentityID()) && existingUser.Role == types.RoleAdmin && user.Role != types.RoleAdmin {
return nil, errors.New(errors.TypeForbidden, errors.CodeForbidden, "cannot change self role")
}
@@ -666,26 +676,6 @@ func (module *setter) GetOrCreateUser(ctx context.Context, user *types.User, opt
return user, nil
}
-func (module *setter) CreateAPIKey(ctx context.Context, apiKey *types.StorableAPIKey) error {
- return module.store.CreateAPIKey(ctx, apiKey)
-}
-
-func (module *setter) UpdateAPIKey(ctx context.Context, id valuer.UUID, apiKey *types.StorableAPIKey, updaterID valuer.UUID) error {
- return module.store.UpdateAPIKey(ctx, id, apiKey, updaterID)
-}
-
-func (module *setter) ListAPIKeys(ctx context.Context, orgID valuer.UUID) ([]*types.StorableAPIKeyUser, error) {
- return module.store.ListAPIKeys(ctx, orgID)
-}
-
-func (module *setter) GetAPIKey(ctx context.Context, orgID, id valuer.UUID) (*types.StorableAPIKeyUser, error) {
- return module.store.GetAPIKey(ctx, orgID, id)
-}
-
-func (module *setter) RevokeAPIKey(ctx context.Context, id, removedByUserID valuer.UUID) error {
- return module.store.RevokeAPIKey(ctx, id, removedByUserID)
-}
-
func (module *setter) CreateFirstUser(ctx context.Context, organization *types.Organization, name string, email valuer.Email, passwd string) (*types.User, error) {
user, err := types.NewRootUser(name, email, organization.ID)
if err != nil {
@@ -741,11 +731,6 @@ func (module *setter) Collect(ctx context.Context, orgID valuer.UUID) (map[strin
stats["user.count.pending_invite"] = counts[types.UserStatusPendingInvite]
}
- count, err := module.store.CountAPIKeyByOrgID(ctx, orgID)
- if err == nil {
- stats["factor.api_key.count"] = count
- }
-
return stats, nil
}
diff --git a/pkg/modules/user/impluser/store.go b/pkg/modules/user/impluser/store.go
index 13be48145a..20b382af51 100644
--- a/pkg/modules/user/impluser/store.go
+++ b/pkg/modules/user/impluser/store.go
@@ -3,7 +3,6 @@ package impluser
import (
"context"
"database/sql"
- "sort"
"time"
"github.com/SigNoz/signoz/pkg/errors"
@@ -182,15 +181,6 @@ func (store *store) DeleteUser(ctx context.Context, orgID string, id string) err
return errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "failed to delete factor password")
}
- // delete api keys
- _, err = tx.NewDelete().
- Model(&types.StorableAPIKey{}).
- Where("user_id = ?", id).
- Exec(ctx)
- if err != nil {
- return errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "failed to delete API keys")
- }
-
// delete user_preference
_, err = tx.NewDelete().
Model(new(preferencetypes.StorableUserPreference)).
@@ -266,15 +256,6 @@ func (store *store) SoftDeleteUser(ctx context.Context, orgID string, id string)
return errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "failed to delete factor password")
}
- // delete api keys
- _, err = tx.NewDelete().
- Model(&types.StorableAPIKey{}).
- Where("user_id = ?", id).
- Exec(ctx)
- if err != nil {
- return errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "failed to delete API keys")
- }
-
// delete user_preference
_, err = tx.NewDelete().
Model(new(preferencetypes.StorableUserPreference)).
@@ -421,111 +402,6 @@ func (store *store) UpdatePassword(ctx context.Context, factorPassword *types.Fa
return nil
}
-// CreateAPIKey creates a new API key.
-func (store *store) CreateAPIKey(ctx context.Context, apiKey *types.StorableAPIKey) error {
- _, err := store.sqlstore.BunDB().NewInsert().
- Model(apiKey).
- Exec(ctx)
- if err != nil {
- return store.sqlstore.WrapAlreadyExistsErrf(err, types.ErrAPIKeyAlreadyExists, "API key with token: %s already exists", apiKey.Token)
- }
-
- return nil
-}
-
-func (store *store) UpdateAPIKey(ctx context.Context, id valuer.UUID, apiKey *types.StorableAPIKey, updaterID valuer.UUID) error {
- apiKey.UpdatedBy = updaterID.String()
- apiKey.UpdatedAt = time.Now()
- _, err := store.sqlstore.BunDB().NewUpdate().
- Model(apiKey).
- Column("role", "name", "updated_at", "updated_by").
- Where("id = ?", id).
- Where("revoked = false").
- Exec(ctx)
- if err != nil {
- return store.sqlstore.WrapNotFoundErrf(err, types.ErrAPIKeyNotFound, "API key with id: %s does not exist", id)
- }
- return nil
-}
-
-func (store *store) ListAPIKeys(ctx context.Context, orgID valuer.UUID) ([]*types.StorableAPIKeyUser, error) {
- orgUserAPIKeys := new(types.OrgUserAPIKey)
-
- if err := store.sqlstore.BunDB().NewSelect().
- Model(orgUserAPIKeys).
- Relation("Users").
- Relation("Users.APIKeys", func(q *bun.SelectQuery) *bun.SelectQuery {
- return q.Where("revoked = false")
- },
- ).
- Relation("Users.APIKeys.CreatedByUser").
- Relation("Users.APIKeys.UpdatedByUser").
- Where("id = ?", orgID).
- Scan(ctx); err != nil {
- return nil, errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "failed to fetch API keys")
- }
-
- // Flatten the API keys from all users
- var allAPIKeys []*types.StorableAPIKeyUser
- for _, user := range orgUserAPIKeys.Users {
- if user.APIKeys != nil {
- allAPIKeys = append(allAPIKeys, user.APIKeys...)
- }
- }
-
- // sort the API keys by updated_at
- sort.Slice(allAPIKeys, func(i, j int) bool {
- return allAPIKeys[i].UpdatedAt.After(allAPIKeys[j].UpdatedAt)
- })
-
- return allAPIKeys, nil
-}
-
-func (store *store) RevokeAPIKey(ctx context.Context, id, revokedByUserID valuer.UUID) error {
- updatedAt := time.Now().Unix()
- _, err := store.sqlstore.BunDB().NewUpdate().
- Model(&types.StorableAPIKey{}).
- Set("revoked = ?", true).
- Set("updated_by = ?", revokedByUserID).
- Set("updated_at = ?", updatedAt).
- Where("id = ?", id).
- Exec(ctx)
- if err != nil {
- return errors.Wrapf(err, errors.TypeInternal, errors.CodeInternal, "failed to revoke API key")
- }
- return nil
-}
-
-func (store *store) GetAPIKey(ctx context.Context, orgID, id valuer.UUID) (*types.StorableAPIKeyUser, error) {
- apiKey := new(types.OrgUserAPIKey)
- if err := store.sqlstore.BunDB().NewSelect().
- Model(apiKey).
- Relation("Users").
- Relation("Users.APIKeys", func(q *bun.SelectQuery) *bun.SelectQuery {
- return q.Where("revoked = false").Where("storable_api_key.id = ?", id).
- OrderExpr("storable_api_key.updated_at DESC").Limit(1)
- },
- ).
- Relation("Users.APIKeys.CreatedByUser").
- Relation("Users.APIKeys.UpdatedByUser").
- Scan(ctx); err != nil {
- return nil, store.sqlstore.WrapNotFoundErrf(err, types.ErrAPIKeyNotFound, "API key with id: %s does not exist", id)
- }
-
- // flatten the API keys
- flattenedAPIKeys := []*types.StorableAPIKeyUser{}
- for _, user := range apiKey.Users {
- if user.APIKeys != nil {
- flattenedAPIKeys = append(flattenedAPIKeys, user.APIKeys...)
- }
- }
- if len(flattenedAPIKeys) == 0 {
- return nil, store.sqlstore.WrapNotFoundErrf(errors.New(errors.TypeNotFound, errors.CodeNotFound, "API key with id: %s does not exist"), types.ErrAPIKeyNotFound, "API key with id: %s does not exist", id)
- }
-
- return flattenedAPIKeys[0], nil
-}
-
func (store *store) CountByOrgID(ctx context.Context, orgID valuer.UUID) (int64, error) {
user := new(types.User)
@@ -573,24 +449,6 @@ func (store *store) CountByOrgIDAndStatuses(ctx context.Context, orgID valuer.UU
return counts, nil
}
-func (store *store) CountAPIKeyByOrgID(ctx context.Context, orgID valuer.UUID) (int64, error) {
- apiKey := new(types.StorableAPIKey)
-
- count, err := store.
- sqlstore.
- BunDB().
- NewSelect().
- Model(apiKey).
- Join("JOIN users ON users.id = storable_api_key.user_id").
- Where("org_id = ?", orgID).
- Count(ctx)
- if err != nil {
- return 0, err
- }
-
- return int64(count), nil
-}
-
func (store *store) RunInTx(ctx context.Context, cb func(ctx context.Context) error) error {
return store.sqlstore.RunInTxCtx(ctx, nil, func(ctx context.Context) error {
return cb(ctx)
diff --git a/pkg/modules/user/user.go b/pkg/modules/user/user.go
index b5a36d7eac..05605374b9 100644
--- a/pkg/modules/user/user.go
+++ b/pkg/modules/user/user.go
@@ -34,7 +34,7 @@ type Setter interface {
// Initiate forgot password flow for a user
ForgotPassword(ctx context.Context, orgID valuer.UUID, email valuer.Email, frontendBaseURL string) error
- UpdateUserDeprecated(ctx context.Context, orgID valuer.UUID, id string, user *types.DeprecatedUser, updatedBy string) (*types.DeprecatedUser, error)
+ UpdateUserDeprecated(ctx context.Context, orgID valuer.UUID, id string, user *types.DeprecatedUser) (*types.DeprecatedUser, error)
UpdateUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, updatable *types.UpdatableUser) (*types.User, error)
// UpdateAnyUser updates a user and persists the changes to the database along with the analytics and identity deletion.
@@ -43,14 +43,7 @@ type Setter interface {
DeleteUser(ctx context.Context, orgID valuer.UUID, id string, deletedBy string) error
// invite
- CreateBulkInvite(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, bulkInvites *types.PostableBulkInviteRequest) ([]*types.Invite, error)
-
- // API KEY
- CreateAPIKey(ctx context.Context, apiKey *types.StorableAPIKey) error
- UpdateAPIKey(ctx context.Context, id valuer.UUID, apiKey *types.StorableAPIKey, updaterID valuer.UUID) error
- ListAPIKeys(ctx context.Context, orgID valuer.UUID) ([]*types.StorableAPIKeyUser, error)
- RevokeAPIKey(ctx context.Context, id, removedByUserID valuer.UUID) error
- GetAPIKey(ctx context.Context, orgID valuer.UUID, id valuer.UUID) (*types.StorableAPIKeyUser, error)
+ CreateBulkInvite(ctx context.Context, orgID valuer.UUID, identityID valuer.UUID, identityEmail valuer.Email, bulkInvites *types.PostableBulkInviteRequest) ([]*types.Invite, error)
// Roles
UpdateUserRoles(ctx context.Context, orgID, userID valuer.UUID, finalRoleNames []string) error
@@ -123,10 +116,4 @@ type Handler interface {
ResetPassword(http.ResponseWriter, *http.Request)
ChangePassword(http.ResponseWriter, *http.Request)
ForgotPassword(http.ResponseWriter, *http.Request)
-
- // API KEY
- CreateAPIKey(http.ResponseWriter, *http.Request)
- ListAPIKeys(http.ResponseWriter, *http.Request)
- UpdateAPIKey(http.ResponseWriter, *http.Request)
- RevokeAPIKey(http.ResponseWriter, *http.Request)
}
diff --git a/pkg/querier/api.go b/pkg/querier/api.go
index a54b6db6bf..254f6169c6 100644
--- a/pkg/querier/api.go
+++ b/pkg/querier/api.go
@@ -268,9 +268,9 @@ func (handler *handler) logEvent(ctx context.Context, referrer string, event *qb
}
if !event.HasData {
- handler.analytics.TrackUser(ctx, claims.OrgID, claims.UserID, "Telemetry Query Returned Empty", properties)
+ handler.analytics.TrackUser(ctx, claims.OrgID, claims.IdentityID(), "Telemetry Query Returned Empty", properties)
return
}
- handler.analytics.TrackUser(ctx, claims.OrgID, claims.UserID, "Telemetry Query Returned Results", properties)
+ handler.analytics.TrackUser(ctx, claims.OrgID, claims.IdentityID(), "Telemetry Query Returned Results", properties)
}
diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.go
index b1be04e683..92a115aadf 100644
--- a/pkg/query-service/app/http_handler.go
+++ b/pkg/query-service/app/http_handler.go
@@ -1533,7 +1533,7 @@ func (aH *APIHandler) registerEvent(w http.ResponseWriter, r *http.Request) {
if errv2 == nil {
switch request.EventType {
case model.TrackEvent:
- aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.UserID, request.EventName, request.Attributes)
+ aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.IdentityID(), request.EventName, request.Attributes)
}
aH.WriteJSON(w, r, map[string]string{"data": "Event Processed Successfully"})
} else {
@@ -4636,7 +4636,7 @@ func (aH *APIHandler) sendQueryResultEvents(r *http.Request, result []*v3.Result
// Check if result is empty or has no data
if len(result) == 0 {
- aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.UserID, "Telemetry Query Returned Empty", properties)
+ aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.IdentityID(), "Telemetry Query Returned Empty", properties)
return
}
@@ -4646,18 +4646,18 @@ func (aH *APIHandler) sendQueryResultEvents(r *http.Request, result []*v3.Result
if len(result[0].List) == 0 {
// Check if first result has no table data
if result[0].Table == nil {
- aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.UserID, "Telemetry Query Returned Empty", properties)
+ aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.IdentityID(), "Telemetry Query Returned Empty", properties)
return
}
if len(result[0].Table.Rows) == 0 {
- aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.UserID, "Telemetry Query Returned Empty", properties)
+ aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.IdentityID(), "Telemetry Query Returned Empty", properties)
return
}
}
}
- aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.UserID, "Telemetry Query Returned Results", properties)
+ aH.Signoz.Analytics.TrackUser(r.Context(), claims.OrgID, claims.IdentityID(), "Telemetry Query Returned Results", properties)
}
diff --git a/pkg/signoz/config.go b/pkg/signoz/config.go
index ee23d0d919..97115ae00f 100644
--- a/pkg/signoz/config.go
+++ b/pkg/signoz/config.go
@@ -22,6 +22,7 @@ import (
"github.com/SigNoz/signoz/pkg/identn"
"github.com/SigNoz/signoz/pkg/instrumentation"
"github.com/SigNoz/signoz/pkg/modules/metricsexplorer"
+ "github.com/SigNoz/signoz/pkg/modules/serviceaccount"
"github.com/SigNoz/signoz/pkg/modules/user"
"github.com/SigNoz/signoz/pkg/pprof"
"github.com/SigNoz/signoz/pkg/prometheus"
@@ -119,6 +120,9 @@ type Config struct {
// IdentN config
IdentN identn.Config `mapstructure:"identn"`
+
+ // ServiceAccount config
+ ServiceAccount serviceaccount.Config `mapstructure:"serviceaccount"`
}
func NewConfig(ctx context.Context, logger *slog.Logger, resolverConfig config.ResolverConfig) (Config, error) {
@@ -148,6 +152,7 @@ func NewConfig(ctx context.Context, logger *slog.Logger, resolverConfig config.R
flagger.NewConfigFactory(),
user.NewConfigFactory(),
identn.NewConfigFactory(),
+ serviceaccount.NewConfigFactory(),
}
conf, err := config.New(ctx, resolverConfig, configFactories)
diff --git a/pkg/signoz/handler.go b/pkg/signoz/handler.go
index f80d50dc61..7a90ff57be 100644
--- a/pkg/signoz/handler.go
+++ b/pkg/signoz/handler.go
@@ -81,7 +81,7 @@ func NewHandlers(
return Handlers{
SavedView: implsavedview.NewHandler(modules.SavedView),
Apdex: implapdex.NewHandler(modules.Apdex),
- Dashboard: impldashboard.NewHandler(modules.Dashboard, providerSettings),
+ Dashboard: impldashboard.NewHandler(modules.Dashboard, providerSettings, authz),
QuickFilter: implquickfilter.NewHandler(modules.QuickFilter),
TraceFunnel: impltracefunnel.NewHandler(modules.TraceFunnel),
RawDataExport: implrawdataexport.NewHandler(modules.RawDataExport),
diff --git a/pkg/signoz/module.go b/pkg/signoz/module.go
index 5245abf992..aeebd7c5c5 100644
--- a/pkg/signoz/module.go
+++ b/pkg/signoz/module.go
@@ -117,7 +117,7 @@ func NewModules(
Services: implservices.NewModule(querier, telemetryStore),
MetricsExplorer: implmetricsexplorer.NewModule(telemetryStore, telemetryMetadataStore, cache, ruleStore, dashboard, providerSettings, config.MetricsExplorer),
Promote: implpromote.NewModule(telemetryMetadataStore, telemetryStore),
- ServiceAccount: implserviceaccount.NewModule(implserviceaccount.NewStore(sqlstore), authz, emailing, providerSettings),
+ ServiceAccount: implserviceaccount.NewModule(implserviceaccount.NewStore(sqlstore), authz, cache, analytics, providerSettings, config.ServiceAccount),
RuleStateHistory: implrulestatehistory.NewModule(implrulestatehistory.NewStore(telemetryStore, telemetryMetadataStore, providerSettings.Logger)),
}
}
diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.go
index 66f3f0266e..e5a3bdd969 100644
--- a/pkg/signoz/provider.go
+++ b/pkg/signoz/provider.go
@@ -31,6 +31,7 @@ import (
"github.com/SigNoz/signoz/pkg/modules/organization/implorganization"
"github.com/SigNoz/signoz/pkg/modules/preference/implpreference"
"github.com/SigNoz/signoz/pkg/modules/promote/implpromote"
+ "github.com/SigNoz/signoz/pkg/modules/serviceaccount"
"github.com/SigNoz/signoz/pkg/modules/session/implsession"
"github.com/SigNoz/signoz/pkg/modules/user"
"github.com/SigNoz/signoz/pkg/modules/user/impluser"
@@ -190,6 +191,9 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewUpdatePlannedMaintenanceRuleFactory(sqlstore, sqlschema),
sqlmigration.NewAddUserRoleFactory(sqlstore, sqlschema),
sqlmigration.NewDropUserRoleColumnFactory(sqlstore, sqlschema),
+ sqlmigration.NewAddServiceAccountFactory(sqlstore, sqlschema),
+ sqlmigration.NewDeprecateAPIKeyFactory(sqlstore, sqlschema),
+ sqlmigration.NewServiceAccountAuthzactory(sqlstore),
)
}
@@ -293,11 +297,11 @@ func NewTokenizerProviderFactories(cache cache.Cache, sqlstore sqlstore.SQLStore
)
}
-func NewIdentNProviderFactories(sqlstore sqlstore.SQLStore, tokenizer tokenizer.Tokenizer, orgGetter organization.Getter, userGetter user.Getter, userConfig user.Config) factory.NamedMap[factory.ProviderFactory[identn.IdentN, identn.Config]] {
+func NewIdentNProviderFactories(tokenizer tokenizer.Tokenizer, serviceAccount serviceaccount.Module, orgGetter organization.Getter, userGetter user.Getter, userConfig user.Config) factory.NamedMap[factory.ProviderFactory[identn.IdentN, identn.Config]] {
return factory.MustNewNamedMap(
impersonationidentn.NewFactory(orgGetter, userGetter, userConfig),
tokenizeridentn.NewFactory(tokenizer),
- apikeyidentn.NewFactory(sqlstore),
+ apikeyidentn.NewFactory(serviceAccount),
)
}
diff --git a/pkg/signoz/signoz.go b/pkg/signoz/signoz.go
index 41e64eed28..ec61920c39 100644
--- a/pkg/signoz/signoz.go
+++ b/pkg/signoz/signoz.go
@@ -415,7 +415,7 @@ func New(
modules := NewModules(sqlstore, tokenizer, emailing, providerSettings, orgGetter, alertmanager, analytics, querier, telemetrystore, telemetryMetadataStore, authNs, authz, cache, queryParser, config, dashboard, userGetter, userRoleStore)
// Initialize identN resolver
- identNFactories := NewIdentNProviderFactories(sqlstore, tokenizer, orgGetter, userGetter, config.User)
+ identNFactories := NewIdentNProviderFactories(tokenizer, modules.ServiceAccount, orgGetter, userGetter, config.User)
identNResolver, err := identn.NewIdentNResolver(ctx, providerSettings, config.IdentN, identNFactories)
if err != nil {
return nil, err
diff --git a/pkg/sqlmigration/073_add_service_account.go b/pkg/sqlmigration/073_add_service_account.go
new file mode 100644
index 0000000000..77f2c1fa39
--- /dev/null
+++ b/pkg/sqlmigration/073_add_service_account.go
@@ -0,0 +1,133 @@
+package sqlmigration
+
+import (
+ "context"
+
+ "github.com/SigNoz/signoz/pkg/factory"
+ "github.com/SigNoz/signoz/pkg/sqlschema"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/uptrace/bun"
+ "github.com/uptrace/bun/migrate"
+)
+
+type addServiceAccount struct {
+ sqlschema sqlschema.SQLSchema
+ sqlstore sqlstore.SQLStore
+}
+
+func NewAddServiceAccountFactory(sqlstore sqlstore.SQLStore, sqlschema sqlschema.SQLSchema) factory.ProviderFactory[SQLMigration, Config] {
+ return factory.NewProviderFactory(factory.MustNewName("add_service_account"), func(_ context.Context, _ factory.ProviderSettings, _ Config) (SQLMigration, error) {
+ return &addServiceAccount{
+ sqlschema: sqlschema,
+ sqlstore: sqlstore,
+ }, nil
+ })
+}
+
+func (migration *addServiceAccount) Register(migrations *migrate.Migrations) error {
+ err := migrations.Register(migration.Up, migration.Down)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (migration *addServiceAccount) Up(ctx context.Context, db *bun.DB) error {
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+
+ defer func() {
+ _ = tx.Rollback()
+ }()
+
+ sqls := [][]byte{}
+
+ tableSQLs := migration.sqlschema.Operator().CreateTable(&sqlschema.Table{
+ Name: "service_account",
+ Columns: []*sqlschema.Column{
+ {Name: "id", DataType: sqlschema.DataTypeText, Nullable: false},
+ {Name: "name", DataType: sqlschema.DataTypeText, Nullable: false},
+ {Name: "email", DataType: sqlschema.DataTypeText, Nullable: false},
+ {Name: "status", DataType: sqlschema.DataTypeText, Nullable: false},
+ {Name: "created_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},
+ {Name: "updated_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},
+ {Name: "org_id", DataType: sqlschema.DataTypeText, Nullable: false},
+ },
+ PrimaryKeyConstraint: &sqlschema.PrimaryKeyConstraint{
+ ColumnNames: []sqlschema.ColumnName{"id"},
+ },
+ ForeignKeyConstraints: []*sqlschema.ForeignKeyConstraint{
+ {
+ ReferencingColumnName: sqlschema.ColumnName("org_id"),
+ ReferencedTableName: sqlschema.TableName("organizations"),
+ ReferencedColumnName: sqlschema.ColumnName("id"),
+ },
+ },
+ })
+ sqls = append(sqls, tableSQLs...)
+
+ indexSQLs := migration.sqlschema.Operator().CreateIndex(
+ &sqlschema.PartialUniqueIndex{
+ TableName: "service_account",
+ ColumnNames: []sqlschema.ColumnName{"name", "org_id"},
+ Where: "status != 'deleted'",
+ })
+ sqls = append(sqls, indexSQLs...)
+
+ indexSQLs = migration.sqlschema.Operator().CreateIndex(
+ &sqlschema.PartialUniqueIndex{
+ TableName: "service_account",
+ ColumnNames: []sqlschema.ColumnName{"email", "org_id"},
+ Where: "status != 'deleted'",
+ })
+ sqls = append(sqls, indexSQLs...)
+
+ tableSQLs = migration.sqlschema.Operator().CreateTable(&sqlschema.Table{
+ Name: "service_account_role",
+ Columns: []*sqlschema.Column{
+ {Name: "id", DataType: sqlschema.DataTypeText, Nullable: false},
+ {Name: "created_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},
+ {Name: "updated_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},
+ {Name: "service_account_id", DataType: sqlschema.DataTypeText, Nullable: false},
+ {Name: "role_id", DataType: sqlschema.DataTypeText, Nullable: false},
+ },
+ PrimaryKeyConstraint: &sqlschema.PrimaryKeyConstraint{
+ ColumnNames: []sqlschema.ColumnName{"id"},
+ },
+ ForeignKeyConstraints: []*sqlschema.ForeignKeyConstraint{
+ {
+ ReferencingColumnName: sqlschema.ColumnName("service_account_id"),
+ ReferencedTableName: sqlschema.TableName("service_account"),
+ ReferencedColumnName: sqlschema.ColumnName("id"),
+ },
+ {
+ ReferencingColumnName: sqlschema.ColumnName("role_id"),
+ ReferencedTableName: sqlschema.TableName("role"),
+ ReferencedColumnName: sqlschema.ColumnName("id"),
+ },
+ },
+ })
+ sqls = append(sqls, tableSQLs...)
+
+ indexSQLs = migration.sqlschema.Operator().CreateIndex(&sqlschema.UniqueIndex{TableName: "service_account_role", ColumnNames: []sqlschema.ColumnName{"service_account_id", "role_id"}})
+ sqls = append(sqls, indexSQLs...)
+
+ for _, sql := range sqls {
+ if _, err := tx.ExecContext(ctx, string(sql)); err != nil {
+ return err
+ }
+ }
+
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (a *addServiceAccount) Down(context.Context, *bun.DB) error {
+ return nil
+}
diff --git a/pkg/sqlmigration/074_deprecate_api_key.go b/pkg/sqlmigration/074_deprecate_api_key.go
new file mode 100644
index 0000000000..742162a5de
--- /dev/null
+++ b/pkg/sqlmigration/074_deprecate_api_key.go
@@ -0,0 +1,359 @@
+package sqlmigration
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "regexp"
+ "strings"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/factory"
+ "github.com/SigNoz/signoz/pkg/sqlschema"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/types/authtypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/uptrace/bun"
+ "github.com/uptrace/bun/migrate"
+)
+
+// sanitizeForEmail converts an arbitrary string into a valid email local part
+// by replacing any character that is not alphanumeric, dot, hyphen, or underscore
+// with a hyphen, then collapsing consecutive hyphens and trimming leading/trailing hyphens.
+var nonEmailLocalPartRe = regexp.MustCompile(`[^a-zA-Z0-9._-]+`)
+
+func sanitizeForEmail(name string) string {
+ s := nonEmailLocalPartRe.ReplaceAllString(name, "-")
+ s = strings.Trim(s, "-")
+ if s == "" {
+ s = "service-account"
+ }
+ return s
+}
+
+type oldFactorAPIKey68 struct {
+ bun.BaseModel `bun:"table:factor_api_key"`
+
+ types.Identifiable
+ CreatedAt time.Time `bun:"created_at"`
+ UpdatedAt time.Time `bun:"updated_at"`
+ Token string `bun:"token"`
+ Role string `bun:"role"`
+ Name string `bun:"name"`
+ ExpiresAt time.Time `bun:"expires_at"`
+ LastUsed time.Time `bun:"last_used"`
+ Revoked bool `bun:"revoked"`
+ UserID string `bun:"user_id"`
+}
+
+type oldUser68 struct {
+ bun.BaseModel `bun:"table:users"`
+
+ types.Identifiable
+ DisplayName string `bun:"display_name"`
+ Email string `bun:"email"`
+ OrgID string `bun:"org_id"`
+}
+
+type oldRole68 struct {
+ bun.BaseModel `bun:"table:role"`
+
+ types.Identifiable
+ Name string `bun:"name"`
+ OrgID string `bun:"org_id"`
+}
+
+type newServiceAccount68 struct {
+ bun.BaseModel `bun:"table:service_account"`
+
+ types.Identifiable
+ CreatedAt time.Time `bun:"created_at"`
+ UpdatedAt time.Time `bun:"updated_at"`
+ Name string `bun:"name"`
+ Email string `bun:"email"`
+ Status string `bun:"status"`
+ OrgID string `bun:"org_id"`
+}
+
+type newServiceAccountRole68 struct {
+ bun.BaseModel `bun:"table:service_account_role"`
+
+ types.Identifiable
+ CreatedAt time.Time `bun:"created_at"`
+ UpdatedAt time.Time `bun:"updated_at"`
+ ServiceAccountID string `bun:"service_account_id"`
+ RoleID string `bun:"role_id"`
+}
+
+type newFactorAPIKey68 struct {
+ bun.BaseModel `bun:"table:factor_api_key"`
+
+ types.Identifiable
+ CreatedAt time.Time `bun:"created_at"`
+ UpdatedAt time.Time `bun:"updated_at"`
+ Name string `bun:"name"`
+ Key string `bun:"key"`
+ ExpiresAt uint64 `bun:"expires_at"`
+ LastObservedAt time.Time `bun:"last_observed_at"`
+ ServiceAccountID string `bun:"service_account_id"`
+}
+
+type deprecateAPIKey struct {
+ sqlstore sqlstore.SQLStore
+ sqlschema sqlschema.SQLSchema
+}
+
+func NewDeprecateAPIKeyFactory(sqlstore sqlstore.SQLStore, sqlschema sqlschema.SQLSchema) factory.ProviderFactory[SQLMigration, Config] {
+ return factory.NewProviderFactory(factory.MustNewName("deprecate_api_key"), func(_ context.Context, _ factory.ProviderSettings, c Config) (SQLMigration, error) {
+ return &deprecateAPIKey{
+ sqlstore: sqlstore,
+ sqlschema: sqlschema,
+ }, nil
+ })
+}
+
+func (migration *deprecateAPIKey) Register(migrations *migrate.Migrations) error {
+ err := migrations.Register(migration.Up, migration.Down)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (migration *deprecateAPIKey) Up(ctx context.Context, db *bun.DB) error {
+ table, _, err := migration.sqlschema.GetTable(ctx, sqlschema.TableName("factor_api_key"))
+ if err != nil {
+ return err
+ }
+
+ hasOldSchema := false
+ for _, col := range table.Columns {
+ if col.Name == "user_id" {
+ hasOldSchema = true
+ break
+ }
+ }
+ if !hasOldSchema {
+ return nil
+ }
+
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+
+ defer func() {
+ _ = tx.Rollback()
+ }()
+
+ // get all the api keys
+ oldKeys := make([]*oldFactorAPIKey68, 0)
+ err = tx.NewSelect().Model(&oldKeys).Where("revoked = ?", false).Scan(ctx)
+ if err != nil && err != sql.ErrNoRows {
+ return err
+ }
+
+ // get all the unique users
+ userIDs := make(map[string]struct{})
+ for _, key := range oldKeys {
+ userIDs[key.UserID] = struct{}{}
+ }
+
+ userIDList := make([]string, 0, len(userIDs))
+ for uid := range userIDs {
+ userIDList = append(userIDList, uid)
+ }
+
+ userMap := make(map[string]*oldUser68)
+ if len(userIDList) > 0 {
+ users := make([]*oldUser68, 0)
+ err = tx.NewSelect().Model(&users).Where("id IN (?)", bun.In(userIDList)).Scan(ctx)
+ if err != nil && err != sql.ErrNoRows {
+ return err
+ }
+ for _, u := range users {
+ userMap[u.ID.String()] = u
+ }
+ }
+
+ // get the role ids
+ type orgRoleKey struct {
+ OrgID string
+ RoleName string
+ }
+ roleMap := make(map[orgRoleKey]string)
+ if len(userMap) > 0 {
+ orgIDs := make(map[string]struct{})
+ for _, u := range userMap {
+ orgIDs[u.OrgID] = struct{}{}
+ }
+ orgIDList := make([]string, 0, len(orgIDs))
+ for oid := range orgIDs {
+ orgIDList = append(orgIDList, oid)
+ }
+
+ roles := make([]*oldRole68, 0)
+ err = tx.NewSelect().Model(&roles).Where("org_id IN (?)", bun.In(orgIDList)).Scan(ctx)
+ if err != nil && err != sql.ErrNoRows {
+ return err
+ }
+ for _, r := range roles {
+ roleMap[orgRoleKey{OrgID: r.OrgID, RoleName: r.Name}] = r.ID.String()
+ }
+ }
+
+ serviceAccounts := make([]*newServiceAccount68, 0)
+ serviceAccountRoles := make([]*newServiceAccountRole68, 0)
+ newKeys := make([]*newFactorAPIKey68, 0)
+
+ // Track used names per org for deduplication.
+ // Names are sanitized first so that dedup, Name, and email all derive
+ // from the same value — avoiding collisions on the unique (email, org_id) index.
+ orgNameCount := make(map[string]map[string]int) // orgID -> sanitized name -> count
+
+ now := time.Now()
+ for _, oldKey := range oldKeys {
+ user, ok := userMap[oldKey.UserID]
+ if !ok {
+ // this should never happen as a key cannot exist without a user
+ continue
+ }
+
+ // Sanitize first, then deduplicate within the same org
+ if orgNameCount[user.OrgID] == nil {
+ orgNameCount[user.OrgID] = make(map[string]int)
+ }
+ baseName := sanitizeForEmail(oldKey.Name)
+ count := orgNameCount[user.OrgID][baseName]
+ finalName := baseName
+ if count > 0 {
+ finalName = fmt.Sprintf("%s-%d", baseName, count)
+ }
+ orgNameCount[user.OrgID][baseName] = count + 1
+
+ saID := valuer.GenerateUUID()
+ serviceAccounts = append(serviceAccounts, &newServiceAccount68{
+ Identifiable: types.Identifiable{ID: saID},
+ CreatedAt: now,
+ UpdatedAt: now,
+ Name: finalName,
+ Email: fmt.Sprintf("%[email protected]", finalName),
+ Status: "active",
+ OrgID: user.OrgID,
+ })
+
+ managedRoleName, ok := authtypes.ExistingRoleToSigNozManagedRoleMap[types.Role(oldKey.Role)]
+ if !ok {
+ managedRoleName = authtypes.SigNozViewerRoleName
+ }
+
+ roleID, ok := roleMap[orgRoleKey{OrgID: user.OrgID, RoleName: managedRoleName}]
+ if ok {
+ serviceAccountRoles = append(serviceAccountRoles, &newServiceAccountRole68{
+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},
+ CreatedAt: now,
+ UpdatedAt: now,
+ ServiceAccountID: saID.String(),
+ RoleID: roleID,
+ })
+ }
+
+ var expiresAtUnix uint64
+ if !oldKey.ExpiresAt.IsZero() && oldKey.ExpiresAt.Unix() > 0 {
+ expiresAtUnix = uint64(oldKey.ExpiresAt.Unix())
+ }
+
+ // Convert last_used to last_observed_at.
+ lastObservedAt := oldKey.LastUsed
+ if lastObservedAt.IsZero() {
+ lastObservedAt = oldKey.CreatedAt
+ }
+
+ newKeys = append(newKeys, &newFactorAPIKey68{
+ Identifiable: oldKey.Identifiable,
+ CreatedAt: oldKey.CreatedAt,
+ UpdatedAt: oldKey.UpdatedAt,
+ Name: oldKey.Name,
+ Key: oldKey.Token,
+ ExpiresAt: expiresAtUnix,
+ LastObservedAt: lastObservedAt,
+ ServiceAccountID: saID.String(),
+ })
+ }
+
+ if len(serviceAccounts) > 0 {
+ if _, err := tx.NewInsert().Model(&serviceAccounts).Exec(ctx); err != nil {
+ return err
+ }
+ }
+
+ if len(serviceAccountRoles) > 0 {
+ if _, err := tx.NewInsert().Model(&serviceAccountRoles).Exec(ctx); err != nil {
+ return err
+ }
+ }
+
+ sqls := [][]byte{}
+ deprecatedFactorAPIKey, _, err := migration.sqlschema.GetTable(ctx, sqlschema.TableName("factor_api_key"))
+ if err != nil {
+ return err
+ }
+
+ dropTableSQLS := migration.sqlschema.Operator().DropTable(deprecatedFactorAPIKey)
+ sqls = append(sqls, dropTableSQLS...)
+
+ tableSQLs := migration.sqlschema.Operator().CreateTable(&sqlschema.Table{
+ Name: "factor_api_key",
+ Columns: []*sqlschema.Column{
+ {Name: "id", DataType: sqlschema.DataTypeText, Nullable: false},
+ {Name: "name", DataType: sqlschema.DataTypeText, Nullable: false},
+ {Name: "key", DataType: sqlschema.DataTypeText, Nullable: false},
+ {Name: "created_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},
+ {Name: "updated_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},
+ {Name: "expires_at", DataType: sqlschema.DataTypeInteger, Nullable: false},
+ {Name: "last_observed_at", DataType: sqlschema.DataTypeTimestamp, Nullable: false},
+ {Name: "service_account_id", DataType: sqlschema.DataTypeText, Nullable: false},
+ },
+ PrimaryKeyConstraint: &sqlschema.PrimaryKeyConstraint{
+ ColumnNames: []sqlschema.ColumnName{"id"},
+ },
+ ForeignKeyConstraints: []*sqlschema.ForeignKeyConstraint{
+ {
+ ReferencingColumnName: sqlschema.ColumnName("service_account_id"),
+ ReferencedTableName: sqlschema.TableName("service_account"),
+ ReferencedColumnName: sqlschema.ColumnName("id"),
+ },
+ },
+ })
+ sqls = append(sqls, tableSQLs...)
+
+ indexSQLs := migration.sqlschema.Operator().CreateIndex(&sqlschema.UniqueIndex{TableName: "factor_api_key", ColumnNames: []sqlschema.ColumnName{"key"}})
+ sqls = append(sqls, indexSQLs...)
+
+ indexSQLs = migration.sqlschema.Operator().CreateIndex(&sqlschema.UniqueIndex{TableName: "factor_api_key", ColumnNames: []sqlschema.ColumnName{"name", "service_account_id"}})
+ sqls = append(sqls, indexSQLs...)
+
+ for _, sql := range sqls {
+ if _, err := tx.ExecContext(ctx, string(sql)); err != nil {
+ return err
+ }
+ }
+
+ if len(newKeys) > 0 {
+ if _, err := tx.NewInsert().Model(&newKeys).Exec(ctx); err != nil {
+ return err
+ }
+ }
+
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (migration *deprecateAPIKey) Down(context.Context, *bun.DB) error {
+ return nil
+}
diff --git a/pkg/sqlmigration/075_service_account_authz.go b/pkg/sqlmigration/075_service_account_authz.go
new file mode 100644
index 0000000000..14bee04aee
--- /dev/null
+++ b/pkg/sqlmigration/075_service_account_authz.go
@@ -0,0 +1,148 @@
+package sqlmigration
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/factory"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/oklog/ulid/v2"
+ "github.com/uptrace/bun"
+ "github.com/uptrace/bun/dialect"
+ "github.com/uptrace/bun/migrate"
+)
+
+type addServiceAccountAuthz struct {
+ sqlstore sqlstore.SQLStore
+}
+
+func NewServiceAccountAuthzactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
+ return factory.NewProviderFactory(factory.MustNewName("add_service_account_authz"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
+ return &addServiceAccountAuthz{sqlstore: sqlstore}, nil
+ })
+}
+
+func (migration *addServiceAccountAuthz) Register(migrations *migrate.Migrations) error {
+ if err := migrations.Register(migration.Up, migration.Down); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (migration *addServiceAccountAuthz) Up(ctx context.Context, db *bun.DB) error {
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+
+ defer func() {
+ _ = tx.Rollback()
+ }()
+
+ var storeID string
+ err = tx.QueryRowContext(ctx, `SELECT id FROM store WHERE name = ? LIMIT 1`, "signoz").Scan(&storeID)
+ if err != nil {
+ return err
+ }
+
+ type saRoleTuple struct {
+ ServiceAccountID string
+ OrgID string
+ RoleName string
+ }
+
+ rows, err := tx.QueryContext(ctx, `
+ SELECT sa.id, sa.org_id, r.name
+ FROM service_account sa
+ JOIN service_account_role sar ON sar.service_account_id = sa.id
+ JOIN role r ON r.id = sar.role_id
+ `)
+ if err != nil && err != sql.ErrNoRows {
+ return err
+ }
+ defer rows.Close()
+
+ tuples := make([]saRoleTuple, 0)
+ for rows.Next() {
+ var t saRoleTuple
+ if err := rows.Scan(&t.ServiceAccountID, &t.OrgID, &t.RoleName); err != nil {
+ return err
+ }
+ tuples = append(tuples, t)
+ }
+
+ for _, t := range tuples {
+ entropy := ulid.DefaultEntropy()
+ now := time.Now().UTC()
+ tupleID := ulid.MustNew(ulid.Timestamp(now), entropy).String()
+
+ objectID := "organization/" + t.OrgID + "/role/" + t.RoleName
+ saUserID := "organization/" + t.OrgID + "/serviceaccount/" + t.ServiceAccountID
+
+ if migration.sqlstore.BunDB().Dialect().Name() == dialect.PG {
+ result, err := tx.ExecContext(ctx, `
+ INSERT INTO tuple (store, object_type, object_id, relation, _user, user_type, ulid, inserted_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (store, object_type, object_id, relation, _user) DO NOTHING`,
+ storeID, "role", objectID, "assignee", "serviceaccount:"+saUserID, "user", tupleID, now,
+ )
+ if err != nil {
+ return err
+ }
+
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if rowsAffected == 0 {
+ continue
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ INSERT INTO changelog (store, object_type, object_id, relation, _user, operation, ulid, inserted_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (store, ulid, object_type) DO NOTHING`,
+ storeID, "role", objectID, "assignee", "serviceaccount:"+saUserID, "TUPLE_OPERATION_WRITE", tupleID, now,
+ )
+ if err != nil {
+ return err
+ }
+ } else {
+ result, err := tx.ExecContext(ctx, `
+ INSERT INTO tuple (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, user_type, ulid, inserted_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation) DO NOTHING`,
+ storeID, "role", objectID, "assignee", "serviceaccount", saUserID, "", "user", tupleID, now,
+ )
+ if err != nil {
+ return err
+ }
+
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if rowsAffected == 0 {
+ continue
+ }
+
+ _, err = tx.ExecContext(ctx, `
+ INSERT INTO changelog (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, operation, ulid, inserted_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (store, ulid, object_type) DO NOTHING`,
+ storeID, "role", objectID, "assignee", "serviceaccount", saUserID, "", 0, tupleID, now,
+ )
+ if err != nil {
+ return err
+ }
+ }
+ }
+
+ return tx.Commit()
+}
+
+func (migration *addServiceAccountAuthz) Down(context.Context, *bun.DB) error {
+ return nil
+}
diff --git a/pkg/tokenizer/jwttokenizer/claims.go b/pkg/tokenizer/jwttokenizer/claims.go
index dfa39959cb..80756f9c7d 100644
--- a/pkg/tokenizer/jwttokenizer/claims.go
+++ b/pkg/tokenizer/jwttokenizer/claims.go
@@ -2,7 +2,6 @@ package jwttokenizer
import (
"github.com/SigNoz/signoz/pkg/errors"
- "github.com/SigNoz/signoz/pkg/types"
"github.com/golang-jwt/jwt/v5"
)
@@ -10,21 +9,15 @@ var _ jwt.ClaimsValidator = (*Claims)(nil)
type Claims struct {
jwt.RegisteredClaims
- UserID string `json:"id"`
- Email string `json:"email"`
- Role types.Role `json:"role"`
- OrgID string `json:"orgId"`
+ UserID string `json:"id"`
+ Email string `json:"email"`
+ OrgID string `json:"orgId"`
}
func (c *Claims) Validate() error {
if c.UserID == "" {
return errors.New(errors.TypeUnauthenticated, errors.CodeUnauthenticated, "id is required")
}
- // The problem is that when the "role" field is missing entirely from the JSON (as opposed to being present but empty), the UnmarshalJSON method for Role isn't called at all.
- // The JSON decoder just sets the Role field to its zero value ("").
- if c.Role == "" {
- return errors.New(errors.TypeUnauthenticated, errors.CodeUnauthenticated, "role is required")
- }
if c.OrgID == "" {
return errors.New(errors.TypeUnauthenticated, errors.CodeUnauthenticated, "orgId is required")
diff --git a/pkg/tokenizer/jwttokenizer/provider.go b/pkg/tokenizer/jwttokenizer/provider.go
index 524b4d423e..86c7b00c3d 100644
--- a/pkg/tokenizer/jwttokenizer/provider.go
+++ b/pkg/tokenizer/jwttokenizer/provider.go
@@ -78,7 +78,6 @@ func (provider *provider) Start(ctx context.Context) error {
func (provider *provider) CreateToken(ctx context.Context, identity *authtypes.Identity, meta map[string]string) (*authtypes.Token, error) {
accessTokenClaims := Claims{
UserID: identity.UserID.String(),
- Role: identity.Role,
Email: identity.Email.String(),
OrgID: identity.OrgID.String(),
RegisteredClaims: jwt.RegisteredClaims{
@@ -94,7 +93,6 @@ func (provider *provider) CreateToken(ctx context.Context, identity *authtypes.I
refreshTokenClaims := Claims{
UserID: identity.UserID.String(),
- Role: identity.Role,
Email: identity.Email.String(),
OrgID: identity.OrgID.String(),
RegisteredClaims: jwt.RegisteredClaims{
@@ -117,17 +115,7 @@ func (provider *provider) GetIdentity(ctx context.Context, accessToken string) (
return nil, err
}
- // check claimed role
- identity, err := provider.getOrSetIdentity(ctx, emptyOrgID, valuer.MustNewUUID(claims.UserID))
- if err != nil {
- return nil, err
- }
-
- if identity.Role != claims.Role {
- return nil, errors.Newf(errors.TypeUnauthenticated, errors.CodeUnauthenticated, "claim role mismatch")
- }
-
- return authtypes.NewIdentity(valuer.MustNewUUID(claims.UserID), valuer.MustNewUUID(claims.OrgID), valuer.MustNewEmail(claims.Email), claims.Role, authtypes.IdentNProviderTokenizer), nil
+ return authtypes.NewPrincipalUserIdentity(valuer.MustNewUUID(claims.UserID), valuer.MustNewUUID(claims.OrgID), valuer.MustNewEmail(claims.Email), authtypes.IdentNProviderTokenizer), nil
}
func (provider *provider) DeleteToken(ctx context.Context, accessToken string) error {
diff --git a/pkg/tokenizer/jwttokenizer/provider_test.go b/pkg/tokenizer/jwttokenizer/provider_test.go
index f15da7ea8f..f583bce2f2 100644
--- a/pkg/tokenizer/jwttokenizer/provider_test.go
+++ b/pkg/tokenizer/jwttokenizer/provider_test.go
@@ -14,7 +14,6 @@ import (
"github.com/SigNoz/signoz/pkg/sqlstore/sqlstoretest"
"github.com/SigNoz/signoz/pkg/tokenizer"
"github.com/SigNoz/signoz/pkg/tokenizer/tokenizerstore/sqltokenizerstore"
- "github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/stretchr/testify/assert"
@@ -62,7 +61,6 @@ func TestLastObservedAt_Concurrent(t *testing.T) {
&authtypes.Identity{
UserID: valuer.GenerateUUID(),
OrgID: orgID,
- Role: types.RoleAdmin,
Email: valuer.MustNewEmail("[email protected]"),
},
map[string]string{},
@@ -74,7 +72,6 @@ func TestLastObservedAt_Concurrent(t *testing.T) {
&authtypes.Identity{
UserID: valuer.GenerateUUID(),
OrgID: orgID,
- Role: types.RoleAdmin,
Email: valuer.MustNewEmail("[email protected]"),
},
map[string]string{},
diff --git a/pkg/tokenizer/tokenizerstore/sqltokenizerstore/store.go b/pkg/tokenizer/tokenizerstore/sqltokenizerstore/store.go
index 2880ef3df6..0591f211ef 100644
--- a/pkg/tokenizer/tokenizerstore/sqltokenizerstore/store.go
+++ b/pkg/tokenizer/tokenizerstore/sqltokenizerstore/store.go
@@ -3,7 +3,6 @@ package sqltokenizerstore
import (
"context"
- "github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
@@ -47,25 +46,7 @@ func (store *store) GetIdentityByUserID(ctx context.Context, userID valuer.UUID)
return nil, store.sqlstore.WrapNotFoundErrf(err, types.ErrCodeUserNotFound, "user with id: %s does not exist", userID)
}
- userRoles := make([]*authtypes.UserRole, 0)
- err = store.sqlstore.
- BunDBCtx(ctx).
- NewSelect().
- Model(&userRoles).
- Where("user_id = ?", userID).
- Relation("Role").
- Scan(ctx)
- if err != nil {
- return nil, err
- }
-
- if len(userRoles) == 0 {
- return nil, errors.Newf(errors.TypeInternal, errors.CodeInternal, "no roles found for user with id: %s", userID)
- }
-
- role := authtypes.SigNozManagedRoleToExistingLegacyRole[userRoles[0].Role.Name]
-
- return authtypes.NewIdentity(userID, user.OrgID, user.Email, role, authtypes.IdentNProviderTokenizer), nil
+ return authtypes.NewPrincipalUserIdentity(userID, user.OrgID, user.Email, authtypes.IdentNProviderTokenizer), nil
}
func (store *store) GetByAccessToken(ctx context.Context, accessToken string) (*authtypes.StorableToken, error) {
diff --git a/pkg/types/authtypes/authn.go b/pkg/types/authtypes/authn.go
index 1559e032b8..c040c735b5 100644
--- a/pkg/types/authtypes/authn.go
+++ b/pkg/types/authtypes/authn.go
@@ -22,14 +22,22 @@ var (
AuthNProviderOIDC = AuthNProvider{valuer.NewString("oidc")}
)
+var (
+ PrincipalUser = Principal{valuer.NewString("user")}
+ PrincipalServiceAccount = Principal{valuer.NewString("service_account")}
+)
+
type AuthNProvider struct{ valuer.String }
+type Principal struct{ valuer.String }
+
type Identity struct {
- UserID valuer.UUID `json:"userId"`
- OrgID valuer.UUID `json:"orgId"`
- IdenNProvider IdentNProvider `json:"identNProvider"`
- Email valuer.Email `json:"email"`
- Role types.Role `json:"role"`
+ UserID valuer.UUID `json:"userId"`
+ ServiceAccountID valuer.UUID `json:"serviceAccountId"`
+ Principal Principal `json:"principal"`
+ OrgID valuer.UUID `json:"orgId"`
+ IdenNProvider IdentNProvider `json:"identNProvider"`
+ Email valuer.Email `json:"email"`
}
type CallbackIdentity struct {
@@ -79,16 +87,37 @@ func NewStateFromString(state string) (State, error) {
}, nil
}
-func NewIdentity(userID valuer.UUID, orgID valuer.UUID, email valuer.Email, role types.Role, identNProvider IdentNProvider) *Identity {
+func NewIdentity(userID valuer.UUID, serviceAccountID valuer.UUID, principal Principal, orgID valuer.UUID, email valuer.Email, identNProvider IdentNProvider) *Identity {
+ return &Identity{
+ UserID: userID,
+ ServiceAccountID: serviceAccountID,
+ Principal: principal,
+ OrgID: orgID,
+ Email: email,
+ IdenNProvider: identNProvider,
+ }
+}
+
+func NewPrincipalUserIdentity(userID valuer.UUID, orgID valuer.UUID, email valuer.Email, identNProvider IdentNProvider) *Identity {
return &Identity{
UserID: userID,
+ Principal: PrincipalUser,
OrgID: orgID,
Email: email,
- Role: role,
IdenNProvider: identNProvider,
}
}
+func NewPrincipalServiceAccountIdentity(serviceAccountID valuer.UUID, orgID valuer.UUID, email valuer.Email, identNProvider IdentNProvider) *Identity {
+ return &Identity{
+ ServiceAccountID: serviceAccountID,
+ Principal: PrincipalServiceAccount,
+ OrgID: orgID,
+ Email: email,
+ IdenNProvider: identNProvider,
+ }
+}
+
func NewCallbackIdentity(name string, email valuer.Email, orgID valuer.UUID, state State, groups []string, role string) *CallbackIdentity {
return &CallbackIdentity{
Name: name,
@@ -118,11 +147,12 @@ func (typ *Identity) UnmarshalBinary(data []byte) error {
func (typ *Identity) ToClaims() Claims {
return Claims{
- UserID: typ.UserID.String(),
- Email: typ.Email.String(),
- Role: typ.Role,
- OrgID: typ.OrgID.String(),
- IdentNProvider: typ.IdenNProvider.StringValue(),
+ UserID: typ.UserID.String(),
+ ServiceAccountID: typ.ServiceAccountID.String(),
+ Principal: typ.Principal,
+ Email: typ.Email.String(),
+ OrgID: typ.OrgID.String(),
+ IdentNProvider: typ.IdenNProvider,
}
}
diff --git a/pkg/types/authtypes/claims.go b/pkg/types/authtypes/claims.go
index bd06b64dcb..539b745a32 100644
--- a/pkg/types/authtypes/claims.go
+++ b/pkg/types/authtypes/claims.go
@@ -3,21 +3,21 @@ package authtypes
import (
"context"
"log/slog"
- "slices"
"github.com/SigNoz/signoz/pkg/errors"
- "github.com/SigNoz/signoz/pkg/types"
)
type claimsKey struct{}
type accessTokenKey struct{}
+type apiKeyKey struct{}
type Claims struct {
- UserID string
- Email string
- Role types.Role
- OrgID string
- IdentNProvider string
+ UserID string
+ ServiceAccountID string
+ Principal Principal
+ Email string
+ OrgID string
+ IdentNProvider IdentNProvider
}
// NewContextWithClaims attaches individual claims to the context.
@@ -48,38 +48,28 @@ func AccessTokenFromContext(ctx context.Context) (string, error) {
return accessToken, nil
}
-func (c *Claims) LogValue() slog.Value {
- return slog.GroupValue(
- slog.String("user_id", c.UserID),
- slog.String("email", c.Email),
- slog.String("role", c.Role.String()),
- slog.String("org_id", c.OrgID),
- slog.String("identn_provider", c.IdentNProvider),
- )
-}
-
-func (c *Claims) IsViewer() error {
- if slices.Contains([]types.Role{types.RoleViewer, types.RoleEditor, types.RoleAdmin}, c.Role) {
- return nil
- }
-
- return errors.New(errors.TypeForbidden, errors.CodeForbidden, "only viewers/editors/admins can access this resource")
+func NewContextWithAPIKey(ctx context.Context, apiKey string) context.Context {
+ return context.WithValue(ctx, apiKeyKey{}, apiKey)
}
-func (c *Claims) IsEditor() error {
- if slices.Contains([]types.Role{types.RoleEditor, types.RoleAdmin}, c.Role) {
- return nil
+func APIKeyFromContext(ctx context.Context) (string, error) {
+ apiKey, ok := ctx.Value(apiKeyKey{}).(string)
+ if !ok {
+ return "", errors.New(errors.TypeUnauthenticated, errors.CodeUnauthenticated, "unauthenticated")
}
- return errors.New(errors.TypeForbidden, errors.CodeForbidden, "only editors/admins can access this resource")
+ return apiKey, nil
}
-func (c *Claims) IsAdmin() error {
- if c.Role == types.RoleAdmin {
- return nil
- }
-
- return errors.New(errors.TypeForbidden, errors.CodeForbidden, "only admins can access this resource")
+func (c *Claims) LogValue() slog.Value {
+ return slog.GroupValue(
+ slog.String("user_id", c.UserID),
+ slog.String("service_account_id", c.ServiceAccountID),
+ slog.String("principal", c.Principal.StringValue()),
+ slog.String("email", c.Email),
+ slog.String("org_id", c.OrgID),
+ slog.String("identn_provider", c.IdentNProvider.StringValue()),
+ )
}
func (c *Claims) IsSelfAccess(id string) error {
@@ -87,9 +77,13 @@ func (c *Claims) IsSelfAccess(id string) error {
return nil
}
- if c.Role == types.RoleAdmin {
- return nil
+ return errors.New(errors.TypeForbidden, errors.CodeForbidden, "only the user/admin can access their own resource")
+}
+
+func (c *Claims) IdentityID() string {
+ if c.Principal == PrincipalUser {
+ return c.UserID
}
- return errors.New(errors.TypeForbidden, errors.CodeForbidden, "only the user/admin can access their own resource")
+ return c.ServiceAccountID
}
diff --git a/pkg/types/authtypes/role.go b/pkg/types/authtypes/role.go
index 9e39b328af..6b2b0ba2ab 100644
--- a/pkg/types/authtypes/role.go
+++ b/pkg/types/authtypes/role.go
@@ -72,12 +72,14 @@ type StorableRole struct {
}
type Role struct {
+ bun.BaseModel `bun:"table:role"`
+
types.Identifiable
types.TimeAuditable
- Name string `json:"name" required:"true"`
- Description string `json:"description" required:"true"`
- Type valuer.String `json:"type" required:"true"`
- OrgID valuer.UUID `json:"orgId" required:"true"`
+ Name string `bun:"name,type:string" json:"name" required:"true"`
+ Description string `bun:"description,type:string" json:"description" required:"true"`
+ Type valuer.String `bun:"type,type:string" json:"type" required:"true"`
+ OrgID valuer.UUID `bun:"org_id,type:string" json:"orgId" required:"true"`
}
type PostableRole struct {
diff --git a/pkg/types/dashboardtypes/dashboard.go b/pkg/types/dashboardtypes/dashboard.go
index 1d569a0469..115aedfdbf 100644
--- a/pkg/types/dashboardtypes/dashboard.go
+++ b/pkg/types/dashboardtypes/dashboard.go
@@ -285,15 +285,15 @@ func (dashboard *Dashboard) Update(ctx context.Context, updatableDashboard Updat
return nil
}
-func (dashboard *Dashboard) CanLockUnlock(role types.Role, updatedBy string) error {
- if dashboard.CreatedBy != updatedBy && role != types.RoleAdmin {
+func (dashboard *Dashboard) CanLockUnlock(isAdmin bool, updatedBy string) error {
+ if dashboard.CreatedBy != updatedBy && !isAdmin {
return errors.Newf(errors.TypeForbidden, errors.CodeForbidden, "you are not authorized to lock/unlock this dashboard")
}
return nil
}
-func (dashboard *Dashboard) LockUnlock(lock bool, role types.Role, updatedBy string) error {
- err := dashboard.CanLockUnlock(role, updatedBy)
+func (dashboard *Dashboard) LockUnlock(lock bool, isAdmin bool, updatedBy string) error {
+ err := dashboard.CanLockUnlock(isAdmin, updatedBy)
if err != nil {
return err
}
diff --git a/pkg/types/factor_api_key.go b/pkg/types/factor_api_key.go
deleted file mode 100644
index 5613400fa4..0000000000
--- a/pkg/types/factor_api_key.go
+++ /dev/null
@@ -1,144 +0,0 @@
-package types
-
-import (
- "crypto/rand"
- "encoding/base64"
- "time"
-
- "github.com/SigNoz/signoz/pkg/errors"
- "github.com/SigNoz/signoz/pkg/valuer"
- "github.com/uptrace/bun"
-)
-
-var NEVER_EXPIRES = time.Unix(0, 0)
-
-type PostableAPIKey struct {
- Name string `json:"name"`
- Role Role `json:"role"`
- ExpiresInDays int64 `json:"expiresInDays"`
-}
-
-type GettableAPIKey struct {
- Identifiable
- TimeAuditable
- UserAuditable
- Token string `json:"token"`
- Role Role `json:"role"`
- Name string `json:"name"`
- ExpiresAt int64 `json:"expiresAt"`
- LastUsed int64 `json:"lastUsed"`
- Revoked bool `json:"revoked"`
- UserID string `json:"userId"`
- CreatedByUser *User `json:"createdByUser"`
- UpdatedByUser *User `json:"updatedByUser"`
-}
-
-type OrgUserAPIKey struct {
- *Organization `bun:",extend"`
- Users []*UserWithAPIKey `bun:"rel:has-many,join:id=org_id"`
-}
-
-type UserWithAPIKey struct {
- *User `bun:",extend"`
- APIKeys []*StorableAPIKeyUser `bun:"rel:has-many,join:id=user_id"`
-}
-
-type StorableAPIKeyUser struct {
- StorableAPIKey `bun:",extend"`
-
- CreatedByUser *User `json:"createdByUser" bun:"created_by_user,rel:belongs-to,join:created_by=id"`
- UpdatedByUser *User `json:"updatedByUser" bun:"updated_by_user,rel:belongs-to,join:updated_by=id"`
-}
-
-type StorableAPIKey struct {
- bun.BaseModel `bun:"table:factor_api_key"`
-
- Identifiable
- TimeAuditable
- UserAuditable
- Token string `json:"token" bun:"token,type:text,notnull,unique"`
- Role Role `json:"role" bun:"role,type:text,notnull,default:'ADMIN'"`
- Name string `json:"name" bun:"name,type:text,notnull"`
- ExpiresAt time.Time `json:"-" bun:"expires_at,notnull,nullzero,type:timestamptz"`
- LastUsed time.Time `json:"-" bun:"last_used,notnull,nullzero,type:timestamptz"`
- Revoked bool `json:"revoked" bun:"revoked,notnull,default:false"`
- UserID valuer.UUID `json:"userId" bun:"user_id,type:text,notnull"`
-}
-
-func NewStorableAPIKey(name string, userID valuer.UUID, role Role, expiresAt int64) (*StorableAPIKey, error) {
- // validate
-
- // we allow the APIKey if expiresAt is not set, which means it never expires
- if expiresAt < 0 {
- return nil, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "expiresAt must be greater than 0")
- }
-
- if name == "" {
- return nil, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "name cannot be empty")
- }
-
- if role == "" {
- return nil, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "role cannot be empty")
- }
-
- now := time.Now()
- // convert expiresAt to unix timestamp from days
- // expiresAt = now.Unix() + (expiresAt * 24 * 60 * 60)
- expiresAtTime := now.AddDate(0, 0, int(expiresAt))
-
- // if the expiresAt is 0, it means the APIKey never expires
- if expiresAt == 0 {
- expiresAtTime = NEVER_EXPIRES
- }
-
- // Generate a 32-byte random token.
- token := make([]byte, 32)
- _, err := rand.Read(token)
- if err != nil {
- return nil, errors.New(errors.TypeInternal, errors.CodeInternal, "failed to generate token")
- }
- // Encode the token in base64.
- encodedToken := base64.StdEncoding.EncodeToString(token)
-
- return &StorableAPIKey{
- Identifiable: Identifiable{
- ID: valuer.GenerateUUID(),
- },
- TimeAuditable: TimeAuditable{
- CreatedAt: now,
- UpdatedAt: now,
- },
- UserAuditable: UserAuditable{
- CreatedBy: userID.String(),
- UpdatedBy: userID.String(),
- },
- Token: encodedToken,
- Name: name,
- Role: role,
- UserID: userID,
- ExpiresAt: expiresAtTime,
- LastUsed: now,
- Revoked: false,
- }, nil
-}
-
-func NewGettableAPIKeyFromStorableAPIKey(storableAPIKey *StorableAPIKeyUser) *GettableAPIKey {
- lastUsed := storableAPIKey.LastUsed.Unix()
- if storableAPIKey.LastUsed.Equal(storableAPIKey.CreatedAt) {
- lastUsed = 0
- }
- return &GettableAPIKey{
- Identifiable: storableAPIKey.Identifiable,
- TimeAuditable: storableAPIKey.TimeAuditable,
- UserAuditable: storableAPIKey.UserAuditable,
- Token: storableAPIKey.Token,
- Role: storableAPIKey.Role,
- Name: storableAPIKey.Name,
- ExpiresAt: storableAPIKey.ExpiresAt.Unix(),
- LastUsed: lastUsed,
- Revoked: storableAPIKey.Revoked,
- UserID: storableAPIKey.UserID.String(),
- CreatedByUser: storableAPIKey.CreatedByUser,
- UpdatedByUser: storableAPIKey.UpdatedByUser,
- }
-}
diff --git a/pkg/types/serviceaccounttypes/factor_api_key.go b/pkg/types/serviceaccounttypes/factor_api_key.go
index 05c4de74d2..5bf39b0383 100644
--- a/pkg/types/serviceaccounttypes/factor_api_key.go
+++ b/pkg/types/serviceaccounttypes/factor_api_key.go
@@ -2,6 +2,7 @@ package serviceaccounttypes
import (
"encoding/json"
+ "regexp"
"time"
"github.com/SigNoz/signoz/pkg/errors"
@@ -11,33 +12,26 @@ import (
)
var (
- 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")
+ factorAPIKeyNameRegex = regexp.MustCompile("^[a-z-]{1,80}$")
)
-type StorableFactorAPIKey struct {
- 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"`
- LastObservedAt time.Time `bun:"last_observed_at"`
- ServiceAccountID string `bun:"service_account_id"`
-}
+var (
+ ErrCodeAPIKeyInvalidInput = errors.MustNewCode("api_key_invalid_input")
+ ErrCodeAPIKeyAlreadyExists = errors.MustNewCode("api_key_already_exists")
+ ErrCodeAPIKeytNotFound = errors.MustNewCode("api_key_not_found")
+ ErrCodeAPIKeyExpired = errors.MustNewCode("api_key_expired")
+)
type FactorAPIKey struct {
+ bun.BaseModel `bun:"table:factor_api_key,alias:factor_api_key"`
+
types.Identifiable
types.TimeAuditable
- Name string `json:"name" requrired:"true"`
- Key string `json:"key" required:"true"`
- ExpiresAt uint64 `json:"expiresAt" required:"true"`
- LastObservedAt time.Time `json:"lastObservedAt" required:"true"`
- ServiceAccountID valuer.UUID `json:"serviceAccountId" required:"true"`
+ Name string `bun:"name"`
+ Key string `bun:"key"`
+ ExpiresAt uint64 `bun:"expires_at"`
+ LastObservedAt time.Time `bun:"last_observed_at"`
+ ServiceAccountID valuer.UUID `bun:"service_account_id"`
}
type GettableFactorAPIKeyWithKey struct {
@@ -64,40 +58,6 @@ type UpdatableFactorAPIKey struct {
ExpiresAt uint64 `json:"expiresAt" required:"true"`
}
-func NewFactorAPIKeyFromStorable(storable *StorableFactorAPIKey) *FactorAPIKey {
- return &FactorAPIKey{
- Identifiable: storable.Identifiable,
- TimeAuditable: storable.TimeAuditable,
- Name: storable.Name,
- Key: storable.Key,
- ExpiresAt: storable.ExpiresAt,
- LastObservedAt: storable.LastObservedAt,
- ServiceAccountID: valuer.MustNewUUID(storable.ServiceAccountID),
- }
-}
-
-func NewFactorAPIKeyFromStorables(storables []*StorableFactorAPIKey) []*FactorAPIKey {
- factorAPIKeys := make([]*FactorAPIKey, len(storables))
-
- for idx, storable := range storables {
- factorAPIKeys[idx] = NewFactorAPIKeyFromStorable(storable)
- }
-
- return factorAPIKeys
-}
-
-func NewStorableFactorAPIKey(factorAPIKey *FactorAPIKey) *StorableFactorAPIKey {
- return &StorableFactorAPIKey{
- Identifiable: factorAPIKey.Identifiable,
- TimeAuditable: factorAPIKey.TimeAuditable,
- Name: factorAPIKey.Name,
- Key: factorAPIKey.Key,
- ExpiresAt: factorAPIKey.ExpiresAt,
- LastObservedAt: factorAPIKey.LastObservedAt,
- ServiceAccountID: factorAPIKey.ServiceAccountID.String(),
- }
-}
-
func NewGettableFactorAPIKeys(keys []*FactorAPIKey) []*GettableFactorAPIKey {
gettables := make([]*GettableFactorAPIKey, len(keys))
@@ -124,10 +84,11 @@ func NewGettableFactorAPIKeyWithKey(id valuer.UUID, key string) *GettableFactorA
}
}
-func (apiKey *FactorAPIKey) Update(name string, expiresAt uint64) {
+func (apiKey *FactorAPIKey) Update(name string, expiresAt uint64) error {
apiKey.Name = name
apiKey.ExpiresAt = expiresAt
apiKey.UpdatedAt = time.Now()
+ return nil
}
func (apiKey *FactorAPIKey) IsExpired() error {
@@ -142,17 +103,6 @@ func (apiKey *FactorAPIKey) IsExpired() error {
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
@@ -161,8 +111,12 @@ func (key *PostableFactorAPIKey) UnmarshalJSON(data []byte) error {
return err
}
- if temp.Name == "" {
- return errors.New(errors.TypeInvalidInput, ErrCodeAPIkeyInvalidInput, "name cannot be empty")
+ if match := factorAPIKeyNameRegex.MatchString(temp.Name); !match {
+ return errors.Newf(errors.TypeInvalidInput, ErrCodeAPIKeyInvalidInput, "name must conform to the regex: %s", factorAPIKeyNameRegex.String())
+ }
+
+ if temp.ExpiresAt != 0 && time.Now().After(time.Unix(int64(temp.ExpiresAt), 0)) {
+ return errors.New(errors.TypeInvalidInput, ErrCodeAPIKeyInvalidInput, "cannot set api key expiry in the past")
}
*key = PostableFactorAPIKey(temp)
@@ -177,10 +131,29 @@ func (key *UpdatableFactorAPIKey) UnmarshalJSON(data []byte) error {
return err
}
- if temp.Name == "" {
- return errors.New(errors.TypeInvalidInput, ErrCodeAPIkeyInvalidInput, "name cannot be empty")
+ if match := factorAPIKeyNameRegex.MatchString(temp.Name); !match {
+ return errors.Newf(errors.TypeInvalidInput, ErrCodeAPIKeyInvalidInput, "name must conform to the regex: %s", factorAPIKeyNameRegex.String())
+ }
+
+ if temp.ExpiresAt != 0 && time.Now().After(time.Unix(int64(temp.ExpiresAt), 0)) {
+ return errors.New(errors.TypeInvalidInput, ErrCodeAPIKeyInvalidInput, "cannot set api key expiry in the past")
}
*key = UpdatableFactorAPIKey(temp)
return nil
}
+
+func (key FactorAPIKey) MarshalBinary() ([]byte, error) {
+ return json.Marshal(key)
+}
+
+func (key *FactorAPIKey) UnmarshalBinary(data []byte) error {
+ return json.Unmarshal(data, key)
+}
+
+func (key *FactorAPIKey) Traits() map[string]any {
+ return map[string]any{
+ "name": key.Name,
+ "expires_at": key.ExpiresAt,
+ }
+}
diff --git a/pkg/types/serviceaccounttypes/service_acccount.go b/pkg/types/serviceaccounttypes/service_acccount.go
index d290f10a64..84e98aa85b 100644
--- a/pkg/types/serviceaccounttypes/service_acccount.go
+++ b/pkg/types/serviceaccounttypes/service_acccount.go
@@ -1,9 +1,11 @@
package serviceaccounttypes
import (
+ "context"
"crypto/rand"
"encoding/base64"
"encoding/json"
+ "fmt"
"regexp"
"time"
@@ -15,6 +17,7 @@ import (
)
var (
+ ErrCodeServiceAccountInvalidConfig = errors.MustNewCode("service_account_invalid_config")
ErrCodeServiceAccountInvalidInput = errors.MustNewCode("service_account_invalid_input")
ErrCodeServiceAccountAlreadyExists = errors.MustNewCode("service_account_already_exists")
ErrCodeServiceAccountNotFound = errors.MustNewCode("service_account_not_found")
@@ -23,55 +26,55 @@ var (
)
var (
- StatusActive = valuer.NewString("active")
- StatusDisabled = valuer.NewString("disabled")
- ValidStatus = []valuer.String{StatusActive, StatusDisabled}
+ ServiceAccountStatusActive = ServiceAccountStatus{valuer.NewString("active")}
+ ServiceAccountStatusDeleted = ServiceAccountStatus{valuer.NewString("deleted")}
)
var (
serviceAccountNameRegex = regexp.MustCompile("^[a-z-]{1,50}$")
)
-type StorableServiceAccount struct {
+type ServiceAccountStatus struct{ valuer.String }
+
+type ServiceAccount 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"`
- DeletedAt time.Time `bun:"deleted_at"`
+ Name string `bun:"name" json:"name" required:"true"`
+ Email valuer.Email `bun:"email" json:"email" required:"true"`
+ Status ServiceAccountStatus `bun:"status" json:"status" required:"true"`
+ OrgID valuer.UUID `bun:"org_id" json:"orgId" required:"true"`
}
-type ServiceAccount struct {
+type ServiceAccountRole struct {
+ bun.BaseModel `bun:"table:service_account_role,alias:service_account_role"`
+
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"`
- DeletedAt time.Time `json:"deletedAt" required:"true"`
+ ServiceAccountID valuer.UUID `bun:"service_account_id" json:"serviceAccountId" required:"true"`
+ RoleID valuer.UUID `bun:"role_id" json:"roleId" required:"true"`
+
+ Role *authtypes.Role `bun:"rel:belongs-to,join:role_id=id" json:"role" required:"true"`
}
-type PostableServiceAccount struct {
- Name string `json:"name" required:"true"`
- Email valuer.Email `json:"email" required:"true"`
- Roles []string `json:"roles" required:"true" nullable:"false"`
+type ServiceAccountWithRoles struct {
+ *ServiceAccount `bun:",extend"`
+
+ ServiceAccountRoles []*ServiceAccountRole `bun:"rel:has-many,join:id=service_account_id" json:"serviceAccountRoles" required:"true" nullable:"true"`
}
-type UpdatableServiceAccount struct {
- Name string `json:"name" required:"true"`
- Email valuer.Email `json:"email" required:"true"`
- Roles []string `json:"roles" required:"true" nullable:"false"`
+type PostableServiceAccount struct {
+ Name string `json:"name" required:"true"`
}
-type UpdatableServiceAccountStatus struct {
- Status valuer.String `json:"status" required:"true"`
+type PostableServiceAccountRole struct {
+ ID valuer.UUID `json:"id" required:"true"`
}
-func NewServiceAccount(name string, email valuer.Email, roles []string, status valuer.String, orgID valuer.UUID) *ServiceAccount {
+type UpdatableServiceAccount = PostableServiceAccount
+
+func NewServiceAccount(name string, emailDomain string, status ServiceAccountStatus, orgID valuer.UUID) *ServiceAccount {
return &ServiceAccount{
Identifiable: types.Identifiable{
ID: valuer.GenerateUUID(),
@@ -80,101 +83,76 @@ 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,
- DeletedAt: time.Time{},
+ Name: name,
+ Email: valuer.MustNewEmail(fmt.Sprintf("%s@%s", name, emailDomain)),
+ Status: status,
+ OrgID: orgID,
}
}
-func NewServiceAccountFromStorables(storableServiceAccount *StorableServiceAccount, roles []string) *ServiceAccount {
- return &ServiceAccount{
- Identifiable: storableServiceAccount.Identifiable,
- TimeAuditable: storableServiceAccount.TimeAuditable,
- Name: storableServiceAccount.Name,
- Email: valuer.MustNewEmail(storableServiceAccount.Email),
- Roles: roles,
- Status: storableServiceAccount.Status,
- OrgID: valuer.MustNewUUID(storableServiceAccount.OrgID),
- DeletedAt: storableServiceAccount.DeletedAt,
+func NewServiceAccountWithRoles(sa *ServiceAccount, saRoles []*ServiceAccountRole) *ServiceAccountWithRoles {
+ return &ServiceAccountWithRoles{
+ ServiceAccount: sa,
+ ServiceAccountRoles: saRoles,
}
}
-func NewServiceAccountsFromRoles(storableServiceAccounts []*StorableServiceAccount, roles []*authtypes.Role, serviceAccountIDToRoleIDsMap map[string][]valuer.UUID) []*ServiceAccount {
- serviceAccounts := make([]*ServiceAccount, 0, len(storableServiceAccounts))
-
- roleIDToRole := make(map[string]*authtypes.Role, len(roles))
- for _, role := range roles {
- roleIDToRole[role.ID.String()] = role
- }
-
- for _, sa := range storableServiceAccounts {
- roleIDs := serviceAccountIDToRoleIDsMap[sa.ID.String()]
-
- roleNames := make([]string, len(roleIDs))
- for idx, rid := range roleIDs {
- if role, ok := roleIDToRole[rid.String()]; ok {
- roleNames[idx] = role.Name
- }
- }
-
- account := NewServiceAccountFromStorables(sa, roleNames)
- serviceAccounts = append(serviceAccounts, account)
+func (serviceAccount *ServiceAccount) Update(name string) error {
+ if err := serviceAccount.ErrIfDeleted(); err != nil {
+ return err
}
- return serviceAccounts
-}
-
-func NewStorableServiceAccount(serviceAccount *ServiceAccount) *StorableServiceAccount {
- return &StorableServiceAccount{
- Identifiable: serviceAccount.Identifiable,
- TimeAuditable: serviceAccount.TimeAuditable,
- Name: serviceAccount.Name,
- Email: serviceAccount.Email.String(),
- Status: serviceAccount.Status,
- OrgID: serviceAccount.OrgID.String(),
- DeletedAt: serviceAccount.DeletedAt,
- }
+ serviceAccount.Name = name
+ serviceAccount.UpdatedAt = time.Now()
+ return nil
}
-func (sa *ServiceAccount) Update(name string, email valuer.Email, roles []string) error {
- if err := sa.ErrIfDisabled(); err != nil {
+func (serviceAccount *ServiceAccount) UpdateStatus(status ServiceAccountStatus) error {
+ if err := serviceAccount.ErrIfDeleted(); err != nil {
return err
}
- sa.Name = name
- sa.Email = email
- sa.Roles = roles
- sa.UpdatedAt = time.Now()
+ serviceAccount.Status = status
+ serviceAccount.UpdatedAt = time.Now()
return nil
}
-func (sa *ServiceAccount) UpdateStatus(status valuer.String) error {
- if err := sa.ErrIfDisabled(); err != nil {
- return err
+func (serviceAccount *ServiceAccount) ErrIfDeleted() error {
+ if serviceAccount.Status == ServiceAccountStatusDeleted {
+ return errors.New(errors.TypeUnsupported, ErrCodeServiceAccountOperationUnsupported, "this operation is not supported for disabled service account")
}
- 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")
+func (serviceAccount *ServiceAccount) AddRole(role *authtypes.Role) (*ServiceAccountRole, error) {
+ if err := serviceAccount.ErrIfDeleted(); err != nil {
+ return nil, err
}
- return nil
+ return &ServiceAccountRole{
+ Identifiable: types.Identifiable{
+ ID: valuer.GenerateUUID(),
+ },
+ TimeAuditable: types.TimeAuditable{
+ CreatedAt: time.Now(),
+ UpdatedAt: time.Now(),
+ },
+ ServiceAccountID: serviceAccount.ID,
+ RoleID: role.ID,
+ Role: role,
+ }, nil
}
-func (sa *ServiceAccount) NewFactorAPIKey(name string, expiresAt uint64) (*FactorAPIKey, error) {
- if err := sa.ErrIfDisabled(); err != nil {
+func (serviceAccount *ServiceAccount) NewFactorAPIKey(name string, expiresAt uint64) (*FactorAPIKey, error) {
+ if err := serviceAccount.ErrIfDeleted(); err != nil {
return nil, err
}
+ if expiresAt != 0 && time.Now().After(time.Unix(int64(expiresAt), 0)) {
+ return nil, errors.New(errors.TypeInvalidInput, ErrCodeAPIKeyInvalidInput, "cannot set api key expiry in the past")
+ }
+
key := make([]byte, 32)
_, err := rand.Read(key)
if err != nil {
@@ -195,41 +173,39 @@ func (sa *ServiceAccount) NewFactorAPIKey(name string, expiresAt uint64) (*Facto
Key: encodedKey,
ExpiresAt: expiresAt,
LastObservedAt: time.Now(),
- ServiceAccountID: sa.ID,
+ ServiceAccountID: serviceAccount.ID,
}, nil
}
-func (sa *ServiceAccount) PatchRoles(input *ServiceAccount) ([]string, []string) {
- currentRolesSet := make(map[string]struct{}, len(sa.Roles))
- inputRolesSet := make(map[string]struct{}, len(input.Roles))
-
- for _, role := range sa.Roles {
- currentRolesSet[role] = struct{}{}
- }
- for _, role := range input.Roles {
- inputRolesSet[role] = struct{}{}
+func (serviceAccount *ServiceAccount) ToIdentity() *authtypes.Identity {
+ return &authtypes.Identity{
+ ServiceAccountID: serviceAccount.ID,
+ Principal: authtypes.PrincipalServiceAccount,
+ OrgID: serviceAccount.OrgID,
+ IdenNProvider: authtypes.IdentNProviderAPIKey,
+ Email: serviceAccount.Email,
}
+}
- // additions: roles present in input but not in current
- additions := []string{}
- for _, role := range input.Roles {
- if _, exists := currentRolesSet[role]; !exists {
- additions = append(additions, role)
- }
+func (serviceAccount *ServiceAccount) Traits() map[string]any {
+ return map[string]any{
+ "name": serviceAccount.Name,
+ "email": serviceAccount.Email.String(),
+ "created_at": serviceAccount.CreatedAt,
+ "status": serviceAccount.Status.StringValue(),
}
+}
- // deletions: roles present in current but not in input
- deletions := []string{}
- for _, role := range sa.Roles {
- if _, exists := inputRolesSet[role]; !exists {
- deletions = append(deletions, role)
- }
+func (serviceAccount *ServiceAccountWithRoles) RoleNames() []string {
+ names := []string{}
+ for _, role := range serviceAccount.ServiceAccountRoles {
+ names = append(names, role.Role.Name)
}
- return additions, deletions
+ return names
}
-func (sa *PostableServiceAccount) UnmarshalJSON(data []byte) error {
+func (serviceAccount *PostableServiceAccount) UnmarshalJSON(data []byte) error {
type Alias PostableServiceAccount
var temp Alias
@@ -241,46 +217,45 @@ func (sa *PostableServiceAccount) UnmarshalJSON(data []byte) error {
return errors.Newf(errors.TypeInvalidInput, ErrCodeServiceAccountInvalidInput, "name must conform to the regex: %s", serviceAccountNameRegex.String())
}
- if len(temp.Roles) == 0 {
- return errors.New(errors.TypeInvalidInput, ErrCodeServiceAccountInvalidInput, "roles cannot be empty")
- }
-
- *sa = PostableServiceAccount(temp)
+ *serviceAccount = PostableServiceAccount(temp)
return nil
}
-func (sa *UpdatableServiceAccount) UnmarshalJSON(data []byte) error {
- type Alias UpdatableServiceAccount
-
- var temp Alias
- if err := json.Unmarshal(data, &temp); err != nil {
- return err
- }
-
- 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 {
- return errors.New(errors.TypeInvalidInput, ErrCodeServiceAccountInvalidInput, "roles cannot be empty")
+func (serviceAccount *ServiceAccountWithRoles) GetRoles() []*authtypes.Role {
+ roles := make([]*authtypes.Role, len(serviceAccount.ServiceAccountRoles))
+ for idx, serviceAccountRole := range serviceAccount.ServiceAccountRoles {
+ roles[idx] = serviceAccountRole.Role
}
- *sa = UpdatableServiceAccount(temp)
- return nil
+ return roles
}
-func (sa *UpdatableServiceAccountStatus) UnmarshalJSON(data []byte) error {
- type Alias UpdatableServiceAccountStatus
-
- var temp Alias
- if err := json.Unmarshal(data, &temp); err != nil {
- return err
- }
-
- if temp.Status != StatusDisabled {
- return errors.Newf(errors.TypeInvalidInput, ErrCodeServiceAccountInvalidInput, "invalid status: %s, allowed status are: %v", temp.Status, StatusDisabled)
- }
-
- *sa = UpdatableServiceAccountStatus(temp)
- return nil
+type Store interface {
+ // Service Account
+ Create(context.Context, *ServiceAccount) error
+ GetWithRoles(context.Context, valuer.UUID, valuer.UUID) (*ServiceAccountWithRoles, error)
+ Get(context.Context, valuer.UUID, valuer.UUID) (*ServiceAccount, error)
+ GetActiveByOrgIDAndName(context.Context, valuer.UUID, string) (*ServiceAccount, error)
+ GetByID(context.Context, valuer.UUID) (*ServiceAccount, error)
+ CountByOrgID(context.Context, valuer.UUID) (int64, error)
+ List(context.Context, valuer.UUID) ([]*ServiceAccount, error)
+ Update(context.Context, valuer.UUID, *ServiceAccount) error
+
+ // Service Account Role
+ CreateServiceAccountRole(context.Context, *ServiceAccountRole) error
+ DeleteServiceAccountRole(context.Context, valuer.UUID, valuer.UUID) error
+
+ // Service Account Factor API Key
+ CreateFactorAPIKey(context.Context, *FactorAPIKey) error
+ GetFactorAPIKey(context.Context, valuer.UUID, valuer.UUID) (*FactorAPIKey, error)
+ GetFactorAPIKeyByName(context.Context, valuer.UUID, string) (*FactorAPIKey, error)
+ GetFactorAPIKeyByKey(context.Context, string) (*FactorAPIKey, error)
+ CountFactorAPIKeysByOrgID(context.Context, valuer.UUID) (int64, error)
+ ListFactorAPIKey(context.Context, valuer.UUID) ([]*FactorAPIKey, error)
+ UpdateFactorAPIKey(context.Context, valuer.UUID, *FactorAPIKey) error
+ UpdateLastObservedAt(context.Context, string, time.Time) error
+ RevokeFactorAPIKey(context.Context, valuer.UUID, valuer.UUID) error
+ RevokeAllFactorAPIKeys(context.Context, valuer.UUID) error
+
+ RunInTx(context.Context, func(context.Context) error) error
}
diff --git a/pkg/types/serviceaccounttypes/service_account_role.go b/pkg/types/serviceaccounttypes/service_account_role.go
deleted file mode 100644
index 79a752633c..0000000000
--- a/pkg/types/serviceaccounttypes/service_account_role.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package serviceaccounttypes
-
-import (
- "time"
-
- "github.com/SigNoz/signoz/pkg/errors"
- "github.com/SigNoz/signoz/pkg/types"
- "github.com/SigNoz/signoz/pkg/types/authtypes"
- "github.com/SigNoz/signoz/pkg/valuer"
- "github.com/uptrace/bun"
-)
-
-type StorableServiceAccountRole struct {
- bun.BaseModel `bun:"table:service_account_role,alias:service_account_role"`
-
- types.Identifiable
- types.TimeAuditable
- ServiceAccountID string `bun:"service_account_id"`
- RoleID string `bun:"role_id"`
-}
-
-func NewStorableServiceAccountRoles(serviceAccountID valuer.UUID, roles []*authtypes.Role) []*StorableServiceAccountRole {
- storableServiceAccountRoles := make([]*StorableServiceAccountRole, len(roles))
- for idx, role := range roles {
- storableServiceAccountRoles[idx] = &StorableServiceAccountRole{
- Identifiable: types.Identifiable{
- ID: valuer.GenerateUUID(),
- },
- TimeAuditable: types.TimeAuditable{
- CreatedAt: time.Now(),
- UpdatedAt: time.Now(),
- },
- ServiceAccountID: serviceAccountID.String(),
- RoleID: role.ID.String(),
- }
- }
-
- return storableServiceAccountRoles
-}
-
-func NewRolesFromStorableServiceAccountRoles(storable []*StorableServiceAccountRole, roles []*authtypes.Role) ([]string, error) {
- roleIDToName := make(map[string]string, len(roles))
- for _, role := range roles {
- roleIDToName[role.ID.String()] = role.Name
- }
-
- names := make([]string, 0, len(storable))
- for _, sar := range storable {
- roleName, ok := roleIDToName[sar.RoleID]
- if !ok {
- return nil, errors.Newf(errors.TypeInternal, errors.CodeInternal, "role id %s not found in provided roles", sar.RoleID)
- }
- names = append(names, roleName)
- }
-
- return names, nil
-}
-
-func GetUniqueRolesAndServiceAccountMapping(storableServiceAccountRoles []*StorableServiceAccountRole) (map[string][]valuer.UUID, []valuer.UUID) {
- serviceAccountIDRoles := make(map[string][]valuer.UUID)
- uniqueRoleIDSet := make(map[string]struct{})
-
- for _, sar := range storableServiceAccountRoles {
- saID := sar.ServiceAccountID
- roleID := sar.RoleID
- if _, ok := serviceAccountIDRoles[saID]; !ok {
- serviceAccountIDRoles[saID] = make([]valuer.UUID, 0)
- }
-
- roleUUID := valuer.MustNewUUID(roleID)
- serviceAccountIDRoles[saID] = append(serviceAccountIDRoles[saID], roleUUID)
- uniqueRoleIDSet[roleID] = struct{}{}
- }
-
- roleIDs := make([]valuer.UUID, 0, len(uniqueRoleIDSet))
- for rid := range uniqueRoleIDSet {
- roleIDs = append(roleIDs, valuer.MustNewUUID(rid))
- }
-
- return serviceAccountIDRoles, roleIDs
-}
diff --git a/pkg/types/serviceaccounttypes/store.go b/pkg/types/serviceaccounttypes/store.go
deleted file mode 100644
index 64d9b9f108..0000000000
--- a/pkg/types/serviceaccounttypes/store.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package serviceaccounttypes
-
-import (
- "context"
-
- "github.com/SigNoz/signoz/pkg/valuer"
-)
-
-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
- Delete(context.Context, valuer.UUID, valuer.UUID) error
-
- // Service Account Role
- CreateServiceAccountRoles(context.Context, []*StorableServiceAccountRole) error
- GetServiceAccountRoles(context.Context, valuer.UUID) ([]*StorableServiceAccountRole, error)
- ListServiceAccountRolesByOrgID(context.Context, valuer.UUID) ([]*StorableServiceAccountRole, error)
- DeleteServiceAccountRoles(context.Context, valuer.UUID) error
-
- // Service Account Factor API Key
- CreateFactorAPIKey(context.Context, *StorableFactorAPIKey) error
- GetFactorAPIKey(context.Context, valuer.UUID, valuer.UUID) (*StorableFactorAPIKey, error)
- ListFactorAPIKey(context.Context, valuer.UUID) ([]*StorableFactorAPIKey, error)
- UpdateFactorAPIKey(context.Context, valuer.UUID, *StorableFactorAPIKey) error
- RevokeFactorAPIKey(context.Context, valuer.UUID, valuer.UUID) error
- RevokeAllFactorAPIKeys(context.Context, valuer.UUID) error
-
- RunInTx(context.Context, func(context.Context) error) error
-}
diff --git a/pkg/types/user.go b/pkg/types/user.go
index 72f07631e9..582319580a 100644
--- a/pkg/types/user.go
+++ b/pkg/types/user.go
@@ -289,14 +289,6 @@ type UserStore interface {
DeleteResetPasswordTokenByPasswordID(ctx context.Context, passwordID valuer.UUID) error
UpdatePassword(ctx context.Context, password *FactorPassword) error
- // API KEY
- CreateAPIKey(ctx context.Context, apiKey *StorableAPIKey) error
- UpdateAPIKey(ctx context.Context, id valuer.UUID, apiKey *StorableAPIKey, updaterID valuer.UUID) error
- ListAPIKeys(ctx context.Context, orgID valuer.UUID) ([]*StorableAPIKeyUser, error)
- RevokeAPIKey(ctx context.Context, id valuer.UUID, revokedByUserID valuer.UUID) error
- GetAPIKey(ctx context.Context, orgID, id valuer.UUID) (*StorableAPIKeyUser, error)
- CountAPIKeyByOrgID(ctx context.Context, orgID valuer.UUID) (int64, error)
-
CountByOrgID(ctx context.Context, orgID valuer.UUID) (int64, error)
CountByOrgIDAndStatuses(ctx context.Context, orgID valuer.UUID, statuses []string) (map[valuer.String]int64, error)
diff --git a/templates/email/api_key_event.gotmpl b/templates/email/api_key_event.gotmpl
deleted file mode 100644
index c788f080e1..0000000000
--- a/templates/email/api_key_event.gotmpl
+++ /dev/null
@@ -1,88 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <title>{{.subject}}</title>
-</head>
-
-<body style="margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;line-height:1.6;color:#333;background:#fff">
- <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background:#fff">
- <tr>
- <td align="center" style="padding:0">
- <table role="presentation" width="600" cellspacing="0" cellpadding="0" border="0" style="max-width:600px;width:100%">
- {{ if .format.Header.Enabled }}
- <tr>
- <td align="center" style="padding:16px 20px 16px">
- <img src="{{.format.Header.LogoURL}}" alt="SigNoz" width="160" height="40" style="display:block;border:0;outline:none;max-width:100%;height:auto">
- </td>
- </tr>
- {{ end }}
- <tr>
- <td style="padding:16px 20px 16px">
- <p style="margin:0 0 16px;font-size:16px;color:#333">
- Hi there,
- </p>
- <p style="margin:0 0 16px;font-size:16px;color:#333;line-height:1.6">
- An API key was {{.Event}} for your service account <strong>{{.Name}}</strong>.
- </p>
- <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="margin:0 0 16px">
- <tr>
- <td style="padding:20px;background:#f5f5f5;border-radius:6px;border-left:4px solid #4E74F8">
- <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0">
- <tr>
- <td style="padding:0 0 8px">
- <p style="margin:0;font-size:15px;color:#333;line-height:1.6">
- <strong>Key ID:</strong> {{.KeyID}}
- </p>
- </td>
- </tr>
- <tr>
- <td style="padding:0 0 8px">
- <p style="margin:0;font-size:15px;color:#333;line-height:1.6">
- <strong>Key Name:</strong> {{.KeyName}}
- </p>
- </td>
- </tr>
- <tr>
- <td style="padding:0 0 8px">
- <p style="margin:0;font-size:15px;color:#333;line-height:1.6">
- <strong>Created At:</strong> {{.KeyCreatedAt}}
- </p>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
- {{ if .format.Help.Enabled }}
- <p style="margin:0 0 16px;font-size:16px;color:#333;line-height:1.6">
- Need help? Chat with our team in the SigNoz application or email us at <a href="mailto:{{.format.Help.Email}}" style="color:#4E74F8;text-decoration:none">{{.format.Help.Email}}</a>.
- </p>
- {{ end }}
- <p style="margin:0;font-size:16px;color:#333;line-height:1.6">
- Thanks,<br><strong>The SigNoz Team</strong>
- </p>
- </td>
- </tr>
- {{ if .format.Footer.Enabled }}
- <tr>
- <td align="center" style="padding:8px 16px 8px">
- <p style="margin:0 0 8px;font-size:12px;color:#999;line-height:1.5">
- <a href="https://signoz.io/terms-of-service/" style="color:#4E74F8;text-decoration:none">Terms of Service</a> - <a href="https://signoz.io/privacy/" style="color:#4E74F8;text-decoration:none">Privacy Policy</a>
- </p>
- <p style="margin:0;font-size:12px;color:#999;line-height:1.5">
- &#169; 2026 SigNoz Inc.
- </p>
- </td>
- </tr>
- {{ end }}
- </table>
- </td>
- </tr>
- </table>
-</body>
-
-</html>
\ No newline at end of file
diff --git a/tests/integration/fixtures/serviceaccount.py b/tests/integration/fixtures/serviceaccount.py
new file mode 100644
index 0000000000..9a21bd6691
--- /dev/null
+++ b/tests/integration/fixtures/serviceaccount.py
@@ -0,0 +1,102 @@
+"""Fixtures and helpers for service account tests."""
+
+from http import HTTPStatus
+
+import requests
+
+from fixtures import types
+from fixtures.logger import setup_logger
+
+logger = setup_logger(__name__)
+
+SERVICE_ACCOUNT_BASE = "/api/v1/service_accounts"
+ROLES_BASE = "/api/v1/roles"
+
+
+def find_role_by_name(signoz: types.SigNoz, token: str, name: str) -> str:
+ """Find a role by name from the roles endpoint and return its UUID."""
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get(ROLES_BASE),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert resp.status_code == HTTPStatus.OK, resp.text
+ roles = resp.json()["data"]
+ role = next(r for r in roles if r["name"] == name)
+ return role["id"]
+
+
+def create_service_account(
+ signoz: types.SigNoz, token: str, name: str, role: str = "signoz-viewer"
+) -> str:
+ """Create a service account, assign a role, and return its ID."""
+ resp = requests.post(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ json={"name": name},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert resp.status_code == HTTPStatus.CREATED, resp.text
+ service_account_id = resp.json()["data"]["id"]
+
+ role_id = find_role_by_name(signoz, token, role)
+ role_resp = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles"
+ ),
+ json={"id": role_id},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert role_resp.status_code == HTTPStatus.NO_CONTENT, role_resp.text
+
+ return service_account_id
+
+
+def create_service_account_with_key(
+ signoz: types.SigNoz, token: str, name: str, role: str = "signoz-admin"
+) -> tuple:
+ """Create a service account with an API key and return (service_account_id, api_key)."""
+ service_account_id = create_service_account(signoz, token, name, role)
+
+ key_resp = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"
+ ),
+ json={"name": "auth-key", "expiresAt": 0},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert key_resp.status_code == HTTPStatus.CREATED, key_resp.text
+ api_key = key_resp.json()["data"]["key"]
+
+ return service_account_id, api_key
+
+
+def delete_service_account(
+ signoz: types.SigNoz, token: str, service_account_id: str
+) -> None:
+ """Soft-delete a service account."""
+ resp = requests.delete(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert resp.status_code == HTTPStatus.NO_CONTENT, resp.text
+
+
+def find_service_account_by_name(signoz: types.SigNoz, token: str, name: str) -> dict:
+ """Find a service account by name from the list endpoint."""
+ list_resp = requests.get(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert list_resp.status_code == HTTPStatus.OK, list_resp.text
+ return next(
+ service_account
+ for service_account in list_resp.json()["data"]
+ if service_account["name"] == name
+ )
diff --git a/tests/integration/src/cloudintegrations/01_get_connection_params.py b/tests/integration/src/cloudintegrations/01_get_connection_params.py
index e2f7571a06..66ce3fe355 100644
--- a/tests/integration/src/cloudintegrations/01_get_connection_params.py
+++ b/tests/integration/src/cloudintegrations/01_get_connection_params.py
@@ -159,3 +159,37 @@ def test_generate_connection_params(
assert (
data["signoz_api_url"] == "https://test-deployment.test.signoz.cloud"
), "signoz_api_url should be https://test-deployment.test.signoz.cloud"
+
+ # Verify the integration service account was created with viewer role, not admin.
+ # This guards against a privilege-escalation regression where the SA was
+ # previously created with admin access.
+ sa_list = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/service_accounts"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert sa_list.status_code == HTTPStatus.OK
+
+ integration_sa = next(
+ (sa for sa in sa_list.json()["data"] if sa["name"] == "integration"),
+ None,
+ )
+ assert integration_sa is not None, "Integration service account should exist"
+
+ # Fetch roles via the dedicated roles endpoint
+ roles_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"/api/v1/service_accounts/{integration_sa['id']}/roles"
+ ),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert roles_resp.status_code == HTTPStatus.OK, roles_resp.text
+ role_names = [role["name"] for role in roles_resp.json()["data"]]
+
+ assert (
+ "signoz-viewer" in role_names
+ ), f"Integration SA should have VIEWER role, got {role_names}"
+ assert (
+ "signoz-admin" not in role_names
+ ), f"Integration SA must NOT have ADMIN role, got {role_names}"
diff --git a/tests/integration/src/passwordauthn/03_apikey.py b/tests/integration/src/passwordauthn/03_apikey.py
deleted file mode 100644
index c5473f3ed4..0000000000
--- a/tests/integration/src/passwordauthn/03_apikey.py
+++ /dev/null
@@ -1,117 +0,0 @@
-from http import HTTPStatus
-from typing import Callable
-
-import requests
-
-from fixtures import types
-
-
-def test_api_key(signoz: types.SigNoz, get_token: Callable[[str, str], str]) -> None:
- admin_token = get_token("[email protected]", "password123Z$")
-
- response = requests.post(
- signoz.self.host_configs["8080"].get("/api/v1/pats"),
- headers={"Authorization": f"Bearer {admin_token}"},
- json={
- "name": "admin",
- "role": "ADMIN",
- "expiresInDays": 1,
- },
- timeout=2,
- )
-
- assert response.status_code == HTTPStatus.CREATED
- pat_response = response.json()
- assert "data" in pat_response
- assert "token" in pat_response["data"]
-
- response = requests.get(
- signoz.self.host_configs["8080"].get("/api/v1/user"),
- timeout=2,
- headers={"SIGNOZ-API-KEY": f"{pat_response["data"]["token"]}"},
- )
-
- assert response.status_code == HTTPStatus.OK
-
- user_response = response.json()
- found_user = next(
- (
- user
- for user in user_response["data"]
- if user["email"] == "[email protected]"
- ),
- None,
- )
-
- response = requests.get(
- signoz.self.host_configs["8080"].get("/api/v1/pats"),
- headers={"SIGNOZ-API-KEY": f"{pat_response["data"]["token"]}"},
- timeout=2,
- )
-
- assert response.status_code == HTTPStatus.OK
- assert "data" in response.json()
-
- found_pat = next(
- (pat for pat in response.json()["data"] if pat["userId"] == found_user["id"]),
- None,
- )
-
- assert found_pat is not None
- assert found_pat["userId"] == found_user["id"]
- assert found_pat["name"] == "admin"
- assert found_pat["role"] == "ADMIN"
-
-
-def test_api_key_role(
- signoz: types.SigNoz, get_token: Callable[[str, str], str]
-) -> None:
- admin_token = get_token("[email protected]", "password123Z$")
-
- response = requests.post(
- signoz.self.host_configs["8080"].get("/api/v1/pats"),
- headers={"Authorization": f"Bearer {admin_token}"},
- json={
- "name": "viewer",
- "role": "VIEWER",
- "expiresInDays": 1,
- },
- timeout=2,
- )
-
- assert response.status_code == HTTPStatus.CREATED
- pat_response = response.json()
- assert "data" in pat_response
- assert "token" in pat_response["data"]
-
- response = requests.get(
- signoz.self.host_configs["8080"].get("/api/v1/user"),
- timeout=2,
- headers={"SIGNOZ-API-KEY": f"{pat_response["data"]["token"]}"},
- )
-
- assert response.status_code == HTTPStatus.FORBIDDEN
-
- response = requests.post(
- signoz.self.host_configs["8080"].get("/api/v1/pats"),
- headers={"Authorization": f"Bearer {admin_token}"},
- json={
- "name": "editor",
- "role": "EDITOR",
- "expiresInDays": 1,
- },
- timeout=2,
- )
-
- assert response.status_code == HTTPStatus.CREATED
- pat_response = response.json()
- assert "data" in pat_response
- assert "token" in pat_response["data"]
-
- response = requests.get(
- signoz.self.host_configs["8080"].get("/api/v1/user"),
- timeout=2,
- headers={"SIGNOZ-API-KEY": f"{pat_response["data"]["token"]}"},
- )
-
- assert response.status_code == HTTPStatus.FORBIDDEN
diff --git a/tests/integration/src/passwordauthn/04_password.py b/tests/integration/src/passwordauthn/03_password.py
similarity index 100%
rename from tests/integration/src/passwordauthn/04_password.py
rename to tests/integration/src/passwordauthn/03_password.py
diff --git a/tests/integration/src/passwordauthn/05_role.py b/tests/integration/src/passwordauthn/04_role.py
similarity index 75%
rename from tests/integration/src/passwordauthn/05_role.py
rename to tests/integration/src/passwordauthn/04_role.py
index e065b7e066..af0ec92bac 100644
--- a/tests/integration/src/passwordauthn/05_role.py
+++ b/tests/integration/src/passwordauthn/04_role.py
@@ -1,5 +1,5 @@
from http import HTTPStatus
-from typing import Callable, Tuple
+from typing import Callable
import requests
@@ -9,7 +9,6 @@ from fixtures import types
def test_change_role(
signoz: types.SigNoz,
get_token: Callable[[str, str], str],
- get_tokens: Callable[[str, str], Tuple[str, str]],
):
admin_token = get_token("[email protected]", "password123Z$")
@@ -35,9 +34,7 @@ def test_change_role(
assert response.status_code == HTTPStatus.NO_CONTENT
# Make some API calls as new user
- new_user_token, new_user_refresh_token = get_tokens(
- "[email protected]", "password123Z$"
- )
+ new_user_token = get_token("[email protected]", "password123Z$")
response = requests.get(
signoz.self.host_configs["8080"].get("/api/v1/user/me"),
@@ -78,27 +75,8 @@ def test_change_role(
headers={"Authorization": f"Bearer {new_user_token}"},
)
- assert response.status_code == HTTPStatus.UNAUTHORIZED
-
- # Rotate token for new user
- response = requests.post(
- signoz.self.host_configs["8080"].get("/api/v2/sessions/rotate"),
- json={
- "refreshToken": new_user_refresh_token,
- },
- headers={"Authorization": f"Bearer {new_user_token}"},
- timeout=2,
- )
-
assert response.status_code == HTTPStatus.OK
- # Make some API call again which is protected
- rotate_response = response.json()["data"]
- new_user_token, new_user_refresh_token = (
- rotate_response["accessToken"],
- rotate_response["refreshToken"],
- )
-
response = requests.get(
signoz.self.host_configs["8080"].get("/api/v1/org/preferences"),
timeout=2,
diff --git a/tests/integration/src/passwordauthn/06_duplicate_invite.py b/tests/integration/src/passwordauthn/05_duplicate_invite.py
similarity index 100%
rename from tests/integration/src/passwordauthn/06_duplicate_invite.py
rename to tests/integration/src/passwordauthn/05_duplicate_invite.py
diff --git a/tests/integration/src/passwordauthn/07_invite_status.py b/tests/integration/src/passwordauthn/06_invite_status.py
similarity index 100%
rename from tests/integration/src/passwordauthn/07_invite_status.py
rename to tests/integration/src/passwordauthn/06_invite_status.py
diff --git a/tests/integration/src/passwordauthn/08_user_unique_index.py b/tests/integration/src/passwordauthn/07_user_unique_index.py
similarity index 100%
rename from tests/integration/src/passwordauthn/08_user_unique_index.py
rename to tests/integration/src/passwordauthn/07_user_unique_index.py
diff --git a/tests/integration/src/serviceaccount/01_crud.py b/tests/integration/src/serviceaccount/01_crud.py
new file mode 100644
index 0000000000..8226f11a2e
--- /dev/null
+++ b/tests/integration/src/serviceaccount/01_crud.py
@@ -0,0 +1,244 @@
+from http import HTTPStatus
+from typing import Callable
+
+import requests
+
+from fixtures import types
+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
+from fixtures.logger import setup_logger
+from fixtures.serviceaccount import (
+ SERVICE_ACCOUNT_BASE,
+ create_service_account,
+ delete_service_account,
+ find_service_account_by_name,
+)
+
+logger = setup_logger(__name__)
+
+
+def test_create_service_account(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ json={"name": "test-sa"},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ data = response.json()["data"]
+ assert "id" in data
+ assert len(data["id"]) > 0
+
+
+def test_create_service_account_invalid_name(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ # name with spaces should be rejected
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ json={"name": "invalid name"},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
+
+
+def test_create_service_account_missing_name(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Creating a service account with an empty name should be rejected."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ json={"name": ""},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
+
+
+def test_list_service_accounts(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.OK, response.text
+ data = response.json()["data"]
+ assert isinstance(data, list)
+
+ # should contain the SA we created in the earlier test
+ names = [service_account["name"] for service_account in data]
+ assert "test-sa" in names
+
+
+def test_get_service_account(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account = find_service_account_by_name(signoz, token, "test-sa")
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account['id']}"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.OK, response.text
+ data = response.json()["data"]
+ assert data["id"] == service_account["id"]
+ assert data["name"] == "test-sa"
+ assert data["status"] == "active"
+ assert "email" in data
+ assert "serviceAccountRoles" in data
+
+
+def test_get_service_account_not_found(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/00000000-0000-0000-0000-000000000000"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.NOT_FOUND, response.text
+
+
+def test_update_service_account(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account = find_service_account_by_name(signoz, token, "test-sa")
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account['id']}"
+ ),
+ json={"name": "test-sa-updated"},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+ # verify the update
+ get_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account['id']}"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert get_resp.json()["data"]["name"] == "test-sa-updated"
+
+
+def test_delete_service_account(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(signoz, token, "sa-to-disable")
+
+ delete_service_account(signoz, token, service_account_id)
+
+ # verify status changed to deleted
+ get_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert get_resp.json()["data"]["status"] == "deleted"
+
+
+def test_create_after_delete_reuses_name(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """The partial unique index on (name, org_id) excludes deleted rows,
+ so create → delete → create with the same name must succeed."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_name = "sa-reuse-name"
+
+ # 1. create
+ first_id = create_service_account(signoz, token, service_account_name)
+
+ # 2. creating again with the same name should fail (conflict)
+ dup_resp = requests.post(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ json={"name": service_account_name},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert dup_resp.status_code == HTTPStatus.CONFLICT, dup_resp.text
+
+ # 3. soft-delete the first one
+ delete_service_account(signoz, token, first_id)
+
+ # 4. now creating with the same name should succeed
+ second_id = create_service_account(signoz, token, service_account_name)
+ assert second_id != first_id, "New SA should have a different ID"
+
+
+def test_delete_already_deleted_service_account(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Deleting an already-deleted service account should be handled gracefully."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(signoz, token, "sa-double-delete")
+
+ # first delete
+ delete_service_account(signoz, token, service_account_id)
+
+ # second delete should be handled gracefully (idempotent or error)
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert (
+ response.status_code == HTTPStatus.NOT_IMPLEMENTED
+ ), f"Expected 501 for already-deleted SA, got {response.status_code}: {response.text}"
diff --git a/tests/integration/src/serviceaccount/02_keys.py b/tests/integration/src/serviceaccount/02_keys.py
new file mode 100644
index 0000000000..5c5a71d77c
--- /dev/null
+++ b/tests/integration/src/serviceaccount/02_keys.py
@@ -0,0 +1,300 @@
+import time
+from http import HTTPStatus
+from typing import Callable
+
+import requests
+
+from fixtures import types
+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
+from fixtures.logger import setup_logger
+from fixtures.serviceaccount import (
+ SERVICE_ACCOUNT_BASE,
+ create_service_account,
+ find_service_account_by_name,
+)
+
+logger = setup_logger(__name__)
+
+
+def test_create_api_key(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(signoz, token, "sa-for-keys")
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"
+ ),
+ json={"name": "my-key", "expiresAt": 0},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ data = response.json()["data"]
+ assert "id" in data
+ assert "key" in data
+ assert len(data["key"]) > 0
+
+
+def test_create_api_key_duplicate_name(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account = find_service_account_by_name(signoz, token, "sa-for-keys")
+
+ # creating a key with the same name should fail
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account['id']}/keys"
+ ),
+ json={"name": "my-key", "expiresAt": 0},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.CONFLICT, response.text
+
+
+def test_list_api_keys(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account = find_service_account_by_name(signoz, token, "sa-for-keys")
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account['id']}/keys"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.OK, response.text
+ data = response.json()["data"]
+ assert isinstance(data, list)
+ assert len(data) >= 1
+
+ key_entry = data[0]
+ assert "id" in key_entry
+ assert "name" in key_entry
+ assert key_entry["name"] == "my-key"
+
+
+def test_update_api_key(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account = find_service_account_by_name(signoz, token, "sa-for-keys")
+
+ keys_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account['id']}/keys"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ key_id = keys_resp.json()["data"][0]["id"]
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account['id']}/keys/{key_id}"
+ ),
+ json={"name": "renamed-key", "expiresAt": 0},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+
+def test_revoke_api_key(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(signoz, token, "sa-revoke-key")
+
+ create_resp = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"
+ ),
+ json={"name": "key-to-revoke", "expiresAt": 0},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert create_resp.status_code == HTTPStatus.CREATED
+ key_id = create_resp.json()["data"]["id"]
+
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys/{key_id}"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+
+def test_create_api_key_with_expiry(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Key created with a future expiresAt should be usable."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(signoz, token, "sa-key-expiry")
+
+ future_ts = int(time.time()) + 3600 # 1 hour from now
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"
+ ),
+ json={"name": "future-key", "expiresAt": future_ts},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ api_key = response.json()["data"]["key"]
+
+ # key should work since it hasn't expired
+ dash_resp = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert dash_resp.status_code == HTTPStatus.OK, dash_resp.text
+
+ # verify expiresAt is stored correctly
+ keys_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ key_entry = next(k for k in keys_resp.json()["data"] if k["name"] == "future-key")
+ assert key_entry["expiresAt"] == future_ts
+
+
+def test_create_api_key_with_past_expiry_rejected(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Creating a key with an already-past expiresAt should be rejected."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(signoz, token, "sa-key-past-expiry")
+
+ past_ts = int(time.time()) - 60 # 1 minute ago
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"
+ ),
+ json={"name": "expired-key", "expiresAt": past_ts},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert (
+ response.status_code == HTTPStatus.BAD_REQUEST
+ ), f"Expected 400 for past expiresAt, got {response.status_code}: {response.text}"
+
+
+def test_create_api_key_no_expiry(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Key with expiresAt=0 should never expire."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(signoz, token, "sa-key-no-expiry")
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"
+ ),
+ json={"name": "forever-key", "expiresAt": 0},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ api_key = response.json()["data"]["key"]
+
+ dash_resp = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert dash_resp.status_code == HTTPStatus.OK, dash_resp.text
+
+ # verify expiresAt is 0
+ keys_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ key_entry = next(k for k in keys_resp.json()["data"] if k["name"] == "forever-key")
+ assert key_entry["expiresAt"] == 0
+
+
+def test_update_api_key_expiry(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Updating expiresAt to a past value should be rejected."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(signoz, token, "sa-key-update-expiry")
+
+ # create with no expiry
+ create_resp = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"
+ ),
+ json={"name": "update-expiry-key", "expiresAt": 0},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert create_resp.status_code == HTTPStatus.CREATED
+ key_id = create_resp.json()["data"]["id"]
+ api_key = create_resp.json()["data"]["key"]
+
+ # updating to expire in the past should be rejected
+ past_ts = int(time.time()) - 60
+ update_resp = requests.put(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys/{key_id}"
+ ),
+ json={"name": "update-expiry-key", "expiresAt": past_ts},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert (
+ update_resp.status_code == HTTPStatus.BAD_REQUEST
+ ), f"Expected 400 for past expiresAt update, got {update_resp.status_code}: {update_resp.text}"
+
+ # key should still work since the update was rejected
+ dash_resp = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ dash_resp.status_code == HTTPStatus.OK
+ ), f"Key should still work after rejected update, got {dash_resp.status_code}: {dash_resp.text}"
diff --git a/tests/integration/src/serviceaccount/03_auth.py b/tests/integration/src/serviceaccount/03_auth.py
new file mode 100644
index 0000000000..97ecd0ed99
--- /dev/null
+++ b/tests/integration/src/serviceaccount/03_auth.py
@@ -0,0 +1,339 @@
+from http import HTTPStatus
+from typing import Callable
+
+import requests
+
+from fixtures import types
+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
+from fixtures.logger import setup_logger
+from fixtures.serviceaccount import (
+ SERVICE_ACCOUNT_BASE,
+ create_service_account_with_key,
+ delete_service_account,
+)
+
+logger = setup_logger(__name__)
+
+
+def test_service_account_key_auth_on_dashboards(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Service account API key with admin role can access dashboards."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ _, api_key = create_service_account_with_key(signoz, token, "sa-dashboard-test")
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.OK, response.text
+
+
+def test_service_account_key_forbidden_on_user_me(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Service account key must not access /api/v1/user/me — it's user-only."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ _, api_key = create_service_account_with_key(signoz, token, "sa-user-me-test")
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/user/me"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+
+ ## This shouldn't be allowed on api key identn, will be updated once we fix that.
+ assert (
+ response.status_code == HTTPStatus.NOT_FOUND
+ ), f"Expected 404 for service account on /user/me, got {response.status_code}: {response.text}"
+
+
+def test_service_account_key_forbidden_on_user_preferences(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Service account key must not access user preference endpoints."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ _, api_key = create_service_account_with_key(signoz, token, "sa-pref-test")
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/user/preferences"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+
+ ## This shouldn't be allowed on api key identn, will be updated once we fix that.
+ assert (
+ response.status_code == HTTPStatus.OK
+ ), f"Expected 200 for service account on /user/preferences, got {response.status_code}: {response.text}"
+
+
+def test_service_account_role_access_admin(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Admin service account can access admin, edit, and view endpoints."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ _, api_key = create_service_account_with_key(
+ signoz, token, "sa-role-admin", role="signoz-admin"
+ )
+
+ # AdminAccess: list service accounts
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.OK
+ ), f"Admin service account should access admin endpoint, got {resp.status_code}: {resp.text}"
+
+ # EditAccess: create a dashboard
+ resp = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ json={
+ "title": "admin-sa-dash",
+ "uploadedGrafana": False,
+ "version": "v4",
+ },
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.CREATED
+ ), f"Admin service account should access edit endpoint, got {resp.status_code}: {resp.text}"
+
+ # ViewAccess: list dashboards
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.OK
+ ), f"Admin service account should access view endpoint, got {resp.status_code}: {resp.text}"
+
+
+def test_service_account_role_access_editor(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Editor service account can access edit and view endpoints but not admin."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ _, api_key = create_service_account_with_key(
+ signoz, token, "sa-role-editor", role="signoz-editor"
+ )
+
+ # AdminAccess: should be forbidden
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.FORBIDDEN
+ ), f"Editor service account should be forbidden from admin endpoint, got {resp.status_code}: {resp.text}"
+
+ # EditAccess: create a dashboard
+ resp = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ json={
+ "title": "editor-sa-dash",
+ "uploadedGrafana": False,
+ "version": "v4",
+ },
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.CREATED
+ ), f"Editor service account should access edit endpoint, got {resp.status_code}: {resp.text}"
+
+ # ViewAccess: list dashboards
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.OK
+ ), f"Editor service account should access view endpoint, got {resp.status_code}: {resp.text}"
+
+
+def test_service_account_role_access_viewer(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Viewer service account can access view endpoints but not edit or admin."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ _, api_key = create_service_account_with_key(
+ signoz, token, "sa-role-viewer", role="signoz-viewer"
+ )
+
+ # AdminAccess: should be forbidden
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.FORBIDDEN
+ ), f"Viewer service account should be forbidden from admin endpoint, got {resp.status_code}: {resp.text}"
+
+ # EditAccess: should be forbidden
+ resp = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ json={
+ "title": "viewer-sa-dash",
+ "uploadedGrafana": False,
+ "version": "v4",
+ },
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.FORBIDDEN
+ ), f"Viewer service account should be forbidden from edit endpoint, got {resp.status_code}: {resp.text}"
+
+ # ViewAccess: list dashboards
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.OK
+ ), f"Viewer service account should access view endpoint, got {resp.status_code}: {resp.text}"
+
+
+def test_service_account_key_deleted_account_rejected(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """A deleted service account's key must be rejected."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id, api_key = create_service_account_with_key(
+ signoz, token, "sa-disable-auth"
+ )
+
+ # verify the key works before deleting
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK
+
+ # soft-delete the SA
+ delete_service_account(signoz, token, service_account_id)
+
+ # now the key should be rejected
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+
+ assert response.status_code in (
+ HTTPStatus.UNAUTHORIZED,
+ HTTPStatus.FORBIDDEN,
+ ), f"Expected 401/403 for disabled service account, got {response.status_code}: {response.text}"
+
+
+def test_service_account_key_revoked_key_rejected(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """A revoked API key must be rejected."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id, api_key = create_service_account_with_key(
+ signoz, token, "sa-revoke-auth"
+ )
+
+ # verify the key works first
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK
+
+ # find the key id
+ keys_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ key_id = keys_resp.json()["data"][0]["id"]
+
+ # revoke it
+ revoke_resp = requests.delete(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys/{key_id}"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert revoke_resp.status_code == HTTPStatus.NO_CONTENT
+
+ # now the key should be rejected
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/dashboards"),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+
+ assert (
+ response.status_code == HTTPStatus.UNAUTHORIZED
+ ), f"Expected 401 for revoked key, got {response.status_code}: {response.text}"
+
+
+def test_user_token_still_works_on_user_me(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Verify that normal user JWT tokens still work on user-only endpoints."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/user/me"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.OK, response.text
+ data = response.json()["data"]
+ assert data["email"] == USER_ADMIN_EMAIL
+
+
+def test_user_token_still_works_on_user_preferences(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Verify that normal user JWT tokens still work on preference endpoints."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v1/user/preferences"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.OK, response.text
+ assert response.json()["data"] is not None
diff --git a/tests/integration/src/serviceaccount/04_roles.py b/tests/integration/src/serviceaccount/04_roles.py
new file mode 100644
index 0000000000..4e53f5da18
--- /dev/null
+++ b/tests/integration/src/serviceaccount/04_roles.py
@@ -0,0 +1,195 @@
+from http import HTTPStatus
+from typing import Callable
+
+import requests
+
+from fixtures import types
+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
+from fixtures.logger import setup_logger
+from fixtures.serviceaccount import (
+ SERVICE_ACCOUNT_BASE,
+ create_service_account,
+ create_service_account_with_key,
+ find_role_by_name,
+)
+
+logger = setup_logger(__name__)
+
+
+def test_get_service_account_roles(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """GET /{id}/roles returns the assigned roles list."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(
+ signoz, token, "sa-get-roles", role="signoz-viewer"
+ )
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.OK, response.text
+ data = response.json()["data"]
+ assert isinstance(data, list)
+ assert len(data) >= 1
+ role_names = [r["name"] for r in data]
+ assert "signoz-viewer" in role_names
+
+
+def test_assign_role_to_service_account(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """POST /{id}/roles assigns a new role, verify via GET."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ # create service account with viewer role
+ service_account_id = create_service_account(
+ signoz, token, "sa-assign-role", role="signoz-viewer"
+ )
+
+ # assign editor role additionally
+ editor_role_id = find_role_by_name(signoz, token, "signoz-editor")
+ assign_resp = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles"
+ ),
+ json={"id": editor_role_id},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert assign_resp.status_code == HTTPStatus.NO_CONTENT, assign_resp.text
+
+ # verify both roles are present
+ roles_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert roles_resp.status_code == HTTPStatus.OK, roles_resp.text
+ role_names = [r["name"] for r in roles_resp.json()["data"]]
+ assert "signoz-viewer" in role_names
+ assert "signoz-editor" in role_names
+
+
+def test_assign_role_idempotent(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """POST same role twice succeeds (store uses ON CONFLICT DO NOTHING)."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(
+ signoz, token, "sa-role-idempotent", role="signoz-viewer"
+ )
+
+ viewer_role_id = find_role_by_name(signoz, token, "signoz-viewer")
+
+ # assign the same role again
+ resp = requests.post(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles"
+ ),
+ json={"id": viewer_role_id},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert resp.status_code == HTTPStatus.NO_CONTENT, resp.text
+
+ # verify only one instance of the role
+ roles_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ role_names = [r["name"] for r in roles_resp.json()["data"]]
+ assert role_names.count("signoz-viewer") == 1
+
+
+def test_remove_role_from_service_account(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """DELETE /{id}/roles/{rid} revokes a role."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id = create_service_account(
+ signoz, token, "sa-remove-role", role="signoz-editor"
+ )
+
+ editor_role_id = find_role_by_name(signoz, token, "signoz-editor")
+
+ # remove the role
+ resp = requests.delete(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles/{editor_role_id}"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert resp.status_code == HTTPStatus.NO_CONTENT, resp.text
+
+ # verify role is gone
+ roles_resp = requests.get(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert roles_resp.status_code == HTTPStatus.OK, roles_resp.text
+ role_names = [r["name"] for r in roles_resp.json()["data"]]
+ assert "signoz-editor" not in role_names
+
+
+def test_remove_role_verify_access_lost(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """After role removal, service account key gets 403 on endpoints requiring that role."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id, api_key = create_service_account_with_key(
+ signoz, token, "sa-role-access-lost", role="signoz-admin"
+ )
+
+ # verify admin access works
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert resp.status_code == HTTPStatus.OK, resp.text
+
+ # remove admin role
+ admin_role_id = find_role_by_name(signoz, token, "signoz-admin")
+ del_resp = requests.delete(
+ signoz.self.host_configs["8080"].get(
+ f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/roles/{admin_role_id}"
+ ),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert del_resp.status_code == HTTPStatus.NO_CONTENT, del_resp.text
+
+ # now admin endpoint should be forbidden
+ resp = requests.get(
+ signoz.self.host_configs["8080"].get(SERVICE_ACCOUNT_BASE),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert (
+ resp.status_code == HTTPStatus.FORBIDDEN
+ ), f"Expected 403 after role removal, got {resp.status_code}: {resp.text}"
diff --git a/tests/integration/src/serviceaccount/05_me.py b/tests/integration/src/serviceaccount/05_me.py
new file mode 100644
index 0000000000..bd78d0b22a
--- /dev/null
+++ b/tests/integration/src/serviceaccount/05_me.py
@@ -0,0 +1,112 @@
+from http import HTTPStatus
+from typing import Callable
+
+import requests
+
+from fixtures import types
+from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
+from fixtures.logger import setup_logger
+from fixtures.serviceaccount import (
+ SERVICE_ACCOUNT_BASE,
+ create_service_account_with_key,
+)
+
+logger = setup_logger(__name__)
+
+ME_ENDPOINT = f"{SERVICE_ACCOUNT_BASE}/me"
+
+
+def test_get_my_service_account(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Service account with API key calls GET /me, gets own details."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id, api_key = create_service_account_with_key(
+ signoz, token, "sa-me-get"
+ )
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(ME_ENDPOINT),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.OK, response.text
+ data = response.json()["data"]
+ assert data["id"] == service_account_id
+ assert data["name"] == "sa-me-get"
+
+
+def test_get_me_requires_sa_identity(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """User JWT on GET /me should fail — no service account identity in claims."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(ME_ENDPOINT),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+
+ # user JWT has no service account ID in claims, should fail
+ assert response.status_code in (
+ HTTPStatus.BAD_REQUEST,
+ HTTPStatus.FORBIDDEN,
+ HTTPStatus.NOT_FOUND,
+ HTTPStatus.UNAUTHORIZED,
+ ), f"Expected error for user JWT on service account /me, got {response.status_code}: {response.text}"
+
+
+def test_update_my_service_account(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Service account calls PUT /me with new name, verify update."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ service_account_id, api_key = create_service_account_with_key(
+ signoz, token, "sa-me-update"
+ )
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(ME_ENDPOINT),
+ json={"name": "sa-me-updated"},
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+ # verify the update via GET /me
+ get_resp = requests.get(
+ signoz.self.host_configs["8080"].get(ME_ENDPOINT),
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+ assert get_resp.status_code == HTTPStatus.OK, get_resp.text
+ assert get_resp.json()["data"]["name"] == "sa-me-updated"
+ assert get_resp.json()["data"]["id"] == service_account_id
+
+
+def test_update_me_invalid_name_rejected(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ """Service account calls PUT /me with invalid name, gets 400."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ _, api_key = create_service_account_with_key(signoz, token, "sa-me-invalid")
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(ME_ENDPOINT),
+ json={"name": "invalid name with spaces"},
+ headers={"SIGNOZ-API-KEY": api_key},
+ timeout=5,
+ )
+
+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text
diff --git a/tests/integration/src/serviceaccount/__init__.py b/tests/integration/src/serviceaccount/__init__.py
new file mode 100644
index 0000000000..e69de29bb2