public static V1PolicyRule CreateRbacPolicy(this EntityRbacAttribute attribute) { var crds = attribute.Entities.Select(CustomEntityDefinitionExtensions.CreateResourceDefinition).ToList(); var policy = new V1PolicyRule { ApiGroups = crds.Select(crd => crd.Group).Distinct().ToList(), Resources = crds.Select(crd => crd.Plural).Distinct().ToList(), Verbs = attribute.Verbs.ConvertToStrings(), }; return(policy); }
public static V1PolicyRule?CreateStatusRbacPolicy(this EntityRbacAttribute attribute) { var crds = attribute.Entities .Where(type => type.GetProperty("Status") != null) .Select(CustomEntityDefinitionExtensions.CreateResourceDefinition) .ToList(); if (crds.Count == 0) { return(null); } var policy = new V1PolicyRule { ApiGroups = crds.Select(crd => crd.Group).Distinct().ToList(), Resources = crds.Select(crd => crd.Plural).Distinct().Select(name => $"{name}/status").ToList(), Verbs = (RbacVerb.Get | RbacVerb.Patch | RbacVerb.Update).ConvertToStrings(), }; return(policy); }
static void Main(string[] args) { var kClient = new Kubernetes(KubernetesClientConfiguration.BuildDefaultConfig()); var namespacesTask = kClient.ListNamespaceWithHttpMessagesAsync(); namespacesTask.Wait(); AssertErrors(namespacesTask.Result); var namespaces = namespacesTask.Result.Body; var namespaceSet = namespaces.Items.Select(e => new { NamespaceName = e.Metadata.Name, Role = GetRole(kClient, e.Metadata.Name) }).Where(e => e.Role != null).ToList(); // Just to assert existing Policies var thoseWithProperRights = namespaceSet.Where(n => n.Role.Rules.Any(r => r.ApiGroups.Any(a => a == "rbac.authorization.k8s.io"))).ToList(); // List of Roles with missing policy var thoseWithoutProperRights = namespaceSet.Where(n => n.Role.Rules.All(r => r.ApiGroups.All(a => a != "rbac.authorization.k8s.io"))).ToList(); foreach (var thoseWithoutProperRight in thoseWithoutProperRights) { var policy = new V1PolicyRule { ApiGroups = new List <string> { "rbac.authorization.k8s.io" }, Resources = new List <string> { "rolebindings", "roles" }, Verbs = new List <string> { "*" } }; var patch = new JsonPatchDocument <V1Role>(); patch.Add(p => p.Rules, policy); try { var body = new V1Patch(patch); var patchTask = kClient.PatchNamespacedRoleWithHttpMessagesAsync(body, thoseWithoutProperRight.Role.Metadata.Name, thoseWithoutProperRight.NamespaceName); patchTask.Wait(); Console.WriteLine($"Updated Policy on {thoseWithoutProperRight.Role.Metadata.Name}"); } catch (Exception e) { Console.WriteLine(e); throw; } } Console.ReadKey(); }