"Captain of the guard" (Genesis 39:1). Even so, "The Lord was with Joseph" (Genesis 39:2). Rabbi Abbahu said: I have proof only that the Lord was with him in ease; from where do I know it even in distress? Behold, it is written, "So Joseph's master took him and put him into the prison" (Genesis 39:20); even so, "The Lord was with Joseph" (Genesis 39:21). Rabbi Abbahu said: You have a person who loves his fellow in ease, but when trouble comes upon him, he acts as though he does not know him. But the Holy One, blessed be He, is not so. Rather, "He was there in the prison" (Genesis 39:20), "The Lord was with Joseph" (Genesis 39:21): in distress and in ease, He was with him.
The Lord Was With Joseph in Prison and in Prosperity
Midrash Tanchuma Buber, Vayeshev 16:4
שר הטבחים. אעפ"י כן, ויהי ה' את יוסף, אמר ר' אבהו אין לי אלא ברווחה, מנין אפילו נבצער, הרי כתב ויקח אדוני יוסף אותו ויתנהו אל בית הסהר (שם לט כ), אעפ"י כן ויהי ה' את יוסף (שם שם כא). אמר ר' אבהו יש לך אדם שהוא אוהב חבירו ברווחה, הגיעה לו צרה עשה כאילו אינו יודעו, אבל הקב"ה אינו נכן, אלא ויהי שם בבית הסהר מ (שם שם כ), ויהי ה' את יוסף (שם שם כא) בצרה וברווחה היה עמו.