Skip to content

feat(azure-devops): connect through the customer's own Entra app - #494

Open
Evgeniy-DB wants to merge 5 commits into
developfrom
feature/172-add-azure-entra-app-integration
Open

Evgeniy-DB wants to merge 5 commits into
developfrom
feature/172-add-azure-entra-app-integration

Conversation

@Evgeniy-DB

Copy link
Copy Markdown
Collaborator

Summary

Adds a third way to connect Azure DevOps, next to "Sign in with Microsoft" and the administrator PAT.

The customer registers a single-tenant app in their own Entra directory and adds a federated credential ("Other issuer") that trusts this deployment as an OIDC issuer. Flow signs
a short-lived JWT, Entra exchanges it for an access token of the customer's app, and from there on the existing service-principal path is used unchanged.

  • No client secret, certificate or PAT is created, stored or rotated.
  • No administrator credential ever reaches Aixle.
  • Nothing of Aixle's is consented to in the customer's directory.
  • The customer revokes by deleting the federated credential or the app.

This does not remove the Azure DevOps administrator. Azure DevOps lets only a Project Collection Administrator add any identity to an organization. The PCA does that once, with a
generated script. What is removed is the third-party-app consent and handing a vendor an admin token.

⚠️ Not verified against a live Azure DevOps organization or Entra tenant. The live run was explicitly dropped from scope. Every request is covered by WebMock stubs written from
Microsoft's documentation. See Known compromises and What was not verified.

How it works

Customer (once)                          Flow (every token)
───────────────                          ──────────────────
1. Register single-tenant app            1. Sign JWT  iss=issuer  sub=aixle:company:<uuid>
2. Add federated credential:                          aud=api://AzureADTokenExchange  (5 min, RS256, kid)
   issuer / subject / audience           2. POST login.microsoftonline.com/<tenant>/oauth2/v2.0/token
3. PCA runs the generated script            client_assertion + customer's client_id
   (Basic license + permissions)         3. Entra fetches /.well-known/jwks.json, matches iss/sub/aud
4. Enter org + client id in Flow         4. Flow calls Azure DevOps with the returned app token

Ownership proof comes from the exchange itself. It succeeds only if someone who controls an app in that organization's directory trusted exactly this company's subject. Company B
cannot reuse company A's app: B's assertion carries B's subject.

What changed

Issuer

  • OidcIssuerController: anonymous GET /.well-known/openid-configuration and /.well-known/jwks.json, 404 unless configured, Cache-Control: public, max-age=300. Only public
    keys.
  • AzureDevops::FederationConfig: issuer URL (default protocol://domain), signing key, audience, previous public keys for rotation. kid is the RFC 7638 thumbprint (checked
    against the RFC's worked example). The feature is on exactly when a ≥2048-bit RSA private key is configured and the issuer is a public HTTPS origin with no path. No separate
    enable flag, same rule as the rest of the integration.
  • Entra::FederatedAssertion: the JWT. No x5t, aud is the token-exchange audience (not the token URL like the certificate assertion).

Data model (20261015140000_add_federation_to_azure_devops)

  • companies.public_id uuid (default gen_random_uuid(), unique, attr_readonly). Backfills existing rows.
  • azure_devops_installations.credential_kind (shared_app default / federated).
  • app_config_key is now nullable (a federated installation uses no operator app config).
  • A federated installation may change client_id and service_principal_object_id together (the customer recreated the app). Everything else stays immutable.

Token path

  • FederatedTokenExchange: sends the assertion, maps Entra errors, new FederationRejected error ("fix it on the customer's side", as opposed to CredentialActionRequired, which
    is the operator's).
  • AppTokenService branches on federated?. Cache generation is federated:<client_id>, so a recreated app is never served the old app's token.
  • CredentialProvider, Client and every agent tool are unchanged.

Connect flow

  • FederatedOnboarding#inspect! (writes nothing) and #complete! (one transaction: bind/rebind, exchange, require chosen projects visible, require Repos permissions, record the SP
    oid, activate). A failure at any step leaves nothing behind.
  • Three new project-integration endpoints (azure_devops_federated_inspect|connect|script), policy entries, routes, regenerated routes.ts.
  • PermissionCheck: asks Azure what the identity can actually do (permission evaluation), not which group it is in.
  • SetupScript: shell script for the PCA, two permission sets.
  • IntegrationService#test re-runs the permission check for a federated connection and reports removed permissions as a warning.

UI

  • AzureDevopsConnectModal gets a mode switch ("Aixle's Microsoft app" / "Your own Entra app"), shown only when the deployment can be an issuer. New AzureDevopsFederatedForm:
    copyable issuer/subject/audience, script generator, "Verify access", project picker, permission report.
  • Small refactor: CapabilityPicker, azureDevopsShared.ts extracted from the modal (no behaviour change for the existing modes).

Shared code touched

  • AppConfig.enabled? now also true when federation is configured (a deployment may have federation and no shared app).
  • azure_devops_props: client_id is nil when there is no shared app; new sharedAppEnabled and federation props.
  • Onboarding reads the oid claim through the new TokenClaims (behaviour-preserving extraction).

Docs / config: user guide (both copies), design doc §15, operator runbook, .env.example, configuration reference (+ synced portal copy), CHANGELOG.

Decisions and the alternatives considered

Decision Chosen Alternatives Why
Who is the issuer Flow The customer's own IdP (Okta, ADFS) issuing tokens Flow accepts The reverse would make Aixle hold a credential in the customer's IdP, which is what
this feature avoids
Subject granularity Per company (aixle:company:<uuid>) Per installation (company + org); per connection One credential serves every org the app reaches and every
Flow project. Per installation needs a draft row before the org is typed (the subject must be shown first). Per connection hits the 20-credentials-per-app limit and is more friction.
The trust boundary is already the company
Subject source New immutable companies.public_id companies.id (bigint), slug, name id is guessable and sequential; slug and name are editable. Nothing a user
can type reaches the subject
Issuer location Application's own domain Dedicated host (oidc.<domain>); static host Least work and no infra change. Cost: a domain change breaks every federated
connection (compromise 6)
Signing key PEM in the environment AWS KMS asymmetric key; SSM only KMS adds aws-sdk-kms and IAM, and open-source deployments need a PEM fallback anyway. Left as a
follow-up that does not change the issuer
Self-hosted Not supported (key unset, option hidden) Public-only; plus rake task + runbook to publish static jwks.json for deployments behind a VPN Entra must fetch the
documents from the internet; publishing them elsewhere is a separate piece of work. issuer_url is still a setting, so adding it later needs no rework
Token exchange failure classes New FederationRejected Reuse CredentialActionRequired The fix is on the customer's side, not the operator's
Rebinding to a recreated app Allow client_id change for federated, only with successful re-verification, in a transaction Keep client_id immutable (needs a new
installation; the restrict FK blocks it while integrations exist) Customers recreate apps; making them disconnect every integration first is hostile
Where bits come from Looked up by action name from _apis/securitynamespaces at runtime Hard-coded bit values A bit remembered wrongly would silently grant or deny.
By name, a wrong name degrades to "unknown"
What blocks a connection Only an explicit "no" on a Repos permission All checks block; nothing blocks (warn only) Boards/Pipelines/Service Hooks only matter to
projects that use them. Blocking on everything would refuse a customer who only wants repositories
Unanswerable check unknown, never blocks (fail-open) Fail-closed I could not verify the API shapes. Fail-closed would turn a wrong assumption into a connection nobody
can make
Setup tool az rest only az devops as the task text says az rest hits the same REST endpoints the code already uses (and that production has exercised:
serviceprincipalentitlements, accesscontrolentries). az devops also needs an extension and cannot add a service principal to a group without a Graph descriptor
"Custom group" Permissions granted directly to the app identity Create a group and add the SP to it Group membership for a service principal needs a Graph subject
descriptor that cannot be derived without a live organization
Project names in the script Passed as arguments; the script resolves ids Embed names (or ids) when generating Names are free text from Azure; embedding them would be an
injection path. Every interpolated value is a validated org name or GUID
Permission check cost Only for the projects the caller names; Test connection checks all selected Always check everything visible Several requests per project; by
default every org member sees every project
Admin PAT / PAT mode / sign-in Untouched Retire the admin PAT in the same release Retirement should follow a successful run on a real tenant
Live run Dropped by decision Required test tenant + org before release See below

Known compromises

Also recorded in docs/design/azure-devops-integration.md §15.4.

  1. Nothing was run against live Azure DevOps or Entra. Unverified: the token exchange, _apis/permissions and _apis/securitynamespaces response shapes, the namespace ids and
    action names (GenericRead, GenericContribute, CreateBranch, PullRequestContribute, WORK_ITEM_READ/WRITE, ViewBuilds, ViewSubscriptions/EditSubscriptions), the area-path
    root lookup, serviceprincipalentitlements for an app with no project entitlement, and the generated script end to end. This is exactly the failure mode design §13 warns about:
    contract tests that match payloads we wrote.
  2. Entra error mapping is thin. Only AADSTS700213 (subject), AADSTS700016 (app not found) and AADSTS7000112 (app disabled) carry a specific hint. Any other invalid_client
    shows Entra's code and a checklist. Codes come from documentation, not observation.
  3. The permission check fails open. unknown never blocks and only a missing Repos permission does. A wrong action name or a changed response shape degrades to "could not be
    checked", at the price of letting a broken connection through.
  4. The setup script differs from the task text. az rest instead of az devops; "custom group" is direct grants to the identity (no group). The project-visibility ACE and the
    identity descriptor shape are assumptions (the descriptor is the fallback ServiceHookGrant already uses). Verified: valid bash for both flavors (bash -n), no injection through
    any interpolated value.
  5. Revocation is not instant. Deleting the credential or the app stops new exchanges at once, but an access token already issued (about an hour) keeps working until it expires
    and Flow cannot recall it. The connection turns red on the next rejected call or test. The acceptance criterion "deleting the credential stops access" is met with this qualification.
  6. Issuer is the application's domain. Changing it breaks every federated connection at once; each customer must edit their credential. AZURE_DEVOPS_FEDERATION_ISSUER_URL
    exists to pin it.
  7. Signing key is a PEM in the environment, no KMS. A leaked key can mint a token for any app that trusts this issuer (subjects are predictable), the same blast radius as the
    shared app's certificate. Rotation is via AZURE_DEVOPS_FEDERATION_PREVIOUS_PUBLIC_KEYS; how long Entra caches the key set is not measured (the runbook says "allow a day").
  8. Self-hosted is not supported. A deployment behind a VPN cannot be reached by Entra and nothing here publishes the documents elsewhere.
  9. Nothing was retired. Admin PAT, PAT mode and Sign in with Microsoft are unchanged.
  10. Visibility is not access. By default any org member sees every project, so the app may list projects it was never granted. Only the permission check tells them apart, and
    only for the projects chosen.
  11. One credential per company serves every org its app reaches, and every Flow project of the company can use an approved installation (same as the shared app today).
  12. Boards, Pipelines and Service Hooks never block. A customer who needs them but did not grant them gets a report, not a refusal. Test connection shows removed permissions as
    a warning, not an error.

Security notes

  • The two new public endpoints are anonymous by design and serve only public keys (asserted in tests: no private JWK fields).
  • Subject is built only from an immutable uuid; the uuid is attr_readonly.
  • Assertion lifetime is 5 minutes with a unique jti; tenant and client ids are validated as GUIDs before any request.
  • Signing key must be a private RSA key ≥2048 bits and the issuer a public HTTPS origin, otherwise the feature is not offered (a misconfiguration cannot silently produce a
    half-working option).
  • The generated script contains only values validated to a fixed shape and single-quoted; project names are never part of it.
  • complete! is transactional: a failed exchange, a missing project or a missing permission leaves no installation behind.
  • Another company can connect the same organization with its own app, but its assertion carries its own subject.

Operator notes

  • Migration: adds companies.public_id with a volatile default (rewrites companies; small table) and a unique index; additive and reversible.
  • Enable: set AZURE_DEVOPS_FEDERATION_SIGNING_KEY (RSA PEM). Verify from outside:
    curl https://<DOMAIN>/.well-known/openid-configuration   # "issuer" must equal https://<DOMAIN>
    curl https://<DOMAIN>/.well-known/jwks.json               # one key, no private fields
  • New variables: AZURE_DEVOPS_FEDERATION_SIGNING_KEY, _ISSUER_URL, _PREVIOUS_PUBLIC_KEYS, _AUDIENCE (documented in the configuration reference).
  • Staging has its own domain and therefore its own issuer; never share a key between deployments.

What was verified

  • Full Rails suite: 8149 runs, 0 failures, 4 errors. The 4 errors are Temporal workflow tests that download a test server from the internet; the sandbox has no network. Unrelated to
    this change.
  • New tests (WebMock, no vendor stubbing): assertion and JWKS (incl. RFC 7638 vector and verification of a signed token against the published keys), config gating, token exchange and
    error mapping, AppTokenService federated branch and cache keying, FederatedOnboarding (incl. rollback, rebinding, cross-company isolation), PermissionCheck (granted / missing /
    unknown cases), SetupScript (shell syntax, injection refusal), controller endpoints, authorization matrix, IntegrationService#test.
  • Frontend: new Vitest suite for the federated form; the existing modal tests pass unchanged. eslint, tsc, steiger (FSD), rubocop, brakeman are clean.

What was not verified

Everything listed in compromise 1, plus a real end-to-end push, pull request and work-item edit with the granted permissions. Recommended before relying on this in production: one
run on a real tenant covering Contributors, the reduced set, and revoking (delete the credential, observe the failure).

Review pointers

  • db/schema.rb was edited by hand to the three intended changes (a dev-database dump reordered unrelated columns).
  • app/frontend/shared/routes.ts was regenerated and trimmed of dev-only letter_opener routes.
  • Start with FederatedOnboarding, AppTokenService and PermissionCheck; the rest is mostly plumbing.

Follow-ups

  • Live run on a real tenant (see above).
  • KMS-held signing key behind the same issuer.
  • Publishing the issuer documents on a static host for deployments behind a VPN.
  • Decide whether to retire the administrator PAT path after a successful live run.
  • Customer confirmation of Contributors vs. the reduced set (default stays Contributors).

Checklist

  • Tests added for new behaviour
  • CHANGELOG entry (Integrations)
  • Docs: user guide, design doc §15, operator runbook, configuration reference
  • rubocop, brakeman, eslint, tsc, steiger, Rails suite, Vitest
  • Verified against a live Azure DevOps organization and Entra tenant

@artempartos artempartos 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.

Reviewed the whole diff. The design matches what we agreed: Flow as the issuer, a per-company subject from an immutable public_id, a PEM signing key, Contributors plus a reduced set, and a permission check that evaluates effective permissions by action name instead of inferring them from group membership. The description is unusually candid about what was not verified, which made this much easier to review. Thanks.

Blocking

  1. CI has never run on this PR. Only cla has reported. The branch is 89 commits behind develop, and the conflicts are trivial (CHANGELOG.md, db/schema.rb, docs/index.md). Please rebase so the suite runs.
  2. Shared-app onboarding can overwrite a federated installation. See the inline comment on azure_devops_installation.rb; the line itself is onboarding.rb:190.
  3. No live run yet. We are configuring staging for one. Before merge, it should cover Contributors, the reduced set, and revocation (delete the credential and watch the failure).

Should fix
4. A signing key with literal \n escapes silently turns the feature off. See federation_config.rb.
5. FederatedOnboarding#complete! keeps a DB transaction open across every Azure call. See inline.

To check in the live run
6. The reduced set adds the service principal with no project entitlement and only direct ACEs. See setup_script.rb.
7. PermissionCheck fails open on required Repos checks. See inline.

Operator note: when enabling this on a deployment, set AZURE_DEVOPS_FEDERATION_ISSUER_URL explicitly instead of relying on the DOMAIN default. Once customers have pinned the issuer, the default would silently follow any later change of DOMAIN. Worth a line in the runbook.

def azure_identity_is_immutable
%w[company_id tenant_id client_id organization_slug].each do |attr|
immutable = %w[company_id tenant_id organization_slug credential_kind]
immutable << "client_id" unless federated?

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.

Bug (blocking), through this exception. It is triggered from Onboarding#build_installation (onboarding.rb:190, which this PR does not change, so I can't comment there).

If this company's installation for the organization is already federated, that line reassigns client_id to the shared app and sets app_config_key, while credential_kind stays federated.

This exception allows a client_id change on a federated row, so save! succeeds. Every later token request then runs the federated exchange with Aixle's multi-tenant app as the client, and that app has no federated credential for our issuer. The result:

  • every connection the company has on that organization breaks;
  • entitle! also adds the shared app's service principal to the organization.

Repro: connect an organization through Your own Entra app. Then, from another project, choose Aixle's Microsoft app, sign in as an administrator and add a project that is not approved yet. That goes complete! → build_installation.

FederatedOnboarding#bind already refuses the opposite direction. This needs the mirror check before OwnershipProof runs, for example raise ValidationFailed, ... if existing_installation(tenant)&.federated?, plus a test like the one for the opposite case.

def parse_signing_key(pem)
key = OpenSSL::PKey::RSA.new(pem)
key.private? && key.n.num_bits >= MIN_KEY_BITS ? key : nil
rescue OpenSSL::PKey::RSAError

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.

A key that is set but does not parse looks exactly like no key at all:

  • enabled? returns false;
  • both .well-known endpoints return 404;
  • the option disappears from the dialog;
  • nothing is logged.

The likeliest way to get there is pasting the PEM with literal \n escapes, which is common for single-line env values and secret stores. .to_json in settings.yml keeps the backslashes, and OpenSSL::PKey::RSA.new then fails.

Suggest both:

  • normalize a literal \n to a newline before parsing;
  • log a warning once when signing_key is present but unusable (not RSA, under 2048 bits, or unparseable), so an operator can see why the feature is off.


tenant = TenantDiscovery.call(organization)

AzureDevopsInstallation.transaction do

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.

This transaction stays open across the token exchange, the project listing and the whole PermissionCheck. That is about nine GETs per chosen project plus the namespace lookups, each with a 30 s read timeout. When Azure is slow, the DB connection and the lock on the installation row are held for all of it.

inspect! already shows the read-only part can run on a static client. Suggest this order instead:

  1. Exchange the token.
  2. List the visible projects and run the permission check.
  3. Open a short transaction only for bind, assign and save!.

The guarantee stays the same, since nothing is written until every check has passed.

CUSTOM_BODY = <<~"BASH"
#{COMMON}
# Basic access only; everything else is granted below, project by project, and nothing more.
add_to_organization '[]'

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.

For the live run: with projectEntitlements: [], the service principal is not a member of any project, and everything else is direct ACEs, including GENERIC_READ on the project.

Whether an identity that is not a project member can list the project, clone and open pull requests with ACEs alone is exactly the unverified part. Please run the reduced set as its own case, separate from Contributors.


answer = @client.get("_apis", "permissions", check.namespace, bit, params: { tokens: token })
value = Array(answer["value"])
return :unknown unless value.size == 1 && [ true, false ].include?(value.first)

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.

Failing open is a reasonable call while the response shapes are unverified, and the dialog does show "could not be checked".

Once the live run confirms the _apis/permissions and _apis/securitynamespaces shapes, consider treating unknown on a required Repos check as blocking, or at least as a warning. Today a connection that will fail on its first push can go through looking almost clean.

Evgeniy-DB and others added 5 commits October 28, 2026 09:35
Add a third way to connect Azure DevOps, next to Sign in with Microsoft and
the administrator PAT. The customer registers a single-tenant app in their
own Entra directory and adds a federated credential that trusts this
deployment as an OIDC issuer. Flow signs a short-lived JWT, Entra exchanges
it for a token of the customer's app, and the existing service-principal
path takes over. No secret, certificate or PAT is stored, and no
administrator credential reaches Aixle.

- publish /.well-known/openid-configuration and jwks.json, enabled when
  AZURE_DEVOPS_FEDERATION_SIGNING_KEY is set
- subject is aixle:company:<companies.public_id>, a new immutable uuid
- installations gain credential_kind; a federated one may move to a
  recreated app only together with re-verification
- FederatedOnboarding binds in one transaction; the token exchange is the
  proof of ownership
- PermissionCheck asks Azure what the identity can do; a missing Repos
  permission blocks, anything it cannot determine does not
- generated setup script for the Project Collection Administrator
- "Your own Entra app" option in the connect dialog

Not run against a live Azure DevOps or Entra: every request is covered by
WebMock stubs written from Microsoft's documentation. The known compromises
are recorded in docs/design/azure-devops-integration.md, section 15.4.

Signed-off-by: Evgeniy Yagnenkov <[email protected]>
…ions

Binding the shared app onto a federated row passed validation, because a
federated row may change its client id, and left it federated with the
shared app's client id. Every later token exchange then failed for every
connection on that organization.

Signed-off-by: Evgeniy Yagnenkov <[email protected]>
Co-authored-by: Cursor <[email protected]>
…log why it is ignored

A key that is set but unusable looked the same as no key: the option
disappeared with nothing in the log.

Signed-off-by: Evgeniy Yagnenkov <[email protected]>
Co-authored-by: Cursor <[email protected]>
…g transaction

The transaction used to stay open across the token exchange and every
permission request, holding a connection and the installation row for as
long as Azure took to answer.

Signed-off-by: Evgeniy Yagnenkov <[email protected]>
Co-authored-by: Cursor <[email protected]>
…bling it

Signed-off-by: Evgeniy Yagnenkov <[email protected]>
Co-authored-by: Cursor <[email protected]>
@Evgeniy-DB
Evgeniy-DB force-pushed the feature/172-add-azure-entra-app-integration branch from 274db27 to 901bea1 Compare October 28, 2026 09:00
alex-astafyev added a commit that referenced this pull request Nov 3, 2026
)

The previous staging merge resolved develop against the stale copies of
branches already squashed into develop, and lost Azure Entra's schema
column and its unsaved-changes wiring in the process. This commit's tree
is develop with the Azure Entra branch and feat/billing-page-redesign
merged on top, conflicts resolved by hand, nothing else.

Signed-off-by: Alex Astafyev <[email protected]>
aixle-com Bot pushed a commit that referenced this pull request Nov 11, 2026
Conflicts were between staging's feature-branch merges of #677, #684 and an
earlier head of #689 and develop's squash-merges of #677/#684 (plus #700,
#704). Each hunk takes develop's side (the final, reviewed version), except
config/settings.yml, which keeps the runners.release block of #689, and
CHANGELOG.md, which keeps both sides' entries. Staging-only content (#494)
merged without conflict and is kept.
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.

2 participants