Skip to content

Commit

Permalink
Maxion sso (#127)
Browse files Browse the repository at this point in the history
* maxion SSO enabled

* staging script update

* change conditional statement

* conditional changes

* condition fix

* change in defaults.ini

* revert defaults.ini change

* trace logs

* added secrets to workflow

* disable role reset

* Update lightsail.sh

* testing tls version

* wait for container

* fix sleep syntax

* disable org role sync

* dashboard deployment workflow

* change environment

* remove boto

* remove extra sleep

* undo env

---------

Co-authored-by: deepaksingh3 <[email protected]>
  • Loading branch information
Priyankg101 and deepaksingh3 authored Nov 8, 2023
1 parent 4007669 commit 18b0a7c
Show file tree
Hide file tree
Showing 7 changed files with 194 additions and 5 deletions.
14 changes: 14 additions & 0 deletions .github/tvarit/conf/prod/grafana.ini.template
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,20 @@ password = """<SMTP_PASSWORD/>"""
from_address = <SMTP_USER/>
from_name = <SMTP_FROM/>

#################################### Azure AD OAuth #######################
[auth.azuread]
name = Maxion Login
enabled = <AD_LOGIN_FLAG/>
;allow_sign_up = false
client_id = <MAXION_CLIENT_ID/>
client_secret = <MAXION_CLIENT_SECRET/>
scopes = openid email profile
auth_url = https://login.microsoftonline.com/58288272-c24c-4c0c-bc60-dc0cbadd0866/oauth2/v2.0/authorize
token_url = https://login.microsoftonline.com/58288272-c24c-4c0c-bc60-dc0cbadd0866/oauth2/v2.0/token
skip_org_role_sync = true
;allowed_domains =
;allowed_groups =

#################################### Unified Alerting ####################
[unified_alerting]
#Enable the Unified Alerting sub-system and interface. When enabled we'll migrate all of your alert rules and notification channels to the new system. New alert rules will be created and your notification channels will be converted into an Alertmanager configuration. Previous data is preserved to enable backwards compatibility but new data is removed.```
Expand Down
127 changes: 127 additions & 0 deletions .github/tvarit/dashboard-deployment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import requests
import json
import subprocess
def find_existing_folder(api_url, api_key, folder_name):
headers = {
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
"Content-Type": "application/json"
}

response = requests.get(f"{api_url}/folders", headers=headers)

if response.status_code == 200:
folders = response.json()
for folder in folders:
if folder.get("title") == folder_name:
return folder.get("id")

# If no matching folder is found, return None
return None
else:
print(f"Failed to fetch folders. Status Code: {response.status_code}")
return None

def replace_in_dict(obj, search, replacement):
if isinstance(obj, dict):
for key in list(obj.keys()):
obj[key] = replace_in_dict(obj[key], search, replacement)
return obj
elif isinstance(obj, list):
return [replace_in_dict(item, search, replacement) for item in obj]
elif isinstance(obj, str):
return obj.replace(search, replacement)
else:
return obj

print('Settting up variables')

maxion_grafana_url = "https://maxion.tvarit.com/api"
cloud_grafana_url = "https://cloud.tvarit.com/api"
test_grafana_url = "https://test.tvarit.com/api"
grafana_url = ""

aws_cli_command = "aws secretsmanager get-secret-value --secret-id /credentials/grafana-user/access-key --output text --query SecretString"

try:
# Run the AWS CLI command and capture its output
result = subprocess.run(aws_cli_command, shell=True, text=True, capture_output=True, check=True)
secret_json = json.loads(result.stdout)

data = secret_json
except subprocess.CalledProcessError as e:
# Handle any errors or exceptions here
print("AWS CLI command failed with error:")
print(e.stderr)

print('###################################Starting Deployment###################################')

data_test = data.get("Test", {})

for key in data_test.keys():
print('Deploying in ',key)
if key in ['Alcar', 'Gienanth', 'Procast', 'Voit', 'Doktas', 'ESW', 'Endurance', 'Foehl', 'Mahle', 'Mbusch']:
grafana_url = cloud_grafana_url
else:
grafana_url = maxion_grafana_url
org_data = data_test[key]
# org_data['api'] = {f'TEST_API_KEY_{key}'}
headers = {
"Authorization": f"Bearer {org_data['api']}"
}

data_prod = data.get("Prod", {}).get(key, {})
api = data_prod['api']
headers2 = {
"Authorization": f"Bearer {api}",
"Accept": "application/json",
"Content-Type": "application/json",
}
for folder in ['Production Dashboards PsQ', 'Production Dashboards PsE']:
source_folder = find_existing_folder(test_grafana_url, org_data['api'], folder)
destination_folder = find_existing_folder(grafana_url, api, folder)
if source_folder and destination_folder:
print(source_folder, destination_folder)
response = requests.get(f"{test_grafana_url}/search", params={"folderIds": [source_folder]}, headers=headers)
dashboards_response = response.json()
print(dashboards_response)
for dashboard in dashboards_response:
dashboard_uid = dashboard["uid"]
dashboard_title = dashboard["title"]

# Add functionality for versioning
print(f"Dashboard '{dashboard_title}' has a new version.")
# print(dashboard)
# Step 5: Retrieve Dashboard JSON
response = requests.get(f"{test_grafana_url}/dashboards/uid/{dashboard_uid}", headers=headers)
# print(response)

dashboard_json = response.json()

for key in org_data.keys():
if key in data_prod:
replace_in_dict(dashboard_json, org_data[key], data_prod[key])
# print("Dashboard JSON")
# print(dashboard_json)
dashboard = dashboard_json.get("dashboard", {})
del dashboard["uid"]
# dashboard["version"] = "1"
del dashboard["id"]
if 'meta' in dashboard_json:
del dashboard_json['meta']
# print(dashboard)
dashboard_json["dashboard"] = dashboard
dashboard_json["overwrite"] = True
dashboard_json["folderId"] = destination_folder

print(f'Uploading to ${grafana_url}')
response = requests.post(f"{grafana_url}/dashboards/db", headers=headers2, json=dashboard_json)
if response.status_code == 200:
print("Dashboard creation/updating successful!")
else:
print(f"Error {response.status_code}: {response.content.decode('utf-8')}")
else:
print(f'Could not find folder {folder} in org {key}')



8 changes: 8 additions & 0 deletions .github/tvarit/deploy_to_production.sh
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ sed -i "s#<SMTP_USER/>#${SMTP_USER}#g" grafana.ini
sed -i "s#<SMTP_PASSWORD/>#${SMTP_PASSWORD}#g" grafana.ini
sed -i "s#<SMTP_FROM/>#Tvarit AI Platform#g" grafana.ini

if [ "${PREFIX}" == "maxion" ]; then
sed -i "s#<AD_LOGIN_FLAG/>#true#g" grafana.ini
sed -i "s#<MAXION_CLIENT_ID/>#${MAXION_CLIENT_ID}#g" grafana.ini
sed -i "s#<MAXION_CLIENT_SECRET/>#${MAXION_CLIENT_SECRET}#g" grafana.ini
else
sed -i "s#<AD_LOGIN_FLAG>#false#g" grafana.ini
fi

cp cloudwatch.json.template cloudwatch.json
sed -i "s#<DOMAIN/>#${PREFIX}.tvarit.com#g" cloudwatch.json

Expand Down
11 changes: 11 additions & 0 deletions .github/tvarit/deploy_to_staging.sh
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,17 @@ sed -i "s#<SMTP_USER/>#${SMTP_USER}#g" grafana.ini
sed -i "s#<SMTP_PASSWORD/>#${SMTP_PASSWORD}#g" grafana.ini
sed -i "s#<SMTP_FROM/>#[BETA] Tvarit AI Platform#g" grafana.ini

if [ "${PREFIX}" == "maxion" ]; then
sed -i "s#<AD_LOGIN_FLAG/>#true#g" grafana.ini
sed -i "s#<MAXION_CLIENT_ID/>#${MAXION_CLIENT_ID}#g" grafana.ini
sed -i "s#<MAXION_CLIENT_SECRET/>#${MAXION_CLIENT_SECRET}#g" grafana.ini
else
sed -i "s#<AD_LOGIN_FLAG>#false#g" grafana.ini
fi

echo "${MAXION_CLIENT_ID}"
cat "grafana.ini"

cp cloudwatch.json.template cloudwatch.json
sed -i "s#<DOMAIN/>#next-${PREFIX}.tvarit.com#g" cloudwatch.json

Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ jobs:
SMTP_HOST: ${{ secrets.SMTP_HOST }}
SMTP_USER: ${{ secrets.SMTP_USER }}
SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }}
MAXION_CLIENT_ID: ${{secrets.MAXION_CLIENT_ID}}
MAXION_CLIENT_SECRET: ${{secrets.MAXION_CLIENT_SECRET}}
steps:
- uses: actions/checkout@v2
- run: |
Expand All @@ -34,6 +36,8 @@ jobs:
SMTP_HOST: ${{ secrets.SMTP_HOST }}
SMTP_USER: ${{ secrets.SMTP_USER }}
SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }}
MAXION_CLIENT_ID: ${{secrets.MAXION_CLIENT_ID}}
MAXION_CLIENT_SECRET: ${{secrets.MAXION_CLIENT_SECRET}}
steps:
- uses: actions/checkout@v2
- run: |
Expand Down
25 changes: 25 additions & 0 deletions .github/workflows/test-to-prod-deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Deploy Dashboards

on:
workflow_dispatch:

jobs:
deploy_to_production:
runs-on: ubuntu-latest
environment: development
env:
AWS_DEFAULT_REGION: eu-central-1
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: 3.9

- name: Run Deployment script
run: |
python .github/tvarit/dashboard-deployment.py
10 changes: 5 additions & 5 deletions pkg/login/social/azuread_oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ func (s *SocialAzureAD) UserInfo(client *http.Client, token *oauth2.Token) (*Bas
return nil, errors.New("error getting user info: no email found in access token")
}

role := extractRole(claims, s.autoAssignOrgRole)
logger.Debug("AzureAD OAuth: extracted role", "email", email, "role", role)
/* role := extractRole(claims, s.autoAssignOrgRole)
logger.Debug("AzureAD OAuth: extracted role", "email", email, "role", role) */

groups, err := extractGroups(client, claims, token)
if err != nil {
Expand All @@ -87,7 +87,7 @@ func (s *SocialAzureAD) UserInfo(client *http.Client, token *oauth2.Token) (*Bas
Name: claims.Name,
Email: email,
Login: email,
Role: string(role),
Role: "", /* string(role), */
Groups: groups,
}, nil
}
Expand Down Expand Up @@ -117,7 +117,7 @@ func extractEmail(claims azureClaims) string {

return claims.Email
}

/*
func extractRole(claims azureClaims, autoAssignRole string) models.RoleType {
if len(claims.Roles) == 0 {
return models.RoleType(autoAssignRole)
Expand Down Expand Up @@ -146,7 +146,7 @@ func hasRole(roles []string, role models.RoleType) bool {
}
return false
}

*/
type getAzureGroupRequest struct {
SecurityEnabledOnly bool `json:"securityEnabledOnly"`
}
Expand Down

0 comments on commit 18b0a7c

Please sign in to comment.