Signing succeeds but validate fails with "Missing code-signing certificate"

We have a command line script that runs xcodebuild to make an archive, then runs xcodebuild again to export the archive to make an ipa, and then runs "altool --validate-app" to check that everything will be fine for a subsequent upload to the app store. This has been working fine for a few years but recently stopped working and we cannot figure out why.

The validation fails with this error:

ERROR: [altool.105912F20] Validation failed (409) Invalid Provisioning Profile. The provisioning profile included in the com.<redacted> bundle [Payload/<redacted>.app] is invalid. [Missing code-signing certificate]. A distribution provisioning profile should be used when uploading apps to App Store Connect. (ID: <redacted uuid looking thing>)

The project is configured with 'Automatically manage signing' unchecked, and the profile was created on developer.apple.com/account/resources/profiles and the matching profile magically appears in the "Provisioning Profile" drop down in Xcode.

The profile was created with two certificates checked, but examining the embedded.mobileprovision profile that ends up in the compiled ipa payload it appears to contain 19 certificates (probably all of them for this org?).

Is there a way to find out which certificate is missing exactly? And once identified is it a case of adding it to the profile used during compilation to fix this?

Ancillary question: why does the embedded.mobileprovision file contain so many certificates, and how does xcodebuild decide which ones it includes there?

Signing succeeds but validate fails with "Missing code-signing certificate"
 
 
Q