📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you handle secrets in CI/CD pipelines? Explain OIDC workload identity federation, Key Vault references and Key Vault-linked variables, least-privilege service connections, and what you do when a secret leaks in a pipeline log.

Pipeline secret management for .NET on Azure: OIDC and workload identity federation instead of stored credentials, managed identity at run time, Key Vault references, least-privilege identities, secret scanning and leak response.

Senior Theory Advanced azure-key-vault ci-cd devops least-privilege oidc secrets-management

🎯 Key points

  • Remove secrets rather than protect them: OIDC / workload identity federation for the pipeline, managed identity for the app
  • Pipeline deploys code and a Key Vault reference; the app's managed identity reads the secret value at run time
  • Key Vault with Azure RBAC (Key Vault Secrets User per app), soft delete, purge protection and diagnostic logs audited regularly
  • One identity per environment, roles scoped to a resource group, protected by environment approvals and branch rules
  • Masking is a safety net, not a control: transformed or partial secrets are not masked
  • Automated detection: GitHub secret scanning with push protection (also GitHub Advanced Security for Azure DevOps), gitleaks pre-commit
  • Leak response: revoke and rotate first, then purge logs, then check access logs; assess under the NDB scheme if personal data was exposed
  • Periodic review of role assignments and stored secrets, driving the count towards zero

⏱ 30-second answer

My rule is to remove secrets rather than protect them. The pipeline authenticates to Azure with OIDC / workload identity federation: the CI platform issues a short-lived token that Entra trusts, so no client secret is stored. The app authenticates to SQL, Storage and Key Vault with managed identity. Remaining secrets (third-party API keys) live in Key Vault; the pipeline deploys only a Key Vault reference such as @Microsoft.KeyVault(VaultName=...;SecretName=...) as an app setting, and the platform resolves it with the app's identity, so the value never passes through the pipeline.

Pipeline identities are least privilege: one per environment, roles on a resource group, protected by environment approvals. Secret scanning with push protection blocks committed secrets.

If a secret leaks, I revoke and rotate first, then clean logs, then check access logs. The trade-off is up-front identity setup in exchange for nothing worth stealing in the pipeline.

🗣 Full answer (senior)

How I would answer this in an interview

"I start by shrinking the problem. Most secrets in pipelines exist only because something can't use identity. So the pipeline itself logs in to Azure through OIDC: GitHub or Azure DevOps issues a short-lived token, Entra trusts it through a federated credential, and there's nothing stored to leak or rotate. The application uses managed identity for Azure SQL, Storage, Service Bus and Key Vault, so there are no connection-string passwords either. For the few real secrets left, like a payment provider API key, I put them in Key Vault and let the app fetch them at run time: an App Service or Container Apps Key Vault reference, or the Key Vault configuration provider. The pipeline deploys a reference, never the value.

Then least privilege. Each environment has its own pipeline identity with roles only on its resource group; the production one can only be used by a job targeting the protected production environment, which needs an approval and only runs from main. For example, at [company] we [found a service connection with Owner on the subscription used by 30 pipelines, replaced it with per-environment federated identities, and cut the number of identities with production write access from 30 to 4].

The mistake I see is relying on log masking. Masking only hides exact matches; if a script base64-encodes a secret, prints part of it, or a tool echoes it in a URL, it's in the log. And when a secret does leak, people delete the log and move on. The secret is compromised the moment it's printed, so the first move is always revoke and rotate, then clean up and investigate what it could access."


The hierarchy I follow

Preference Mechanism Example
1. No secret at all OIDC / workload identity federation; managed identity Pipeline → Azure; app → Azure SQL with Authentication=Active Directory Default
2. Secret only the app reads Key Vault + managed identity at run time @Microsoft.KeyVault(SecretUri=...) app setting
3. Secret the pipeline must use Key Vault-linked variable group / fetch with azure/get-keyvault-secrets or az keyvault secret show at the step that needs it Signing certificate password for a NuGet package
4. Last resort Platform secret store (GitHub environment secret, Azure DevOps secret variable) Token for a tool without identity support

Least-privilege pipeline identities

Do Don't
One identity per environment One identity for dev, test and prod
Roles on a resource group or resource Owner/Contributor on the subscription
User Access Administrator only when deploying role assignments, ideally with conditions limiting assignable roles Broad role-assignment rights
Federated credential bound to environment:production Trust bound to any branch or PRs
Approvals and branch control on the prod environment/service connection Anyone with repo write can deploy prod

When a secret leaks

  1. Revoke/rotate immediately (regenerate the key, create a new version in Key Vault, restart or let apps pick up the new version).
  2. Contain: cancel running jobs, delete the run logs or artefacts that contain it.
  3. Investigate: Entra sign-in logs, Key Vault diagnostic logs, the provider's access logs for use since the leak.
  4. Assess: if personal information could have been accessed, assess it under the Notifiable Data Breaches scheme (Privacy Act 1988).
  5. Prevent: fix the step that printed it, add push protection, and replace the secret with identity if possible.

Production example

After moving 40 pipelines from stored service principal secrets to federated identities and Key Vault references, a team removed 55 stored secrets, ended a quarterly rotation that took about two days of effort, and passed an Essential Eight assessment item on restricting administrative privileges that had previously been flagged.

🔍 What the interviewer is checking

Checks whether the candidate designs pipelines with identity instead of secrets, applies least privilege per environment, and knows how to respond to a leak.

Green flags

  • Explains OIDC / workload identity federation and the subject/condition that restricts it
  • Separates pipeline identity from app identity; app reads its own secrets
  • Knows the limits of log masking
  • Leak response starts with revoke and rotate, and mentions NDB assessment where relevant

Red flags

  • Stores client secrets or publish profiles as the normal approach
  • Uses one powerful identity for all environments
  • Thinks deleting the log fixes a leak

📚 Learn in depth

1. Three identities, not one

            ┌────────────── build ──────────────┐      ┌────── deploy (prod) ───────┐
repo ───► │ OIDC → id-build (AcrPush on ACR)      │ ──► │ OIDC → id-deploy-prod          │
            └──────────────────────────────────────┘      │ (Contributor on rg-orders-prod) │
                                                         └──────────────┬────────────────┘
                                                                        │ deploys app + reference
                                                                        ▼
                                       app's managed identity ──► Key Vault (Key Vault Secrets User)
                                                             ──► Azure SQL (db user from external provider)
                                                             ──► ACR (AcrPull)

The pipeline's job is to put the right code and configuration in place; the app's identity reads the secrets. The deploy identity doesn't need Key Vault Secrets User at all.

2. Workload identity federation in both platforms

  • GitHub Actions: permissions: id-token: write, azure/login with client-id, tenant-id, subscription-id. The federated credential subject (repo:org/repo:environment:production) decides which jobs qualify.
  • Azure DevOps: Azure Resource Manager service connection of type workload identity federation. The subject identifies the organisation, project and service connection; checks on the service connection (approvals, branch control) apply before a token is issued.
  • Tokens from Entra last about an hour and are never stored.

3. Key Vault references

App Service, Functions and Container Apps can resolve a secret from Key Vault using the app's managed identity:

  • App Service: app setting value @Microsoft.KeyVault(SecretUri=https://kv-orders-prod.vault.azure.net/secrets/PaymentApiKey/). Without a version, the platform picks up new versions (refreshed periodically, within about 24 hours, or immediately on a config change/restart).
  • Container Apps: a secret with keyVaultUrl and an identity, then referenced by an environment variable secretRef.
  • In code: builder.Configuration.AddAzureKeyVault(uri, new DefaultAzureCredential()) with a ReloadInterval if you need faster rotation.

Use RBAC on Key Vault (not legacy access policies), enable soft delete and purge protection, and private endpoints for production vaults.

4. Why masking isn't enough

Platforms mask the exact string of a registered secret in logs. They don't mask:

  • transformed values (base64, URL-encoded, JSON-escaped),
  • substrings or values split across lines,
  • secrets printed by a tool you didn't register them with,
  • values written to artefacts, test results or container image layers (ARG/ENV in a Dockerfile).

So design so secrets never reach steps that might print them, and keep set -x / verbose logging off around them.

5. Preventing commits

  • GitHub secret scanning with push protection blocks pushes containing known secret patterns; Azure DevOps has the equivalent through GitHub Advanced Security for Azure DevOps.
  • Pre-commit hooks (gitleaks) catch custom patterns.
  • dotnet user-secrets locally keeps development secrets out of the repo.
  • If a secret was committed, rewriting history doesn't make it safe: forks and clones have it. Rotate.

6. Australian context

ACSC Essential Eight's "restrict administrative privileges" maps directly onto per-environment, least-privilege pipeline identities with approvals. If a leaked credential could expose personal information, the organisation must assess whether it's an eligible data breach under the NDB scheme (assessment within 30 days, notify OAIC and affected individuals if likely to cause serious harm).

Try it yourself

  1. Convert an Azure DevOps service connection from secret to workload identity federation and confirm the client secret can be deleted.
  2. Add a Key Vault reference to an App Service setting and check its status in the portal (green tick or the resolution error).
  3. In a test repo, register a secret and print its base64 form in a workflow step; see that masking doesn't hide it (then delete the run).
  4. Enable push protection and try to commit a fake Azure Storage key.
  5. List role assignments for your pipeline identities with az role assignment list --assignee <id> --all and remove anything broader than a resource group.

💻 Code

The app reads its own secrets with managed identity, so the pipeline never sees them, and it fails fast and visibly if Key Vault can't be reached (Program.cs):

using Azure;
using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;

var builder = WebApplication.CreateBuilder(args);

if (!builder.Environment.IsDevelopment())
{
    try
    {
        // Managed identity in Azure; no client secret anywhere.
        builder.Configuration.AddAzureKeyVault(
            new Uri(builder.Configuration["KeyVault:Uri"]!),
            new DefaultAzureCredential(),
            new AzureKeyVaultConfigurationOptions
            {
                // Re-reads the latest secret versions, so a rotation needs no redeploy.
                ReloadInterval = TimeSpan.FromMinutes(15)
            });
    }
    catch (Exception ex) when (ex is RequestFailedException or AuthenticationFailedException)
    {
        // 403 = missing RBAC role or firewall; auth failure = identity not assigned.
        // Log without the secret, then stop: running without secrets is worse than not starting.
        Console.Error.WriteLine($"Key Vault load failed: {ex.GetType().Name} {(ex as RequestFailedException)?.Status}");
        throw;
    }
}
// In development the same keys come from `dotnet user-secrets`.

builder.Services.AddOptions<PaymentOptions>()
    .Bind(builder.Configuration.GetSection("Payment"))   // Key Vault secret name: Payment--ApiKey
    .Validate(o => !string.IsNullOrWhiteSpace(o.ApiKey), "Payment:ApiKey is missing")
    .ValidateOnStart();                                    // also catches an unresolved Key Vault reference

var app = builder.Build();
app.MapGet("/health/live", () => Results.Ok());
app.Run();

public sealed class PaymentOptions
{
    public string ApiKey { get; set; } = "";
}

If an App Service Key Vault reference can't be resolved, the setting contains the literal @Microsoft.KeyVault(...) text, so ValidateOnStart with a format check (for example !o.ApiKey.StartsWith("@Microsoft.KeyVault")) turns a silent misconfiguration into a failed deployment that the slot swap's warm-up will catch.

The deploy step passes a reference, not the value, and the identity is federated:

  deploy-prod:
    environment: production            # approval + main-only
    runs-on: ubuntu-latest
    permissions: { id-token: write, contents: read }
    steps:
      - uses: azure/login@v2
        with:
          client-id: ${{ vars.AZURE_CLIENT_ID_PROD }}   # identifier, not a secret
          tenant-id: ${{ vars.AZURE_TENANT_ID }}
          subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
      - name: Point the app at Key Vault (value never enters the pipeline)
        run: |
          az webapp config appsettings set -g rg-orders-prod-aue -n app-orders-prod-aue --slot staging --settings \
            "[email protected](VaultName=kv-orders-prod-aue;SecretName=PaymentApiKey)"
# Least privilege: the app reads secrets; the pipeline identity gets no Key Vault data role
az role assignment create --assignee <app-managed-identity-principal-id> \
  --role "Key Vault Secrets User" \
  --scope /subscriptions/<sub>/resourceGroups/rg-orders-prod-aue/providers/Microsoft.KeyVault/vaults/kv-orders-prod-aue

# Regular audit: who can read secrets in this vault?
az role assignment list --scope <vault-resource-id> --query "[].{who:principalName, role:roleDefinitionName}" -o table

⚠ Common mistakes

  • Mistake: Storing a service principal secret for the pipeline. Why it is wrong: It's long-lived, copyable and must be rotated. Instead: Use OIDC / workload identity federation.
  • Mistake: Having the pipeline read secrets from Key Vault and write them into app settings. Why it is wrong: The values pass through the pipeline, its logs and the deployment history. Instead: Deploy Key Vault references and let the app's managed identity resolve them.
  • Mistake: One identity with subscription Contributor for every environment. Why it is wrong: A compromised dev pipeline can change production. Instead: One identity per environment with roles on its resource group.
  • Mistake: Trusting log masking. Why it is wrong: Encoded, partial or tool-echoed secrets aren't masked. Instead: Keep secrets out of steps that log, and avoid verbose shell tracing.
  • Mistake: Deleting the log and carrying on after a leak. Why it is wrong: The secret is already exposed. Instead: Revoke and rotate first, then clean up and investigate.
  • Mistake: Passing secrets as Docker build ARG or ENV. Why it is wrong: They're stored in image layers and history. Instead: Use BuildKit secret mounts at build time and runtime identity for the app.
  • Mistake: Making secrets available to pull request workflows from forks. Why it is wrong: Untrusted code can exfiltrate them. Instead: Keep secrets in protected environments that PR jobs can't use.
  • Mistake: Using Key Vault access policies with broad get/list for many principals. Why it is wrong: Hard to audit, not least privilege. Instead: Use Azure RBAC on the vault with narrow roles.

🏛 Senior insight: trade-offs

The senior move is to treat secret management as identity design. Every stored secret is a liability with a rotation cost and a leak risk, so I count them and drive the number towards zero: federated identity for pipelines, managed identity for apps, Key Vault for the remainder, read only by the workload that needs it.

The controls belong on the identity and the environment, not in pipeline YAML that any contributor can edit. And it isn't a one-off project: I schedule a quarterly review of role assignments on vaults and resource groups (Entra access reviews or a script over az role assignment list), alert on Key Vault access from unexpected identities in Log Analytics, use Azure Policy to deny shared-key storage access and Key Vaults without purge protection, and track three numbers over time: stored secrets, identities with production write access, and time to rotate a credential end to end.

Option When it fits Cost When not to
OIDC / workload identity federation Pipeline → Azure (and AWS, GCP) One-off identity setup Never worse than a stored secret
Managed identity at run time App → Azure services Role assignments per resource Services without Entra auth
Key Vault reference Third-party keys the app needs Vault, RBAC, rotation process Values the pipeline truly needs (e.g. signing)
Platform secret store Tools with no identity option Manual rotation, leak risk Anything that supports identity

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions OIDC in GitHub Actions. Why: Checks that the candidate can write the OIDC login and environment gating in a real workflow.
    How to answer

    The workflow has a build job (restore, build, test, dotnet publish /t:PublishContainer to push an image tagged with the commit SHA to Azure Container Registry) and deploy jobs per environment that reuse that same image.

    For Azure access I use OpenID Connect: the job declares permissions: id-token: write, GitHub issues a short-lived token, and azure/login exchanges it for an Entra token through a federated credential on an app registration or user-assigned managed identity. No client secret is stored anywhere.

    Production is gated with a GitHub environment that has required reviewers, and the federated credential's subject is scoped to environment:production, so only an approved job can get production access.

    The trade-off: OIDC needs one-off Entra setup per repo and environment, but removes secret rotation and leaked-secret risk entirely.

  2. When: Candidate says the app reads secrets from Key Vault at run time. Why: Checks how the app side consumes Key Vault and App Configuration, including rotation and refresh.
    How to answer

    I'd inventory and classify every setting first: secrets, environment-specific values, shared values, and which must change live. Secrets go to Key Vault. Non-secret settings and feature flags go to Azure App Configuration with a label per environment, and secrets are referenced from there through Key Vault references. The app authenticates with its managed identity using least-privilege roles, and where possible secrets disappear entirely through passwordless Entra ID auth to SQL, Storage and Service Bus.

    For refresh, use a sentinel key with a refresh interval and a secret refresh interval, and read live values through IOptionsMonitor. Rotation uses overlapping versions, so old and new both work during the window. Add start-up timeouts and replicas, and keep ValidateOnStart.

    The trade-off: central, audited, rotatable configuration, in exchange for a network dependency at start-up that you must design for.

  3. When: Candidate talks about per-environment, least-privilege identities. Why: Checks least-privilege thinking for database migrations run by the pipeline.
    How to answer

    Database.Migrate() at start-up means the runtime identity must hold DDL rights, so any SQL injection or RCE can alter or drop schema. It also couples deployment to start-up: several scaled-out instances can try to migrate at once (EF Core 9+ takes a database lock to serialise this, but a long migration still blocks start-up and health checks), and a failed migration takes the app down with it. Instead I generate an idempotent script or a migration bundle (dotnet ef migrations bundle) in CI and run it once in the release stage under a separate migration identity with db_ddladmin, after a backup and an approval gate for production. Migrations are written to be backward compatible (expand, then contract) so the old and new app versions both work during rollout, and the runtime identity keeps only DML.

🛠 Real-world problems: how you handle them

Storage key printed in a pipeline log
Situation
An Azure DevOps release pipeline for a .NET 10 document service handling [customer identity documents] in Australia East. A debugging step added `set -x` around a script that used a storage account key from a variable group.
Signals
A developer noticed the key in plain text in a run log because the script had base64-encoded it before use, so masking didn't apply; the log was visible to [about 60] project members.
Investigation
Searched recent run logs via the Azure DevOps REST API for the key's prefix; checked Storage account diagnostic logs in Log Analytics (KQL on `StorageBlobLogs` filtered by `AuthenticationType == "AccountKey"`) for requests from unknown IPs since the run; reviewed who could view the pipeline.
Resolution
Immediate: rotated the storage account key, updated the dependent Key Vault secret, restarted the app, deleted the affected run logs. Logs showed no unknown access, documented for the privacy officer's NDB assessment. Long term: disabled shared key access on the storage account and switched the app and pipeline to managed identity and workload identity federation.
Prevention
Storage `allowSharedKeyAccess=false` enforced by Azure Policy; no secrets in variable groups for this project; secret scanning on repos; a pipeline lint rule forbidding `set -x` in steps with secret variables.

How to tell it (STAR)

**S:** A storage key for a service holding sensitive customer documents ended up readable in a pipeline log. **T:** I owned the response and needed to contain it and make sure it couldn't happen again. **A:** I rotated the key first, then deleted the logs, checked Storage diagnostics in Log Analytics for any use of the old key, and gave the privacy officer the evidence for the breach assessment; then I replaced key-based access with managed identity and a federated pipeline identity and turned shared key access off by policy. **R:** The key was rotated within [about 15 minutes], logs showed [no unauthorised access], and the account has had [no stored keys] since.

↩ Usually asked after

More in CI/CD

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me