Appauth plugin: WIP

This commit is contained in:
Gina Häußge committed 2018-09-29 15:00:26 +02:00
1 parent 4e3adcc3f3
commit b428faacc8
3 files changed
+480

No files matched your search

+269
View File
@@ -0,0 +1,269 @@
# coding=utf-8
from __future__ import absolute_import
import flask
import threading
import os
from binascii import hexlify
from collections import defaultdict
import octoprint.plugin
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, no_firstrun_access
from octoprint.server import NO_CONTENT, current_user, user_permission
class AppAlreadyExists(Exception):
pass
class PendingDecision(object):
def __init__(self, app_id, app_token, user_id, user_token):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.user_token = user_token
def external(self):
return dict(app_id=self.app_id,
user_id=self.user_id,
user_token=self.user_token)
class ReadyDecision(object):
def __init__(self, app_id, app_token, user_id, api_key):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.api_key = api_key
@classmethod
def for_pending(cls, pending, api_key):
return cls(pending.app_id, pending.app_token, pending.user_id, api_key)
class ActiveKey(object):
def __init__(self, app_id, api_key):
self.app_id = app_id
self.api_key = api_key
def external(self):
return dict(app_id=self.app_id,
api_key=self.api_key)
class AppAuthPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
def __init__(self):
self._pending_decisions = []
self._pending_lock = threading.RLock()
self._ready_decisions = []
self._ready_lock = threading.RLock()
self._keys = defaultdict(list)
self._keys_lock = threading.RLock()
##-- AssetPlugin hooks
def get_assets(self):
return dict(js=["js/appauth.js"])
##~~ BlueprintPlugin mixin
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
@no_firstrun_access
def handle_request(self):
data = flask.request.json
if not "app" in data:
return flask.make_response("No app name provided", 400)
app_name = data["app"]
user_id = None
if "user" in data:
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access",
app_name=app_name,
user_token=user_token,
user_id=user_id))
response = flask.jsonify(app_token=app_token)
response.status_code = 202
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
return response
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
@no_firstrun_access
def handle_decision_poll(self, app_token):
if self._is_pending(app_token):
return flask.make_response("Awaiting decision", 202)
result = self._get_decision(app_token)
if result is not None:
return flask.jsonify(api_key=result)
return flask.abort(404)
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
@restricted_access
def handle_decision(self, user_token):
data = flask.request.json
if not "decision" in data:
return flask.make_response("No decision provided", 400)
decision = data["decision"] in valid_boolean_trues
user_id = current_user.get_name()
result = self._set_decision(user_token, decision, user_id)
if not result:
return flask.abort(404)
return NO_CONTENT
def is_blueprint_protected(self):
return False # No API key required to request API access
##~~ SimpleApiPlugin mixin
def get_api_commands(self):
return dict(generate=["app"],
revoke=["key"])
def on_api_get(self, request):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
return flask.jsonify(keys=map(lambda x: x.external(), self._api_keys_for_user(user_id)),
pending=dict((x.user_token, x.external()) for x in self._get_pending(user_id)))
def on_api_command(self, command, data):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if command == "revoke":
api_key = data.get("key")
if not api_key:
return flask.abort(400)
self._delete_api_key(user_id, api_key)
elif command == "generate":
# manual generateKey
app_name = data.get("app")
if not app_name:
return flask.abort(400)
api_key = self._generate_key()
try:
self._add_api_key(user_id, app_name.trim(), api_key)
except AppAlreadyExists:
return flask.abort(409)
return NO_CONTENT
##~~ key validator hook
def validate_api_key(self, api_key, *args, **kwargs):
return self._user_for_api_key(api_key)
##~~ Helpers
def _add_pending_decision(self, app_name, user_id=None):
app_token = self._generate_key()
user_token = self._generate_key()
with self._pending_lock:
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token))
return app_token, user_token
def _is_pending(self, app_token):
with self._pending_lock:
for data in self._pending_decisions:
if data.app_token == app_token:
return True
return False
def _get_pending(self, user_id):
result = []
with self._pending_lock:
for data in self._pending_decisions:
if data.user_id == user_id or data.user_id is None:
result.append(data)
return result
def _set_decision(self, user_token, decision, user_id):
with self._pending_lock:
for data in self._pending_decisions:
if data.user_token == user_token and (data.user_id == user_id or data.user_id is None):
pending = data
break
else:
return False # not found
if decision:
with self._ready_lock:
self._ready_decisions.append(ReadyDecision.for_pending(pending, self._generate_key()))
with self._pending_lock:
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
return True
def _get_decision(self, app_token):
with self._ready_lock:
for data in self._ready_decisions:
if data.app_token == app_token:
decision = data
break
else:
return False # not found
self._add_api_key(decision.user_id, decision.app_id, decision.api_key)
with self._ready_lock:
self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions)
return decision.api_key
def _add_api_key(self, user_id, app_name, api_key):
with self._keys_lock:
# TODO: persist to disk
for key in self._keys[user_id]:
if key.app_id.lower() == app_name.lower():
raise AppAlreadyExists("app {} does already exist".format(app_name))
self._keys[user_id].append(ActiveKey(app_name, api_key))
def _delete_api_key(self, user_id, api_key):
with self._keys_lock:
# TODO: persist to disk
self._keys[user_id] = filter(lambda x: x.api_key != api_key, self._keys[user_id])
def _user_for_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
if filter(lambda x: x.api_key == api_key, data):
return self._user_manager.findUser(userid=user_id)
return None
def _api_keys_for_user(self, user_id):
with self._keys_lock:
return self._keys.get(user_id, [])
def _generate_key(self):
return hexlify(os.urandom(16))
__plugin_name__ = "AppAuth Plugin"
__plugin_description__ = "TODO"
__plugin_author__ = "Gina Häußge, Aldo Hoeben"
__plugin_implementation__ = AppAuthPlugin()
__plugin_hooks__ = {
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
}
@@ -0,0 +1,169 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintAppAuthClient = function(base) {
this.base = base;
};
OctoPrintAppAuthClient.prototype.getKeys = function(opts) {
return this.base.simpleApiGet("appauth", opts);
};
OctoPrintAppAuthClient.prototype.generateKey = function(app, opts) {
return this.base.simpleApiCommand("appauth", "generate", {"app": app}, opts);
};
OctoPrintAppAuthClient.prototype.revokeKey = function(key, opts) {
return this.base.simpleApiCommand("appauth", "revoke", {"key": key}, opts);
};
OctoPrintAppAuthClient.prototype.decide = function(token, decision, opts) {
return this.base.postJson(this.base.getBlueprintUrl("appauth") + "decision/" + token, {decision: !!decision}, opts);
};
OctoPrintClient.registerPluginComponent("appauth", OctoPrintAppAuthClient);
return OctoPrintAppAuthClient;
});
$(function() {
function AppAuthViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.keys = new ItemListHelper(
"plugin.appauth.keys",
{
"app": function (a, b) {
// sorts descending
if (a["app"] > b["app"]) return -1;
if (a["app"] < b["app"]) return 1;
return 0;
}
},
{
},
"app",
[],
[],
10
);
self.pending = {};
self.openRequests = {};
self.editorApp = ko.observable();
self.requestData = function() {
OctoPrint.plugins.appauth.getKeys()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
self.keys.updateItems(response.keys);
self.pending = response.pending;
_.each(self.pending, function(data, token) {
self.openRequests[token] = self.promptForAccess(data.app_id, token);
})
};
self.generateKey = function() {
return OctoPrint.plugins.appauth.generateKey(self.editorApp())
.done(self.requestData);
};
self.revokeKey = function(key) {
return OctoPrint.plugins.appauth.revokeKey(key)
.done(self.requestData);
};
self.allowApp = function(token) {
return OctoPrint.plugins.appauth.decide(token, true)
.done(self.requestData);
};
self.denyApp = function(token) {
return OctoPrint.plugins.appauth.decide(token, false)
.done(self.requestData);
};
self.promptForAccess = function(app, token) {
var message = gettext("\"%(app)s\" has requested access to control OctoPrint through the API. Do you want to allow access to this application with your user account?");
message = _.sprintf(message, {app: app});
return new PNotify({
title: gettext("Access Request"),
text: message,
confirm: {
confirm: true,
buttons: [{
text: gettext("Allow"),
click: function(notice) {
self.allowApp(token);
}
}, {
text: gettext("Deny"),
click: function(notice) {
self.denyApp(token);
}
}]
},
buttons: {
sticker: false,
closer: false
}
});
};
self.onUserSettingsShown = function() {
self.requestData();
};
self.onUserLoggedIn = function() {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (plugin !== "appauth") {
return;
}
var app, token, user;
if (data.type === "request_access" && self.loginState.isUser()) {
app = data.app_name;
token = data.user_token;
user = data.user_id;
if (user && user !== self.loginState.username()) {
return;
}
if (self.pending[token] === undefined) {
return;
}
self.openRequests[token] = self.promptForAccess(app, token);
} else if (data.type === "end_request") {
token = data.user_token;
if (self.openRequests[token] !== undefined) {
// another instance responded to the access request before the current user did
if (self.openRequests[token].state !== "closed") {
self.openRequests[token].remove();
}
delete self.openRequests[token]
}
}
};
}
OCTOPRINT_VIEWMODELS.push([
AppAuthViewModel,
["loginStateViewModel"],
["#usersettings_plugin_appauth"]
]);
});
@@ -0,0 +1,42 @@
<table class="table table-condensed table-hover" id="settings_plugin_appauth_keys_table">
<thead>
<tr>
<th class="settings_plugin_appauth_keys_app">{{ _('Application') }}</th>
<th class="settings_plugin_appauth_keys_actions">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: keys.paginatedItems">
<tr>
<td class="settings_plugin_appauth_keys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span></small></td>
<td class="settings_plugin_appauth_keys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key) }"></a></td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: keys.pages">
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
</ul>
</div>
<hr>
<form class="form-horizontal">
<div class="control-group">
<label>App</label>
<div class="controls">
<input type="text" data-bind="value: editorApp">
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="click: generateKey">{{ _('Generate app key') }}</button>
</div>
</div>
</form>