Skip to content

Commit 65b1af2

Browse files
committed
add webhook
1 parent affe43c commit 65b1af2

File tree

1 file changed

+116
-14
lines changed

1 file changed

+116
-14
lines changed

restapi/router.go

Lines changed: 116 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@ import (
66
"fmt"
77
"log"
88
"os"
9+
"path/filepath"
910
"time"
1011

12+
"github.com/go-git/go-git/v5"
13+
githttp "github.com/go-git/go-git/v5/plumbing/transport/http"
1114
"github.com/gofiber/fiber/v2"
12-
"github.com/gofiber/fiber/v2/middleware/cors" // Import CORS middleware
15+
"github.com/gofiber/fiber/v2/middleware/cors"
1316
"github.com/ortelius/pdvd-backend/v12/database"
1417
"github.com/ortelius/pdvd-backend/v12/restapi/modules/auth"
15-
"github.com/ortelius/pdvd-backend/v12/restapi/modules/github" // Import GitHub module
18+
"github.com/ortelius/pdvd-backend/v12/restapi/modules/github"
1619
"github.com/ortelius/pdvd-backend/v12/restapi/modules/releases"
1720
"github.com/ortelius/pdvd-backend/v12/restapi/modules/sync"
1821
)
@@ -90,6 +93,7 @@ func SetupRoutes(app *fiber.App, db database.DBConnection) {
9093
rbac.Post("/validate", auth.HandleRBACValidate(db))
9194
rbac.Get("/config", auth.GetRBACConfig(db))
9295
rbac.Get("/invitations", auth.ListPendingInvitationsHandler(db))
96+
rbac.Post("/webhook", handleRBACWebhook(db, emailConfig))
9397

9498
// Release & Sync
9599
api.Post("/releases", auth.OptionalAuth(db), releases.PostReleaseWithSBOM(db))
@@ -98,6 +102,75 @@ func SetupRoutes(app *fiber.App, db database.DBConnection) {
98102
log.Println("API routes initialized successfully")
99103
}
100104

105+
func handleRBACWebhook(db database.DBConnection, emailConfig *auth.EmailConfig) fiber.Handler {
106+
return func(c *fiber.Ctx) error {
107+
yamlContent, err := syncRBACFromRepo()
108+
if err != nil {
109+
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
110+
"error": err.Error(),
111+
})
112+
}
113+
114+
config, err := auth.LoadPeriobolosConfig(yamlContent)
115+
if err != nil {
116+
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
117+
"error": "Invalid RBAC config: " + err.Error(),
118+
})
119+
}
120+
121+
result, err := auth.ApplyRBAC(db, config, emailConfig)
122+
if err != nil {
123+
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
124+
"error": "Failed to apply RBAC: " + err.Error(),
125+
})
126+
}
127+
128+
return c.JSON(fiber.Map{
129+
"success": true,
130+
"message": "RBAC synchronized from repository",
131+
"result": result,
132+
})
133+
}
134+
}
135+
136+
func syncRBACFromRepo() (string, error) {
137+
repoURL := os.Getenv("RBAC_REPO")
138+
token := os.Getenv("RBAC_REPO_TOKEN")
139+
140+
if repoURL == "" || token == "" {
141+
return "", fmt.Errorf("RBAC_REPO and RBAC_REPO_TOKEN must be configured")
142+
}
143+
144+
tempDir, err := os.MkdirTemp("", "rbac-sync-*")
145+
if err != nil {
146+
return "", fmt.Errorf("failed to create temp directory: %w", err)
147+
}
148+
defer os.RemoveAll(tempDir)
149+
150+
authMethod := &githttp.BasicAuth{
151+
Username: "oauth2",
152+
Password: token,
153+
}
154+
155+
_, err = git.PlainClone(tempDir, false, &git.CloneOptions{
156+
URL: repoURL,
157+
Auth: authMethod,
158+
Depth: 1,
159+
Progress: nil,
160+
})
161+
if err != nil {
162+
return "", fmt.Errorf("failed to clone RBAC repo: %w", err)
163+
}
164+
165+
yamlPath := filepath.Join(tempDir, "rbac.yaml")
166+
yamlContent, err := os.ReadFile(yamlPath)
167+
if err != nil {
168+
return "", fmt.Errorf("failed to read rbac.yaml: %w", err)
169+
}
170+
171+
return string(yamlContent), nil
172+
}
173+
101174
func startInvitationCleanup(db database.DBConnection) {
102175
runCleanup(db)
103176
ticker := time.NewTicker(1 * time.Hour)
@@ -121,23 +194,52 @@ func runCleanup(db database.DBConnection) {
121194
}
122195

123196
func autoApplyRBACOnStartup(db database.DBConnection, emailConfig *auth.EmailConfig) {
124-
configPath := os.Getenv("RBAC_CONFIG_PATH")
125-
if configPath == "" {
126-
configPath = "/etc/pdvd/rbac.yaml"
127-
}
128-
if _, err := os.Stat(configPath); err == nil {
129-
fmt.Println("🔄 Auto-applying RBAC configuration from:", configPath)
130-
config, err := auth.LoadPeriobolosConfig(configPath)
197+
// Check if RBAC repo is configured for GitOps mode
198+
repoURL := os.Getenv("RBAC_REPO")
199+
token := os.Getenv("RBAC_REPO_TOKEN")
200+
201+
var yamlContent string
202+
var err error
203+
204+
if repoURL != "" && token != "" {
205+
// GitOps mode: Fetch from GitHub
206+
fmt.Println("🔄 Auto-applying RBAC configuration from GitHub:", repoURL)
207+
yamlContent, err = syncRBACFromRepo()
131208
if err != nil {
132-
fmt.Printf("⚠️ Failed to load RBAC config: %v\n", err)
209+
fmt.Printf("⚠️ Failed to sync RBAC from GitHub: %v\n", err)
133210
return
134211
}
135-
result, err := auth.ApplyRBAC(db, config, emailConfig)
212+
} else {
213+
// Fallback to local file mode
214+
configPath := os.Getenv("RBAC_CONFIG_PATH")
215+
if configPath == "" {
216+
configPath = "/etc/pdvd/rbac.yaml"
217+
}
218+
if _, err := os.Stat(configPath); err != nil {
219+
// Neither GitHub nor local file configured
220+
return
221+
}
222+
fmt.Println("🔄 Auto-applying RBAC configuration from local file:", configPath)
223+
yamlBytes, err := os.ReadFile(configPath)
136224
if err != nil {
137-
fmt.Printf("⚠️ RBAC apply failed: %v\n", err)
225+
fmt.Printf("⚠️ Failed to read RBAC config: %v\n", err)
138226
return
139227
}
140-
fmt.Printf("✅ RBAC apply complete: %d created, %d updated, %d removed, %d invited\n",
141-
len(result.Created), len(result.Updated), len(result.Removed), len(result.Invited))
228+
yamlContent = string(yamlBytes)
229+
}
230+
231+
config, err := auth.LoadPeriobolosConfig(yamlContent)
232+
if err != nil {
233+
fmt.Printf("⚠️ Failed to load RBAC config: %v\n", err)
234+
return
142235
}
236+
237+
result, err := auth.ApplyRBAC(db, config, emailConfig)
238+
if err != nil {
239+
fmt.Printf("⚠️ RBAC apply failed: %v\n", err)
240+
return
241+
}
242+
243+
fmt.Printf("✅ RBAC apply complete: %d created, %d updated, %d removed, %d invited\n",
244+
len(result.Created), len(result.Updated), len(result.Removed), len(result.Invited))
143245
}

0 commit comments

Comments
 (0)