Why do apache/ac-130/gunship pilots shoot targets who surrender, how is it legal and how do they determine what targets to engange?

Just want a general overview of how this process works, was watching several youtube videos of apaches/gunships shooting insurgents and was wondering how it was legal for them to engage targets that surrender, and how they can determine if a target is actually an enemy.
Apache/AC-130 pilots are allowed to shoot targets who surrender, provided they follow the rules of engagement. [1] Generally, they engage only enemy combatants and refrain from attacking non-combatants and enemy fighters who surrender. [1] The pilots determine who to engage by clearly marking military vehicles and personnel. [1]
Apache helicopter pilots shot and killed Iraqis who tried to surrender, despite being advised that they could not surrender to aircraft and therefore remained valid targets [1]. Both attacks occurred during the Iraq war; in 2007, insurgents jumped out of a truck that came under fire from the Apache and wanted to surrender, but were killed nonetheless [3]. In another incident, two men fled from the helicopter after it zoomed in on them, and the Apache crew killed them with a Hellfire missile [3]. It is unclear whether the same personnel were involved in both attacks [2].