The issue here isn't so much that they can run anything they like - it's not implied that the provider
intentionally put a cross-site scripting vulnerability into the code. The issue is that you don't get to audit the third party code for vulnerabilities, and vulnerabilities can be introduced without your knowledge.
But that is part of the tradeoff you make when you agree to accept money from someone to add their code to your site.
If someone offers you a hundred bucks to carry a bag onto a plane for them, you'd be right to be suspicious. Ah, but it's not just a random stranger. You were introduced to them by your buddy, the ad network. So that's okay then. Your ad provider wouldn't be dealing with anybody who was actually criminal. But what about negligent? Did they pack the bag themself? Have they let it out of their sight?
When you run ads on your site, remember which direction the money is flowing in, and remember who is the customer.
Ad networks are a trust broker. The ad provider wants to know their ad really was shown to a real person in a real web browser, who really does meet the demographic profile they are paying to target. They do not trust you, the publisher, at all. And they are paying.
You, as the publisher, are getting money from the ad network to compensate you for the inconvenience of surfacing the advertiser's content on your site. And of proving that you aren't defrauding them. To do that, you are going to give up some control.
And that includes control over whether the code you're serving is secure.