Skip to content

Implement org-owned service accounts with space entitlements and workload identity - #5520

Open
rkoster wants to merge 207 commits into
cloudfoundry:mainfrom
rkoster:service-accounts-poc
Open

rkoster wants to merge 207 commits into
cloudfoundry:mainfrom
rkoster:service-accounts-poc

Conversation

@rkoster

@rkoster rkoster commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implement the Cloud Controller portion of Service Accounts for Cloud Foundry Workload Identity (community #1645), aligned with the RFC document at its merged revision.

Service accounts are org-owned identities, shared by apps only in explicitly entitled spaces of the same org. Each org has an admin-allocated, immutable, foundation-unique service_account_prefix; account names are immutable and unique within that org. Both use lowercase RFC 1123 labels of 3–63 characters.

For prefix acme-payments and account payments-worker:

Identity Value
UAA client ID / token subject cf:service-account:acme-payments:payments-worker
Instance-certificate DNS SAN payments-worker.acme-payments.svc.identity
Route-policy source cf:svc:acme-payments:payments-worker

One app has at most one account; many apps can share an account. Assignment grants no permissions: account use, CAPI roles, external grants and route policies remain explicit and independent.

Intentional RFC divergence: independent CAPI user lifecycle

Unlike RFC Appendix D, first bind provisions only the managed UAA client; it does not create a roleless CAPI user. CAPI users and their role grants remain independently managed. The existing CAPI authentication flow can lazily create a roleless OAuth user on its first API request; explicit roles are still required for resource access. No new explicit-user-creation command or authentication behavior is introduced here.

Disable, enable and service-account retirement do not create, disable or delete CAPI users or their roles, nor do they change external WIF identities/grants. Account deletion removes the managed UAA client and account resource. Ordinary space/org deletion still removes roles on deleted resources. If an identity is explicitly reused, independently retained CAPI roles can apply to the same client ID, just as retained external grants can; remove those grants independently when retiring access. This avoids coupling workload identity lifecycle to CAPI user lifecycle and requires no account-to-principal ownership field.

Proposed RFC amendment: nested attribution

Following Draft RFC amendments #1709, new managed registrations map attribution to cf.instance_guid, cf.app_guid, cf.space_guid and cf.org_guid, emitted by UAA as one nested cf object. The owning-org certificate requirement uses the same cf.org_guid mapping key. Issuer/subject identity and role authorization remain unchanged. Operators configure token lifetime through cc.service_accounts.token_validity_in_seconds: a positive integer defaulting to 300, with no CAPI-imposed five-minute ceiling. UAA must still enforce certificate expiry and its applicable token-policy limits. Existing managed registrations receive validity-only updates on their next provisioning/enable reconciliation; configuration deployment alone does not immediately update them, and issued tokens are unaffected. Identity/trust/authority drift still fails closed. The amendment is still proposed. Existing flat-claim UAA registrations are not silently rewritten and require deliberate reconciliation/retirement before using the new profile.

Cloud Controller implementation

Accounts, namespaces and permissions

  • Add /v3/service_accounts lifecycle, metadata, filtering, app listing and space-entitlement APIs, plus GET/PATCH /v3/apps/:guid/relationships/service_account.
  • Add organization service_account_prefix on creation or one-time unset-to-value update. Allocation is admin-only and atomic; an allocated prefix cannot be renamed, cleared or automatically released on org deletion. An unset prefix prevents account creation, entitlement expansion and assignment.
  • Space Developers create accounts with an initial entitlement to their space. Org Managers/admins oversee all accounts in the org, including accounts with no entitled spaces. Developers manage accounts entitled to their active spaces; sharing requires management authority or Developer access to an existing entitled space and the destination space. Cross-org entitlements are rejected; app writers assign only in entitled spaces. No new roles are introduced.
  • Add service_accounts.total_service_accounts to org quotas and an optional rolling seven-day creation budget per authenticated user/client across spaces. Admins are exempt from the budget; failed creation rolls back consumption and deletion does not refund it. Concurrent creation and first-bind provisioning are serialized, including MySQL repeatable-read handling.
  • Keep org-local deleted-name reservations and timestamped deletion history independently of audit retention. Explicit Org Manager/admin reuse_name creates a new UUID, is audited, and warns that external grants and still-valid old certificates may apply. Live collisions and quotas remain enforced.

Lifecycle, UAA registration and runtime identity

  • Provision a secretless UAA client on first bind through retryable pollable jobs, without creating a CAPI user. Reuse active provisioning jobs, reject registration collisions and human-user shadowing, and reconcile enable, disable and deletion. Independently managed OAuth users and their roles are left untouched.
  • Register the exact qualified SAN and owning-org claim restriction, reference an operator-defined UAA CA trust bundle, request bearer issuance with tls_client_certificate_bound_access_tokens: false, configure operator-selected token validity (default 300 seconds), and map nested instance/app/space/org attribution claims. Support the named allowed-resource-policy reference for federation audiences; developers do not control registration inputs.
  • Add typed BBS account name/prefix properties and generated Ruby bindings. Preserve existing certificate attribution; expose only non-secret discovery through VCAP_SERVICE_ACCOUNT. Snapshot process identity until explicit restart; new runtime tasks use the current assignment; staging excludes account identity.
  • Retain accounts when spaces are deleted, removing their entitlements. Org deletion cleans up accounts and managed UAA clients retryably; ordinary resource deletion removes roles on deleted orgs/spaces, while CAPI user records remain independently managed. Failures retain the parent for retry. Direct deletion/unentitlement checks desired and active process/task references and identity-bearing service bindings.
  • Create the final org-owned schema directly, with required prefix-qualified identities. There are no compatibility paths, identity fallbacks or backfill migrations for intermediate unpublished POC models. Retain deletion timestamps for future ad hoc operational queries; no reservation-statistics collection is implemented.

Explicit authorization and integrations

  • Resolve qualified service-account principals locally for existing CAPI role APIs. Binding does not grant resource roles.
  • Support qualified cf:svc:<prefix>:<name> route-policy sources, account resolution and domain org/space restrictions while preserving existing source semantics.
  • Snapshot account identity on service bindings and add { issuer, subject } to the CF platform context.service_account of broker bind requests for ready accounts; service keys do not receive it. Identity-based bindings must be removed before app reassignment. Existing bindings require rebind to adopt the account. Broker-side shared-grant lifecycle remains the broker's responsibility.
  • Add lifecycle, prefix allocation, entitlement, assignment and name-reuse audit evidence, API documentation, migrations and regression coverage.

Verification

  • All 18 GitHub checks pass at 498d40b4c, including normal and backward-compatibility suites on MySQL 8.0/8.2 and PostgreSQL 14/15/17, OpenAPI request conformance, docs, RuboCop, CodeQL and CLA. Main test run · backward compatibility.
  • Full local OpenAPI request-conformance run: 8,164 examples, zero failures before the final database-specific corrections; subsequent CI OpenAPI conformance also passes at the current head.
  • Full migration/creation-budget regression runs on MySQL 8.2 and PostgreSQL 17 passed with platform-specific pending examples; additional MySQL creation, quota, assignment and entitlement regressions passed 68 examples. Meaningful failing-test RED and passing-implementation GREEN commits are preserved, including deterministic concurrency and FK/index rollback regressions.
  • Lab validation with the companion native CLI/CATs demonstrates shared qualified account identity across apps in entitled spaces, independent instance keys, bearer HTTPS CAPI access with explicit roles, wrong/unbound identity denials, disable/enable, restart-sensitive assignment, current-identity tasks, staging exclusion, and Org Manager recovery after deletion of the last entitled space. Account-routing cases exercise certificate-only access/denials, disable semantics and domain space scope. Companion acceptance tests.
  • UAA lab checks demonstrate attribution claims, bearer tokens without cnf, named resource-policy audience selection/denials, and policy-only updates without re-registering account clients. These are integration evidence, not proof of every external provider's token requirements.

Dependencies, rollout and remaining validation

  • Companion changes: capi-release #702, BBS #168, Diego #1216, CLI #3875, and CATs #2193. Generated BBS consumers and deployment/module pins must agree on the qualified account contract.
  • UAA mTLS baseline is merged in UAA #4109, superseding the earlier build(deps): bump json_pure from 2.7.6 to 2.8.1 #4076 baseline. Named federation resource policies are tracked by UAA #4125 / implementation #4137; build(deps-dev): bump rubocop from 1.69.1 to 1.69.2 #4137 is the tested lab baseline.
  • Service-account activation uses one default-off setting: cc.service_accounts.enabled in BOSH, rendered as service_accounts_enabled for API, worker, clock and deployment updater. Deploy compatible UAA/BBS/Diego and routing components before enabling it; there is no numeric contract-version setting. The app-facing token endpoint must support reachable, trusted mTLS, either directly or through UAA's authenticated trusted-proxy mode.
  • Deploy compatible routing enforcement before enabling CAPI account route-policy producers. There is no router-version configuration gate; parallel release updates do not establish this ordering.
  • Remaining integration criteria include the near-leaf-expiry token lifetime cap, long-running credential renewal, real cloud-provider federation (including AWS azp/audience semantics), broker-managed shared grants end to end, Windows runtime, and namespace-limited UAA client administration. CAPI registration alone does not demonstrate these UAA/provider/broker properties.
  • Disable stops new token issuance when effective; unbind/restart, entitlement changes and deletion are not immediate cryptographic revocation of existing certificates, JWTs or exchanged provider credentials. Certificate-only route access requires removal of the relevant route policy to withdraw its grant.

The RFC document's recorded status is Draft, although community #1645 is merged. This PR implements the CAPI scope and records its cross-component dependencies; it does not claim complete end-to-end RFC acceptance.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Potential foundation-wide entitlement scans and repeated UAA discovery while bind transactions hold locks warrant human assessment of scalability and availability risks.

No open issues 🎉

4 resolved since last review

Review effort: Balanced

@rkoster

rkoster commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Potential foundation-wide entitlement scans

Addressed in f2903b3 (RED 58a04f1): added a space-first (space_guid, service_account_guid) index to the entitlement schema, with creation/rollback coverage. Account-first lookups retain the primary key. This addresses the space-filtered lookup path noted in review #5520 (review).

@rkoster

rkoster commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

repeated UAA discovery while bind transactions hold locks

Addressed in e4a087a (RED 2f0f042): broker clients now use shared, synchronized issuer discovery with a five-minute cache instead of constructing a token decoder per bind. Tests cover reuse across clients, concurrent callers, expiry, retry after failure, and refusal to use expired data. Cold/expired discovery still requires a UAA request. Combined migration/discovery/broker/V2 suites pass 216 examples on each of PostgreSQL 17 and MySQL 8.2; changed-file lint passes. Review: #5520 (review).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because a critical edge case involving role grants before provisioning can reject unclassified client users, blocking provisioning and retries before the first token is issued.

No open issues 🎉

Review effort: Balanced

@tcdowney tcdowney left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Statler: Well, it's certainly a big PR.
Waldorf: Big? I've seen shorter RFCs! Doh-ho-ho-ho!

Heckling aside, we did a multi-pass review of 8bbbd9286 focused on correctness and not breaking existing users (operators/apps that never touch service accounts). Static review only; we did not run tests. Findings are inline. Summary:

Must fix

  1. v2 managed bind holds an app row lock across the broker HTTP call: affects every foundation, even with the feature off (service_binding_create.rb:29).
  2. Non-NotReady identity errors suppress bump_freshness for the whole sync (service_account_identity.rb:49, :26; processes_sync.rb:73).
  3. Role granted before first provisioning permanently blocks provisioning (service_account_provision.rb:26). This agrees with the existing Copilot comment.

Should fix

  1. Unprovisioned reservations can't be deleted while the feature is disabled (service_accounts_controller.rb:106).
  2. username_populator relabels a pre-existing OAuth client whose ID matches a reserved/failed account.
  3. One extra org query per desired process in certificate_properties (process.app.organization not eager-loaded).

Checked and looks fine for existing users

  • DesiredLRP/Task payloads for account-free apps are unchanged (same OU values/order, new protobuf field unset, no new env). ProcessesSync compares updated_at and no migration touches it, so no mass re-desire on upgrade.
  • Broker bind context/bind_resource are byte-identical for account-free apps (v2 and v3). Service keys and route bindings are unchanged. Issuer discovery is only reached for account-bearing bindings.
  • All new config keys are optional with defaults, so existing manifests boot.
  • Existing quotas get -1 (unlimited). Org/space/quota/presenter changes are additive. Org delete with zero accounts makes no UAA call.
  • Route policy source validation is unchanged for existing formats. OAuth client auth classification is unchanged.

Not verified

Migration duration/locking on production-sized tables; the old-code/new-schema suite; strict client/CLI tolerance of the new top-level service_accounts key in quota responses; external UAA/Diego/router behavior.

— Statler & Waldorf (the Muppets), assisted by Claude Code (Opus 5.5)

def create(app, service_instance, message, volume_mount_services_enabled, accepts_incomplete)
broker_error = nil
binding = ServiceBinding.db.transaction(savepoint: true) do
app.lock! if service_instance.is_a?(ManagedServiceInstance)

@tcdowney tcdowney Nov 23, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Must fix] App row lock held across the broker HTTP request: affects existing users

This takes app.lock! for every managed-service v2 bind, then calls request_binding_from_broker (line 68) inside the same transaction. That happens even on foundations with service accounts disabled and for apps with no account.

Scenario: a broker that takes 30–60s to respond to bind. During that time, TaskCreate (task_create.rb:21), AppStop (app_stop.rb:8), and any other bind to the same app block on the row lock. They can fail with a DB lock-wait timeout. Before this PR the broker call held no app lock. On post-save failure, cleanup_binding_without_db also makes a second synchronous broker call (unbind) while still holding the lock.

Suggestion: only lock when an account snapshot is actually needed (e.g. app.service_account_guid present), or capture the identity before the broker call without holding the lock.

Also note: the rescue list here has to stay exactly in sync with the errors on which Client#bind enqueues orphan mitigation. It matches today, but if someone adds a new mitigated error there, its job will silently roll back here.

— Statler & Waldorf (the Muppets), assisted by Claude Code (Opus 5.5)

return unless @account_guid

unless @config.get(:service_accounts_enabled) == true
raise CloudController::Errors::ApiError.new_from_details('UnprocessableEntity', 'Service account runtime is not enabled')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Must fix] Non-NotReady errors here suppress bump_freshness for every app in the sync

ProcessesSync#process_workpool_exceptions (processes_sync.rb:73) only tolerates RunnerInvalidRequest and NotReady. This branch (feature disabled) and the token-endpoint check at line 26 raise a plain ApiError/UnprocessableEntity, so any such failure sets @bump_freshness = false.

Scenario: a foundation has at least one STARTED process with an assigned account. The operator sets service_accounts_enabled: false, or the token endpoint is missing or invalid. That process's LRP then needs re-desiring, and every sync pass fails freshness. That affects freshness for all apps, including account-free ones. The existing regression test only covers a disabled account with the feature enabled.

Suggestion: raise NotReady (or a sibling error class that sync isolates) for both configuration branches, and add sync coverage for each alongside a healthy account-free process.

Waldorf: One bad apple spoils the whole sync!
Statler: At least the sync stops before the apples do!

— Statler & Waldorf (the Muppets), assisted by Claude Code (Opus 5.5)

begin
account.db.transaction(savepoint: true) do
principal = User.first(guid: account.client_id)
raise Conflict.new('principal identity collision') if principal && !principal.is_oauth_client

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Must fix] An unclassified (NULL) principal is treated as a human collision, so pre-granting a role blocks provisioning forever

Scenario: create a reserved account, then POST /v3/roles with relationships.user.data.guid set to its qualified client ID before first bind. The roles path creates the CAPI user via UserCreate with is_oauth_client NULL. principal && !principal.is_oauth_client is then true. The account is marked failed and every retry fails before the UAA client is registered. The client can never authenticate to become classified, so this can't fix itself.

spec/request/service_account_roles_spec.rb inserts an already-classified OAuth user, which bypasses the real path. Suggest treating only an explicit false as a human collision (or checking UAA user existence), and adding a test that grants the role through the API first.

(This agrees with the latest Copilot comment.)

— Statler & Waldorf (the Muppets), assisted by Claude Code (Opus 5.5)

def destroy
account = readable_account
authorize_account_management!(account)
require_provisioning!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] Unprovisioned reservations can't be deleted without provisioning configured

With an org prefix allocated but provisioning disabled or unconfigured, developers can POST reserved accounts up to the org quota. DELETE then always conflicts at require_provisioning!. Enabling the flag alone queues a job that fails without UAA management credentials. No UAA client exists for these accounts, and organization_service_account_cleanup.rb already deletes them locally. Suggest using that path for accounts that never reached UAA.

— Statler & Waldorf (the Muppets), assisted by Claude Code (Opus 5.5)

users.each { |user| user.username = username_mapping[user.guid] }
client_ids = users.select(&:is_oauth_client).map(&:guid)
accounts = ServiceAccountModel.for_client_ids(client_ids).all
account_names = accounts.to_h { |account| [account.client_id, account.name] }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix, minor] A pre-existing OAuth client can be relabeled by a reserved account

ServiceAccountModel.for_client_ids also matches reserved/failed accounts. Suppose a foundation already has an unrelated UAA client named cf:service-account:acme:worker, and someone reserves worker under prefix acme. That client then shows up as worker in role/user listings, even though provisioning correctly rejects the collision. Suggest only substituting names for accounts that reached ready (or otherwise proved ownership).

— Statler & Waldorf (the Muppets), assisted by Claude Code (Opus 5.5)


def certificate_properties
account = ready_account
attributes = { organizational_unit: ["organization:#{@app.organization_guid}", "space:#{@app.space_guid}", "app:#{@app.guid}"] }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Minor] Extra query per desired process

@app.organization_guid lazily loads app.space.organization per process. Before this change, the recipe builder reused the already-loaded process.organization. ProcessesSync doesn't eager-load this, so desiring N new LRPs adds about N organization queries. The update-only path isn't affected. Consider passing in the org GUID the builder already has.

— Statler & Waldorf (the Muppets), assisted by Claude Code (Opus 5.5)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants