/* Copyright 2024. 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 controller import ( "context" "fmt" "reflect" "sort" "time" zitadelv1alpha1 "gitea.corredorconect.com/software-engineering/zitadel-resources-operator/api/v1alpha1" condition "gitea.corredorconect.com/software-engineering/zitadel-resources-operator/pkg/condition" "gitea.corredorconect.com/software-engineering/zitadel-resources-operator/pkg/controller/core" clientv2 "github.com/zitadel/zitadel-go/v3/pkg/client" "github.com/zitadel/zitadel-go/v3/pkg/client/zitadel/filter/v2" "github.com/zitadel/zitadel-go/v3/pkg/client/zitadel/project/v2" "k8s.io/client-go/util/workqueue" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" ctrlClient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/reconcile" ) // ProjectReconciler reconciles a Project object type ProjectReconciler struct { client.Client RefResolver *zitadelv1alpha1.RefResolver ConditionReady *condition.Ready RequeueInterval time.Duration } func NewProjectReconciler(client client.Client, refResolver *zitadelv1alpha1.RefResolver, conditionReady *condition.Ready, requeueInterval time.Duration) *ProjectReconciler { return &ProjectReconciler{ Client: client, RefResolver: refResolver, ConditionReady: conditionReady, RequeueInterval: requeueInterval, } } //+kubebuilder:rbac:groups=zitadel.github.com,resources=projects,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=zitadel.github.com,resources=projects/status,verbs=get;update;patch //+kubebuilder:rbac:groups=zitadel.github.com,resources=projects/finalizers,verbs=update // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. func (r *ProjectReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { var project zitadelv1alpha1.Project if err := r.Get(ctx, req.NamespacedName, &project); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) } wr := newWrappedProjectReconciler(r.Client, r.RefResolver, &project) wf := newWrappedProjectFinalizer(r.Client, &project, r.RefResolver) tf := core.NewCoreFinalizer(r.Client, wf) tr := core.NewCoreReconciler(r.Client, r.ConditionReady, wr, tf, r.RequeueInterval) result, err := tr.Reconcile(ctx, &project) if err != nil { return result, fmt.Errorf("error reconciling in ProjectReconciler: %v", err) } return result, nil } type wrappedProjectReconciler struct { client.Client refResolver *zitadelv1alpha1.RefResolver project *zitadelv1alpha1.Project } func newWrappedProjectReconciler(client client.Client, refResolver *zitadelv1alpha1.RefResolver, project *zitadelv1alpha1.Project) core.WrappedCoreReconciler { return &wrappedProjectReconciler{ Client: client, refResolver: refResolver, project: project, } } type projectReconcilePhase struct { Name string Reconcile func(context.Context, *clientv2.Client) error } func (wr *wrappedProjectReconciler) Reconcile(ctx context.Context, ztdClient *clientv2.Client) error { phases := []projectReconcilePhase{ { Name: "project", Reconcile: wr.reconcileProject, }, { Name: "roles", Reconcile: wr.reconcileRoles, }, { Name: "grants", Reconcile: wr.reconcileGrants, }, } for _, p := range phases { err := p.Reconcile(ctx, ztdClient) if err != nil { return err } } return nil } func (wr *wrappedProjectReconciler) reconcileProject(ctx context.Context, ztdClient *clientv2.Client) error { org, err := wr.refResolver.OrganizationRef(ctx, &wr.project.Spec.OrganizationRef, wr.project.Namespace) if err != nil { return err } if org.Status.OrganizationId == nil { return fmt.Errorf("Organization not created yet") } var projectId *string projectList, err := ztdClient.ProjectServiceV2().ListProjects(ctx, &project.ListProjectsRequest{ Filters: []*project.ProjectSearchFilter{ &project.ProjectSearchFilter{ Filter: &project.ProjectSearchFilter_ProjectNameFilter{ ProjectNameFilter: &project.ProjectNameFilter{ ProjectName: wr.project.Spec.ProjectName, Method: filter.TextFilterMethod_TEXT_FILTER_METHOD_EQUALS, }, }, }, &project.ProjectSearchFilter{ Filter: &project.ProjectSearchFilter_OrganizationIdFilter{ OrganizationIdFilter: &project.ProjectOrganizationIDFilter{ OrganizationId: *org.Status.OrganizationId, Type: project.ProjectOrganizationIDFilter_OWNED, }, }, }, }, }) if err != nil { return fmt.Errorf("error listing project: %v", err) } if len(projectList.Projects) > 0 { projectId = &projectList.Projects[0].ProjectId } if projectId == nil { resp, err := ztdClient.ProjectServiceV2().CreateProject(ctx, &project.CreateProjectRequest{ OrganizationId: *org.Status.OrganizationId, Name: wr.project.Spec.ProjectName, ProjectRoleAssertion: wr.project.Spec.ProjectRoleAssertion, AuthorizationRequired: wr.project.Spec.ProjectRoleCheck, ProjectAccessRequired: wr.project.Spec.HasProjectCheck, }, ) if err != nil { return fmt.Errorf("error creating project: %v", err) } projectId = &resp.ProjectId } patch := ctrlClient.MergeFrom(wr.project.DeepCopy()) wr.project.Status.ProjectId = projectId return wr.Client.Status().Patch(ctx, wr.project, patch) } func (wr *wrappedProjectReconciler) reconcileRoles(ctx context.Context, ztdClient *clientv2.Client) error { resp, err := ztdClient.ProjectServiceV2().ListProjectRoles(ctx, &project.ListProjectRolesRequest{ ProjectId: *wr.project.Status.ProjectId, }) if err != nil { return fmt.Errorf("Could not list project roles: %v", err) } roles := map[string]*project.ProjectRole{} deleteRolesKeys := []string{} for _, role := range wr.project.Spec.Roles { roles[role.Key] = &project.ProjectRole{ Key: role.Key, DisplayName: role.DisplayName, Group: role.Group, ProjectId: *wr.project.Status.ProjectId, } } for _, role := range resp.ProjectRoles { if r, ok := roles[role.Key]; ok { if r.DisplayName != role.DisplayName || r.Group != role.Group { deleteRolesKeys = append(deleteRolesKeys, role.Key) } else { delete(roles, role.Key) } } else { deleteRolesKeys = append(deleteRolesKeys, role.Key) } } if len(deleteRolesKeys) > 0 { for _, key := range deleteRolesKeys { if _, err = ztdClient.ProjectServiceV2().RemoveProjectRole(ctx, &project.RemoveProjectRoleRequest{ ProjectId: *wr.project.Status.ProjectId, RoleKey: key, }); err != nil { return fmt.Errorf("Error removing project role: %v", err) } } } if len(roles) > 0 { for _, value := range roles { if _, err = ztdClient.ProjectServiceV2().AddProjectRole(ctx, &project.AddProjectRoleRequest{ ProjectId: *wr.project.Status.ProjectId, RoleKey: value.Key, DisplayName: value.DisplayName, Group: &value.Group, }); err != nil { return fmt.Errorf("Error adding project role: %v", err) } } } return nil } func (wr *wrappedProjectReconciler) reconcileGrants(ctx context.Context, ztdClient *clientv2.Client) error { existingGrants, err := ztdClient.ProjectServiceV2().ListProjectGrants(ctx, &project.ListProjectGrantsRequest{ Filters: []*project.ProjectGrantSearchFilter{ { Filter: &project.ProjectGrantSearchFilter_InProjectIdsFilter{ InProjectIdsFilter: &filter.InIDsFilter{ Ids: []string{ *wr.project.Status.ProjectId, }, }, }, }, }, }) if err != nil { return fmt.Errorf("Error listing project grants: %v", err) } for _, grant := range wr.project.DeepCopy().Spec.Grants { grantedOrg, err := wr.refResolver.OrganizationRef(ctx, &grant.OrganizationRef, wr.project.Namespace) if err != nil { return err } if grantedOrg.Status.OrganizationId == nil { continue } var existingGrant *project.ProjectGrant for _, eGrant := range existingGrants.ProjectGrants { if eGrant.GrantedOrganizationId == *grantedOrg.Status.OrganizationId { existingGrant = eGrant break } } if existingGrant == nil { _, err := ztdClient.ProjectServiceV2().CreateProjectGrant(ctx, &project.CreateProjectGrantRequest{ ProjectId: *wr.project.Status.ProjectId, GrantedOrganizationId: *grantedOrg.Status.OrganizationId, RoleKeys: grant.RoleKeys, }) if err != nil { return fmt.Errorf("Error Adding project grant: %v", err) } } else { sort.Strings(existingGrant.GrantedRoleKeys) sort.Strings(grant.RoleKeys) if !reflect.DeepEqual(existingGrant.GrantedRoleKeys, grant.RoleKeys) { _, err := ztdClient.ProjectServiceV2().UpdateProjectGrant(ctx, &project.UpdateProjectGrantRequest{ ProjectId: *wr.project.Status.ProjectId, GrantedOrganizationId: existingGrant.GrantedOrganizationId, RoleKeys: grant.RoleKeys, }) if err != nil { return fmt.Errorf("Error Updating project grant: %v", err) } } } } return nil } func (wr *wrappedProjectReconciler) PatchStatus(ctx context.Context, patcher condition.Patcher) error { patch := client.MergeFrom(wr.project.DeepCopy()) patcher(&wr.project.Status) if err := wr.Client.Status().Patch(ctx, wr.project, patch); err != nil { return fmt.Errorf("error patching Project status: %v", err) } return nil } // SetupWithManager sets up the controller with the Manager. func (r *ProjectReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&zitadelv1alpha1.Project{}). WithOptions(controller.Options{RateLimiter: workqueue.NewTypedItemExponentialFailureRateLimiter[reconcile.Request](time.Millisecond*500, time.Minute*3)}). Complete(r) }