WASHINGTON—A federal judge ruled Monday that the National Security Agency's collection of phone records "almost certainly" violates the Constitution, setting up a larger legal battle over long-secret counterterrorism programs.

U.S. District Judge Richard Leon's sharply worded opinion labeled as "almost Orwellian" the NSA's bulk phone-surveillance program, one of several shots the judge took at the spying and its legal justifications.

...