You need to go to an auto repair shop, one that sells car parts, and ask for some black silicon sealant, especially for a sun roof.
There are some foam sticky washers too, that can be trimmed to fit your purposes, and will channel the water away from the roof. They have to be glued on very carefully with a weather resistant adhesive, and trimmed properly.
If you go with the silicon option, first clean up the are and scrape off any old perished adhesive, then clean the area with rubbing alcohol.
When it is dry, clean and dust free, apply the silicon to both edges, in a smooth steady stream with no breaks. It should be even. The corners can take a double take. The sealant should be allowed to dry on a sunny day.
The car should not be parked in the direct sun for long periods after that, as the sealant must stay soft and flexible, and not harden and crack in direct heat, or it won't last.