include ${NGX_CONF_DIR}/common-includes/server_filters;
include ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/ssl_config;
include ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/proxy_headers;
include ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/config_override;

# Deny access to all cloud connect endpoints
location / {
	deny all;
    # 421 Misdirected Request
	return 421;
}

# Allow access to only task API
location ~ ^/drapi/v[1-9]+/tasks(/.*)?$ {

    limit_except GET POST PUT {
        deny all;
    }

    access_log  ${NGX_LOG_DIR}/access.log dr_api buffer=16k flush=30s;
    if ($known_dr_client = "false") {
        return 403;
    }

    limit_req zone=drtaskratelimit burst=${NGX_CLOUDCONNECT_DR_TASK_REQUEST_BURST_LIMIT} nodelay;

    proxy_pass $scheme://$backend;
    proxy_no_cache 1;
    proxy_cache_bypass 1;

    log_by_lua_file ${NGX_LUA_DIR}/log_dr_requests.lua;
}

# Allow access to Usersync webhook callbacks
location ~ ^/dataconn/synccallback$ {

 	limit_except POST {
        deny all;
    }

    if ($known_dr_client = "false") {
        return 403;
    }

    limit_req zone=usersyncratelimit burst=${NGX_CLOUDCONNECT_USER_SYNC_CALLBACK_REQUEST_BURST_LIMIT} nodelay;

	proxy_pass $scheme://${NGX_CLOUDCONNECT_HOSTNAME}:8445;
	proxy_no_cache 1;
	proxy_cache_bypass 1;
}

# Error Pages Handling
error_page  403			/error/403.json;
error_page  404			/error/404.json;
error_page  429 		/error/429.json;
error_page  500 		/error/500.json;
error_page  503 		/error/503.json;
error_page  504 		/error/504.json;
error_page  502 		/error/502.json;

location ^~ /error/ {
    internal;
    alias   ${NGX_CONF_DIR}/components/${NGX_COMP_DIR_NAME}/json/;
}