Search code examples
varnishvarnish-vclvarnish-4

Can I create a custom list of values like ACL in Varnish 4?


I'm using Varnish version 4. I'd like to know if VCL allows a custom and reusable list of values like ACL. I want to use it to check against visitors' cookies. If he is a moderator, don't serve cached content.

Cookie String:

   session=9urt2jipvkq77brfrf; UserID=158

Code:

   acl moderator{
       "158";
       "114";
   }

   sub vcl_recv {

      set req.http.UserID = regsub(req.http.Cookie,".*UserID=(\d+).*","\1"); // 158

      if(req.http.UserID ~ moderator){ // 158 found in the moderator list

          return(pass);
      }
   }

Solution

  • Short answer: no

    ACL (access control list) is only used for specifying different IPs/hosts.

    However you can use a VMOD to accomplish this. Checkout Variable

    It has some basic functions for setting and getting variables.

    set("my_var", "this is the value")
    set req.http.x-my-var = get("my_var")
    

    There is also some more advanced functions, like setting multiple variables from a single string using regex.

    variable.regset("ttl:d=\1s,grace:d=\2s", "^(?:.*,)?max-age=([0-9]+)(?:+([0-9]+))", beresp.http.Surrogate-Control);
    set beresp.ttl = variable.get_duration("ttl");
    set beresp.grace = variable.get_duration("grace");
    

    ttl is the name of the variable, grace is the name of the second variable

    \1 & \2 are simple back-references to the regex

    :d specifies the type, in this case duration

    Your list of user id:s

    You could just set them in a comma separated string

    set("moderators", ",158,114,") //Notice the starting and ending comma-sign
    
    if(","+req.http.UserID+"," ~ get("moderators")){
    
         return(pass);
     }