Any sovereign nation can write whatever it likes into its legal code. Anyone wishing to do business there must obey the law of that land. If, for example, the US decided retirement age was 47 for pilots and that no pilot over that age could operate in their airspace, then any company that wished to fly to the US would have to ensure that it's pilots met that criterion for that route.
We may not like that other countries have laws we don't like but we still have to obey them whilst in that country.
So to ask if it is legal for any country to impose an age for pilot retirement, is a bit confused. A sovereign state determines its own laws and therefore determines what is legal within its borders.
The only exemptions to that are international laws, which are essentially treaties between countries, if broken then sanctions or other more forceful measures would have to be taken by a coalition of other countries to force the recalcitrant nation to heel. Which simply won't happen over the retirement age for a few well paid pilots.