From 076d24d5c680a4fd29ddf8db16ec9e6984f08911 Mon Sep 17 00:00:00 2001 From: Colby Williams Date: Mon, 18 Nov 2024 12:50:10 -0600 Subject: [PATCH] oidc --- .github/CODEOWNERS | 3 + .github/workflows/connect.yml | 176 ++++++++++++++ .gitignore | 432 ++++++++++++++++++++++++++++++++++ .vscode/settings.json | 6 + sample_deploy.yml | 26 ++ 5 files changed, 643 insertions(+) create mode 100644 .github/CODEOWNERS create mode 100644 .github/workflows/connect.yml create mode 100644 .gitignore create mode 100644 .vscode/settings.json create mode 100644 sample_deploy.yml diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..eb2a5c6 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,3 @@ +* @colbylwilliams + +/.github/ @colbylwilliams \ No newline at end of file diff --git a/.github/workflows/connect.yml b/.github/workflows/connect.yml new file mode 100644 index 0000000..70972c5 --- /dev/null +++ b/.github/workflows/connect.yml @@ -0,0 +1,176 @@ +name: Connect OIDC + +permissions: + id-token: write + contents: read + +on: + workflow_dispatch: + inputs: + _entity_repository_metadata_Name: + description: Select a repository + required: true + type: string + _entity_environment_spec_Subscription: + description: The Azure subscription id (guid) where the resource group exists + required: true + type: string + _entity_environment_spec_ResourceGroup: + description: The name of an existing resource group + required: true + type: string + +run-name: "Configure '${{ inputs._entity_repository_metadata_Name }}' to deploy to '${{ inputs._entity_environment_spec_ResourceGroup }}'" + +env: + # this will be used as the description for the template entity in the dev platform + description: This template enables a repository's workflows to deploy to Azure. It first generates a new deployment identity, grants it the necessary permissions to deploy to a specified resource group, then configures repository to authenticate using OpenID Connect (OIDC). Finally, a sample workflow is added to the repository to demonstrate how to use the new identity. + + OIDC_REPOSITORY: ${{ github.repository_owner }}/${{ inputs._entity_repository_metadata_Name }} + OIDC_REPOSITORY_URL: ${{ github.server_url }}/${{ github.repository_owner }}/${{ inputs._entity_repository_metadata_Name }} + + AZURE_RBAC_ROLE: Contributor + AZURE_RESOURCE_GROUP_ID: /subscriptions/${{ inputs._entity_environment_spec_Subscription }}/resourceGroups/${{ inputs._entity_environment_spec_ResourceGroup }} + AZURE_RESOURCE_GROUP_URL: https://portal.azure.com/#@${{ vars.AZURE_TENANT_ID }}/resource/subscriptions/${{ inputs._entity_environment_spec_Subscription }}/resourceGroups/${{ inputs._entity_environment_spec_ResourceGroup }}/overview + +jobs: + print: + name: OIDC Connection Request + runs-on: ubuntu-latest + + steps: + - run: | + echo "### @${{ github.triggering_actor }} would like to connect repository [${{inputs._entity_repository_metadata_Name}}](${{ env.OIDC_REPOSITORY_URL }}) to Azure resource group [${{ inputs._entity_environment_spec_ResourceGroup }}](${{ env.AZURE_RESOURCE_GROUP_URL }})" >> $GITHUB_STEP_SUMMARY + echo "Triggered by: @${{ github.triggering_actor }}" >> $GITHUB_STEP_SUMMARY + + connect: + name: OIDC Connection + runs-on: ubuntu-latest + environment: default + + steps: + - name: Az CLI login + uses: azure/login@v2 + with: + client-id: ${{ vars.AZURE_CLIENT_ID }} + tenant-id: ${{ vars.AZURE_TENANT_ID }} + allow-no-subscriptions: true + + - name: Validate Resource Group + run: | + set +e + rg_output=$( az group show --subscription "${{ inputs._entity_environment_spec_Subscription }}" --name "${{ inputs._entity_environment_spec_ResourceGroup }}" 2>&1 ) + rg_output_status=$? + + if [ $rg_output_status -ne 0 ]; then + while IFS= read -r line ; do echo "::error::$line"; done <<< "$rg_output" + exit $rg_output_status + fi + + - name: Validate Repository + env: + GITHUB_TOKEN: ${{ secrets.ORG_GITHUB_TOKEN }} + run: | + set +e + repo_output=$( gh repo view "${{ env.OIDC_REPOSITORY }}" --json id,url 2>&1 ) + repo_output_status=$? + + if [ $repo_output_status -ne 0 ]; then + while IFS= read -r line ; do echo "::error::$line"; done <<< "$repo_output" + exit $repo_output_status + fi + + set -e + repo_secrets=$( gh secret list -R "${{ env.OIDC_REPOSITORY }}" ) + repo_variables=$( gh variable list -R "${{ env.OIDC_REPOSITORY }}" ) + + for VARIABLE in "AZURE_TENANT_ID" "AZURE_CLIENT_ID" + do + if [[ $repo_variables == *"$VARIABLE"* ]]; then + echo "::error::Repository already contains variable '$VARIABLE'."; exit 1 + fi + + if [[ $repo_secrets == *"$VARIABLE"* ]]; then + echo "::error::Repository already contains secret '$VARIABLE'."; exit 1 + fi + done + + - name: Create Azure AD Application + id: application + run: | + application_name="Dev Platform OIDC ${{ inputs._entity_repository_metadata_Name }}" + + application=$(az ad app create --display-name "$application_name") + + application_object_id=$(jq -r '.id' <<< "$application") + application_client_id=$(jq -r '.appId' <<< "$application") + + echo "name=$application_name" >> $GITHUB_OUTPUT + echo "id=$application_object_id" >> $GITHUB_OUTPUT + echo "appId=$application_client_id" >> $GITHUB_OUTPUT + + - name: Create Service Principal + id: principal + run: | + service_principal=$(az ad sp create --id "${{ steps.application.outputs.id }}") + service_principal_object_id=$(jq -r '.id' <<< "$service_principal") + + echo "id=$service_principal_object_id" >> $GITHUB_OUTPUT + + - name: Create OIDC Creds + run: | + credentials_name="DevPlatformOIDC-${{ inputs._entity_repository_metadata_Name }}" + + az rest --method POST \ + --uri "https://graph.microsoft.com/beta/applications/${{ steps.application.outputs.id }}/federatedIdentityCredentials" \ + --body '{"name":"'$credentials_name'","issuer":"https://token.actions.githubusercontent.com","subject":"repo:'"${{ env.OIDC_REPOSITORY }}:ref:refs/heads/main"'","description":"'"${{ steps.application.outputs.name }}"'","audiences":["api://AzureADTokenExchange"]}' + + - name: Add Role Assignment + run: | + az role assignment create \ + --scope ${{ env.AZURE_RESOURCE_GROUP_ID }} \ + --role ${{ env.AZURE_RBAC_ROLE }} \ + --assignee-object-id ${{ steps.principal.outputs.id }} \ + --assignee-principal-type ServicePrincipal + + - name: Set Repository Variables + env: + GITHUB_TOKEN: ${{ secrets.ORG_GITHUB_TOKEN }} + run: | + gh variable set AZURE_TENANT_ID -R "${{ env.OIDC_REPOSITORY }}" --body "${{ vars.AZURE_TENANT_ID }}" + gh variable set AZURE_CLIENT_ID -R "${{ env.OIDC_REPOSITORY }}" --body "${{ steps.application.outputs.appId }}" + gh variable set AZURE_SUBSCRIPTION_ID -R "${{ env.OIDC_REPOSITORY }}" --body "${{ inputs._entity_environment_spec_Subscription }}" + gh variable set AZURE_RESOURCE_GROUP_NAME -R "${{ env.OIDC_REPOSITORY }}" --body "${{ inputs._entity_environment_spec_ResourceGroup }}" + + - uses: actions/checkout@v4 + with: + path: main + + - uses: actions/checkout@v4 + with: + path: oidc + repository: ${{ env.OIDC_REPOSITORY }} + token: ${{ secrets.ORG_GITHUB_TOKEN }} + + - name: Copy Sample Workflow + run: | + mkdir -p oidc/.github/workflows + cp main/sample_deploy.yml oidc/.github/workflows/sample_deploy.yml + + - name: Commit and Push + working-directory: oidc + run: | + git add .github/workflows/sample_deploy.yml + git config --global user.name "${{ github.actor }}" + git config --global user.email "${{ github.actor }}@users.noreply.github.com" + git commit -am "Add sample workflow using OIDC" + git push + + - name: Write Summary + run: | + echo "#### Successfully connected repository [${{ env.OIDC_REPOSITORY }}](${{ env.OIDC_REPOSITORY_URL }}) to Azure resource group [${{ inputs._entity_environment_spec_ResourceGroup }}](${{ env.AZURE_RESOURCE_GROUP_URL }})" >> $GITHUB_STEP_SUMMARY + echo "To use..." >> $GITHUB_STEP_SUMMARY + + - name: Done + run: | + echo done. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c0a80a8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,432 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +!/src/Microsoft.Developer.Azure/Arm +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +*.code-workspace +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!developer-platform-pr.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +.DS_Store + +.local +docs/.local + +secrets.* + +test.*.bicepparam + +# appsettings.Development.json +*.json.zip + +local.settings.json + +# .env.development + +sdks/** +schemas/** + +# deploy/** +**/*.pem + +/deploy/**/params +/deploy/**/testparams +/deploy/**/portal +/deploy/local + +local.bicep +all.bicep + +**/home \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..c7c720e --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "cSpell.words": [ + "Creds", + "noreply" + ] +} \ No newline at end of file diff --git a/sample_deploy.yml b/sample_deploy.yml new file mode 100644 index 0000000..ec9afb0 --- /dev/null +++ b/sample_deploy.yml @@ -0,0 +1,26 @@ +name: Sample Deploy + +permissions: + id-token: write + contents: read + +on: + push: + branches: + - main + +jobs: + deploy: + runs-on: ubuntu-latest + + steps: + - name: Az CLI login + uses: azure/login@v1 + with: + client-id: ${{ vars.AZURE_CLIENT_ID }} + tenant-id: ${{ vars.AZURE_TENANT_ID }} + subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} + + - name: Show Resource Group + run: | + az group show --subscription ${{ vars.AZURE_SUBSCRIPTION_ID }} --name ${{ vars.AZURE_RESOURCE_GROUP_NAME }}