Proverbs 16:4 (ESV)

4 The LORD has made everything for its purpose, even the wicked for the day of trouble.

All created things act spontaneously according to their natures. Yet while acting to fulfill their own purposes, they act, individually and together, to fulfill the holy purposes of the Lord. God made all things in this way for himself, for (as Paul says), from him, and through him, and to him are all things (Romans 11:36). Even though our holy God could not be the Author of sin, he allows and uses it in a sovereign and sinless way for his glory and our good. By faith, we can only understand a small part of this now, but one day it will be unquestionably clear to all.