Repository navigation
fix(purchases): gate scheduled-purchase management on creator-scope ownership (closes #950) #995
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
cristim
merged 5 commits into
feat/multicloud-web-frontend
from
sec/950-scheduled-purchase-ownership-gate
Jun 6, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c46539f
fix(purchases): gate scheduled-purchase management on creator-scope o…
cristim dd2cc1c
refactor: extract cancelOrRecoverExecution helper to clear gocyclo (#…
cristim 1f66f71
fix(purchases): address CR pass-1 findings on PR #995
cristim 9ef1b43
fix(purchases): stamp creator on scheduled purchases from plan endpoi…
cristim 94326f6
fix(dashboard): gate upcoming-purchase Cancel on creator-scope owners…
cristim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,198 @@ | ||
| /** | ||
| * Issue #950 follow-up: creator-scope ownership gating on the dashboard | ||
| * upcoming-purchases widget's Cancel buttons. | ||
| * | ||
| * The pre-fix dashboard widget rendered a "Cancel" button on every | ||
| * upcoming-purchase card (and a "Cancel Purchase" button in the | ||
| * View Details modal) regardless of who created the underlying | ||
| * execution. Clicking it called DELETE /api/purchases/planned/{id}, | ||
| * which the backend now (correctly) 403s for non-owners after PR #995. | ||
| * The result was a UX hole: the operator sees the button, clicks it, | ||
| * and gets a confusing failure toast. | ||
| * | ||
| * The fix gates both buttons on canCancelUpcomingPurchase(), which | ||
| * mirrors plans.ts's canManageScheduledPurchase: admin / update-any | ||
| * see Cancel on any row; otherwise the row's created_by_user_id must | ||
| * match the current user (legacy NULL-creator rows are out of reach | ||
| * for non-privileged users). | ||
| * | ||
| * These tests drive the real renderUpcomingPurchases pipe via | ||
| * loadDashboard() so the production gate is what's exercised, not a | ||
| * unit shim around the helper. | ||
| */ | ||
|
|
||
| // Chart.js + recommendations + freshness need to be mocked before the | ||
| // dashboard import the same way dashboard.test.ts does. | ||
| const mockShowToast = jest.fn<{ dismiss: () => void }, [unknown]>(() => ({ dismiss: jest.fn() })); | ||
| jest.mock('../toast', () => ({ | ||
| showToast: (opts: unknown) => mockShowToast(opts), | ||
| })); | ||
| jest.mock('../confirmDialog', () => ({ | ||
| confirmDialog: jest.fn(() => Promise.resolve(true)), | ||
| })); | ||
| jest.mock('chart.js', () => { | ||
| const MockChart = jest.fn().mockImplementation(() => ({ destroy: jest.fn() })); | ||
| (MockChart as unknown as { register: jest.Mock }).register = jest.fn(); | ||
| return { Chart: MockChart, registerables: [] }; | ||
| }); | ||
| jest.mock('../recommendations', () => ({ | ||
| groupRecsByCell: jest.fn(() => new Map()), | ||
| pageLevelRange: jest.fn(() => ({ savingsMin: 0, savingsMax: 0, cellCount: 0 })), | ||
| formatSavingsRange: jest.fn((min: number, max: number) => `$${min}-$${max}`), | ||
| triggerAutoRefreshIfStale: jest.fn(() => Promise.resolve()), | ||
| })); | ||
|
|
||
| jest.mock('../api', () => ({ | ||
| getDashboardSummary: jest.fn().mockResolvedValue({ potential_monthly_savings: 0, by_service: {} }), | ||
| getUpcomingPurchases: jest.fn(), | ||
| getPurchaseDetails: jest.fn(), | ||
| cancelPurchase: jest.fn(), | ||
| deletePlannedPurchase: jest.fn().mockResolvedValue({}), | ||
| deletePlan: jest.fn(), | ||
| listAccounts: jest.fn().mockResolvedValue([]), | ||
| getSavingsAnalytics: jest.fn().mockResolvedValue({ data_points: [] }), | ||
| getRecommendations: jest.fn().mockResolvedValue([]), | ||
| })); | ||
|
|
||
| jest.mock('../state', () => ({ | ||
| getCurrentProvider: jest.fn().mockReturnValue(''), | ||
| setCurrentProvider: jest.fn(), | ||
| getCurrentAccountIDs: jest.fn().mockReturnValue([]), | ||
| setCurrentAccountIDs: jest.fn(), | ||
| getSavingsChart: jest.fn().mockReturnValue(null), | ||
| setSavingsChart: jest.fn(), | ||
| subscribeProvider: jest.fn().mockReturnValue(() => {}), | ||
| subscribeAccount: jest.fn().mockReturnValue(() => {}), | ||
| getCurrentUser: jest.fn(), | ||
| })); | ||
|
|
||
| jest.mock('../utils', () => ({ | ||
| formatCurrency: jest.fn((val) => `$${val || 0}`), | ||
| getDateParts: jest.fn(() => ({ day: 15, month: 'Jan' })), | ||
| escapeHtml: jest.fn((str) => str || ''), | ||
| populateAccountFilter: jest.fn(() => Promise.resolve()), | ||
| })); | ||
|
|
||
| import { loadDashboard } from '../dashboard'; | ||
| import * as api from '../api'; | ||
| import * as state from '../state'; | ||
|
|
||
| const CREATOR_ID = 'creator-aaaa'; | ||
| const OTHER_ID = 'other-bbbb'; | ||
| const ADMIN_GROUP = '00000000-0000-5000-8000-000000000001'; | ||
|
|
||
| const ownedPurchase = { | ||
| execution_id: 'exec-1', | ||
| plan_id: 'plan-1', | ||
| plan_name: 'Owned Plan', | ||
| scheduled_date: '2026-06-01', | ||
| provider: 'aws', | ||
| service: 'ec2', | ||
| step_number: 1, | ||
| total_steps: 4, | ||
| estimated_savings: 100, | ||
| created_by_user_id: CREATOR_ID, | ||
| }; | ||
|
|
||
| const legacyPurchase = { | ||
| ...ownedPurchase, | ||
| execution_id: 'exec-legacy', | ||
| created_by_user_id: undefined as string | undefined, | ||
| }; | ||
|
|
||
| type StubUserOpts = { updateAny?: boolean; admin?: boolean; deletePurchases?: boolean }; | ||
| const setUser = (id: string, opts: StubUserOpts = {}) => { | ||
| const effectivePermissions: Array<{ action: string; resource: string }> = []; | ||
| if (opts.admin) { | ||
| effectivePermissions.push({ action: 'admin', resource: '*' }); | ||
| } else if (opts.deletePurchases !== false) { | ||
| // Standard user holds delete:purchases (PR #660 default). | ||
| effectivePermissions.push({ action: 'delete', resource: 'purchases' }); | ||
| } | ||
| if (opts.updateAny) { | ||
| effectivePermissions.push({ action: 'update-any', resource: 'purchases' }); | ||
| } | ||
| (state.getCurrentUser as jest.Mock).mockReturnValue({ | ||
| id, | ||
| email: `${id}@example.com`, | ||
| groups: opts.admin ? [ADMIN_GROUP] : [], | ||
| effectivePermissions, | ||
| }); | ||
| }; | ||
|
|
||
| const setupDom = () => { | ||
| document.body.innerHTML = ` | ||
| <div id="summary"></div> | ||
| <section id="savings-by-service-section"> | ||
| <canvas id="savings-by-service-chart"></canvas> | ||
| <p id="savings-by-service-empty" class="empty hidden"></p> | ||
| </section> | ||
| <div id="upcoming-list"></div> | ||
| `; | ||
| }; | ||
|
|
||
| const cancelBtns = () => | ||
| document.querySelectorAll<HTMLButtonElement>('[data-action="cancel-purchase"]'); | ||
|
|
||
| describe('Dashboard upcoming-purchase ownership gating (issue #950)', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| setupDom(); | ||
| }); | ||
|
|
||
| test('creator sees the Cancel button on their own scheduled purchase', async () => { | ||
| setUser(CREATOR_ID); | ||
| (api.getUpcomingPurchases as jest.Mock).mockResolvedValue({ purchases: [ownedPurchase] }); | ||
| await loadDashboard(); | ||
| expect(cancelBtns()).toHaveLength(1); | ||
| }); | ||
|
|
||
| test('non-creator with the same verbs sees NO Cancel button (the bug)', async () => { | ||
| setUser(OTHER_ID); | ||
| (api.getUpcomingPurchases as jest.Mock).mockResolvedValue({ purchases: [ownedPurchase] }); | ||
| await loadDashboard(); | ||
| expect(cancelBtns()).toHaveLength(0); | ||
| // The card still renders -- the operator sees the row and can click | ||
| // "View Details", which is intentionally unrestricted. | ||
| const viewBtns = document.querySelectorAll<HTMLButtonElement>('[data-action="view-purchase"]'); | ||
| expect(viewBtns).toHaveLength(1); | ||
| }); | ||
|
|
||
| test('update-any holder sees Cancel on another user\'s scheduled purchase', async () => { | ||
| setUser(OTHER_ID, { updateAny: true }); | ||
| (api.getUpcomingPurchases as jest.Mock).mockResolvedValue({ purchases: [ownedPurchase] }); | ||
| await loadDashboard(); | ||
| expect(cancelBtns()).toHaveLength(1); | ||
| }); | ||
|
|
||
| test('admin sees Cancel on every row (admin:* covers delete:purchases)', async () => { | ||
| setUser(OTHER_ID, { admin: true }); | ||
| (api.getUpcomingPurchases as jest.Mock).mockResolvedValue({ | ||
| purchases: [ownedPurchase, { ...ownedPurchase, execution_id: 'exec-2' }], | ||
| }); | ||
| await loadDashboard(); | ||
| expect(cancelBtns()).toHaveLength(2); | ||
| }); | ||
|
|
||
| test('legacy NULL-creator row shows no Cancel for a non-update-any user', async () => { | ||
| setUser(CREATOR_ID); | ||
| (api.getUpcomingPurchases as jest.Mock).mockResolvedValue({ purchases: [legacyPurchase] }); | ||
| await loadDashboard(); | ||
| expect(cancelBtns()).toHaveLength(0); | ||
| }); | ||
|
|
||
| test('user without delete:purchases sees no Cancel even on their own row', async () => { | ||
| // Read-only style: holds neither delete:purchases nor admin nor | ||
| // update-any. Even on their own row the button must stay hidden | ||
| // because the backend would reject the click on verb grounds. | ||
| (state.getCurrentUser as jest.Mock).mockReturnValue({ | ||
| id: CREATOR_ID, | ||
| email: 'ro@example.com', | ||
| groups: [], | ||
| effectivePermissions: [{ action: 'view', resource: 'purchases' }], | ||
| }); | ||
| (api.getUpcomingPurchases as jest.Mock).mockResolvedValue({ purchases: [ownedPurchase] }); | ||
| await loadDashboard(); | ||
| expect(cancelBtns()).toHaveLength(0); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| /** | ||
| * Issue #950: creator-scope ownership gating on Scheduled (Planned) Purchase | ||
| * row action buttons. | ||
| * | ||
| * The pre-fix behaviour gated the Run / Pause / Resume / Edit / Disable | ||
| * buttons purely on the plan-management verbs (update:plans / delete:plans), | ||
| * so a Standard user with those verbs saw actionable buttons on scheduled | ||
| * purchases created by OTHER users. The fix ANDs in | ||
| * canManageScheduledPurchase(): a non-creator without update-any:purchases | ||
| * sees NO action buttons. | ||
| * | ||
| * These tests drive the real loadPlans() render path. They set | ||
| * effectivePermissions on the mock user so the #365 verb gate passes, | ||
| * isolating the new ownership gate as the deciding factor. | ||
| */ | ||
| import { loadPlans } from '../plans'; | ||
|
|
||
| jest.mock('../api', () => ({ | ||
| getPlans: jest.fn(), | ||
| getPlannedPurchases: jest.fn(), | ||
| listPlanAccounts: jest.fn().mockResolvedValue([]), | ||
| })); | ||
|
|
||
| jest.mock('../state', () => ({ | ||
| getRecommendations: jest.fn().mockReturnValue([]), | ||
| getSelectedRecommendationIDs: jest.fn().mockReturnValue(new Set()), | ||
| getVisibleRecommendations: jest.fn().mockReturnValue([]), | ||
| setVisibleRecommendations: jest.fn(), | ||
| getCurrentProvider: jest.fn().mockReturnValue(''), | ||
| setCurrentProvider: jest.fn(), | ||
| getCurrentAccountIDs: jest.fn().mockReturnValue([]), | ||
| setCurrentAccountIDs: jest.fn(), | ||
| subscribeProvider: jest.fn().mockReturnValue(() => {}), | ||
| subscribeAccount: jest.fn().mockReturnValue(() => {}), | ||
| getCurrentUser: jest.fn(), | ||
| getPlansColumnFilters: jest.fn().mockReturnValue({}), | ||
| setPlansColumnFilter: jest.fn(), | ||
| clearAllPlansColumnFilters: jest.fn(), | ||
| })); | ||
|
|
||
| jest.mock('../history', () => ({ viewPlanHistory: jest.fn() })); | ||
|
|
||
| import * as api from '../api'; | ||
| import * as state from '../state'; | ||
|
|
||
| const CREATOR_ID = 'creator-aaaa'; | ||
| const OTHER_ID = 'other-bbbb'; | ||
|
|
||
| const samplePlan = { | ||
| id: 'plan-1', | ||
| name: 'Sample Plan', | ||
| enabled: true, | ||
| auto_purchase: true, | ||
| services: { | ||
| ec2: { provider: 'aws', service: 'ec2', enabled: true, term: 1, payment: 'all-upfront', coverage: 80 }, | ||
| }, | ||
| ramp_schedule: { type: 'immediate', percent_per_step: 100, step_interval_days: 0, current_step: 1, total_steps: 4 }, | ||
| }; | ||
|
|
||
| // A scheduled purchase created by CREATOR_ID. | ||
| const ownedPurchase = { | ||
| id: 'pp-1', | ||
| plan_id: 'plan-1', | ||
| plan_name: 'Sample Plan', | ||
| scheduled_date: '2026-06-01T00:00:00Z', | ||
| provider: 'aws', | ||
| service: 'ec2', | ||
| resource_type: 't3.medium', | ||
| region: 'us-east-1', | ||
| count: 5, | ||
| term: 1, | ||
| payment: 'all-upfront', | ||
| upfront_cost: 100, | ||
| estimated_savings: 50, | ||
| step_number: 1, | ||
| total_steps: 4, | ||
| status: 'pending', | ||
| created_by_user_id: CREATOR_ID, | ||
| }; | ||
|
|
||
| // Legacy row with no creator (pre-migration NULL). | ||
| const legacyPurchase = { ...ownedPurchase, created_by_user_id: undefined as string | undefined }; | ||
|
|
||
| // A user holding the plan-management verbs + update:purchases (so the #365 | ||
| // verb gate passes), optionally update-any:purchases. id identifies the | ||
| // session user for the ownership comparison. | ||
| const setUser = (id: string, opts: { updateAny?: boolean } = {}) => { | ||
| const effectivePermissions = [ | ||
| { action: 'update', resource: 'plans' }, | ||
| { action: 'delete', resource: 'plans' }, | ||
| { action: 'execute', resource: 'purchases' }, | ||
| { action: 'update', resource: 'purchases' }, | ||
| { action: 'delete', resource: 'purchases' }, | ||
| ]; | ||
| if (opts.updateAny) { | ||
| effectivePermissions.push({ action: 'update-any', resource: 'purchases' }); | ||
| } | ||
| (state.getCurrentUser as jest.Mock).mockReturnValue({ | ||
| id, | ||
| email: `${id}@example.com`, | ||
| groups: [], | ||
| effectivePermissions, | ||
| }); | ||
| }; | ||
|
|
||
| const ppHtml = (): string => (document.getElementById('planned-purchases-list') as HTMLElement).innerHTML; | ||
|
|
||
| const setupDom = () => { | ||
| const btn = document.createElement('button'); | ||
| btn.id = 'new-plan-btn'; | ||
| const list = document.createElement('div'); | ||
| list.id = 'plans-list'; | ||
| const planned = document.createElement('div'); | ||
| planned.id = 'planned-purchases-list'; | ||
| document.body.replaceChildren(btn, list, planned); | ||
| }; | ||
|
|
||
| const ACTIONS = ['run', 'pause', 'resume', 'edit', 'disable']; | ||
|
|
||
| describe('Scheduled-purchase ownership gating (issue #950)', () => { | ||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| setupDom(); | ||
| (api.getPlans as jest.Mock).mockResolvedValue({ plans: [samplePlan] }); | ||
| }); | ||
|
|
||
| test("creator sees action buttons on their own scheduled purchase", async () => { | ||
| setUser(CREATOR_ID); | ||
| (api.getPlannedPurchases as jest.Mock).mockResolvedValue({ purchases: [ownedPurchase] }); | ||
| await loadPlans(); | ||
| const html = ppHtml(); | ||
| // run/pause are status-dependent (pending -> run+pause shown). | ||
| expect(html).toContain('data-action="run"'); | ||
| expect(html).toContain('data-action="pause"'); | ||
| expect(html).toContain('data-action="edit"'); | ||
| expect(html).toContain('data-action="disable"'); | ||
| }); | ||
|
|
||
| test("non-creator with the same verbs sees NO action buttons (the bug)", async () => { | ||
| // The deciding factor is ownership: this user holds update:plans / | ||
| // delete:plans / update:purchases but did NOT create the row. | ||
| setUser(OTHER_ID); | ||
| (api.getPlannedPurchases as jest.Mock).mockResolvedValue({ purchases: [ownedPurchase] }); | ||
| await loadPlans(); | ||
| const html = ppHtml(); | ||
| ACTIONS.forEach((act) => expect(html).not.toContain(`data-action="${act}"`)); | ||
| // The row itself still renders (status badge visible), just no buttons. | ||
| expect(html).toContain('Sample Plan'); | ||
| }); | ||
|
|
||
| test("update-any holder sees buttons on another user's scheduled purchase", async () => { | ||
| setUser(OTHER_ID, { updateAny: true }); | ||
| (api.getPlannedPurchases as jest.Mock).mockResolvedValue({ purchases: [ownedPurchase] }); | ||
| await loadPlans(); | ||
| const html = ppHtml(); | ||
| expect(html).toContain('data-action="run"'); | ||
| expect(html).toContain('data-action="pause"'); | ||
| expect(html).toContain('data-action="edit"'); | ||
| expect(html).toContain('data-action="disable"'); | ||
| }); | ||
|
|
||
| test("legacy NULL-creator row shows no buttons for a non-update-any user", async () => { | ||
| setUser(CREATOR_ID); | ||
| (api.getPlannedPurchases as jest.Mock).mockResolvedValue({ purchases: [legacyPurchase] }); | ||
| await loadPlans(); | ||
| const html = ppHtml(); | ||
| ACTIONS.forEach((act) => expect(html).not.toContain(`data-action="${act}"`)); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.