#
# An haproxy configuration that terminates SSL, delegates to an instance of the
# authentication service, uses a specific cookie for session affinity, and sets
# a limit on the number of requests to certain paths within a short time period.
#
global
    daemon
    maxconn 256

defaults
    mode http
    timeout queue 20s
    timeout connect 5s
    timeout client 30s
    # Set a timeout longer than the service's own timeout period, otherwise
    # haproxy will return a 504 instead of the expected 408.
    timeout server 75s

backend servers
    option forwardfor
    http-request set-header X-Forwarded-Proto https
    cookie JSESSIONID prefix nocache
    server auth1 auth-svc1.doc:3001 check cookie auth1 maxconn 32
    server auth2 auth-svc2.doc:3002 check cookie auth2 maxconn 32

frontend http-in
    bind *:443 ssl crt /etc/ssl/certs/mysite.pem verify optional ca-file /etc/ssl/certs/ca.crt
    http-request set-header X-SSL-Client-Cert %{+Q}[ssl_c_der,base64]

    #
    # Perform very basic rate limiting for specific paths by use of a
    # stick-table and counters associated with the source address.
    #
    # Other examples of rate limiting, most of which are very complex:
    # 
    # * https://www.haproxy.com/blog/bot-protection-with-haproxy
    # * https://www.sysbee.net/blog/smart-throttling-and-blocking-of-abusive-clients-using-haproxy/
    # * https://www.baeldung.com/devops/haproxy-api-gateway
    #
    acl throttled_url path_beg -i /requests/
    acl throttled_url path_beg -i /scim/
    acl throttled_url path_beg -i /status/
    stick-table type ipv6 size 100k expire 30s store http_req_rate(30s)
    http-request track-sc0 src if throttled_url
    http-request deny deny_status 429 if { sc_http_req_rate(0) gt 15 }

    default_backend servers
