Skip to content

Latest commit

 

History

History
590 lines (453 loc) · 17.2 KB

SETUP_GUIDE.md

File metadata and controls

590 lines (453 loc) · 17.2 KB

🎯 دليل الإعداد الشامل - Gratech Comet-X

Comprehensive Setup Guide

تاريخ الإنشاء: 2025-12-13
الإصدار: 1.0.0
المالك (OWNER): Grar00t
المستودع: gratech-comet-x


📦 المحتويات

  1. إعداد OIDC في Azure Entra ID
  2. إنشاء المستودع على GitHub
  3. إضافة الأسرار
  4. تفعيل حماية الفرع
  5. دفع الملفات وتشغيل CI/CD
  6. التحقق من النشر
  7. الأوامر الكاملة (نسخ/لصق)

1. إعداد OIDC في Azure Entra ID

الهدف

السماح لـ GitHub Actions بالاتصال بـ Azure بدون مفاتيح ثابتة، باستخدام Workload Identity Federation.

الخطوات التفصيلية

1.1 إنشاء App Registration

# عبر Azure CLI (أو استخدم Portal)
az ad app create \
  --display-name "gratech-cometx-ci" \
  --sign-in-audience AzureADMyOrg

# احفظ الناتج - ستحتاج Application (client) ID

عبر Azure Portal:

  1. اذهب إلى Microsoft Entra ID → App registrations → New registration
  2. الاسم: gratech-cometx-ci
  3. النوع: Single tenant
  4. لا حاجة لـ Redirect URI
  5. اضغط Register
  6. انسخ (لا تعرض علناً):
    • Application (client) ID → سيصبح AZURE_CLIENT_ID
    • Directory (tenant) ID → سيصبح AZURE_TENANT_ID

1.2 إنشاء Federated Credential

# عبر Azure CLI
az ad app federated-credential create \
  --id <APPLICATION_ID> \
  --parameters '{
    "name": "github-actions-gratech-comet-x",
    "issuer": "https://token.actions.githubusercontent.com",
    "subject": "repo:Grar00t/gratech-comet-x:ref:refs/heads/main",
    "audiences": ["api://AzureADTokenExchange"]
  }'

عبر Azure Portal:

  1. افتح التطبيق gratech-cometx-ci
  2. اذهب إلى Certificates & secrets → Federated credentials → Add credential
  3. اختر GitHub Actions deploying Azure resources
  4. أدخل:
    • Organization: Grar00t
    • Repository: gratech-comet-x
    • Entity type: Branch
    • Branch name: main
    • أو يدوياً:
      • Issuer: https://token.actions.githubusercontent.com
      • Subject: repo:Grar00t/gratech-comet-x:ref:refs/heads/main
      • Audience: api://AzureADTokenExchange
  5. اسم الـ Credential: github-actions-main
  6. اضغط Add

1.3 إسناد صلاحيات للتطبيق

# الحصول على Subscription ID
SUBSCRIPTION_ID=$(az account show --query id -o tsv)

# الحصول على Service Principal للتطبيق
APP_ID="<APPLICATION_CLIENT_ID>"
SP_ID=$(az ad sp list --filter "appId eq '$APP_ID'" --query [0].id -o tsv)

# إسناد دور Contributor (أو دور محدود أكثر)
az role assignment create \
  --assignee $SP_ID \
  --role "Contributor" \
  --scope "/subscriptions/$SUBSCRIPTION_ID"

عبر Azure Portal:

  1. اذهب إلى Subscriptions → اختر اشتراكك
  2. Access control (IAM) → Add role assignment
  3. Role: Contributor (أو Website Contributor لحدود أضيق)
  4. Members: ابحث عن gratech-cometx-ci
  5. Review + assign

1.4 القيم المطلوبة للأسرار

انسخ هذه القيم (لا تعرضها علناً):

# من App Registration
AZURE_CLIENT_ID="<APPLICATION_CLIENT_ID>"

# من Entra ID
AZURE_TENANT_ID="<DIRECTORY_TENANT_ID>"

# من Subscriptions
AZURE_SUBSCRIPTION_ID="<SUBSCRIPTION_ID>"

2. إنشاء المستودع على GitHub

الأوامر الكاملة

# الانتقال إلى مجلد المشروع
cd ~/gratech-comet-x-final

# تهيئة Git
git init -b main
git add .
git commit -m "Initial: Comet-X Full Setup - Workflows + Security + Templates"

# إنشاء مستودع خاص ودفع
gh repo create Grar00t/gratech-comet-x --private --source=. --push

# التحقق من الرؤية
gh repo view --json visibility --jq .visibility
# المتوقع: "PRIVATE"

3. إضافة الأسرار

طريقة 1: عبر GitHub CLI (سريعة)

# أسرار X API (ستُطلب القيمة بعد كل أمر)
gh secret set X_API_KEY
gh secret set X_API_SECRET
gh secret set X_ACCESS_TOKEN
gh secret set X_ACCESS_SECRET
gh secret set X_BEARER_TOKEN
gh secret set X_CLIENT_ID
gh secret set X_CLIENT_SECRET

# أسرار Azure OIDC
gh secret set AZURE_CLIENT_ID
gh secret set AZURE_TENANT_ID
gh secret set AZURE_SUBSCRIPTION_ID

طريقة 2: عبر واجهة GitHub (يدوياً)

  1. افتح المستودع: https://github.com/Grar00t/gratech-comet-x
  2. Settings → Secrets and variables → Actions
  3. New repository secret لكل سر:
    • Name: مثل X_API_KEY
    • Value: القيمة الفعلية (لا تشاركها)
  4. كرر لجميع الأسرار أعلاه

طريقة 3: عبر ملف (للأتمتة - احذر من التسريبات!)

# إنشاء ملف مؤقت آمن
cat > /tmp/secrets.env << 'EOF'
X_API_KEY=xxxxx
X_API_SECRET=xxxxx
X_ACCESS_TOKEN=xxxxx
X_ACCESS_SECRET=xxxxx
X_BEARER_TOKEN=xxxxx
X_CLIENT_ID=xxxxx
X_CLIENT_SECRET=xxxxx
AZURE_CLIENT_ID=xxxxx
AZURE_TENANT_ID=xxxxx
AZURE_SUBSCRIPTION_ID=xxxxx
EOF

# رفع الأسرار (احذف الملف فوراً بعد الرفع)
cat /tmp/secrets.env | while IFS='=' read -r key value; do
  echo "$value" | gh secret set "$key"
done

# احذف الملف المؤقت فوراً
rm -f /tmp/secrets.env

⚠️ تحذير: لا ترفع ملف .env إلى Git أبداً!


4. تفعيل حماية الفرع

الأوامر الكاملة (gh CLI)

# المتغيرات
OWNER="Grar00t"
REPO="gratech-comet-x"
BRANCH="main"

# قائمة الـ Status Checks المطلوبة
REQ_CONTEXTS='["CodeQL Analysis","CI-CD (CometX) - Azure OIDC","build-scan-push"]'

# تطبيق حماية الفرع: PR + Approval + Status Checks + Enforce Admins
jq -n \
  --argjson contexts "$REQ_CONTEXTS" \
  '{
    "required_status_checks": {
      "strict": true,
      "contexts": $contexts
    },
    "enforce_admins": true,
    "required_pull_request_reviews": {
      "dismissal_restrictions": {},
      "dismiss_stale_reviews": true,
      "require_code_owner_reviews": false,
      "required_approving_review_count": 1,
      "require_last_push_approval": false
    },
    "restrictions": null,
    "required_linear_history": false,
    "allow_force_pushes": false,
    "allow_deletions": false,
    "required_conversation_resolution": true,
    "lock_branch": false,
    "allow_fork_syncing": true
  }' \
| gh api -X PUT "repos/$OWNER/$REPO/branches/$BRANCH/protection" \
  -H "Accept: application/vnd.github+json" \
  --input - --silent

echo "✅ Branch protection enabled for $BRANCH"

إضافة Signed Commits (اختياري)

# عبر API (بعض الإصدارات تدعمه)
gh api -X POST \
  "repos/$OWNER/$REPO/branches/$BRANCH/protection/required_signatures" \
  -H "Accept: application/vnd.github+json" || \
  echo "⚠️ Enable 'Require signed commits' manually in GitHub UI"

عبر واجهة GitHub:

  1. Settings → Branches → Branch protection rules
  2. اضغط على القاعدة لـ main
  3. فعّل Require signed commits
  4. Save changes

التحقق من الحماية

# عرض إعدادات الحماية الحالية
gh api \
  -H "Accept: application/vnd.github+json" \
  "repos/$OWNER/$REPO/branches/$BRANCH/protection" | jq '.'

# عرض القواعد الفعّالة
gh api \
  -H "Accept: application/vnd.github+json" \
  "repos/$OWNER/$REPO/rules/branches/$BRANCH" | jq '.'

5. دفع الملفات وتشغيل CI/CD

cd ~/gratech-comet-x-final

# تأكد من أن جميع الملفات موجودة
ls -lah .github/workflows/
ls -lah .github/ISSUE_TEMPLATE/

# دفع إلى main (سيُطلق workflows تلقائياً)
git add .
git commit -m "feat: Add all workflows + security policies + templates"
git push origin main

# مراقبة التشغيل
gh run watch

# عرض جميع الـ workflows
gh run list --limit 10

6. التحقق من النشر

6.1 التحقق من GitHub Actions

# عرض حالة الـ workflows
gh run list --workflow="CI-CD (CometX) - Azure OIDC" --limit 5
gh run list --workflow="CodeQL Analysis" --limit 5
gh run list --workflow="Docker → GHCR + Trivy Security Scan" --limit 5

# عرض سجلات آخر run
gh run view --log

6.2 التحقق من Security Tab

# عرض CodeQL alerts
gh api repos/Grar00t/gratech-comet-x/code-scanning/alerts | jq '.'

# عرض Dependabot alerts
gh api repos/Grar00t/gratech-comet-x/dependabot/alerts | jq '.'

عبر الواجهة:

  1. افتح https://github.com/Grar00t/gratech-comet-x/security
  2. Code scanning: تحقق من تنبيهات CodeQL + Trivy
  3. Dependabot: تحقق من PRs التلقائية

6.3 التحقق من Docker Image على GHCR

# عرض الحزم
gh api users/Grar00t/packages?package_type=container | jq '.[] | {name, visibility}'

# أو عبر الواجهة
open https://github.com/Grar00t?tab=packages

6.4 التحقق من صحة الموقع (Health Check)

# API Health Check
curl -sSf https://api.gratech.sa/health && echo "✅ API OK" || echo "❌ API Failed"

# Frontend Check
curl -sSf https://ai.gratech.sa && echo "✅ Frontend OK" || echo "❌ Frontend Failed"

7. الأوامر الكاملة (نسخ/لصق)

🚀 سكربت تنفيذ كامل (One-liner)

احفظ هذا في ملف deploy-full.sh:

#!/bin/bash
set -euo pipefail

# ========================
# متغيرات التكوين
# ========================
OWNER="Grar00t"
REPO="gratech-comet-x"
BRANCH="main"
PROJECT_DIR="$HOME/gratech-comet-x-final"

# الألوان
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}🚀 Starting Gratech Comet-X Full Deployment${NC}"
echo "=================================================="

# ========================
# 1. التحقق من المتطلبات
# ========================
echo -e "\n${YELLOW}📋 Checking prerequisites...${NC}"

command -v gh >/dev/null 2>&1 || { echo -e "${RED}❌ GitHub CLI not found${NC}"; exit 1; }
command -v jq >/dev/null 2>&1 || { echo -e "${RED}❌ jq not found${NC}"; exit 1; }
command -v git >/dev/null 2>&1 || { echo -e "${RED}❌ git not found${NC}"; exit 1; }

gh auth status || { echo -e "${RED}❌ Not logged in to GitHub${NC}"; exit 1; }

echo -e "${GREEN}✅ All prerequisites met${NC}"

# ========================
# 2. إنشاء المستودع
# ========================
echo -e "\n${YELLOW}📦 Creating repository...${NC}"

cd "$PROJECT_DIR"

if gh repo view "$OWNER/$REPO" &>/dev/null; then
  echo -e "${YELLOW}⚠️  Repository already exists${NC}"
else
  git init -b main
  git add .
  git commit -m "Initial: Comet-X Full Setup"
  gh repo create "$OWNER/$REPO" --private --source=. --push
  echo -e "${GREEN}✅ Repository created${NC}"
fi

# ========================
# 3. تفعيل Branch Protection
# ========================
echo -e "\n${YELLOW}🔒 Enabling branch protection...${NC}"

REQ_CONTEXTS='["CodeQL Analysis","CI-CD (CometX) - Azure OIDC","build-scan-push"]'

jq -n \
  --argjson contexts "$REQ_CONTEXTS" \
  '{
    "required_status_checks": {
      "strict": true,
      "contexts": $contexts
    },
    "enforce_admins": true,
    "required_pull_request_reviews": {
      "required_approving_review_count": 1,
      "dismiss_stale_reviews": true
    },
    "restrictions": null,
    "allow_force_pushes": false,
    "allow_deletions": false
  }' \
| gh api -X PUT "repos/$OWNER/$REPO/branches/$BRANCH/protection" \
  -H "Accept: application/vnd.github+json" \
  --input - --silent && \
  echo -e "${GREEN}✅ Branch protection enabled${NC}" || \
  echo -e "${RED}❌ Failed to enable protection${NC}"

# ========================
# 4. تفعيل Vulnerability Alerts
# ========================
echo -e "\n${YELLOW}🔍 Enabling vulnerability alerts...${NC}"

gh api -X PUT "repos/$OWNER/$REPO/vulnerability-alerts" \
  -H "Accept: application/vnd.github+json" --silent && \
  echo -e "${GREEN}✅ Vulnerability alerts enabled${NC}"

gh api -X PUT "repos/$OWNER/$REPO/automated-security-fixes" \
  -H "Accept: application/vnd.github+json" --silent && \
  echo -e "${GREEN}✅ Dependabot security updates enabled${NC}"

# ========================
# 5. عرض ملخص
# ========================
echo -e "\n${GREEN}✅ Deployment Summary${NC}"
echo "=================================================="
echo -e "📍 Repository: https://github.com/$OWNER/$REPO"
echo -e "🔐 Security: https://github.com/$OWNER/$REPO/security"
echo -e "⚙️  Actions: https://github.com/$OWNER/$REPO/actions"
echo -e "📦 Packages: https://github.com/$OWNER?tab=packages"
echo ""
echo -e "${YELLOW}📝 Next steps:${NC}"
echo "1. Add secrets in GitHub: Settings → Secrets → Actions"
echo "2. Configure Azure OIDC (Federated Credential)"
echo "3. Monitor workflows: gh run watch"
echo "4. Check health: curl https://api.gratech.sa/health"
echo ""
echo -e "${GREEN}🎯 Setup complete! Good luck! 🚀${NC}"

تشغيل السكربت

# جعل السكربت قابل للتنفيذ
chmod +x deploy-full.sh

# تشغيل
./deploy-full.sh

📋 Checklist التنفيذ الكامل

قبل التنفيذ

  • تثبيت GitHub CLI (gh)
  • تثبيت jq (sudo apt install jq أو brew install jq)
  • تسجيل دخول GitHub (gh auth login)
  • تسجيل دخول Azure (az login)
  • نسخ ملفات المشروع إلى ~/gratech-comet-x-final

خطوات Azure

  • إنشاء App Registration في Entra ID
  • إنشاء Federated Credential
  • إسناد Role (Contributor أو محدود)
  • نسخ AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_SUBSCRIPTION_ID

خطوات GitHub

  • إنشاء المستودع الخاص Grar00t/gratech-comet-x
  • إضافة جميع الأسرار (10 أسرار)
  • تفعيل Branch Protection على main
  • تفعيل Vulnerability Alerts
  • دفع جميع الملفات إلى main

التحقق

  • CodeQL workflow يعمل بنجاح
  • Trivy workflow يفحص + يرفع SARIF
  • Deploy workflow يسجل دخول Azure بنجاح
  • Docker image منشور على GHCR
  • Dependabot يفتح PRs
  • Security tab يعرض alerts
  • Health check يرجع 200 OK

🔧 استكشاف الأخطاء

مشكلة: OIDC Login يفشل

الخطأ: Error: Login failed with Error: Unable to get OIDC token

الحل:

  1. تحقق من permissions: id-token: write في workflow
  2. تحقق من Federated Credential في Azure:
    • Issuer صحيح: https://token.actions.githubusercontent.com
    • Subject صحيح: repo:Grar00t/gratech-comet-x:ref:refs/heads/main
    • Audience صحيح: api://AzureADTokenExchange
  3. تحقق من Role Assignment (Contributor)

مشكلة: Trivy يفشل دائماً

الخطأ: Error: Image scanning failed

الحل:

  1. تحقق من وجود Dockerfile في الجذر
  2. تحقق من بناء الصورة بنجاح قبل الفحص
  3. خفف الشدة: severity: 'CRITICAL' فقط

مشكلة: Branch Protection لا يطبق

الحل:

# تحقق من الإعدادات الحالية
gh api repos/Grar00t/gratech-comet-x/branches/main/protection | jq '.'

# تأكد من أسماء Status Checks مطابقة لأسماء Jobs
gh run list --limit 1 --json name,conclusion

مشكلة: Dependabot لا يفتح PRs

الحل:

  1. تحقق من وجود package.json أو Dockerfile
  2. تحقق من صحة syntax في dependabot.yml
  3. فعّل Dependabot في Settings → Security → Dependabot

📚 المراجع


🎯 خطوات ما بعد الإعداد

  1. اختبار OIDC: شغّل workflow oidc-smoke-test.yml يدوياً
  2. مراجعة Alerts: تحقق من Security tab يومياً
  3. دمج Dependabot PRs: راجع واختبر ثم ادمج
  4. تحديث DNS: بعد النشر، حدّث CNAME records لـ api.gratech.sa و ai.gratech.sa
  5. مراقبة Health: راقب endpoints يومياً

تم الإعداد بواسطة: GitHub Copilot CLI
للدعم: security@gratech.sa
الإصدار: 1.0.0 — 2025-12-13


بيت الحكمة الرقمي | The Digital House of Wisdom 🕌🚀