Security Configuration

Comprehensive security guide for the Beas Rule Engine

Security Overview

The Beas Rule Engine implements multiple layers of security to protect sensitive data and ensure secure access to the system. This guide covers all security aspects including authentication, authorization, encryption, and best practices.

Security Features
  • OAuth2/JWT Authentication
  • Role-based Access Control (RBAC)
  • TripleDES Data Encryption
  • Input Validation and Sanitization
  • Secure Configuration Management
  • Audit Logging

Authentication

OAuth2/JWT Authentication

The system uses OAuth2 with JWT tokens for secure authentication. All API endpoints require valid JWT tokens in the Authorization header.

JWT Token Format:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Keycloak Configuration:
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: ${KEYCLOAK_AUTH_SERVER_URL}/realms/${KEYCLOAK_REALM}
          jwk-set-uri: ${KEYCLOAK_AUTH_SERVER_URL}/realms/${KEYCLOAK_REALM}/protocol/openid-connect/certs
Important

Always use HTTPS in production environments. Never transmit JWT tokens over unencrypted connections.

Token Validation

JWT tokens are validated for:

  • Signature verification
  • Expiration time
  • Issuer validation
  • Audience validation
Token Validation Configuration:
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          claim-set-converter: org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter
          claim-set-converter.claim-name: roles
          claim-set-converter.authority-prefix: ROLE_

Authorization

Role-Based Access Control

The system implements role-based access control with predefined roles:

Available Roles:
ROLE_ADMIN      - Full system access
ROLE_DEVELOPER  - Rule management and execution
ROLE_USER       - Rule execution only
ROLE_VIEWER     - Read-only access
Endpoint Security Configuration:
@RestController
@RequestMapping("/beasre/v1/rule-engine")
public class RuleEngine {
    
    @PostMapping("/evaluate")
    @PreAuthorize("hasAnyRole('ADMIN', 'DEVELOPER', 'USER')")
    public ResponseEntity<RuleResponse> evaluateRule(@RequestBody RuleRequest request) {
        // Implementation
    }
    
    @PostMapping("/rule-library")
    @PreAuthorize("hasAnyRole('ADMIN', 'DEVELOPER')")
    public ResponseEntity<RuleLibrary> createRuleLibrary(@RequestBody RuleLibrary ruleLibrary) {
        // Implementation
    }
}

Method-Level Security

Use method-level security annotations to control access to specific operations:

Security Annotations:
@Service
public class RuleLibraryService {
    
    @PreAuthorize("hasRole('ADMIN')")
    public void deleteRuleLibrary(String id) {
        // Only admins can delete
    }
    
    @PreAuthorize("hasAnyRole('ADMIN', 'DEVELOPER')")
    public RuleLibrary updateRuleLibrary(RuleLibrary ruleLibrary) {
        // Admins and developers can update
    }
    
    @PreAuthorize("isAuthenticated()")
    public List<RuleLibrary> getAllRuleLibraries() {
        // Any authenticated user can read
    }
}

Data Encryption

TripleDES Encryption

The system uses TripleDES encryption for sensitive data storage and transmission.

Encryption Configuration:
cryptography:
  algorithm: DESede
  transformation: DESede/CBC/PKCS5Padding
  key: ${CRYPTO_KEY}
  iv: ${CRYPTO_IV}
  key-size: 168
Encryption Usage:
@Service
public class Cryptography {
    
    public String encrypt(String data) {
        return cryptoState.encrypt(data);
    }
    
    public String decrypt(String encryptedData) {
        return cryptoState.decrypt(encryptedData);
    }
    
    public boolean isEncrypted(String data) {
        return cryptoState.isEncrypted(data);
    }
}
Security Warning

Never hardcode encryption keys in source code. Always use environment variables or secure key management systems.

Input Validation

All input is validated and sanitized to prevent injection attacks and data corruption.

Validation Example:
@Validated
@RestController
public class RuleEngine {
    
    @PostMapping("/evaluate")
    public ResponseEntity<RuleResponse> evaluateRule(
        @Valid @RequestBody RuleRequest request,
        @Pattern(regexp = "^[a-zA-Z0-9_-]+$") @RequestParam String ruleName
    ) {
        // Implementation
    }
}

public record RuleRequest(
    @NotBlank @Size(max = 100) String ruleName,
    @Valid Map<String, Object> parameters,
    Object payload
) {}

Environment Variables

Required Environment Variables

Set these environment variables for secure configuration:

Cryptography Keys:
# 32-character encryption key
export CRYPTO_KEY="your-32-character-encryption-key-here"

# 16-character initialization vector
export CRYPTO_IV="your-16-char-iv"
Keycloak Configuration:
# Keycloak server URL
export KEYCLOAK_AUTH_SERVER_URL="http://localhost:8080/auth"

# Keycloak realm
export KEYCLOAK_REALM="beasre"

# Client ID
export KEYCLOAK_RESOURCE="beas-rule-engine"

# JWT secret (if using symmetric signing)
export JWT_SECRET="your-jwt-secret-key"
Database Security:
# MongoDB credentials
export MONGODB_USERNAME="admin"
export MONGODB_PASSWORD="secure-password"

# Database name
export MONGODB_DATABASE="beasre"
Important

Use strong, unique passwords and keys. Consider using a secrets management system in production.

Environment File Setup

Create an environment file for easy configuration management:

Create .env file:
# Copy example file
cp env-example.sh .env

# Edit with your values
nano .env

# Source the environment variables
source .env
Example .env file:
#!/bin/bash

# Cryptography Configuration
export CRYPTO_KEY="your-32-character-encryption-key-here"
export CRYPTO_IV="your-16-char-iv"

# Keycloak Configuration
export KEYCLOAK_AUTH_SERVER_URL="http://localhost:8080/auth"
export KEYCLOAK_REALM="beasre"
export KEYCLOAK_RESOURCE="beas-rule-engine"

# MongoDB Configuration
export MONGODB_HOST="localhost"
export MONGODB_PORT="27017"
export MONGODB_DATABASE="beasre"
export MONGODB_USERNAME="admin"
export MONGODB_PASSWORD="secure-password"

# Server Configuration
export SERVER_PORT="8070"
export SERVER_CONTEXT_PATH="/beasre"

Security Best Practices

General Security Practices

Do's:
  • Use HTTPS in production
  • Store secrets in environment variables
  • Regularly rotate encryption keys
  • Implement proper logging and monitoring
  • Keep dependencies updated
  • Use strong passwords and keys
  • Implement rate limiting
Don'ts:
  • Never hardcode secrets in source code
  • Don't use default passwords
  • Avoid transmitting sensitive data over HTTP
  • Don't log sensitive information
  • Avoid using deprecated security algorithms

Production Security

Production Checklist:
□ Use HTTPS with valid SSL certificates
□ Configure proper firewall rules
□ Set up intrusion detection systems
□ Implement comprehensive logging
□ Use secrets management systems
□ Regular security audits
□ Backup encryption keys securely
□ Monitor for suspicious activities
□ Keep all systems updated
□ Implement proper access controls

Security Troubleshooting

Common Issues

Authentication Issues:
  • Invalid JWT token: Check token expiration and signature
  • Keycloak connection failed: Verify server URL and realm configuration
  • Role not found: Ensure user has proper roles assigned
Encryption Issues:
  • Decryption failed: Verify encryption key and IV
  • Key length error: Ensure key is exactly 32 characters
  • IV length error: Ensure IV is exactly 16 characters
Debug Configuration:
logging:
  level:
    org.springframework.security: DEBUG
    com.beassolution.rule.crypto: DEBUG
    org.springframework.security.oauth2: DEBUG