WASHINGTON — In the first legal decision on a federal law that denies access to U.S. courts to detainees in the war on terrorism, a federal judge ruled Wednesday that foreign prisoners held at Guantánamo Bay, Cuba, could not sue for freedom.

But, in a split decision, U.S. District Judge James Robertson also ruled that the law’s denial of that right to the more than 12 million legal immigrants living in the United States was unconstitutional.

The first part of the ruling affirmed what Congress intended when it passed the Military Commissions Act in October. The decision came in the case of Salim Hamdan, the onetime driver to Osama bin Laden, who won what appeared to be a landmark victory in the Supreme Court in June.

Taking up Hamdan’s lawsuit, the high court’s justices said President Bush had overstepped his power when he created a system of military tribunals for foreign-born alleged terrorists.

In response, Congress passed a law authorizing military tribunals. In addition, it moved to deny access to the courts to “aliens” accused by the president of being terrorists or “unlawful combatants.”

Critics in the Senate said the provision was written so broadly that it took away legal immigrants’ right of habeas corpus. This right allows people who are arrested and imprisoned to go before a judge and plead for freedom.

In Wednesday’s ruling, Robertson said lawmakers had the legal power to close the courts to the detainees at Guantánamo Bay.

“Congress unquestionably has the power to establish and define the jurisdiction of the lower federal courts,” he wrote in a 22-page opinion. Until some recent decisions, he said, it had always been understood that “an alien captured abroad and detained outside the United States” did not have a right to sue in a federal court.

However, the Constitution protects the right of habeas corpus for people living in the United States, the judge said.

Meanwhile, the incoming chairman of the Senate Judiciary Committee said Wednesday he would subpoena Bush administration officials if they refuse requests for documents and testimony, including two long-sought memos detailing its detention and treatment of terror suspects overseas.

One is a presidential order signed by Bush authorizing the Central Intelligence Agency to set up secret prisons outside the United States to house terrorism suspects. The other is a 2002 Justice Department memorandum outlining “aggressive interrogation techniques” that could be used against terror suspects.

“I expect to get the answers. If I don’t … then I really think we should subpoena,” said Sen. Patrick Leahy, D-Vt.