Add and enable Rut Auth capability using scripting API

Continuing the discussion from Advanced Use Cases for the Nexus Repository Manager API:

In addition to what @rseddon mentioned, you may also need to create and configure a Nexus Capability so that Nexus knows which HTTP header to look at for the authenticated user name.

More about RUT Auth can be found in the docs at Authentication via Remote User Token. And, not directly related, but architecturally the same, this guide provides context around Remote User Token Authentication: PKI Authentication for Nexus - Sonatype Guides

A sample groovy script to create and configure the capability, which will also automatically enable the realm:

import groovy.json.JsonOutput
import org.sonatype.nexus.capability.CapabilityReference
import org.sonatype.nexus.capability.CapabilityType
import org.sonatype.nexus.internal.capability.DefaultCapabilityReference
import org.sonatype.nexus.internal.capability.DefaultCapabilityRegistry

returnValue = JsonOutput.toJson([result : 'Did NOT add Rut Auth'])

def capabilityRegistry = container.lookup(DefaultCapabilityRegistry.class.getName())

//Capability specific values/properties
def capabilityType = CapabilityType.capabilityType("rutauth")
def capabilityProps = ['httpHeader': 'some_auth_header']
def capabilityNotes = 'configured through scripting api'

//check if existing Rut Auth capability exists
DefaultCapabilityReference existing = capabilityRegistry.all.find { CapabilityReference capabilityReference ->
  capabilityReference.context().descriptor().type() == capabilityType
}

//If it doesn't, add it with given values/properties
//This should also enable the rutauth-realm
if (!existing)
{
  log.info('Rut Auth capability created as: {}',
           capabilityRegistry.add(capabilityType, true, capabilityNotes, capabilityProps).toString())

  returnValue = JsonOutput.toJson([result : 'Successfully added Rut Auth!'])
}

return returnValue