This is the third post in the Sitecore and FxCop series.



I’ve been working on a bunch of easier to implement rules, which I figured I’d run through here. As always, I’m trying to improve the code, either increasing the performance of the code or making it a little more safe to use.

There’s a couple of categories in which I’ve added rules, and I’ll be creating a post per category, as it’ll be a huge post otherwise.

The categories I added rules in are:

Security

Fields

ItemAxes

Database

Security

The first new FxCop rule I implemented is to make sure to use the Sitecore.Security.Accounts.UserSwitcher, rather than the Sitecore.SecurityModel.SecurityDisabler.

The SecurityDisabler elevates the users permission (temporarily) to administrator rights, which has the potential to be very dangerous to use and errors to potentially be very costly. An interesting side effect is that anything done with the SecurityDisabler will show up as being done by the sitecore\Anonymous role, messing up the audit trail.

However, if we use a UserSwitcher, we will actually tell the system to do something based on a user, with the access rights of that user. Consider the following code snippet:

namespace SomeNamespace { public class SomeClass { var home = Sitecore.Context.Database.GetItem("{66EC0398-1E67-4D43-B2EB-ED29E3E8E291}"); using (new Sitecore.SecurityModel.SecurityDisabler()) { home.Delete(); } Sitecore.Security.Accounts.User someUser = Sitecore.Security.Accounts.User.FromName(@"sitecore\SomeUser", false); using (new Sitecore.Security.Accounts.UserSwitcher(someUser)) { home.Delete(); } } }

Assuming we have set up the access for the SomeUser account correctly, the home item will not be deleted with the UserSwitcher, but will be deleted with the SecurityDisabler, because we have effectively disabled all security there. In our case, because the SomeUser account has been set up correctly, an AccessDeniedException will be thrown.

Although this is a trivial example, it does point out the dangers of the SecurityDisabler.

The rule is actually also very easy, and is very similar to the rules described in earlier posts. The biggest difference is that because we’re now looking for a constructor rather than a method that’s been called, we need to override the VisitConstruct method.

public override void VisitConstruct(Construct construct) { base.VisitConstruct(construct); Method method = (Method)((MemberBinding)construct.Constructor).BoundMember; if (method.FullName.Equals("Sitecore.SecurityModel.SecurityDisabler.#ctor", StringComparison.OrdinalIgnorecase) { this.Problems.Add(new Problem(this.GetResolution(method), construct)); } }

We don’t really care about anything else – if the SecurityDisabler is getting called, we want to add a warning that the UserSwitcher should be used.