A US judge has ruled Donald Trump's firing of the head of a federal watchdog agency illegal, in an early test of the scope of presidential power.