Phase 3C — Commit Summary
feat: workspaces — collaborative repo namespaces Backend - internal/models/workspace.go — Workspace (handle, displayName, description, createdBy) + WorkspaceMember (workspaceId, userId, username, role: owner/admin/member) - internal/models/repo.go — added nullable workspace_id column; existing user repos unaffected - internal/models/migrations/011_workspaces.go — syncs both tables + adds column to repository - internal/api/handlers/workspace.go — ListWorkspaces, CreateWorkspace, GetWorkspace, UpdateWorkspace, DeleteWorkspace (blocks if repos remain), ListRepos, ListMembers, AddMember, UpdateMember, RemoveMember - internal/api/handlers/repos.go — lookupRepo resolves workspace handles; Create accepts workspace field; List includes workspace member repos; withOwnerName uses workspace handle for workspace-owned repos - internal/api/handlers/dashboard.go — recentRuns + repo list include workspace repos the user is a member of - internal/api/router.go — /workspaces, /workspaces/:handle/* routes Workspace rules enforced: - Handle globally unique across usernames + workspace handles (409 on collision) - Creator auto-assigned owner role - Delete blocked if repos exist - Last owner cannot be demoted/removed --- feat: secret management hierarchy (Global → Workspace → Repo → Env) Backend - internal/models/secret.go — Secret struct + EncryptSecret/DecryptSecret with AES-256-GCM (key = SHA-256 of SESSION_SECRET); values never serialised to JSON - internal/models/migrations/012_secrets.go — syncs secret table - internal/api/handlers/secret.go — List/Upsert/Delete for all four scopes; ResolveSecretsForRun builds merged env map for CI - internal/domain/ci/executor.go — JobContext.Secrets field; secrets injected as --env KEY=VALUE into docker run; buildJobContext calls resolveSecrets(Global < Workspace < Repo < Env) - internal/domain/ci/runner_manager.go — passes cfg.SessionSecret to buildJobContext - internal/api/router.go — /repos/:owner/:repo/secrets, /environments/:envName/secrets, /workspaces/:handle/secrets, /admin/secrets --- feat: workspace + secret management UI Frontend - types/api.ts — Workspace, WorkspaceWithMeta, WorkspaceMember, SecretListItem types - api/queries/workspaces.ts — full CRUD hooks + WorkspaceRepo type - api/queries/secrets.ts — repo/env/workspace secret hooks - pages/WorkspacesPage.tsx — list + create modal - pages/WorkspacePage.tsx — workspace dashboard with repo list - pages/WorkspaceSettingsPage.tsx — general settings, members CRUD, workspace secrets, danger zone - pages/RepoSecretsPage.tsx — repo secrets + per-environment secret sections with priority hierarchy callout - pages/CreateRepoPage.tsx — ?workspace= query param pre-fills owner selector; only admin/owner workspaces shown - components/layout/Sidebar.tsx — "Workspaces" global nav item + workspace quick-links; "Secrets" in RepoSubNav; new SecretsIcon, WorkspaceIcon - App.tsx — routes for /workspaces, /workspaces/:handle, /workspaces/:handle/settings, /repos/:owner/:repo/secrets
This commit is contained in:
@@ -89,9 +89,21 @@ type dashboardResponse struct {
|
||||
func (h *DashboardHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
// 1. Repos owned by this user.
|
||||
// 1. Repos owned by this user (user-level) + workspace repos where user is a member.
|
||||
var repos []models.Repository
|
||||
h.db.Where("owner_id = ?", userID).Desc("updated_at").Find(&repos)
|
||||
h.db.Where("owner_id = ? AND workspace_id IS NULL", userID).Desc("updated_at").Find(&repos)
|
||||
|
||||
var memberships []models.WorkspaceMember
|
||||
h.db.Where("user_id = ?", userID).Find(&memberships)
|
||||
if len(memberships) > 0 {
|
||||
wsIDs := make([]int64, len(memberships))
|
||||
for i, m := range memberships {
|
||||
wsIDs[i] = m.WorkspaceID
|
||||
}
|
||||
var wsRepos []models.Repository
|
||||
h.db.In("workspace_id", wsIDs).Desc("updated_at").Find(&wsRepos)
|
||||
repos = append(repos, wsRepos...)
|
||||
}
|
||||
|
||||
repoIDs := make([]int64, len(repos))
|
||||
repoByID := make(map[int64]models.Repository, len(repos))
|
||||
@@ -184,8 +196,22 @@ func (h *DashboardHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
return dp
|
||||
}
|
||||
|
||||
// Cache workspace handles to avoid N+1.
|
||||
wsHandleByID := map[int64]string{}
|
||||
|
||||
dashRepos := make([]dashRepo, 0, len(repos))
|
||||
for _, rp := range repos {
|
||||
ownerName := owner.Username
|
||||
if rp.WorkspaceID != nil && *rp.WorkspaceID != 0 {
|
||||
if wsHandle, ok := wsHandleByID[*rp.WorkspaceID]; ok {
|
||||
ownerName = wsHandle
|
||||
} else {
|
||||
var ws models.Workspace
|
||||
h.db.ID(*rp.WorkspaceID).Cols("handle").Get(&ws)
|
||||
wsHandleByID[*rp.WorkspaceID] = ws.Handle
|
||||
ownerName = ws.Handle
|
||||
}
|
||||
}
|
||||
dashRepos = append(dashRepos, dashRepo{
|
||||
ID: rp.ID,
|
||||
Name: rp.Name,
|
||||
@@ -193,8 +219,8 @@ func (h *DashboardHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
IsPrivate: rp.IsPrivate,
|
||||
DefaultBranch: rp.DefaultBranch,
|
||||
UpdatedAt: rp.UpdatedAt.Format("2006-01-02T15:04:05Z"),
|
||||
OwnerName: owner.Username,
|
||||
AvatarURL: "/api/v1/repos/" + owner.Username + "/" + rp.Name + "/avatar",
|
||||
OwnerName: ownerName,
|
||||
AvatarURL: "/api/v1/repos/" + ownerName + "/" + rp.Name + "/avatar",
|
||||
OpenPRCount: prCountByRepo[rp.ID],
|
||||
OpenIssueCount: issueCountByRepo[rp.ID],
|
||||
})
|
||||
|
||||
@@ -46,19 +46,28 @@ func isValidRepoName(name string) bool {
|
||||
}
|
||||
|
||||
func (h *RepoHandler) withOwnerName(repo *models.Repository) repoResponse {
|
||||
var owner models.User
|
||||
h.db.ID(repo.OwnerID).Get(&owner)
|
||||
gitdomain.SetRepoRoot(h.cfg.RepoRoot)
|
||||
|
||||
ownerName := ""
|
||||
if repo.WorkspaceID != nil && *repo.WorkspaceID != 0 {
|
||||
var ws models.Workspace
|
||||
h.db.ID(*repo.WorkspaceID).Cols("handle").Get(&ws)
|
||||
ownerName = ws.Handle
|
||||
} else {
|
||||
var owner models.User
|
||||
h.db.ID(repo.OwnerID).Cols("username").Get(&owner)
|
||||
ownerName = owner.Username
|
||||
}
|
||||
|
||||
avURL := ""
|
||||
if _, err := os.Stat(avatarPath(h.cfg.RepoRoot, repo.ID)); err == nil {
|
||||
avURL = "/api/v1/repos/" + owner.Username + "/" + repo.Name + "/avatar"
|
||||
avURL = "/api/v1/repos/" + ownerName + "/" + repo.Name + "/avatar"
|
||||
}
|
||||
|
||||
return repoResponse{
|
||||
Repository: *repo,
|
||||
AvatarURL: avURL,
|
||||
OwnerName: owner.Username,
|
||||
OwnerName: ownerName,
|
||||
IsEmpty: gitdomain.IsEmpty(repo.DiskPath),
|
||||
}
|
||||
}
|
||||
@@ -75,10 +84,21 @@ func NewRepoHandler(db *xorm.Engine, cfg *config.Config) *RepoHandler {
|
||||
func (h *RepoHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
// User-owned repos.
|
||||
var repos []models.Repository
|
||||
if err := h.db.Where("owner_id = ?", userID).Find(&repos); err != nil {
|
||||
jsonError(w, "could not list repositories", http.StatusInternalServerError)
|
||||
return
|
||||
h.db.Where("owner_id = ? AND workspace_id IS NULL", userID).Find(&repos)
|
||||
|
||||
// Workspace repos where user is a member.
|
||||
var memberships []models.WorkspaceMember
|
||||
h.db.Where("user_id = ?", userID).Find(&memberships)
|
||||
if len(memberships) > 0 {
|
||||
wsIDs := make([]int64, len(memberships))
|
||||
for i, m := range memberships {
|
||||
wsIDs[i] = m.WorkspaceID
|
||||
}
|
||||
var wsRepos []models.Repository
|
||||
h.db.In("workspace_id", wsIDs).Find(&wsRepos)
|
||||
repos = append(repos, wsRepos...)
|
||||
}
|
||||
|
||||
result := make([]repoResponse, len(repos))
|
||||
@@ -98,6 +118,7 @@ func (h *RepoHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
DefaultBranch string `json:"defaultBranch"`
|
||||
InitReadme string `json:"initReadme"` // "none" | "blank" | "tutorial"
|
||||
InitGitignore bool `json:"initGitignore"` // true → add .gitignore
|
||||
Workspace string `json:"workspace"` // optional workspace handle
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||
@@ -112,10 +133,35 @@ func (h *RepoHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
branch = "main"
|
||||
}
|
||||
|
||||
diskPath := filepath.Join(h.cfg.RepoRoot, strconv.FormatInt(userID, 10), body.Name+".git")
|
||||
// Determine owner: workspace or user.
|
||||
var workspaceID *int64
|
||||
var diskPath string
|
||||
if body.Workspace != "" {
|
||||
var ws models.Workspace
|
||||
if found, _ := h.db.Where("handle = ?", body.Workspace).Get(&ws); !found {
|
||||
jsonError(w, "workspace not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
// Caller must be a member with write access.
|
||||
var member models.WorkspaceMember
|
||||
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, userID).Get(&member); !found {
|
||||
jsonError(w, "not a member of this workspace", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if member.Role == models.WorkspaceRoleMember {
|
||||
jsonError(w, "admin or owner required to create repos in a workspace", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
wsID := ws.ID
|
||||
workspaceID = &wsID
|
||||
diskPath = diskPathForWorkspaceRepo(h.cfg.RepoRoot, ws.ID, body.Name)
|
||||
} else {
|
||||
diskPath = filepath.Join(h.cfg.RepoRoot, strconv.FormatInt(userID, 10), body.Name+".git")
|
||||
}
|
||||
|
||||
repo := &models.Repository{
|
||||
OwnerID: userID,
|
||||
WorkspaceID: workspaceID,
|
||||
Name: body.Name,
|
||||
Description: body.Description,
|
||||
IsPrivate: body.IsPrivate,
|
||||
@@ -559,33 +605,48 @@ func (h *RepoHandler) Diff(w http.ResponseWriter, r *http.Request) {
|
||||
jsonOK(w, diffs)
|
||||
}
|
||||
|
||||
// lookupRepo resolves {owner}/{repo} URL params to a DB row, enforcing access.
|
||||
// lookupRepo resolves {owner}/{repo} URL params to a DB row.
|
||||
// The owner segment can be either a username (user-owned repo) or a
|
||||
// workspace handle (workspace-owned repo).
|
||||
func (h *RepoHandler) lookupRepo(w http.ResponseWriter, r *http.Request) (*models.Repository, bool) {
|
||||
ownerName := chi.URLParam(r, "owner")
|
||||
repoName := chi.URLParam(r, "repo")
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
var owner models.User
|
||||
found, err := h.db.Where("username = ?", ownerName).Get(&owner)
|
||||
if err != nil || !found {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
|
||||
var repo models.Repository
|
||||
found, err = h.db.Where("owner_id = ? AND name = ?", owner.ID, repoName).Get(&repo)
|
||||
if err != nil || !found {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Private repo: only the owner may access (RBAC will be expanded in Phase 3)
|
||||
if repo.IsPrivate {
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
if callerID != repo.OwnerID {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
// 1. Try user namespace first.
|
||||
var user models.User
|
||||
if found, _ := h.db.Where("username = ?", ownerName).Get(&user); found {
|
||||
var repo models.Repository
|
||||
if found2, _ := h.db.Where("owner_id = ? AND name = ? AND workspace_id IS NULL", user.ID, repoName).Get(&repo); found2 {
|
||||
if repo.IsPrivate && callerID != repo.OwnerID {
|
||||
// Check repo membership for private user repos.
|
||||
var m models.RepoMember
|
||||
if mfound, _ := h.db.Where("repo_id = ? AND user_id = ?", repo.ID, callerID).Get(&m); !mfound {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return &repo, true
|
||||
}
|
||||
}
|
||||
|
||||
return &repo, true
|
||||
// 2. Try workspace namespace.
|
||||
var ws models.Workspace
|
||||
if found, _ := h.db.Where("handle = ?", ownerName).Get(&ws); found {
|
||||
var repo models.Repository
|
||||
if found2, _ := h.db.Where("workspace_id = ? AND name = ?", ws.ID, repoName).Get(&repo); found2 {
|
||||
if repo.IsPrivate {
|
||||
// Private workspace repo: caller must be a workspace member.
|
||||
var m models.WorkspaceMember
|
||||
if mfound, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, callerID).Get(&m); !mfound {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return &repo, true
|
||||
}
|
||||
}
|
||||
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"xorm.io/xorm"
|
||||
|
||||
"github.com/forgeo/forgebucket/internal/api/middleware"
|
||||
"github.com/forgeo/forgebucket/internal/models"
|
||||
)
|
||||
|
||||
type SecretHandler struct {
|
||||
db *xorm.Engine
|
||||
sessionSecret string
|
||||
}
|
||||
|
||||
func NewSecretHandler(db *xorm.Engine, sessionSecret string) *SecretHandler {
|
||||
return &SecretHandler{db: db, sessionSecret: sessionSecret}
|
||||
}
|
||||
|
||||
// ── Secret list response (names only — never values) ─────────────────────────
|
||||
|
||||
type secretListItem struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
func toListItem(s models.Secret) secretListItem {
|
||||
return secretListItem{
|
||||
ID: s.ID,
|
||||
Name: s.Name,
|
||||
CreatedAt: s.CreatedAt.Format("2006-01-02T15:04:05Z"),
|
||||
UpdatedAt: s.UpdatedAt.Format("2006-01-02T15:04:05Z"),
|
||||
}
|
||||
}
|
||||
|
||||
// ── Repo secrets ──────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *SecretHandler) ListRepoSecrets(w http.ResponseWriter, r *http.Request) {
|
||||
repoID, ok := h.resolveRepoID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.listSecrets(w, models.SecretScopeRepo, repoID)
|
||||
}
|
||||
|
||||
func (h *SecretHandler) UpsertRepoSecret(w http.ResponseWriter, r *http.Request) {
|
||||
repoID, ok := h.resolveRepoID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.upsertSecret(w, r, models.SecretScopeRepo, repoID)
|
||||
}
|
||||
|
||||
func (h *SecretHandler) DeleteRepoSecret(w http.ResponseWriter, r *http.Request) {
|
||||
repoID, ok := h.resolveRepoID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.deleteSecret(w, r, models.SecretScopeRepo, repoID)
|
||||
}
|
||||
|
||||
// ── Env secrets ───────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *SecretHandler) ListEnvSecrets(w http.ResponseWriter, r *http.Request) {
|
||||
envID, ok := h.resolveEnvID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.listSecrets(w, models.SecretScopeEnv, envID)
|
||||
}
|
||||
|
||||
func (h *SecretHandler) UpsertEnvSecret(w http.ResponseWriter, r *http.Request) {
|
||||
envID, ok := h.resolveEnvID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.upsertSecret(w, r, models.SecretScopeEnv, envID)
|
||||
}
|
||||
|
||||
func (h *SecretHandler) DeleteEnvSecret(w http.ResponseWriter, r *http.Request) {
|
||||
envID, ok := h.resolveEnvID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.deleteSecret(w, r, models.SecretScopeEnv, envID)
|
||||
}
|
||||
|
||||
// ── Workspace secrets ─────────────────────────────────────────────────────────
|
||||
|
||||
func (h *SecretHandler) ListWorkspaceSecrets(w http.ResponseWriter, r *http.Request) {
|
||||
wsID, ok := h.resolveWorkspaceID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.listSecrets(w, models.SecretScopeWorkspace, wsID)
|
||||
}
|
||||
|
||||
func (h *SecretHandler) UpsertWorkspaceSecret(w http.ResponseWriter, r *http.Request) {
|
||||
wsID, ok := h.resolveWorkspaceID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.upsertSecret(w, r, models.SecretScopeWorkspace, wsID)
|
||||
}
|
||||
|
||||
func (h *SecretHandler) DeleteWorkspaceSecret(w http.ResponseWriter, r *http.Request) {
|
||||
wsID, ok := h.resolveWorkspaceID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.deleteSecret(w, r, models.SecretScopeWorkspace, wsID)
|
||||
}
|
||||
|
||||
// ── Global secrets (admin only) ───────────────────────────────────────────────
|
||||
|
||||
func (h *SecretHandler) ListGlobalSecrets(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.requireAdmin(w, r) {
|
||||
return
|
||||
}
|
||||
h.listSecrets(w, models.SecretScopeGlobal, 0)
|
||||
}
|
||||
|
||||
func (h *SecretHandler) UpsertGlobalSecret(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.requireAdmin(w, r) {
|
||||
return
|
||||
}
|
||||
h.upsertSecret(w, r, models.SecretScopeGlobal, 0)
|
||||
}
|
||||
|
||||
func (h *SecretHandler) DeleteGlobalSecret(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.requireAdmin(w, r) {
|
||||
return
|
||||
}
|
||||
h.deleteSecret(w, r, models.SecretScopeGlobal, 0)
|
||||
}
|
||||
|
||||
// ── Shared CRUD primitives ────────────────────────────────────────────────────
|
||||
|
||||
func (h *SecretHandler) listSecrets(w http.ResponseWriter, scope models.SecretScope, scopeID int64) {
|
||||
var secrets []models.Secret
|
||||
h.db.Where("scope = ? AND scope_id = ?", scope, scopeID).Asc("name").Find(&secrets)
|
||||
items := make([]secretListItem, len(secrets))
|
||||
for i, s := range secrets {
|
||||
items[i] = toListItem(s)
|
||||
}
|
||||
jsonOK(w, items)
|
||||
}
|
||||
|
||||
func (h *SecretHandler) upsertSecret(w http.ResponseWriter, r *http.Request, scope models.SecretScope, scopeID int64) {
|
||||
var body struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if body.Name == "" || body.Value == "" {
|
||||
jsonError(w, "name and value are required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
encrypted, err := models.EncryptSecret(body.Value, h.sessionSecret)
|
||||
if err != nil {
|
||||
jsonError(w, "encryption failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Upsert: update if the name already exists for this scope.
|
||||
var existing models.Secret
|
||||
found, _ := h.db.Where("scope = ? AND scope_id = ? AND name = ?", scope, scopeID, body.Name).Get(&existing)
|
||||
if found {
|
||||
existing.EncryptedValue = encrypted
|
||||
h.db.ID(existing.ID).Cols("encrypted_value", "updated_at").Update(&existing) //nolint:errcheck
|
||||
jsonOK(w, toListItem(existing))
|
||||
return
|
||||
}
|
||||
|
||||
secret := &models.Secret{
|
||||
Scope: scope,
|
||||
ScopeID: scopeID,
|
||||
Name: body.Name,
|
||||
EncryptedValue: encrypted,
|
||||
}
|
||||
if _, err := h.db.Insert(secret); err != nil {
|
||||
jsonError(w, "could not save secret", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(toListItem(*secret)) //nolint:errcheck
|
||||
}
|
||||
|
||||
func (h *SecretHandler) deleteSecret(w http.ResponseWriter, r *http.Request, scope models.SecretScope, scopeID int64) {
|
||||
name := chi.URLParam(r, "name")
|
||||
res, err := h.db.Where("scope = ? AND scope_id = ? AND name = ?", scope, scopeID, name).
|
||||
Delete(&models.Secret{})
|
||||
if err != nil || res == 0 {
|
||||
jsonError(w, "secret not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// ── ResolveSecretsForRun ──────────────────────────────────────────────────────
|
||||
// Used by the CI executor to build the env var map for a pipeline job.
|
||||
// Priority order (highest wins): Env > Repo > Workspace > Global.
|
||||
|
||||
func ResolveSecretsForRun(db *xorm.Engine, repoID, workspaceID, envID int64, sessionSecret string) map[string]string {
|
||||
out := map[string]string{}
|
||||
|
||||
loadScope := func(scope models.SecretScope, scopeID int64) {
|
||||
var secrets []models.Secret
|
||||
db.Where("scope = ? AND scope_id = ?", scope, scopeID).Find(&secrets)
|
||||
for _, s := range secrets {
|
||||
if _, already := out[s.Name]; !already {
|
||||
pt, err := models.DecryptSecret(s.EncryptedValue, sessionSecret)
|
||||
if err == nil {
|
||||
out[s.Name] = pt
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Load in reverse priority so higher-priority scopes overwrite.
|
||||
loadScope(models.SecretScopeGlobal, 0)
|
||||
if workspaceID != 0 {
|
||||
loadScope(models.SecretScopeWorkspace, workspaceID)
|
||||
}
|
||||
loadScope(models.SecretScopeRepo, repoID)
|
||||
if envID != 0 {
|
||||
loadScope(models.SecretScopeEnv, envID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *SecretHandler) resolveRepoID(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||
owner := chi.URLParam(r, "owner")
|
||||
repoName := chi.URLParam(r, "repo")
|
||||
var u models.User
|
||||
if found, _ := h.db.Where("username = ?", owner).Get(&u); !found {
|
||||
// Try workspace
|
||||
var ws models.Workspace
|
||||
if found2, _ := h.db.Where("handle = ?", owner).Get(&ws); !found2 {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return 0, false
|
||||
}
|
||||
var repo models.Repository
|
||||
if found3, _ := h.db.Where("workspace_id = ? AND name = ?", ws.ID, repoName).Get(&repo); !found3 {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return 0, false
|
||||
}
|
||||
return repo.ID, true
|
||||
}
|
||||
var repo models.Repository
|
||||
if found, _ := h.db.Where("owner_id = ? AND name = ?", u.ID, repoName).Get(&repo); !found {
|
||||
jsonError(w, "repository not found", http.StatusNotFound)
|
||||
return 0, false
|
||||
}
|
||||
return repo.ID, true
|
||||
}
|
||||
|
||||
func (h *SecretHandler) resolveEnvID(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||
repoID, ok := h.resolveRepoID(w, r)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
envName := chi.URLParam(r, "envName")
|
||||
var env models.Environment
|
||||
if found, _ := h.db.Where("repo_id = ? AND name = ?", repoID, envName).Get(&env); !found {
|
||||
jsonError(w, "environment not found", http.StatusNotFound)
|
||||
return 0, false
|
||||
}
|
||||
return env.ID, true
|
||||
}
|
||||
|
||||
func (h *SecretHandler) resolveWorkspaceID(w http.ResponseWriter, r *http.Request) (int64, bool) {
|
||||
handle := chi.URLParam(r, "handle")
|
||||
var ws models.Workspace
|
||||
if found, _ := h.db.Where("handle = ?", handle).Get(&ws); !found {
|
||||
jsonError(w, "workspace not found", http.StatusNotFound)
|
||||
return 0, false
|
||||
}
|
||||
// Require membership.
|
||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||
var member models.WorkspaceMember
|
||||
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, userID).Get(&member); !found {
|
||||
jsonError(w, "workspace not found", http.StatusNotFound)
|
||||
return 0, false
|
||||
}
|
||||
return ws.ID, true
|
||||
}
|
||||
|
||||
func (h *SecretHandler) requireAdmin(w http.ResponseWriter, r *http.Request) bool {
|
||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||
var u models.User
|
||||
if found, _ := h.db.ID(userID).Get(&u); !found || !u.IsAdmin {
|
||||
jsonError(w, "admin required", http.StatusForbidden)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"xorm.io/xorm"
|
||||
|
||||
"github.com/forgeo/forgebucket/internal/api/middleware"
|
||||
"github.com/forgeo/forgebucket/internal/config"
|
||||
"github.com/forgeo/forgebucket/internal/models"
|
||||
)
|
||||
|
||||
type WorkspaceHandler struct {
|
||||
db *xorm.Engine
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
func NewWorkspaceHandler(db *xorm.Engine, cfg *config.Config) *WorkspaceHandler {
|
||||
return &WorkspaceHandler{db: db, cfg: cfg}
|
||||
}
|
||||
|
||||
// ── Response shapes ───────────────────────────────────────────────────────────
|
||||
|
||||
type workspaceResponse struct {
|
||||
models.Workspace
|
||||
MemberCount int `json:"memberCount"`
|
||||
RepoCount int `json:"repoCount"`
|
||||
MyRole string `json:"myRole"` // caller's role, empty if not a member
|
||||
}
|
||||
|
||||
// ── List ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
// ListWorkspaces returns all workspaces the current user belongs to.
|
||||
func (h *WorkspaceHandler) ListWorkspaces(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
var memberships []models.WorkspaceMember
|
||||
h.db.Where("user_id = ?", userID).Find(&memberships)
|
||||
|
||||
if len(memberships) == 0 {
|
||||
jsonOK(w, []workspaceResponse{})
|
||||
return
|
||||
}
|
||||
|
||||
wsIDs := make([]int64, len(memberships))
|
||||
roleByWS := map[int64]string{}
|
||||
for i, m := range memberships {
|
||||
wsIDs[i] = m.WorkspaceID
|
||||
roleByWS[m.WorkspaceID] = string(m.Role)
|
||||
}
|
||||
|
||||
var workspaces []models.Workspace
|
||||
h.db.In("id", wsIDs).Find(&workspaces)
|
||||
|
||||
result := make([]workspaceResponse, len(workspaces))
|
||||
for i, ws := range workspaces {
|
||||
memberCount, _ := h.db.Where("workspace_id = ?", ws.ID).Count(&models.WorkspaceMember{})
|
||||
repoCount, _ := h.db.Where("workspace_id = ?", ws.ID).Count(&models.Repository{})
|
||||
result[i] = workspaceResponse{
|
||||
Workspace: ws,
|
||||
MemberCount: int(memberCount),
|
||||
RepoCount: int(repoCount),
|
||||
MyRole: roleByWS[ws.ID],
|
||||
}
|
||||
}
|
||||
jsonOK(w, result)
|
||||
}
|
||||
|
||||
// ── Create ────────────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *WorkspaceHandler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
|
||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||
|
||||
var body struct {
|
||||
Handle string `json:"handle"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if body.Handle == "" {
|
||||
jsonError(w, "handle is required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !isValidHandle(body.Handle) {
|
||||
jsonError(w, "handle may only contain letters, numbers, hyphens, and underscores", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Handle must not collide with any username or existing workspace handle.
|
||||
var existingUser models.User
|
||||
if found, _ := h.db.Where("username = ?", body.Handle).Get(&existingUser); found {
|
||||
jsonError(w, "handle is already taken by a user", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
var existingWS models.Workspace
|
||||
if found, _ := h.db.Where("handle = ?", body.Handle).Get(&existingWS); found {
|
||||
jsonError(w, "handle is already taken by a workspace", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
|
||||
ws := &models.Workspace{
|
||||
Handle: body.Handle,
|
||||
DisplayName: body.DisplayName,
|
||||
Description: body.Description,
|
||||
CreatedBy: userID,
|
||||
}
|
||||
if _, err := h.db.Insert(ws); err != nil {
|
||||
jsonError(w, "could not create workspace", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Creator becomes owner automatically.
|
||||
var creator models.User
|
||||
h.db.ID(userID).Cols("username").Get(&creator)
|
||||
member := &models.WorkspaceMember{
|
||||
WorkspaceID: ws.ID,
|
||||
UserID: userID,
|
||||
Username: creator.Username,
|
||||
Role: models.WorkspaceRoleOwner,
|
||||
}
|
||||
h.db.Insert(member) //nolint:errcheck
|
||||
|
||||
resp := workspaceResponse{Workspace: *ws, MemberCount: 1, MyRole: string(models.WorkspaceRoleOwner)}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(resp) //nolint:errcheck
|
||||
}
|
||||
|
||||
// ── Get ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *WorkspaceHandler) GetWorkspace(w http.ResponseWriter, r *http.Request) {
|
||||
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
memberCount, _ := h.db.Where("workspace_id = ?", ws.ID).Count(&models.WorkspaceMember{})
|
||||
repoCount, _ := h.db.Where("workspace_id = ?", ws.ID).Count(&models.Repository{})
|
||||
jsonOK(w, workspaceResponse{Workspace: *ws, MemberCount: int(memberCount), RepoCount: int(repoCount), MyRole: myRole})
|
||||
}
|
||||
|
||||
// ── Update ────────────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *WorkspaceHandler) UpdateWorkspace(w http.ResponseWriter, r *http.Request) {
|
||||
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if myRole != string(models.WorkspaceRoleOwner) && myRole != string(models.WorkspaceRoleAdmin) {
|
||||
jsonError(w, "admin or owner required", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
DisplayName *string `json:"displayName"`
|
||||
Description *string `json:"description"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
cols := []string{}
|
||||
if body.DisplayName != nil {
|
||||
ws.DisplayName = *body.DisplayName
|
||||
cols = append(cols, "display_name")
|
||||
}
|
||||
if body.Description != nil {
|
||||
ws.Description = *body.Description
|
||||
cols = append(cols, "description")
|
||||
}
|
||||
if len(cols) > 0 {
|
||||
h.db.ID(ws.ID).Cols(cols...).Update(ws) //nolint:errcheck
|
||||
}
|
||||
jsonOK(w, ws)
|
||||
}
|
||||
|
||||
// ── Delete ────────────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *WorkspaceHandler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
|
||||
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if myRole != string(models.WorkspaceRoleOwner) {
|
||||
jsonError(w, "only the workspace owner can delete it", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// Refuse if the workspace still has repos.
|
||||
count, _ := h.db.Where("workspace_id = ?", ws.ID).Count(&models.Repository{})
|
||||
if count > 0 {
|
||||
jsonError(w, "delete or transfer all repositories before deleting the workspace", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
h.db.Where("workspace_id = ?", ws.ID).Delete(&models.WorkspaceMember{}) //nolint:errcheck
|
||||
h.db.ID(ws.ID).Delete(&models.Workspace{}) //nolint:errcheck
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// ── Repos in workspace ────────────────────────────────────────────────────────
|
||||
|
||||
func (h *WorkspaceHandler) ListRepos(w http.ResponseWriter, r *http.Request) {
|
||||
ws, _, ok := h.resolveWorkspace(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var repos []models.Repository
|
||||
h.db.Where("workspace_id = ?", ws.ID).Find(&repos)
|
||||
if repos == nil {
|
||||
repos = []models.Repository{}
|
||||
}
|
||||
// Return the same enriched shape that the repo list uses.
|
||||
type wsRepoResponse struct {
|
||||
models.Repository
|
||||
OwnerName string `json:"ownerName"`
|
||||
}
|
||||
result := make([]wsRepoResponse, len(repos))
|
||||
for i, r := range repos {
|
||||
result[i] = wsRepoResponse{Repository: r, OwnerName: ws.Handle}
|
||||
}
|
||||
jsonOK(w, result)
|
||||
}
|
||||
|
||||
// ── Members ───────────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *WorkspaceHandler) ListMembers(w http.ResponseWriter, r *http.Request) {
|
||||
ws, _, ok := h.resolveWorkspace(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var members []models.WorkspaceMember
|
||||
h.db.Where("workspace_id = ?", ws.ID).Find(&members)
|
||||
if members == nil {
|
||||
members = []models.WorkspaceMember{}
|
||||
}
|
||||
jsonOK(w, members)
|
||||
}
|
||||
|
||||
func (h *WorkspaceHandler) AddMember(w http.ResponseWriter, r *http.Request) {
|
||||
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if myRole != string(models.WorkspaceRoleOwner) && myRole != string(models.WorkspaceRoleAdmin) {
|
||||
jsonError(w, "admin or owner required", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"` // "admin" | "member"
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
role := models.WorkspaceRole(body.Role)
|
||||
if role != models.WorkspaceRoleAdmin && role != models.WorkspaceRoleMember {
|
||||
role = models.WorkspaceRoleMember
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if found, _ := h.db.Where("username = ?", body.Username).Get(&user); !found {
|
||||
jsonError(w, "user not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Idempotent: update role if already a member.
|
||||
var existing models.WorkspaceMember
|
||||
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, user.ID).Get(&existing); found {
|
||||
existing.Role = role
|
||||
h.db.ID(existing.ID).Cols("role").Update(&existing) //nolint:errcheck
|
||||
jsonOK(w, existing)
|
||||
return
|
||||
}
|
||||
|
||||
member := &models.WorkspaceMember{
|
||||
WorkspaceID: ws.ID,
|
||||
UserID: user.ID,
|
||||
Username: user.Username,
|
||||
Role: role,
|
||||
}
|
||||
if _, err := h.db.Insert(member); err != nil {
|
||||
jsonError(w, "could not add member", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(member) //nolint:errcheck
|
||||
}
|
||||
|
||||
func (h *WorkspaceHandler) UpdateMember(w http.ResponseWriter, r *http.Request) {
|
||||
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if myRole != string(models.WorkspaceRoleOwner) && myRole != string(models.WorkspaceRoleAdmin) {
|
||||
jsonError(w, "admin or owner required", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
targetUsername := chi.URLParam(r, "username")
|
||||
var body struct{ Role string `json:"role"` }
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var target models.User
|
||||
if found, _ := h.db.Where("username = ?", targetUsername).Get(&target); !found {
|
||||
jsonError(w, "user not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
var member models.WorkspaceMember
|
||||
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, target.ID).Get(&member); !found {
|
||||
jsonError(w, "member not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
// Cannot demote the last owner.
|
||||
if member.Role == models.WorkspaceRoleOwner && models.WorkspaceRole(body.Role) != models.WorkspaceRoleOwner {
|
||||
count, _ := h.db.Where("workspace_id = ? AND role = 'owner'", ws.ID).Count(&models.WorkspaceMember{})
|
||||
if count <= 1 {
|
||||
jsonError(w, "workspace must have at least one owner", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
}
|
||||
member.Role = models.WorkspaceRole(body.Role)
|
||||
h.db.ID(member.ID).Cols("role").Update(&member) //nolint:errcheck
|
||||
jsonOK(w, member)
|
||||
}
|
||||
|
||||
func (h *WorkspaceHandler) RemoveMember(w http.ResponseWriter, r *http.Request) {
|
||||
ws, myRole, ok := h.resolveWorkspace(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
callerID, _ := middleware.UserIDFromContext(r.Context())
|
||||
targetUsername := chi.URLParam(r, "username")
|
||||
|
||||
var target models.User
|
||||
if found, _ := h.db.Where("username = ?", targetUsername).Get(&target); !found {
|
||||
jsonError(w, "user not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Members can remove themselves; admins/owners can remove others.
|
||||
if target.ID != callerID {
|
||||
if myRole != string(models.WorkspaceRoleOwner) && myRole != string(models.WorkspaceRoleAdmin) {
|
||||
jsonError(w, "admin or owner required", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var member models.WorkspaceMember
|
||||
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, target.ID).Get(&member); !found {
|
||||
jsonError(w, "member not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if member.Role == models.WorkspaceRoleOwner {
|
||||
count, _ := h.db.Where("workspace_id = ? AND role = 'owner'", ws.ID).Count(&models.WorkspaceMember{})
|
||||
if count <= 1 {
|
||||
jsonError(w, "cannot remove the last owner", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
}
|
||||
h.db.ID(member.ID).Delete(&models.WorkspaceMember{}) //nolint:errcheck
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
func (h *WorkspaceHandler) resolveWorkspace(w http.ResponseWriter, r *http.Request) (*models.Workspace, string, bool) {
|
||||
handle := chi.URLParam(r, "handle")
|
||||
var ws models.Workspace
|
||||
if found, _ := h.db.Where("handle = ?", handle).Get(&ws); !found {
|
||||
jsonError(w, "workspace not found", http.StatusNotFound)
|
||||
return nil, "", false
|
||||
}
|
||||
userID, _ := middleware.UserIDFromContext(r.Context())
|
||||
var member models.WorkspaceMember
|
||||
myRole := ""
|
||||
if found, _ := h.db.Where("workspace_id = ? AND user_id = ?", ws.ID, userID).Get(&member); found {
|
||||
myRole = string(member.Role)
|
||||
}
|
||||
return &ws, myRole, true
|
||||
}
|
||||
|
||||
// diskPathForWorkspaceRepo returns the on-disk bare repo path for workspace-owned repos.
|
||||
func diskPathForWorkspaceRepo(repoRoot string, workspaceID int64, repoName string) string {
|
||||
return filepath.Join(repoRoot, "ws_"+strconv.FormatInt(workspaceID, 10), repoName+".git")
|
||||
}
|
||||
|
||||
func isValidHandle(h string) bool {
|
||||
if len(h) == 0 || len(h) > 64 {
|
||||
return false
|
||||
}
|
||||
for _, c := range h {
|
||||
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
|
||||
(c >= '0' && c <= '9') || c == '-' || c == '_') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user