Files
fleet/website/api/controllers/android-proxy/delete-one-android-enterprise.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

100 lines
4.1 KiB
JavaScript
Vendored

module.exports = {
friendlyName: 'Delete one android enterprise',
description: 'Deletes an android enterprise and the associated database record.',
inputs: {
androidEnterpriseId: {
type: 'string',
required: true,
},
},
exits: {
success: { description: 'An Android enterprise was successfully deleted.' },
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'},
},
fn: async function ({androidEnterpriseId}) {
// 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';
}
// Look up the database record for this Android enterprise
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();
// Delete the Android enterprise from Google (if it still exists)
// Note: If the enterprise is already deleted in Google, we still want to clean up proxy database
try {
await sails.helpers.flow.build(async ()=>{
let { google } = require('googleapis');
let androidManagementConnection = google.androidmanagement({version: 'v1', auth: androidManagementAuthClient});
// Delete the android enterprise.
sails.androidProxyApiRequestCount++;// Count this Android Management API request toward the per-minute total logged in api/hooks/custom/index.js.
await androidManagementConnection.enterprises.delete({
name: `enterprises/${androidEnterpriseId}`,
});
let pubsub = google.pubsub({version: 'v1', auth: androidManagementAuthClient});
// Delete the enterprise's pubsub topic
await pubsub.projects.topics.delete({
topic: thisAndroidEnterprise.pubsubTopicName,
});
// Delete the topic's subscription, which should have the same name as the topic.
await pubsub.projects.subscriptions.delete({
subscription: thisAndroidEnterprise.pubsubSubscriptionName,
});
return;
}).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! Error: ${require('util').inspect(err)}`);
return new Error(`When attempting to delete android enterprise from Google (${androidEnterpriseId}), an error occurred. Error: ${err}`);
}).intercept((err)=>{
return new Error(`When attempting to delete android enterprise from Google (${androidEnterpriseId}), an error occurred. Error: ${require('util').inspect(err)}`);
});
} catch (unusedErr) {
// If Google API deletion fails (e.g., enterprise already deleted), continue with proxy cleanup
}
// Delete the database record for this Android enterprise
await AndroidEnterprise.destroyOne({ id: thisAndroidEnterprise.id });
// All done. Send back an empty JSON object as expected by Android Management API.
return {};
}
};