From f927eb639cbdb3c75f323ce4f5947e46497c4f8b Mon Sep 17 00:00:00 2001 From: Puja Thacker Date: Tue, 29 Jul 2025 11:23:26 +0530 Subject: [PATCH 1/6] Pushing changes for Atlan backend --- appconfig/default.yaml | 7 +- internal/controller/group_controller.go | 29 ++++++ pkg/clients/atlan/client.go | 115 ++++++++++++++++++++++ pkg/clients/atlan/team_membership.go | 22 +++++ pkg/clients/atlan/teams.go | 125 ++++++++++++++++++++++++ pkg/clients/atlan/users.go | 29 ++++++ pkg/clients/client.go | 10 +- 7 files changed, 335 insertions(+), 2 deletions(-) create mode 100644 pkg/clients/atlan/client.go create mode 100644 pkg/clients/atlan/team_membership.go create mode 100644 pkg/clients/atlan/teams.go create mode 100644 pkg/clients/atlan/users.go diff --git a/appconfig/default.yaml b/appconfig/default.yaml index 7c2504ca..b8928528 100644 --- a/appconfig/default.yaml +++ b/appconfig/default.yaml @@ -30,7 +30,6 @@ pattern: - input: "^([^\\_]+)$" output: "$1" - app: name: "usernaut" version: "0.0.1" @@ -81,3 +80,9 @@ backends: cert_path: "/path/to/usernaut.crt" private_key_path: "/path/to/usernaut.pem" service_account_name: test-service-account + - name: atlan + type: "atlan" + enabled: true + connection: + url: "https://yourcompany.atlan.com" + api_token: file|path/to/api_token diff --git a/internal/controller/group_controller.go b/internal/controller/group_controller.go index e7b0a1af..9cf5058a 100644 --- a/internal/controller/group_controller.go +++ b/internal/controller/group_controller.go @@ -310,6 +310,35 @@ func (r *GroupReconciler) fetchOrCreateTeam(ctx context.Context, return teamID, nil } } + + // ATLAN VALIDATION: Check if Rover group exists in CRs before creating Atlan team + if backendType == "atlan" { + groupList := &usernautdevv1alpha1.GroupList{} + if err := r.Client.List(ctx, groupList); err != nil { + r.backendLogger.WithError(err).Error("error listing Group CRs for Rover validation") + return "", err + } + + roverExists := false + for _, group := range groupList.Items { + if group.Spec.GroupName == groupName { + for _, backend := range group.Spec.Backends { + if backend.Type == "rover" { + roverExists = true + break + } + } + if roverExists { + break + } + } + } + + if !roverExists { + return "", errors.New("cannot create Atlan team: Rover group must exist first") + } + } + // If team details are not found in cache, create a new team r.backendLogger.Info("team details not found in cache, creating a new team") diff --git a/pkg/clients/atlan/client.go b/pkg/clients/atlan/client.go new file mode 100644 index 00000000..c2feeb63 --- /dev/null +++ b/pkg/clients/atlan/client.go @@ -0,0 +1,115 @@ +/* +Copyright 2025. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package atlan + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "slices" + "time" + + "github.com/gojek/heimdall/v7" + "github.com/redhat-data-and-ai/usernaut/pkg/request" + "github.com/redhat-data-and-ai/usernaut/pkg/request/httpclient" + "github.com/redhat-data-and-ai/usernaut/pkg/utils" +) + +// AtlanClient is a simple HTTP client for Atlan API +type AtlanClient struct { + client heimdall.Doer + url string + apiToken string +} + +// AtlanConfig holds the configuration needed to connect to Atlan +type AtlanConfig struct { + URL string `json:"url"` + APIToken string `json:"api_token"` +} + +// NewClient creates a new Atlan client with simple API token authentication +func NewClient(atlanAppConfig map[string]interface{}, + connectionPoolConfig httpclient.ConnectionPoolConfig, + hystrixResiliencyConfig httpclient.HystrixResiliencyConfig) (*AtlanClient, error) { + + atlanConfig := AtlanConfig{} + if err := utils.MapToStruct(atlanAppConfig, &atlanConfig); err != nil { + return nil, fmt.Errorf("failed to parse atlan configuration: %w", err) + } + + // Validate required fields + if atlanConfig.URL == "" { + return nil, fmt.Errorf("atlan configuration is missing required field: URL") + } + if atlanConfig.APIToken == "" { + return nil, fmt.Errorf("atlan configuration is missing required field: APIToken") + } + + // Initialize HTTP client without certificates (Atlan uses API token, not certs) + client, err := httpclient.InitializeClient( + "atlan", + connectionPoolConfig, + hystrixResiliencyConfig, + heimdall.NewRetrier(heimdall.NewConstantBackoff(100*time.Millisecond, 50*time.Millisecond)), // retry logic + 3, + nil) + if err != nil { + return nil, fmt.Errorf("failed to initialize http client: %w", err) + } + + return &AtlanClient{ + client: client, + url: atlanConfig.URL, + apiToken: atlanConfig.APIToken, + }, nil +} + +// sendRequest makes an HTTP request to the Atlan API with proper authentication +func (aC *AtlanClient) sendRequest(ctx context.Context, url string, method string, body interface{}, + headers map[string]string, methodName string) ([]byte, int, error) { + requestBody, err := json.Marshal(body) + if err != nil { + return nil, 0, fmt.Errorf("failed to marshal request body: %w", err) + } + + req, err := request.NewRequest(ctx, method, url, requestBody) + if err != nil { + return nil, 0, fmt.Errorf("failed to create request: %w", err) + } + + if headers == nil { + headers = make(map[string]string) + } + headers["Authorization"] = "Bearer " + aC.apiToken + headers["Content-Type"] = "application/json" + headers["Accept"] = "application/json" + + req.SetHeaders(headers) + + response, statusCode, err := req.MakeRequest(aC.client, methodName, "atlan") + if err != nil { + return nil, statusCode, fmt.Errorf("request failed: %w", err) + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, statusCode) { + return nil, statusCode, fmt.Errorf("unexpected status code: %d", statusCode) + } + + return response, statusCode, nil +} diff --git a/pkg/clients/atlan/team_membership.go b/pkg/clients/atlan/team_membership.go new file mode 100644 index 00000000..e8cf24d8 --- /dev/null +++ b/pkg/clients/atlan/team_membership.go @@ -0,0 +1,22 @@ +package atlan + +import ( + "context" + + "github.com/redhat-data-and-ai/usernaut/pkg/common/structs" +) + +func (ac *AtlanClient) FetchTeamMembersByTeamID(ctx context.Context, teamID string) (map[string]*structs.User, error) { + // Team membership is synced via LDAP, return empty map like Rover does + return make(map[string]*structs.User), nil +} + +func (ac *AtlanClient) AddUserToTeam(ctx context.Context, teamID, userID string) error { + // Team membership is synced via LDAP, return nil like Rover does + return nil +} + +func (ac *AtlanClient) RemoveUserFromTeam(ctx context.Context, teamID, userID string) error { + // Team membership is synced via LDAP, return nil like Rover does + return nil +} diff --git a/pkg/clients/atlan/teams.go b/pkg/clients/atlan/teams.go new file mode 100644 index 00000000..4238ccab --- /dev/null +++ b/pkg/clients/atlan/teams.go @@ -0,0 +1,125 @@ +package atlan + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/redhat-data-and-ai/usernaut/pkg/common/structs" + "github.com/redhat-data-and-ai/usernaut/pkg/logger" + "github.com/sirupsen/logrus" +) + +type AtlanGroup struct { + ID string `json:"id"` + Name string `json:"name"` +} + +type AtlanGroupsResponse struct { + TotalRecord int `json:"totalRecord"` + FilterRecord int `json:"filterRecord"` + Records []AtlanGroup `json:"records"` +} + +func (ac *AtlanClient) FetchAllTeams(ctx context.Context) (map[string]structs.Team, error) { + log := logger.Logger(ctx).WithField("service", "atlan") + log.Info("fetching all teams from Atlan") + + url := fmt.Sprintf("%s/api/service/v2/groups?columns=name", ac.url) + response, statusCode, err := ac.sendRequest(ctx, url, http.MethodGet, nil, nil, "FetchAllTeams") + if err != nil { + return nil, fmt.Errorf("failed to fetch teams from Atlan: %w", err) + } + + if statusCode != http.StatusOK { + return nil, fmt.Errorf("unexpected status code %d when fetching teams from Atlan", statusCode) + } + + var apiResponse AtlanGroupsResponse + if err := json.Unmarshal(response, &apiResponse); err != nil { + return nil, fmt.Errorf("failed to parse response from Atlan: %w", err) + } + + teams := make(map[string]structs.Team) + for _, group := range apiResponse.Records { + teams[group.ID] = structs.Team{ + ID: group.ID, + Name: group.Name, + } + } + + log.WithField("team_count", len(teams)).Info("successfully fetched teams from Atlan") + return teams, nil +} + +func (ac *AtlanClient) CreateTeam(ctx context.Context, team *structs.Team) (*structs.Team, error) { + log := logger.Logger(ctx).WithFields(logrus.Fields{ + "service": "atlan", + "team_name": team.Name, + }) + + log.Info("creating team in Atlan") + + url := fmt.Sprintf("%s/api/service/groups", ac.url) + + // Convert team name to valid internal name as per Atlan guidelines (lowercase, alphanumeric + underscore only) + internalName := strings.ToLower(strings.ReplaceAll(team.Name, " ", "_")) + internalName = strings.ReplaceAll(internalName, "-", "_") + + requestBody := map[string]interface{}{ + "group": map[string]interface{}{ + "attributes": map[string]interface{}{ + "alias": []string{team.Name}, + "isDefault": []string{"false"}, + }, + "name": internalName, // Sanitized internal name + }, + } + + response, statusCode, err := ac.sendRequest(ctx, url, http.MethodPost, requestBody, nil, "CreateTeam") + if err != nil { + return nil, fmt.Errorf("failed to create team in Atlan: %w", err) + } + + if statusCode != http.StatusCreated && statusCode != http.StatusOK { + return nil, fmt.Errorf("unexpected status code %d when creating team in Atlan", statusCode) + } + + var createdGroup AtlanGroup + if err := json.Unmarshal(response, &createdGroup); err != nil { + return nil, fmt.Errorf("failed to parse created team response from Atlan: %w", err) + } + + log.WithField("team_id", createdGroup.ID).Info("successfully created team in Atlan") + return &structs.Team{ + ID: createdGroup.ID, + Name: createdGroup.Name, + }, nil +} + +func (ac *AtlanClient) DeleteTeamByID(ctx context.Context, teamID string) error { + log := logger.Logger(ctx).WithFields(logrus.Fields{ + "service": "atlan", + "team_id": teamID, + }) + log.Info("deleting team from Atlan") + + url := fmt.Sprintf("%s/api/service/groups/%s", ac.url, teamID) + _, statusCode, err := ac.sendRequest(ctx, url, http.MethodDelete, nil, nil, "DeleteTeamByID") + if err != nil { + return fmt.Errorf("failed to delete team from Atlan: %w", err) + } + + if statusCode != http.StatusOK && statusCode != http.StatusNoContent { + return fmt.Errorf("unexpected status code %d when deleting team from Atlan", statusCode) + } + + log.Info("successfully deleted team from Atlan") + return nil +} + +func (ac *AtlanClient) FetchTeamDetails(ctx context.Context, teamID string) (*structs.Team, error) { + return nil, fmt.Errorf("FetchTeamDetails is not implemented for Atlan") +} diff --git a/pkg/clients/atlan/users.go b/pkg/clients/atlan/users.go new file mode 100644 index 00000000..e036f815 --- /dev/null +++ b/pkg/clients/atlan/users.go @@ -0,0 +1,29 @@ +package atlan + +import ( + "context" + + "github.com/redhat-data-and-ai/usernaut/pkg/common/structs" +) + +func (ac *AtlanClient) FetchAllUsers(ctx context.Context) (map[string]*structs.User, map[string]*structs.User, error) { + // Users are synced via LDAP, return empty maps like Rover does + return make(map[string]*structs.User), make(map[string]*structs.User), nil +} + +func (ac *AtlanClient) FetchUserDetails(ctx context.Context, userID string) (*structs.User, error) { + // Users are synced via LDAP, return empty user like Rover does + return &structs.User{}, nil +} + +func (ac *AtlanClient) CreateUser(ctx context.Context, u *structs.User) (*structs.User, error) { + // Users are synced via LDAP, return minimal user struct like Rover does + return &structs.User{ + ID: u.UserName, + }, nil +} + +func (ac *AtlanClient) DeleteUser(ctx context.Context, userID string) error { + // Users are synced via LDAP, return nil like Rover does + return nil +} diff --git a/pkg/clients/client.go b/pkg/clients/client.go index 11ddb375..5fba54c1 100644 --- a/pkg/clients/client.go +++ b/pkg/clients/client.go @@ -21,6 +21,7 @@ import ( "errors" "strings" + "github.com/redhat-data-and-ai/usernaut/pkg/clients/atlan" "github.com/redhat-data-and-ai/usernaut/pkg/clients/fivetran" redhatrover "github.com/redhat-data-and-ai/usernaut/pkg/clients/redhat_rover" "github.com/redhat-data-and-ai/usernaut/pkg/common/structs" @@ -88,8 +89,15 @@ func New(backendName, backendType string, backends map[string]map[string]config. return redhatrover.NewClient(backend.Connection, appConfig.HttpClient.ConnectionPoolConfig, appConfig.HttpClient.HystrixResiliencyConfig) + case "atlan": + appConfig, err := config.GetConfig() + if err != nil { + return nil, err + } + + return atlan.NewClient(backend.Connection, + appConfig.HttpClient.ConnectionPoolConfig, appConfig.HttpClient.HystrixResiliencyConfig) default: - // If no valid backend type is matched, return an error return nil, ErrInvalidBackend } } From 70d2b112d10468938eb1ffcd834637864129ea90 Mon Sep 17 00:00:00 2001 From: Puja Thacker Date: Tue, 29 Jul 2025 11:30:56 +0530 Subject: [PATCH 2/6] comments cleanup --- pkg/clients/atlan/team_membership.go | 6 +++--- pkg/clients/atlan/users.go | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pkg/clients/atlan/team_membership.go b/pkg/clients/atlan/team_membership.go index e8cf24d8..e01e0ce3 100644 --- a/pkg/clients/atlan/team_membership.go +++ b/pkg/clients/atlan/team_membership.go @@ -7,16 +7,16 @@ import ( ) func (ac *AtlanClient) FetchTeamMembersByTeamID(ctx context.Context, teamID string) (map[string]*structs.User, error) { - // Team membership is synced via LDAP, return empty map like Rover does + // Team membership is synced via LDAP, returning empty map return make(map[string]*structs.User), nil } func (ac *AtlanClient) AddUserToTeam(ctx context.Context, teamID, userID string) error { - // Team membership is synced via LDAP, return nil like Rover does + // Team membership is synced via LDAP, returning nil return nil } func (ac *AtlanClient) RemoveUserFromTeam(ctx context.Context, teamID, userID string) error { - // Team membership is synced via LDAP, return nil like Rover does + // Team membership is synced via LDAP, returning nil return nil } diff --git a/pkg/clients/atlan/users.go b/pkg/clients/atlan/users.go index e036f815..90c45c24 100644 --- a/pkg/clients/atlan/users.go +++ b/pkg/clients/atlan/users.go @@ -7,23 +7,23 @@ import ( ) func (ac *AtlanClient) FetchAllUsers(ctx context.Context) (map[string]*structs.User, map[string]*structs.User, error) { - // Users are synced via LDAP, return empty maps like Rover does + // Users are synced via LDAP, return empty maps return make(map[string]*structs.User), make(map[string]*structs.User), nil } func (ac *AtlanClient) FetchUserDetails(ctx context.Context, userID string) (*structs.User, error) { - // Users are synced via LDAP, return empty user like Rover does + // Users are synced via LDAP, return empty user return &structs.User{}, nil } func (ac *AtlanClient) CreateUser(ctx context.Context, u *structs.User) (*structs.User, error) { - // Users are synced via LDAP, return minimal user struct like Rover does + // Users are synced via LDAP, return minimal user struct return &structs.User{ ID: u.UserName, }, nil } func (ac *AtlanClient) DeleteUser(ctx context.Context, userID string) error { - // Users are synced via LDAP, return nil like Rover does + // Users are synced via LDAP, return nil return nil } From 4785a79162441a2175a78a0b732b5767246dda20 Mon Sep 17 00:00:00 2001 From: Puja Thacker Date: Tue, 29 Jul 2025 12:10:04 +0530 Subject: [PATCH 3/6] moving appConfig pull at the start of the function --- pkg/clients/client.go | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/pkg/clients/client.go b/pkg/clients/client.go index 5fba54c1..83afc91f 100644 --- a/pkg/clients/client.go +++ b/pkg/clients/client.go @@ -71,6 +71,12 @@ func New(backendName, backendType string, backends map[string]map[string]config. if !backend.Enabled { return nil, errors.New("backend is not enabled") } + + appConfig, err := config.GetConfig() + if err != nil { + return nil, err + } + switch strings.ToLower(backendType) { case "fivetran": apiKey := backend.GetStringConnection("apikey", "") @@ -82,19 +88,9 @@ func New(backendName, backendType string, backends map[string]map[string]config. // using the API key and secret from the backend configuration return fivetran.NewClient(apiKey, apiSecret), nil case "rover": - appConfig, err := config.GetConfig() - if err != nil { - return nil, err - } - return redhatrover.NewClient(backend.Connection, appConfig.HttpClient.ConnectionPoolConfig, appConfig.HttpClient.HystrixResiliencyConfig) case "atlan": - appConfig, err := config.GetConfig() - if err != nil { - return nil, err - } - return atlan.NewClient(backend.Connection, appConfig.HttpClient.ConnectionPoolConfig, appConfig.HttpClient.HystrixResiliencyConfig) default: From 281077cf774209d30904484938e511883811a7df Mon Sep 17 00:00:00 2001 From: Puja Thacker <136712767+Pujathacker2210@users.noreply.github.com> Date: Tue, 29 Jul 2025 15:35:29 +0530 Subject: [PATCH 4/6] Update internal/controller/group_controller.go Accepting Copilot's suggestion on adding group name to the error Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- internal/controller/group_controller.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/controller/group_controller.go b/internal/controller/group_controller.go index 9cf5058a..67934586 100644 --- a/internal/controller/group_controller.go +++ b/internal/controller/group_controller.go @@ -335,7 +335,7 @@ func (r *GroupReconciler) fetchOrCreateTeam(ctx context.Context, } if !roverExists { - return "", errors.New("cannot create Atlan team: Rover group must exist first") + return "", fmt.Errorf("cannot create Atlan team for group '%s': Rover group must exist first", groupName) } } From a2464b0e6af2f815291578ca85a248920090d51d Mon Sep 17 00:00:00 2001 From: Puja Thacker Date: Tue, 29 Jul 2025 15:39:06 +0530 Subject: [PATCH 5/6] updated CR check to current CR and added deletion status code validation --- internal/controller/group_controller.go | 44 +++++++++---------------- pkg/clients/atlan/client.go | 2 +- 2 files changed, 17 insertions(+), 29 deletions(-) diff --git a/internal/controller/group_controller.go b/internal/controller/group_controller.go index 67934586..75e2ffa2 100644 --- a/internal/controller/group_controller.go +++ b/internal/controller/group_controller.go @@ -104,6 +104,22 @@ func (r *GroupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl "backend_type": backend.Type, }) + // ATLAN VALIDATION: Check if Rover backend exists in current CR before creating Atlan team + if backend.Type == "atlan" { + roverExists := false + for _, b := range groupCR.Spec.Backends { + if b.Type == "rover" { + roverExists = true + break + } + } + + if !roverExists { + r.backendLogger.Error("cannot process Atlan backend: Rover backend must exist in the same Group CR") + return ctrl.Result{}, errors.New("cannot process Atlan backend: Rover backend must exist in the same Group CR") + } + } + // process each backend in the group CR backendClient, err := clients.New(backend.Name, backend.Type, r.AppConfig.BackendMap) if err != nil { @@ -311,34 +327,6 @@ func (r *GroupReconciler) fetchOrCreateTeam(ctx context.Context, } } - // ATLAN VALIDATION: Check if Rover group exists in CRs before creating Atlan team - if backendType == "atlan" { - groupList := &usernautdevv1alpha1.GroupList{} - if err := r.Client.List(ctx, groupList); err != nil { - r.backendLogger.WithError(err).Error("error listing Group CRs for Rover validation") - return "", err - } - - roverExists := false - for _, group := range groupList.Items { - if group.Spec.GroupName == groupName { - for _, backend := range group.Spec.Backends { - if backend.Type == "rover" { - roverExists = true - break - } - } - if roverExists { - break - } - } - } - - if !roverExists { - return "", fmt.Errorf("cannot create Atlan team for group '%s': Rover group must exist first", groupName) - } - } - // If team details are not found in cache, create a new team r.backendLogger.Info("team details not found in cache, creating a new team") diff --git a/pkg/clients/atlan/client.go b/pkg/clients/atlan/client.go index c2feeb63..502c547a 100644 --- a/pkg/clients/atlan/client.go +++ b/pkg/clients/atlan/client.go @@ -107,7 +107,7 @@ func (aC *AtlanClient) sendRequest(ctx context.Context, url string, method strin return nil, statusCode, fmt.Errorf("request failed: %w", err) } - if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, statusCode) { + if !slices.Contains([]int{http.StatusOK, http.StatusCreated, http.StatusNoContent}, statusCode) { return nil, statusCode, fmt.Errorf("unexpected status code: %d", statusCode) } From 7e4aeb798a078765a2226ad38a2f7ed167e24c77 Mon Sep 17 00:00:00 2001 From: Puja Thacker Date: Mon, 4 Aug 2025 15:21:46 +0530 Subject: [PATCH 6/6] Pushing sso-atlan group sync functions --- appconfig/default.yaml | 1 + pkg/clients/atlan/client.go | 19 ++-- pkg/clients/atlan/teams.go | 167 +++++++++++++++++++++++++++++++++++- 3 files changed, 177 insertions(+), 10 deletions(-) diff --git a/appconfig/default.yaml b/appconfig/default.yaml index b8928528..0c28ca03 100644 --- a/appconfig/default.yaml +++ b/appconfig/default.yaml @@ -86,3 +86,4 @@ backends: connection: url: "https://yourcompany.atlan.com" api_token: file|path/to/api_token + identity_provider_alias: {saml|azure} # REQUIRED for SSO-Group mapping functions diff --git a/pkg/clients/atlan/client.go b/pkg/clients/atlan/client.go index 502c547a..2f6f0205 100644 --- a/pkg/clients/atlan/client.go +++ b/pkg/clients/atlan/client.go @@ -32,15 +32,17 @@ import ( // AtlanClient is a simple HTTP client for Atlan API type AtlanClient struct { - client heimdall.Doer - url string - apiToken string + client heimdall.Doer + url string + apiToken string + identityProviderAlias string } // AtlanConfig holds the configuration needed to connect to Atlan type AtlanConfig struct { - URL string `json:"url"` - APIToken string `json:"api_token"` + URL string `json:"url"` + APIToken string `json:"api_token"` + IdentityProviderAlias string `json:"identity_provider_alias"` } // NewClient creates a new Atlan client with simple API token authentication @@ -74,9 +76,10 @@ func NewClient(atlanAppConfig map[string]interface{}, } return &AtlanClient{ - client: client, - url: atlanConfig.URL, - apiToken: atlanConfig.APIToken, + client: client, + url: atlanConfig.URL, + apiToken: atlanConfig.APIToken, + identityProviderAlias: atlanConfig.IdentityProviderAlias, }, nil } diff --git a/pkg/clients/atlan/teams.go b/pkg/clients/atlan/teams.go index 4238ccab..ece35a56 100644 --- a/pkg/clients/atlan/teams.go +++ b/pkg/clients/atlan/teams.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "strings" + "time" "github.com/redhat-data-and-ai/usernaut/pkg/common/structs" "github.com/redhat-data-and-ai/usernaut/pkg/logger" @@ -23,6 +24,23 @@ type AtlanGroupsResponse struct { Records []AtlanGroup `json:"records"` } +type SSOGroupMappingConfig struct { + SyncMode string `json:"syncMode"` + Attributes string `json:"attributes"` + AreAttributeValuesRegex string `json:"are.attribute.values.regex"` + AttributeName string `json:"attribute.name"` + Group string `json:"group"` + AttributeValue string `json:"attribute.value"` +} + +type SSOGroupMapping struct { + ID string `json:"id"` + IdentityProviderAlias string `json:"identityProviderAlias"` + IdentityProviderMapper string `json:"identityProviderMapper"` + Name string `json:"name"` + Config SSOGroupMappingConfig `json:"config"` +} + func (ac *AtlanClient) FetchAllTeams(ctx context.Context) (map[string]structs.Team, error) { log := logger.Logger(ctx).WithField("service", "atlan") log.Info("fetching all teams from Atlan") @@ -64,7 +82,6 @@ func (ac *AtlanClient) CreateTeam(ctx context.Context, team *structs.Team) (*str url := fmt.Sprintf("%s/api/service/groups", ac.url) - // Convert team name to valid internal name as per Atlan guidelines (lowercase, alphanumeric + underscore only) internalName := strings.ToLower(strings.ReplaceAll(team.Name, " ", "_")) internalName = strings.ReplaceAll(internalName, "-", "_") @@ -74,7 +91,7 @@ func (ac *AtlanClient) CreateTeam(ctx context.Context, team *structs.Team) (*str "alias": []string{team.Name}, "isDefault": []string{"false"}, }, - "name": internalName, // Sanitized internal name + "name": internalName, }, } @@ -93,12 +110,88 @@ func (ac *AtlanClient) CreateTeam(ctx context.Context, team *structs.Team) (*str } log.WithField("team_id", createdGroup.ID).Info("successfully created team in Atlan") + return &structs.Team{ ID: createdGroup.ID, Name: createdGroup.Name, }, nil } +func (ac *AtlanClient) CreateTeamWithSSO(ctx context.Context, team *structs.Team, ssoGroupName string) (*structs.Team, error) { + createdTeam, err := ac.CreateTeam(ctx, team) + if err != nil { + return nil, err + } + + if ssoGroupName == "" { + ssoGroupName = createdTeam.Name + } + + if err := ac.CreateSSOMapping(ctx, createdTeam.ID, createdTeam.Name, ssoGroupName); err != nil { + log := logger.Logger(ctx) + log.WithError(err).Error("failed to create SSO group mapping") + } + + return createdTeam, nil +} + +func (ac *AtlanClient) CreateSSOMapping(ctx context.Context, teamID, teamName, ssoGroupName string) error { + provider := ac.identityProviderAlias + if provider == "" { + return fmt.Errorf("identity provider alias not configured - please set identity_provider_alias in backend connection config") + } + + groupMapping := SSOGroupMapping{ + IdentityProviderAlias: provider, + IdentityProviderMapper: "saml-group-idp-mapper", + Name: fmt.Sprintf("%s--%d", teamID, time.Now().UnixMilli()), + Config: SSOGroupMappingConfig{ + SyncMode: "FORCE", + Attributes: "[]", + AreAttributeValuesRegex: "", + AttributeName: "memberOf", + Group: teamName, + AttributeValue: ssoGroupName, + }, + } + + url := fmt.Sprintf("%s/api/service/idp/%s/mappers", ac.url, provider) + _, statusCode, err := ac.sendRequest(ctx, url, http.MethodPost, groupMapping, nil, "CreateSSOMapping") + if err != nil { + return fmt.Errorf("failed to create SSO group mapping: %w", err) + } + + if statusCode != http.StatusCreated && statusCode != http.StatusOK { + return fmt.Errorf("unexpected status code %d when creating SSO group mapping", statusCode) + } + + return nil +} + +func (ac *AtlanClient) DeleteSSOMapping(ctx context.Context, teamName string) error { + mappingID, err := ac.FindSSOMapping(ctx, teamName) + if err != nil { + return err + } + + provider := ac.identityProviderAlias + if provider == "" { + return fmt.Errorf("identity provider alias not configured - please set identity_provider_alias in backend connection config") + } + + url := fmt.Sprintf("%s/api/service/idp/%s/mappers/%s/delete", ac.url, provider, mappingID) + _, statusCode, err := ac.sendRequest(ctx, url, http.MethodPost, nil, nil, "DeleteSSOMapping") + if err != nil { + return fmt.Errorf("failed to delete SSO group mapping: %w", err) + } + + if statusCode != http.StatusOK && statusCode != http.StatusNoContent { + return fmt.Errorf("unexpected status code %d when deleting SSO group mapping", statusCode) + } + + return nil +} + func (ac *AtlanClient) DeleteTeamByID(ctx context.Context, teamID string) error { log := logger.Logger(ctx).WithFields(logrus.Fields{ "service": "atlan", @@ -120,6 +213,76 @@ func (ac *AtlanClient) DeleteTeamByID(ctx context.Context, teamID string) error return nil } +// This function pulls all SSO mappings and returns the ID of the mapping for the given team name. This needs to be added to the Cache later on as an enhancement +func (ac *AtlanClient) FindSSOMapping(ctx context.Context, teamName string) (string, error) { + provider := ac.identityProviderAlias + if provider == "" { + return "", fmt.Errorf("identity provider alias not configured - please set identity_provider_alias in backend connection config") + } + + url := fmt.Sprintf("%s/api/service/idp/%s/mappers", ac.url, provider) + response, statusCode, err := ac.sendRequest(ctx, url, http.MethodGet, nil, nil, "FindSSOMapping") + if err != nil { + return "", fmt.Errorf("failed to get SSO mappings: %w", err) + } + + if statusCode != http.StatusOK { + return "", fmt.Errorf("unexpected status code %d when getting SSO mappings", statusCode) + } + + var mappings []SSOGroupMapping + if err := json.Unmarshal(response, &mappings); err != nil { + return "", fmt.Errorf("failed to parse SSO mappings response: %w", err) + } + + for _, mapping := range mappings { + if mapping.Config.Group == teamName { + return mapping.ID, nil + } + } + + return "", fmt.Errorf("SSO mapping not found for team: %s", teamName) +} + +func (ac *AtlanClient) UpdateSSOMapping(ctx context.Context, teamName, newSSOGroupName string) error { + mappingID, err := ac.FindSSOMapping(ctx, teamName) + if err != nil { + return err + } + + provider := ac.identityProviderAlias + if provider == "" { + return fmt.Errorf("identity provider alias not configured - please set identity_provider_alias in backend connection config") + } + + groupMapping := SSOGroupMapping{ + ID: mappingID, + IdentityProviderAlias: provider, + IdentityProviderMapper: "saml-group-idp-mapper", + Name: fmt.Sprintf("%s--%d", mappingID, time.Now().UnixMilli()), + Config: SSOGroupMappingConfig{ + SyncMode: "FORCE", + Attributes: "[]", + AreAttributeValuesRegex: "", + AttributeName: "memberOf", + Group: teamName, + AttributeValue: newSSOGroupName, + }, + } + + url := fmt.Sprintf("%s/api/service/idp/%s/mappers/%s", ac.url, provider, mappingID) + _, statusCode, err := ac.sendRequest(ctx, url, http.MethodPost, groupMapping, nil, "UpdateSSOMapping") + if err != nil { + return fmt.Errorf("failed to update SSO group mapping: %w", err) + } + + if statusCode != http.StatusOK { + return fmt.Errorf("unexpected status code %d when updating SSO group mapping", statusCode) + } + + return nil +} + func (ac *AtlanClient) FetchTeamDetails(ctx context.Context, teamID string) (*structs.Team, error) { return nil, fmt.Errorf("FetchTeamDetails is not implemented for Atlan") }