search-api-handler.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import type { IncomingMessage } from 'node:http';
  2. import { diag } from '@opentelemetry/api';
  3. import { ATTR_HTTP_TARGET } from '../../semconv';
  4. import type { AnonymizationModule } from '../interfaces/anonymization-module';
  5. import { anonymizeQueryParams } from '../utils/anonymize-query-params';
  6. const logger = diag.createComponentLogger({
  7. namespace: 'growi:anonymization:search-handler',
  8. });
  9. /**
  10. * Search API anonymization module
  11. */
  12. export const searchApiModule: AnonymizationModule = {
  13. /**
  14. * Check if this module can handle search API endpoints
  15. */
  16. canHandle(url: string): boolean {
  17. // More precise matching to avoid false positives
  18. return (
  19. url.match(/\/_api\/search(\?|$)/) !== null ||
  20. url.match(/\/_search(\?|$)/) !== null ||
  21. url.includes('/_api/search/') ||
  22. url.includes('/_search/')
  23. );
  24. },
  25. /**
  26. * Handle anonymization for search API endpoints
  27. */
  28. handle(request: IncomingMessage, url: string): Record<string, string> | null {
  29. // Check if this is a search request that needs anonymization
  30. // Look for q parameter anywhere in the query string
  31. if (url.includes('?q=') || url.includes('&q=')) {
  32. const anonymizedUrl = anonymizeQueryParams(url, ['q']);
  33. logger.debug(`Anonymized search API URL: ${url} -> ${anonymizedUrl}`);
  34. return {
  35. [ATTR_HTTP_TARGET]: anonymizedUrl,
  36. };
  37. }
  38. return null;
  39. },
  40. };