Debian Codegraph @

docs/authentication.rst

raw
1 .. _authentication:
2
3 ================================
4 Authentication and permissions
5 ================================
6
7 Datasette does not require authentication by default. Any visitor to a Datasette instance can explore the full data and execute read-only SQL queries.
8
9 Datasette's plugin system can be used to add many different styles of authentication, such as user accounts, single sign-on or API keys.
10
11 .. _authentication_actor:
12
13 Actors
14 ======
15
16 Through plugins, Datasette can support both authenticated users (with cookies) and authenticated API agents (via authentication tokens). The word "actor" is used to cover both of these cases.
17
18 Every request to Datasette has an associated actor value, available in the code as ``request.actor``. This can be ``None`` for unauthenticated requests, or a JSON compatible Python dictionary for authenticated users or API agents.
19
20 The actor dictionary can be any shape - the design of that data structure is left up to the plugins. A useful convention is to include an ``"id"`` string, as demonstrated by the "root" actor below.
21
22 Plugins can use the :ref:`plugin_hook_actor_from_request` hook to implement custom logic for authenticating an actor based on the incoming HTTP request.
23
24 .. _authentication_root:
25
26 Using the "root" actor
27 ----------------------
28
29 Datasette currently leaves almost all forms of authentication to plugins - `datasette-auth-github <https://github.com/simonw/datasette-auth-github>`__ for example.
30
31 The one exception is the "root" account, which you can sign into while using Datasette on your local machine. This provides access to a small number of debugging features.
32
33 To sign in as root, start Datasette using the ``--root`` command-line option, like this::
34
35 $ datasette --root
36 http://127.0.0.1:8001/-/auth-token?token=786fc524e0199d70dc9a581d851f466244e114ca92f33aa3b42a139e9388daa7
37 INFO: Started server process [25801]
38 INFO: Waiting for application startup.
39 INFO: Application startup complete.
40 INFO: Uvicorn running on http://127.0.0.1:8001 (Press CTRL+C to quit)
41
42 The URL on the first line includes a one-use token which can be used to sign in as the "root" actor in your browser. Click on that link and then visit ``http://127.0.0.1:8001/-/actor`` to confirm that you are authenticated as an actor that looks like this:
43
44 .. code-block:: json
45
46 {
47 "id": "root"
48 }
49
50 .. _authentication_permissions:
51
52 Permissions
53 ===========
54
55 Datasette has an extensive permissions system built-in, which can be further extended and customized by plugins.
56
57 The key question the permissions system answers is this:
58
59 Is this **actor** allowed to perform this **action**, optionally against this particular **resource**?
60
61 **Actors** are :ref:`described above <authentication_actor>`.
62
63 An **action** is a string describing the action the actor would like to perform. A full list is :ref:`provided below <permissions>` - examples include ``view-table`` and ``execute-sql``.
64
65 A **resource** is the item the actor wishes to interact with - for example a specific database or table. Some actions, such as ``permissions-debug``, are not associated with a particular resource.
66
67 Datasette's built-in view permissions (``view-database``, ``view-table`` etc) default to *allow* - unless you :ref:`configure additional permission rules <authentication_permissions_metadata>` unauthenticated users will be allowed to access content.
68
69 Permissions with potentially harmful effects should default to *deny*. Plugin authors should account for this when designing new plugins - for example, the `datasette-upload-csvs <https://github.com/simonw/datasette-upload-csvs>`__ plugin defaults to deny so that installations don't accidentally allow unauthenticated users to create new tables by uploading a CSV file.
70
71 .. _authentication_permissions_allow:
72
73 Defining permissions with "allow" blocks
74 ----------------------------------------
75
76 The standard way to define permissions in Datasette is to use an ``"allow"`` block. This is a JSON document describing which actors are allowed to perform a permission.
77
78 The most basic form of allow block is this (`allow demo <https://latest.datasette.io/-/allow-debug?actor=%7B%22id%22%3A+%22root%22%7D&allow=%7B%0D%0A++++++++%22id%22%3A+%22root%22%0D%0A++++%7D>`__, `deny demo <https://latest.datasette.io/-/allow-debug?actor=%7B%22id%22%3A+%22trevor%22%7D&allow=%7B%0D%0A++++++++%22id%22%3A+%22root%22%0D%0A++++%7D>`__):
79
80 .. code-block:: json
81
82 {
83 "allow": {
84 "id": "root"
85 }
86 }
87
88 This will match any actors with an ``"id"`` property of ``"root"`` - for example, an actor that looks like this:
89
90 .. code-block:: json
91
92 {
93 "id": "root",
94 "name": "Root User"
95 }
96
97 An allow block can specify "deny all" using ``false`` (`demo <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22root%22%0D%0A%7D&allow=false>`__):
98
99 .. code-block:: json
100
101 {
102 "allow": false
103 }
104
105 An ``"allow"`` of ``true`` allows all access (`demo <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22root%22%0D%0A%7D&allow=true>`__):
106
107 .. code-block:: json
108
109 {
110 "allow": true
111 }
112
113 Allow keys can provide a list of values. These will match any actor that has any of those values (`allow demo <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22cleopaws%22%0D%0A%7D&allow=%7B%0D%0A++++%22id%22%3A+%5B%0D%0A++++++++%22simon%22%2C%0D%0A++++++++%22cleopaws%22%0D%0A++++%5D%0D%0A%7D>`__, `deny demo <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22pancakes%22%0D%0A%7D&allow=%7B%0D%0A++++%22id%22%3A+%5B%0D%0A++++++++%22simon%22%2C%0D%0A++++++++%22cleopaws%22%0D%0A++++%5D%0D%0A%7D>`__):
114
115 .. code-block:: json
116
117 {
118 "allow": {
119 "id": ["simon", "cleopaws"]
120 }
121 }
122
123 This will match any actor with an ``"id"`` of either ``"simon"`` or ``"cleopaws"``.
124
125 Actors can have properties that feature a list of values. These will be matched against the list of values in an allow block. Consider the following actor:
126
127 .. code-block:: json
128
129 {
130 "id": "simon",
131 "roles": ["staff", "developer"]
132 }
133
134 This allow block will provide access to any actor that has ``"developer"`` as one of their roles (`allow demo <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22simon%22%2C%0D%0A++++%22roles%22%3A+%5B%0D%0A++++++++%22staff%22%2C%0D%0A++++++++%22developer%22%0D%0A++++%5D%0D%0A%7D&allow=%7B%0D%0A++++%22roles%22%3A+%5B%0D%0A++++++++%22developer%22%0D%0A++++%5D%0D%0A%7D>`__, `deny demo <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22cleopaws%22%2C%0D%0A++++%22roles%22%3A+%5B%22dog%22%5D%0D%0A%7D&allow=%7B%0D%0A++++%22roles%22%3A+%5B%0D%0A++++++++%22developer%22%0D%0A++++%5D%0D%0A%7D>`__):
135
136 .. code-block:: json
137
138 {
139 "allow": {
140 "roles": ["developer"]
141 }
142 }
143
144 Note that "roles" is not a concept that is baked into Datasette - it's a convention that plugins can choose to implement and act on.
145
146 If you want to provide access to any actor with a value for a specific key, use ``"*"``. For example, to match any logged-in user specify the following (`allow demo <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22simon%22%0D%0A%7D&allow=%7B%0D%0A++++%22id%22%3A+%22*%22%0D%0A%7D>`__, `deny demo <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22bot%22%3A+%22readme-bot%22%0D%0A%7D&allow=%7B%0D%0A++++%22id%22%3A+%22*%22%0D%0A%7D>`__):
147
148 .. code-block:: json
149
150 {
151 "allow": {
152 "id": "*"
153 }
154 }
155
156 You can specify that only unauthenticated actors (from anonymous HTTP requests) should be allowed access using the special ``"unauthenticated": true`` key in an allow block (`allow demo <https://latest.datasette.io/-/allow-debug?actor=null&allow=%7B%0D%0A++++%22unauthenticated%22%3A+true%0D%0A%7D>`__, `deny demo <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22hello%22%0D%0A%7D&allow=%7B%0D%0A++++%22unauthenticated%22%3A+true%0D%0A%7D>`__):
157
158 .. code-block:: json
159
160 {
161 "allow": {
162 "unauthenticated": true
163 }
164 }
165
166 Allow keys act as an "or" mechanism. An actor will be able to execute the query if any of their JSON properties match any of the values in the corresponding lists in the ``allow`` block. The following block will allow users with either a ``role`` of ``"ops"`` OR users who have an ``id`` of ``"simon"`` or ``"cleopaws"``:
167
168 .. code-block:: json
169
170 {
171 "allow": {
172 "id": ["simon", "cleopaws"],
173 "role": "ops"
174 }
175 }
176
177 `Demo for cleopaws <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22cleopaws%22%0D%0A%7D&allow=%7B%0D%0A++++%22id%22%3A+%5B%0D%0A++++++++%22simon%22%2C%0D%0A++++++++%22cleopaws%22%0D%0A++++%5D%2C%0D%0A++++%22role%22%3A+%22ops%22%0D%0A%7D>`__, `demo for ops role <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22trevor%22%2C%0D%0A++++%22role%22%3A+%5B%0D%0A++++++++%22ops%22%2C%0D%0A++++++++%22staff%22%0D%0A++++%5D%0D%0A%7D&allow=%7B%0D%0A++++%22id%22%3A+%5B%0D%0A++++++++%22simon%22%2C%0D%0A++++++++%22cleopaws%22%0D%0A++++%5D%2C%0D%0A++++%22role%22%3A+%22ops%22%0D%0A%7D>`__, `demo for an actor matching neither rule <https://latest.datasette.io/-/allow-debug?actor=%7B%0D%0A++++%22id%22%3A+%22percy%22%2C%0D%0A++++%22role%22%3A+%5B%0D%0A++++++++%22staff%22%0D%0A++++%5D%0D%0A%7D&allow=%7B%0D%0A++++%22id%22%3A+%5B%0D%0A++++++++%22simon%22%2C%0D%0A++++++++%22cleopaws%22%0D%0A++++%5D%2C%0D%0A++++%22role%22%3A+%22ops%22%0D%0A%7D>`__.
178
179 .. _AllowDebugView:
180
181 The /-/allow-debug tool
182 -----------------------
183
184 The ``/-/allow-debug`` tool lets you try out different ``"action"`` blocks against different ``"actor"`` JSON objects. You can try that out here: https://latest.datasette.io/-/allow-debug
185
186 .. _authentication_permissions_metadata:
187
188 Configuring permissions in metadata.json
189 ========================================
190
191 You can limit who is allowed to view different parts of your Datasette instance using ``"allow"`` keys in your :ref:`metadata` configuration.
192
193 You can control the following:
194
195 * Access to the entire Datasette instance
196 * Access to specific databases
197 * Access to specific tables and views
198 * Access to specific :ref:`canned_queries`
199
200 If a user cannot access a specific database, they will not be able to access tables, views or queries within that database. If a user cannot access the instance they will not be able to access any of the databases, tables, views or queries.
201
202 .. _authentication_permissions_instance:
203
204 Controlling access to an instance
205 ---------------------------------
206
207 Here's how to restrict access to your entire Datasette instance to just the ``"id": "root"`` user:
208
209 .. code-block:: json
210
211 {
212 "title": "My private Datasette instance",
213 "allow": {
214 "id": "root"
215 }
216 }
217
218 To deny access to all users, you can use ``"allow": false``:
219
220 .. code-block:: json
221
222 {
223 "title": "My entirely inaccessible instance",
224 "allow": false
225 }
226
227 One reason to do this is if you are using a Datasette plugin - such as `datasette-permissions-sql <https://github.com/simonw/datasette-permissions-sql>`__ - to control permissions instead.
228
229 .. _authentication_permissions_database:
230
231 Controlling access to specific databases
232 ----------------------------------------
233
234 To limit access to a specific ``private.db`` database to just authenticated users, use the ``"allow"`` block like this:
235
236 .. code-block:: json
237
238 {
239 "databases": {
240 "private": {
241 "allow": {
242 "id": "*"
243 }
244 }
245 }
246 }
247
248 .. _authentication_permissions_table:
249
250 Controlling access to specific tables and views
251 -----------------------------------------------
252
253 To limit access to the ``users`` table in your ``bakery.db`` database:
254
255 .. code-block:: json
256
257 {
258 "databases": {
259 "bakery": {
260 "tables": {
261 "users": {
262 "allow": {
263 "id": "*"
264 }
265 }
266 }
267 }
268 }
269 }
270
271 This works for SQL views as well - you can list their names in the ``"tables"`` block above in the same way as regular tables.
272
273 .. warning::
274 Restricting access to tables and views in this way will NOT prevent users from querying them using arbitrary SQL queries, `like this <https://latest.datasette.io/fixtures?sql=select+*+from+facetable>`__ for example.
275
276 If you are restricting access to specific tables you should also use the ``"allow_sql"`` block to prevent users from bypassing the limit with their own SQL queries - see :ref:`authentication_permissions_execute_sql`.
277
278 .. _authentication_permissions_query:
279
280 Controlling access to specific canned queries
281 ---------------------------------------------
282
283 :ref:`canned_queries` allow you to configure named SQL queries in your ``metadata.json`` that can be executed by users. These queries can be set up to both read and write to the database, so controlling who can execute them can be important.
284
285 To limit access to the ``add_name`` canned query in your ``dogs.db`` database to just the :ref:`root user<authentication_root>`:
286
287 .. code-block:: json
288
289 {
290 "databases": {
291 "dogs": {
292 "queries": {
293 "add_name": {
294 "sql": "INSERT INTO names (name) VALUES (:name)",
295 "write": true,
296 "allow": {
297 "id": ["root"]
298 }
299 }
300 }
301 }
302 }
303 }
304
305 .. _authentication_permissions_execute_sql:
306
307 Controlling the ability to execute arbitrary SQL
308 ------------------------------------------------
309
310 Datasette defaults to allowing any site visitor to execute their own custom SQL queries, for example using the form on `the database page <https://latest.datasette.io/fixtures>`__ or by appending a ``?_where=`` parameter to the table page `like this <https://latest.datasette.io/fixtures/facetable?_where=_city_id=1>`__.
311
312 Access to this ability is controlled by the :ref:`permissions_execute_sql` permission.
313
314 The easiest way to disable arbitrary SQL queries is using the :ref:`default_allow_sql setting <setting_default_allow_sql>` when you first start Datasette running.
315
316 You can alternatively use an ``"allow_sql"`` block to control who is allowed to execute arbitrary SQL queries.
317
318 To prevent any user from executing arbitrary SQL queries, use this:
319
320 .. code-block:: json
321
322 {
323 "allow_sql": false
324 }
325
326 To enable just the :ref:`root user<authentication_root>` to execute SQL for all databases in your instance, use the following:
327
328 .. code-block:: json
329
330 {
331 "allow_sql": {
332 "id": "root"
333 }
334 }
335
336 To limit this ability for just one specific database, use this:
337
338 .. code-block:: json
339
340 {
341 "databases": {
342 "mydatabase": {
343 "allow_sql": {
344 "id": "root"
345 }
346 }
347 }
348 }
349
350 .. _permissions_plugins:
351
352 Checking permissions in plugins
353 ===============================
354
355 Datasette plugins can check if an actor has permission to perform an action using the :ref:`datasette.permission_allowed(...)<datasette_permission_allowed>` method.
356
357 Datasette core performs a number of permission checks, :ref:`documented below <permissions>`. Plugins can implement the :ref:`plugin_hook_permission_allowed` plugin hook to participate in decisions about whether an actor should be able to perform a specified action.
358
359 .. _authentication_actor_matches_allow:
360
361 actor_matches_allow()
362 =====================
363
364 Plugins that wish to implement this same ``"allow"`` block permissions scheme can take advantage of the ``datasette.utils.actor_matches_allow(actor, allow)`` function:
365
366 .. code-block:: python
367
368 from datasette.utils import actor_matches_allow
369
370 actor_matches_allow({"id": "root"}, {"id": "*"})
371 # returns True
372
373 The currently authenticated actor is made available to plugins as ``request.actor``.
374
375 .. _PermissionsDebugView:
376
377 The permissions debug tool
378 ==========================
379
380 The debug tool at ``/-/permissions`` is only available to the :ref:`authenticated root user <authentication_root>` (or any actor granted the ``permissions-debug`` action according to a plugin).
381
382 It shows the thirty most recent permission checks that have been carried out by the Datasette instance.
383
384 This is designed to help administrators and plugin authors understand exactly how permission checks are being carried out, in order to effectively configure Datasette's permission system.
385
386 .. _authentication_ds_actor:
387
388 The ds_actor cookie
389 ===================
390
391 Datasette includes a default authentication plugin which looks for a signed ``ds_actor`` cookie containing a JSON actor dictionary. This is how the :ref:`root actor <authentication_root>` mechanism works.
392
393 Authentication plugins can set signed ``ds_actor`` cookies themselves like so:
394
395 .. code-block:: python
396
397 response = Response.redirect("/")
398 response.set_cookie(
399 "ds_actor",
400 datasette.sign({"a": {"id": "cleopaws"}}, "actor"),
401 )
402
403 Note that you need to pass ``"actor"`` as the namespace to :ref:`datasette_sign`.
404
405 The shape of data encoded in the cookie is as follows::
406
407 {
408 "a": {... actor ...}
409 }
410
411 .. _authentication_ds_actor_expiry:
412
413 Including an expiry time
414 ------------------------
415
416 ``ds_actor`` cookies can optionally include a signed expiry timestamp, after which the cookies will no longer be valid. Authentication plugins may chose to use this mechanism to limit the lifetime of the cookie. For example, if a plugin implements single-sign-on against another source it may decide to set short-lived cookies so that if the user is removed from the SSO system their existing Datasette cookies will stop working shortly afterwards.
417
418 To include an expiry, add a ``"e"`` key to the cookie value containing a base62-encoded integer representing the timestamp when the cookie should expire. For example, here's how to set a cookie that expires after 24 hours:
419
420 .. code-block:: python
421
422 import time
423 from datasette.utils import baseconv
424
425 expires_at = int(time.time()) + (24 * 60 * 60)
426
427 response = Response.redirect("/")
428 response.set_cookie(
429 "ds_actor",
430 datasette.sign(
431 {
432 "a": {"id": "cleopaws"},
433 "e": baseconv.base62.encode(expires_at),
434 },
435 "actor",
436 ),
437 )
438
439 The resulting cookie will encode data that looks something like this:
440
441 .. code-block:: json
442
443 {
444 "a": {
445 "id": "cleopaws"
446 },
447 "e": "1jjSji"
448 }
449
450
451 .. _LogoutView:
452
453 The /-/logout page
454 ------------------
455
456 The page at ``/-/logout`` provides the ability to log out of a ``ds_actor`` cookie authentication session.
457
458 .. _permissions:
459
460 Built-in permissions
461 ====================
462
463 This section lists all of the permission checks that are carried out by Datasette core, along with the ``resource`` if it was passed.
464
465 .. _permissions_view_instance:
466
467 view-instance
468 -------------
469
470 Top level permission - Actor is allowed to view any pages within this instance, starting at https://latest.datasette.io/
471
472 Default *allow*.
473
474 .. _permissions_view_database:
475
476 view-database
477 -------------
478
479 Actor is allowed to view a database page, e.g. https://latest.datasette.io/fixtures
480
481 ``resource`` - string
482 The name of the database
483
484 Default *allow*.
485
486 .. _permissions_view_database_download:
487
488 view-database-download
489 -----------------------
490
491 Actor is allowed to download a database, e.g. https://latest.datasette.io/fixtures.db
492
493 ``resource`` - string
494 The name of the database
495
496 Default *allow*.
497
498 .. _permissions_view_table:
499
500 view-table
501 ----------
502
503 Actor is allowed to view a table (or view) page, e.g. https://latest.datasette.io/fixtures/complex_foreign_keys
504
505 ``resource`` - tuple: (string, string)
506 The name of the database, then the name of the table
507
508 Default *allow*.
509
510 .. _permissions_view_query:
511
512 view-query
513 ----------
514
515 Actor is allowed to view (and execute) a :ref:`canned query <canned_queries>` page, e.g. https://latest.datasette.io/fixtures/pragma_cache_size - this includes executing :ref:`canned_queries_writable`.
516
517 ``resource`` - tuple: (string, string)
518 The name of the database, then the name of the canned query
519
520 Default *allow*.
521
522 .. _permissions_execute_sql:
523
524 execute-sql
525 -----------
526
527 Actor is allowed to run arbitrary SQL queries against a specific database, e.g. https://latest.datasette.io/fixtures?sql=select+100
528
529 ``resource`` - string
530 The name of the database
531
532 Default *allow*. See also :ref:`the default_allow_sql setting <setting_default_allow_sql>`.
533
534 .. _permissions_permissions_debug:
535
536 permissions-debug
537 -----------------
538
539 Actor is allowed to view the ``/-/permissions`` debug page.
540
541 Default *deny*.
542
543 .. _permissions_debug_menu:
544
545 debug-menu
546 ----------
547
548 Controls if the various debug pages are displayed in the navigation menu.
549
550 Default *deny*.