Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Security Bundle Laravel Package

ano/security-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ano/security-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Ano\SecurityBundle\AnoSecurityBundle::class => ['all' => true],
    ];
    
  2. First Use Case:

    • Enable Anonymization: Configure the bundle in config/packages/ano_security.yaml:
      ano_security:
          enabled: true
          anonymize_ips: true
          anonymize_user_agents: true
      
    • Test Anonymization: Inject the AnoSecurity service in a controller or service:
      use Ano\SecurityBundle\Service\AnoSecurity;
      
      public function __construct(private AnoSecurity $anoSecurity) {}
      
      public function anonymizeRequest(Request $request) {
          $anonymizedIp = $this->anoSecurity->anonymizeIp($request->getClientIp());
          $anonymizedUserAgent = $this->anoSecurity->anonymizeUserAgent($request->headers->get('User-Agent'));
          return response()->json(['ip' => $anonymizedIp, 'user_agent' => $anonymizedUserAgent]);
      }
      
  3. Key Classes:

    • AnoSecurity (Main service for anonymization logic).
    • AnoSecurityEventListener (For event-driven anonymization, e.g., in Symfony events).

Implementation Patterns

Core Workflows

  1. Request Anonymization:

    • Use the AnoSecurity service to anonymize sensitive data before logging or processing:
      $this->anoSecurity->anonymizeIp($ip);
      $this->anoSecurity->anonymizeUserAgent($userAgent);
      
    • Integrate with Symfony’s KernelEvents::REQUEST to anonymize requests globally:
      # config/services.yaml
      services:
          Ano\SecurityBundle\EventListener\AnoSecurityEventListener:
              tags:
                  - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
      
  2. Response Filtering:

    • Anonymize sensitive data in API responses using a response listener:
      use Symfony\Component\HttpKernel\Event\ResponseEvent;
      
      public function onKernelResponse(ResponseEvent $event) {
          $response = $event->getResponse();
          $content = $this->anoSecurity->anonymizeJsonResponse($response->getContent());
          $response->setContent($content);
      }
      
  3. Database Anonymization:

    • Use the AnoSecurity service in Doctrine repositories or query builders to sanitize data before storage:
      $queryBuilder->andWhere('ip = :ip')
                  ->setParameter('ip', $this->anoSecurity->anonymizeIp($rawIp));
      

Integration Tips

  • Symfony Events: Leverage kernel.response, kernel.exception, or monolog.logger events to automate anonymization.
  • Monolog Integration: Extend the AnoSecurityEventListener to filter logs:
    public function onKernelRequest(Request $request, EventDispatcherInterface $dispatcher) {
        $dispatcher->addListener(MonologEvents::PROCESS_RECORD, function ($record) {
            $record->message = $this->anoSecurity->anonymizeLogMessage($record->message);
        });
    }
    
  • Custom Rules: Extend the AnoSecurity service to add domain-specific anonymization (e.g., for custom headers or cookies):
    $this->anoSecurity->addCustomAnonymizer('X-Custom-Header', function ($value) {
        return '*****';
    });
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Anonymization adds processing time. Cache anonymized values if used frequently:
      $cacheKey = 'anonymized_ip_' . $ip;
      $anonymizedIp = $cache->get($cacheKey) ?? $this->anoSecurity->anonymizeIp($ip);
      $cache->set($cacheKey, $anonymizedIp, 3600);
      
    • Avoid anonymizing in hot paths (e.g., loop iterations) unless necessary.
  2. False Positives in Logging:

    • Over-anonymization may hide legitimate debugging info. Use config to toggle features:
      ano_security:
          anonymize_ips: '%env(bool:ANONYMIZE_IPS)%'  # Disable in dev
      
  3. Event Listener Conflicts:

    • If multiple listeners modify the same request/response, order matters. Use priority tags:
      tags:
          - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: -10 }
      
  4. JSON Parsing Issues:

    • The anonymizeJsonResponse method may fail on malformed JSON. Validate input:
      try {
          $content = json_decode($response->getContent(), true);
          $anonymized = $this->anoSecurity->anonymizeAssoc($content);
          $response->setContent(json_encode($anonymized));
      } catch (\JsonException $e) {
          // Fallback: return original content
      }
      

Debugging Tips

  1. Enable Verbose Logging: Add to config/packages/monolog.yaml:

    handlers:
        main:
            level: debug
            channels: ["ano_security"]
    

    Then log anonymization steps:

    $this->logger->debug('Anonymized IP', ['original' => $ip, 'anonymized' => $anonymizedIp]);
    
  2. Test Edge Cases:

    • Null/Empty Inputs: Ensure the service handles null or empty strings gracefully.
    • Unicode/Non-ASCII Data: Test with non-Latin characters (e.g., 用户代理).
  3. Configuration Validation:

    • Validate ano_security.yaml for typos or unsupported options. Use Symfony’s parameter validation:
      if (!$this->container->getParameter('ano_security.enabled')) {
          throw new \RuntimeException('AnoSecurityBundle is disabled.');
      }
      

Extension Points

  1. Custom Anonymizers:

    • Implement Ano\SecurityBundle\Anonymizer\AnonymizerInterface for domain-specific rules:
      class CustomHeaderAnonymizer implements AnonymizerInterface {
          public function anonymize($value) {
              return str_repeat('*', strlen($value));
          }
      }
      
    • Register via service:
      services:
          Ano\SecurityBundle\Anonymizer\CustomHeaderAnonymizer:
              tags: [ano_security.anonymizer]
      
  2. Override Default Behavior:

    • Extend the AnoSecurity service to modify anonymization logic:
      class CustomAnoSecurity extends \Ano\SecurityBundle\Service\AnoSecurity {
          public function anonymizeIp($ip) {
              return parent::anonymizeIp($ip) . ' [CUSTOM]';
          }
      }
      
    • Bind the custom service in config/services.yaml:
      services:
          Ano\SecurityBundle\Service\AnoSecurity: '@custom_ano_security'
      
  3. Event-Driven Extensions:

    • Dispatch custom events after anonymization (e.g., for analytics):
      use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
      
      public function onKernelRequest(Request $request) {
          $anonymizedIp = $this->anoSecurity->anonymizeIp($request->getClientIp());
          $this->eventDispatcher->dispatch(new IpAnonymizedEvent($anonymizedIp));
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed