airqo-platform / airqo-platform/AirQo-api

Fix ObjectId validation and tenant normalization in getSiteById utility

未关闭
#5,172 0 条评论 0 个 reaction 已指派 1 人 已被 @Baalmart 认领 在 GitHub 查看
主要语言
JavaScript
星标
26
派生
24
平均合并
5 小时 36 分钟
30 天内合并 PR
81

描述

## Description

A potential runtime error exists in `src/device-registry/utils/site.util.js` in the `getSiteById` function where:

1. **Tenant normalization issue**: `tenant.toLowerCase()` is called without checking if `tenant` is defined, which could cause a TypeError
2. **ObjectId validation issue**: The `id` parameter is used directly in MongoDB aggregation `$match` stage without validating it's a proper ObjectId

## Location
- **File**: `src/device-registry/utils/site.util.js`
- **Function**: `getSiteById`
- **Lines**: Around 37-41

## Problematic Code
```javascript
const { tenant, maxActivities = 500 } = req.query;
// ...
const sitePipeline = await SiteModel(tenant.toLowerCase()).aggregate([
{
$match: { _id: id },
},
```

## Expected Fix
1. Add mongoose import at the top of the file
2. Validate and normalize tenant before use:
```javascript
const safeTenant = isEmpty(tenant)
? (constants.DEFAULT_TENANT || "airqo")
: String(tenant).toLowerCase();
```
3. Validate ObjectId before aggregation:
```javascript
if (!mongoose.Types.ObjectId.isValid(id)) {
throw new HttpError("Invalid site id", httpStatus.BAD_REQUEST);
}
const _id = new mongoose.Types.ObjectId(id);
```

## Steps to Reproduce
1. Call the getSiteById endpoint without a tenant parameter
2. Call the getSiteById endpoint with an invalid ObjectId

## References
- **PR**: https://github.com/airqo-platform/AirQo-api/pull/5170
- **Comment**: https://github.com/airqo-platform/AirQo-api/pull/5170#discussion_r2326421976
- **Reported by**: @Baalmart

贡献指南

打开贡献指南

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。