There's definitely no rule precluding being overtaken on the last lap / corner; it's all fair game (yellow "no overtaking" flags permitting in the event of an incident). Drivers simply do this "for show" and/or to acknowledge their team who may be gathered and celebrating on the pit wall as they cross the line. It's not limited to the leader either. For example a driver finishing unexpectedly higher than normal (e.g. 4th or 5th place) may do the same thing whereas a driver who is unhappy with their finishing position would typically not (even if they were in second place).
For example in this clip, Vettel (red car) crossed the line first but knew he had a penalty so knew he was effectively in second place. He very much did not celebrate as he crossed the line. Behind him, Hamilton (silver car) won and was happy so he swerved to his to team to celebrate: