-
-
Notifications
You must be signed in to change notification settings - Fork 702
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
datasette create-token
ability to create tokens with a reduced set of permissions
#1855
Comments
I'm going to delay working on this until after I have some of the write APIs built to try it against: |
Here's an interesting edge-case to consider: what if a user creates themselves a token for a specific table, then deletes that table, and waits for another user to create a table of the same name... and then uses their previously created token to write to the table that someone else created? Not sure if this is a threat I need to actively consider, but it's worth thinking a little bit about the implications of such a thing - since there will be APIs that allow users to create tables, and there may be cases where people want to have a concept of users "owning" specific tables. This is probably something that could be left for plugins to solve, but it still needs to be understood and potentially documented. There may even be a world in which tracking the timestamp at which a table was created becomes useful - because that could then be baked into API tokens, such that a token created BEFORE the table was created does not grant access to that table. |
My hunch on this is that anyone with that level of complex permissions requirements needs to be using a custom authentication plugin which includes much more concrete token rules, rather than the default signed stateless token implementation that ships with Datasette core. |
Maybe the way to do this is through a new standard mechanism on the actor: a set of additional restrictions, e.g.:
The way this works is there's a default permission_allowed(datasette, actor, action, resource) hook which only consults these, and crucially just says NO if those rules do not match. In this way it would apply as an extra layer of permission rules over the defaults (which for this |
Built a prototype of the above: diff --git a/datasette/default_permissions.py b/datasette/default_permissions.py
index 32b0c758..f68aa38f 100644
--- a/datasette/default_permissions.py
+++ b/datasette/default_permissions.py
@@ -6,8 +6,8 @@ import json
import time
-@hookimpl(tryfirst=True)
-def permission_allowed(datasette, actor, action, resource):
+@hookimpl(tryfirst=True, specname="permission_allowed")
+def permission_allowed_default(datasette, actor, action, resource):
async def inner():
if action in (
"permissions-debug",
@@ -57,6 +57,44 @@ def permission_allowed(datasette, actor, action, resource):
return inner
+@hookimpl(specname="permission_allowed")
+def permission_allowed_actor_restrictions(actor, action, resource):
+ if actor is None:
+ return None
+ _r = actor.get("_r")
+ if not _r:
+ # No restrictions, so we have no opinion
+ return None
+ action_initials = "".join([word[0] for word in action.split("-")])
+ # If _r is defined then we use those to further restrict the actor
+ # Crucially, we only use this to say NO (return False) - we never
+ # use it to return YES (True) because that might over-ride other
+ # restrictions placed on this actor
+ all_allowed = _r.get("a")
+ if all_allowed is not None:
+ assert isinstance(all_allowed, list)
+ if action_initials in all_allowed:
+ return None
+ # How about for the current database?
+ if action in ("view-database", "view-database-download", "execute-sql"):
+ database_allowed = _r.get("d", {}).get(resource)
+ if database_allowed is not None:
+ assert isinstance(database_allowed, list)
+ if action_initials in database_allowed:
+ return None
+ # Or the current table? That's any time the resource is (database, table)
+ if not isinstance(resource, str) and len(resource) == 2:
+ database, table = resource
+ table_allowed = _r.get("t", {}).get(database, {}).get(table)
+ # TODO: What should this do for canned queries?
+ if table_allowed is not None:
+ assert isinstance(table_allowed, list)
+ if action_initials in table_allowed:
+ return None
+ # This action is not specifically allowed, so reject it
+ return False
+
+
@hookimpl
def actor_from_request(datasette, request):
prefix = "dstok_"
|
That still needs comprehensive tests before I land it. |
New mechanism for restricting permissions further for a given actor. This still needs documentation. It will eventually be used by the mechanism to issue signed API tokens that are only able to perform a subset of actions. This also adds tests that exercise the POST /-/permissions tool, refs #1881
Added the tests. |
The Right now that command looks like this:
(The Syntax for adding "insert row" for everything, "update row" for all in the "data" database and "delete row" just for the docs / titles table:
The
Short versions: UPDATE: I have decided to use the term So |
Also made a few tweaks to how _r works in tokens and actors, refs #1855 - I needed that mechanism for the tests.
That commit there 6da17d5 (which will be squash-merged in a PR later on) made it so that I needed that mechanism to write a test that exercised different API permissions. |
The hardest piece here is the UI. I'm going to implement the CLI command first. |
I was going to have the CLI command throw an error if you attempt to use a permission that isn't registered with Datasette, but then I remembered that one of the uses for the CLI tool is to create signed tokens that will work against other Datasette instances (via the So I might have it output warnings instead. |
I'm going to rename "t" in the magic format to "r" for resource. |
Initial prototype of the diff --git a/datasette/default_permissions.py b/datasette/default_permissions.py
index 406dae40..bbe1247e 100644
--- a/datasette/default_permissions.py
+++ b/datasette/default_permissions.py
@@ -278,17 +278,55 @@ def register_commands(cli):
help="Token should expire after this many seconds",
type=int,
)
+ @click.option(
+ "alls",
+ "-a",
+ "--all",
+ type=str,
+ multiple=True,
+ help="Restrict token to this permission",
+ )
+ @click.option(
+ "databases",
+ "-d",
+ "--database",
+ type=(str, str),
+ multiple=True,
+ help="Restrict token to this permission on this database",
+ )
+ @click.option(
+ "resources",
+ "-r",
+ "--resource",
+ type=(str, str, str),
+ multiple=True,
+ help="Restrict token to this permission on this database resource (a table, SQL view or named query)",
+ )
@click.option(
"--debug",
help="Show decoded token",
is_flag=True,
)
- def create_token(id, secret, expires_after, debug):
+ def create_token(id, secret, expires_after, alls, databases, resources, debug):
"Create a signed API token for the specified actor ID"
ds = Datasette(secret=secret)
bits = {"a": id, "token": "dstok", "t": int(time.time())}
if expires_after:
bits["d"] = expires_after
+ if alls or databases or resources:
+ bits["_r"] = {}
+ if alls:
+ bits["_r"]["a"] = list(alls)
+ if databases:
+ bits["_r"]["d"] = {}
+ for database, action in databases:
+ bits["_r"]["d"].setdefault(database, []).append(action)
+ if resources:
+ bits["_r"]["r"] = {}
+ for database, table, action in resources:
+ bits["_r"]["r"].setdefault(database, {}).setdefault(
+ table, []
+ ).append(action)
token = ds.sign(bits, namespace="token")
click.echo("dstok_{}".format(token))
if debug: Still needs tests, plus I'd like it to use abbreviations if available to keep the token length shorter. |
I just noticed this in the existing code: datasette/datasette/default_permissions.py Lines 195 to 203 in c5d30b5
Hard-coding those action names should not be necessary any more, especially now we have |
Help looks like this:
|
I'm going to move this code into |
For the tests for |
Decided to do the |
datasette create-token
ability to create tokens with a reduced set of permissions
Initial design ideas: #1852 (comment)
Remaining tasks
datasette create-token
commanddatasette create-token
optionspermission_allowed_actor_restrictions
functionThe text was updated successfully, but these errors were encountered: