Code Monkey home page Code Monkey logo

lua-resty-cookie's Introduction

Name

lua-resty-cookie - This library parses HTTP Cookie header for Nginx and returns each field in the cookie.

Table of Contents

Status

This library is production ready.

Synopsis

    lua_package_path "/path/to/lua-resty-cookie/lib/?.lua;;";

    server {
        location /test {
            content_by_lua '
                local ck = require "resty.cookie"
                local cookie, err = ck:new()
                if not cookie then
                    ngx.log(ngx.ERR, err)
                    return
                end

                -- get single cookie
                local field, err = cookie:get("lang")
                if not field then
                    ngx.log(ngx.ERR, err)
                    return
                end
                ngx.say("lang", " => ", field)

                -- get all cookies
                local fields, err = cookie:get_all()
                if not fields then
                    ngx.log(ngx.ERR, err)
                    return
                end

                for k, v in pairs(fields) do
                    ngx.say(k, " => ", v)
                end

                -- set one cookie
                local ok, err = cookie:set({
                    key = "Name", value = "Bob", path = "/",
                    domain = "example.com", secure = true, httponly = true,
                    expires = "Wed, 09 Jun 2021 10:18:14 GMT", max_age = 50,
                    samesite = "Strict", extension = "a4334aebaec"
                })
                if not ok then
                    ngx.log(ngx.ERR, err)
                    return
                end

                -- set another cookie, both cookies will appear in HTTP response
                local ok, err = cookie:set({
                    key = "Age", value = "20",
                })
                if not ok then
                    ngx.log(ngx.ERR, err)
                    return
                end
            ';
        }
    }

Methods

Back to TOC

new

syntax: cookie_obj = cookie()

Create a new cookie object for current request. You can get parsed cookie from client or set cookie to client later using this object.

Back to TOC

get

syntax: cookie_val, err = cookie_obj:get(cookie_name)

Get a single client cookie value. On error, returns nil and an error message.

Back to TOC

get_all

syntax: fields, err = cookie_obj:get_all()

Get all client cookie key/value pairs in a lua table. On error, returns nil and an error message.

Back to TOC

get_cookie_size

syntax: size = cookie_obj:get_cookie_size()

Get the cookie size, i.e the string length of the cookie header value.

Back to TOC

set

syntax: ok, err = cookie_obj:set({
    key = "Name",
    value = "Bob",
    path = "/",
    domain = "example.com",
    secure = true, httponly = true,
    expires = "Wed, 09 Jun 2021 10:18:14 GMT",
    max_age = 50,
    samesite = "Strict",
    extension = "a4334aebaec"
})

Set a cookie to client. This will add a new 'Set-Cookie' response header. key and value are required, all other fields are optional. If the same cookie (whole cookie string, e.g. "Name=Bob; Expires=Wed, 09 Jun 2021 10:18:14 GMT; Max-Age=50; Domain=example.com; Path=/; Secure; HttpOnly;") has already been setted, new cookie will be ignored.

Back to TOC

get_cookie_string

syntax: cookie_string, err = cookie.get_cookie_string({ --[[ see "set" method ]] })

Returns a cookie string representing the table passed. See the set method for details, but unlike set, this function doesn't change the current request response, but just return the generated string. On error, returns nil and an error message.

This is a static function, not a method of the cookie object.

Back to TOC

Installation

You need to compile ngx_lua with your Nginx.

You need to configure the lua_package_path directive to add the path of your lua-resty-cookie source tree to ngx_lua's Lua module search path, as in

# nginx.conf
http {
    lua_package_path "/path/to/lua-resty-cookie/lib/?.lua;;";
    ...
}

and then load the library in Lua:

local ck = require "resty.cookie"

Back to TOC

Authors

Jiale Zhi [email protected], CloudFlare Inc.

Yichun Zhang (agentzh) [email protected], CloudFlare Inc.

Back to TOC

Copyright and License

This module is licensed under the BSD license.

Copyright (C) 2013, by Jiale Zhi [email protected], CloudFlare Inc.

Copyright (C) 2013, by Yichun Zhang [email protected], CloudFlare Inc.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Back to TOC

lua-resty-cookie's People

Contributors

bobrik avatar calio avatar eberbis avatar hellobug0 avatar jbampton avatar jdesgats avatar jgrahamc avatar kikito avatar maurizioabba avatar maxvipon avatar p0pr0ck5 avatar stockrt avatar utix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lua-resty-cookie's Issues

cookie value have a blank space will cause get a truncated value;

local cookie = require "resty.http_cookie"
local coo = cookie:new()

coo:set({key="test",value="test value"})

next request ,i use coo:get("test") ,it will return "test" not "test value";

        if state == EXPECT_KEY then
            if byte(text_cookie, j) == EQUAL then
                key = sub(text_cookie, i, j - 1)
                state = EXPECT_VALUE
                i = j + 1
            end
        elseif state == EXPECT_VALUE then
            if byte(text_cookie, j) == SEMICOLON
                    --this is the reason code,it use SPACE OR HTAB as a separator,why?
                    or byte(text_cookie, j) == SPACE
                    or byte(text_cookie, j) == HTAB
            then
                value = sub(text_cookie, i, j - 1)
                cookie_table[key] = value
                cnt = cnt + 1
            end
                key, value = nil, nil
                state = EXPECT_SP
                i = j + 1
            end
        elseif state == EXPECT_SP then

bad argument #1 to 'clear_tab' (table expected, got nil)

Hi,

I am getting the following error when trying to set a new cookie:
failed to run body_filter_by_lua*: /usr/local/share/lua/5.1/resty/cookie.lua:164: bad argument #1 to 'clear_tab' (table expected, got nil)

My code:

return cookie:set({
        key = "Name",
        value = "Bob",
        path = "/",
        domain = "domain.com",
        secure = false, httponly = true,
        expires = "Wed, 09 Jun 2021 10:18:14 GMT",
        max_age = 50,
        samesite = "Strict",
        extension = "a4334aebaec"
    })

Thank you for your help

License

Hi, is there a way to set a License on this repo? as to remove some ambiguity?
Thanks

Cannot install via Docker

Hi there, thank you for this library, I have been using it for years with rock solid reliability.

I'm running into a new issue that has me somewhat baffled, I'm not sure where else to go.

When running "docker build", I'm hitting an error when it comes to installing lua-resty-cookie:

Installing https://luarocks.org/lua-resty-cookie-0.1.0-1.rockspec
Cloning into 'lua-resty-cookie'...
fatal: unable to connect to github.com:
github.com[0: 140.82.112.3]: errno=Connection timed out


Error: Failed cloning git repository.

I'm seeing this problem when working from a DigitalOcean droplet (2 different ones).

Stripped down Dockerfile:

FROM openresty/openresty:bionic

RUN apt-get update

RUN apt-get install git -y

RUN /usr/local/openresty/luajit/bin/luarocks install lua-resty-http \
    && /usr/local/openresty/luajit/bin/luarocks install lua-resty-auto-ssl \
    && /usr/local/openresty/luajit/bin/luarocks install lua-resty-template \
    && /usr/local/openresty/luajit/bin/luarocks install lua-resty-cookie \
    && /usr/local/openresty/luajit/bin/luarocks install web_sanitize

RUN openssl req -new -newkey rsa:2048 -days 3650 -nodes -x509 -subj '/CN=sni-support-required-for-valid-ssl' -keyout /etc/ssl/resty-auto-ssl-fallback.key -out /etc/ssl/resty-auto-ssl-fallback.crt

ADD ssl /etc/ssl

ADD templates /usr/local/openresty/nginx/html/templates

ADD static /usr/local/openresty/nginx/

ADD blocks /usr/local/openresty/nginx/html/templates

ADD confs /usr/local/openresty/nginx/conf

EXPOSE 8080
ENTRYPOINT ["/usr/local/openresty/nginx/sbin/nginx", "-g", "daemon off;"]

Does anyone have any insight or experience this issue? I woudln't be surprised if this was somehow my fault, but it feels like it popped up out of the blue.

Thanks,

[Edit]:

... only users connecting via SSH or git:// are affected. If your Git remotes start with https://, nothing here will affect you

So, is the issue with the git repo URL within the .rockspec file? Or it is something else?

Edit2:

I didn't realize there is an open PR addressing this:

#50

Failed parse cookies value with space

Failed parse cookies value with space, should comment out 2 lines (73 74)
-- or byte(text_cookie, j) == SPACE
-- or byte(text_cookie, j) == HTAB

to make it work with space in cookie value

Add API for updating/serializing cookie table

I'm trying to use this library in a reverse proxy that modifies a cookie header before passing the request to the upstream. For example, if an incoming request has this header:

Cookie: a=1; b=2; c=3

I want to parse it, remove b and change the value of a, producing a value like:

a=4; c=3

After that, I use a directive like proxy_set_header Cookie $new_cookies to override the cookies sent to the upstream.

Right now I can't cleanly accomplish this using lua-resty-cookie. I can parse the incoming Cookie header using get_all(), but I have to filter/modify/assemble the resulting cookie myself.

It would be helpful to have API for updating values inside the cookie table, and serializing the table to the format used in a Cookie header. E.g. something like this:

  • cookie.update(key, value) -- updates a cookie in the table
  • cookie.del(name) -- removes a cookie from the table
  • cookie.to_string() -- serializes table as a Cookie header

Would this fit within the scope of this library? Or is this project intended only as a wrapper for Set-Cookie?

Publishing to OPM/Luarocks

Could we please get this package either updated to the latest version on LuaRocks or published to OPM?

Code does not handle whitespace after cookie value before semicolon

This curl:

curl -b "name3=booboo; name2=hello_Hahabooboo ; username=foofoo" -o zoo1 -v "http://test.com/1.jpg"

breaks the code, the next cookie name starts with a semicolon.

Here is the proposed fix:

--- /usr/local/openresty/lualib/resty/cookie.lua.orig 2017-07-05 17:39:05.660555808 +0000
+++ /usr/local/openresty/lualib/resty/cookie.lua       2017-07-05 18:08:51.604555808 +0000
@@ -41,6 +41,7 @@
     local EXPECT_KEY    = 1
     local EXPECT_VALUE  = 2
     local EXPECT_SP     = 3
+    local EXPECT_SEMI   = 4
 
     local n = 0
     local len = #text_cookie
@@ -74,8 +75,12 @@
                 cookie_table[key] = value
 
                 key, value = nil, nil
-                state = EXPECT_SP
                 i = j + 1
+                              if byte(text_cookie, j) == SEMICOLON then
+                    state = EXPECT_SP
+                              else
+                                  state = EXPECT_SEMI
+                              end
             end
         elseif state == EXPECT_SP then
             if byte(text_cookie, j) ~= SPACE
@@ -85,6 +90,12 @@
                 i = j
                 j = j - 1
             end
+              elseif state == EXPECT_SEMI then
+                  if byte(text_cookie, j) ~= SEMICOLON then
+                  else
+                              state = EXPECT_SP
+                              i = j + 1
+                  end
         end
         j = j + 1
     end

extension parameter in `cookie:set`

it is not obvious to me the utility for cookie parameter extension
from my understanding it is just something added at the end of cookie value string

am i correct ?

Make test is broken

From master

make test
PATH=/usr/local/openresty/nginx/sbin:$PATH prove -I../test-nginx/lib -r t
t/sanity.t .. 44/72 # Looks like you planned 72 tests but ran 74.
t/sanity.t .. Dubious, test returned 255 (wstat 65280, 0xff00)
All 72 subtests passed 

Test Summary Report
-------------------
t/sanity.t (Wstat: 65280 Tests: 74 Failed: 2)
  Failed tests:  73-74
  Non-zero exit status: 255
  Parse errors: Bad plan.  You planned 72 tests but ran 74.
Files=1, Tests=74,  2 wallclock secs ( 0.04 usr  0.00 sys +  0.38 cusr  0.13 csys =  0.55 CPU)
Result: FAIL
make: *** [Makefile:17: test] Error 1

Using git bisect
a2cb7798133d891510bd37340390314644083da9 is the first bad commit

a2cb779 is the commit adding a test but not updating plan tests

Is this repo maintained anymore?

The last PR was over a year ago. There are 10 PRs open and a ton of issues that have been addressed. Is this repo unmanaged now?

Failed to set the Cookie in the request header

Dear experts,

Is there any way to set the cookie before the request is forwarded to the upstream? The main idea is to make sure all the incoming requests can come in with cookie available.

Thanks,

Unable to change samesite attribute of cookies

2 weeks ago I started to have errors with cookies.
When I checked cookie attributes, I saw "SameSite" key is always empty.
I tried to use all values ("None", "Strict", "Lax") and the final result is the same, "SameSite" is empty. I modified another key of my cookie at the same time and is was well updated.
Here is my cookie :

local ck, error = cookie:set({
        key = "tmp",
        value  = "xxx",
        domain = '.' .. myDomain,
        path   = "/",
        secure = true,
        httponly = true,
        samesite = "Strict",
        expires = "Thu, 7 Jun 2023 02:02:02 GMT"
    })

Do something changed with the last release ?

[Question]Do we need to convert the time when set cookie?

From the doc https://github.com/cloudflare/lua-resty-cookie/blob/master/README.md#set, when set cookie with expires time, it need to transfer the time to cookie.time() first which was not same like nginx-sticky-module-ng did. refer https://bitbucket.org/nginx-goodies/nginx-sticky-module-ng/overview.

The question was, Do I need to calculate the expires time before set cookie? and does there have any lua module can parse the time like ngx_parse.c did(https://www.cnblogs.com/xiangnan/p/5647115.html).

@agentzh

did not get response header cookie Secure?

  • did not get Secure?
"Set-Cookie: X_SADG_RouterID=test"
"Set-Cookie: tag=sign-8080; path=/; Secure"
  • demo
    local fields, err = cookie:get_all()
    if not fields then
        ngx.log(ngx.ERR, err)
        return
    end

    for k, v in pairs(fields) do
        ngx.log(ngx.ERR, "=============" .. k .. " => ", v)
    end

Delete a cookie?

Hello. Is it possible to completely delete a cookie?

I've tried cookie:set({key = "jwt",value = nil}) but that does nothing. cookie:set({key = "jwt",value = ""}) does succeed in setting the cookie value to empty, but my goal is to delete the cookie completely.

Thanks!

ngx.header.HEADER

When I try to set cookie:

2016/07/11 10:44:43 [error] 19243#0: *272 attempt to set ngx.header.HEADER after sending out response headers, client: 5.61.237.205, server: localhost, request:

Synopsis should be wrapped in content_by_lua

The Synopsis example in README.md is not a valid nginx config file, right? The Lua code there should be wrapped in content_by_lua. I don't mind doing a PR, I just wanted to make sure I was correct before doing so...

There are some problems in obtaining cookies

Assume that the client's cookie is
Hm_lvt_ff7f6fcad4e6116760e7b632f9614dc2=1583134761; Hm_lvt_137ae1af30761db81edff2e16f0bf0f8=1583134761; Hm_lpvt_ff7f6fcad4e6116760e7b632f9614dc2=1583309076 Hm_lpvt_137ae1af30761db81edff2e16f0bf0f8=<img src=x onerror=alert(1)>

Then get the following:
{"Hm_lvt_ff7f6fcad4e6116760e7b632f9614dc2":"1583134761","onerror":"alert(1)>","Hm_lvt_137ae1af30761db81edff2e16f0bf0f8":"1583134761","Hm_lpvt_137ae1af30761db81edff2e16f0bf0f8":"<img","Hm_lpvt_ff7f6fcad4e6116760e7b632f9614dc2":"1583309076","src":"x"}

This confused me. I also plan to modify some of your code logic

Cross domain cookie

Hello.

If I try to set cookie for different domain, it does not work.

For example I go to site.corp.com and I want to set cookie to this session, but for different domain. For example to site.bank.net.

Is it possible?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.