airqo-platform / airqo-platform/AirQo-api
Fix ObjectId validation and tenant normalization in getSiteById utility
- 主要語言
- 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 還沒有評估資料。