Files
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

105 lines
5.2 KiB
JavaScript
Vendored

module.exports = {
friendlyName: 'Modify android policies',
description: 'Modifies a policy of an Android enterprise',
inputs: {
androidEnterpriseId: {
type: 'string',
required: true,
},
policyId: {
type: 'string',
required: true,
},
},
exits: {
success: { description: 'The policy of an Android enterprise was successfully updated.' },
missingAuthHeader: { description: 'This request was missing an authorization header.', responseType: 'unauthorized'},
unauthorized: { description: 'Invalid authentication token.', responseType: 'unauthorized'},
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' },
invalidPolicy: { description: 'Invalid patch policy request', responseType: 'badRequest' },
policyNotFound: { description: 'The specified policy was not found on this Android enterprise', responseType: 'notFound' },
managementApiError: { statusCode: 503, description: 'The Android management API returned a transient 5xx error.' },
},
fn: async function ({ androidEnterpriseId, policyId}) {
// 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';
}
// Authenticate this request
let thisAndroidEnterprise = await AndroidEnterprise.findOne({
androidEnterpriseId: androidEnterpriseId
});
// Return a 404 response if no records are found.
if (!thisAndroidEnterprise) {
throw 'notFound';
}
// Return an unauthorized response if the provided secret does not match.
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();
// Update the policy for this Android enterprise.
// Note: We're using sails.helpers.flow.build here to handle any errors that occurr using google's node library.
let modifyPoliciesResponse = await sails.helpers.flow.build(async () => {
let { google } = require('googleapis');
let androidManagementConnection = google.androidmanagement({version: 'v1', auth: androidManagementAuthClient});
// [?]: https://googleapis.dev/nodejs/googleapis/latest/androidmanagement/classes/Resource$Enterprises$Policies.html#patch
sails.androidProxyApiRequestCount++;// Count this Android Management API request toward the per-minute total logged in api/hooks/custom/index.js.
let patchPoliciesResponse = await androidManagementConnection.enterprises.policies.patch({
name: `enterprises/${androidEnterpriseId}/policies/${policyId}`,
// Note: Typically, we use defined inputs instead of accessing req.body directly. We forward req.body here to prevent previously set values from being overwritten by undefined values.
// This behavior should not be repeated in future Android proxy endpoints.
requestBody: this.req.body,
updateMask: this.req.param('updateMask') // Pass the update mask to avoid overwriting applications
});
return patchPoliciesResponse.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 update a policy for an Android enterprise (${androidEnterpriseId}), an error occurred. Error: ${err}`);
}).intercept({ status: 400 }, (err) => {
return {'invalidPolicy': `Attempted to update a policy with an invalid value for an Android enterprise (${androidEnterpriseId}): ${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({ status: 404 }, (err) => {
return {'policyNotFound': `Specified policy not found on this Android enterprise (${androidEnterpriseId}): ${err}`};
}).intercept((err) => {
if([502, 503, 504].includes(err.status)){
return {'managementApiError': `The Android management API returned a transient 5xx error: ${err}`};
}
return new Error(`When attempting to update a policy for an Android enterprise (${androidEnterpriseId}), an error occurred. Error: ${require('util').inspect(err)}`);
});
// Return the modified policy back to the Fleet server.
return modifyPoliciesResponse;
}
};