This is a good enough question that Newton allegedly delayed publishing his Principia while he worked it out.
The search term you want is "shell theorem" which states (among other things) that the gravitational field due to any spherically symmetric mass distribution outside that mass distribution is equivalent to that for a all the mass concentrated in at the center.
So it is completely valid for all perfectly spherically symmetric objects.
Now, objects like the Earth and the Sun are not completely spherically symmetric (they are fat around the equator, and the Earth is slightly pear-shaped), but it is also true that the effects of those differences fall off faster than the overall effect, so the father you get from an object that is not spherically symmetric the less you care about the difference, and the more valid the point mass approximation becomes. Search term here "multipole expansion".
The Earth's dipole and quadrupole moments affect what satellite orbits are stable, and the Moon's "mass concentrations" are significant enough that numerous early flyby and impact missions failed to achieve their goals (some failed spectacularly).