-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added terraform scripts for provisioning an app service plan containi…
…ng an Azure Web App. Implemented our server API, which is deployed to Azure Web Apps on push to main via a GitHub Actions Workflow script generated by Azure.
- Loading branch information
1 parent
760e40b
commit efdd681
Showing
82 changed files
with
1,400 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy | ||
# More GitHub Actions for Azure: https://github.com/Azure/actions | ||
# More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions | ||
|
||
name: Build and deploy Python app to Azure Web App - hvalfangstlinuxwebapp | ||
|
||
on: | ||
push: | ||
branches: | ||
- main | ||
workflow_dispatch: | ||
|
||
jobs: | ||
build: | ||
runs-on: ubuntu-latest | ||
|
||
steps: | ||
- uses: actions/checkout@v4 | ||
|
||
- name: Set up Python version | ||
uses: actions/setup-python@v5 | ||
with: | ||
python-version: '3.10' | ||
|
||
- name: Create and start virtual environment | ||
run: | | ||
python -m venv venv | ||
source venv/bin/activate | ||
- name: Install dependencies | ||
run: pip install -r server/requirements.txt | ||
|
||
# Optional: Add step to run tests here (PyTest, Django test suites, etc.) | ||
|
||
- name: Zip artifact for deployment | ||
run: cd server && zip -r ../release.zip ./* | ||
|
||
- name: Upload artifact for deployment jobs | ||
uses: actions/upload-artifact@v4 | ||
with: | ||
name: python-app | ||
path: | | ||
release.zip | ||
!venv/ | ||
deploy: | ||
runs-on: ubuntu-latest | ||
needs: build | ||
environment: | ||
name: 'Production' | ||
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} | ||
permissions: | ||
id-token: write #This is required for requesting the JWT | ||
env: | ||
HVALFANGST_TENANT_ID: ${{ secrets.HVALFANGST_TENANT_ID }} | ||
HVALFANGST_API_SERVER_CLIENT_ID: ${{ secrets.HVALFANGST_API_SERVER_CLIENT_ID }} | ||
|
||
steps: | ||
- name: Download artifact from build job | ||
uses: actions/download-artifact@v4 | ||
with: | ||
name: python-app | ||
|
||
- name: Unzip artifact for deployment | ||
run: unzip release.zip -d . | ||
|
||
- name: Login to Azure | ||
uses: azure/login@v2 | ||
with: | ||
client-id: ${{ secrets.AZUREAPPSERVICE_CLIENTID_40531D048E714BC9BF1FF2DB2DD35753 }} | ||
tenant-id: ${{ secrets.AZUREAPPSERVICE_TENANTID_336AC753681745D78B7B262945914F63 }} | ||
subscription-id: ${{ secrets.AZUREAPPSERVICE_SUBSCRIPTIONID_97162121CF214550B81AF6E0B11ADA2C }} | ||
|
||
- name: Check and set environment variables on Azure App Service if not already set | ||
run: | | ||
# Check for HVALFANGST_TENANT_ID and set it if missing | ||
existing_tenant_id=$(az webapp config appsettings list --name hvalfangstlinuxwebapp \ | ||
--resource-group hvalfangstresourcegroup \ | ||
--query "[?name=='HVALFANGST_TENANT_ID'].value" \ | ||
--output tsv) | ||
if [ -z "$existing_tenant_id" ]; then | ||
echo "Setting HVALFANGST_TENANT_ID..." | ||
az webapp config appsettings set --name hvalfangstlinuxwebapp \ | ||
--resource-group hvalfangstresourcegroup \ | ||
--settings HVALFANGST_TENANT_ID=${{ secrets.HVALFANGST_TENANT_ID }} | ||
else | ||
echo "HVALFANGST_TENANT_ID is already set." | ||
fi | ||
# Check for HVALFANGST_API_SERVER_CLIENT_ID and set it if missing | ||
existing_client_id=$(az webapp config appsettings list --name hvalfangstlinuxwebapp \ | ||
--resource-group hvalfangstresourcegroup \ | ||
--query "[?name=='HVALFANGST_API_SERVER_CLIENT_ID'].value" \ | ||
--output tsv) | ||
if [ -z "$existing_client_id" ]; then | ||
echo "Setting HVALFANGST_API_SERVER_CLIENT_ID..." | ||
az webapp config appsettings set --name hvalfangstlinuxwebapp \ | ||
--resource-group hvalfangstresourcegroup \ | ||
--settings HVALFANGST_API_SERVER_CLIENT_ID=${{ secrets.HVALFANGST_API_SERVER_CLIENT_ID }} | ||
else | ||
echo "HVALFANGST_API_SERVER_CLIENT_ID is already set." | ||
fi | ||
|
||
- name: 'Deploy to Azure Web App' | ||
uses: azure/webapps-deploy@v3 | ||
id: deploy-to-webapp | ||
with: | ||
app-name: 'hvalfangstlinuxwebapp' | ||
slot-name: 'Production' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
/.env_oauth | ||
/infra/terraform.tfvars | ||
/.idea/.gitignore | ||
/infra/.terraform.lock.hcl | ||
/.idea/azure-oauth2-auth-code-flow-fastapi.iml | ||
/.idea/azure-oauth2-auth-code-flow-fastapi2.iml | ||
/.idea/codeStyles/codeStyleConfig.xml | ||
/infra/.terraform/providers/registry.terraform.io/hashicorp/azurerm/4.4.0/windows_amd64/LICENSE.txt | ||
/.idea/misc.xml | ||
/.idea/modules.xml | ||
/.idea/codeStyles/Project.xml | ||
/pu.xml | ||
/infra/terraform.tfstate | ||
/infra/terraform.tfstate.backup | ||
/infra/.terraform/providers/registry.terraform.io/hashicorp/azurerm/4.4.0/windows_amd64/terraform-provider-azurerm_v4.4.0_x5.exe | ||
/.idea/vcs.xml |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,116 @@ | ||
# oauth | ||
# Azure OAuth2 OIDC Auth Code Flow demonstration | ||
|
||
The goal of this repository is to demonstrate how to incorporate [OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc6749) on Azure **WITHOUT** the use of [MSAL](https://learn.microsoft.com/en-us/entra/identity-platform/msal-overview) for educational purposes. | ||
In a production environment one should **ALWAYS** use MSAL or similar battle-tested libraries, but it is vital for any engineer to understand what is going on under the hood instead of just blindly calling a library which | ||
automagically solves all your needs. | ||
|
||
The repo contains code for both the client and the server. The client is utilizing [OpenID Connect (OIDC)](https://auth0.com/docs/authenticate/protocols/openid-connect-protocol) with | ||
Auth code flow. A comprehensive step-by-step guide is included on how to register the client and server on Azure Entra ID. | ||
|
||
## Requirements | ||
|
||
- **Platform**: x86-64, Linux/WSL | ||
- **Programming Language**: [Python 3](https://www.python.org/downloads/) | ||
- **Azure Account**: Access to [Azure Subscription](https://azure.microsoft.com/en-us/pricing/purchase-options/azure-account) | ||
- **IAC Tool**: [Terraform](https://www.terraform.io/) | ||
|
||
|
||
## Allocate resources | ||
|
||
The script [up](up.sh) provisions Azure resources by applying our [Terraform script](infra/terraform.tf). | ||
|
||
It is necessary to create a file named **terraform.tfvars** in the [infra](infra) directory. This file holds sensitive information | ||
necessary for terraform to be able to interact with your cloud resources, namely that of your tenant and subscription id. | ||
An exemption for this file has been added in our [.gitignore](.gitignore) so that you do not accidentally commit it. | ||
|
||
The file structure is as follows: | ||
|
||
![screenshot](images/terraform_tfvars.png) | ||
|
||
|
||
## Set up CI/CD via Deployment Center | ||
|
||
Now that we have our new Web App resource up and running on Azure, we may proceed to set up our means of deploying our code to the | ||
aforementioned Web App. We will do so by connecting our Web App to our GitHub repository. Azure Web Apps has the ability | ||
to create a fully fledged CI/CD pipeline in the form of a GitHub Action Workflows script, which it commits on our behalf. As part of this pipeline a managed identify | ||
will be created in Azure in order to authenticate requests. Secrets will be automatically created and referenced in the CI/CD script by Azure. | ||
|
||
Click on the **Deployment Center** section under the **Deployment** blade. Choose GitHub as source and set the appropriate organization, repository and branch. | ||
For authentication keep it as is (user-assigned identity). Click on the **Save** button in the top left corner. | ||
|
||
![screenshot](images/deployment_center.png) | ||
|
||
After the changes have persisted, navigate to your GitHub repository. A new commit which contains the CI/CD workflows file should be present. As mentioned earlier, | ||
this has been committed by Azure on our behalf. | ||
|
||
![screenshot](images/github_workflow_commit.png) | ||
|
||
Navigate to the bottom of the workflow file. Take notice of the three secrets being referenced. | ||
|
||
![screenshot](images/github_workflow_secrets.png) | ||
|
||
If you navigate to your secrets and variables associated with your GitHub Actions you will see that there are three new secrets, the same referenced above. Again, | ||
these have been set by Azure on your behalf in order to set up authentication with our managed identity which was created as part of the Deployment Center rollout. | ||
|
||
For the CI/CD workflow script to actually work, we have to make some adjustments. Remember, this repo contains code for both the client and server - | ||
which are located in their own directories. The autogenerated script assumes that the files are located in the root folder, which is not the case here. | ||
Thus, we need to change the script to reference files located under the server directory, as we are to deploy our server. | ||
|
||
The final pipeline definition should look like [this](.github/workflows/main_hvalfangstlinuxwebapp.yml). | ||
|
||
## Deploy API | ||
|
||
In order to deploy our code to our Azure Web App slot, we need to trigger the newly registered GitHub Actions Workflow manually. Head over to the **Actions** section of your repository. Click on the **Run workflow** button located in the right corner. | ||
|
||
![screenshot](images/github_actions.png) | ||
|
||
Running said action should result in the following: | ||
|
||
![screenshot](images/github_actions_dispatched_task.png) | ||
|
||
Navigate to the **Deployment Center** section of your Azure Web App. A new deployment will be visible. Commit author and message will be equal to that of GitHub. | ||
|
||
![screenshot](images/deployment_center_post_action.png) | ||
|
||
Now that we know that it deployed successfully it is finally time to access the API. Click on URI associated with **Default Domain** | ||
|
||
![screenshot](images/overview_default_domain.png) | ||
|
||
You will be prompted with the following default page, which indicates that the API is up and running. | ||
|
||
![screenshot](images/firefox_api_home.png) | ||
|
||
|
||
## Register API on Azure AD | ||
|
||
Now that we have deployed our API to Azure Web Apps, we need to register it on Microsoft Entra ID. | ||
|
||
### Create a new app registration | ||
|
||
Navigate to the **App registrations** blade and click on **New registration** button in the top left tab | ||
|
||
![screenshot](images/azuread_app_registrations.png) | ||
|
||
![screenshot](images/azure_entra_id_register_hvalfangst_server_api.png) | ||
|
||
![screenshot](images/hvalfangst_server_api_app_registration.png) | ||
|
||
|
||
### Expose API | ||
|
||
|
||
![screenshot](images/hvalfangst_server_api_expose_api.png) | ||
|
||
|
||
![screenshot](images/hvalfangst_server_api_add_scope.png) | ||
|
||
![screenshot](images/hvalfangst_server_api_all_scopes.png) | ||
|
||
|
||
|
||
|
||
|
||
## Running API | ||
```bash | ||
python -m uvicorn app.main:app --reload | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# client/__init__.py |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# client/config/__init__.py | ||
|
||
from .oauth import oauth_settings | ||
|
||
__all__ = ["oauth_settings"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
# client/config/oauth.py | ||
|
||
from dotenv import load_dotenv | ||
from fastapi import HTTPException | ||
from pydantic_settings import BaseSettings | ||
from client import logger | ||
|
||
load_dotenv() | ||
|
||
class OAuthSettings(BaseSettings): | ||
AZURE_CLIENT_ID: str | ||
AZURE_CLIENT_SECRET: str | ||
AZURE_TENANT_ID: str | ||
API_SCOPE: str | ||
REDIRECT_URI: str | ||
|
||
class Config: | ||
env_file = ".env_oauth" | ||
|
||
|
||
def initialize_oauth_settings(): | ||
try: | ||
# Create an instance of OAuthSettings | ||
internal_oauth_settings = OAuthSettings() | ||
|
||
# Check if the required OAuth fields are set | ||
if not internal_oauth_settings.AZURE_CLIENT_ID or not internal_oauth_settings.AZURE_CLIENT_SECRET or not internal_oauth_settings.AZURE_TENANT_ID or not internal_oauth_settings.API_SCOPE: | ||
logger.logger.error("One or more required OAuth environment variables are missing.") | ||
raise HTTPException(status_code=500, | ||
detail="Configuration error: Required OAuth environment variables are missing.") | ||
|
||
logger.logger.info("OAuth settings loaded successfully.") | ||
return internal_oauth_settings | ||
except FileNotFoundError: | ||
logger.logger.critical(".env file not found.") | ||
raise HTTPException(status_code=500, detail="Configuration error: .env file not found.") | ||
except Exception as e: | ||
logger.logger.critical(f"Error loading OAuth settings: {e}") | ||
raise HTTPException(status_code=500, | ||
detail="Configuration error: An error occurred while loading OAuth settings.") | ||
|
||
|
||
# Initialize OAuth settings | ||
oauth_settings = initialize_oauth_settings() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
# client/logger.py | ||
|
||
import logging | ||
|
||
# Configure logging | ||
logging.basicConfig( | ||
level=logging.INFO, | ||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | ||
) | ||
|
||
# Create a logger object that can be imported across the application | ||
logger = logging.getLogger(__name__) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# client/main.py | ||
|
||
from fastapi import FastAPI | ||
from client.routers import auth, heroes | ||
|
||
app = FastAPI( | ||
title="Hero API", | ||
description="An API to manage heroes secure by OAuth 2.0 auth code flow", | ||
version="1.0.0" | ||
) | ||
|
||
# Register the oauth and heroes router | ||
app.include_router(auth.router, prefix="/auth", tags=["OAuth2 Back-channel"]) | ||
app.include_router(heroes.router, prefix="/api", tags=["Heroes"]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# client/models/__init__.py | ||
|
||
from .dnd_hero import DnDHero, AbilityScores, SkillProficiencies, Equipment, Spell | ||
|
||
__all__ = ["DnDHero", "AbilityScores", "SkillProficiencies", "Equipment", "Spell"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
# client/models/ability_scores.py | ||
|
||
from pydantic import BaseModel | ||
|
||
|
||
class AbilityScores(BaseModel): | ||
strength: int | ||
dexterity: int | ||
constitution: int | ||
intelligence: int | ||
wisdom: int | ||
charisma: int |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# client/models/dnd_hero.py | ||
|
||
from pydantic import BaseModel | ||
from typing import List, Optional | ||
from client.models.ability_scores import AbilityScores | ||
from client.models.equipment import Equipment | ||
from client.models.skill_proficiencies import SkillProficiencies | ||
from client.models.spell import Spell | ||
|
||
|
||
class DnDHero(BaseModel): | ||
id: str | ||
name: str | ||
race: str | ||
class_: str # Avoids conflict with the Python `class` keyword | ||
level: int | ||
background: Optional[str] = None | ||
alignment: Optional[str] = None | ||
|
||
# Nested fields | ||
ability_scores: AbilityScores | ||
skill_proficiencies: SkillProficiencies | ||
equipment: Equipment | ||
spells: Optional[List[Spell]] = None # Optional, only for spellcasters | ||
|
||
hit_points: int | ||
armor_class: int | ||
speed: int | ||
|
||
# Additional optional features | ||
personality_traits: Optional[str] = None | ||
ideals: Optional[str] = None | ||
bonds: Optional[str] = None | ||
flaws: Optional[str] = None |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# client/models/equipment.py | ||
|
||
from typing import Optional, List | ||
from pydantic import BaseModel | ||
|
||
|
||
class Equipment(BaseModel): | ||
weapon: Optional[str] = None | ||
armor: Optional[str] = None | ||
items: List[str] = [] |
Oops, something went wrong.