WASHINGTON - Some of the FBI’s electronic surveillance activities violated the constitutional privacy rights of Americans swept up in a controversial foreign intelligence program, a secretive surveillance court has ruled.

The ruling deals a rare rebuke to U.S. spying programs that have generally withstood legal challenge and review since they were dramatically expanded after the Sept. 11, 2001, attacks. The opinion resulted in the FBI agreeing to better safeguard privacy and apply new procedures, including recording how the database is searched to detect possible future compliance issues.

The intelligence community disclosed Tuesday that the Foreign Intelligence Surveillance Court last year found that the FBI’s efforts to search data about Americans ensnared in a warrantless internet-surveillance program intended to target foreign suspects have violated the law authorizing the program, as well as the Constitution’s Fourth Amendment protections against unreasonable searches. The issue was made public by the government only after it lost an appeal of the judgment earlier this year before another secret court.

The court concluded that in at least a handful of cases, the FBI had been improperly searching a database of raw intelligence for information on Americans—raising concerns about oversight of the program, which as a spy program operates in near total secrecy.

The October 2018 court ruling identifies improper searches of raw intelligence databases by the bureau in 2017 and 2018 that were deemed problematic in part because of their breadth, which sometimes involved queries related to thousands or tens of thousands of pieces of data, such as emails or telephone numbers. In one case, the ruling suggested, the FBI was using the intelligence information to vet its personnel and cooperating sources. Federal law requires that the database only be searched by the FBI as part of seeking evidence of a crime or for foreign-intelligence information.