Skip to content

Instantly share code, notes, and snippets.

@qrtt1
Last active June 24, 2018 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save qrtt1/c695e145b5eef7de6d68 to your computer and use it in GitHub Desktop.
Save qrtt1/c695e145b5eef7de6d68 to your computer and use it in GitHub Desktop.

本來打算試著用 ngx_lua 取代原本用 C 實作的 access control,可是看完了「基本語法」想要找一些相關會用到的 library 都找不太到,像 lua-aws 雖然有人寫,但看起來不太完整。這樣就不能透過 lua script 存取 aws service 取得認證的資訊。

不過,想了想它網頁上 access_by_lua 的例子也沒有直接寫在裡面,就以 deleagte 的形式問了其它 uri:

location / {
    deny    192.168.1.1;
    allow   192.168.1.0/24;
    allow   10.1.1.0/16;
    deny    all;

    access_by_lua '
        local res = ngx.location.capture("/mysql", { ... })
        ...
        ';

# proxy_pass/fastcgi_pass/...
}

所以,這給了我一點靈感,我應該弄一個 /acl 後面接我比較熟悉的 Python 來處理它:

location / {
    access_by_lua '
        res = ngx.location.capture("/acl")
        if res.status ~=200 then
            return ngx.exit(res.status)
        end
    ';
}

location /acl {
    allow 127.0.0.1;
    deny all;
    include uwsgi_params;
    uwsgi_pass unix:/tmp/uwsgi.sock;
}

後端是個簡單的 wsgi

import time

def application(env, start_response):
    print env
    v = int(time.time()) % 2

    status_code = '200 OK' if v == 0 else '403 Forbidden'
    start_response(status_code, [('Content-Type','text/html')])
    return ["ACL WEB"]

env 會有哪些訊息呢?需要用來判斷權限的資料大致都有(主要是 REQUEST_URI 的內容):

{'wsgi.multiprocess': False, 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/acl', 
'SERVER_PROTOCOL': 'HTTP/1.1', 'QUERY_STRING': '', 'UWSGI_SCHEME': 'http', 
'CONTENT_LENGTH': '', 'HTTP_USER_AGENT': 'curl/7.37.1', 'SERVER_NAME': 'localhost', 
'REMOTE_ADDR': '172.16.67.1', 'wsgi.url_scheme': 'http', 'SERVER_PORT': '80', 
'uwsgi.node': '7be01af6c10c', 'DOCUMENT_ROOT': '/usr/share/nginx/html', 
'wsgi.input': <uwsgi._Input object at 0x7f481cd26120>, 
'HTTP_HOST': '172.16.67.135:8877', 'wsgi.multithread': False, 
'REQUEST_URI': '/abc.mp4?auth_info=3&djd=3', 
'HTTP_ACCEPT': '*/*', 'wsgi.version': (1, 0), 'wsgi.run_once': False, 
'wsgi.errors': <open file 'wsgi_errors', mode 'w' at 0x7f481cc8c4b0>, 
'REMOTE_PORT': '62726', 'uwsgi.version': '2.0.10', 'CONTENT_TYPE': '', 
'wsgi.file_wrapper': <built-in function uwsgi_sendfile>}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment