| Matthias Andreas Benkard | 97f1202 | 2026-10-23 08:46:40 +0200 | [diff] [blame^] | 1 | function auth_password_verify(request, password) |
| 2 | if request.domain == nil then |
| 3 | return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, "No such user" |
| 4 | end |
| 5 | |
| 6 | local json = require "cjson" |
| 7 | local ltn12 = require "ltn12" |
| 8 | local https = require "ssl.https" |
| 9 | https.TIMEOUT = 30 |
| 10 | |
| 11 | local req = { |
| 12 | username = request.user, |
| 13 | password = password, |
| 14 | real_rip = request.real_rip, |
| 15 | service = request.service |
| 16 | } |
| 17 | local req_json = json.encode(req) |
| 18 | local res = {} |
| 19 | |
| 20 | local b, c = https.request { |
| 21 | method = "POST", |
| 22 | url = "https://nginx:9082", |
| 23 | source = ltn12.source.string(req_json), |
| 24 | headers = { |
| 25 | ["content-type"] = "application/json", |
| 26 | ["content-length"] = tostring(#req_json) |
| 27 | }, |
| 28 | sink = ltn12.sink.table(res), |
| 29 | insecure = true |
| 30 | } |
| 31 | |
| 32 | -- Returning PASSDB_RESULT_PASSWORD_MISMATCH will reset the user's auth cache entry. |
| 33 | -- Returning PASSDB_RESULT_INTERNAL_FAILURE keeps the existing cache entry, |
| 34 | -- even if the TTL has expired. Useful to avoid cache eviction during backend issues. |
| 35 | |
| 36 | -- On a network-level failure (nginx unreachable, DNS failure, timeout) https.request |
| 37 | -- returns nil plus an error string, so c is not a numeric HTTP status code. Treat this |
| 38 | -- as a backend outage and keep the cache entry, rather than wiping it as a mismatch. |
| 39 | if type(c) ~= "number" then |
| 40 | dovecot.i_info("HTTP request to auth backend failed with " .. tostring(c) .. " for user " .. request.user) |
| 41 | return dovecot.auth.PASSDB_RESULT_INTERNAL_FAILURE, "Upstream unreachable" |
| 42 | end |
| 43 | |
| 44 | if c ~= 200 and c ~= 401 then |
| 45 | dovecot.i_info("HTTP request failed with " .. tostring(c) .. " for user " .. request.user) |
| 46 | return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Upstream error" |
| 47 | end |
| 48 | |
| 49 | local response_str = table.concat(res) |
| 50 | local is_response_valid, response_json = pcall(json.decode, response_str) |
| 51 | |
| 52 | if not is_response_valid then |
| 53 | dovecot.i_info("Invalid JSON received: " .. response_str) |
| 54 | return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Invalid response format" |
| 55 | end |
| 56 | |
| 57 | if response_json.success == true then |
| 58 | return dovecot.auth.PASSDB_RESULT_OK, "" |
| 59 | end |
| 60 | |
| 61 | return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, "Failed to authenticate" |
| 62 | end |
| 63 | |
| 64 | function auth_passdb_lookup(req) |
| 65 | return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, "" |
| 66 | end |