public DotNetCfgUser(AccessControlList acl, UserElement userElement) { _userElement = userElement; _memberOf = new Dictionary<string, Group>(); foreach(MembershipElement memberOf in userElement.Memberships) { if(_memberOf.ContainsKey(memberOf.Gid)) throw new ConfigurationErrorsException(string.Format("Group membership '{0}' is specified more than once for user '{1}'", memberOf.Gid, Uid)); Group myGroup = acl.FindGroupById(memberOf.Gid); if(myGroup == null) throw new ConfigurationErrorsException( string.Format("User '{0}' defines membership to group '{1}' but group does not exist", Uid, memberOf.Gid)); _memberOf.Add(myGroup.Gid, myGroup); } _authentications = new Dictionary<string, Authentication>(); foreach(AuthenticationType authenticationType in userElement.AuthenticationTypes) { Authentication auth = DotNetCfgAuthenticationFactory.CreateAuthentication(authenticationType); if(auth != null) _authentications.Add(auth.AuthenticationType, auth); else throw new ConfigurationErrorsException( string.Format("User '{0}' want to use authentication type '{1}', but this type is not known!", Uid, authenticationType.Type)); } }
public DotNetCfgPermission(AccessControlList acl, PermissionElement permissionElement) { _permissionElement = permissionElement; foreach(PermissionMember permissionMember in permissionElement) _permissionEntries.Add(DotNetCfgPermissionFactory.CreatePermissionEntry(acl, UniqueId, permissionMember)); }
public AccessControlListDialog(string objectName, AccessControlList acl, List<AceRights> supportedRights, List<AceType> supportedTypes) { InitializeComponent(); if (objectName == null) { throw new ArgumentNullException("objectName"); } if (acl == null) { throw new ArgumentNullException("acl"); } this.objectName = objectName; this.acl = acl; this.labelObjectName.Text = objectName; this.userList = new List<SecurityIdentity>(); foreach (AccessControlEntry ace in this.acl) { if (!this.userList.Contains(ace.AccountSID)) { this.userList.Add(ace.AccountSID); } } this.aclListPermissions.SupportedRights.AddRange(supportedRights); this.aclListPermissions.SupportedTypes.AddRange(supportedTypes); this.aclListPermissions.ACL = this.acl; }
public static PermissionEntry CreatePermissionEntry(AccessControlList acl, string uniquePid, PermissionMember permissionMember) { if(permissionMember.IdType == IdTypeEnum.User) { User user = acl.FindUserById(permissionMember.Id); if(user == null) throw new ConfigurationErrorsException( string.Format("Permission '{0}' contains permission for internal user '{1}' who is not defined", uniquePid, permissionMember.Id)); return new UserPermissionEntry(permissionMember.Access, user); } else if(permissionMember.IdType == IdTypeEnum.Group) { Group group = acl.FindGroupById(permissionMember.Id); if(group == null) throw new ConfigurationErrorsException( string.Format("Permission '{0}' contains permission for internal group '{1}' which is not defined", uniquePid, permissionMember.Id)); return new GroupPermissionEntry(permissionMember.Access, group); } else if(permissionMember.IdType == IdTypeEnum.UserExtern) return new ExternUserPermissionEntry(permissionMember.Access, permissionMember.Id); else if(permissionMember.IdType == IdTypeEnum.GroupExtern) return new ExternGroupPermissionEntry(permissionMember.Access, permissionMember.Id); else if(permissionMember.IdType == IdTypeEnum.Meta) return new MetaPermissionEntry(permissionMember.Access, permissionMember.Id); else throw new ConfigurationErrorsException(string.Format("Permission IdType of '{0}' is not supported", permissionMember.IdType)); }
/// <summary>Get the ACLs associated with this queue.</summary> /// <remarks> /// Get the ACLs associated with this queue. If a given ACL is not explicitly /// configured, include the default value for that ACL. The default for the /// root queue is everybody ("*") and the default for all other queues is /// nobody ("") /// </remarks> public virtual AccessControlList GetQueueAcl(string queue, QueueACL operation) { IDictionary <QueueACL, AccessControlList> queueAcls = this.queueAcls[queue]; if (queueAcls != null) { AccessControlList operationAcl = queueAcls[operation]; if (operationAcl != null) { return(operationAcl); } } return((queue.Equals("root")) ? EverybodyAcl : NobodyAcl); }
internal static AccessControlListWrapper GetInstance() { AccessControlList real = default(AccessControlList); RealInstanceFactory(ref real); var instance = (AccessControlListWrapper)AccessControlListWrapper.GetWrapper(real); InstanceFactory(ref instance); if (instance == null) { Assert.Inconclusive("Could not Create Test Instance"); } return(instance); }
private static string AclToString(AccessControlList acl) { if (acl == null) { return(string.Empty); } var sb = new StringBuilder(); foreach (var entry in acl.Entries) { sb.Append($"{entry.Name}, {entry.Access}, {entry.EntityType}; "); } return(sb.ToString().TrimEnd().TrimEnd(';')); }
public AccessControlList CreateStatefulAcl(params AccessControlEntry[] aces) { using (_transaction.EnterNonDiscardingScope()) { AccessControlList acl = StatefulAccessControlList.NewObject(); foreach (AccessControlEntry ace in aces) { acl.AccessControlEntries.Add(ace); } return(acl); } }
public void AccessControlList_Constructor() { // Arrange var obj = BaseTests.LoadJson("Get-VSTeamAccessControlList.json"); // Act var target = new AccessControlList(obj[0]); // Assert Assert.AreEqual(1, target.Aces.Count, "Aces"); Assert.AreEqual(true, target.InheritPermissions, "InheritPermissions"); Assert.AreEqual("$/00000000-0000-0000-0000-000000000001", target.Token, "Token"); Assert.AreEqual("$/00000000-0000-0000-0000-000000000001", target.ToString(), "ToString()"); }
public void RemovePermissionSender_WhenPermissionExists_ReturnsTrue() { var address = this.addressFactory.CreateAddress(); var newAddress = this.addressFactory.CreateAddress(); var acl = new AccessControlList(); Assert.True(acl.AddPermission(address, SetFavoriteNumberAction.Type, null)); Assert.True(acl.AddPermission(newAddress, SetFavoriteNumberAction.Type, null)); Assert.True(acl.RemovePermission(newAddress, SetFavoriteNumberAction.Type, null)); Assert.True(acl.HasPermission(address, SetFavoriteNumberAction.Type, this.addressFactory.CreateAddress())); Assert.False(acl.HasPermission(newAddress, SetFavoriteNumberAction.Type, this.addressFactory.CreateAddress())); }
internal List <Permission> GitPermissionsDetails(AccessControlList acessControlList, IEnumerable <GraphUser> users, IEnumerable <GraphGroup> groups, List <GitRepository> repositories) { List <Permission> permissions = new List <Permission>(); Regex extractEmail = new Regex(@"\\(.*$)"); Regex extractGuid = new Regex(@".{8}-.{9}-.{4}-.{12}"); GitHttpClient gitClient = connection.GetClient <GitHttpClient>(); SecurityHttpClient securityClient = connection.GetClient <SecurityHttpClient>(); GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>(); // Guid guid = Guid.Parse(acessControlList.Token.Remove(0, 7)); IEnumerable <AccessControlList> acls = securityClient.QueryAccessControlListsAsync( Guid.Parse("2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87"), acessControlList.Token, descriptors: null, includeExtendedInfo: false, recurse: true).Result; // get the details for Git permissions Dictionary <int, string> permission = GetGitPermissionNames(); var tokenGuids = extractGuid.Matches(acessControlList.Token); var lastGuidFromToken = Guid.Parse(tokenGuids[tokenGuids.Count - 1].Value); var repository = repositories.FirstOrDefault(r => r.Id.Equals(lastGuidFromToken)); var repositoryName = repository != null ? repository.Name : "<none>"; // use the Git permissions data to expand the ACL Console.WriteLine("Expanding ACL for {0} ({1} ACEs)", repositoryName, acessControlList.AcesDictionary.Count()); foreach (var kvp in acessControlList.AcesDictionary) { // in the key-value pair, Key is an identity and Value is an ACE (access control entry) // allow and deny are bit flags indicating which permissions are allowed/denied //PagedGraphUsers group = graphClient.GetGroupAsync(kvp.Key); //var user = users.First(u => u.Descriptor.ToString().Equals(kvp.Key.ToString())); var group = groups.FirstOrDefault(g => g.Descriptor.Identifier.Equals(kvp.Key.Identifier)); if (group != null) { AddByGroup(permissions, graphClient, permission, repositoryName, kvp, group); } else { AddByUser(users, permissions, extractEmail, permission, repositoryName, kvp); } } return(permissions); }
public InvokeResponse Build() { if (this.invokeRequest.M == null || this.invokeRequest.I == null || this.invokeRequest.V == null) { throw new ArgumentException(); } var obj = this.session.Instantiate(this.invokeRequest.I); var composite = (Composite)obj.Strategy.Class; var methodTypes = composite.MethodTypesByGroup[@group]; var methodType = methodTypes.FirstOrDefault(x => x.Name.Equals(this.invokeRequest.M)); if (methodType == null) { throw new Exception("Method " + this.invokeRequest.M + " not found."); } var invokeResponse = new InvokeResponse(); if (!this.invokeRequest.V.Equals(obj.Strategy.ObjectVersion.ToString())) { invokeResponse.AddVersionError(obj); } else { var acl = new AccessControlList(obj, this.user); if (acl.CanExecute(methodType)) { var method = obj.GetType().GetMethod(methodType.Name, new Type[] { }); method.Invoke(obj, null); var derivationLog = this.session.Derive(); if (!derivationLog.HasErrors) { this.session.Commit(); } else { invokeResponse.AddDerivationErrors(derivationLog); } } else { invokeResponse.AddAccessError(obj); } } return(invokeResponse); }
public ObjectID CreateAndCommitAccessControlEntryWithPermissions(int permissions, ClientTransaction transaction) { CreateEmptyDomain(); using (transaction.EnterNonDiscardingScope()) { SecurableClassDefinition classDefinition = CreateSecurableClassDefinitionWithAccessTypes(permissions); AccessControlList acl = classDefinition.CreateStatefulAccessControlList(); AccessControlEntry ace = acl.CreateAccessControlEntry(); ClientTransactionScope.CurrentTransaction.Commit(); return(ace.ID); } }
public void DelegateAccessReturnsTokens() { var administrator = new People(this.Session).FindBy(M.Person.UserName, "Administrator"); var accessClass = new AccessClassBuilder(this.Session).Build(); var acl = new AccessControlList(accessClass, administrator); Assert.True(acl.CanRead(M.AccessClass.Property)); Assert.True(acl.CanWrite(M.AccessClass.Property)); this.Session.Commit(); Assert.True(acl.CanRead(M.AccessClass.Property)); Assert.True(acl.CanWrite(M.AccessClass.Property)); }
private void menuItem7_Click(object sender, System.EventArgs e) { object[] hiddenObject = (object[])this.lvwPermEntries.SelectedItems[0].Tag; object ace = (object)hiddenObject.GetValue(1); AccessControlList acl = new AccessControlList(util.SharedEntry); acl.Remove(ace); acl.CommitChanges(); LoadSecurity_Click(this, new EventArgs()); }
public void GetAccessTypes_WithoutMatchingAce() { AccessControlEntry ace = _testHelper.CreateAceWithAbstractRole(); _testHelper.CreateReadAccessTypeAndAttachToAce(ace, true); _testHelper.CreateWriteAccessTypeAndAttachToAce(ace, null); _testHelper.CreateDeleteAccessTypeAndAttachToAce(ace, false); AccessControlList acl = _testHelper.CreateStatefulAcl(ace); SecurityToken token = _testHelper.CreateTokenWithoutUser(); AccessInformation accessInformation = acl.GetAccessTypes(token); Assert.That(accessInformation.AllowedAccessTypes, Is.Empty); Assert.That(accessInformation.DeniedAccessTypes, Is.Empty); }
/// <summary>Get the acls configured for the job</summary> public virtual IDictionary <JobACL, AccessControlList> GetJobAcls() { IDictionary <JobACL, AccessControlList> jobAcls = new Dictionary <JobACL, AccessControlList >(); foreach (JobACL jobACL in JobACL.Values()) { Utf8 jobACLsUtf8 = new Utf8(jobACL.GetAclName()); if (datum.acls.Contains(jobACLsUtf8)) { jobAcls[jobACL] = new AccessControlList(datum.acls[jobACLsUtf8].ToString()); } } return(jobAcls); }
static void ShowRights(string path) { AccessControlSettings settings = new AccessControlSettings(@namespace, managementKey); Uri uri = ServiceBusEnvironment.CreateServiceUri("http", @namespace, path); AccessControlList list = NamespaceAccessControl.GetAccessControlList(uri, settings); Console.WriteLine("Path {0}", path); Console.WriteLine("------------------------------------------"); Console.WriteLine("{0,-6} {1,-25} {2,-4}", "Right", "Assigned To", "Inherited"); Console.WriteLine("------------------------------------------"); foreach (AccessControlRule rule in list) { Console.WriteLine("{0,-6} {1,-25} {2,-4}", rule.Right.ClaimValue, rule.Condition.ClaimValue, rule.Inherited); } }
private void GetACLData() { AccessControlList ACLr = AccessControlList.GetACL(FolderId); ViewState["ACL"] = ACLr; if (ACLr.IsInherited) { ViewState["isChecked"] = "1"; } else { ViewState["isChecked"] = "0"; } }
/// <summary> /// Fill the datatable with current permissions /// </summary> void FillDataTable(AccessControlList acl) { DataTable dt = DataTable; dt.Clear(); foreach (AclItem p0 in acl.Items) { DataRow dr = dt.NewRow(); SetDataRow(dr, p0); dt.Rows.Add(dr); } Grid.DataSource = dt; Grid.Refresh(); }
private void dgMembers_DeleteCommand(object source, DataGridCommandEventArgs e) { AccessControlList ACLr = (AccessControlList)ViewState["ACL"]; int Id = int.Parse(e.Item.Cells[0].Text); ACLr.Remove(Id); ViewState["ACL"] = ACLr; ListItem _li = ddGroups.SelectedItem; if (_li != null) { BindUsers(int.Parse(_li.Value)); } BinddgMembers(); }
private void btnClearInherited_Click(object sender, EventArgs e) { AccessControlList ACLr = (AccessControlList)ViewState["ACL"]; ACLr.TurnOffIsInherited(false); ViewState["ACL"] = ACLr; ListItem _li = ddGroups.SelectedItem; if (_li != null) { BindUsers(int.Parse(_li.Value)); } BinddgMembers(); ViewState["isChecked"] = "0"; }
/// <summary> /// Get Bucket Acl /// </summary> /// <returns></returns> public CannedAccessControlList GetBucketAcl() { AccessControlList acl = null; CannedAccessControlList accessType = CannedAccessControlList.Default; try { acl = client.GetBucketAcl(bucketName); accessType = acl.ACL; } catch (OssException ex) { lastError = ex; } return(accessType); }
private void VerifyServiceACLsRefresh(ServiceAuthorizationManager manager, Type protocol , string aclString) { foreach (Type protocolClass in manager.GetProtocolsWithAcls()) { AccessControlList accessList = manager.GetProtocolsAcls(protocolClass); if (protocolClass == protocol) { NUnit.Framework.Assert.AreEqual(accessList.GetAclString(), aclString); } else { NUnit.Framework.Assert.AreEqual(accessList.GetAclString(), "*"); } } }
/// <exception cref="System.Exception"/> private void VerifyEnemyAccess() { AccessControlList viewACL = new AccessControlList(string.Empty); viewACL.AddGroup(FriendlyGroup); AccessControlList modifyACL = new AccessControlList(string.Empty); modifyACL.AddUser(Friend); ApplicationId applicationId = SubmitAppAndGetAppId(viewACL, modifyACL); GetApplicationReportRequest appReportRequest = recordFactory.NewRecordInstance <GetApplicationReportRequest >(); appReportRequest.SetApplicationId(applicationId); KillApplicationRequest finishAppRequest = recordFactory.NewRecordInstance <KillApplicationRequest >(); finishAppRequest.SetApplicationId(applicationId); ApplicationClientProtocol enemyRmClient = GetRMClientForUser(Enemy); // View as the enemy ApplicationReport appReport = enemyRmClient.GetApplicationReport(appReportRequest ).GetApplicationReport(); VerifyEnemyAppReport(appReport); // List apps as enemy IList <ApplicationReport> appReports = enemyRmClient.GetApplications(recordFactory .NewRecordInstance <GetApplicationsRequest>()).GetApplicationList(); NUnit.Framework.Assert.AreEqual("App view by enemy should list the apps!!", 4, appReports .Count); foreach (ApplicationReport report in appReports) { VerifyEnemyAppReport(report); } // Kill app as the enemy try { enemyRmClient.ForceKillApplication(finishAppRequest); NUnit.Framework.Assert.Fail("App killing by the enemy should fail!!"); } catch (YarnException e) { Log.Info("Got exception while killing app as the enemy", e); NUnit.Framework.Assert.IsTrue(e.Message.Contains("User enemy cannot perform operation MODIFY_APP on " + applicationId)); } rmClient.ForceKillApplication(finishAppRequest); }
private static string securityDescriptorToString(DirectoryEntry objRootDSE, string strAttrName, string propertyValue) { SecurityDescriptor sd = (SecurityDescriptor)objRootDSE.Properties[strAttrName].Value; AccessControlList acl = (AccessControlList)sd.DiscretionaryAcl; String m_Trustee = String.Empty; String m_AccessMask = String.Empty; String m_AceType = String.Empty; foreach (AccessControlEntry ace in (IEnumerable)acl) { m_Trustee = m_Trustee + "," + ace.Trustee; m_AccessMask = m_AccessMask + "," + ace.AccessMask.ToString(); m_AceType = m_AceType + "," + ace.AceType.ToString(); } propertyValue = "Trustee: " + m_Trustee + " " + "AccessMask: " + m_AccessMask + "AcessType: " + m_AceType; return(propertyValue); }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously static async Task <AccessControlPolicy> ObjectReadAcl(S3Context ctx) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { Console.WriteLine("ObjectReadAcl: " + ctx.Request.Bucket + "/" + ctx.Request.Key); AccessControlList acl = new AccessControlList( new List <Grant>() { new Grant(_Grantee, "FULL_CONTROL") }); AccessControlPolicy policy = new AccessControlPolicy( _Owner, acl); return(policy); }
static void SetBucketACL() { try { Owner owner = new Owner { DisplayName = "ownername", Id = "ownerid", }; Grant grant = new Grant { Grantee = new CanonicalGrantee() { DisplayName = "granteename", Id = "granteeid", }, Permission = PermissionEnum.FullControl, }; List <Grant> Grants = new List <Grant>(); Grants.Add(grant); AccessControlList accessControlList = new AccessControlList { Owner = owner, Grants = Grants, }; SetBucketAclRequest request = new SetBucketAclRequest() { BucketName = bucketName, AccessControlList = accessControlList }; SetBucketAclResponse response = client.SetBucketAcl(request); Console.WriteLine("SetBucketACL response: {0}", response.StatusCode); } catch (ObsException ex) { Console.WriteLine("Exception errorcode: {0}, when set bucket acl.", ex.ErrorCode); Console.WriteLine("Exception errormessage: {0}", ex.ErrorMessage); } }
/// <summary>Constructs and initializes this AdminACLsManager</summary> /// <param name="conf">configuration for this object to use</param> public AdminACLsManager(Configuration conf) { this.adminAcl = new AccessControlList(conf.Get(YarnConfiguration.YarnAdminAcl, YarnConfiguration .DefaultYarnAdminAcl)); try { owner = UserGroupInformation.GetCurrentUser(); adminAcl.AddUser(owner.GetShortUserName()); } catch (IOException e) { Log.Warn("Could not add current user to admin:" + e); throw new YarnRuntimeException(e); } aclsEnabled = conf.GetBoolean(YarnConfiguration.YarnAclEnable, YarnConfiguration. DefaultYarnAclEnable); }
private bool CheckKeyAccess(IDictionary <KeyAuthorizationKeyProvider.KeyOpType, AccessControlList > keyAcl, UserGroupInformation ugi, KeyAuthorizationKeyProvider.KeyOpType opType ) { AccessControlList acl = keyAcl[opType]; if (acl == null) { // If no acl is specified for this operation, // deny access return(false); } else { return(acl.IsUserAllowed(ugi)); } }
private void BinddgMembers() { AccessControlList ACLr = (AccessControlList)ViewState["ACL"]; DataTable dt = ACLToDateTable(ACLr); DataView dv = dt.DefaultView; dv.Sort = "IsInherited DESC, Weight"; dgMembers.DataSource = dv; dgMembers.DataBind(); foreach (DataGridItem dgi in dgMembers.Items) { ImageButton ib = (ImageButton)dgi.FindControl("ibDelete"); ib.Attributes.Add("onclick", "if(confirm('" + LocRM.GetString("Warning") + "')){DisableButtons(this);DisableCheck();return true;}else return false;"); ib.ToolTip = LocRM.GetString("Delete"); } }
/// <summary> /// Extracts the generic security namespace permissions. /// </summary> /// <param name="server">The server.</param> /// <param name="permissionScope">The permission scope.</param> /// <param name="userIdentity">The user identity.</param> /// <param name="securityToken">The security token.</param> /// <param name="identityManagementService">The identityManagementService.</param> /// <param name="groups">The groups.</param> /// <returns>List of Permissions</returns> private static List <Permission> ExtractGenericSecurityNamespacePermissions(ISecurityService server, PermissionScope permissionScope, TeamFoundationIdentity userIdentity, string securityToken, IIdentityManagementService identityManagementService, IEnumerable <string> groups) { SecurityNamespace genericSecurityNamespace = server.GetSecurityNamespace(Helpers.GetSecurityNamespaceId(permissionScope, server)); var result = new List <Permission>(); try { AccessControlList userAccessList = genericSecurityNamespace.QueryAccessControlList( securityToken, new List <IdentityDescriptor> { userIdentity.Descriptor }, true); result.AddRange(Helpers.AccessControlEntryToPermission(genericSecurityNamespace, userAccessList.AccessControlEntries, false, string.Empty)); // handle group inheritance foreach (string group in groups) { TeamFoundationIdentity groupIdentity = identityManagementService.ReadIdentity( IdentitySearchFactor.Identifier, group, MembershipQuery.None, ReadIdentityOptions.IncludeReadFromSource); AccessControlList groupAccessList = genericSecurityNamespace.QueryAccessControlList( securityToken, new List <IdentityDescriptor> { groupIdentity.Descriptor }, true); result.AddRange(Helpers.AccessControlEntryToPermission(genericSecurityNamespace, groupAccessList.AccessControlEntries, true, groupIdentity.DisplayName)); } } catch (TeamFoundationServiceException ex) { Console.Error.WriteLine("ERROR: " + ex.Message); } var modifiedPermissions = Helpers.RemoveDuplicatePermissionsAndCombineGroups(result); return(modifiedPermissions); }
protected void btnAdd_Click(object sender, System.EventArgs e) { AccessControlList ACLr = (AccessControlList)ViewState["ACL"]; AccessControlEntry ACEr; string sRight = ""; switch (ddRights.SelectedValue) { case "1": sRight = "Read"; break; case "2": sRight = "Write"; break; case "3": sRight = "Admin"; break; default: break; } if (ddGroups.SelectedValue == "0") { ACEr = new AccessControlEntry(ddUsers.SelectedValue, sRight, (rbList.SelectedValue == "0")); } else { int iPrincipalId = (ddUsers.SelectedValue == "0") ? int.Parse(ddGroups.SelectedValue) : int.Parse(ddUsers.SelectedValue); ACEr = new AccessControlEntry(iPrincipalId, sRight, (rbList.SelectedValue == "0")); } ACLr.Add(ACEr); ViewState["ACL"] = ACLr; ListItem _li = ddGroups.SelectedItem; if (_li != null) { BindUsers(int.Parse(_li.Value)); } BinddgMembers(); }
public virtual void TestIsValidRequestor() { Configuration conf = new HdfsConfiguration(); KerberosName.SetRules("RULE:[1:$1]\nRULE:[2:$1]"); // Set up generic HA configs. conf.Set(DFSConfigKeys.DfsNameservices, "ns1"); conf.Set(DFSUtil.AddKeySuffixes(DFSConfigKeys.DfsHaNamenodesKeyPrefix, "ns1"), "nn1,nn2" ); // Set up NN1 HA configs. conf.Set(DFSUtil.AddKeySuffixes(DFSConfigKeys.DfsNamenodeRpcAddressKey, "ns1", "nn1" ), "host1:1234"); conf.Set(DFSUtil.AddKeySuffixes(DFSConfigKeys.DfsNamenodeKerberosPrincipalKey, "ns1" , "nn1"), "hdfs/[email protected]"); // Set up NN2 HA configs. conf.Set(DFSUtil.AddKeySuffixes(DFSConfigKeys.DfsNamenodeRpcAddressKey, "ns1", "nn2" ), "host2:1234"); conf.Set(DFSUtil.AddKeySuffixes(DFSConfigKeys.DfsNamenodeKerberosPrincipalKey, "ns1" , "nn2"), "hdfs/[email protected]"); // Initialize this conf object as though we're running on NN1. NameNode.InitializeGenericKeys(conf, "ns1", "nn1"); AccessControlList acls = Org.Mockito.Mockito.Mock <AccessControlList>(); Org.Mockito.Mockito.When(acls.IsUserAllowed(Org.Mockito.Mockito.Any <UserGroupInformation >())).ThenReturn(false); ServletContext context = Org.Mockito.Mockito.Mock <ServletContext>(); Org.Mockito.Mockito.When(context.GetAttribute(HttpServer2.AdminsAcl)).ThenReturn( acls); // Make sure that NN2 is considered a valid fsimage/edits requestor. NUnit.Framework.Assert.IsTrue(ImageServlet.IsValidRequestor(context, "hdfs/[email protected]" , conf)); // Mark atm as an admin. Org.Mockito.Mockito.When(acls.IsUserAllowed(Org.Mockito.Mockito.ArgThat(new _ArgumentMatcher_76 ()))).ThenReturn(true); // Make sure that NN2 is still considered a valid requestor. NUnit.Framework.Assert.IsTrue(ImageServlet.IsValidRequestor(context, "hdfs/[email protected]" , conf)); // Make sure an admin is considered a valid requestor. NUnit.Framework.Assert.IsTrue(ImageServlet.IsValidRequestor(context, "*****@*****.**" , conf)); // Make sure other users are *not* considered valid requestors. NUnit.Framework.Assert.IsFalse(ImageServlet.IsValidRequestor(context, "*****@*****.**" , conf)); }
public void DeniedPermissions() { var readOrganisationName = this.FindPermission(Organisations.Meta.Name, Operation.Read); var databaseRole = new RoleBuilder(this.DatabaseSession).WithName("Role").WithPermission(readOrganisationName).Build(); var person = new PersonBuilder(this.DatabaseSession).WithFirstName("John").WithLastName("Doe").Build(); this.DatabaseSession.Derive(true); this.DatabaseSession.Commit(); new AccessControlBuilder(this.DatabaseSession).WithRole(databaseRole).WithSubject(person).Build(); this.DatabaseSession.Commit(); var sessions = new ISession[] { this.DatabaseSession, this.CreateWorkspaceSession() }; foreach (var session in sessions) { session.Commit(); var organisation = new OrganisationBuilder(session).WithName("Organisation").Build(); var token = new SecurityTokenBuilder(session).Build(); organisation.AddSecurityToken(token); var role = (Role)session.Instantiate(new Roles(this.DatabaseSession).FindBy(Roles.Meta.Name, "Role")); var accessControl = (AccessControl)session.Instantiate(role.AccessControlsWhereRole.First); accessControl.AddObject(token); Assert.IsFalse(this.DatabaseSession.Derive().HasErrors); var accessList = new AccessControlList(organisation, person); Assert.IsTrue(accessList.CanRead(Organisations.Meta.Name)); organisation.AddDeniedPermission(readOrganisationName); accessList = new AccessControlList(organisation, person); Assert.IsFalse(accessList.CanRead(Organisations.Meta.Name)); session.Rollback(); } }
public void GivenAUserGroupAndAnAccessControlledObjectWhenGettingTheAccessListThenUserHasAccessToThePermissionsInTheRole() { var readOrganisationName = this.FindPermission(Organisations.Meta.Name, Operation.Read); var databaseRole = new RoleBuilder(this.Session).WithName("Role").WithPermission(readOrganisationName).Build(); var person = new PersonBuilder(this.Session).WithFirstName("John").WithLastName("Doe").Build(); new UserGroupBuilder(this.Session).WithName("Group").WithMember(person).Build(); this.Session.Derive(true); this.Session.Commit(); new AccessControlBuilder(this.Session).WithSubject(person).WithRole(databaseRole).Build(); this.Session.Commit(); var sessions = new ISession[] { this.Session }; foreach (var session in sessions) { session.Commit(); var organisation = new OrganisationBuilder(session).WithName("Organisation").Build(); var token = new SecurityTokenBuilder(session).Build(); organisation.AddSecurityToken(token); var role = (Role)session.Instantiate(new Roles(this.Session).FindBy(Roles.Meta.Name, "Role")); var accessControl = (AccessControl)session.Instantiate(role.AccessControlsWhereRole.First); accessControl.AddObject(token); Assert.IsFalse(this.Session.Derive().HasErrors); var accessList = new AccessControlList(organisation, person); Assert.IsTrue(accessList.CanRead(Organisations.Meta.Name)); session.Rollback(); } }
public void SetPermissions(AccessControlList dacl) {}
public void GivenAnAuthenticationPopulatonWhenCreatingAnAccessListForGuestThenPermissionIsDenied() { var guest = new PersonBuilder(this.DatabaseSession).WithUserName("guest").WithLastName("Guest").Build(); var administrator = new PersonBuilder(this.DatabaseSession).WithUserName("admin").WithLastName("Administrator").Build(); var user = new PersonBuilder(this.DatabaseSession).WithUserName("user").WithLastName("User").Build(); Singleton.Instance(this.DatabaseSession).Guest = guest; new UserGroups(this.DatabaseSession).FindBy(UserGroups.Meta.Name, "Administrators").AddMember(administrator); this.DatabaseSession.Derive(true); this.DatabaseSession.Commit(); var sessions = new ISession[] { this.DatabaseSession, this.CreateWorkspaceSession() }; foreach (var session in sessions) { session.Commit(); foreach (AccessControlledObject aco in this.GetObjects(session, Organisations.Meta.ObjectType)) { // When var accessList = new AccessControlList(aco, guest); // Then Assert.IsFalse(accessList.CanExecute(Organisations.Meta.JustDoIt)); } session.Rollback(); } }
public void GivenAWorkspaceNewAccessControlledObjectWhenGettingTheAccessControlListThenUserHasAccessToThePermissionsInTheRole() { var readOrganisationName = this.FindPermission(Organisations.Meta.Name, Operation.Read); var databaseRole = new RoleBuilder(this.DatabaseSession).WithName("Role").WithPermission(readOrganisationName).Build(); var person = new PersonBuilder(this.DatabaseSession).WithFirstName("John").WithLastName("Doe").Build(); this.DatabaseSession.Derive(true); this.DatabaseSession.Commit(); new AccessControlBuilder(this.DatabaseSession).WithSubject(person).WithRole(databaseRole).Build(); this.DatabaseSession.Commit(); var workspaceSession = this.CreateWorkspaceSession(); var organisation = new OrganisationBuilder(workspaceSession).WithName("Organisation").Build(); var token = new SecurityTokenBuilder(workspaceSession).Build(); organisation.AddSecurityToken(token); var role = (Role)workspaceSession.Instantiate(new Roles(this.DatabaseSession).FindBy(Roles.Meta.Name, "Role")); var accessControl = (AccessControl)workspaceSession.Instantiate(role.AccessControlsWhereRole.First); accessControl.AddObject(token); Assert.IsFalse(this.DatabaseSession.Derive().HasErrors); var accessList = new AccessControlList(organisation, person); accessList.CanRead(Organisations.Meta.Name); }
public void GivenAnAccessListWithWriteOperationsWhenUsingTheHasWriteOperationBeforeAnyOtherMehodThenHasWriteOperationReturnTrue() { var guest = new PersonBuilder(this.DatabaseSession).WithUserName("guest").WithLastName("Guest").Build(); var administrator = new PersonBuilder(this.DatabaseSession).WithUserName("admin").WithLastName("Administrator").Build(); Singleton.Instance(this.DatabaseSession).Guest = guest; new UserGroups(this.DatabaseSession).FindBy(UserGroups.Meta.Name, "Administrators").AddMember(administrator); this.DatabaseSession.Derive(true); this.DatabaseSession.Commit(); var sessions = new ISession[] { this.CreateWorkspaceSession(), this.DatabaseSession }; foreach (var session in sessions) { session.Commit(); AccessControlledObject aco = new OrganisationBuilder(session).Build(); var accessList = new AccessControlList(aco, administrator); Assert.IsTrue(accessList.HasWriteOperation); session.Rollback(); } }
private bool HasAccess(AccessControlList list, string editModeAccessLevel) { AccessLevel al; if (AccessLevel.TryParse(editModeAccessLevel, true, out al)) return list.QueryDistinctAccess(al); return true; }