You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airavata.apache.org by ya...@apache.org on 2026/10/08 19:42:26 UTC

(airavata-custos) 01/02: Admin editing for Custos-origin projects; externally managed projects stay read-only over HTTP

This is an automated email from the ASF dual-hosted git repository.

yasithdev pushed a commit to branch amie-cr-fixes
in repository https://gitbox.apache.org/repos/asf/airavata-custos.git

commit c63db32b03d34b68a137462091047770201574ae
Author: Yasith Jayawardana <ya...@icloud.com>
AuthorDate: Wed Oct 7 17:14:51 2026 -0400

    Admin editing for Custos-origin projects; externally managed projects stay read-only over HTTP
---
 api/core.openapi.yaml                              |  79 +++++++++++++
 internal/server/admin_project_integration_test.go  | 127 +++++++++++++++++++++
 .../server/membership_scope_integration_test.go    |   5 +-
 internal/server/project.go                         |  70 +++++++++++-
 internal/server/server.go                          |   3 +
 .../store/compute_allocation_membership_store.go   |  14 ++-
 pkg/common/support.go                              |   2 +-
 pkg/models/project.go                              |   2 +
 pkg/service/compute_allocation.go                  |   8 +-
 pkg/service/compute_allocation_change_request.go   |   8 ++
 .../compute_allocation_change_request_event.go     |   9 +-
 pkg/service/compute_allocation_diff.go             |  16 ++-
 pkg/service/compute_allocation_membership.go       |  11 ++
 ...pute_allocation_membership_resource_override.go |  32 ++++--
 pkg/service/compute_allocation_resource_mapping.go |  32 ++++--
 pkg/service/compute_allocation_usage.go            |  12 +-
 pkg/service/errors.go                              |   9 +-
 pkg/service/project.go                             |  81 +++++++++++++
 pkg/service/project_membership.go                  |   3 +
 19 files changed, 473 insertions(+), 50 deletions(-)

diff --git a/api/core.openapi.yaml b/api/core.openapi.yaml
index 54dfd5baa..a0b96e21c 100644
--- a/api/core.openapi.yaml
+++ b/api/core.openapi.yaml
@@ -3474,6 +3474,21 @@ paths:
       tags:
       - Projects
   /projects/{id}:
+    delete:
+      parameters:
+      - description: Project ID
+        in: path
+        name: id
+        required: true
+        type: string
+      responses:
+        "204":
+          description: No Content
+      security:
+      - BearerAuth: []
+      summary: Delete a project without allocations
+      tags:
+      - Projects
     get:
       description: Callers without the projects read privilege only see projects they
         participate in; others return 404.
@@ -3509,6 +3524,38 @@ paths:
       summary: Get a project by ID
       tags:
       - Projects
+    put:
+      consumes:
+      - application/json
+      parameters:
+      - description: Project ID
+        in: path
+        name: id
+        required: true
+        type: string
+      - description: Fields to change
+        in: body
+        name: request
+        required: true
+        schema:
+          properties:
+            project_pi_id:
+              type: string
+            title:
+              type: string
+          type: object
+      produces:
+      - application/json
+      responses:
+        "200":
+          description: OK
+          schema:
+            $ref: '#/definitions/Project'
+      security:
+      - BearerAuth: []
+      summary: Update a project
+      tags:
+      - Projects
   /projects/{id}/members:
     get:
       parameters:
@@ -3538,6 +3585,38 @@ paths:
       summary: List project members (one row per distinct user, with allocations)
       tags:
       - Projects
+  /projects/{id}/members/{userId}:
+    put:
+      consumes:
+      - application/json
+      parameters:
+      - description: Project ID
+        in: path
+        name: id
+        required: true
+        type: string
+      - description: User ID
+        in: path
+        name: userId
+        required: true
+        type: string
+      - description: Role
+        in: body
+        name: request
+        required: true
+        schema:
+          properties:
+            role:
+              type: string
+          type: object
+      responses:
+        "204":
+          description: No Content
+      security:
+      - BearerAuth: []
+      summary: Set a project member's role; MEMBER removes the role
+      tags:
+      - Projects
   /projects/{id}/status:
     put:
       consumes:
diff --git a/internal/server/admin_project_integration_test.go b/internal/server/admin_project_integration_test.go
new file mode 100644
index 000000000..fa4f2c011
--- /dev/null
+++ b/internal/server/admin_project_integration_test.go
@@ -0,0 +1,127 @@
+//go:build integration
+
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package server
+
+import (
+	"bytes"
+	"encoding/json"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+
+	"github.com/apache/airavata-custos/pkg/models"
+	"github.com/apache/airavata-custos/pkg/service"
+)
+
+func doWrite(t *testing.T, srv *Server, method, path string, body any) *httptest.ResponseRecorder {
+	t.Helper()
+	raw, _ := json.Marshal(body)
+	rr := httptest.NewRecorder()
+	srv.ServeHTTP(rr, withTestCaller(httptest.NewRequest(method, path, bytes.NewReader(raw)), "admin", models.ProjectsWrite, models.ProjectsRead, models.AllocationsWrite))
+	return rr
+}
+
+func projectRoles(t *testing.T, srv *Server, projectID string) map[string]string {
+	t.Helper()
+	var rows []ProjectMemberResponse
+	_ = json.NewDecoder(doGet(t, srv, "/projects/"+projectID+"/members", "admin", models.ProjectsRead).Body).Decode(&rows)
+	roles := map[string]string{}
+	for _, r := range rows {
+		roles[r.UserID] = r.Role
+	}
+	return roles
+}
+
+func TestAdminProject_CreateAssignRoleAndChangePI(t *testing.T) {
+	database, svc, srv := setupTestStack(t)
+	f := seedScopedFixtures(t, database, svc)
+	newPIID := seedUser(t, database, "admin.new.pi@example.edu")
+
+	rr := doWrite(t, srv, http.MethodPost, "/projects", map[string]string{"title": "Admin Project", "project_pi_id": f.piID})
+	var created models.Project
+	_ = json.NewDecoder(rr.Body).Decode(&created)
+	if rr.Code != http.StatusCreated || created.Origination != models.ProjectOriginationCustos {
+		t.Fatalf("create: %d %+v", rr.Code, created)
+	}
+	if roles := projectRoles(t, srv, created.ID); len(roles) != 1 || roles[f.piID] != "PI" {
+		t.Fatalf("created project roles: %v", roles)
+	}
+
+	path := "/projects/" + f.projectA.ID
+	if rr := doWrite(t, srv, http.MethodPut, path+"/members/"+newPIID, map[string]string{"role": "CO_PI"}); rr.Code != http.StatusNoContent {
+		t.Fatalf("assign role: %d %s", rr.Code, rr.Body.String())
+	}
+	if roles := projectRoles(t, srv, f.projectA.ID); roles[newPIID] != "CO_PI" {
+		t.Fatalf("assigned role: %v", roles)
+	}
+
+	if _, err := svc.CreateComputeAllocationMembership(t.Context(), &models.ComputeAllocationMembership{
+		ComputeAllocationID: f.allocA.ID, UserID: f.piID,
+	}); err != nil {
+		t.Fatalf("seed PI membership: %v", err)
+	}
+	if rr := doWrite(t, srv, http.MethodPut, path, map[string]string{"project_pi_id": newPIID}); rr.Code != http.StatusOK {
+		t.Fatalf("change PI: %d %s", rr.Code, rr.Body.String())
+	}
+	if roles := projectRoles(t, srv, f.projectA.ID); roles[newPIID] != "PI" || roles[f.piID] != "MEMBER" {
+		t.Fatalf("roles after PI change: %v", roles)
+	}
+
+	if rr := doWrite(t, srv, http.MethodDelete, path, nil); rr.Code != http.StatusBadRequest {
+		t.Fatalf("delete with allocations: %d %s", rr.Code, rr.Body.String())
+	}
+	if rr := doWrite(t, srv, http.MethodDelete, "/projects/"+created.ID, nil); rr.Code != http.StatusNoContent {
+		t.Fatalf("delete: %d %s", rr.Code, rr.Body.String())
+	}
+}
+
+func TestAccessProject_ReadOnlyOverHTTP(t *testing.T) {
+	database, svc, srv := setupTestStack(t)
+	f := seedScopedFixtures(t, database, svc)
+
+	cr, err := svc.CreateComputeAllocationChangeRequest(t.Context(), &models.ComputeAllocationChangeRequest{
+		ComputeAllocationID: f.allocB.ID, RequesterID: f.piID,
+	})
+	if err != nil {
+		t.Fatalf("connector change request: %v", err)
+	}
+
+	members := "/projects/" + f.projectB.ID + "/members/"
+	for _, c := range []struct {
+		method, path string
+		body         any
+	}{
+		{http.MethodPut, "/projects/" + f.projectB.ID + "/status", map[string]string{"status": "INACTIVE"}},
+		{http.MethodDelete, "/projects/" + f.projectB.ID, nil},
+		{http.MethodPut, members + f.memberID, map[string]string{"role": "PI"}},
+		{http.MethodPut, members + f.memberID, map[string]string{"role": "MEMBER"}},
+		{http.MethodPut, members + f.memberID, map[string]string{"role": "BOGUS"}},
+		{http.MethodPost, "/compute-allocation-memberships", map[string]string{"compute_allocation_id": f.allocB.ID, "user_id": f.piID}},
+		{http.MethodPost, "/compute-allocation-change-requests", map[string]string{"compute_allocation_id": f.allocB.ID, "requester_id": f.piID}},
+		{http.MethodPost, "/compute-allocation-change-request-events", map[string]string{"compute_allocation_change_request_id": cr.ID}},
+		{http.MethodPost, "/compute-allocation-diffs", map[string]string{"compute_allocation_id": f.allocB.ID}},
+		{http.MethodPost, "/compute-allocation-usages", map[string]any{"compute_allocation_id": f.allocB.ID, "used_su_amount": -1}},
+	} {
+		if rr := doWrite(t, srv, c.method, c.path, c.body); rr.Code != http.StatusConflict || !strings.Contains(rr.Body.String(), service.ErrExternalManaged.Error()) {
+			t.Errorf("%s %s %v: %d %s", c.method, c.path, c.body, rr.Code, rr.Body.String())
+		}
+	}
+}
diff --git a/internal/server/membership_scope_integration_test.go b/internal/server/membership_scope_integration_test.go
index 8f698633e..dadb65f75 100644
--- a/internal/server/membership_scope_integration_test.go
+++ b/internal/server/membership_scope_integration_test.go
@@ -49,6 +49,7 @@ func seedScopedFixtures(t *testing.T, database *sqlx.DB, svc *service.Service) s
 	suffix := time.Now().UnixNano()
 	memberID := seedUser(t, database, fmt.Sprintf("scope.member+%d@example.edu", suffix))
 	piID := seedUser(t, database, fmt.Sprintf("scope.pi+%d@example.edu", suffix))
+	otherPIID := seedUser(t, database, fmt.Sprintf("scope.pi.b+%d@example.edu", suffix))
 
 	cluster, err := svc.CreateComputeCluster(t.Context(), &models.ComputeCluster{
 		Name: fmt.Sprintf("scope-cluster-%d", suffix),
@@ -58,13 +59,13 @@ func seedScopedFixtures(t *testing.T, database *sqlx.DB, svc *service.Service) s
 	}
 
 	projectA, err := svc.CreateProject(t.Context(), &models.Project{
-		Title: fmt.Sprintf("Scope Project A %d", suffix), ProjectPIID: piID,
+		Title: fmt.Sprintf("Scope Project A %d", suffix), ProjectPIID: piID, Origination: models.ProjectOriginationCustos,
 	})
 	if err != nil {
 		t.Fatalf("seed project A: %v", err)
 	}
 	projectB, err := svc.CreateProject(t.Context(), &models.Project{
-		Title: fmt.Sprintf("Scope Project B %d", suffix), ProjectPIID: piID,
+		Title: fmt.Sprintf("Scope Project B %d", suffix), ProjectPIID: otherPIID, Origination: "access",
 	})
 	if err != nil {
 		t.Fatalf("seed project B: %v", err)
diff --git a/internal/server/project.go b/internal/server/project.go
index 90ae002e8..fd8c70198 100644
--- a/internal/server/project.go
+++ b/internal/server/project.go
@@ -42,6 +42,7 @@ func (s *Server) createProject(w http.ResponseWriter, r *http.Request) {
 		common.WriteError(w, http.StatusBadRequest, err)
 		return
 	}
+	p.Origination = models.ProjectOriginationCustos
 	created, err := s.svc.CreateProject(r.Context(), &p)
 	if err != nil {
 		common.WriteServiceError(w, err)
@@ -105,6 +106,46 @@ func (s *Server) updateProjectStatus(w http.ResponseWriter, r *http.Request) {
 	common.WriteJSON(w, http.StatusOK, p)
 }
 
+// @Summary	Update a project
+// @Tags	Projects
+// @Security	BearerAuth
+// @Accept	json
+// @Produce	json
+// @Param	id	path	string	true	"Project ID"
+// @Param	request	body	object{title=string,project_pi_id=string}	true	"Fields to change"
+// @Success	200	{object}	models.Project
+// @Router	/projects/{id} [put]
+func (s *Server) updateProject(w http.ResponseWriter, r *http.Request) {
+	var req struct {
+		Title       string `json:"title"`
+		ProjectPIID string `json:"project_pi_id"`
+	}
+	if err := common.DecodeJSON(r, &req); err != nil {
+		common.WriteError(w, http.StatusBadRequest, err)
+		return
+	}
+	p := models.Project{ID: r.PathValue("id"), Title: req.Title, ProjectPIID: req.ProjectPIID}
+	if err := s.svc.UpdateProject(r.Context(), &p); err != nil {
+		common.WriteServiceError(w, err)
+		return
+	}
+	common.WriteJSON(w, http.StatusOK, p)
+}
+
+// @Summary	Delete a project without allocations
+// @Tags	Projects
+// @Security	BearerAuth
+// @Param	id	path	string	true	"Project ID"
+// @Success	204	"No Content"
+// @Router	/projects/{id} [delete]
+func (s *Server) deleteProject(w http.ResponseWriter, r *http.Request) {
+	if err := s.svc.DeleteProject(r.Context(), r.PathValue("id")); err != nil {
+		common.WriteServiceError(w, err)
+		return
+	}
+	w.WriteHeader(http.StatusNoContent)
+}
+
 // @Summary	List projects (filtered + paginated, PI joined)
 // @Description	Callers without the projects read privilege get only the projects they participate in; filters and pagination apply to privileged callers only.
 // @Tags	Projects
@@ -183,10 +224,13 @@ func (s *Server) listProjectMembers(w http.ResponseWriter, r *http.Request) {
 	for _, m := range rows {
 		agg, ok := byUser[m.UserID]
 		if !ok {
-			agg = &aggregate{base: m}
+			agg = &aggregate{base: m, allocations: []ProjectMemberAllocationRef{}}
 			byUser[m.UserID] = agg
 			order = append(order, m.UserID)
 		}
+		if m.ComputeAllocationID == "" {
+			continue
+		}
 		agg.allocations = append(agg.allocations, ProjectMemberAllocationRef{
 			ID:   m.ComputeAllocationID,
 			Name: m.AllocationName,
@@ -211,3 +255,27 @@ func (s *Server) listProjectMembers(w http.ResponseWriter, r *http.Request) {
 	}
 	common.WriteJSON(w, http.StatusOK, out)
 }
+
+// @Summary	Set a project member's role; MEMBER removes the role
+// @Tags	Projects
+// @Security	BearerAuth
+// @Accept	json
+// @Param	id	path	string	true	"Project ID"
+// @Param	userId	path	string	true	"User ID"
+// @Param	request	body	object{role=string}	true	"Role"
+// @Success	204	"No Content"
+// @Router	/projects/{id}/members/{userId} [put]
+func (s *Server) updateProjectMember(w http.ResponseWriter, r *http.Request) {
+	var req struct {
+		Role string `json:"role"`
+	}
+	if err := common.DecodeJSON(r, &req); err != nil {
+		common.WriteError(w, http.StatusBadRequest, err)
+		return
+	}
+	if err := s.svc.EnsureProjectMembership(r.Context(), r.PathValue("id"), r.PathValue("userId"), req.Role); err != nil {
+		common.WriteServiceError(w, err)
+		return
+	}
+	w.WriteHeader(http.StatusNoContent)
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index 6ed954037..9cf78be75 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -78,8 +78,11 @@ func (s *Server) routes() {
 	s.router.RequireAuth("GET /projects", s.listProjects)
 	s.router.RequirePrivilege("POST /projects", models.ProjectsWrite, s.createProject)
 	s.router.RequireScoped("GET /projects/{id}", s.canReadProject, s.getProject)
+	s.router.RequirePrivilege("PUT /projects/{id}", models.ProjectsWrite, s.updateProject)
 	s.router.RequirePrivilege("PUT /projects/{id}/status", models.ProjectsWrite, s.updateProjectStatus)
+	s.router.RequirePrivilege("DELETE /projects/{id}", models.ProjectsWrite, s.deleteProject)
 	s.router.RequirePrivilege("GET /projects/{id}/members", models.ProjectsRead, s.listProjectMembers)
+	s.router.RequirePrivilege("PUT /projects/{id}/members/{userId}", models.ProjectsWrite, s.updateProjectMember)
 
 	s.router.RequirePrivilege("POST /compute-clusters", models.ClustersWrite, s.createComputeCluster)
 	s.router.RequirePrivilege("GET /compute-clusters", models.ClustersRead, s.listComputeClusters)
diff --git a/internal/store/compute_allocation_membership_store.go b/internal/store/compute_allocation_membership_store.go
index e183ff96e..890579a4f 100644
--- a/internal/store/compute_allocation_membership_store.go
+++ b/internal/store/compute_allocation_membership_store.go
@@ -203,7 +203,8 @@ func (s *pgComputeAllocationMembershipStore) FindByAllocationWithUser(ctx contex
 
 // FindByProjectWithUser returns every membership across every allocation in
 // the project, joined with the user, the owning allocation name, and the
-// project-level role. Returned rows are ordered by user; callers aggregate it
+// project-level role, plus one allocation-less row per project role holder
+// without a membership. Returned rows are ordered by user; callers aggregate it
 // per-user (collapsing into the response's allocation list).
 func (s *pgComputeAllocationMembershipStore) FindByProjectWithUser(ctx context.Context, projectID string) ([]MembershipWithUser, error) {
 	type row struct {
@@ -227,7 +228,16 @@ func (s *pgComputeAllocationMembershipStore) FindByProjectWithUser(ctx context.C
 		   LEFT JOIN project_memberships pm
 		         ON pm.project_id = ca.project_id AND pm.user_id = m.user_id
 		  WHERE ca.project_id = $1
-		  ORDER BY u.email, ca.name`, projectID)
+		 UNION ALL
+		 SELECT '', '', pm.user_id, pm.added_time, pm.added_time, 'ACTIVE', pm.role,
+		        u.first_name, u.last_name, u.email, ''
+		   FROM project_memberships pm
+		   JOIN users u ON u.id = pm.user_id
+		  WHERE pm.project_id = $1
+		    AND NOT EXISTS (SELECT 1 FROM compute_allocation_memberships m
+		                      JOIN compute_allocations ca ON ca.id = m.compute_allocation_id
+		                     WHERE ca.project_id = $1 AND m.user_id = pm.user_id)
+		  ORDER BY user_email, allocation_name`, projectID)
 	if err != nil {
 		return nil, err
 	}
diff --git a/pkg/common/support.go b/pkg/common/support.go
index d819f2c35..12628d27d 100644
--- a/pkg/common/support.go
+++ b/pkg/common/support.go
@@ -55,7 +55,7 @@ func WriteServiceError(w http.ResponseWriter, err error) {
 	switch {
 	case errors.Is(err, service.ErrNotFound):
 		WriteError(w, http.StatusNotFound, err)
-	case errors.Is(err, service.ErrAlreadyExists):
+	case errors.Is(err, service.ErrAlreadyExists), errors.Is(err, service.ErrPIChange), errors.Is(err, service.ErrExternalManaged):
 		WriteError(w, http.StatusConflict, err)
 	case errors.Is(err, service.ErrInvalidInput):
 		WriteError(w, http.StatusBadRequest, err)
diff --git a/pkg/models/project.go b/pkg/models/project.go
index 9ebecac7c..2dee5ac95 100644
--- a/pkg/models/project.go
+++ b/pkg/models/project.go
@@ -39,6 +39,8 @@ const (
 	ProjectDeleted  ProjectStatus = "DELETED"
 )
 
+const ProjectOriginationCustos = "custos"
+
 type Project struct {
 	ID           string        `json:"id"            db:"id"`
 	OriginatedID string        `json:"originated_id" db:"originated_id"` // The ID of the project in origination. For example: ACCESS Record ID.
diff --git a/pkg/service/compute_allocation.go b/pkg/service/compute_allocation.go
index 588672951..ec7de80e7 100644
--- a/pkg/service/compute_allocation.go
+++ b/pkg/service/compute_allocation.go
@@ -61,9 +61,6 @@ func (s *Service) CreateComputeAllocation(ctx context.Context, alloc *models.Com
 	if alloc == nil {
 		return nil, fmt.Errorf("%w: compute allocation is nil", ErrInvalidInput)
 	}
-	if alloc.Name == "" {
-		return nil, fmt.Errorf("%w: compute allocation name is required", ErrInvalidInput)
-	}
 	if alloc.ProjectID == "" {
 		return nil, fmt.Errorf("%w: project_id is required", ErrInvalidInput)
 	}
@@ -82,6 +79,11 @@ func (s *Service) CreateComputeAllocation(ctx context.Context, alloc *models.Com
 		return nil, fmt.Errorf("lookup project: %w", err)
 	} else if proj == nil {
 		return nil, fmt.Errorf("%w: project %q not found", ErrInvalidInput, alloc.ProjectID)
+	} else if err := requireEditable(ctx, proj); err != nil {
+		return nil, err
+	}
+	if alloc.Name == "" {
+		return nil, fmt.Errorf("%w: compute allocation name is required", ErrInvalidInput)
 	}
 
 	if cluster, err := s.clusters.FindByID(ctx, alloc.ComputeClusterID); err != nil {
diff --git a/pkg/service/compute_allocation_change_request.go b/pkg/service/compute_allocation_change_request.go
index 5f9c4a05e..762a3060d 100644
--- a/pkg/service/compute_allocation_change_request.go
+++ b/pkg/service/compute_allocation_change_request.go
@@ -56,6 +56,8 @@ func (s *Service) CreateComputeAllocationChangeRequest(ctx context.Context, req
 		return nil, fmt.Errorf("lookup compute allocation: %w", err)
 	} else if alloc == nil {
 		return nil, fmt.Errorf("%w: compute allocation %q not found", ErrInvalidInput, req.ComputeAllocationID)
+	} else if err := s.requireEditableProject(ctx, alloc.ProjectID); err != nil {
+		return nil, err
 	}
 
 	if req.ID == "" {
@@ -140,6 +142,9 @@ func (s *Service) UpdateComputeAllocationChangeRequest(ctx context.Context, req
 	if existing == nil {
 		return nil, ErrNotFound
 	}
+	if err := s.requireEditableAllocation(ctx, existing.ComputeAllocationID); err != nil {
+		return nil, err
+	}
 	if req.ComputeAllocationID == "" {
 		req.ComputeAllocationID = existing.ComputeAllocationID
 	}
@@ -212,6 +217,9 @@ func (s *Service) DeleteComputeAllocationChangeRequest(ctx context.Context, id s
 	if existing == nil {
 		return ErrNotFound
 	}
+	if err := s.requireEditableAllocation(ctx, existing.ComputeAllocationID); err != nil {
+		return err
+	}
 	if err := s.inTx(ctx, func(tx *sql.Tx) error {
 		if err := s.changeEvents.Create(ctx, tx, &models.ComputeAllocationChangeRequestEvent{
 			ID:                               newID(),
diff --git a/pkg/service/compute_allocation_change_request_event.go b/pkg/service/compute_allocation_change_request_event.go
index 7dd277796..b7360bad6 100644
--- a/pkg/service/compute_allocation_change_request_event.go
+++ b/pkg/service/compute_allocation_change_request_event.go
@@ -36,14 +36,15 @@ func (s *Service) CreateComputeAllocationChangeRequestEvent(ctx context.Context,
 	if evt.ComputeAllocationChangeRequestID == "" {
 		return nil, fmt.Errorf("%w: compute_allocation_change_request_id is required", ErrInvalidInput)
 	}
-	if evt.EventType == "" {
-		return nil, fmt.Errorf("%w: event_type is required", ErrInvalidInput)
-	}
-
 	if cr, err := s.changeRequests.FindByID(ctx, evt.ComputeAllocationChangeRequestID); err != nil {
 		return nil, fmt.Errorf("lookup compute allocation change request: %w", err)
 	} else if cr == nil {
 		return nil, fmt.Errorf("%w: compute allocation change request %q not found", ErrInvalidInput, evt.ComputeAllocationChangeRequestID)
+	} else if err := s.requireEditableAllocation(ctx, cr.ComputeAllocationID); err != nil {
+		return nil, err
+	}
+	if evt.EventType == "" {
+		return nil, fmt.Errorf("%w: event_type is required", ErrInvalidInput)
 	}
 
 	if evt.ID == "" {
diff --git a/pkg/service/compute_allocation_diff.go b/pkg/service/compute_allocation_diff.go
index 881d0cef5..98c9d16ea 100644
--- a/pkg/service/compute_allocation_diff.go
+++ b/pkg/service/compute_allocation_diff.go
@@ -37,6 +37,13 @@ func (s *Service) CreateComputeAllocationDiff(ctx context.Context, diff *models.
 	if diff.ComputeAllocationID == "" {
 		return nil, fmt.Errorf("%w: compute_allocation_id is required", ErrInvalidInput)
 	}
+	if alloc, err := s.allocs.FindByID(ctx, diff.ComputeAllocationID); err != nil {
+		return nil, fmt.Errorf("lookup compute allocation: %w", err)
+	} else if alloc == nil {
+		return nil, fmt.Errorf("%w: compute allocation %q not found", ErrInvalidInput, diff.ComputeAllocationID)
+	} else if err := s.requireEditableProject(ctx, alloc.ProjectID); err != nil {
+		return nil, err
+	}
 	if diff.DiffType == "" {
 		return nil, fmt.Errorf("%w: diff_type is required", ErrInvalidInput)
 	}
@@ -44,12 +51,6 @@ func (s *Service) CreateComputeAllocationDiff(ctx context.Context, diff *models.
 		return nil, fmt.Errorf("%w: status is required", ErrInvalidInput)
 	}
 
-	if alloc, err := s.allocs.FindByID(ctx, diff.ComputeAllocationID); err != nil {
-		return nil, fmt.Errorf("lookup compute allocation: %w", err)
-	} else if alloc == nil {
-		return nil, fmt.Errorf("%w: compute allocation %q not found", ErrInvalidInput, diff.ComputeAllocationID)
-	}
-
 	if diff.ID == "" {
 		diff.ID = newID()
 	}
@@ -124,6 +125,9 @@ func (s *Service) DeleteComputeAllocationDiff(ctx context.Context, id string) er
 	if diff == nil {
 		return ErrNotFound
 	}
+	if err := s.requireEditableAllocation(ctx, diff.ComputeAllocationID); err != nil {
+		return err
+	}
 	if err := s.inTx(ctx, func(tx *sql.Tx) error {
 		if err := s.allocDiffs.Delete(ctx, tx, id); err != nil {
 			return err
diff --git a/pkg/service/compute_allocation_membership.go b/pkg/service/compute_allocation_membership.go
index 33cf4d274..965b2b5db 100644
--- a/pkg/service/compute_allocation_membership.go
+++ b/pkg/service/compute_allocation_membership.go
@@ -46,6 +46,8 @@ func (s *Service) CreateComputeAllocationMembership(ctx context.Context, m *mode
 		return nil, fmt.Errorf("lookup compute allocation: %w", err)
 	} else if alloc == nil {
 		return nil, fmt.Errorf("%w: compute allocation %q not found", ErrInvalidInput, m.ComputeAllocationID)
+	} else if err := s.requireEditableProject(ctx, alloc.ProjectID); err != nil {
+		return nil, err
 	}
 	if u, err := s.users.FindByID(ctx, m.UserID); err != nil {
 		return nil, fmt.Errorf("lookup user: %w", err)
@@ -155,6 +157,9 @@ func (s *Service) UpdateComputeAllocationMembership(ctx context.Context, m *mode
 	if existing == nil {
 		return nil, ErrNotFound
 	}
+	if err := s.requireEditableAllocation(ctx, existing.ComputeAllocationID); err != nil {
+		return nil, err
+	}
 	if m.ComputeAllocationID == "" {
 		m.ComputeAllocationID = existing.ComputeAllocationID
 	}
@@ -198,6 +203,9 @@ func (s *Service) UpdateMembershipStatus(ctx context.Context, id string, status
 	if existing == nil {
 		return nil, ErrNotFound
 	}
+	if err := s.requireEditableAllocation(ctx, existing.ComputeAllocationID); err != nil {
+		return nil, err
+	}
 	existing.MembershipStatus = status
 	if err := s.inTx(ctx, func(tx *sql.Tx) error {
 		if err := s.memberships.Update(ctx, tx, existing); err != nil {
@@ -222,6 +230,9 @@ func (s *Service) DeleteComputeAllocationMembership(ctx context.Context, id stri
 	if existing == nil {
 		return ErrNotFound
 	}
+	if err := s.requireEditableAllocation(ctx, existing.ComputeAllocationID); err != nil {
+		return err
+	}
 	if err := s.inTx(ctx, func(tx *sql.Tx) error {
 		if err := s.memberships.Delete(ctx, tx, id); err != nil {
 			return err
diff --git a/pkg/service/compute_allocation_membership_resource_override.go b/pkg/service/compute_allocation_membership_resource_override.go
index 437e8449d..e4489febc 100644
--- a/pkg/service/compute_allocation_membership_resource_override.go
+++ b/pkg/service/compute_allocation_membership_resource_override.go
@@ -40,18 +40,20 @@ func (s *Service) CreateComputeAllocationMembershipResourceOverride(ctx context.
 	if o.ComputeAllocationResourceID == "" {
 		return nil, fmt.Errorf("%w: compute_allocation_resource_id is required", ErrInvalidInput)
 	}
-	if o.OverrideResourceAmount < 0 {
-		return nil, fmt.Errorf("%w: override_resource_amount must be non-negative", ErrInvalidInput)
-	}
-	if o.OverrideResourceTime < 0 {
-		return nil, fmt.Errorf("%w: override_resource_time must be non-negative", ErrInvalidInput)
-	}
 
 	if m, err := s.memberships.FindByID(ctx, o.ComputeAllocationMembershipID); err != nil {
 		return nil, fmt.Errorf("lookup compute allocation membership: %w", err)
 	} else if m == nil {
 		return nil, fmt.Errorf("%w: compute allocation membership %q not found",
 			ErrInvalidInput, o.ComputeAllocationMembershipID)
+	} else if err := s.requireEditableAllocation(ctx, m.ComputeAllocationID); err != nil {
+		return nil, err
+	}
+	if o.OverrideResourceAmount < 0 {
+		return nil, fmt.Errorf("%w: override_resource_amount must be non-negative", ErrInvalidInput)
+	}
+	if o.OverrideResourceTime < 0 {
+		return nil, fmt.Errorf("%w: override_resource_time must be non-negative", ErrInvalidInput)
 	}
 	if r, err := s.resources.FindByID(ctx, o.ComputeAllocationResourceID); err != nil {
 		return nil, fmt.Errorf("lookup compute allocation resource: %w", err)
@@ -145,12 +147,6 @@ func (s *Service) UpdateComputeAllocationMembershipResourceOverride(ctx context.
 	if o == nil || o.ID == "" {
 		return nil, fmt.Errorf("%w: membership resource override id is required", ErrInvalidInput)
 	}
-	if o.OverrideResourceAmount < 0 {
-		return nil, fmt.Errorf("%w: override_resource_amount must be non-negative", ErrInvalidInput)
-	}
-	if o.OverrideResourceTime < 0 {
-		return nil, fmt.Errorf("%w: override_resource_time must be non-negative", ErrInvalidInput)
-	}
 	existing, err := s.membershipOverrides.FindByID(ctx, o.ID)
 	if err != nil {
 		return nil, fmt.Errorf("lookup membership resource override: %w", err)
@@ -158,6 +154,15 @@ func (s *Service) UpdateComputeAllocationMembershipResourceOverride(ctx context.
 	if existing == nil {
 		return nil, ErrNotFound
 	}
+	if err := s.requireEditableMembership(ctx, existing.ComputeAllocationMembershipID); err != nil {
+		return nil, err
+	}
+	if o.OverrideResourceAmount < 0 {
+		return nil, fmt.Errorf("%w: override_resource_amount must be non-negative", ErrInvalidInput)
+	}
+	if o.OverrideResourceTime < 0 {
+		return nil, fmt.Errorf("%w: override_resource_time must be non-negative", ErrInvalidInput)
+	}
 	if o.ComputeAllocationMembershipID == "" {
 		o.ComputeAllocationMembershipID = existing.ComputeAllocationMembershipID
 	}
@@ -188,6 +193,9 @@ func (s *Service) DeleteComputeAllocationMembershipResourceOverride(ctx context.
 	if existing == nil {
 		return ErrNotFound
 	}
+	if err := s.requireEditableMembership(ctx, existing.ComputeAllocationMembershipID); err != nil {
+		return err
+	}
 	if err := s.inTx(ctx, func(tx *sql.Tx) error {
 		if err := s.membershipOverrides.Delete(ctx, tx, id); err != nil {
 			return err
diff --git a/pkg/service/compute_allocation_resource_mapping.go b/pkg/service/compute_allocation_resource_mapping.go
index acef8f82f..18c22523c 100644
--- a/pkg/service/compute_allocation_resource_mapping.go
+++ b/pkg/service/compute_allocation_resource_mapping.go
@@ -38,17 +38,19 @@ func (s *Service) AttachResourceToAllocation(ctx context.Context, allocationID,
 	if resourceID == "" {
 		return nil, fmt.Errorf("%w: compute_allocation_resource_id is required", ErrInvalidInput)
 	}
-	if resourceAmount < 0 {
-		return nil, fmt.Errorf("%w: resource_amount must be non-negative", ErrInvalidInput)
-	}
-	if resourceTime < 0 {
-		return nil, fmt.Errorf("%w: resource_time must be non-negative", ErrInvalidInput)
-	}
 
 	if alloc, err := s.allocs.FindByID(ctx, allocationID); err != nil {
 		return nil, fmt.Errorf("lookup compute allocation: %w", err)
 	} else if alloc == nil {
 		return nil, fmt.Errorf("%w: compute allocation %q not found", ErrInvalidInput, allocationID)
+	} else if err := s.requireEditableProject(ctx, alloc.ProjectID); err != nil {
+		return nil, err
+	}
+	if resourceAmount < 0 {
+		return nil, fmt.Errorf("%w: resource_amount must be non-negative", ErrInvalidInput)
+	}
+	if resourceTime < 0 {
+		return nil, fmt.Errorf("%w: resource_time must be non-negative", ErrInvalidInput)
 	}
 
 	if res, err := s.resources.FindByID(ctx, resourceID); err != nil {
@@ -87,12 +89,6 @@ func (s *Service) UpdateAllocationResourceMapping(ctx context.Context, allocatio
 	if allocationID == "" || resourceID == "" {
 		return nil, fmt.Errorf("%w: allocation and resource ids are required", ErrInvalidInput)
 	}
-	if resourceAmount < 0 {
-		return nil, fmt.Errorf("%w: resource_amount must be non-negative", ErrInvalidInput)
-	}
-	if resourceTime < 0 {
-		return nil, fmt.Errorf("%w: resource_time must be non-negative", ErrInvalidInput)
-	}
 
 	existing, err := s.resourceMappings.FindByPair(ctx, allocationID, resourceID)
 	if err != nil {
@@ -101,6 +97,15 @@ func (s *Service) UpdateAllocationResourceMapping(ctx context.Context, allocatio
 	if existing == nil {
 		return nil, ErrNotFound
 	}
+	if err := s.requireEditableAllocation(ctx, allocationID); err != nil {
+		return nil, err
+	}
+	if resourceAmount < 0 {
+		return nil, fmt.Errorf("%w: resource_amount must be non-negative", ErrInvalidInput)
+	}
+	if resourceTime < 0 {
+		return nil, fmt.Errorf("%w: resource_time must be non-negative", ErrInvalidInput)
+	}
 
 	existing.ResourceAmount = resourceAmount
 	existing.ResourceTime = resourceTime
@@ -130,6 +135,9 @@ func (s *Service) DetachResourceFromAllocation(ctx context.Context, allocationID
 	if existing == nil {
 		return ErrNotFound
 	}
+	if err := s.requireEditableAllocation(ctx, allocationID); err != nil {
+		return err
+	}
 
 	if err := s.inTx(ctx, func(tx *sql.Tx) error {
 		if err := s.resourceMappings.DeleteByPair(ctx, tx, allocationID, resourceID); err != nil {
diff --git a/pkg/service/compute_allocation_usage.go b/pkg/service/compute_allocation_usage.go
index bd5a8d93d..9a0dda03e 100644
--- a/pkg/service/compute_allocation_usage.go
+++ b/pkg/service/compute_allocation_usage.go
@@ -37,14 +37,15 @@ func (s *Service) CreateComputeAllocationUsage(ctx context.Context, u *models.Co
 	if u.ComputeAllocationID == "" {
 		return nil, fmt.Errorf("%w: compute_allocation_id is required", ErrInvalidInput)
 	}
-	if u.UsedRawAmount < 0 || u.UsedSUAmount < 0 {
-		return nil, fmt.Errorf("%w: used_raw_amount and used_su_amount must be non-negative", ErrInvalidInput)
-	}
-
 	if alloc, err := s.allocs.FindByID(ctx, u.ComputeAllocationID); err != nil {
 		return nil, fmt.Errorf("lookup compute allocation: %w", err)
 	} else if alloc == nil {
 		return nil, fmt.Errorf("%w: compute allocation %q not found", ErrInvalidInput, u.ComputeAllocationID)
+	} else if err := s.requireEditableProject(ctx, alloc.ProjectID); err != nil {
+		return nil, err
+	}
+	if u.UsedRawAmount < 0 || u.UsedSUAmount < 0 {
+		return nil, fmt.Errorf("%w: used_raw_amount and used_su_amount must be non-negative", ErrInvalidInput)
 	}
 	if u.ComputeAllocationResourceID != "" {
 		if r, err := s.resources.FindByID(ctx, u.ComputeAllocationResourceID); err != nil {
@@ -181,6 +182,9 @@ func (s *Service) DeleteComputeAllocationUsage(ctx context.Context, id string) e
 	if existing == nil {
 		return ErrNotFound
 	}
+	if err := s.requireEditableAllocation(ctx, existing.ComputeAllocationID); err != nil {
+		return err
+	}
 	if err := s.inTx(ctx, func(tx *sql.Tx) error {
 		return s.usages.Delete(ctx, tx, id)
 	}); err != nil {
diff --git a/pkg/service/errors.go b/pkg/service/errors.go
index c558faafe..6f4f8ab4a 100644
--- a/pkg/service/errors.go
+++ b/pkg/service/errors.go
@@ -33,7 +33,10 @@ var ErrAlreadyExists = errors.New("record already exists")
 // ErrInvalidInput is returned when required fields are missing or invalid.
 var ErrInvalidInput = errors.New("invalid input")
 
-// ErrPIChange is returned when an operation would change a project's PI to a
-// different user. PI is set once at project creation and cannot be reassigned
-// through normal flows.
+// ErrPIChange is returned when membership sync would change or demote a
+// project's PI; only UpdateProject reassigns the PI.
 var ErrPIChange = errors.New("project PI cannot be changed")
+
+// ErrExternalManaged is returned when an HTTP caller writes to a project that
+// originated outside Custos; only connectors write those.
+var ErrExternalManaged = errors.New("project is managed externally")
diff --git a/pkg/service/project.go b/pkg/service/project.go
index e385ebea2..c15b12b56 100644
--- a/pkg/service/project.go
+++ b/pkg/service/project.go
@@ -24,6 +24,7 @@ import (
 
 	"github.com/apache/airavata-custos/internal/store"
 	"github.com/apache/airavata-custos/pkg/events"
+	"github.com/apache/airavata-custos/pkg/identity"
 	"github.com/apache/airavata-custos/pkg/models"
 )
 
@@ -68,6 +69,11 @@ func (s *Service) CreateProject(ctx context.Context, project *models.Project) (*
 		if err := s.projs.Create(ctx, tx, project); err != nil {
 			return err
 		}
+		if err := s.projMemberships.Create(ctx, tx, &models.ProjectMembership{
+			ProjectID: project.ID, UserID: project.ProjectPIID, Role: models.ProjectRolePI, AddedTime: nowUTC(),
+		}); err != nil {
+			return err
+		}
 		return s.eventBus.Publish(ctx, tx, events.ProjectCreateEvent, project)
 	}); err != nil {
 		return nil, fmt.Errorf("create project: %w", err)
@@ -181,6 +187,9 @@ func (s *Service) UpdateProject(ctx context.Context, project *models.Project) er
 	if existing == nil {
 		return ErrNotFound
 	}
+	if err := requireEditable(ctx, existing); err != nil {
+		return err
+	}
 	if project.OriginatedID == "" {
 		project.OriginatedID = existing.OriginatedID
 	}
@@ -203,6 +212,19 @@ func (s *Service) UpdateProject(ctx context.Context, project *models.Project) er
 		if err := s.projs.Update(ctx, tx, project); err != nil {
 			return err
 		}
+		if project.ProjectPIID != existing.ProjectPIID {
+			// The new PI's CO_PI or ALLOCATION_MANAGER tag is replaced.
+			for _, userID := range []string{existing.ProjectPIID, project.ProjectPIID} {
+				if err := s.projMemberships.Delete(ctx, tx, project.ID, userID); err != nil {
+					return err
+				}
+			}
+			if err := s.projMemberships.Create(ctx, tx, &models.ProjectMembership{
+				ProjectID: project.ID, UserID: project.ProjectPIID, Role: models.ProjectRolePI, AddedTime: nowUTC(),
+			}); err != nil {
+				return err
+			}
+		}
 		return s.eventBus.Publish(ctx, tx, events.ProjectUpdateEvent, project)
 	}); err != nil {
 		return fmt.Errorf("update project: %w", err)
@@ -226,6 +248,9 @@ func (s *Service) UpdateProjectStatus(ctx context.Context, id string, status mod
 	if existing == nil {
 		return nil, ErrNotFound
 	}
+	if err := requireEditable(ctx, existing); err != nil {
+		return nil, err
+	}
 	existing.Status = status
 	if err := s.inTx(ctx, func(tx *sql.Tx) error {
 		if err := s.projs.UpdateStatus(ctx, tx, id, status); err != nil {
@@ -250,6 +275,14 @@ func (s *Service) DeleteProject(ctx context.Context, id string) error {
 	if project == nil {
 		return ErrNotFound
 	}
+	if err := requireEditable(ctx, project); err != nil {
+		return err
+	}
+	if allocs, err := s.allocs.FindByProject(ctx, id); err != nil {
+		return fmt.Errorf("lookup allocations: %w", err)
+	} else if len(allocs) > 0 {
+		return fmt.Errorf("%w: project %q still has allocations", ErrInvalidInput, id)
+	}
 	if err := s.inTx(ctx, func(tx *sql.Tx) error {
 		if err := s.projs.Delete(ctx, tx, id); err != nil {
 			return err
@@ -260,3 +293,51 @@ func (s *Service) DeleteProject(ctx context.Context, id string) error {
 	}
 	return nil
 }
+
+// requireEditable refuses HTTP callers' writes to externally managed projects;
+// connectors write without a caller.
+func requireEditable(ctx context.Context, p *models.Project) error {
+	if identity.CallerFromContext(ctx) != nil && p.Origination != models.ProjectOriginationCustos {
+		return ErrExternalManaged
+	}
+	return nil
+}
+
+func (s *Service) requireEditableProject(ctx context.Context, projectID string) error {
+	if identity.CallerFromContext(ctx) == nil {
+		return nil
+	}
+	p, err := s.projs.FindByID(ctx, projectID)
+	if err != nil {
+		return fmt.Errorf("lookup project: %w", err)
+	}
+	if p == nil {
+		return ErrNotFound
+	}
+	return requireEditable(ctx, p)
+}
+
+func (s *Service) requireEditableAllocation(ctx context.Context, allocationID string) error {
+	if identity.CallerFromContext(ctx) == nil {
+		return nil
+	}
+	a, err := s.allocs.FindByID(ctx, allocationID)
+	if err != nil {
+		return fmt.Errorf("lookup compute allocation: %w", err)
+	}
+	if a == nil { // usages outlive their allocation
+		return nil
+	}
+	return s.requireEditableProject(ctx, a.ProjectID)
+}
+
+func (s *Service) requireEditableMembership(ctx context.Context, membershipID string) error {
+	if identity.CallerFromContext(ctx) == nil {
+		return nil
+	}
+	m, err := s.memberships.FindByID(ctx, membershipID)
+	if err != nil {
+		return fmt.Errorf("lookup compute allocation membership: %w", err)
+	}
+	return s.requireEditableAllocation(ctx, m.ComputeAllocationID)
+}
diff --git a/pkg/service/project_membership.go b/pkg/service/project_membership.go
index b7abf593c..77999f396 100644
--- a/pkg/service/project_membership.go
+++ b/pkg/service/project_membership.go
@@ -41,6 +41,9 @@ func (s *Service) EnsureProjectMembership(ctx context.Context, projectID, userID
 	if userID == "" {
 		return fmt.Errorf("%w: user_id is required", ErrInvalidInput)
 	}
+	if err := s.requireEditableProject(ctx, projectID); err != nil {
+		return err
+	}
 
 	if role == "MEMBER" || role == "" {
 		existing, err := s.projMemberships.FindByPair(ctx, projectID, userID)