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

Symfony Opa Form Laravel Package

acrnogor/symfony-opa-form

Symfony middleware for authorization via build.security PDP/Open Policy Agent. Configure PDP host/port/policy path and timeouts in services.yaml, then use the OpenPolicyAgent service to send authz checks. Requires PHP 8+ and Symfony 4.4+.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require buildsecurity/symfony-opa
    

    Verify PHP 8.0+ and Symfony 4.22+ compatibility.

  2. Configure PDP Connection Add to config/packages/security.yaml (or services.yaml):

    parameters:
        pdp:
            hostname: "http://localhost"  # or your PDP endpoint
            port: 8181
            policy_path: "/authz/allow"
            read_timeout_ms: 5000
            connection_timeout_ms: 3000
    
  3. First Use Case: Basic Middleware Integration Add to config/packages/security.yaml under firewalls:

    firewalls:
        main:
            middleware: [buildsecurity_opa]
            # ... other middleware
    
  4. Define Input/Output Format Create a opa_input.yaml in config/packages/ to define request/response mappings:

    opa:
        input:
            path: "request.attributes"  # Symfony request attributes
            fields:
                - "user.id"
                - "resource.id"
        output:
            path: "result.allow"
    
  5. Test Locally Use the standalone Docker PDP for development.


Implementation Patterns

Workflow: Policy-Driven Authorization

  1. Request Attributes Injection Populate request.attributes in controllers or event listeners:

    $request->attributes->set('user.id', $user->id);
    $request->attributes->set('resource.id', $resource->id);
    
  2. Policy Evaluation The middleware automatically:

    • Serializes request.attributes → OPA input.
    • Sends to PDP via pdp.policy.path.
    • Deserializes response into result.allow (boolean).
  3. Decision Handling Use Symfony voters or access control:

    # security.yaml
    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN, opa: { allow: true } }
    

Integration Tips

  • Dynamic Policies: Update opa_input.yaml to adapt to new resource types.
  • Caching: Cache PDP responses for static policies (e.g., StashBundle).
  • Fallback Logic: Combine with Symfony’s access_control for hybrid auth:
    access_control:
        - { path: ^/profile, roles: ROLE_USER, opa: { allow: true, fallback: true } }
    
  • Testing: Mock PDP responses in PHPUnit:
    $this->getContainer()->get('buildsecurity_opa.client')->setMockResponse(true);
    

Advanced: Custom Input/Output

Extend the default format via a service:

# config/services.yaml
services:
    App\Opa\CustomInputMapper:
        tags: [buildsecurity_opa.input_mapper]
        arguments:
            $inputPath: "request.attributes.custom"

Gotchas and Tips

Pitfalls

  1. Timeouts

    • Default read_timeout_ms (5s) may be too short for slow PDPs.
    • Fix: Increase in services.yaml or handle timeouts gracefully:
      // In a subscriber
      if ($event->isGranted() === false && $event->getThrowable() instanceof \RuntimeException) {
          $event->allowIf($event->getThrowable()->getMessage() === 'PDP timeout');
      }
      
  2. Input Mismatch

    • OPA expects exact field names. Typos in opa_input.yaml cause silent failures.
    • Debug: Enable OPA logs:
      # config/packages/monolog.yaml
      handlers:
          opa:
              type: stream
              path: "%kernel.logs_dir%/opa.log"
              level: debug
      
  3. CORS/Network Issues

    • PDP endpoints must allow requests from your Symfony app.
    • Test: Use curl to verify PDP accessibility:
      curl -X POST http://localhost:8181/authz/allow -d '{"input": {"user.id": 123}}'
      
  4. Policy Versioning

    • Hardcoding policy paths (e.g., /authz/allow) breaks if policies change.
    • Solution: Use environment variables:
      parameters:
          pdp.policy.path: "%env(OPA_POLICY_PATH)%"
      

Tips

  • Policy Development Use build.security’s playground to test policies before integrating.

  • Performance Batch requests for multiple resources:

    // In a controller
    $request->attributes->set('resources', [$id1, $id2]);
    // Update opa_input.yaml to handle arrays
    
  • Error Handling Customize error responses via a subscriber:

    $event->setResponse(new JsonResponse(['error' => 'Policy denied'], 403));
    
  • Extension Points

    • Pre-Processing: Use buildsecurity_opa.pre_process event to modify input.
    • Post-Processing: Use buildsecurity_opa.post_process to transform output.
  • Docker Tips For local development, mount opa_input.yaml into the PDP container for hot-reloading:

    # docker-compose.yml
    volumes:
        - ./config/packages/opa_input.yaml:/etc/opa/opa_input.yaml
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
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