diff --git a/db/task_scope.go b/db/task_scope.go index 5452b884..20392b31 100644 --- a/db/task_scope.go +++ b/db/task_scope.go @@ -2,6 +2,7 @@ package db import ( "database/sql" + "errors" "fmt" "net" "sort" @@ -351,14 +352,34 @@ func scopeRowCovers(existing, cand TaskScope) bool { } // DeleteTaskScope removes a single scope row by id, scoped to the given task. -// Returns whether a row was actually deleted. +// Returns whether a row was actually deleted. Deleting a company grant also +// drops its materialized task_scope_egress entries: leaving them would keep the +// task's egress proxy open after the operator revoked the company. func (s *AssetStore) DeleteTaskScope(taskID, scopeID int64) (bool, error) { - res, err := s.db.Exec(`DELETE FROM task_scope WHERE id=$1 AND task_id=$2`, scopeID, taskID) + tx, err := s.db.Begin() if err != nil { return false, err } - n, _ := res.RowsAffected() - return n > 0, nil + defer func() { _ = tx.Rollback() }() + var kind string + var companyID sql.NullInt64 + err = tx.QueryRow(`DELETE FROM task_scope WHERE id=$1 AND task_id=$2 RETURNING kind, company_id`, scopeID, taskID). + Scan(&kind, &companyID) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + if kind == "company" && companyID.Valid { + if _, err := tx.Exec(`DELETE FROM task_scope_egress WHERE task_id=$1 AND company_id=$2`, taskID, companyID.Int64); err != nil { + return false, err + } + } + if err := tx.Commit(); err != nil { + return false, err + } + return true, nil } // ListTaskScope returns all scope rows for a task. diff --git a/server/sandbox_company_egress_test.go b/server/sandbox_company_egress_test.go index 0e182a28..ad32a2d8 100644 --- a/server/sandbox_company_egress_test.go +++ b/server/sandbox_company_egress_test.go @@ -109,4 +109,27 @@ func TestSandboxCompanyEgressFrozenAtApproval(t *testing.T) { if !scopeHas(domains, approvedDom) || !scopeHas(domains, injectedDom) || !scopeHas(cidrs, approvedCIDR) { t.Fatalf("approval snapshot incomplete: domains=%v cidrs=%v", domains, cidrs) } + + // Removing the company grant revokes the materialized egress, so the proxy + // does not stay open after the operator deletes the scope row. + rows, err := as.ListTaskScope(task2.ID) + if err != nil { + t.Fatalf("ListTaskScope: %v", err) + } + companyScopeID := int64(0) + for _, r := range rows { + if r.Kind == "company" && r.CompanyID != nil && *r.CompanyID == compID { + companyScopeID = r.ID + } + } + if companyScopeID == 0 { + t.Fatal("company scope row not found") + } + if ok, err := as.DeleteTaskScope(task2.ID, companyScopeID); err != nil || !ok { + t.Fatalf("DeleteTaskScope: ok=%v err=%v", ok, err) + } + domains, cidrs = runInfo(t, task2.ID) + if len(domains) != 0 || len(cidrs) != 0 { + t.Fatalf("revoked company grant still grants egress: domains=%v cidrs=%v", domains, cidrs) + } }