Files
fleet/website/api/controllers/android-proxy/get-android-devices.js
T
Eric f145c778b8 Website: log number of android enterprise requests in the past minute (#50780)
Related to: https://github.com/fleetdm/fleet/issues/49212

Changes:
- Updated the custom hook to create `sails.androidProxyApiRequestCount`,
and to log and reset the value every minute
- Updated android proxy endpoints to increment
`sails.androidProxyApiRequestCount` every time a request to the Android
management API is sent

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Monitoring**
* Added comprehensive tracking for Android Management API requests
across enrollment, enterprise, device, application, policy, and command
operations.
* Added periodic request-count logging and automatic resets when Android
Enterprise credentials are configured.
* Improved reporting alignment with minute-based API limits while
keeping logs quiet during periods without requests.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-08-07 11:58:35 -05:00

99 lines
4.0 KiB
JavaScript
Vendored

module.exports = {
friendlyName: 'Get android devices',
description: 'List android devices accessible to the Android enterprise.',
inputs: {
androidEnterpriseId: {
type: 'string',
required: true,
},
pageSize: {
type: 'number',
description: 'The maximum number of devices to return.',
min: 1,
defaultsTo: 100,
isInteger: true,
},
pageToken: {
type: 'string',
},
fields: {
type: 'string',
description: 'Selector specifying which fields to include in a partial response if any.',
}
},
exits: {
success: { description: 'Android devices list was successfully retrieved.' },
missingAuthHeader: { description: 'This request was missing an authorization header.', responseType: 'unauthorized'},
missingOriginHeader: { description: 'The request was missing an Origin header', responseType: 'badRequest'},
notFound: { description: 'No Android enterprise found for this Fleet server.', responseType: 'notFound' },
enterpriseNotAccessible: { description: 'Fleet is not authorized to manage this Android enterprise.', responseType: 'notFound' },
unauthorized: { description: 'Invalid authentication token.', responseType: 'unauthorized'},
},
fn: async function ({ androidEnterpriseId, pageSize, pageToken, fields }) {
// Extract fleetServerSecret from the Authorization header
let authHeader = this.req.get('authorization');
let fleetServerSecret;
if (authHeader && authHeader.startsWith('Bearer')) {
fleetServerSecret = authHeader.replace('Bearer', '').trim();
} else {
throw 'missingAuthHeader';
}
let thisAndroidEnterprise = await AndroidEnterprise.findOne({
androidEnterpriseId: androidEnterpriseId
});
if (!thisAndroidEnterprise) {
throw 'notFound';
}
if (thisAndroidEnterprise.fleetServerSecret !== fleetServerSecret) {
throw 'unauthorized';
}
// Get the shared Google API auth client with the getAndroidManagementAuthorizationClient helper.
// Note: we are doing this outside of the sails.helpers.flow.build() so any errors related to the website's credentials returned by the helper are not intercepted.
let androidManagementAuthClient = await sails.helpers.androidProxy.getAndroidManagementAuthorizationClient();
// List android devices from an enterprises using the passed parameters
return await sails.helpers.flow.build(async ()=>{
let { google } = require('googleapis');
let androidManagementConnection = google.androidmanagement({version: 'v1', auth: androidManagementAuthClient});
// Get the Android devices list from Google
sails.androidProxyApiRequestCount++;// Count this Android Management API request toward the per-minute total logged in api/hooks/custom/index.js.
let devicesResponse = await androidManagementConnection.enterprises.devices.list({
parent: `enterprises/${thisAndroidEnterprise.androidEnterpriseId}`,
pageSize: pageSize,
pageToken: pageToken,
fields: fields,
});
// Return the devices (no filtering needed since parent parameter already filters by enterprise)
return devicesResponse.data;
}).intercept({status: 429}, (err)=>{
// If the Android management API returns a 429 response, log an additional warning that will trigger a help-p1 alert.
sails.log.warn(`p1: Android management API rate limit exceeded!`);
return new Error(`When attempting to list devices for an Android enterprise (${androidEnterpriseId}), an error occurred. Error: ${err}`);
}).intercept({status: 403}, ()=>{
// If the Android management API returns a 403 response, return a enterpriseNotAccessible (notFound) response to the Fleet server.
return {'enterpriseNotAccessible': 'Fleet is not authorized to manage this Android enterprise.'};
}).intercept((err)=>{
return new Error(`When attempting to list devices for an Android enterprise (${androidEnterpriseId}), an error occurred. Error: ${require('util').inspect(err)}`);
});
}
};