changeset 3802:f88e07630e4e

mod_rest: Add support for simple Bearer token auth Token specified in config
author Kim Alvefur <zash@zash.se>
date Tue, 31 Dec 2019 03:37:46 +0100
parents d59fb4dcf100
children dc2b5a412286
files mod_rest/README.markdown mod_rest/mod_rest.lua
diffstat 2 files changed, 18 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/mod_rest/README.markdown	Mon Dec 30 07:22:15 2019 +0100
+++ b/mod_rest/README.markdown	Tue Dec 31 03:37:46 2019 +0100
@@ -12,13 +12,11 @@
 
 # Usage
 
-Note that there is currently **no authentication**, so be careful with
-exposing the API endpoint to the Internet.
-
 ## Enabling
 
 ``` {.lua}
 Component "rest.example.net" "rest"
+rest_credentials = "Bearer dmVyeSBzZWNyZXQgdG9rZW4K"
 ```
 
 ## Sending stanzas
@@ -30,6 +28,7 @@
 
 ``` {.sh}
 curl https://prosody.example:5281/rest \
+    --oauth2-bearer dmVyeSBzZWNyZXQgdG9rZW4K \
     -H 'Content-Type: application/xmpp+xml' \
     --data-binary '<message type="chat" to="user@example.org">
             <body>Hello!</body>
@@ -45,6 +44,7 @@
 
 ``` {.sh}
 curl https://prosody.example:5281/rest \
+    --oauth2-bearer dmVyeSBzZWNyZXQgdG9rZW4K \
     -H 'Content-Type: application/xmpp+xml' \
     --data-binary '<iq type="get" to="example.net">
             <ping xmlns="urn:xmpp:ping"/>
@@ -62,6 +62,7 @@
 
 ``` {.lua}
 Component "rest.example.net" "rest"
+rest_credentials = "Bearer dmVyeSBzZWNyZXQgdG9rZW4K"
 rest_callback_url = "http://my-api.example:9999/stanzas"
 ```
 
--- a/mod_rest/mod_rest.lua	Mon Dec 30 07:22:15 2019 +0100
+++ b/mod_rest/mod_rest.lua	Tue Dec 31 03:37:46 2019 +0100
@@ -13,9 +13,23 @@
 
 local allow_any_source = module:get_host_type() == "component";
 local validate_from_addresses = module:get_option_boolean("validate_from_addresses", true);
+local secret = assert(module:get_option_string("rest_credentials"), "rest_credentials is a required setting");
+local auth_type = assert(secret:match("^%S+"), "Format of rest_credentials MUST be like 'Bearer secret'");
+assert(auth_type == "Bearer", "Only 'Bearer' is supported in rest_credentials");
+
+-- Bearer token
+local function check_credentials(request)
+	return request.headers.authorization == secret;
+end
 
 local function handle_post(event)
 	local request, response = event.request, event.response;
+	if not request.headers.authorization then
+		response.headers.www_authenticate = ("%s realm=%q"):format(auth_type, module.host.."/"..module.name);
+		return 401;
+	elseif not check_credentials(request) then
+		return 401;
+	end
 	if request.headers.content_type ~= "application/xmpp+xml" then
 		return errors.new({ code = 415, text = "'application/xmpp+xml' expected"  });
 	end