Expand token troubleshooting script to provide when large number of tokens will be expiring
In addition to the trouble shooting scripts added to https://docs.gitlab.com/ee/security/token_overview.html#troubleshooting to identify token expiration, it would be beneficial to allow admins to easily identify when there are large number of token expirations set. An earlier version of this script was composed by @atevans that we can use to modify and add to the trouble shooting docs.
def find_big_expiry_dates(top_n = 5)
PersonalAccessToken.where('expires_at > NOW()')
.select('expires_at, count(*) as total')
.group(:expires_at)
.map {|row| [row.expires_at, row.total] }
.sort_by(&:last)
.reverse
.take(top_n)
end
def update_expiry_for_date(dt, new_expires_at: 6.month.from_now)
PersonalAccessToken.where(expires_at: dt.to_date).update_all(expires_at: new_expires_at)
end
########################
# HOW TO USE:
#
# 1. Copy the above functions and paste into the Rails console
# 2. Follow the steps below to check for dates with many expiring
# tokens and update the tokens expiring on that date to a future date
# instead
#########################
big_expiry_dates = find_big_expiry_dates
# you should see the top 5 dates with the most tokens expiring,
# paired with the number of token expiries on that date
# printed to your console. If the first date looks correct,
# (many tokens expiring, about 1 year from when you upgraded to 16.0)
# store the date in a variable to pass to the next function:
biggest_expiry_date_info = big_expiry_dates[0]
biggest_expiry_date = biggest_expiry_date_info.first
# call the second function to update all tokens with this expiry date to have an expiry date
# 6 months in the future
update_expiry_for_date(biggest_expiry_date)
# this should print how many PATs were updated
# you can check the expiry dates again; the date with the most tokens expiring should
# now be 6mo in the future
find_big_expiry_dates