The context is inserted by tradition, not a part of the original words, referencing events in 2 Samuel 15. It is by no means implausible. This psalm reveals how David was hardly arrogant, rather quite confident in the power of moral purity. We could argue that David’s sorrows were often of his own making. He was overly indulgent of his kin, particularly his sons and his cousin, Joab. Such was the source of much evil during David’s reign. No one argues David’s failings, but He was deeply and personally loyal to his God more than anyone living on this earth. His primary virtue was his utter humility toward the Lord.
At the point when David and his court fled over the ridge toward the Jordan Valley, it certainly appeared God did not favor him. David knew better, because the problem was with David’s choices, not God’s. The Lord is not fickle as humans are, so David felt certain things would run their course. Eventually God would restore him to the throne of Israel. Meanwhile, David had no reason to believe this was the hand of God turned against Him, so he maintained his faith. He presents the image of God patiently waiting in His tent in Zion for David to return, this being before the Temple was built. Meanwhile, God had His own plans for events and David must ride out the storm.
With this divine assurance, David had no trouble sleeping peacefully at night. Being surrounded by human enemies was no significant threat because God had already seen him through worse. Remember Goliath? In God’s good time, He would rise up and strike most decisively. That’s how God handled people who served His purpose.