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(authz): enable FGA for auth domains (#12588)

Vikrant Guptabb47550c016b
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index 115c6a4a4a..a9f62f7433 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -14376,9 +14376,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- - ADMIN
+ - auth-domain:list
- tokenizer:
- - ADMIN
+ - auth-domain:list
summary: List all auth domains
tags:
- authdomains
@@ -14438,9 +14438,13 @@ paths:
description: Internal Server Error
security:
- api_key:
- - ADMIN
+ - auth-domain:create
+ - auth-domain:attach
+ - role:attach
- tokenizer:
- - ADMIN
+ - auth-domain:create
+ - auth-domain:attach
+ - role:attach
summary: Create auth domain
tags:
- authdomains
@@ -14484,9 +14488,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- - ADMIN
+ - auth-domain:delete
- tokenizer:
- - ADMIN
+ - auth-domain:delete
summary: Delete auth domain
tags:
- authdomains
@@ -14541,9 +14545,9 @@ paths:
description: Internal Server Error
security:
- api_key:
- - ADMIN
+ - auth-domain:read
- tokenizer:
- - ADMIN
+ - auth-domain:read
summary: Get auth domain by ID
tags:
- authdomains
@@ -14597,9 +14601,17 @@ paths:
description: Internal Server Error
security:
- api_key:
- - ADMIN
+ - auth-domain:update
+ - auth-domain:attach
+ - auth-domain:detach
+ - role:attach
+ - role:detach
- tokenizer:
- - ADMIN
+ - auth-domain:update
+ - auth-domain:attach
+ - auth-domain:detach
+ - role:attach
+ - role:detach
summary: Update auth domain
tags:
- authdomains
diff --git a/pkg/apiserver/signozapiserver/authdomain.go b/pkg/apiserver/signozapiserver/authdomain.go
index 690bfb8b34..fbbd61774e 100644
--- a/pkg/apiserver/signozapiserver/authdomain.go
+++ b/pkg/apiserver/signozapiserver/authdomain.go
@@ -1,99 +1,269 @@
package signozapiserver
import (
+ "encoding/json"
"net/http"
+ "slices"
+ "github.com/SigNoz/signoz/pkg/errors"
"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/coretypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
"github.com/gorilla/mux"
+ "github.com/tidwall/gjson"
)
func (provider *provider) addAuthDomainRoutes(router *mux.Router) error {
- if err := router.Handle("/api/v2/auth_domains", handler.New(provider.authzMiddleware.AdminAccess(provider.authDomainHandler.List), handler.OpenAPIDef{
- ID: "ListAuthDomains",
- Tags: []string{"authdomains"},
- Summary: "List all auth domains",
- Description: "This endpoint lists all auth domains",
- Request: nil,
- RequestContentType: "",
- Response: make([]*authtypes.GettableAuthDomain, 0),
- ResponseContentType: "application/json",
- SuccessStatusCode: http.StatusOK,
- ErrorStatusCodes: []int{},
- Deprecated: false,
- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
- })).Methods(http.MethodGet).GetError(); err != nil {
+ if err := router.Handle("/api/v2/auth_domains", handler.New(
+ provider.authzMiddleware.CheckResources(provider.authDomainHandler.List, authtypes.SigNozAdminRoleName),
+ handler.OpenAPIDef{
+ ID: "ListAuthDomains",
+ Tags: []string{"authdomains"},
+ Summary: "List all auth domains",
+ Description: "This endpoint lists all auth domains",
+ Request: nil,
+ RequestContentType: "",
+ Response: make([]*authtypes.GettableAuthDomain, 0),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{},
+ Deprecated: false,
+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceAuthDomain.Scope(coretypes.VerbList)}),
+ },
+ handler.WithResourceDefs(handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceAuthDomain,
+ Verb: coretypes.VerbList,
+ Category: coretypes.ActionCategoryAccessControl,
+ Selector: coretypes.WildcardSelector,
+ }),
+ )).Methods(http.MethodGet).GetError(); err != nil {
return err
}
- if err := router.Handle("/api/v2/auth_domains", handler.New(provider.authzMiddleware.AdminAccess(provider.authDomainHandler.Create), handler.OpenAPIDef{
- ID: "CreateAuthDomain",
- Tags: []string{"authdomains"},
- Summary: "Create auth domain",
- Description: "This endpoint creates an auth domain",
- Request: new(authtypes.PostableAuthDomain),
- RequestContentType: "application/json",
- Response: new(types.Identifiable),
- ResponseContentType: "application/json",
- SuccessStatusCode: http.StatusCreated,
- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusConflict},
- Deprecated: false,
- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
- })).Methods(http.MethodPost).GetError(); err != nil {
+ if err := router.Handle("/api/v2/auth_domains", handler.New(
+ provider.authzMiddleware.CheckResources(provider.authDomainHandler.Create, authtypes.SigNozAdminRoleName),
+ handler.OpenAPIDef{
+ ID: "CreateAuthDomain",
+ Tags: []string{"authdomains"},
+ Summary: "Create auth domain",
+ Description: "This endpoint creates an auth domain",
+ Request: new(authtypes.PostableAuthDomain),
+ RequestContentType: "application/json",
+ Response: new(types.Identifiable),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusCreated,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusConflict},
+ Deprecated: false,
+ SecuritySchemes: newScopedSecuritySchemes([]string{
+ coretypes.ResourceMetaResourceAuthDomain.Scope(coretypes.VerbCreate),
+ coretypes.ResourceMetaResourceAuthDomain.Scope(coretypes.VerbAttach),
+ coretypes.ResourceRole.Scope(coretypes.VerbAttach),
+ }),
+ },
+ handler.WithResourceDefs(
+ handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceAuthDomain,
+ Verb: coretypes.VerbCreate,
+ Category: coretypes.ActionCategoryAccessControl,
+ ID: coretypes.ResponseJSONPath("data.id"),
+ Selector: coretypes.WildcardSelector,
+ },
+ handler.AttachDetachSiblingResourceDef{
+ Verb: coretypes.VerbAttach,
+ Category: coretypes.ActionCategoryAccessControl,
+ SourceResource: coretypes.ResourceMetaResourceAuthDomain,
+ SourceIDs: coretypes.OneID(coretypes.ResponseJSONPath("data.id")),
+ SourceSelector: coretypes.WildcardSelector,
+ TargetResource: coretypes.ResourceRole,
+ TargetIDs: authDomainRoleNamesExtractor(),
+ TargetSelector: coretypes.IDSelector,
+ },
+ ),
+ )).Methods(http.MethodPost).GetError(); err != nil {
return err
}
- if err := router.Handle("/api/v2/auth_domains/{id}", handler.New(provider.authzMiddleware.AdminAccess(provider.authDomainHandler.Get), handler.OpenAPIDef{
- ID: "GetAuthDomain",
- Tags: []string{"authdomains"},
- Summary: "Get auth domain by ID",
- Description: "This endpoint returns an auth domain by ID",
- Request: nil,
- RequestContentType: "",
- Response: new(authtypes.GettableAuthDomain),
- ResponseContentType: "application/json",
- SuccessStatusCode: http.StatusOK,
- ErrorStatusCodes: []int{http.StatusNotFound},
- Deprecated: false,
- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
- })).Methods(http.MethodGet).GetError(); err != nil {
+ if err := router.Handle("/api/v2/auth_domains/{id}", handler.New(
+ provider.authzMiddleware.CheckResources(provider.authDomainHandler.Get, authtypes.SigNozAdminRoleName),
+ handler.OpenAPIDef{
+ ID: "GetAuthDomain",
+ Tags: []string{"authdomains"},
+ Summary: "Get auth domain by ID",
+ Description: "This endpoint returns an auth domain by ID",
+ Request: nil,
+ RequestContentType: "",
+ Response: new(authtypes.GettableAuthDomain),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusNotFound},
+ Deprecated: false,
+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceAuthDomain.Scope(coretypes.VerbRead)}),
+ },
+ handler.WithResourceDefs(handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceAuthDomain,
+ Verb: coretypes.VerbRead,
+ Category: coretypes.ActionCategoryAccessControl,
+ ID: coretypes.PathParam("id"),
+ Selector: coretypes.IDSelector,
+ }),
+ )).Methods(http.MethodGet).GetError(); err != nil {
return err
}
- if err := router.Handle("/api/v2/auth_domains/{id}", handler.New(provider.authzMiddleware.AdminAccess(provider.authDomainHandler.Update), handler.OpenAPIDef{
- ID: "UpdateAuthDomain",
- Tags: []string{"authdomains"},
- Summary: "Update auth domain",
- Description: "This endpoint updates an auth domain",
- Request: new(authtypes.UpdatableAuthDomain),
- RequestContentType: "application/json",
- Response: nil,
- ResponseContentType: "",
- SuccessStatusCode: http.StatusNoContent,
- ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusConflict},
- Deprecated: false,
- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
- })).Methods(http.MethodPut).GetError(); err != nil {
+ if err := router.Handle("/api/v2/auth_domains/{id}", handler.New(
+ provider.authzMiddleware.CheckResources(provider.authDomainHandler.Update, authtypes.SigNozAdminRoleName),
+ handler.OpenAPIDef{
+ ID: "UpdateAuthDomain",
+ Tags: []string{"authdomains"},
+ Summary: "Update auth domain",
+ Description: "This endpoint updates an auth domain",
+ Request: new(authtypes.UpdatableAuthDomain),
+ RequestContentType: "application/json",
+ Response: nil,
+ ResponseContentType: "",
+ SuccessStatusCode: http.StatusNoContent,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusConflict},
+ Deprecated: false,
+ SecuritySchemes: newScopedSecuritySchemes([]string{
+ coretypes.ResourceMetaResourceAuthDomain.Scope(coretypes.VerbUpdate),
+ coretypes.ResourceMetaResourceAuthDomain.Scope(coretypes.VerbAttach),
+ coretypes.ResourceMetaResourceAuthDomain.Scope(coretypes.VerbDetach),
+ coretypes.ResourceRole.Scope(coretypes.VerbAttach),
+ coretypes.ResourceRole.Scope(coretypes.VerbDetach),
+ }),
+ },
+ handler.WithResourceDefs(
+ handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceAuthDomain,
+ Verb: coretypes.VerbUpdate,
+ Category: coretypes.ActionCategoryAccessControl,
+ ID: coretypes.PathParam("id"),
+ Selector: coretypes.IDSelector,
+ },
+ handler.AttachDetachSiblingResourceDef{
+ Verb: coretypes.VerbAttach,
+ Category: coretypes.ActionCategoryAccessControl,
+ SourceResource: coretypes.ResourceMetaResourceAuthDomain,
+ SourceIDs: coretypes.OneID(coretypes.PathParam("id")),
+ SourceSelector: coretypes.IDSelector,
+ TargetResource: coretypes.ResourceRole,
+ TargetIDs: authDomainRoleNamesExtractor(),
+ TargetSelector: coretypes.IDSelector,
+ },
+ handler.AttachDetachSiblingResourceDef{
+ Verb: coretypes.VerbDetach,
+ Category: coretypes.ActionCategoryAccessControl,
+ SourceResource: coretypes.ResourceMetaResourceAuthDomain,
+ SourceIDs: coretypes.OneID(coretypes.PathParam("id")),
+ SourceSelector: coretypes.IDSelector,
+ TargetResource: coretypes.ResourceRole,
+ TargetIDs: provider.authDomainStoredRoleNamesExtractor(),
+ TargetSelector: coretypes.IDSelector,
+ },
+ ),
+ )).Methods(http.MethodPut).GetError(); err != nil {
return err
}
- if err := router.Handle("/api/v2/auth_domains/{id}", handler.New(provider.authzMiddleware.AdminAccess(provider.authDomainHandler.Delete), handler.OpenAPIDef{
- ID: "DeleteAuthDomain",
- Tags: []string{"authdomains"},
- Summary: "Delete auth domain",
- Description: "This endpoint deletes an auth domain",
- Request: nil,
- RequestContentType: "",
- Response: nil,
- ResponseContentType: "",
- SuccessStatusCode: http.StatusNoContent,
- ErrorStatusCodes: []int{http.StatusBadRequest},
- Deprecated: false,
- SecuritySchemes: newSecuritySchemes(types.RoleAdmin),
- })).Methods(http.MethodDelete).GetError(); err != nil {
+ if err := router.Handle("/api/v2/auth_domains/{id}", handler.New(
+ provider.authzMiddleware.CheckResources(provider.authDomainHandler.Delete, authtypes.SigNozAdminRoleName),
+ handler.OpenAPIDef{
+ ID: "DeleteAuthDomain",
+ Tags: []string{"authdomains"},
+ Summary: "Delete auth domain",
+ Description: "This endpoint deletes an auth domain",
+ Request: nil,
+ RequestContentType: "",
+ Response: nil,
+ ResponseContentType: "",
+ SuccessStatusCode: http.StatusNoContent,
+ ErrorStatusCodes: []int{http.StatusBadRequest},
+ Deprecated: false,
+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceAuthDomain.Scope(coretypes.VerbDelete)}),
+ },
+ handler.WithResourceDefs(handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceAuthDomain,
+ Verb: coretypes.VerbDelete,
+ Category: coretypes.ActionCategoryAccessControl,
+ ID: coretypes.PathParam("id"),
+ Selector: coretypes.IDSelector,
+ }),
+ )).Methods(http.MethodDelete).GetError(); err != nil {
return err
}
return nil
}
+
+// The extracted names are the roles the request body's mapping grants at SSO
+// login — see authDomainEffectiveRoleNames.
+func authDomainRoleNamesExtractor() coretypes.ResourceIDsExtractor {
+ return coretypes.ResourceIDsExtractor{Phase: coretypes.PhaseRequest, Fn: func(ec coretypes.ExtractorContext) ([]string, error) {
+ roleMappingJSON := gjson.GetBytes(ec.RequestBody, "roleMapping")
+ if !roleMappingJSON.Exists() || roleMappingJSON.Type == gjson.Null {
+ return authDomainEffectiveRoleNames(nil), nil
+ }
+
+ roleMapping := new(authtypes.RoleMapping)
+ if err := json.Unmarshal([]byte(roleMappingJSON.Raw), roleMapping); err != nil {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid role mapping: %v", err)
+ }
+
+ return authDomainEffectiveRoleNames(roleMapping), nil
+ }}
+}
+
+// The extracted names are the roles the stored domain's mapping grants at SSO
+// login — an update replaces that mapping, so the caller must be able to detach
+// them.
+func (provider *provider) authDomainStoredRoleNamesExtractor() coretypes.ResourceIDsExtractor {
+ return coretypes.ResourceIDsExtractor{Phase: coretypes.PhaseRequest, Fn: func(ec coretypes.ExtractorContext) ([]string, error) {
+ if ec.Request == nil {
+ return nil, nil
+ }
+
+ claims, err := authtypes.ClaimsFromContext(ec.Request.Context())
+ if err != nil {
+ return nil, err
+ }
+
+ orgID, err := valuer.NewUUID(claims.OrgID)
+ if err != nil {
+ return nil, err
+ }
+
+ id, err := valuer.NewUUID(mux.Vars(ec.Request)["id"])
+ if err != nil {
+ return nil, err
+ }
+
+ authDomain, err := provider.authDomainModule.GetByOrgIDAndID(ec.Request.Context(), orgID, id)
+ if err != nil {
+ return nil, err
+ }
+
+ return authDomainEffectiveRoleNames(authDomain.RoleMapping()), nil
+ }}
+}
+
+// The effective names are the roles a domain grants at SSO login: the mapped
+// roles plus the default (signoz-viewer when unset), or every role when the IDP
+// role attribute is trusted. Never empty — a check with no selectors is forbidden.
+func authDomainEffectiveRoleNames(roleMapping *authtypes.RoleMapping) []string {
+ if roleMapping == nil {
+ return []string{authtypes.SigNozViewerRoleName}
+ }
+
+ if roleMapping.UseRoleAttribute {
+ return []string{coretypes.WildCardSelectorString}
+ }
+
+ roleNames := roleMapping.RoleNames()
+ if !slices.Contains(roleNames, roleMapping.DefaultRoleName()) {
+ roleNames = append(roleNames, roleMapping.DefaultRoleName())
+ }
+
+ return roleNames
+}
diff --git a/pkg/apiserver/signozapiserver/provider.go b/pkg/apiserver/signozapiserver/provider.go
index 4854bf0185..c3b79b858b 100644
--- a/pkg/apiserver/signozapiserver/provider.go
+++ b/pkg/apiserver/signozapiserver/provider.go
@@ -51,6 +51,7 @@ type provider struct {
userHandler user.Handler
sessionHandler session.Handler
authDomainHandler authdomain.Handler
+ authDomainModule authdomain.Module
preferenceHandler preference.Handler
globalHandler global.Handler
promoteHandler promote.Handler
@@ -88,6 +89,7 @@ func NewFactory(
userHandler user.Handler,
sessionHandler session.Handler,
authDomainHandler authdomain.Handler,
+ authDomainModule authdomain.Module,
preferenceHandler preference.Handler,
globalHandler global.Handler,
promoteHandler promote.Handler,
@@ -128,6 +130,7 @@ func NewFactory(
userHandler,
sessionHandler,
authDomainHandler,
+ authDomainModule,
preferenceHandler,
globalHandler,
promoteHandler,
@@ -170,6 +173,7 @@ func newProvider(
userHandler user.Handler,
sessionHandler session.Handler,
authDomainHandler authdomain.Handler,
+ authDomainModule authdomain.Module,
preferenceHandler preference.Handler,
globalHandler global.Handler,
promoteHandler promote.Handler,
@@ -211,6 +215,7 @@ func newProvider(
authzService: authzService,
sessionHandler: sessionHandler,
authDomainHandler: authDomainHandler,
+ authDomainModule: authDomainModule,
preferenceHandler: preferenceHandler,
globalHandler: globalHandler,
promoteHandler: promoteHandler,
diff --git a/pkg/signoz/openapi.go b/pkg/signoz/openapi.go
index 064cc56abe..52a325f132 100644
--- a/pkg/signoz/openapi.go
+++ b/pkg/signoz/openapi.go
@@ -64,6 +64,7 @@ func NewOpenAPI(ctx context.Context, instrumentation instrumentation.Instrumenta
struct{ user.Handler }{},
struct{ session.Handler }{},
struct{ authdomain.Handler }{},
+ struct{ authdomain.Module }{},
struct{ preference.Handler }{},
struct{ global.Handler }{},
struct{ promote.Handler }{},
diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.go
index 267c8b7112..52d80b2e19 100644
--- a/pkg/signoz/provider.go
+++ b/pkg/signoz/provider.go
@@ -243,6 +243,7 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewFixSavedViewSelectFieldsFactory(sqlstore),
sqlmigration.NewDeleteOrphanUserRolesFactory(),
sqlmigration.NewMigrateLambdaDashboardsFactory(),
+ sqlmigration.NewAddAuthDomainTuplesFactory(sqlstore),
)
}
@@ -317,6 +318,7 @@ func NewAPIServerProviderFactories(orgGetter organization.Getter, authz authz.Au
impluser.NewHandler(modules.UserSetter, modules.UserGetter),
implsession.NewHandler(modules.Session, globalConfig),
implauthdomain.NewHandler(modules.AuthDomain),
+ modules.AuthDomain,
implpreference.NewHandler(modules.Preference),
handlers.Global,
implpromote.NewHandler(modules.Promote),
diff --git a/pkg/sqlmigration/117_add_auth_domain_tuples.go b/pkg/sqlmigration/117_add_auth_domain_tuples.go
new file mode 100644
index 0000000000..3ebb2faa3c
--- /dev/null
+++ b/pkg/sqlmigration/117_add_auth_domain_tuples.go
@@ -0,0 +1,167 @@
+package sqlmigration
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/factory"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/types/authtypes"
+ "github.com/SigNoz/signoz/pkg/types/coretypes"
+ "github.com/oklog/ulid/v2"
+ "github.com/uptrace/bun"
+ "github.com/uptrace/bun/dialect"
+ "github.com/uptrace/bun/migrate"
+)
+
+type addAuthDomainTuples struct {
+ sqlstore sqlstore.SQLStore
+}
+
+func NewAddAuthDomainTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
+ return factory.NewProviderFactory(factory.MustNewName("add_auth_domain_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
+ return &addAuthDomainTuples{sqlstore: sqlstore}, nil
+ })
+}
+
+func (migration *addAuthDomainTuples) Register(migrations *migrate.Migrations) error {
+ return migrations.Register(migration.Up, migration.Down)
+}
+
+func (migration *addAuthDomainTuples) 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
+ }
+
+ var orgIDs []string
+ err = tx.NewSelect().
+ Table("organizations").
+ Column("id").
+ Scan(ctx, &orgIDs)
+ if err != nil && err != sql.ErrNoRows {
+ return err
+ }
+
+ isPG := migration.sqlstore.BunDB().Dialect().Name() == dialect.PG
+
+ // auth-domain moved from the legacy AdminAccess role gate to CheckResources,
+ // which on enterprise requires real tuples -- existing orgs never had these
+ // written, only new orgs get them from the registry at bootstrap.
+ tuples := []migrationTuple{
+ {authtypes.SigNozAdminRoleName, "metaresource", "auth-domain", "create"},
+ {authtypes.SigNozAdminRoleName, "metaresource", "auth-domain", "read"},
+ {authtypes.SigNozAdminRoleName, "metaresource", "auth-domain", "update"},
+ {authtypes.SigNozAdminRoleName, "metaresource", "auth-domain", "delete"},
+ {authtypes.SigNozAdminRoleName, "metaresource", "auth-domain", "list"},
+ {authtypes.SigNozAdminRoleName, "metaresource", "auth-domain", "attach"},
+ {authtypes.SigNozAdminRoleName, "metaresource", "auth-domain", "detach"},
+ }
+
+ for _, orgID := range orgIDs {
+ for _, tuple := range tuples {
+ entropy := ulid.DefaultEntropy()
+ now := time.Now().UTC()
+ tupleID := ulid.MustNew(ulid.Timestamp(now), entropy).String()
+
+ objectID := "organization/" + orgID + "/" + tuple.objectName + "/*"
+ roleSubject := "organization/" + orgID + "/role/" + tuple.roleName
+
+ if isPG {
+ user := "role:" + roleSubject + "#assignee"
+ 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, tuple.objectType, objectID, tuple.relation, user, "userset", 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, tuple.objectType, objectID, tuple.relation, user, 0, 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, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", "userset", 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, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", 0, tupleID, now,
+ )
+ if err != nil {
+ return err
+ }
+ }
+ }
+ }
+
+ // The auth-domain attach/detach transactions are new to the registry, so the
+ // managed-role transaction groups stored per org (served by the roles API)
+ // must be re-synced from it, like 105_update_role_transaction_groups did.
+ managedRoleGroups := make(map[string]string, len(coretypes.ManagedRoleToTransactions))
+ for roleName, transactions := range coretypes.ManagedRoleToTransactions {
+ data, err := json.Marshal(authtypes.NewTransactionGroupsFromTransactions(transactions))
+ if err != nil {
+ return err
+ }
+ managedRoleGroups[roleName] = string(data)
+ }
+
+ for _, orgID := range orgIDs {
+ for roleName, data := range managedRoleGroups {
+ if _, err := tx.NewUpdate().
+ Model(new(roles)).
+ Set("transaction_groups = ?", data).
+ Where("org_id = ?", orgID).
+ Where("type = ?", authtypes.RoleTypeManaged.StringValue()).
+ Where("name = ?", roleName).
+ Exec(ctx); err != nil {
+ return err
+ }
+ }
+ }
+
+ return tx.Commit()
+}
+
+func (migration *addAuthDomainTuples) Down(context.Context, *bun.DB) error {
+ return nil
+}
diff --git a/pkg/types/coretypes/registry_managed_role.go b/pkg/types/coretypes/registry_managed_role.go
index 7c2ced052e..3cb0e6d823 100644
--- a/pkg/types/coretypes/registry_managed_role.go
+++ b/pkg/types/coretypes/registry_managed_role.go
@@ -33,6 +33,8 @@ var ManagedRoleToTransactions = map[string][]Transaction{
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindAuthDomain}, WildCardSelectorString)},
{Verb: VerbCreate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindAuthDomain}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindAuthDomain}, WildCardSelectorString)},
+ {Verb: VerbAttach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindAuthDomain}, WildCardSelectorString)},
+ {Verb: VerbDetach, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindAuthDomain}, WildCardSelectorString)},
// cloud-integration — admin only
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindCloudIntegration}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindCloudIntegration}, WildCardSelectorString)},
diff --git a/tests/integration/testdata/role/managed_role_transactions.json b/tests/integration/testdata/role/managed_role_transactions.json
index 14b7a9f092..ce19659827 100644
--- a/tests/integration/testdata/role/managed_role_transactions.json
+++ b/tests/integration/testdata/role/managed_role_transactions.json
@@ -47,7 +47,9 @@
"read",
"update",
"delete",
- "list"
+ "list",
+ "attach",
+ "detach"
]
},
{
diff --git a/tests/integration/tests/callbackauthn/05_authz.py b/tests/integration/tests/callbackauthn/05_authz.py
new file mode 100644
index 0000000000..29439c5700
--- /dev/null
+++ b/tests/integration/tests/callbackauthn/05_authz.py
@@ -0,0 +1,511 @@
+from collections.abc import Callable
+from http import HTTPStatus
+
+import requests
+from wiremock.resources.mappings import Mapping
+
+from fixtures import types
+from fixtures.auth import (
+ USER_ADMIN_EMAIL,
+ USER_ADMIN_PASSWORD,
+ add_license,
+ change_user_role,
+ create_active_user,
+)
+from fixtures.role import find_role_by_name, transaction_group
+
+_EDITOR_EMAIL = "[email protected]"
+_EDITOR_PASSWORD = "password123Z$"
+_VIEWER_EMAIL = "[email protected]"
+_VIEWER_PASSWORD = "password123Z$"
+
+_ACTOR_ROLE_NAME = "auth-domain-fga-actor"
+_ACTOR_EMAIL = "[email protected]"
+_ACTOR_PASSWORD = "password123Z$"
+
+# Instance verbs are granted on _TARGET_A only; _TARGET_B must stay forbidden.
+_TARGET_A = "target-a-authdomain.integration.test"
+_TARGET_B = "target-b-authdomain.integration.test"
+_ADMIN_DOMAIN = "admin-crud-authdomain.integration.test"
+_ACTOR_DOMAIN = "actor-crud-authdomain.integration.test"
+
+_SAML_CONFIG = {
+ "kind": "saml",
+ "spec": {
+ "entityId": "saml-entity",
+ "location": "saml-idp",
+ "certificate": "saml-cert",
+ },
+}
+
+
+def test_setup_managed_role_users_and_targets(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ for email, role, password, name in (
+ (_EDITOR_EMAIL, "signoz-editor", _EDITOR_PASSWORD, "auth domain authz editor"),
+ (_VIEWER_EMAIL, "signoz-viewer", _VIEWER_PASSWORD, "auth domain authz viewer"),
+ ):
+ create_active_user(signoz, admin_token, email=email, role=role, password=password, name=name)
+
+ for name in (_TARGET_A, _TARGET_B):
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ json={"name": name, "enabled": True, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+
+
+def test_admin_can_crud(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ json={"name": _ADMIN_DOMAIN, "enabled": True, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ domain_id = response.json()["data"]["id"]
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ assert _ADMIN_DOMAIN in {domain["name"] for domain in response.json()["data"]}
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{domain_id}"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{domain_id}"),
+ json={"enabled": False, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{domain_id}"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+
+def test_editor_and_viewer_forbidden(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ a_id = next(domain["id"] for domain in response.json()["data"] if domain["name"] == _TARGET_A)
+
+ for email, password in ((_EDITOR_EMAIL, _EDITOR_PASSWORD), (_VIEWER_EMAIL, _VIEWER_PASSWORD)):
+ token = get_token(email, password)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"{email} list: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ json={"name": _ACTOR_DOMAIN, "enabled": True, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"{email} create: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{a_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"{email} get: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{a_id}"),
+ json={"enabled": True, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"{email} update: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{a_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"{email} delete: expected 403, got {response.status_code}: {response.text}"
+
+
+def test_apply_license(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ make_http_mocks: Callable[[types.TestContainerDocker, list[Mapping]], None],
+ get_token: Callable[[str, str], str],
+) -> None:
+ add_license(signoz, make_http_mocks, get_token)
+
+
+def test_setup_actor(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ create_role: Callable[..., str],
+):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+
+ create_role(admin_token, _ACTOR_ROLE_NAME)
+
+ user_id = create_active_user(
+ signoz,
+ admin_token,
+ email=_ACTOR_EMAIL,
+ role="signoz-viewer",
+ password=_ACTOR_PASSWORD,
+ name="auth-domain-fga-test-user",
+ )
+ change_user_role(signoz, admin_token, user_id, "signoz-viewer", _ACTOR_ROLE_NAME)
+
+
+def test_actor_without_grants_forbidden(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ a_id = next(domain["id"] for domain in response.json()["data"] if domain["name"] == _TARGET_A)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"list without grant: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ json={"name": _ACTOR_DOMAIN, "enabled": True, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"create without grant: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{a_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"read without grant: expected 403, got {response.status_code}: {response.text}"
+
+
+def test_create_requires_attach_on_mapped_roles(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ actor_id = find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v1/roles/{actor_id}"),
+ json={
+ "description": "",
+ "transactionGroups": [
+ transaction_group("create", "metaresource", "auth-domain", ["*"]),
+ transaction_group("delete", "metaresource", "auth-domain", ["*"]),
+ transaction_group("list", "metaresource", "auth-domain", ["*"]),
+ transaction_group("attach", "metaresource", "auth-domain", ["*"]),
+ transaction_group("attach", "role", "role", ["signoz-viewer"]),
+ ],
+ },
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+ token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
+
+ # No roleMapping means SSO users get signoz-viewer, which is granted.
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ json={"name": _ACTOR_DOMAIN, "enabled": True, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, f"create with default mapping: {response.text}"
+ domain_id = response.json()["data"]["id"]
+
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{domain_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ json={
+ "name": _ACTOR_DOMAIN,
+ "enabled": True,
+ "config": _SAML_CONFIG,
+ "roleMapping": {"defaultRole": "EDITOR"},
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"map to unattachable role: expected 403, got {response.status_code}: {response.text}"
+
+ # Trusting the IDP role attribute can grant any role, so it needs attach on role "*".
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ json={
+ "name": _ACTOR_DOMAIN,
+ "enabled": True,
+ "config": _SAML_CONFIG,
+ "roleMapping": {"defaultRole": "VIEWER", "useRoleAttribute": True},
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"role attribute without wildcard attach: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v1/roles/{actor_id}"),
+ json={
+ "description": "",
+ "transactionGroups": [
+ transaction_group("create", "metaresource", "auth-domain", ["*"]),
+ transaction_group("delete", "metaresource", "auth-domain", ["*"]),
+ transaction_group("list", "metaresource", "auth-domain", ["*"]),
+ transaction_group("attach", "metaresource", "auth-domain", ["*"]),
+ transaction_group("attach", "role", "role", ["*"]),
+ ],
+ },
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ json={
+ "name": _ACTOR_DOMAIN,
+ "enabled": True,
+ "config": _SAML_CONFIG,
+ "roleMapping": {"defaultRole": "EDITOR", "groupMappings": {"platform-team": "ADMIN"}},
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, f"create with wildcard role attach: {response.text}"
+ domain_id = response.json()["data"]["id"]
+
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{domain_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+
+def test_update_requires_detach_on_stored_roles(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ actor_id = find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)
+
+ response = requests.post(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ json={
+ "name": _ACTOR_DOMAIN,
+ "enabled": True,
+ "config": _SAML_CONFIG,
+ "roleMapping": {"defaultRole": "EDITOR"},
+ },
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ domain_id = response.json()["data"]["id"]
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v1/roles/{actor_id}"),
+ json={
+ "description": "",
+ "transactionGroups": [
+ transaction_group("update", "metaresource", "auth-domain", [domain_id]),
+ transaction_group("attach", "metaresource", "auth-domain", [domain_id]),
+ transaction_group("detach", "metaresource", "auth-domain", [domain_id]),
+ transaction_group("attach", "role", "role", ["signoz-viewer"]),
+ transaction_group("detach", "role", "role", ["signoz-viewer"]),
+ ],
+ },
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+ token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
+
+ # Dropping the mapping detaches the stored signoz-editor grant, which the
+ # actor cannot detach.
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{domain_id}"),
+ json={"enabled": True, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"drop mapping without detach on stored role: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v1/roles/{actor_id}"),
+ json={
+ "description": "",
+ "transactionGroups": [
+ transaction_group("update", "metaresource", "auth-domain", [domain_id]),
+ transaction_group("attach", "metaresource", "auth-domain", [domain_id]),
+ transaction_group("detach", "metaresource", "auth-domain", [domain_id]),
+ transaction_group("attach", "role", "role", ["signoz-viewer"]),
+ transaction_group("detach", "role", "role", ["signoz-editor"]),
+ ],
+ },
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{domain_id}"),
+ json={"enabled": True, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, f"drop mapping with detach on stored role: {response.text}"
+
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{domain_id}"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+
+def test_instance_verbs_scoped_to_granted_domain(
+ signoz: types.SigNoz,
+ create_user_admin: types.Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+):
+ admin_token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ actor_id = find_role_by_name(signoz, admin_token, _ACTOR_ROLE_NAME)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v2/auth_domains"),
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ ids = {domain["name"]: domain["id"] for domain in response.json()["data"]}
+ a_id, b_id = ids[_TARGET_A], ids[_TARGET_B]
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v1/roles/{actor_id}"),
+ json={
+ "description": "",
+ "transactionGroups": [
+ transaction_group("read", "metaresource", "auth-domain", [a_id]),
+ transaction_group("update", "metaresource", "auth-domain", [a_id]),
+ transaction_group("delete", "metaresource", "auth-domain", [a_id]),
+ transaction_group("attach", "metaresource", "auth-domain", [a_id]),
+ transaction_group("detach", "metaresource", "auth-domain", [a_id]),
+ transaction_group("attach", "role", "role", ["signoz-viewer"]),
+ transaction_group("detach", "role", "role", ["signoz-viewer"]),
+ ],
+ },
+ headers={"Authorization": f"Bearer {admin_token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text
+
+ token = get_token(_ACTOR_EMAIL, _ACTOR_PASSWORD)
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{a_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK, f"read granted domain: {response.text}"
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{b_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"read other domain: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{a_id}"),
+ json={"enabled": False, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, f"update granted domain: {response.text}"
+
+ response = requests.put(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{b_id}"),
+ json={"enabled": False, "config": _SAML_CONFIG},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"update other domain: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{b_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.FORBIDDEN, f"delete other domain: expected 403, got {response.status_code}: {response.text}"
+
+ response = requests.delete(
+ signoz.self.host_configs["8080"].get(f"/api/v2/auth_domains/{a_id}"),
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.NO_CONTENT, f"delete granted domain: {response.text}"