Recently I got into a situation where a user had some roles, which granted additional roles, and so on.
As I did not understand where a particular permission came from, I wrote this code which gets an initial set of roles and unwraps them recursively, accounting for any repeats.