Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/dashboard-patch-team-immutable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hyperdx/api': patch
---

fix: ignore `team` and `createdBy` in dashboard and saved search PATCH bodies so they can't be moved to another team or have their owner rewritten
15 changes: 14 additions & 1 deletion packages/api/src/controllers/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,19 @@ export async function updateDashboard(
updates: Partial<z.infer<typeof DashboardWithoutIdSchema>>,
userId?: ObjectId,
) {
// Defense-in-depth: callers pass spread objects into the update doc below.
// A smuggled `team`/`createdBy` here would move the document between
// tenants / forge ownership (the model marks them immutable, but the
// write below reaches Mongo directly).
const {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — Controller guard can't be reached, throws (a 500) where the PR says the fields are ignored, and uses an as cast

updates is typed Partial<DashboardWithoutId>, which has no team/createdBy. The only caller (routers/api/dashboards.ts) re-parses and strips them, and the model now marks both immutable. So this branch never runs. If it ever did, it would return a 500, which contradicts the changeset's 'ignore' wording and the silent drop in controllers/savedSearch.ts. The as Record<string, unknown> cast also erases the type of safeUpdates, which breaks the 'avoid as casts' convention. Remove the block and spread updates, or at least drop the keys silently without the cast.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

team: _ignoredTeam,
createdBy: _ignoredCreatedBy,
...safeUpdates
} = updates as Record<string, unknown>;
if (_ignoredTeam !== undefined || _ignoredCreatedBy !== undefined) {
throw new Error('updateDashboard: team/createdBy are not updatable');
}

const oldDashboard = await getDashboard(dashboardId, teamId);

if (oldDashboard == null) {
Expand All @@ -261,7 +274,7 @@ export async function updateDashboard(
team: teamId,
},
{
...updates,
...safeUpdates,
tags: updates.tags && uniq(updates.tags),
updatedBy: userId,
},
Expand Down
6 changes: 5 additions & 1 deletion packages/api/src/controllers/savedSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,14 @@ export function updateSavedSearch(
savedSearch: SavedSearchWithoutId,
userId?: string,
) {
// Callers may pass a merged stored document, which carries `createdBy`.
// Drop it so a spread can never rewrite ownership attribution.
const { createdBy: _createdBy, ...safeSavedSearch } =
savedSearch as SavedSearchWithoutId & { createdBy?: unknown };
return SavedSearch.findOneAndUpdate(
{ _id: savedSearchId, team: teamId },
{
...savedSearch,
...safeSavedSearch,
team: teamId,
updatedBy: userId,
},
Expand Down
15 changes: 14 additions & 1 deletion packages/api/src/models/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,17 @@ export default mongoose.model<IDashboard>(
required: true,
},
tiles: { type: mongoose.Schema.Types.Mixed, required: true },
team: { type: mongoose.Schema.Types.ObjectId, ref: 'Team' },
// Immutable: `team` pins a dashboard to its owning tenant. Client PATCH
// bodies are re-parsed against DashboardWithoutIdSchema (which declares
// no `team`), so a smuggled key never reaches the update doc — this is
// defense-in-depth for any other caller that spreads into an update.
// The provisioner sets it via $setOnInsert only, which immutability
// permits.
team: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Team',
immutable: true,
},
tags: {
type: [String],
default: [],
Expand All @@ -39,10 +49,13 @@ export default mongoose.model<IDashboard>(
required: false,
},
containers: { type: mongoose.Schema.Types.Array, required: false },
// Immutable: ownership attribution is set once at creation; updates
// may only change `updatedBy`.
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: false,
immutable: true,
},
updatedBy: {
type: mongoose.Schema.Types.ObjectId,
Expand Down
4 changes: 4 additions & 0 deletions packages/api/src/models/savedSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ const savedSearchSchema = new Schema<
ISavedSearchMethods
>(
{
// Immutable: `team` pins a saved search to its owning tenant.
team: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Team',
immutable: true,
},

name: String,
Expand All @@ -59,10 +61,12 @@ const savedSearchSchema = new Schema<
},
tags: [String],
filters: [{ type: mongoose.Schema.Types.Mixed }],
// Immutable: ownership attribution is set once at creation.
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: false,
immutable: true,
},
updatedBy: {
type: mongoose.Schema.Types.ObjectId,
Expand Down
63 changes: 63 additions & 0 deletions packages/api/src/routers/api/__tests__/dashboard.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2638,4 +2638,67 @@ describe('dashboard router', () => {
});
});
});

describe('PATCH /:id server-owned fields', () => {
// Security regression: `team` and `createdBy` are server-owned. A PATCH
// body that smuggled them used to move a dashboard into another team's
// namespace (cross-tenant injection) and forge ownership attribution —
// zod-express-middleware's validateRequest validates without replacing
// req.body, and the handler used to spread req.body into the update.
// Now the handler re-parses the body against
// DashboardWithoutIdSchema.partial(), which declares neither field.
it('ignores smuggled team and createdBy on PATCH', async () => {
const victimTeamId = new mongoose.Types.ObjectId();
const victimUserId = new mongoose.Types.ObjectId();

const created = await agent
.post('/dashboards')
.send(MOCK_DASHBOARD)
.expect(200);

const updated = await agent
.patch(`/dashboards/${created.body.id}`)
.send({
name: 'Hijacked Dashboard',
team: victimTeamId.toString(),
createdBy: victimUserId.toString(),
})
.expect(200);

// API response must not echo the forged values
expect(updated.body.team).toBe(team._id.toString());

// Ground truth: the persisted document stays in the owning team
const stored = await Dashboard.findById(created.body.id).lean();
expect(String(stored?.team)).toBe(team._id.toString());
expect(String(stored?.createdBy)).toBe(user._id.toString());

// And the owner can still reach it (a real move would orphan it)
const list = await agent.get('/dashboards').expect(200);
const listedIds = list.body.map((d: { _id: string }) => d._id);
expect(listedIds).toContain(created.body.id);
});

// Same mechanism via a client that round-trips a full GET response: the
// extra keys ride along in the spread and must still be dropped.
it('drops server-owned keys from a round-tripped PATCH body', async () => {
const created = await agent
.post('/dashboards')
.send(MOCK_DASHBOARD)
.expect(200);
const before = await agent.get('/dashboards').expect(200);
const full = before.body.find(
(d: { _id: string }) => d._id === created.body.id,
);

await agent
.patch(`/dashboards/${created.body.id}`)
.send({ ...full, name: 'Updated Name' })
.expect(200);

const stored = await Dashboard.findById(created.body.id).lean();
expect(String(stored?.team)).toBe(team._id.toString());
expect(String(stored?.createdBy)).toBe(user._id.toString());
});
});
});
30 changes: 30 additions & 0 deletions packages/api/src/routers/api/__tests__/savedSearch.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,36 @@ describe('savedSearch router', () => {
expect(dbRecord?.createdBy?.toString()).toBe(user._id.toString());
});

it('ignores smuggled team and createdBy on PATCH', async () => {
const otherUser = await User.create({
email: 'other@test.com',
name: 'Other User',
});
const otherTeamId = '679b12d6cf282580fc63aad5';
const created = await agent
.post('/saved-search')
.send(MOCK_SAVED_SEARCH)
.expect(200);

await agent
.patch(`/saved-search/${created.body._id}`)
.send({
name: 'updated name',
team: otherTeamId,
createdBy: otherUser._id.toString(),
})
.expect(200);

const dbRecord = await SavedSearch.findById(created.body._id);
expect(dbRecord?.name).toBe('updated name');
expect(dbRecord?.team.toString()).toBe(team._id.toString());
expect(dbRecord?.createdBy?.toString()).toBe(user._id.toString());

const savedSearches = await agent.get('/saved-search').expect(200);
const listed = savedSearches.body.find(s => s._id === created.body._id);
expect(listed.createdBy).toMatchObject({ email: user.email });
});

it('sets createdBy on alerts created from a saved search and populates it in list', async () => {
// Create a saved search
const savedSearch = await agent
Expand Down
13 changes: 10 additions & 3 deletions packages/api/src/routers/api/dashboards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,16 @@ router.patch(
return res.sendStatus(404);
}

// Only omit undefined values, keep null (which signals field removal)
// `provisioned` is server-owned — see the POST handler above.
const updates = _.omitBy(_.omit(req.body, 'provisioned'), _.isUndefined);
// Re-parse instead of omitting keys by name: DashboardWithoutIdSchema
// declares no `team`/`createdBy`/`provisioned`, so parsing drops them
// along with every other unknown key. All three are server-owned —
// `team`/`provisioned` for tenant isolation and the provisioner, and
// `createdBy` for ownership attribution (a smuggled `team` used to move
// a dashboard into another team's namespace; see the POST handler's
// comment for why validateRequest alone can't enforce this).
// Nulls survive: the schema's optional fields are `.nullable()`, and a
// null still signals field removal downstream.
const updates = DashboardWithoutIdSchema.partial().parse(req.body);

const sourceError = await validateFilterSources(
teamId,
Expand Down
16 changes: 12 additions & 4 deletions packages/api/src/routers/api/savedSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import { objectIdSchema } from '@/utils/zod';

const router = express.Router();

const updateSavedSearchBodySchema = SavedSearchSchema.partial().extend({
name: z.string().trim().min(1).optional(),
});

type SavedSearchListExpRes = express.Response<SavedSearchListApiResponse[]>;

router.get('/', async (req, res: SavedSearchListExpRes, next) => {
Expand Down Expand Up @@ -60,9 +64,7 @@ router.post(
router.patch(
'/:id',
validateRequest({
body: SavedSearchSchema.partial().extend({
name: z.string().trim().min(1).optional(),
}),
body: updateSavedSearchBodySchema,
params: z.object({
id: objectIdSchema,
}),
Expand All @@ -81,7 +83,13 @@ router.patch(
return;
}

const updates = _.omitBy(req.body, _.isNil);
// Re-parse: validateRequest validates without replacing req.body, so
// server-owned keys like `team`/`createdBy` would otherwise reach the
// update. Parsing drops every key the schema doesn't declare.
const updates = _.omitBy(
updateSavedSearchBodySchema.parse(req.body),
_.isNil,
);

const updatedSavedSearch = await updateSavedSearch(
teamId.toString(),
Expand Down
Loading