Skip to content

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

feat: scim sync from okta (#18526)

ecmadao836d5c8590b9
diff --git a/backend/api/directory-sync/aad.go b/backend/api/directory-sync/aad.go
deleted file mode 100644
index b1c5247982..0000000000
--- a/backend/api/directory-sync/aad.go
+++ /dev/null
@@ -1,93 +0,0 @@
-package directorysync
-
-type AADUserEmail struct {
- Type string `json:"type"`
- Value string `json:"value"`
- Primary bool `json:"primary"`
-}
-
-type AADResourceMeta struct {
- ResourceType string `json:"resourceType"`
-}
-
-// AADUser represents the SCIM User schema for Azure AD (Entra ID) provisioning.
-// Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups#design-your-user-and-group-schema
-//
-// SCIM ID mapping for users:
-// - id: Bytebase's user UID (numeric, returned as string). Used by Azure in subsequent API calls.
-// - externalId: Azure's objectId (optional). Azure sends this but we use userName (email) for user matching.
-// - userName: User's email address (maps to userPrincipalName in Azure). Primary identifier for user lookup.
-//
-// Unlike groups, users are matched by userName (email) rather than externalId because:
-// - Email is the natural unique identifier for users in Bytebase
-// - Azure's default attribute mapping uses userPrincipalName -> userName
-//
-// Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups#get-user-by-query
-type AADUser struct {
- // id is Bytebase's user UID, used by Azure in subsequent requests (GET/PATCH/DELETE /Users/{id}).
- ID string `json:"id"`
- Schemas []string `json:"schemas"`
- // externalId is Azure's objectId. We don't use this for user matching; we use userName instead.
- ExternalID string `json:"externalId"`
- // userName maps to userPrincipalName in Azure. This is the primary identifier for user lookup.
- UserName string `json:"userName"`
- Active bool `json:"active"`
- DisplayName string `json:"displayName"`
- Emails []*AADUserEmail `json:"emails"`
- Meta *AADResourceMeta `json:"meta"`
-}
-
-// AADGroup represents the SCIM Group schema for Azure AD (Entra ID) provisioning.
-// Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups
-//
-// SCIM ID mapping:
-// - id: Bytebase's internal group identifier (returned to Azure, used in subsequent API calls)
-// - externalId: Azure's objectId for the group (sent by Azure to identify the group in their system)
-//
-// Docs: https://learn.microsoft.com/en-us/answers/questions/1394370/azure-ad-scim-provisioning-group-update-requests-w
-// Docs: https://stackoverflow.com/questions/67198152/where-does-azuread-store-the-id-attribute-returned-by-a-scim-endpoint
-type AADGroup struct {
- // id is returned by our SCIM server and used by Azure in subsequent requests (GET/PATCH/DELETE /Groups/{id}).
- ID string `json:"id"`
- Schemas []string `json:"schemas"`
- // externalId is Azure's objectId for the group. Azure sends this so we can correlate their group with ours.
- // By default, Azure maps objectId -> externalId in attribute mappings.
- ExternalID string `json:"externalId"`
- // email is a custom attribute mapped from Azure group's mail attribute.
- // Configure in Azure: Entra ID -> Enterprise apps -> Provisioning -> Attribute Mappings -> Groups
- // Add custom attribute "email" and map Azure "mail" -> SCIM "email".
- // Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/customize-application-attributes
- Email string `json:"email"`
- DisplayName string `json:"displayName"`
- Members []string `json:"members"`
- Meta *AADResourceMeta `json:"meta"`
-}
-
-// Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups#get-user-by-query
-type ListUsersResponse struct {
- Schemas []string `json:"schemas"`
- TotalResults int `json:"totalResults"`
- Resources []*AADUser `json:"Resources"`
-}
-
-type ListGroupsResponse struct {
- Schemas []string `json:"schemas"`
- TotalResults int `json:"totalResults"`
- Resources []*AADGroup `json:"Resources"`
-}
-
-type PatchMember struct {
- Value string `json:"value"`
-}
-
-type PatchOperation struct {
- OP string `json:"op"`
- Path string `json:"path"`
- Value any `json:"value"`
-}
-
-// Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups#update-user-multi-valued-properties
-type PatchRequest struct {
- Schemas []string `json:"schemas"`
- Operations []*PatchOperation `json:"Operations"`
-}
diff --git a/backend/api/directory-sync/scim.go b/backend/api/directory-sync/scim.go
new file mode 100644
index 0000000000..3d7fdbfb3d
--- /dev/null
+++ b/backend/api/directory-sync/scim.go
@@ -0,0 +1,145 @@
+package directorysync
+
+type SCIMUserEmail struct {
+ Type string `json:"type"`
+ Value string `json:"value"`
+ Primary bool `json:"primary"`
+}
+
+type SCIMResourceMeta struct {
+ ResourceType string `json:"resourceType"`
+}
+
+// SCIMUser represents the SCIM 2.0 User schema for identity provider provisioning.
+// Supports both Azure Entra ID and Okta SCIM clients.
+// Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups#design-your-user-and-group-schema
+// Docs: https://developer.okta.com/docs/reference/scim/scim-20/
+//
+// SCIM ID mapping for users:
+// - id: Bytebase's user UID (numeric, returned as string). Used by IdP in subsequent API calls.
+// - externalId: IdP's user identifier (optional). We use userName (email) for user matching instead.
+// - userName: User's email address. Primary identifier for user lookup.
+//
+// Unlike groups, users are matched by userName (email) rather than externalId because:
+// - Email is the natural unique identifier for users in Bytebase
+// - Both Azure and Okta default attribute mappings use email -> userName
+type SCIMUser struct {
+ // id is Bytebase's user UID, used by IdP in subsequent requests (GET/PATCH/DELETE /Users/{id}).
+ ID string `json:"id"`
+ Schemas []string `json:"schemas"`
+ // externalId is the IdP's user identifier. We don't use this for user matching; we use userName instead.
+ ExternalID string `json:"externalId"`
+ // userName is the user's email address. This is the primary identifier for user lookup.
+ UserName string `json:"userName"`
+ Active bool `json:"active"`
+ DisplayName string `json:"displayName"`
+ Emails []*SCIMUserEmail `json:"emails"`
+ Meta *SCIMResourceMeta `json:"meta"`
+}
+
+// SCIMGroup represents the SCIM 2.0 Group schema for identity provider provisioning.
+// Supports both Azure Entra ID and Okta SCIM clients.
+// Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups
+// Docs: https://developer.okta.com/docs/reference/scim/scim-20/
+//
+// SCIM ID mapping:
+// - id: Bytebase's internal group identifier (returned to IdP, used in subsequent API calls)
+// - externalId: IdP's group identifier (sent by IdP to identify the group in their system)
+type SCIMGroup struct {
+ // id is returned by our SCIM server and used by IdP in subsequent requests (GET/PATCH/DELETE /Groups/{id}).
+ ID string `json:"id"`
+ Schemas []string `json:"schemas"`
+ // externalId is the IdP's group identifier. The IdP sends this so we can correlate their group with ours.
+ ExternalID string `json:"externalId"`
+ // email is a custom attribute mapped from the IdP's group mail attribute.
+ // Configure in IdP: Add custom attribute "email" and map group mail -> SCIM "email".
+ // Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/customize-application-attributes
+ Email string `json:"email"`
+ DisplayName string `json:"displayName"`
+ Members []*SCIMMember `json:"members"`
+ Meta *SCIMResourceMeta `json:"meta"`
+}
+
+// ListUsersResponse is the SCIM 2.0 list response for users.
+// Docs: https://datatracker.ietf.org/doc/html/rfc7644#section-3.4.2
+type ListUsersResponse struct {
+ Schemas []string `json:"schemas"`
+ TotalResults int `json:"totalResults"`
+ Resources []*SCIMUser `json:"Resources"`
+}
+
+// ListGroupsResponse is the SCIM 2.0 list response for groups.
+type ListGroupsResponse struct {
+ Schemas []string `json:"schemas"`
+ TotalResults int `json:"totalResults"`
+ Resources []*SCIMGroup `json:"Resources"`
+}
+
+// SCIMMember represents a member in SCIM group operations.
+// Used in both POST /Groups (with members) and PATCH /Groups (add/remove members).
+// Okta sends: {"value": "101", "display": "[email protected]"}
+// Azure sends: {"value": "101"}
+type SCIMMember struct {
+ Value string `json:"value"` // Bytebase user UID
+ Display string `json:"display,omitempty"` // User's email/display name (optional)
+}
+
+// PatchOperation represents a single operation in a SCIM PATCH request.
+// Docs: https://datatracker.ietf.org/doc/html/rfc7644#section-3.5.2
+type PatchOperation struct {
+ OP string `json:"op"`
+ Path string `json:"path"`
+ Value any `json:"value"`
+}
+
+// PatchRequest represents a SCIM 2.0 PATCH request.
+// Docs: https://datatracker.ietf.org/doc/html/rfc7644#section-3.5.2
+type PatchRequest struct {
+ Schemas []string `json:"schemas"`
+ Operations []*PatchOperation `json:"Operations"`
+}
+
+// ServiceProviderConfig represents the SCIM 2.0 ServiceProviderConfig response.
+// This endpoint allows SCIM clients to discover the capabilities of the SCIM server.
+// Docs: https://datatracker.ietf.org/doc/html/rfc7644#section-4
+type ServiceProviderConfig struct {
+ Schemas []string `json:"schemas"`
+ DocumentationURI string `json:"documentationUri,omitempty"`
+ Patch ServiceProviderConfigPatch `json:"patch"`
+ Bulk ServiceProviderConfigBulk `json:"bulk"`
+ Filter ServiceProviderConfigFilter `json:"filter"`
+ ChangePassword ServiceProviderConfigSupported `json:"changePassword"`
+ Sort ServiceProviderConfigSupported `json:"sort"`
+ Etag ServiceProviderConfigSupported `json:"etag"`
+ AuthenticationSchemes []AuthenticationScheme `json:"authenticationSchemes"`
+}
+
+// ServiceProviderConfigPatch indicates PATCH operation support.
+type ServiceProviderConfigPatch struct {
+ Supported bool `json:"supported"`
+}
+
+// ServiceProviderConfigBulk indicates bulk operation support.
+type ServiceProviderConfigBulk struct {
+ Supported bool `json:"supported"`
+ MaxOperations int `json:"maxOperations"`
+ MaxPayloadSize int `json:"maxPayloadSize"`
+}
+
+// ServiceProviderConfigFilter indicates filter support.
+type ServiceProviderConfigFilter struct {
+ Supported bool `json:"supported"`
+ MaxResults int `json:"maxResults"`
+}
+
+// ServiceProviderConfigSupported indicates feature support.
+type ServiceProviderConfigSupported struct {
+ Supported bool `json:"supported"`
+}
+
+// AuthenticationScheme describes an authentication method supported by the SCIM server.
+type AuthenticationScheme struct {
+ Type string `json:"type"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+}
diff --git a/backend/api/directory-sync/webhook.go b/backend/api/directory-sync/webhook.go
index 7ff39fd6f4..f940fbfa00 100644
--- a/backend/api/directory-sync/webhook.go
+++ b/backend/api/directory-sync/webhook.go
@@ -27,36 +27,104 @@ import (
"github.com/bytebase/bytebase/backend/utils"
)
-const entraIDSource = "Entra ID"
+const (
+ entraIDSource = "Entra ID"
+ oktaSource = "Okta"
+)
-// https://developer.xurrent.com/v1/scim/service_provider_config/
-// https://scim.cloud/
-// https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups
-func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
- g.POST("/workspaces/:workspaceID/Users", func(c echo.Context) error {
+// detectSCIMSource detects the identity provider source based on User-Agent header.
+// Okta sends "Okta SCIM Client" in User-Agent, Azure sends "Azure" or "Microsoft".
+func detectSCIMSource(c echo.Context) string {
+ userAgent := c.Request().Header.Get("User-Agent")
+ userAgentLower := strings.ToLower(userAgent)
+ if strings.Contains(userAgentLower, "okta") {
+ return oktaSource
+ }
+ return entraIDSource
+}
+
+// scimAuthMiddleware validates authentication and license for all SCIM endpoints.
+func (s *Service) scimAuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
ctx := c.Request().Context()
if err := s.validRequestURL(ctx, c); err != nil {
- return c.String(http.StatusInternalServerError, err.Error())
+ return c.String(http.StatusUnauthorized, err.Error())
}
if err := s.licenseService.IsFeatureEnabled(v1pb.PlanFeature_FEATURE_DIRECTORY_SYNC); err != nil {
return c.String(http.StatusForbidden, err.Error())
}
+ return next(c)
+ }
+}
+
+// https://developer.xurrent.com/v1/scim/service_provider_config/
+// https://scim.cloud/
+// https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups
+// https://developer.okta.com/docs/reference/scim/scim-20/
+func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
+ // Apply authentication and license check middleware to all SCIM endpoints.
+ g.Use(s.scimAuthMiddleware)
+
+ // ServiceProviderConfig endpoint allows SCIM clients to discover server capabilities.
+ // This is required by Okta and recommended by the SCIM 2.0 specification.
+ // Docs: https://datatracker.ietf.org/doc/html/rfc7644#section-4
+ g.GET("/workspaces/:workspaceID/ServiceProviderConfig", func(c echo.Context) error {
+ config := &ServiceProviderConfig{
+ Schemas: []string{
+ "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig",
+ },
+ DocumentationURI: "https://www.bytebase.com/docs/administration/scim/overview",
+ Patch: ServiceProviderConfigPatch{
+ Supported: true,
+ },
+ Bulk: ServiceProviderConfigBulk{
+ Supported: false,
+ MaxOperations: 0,
+ MaxPayloadSize: 0,
+ },
+ Filter: ServiceProviderConfigFilter{
+ Supported: true,
+ MaxResults: 100,
+ },
+ ChangePassword: ServiceProviderConfigSupported{
+ Supported: false,
+ },
+ Sort: ServiceProviderConfigSupported{
+ Supported: false,
+ },
+ Etag: ServiceProviderConfigSupported{
+ Supported: false,
+ },
+ AuthenticationSchemes: []AuthenticationScheme{
+ {
+ Type: "oauthbearertoken",
+ Name: "OAuth Bearer Token",
+ Description: "Authentication scheme using the OAuth Bearer Token Standard",
+ },
+ },
+ }
+ return c.JSON(http.StatusOK, config)
+ })
+
+ g.POST("/workspaces/:workspaceID/Users", func(c echo.Context) error {
+ ctx := c.Request().Context()
+ source := detectSCIMSource(c)
body, err := io.ReadAll(c.Request().Body)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read body, error %v", err))
}
- var aadUser AADUser
- if err := json.Unmarshal(body, &aadUser); err != nil {
+ var scimUser SCIMUser
+ if err := json.Unmarshal(body, &scimUser); err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal body, error %v", err))
}
// Normalize email to lowercase as Bytebase requires lowercase emails
- normalizedEmail := normalizeEmail(aadUser.UserName)
+ normalizedEmail := normalizeEmail(scimUser.UserName)
user, err := s.store.GetUserByEmail(ctx, normalizedEmail)
if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to get user %s, error %v", aadUser.UserName, err))
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to get user %s, error %v", scimUser.UserName, err))
}
if user == nil {
password, err := common.RandomString(20)
@@ -68,89 +136,53 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to generate password hash, error %v", err))
}
newUser, err := s.store.CreateUser(ctx, &store.UserMessage{
- Name: aadUser.DisplayName,
+ Name: scimUser.DisplayName,
Email: normalizedEmail,
Type: storepb.PrincipalType_END_USER,
- MemberDeleted: !aadUser.Active,
+ MemberDeleted: !scimUser.Active,
PasswordHash: string(passwordHash),
Profile: &storepb.UserProfile{
- Source: entraIDSource,
+ Source: source,
},
})
if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf(`failed to create user "%s", error %v`, aadUser.UserName, err))
+ return c.String(http.StatusInternalServerError, fmt.Sprintf(`failed to create user "%s", error %v`, scimUser.UserName, err))
}
user = newUser
} else {
- deleted := !aadUser.Active
- updatedUser, err := s.store.UpdateUser(ctx, user, &store.UpdateUserMessage{
- Delete: &deleted,
- Name: &aadUser.DisplayName,
- Email: &normalizedEmail,
- Profile: &storepb.UserProfile{
- Source: entraIDSource,
- LastLoginTime: user.Profile.LastLoginTime,
- LastChangePasswordTime: user.Profile.LastChangePasswordTime,
- },
- })
+ updatedUser, err := s.updateUserFromSCIM(ctx, user, &scimUser, source)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf(`failed to update user "%s", error %v`, user.Email, err))
}
user = updatedUser
}
- return c.JSON(http.StatusCreated, convertToAADUser(user))
+ return c.JSON(http.StatusCreated, convertToSCIMUser(user))
})
// Get a single user. The user id is the Bytebase user uid.
g.GET("/workspaces/:workspaceID/Users/:userID", func(c echo.Context) error {
ctx := c.Request().Context()
- if err := s.validRequestURL(ctx, c); err != nil {
- return c.String(http.StatusInternalServerError, err.Error())
- }
- if err := s.licenseService.IsFeatureEnabled(v1pb.PlanFeature_FEATURE_DIRECTORY_SYNC); err != nil {
- return c.String(http.StatusForbidden, err.Error())
- }
-
- uid, err := strconv.Atoi(c.Param("userID"))
+ user, err := s.getUser(ctx, c)
if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to parse user id, error %v", err))
+ return err
}
- user, err := s.store.GetUserByID(ctx, uid)
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to get user, error %v", err))
- }
- if user == nil || user.MemberDeleted {
- return c.JSON(http.StatusNotFound, map[string]any{
- "schemas": []string{
- "urn:ietf:params:scim:api:messages:2.0:Error",
- },
- "status": "404",
- })
- }
-
- return c.JSON(http.StatusOK, convertToAADUser(user))
+ return c.JSON(http.StatusOK, convertToSCIMUser(user))
})
- // List users. AAD SCIM will send ?filter=userName eq "{email}" query.
- // userName maps to userPrincipalName in Azure, which is typically the user's email.
+ // List users. SCIM clients (Okta, Azure) send ?filter=userName eq "{email}" query.
+ // userName maps to userPrincipalName in Azure or login in Okta, which is typically the user's email.
// Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups#get-user-by-query
+ // Docs: https://developer.okta.com/docs/reference/scim/scim-20/
g.GET("/workspaces/:workspaceID/Users", func(c echo.Context) error {
ctx := c.Request().Context()
- if err := s.validRequestURL(ctx, c); err != nil {
- return c.String(http.StatusInternalServerError, err.Error())
- }
- if err := s.licenseService.IsFeatureEnabled(v1pb.PlanFeature_FEATURE_DIRECTORY_SYNC); err != nil {
- return c.String(http.StatusForbidden, err.Error())
- }
-
response := &ListUsersResponse{
Schemas: []string{
"urn:ietf:params:scim:api:messages:2.0:ListResponse",
},
TotalResults: 0,
- Resources: []*AADUser{},
+ Resources: []*SCIMUser{},
}
filter := c.QueryParam("filter")
@@ -188,7 +220,7 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
continue
}
response.TotalResults++
- response.Resources = append(response.Resources, convertToAADUser(user))
+ response.Resources = append(response.Resources, convertToSCIMUser(user))
}
return c.JSON(http.StatusOK, response)
@@ -196,24 +228,9 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
g.DELETE("/workspaces/:workspaceID/Users/:userID", func(c echo.Context) error {
ctx := c.Request().Context()
- if err := s.validRequestURL(ctx, c); err != nil {
- return c.String(http.StatusInternalServerError, err.Error())
- }
- if err := s.licenseService.IsFeatureEnabled(v1pb.PlanFeature_FEATURE_DIRECTORY_SYNC); err != nil {
- return c.String(http.StatusForbidden, err.Error())
- }
-
- uid, err := strconv.Atoi(c.Param("userID"))
+ user, err := s.getUser(ctx, c)
if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to parse user id, error %v", err))
- }
-
- user, err := s.store.GetUserByID(ctx, uid)
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to get user, error %v", err))
- }
- if user == nil || user.MemberDeleted {
- return c.String(http.StatusNoContent, "")
+ return err
}
deleteUser := true
@@ -226,15 +243,36 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
return c.String(http.StatusNoContent, "")
})
- g.PATCH("/workspaces/:workspaceID/Users/:userID", func(c echo.Context) error {
+ // PUT replaces the entire user resource. Required by SCIM 2.0 (RFC 7644 Section 3.5.1).
+ // Body format is same as POST (full SCIMUser object).
+ g.PUT("/workspaces/:workspaceID/Users/:userID", func(c echo.Context) error {
ctx := c.Request().Context()
- if err := s.validRequestURL(ctx, c); err != nil {
- return c.String(http.StatusInternalServerError, err.Error())
+ user, err := s.getUser(ctx, c)
+ if err != nil {
+ return err
}
- if err := s.licenseService.IsFeatureEnabled(v1pb.PlanFeature_FEATURE_DIRECTORY_SYNC); err != nil {
- return c.String(http.StatusForbidden, err.Error())
+
+ source := detectSCIMSource(c)
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read body, error %v", err))
+ }
+
+ var scimUser SCIMUser
+ if err := json.Unmarshal(body, &scimUser); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal body, error %v", err))
}
+ updatedUser, err := s.updateUserFromSCIM(ctx, user, &scimUser, source)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf(`failed to update user "%s", error %v`, user.Email, err))
+ }
+
+ return c.JSON(http.StatusOK, convertToSCIMUser(updatedUser))
+ })
+
+ g.PATCH("/workspaces/:workspaceID/Users/:userID", func(c echo.Context) error {
+ ctx := c.Request().Context()
body, err := io.ReadAll(c.Request().Body)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read body, error %v", err))
@@ -260,10 +298,14 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
updateUser := &store.UpdateUserMessage{}
for _, op := range patch.Operations {
- if op.OP != "Replace" {
- slog.Warn("unsupport operation type", slog.String("operation", op.OP), slog.String("path", op.Path))
+ // SCIM PATCH operations are case-insensitive per RFC 7644.
+ // Azure uses PascalCase (Replace), Okta uses lowercase (replace).
+ opLower := strings.ToLower(op.OP)
+ if opLower != "replace" {
+ slog.Warn("empty path only supports replace operation", slog.String("operation", op.OP))
continue
}
+
switch op.Path {
case "displayName":
displayName, ok := op.Value.(string)
@@ -289,8 +331,43 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
}
isDelete := !active
updateUser.Delete = &isDelete
+ case "":
+ // Empty path with replace operation - Okta sends full resource attributes.
+ // Per RFC 7644 Section 3.5.2.3: If path is omitted, the value must be a complex
+ // attribute containing sub-attributes to replace.
+ valueMap, ok := op.Value.(map[string]any)
+ if !ok {
+ slog.Warn("unsupport value for empty path, expect object", slog.String("operation", op.OP), slog.Any("value", op.Value))
+ continue
+ }
+ // Extract user attributes from the value object
+ if displayName, ok := valueMap["displayName"].(string); ok {
+ updateUser.Name = &displayName
+ }
+ if userName, ok := valueMap["userName"].(string); ok {
+ normalizedEmail := normalizeEmail(userName)
+ updateUser.Email = &normalizedEmail
+ }
+ if active, ok := valueMap["active"].(bool); ok {
+ isDelete := !active
+ updateUser.Delete = &isDelete
+ }
+ // Handle nested name object (name.givenName, name.familyName)
+ if nameObj, ok := valueMap["name"].(map[string]any); ok {
+ var nameParts []string
+ if givenName, ok := nameObj["givenName"].(string); ok {
+ nameParts = append(nameParts, givenName)
+ }
+ if familyName, ok := nameObj["familyName"].(string); ok {
+ nameParts = append(nameParts, familyName)
+ }
+ if len(nameParts) > 0 {
+ fullName := strings.Join(nameParts, " ")
+ updateUser.Name = &fullName
+ }
+ }
default:
- slog.Warn("unsupport patch", slog.String("operation", op.OP), slog.String("path", op.Path))
+ slog.Warn("unsupport patch path", slog.String("operation", op.OP), slog.String("path", op.Path))
}
}
@@ -299,97 +376,77 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to update user, error %v", err))
}
- return c.JSON(http.StatusOK, convertToAADUser(updatedUser))
+ return c.JSON(http.StatusOK, convertToSCIMUser(updatedUser))
})
g.POST("/workspaces/:workspaceID/Groups", func(c echo.Context) error {
ctx := c.Request().Context()
- if err := s.validRequestURL(ctx, c); err != nil {
- return c.String(http.StatusInternalServerError, err.Error())
- }
- if err := s.licenseService.IsFeatureEnabled(v1pb.PlanFeature_FEATURE_DIRECTORY_SYNC); err != nil {
- return c.String(http.StatusForbidden, err.Error())
- }
+ source := detectSCIMSource(c)
body, err := io.ReadAll(c.Request().Body)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read body, error %v", err))
}
- var aadGroup AADGroup
- if err := json.Unmarshal(body, &aadGroup); err != nil {
+ var scimGroup SCIMGroup
+ if err := json.Unmarshal(body, &scimGroup); err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal body, error %v", err))
}
- // Azure SCIM sync group process:
- // 1. POST users
- // 2. POST group without members
- // 3. PATCH group with members
+ // SCIM sync group process:
+ // - Azure: POST group without members, then PATCH to add members
+ // - Okta: May POST group with members directly
+ var members []*storepb.GroupMember
+ for _, scimMember := range scimGroup.Members {
+ member, err := s.getGroupMember(ctx, scimMember)
+ if err != nil {
+ slog.Error("failed to get scim group member", slog.Any("member", scimMember), log.BBError(err))
+ continue
+ }
+ members = append(members, member)
+ }
+
group, err := s.store.CreateGroup(ctx, &store.GroupMessage{
- ID: aadGroup.ExternalID,
- Email: aadGroup.Email,
- Title: aadGroup.DisplayName,
+ ID: scimGroup.ExternalID,
+ Email: scimGroup.Email,
+ Title: scimGroup.DisplayName,
Payload: &storepb.GroupPayload{
- Source: entraIDSource,
+ Source: source,
+ Members: members,
},
})
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to create group, error %v", err))
}
- return c.JSON(http.StatusCreated, convertToAADGroup(group))
+ return c.JSON(http.StatusCreated, convertToSCIMGroup(group))
})
// Get a single group. The group id is the Bytebase group resource id.
g.GET("/workspaces/:workspaceID/Groups/:groupID", func(c echo.Context) error {
ctx := c.Request().Context()
- if err := s.validRequestURL(ctx, c); err != nil {
- return c.String(http.StatusInternalServerError, err.Error())
- }
- if err := s.licenseService.IsFeatureEnabled(v1pb.PlanFeature_FEATURE_DIRECTORY_SYNC); err != nil {
- return c.String(http.StatusForbidden, err.Error())
- }
-
- groupName, err := decodeGroupIdentifier(c.Param("groupID"))
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to parse group %v, error %v", c.Param("groupID"), err))
- }
- group, err := utils.GetGroupByName(ctx, s.store, groupName)
+ group, err := s.getGroup(ctx, c)
if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to find group, error %v", err))
- }
- if group == nil {
- return c.JSON(http.StatusNotFound, map[string]any{
- "schemas": []string{
- "urn:ietf:params:scim:api:messages:2.0:Error",
- },
- "status": "404",
- })
+ return err
}
- return c.JSON(http.StatusOK, convertToAADGroup(group))
+ return c.JSON(http.StatusOK, convertToSCIMGroup(group))
})
- // List groups. AAD SCIM will send ?filter=externalId eq "{value}" query.
- // externalId can be Azure's objectId or group email depending on customer's attribute mapping:
- // - New default: objectId -> externalId (recommended, stable across email changes)
+ // List groups. SCIM clients (Okta, Azure) send ?filter=externalId eq "{value}" query.
+ // externalId can be the IdP's group ID or group email depending on customer's attribute mapping:
+ // - Default: objectId/groupId -> externalId (recommended, stable across email changes)
// - Legacy mapping: mail -> externalId (for backward compatibility)
// Docs: https://learn.microsoft.com/en-us/entra/identity/app-provisioning/use-scim-to-provision-users-and-groups#get-group-by-query
+ // Docs: https://developer.okta.com/docs/reference/scim/scim-20/
g.GET("/workspaces/:workspaceID/Groups", func(c echo.Context) error {
ctx := c.Request().Context()
- if err := s.validRequestURL(ctx, c); err != nil {
- return c.String(http.StatusInternalServerError, err.Error())
- }
- if err := s.licenseService.IsFeatureEnabled(v1pb.PlanFeature_FEATURE_DIRECTORY_SYNC); err != nil {
- return c.String(http.StatusForbidden, err.Error())
- }
-
response := &ListGroupsResponse{
Schemas: []string{
"urn:ietf:params:scim:api:messages:2.0:ListResponse",
},
TotalResults: 0,
- Resources: []*AADGroup{},
+ Resources: []*SCIMGroup{},
}
filter := c.QueryParam("filter")
@@ -412,8 +469,8 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
slog.Warn("unsupport filter key", slog.String("key", expr.Key), slog.String("operator", string(expr.Operator)), slog.String("value", expr.Value))
continue
}
- // externalId can be either Azure's objectId or group email, depending on customer's attribute mapping.
- // - New default: objectId -> externalId (UUID format, no @)
+ // externalId can be either the IdP's group ID or group email, depending on customer's attribute mapping.
+ // - Default: objectId/groupId -> externalId (UUID format, no @)
// - Legacy mapping: mail -> externalId (email format, contains @)
if strings.Contains(expr.Value, "@") {
find.Email = &expr.Value
@@ -429,7 +486,7 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
for _, group := range groups {
response.TotalResults++
- response.Resources = append(response.Resources, convertToAADGroup(group))
+ response.Resources = append(response.Resources, convertToSCIMGroup(group))
}
return c.JSON(http.StatusOK, response)
@@ -437,28 +494,9 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
g.DELETE("/workspaces/:workspaceID/Groups/:groupID", func(c echo.Context) error {
ctx := c.Request().Context()
- if err := s.validRequestURL(ctx, c); err != nil {
- return c.String(http.StatusInternalServerError, err.Error())
- }
- if err := s.licenseService.IsFeatureEnabled(v1pb.PlanFeature_FEATURE_DIRECTORY_SYNC); err != nil {
- return c.String(http.StatusForbidden, err.Error())
- }
-
- groupName, err := decodeGroupIdentifier(c.Param("groupID"))
+ group, err := s.getGroup(ctx, c)
if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to parse group %v, error %v", c.Param("groupID"), err))
- }
- group, err := utils.GetGroupByName(ctx, s.store, groupName)
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to find group, error %v", err))
- }
- if group == nil {
- return c.JSON(http.StatusNotFound, map[string]any{
- "schemas": []string{
- "urn:ietf:params:scim:api:messages:2.0:Error",
- },
- "status": "404",
- })
+ return err
}
if err := s.store.DeleteGroup(ctx, group.ID); err != nil {
@@ -472,107 +510,114 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
return c.JSON(http.StatusNoContent, "")
})
- g.PATCH("/workspaces/:workspaceID/Groups/:groupID", func(c echo.Context) error {
+ // PUT replaces the entire group resource. Required by SCIM 2.0 (RFC 7644 Section 3.5.1).
+ // Body format is same as POST (full SCIMGroup object).
+ g.PUT("/workspaces/:workspaceID/Groups/:groupID", func(c echo.Context) error {
ctx := c.Request().Context()
- if err := s.validRequestURL(ctx, c); err != nil {
- return c.String(http.StatusInternalServerError, err.Error())
- }
- if err := s.licenseService.IsFeatureEnabled(v1pb.PlanFeature_FEATURE_DIRECTORY_SYNC); err != nil {
- return c.String(http.StatusForbidden, err.Error())
+ group, err := s.getGroup(ctx, c)
+ if err != nil {
+ return err
}
+ source := detectSCIMSource(c)
body, err := io.ReadAll(c.Request().Body)
if err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read body, error %v", err))
}
- var patch PatchRequest
- if err := json.Unmarshal(body, &patch); err != nil {
+ var scimGroup SCIMGroup
+ if err := json.Unmarshal(body, &scimGroup); err != nil {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal body, error %v", err))
}
- groupName, err := decodeGroupIdentifier(c.Param("groupID"))
+ updatedGroup, err := s.updateGroupFromSCIM(ctx, group, &scimGroup, source)
if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to parse group %v, error %v", c.Param("groupID"), err))
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to update group, error %v", err))
+ }
+
+ if err := s.iamManager.ReloadCache(ctx); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to reload iam cache, error %v", err))
}
- group, err := utils.GetGroupByName(ctx, s.store, groupName)
+
+ return c.JSON(http.StatusOK, convertToSCIMGroup(updatedGroup))
+ })
+
+ g.PATCH("/workspaces/:workspaceID/Groups/:groupID", func(c echo.Context) error {
+ ctx := c.Request().Context()
+ group, err := s.getGroup(ctx, c)
if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to find group, error %v", err))
+ return err
}
- if group == nil {
- return c.JSON(http.StatusNotFound, map[string]any{
- "schemas": []string{
- "urn:ietf:params:scim:api:messages:2.0:Error",
- },
- "status": "404",
- })
+
+ source := detectSCIMSource(c)
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to read body, error %v", err))
+ }
+
+ var patch PatchRequest
+ if err := json.Unmarshal(body, &patch); err != nil {
+ return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to unmarshal body, error %v", err))
}
updateGroup := &store.UpdateGroupMessage{
ID: group.ID,
}
for _, op := range patch.Operations {
+ // SCIM PATCH operations are case-insensitive per RFC 7644.
+ opLower := strings.ToLower(op.OP)
+
switch op.Path {
case "members":
values, ok := op.Value.([]any)
if !ok {
- slog.Warn("unsupport value, expect PatchMember slice", slog.Any("value", op.Value), slog.String("operation", op.OP), slog.String("path", op.Path))
+ slog.Warn("unsupport value, expect SCIMMember slice", slog.Any("value", op.Value), slog.String("operation", op.OP), slog.String("path", op.Path))
continue
}
updateGroup.Payload = group.Payload
- updateGroup.Payload.Source = entraIDSource
+ updateGroup.Payload.Source = source
- for _, value := range values {
- var patchMember PatchMember
- bytes, err := json.Marshal(value)
- if err != nil {
- slog.Warn("failed to marshal patch member", slog.Any("value", value), slog.String("operation", op.OP), slog.String("path", op.Path), log.BBError(err))
- continue
- }
- if err := json.Unmarshal(bytes, &patchMember); err != nil {
- slog.Warn("failed to unmarshal patch member", slog.Any("value", value), slog.String("operation", op.OP), slog.String("path", op.Path), log.BBError(err))
- continue
- }
+ // For replace operation, clear existing members first
+ if opLower == "replace" {
+ updateGroup.Payload.Members = []*storepb.GroupMember{}
+ }
- // the member identifier in group patch is Bytebase user uid
- uid, err := strconv.Atoi(patchMember.Value)
- if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to parse user id, error %v", err))
- }
- user, err := s.store.GetUserByID(ctx, uid)
+ for _, value := range values {
+ member, err := s.getGroupMember(ctx, value)
if err != nil {
- return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to get user, error %v", err))
- }
- if user == nil {
- slog.Warn("cannot found user", slog.String("operation", op.OP), slog.String("uid", patchMember.Value))
+ slog.Error("failed to get scim group member", slog.Any("value", value), log.BBError(err))
continue
}
- member := &storepb.GroupMember{
- Member: common.FormatUserEmail(user.Email),
- Role: storepb.GroupMember_MEMBER,
- }
- index := slices.IndexFunc(group.Payload.Members, func(m *storepb.GroupMember) bool {
- return m.Member == member.Member
- })
- switch op.OP {
- case "Add":
+ // Azure uses PascalCase (Add/Remove), Okta uses lowercase (add/remove).
+ switch opLower {
+ case "add":
+ // For add: only add if not already a member
+ index := slices.IndexFunc(updateGroup.Payload.Members, func(m *storepb.GroupMember) bool {
+ return m.Member == member.Member
+ })
if index < 0 {
updateGroup.Payload.Members = append(updateGroup.Payload.Members, member)
}
- case "Remove":
+ case "remove":
+ index := slices.IndexFunc(updateGroup.Payload.Members, func(m *storepb.GroupMember) bool {
+ return m.Member == member.Member
+ })
if index >= 0 {
updateGroup.Payload.Members = slices.Delete(updateGroup.Payload.Members, index, index+1)
}
+ case "replace":
+ // For replace: members already cleared, just add all
+ updateGroup.Payload.Members = append(updateGroup.Payload.Members, member)
default:
- slog.Warn("unsupport operation type", slog.String("operation", op.OP), slog.String("path", op.Path))
+ slog.Warn("unsupport operation type for members", slog.String("operation", op.OP), slog.String("path", op.Path))
continue
}
}
case "displayName":
- if op.OP != "Replace" {
- slog.Warn("unsupport operation type", slog.String("operation", op.OP), slog.String("path", op.Path))
+ if opLower != "replace" {
+ slog.Warn("unsupport operation type for displayName", slog.String("operation", op.OP), slog.String("path", op.Path))
continue
}
displayName, ok := op.Value.(string)
@@ -581,13 +626,47 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
continue
}
updateGroup.Title = &displayName
+ case "":
+ // Empty path with replace operation - Okta sends full resource attributes.
+ // Per RFC 7644 Section 3.5.2.3: If path is omitted, the value must be a complex
+ // attribute containing sub-attributes to replace.
+ if opLower != "replace" {
+ slog.Warn("empty path only supports replace operation", slog.String("operation", op.OP))
+ continue
+ }
+ valueMap, ok := op.Value.(map[string]any)
+ if !ok {
+ slog.Warn("unsupport value for empty path, expect object", slog.String("operation", op.OP), slog.Any("value", op.Value))
+ continue
+ }
+ // Extract group attributes from the value object
+ if displayName, ok := valueMap["displayName"].(string); ok {
+ updateGroup.Title = &displayName
+ }
+ // Handle members array in the value object
+ if members, ok := valueMap["members"].([]any); ok {
+ updateGroup.Payload = group.Payload
+ updateGroup.Payload.Source = source
+ // Clear existing members for full replacement
+ updateGroup.Payload.Members = []*storepb.GroupMember{}
+
+ for _, memberValue := range members {
+ member, err := s.getGroupMember(ctx, memberValue)
+ if err != nil {
+ slog.Error("failed to get scim group member", slog.Any("value", memberValue), log.BBError(err))
+ continue
+ }
+ updateGroup.Payload.Members = append(updateGroup.Payload.Members, member)
+ }
+ }
default:
- slog.Warn("unsupport patch", slog.String("operation", op.OP), slog.String("path", op.Path))
+ slog.Warn("unsupport patch path", slog.String("operation", op.OP), slog.String("path", op.Path))
}
}
updatedGroup, err := s.store.UpdateGroup(ctx, updateGroup)
if err != nil {
+ slog.Error("failed to update group", log.BBError(err), slog.String("group", updateGroup.ID))
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to update group, error %v", err))
}
// Reload IAM cache to make sure the group members are updated.
@@ -595,7 +674,7 @@ func (s *Service) RegisterDirectorySyncRoutes(g *echo.Group) {
return c.String(http.StatusInternalServerError, fmt.Sprintf("failed to reload iam cache, error %v", err))
}
- return c.JSON(http.StatusOK, convertToAADGroup(updatedGroup))
+ return c.JSON(http.StatusOK, convertToSCIMGroup(updatedGroup))
})
}
@@ -641,6 +720,46 @@ func (s *Service) validRequestURL(ctx context.Context, c echo.Context) error {
return nil
}
+func (s *Service) getUser(ctx context.Context, c echo.Context) (*store.UserMessage, error) {
+ uid, err := strconv.Atoi(c.Param("userID"))
+ if err != nil {
+ return nil, c.String(http.StatusInternalServerError, fmt.Sprintf("failed to parse user id, error %v", err))
+ }
+
+ user, err := s.store.GetUserByID(ctx, uid)
+ if err != nil {
+ return nil, c.String(http.StatusInternalServerError, fmt.Sprintf("failed to get user, error %v", err))
+ }
+ if user == nil {
+ // PUT must not create new resources per RFC 7644
+ return nil, c.JSON(http.StatusNotFound, map[string]any{
+ "schemas": []string{"urn:ietf:params:scim:api:messages:2.0:Error"},
+ "status": "404",
+ })
+ }
+ return user, nil
+}
+
+func (s *Service) getGroup(ctx context.Context, c echo.Context) (*store.GroupMessage, error) {
+ groupName, err := decodeGroupIdentifier(c.Param("groupID"))
+ if err != nil {
+ return nil, c.String(http.StatusInternalServerError, fmt.Sprintf("failed to parse group %v, error %v", c.Param("groupID"), err))
+ }
+ group, err := utils.GetGroupByName(ctx, s.store, common.FormatGroupEmail(groupName))
+ if err != nil {
+ return nil, c.String(http.StatusInternalServerError, fmt.Sprintf("failed to find group, error %v", err))
+ }
+ if group == nil {
+ return nil, c.JSON(http.StatusNotFound, map[string]any{
+ "schemas": []string{
+ "urn:ietf:params:scim:api:messages:2.0:Error",
+ },
+ "status": "404",
+ })
+ }
+ return group, nil
+}
+
func decodeGroupIdentifier(groupID string) (string, error) {
identifier, err := url.QueryUnescape(groupID)
if err != nil {
@@ -649,8 +768,74 @@ func decodeGroupIdentifier(groupID string) (string, error) {
return identifier, nil
}
-func convertToAADUser(user *store.UserMessage) *AADUser {
- return &AADUser{
+func (s *Service) getGroupMember(ctx context.Context, memberValue any) (*storepb.GroupMember, error) {
+ var scimMember SCIMMember
+ bytes, err := json.Marshal(memberValue)
+ if err != nil {
+ return nil, err
+ }
+ if err := json.Unmarshal(bytes, &scimMember); err != nil {
+ return nil, err
+ }
+
+ uid, err := strconv.Atoi(scimMember.Value)
+ if err != nil {
+ return nil, err
+ }
+ user, err := s.store.GetUserByID(ctx, uid)
+ if err != nil {
+ return nil, err
+ }
+ if user == nil {
+ return nil, errors.Errorf("cannot find user %v", uid)
+ }
+
+ return &storepb.GroupMember{
+ Member: common.FormatUserEmail(user.Email),
+ Role: storepb.GroupMember_MEMBER,
+ }, nil
+}
+
+// updateUserFromSCIM updates an existing user with data from SCIMUser.
+// Used by both POST (when user exists) and PUT operations.
+func (s *Service) updateUserFromSCIM(ctx context.Context, user *store.UserMessage, scimUser *SCIMUser, source string) (*store.UserMessage, error) {
+ normalizedEmail := normalizeEmail(scimUser.UserName)
+ deleted := !scimUser.Active
+ patch := &store.UpdateUserMessage{
+ Delete: &deleted,
+ Name: &scimUser.DisplayName,
+ Email: &normalizedEmail,
+ Profile: user.Profile,
+ }
+ patch.Profile.Source = source
+ return s.store.UpdateUser(ctx, user, patch)
+}
+
+// updateGroupFromSCIM updates an existing group with data from SCIMGroup.
+// Used by both POST (when group exists) and PUT operations.
+func (s *Service) updateGroupFromSCIM(ctx context.Context, group *store.GroupMessage, scimGroup *SCIMGroup, source string) (*store.GroupMessage, error) {
+ var members []*storepb.GroupMember
+ for _, scimMember := range scimGroup.Members {
+ member, err := s.getGroupMember(ctx, scimMember)
+ if err != nil {
+ slog.Error("failed to get scim group member", slog.Any("member", scimMember), log.BBError(err))
+ continue
+ }
+ members = append(members, member)
+ }
+
+ return s.store.UpdateGroup(ctx, &store.UpdateGroupMessage{
+ ID: group.ID,
+ Title: &scimGroup.DisplayName,
+ Payload: &storepb.GroupPayload{
+ Source: source,
+ Members: members,
+ },
+ })
+}
+
+func convertToSCIMUser(user *store.UserMessage) *SCIMUser {
+ return &SCIMUser{
Schemas: []string{
"urn:ietf:params:scim:schemas:core:2.0:User",
},
@@ -658,31 +843,35 @@ func convertToAADUser(user *store.UserMessage) *AADUser {
Active: !user.MemberDeleted,
DisplayName: user.Name,
ID: fmt.Sprintf("%d", user.ID),
- Emails: []*AADUserEmail{
+ Emails: []*SCIMUserEmail{
{
Type: "work",
Primary: true,
Value: user.Email,
},
},
- Meta: &AADResourceMeta{
+ Meta: &SCIMResourceMeta{
ResourceType: "User",
},
}
}
-func convertToAADGroup(group *store.GroupMessage) *AADGroup {
- return &AADGroup{
+func convertToSCIMGroup(group *store.GroupMessage) *SCIMGroup {
+ // Return empty members array. IdPs track members on their side and use PATCH to update.
+ // Note: Returning actual members would require looking up user IDs for each member email,
+ // which is expensive and not typically needed since IdPs don't rely on GET responses for member state.
+ return &SCIMGroup{
Schemas: []string{
"urn:ietf:params:scim:schemas:core:2.0:Group",
},
- // We use the azure group object id (external id) to create the group.
+ // We use the IdP's group object id (external id) to create the group.
// So both ID and ExternalID should be the group.ID (equals external id).
ID: group.ID,
ExternalID: group.ID,
Email: group.Email,
DisplayName: group.Title,
- Meta: &AADResourceMeta{
+ Members: []*SCIMMember{},
+ Meta: &SCIMResourceMeta{
ResourceType: "Group",
},
}
diff --git a/backend/store/group.go b/backend/store/group.go
index 9f172c8f31..ffe2e62015 100644
--- a/backend/store/group.go
+++ b/backend/store/group.go
@@ -233,7 +233,9 @@ func (s *Store) CreateGroup(ctx context.Context, create *GroupMessage) (*GroupMe
return nil, errors.Wrap(err, "failed to commit")
}
- s.groupCache.Add(create.Email, create)
+ if create.Email != "" {
+ s.groupCache.Add(create.Email, create)
+ }
return create, nil
}
@@ -282,10 +284,11 @@ func (s *Store) UpdateGroup(ctx context.Context, patch *UpdateGroupMessage) (*Gr
var group GroupMessage
var payload []byte
+ var email sql.NullString
if err := tx.QueryRowContext(ctx, query, args...).Scan(
&group.ID,
- &group.Email,
+ &email,
&group.Title,
&group.Description,
&payload,
@@ -298,12 +301,17 @@ func (s *Store) UpdateGroup(ctx context.Context, patch *UpdateGroupMessage) (*Gr
return nil, err
}
group.Payload = &groupPayload
+ if email.Valid {
+ group.Email = email.String
+ }
if err := tx.Commit(); err != nil {
return nil, errors.Wrap(err, "failed to commit transaction")
}
- s.groupCache.Add(group.Email, &group)
+ if group.Email != "" {
+ s.groupCache.Add(group.Email, &group)
+ }
return &group, nil
}
@@ -321,7 +329,7 @@ func (s *Store) DeleteGroup(ctx context.Context, id string) error {
return errors.Wrapf(err, "failed to build sql")
}
- var email string
+ var email sql.NullString
if err := tx.QueryRowContext(ctx, query, args...).Scan(&email); err != nil {
return err
}
@@ -330,7 +338,9 @@ func (s *Store) DeleteGroup(ctx context.Context, id string) error {
return errors.Wrap(err, "failed to commit transaction")
}
- s.groupCache.Remove(email)
+ if email.Valid && email.String != "" {
+ s.groupCache.Remove(email.String)
+ }
return nil
}
diff --git a/frontend/src/components/User/Settings/AADSyncDrawer.vue b/frontend/src/components/User/Settings/AADSyncDrawer.vue
index b194c8ad49..e6c1f9e1d7 100644
--- a/frontend/src/components/User/Settings/AADSyncDrawer.vue
+++ b/frontend/src/components/User/Settings/AADSyncDrawer.vue
@@ -23,10 +23,6 @@
</div>
<div class="text-sm text-gray-400">
{{ $t(`settings.members.entra-sync.endpoint-tip`) }}
- <LearnMoreLink
- url="https://aka.ms/MSEntraPortal"
- :text="$t('settings.members.entra-sync.goto-entra-dashboard')"
- />
</div>
</div>
<div class="flex gap-x-2">
@@ -56,10 +52,6 @@
</div>
<div class="text-sm text-gray-400">
{{ $t("settings.members.entra-sync.secret-token-tip") }}
- <LearnMoreLink
- url="https://aka.ms/MSEntraPortal"
- :text="$t('settings.members.entra-sync.goto-entra-dashboard')"
- />
</div>
</div>
<div class="flex gap-x-2">
diff --git a/frontend/src/components/User/Settings/CreateGroupDrawer.vue b/frontend/src/components/User/Settings/CreateGroupDrawer.vue
index 1273deb724..baa4c46662 100644
--- a/frontend/src/components/User/Settings/CreateGroupDrawer.vue
+++ b/frontend/src/components/User/Settings/CreateGroupDrawer.vue
@@ -111,7 +111,7 @@
quaternary
size="small"
:group="group!"
- @removed="$emit('close')"
+ @removed="$emit('removed', group!)"
>
<template #icon>
<Trash2Icon class="w-4 h-auto" />
@@ -189,6 +189,7 @@ const props = defineProps<{
const emit = defineEmits<{
(event: "close"): void;
+ (event: "removed", group: Group): void;
(event: "updated", group: Group): void;
}>();
diff --git a/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue b/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue
index 6042ac8816..b944664419 100644
--- a/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue
+++ b/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupNameCell.vue
@@ -31,8 +31,8 @@
</span>
<UserRolesCell v-if="role" :role="role" />
</div>
- <span v-if="showEmail" class="textinfolabel text-sm">
- {{ extractGroupEmail(group.name) }}
+ <span v-if="showEmail && group.email" class="textinfolabel text-sm">
+ {{ group.email }}
</span>
</div>
</div>
@@ -45,7 +45,7 @@ import { computed } from "vue";
import UserRolesCell from "@/components/Member/MemberDataTable/cells/UserRolesCell.vue";
import type { MemberRole } from "@/components/Member/types";
import { WORKSPACE_ROUTE_USERS } from "@/router/dashboard/workspaceRoutes";
-import { extractGroupEmail, extractUserId, useCurrentUserV1 } from "@/store";
+import { extractUserId, useCurrentUserV1 } from "@/store";
import type { Group } from "@/types/proto-es/v1/group_service_pb";
import { hasWorkspacePermissionV2 } from "@/utils";
diff --git a/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupOperationsCell.vue b/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupOperationsCell.vue
index bad17f8d8c..3ad245407c 100644
--- a/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupOperationsCell.vue
+++ b/frontend/src/components/User/Settings/UserDataTableByGroup/cells/GroupOperationsCell.vue
@@ -1,6 +1,6 @@
<template>
<div class="flex justify-end gap-x-2">
- <RemoveGroupButton v-if="allowDeleteGroup" :group="group!">
+ <RemoveGroupButton v-if="allowDeleteGroup" :group="group" @removed="$emit('remove-group')">
<Trash2Icon class="w-4 h-auto" />
</RemoveGroupButton>
@@ -30,6 +30,7 @@ const props = defineProps<{
defineEmits<{
(event: "update-group"): void;
+ (event: "remove-group"): void;
}>();
const currentUser = useCurrentUserV1();
diff --git a/frontend/src/components/User/Settings/UserDataTableByGroup/index.vue b/frontend/src/components/User/Settings/UserDataTableByGroup/index.vue
index 314e8c312a..efbb4f474e 100644
--- a/frontend/src/components/User/Settings/UserDataTableByGroup/index.vue
+++ b/frontend/src/components/User/Settings/UserDataTableByGroup/index.vue
@@ -58,6 +58,7 @@ const props = withDefaults(
const emit = defineEmits<{
(event: "update-group", group: Group): void;
+ (event: "remove-group", group: Group): void;
}>();
const { t } = useI18n();
@@ -128,6 +129,9 @@ const columns = computed(() => {
"onUpdate-group": () => {
emit("update-group", row.group);
},
+ "onRemove-group": () => {
+ emit("remove-group", row.group);
+ },
});
} else {
return "";
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 1f6de40b75..926c77b99b 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -515,15 +515,14 @@
"add-member": "Add member",
"add-user": "Add user",
"entra-sync": {
- "self": "Sync from Entra ID (Azure AD)",
- "description": "Sync users and groups from Entra ID (formerly Azure AD) to your Bytebase instance.",
+ "self": "Sync from SCIM",
+ "description": "Sync users and groups from Entra ID (formerly Azure AD) or Okta to your Bytebase instance.",
"endpoint": "Endpoint",
- "endpoint-tip": "Entra will sync users and groups to Bytebase via this endpoint. Paste this to the \"Tenant URL\" field in Entra.",
+ "endpoint-tip": "Users and groups will be synced to Bytebase via this endpoint.",
"secret-token": "Secret Token",
- "secret-token-tip": "Paste this to the \"Secret Token\" field in Entra.",
+ "secret-token-tip": "The verification token for the endpoint. Please keep it in secret.",
"reset-token": "Reset token",
- "reset-token-warning": "You need to update the Entra application provisioning config.",
- "goto-entra-dashboard": "Go to Entra Dashboard"
+ "reset-token-warning": "You need to update the application provisioning config."
},
"all-users": "All users",
"search-member": "Search member",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 0ac50b3c84..bc9ceeb45b 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -515,15 +515,14 @@
"add-member": "Agregar miembro",
"add-user": "Agregar usuario",
"entra-sync": {
- "self": "Sincronización desde Entra ID (Azure AD)",
- "description": "Sincronice usuarios y grupos de Entra ID (anteriormente Azure AD) con su instancia de Bytebase.",
+ "self": "Sincronización desde SCIM",
+ "description": "Sincronice usuarios y grupos de Entra ID (anteriormente Azure AD) u Okta con su instancia de Bytebase.",
"endpoint": "Punto final",
- "endpoint-tip": "Pegue esto en el campo \"Tenant URL\" en Entra. Entra sincronizará usuarios y grupos con Bytebase a través de este punto de conexión.",
+ "endpoint-tip": "Los usuarios y grupos se sincronizarán con Bytebase a través de este endpoint.",
"secret-token": "Secret Token",
- "secret-token-tip": "Pegue esto en el campo \"Secret Token\" en Entra.",
+ "secret-token-tip": "El token de verificación para el endpoint. Por favor, manténgalo en secreto.",
"reset-token": "Restablecer token",
- "reset-token-warning": "Debe actualizar la configuración de aprovisionamiento de aplicaciones de Entra.",
- "goto-entra-dashboard": "Ir al panel de control de Entra"
+ "reset-token-warning": "Debe actualizar la configuración de aprovisionamiento de aplicaciones de Entra."
},
"all-users": "Todos los usuarios",
"search-member": "Buscar miembro",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 9dbc916fbf..d1f33daee2 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -515,15 +515,14 @@
"add-member": "メンバーを追加",
"add-user": "ユーザーを追加",
"entra-sync": {
- "self": "Entra ID (Azure AD) から同期",
- "description": "Entra ID (旧 Azure AD) のユーザーとグループを Bytebase インスタンスに同期します。",
+ "self": "SCIM から同期",
+ "description": "Entra ID (旧 Azure AD) または Okta のユーザーとグループを Bytebase インスタンスに同期します。",
"endpoint": "Endpoint",
- "endpoint-tip": "これを Entra の「Tenant URL」フィールドに貼り付けます。Entra は、このエンドポイントを介してユーザーとグループを Bytebase に同期します。",
+ "endpoint-tip": "ユーザーとグループはこのエンドポイントを介して Bytebase に同期されます。",
"secret-token": "Secret Token",
- "secret-token-tip": "これを Entra の「Secret Token」フィールドに貼り付けます。",
+ "secret-token-tip": "エンドポイントの検証トークンです。秘密にしてください。",
"reset-token": "トークンをリセット",
- "reset-token-warning": "Entra アプリケーションのプロビジョニング設定を更新する必要があります。",
- "goto-entra-dashboard": "Entraダッシュボードへ"
+ "reset-token-warning": "Entra アプリケーションのプロビジョニング設定を更新する必要があります。"
},
"all-users": "すべてのユーザー",
"search-member": "メンバーを検索",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 85a7c002da..3276581e0b 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -515,15 +515,14 @@
"add-member": "Thêm thành viên",
"add-user": "Thêm người dùng",
"entra-sync": {
- "self": "Đồng bộ từ Entra ID (Azure AD)",
- "description": "Đồng bộ người dùng và nhóm từ Entra ID (trước đây là Azure AD) sang phiên bản Bytebase của bạn.",
+ "self": "Đồng bộ từ SCIM",
+ "description": "Đồng bộ người dùng và nhóm từ Entra ID (trước đây là Azure AD) hoặc Okta sang phiên bản Bytebase của bạn.",
"endpoint": "Điểm cuối",
- "endpoint-tip": "Dán vào trường \"Tenant URL\" trong Entra. Entra sẽ đồng bộ người dùng và nhóm đến Bytebase qua điểm cuối này.",
+ "endpoint-tip": "Người dùng và nhóm sẽ được đồng bộ đến Bytebase qua điểm cuối này.",
"secret-token": "Mã thông báo bí mật",
- "secret-token-tip": "Dán vào trường \"Secret Token\" trong Entra.",
+ "secret-token-tip": "Mã xác thực cho điểm cuối. Vui lòng giữ bí mật.",
"reset-token": "Đặt lại mã thông báo",
- "reset-token-warning": "Bạn cần cập nhật cấu hình cung cấp ứng dụng Entra.",
- "goto-entra-dashboard": "Đi tới Bảng điều khiển Entra"
+ "reset-token-warning": "Bạn cần cập nhật cấu hình cung cấp ứng dụng Entra."
},
"all-users": "Tất cả người dùng",
"search-member": "Tìm kiếm thành viên",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 50ddde478f..d6c7753ccd 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -515,15 +515,14 @@
"add-member": "添加成员",
"add-user": "添加用户",
"entra-sync": {
- "self": "从 Entra ID (Azure AD) 同步",
- "description": "将 Entra ID(前 Azure AD)中的用户和组同步到您的 Bytebase 实例。",
+ "self": "从 SCIM 同步",
+ "description": "将 Entra ID(前 Azure AD)或 Okta 中的用户和组同步到您的 Bytebase 实例。",
"endpoint": "Endpoint",
- "endpoint-tip": "将其粘贴到 Entra 中的「Tenant URL」字段。Entra 将通过该 endpoint 将用户和组同步到 Bytebase。",
+ "endpoint-tip": "用户和组将通过此端点同步到 Bytebase。",
"secret-token": "Secret Token",
- "secret-token-tip": "将其粘贴到 Entra 中的「Secret Token」字段。",
+ "secret-token-tip": "端点的验证令牌,请妥善保管。",
"reset-token": "重置密钥",
- "reset-token-warning": "您需要更新 Entra 应用程序配置。",
- "goto-entra-dashboard": "前往 Entra 配置"
+ "reset-token-warning": "您需要更新 Entra 应用程序配置。"
},
"all-users": "全部用户",
"search-member": "搜索成员",
diff --git a/frontend/src/views/SettingWorkspaceUsers.vue b/frontend/src/views/SettingWorkspaceUsers.vue
index b5902f39b9..83cc57e506 100644
--- a/frontend/src/views/SettingWorkspaceUsers.vue
+++ b/frontend/src/views/SettingWorkspaceUsers.vue
@@ -57,6 +57,7 @@
:loading="loading"
:on-click-user="onUserClick"
@update-group="handleUpdateGroup"
+ @remove-group="handleRemoveGroup"
/>
</template>
</PagedTable>
@@ -180,6 +181,10 @@
v-if="state.showCreateGroupDrawer"
:group="state.editingGroup"
@close="state.showCreateGroupDrawer = false"
+ @removed="(group) => {
+ handleRemoveGroup(group)
+ state.showCreateGroupDrawer = false
+ }"
@updated="handleGroupUpdated"
/>
@@ -443,6 +448,10 @@ const handleUpdateGroup = (group: Group) => {
state.showCreateGroupDrawer = true;
};
+const handleRemoveGroup = (group: Group) => {
+ groupPagedTable.value?.removeCache(group);
+};
+
const handleCreateUser = () => {
state.showCreateUserDrawer = true;
};