Anyone not signed in holds the guest role

Whether somebody with no account may see something was being answered one
feature at a time: a securesend_allow_guests setting, an enable flag per kiosk,
and very nearly a third for guides - each with its own settings page, its own
vocabulary and its own hand-written branch inside a route. Every one of them
answered a permissions question, and this app already administers permissions
per role.

So a caller with no token is not nobody: they hold the seeded `guest` role.
require_permission consults it when there is no identity, which is the entire
mechanism. The role is seeded holding NOTHING, so an upgrade opens no door; a
site opens one by ticking a box in the same grid it uses for every other role,
and closes it the same way. Revocation is read on every request rather than
cached, because taking guest access away is what somebody does the moment they
realise what they opened, and it has to bite immediately.

The redundant @jwt_required() above require_permission is gone from 184 routes.
It was belt-and-braces before; now it is actively wrong, because it refuses a
request with no token before the permission check can have an opinion, so a
grant would appear to do nothing.

What a guest may hold is bounded. Any .view or .read permission is grantable.
A WRITE has to be blessed by whoever owns it, through the new
get_guest_grantable_permissions hook (contract 0.21.0), and Secure Send is the
only case that exists: sending a password to a vendor is the one write this
product means to offer somebody who never signs in. Everything else is refused
by the API and greyed out in the grid rather than warned about - a checkbox
that quietly makes deleting an asset anonymous is not a warning anybody reads
twice. A guest write records no creator: the trail says when and from where,
never who, and that is the reason for the bar.

GE-Enforce and Slides gained read permissions so they can be opened to guests
without handing out the manage right. Their read routes accept either through
require_any_permission, so nothing an existing manager could reach has moved.

The navigation endpoint now returns only what the caller can actually reach.
Without that a signed-out visitor gets a sidebar of the whole app where every
link bounces off the login page, which reads as a broken site rather than as a
closed door. A nav item may name several permissions; holding any one is
enough, which is what GE-Enforce and Slides need now that a viewer and a
manager hold different strings.

Two things this found on the way: current_user is a LocalProxy, so
`current_user is None` is False for a request with nobody behind it - harmless
under a required JWT, an AttributeError the moment verification became
optional. And an image pasted into a guide before its first save was never
attached to it, so it was visible to editors and invisible to every reader;
saving now attaches it, and `flask guides fix-images` repairs what is stored.

The guides guest setting written earlier today is gone. Granting guides.view to
the guest role replaces it, which is the point.
This commit is contained in:
cproudlock
2026-08-27 12:51:58 -04:00
parent 8531559f22
commit 151d7c4f44
44 changed files with 783 additions and 240 deletions

View File

@@ -12,6 +12,34 @@ ADR-007 and ADR-002.
### Added ### Added
- **A guest is a role now, not a switch per feature.** Whether somebody with no
account may see something was answered one feature at a time: a
`securesend_allow_guests` setting, an enable flag per kiosk, and very nearly a
third for guides - each with its own settings page and its own hand-written
branch inside a route. It is a permissions question, and this app already
administers permissions per role, so anyone not signed in now holds the
seeded `guest` role. It starts with nothing, so an upgrade opens no door; a
site opens one by ticking a box in the same role grid it uses for everybody
else, and closes it the same way - taking effect on the next request, not the
next restart. `require_permission` consults the role when there is no token,
which is the whole mechanism.
What a guest may be granted is bounded: any `.view` or `.read` permission,
plus writes a plugin has explicitly declared safe to perform without an
account (`get_guest_grantable_permissions`, contract 0.21.0). Secure Send
declares its create permission, because sending a password to a vendor is the
one write the product means to offer somebody who never signs in. Everything
else is refused by the API and greyed out in the grid rather than warned
about. A guest write records no creator - the audit trail can say when and
from where, never who - and that is the reason for the bar.
GE-Enforce and Slides gained read permissions (`geenforce.view`,
`slides.view`) so they can be opened to guests without handing out the manage
right; their read routes accept either, so nothing an existing manager could
reach has moved. The navigation endpoint now returns only what the caller can
actually reach, so a signed-out visitor sees the pages that were opened to
them rather than a sidebar of links that bounce off a login page.
- **USB check-in / check-out audit report.** CMMC removable-media tracking is an - **USB check-in / check-out audit report.** CMMC removable-media tracking is an
audit obligation and there was no report for it - answering "who had this audit obligation and there was no report for it - answering "who had this
drive, and when" meant paging through the check-in/out list by hand. The drive, and when" meant paging through the check-in/out list by hand. The

View File

@@ -40,6 +40,7 @@ Recorded in the comment block in `shopdb/__init__.py`:
| 0.18.0 | Added `DISPLAY_ROLES`, `DISPLAY_ROLE_PATHS` and `normalize_display_role`, and finally exported `DashboardDefault`, which 0.17.0 imported but left out of `__all__`. The role vocabulary became the kiosk's own - `Dashboard`, `Lobby`, `3DPrintRoom` - so a plugin holding its own copy of that map reads core's instead of drifting from it | additive surface (minor) | | 0.18.0 | Added `DISPLAY_ROLES`, `DISPLAY_ROLE_PATHS` and `normalize_display_role`, and finally exported `DashboardDefault`, which 0.17.0 imported but left out of `__all__`. The role vocabulary became the kiosk's own - `Dashboard`, `Lobby`, `3DPrintRoom` - so a plugin holding its own copy of that map reads core's instead of drifting from it | additive surface (minor) |
| 0.19.0 | **BREAKING.** `get_dashboard_widgets` returns DATA AND SHAPE, not a component name. The old shape (`name` + `component` + `size`) named a Vue component per widget, which cannot survive a lean build - a plugin's component may never be staged into the frontend bundle (ADR-013) - and five plugins were declaring widgets that pointed at components nobody had written. A card now declares `id` / `title` / `endpoint` / `render` / `severity` / `permission` / `empty` / `position`; see PLUGIN-HOOKS.md. Also added `send_upload` so a plugin serving user-supplied bytes gets the headers that keep an SVG from running as script | **contract change (minor, pre-1.0)** | | 0.19.0 | **BREAKING.** `get_dashboard_widgets` returns DATA AND SHAPE, not a component name. The old shape (`name` + `component` + `size`) named a Vue component per widget, which cannot survive a lean build - a plugin's component may never be staged into the frontend bundle (ADR-013) - and five plugins were declaring widgets that pointed at components nobody had written. A card now declares `id` / `title` / `endpoint` / `render` / `severity` / `permission` / `empty` / `position`; see PLUGIN-HOOKS.md. Also added `send_upload` so a plugin serving user-supplied bytes gets the headers that keep an SVG from running as script | **contract change (minor, pre-1.0)** |
| 0.20.0 | The `Asset` model gained `levelid` (which floor plan its `mapx`/`mapy` are pixels of) and `mapverifiedat`; `Location` gained `levelid` too, and `resolve_asset_position` now returns the `levelid` belonging to whichever source supplied the coordinates. A plugin that writes a map position MUST write the level with it - a position without one renders as "level unknown" rather than being drawn on the default drawing, because a marker on the wrong floor plan looks correct (ADR-017) | additive surface (minor) | | 0.20.0 | The `Asset` model gained `levelid` (which floor plan its `mapx`/`mapy` are pixels of) and `mapverifiedat`; `Location` gained `levelid` too, and `resolve_asset_position` now returns the `levelid` belonging to whichever source supplied the coordinates. A plugin that writes a map position MUST write the level with it - a position without one renders as "level unknown" rather than being drawn on the default drawing, because a marker on the wrong floor plan looks correct (ADR-017) | additive surface (minor) |
| 0.21.0 | Added the `get_guest_grantable_permissions` hook: a plugin names the WRITE permissions a site may grant to the seeded `guest` role, which is who anyone without a token now holds. Reads (`.view`/`.read`) are grantable without a plugin saying anything; anything else is refused. Also exposed `require_any_permission` on `shopdb.api` for a read two different rights should reach | additive optional hook + surface (minor) |
The source comment block documents 0.3.0, 0.4.0, 0.6.0, 0.7.0, 0.9.0, 0.10.0, The source comment block documents 0.3.0, 0.4.0, 0.6.0, 0.7.0, 0.9.0, 0.10.0,
0.11.0, 0.16.0, 0.18.0 and 0.19.0; 0.12.0 through 0.15.0 and 0.17.0 are recorded 0.11.0, 0.16.0, 0.18.0 and 0.19.0; 0.12.0 through 0.15.0 and 0.17.0 are recorded

View File

@@ -298,6 +298,40 @@ The `Permission` ROWS already in the database are NOT deleted, so roles that
already reference them keep working until an admin edits the role. A broken already reference them keep working until an admin edits the role. A broken
plugin is isolated in prod and re-raised in dev/test. plugin is isolated in prod and re-raised in dev/test.
### `get_guest_grantable_permissions() -> List[str]`
Names the WRITE permissions this plugin allows a site to grant to the `guest`
role. Added in contract 0.21.0.
Anyone with no account holds the `guest` role. It is seeded with nothing, and a
site opens a door by granting it a permission in the role grid - which replaced
the per-feature booleans (`securesend_allow_guests`, one per kiosk) that used to
answer the same question one feature at a time.
Any `.view` or `.read` permission is grantable without a plugin saying anything.
This hook is only for the exception: a write that is genuinely meant to work for
somebody who never signs in. Naming one here does not open it - it makes the
checkbox available, and a site still has to tick it.
```python
class ToolsPlugin(BasePlugin):
def get_guest_grantable_permissions(self):
# Sending a password to a vendor: the recipient has no account here,
# and often neither does the sender. The unguessable token is the
# authorisation and the link is one-view.
return ['tools.secrets']
```
The bar for naming one: could this action be attributed to nobody, forever, and
still be defensible in the audit log? A guest write records no creator - the
trail says when and from where, never who. Return `[]` (the default) and none of
this plugin's writes can ever be made anonymous; anything not named is refused
by the API when an admin tries to grant it, not merely warned about.
Consumed by `guest_grantable_permissions()`, which backs the role API's guard on
the guest role and the greyed-out checkboxes in the role grid. A plugin may only
bless permissions that already exist in the catalog, so a typo widens nothing.
### `get_settings_cards() -> List[Dict]` ### `get_settings_cards() -> List[Dict]`
Returns settings-catalog card definitions. Added in contract 0.7.0 (ADR-010). Returns settings-catalog card definitions. Added in contract 0.7.0 (ADR-010).

View File

@@ -12,7 +12,7 @@ never by editing this file.
| series | value | governed by | | series | value | governed by |
|---|---|---| |---|---|---|
| product `__version__` | `0.12.0` | ADR-007 | | product `__version__` | `0.12.0` | ADR-007 |
| plugin contract `__contract_version__` | `0.20.0` | ADR-002 | | plugin contract `__contract_version__` | `0.21.0` | ADR-002 |
They move independently. A contract bump is not a release. They move independently. A contract bump is not a release.
@@ -88,6 +88,6 @@ Manifest-less directories under `plugins/` are core frontend surface and always
## Size ## Size
- test functions defined: **1396** (parametrised cases collect higher) - test functions defined: **1413** (parametrised cases collect higher)
- documented API paths: **305** (`docs/openapi.json`, regenerate with `scripts/gen_openapi.py`) - documented API paths: **305** (`docs/openapi.json`, regenerate with `scripts/gen_openapi.py`)

View File

@@ -11,7 +11,9 @@
</div> </div>
</div> </div>
<div class="sidebar-search"> <!-- Global search is authenticated; offering the box to a signed-out
reader gives them a control that can only answer 401. -->
<div v-if="authStore.isAuthenticated" class="sidebar-search">
<input <input
v-model="searchQuery" v-model="searchQuery"
type="text" type="text"
@@ -222,8 +224,23 @@ function buildNavItems(items) {
// Drop items the user cannot reach: a nav item may carry a `permission` // Drop items the user cannot reach: a nav item may carry a `permission`
// (e.g. Slides -> slides.manage); hide it from anyone who lacks it so the // (e.g. Slides -> slides.manage); hide it from anyone who lacks it so the
// link does not dead-end at the router guard. Admins hold every permission. // link does not dead-end at the router guard. Admins hold every permission.
const visible = items.filter(item => //
!item.permission || authStore.hasPermission(item.permission)) // A signed-out visitor sees only what a plugin has declared guest-reachable.
// Without this the sidebar offers a signed-out reader the whole app and every
// link bounces them to the login page, which reads as a broken site rather
// than as a closed door.
// A nav item may name one permission or several; holding ANY of them is
// enough. GE-Enforce and Slides need that: the page is reachable by a
// manager and by a plain viewer, and they hold different strings.
const holds = item => {
if (!item.permission) return true
const names = Array.isArray(item.permission) ? item.permission : [item.permission]
return names.some(name => authStore.hasPermission(name))
}
// A signed-out visitor gets whatever the server sent, which is already
// filtered to what the guest role can reach - hasPermission knows nothing
// about guests, so asking it here would hide everything.
const visible = authStore.isAuthenticated ? items.filter(holds) : items
const known = new Set(NAV_SECTIONS.map(s => s.key).filter(Boolean)) const known = new Set(NAV_SECTIONS.map(s => s.key).filter(Boolean))
const bucket = item => { const bucket = item => {

View File

@@ -225,6 +225,17 @@
<p class="text-muted" style="font-size: 0.85rem; margin: 0 0 0.5rem 0"> <p class="text-muted" style="font-size: 0.85rem; margin: 0 0 0.5rem 0">
Select which actions this role can perform Select which actions this role can perform
</p> </p>
<!-- The guest role is everyone who is not signed in, so what it may
hold is bounded: reads, plus the few writes a plugin has
declared safe to do anonymously. The rest are disabled here
rather than refused on save, so the limit is visible while the
decision is being made. -->
<p v-if="editingRole?.isguest" class="guest-note">
This role is <strong>everyone who is not signed in</strong>.
Anything ticked here is readable by anybody who can reach this
site, with no account and no name in the audit log. Greyed-out
permissions cannot be given to guests at all.
</p>
<div class="permissions-grid"> <div class="permissions-grid">
<div v-for="(perms, category) in permissionsGrouped" :key="category" class="permission-category"> <div v-for="(perms, category) in permissionsGrouped" :key="category" class="permission-category">
<div class="category-header"> <div class="category-header">
@@ -239,10 +250,14 @@
</label> </label>
</div> </div>
<div class="category-perms"> <div class="category-perms">
<label v-for="p in perms" :key="p.name" class="checkbox-label perm-item"> <label v-for="p in perms" :key="p.name" class="checkbox-label perm-item"
:class="{ 'perm-blocked': !mayGrant(p.name) }"
:title="mayGrant(p.name) ? null
: 'A guest cannot be given this. Reading is grantable; a write has to be declared safe to do without an account.'">
<input <input
type="checkbox" type="checkbox"
:value="p.name" :value="p.name"
:disabled="!mayGrant(p.name)"
v-model="roleForm.permissions" v-model="roleForm.permissions"
> >
{{ p.description }} {{ p.description }}
@@ -382,19 +397,33 @@ function formatCategory(cat) {
return cat.charAt(0).toUpperCase() + cat.slice(1) return cat.charAt(0).toUpperCase() + cat.slice(1)
} }
// Which permissions this role is allowed to hold at all. Only the guest role
// is bounded; the API sends the list it will accept, so the grid and the server
// cannot disagree about it.
function mayGrant(name) {
if (!editingRole.value?.isguest) return true
const grantable = editingRole.value?.grantable
return Array.isArray(grantable) ? grantable.includes(name) : false
}
function isCategoryFullySelected(category) { function isCategoryFullySelected(category) {
const catPerms = permissionsGrouped.value[category] || [] const catPerms = (permissionsGrouped.value[category] || [])
.filter(p => mayGrant(p.name))
return catPerms.length > 0 && catPerms.every(p => roleForm.permissions.includes(p.name)) return catPerms.length > 0 && catPerms.every(p => roleForm.permissions.includes(p.name))
} }
function isCategoryPartiallySelected(category) { function isCategoryPartiallySelected(category) {
const catPerms = permissionsGrouped.value[category] || [] const catPerms = (permissionsGrouped.value[category] || [])
.filter(p => mayGrant(p.name))
const selected = catPerms.filter(p => roleForm.permissions.includes(p.name)) const selected = catPerms.filter(p => roleForm.permissions.includes(p.name))
return selected.length > 0 && selected.length < catPerms.length return selected.length > 0 && selected.length < catPerms.length
} }
function toggleCategory(category, checked) { function toggleCategory(category, checked) {
const catPerms = permissionsGrouped.value[category] || [] // Ticking a whole category must not try to grant a guest something the API
// will refuse - the header checkbox would then look broken.
const catPerms = (permissionsGrouped.value[category] || [])
.filter(p => mayGrant(p.name))
const permNames = catPerms.map(p => p.name) const permNames = catPerms.map(p => p.name)
if (checked) { if (checked) {
@@ -780,4 +809,13 @@ onMounted(loadData)
font-size: 0.85rem; font-size: 0.85rem;
padding: 0.25rem 0; padding: 0.25rem 0;
} }
.perm-blocked { opacity: 0.45; cursor: not-allowed; }
.guest-note {
font-size: 0.85rem;
color: var(--warning);
border-left: 3px solid var(--warning);
padding-left: 0.6rem;
margin: 0 0 0.75rem;
}
</style> </style>

View File

@@ -77,7 +77,6 @@ def _summary(revision, islatest=False):
@backups_bp.route('/kinds', methods=['GET']) @backups_bp.route('/kinds', methods=['GET'])
@jwt_required()
@require_permission('backups.view') @require_permission('backups.view')
def list_kinds(): def list_kinds():
"""Registered backup kinds, for UI that needs to enumerate them.""" """Registered backup kinds, for UI that needs to enumerate them."""
@@ -94,7 +93,6 @@ def list_kinds():
@backups_bp.route('/asset/<int:assetid>', methods=['GET']) @backups_bp.route('/asset/<int:assetid>', methods=['GET'])
@jwt_required()
@require_permission('backups.view') @require_permission('backups.view')
def asset_revisions(assetid): def asset_revisions(assetid):
"""Revision history for one asset, newest first. """Revision history for one asset, newest first.
@@ -130,7 +128,6 @@ def asset_revisions(assetid):
@backups_bp.route('/asset/<int:assetid>/info', methods=['GET']) @backups_bp.route('/asset/<int:assetid>/info', methods=['GET'])
@jwt_required()
@require_permission('backups.view') @require_permission('backups.view')
def asset_info(assetid): def asset_info(assetid):
"""A kind's 'at a glance' card, built from its LATEST revision. """A kind's 'at a glance' card, built from its LATEST revision.
@@ -190,7 +187,6 @@ def asset_info(assetid):
@backups_bp.route('/revisions/<int:backuprevisionid>', methods=['GET']) @backups_bp.route('/revisions/<int:backuprevisionid>', methods=['GET'])
@jwt_required()
@require_permission('backups.view') @require_permission('backups.view')
def get_revision(backuprevisionid): def get_revision(backuprevisionid):
"""One revision, including its parsed payload where there is one.""" """One revision, including its parsed payload where there is one."""
@@ -207,7 +203,6 @@ def get_revision(backuprevisionid):
@backups_bp.route('/revisions/<int:backuprevisionid>/download', methods=['GET']) @backups_bp.route('/revisions/<int:backuprevisionid>/download', methods=['GET'])
@jwt_required()
@require_permission('backups.download') @require_permission('backups.download')
def download_revision(backuprevisionid): def download_revision(backuprevisionid):
"""Render a revision back to its native file format. """Render a revision back to its native file format.
@@ -282,7 +277,6 @@ def download_revision(backuprevisionid):
@backups_bp.route('/revisions/<int:backuprevisionid>/diff', methods=['GET']) @backups_bp.route('/revisions/<int:backuprevisionid>/diff', methods=['GET'])
@jwt_required()
@require_permission('backups.view') @require_permission('backups.view')
def diff_revision(backuprevisionid): def diff_revision(backuprevisionid):
"""Diff two revisions of the same asset+kind. """Diff two revisions of the same asset+kind.
@@ -372,7 +366,6 @@ def _diffprojections(old, new):
@backups_bp.route('/dashboard/stale', methods=['GET']) @backups_bp.route('/dashboard/stale', methods=['GET'])
@jwt_required()
@require_permission('backups.view') @require_permission('backups.view')
def dashboard_stale(): def dashboard_stale():
"""Chains whose backup has stopped running. """Chains whose backup has stopped running.

View File

@@ -55,7 +55,6 @@ def get_computer_type(type_id: int):
@computers_bp.route('/types', methods=['POST']) @computers_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('computers.create') @require_permission('computers.create')
def create_computer_type(): def create_computer_type():
"""Create a new computer type.""" """Create a new computer type."""
@@ -93,7 +92,6 @@ def create_computer_type():
@computers_bp.route('/types/<int:type_id>', methods=['PUT']) @computers_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('computers.edit') @require_permission('computers.edit')
def update_computer_type(type_id: int): def update_computer_type(type_id: int):
"""Update a computer type.""" """Update a computer type."""
@@ -127,7 +125,6 @@ def update_computer_type(type_id: int):
@computers_bp.route('/types/<int:type_id>', methods=['DELETE']) @computers_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.delete') @require_permission('computers.delete')
def delete_computer_type(type_id: int): def delete_computer_type(type_id: int):
"""Delete a computer type. Refused if any PC still uses it.""" """Delete a computer type. Refused if any PC still uses it."""
@@ -159,7 +156,6 @@ def list_protocols():
@computers_bp.route('/protocols', methods=['POST']) @computers_bp.route('/protocols', methods=['POST'])
@jwt_required()
@require_permission('computers.edit') @require_permission('computers.edit')
def create_protocol(): def create_protocol():
data = request.get_json() or {} data = request.get_json() or {}
@@ -180,7 +176,6 @@ def create_protocol():
@computers_bp.route('/protocols/<int:protocol_id>', methods=['PUT', 'PATCH']) @computers_bp.route('/protocols/<int:protocol_id>', methods=['PUT', 'PATCH'])
@jwt_required()
@require_permission('computers.edit') @require_permission('computers.edit')
def update_protocol(protocol_id): def update_protocol(protocol_id):
p = db.session.get(AccessProtocol, protocol_id) p = db.session.get(AccessProtocol, protocol_id)
@@ -199,7 +194,6 @@ def update_protocol(protocol_id):
@computers_bp.route('/protocols/<int:protocol_id>', methods=['DELETE']) @computers_bp.route('/protocols/<int:protocol_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.edit') @require_permission('computers.edit')
def delete_protocol(protocol_id): def delete_protocol(protocol_id):
p = db.session.get(AccessProtocol, protocol_id) p = db.session.get(AccessProtocol, protocol_id)
@@ -505,7 +499,6 @@ def get_computer_by_hostname(hostname: str):
@computers_bp.route('', methods=['POST']) @computers_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('computers.create') @require_permission('computers.create')
def create_computer(): def create_computer():
""" """
@@ -620,7 +613,6 @@ def create_computer():
@computers_bp.route('/<int:computer_id>', methods=['PUT']) @computers_bp.route('/<int:computer_id>', methods=['PUT'])
@jwt_required()
@require_permission('computers.edit') @require_permission('computers.edit')
def update_computer(computer_id: int): def update_computer(computer_id: int):
"""Update computer (both Asset and Computer records).""" """Update computer (both Asset and Computer records)."""
@@ -732,7 +724,6 @@ def update_computer(computer_id: int):
@computers_bp.route('/<int:computer_id>', methods=['DELETE']) @computers_bp.route('/<int:computer_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.delete') @require_permission('computers.delete')
def delete_computer(computer_id: int): def delete_computer(computer_id: int):
"""Delete (soft delete) computer.""" """Delete (soft delete) computer."""
@@ -785,7 +776,6 @@ def get_installed_apps(computer_id: int):
@computers_bp.route('/<int:computer_id>/apps', methods=['POST']) @computers_bp.route('/<int:computer_id>/apps', methods=['POST'])
@jwt_required()
@require_permission('computers.create') @require_permission('computers.create')
def add_installed_app(computer_id: int): def add_installed_app(computer_id: int):
"""Add an installed application to a computer.""" """Add an installed application to a computer."""
@@ -842,7 +832,6 @@ def add_installed_app(computer_id: int):
@computers_bp.route('/<int:computer_id>/apps/<int:app_id>', methods=['DELETE']) @computers_bp.route('/<int:computer_id>/apps/<int:app_id>', methods=['DELETE'])
@jwt_required()
@require_permission('computers.delete') @require_permission('computers.delete')
def remove_installed_app(computer_id: int, app_id: int): def remove_installed_app(computer_id: int, app_id: int):
"""Remove an installed application from a computer.""" """Remove an installed application from a computer."""
@@ -870,7 +859,6 @@ def remove_installed_app(computer_id: int, app_id: int):
# ============================================================================= # =============================================================================
@computers_bp.route('/<int:computer_id>/report', methods=['POST']) @computers_bp.route('/<int:computer_id>/report', methods=['POST'])
@jwt_required()
@require_permission('computers.create') @require_permission('computers.create')
def report_status(computer_id: int): def report_status(computer_id: int):
""" """
@@ -954,7 +942,6 @@ def dashboard_summary():
@computers_bp.route('/dashboard/quiet', methods=['GET']) @computers_bp.route('/dashboard/quiet', methods=['GET'])
@jwt_required()
@require_permission('computers.view') @require_permission('computers.view')
def dashboard_quiet(): def dashboard_quiet():
"""PCs that WERE reporting, have stopped, and are still meant to be in use. """PCs that WERE reporting, have stopped, and are still meant to be in use.
@@ -1008,7 +995,6 @@ def dashboard_quiet():
@computers_bp.route('/dashboard/sharedmachines', methods=['GET']) @computers_bp.route('/dashboard/sharedmachines', methods=['GET'])
@jwt_required()
@require_permission('computers.view') @require_permission('computers.view')
def dashboard_sharedmachines(): def dashboard_sharedmachines():
"""Machine numbers claimed by more than one PC, with nothing filed under """Machine numbers claimed by more than one PC, with nothing filed under

View File

@@ -20,6 +20,7 @@ from sqlalchemy.exc import IntegrityError
from shopdb.api import ( from shopdb.api import (
db, cache, success_response, error_response, ErrorCodes, require_permission, db, cache, success_response, error_response, ErrorCodes, require_permission,
require_any_permission,
authorized_service_token, Setting, Application, authorized_service_token, Setting, Application,
) )
@@ -338,8 +339,7 @@ def post_report():
# -- admin read surface (P2 adds full CRUD + publish) ------------------------- # -- admin read surface (P2 adds full CRUD + publish) -------------------------
@geenforce_bp.route('/scopes', methods=['GET']) @geenforce_bp.route('/scopes', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def list_scopes(): def list_scopes():
"""List imaging PC-type scopes with entry + published-version counts.""" """List imaging PC-type scopes with entry + published-version counts."""
scopes = ManifestScope.query.order_by( scopes = ManifestScope.query.order_by(
@@ -364,8 +364,7 @@ def list_scopes():
@geenforce_bp.route('/scopes/<int:scopeid>/preview', methods=['GET']) @geenforce_bp.route('/scopes/<int:scopeid>/preview', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def preview_scope(scopeid): def preview_scope(scopeid):
"""Render the DRAFT manifest JSON a publish would freeze (review before ship).""" """Render the DRAFT manifest JSON a publish would freeze (review before ship)."""
scope = db.session.get(ManifestScope, scopeid) scope = db.session.get(ManifestScope, scopeid)
@@ -377,8 +376,7 @@ def preview_scope(scopeid):
@geenforce_bp.route('/applications', methods=['GET']) @geenforce_bp.route('/applications', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def list_applications(): def list_applications():
"""The core Applications catalog (id + name) for the curated entry->app link """The core Applications catalog (id + name) for the curated entry->app link
picker in the entry editor.""" picker in the entry editor."""
@@ -446,7 +444,6 @@ def _apply_app_link(entry, payload):
@geenforce_bp.route('/scopes', methods=['POST']) @geenforce_bp.route('/scopes', methods=['POST'])
@jwt_required()
@require_permission('geenforce.manage') @require_permission('geenforce.manage')
def create_scope(): def create_scope():
payload = request.get_json(silent=True) or {} payload = request.get_json(silent=True) or {}
@@ -475,8 +472,7 @@ def create_scope():
@geenforce_bp.route('/scopes/<int:scopeid>', methods=['GET']) @geenforce_bp.route('/scopes/<int:scopeid>', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def get_scope(scopeid): def get_scope(scopeid):
scope = db.session.get(ManifestScope, scopeid) scope = db.session.get(ManifestScope, scopeid)
if not scope: if not scope:
@@ -487,7 +483,6 @@ def get_scope(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>', methods=['PUT']) @geenforce_bp.route('/scopes/<int:scopeid>', methods=['PUT'])
@jwt_required()
@require_permission('geenforce.manage') @require_permission('geenforce.manage')
def update_scope(scopeid): def update_scope(scopeid):
scope = db.session.get(ManifestScope, scopeid) scope = db.session.get(ManifestScope, scopeid)
@@ -510,7 +505,6 @@ def update_scope(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>', methods=['DELETE']) @geenforce_bp.route('/scopes/<int:scopeid>', methods=['DELETE'])
@jwt_required()
@require_permission('geenforce.manage') @require_permission('geenforce.manage')
def delete_scope(scopeid): def delete_scope(scopeid):
scope = db.session.get(ManifestScope, scopeid) scope = db.session.get(ManifestScope, scopeid)
@@ -533,7 +527,6 @@ def _validate_entry(payload):
@geenforce_bp.route('/scopes/<int:scopeid>/entries', methods=['POST']) @geenforce_bp.route('/scopes/<int:scopeid>/entries', methods=['POST'])
@jwt_required()
@require_permission('geenforce.manage') @require_permission('geenforce.manage')
def create_entry(scopeid): def create_entry(scopeid):
scope = db.session.get(ManifestScope, scopeid) scope = db.session.get(ManifestScope, scopeid)
@@ -558,7 +551,6 @@ def create_entry(scopeid):
@geenforce_bp.route('/entries/<int:entryid>', methods=['PUT']) @geenforce_bp.route('/entries/<int:entryid>', methods=['PUT'])
@jwt_required()
@require_permission('geenforce.manage') @require_permission('geenforce.manage')
def update_entry(entryid): def update_entry(entryid):
entry = db.session.get(ManifestEntry, entryid) entry = db.session.get(ManifestEntry, entryid)
@@ -587,7 +579,6 @@ def update_entry(entryid):
@geenforce_bp.route('/entries/<int:entryid>', methods=['DELETE']) @geenforce_bp.route('/entries/<int:entryid>', methods=['DELETE'])
@jwt_required()
@require_permission('geenforce.manage') @require_permission('geenforce.manage')
def delete_entry(entryid): def delete_entry(entryid):
entry = db.session.get(ManifestEntry, entryid) entry = db.session.get(ManifestEntry, entryid)
@@ -599,7 +590,6 @@ def delete_entry(entryid):
@geenforce_bp.route('/scopes/<int:scopeid>/entries/reorder', methods=['PUT']) @geenforce_bp.route('/scopes/<int:scopeid>/entries/reorder', methods=['PUT'])
@jwt_required()
@require_permission('geenforce.manage') @require_permission('geenforce.manage')
def reorder_entries(scopeid): def reorder_entries(scopeid):
"""Set entry order from a list of entryids (the ordering contract).""" """Set entry order from a list of entryids (the ordering contract)."""
@@ -621,8 +611,7 @@ def reorder_entries(scopeid):
# -- simulate: "what would this PC get" --------------------------------------- # -- simulate: "what would this PC get" ---------------------------------------
@geenforce_bp.route('/scopes/<int:scopeid>/simulate', methods=['GET']) @geenforce_bp.route('/scopes/<int:scopeid>/simulate', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def simulate_scope(scopeid): def simulate_scope(scopeid):
"""Which draft entries apply to a given machine profile, and why the rest """Which draft entries apply to a given machine profile, and why the rest
are filtered out (reuses the engine-mirror filters).""" are filtered out (reuses the engine-mirror filters)."""
@@ -662,8 +651,7 @@ def simulate_scope(scopeid):
# -- compliance: "how much of the fleet has this app" ------------------------- # -- compliance: "how much of the fleet has this app" -------------------------
@geenforce_bp.route('/scopes/<int:scopeid>/compliance', methods=['GET']) @geenforce_bp.route('/scopes/<int:scopeid>/compliance', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def scope_compliance(scopeid): def scope_compliance(scopeid):
"""Fleet-install coverage per app-linked entry (from collected PC data). """Fleet-install coverage per app-linked entry (from collected PC data).
@@ -684,7 +672,6 @@ PAYLOAD_MAX_BYTES = 1024 * 1024
@geenforce_bp.route('/entries/<int:entryid>/payload', methods=['POST']) @geenforce_bp.route('/entries/<int:entryid>/payload', methods=['POST'])
@jwt_required()
@require_permission('geenforce.publish') @require_permission('geenforce.publish')
def upload_entry_payload(entryid): def upload_entry_payload(entryid):
"""Store an inline payload (<= 1 MB) for an entry and point the entry at it.""" """Store an inline payload (<= 1 MB) for an entry and point the entry at it."""
@@ -709,8 +696,7 @@ def upload_entry_payload(entryid):
@geenforce_bp.route('/entries/<int:entryid>/payload', methods=['GET']) @geenforce_bp.route('/entries/<int:entryid>/payload', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def download_entry_payload(entryid): def download_entry_payload(entryid):
"""Return the stored inline payload bytes for an entry (404 if none).""" """Return the stored inline payload bytes for an entry (404 if none)."""
entry = db.session.get(ManifestEntry, entryid) entry = db.session.get(ManifestEntry, entryid)
@@ -730,7 +716,6 @@ def download_entry_payload(entryid):
# -- publish lifecycle (geenforce.publish) ------------------------------------ # -- publish lifecycle (geenforce.publish) ------------------------------------
@geenforce_bp.route('/scopes/<int:scopeid>/publish', methods=['POST']) @geenforce_bp.route('/scopes/<int:scopeid>/publish', methods=['POST'])
@jwt_required()
@require_permission('geenforce.publish') @require_permission('geenforce.publish')
def publish_scope_route(scopeid): def publish_scope_route(scopeid):
scope = db.session.get(ManifestScope, scopeid) scope = db.session.get(ManifestScope, scopeid)
@@ -759,8 +744,7 @@ def publish_scope_route(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>/publish-preflight', methods=['GET']) @geenforce_bp.route('/scopes/<int:scopeid>/publish-preflight', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def publish_preflight(scopeid): def publish_preflight(scopeid):
"""Would publishing this scope outrun the fleet's enforcer lib? """Would publishing this scope outrun the fleet's enforcer lib?
@@ -781,8 +765,7 @@ def publish_preflight(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>/versions', methods=['GET']) @geenforce_bp.route('/scopes/<int:scopeid>/versions', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def list_versions(scopeid): def list_versions(scopeid):
scope = db.session.get(ManifestScope, scopeid) scope = db.session.get(ManifestScope, scopeid)
if not scope: if not scope:
@@ -801,8 +784,7 @@ def list_versions(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>/versions/<int:versionnumber>', @geenforce_bp.route('/scopes/<int:scopeid>/versions/<int:versionnumber>',
methods=['GET']) methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def get_version(scopeid, versionnumber): def get_version(scopeid, versionnumber):
version = ManifestPublishedVersion.query.filter_by( version = ManifestPublishedVersion.query.filter_by(
scopeid=scopeid, versionnumber=versionnumber).first() scopeid=scopeid, versionnumber=versionnumber).first()
@@ -830,8 +812,7 @@ def _normalize_cidrs(raw):
@geenforce_bp.route('/config', methods=['GET']) @geenforce_bp.route('/config', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def get_config(): def get_config():
"""Plugin config: the on-share export root + the client IP allowlist.""" """Plugin config: the on-share export root + the client IP allowlist."""
shareroot = Setting.query.filter_by(key=SHAREROOT_SETTING).first() shareroot = Setting.query.filter_by(key=SHAREROOT_SETTING).first()
@@ -843,7 +824,6 @@ def get_config():
@geenforce_bp.route('/config', methods=['PUT']) @geenforce_bp.route('/config', methods=['PUT'])
@jwt_required()
@require_permission('geenforce.publish') @require_permission('geenforce.publish')
def put_config(): def put_config():
payload = request.get_json(silent=True) or {} payload = request.get_json(silent=True) or {}
@@ -870,7 +850,6 @@ def put_config():
@geenforce_bp.route('/scopes/<int:scopeid>/export-share', methods=['POST']) @geenforce_bp.route('/scopes/<int:scopeid>/export-share', methods=['POST'])
@jwt_required()
@require_permission('geenforce.publish') @require_permission('geenforce.publish')
def export_share_route(scopeid): def export_share_route(scopeid):
"""Write the scope's current published JSON to the configured share root """Write the scope's current published JSON to the configured share root
@@ -892,7 +871,6 @@ def export_share_route(scopeid):
@geenforce_bp.route('/scopes/<int:scopeid>/rollback', methods=['POST']) @geenforce_bp.route('/scopes/<int:scopeid>/rollback', methods=['POST'])
@jwt_required()
@require_permission('geenforce.publish') @require_permission('geenforce.publish')
def rollback_scope_route(scopeid): def rollback_scope_route(scopeid):
scope = db.session.get(ManifestScope, scopeid) scope = db.session.get(ManifestScope, scopeid)
@@ -1221,8 +1199,7 @@ def _report_stale_cutoff():
@geenforce_bp.route('/reports', methods=['GET']) @geenforce_bp.route('/reports', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def list_reports(): def list_reports():
"""Latest enforcement report per PC (fleet compliance view). """Latest enforcement report per PC (fleet compliance view).
@@ -1328,8 +1305,7 @@ def list_reports():
@geenforce_bp.route('/reports/<int:reportid>', methods=['GET']) @geenforce_bp.route('/reports/<int:reportid>', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def get_report(reportid): def get_report(reportid):
"""One report with per-entry outcomes (self-heal / failure detail).""" """One report with per-entry outcomes (self-heal / failure detail)."""
report = db.session.get(ManifestEnforcementReport, reportid) report = db.session.get(ManifestEnforcementReport, reportid)
@@ -1358,8 +1334,7 @@ def get_report(reportid):
@geenforce_bp.route('/dashboard/failures', methods=['GET']) @geenforce_bp.route('/dashboard/failures', methods=['GET'])
@jwt_required() @require_any_permission('geenforce.view', 'geenforce.manage')
@require_permission('geenforce.manage')
def dashboard_failures(): def dashboard_failures():
"""Entries that FAILED on their PC's most recent enforcement cycle. """Entries that FAILED on their PC's most recent enforcement cycle.

View File

@@ -106,6 +106,8 @@ class GeEnforcePlugin(BasePlugin):
def get_permissions(self) -> List: def get_permissions(self) -> List:
"""RBAC permissions this plugin owns (edit vs ship are split).""" """RBAC permissions this plugin owns (edit vs ship are split)."""
return [ return [
('geenforce.view', 'View imaging PC types and manifests',
'geenforce'),
('geenforce.manage', 'Edit imaging PC types and manifest drafts', ('geenforce.manage', 'Edit imaging PC types and manifest drafts',
'geenforce'), 'geenforce'),
('geenforce.publish', 'Publish, roll back, and export manifests', ('geenforce.publish', 'Publish, roll back, and export manifests',
@@ -125,6 +127,9 @@ class GeEnforcePlugin(BasePlugin):
'icon': 'shield', 'icon': 'shield',
'route': '/geenforce/manifests', 'route': '/geenforce/manifests',
'position': 46, 'position': 46,
# The READ permission: managing implies it, and it is the one a
# site can hand to guests.
'permission': ['geenforce.view', 'geenforce.manage'],
'section': 'fleet', 'section': 'fleet',
}, },
] ]

View File

@@ -14,7 +14,7 @@ from datetime import datetime
import json import json
import re import re
from flask import Blueprint, request, Response from flask import Blueprint, request, Response, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity, current_user from flask_jwt_extended import jwt_required, get_jwt_identity, current_user
from shopdb.api import ( from shopdb.api import (
@@ -42,9 +42,25 @@ ALLOWEDIMAGETYPES = {
} }
def _currentuser():
"""The signed-in user, or None.
`current_user` is a LocalProxy, so `current_user is not None` is True even
when nobody is signed in - the proxy exists, the user behind it does not.
Under a required JWT that never showed; the read routes are jwt-optional
now, and the first guest request found it by way of
"'NoneType' object has no attribute 'haspermission'".
"""
try:
return current_user._get_current_object()
except Exception:
return None
def _userid(): def _userid():
if current_user is not None: user = _currentuser()
return current_user.userid if user is not None:
return user.userid
try: try:
return int(get_jwt_identity()) return int(get_jwt_identity())
except (TypeError, ValueError): except (TypeError, ValueError):
@@ -59,8 +75,12 @@ def _has(permission):
the decorator makes, including the admin bypass that lives inside the decorator makes, including the admin bypass that lives inside
haspermission. haspermission.
""" """
return bool(current_user is not None user = _currentuser()
and current_user.haspermission(permission)) return bool(user is not None and user.haspermission(permission))
def _signedin():
return _currentuser() is not None
def _mayedit(guide): def _mayedit(guide):
@@ -101,7 +121,6 @@ def _slugify(title, guideid=None):
# ---------------------------------------------------------------- reading --- # ---------------------------------------------------------------- reading ---
@guides_bp.route('', methods=['GET']) @guides_bp.route('', methods=['GET'])
@jwt_required()
@require_permission('guides.view') @require_permission('guides.view')
def list_guides(): def list_guides():
"""Published guides, plus the caller's own drafts if they can author. """Published guides, plus the caller's own drafts if they can author.
@@ -109,9 +128,15 @@ def list_guides():
A half-written procedure on a shop floor is worse than no procedure, so A half-written procedure on a shop floor is worse than no procedure, so
drafts are invisible to readers - but an author must be able to find their drafts are invisible to readers - but an author must be able to find their
own, or drafting is a trap door. own, or drafting is a trap door.
A guest reaches this only if the guest role has been granted guides.view.
A guest is never an author, so the draft branches below cannot open for one.
""" """
caneditall = _has('guides.edit') caneditall = _has('guides.edit')
mine = _userid() # A guest has no user id, and `createdby == None` is a real match in SQL
# against every guide imported without an author. Their drafts are not
# theirs; nobody's are.
mine = _userid() if _signedin() else -1
# Match against the PUBLISHED text for anything the caller is only allowed # Match against the PUBLISHED text for anything the caller is only allowed
# to read, and against the working copy only for guides they may edit. # to read, and against the working copy only for guides they may edit.
@@ -185,7 +210,6 @@ def list_guides():
@guides_bp.route('/tags', methods=['GET']) @guides_bp.route('/tags', methods=['GET'])
@jwt_required()
@require_permission('guides.view') @require_permission('guides.view')
def list_tags(): def list_tags():
"""Every tag in use, with a count, for the filter chips. """Every tag in use, with a count, for the filter chips.
@@ -215,7 +239,6 @@ def list_tags():
@guides_bp.route('/<slug>', methods=['GET']) @guides_bp.route('/<slug>', methods=['GET'])
@jwt_required()
@require_permission('guides.view') @require_permission('guides.view')
def read_guide(slug): def read_guide(slug):
"""What a reader gets: the published revision. """What a reader gets: the published revision.
@@ -257,7 +280,6 @@ def read_guide(slug):
@guides_bp.route('/<int:guideid>/working', methods=['GET']) @guides_bp.route('/<int:guideid>/working', methods=['GET'])
@jwt_required()
@require_permission('guides.view') @require_permission('guides.view')
def read_working(guideid): def read_working(guideid):
"""The working copy, for the editor.""" """The working copy, for the editor."""
@@ -275,7 +297,6 @@ def read_working(guideid):
@guides_bp.route('/<int:guideid>/revisions', methods=['GET']) @guides_bp.route('/<int:guideid>/revisions', methods=['GET'])
@jwt_required()
@require_permission('guides.view') @require_permission('guides.view')
def list_revisions(guideid): def list_revisions(guideid):
guide = db.session.get(Guide, guideid) guide = db.session.get(Guide, guideid)
@@ -298,7 +319,6 @@ def list_revisions(guideid):
@guides_bp.route('/revisions/<int:revisionid>', methods=['GET']) @guides_bp.route('/revisions/<int:revisionid>', methods=['GET'])
@jwt_required()
@require_permission('guides.view') @require_permission('guides.view')
def read_revision(revisionid): def read_revision(revisionid):
"""One revision by id. """One revision by id.
@@ -327,8 +347,40 @@ def read_revision(revisionid):
# ---------------------------------------------------------------- writing --- # ---------------------------------------------------------------- writing ---
def _attachimages(guide, blocks):
"""Attach the images this guide's blocks reference but nothing owns yet.
An image pasted into a guide that has not been saved is uploaded with no
guideid - there is no id to give it. The upload route says the editor
attaches it on save, and the editor never did: it only sends a guideid when
the guide already has one. So a screenshot pasted while writing a NEW guide
stayed unattached forever.
An unattached image is visible to editors and to whoever uploaded it, and
to nobody else - so the guide looked right to the person who wrote it and
showed "Image unavailable" to every reader. Attaching on save is what makes
the image belong to the guide, and therefore readable by anyone allowed to
read the guide once it is published.
Only images nothing else owns are claimed: an image already attached to
another guide is left alone rather than stolen by whoever references it.
"""
referenced = set()
for block in blocks or []:
if isinstance(block, dict) and block.get('imageid') is not None:
try:
referenced.add(int(block['imageid']))
except (TypeError, ValueError):
continue
if not referenced:
return
(GuideImage.query
.filter(GuideImage.guideimageid.in_(referenced))
.filter(GuideImage.guideid.is_(None))
.update({'guideid': guide.guideid}, synchronize_session=False))
@guides_bp.route('', methods=['POST']) @guides_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('guides.create') @require_permission('guides.create')
def create_guide(): def create_guide():
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
@@ -353,13 +405,15 @@ def create_guide():
db.session.rollback() db.session.rollback()
return error_response(ErrorCodes.VALIDATION_ERROR, str(exc)) return error_response(ErrorCodes.VALIDATION_ERROR, str(exc))
# The first save is exactly when a pasted image has no owner yet.
_attachimages(guide, guide.blocks)
db.session.commit() db.session.commit()
return success_response(guide.to_dict(includeblocks=True), return success_response(guide.to_dict(includeblocks=True),
message='Guide created') message='Guide created')
@guides_bp.route('/<int:guideid>', methods=['PUT']) @guides_bp.route('/<int:guideid>', methods=['PUT'])
@jwt_required()
@require_permission('guides.view') @require_permission('guides.view')
def update_guide(guideid): def update_guide(guideid):
guide = db.session.get(Guide, guideid) guide = db.session.get(Guide, guideid)
@@ -387,6 +441,8 @@ def update_guide(guideid):
db.session.rollback() db.session.rollback()
return error_response(ErrorCodes.VALIDATION_ERROR, str(exc)) return error_response(ErrorCodes.VALIDATION_ERROR, str(exc))
_attachimages(guide, guide.blocks)
# The slug is set once, at create, and does NOT follow the title. # The slug is set once, at create, and does NOT follow the title.
# #
# _slugify's own docstring says the slug is stored so that renaming cannot # _slugify's own docstring says the slug is stored so that renaming cannot
@@ -409,7 +465,6 @@ def update_guide(guideid):
@guides_bp.route('/<int:guideid>/publish', methods=['POST']) @guides_bp.route('/<int:guideid>/publish', methods=['POST'])
@jwt_required()
@require_permission('guides.publish') @require_permission('guides.publish')
def publish_guide(guideid): def publish_guide(guideid):
guide = db.session.get(Guide, guideid) guide = db.session.get(Guide, guideid)
@@ -425,7 +480,6 @@ def publish_guide(guideid):
@guides_bp.route('/<int:guideid>/unpublish', methods=['POST']) @guides_bp.route('/<int:guideid>/unpublish', methods=['POST'])
@jwt_required()
@require_permission('guides.publish') @require_permission('guides.publish')
def unpublish_guide(guideid): def unpublish_guide(guideid):
guide = db.session.get(Guide, guideid) guide = db.session.get(Guide, guideid)
@@ -437,7 +491,6 @@ def unpublish_guide(guideid):
@guides_bp.route('/<int:guideid>/restore/<int:revisionid>', methods=['POST']) @guides_bp.route('/<int:guideid>/restore/<int:revisionid>', methods=['POST'])
@jwt_required()
@require_permission('guides.view') @require_permission('guides.view')
def restore_revision(guideid, revisionid): def restore_revision(guideid, revisionid):
guide = db.session.get(Guide, guideid) guide = db.session.get(Guide, guideid)
@@ -458,7 +511,6 @@ def restore_revision(guideid, revisionid):
@guides_bp.route('/<int:guideid>', methods=['DELETE']) @guides_bp.route('/<int:guideid>', methods=['DELETE'])
@jwt_required()
@require_permission('guides.delete') @require_permission('guides.delete')
def delete_guide(guideid): def delete_guide(guideid):
guide = db.session.get(Guide, guideid) guide = db.session.get(Guide, guideid)
@@ -472,7 +524,6 @@ def delete_guide(guideid):
# ----------------------------------------------------------------- images --- # ----------------------------------------------------------------- images ---
@guides_bp.route('/images', methods=['POST']) @guides_bp.route('/images', methods=['POST'])
@jwt_required()
@require_permission('guides.create') @require_permission('guides.create')
def upload_image(): def upload_image():
"""Take a pasted or dropped image. """Take a pasted or dropped image.
@@ -553,9 +604,16 @@ def _mayseeimage(image):
@guides_bp.route('/images/<int:imageid>', methods=['GET']) @guides_bp.route('/images/<int:imageid>', methods=['GET'])
@jwt_required()
@require_permission('guides.view') @require_permission('guides.view')
def serve_image(imageid): def serve_image(imageid):
"""The image itself, under the same rule as the guide that holds it.
A guest who may read a published guide must see its screenshots, or every
image renders as "Image unavailable" and the guide looks broken.
_mayseeimage already answers correctly for somebody holding nothing - it
requires the PUBLISHED revision to reference the image - so a guest needs no
separate branch here.
"""
image = db.session.get(GuideImage, imageid) image = db.session.get(GuideImage, imageid)
if image is None: if image is None:
return error_response(ErrorCodes.NOT_FOUND, 'Image not found', http_code=404) return error_response(ErrorCodes.NOT_FOUND, 'Image not found', http_code=404)

View File

@@ -114,6 +114,52 @@ def build_cli():
click.echo(' imported as /guides/{} (draft, revision {})' click.echo(' imported as /guides/{} (draft, revision {})'
.format(guide.slug, guide.revision)) .format(guide.slug, guide.revision))
@guides_cli.command('fix-images')
@click.option('--apply/--dry-run', default=False,
help='Write to the database. The default reports only.')
@with_appcontext
def fix_images(apply):
"""Attach images a guide references but nothing owns.
An image pasted into a guide that had not been saved yet was uploaded
with no guideid, and nothing ever attached it. Editors and the uploader
could see it; every other reader got "Image unavailable" on a published
guide. Saving a guide attaches its images now, but a guide nobody edits
again would stay broken, so this repairs what is already stored.
"""
orphans = GuideImage.query.filter(GuideImage.guideid.is_(None)).all()
if not orphans:
click.echo('No unattached images.')
return
wanted = {}
for guide in Guide.query.all():
for block in guide.blocks or []:
if isinstance(block, dict) and block.get('imageid') is not None:
try:
wanted.setdefault(int(block['imageid']), guide)
except (TypeError, ValueError):
continue
fixed = 0
for image in orphans:
guide = wanted.get(image.guideimageid)
if guide is None:
click.echo(' image {} is referenced by no guide - left alone'
.format(image.guideimageid))
continue
click.echo(' image {} -> guide {} ({})'.format(
image.guideimageid, guide.guideid, guide.slug))
if apply:
image.guideid = guide.guideid
fixed += 1
if not apply:
click.echo('{} would be attached. Pass --apply to write.'.format(fixed))
return
db.session.commit()
click.echo('{} image(s) attached.'.format(fixed))
@guides_cli.command('export') @guides_cli.command('export')
@click.option('--out', 'outdir', required=True, @click.option('--out', 'outdir', required=True,
type=click.Path(file_okay=False), type=click.Path(file_okay=False),

View File

@@ -6,15 +6,20 @@
* checkboxes are live in exactly one of them. * checkboxes are live in exactly one of them.
* *
* meta.plugin = 'guides' so the ADR-009 router guard redirects when the backend * meta.plugin = 'guides' so the ADR-009 router guard redirects when the backend
* plugin is disabled. Every route requires auth because every guides API route * plugin is disabled.
* is behind JWT plus a guides.* permission. *
* READING does not require auth; WRITING does. The read routes are gated on
* guides.view, and a signed-out visitor holds whatever the GUEST role has been
* granted - so the role decides, not the router. Sending a guest to /login when
* the site has granted them guides.view would make the grant look broken;
* letting them through when it has not costs one 401 the view already handles.
*/ */
export default [ export default [
{ {
path: 'guides', path: 'guides',
name: 'guides', name: 'guides',
component: () => import('./views/GuidesList.vue'), component: () => import('./views/GuidesList.vue'),
meta: { requiresAuth: true, plugin: 'guides' } meta: { plugin: 'guides' }
}, },
{ {
path: 'guides/new', path: 'guides/new',
@@ -26,7 +31,7 @@ export default [
path: 'guides/:slug', path: 'guides/:slug',
name: 'guide-view', name: 'guide-view',
component: () => import('./views/GuideView.vue'), component: () => import('./views/GuideView.vue'),
meta: { requiresAuth: true, plugin: 'guides' } meta: { plugin: 'guides' }
}, },
{ {
path: 'guides/:guideid/edit', path: 'guides/:guideid/edit',

View File

@@ -90,6 +90,10 @@ class GuidesPlugin(BasePlugin):
'icon': 'book-open', 'icon': 'book-open',
'route': '/guides', 'route': '/guides',
'position': 8, 'position': 8,
# The nav endpoint hides an item whose permission the caller
# does not hold, so a signed-out visitor sees Guides only when
# the guest role has been granted guides.view.
'permission': 'guides.view',
}, },
] ]

View File

@@ -197,7 +197,6 @@ def track_click(link_id: int):
@knowledgebase_bp.route('', methods=['POST']) @knowledgebase_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('kb.create') @require_permission('kb.create')
def create_article(): def create_article():
"""Create a new knowledge base article.""" """Create a new knowledge base article."""
@@ -231,7 +230,6 @@ def create_article():
@knowledgebase_bp.route('/<int:link_id>', methods=['PUT']) @knowledgebase_bp.route('/<int:link_id>', methods=['PUT'])
@jwt_required()
@require_permission('kb.edit') @require_permission('kb.edit')
def update_article(link_id: int): def update_article(link_id: int):
"""Update a knowledge base article.""" """Update a knowledge base article."""
@@ -261,7 +259,6 @@ def update_article(link_id: int):
@knowledgebase_bp.route('/<int:link_id>', methods=['DELETE']) @knowledgebase_bp.route('/<int:link_id>', methods=['DELETE'])
@jwt_required()
@require_permission('kb.delete') @require_permission('kb.delete')
def delete_article(link_id: int): def delete_article(link_id: int):
"""Delete (deactivate) a knowledge base article.""" """Delete (deactivate) a knowledge base article."""

View File

@@ -55,7 +55,6 @@ def get_machine_type(type_id: int):
@machines_bp.route('/types', methods=['POST']) @machines_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('machines.create') @require_permission('machines.create')
def create_machine_type(): def create_machine_type():
"""Create a new machine type.""" """Create a new machine type."""
@@ -92,7 +91,6 @@ def create_machine_type():
@machines_bp.route('/types/<int:type_id>', methods=['PUT']) @machines_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('machines.edit') @require_permission('machines.edit')
def update_machine_type(type_id: int): def update_machine_type(type_id: int):
"""Update a machine type.""" """Update a machine type."""
@@ -126,7 +124,6 @@ def update_machine_type(type_id: int):
@machines_bp.route('/types/<int:type_id>', methods=['DELETE']) @machines_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('machines.delete') @require_permission('machines.delete')
def delete_machine_type(type_id: int): def delete_machine_type(type_id: int):
"""Delete a machine type. Refused if any asset still uses it.""" """Delete a machine type. Refused if any asset still uses it."""
@@ -324,7 +321,6 @@ def get_machine_by_asset(asset_id: int):
@machines_bp.route('', methods=['POST']) @machines_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('machines.create') @require_permission('machines.create')
def create_machine(): def create_machine():
""" """
@@ -418,7 +414,6 @@ def create_machine():
@machines_bp.route('/<int:machine_id>', methods=['PUT']) @machines_bp.route('/<int:machine_id>', methods=['PUT'])
@jwt_required()
@require_permission('machines.edit') @require_permission('machines.edit')
def update_machine(machine_id: int): def update_machine(machine_id: int):
"""Update machine (both Asset and Machine records).""" """Update machine (both Asset and Machine records)."""
@@ -501,7 +496,6 @@ def update_machine(machine_id: int):
@machines_bp.route('/<int:machine_id>', methods=['DELETE']) @machines_bp.route('/<int:machine_id>', methods=['DELETE'])
@jwt_required()
@require_permission('machines.delete') @require_permission('machines.delete')
def delete_machine(machine_id: int): def delete_machine(machine_id: int):
"""Delete (soft delete) machine.""" """Delete (soft delete) machine."""
@@ -578,7 +572,6 @@ def dashboard_summary():
@machines_bp.route('/dashboard/outofservice', methods=['GET']) @machines_bp.route('/dashboard/outofservice', methods=['GET'])
@jwt_required()
@require_permission('machines.view') @require_permission('machines.view')
def dashboard_outofservice(): def dashboard_outofservice():
"""Machines whose status says they are not running. """Machines whose status says they are not running.

View File

@@ -75,7 +75,6 @@ def get_type(type_id: int):
@measuringtools_bp.route('/types', methods=['POST']) @measuringtools_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('measuringtools.create') @require_permission('measuringtools.create')
def create_type(): def create_type():
"""Create a measuring-tool type (reactivates a soft-deleted same-named one).""" """Create a measuring-tool type (reactivates a soft-deleted same-named one)."""
@@ -108,7 +107,6 @@ def create_type():
@measuringtools_bp.route('/types/<int:type_id>', methods=['PUT']) @measuringtools_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('measuringtools.edit') @require_permission('measuringtools.edit')
def update_type(type_id: int): def update_type(type_id: int):
"""Update a measuring-tool type.""" """Update a measuring-tool type."""
@@ -130,7 +128,6 @@ def update_type(type_id: int):
@measuringtools_bp.route('/types/<int:type_id>', methods=['DELETE']) @measuringtools_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('measuringtools.delete') @require_permission('measuringtools.delete')
def delete_type(type_id: int): def delete_type(type_id: int):
"""Delete a measuring-tool type. Refused if any tool still uses it.""" """Delete a measuring-tool type. Refused if any tool still uses it."""
@@ -239,7 +236,6 @@ def _asset_type_id():
@measuringtools_bp.route('', methods=['POST']) @measuringtools_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('measuringtools.create') @require_permission('measuringtools.create')
def create_tool(): def create_tool():
"""Create a measuring tool: one Asset core row + one extension row.""" """Create a measuring tool: one Asset core row + one extension row."""
@@ -305,7 +301,6 @@ _TOOL_FIELDS = ('measuringtooltypeid', 'calibrationintervaldays',
@measuringtools_bp.route('/<int:tool_id>', methods=['PUT']) @measuringtools_bp.route('/<int:tool_id>', methods=['PUT'])
@jwt_required()
@require_permission('measuringtools.edit') @require_permission('measuringtools.edit')
def update_tool(tool_id: int): def update_tool(tool_id: int):
"""Update a measuring tool (asset core fields + extension in one payload).""" """Update a measuring tool (asset core fields + extension in one payload)."""
@@ -357,7 +352,6 @@ def update_tool(tool_id: int):
@measuringtools_bp.route('/<int:tool_id>', methods=['DELETE']) @measuringtools_bp.route('/<int:tool_id>', methods=['DELETE'])
@jwt_required()
@require_permission('measuringtools.delete') @require_permission('measuringtools.delete')
def delete_tool(tool_id: int): def delete_tool(tool_id: int):
"""Soft delete a measuring tool (deactivates its asset).""" """Soft delete a measuring tool (deactivates its asset)."""

View File

@@ -85,7 +85,6 @@ def get_network_device_type(type_id: int):
@network_bp.route('/types', methods=['POST']) @network_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('network.create') @require_permission('network.create')
def create_network_device_type(): def create_network_device_type():
"""Create a new network device type.""" """Create a new network device type."""
@@ -123,7 +122,6 @@ def create_network_device_type():
@network_bp.route('/types/<int:type_id>', methods=['PUT']) @network_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('network.edit') @require_permission('network.edit')
def update_network_device_type(type_id: int): def update_network_device_type(type_id: int):
"""Update a network device type.""" """Update a network device type."""
@@ -158,7 +156,6 @@ def update_network_device_type(type_id: int):
@network_bp.route('/types/<int:type_id>', methods=['DELETE']) @network_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('network.delete') @require_permission('network.delete')
def delete_network_device_type(type_id: int): def delete_network_device_type(type_id: int):
"""Delete a network device type. Refused if any device still uses it.""" """Delete a network device type. Refused if any device still uses it."""
@@ -347,7 +344,6 @@ def get_network_device_by_hostname(hostname: str):
@network_bp.route('', methods=['POST']) @network_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('network.create') @require_permission('network.create')
def create_network_device(): def create_network_device():
""" """
@@ -464,7 +460,6 @@ def create_network_device():
@network_bp.route('/<int:device_id>', methods=['PUT']) @network_bp.route('/<int:device_id>', methods=['PUT'])
@jwt_required()
@require_permission('network.edit') @require_permission('network.edit')
def update_network_device(device_id: int): def update_network_device(device_id: int):
"""Update network device (both Asset and NetworkDevice records).""" """Update network device (both Asset and NetworkDevice records)."""
@@ -559,7 +554,6 @@ def update_network_device(device_id: int):
@network_bp.route('/<int:device_id>', methods=['DELETE']) @network_bp.route('/<int:device_id>', methods=['DELETE'])
@jwt_required()
@require_permission('network.delete') @require_permission('network.delete')
def delete_network_device(device_id: int): def delete_network_device(device_id: int):
"""Delete (soft delete) network device.""" """Delete (soft delete) network device."""
@@ -690,7 +684,6 @@ def get_vlan(vlan_id: int):
@network_bp.route('/vlans', methods=['POST']) @network_bp.route('/vlans', methods=['POST'])
@jwt_required()
@require_permission('network.create') @require_permission('network.create')
def create_vlan(): def create_vlan():
"""Create a new VLAN.""" """Create a new VLAN."""
@@ -732,7 +725,6 @@ def create_vlan():
@network_bp.route('/vlans/<int:vlan_id>', methods=['PUT']) @network_bp.route('/vlans/<int:vlan_id>', methods=['PUT'])
@jwt_required()
@require_permission('network.edit') @require_permission('network.edit')
def update_vlan(vlan_id: int): def update_vlan(vlan_id: int):
"""Update a VLAN.""" """Update a VLAN."""
@@ -778,7 +770,6 @@ def update_vlan(vlan_id: int):
@network_bp.route('/vlans/<int:vlan_id>', methods=['DELETE']) @network_bp.route('/vlans/<int:vlan_id>', methods=['DELETE'])
@jwt_required()
@require_permission('network.delete') @require_permission('network.delete')
def delete_vlan(vlan_id: int): def delete_vlan(vlan_id: int):
"""Delete (soft delete) a VLAN.""" """Delete (soft delete) a VLAN."""
@@ -932,7 +923,6 @@ def _asset_detail_url(assettype, assetid):
@network_bp.route('/subnets', methods=['POST']) @network_bp.route('/subnets', methods=['POST'])
@jwt_required()
@require_permission('network.create') @require_permission('network.create')
def create_subnet(): def create_subnet():
"""Create a new subnet.""" """Create a new subnet."""
@@ -998,7 +988,6 @@ def create_subnet():
@network_bp.route('/subnets/<int:subnet_id>', methods=['PUT']) @network_bp.route('/subnets/<int:subnet_id>', methods=['PUT'])
@jwt_required()
@require_permission('network.edit') @require_permission('network.edit')
def update_subnet(subnet_id: int): def update_subnet(subnet_id: int):
"""Update a subnet.""" """Update a subnet."""
@@ -1049,7 +1038,6 @@ def update_subnet(subnet_id: int):
@network_bp.route('/subnets/<int:subnet_id>', methods=['DELETE']) @network_bp.route('/subnets/<int:subnet_id>', methods=['DELETE'])
@jwt_required()
@require_permission('network.delete') @require_permission('network.delete')
def delete_subnet(subnet_id: int): def delete_subnet(subnet_id: int):
"""Delete (soft delete) a subnet.""" """Delete (soft delete) a subnet."""

View File

@@ -257,7 +257,6 @@ def list_notification_types():
@notifications_bp.route('/types', methods=['POST']) @notifications_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('notifications.create') @require_permission('notifications.create')
def create_notification_type(): def create_notification_type():
"""Create a new notification type.""" """Create a new notification type."""
@@ -293,7 +292,6 @@ def create_notification_type():
@notifications_bp.route('/types/<int:type_id>', methods=['PUT', 'PATCH']) @notifications_bp.route('/types/<int:type_id>', methods=['PUT', 'PATCH'])
@jwt_required()
@require_permission('notifications.create') @require_permission('notifications.create')
def update_notification_type(type_id: int): def update_notification_type(type_id: int):
"""Update a notification type, including its auto-expiry rule.""" """Update a notification type, including its auto-expiry rule."""
@@ -405,7 +403,6 @@ def get_notification(notification_id: int):
@notifications_bp.route('', methods=['POST']) @notifications_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('notifications.create') @require_permission('notifications.create')
def create_notification(): def create_notification():
"""Create a new notification.""" """Create a new notification."""
@@ -465,7 +462,6 @@ def create_notification():
@notifications_bp.route('/<int:notification_id>', methods=['PUT']) @notifications_bp.route('/<int:notification_id>', methods=['PUT'])
@jwt_required()
@require_permission('notifications.edit') @require_permission('notifications.edit')
def update_notification(notification_id: int): def update_notification(notification_id: int):
"""Update a notification.""" """Update a notification."""
@@ -532,7 +528,6 @@ def update_notification(notification_id: int):
@notifications_bp.route('/<int:notification_id>', methods=['DELETE']) @notifications_bp.route('/<int:notification_id>', methods=['DELETE'])
@jwt_required()
@require_permission('notifications.delete') @require_permission('notifications.delete')
def delete_notification(notification_id: int): def delete_notification(notification_id: int):
"""Delete (soft delete) a notification.""" """Delete (soft delete) a notification."""

View File

@@ -29,7 +29,6 @@ printedparts_bp = Blueprint('printedparts', __name__)
@printedparts_bp.route('/items', methods=['GET']) @printedparts_bp.route('/items', methods=['GET'])
@jwt_required()
@require_permission('printedparts.view') @require_permission('printedparts.view')
def list_items(): def list_items():
"""List printed items, paginated; search + low-stock filter.""" """List printed items, paginated; search + low-stock filter."""
@@ -56,7 +55,6 @@ def list_items():
@printedparts_bp.route('/items/<int:item_id>', methods=['GET']) @printedparts_bp.route('/items/<int:item_id>', methods=['GET'])
@jwt_required()
@require_permission('printedparts.view') @require_permission('printedparts.view')
def get_item(item_id: int): def get_item(item_id: int):
"""Get one printed item with its recent transactions.""" """Get one printed item with its recent transactions."""
@@ -101,7 +99,6 @@ def _mint_itemcode(item):
@printedparts_bp.route('/items', methods=['POST']) @printedparts_bp.route('/items', methods=['POST'])
@jwt_required()
@require_permission('printedparts.create') @require_permission('printedparts.create')
def create_item(): def create_item():
"""Create a printed item. """Create a printed item.
@@ -141,7 +138,6 @@ def create_item():
@printedparts_bp.route('/items/<int:item_id>', methods=['PUT']) @printedparts_bp.route('/items/<int:item_id>', methods=['PUT'])
@jwt_required()
@require_permission('printedparts.edit') @require_permission('printedparts.edit')
def update_item(item_id: int): def update_item(item_id: int):
"""Update catalog fields. Quantity moves ONLY through the ledger.""" """Update catalog fields. Quantity moves ONLY through the ledger."""
@@ -174,7 +170,6 @@ def update_item(item_id: int):
@printedparts_bp.route('/items/<int:item_id>', methods=['DELETE']) @printedparts_bp.route('/items/<int:item_id>', methods=['DELETE'])
@jwt_required()
@require_permission('printedparts.delete') @require_permission('printedparts.delete')
def delete_item(item_id: int): def delete_item(item_id: int):
"""Soft-retire an item; its ledger history stays.""" """Soft-retire an item; its ledger history stays."""
@@ -188,7 +183,6 @@ def delete_item(item_id: int):
@printedparts_bp.route('/items/<int:item_id>/restore', methods=['POST']) @printedparts_bp.route('/items/<int:item_id>/restore', methods=['POST'])
@jwt_required()
@require_permission('printedparts.delete') @require_permission('printedparts.delete')
def restore_item(item_id: int): def restore_item(item_id: int):
"""Bring a retired item back; code, photo, and history are intact.""" """Bring a retired item back; code, photo, and history are intact."""
@@ -204,7 +198,6 @@ def restore_item(item_id: int):
# --- item image: the models.py upload/serve/delete trio --------------------- # --- item image: the models.py upload/serve/delete trio ---------------------
@printedparts_bp.route('/items/<int:item_id>/image', methods=['POST']) @printedparts_bp.route('/items/<int:item_id>/image', methods=['POST'])
@jwt_required()
@require_permission('printedparts.edit') @require_permission('printedparts.edit')
def upload_item_image(item_id: int): def upload_item_image(item_id: int):
"""Upload (or replace) the photo for an item (multipart file=<image>).""" """Upload (or replace) the photo for an item (multipart file=<image>)."""
@@ -240,7 +233,6 @@ def serve_item_image(filename):
@printedparts_bp.route('/items/<int:item_id>/image', methods=['DELETE']) @printedparts_bp.route('/items/<int:item_id>/image', methods=['DELETE'])
@jwt_required()
@require_permission('printedparts.delete') @require_permission('printedparts.delete')
def delete_item_image(item_id: int): def delete_item_image(item_id: int):
"""Clear an item image; delete the file only if this plugin owns it.""" """Clear an item image; delete the file only if this plugin owns it."""
@@ -387,7 +379,6 @@ def _alert_team_webhook():
@printedparts_bp.route('/items/<int:item_id>/restock', methods=['POST']) @printedparts_bp.route('/items/<int:item_id>/restock', methods=['POST'])
@jwt_required()
@require_permission('printedparts.restock') @require_permission('printedparts.restock')
def restock_item(item_id: int): def restock_item(item_id: int):
"""Add freshly printed stock. Body: {quantity, badge}.""" """Add freshly printed stock. Body: {quantity, badge}."""
@@ -410,7 +401,6 @@ def restock_item(item_id: int):
@printedparts_bp.route('/items/<int:item_id>/adjust', methods=['POST']) @printedparts_bp.route('/items/<int:item_id>/adjust', methods=['POST'])
@jwt_required()
@require_permission('printedparts.restock') @require_permission('printedparts.restock')
def adjust_item(item_id: int): def adjust_item(item_id: int):
"""Correct the count (damage, recount). Body: {quantitychange, reason, badge}.""" """Correct the count (damage, recount). Body: {quantitychange, reason, badge}."""
@@ -668,7 +658,6 @@ def _uploader_name():
@printedparts_bp.route('/items/<int:item_id>/files', methods=['GET']) @printedparts_bp.route('/items/<int:item_id>/files', methods=['GET'])
@jwt_required()
@require_permission('printedparts.view') @require_permission('printedparts.view')
def list_item_files(item_id: int): def list_item_files(item_id: int):
"""Revision history, newest first.""" """Revision history, newest first."""
@@ -678,7 +667,6 @@ def list_item_files(item_id: int):
@printedparts_bp.route('/items/<int:item_id>/files', methods=['POST']) @printedparts_bp.route('/items/<int:item_id>/files', methods=['POST'])
@jwt_required()
@require_permission('printedparts.edit') @require_permission('printedparts.edit')
def upload_item_file(item_id: int): def upload_item_file(item_id: int):
"""Upload the next revision of the item's print file. """Upload the next revision of the item's print file.
@@ -747,7 +735,6 @@ def download_item_file(file_id: int):
@printedparts_bp.route('/files/<int:file_id>', methods=['DELETE']) @printedparts_bp.route('/files/<int:file_id>', methods=['DELETE'])
@jwt_required()
@require_permission('printedparts.delete') @require_permission('printedparts.delete')
def delete_item_file(file_id: int): def delete_item_file(file_id: int):
"""Remove a bad revision (wrong file uploaded). History otherwise stays.""" """Remove a bad revision (wrong file uploaded). History otherwise stays."""

View File

@@ -107,6 +107,9 @@ class PrintedpartsPlugin(BasePlugin):
'icon': 'box', 'icon': 'box',
'route': '/printedparts', 'route': '/printedparts',
'position': 27, 'position': 27,
# Named so the nav can hide it from anybody - a signed-out
# visitor included - who does not hold it.
'permission': 'printedparts.view',
'section': 'assets', 'section': 'assets',
}, },
] ]

View File

@@ -68,7 +68,6 @@ def get_printer_type(type_id: int):
@printers_asset_bp.route('/types', methods=['POST']) @printers_asset_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('printers.create') @require_permission('printers.create')
def create_printer_type(): def create_printer_type():
"""Create a new printer type.""" """Create a new printer type."""
@@ -105,7 +104,6 @@ def create_printer_type():
@printers_asset_bp.route('/types/<int:type_id>', methods=['PUT']) @printers_asset_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('printers.edit') @require_permission('printers.edit')
def update_printer_type(type_id: int): def update_printer_type(type_id: int):
"""Update a printer type.""" """Update a printer type."""
@@ -129,7 +127,6 @@ def update_printer_type(type_id: int):
@printers_asset_bp.route('/types/<int:type_id>', methods=['DELETE']) @printers_asset_bp.route('/types/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('printers.delete') @require_permission('printers.delete')
def delete_printer_type(type_id: int): def delete_printer_type(type_id: int):
"""Delete a printer type. Refused if any printer still uses it.""" """Delete a printer type. Refused if any printer still uses it."""
@@ -161,7 +158,6 @@ def list_drivers():
@printers_asset_bp.route('/drivers', methods=['POST']) @printers_asset_bp.route('/drivers', methods=['POST'])
@jwt_required()
@require_permission('printers.create') @require_permission('printers.create')
def create_driver(): def create_driver():
data = request.get_json() or {} data = request.get_json() or {}
@@ -180,7 +176,6 @@ def create_driver():
@printers_asset_bp.route('/drivers/<int:driver_id>', methods=['PUT']) @printers_asset_bp.route('/drivers/<int:driver_id>', methods=['PUT'])
@jwt_required()
@require_permission('printers.edit') @require_permission('printers.edit')
def update_driver(driver_id): def update_driver(driver_id):
d = db.session.get(PrinterDriver, driver_id) d = db.session.get(PrinterDriver, driver_id)
@@ -197,7 +192,6 @@ def update_driver(driver_id):
@printers_asset_bp.route('/drivers/<int:driver_id>', methods=['DELETE']) @printers_asset_bp.route('/drivers/<int:driver_id>', methods=['DELETE'])
@jwt_required()
@require_permission('printers.delete') @require_permission('printers.delete')
def delete_driver(driver_id): def delete_driver(driver_id):
d = db.session.get(PrinterDriver, driver_id) d = db.session.get(PrinterDriver, driver_id)
@@ -993,7 +987,6 @@ def get_asset_printer_assignment(asset_id: int):
@printers_asset_bp.route('/assignments/for-asset/<int:asset_id>', methods=['PUT']) @printers_asset_bp.route('/assignments/for-asset/<int:asset_id>', methods=['PUT'])
@jwt_required()
@require_permission('printers.edit') @require_permission('printers.edit')
def set_asset_printer_assignment(asset_id: int): def set_asset_printer_assignment(asset_id: int):
"""Reconcile one asset's whole printer assignment in a single call. """Reconcile one asset's whole printer assignment in a single call.
@@ -1498,7 +1491,6 @@ def _observed_host_block(hostname, asset, index):
@printers_asset_bp.route('/observed/<hostname>', methods=['GET']) @printers_asset_bp.route('/observed/<hostname>', methods=['GET'])
@jwt_required()
@require_permission('printers.view') @require_permission('printers.view')
def observed_for_host(hostname: str): def observed_for_host(hostname: str):
"""What a host last reported, each queue judged against what it is assigned. """What a host last reported, each queue judged against what it is assigned.
@@ -1536,7 +1528,6 @@ def observed_for_host(hostname: str):
@printers_asset_bp.route('/observed/for-asset/<int:asset_id>', methods=['GET']) @printers_asset_bp.route('/observed/for-asset/<int:asset_id>', methods=['GET'])
@jwt_required()
@require_permission('printers.view') @require_permission('printers.view')
def observed_for_asset(asset_id: int): def observed_for_asset(asset_id: int):
"""The same comparison, reached from an asset page: one block per host. """The same comparison, reached from an asset page: one block per host.
@@ -1649,7 +1640,6 @@ def _seed_source_hostnames(asset):
@printers_asset_bp.route('/assignments/seed-from-observed/<int:asset_id>', @printers_asset_bp.route('/assignments/seed-from-observed/<int:asset_id>',
methods=['POST']) methods=['POST'])
@jwt_required()
@require_permission('printers.edit') @require_permission('printers.edit')
def seed_assignment_from_observed(asset_id: int): def seed_assignment_from_observed(asset_id: int):
"""Write what a PC observed as the assignment of the asset in the path. """Write what a PC observed as the assignment of the asset in the path.
@@ -1840,7 +1830,6 @@ def get_printer_by_asset(asset_id: int):
@printers_asset_bp.route('', methods=['POST']) @printers_asset_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('printers.create') @require_permission('printers.create')
def create_printer(): def create_printer():
""" """
@@ -1944,7 +1933,6 @@ def create_printer():
@printers_asset_bp.route('/<int:printer_id>', methods=['PUT']) @printers_asset_bp.route('/<int:printer_id>', methods=['PUT'])
@jwt_required()
@require_permission('printers.edit') @require_permission('printers.edit')
def update_printer(printer_id: int): def update_printer(printer_id: int):
"""Update printer (both Asset and Printer records).""" """Update printer (both Asset and Printer records)."""
@@ -2031,7 +2019,6 @@ def update_printer(printer_id: int):
@printers_asset_bp.route('/<int:printer_id>', methods=['DELETE']) @printers_asset_bp.route('/<int:printer_id>', methods=['DELETE'])
@jwt_required()
@require_permission('printers.delete') @require_permission('printers.delete')
def delete_printer(printer_id: int): def delete_printer(printer_id: int):
"""Delete (soft delete) printer.""" """Delete (soft delete) printer."""
@@ -2303,7 +2290,6 @@ def printer_lookup():
@printers_asset_bp.route('/supplies/refresh', methods=['POST']) @printers_asset_bp.route('/supplies/refresh', methods=['POST'])
@jwt_required()
@require_permission('printers.create') @require_permission('printers.create')
def refresh_supplies_cache(): def refresh_supplies_cache():
"""Clear cached Zabbix supply data so the next read pulls fresh values. """Clear cached Zabbix supply data so the next read pulls fresh values.
@@ -2485,7 +2471,6 @@ def list_model_supplies(modelnumberid: int):
@printers_asset_bp.route('/models/<int:modelnumberid>/supplies', methods=['POST']) @printers_asset_bp.route('/models/<int:modelnumberid>/supplies', methods=['POST'])
@jwt_required()
@require_permission('printers.create') @require_permission('printers.create')
def create_model_supply(modelnumberid: int): def create_model_supply(modelnumberid: int):
"""Add a supply to a model.""" """Add a supply to a model."""
@@ -2526,7 +2511,6 @@ def create_model_supply(modelnumberid: int):
@printers_asset_bp.route('/supplies/<int:modelsupplyid>', methods=['PUT']) @printers_asset_bp.route('/supplies/<int:modelsupplyid>', methods=['PUT'])
@jwt_required()
@require_permission('printers.edit') @require_permission('printers.edit')
def update_model_supply(modelsupplyid: int): def update_model_supply(modelsupplyid: int):
"""Update a model supply.""" """Update a model supply."""
@@ -2571,7 +2555,6 @@ def update_model_supply(modelsupplyid: int):
@printers_asset_bp.route('/supplies/<int:modelsupplyid>', methods=['DELETE']) @printers_asset_bp.route('/supplies/<int:modelsupplyid>', methods=['DELETE'])
@jwt_required()
@require_permission('printers.delete') @require_permission('printers.delete')
def delete_model_supply(modelsupplyid: int): def delete_model_supply(modelsupplyid: int):
"""Delete a model supply.""" """Delete a model supply."""
@@ -2615,7 +2598,6 @@ def _reordertip(supply):
@printers_asset_bp.route('/dashboard/supplies', methods=['GET']) @printers_asset_bp.route('/dashboard/supplies', methods=['GET'])
@jwt_required()
@require_permission('printers.view') @require_permission('printers.view')
def dashboard_supplies(): def dashboard_supplies():
"""Printers needing a cartridge, flattened to one row per printer. """Printers needing a cartridge, flattened to one row per printer.

View File

@@ -14,7 +14,7 @@ from flask_jwt_extended import jwt_required
from werkzeug.utils import secure_filename from werkzeug.utils import secure_filename
from shopdb.api import (db, success_response, error_response, ErrorCodes, from shopdb.api import (db, success_response, error_response, ErrorCodes,
require_permission) require_permission, require_any_permission)
from shopdb.api import send_upload from shopdb.api import send_upload
from ..models import TvSlide from ..models import TvSlide
@@ -90,8 +90,7 @@ def serve_image(surface, filename):
# ============================================================================= # =============================================================================
@slides_bp.route('/<surface>', methods=['GET']) @slides_bp.route('/<surface>', methods=['GET'])
@jwt_required() @require_any_permission('slides.view', 'slides.manage')
@require_permission('slides.manage')
def list_slides(surface): def list_slides(surface):
if not _valid_surface(surface): if not _valid_surface(surface):
return error_response(ErrorCodes.VALIDATION_ERROR, 'Unknown surface') return error_response(ErrorCodes.VALIDATION_ERROR, 'Unknown surface')
@@ -108,7 +107,6 @@ def list_slides(surface):
@slides_bp.route('/<surface>/upload', methods=['POST']) @slides_bp.route('/<surface>/upload', methods=['POST'])
@jwt_required()
@require_permission('slides.manage') @require_permission('slides.manage')
def upload_slides(surface): def upload_slides(surface):
if not _valid_surface(surface): if not _valid_surface(surface):
@@ -153,7 +151,6 @@ def upload_slides(surface):
@slides_bp.route('/<surface>/order', methods=['POST']) @slides_bp.route('/<surface>/order', methods=['POST'])
@jwt_required()
@require_permission('slides.manage') @require_permission('slides.manage')
def reorder_slides(surface): def reorder_slides(surface):
if not _valid_surface(surface): if not _valid_surface(surface):
@@ -169,7 +166,6 @@ def reorder_slides(surface):
@slides_bp.route('/<surface>/delete', methods=['POST']) @slides_bp.route('/<surface>/delete', methods=['POST'])
@jwt_required()
@require_permission('slides.manage') @require_permission('slides.manage')
def delete_slides(surface): def delete_slides(surface):
if not _valid_surface(surface): if not _valid_surface(surface):
@@ -195,7 +191,6 @@ def delete_slides(surface):
@slides_bp.route('/<surface>/<int:slideid>', methods=['PATCH']) @slides_bp.route('/<surface>/<int:slideid>', methods=['PATCH'])
@jwt_required()
@require_permission('slides.manage') @require_permission('slides.manage')
def update_slide(surface, slideid): def update_slide(surface, slideid):
if not _valid_surface(surface): if not _valid_surface(surface):

View File

@@ -63,6 +63,7 @@ class SlidesPlugin(BasePlugin):
non-admin role so a curator can manage the lobby TV + screensaver non-admin role so a curator can manage the lobby TV + screensaver
without full admin. Admins hold it by default.""" without full admin. Admins hold it by default."""
return [ return [
('slides.view', 'View the slide decks', 'slides'),
('slides.manage', ('slides.manage',
'Manage lobby display and screensaver slides', 'slides'), 'Manage lobby display and screensaver slides', 'slides'),
] ]
@@ -76,7 +77,10 @@ class SlidesPlugin(BasePlugin):
'icon': 'image', 'icon': 'image',
'route': '/settings/slides', 'route': '/settings/slides',
'position': 7, 'position': 7,
'permission': 'slides.manage', # The read permission: a manager holds it implicitly through
# the route's require_any_permission, and it is the one a site
# can grant to guests.
'permission': ['slides.view', 'slides.manage'],
}, },
] ]

View File

@@ -70,6 +70,19 @@ class ToolsPlugin(BasePlugin):
('tools.secrets', 'Create secure send links', 'tools'), ('tools.secrets', 'Create secure send links', 'tools'),
] ]
def get_guest_grantable_permissions(self) -> List[str]:
"""Creating a secure send link is meant to work without an account.
Somebody standing at a bench needs to send a password to a vendor. The
recipient never had an account, and often neither does the sender - the
unguessable token is the authorisation, and the link is one-view.
A guest-created link records no creator. The audit trail says when and
from where, and never who. That is the cost, and it is why this is the
only write in the product offered to guests at all.
"""
return ['tools.secrets']
def get_settings_defaults(self) -> List[dict]: def get_settings_defaults(self) -> List[dict]:
"""The one switch this plugin owns. """The one switch this plugin owns.

View File

@@ -338,7 +338,6 @@ def get_usb_device(device_id):
@usb_bp.route('', methods=['POST']) @usb_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('usb.create') @require_permission('usb.create')
def create_usb_device(): def create_usb_device():
"""Add a device (starts checked-in).""" """Add a device (starts checked-in)."""
@@ -385,7 +384,6 @@ def create_usb_device():
@usb_bp.route('/<device_id>', methods=['PUT']) @usb_bp.route('/<device_id>', methods=['PUT'])
@jwt_required()
@require_permission('usb.edit') @require_permission('usb.edit')
def update_usb_device(device_id): def update_usb_device(device_id):
"""Edit device_desc / device_owner / locker_location / status.""" """Edit device_desc / device_owner / locker_location / status."""
@@ -428,7 +426,6 @@ def update_usb_device(device_id):
@usb_bp.route('/<device_id>/retire', methods=['POST']) @usb_bp.route('/<device_id>/retire', methods=['POST'])
@jwt_required()
@require_permission('usb.edit') @require_permission('usb.edit')
def retire_usb_device(device_id): def retire_usb_device(device_id):
"""Retire a device (status -> retired).""" """Retire a device (status -> retired)."""
@@ -463,7 +460,6 @@ def retire_usb_device(device_id):
# ============================================================================= # =============================================================================
@usb_bp.route('/<device_id>/checkout', methods=['POST']) @usb_bp.route('/<device_id>/checkout', methods=['POST'])
@jwt_required()
@require_permission('usb.create') @require_permission('usb.create')
def checkout_device(device_id): def checkout_device(device_id):
"""Check a device out to a badge.""" """Check a device out to a badge."""
@@ -528,7 +524,6 @@ def checkout_device(device_id):
@usb_bp.route('/<device_id>/checkin', methods=['POST']) @usb_bp.route('/<device_id>/checkin', methods=['POST'])
@jwt_required()
@require_permission('usb.create') @require_permission('usb.create')
def checkin_device(device_id): def checkin_device(device_id):
"""Check a device back in from a badge.""" """Check a device back in from a badge."""
@@ -1111,7 +1106,6 @@ AUDITCOLUMNS = ['timestamp', 'action', 'device_id', 'device_desc', 'badge',
@usb_bp.route('/reports/audit', methods=['GET']) @usb_bp.route('/reports/audit', methods=['GET'])
@jwt_required()
@require_permission('usb.view') @require_permission('usb.view')
def report_audit(): def report_audit():
"""Every check-out and check-in in the window, newest first. """Every check-out and check-in in the window, newest first.

View File

@@ -197,7 +197,6 @@ def get_warranty(warrantyid):
@warranty_bp.route('', methods=['POST']) @warranty_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('warranty.create') @require_permission('warranty.create')
def create_warranty(): def create_warranty():
data = request.get_json() or {} data = request.get_json() or {}
@@ -220,7 +219,6 @@ def create_warranty():
@warranty_bp.route('/<int:warrantyid>', methods=['PUT']) @warranty_bp.route('/<int:warrantyid>', methods=['PUT'])
@jwt_required()
@require_permission('warranty.edit') @require_permission('warranty.edit')
def update_warranty(warrantyid): def update_warranty(warrantyid):
warranty = db.session.get(Warranty, warrantyid) warranty = db.session.get(Warranty, warrantyid)
@@ -250,7 +248,6 @@ def update_warranty(warrantyid):
@warranty_bp.route('/<int:warrantyid>', methods=['DELETE']) @warranty_bp.route('/<int:warrantyid>', methods=['DELETE'])
@jwt_required()
@require_permission('warranty.delete') @require_permission('warranty.delete')
def delete_warranty(warrantyid): def delete_warranty(warrantyid):
warranty = db.session.get(Warranty, warrantyid) warranty = db.session.get(Warranty, warrantyid)
@@ -266,7 +263,6 @@ def delete_warranty(warrantyid):
# ============================================================================= # =============================================================================
@warranty_bp.route('/<int:warrantyid>/refresh', methods=['POST']) @warranty_bp.route('/<int:warrantyid>/refresh', methods=['POST'])
@jwt_required()
@require_permission('warranty.edit') @require_permission('warranty.edit')
def refresh_warranty(warrantyid): def refresh_warranty(warrantyid):
warranty = db.session.get(Warranty, warrantyid) warranty = db.session.get(Warranty, warrantyid)
@@ -296,7 +292,6 @@ def refresh_warranty(warrantyid):
# ============================================================================= # =============================================================================
@warranty_bp.route('/sync/dell', methods=['POST']) @warranty_bp.route('/sync/dell', methods=['POST'])
@jwt_required()
@require_permission('warranty.edit') @require_permission('warranty.edit')
def sync_dell(): def sync_dell():
"""Look up every asset serial (= Dell service tag) that has no warranty yet """Look up every asset serial (= Dell service tag) that has no warranty yet
@@ -414,7 +409,6 @@ def warranty_report():
@warranty_bp.route('/dashboard/expiring', methods=['GET']) @warranty_bp.route('/dashboard/expiring', methods=['GET'])
@jwt_required()
@require_permission('warranty.view') @require_permission('warranty.view')
def dashboard_expiring(): def dashboard_expiring():
"""Warranties running out, and ones that already have. """Warranties running out, and ones that already have.
@@ -498,7 +492,6 @@ def _hostname(asset):
# ============================================================================= # =============================================================================
@warranty_bp.route('/<int:warrantyid>/proof', methods=['POST']) @warranty_bp.route('/<int:warrantyid>/proof', methods=['POST'])
@jwt_required()
@require_permission('warranty.edit') @require_permission('warranty.edit')
def upload_proof(warrantyid): def upload_proof(warrantyid):
"""Upload (or replace) the proof-of-cover document for a warranty.""" """Upload (or replace) the proof-of-cover document for a warranty."""
@@ -548,7 +541,6 @@ def upload_proof(warrantyid):
@warranty_bp.route('/proof/<path:filename>', methods=['GET']) @warranty_bp.route('/proof/<path:filename>', methods=['GET'])
@jwt_required()
@require_permission('warranty.view') @require_permission('warranty.view')
def serve_proof(filename): def serve_proof(filename):
"""Download a proof document. """Download a proof document.
@@ -566,7 +558,6 @@ def serve_proof(filename):
@warranty_bp.route('/<int:warrantyid>/proof', methods=['DELETE']) @warranty_bp.route('/<int:warrantyid>/proof', methods=['DELETE'])
@jwt_required()
@require_permission('warranty.edit') @require_permission('warranty.edit')
def delete_proof(warrantyid): def delete_proof(warrantyid):
"""Remove a warranty's proof document.""" """Remove a warranty's proof document."""

View File

@@ -57,7 +57,7 @@ from .plugins import plugin_manager
# permission / empty / position. BREAKING for any plugin still using the old # permission / empty / position. BREAKING for any plugin still using the old
# shape, which is why it is recorded here: the change itself shipped earlier # shape, which is why it is recorded here: the change itself shipped earlier
# without a bump, and a contract that changes silently is not a contract. # without a bump, and a contract that changes silently is not a contract.
__contract_version__ = '0.20.0' __contract_version__ = '0.21.0'
# Product release version (see ADR-007). The product version and the # Product release version (see ADR-007). The product version and the
# plugin-contract version above are distinct series with independent # plugin-contract version above are distinct series with independent

View File

@@ -68,7 +68,7 @@ from shopdb.utils.responses import (
from shopdb.utils.pagination import get_pagination_params, paginate_query from shopdb.utils.pagination import get_pagination_params, paginate_query
# Authorization decorators for gating plugin write routes # Authorization decorators for gating plugin write routes
from shopdb.utils.authz import require_permission, require_role from shopdb.utils.authz import require_permission, require_any_permission, require_role
# Service-token authorization for unattended plugin endpoints (collector, # Service-token authorization for unattended plugin endpoints (collector,
# GE-Enforce fetch, ...): checks a scoped managed token without exposing token # GE-Enforce fetch, ...): checks a scoped managed token without exposing token
@@ -298,6 +298,7 @@ __all__ = [
'paginate_query', 'paginate_query',
# Authorization decorators # Authorization decorators
'require_permission', 'require_permission',
'require_any_permission',
'require_role', 'require_role',
'service_token_authorized', 'service_token_authorized',
'authorized_service_token', 'authorized_service_token',

View File

@@ -784,13 +784,20 @@ def fix_controls_direction():
@seed_cli.command('permissions') @seed_cli.command('permissions')
@with_appcontext @with_appcontext
def seed_permissions(): def seed_permissions():
"""Seed predefined permissions.""" """Seed predefined permissions, and the guest role that can hold them."""
from shopdb.extensions import db from shopdb.extensions import db
from shopdb.core.models import Permission from shopdb.core.models import Permission, Role
created = Permission.seed() created = Permission.seed()
# Seeded here rather than in `seed admin` so an existing site picks it up
# on the upgrade it already runs. It holds nothing until somebody grants
# it something, so seeding it changes no behaviour.
guest = Role.seedguest()
db.session.commit() db.session.commit()
click.echo(click.style(f"{created} permissions created.", fg='green')) click.echo(click.style(f"{created} permissions created.", fg='green'))
if guest:
click.echo(click.style(
"guest role created (holds no permissions).", fg='green'))
@seed_cli.command('settings') @seed_cli.command('settings')

View File

@@ -86,7 +86,6 @@ def list_apitokens():
@apitokens_bp.route('', methods=['POST']) @apitokens_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('apitokens.create') @require_permission('apitokens.create')
def create_apitoken(): def create_apitoken():
"""Create a token for the caller. Returns the full secret ONCE. """Create a token for the caller. Returns the full secret ONCE.
@@ -141,7 +140,6 @@ def create_apitoken():
@apitokens_bp.route('/<int:tokenid>', methods=['PUT']) @apitokens_bp.route('/<int:tokenid>', methods=['PUT'])
@jwt_required()
@require_permission('apitokens.create') @require_permission('apitokens.create')
def update_apitoken(tokenid: int): def update_apitoken(tokenid: int):
"""Rename, rescope, or deactivate a token. Own token, or any if admin. """Rename, rescope, or deactivate a token. Own token, or any if admin.
@@ -183,7 +181,6 @@ def update_apitoken(tokenid: int):
@apitokens_bp.route('/<int:tokenid>', methods=['DELETE']) @apitokens_bp.route('/<int:tokenid>', methods=['DELETE'])
@jwt_required()
@require_permission('apitokens.create') @require_permission('apitokens.create')
def revoke_apitoken(tokenid: int): def revoke_apitoken(tokenid: int):
"""Revoke (deactivate) a token. Own token, or any if admin.""" """Revoke (deactivate) a token. Own token, or any if admin."""

View File

@@ -180,7 +180,6 @@ def get_application(app_id: int):
@applications_bp.route('', methods=['POST']) @applications_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('applications.create') @require_permission('applications.create')
def create_application(): def create_application():
"""Create a new application.""" """Create a new application."""
@@ -224,7 +223,6 @@ def create_application():
@applications_bp.route('/<int:app_id>', methods=['PUT']) @applications_bp.route('/<int:app_id>', methods=['PUT'])
@jwt_required()
@require_permission('applications.edit') @require_permission('applications.edit')
def update_application(app_id: int): def update_application(app_id: int):
"""Update an application.""" """Update an application."""
@@ -270,7 +268,6 @@ def update_application(app_id: int):
@applications_bp.route('/<int:app_id>', methods=['DELETE']) @applications_bp.route('/<int:app_id>', methods=['DELETE'])
@jwt_required()
@require_permission('applications.delete') @require_permission('applications.delete')
def delete_application(app_id: int): def delete_application(app_id: int):
"""Delete (deactivate) an application.""" """Delete (deactivate) an application."""
@@ -303,7 +300,6 @@ def list_versions(app_id: int):
@applications_bp.route('/<int:app_id>/versions', methods=['POST']) @applications_bp.route('/<int:app_id>/versions', methods=['POST'])
@jwt_required()
@require_permission('applications.create') @require_permission('applications.create')
def create_version(app_id: int): def create_version(app_id: int):
"""Create a new version for an application.""" """Create a new version for an application."""
@@ -397,7 +393,6 @@ def list_machine_applications(machine_id: int):
@applications_bp.route('/machines/<int:machine_id>', methods=['POST']) @applications_bp.route('/machines/<int:machine_id>', methods=['POST'])
@jwt_required()
@require_permission('applications.create') @require_permission('applications.create')
def install_application(machine_id: int): def install_application(machine_id: int):
"""Install an application on a computer.""" """Install an application on a computer."""
@@ -449,7 +444,6 @@ def install_application(machine_id: int):
@applications_bp.route('/machines/<int:machine_id>/<int:app_id>', methods=['DELETE']) @applications_bp.route('/machines/<int:machine_id>/<int:app_id>', methods=['DELETE'])
@jwt_required()
@require_permission('applications.delete') @require_permission('applications.delete')
def uninstall_application(machine_id: int, app_id: int): def uninstall_application(machine_id: int, app_id: int):
"""Uninstall an application from a computer.""" """Uninstall an application from a computer."""
@@ -474,7 +468,6 @@ def uninstall_application(machine_id: int, app_id: int):
@applications_bp.route('/machines/<int:machine_id>/<int:app_id>', methods=['PUT']) @applications_bp.route('/machines/<int:machine_id>/<int:app_id>', methods=['PUT'])
@jwt_required()
@require_permission('applications.edit') @require_permission('applications.edit')
def update_installed_app(machine_id: int, app_id: int): def update_installed_app(machine_id: int, app_id: int):
"""Update installed application (e.g., change version).""" """Update installed application (e.g., change version)."""
@@ -516,7 +509,6 @@ def update_installed_app(machine_id: int, app_id: int):
# ============================================================================= # =============================================================================
@applications_bp.route('/<int:app_id>/image', methods=['POST']) @applications_bp.route('/<int:app_id>/image', methods=['POST'])
@jwt_required()
@require_permission('applications.edit') @require_permission('applications.edit')
def upload_application_image(app_id: int): def upload_application_image(app_id: int):
"""Upload (or replace) an application's image. """Upload (or replace) an application's image.
@@ -555,7 +547,6 @@ def serve_application_image(filename):
@applications_bp.route('/<int:app_id>/image', methods=['DELETE']) @applications_bp.route('/<int:app_id>/image', methods=['DELETE'])
@jwt_required()
@require_permission('applications.edit') @require_permission('applications.edit')
def delete_application_image(app_id: int): def delete_application_image(app_id: int):
"""Remove an application's image and clear the field.""" """Remove an application's image and clear the field."""
@@ -574,7 +565,6 @@ def delete_application_image(app_id: int):
@applications_bp.route('/<int:app_id>/package', methods=['POST']) @applications_bp.route('/<int:app_id>/package', methods=['POST'])
@jwt_required()
@require_permission('applications.edit') @require_permission('applications.edit')
def upload_application_package(app_id: int): def upload_application_package(app_id: int):
"""Upload (or replace) the installer for an application. """Upload (or replace) the installer for an application.
@@ -627,7 +617,6 @@ def upload_application_package(app_id: int):
@applications_bp.route('/package/<path:filename>', methods=['GET']) @applications_bp.route('/package/<path:filename>', methods=['GET'])
@jwt_required()
@require_permission('applications.view') @require_permission('applications.view')
def serve_application_package(filename): def serve_application_package(filename):
"""Download an uploaded installer. """Download an uploaded installer.
@@ -640,7 +629,6 @@ def serve_application_package(filename):
@applications_bp.route('/<int:app_id>/package', methods=['DELETE']) @applications_bp.route('/<int:app_id>/package', methods=['DELETE'])
@jwt_required()
@require_permission('applications.edit') @require_permission('applications.edit')
def delete_application_package(app_id: int): def delete_application_package(app_id: int):
"""Remove an uploaded installer and clear the path it set.""" """Remove an uploaded installer and clear the path it set."""

View File

@@ -60,7 +60,6 @@ def get_asset_type(type_id: int):
@assets_bp.route('/types', methods=['POST']) @assets_bp.route('/types', methods=['POST'])
@jwt_required()
@require_permission('assets.create') @require_permission('assets.create')
def create_asset_type(): def create_asset_type():
"""Create a new asset type.""" """Create a new asset type."""
@@ -92,7 +91,6 @@ def create_asset_type():
@assets_bp.route('/types/<int:type_id>', methods=['PUT']) @assets_bp.route('/types/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('assets.edit') @require_permission('assets.edit')
def update_asset_type(type_id: int): def update_asset_type(type_id: int):
"""Update an asset type's display fields (color/icon/description). The name, """Update an asset type's display fields (color/icon/description). The name,
@@ -148,7 +146,6 @@ def get_asset_status(status_id: int):
@assets_bp.route('/statuses', methods=['POST']) @assets_bp.route('/statuses', methods=['POST'])
@jwt_required()
@require_permission('assets.create') @require_permission('assets.create')
def create_asset_status(): def create_asset_status():
"""Create a new asset status.""" """Create a new asset status."""
@@ -177,7 +174,6 @@ def create_asset_status():
@assets_bp.route('/statuses/<int:status_id>', methods=['PUT']) @assets_bp.route('/statuses/<int:status_id>', methods=['PUT'])
@jwt_required()
@require_permission('assets.edit') @require_permission('assets.edit')
def update_asset_status(status_id: int): def update_asset_status(status_id: int):
"""Update an asset status.""" """Update an asset status."""
@@ -206,7 +202,6 @@ def update_asset_status(status_id: int):
@assets_bp.route('/statuses/<int:status_id>', methods=['DELETE']) @assets_bp.route('/statuses/<int:status_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete') @require_permission('assets.delete')
def delete_asset_status(status_id: int): def delete_asset_status(status_id: int):
"""Delete an asset status. Refused if any asset still uses it.""" """Delete an asset status. Refused if any asset still uses it."""
@@ -241,7 +236,6 @@ def list_relationship_types():
@assets_bp.route('/relationshiptypes', methods=['POST']) @assets_bp.route('/relationshiptypes', methods=['POST'])
@jwt_required()
@require_permission('assets.create') @require_permission('assets.create')
def create_relationship_type(): def create_relationship_type():
"""Create a new asset relationship type.""" """Create a new asset relationship type."""
@@ -288,7 +282,6 @@ def _rel_type_dict(t):
@assets_bp.route('/relationshiptypes/<int:type_id>', methods=['PUT']) @assets_bp.route('/relationshiptypes/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_permission('assets.edit') @require_permission('assets.edit')
def update_relationship_type(type_id: int): def update_relationship_type(type_id: int):
"""Update a relationship type.""" """Update a relationship type."""
@@ -308,7 +301,6 @@ def update_relationship_type(type_id: int):
@assets_bp.route('/relationshiptypes/<int:type_id>', methods=['DELETE']) @assets_bp.route('/relationshiptypes/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete') @require_permission('assets.delete')
def delete_relationship_type(type_id: int): def delete_relationship_type(type_id: int):
"""Delete a relationship type. Refused if any relationship still uses it.""" """Delete a relationship type. Refused if any relationship still uses it."""
@@ -437,7 +429,6 @@ def get_asset(asset_id: int):
@assets_bp.route('', methods=['POST']) @assets_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('assets.create') @require_permission('assets.create')
def create_asset(): def create_asset():
"""Create a new asset.""" """Create a new asset."""
@@ -489,7 +480,6 @@ def create_asset():
@assets_bp.route('/<int:asset_id>', methods=['PUT']) @assets_bp.route('/<int:asset_id>', methods=['PUT'])
@jwt_required()
@require_permission('assets.edit') @require_permission('assets.edit')
def update_asset(asset_id: int): def update_asset(asset_id: int):
"""Update an asset.""" """Update an asset."""
@@ -542,7 +532,6 @@ def update_asset(asset_id: int):
@assets_bp.route('/<int:asset_id>', methods=['DELETE']) @assets_bp.route('/<int:asset_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete') @require_permission('assets.delete')
def delete_asset(asset_id: int): def delete_asset(asset_id: int):
"""Delete (soft delete) an asset.""" """Delete (soft delete) an asset."""
@@ -733,7 +722,6 @@ def get_asset_relationships(asset_id: int):
@assets_bp.route('/relationships', methods=['POST']) @assets_bp.route('/relationships', methods=['POST'])
@jwt_required()
@require_permission('assets.create') @require_permission('assets.create')
def create_asset_relationship(): def create_asset_relationship():
"""Create a relationship between two assets. """Create a relationship between two assets.
@@ -884,7 +872,6 @@ def create_asset_relationship():
@assets_bp.route('/relationships/<int:rel_id>', methods=['DELETE']) @assets_bp.route('/relationships/<int:rel_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete') @require_permission('assets.delete')
def delete_asset_relationship(rel_id: int): def delete_asset_relationship(rel_id: int):
"""Delete an asset relationship. """Delete an asset relationship.

View File

@@ -52,7 +52,6 @@ def _resolve_full_names(ssos):
@auditlogs_bp.route('', methods=['GET']) @auditlogs_bp.route('', methods=['GET'])
@jwt_required()
@require_permission('audit.view') @require_permission('audit.view')
def list_auditlogs(): def list_auditlogs():
""" """
@@ -136,7 +135,6 @@ def list_auditlogs():
@auditlogs_bp.route('/entity/<entitytype>/<int:entityid>', methods=['GET']) @auditlogs_bp.route('/entity/<entitytype>/<int:entityid>', methods=['GET'])
@jwt_required()
@require_permission('audit.view') @require_permission('audit.view')
def get_entity_history(entitytype: str, entityid: int): def get_entity_history(entitytype: str, entityid: int):
"""Get audit history for a specific entity.""" """Get audit history for a specific entity."""
@@ -149,7 +147,6 @@ def get_entity_history(entitytype: str, entityid: int):
@auditlogs_bp.route('/stats', methods=['GET']) @auditlogs_bp.route('/stats', methods=['GET'])
@jwt_required()
@require_permission('audit.view') @require_permission('audit.view')
def get_stats(): def get_stats():
"""Get audit log statistics.""" """Get audit log statistics."""
@@ -198,7 +195,6 @@ def db_func_count_by(column):
@auditlogs_bp.route('/retention', methods=['GET']) @auditlogs_bp.route('/retention', methods=['GET'])
@jwt_required()
@require_permission('audit.view') @require_permission('audit.view')
def get_retention(): def get_retention():
"""Size of the log and what the configured retention would remove. """Size of the log and what the configured retention would remove.
@@ -212,7 +208,6 @@ def get_retention():
@auditlogs_bp.route('/purge', methods=['POST']) @auditlogs_bp.route('/purge', methods=['POST'])
@jwt_required()
@require_permission('audit.purge') @require_permission('audit.purge')
def purge_auditlogs(): def purge_auditlogs():
"""Delete entries older than the retention window. """Delete entries older than the retention window.

View File

@@ -187,6 +187,26 @@ def get_navigation():
# Sort by position # Sort by position
all_items.sort(key=lambda x: x.get('position', 99)) all_items.sort(key=lambda x: x.get('position', 99))
# A signed-out visitor is shown only what the guest role can actually
# reach. Without this the sidebar offers them the whole app and every link
# bounces off a 401, which reads as a broken site rather than a closed
# door. An item with no declared permission is treated as members-only: a
# plugin opts into being guest-visible by naming the permission its page
# needs, which is the same string the API already gates on.
from flask_jwt_extended import verify_jwt_in_request
from shopdb.utils.authz import currentuser, guestholds
verify_jwt_in_request(optional=True)
def guestmayreach(item):
declared = item.get('permission')
if not declared:
return False
names = declared if isinstance(declared, list) else [declared]
return any(guestholds(name) for name in names)
if currentuser() is None:
all_items = [item for item in all_items if guestmayreach(item)]
return success_response(all_items) return success_response(all_items)

View File

@@ -115,7 +115,6 @@ def apply_transform(asset, transform):
@mappositions_bp.route('/transform', methods=['POST']) @mappositions_bp.route('/transform', methods=['POST'])
@jwt_required()
@require_permission('assets.edit') @require_permission('assets.edit')
def transform_positions(): def transform_positions():
"""Move every placed marker on a level by a transform read off landmarks. """Move every placed marker on a level by a transform read off landmarks.
@@ -225,7 +224,6 @@ def transform_positions():
# ============================================================================= # =============================================================================
@mappositions_bp.route('/positions', methods=['POST']) @mappositions_bp.route('/positions', methods=['POST'])
@jwt_required()
@require_permission('assets.edit') @require_permission('assets.edit')
def set_positions(): def set_positions():
"""Set positions for many assets at once. """Set positions for many assets at once.
@@ -301,7 +299,6 @@ def set_positions():
@mappositions_bp.route('/verify', methods=['POST']) @mappositions_bp.route('/verify', methods=['POST'])
@jwt_required()
@require_permission('assets.edit') @require_permission('assets.edit')
def verify_positions(): def verify_positions():
"""Mark markers as reviewed against the current drawing without moving them. """Mark markers as reviewed against the current drawing without moving them.
@@ -330,7 +327,6 @@ def verify_positions():
# ============================================================================= # =============================================================================
@mappositions_bp.route('/snapshots', methods=['GET']) @mappositions_bp.route('/snapshots', methods=['GET'])
@jwt_required()
@require_permission('assets.view') @require_permission('assets.view')
def list_snapshots(): def list_snapshots():
"""Snapshots, newest first. Metadata only - the positions are large.""" """Snapshots, newest first. Metadata only - the positions are large."""
@@ -341,7 +337,6 @@ def list_snapshots():
@mappositions_bp.route('/snapshots/<int:snapshotid>/restore', methods=['POST']) @mappositions_bp.route('/snapshots/<int:snapshotid>/restore', methods=['POST'])
@jwt_required()
@require_permission('assets.edit') @require_permission('assets.edit')
def restore_snapshot(snapshotid): def restore_snapshot(snapshotid):
"""Put the positions in this snapshot back. """Put the positions in this snapshot back.

View File

@@ -525,7 +525,6 @@ def pc_relationships():
@reports_bp.route('/email', methods=['POST']) @reports_bp.route('/email', methods=['POST'])
@jwt_required()
@require_permission('reports.export') @require_permission('reports.export')
def email_report(): def email_report():
"""Email a report's data as an HTML table (on-demand delivery). """Email a report's data as an HTML table (on-demand delivery).

View File

@@ -277,7 +277,6 @@ def get_setting(key: str):
@settings_bp.route('/<key>', methods=['PUT']) @settings_bp.route('/<key>', methods=['PUT'])
@jwt_required()
@require_permission('settings.edit') @require_permission('settings.edit')
def update_setting(key: str): def update_setting(key: str):
"""Update a setting value.""" """Update a setting value."""
@@ -336,7 +335,6 @@ def update_setting(key: str):
@settings_bp.route('/test-email', methods=['POST']) @settings_bp.route('/test-email', methods=['POST'])
@jwt_required()
@require_permission('settings.edit') @require_permission('settings.edit')
def test_email(): def test_email():
"""Send a test email to verify SMTP configuration. """Send a test email to verify SMTP configuration.
@@ -374,7 +372,6 @@ def test_email():
@settings_bp.route('', methods=['POST']) @settings_bp.route('', methods=['POST'])
@jwt_required()
@require_permission('settings.edit') @require_permission('settings.edit')
def create_setting(): def create_setting():
"""Create a new setting (admin only).""" """Create a new setting (admin only)."""
@@ -986,7 +983,6 @@ def build_default_settings():
@settings_bp.route('/seed', methods=['POST']) @settings_bp.route('/seed', methods=['POST'])
@jwt_required()
@require_permission('settings.edit') @require_permission('settings.edit')
def seed_default_settings(): def seed_default_settings():
"""Seed default settings if they don't exist.""" """Seed default settings if they don't exist."""

View File

@@ -6,7 +6,8 @@ from werkzeug.security import generate_password_hash
from shopdb.extensions import db from shopdb.extensions import db
from shopdb.core.models import ( from shopdb.core.models import (
User, Role, Permission, AuditLog, full_permission_catalog) User, Role, Permission, AuditLog, full_permission_catalog,
guest_grantable_permissions)
from shopdb.utils.responses import success_response, error_response, ErrorCodes from shopdb.utils.responses import success_response, error_response, ErrorCodes
from shopdb.utils.authz import require_role from shopdb.utils.authz import require_role
@@ -266,6 +267,9 @@ def list_permissions():
def list_roles(): def list_roles():
"""List all roles with their permissions.""" """List all roles with their permissions."""
roles = Role.query.order_by(Role.rolename).all() roles = Role.query.order_by(Role.rolename).all()
# What a guest MAY be granted, so the grid can grey out the rest rather
# than letting somebody tick a box the API will refuse.
guestgrantable = sorted(guest_grantable_permissions())
return success_response([{ return success_response([{
'roleid': r.roleid, 'roleid': r.roleid,
'rolename': r.rolename, 'rolename': r.rolename,
@@ -273,7 +277,9 @@ def list_roles():
'color': r.color, 'color': r.color,
'usercount': r.users.count(), 'usercount': r.users.count(),
'permissions': [p.name for p in r.permissions], 'permissions': [p.name for p in r.permissions],
'isadmin': r.rolename == 'admin' 'isadmin': r.rolename == 'admin',
'isguest': r.rolename == Role.GUEST,
'grantable': guestgrantable if r.rolename == Role.GUEST else None,
} for r in roles]) } for r in roles])
@@ -344,6 +350,20 @@ def update_role(roleid: int):
# Update permissions # Update permissions
if 'permissions' in data and role.rolename != 'admin': if 'permissions' in data and role.rolename != 'admin':
# The guest role is anyone with no account, so what it may hold is
# bounded: reads, plus the handful of writes a plugin has explicitly
# declared safe to do anonymously. Refused at the door rather than
# warned about - a checkbox that quietly makes deleting an asset
# anonymous is not a warning anybody reads twice.
if role.rolename == Role.GUEST:
allowed = guest_grantable_permissions()
refused = sorted(set(data['permissions']) - allowed)
if refused:
return error_response(
ErrorCodes.VALIDATION_ERROR,
'The guest role cannot hold {}. A guest may be granted any '
'view permission, and only writes a plugin has declared '
'safe to do without an account.'.format(', '.join(refused)))
old_perms = [p.name for p in role.permissions] old_perms = [p.name for p in role.permissions]
perms = Permission.query.filter(Permission.name.in_(data['permissions'])).all() perms = Permission.query.filter(Permission.name.in_(data['permissions'])).all()
new_perms = [p.name for p in perms] new_perms = [p.name for p in perms]
@@ -377,6 +397,14 @@ def delete_role(roleid: int):
if role.rolename == 'admin': if role.rolename == 'admin':
return error_response(ErrorCodes.VALIDATION_ERROR, 'Cannot delete the admin role') return error_response(ErrorCodes.VALIDATION_ERROR, 'Cannot delete the admin role')
# Deleting the guest role does not close the door, it removes the only
# place the door is described. Revoke its permissions instead.
if role.rolename == Role.GUEST:
return error_response(
ErrorCodes.VALIDATION_ERROR,
'Cannot delete the guest role. To close guest access, clear its '
'permissions.')
if role.users.count() > 0: if role.users.count() > 0:
return error_response(ErrorCodes.VALIDATION_ERROR, f'Role is assigned to {role.users.count()} user(s)') return error_response(ErrorCodes.VALIDATION_ERROR, f'Role is assigned to {role.users.count()} user(s)')

View File

@@ -13,7 +13,8 @@ from .mapsnapshot import MapPositionSnapshot
from .operatingsystem import OperatingSystem from .operatingsystem import OperatingSystem
from .relationship import AssetRelationship, RelationshipType, RelationshipTypePropagation from .relationship import AssetRelationship, RelationshipType, RelationshipTypePropagation
from .communication import Communication, CommunicationType from .communication import Communication, CommunicationType
from .user import User, Role, Permission, full_permission_catalog from .user import (User, Role, Permission, full_permission_catalog,
guest_grantable_permissions)
from .application import Application, AppVersion from .application import Application, AppVersion
from .supportteam import SupportTeam, SupportTeamContact from .supportteam import SupportTeam, SupportTeamContact
from .setting import Setting from .setting import Setting
@@ -57,6 +58,7 @@ __all__ = [
'Role', 'Role',
'Permission', 'Permission',
'full_permission_catalog', 'full_permission_catalog',
'guest_grantable_permissions',
# Applications # Applications
'Application', 'Application',
'AppVersion', 'AppVersion',

View File

@@ -152,6 +152,53 @@ def full_permission_catalog(include_disabled=False):
return catalog return catalog
def guest_grantable_permissions():
"""Which permissions the guest role may be granted.
Reading is the safe default and covers almost everything a site wants to
open up: any `.view` or `.read` permission may be handed to guests.
A write is different - it lets somebody with no account change this
database, and the audit trail can then say when and from where but never
who. So a write has to be BLESSED by whoever owns it, through the plugin's
get_guest_grantable_permissions(). Secure Send is the case that exists:
creating a one-view link for somebody is the whole point of the page, and
the page has always been usable by people with no account here.
Everything else is refused at the door rather than warned about, because a
checkbox that quietly makes deleting an asset anonymous is not a warning
anybody reads twice.
"""
from flask import current_app, has_app_context
catalog = full_permission_catalog()
grantable = {name for name, _, _ in catalog
if name.endswith('.view') or name.endswith('.read')}
if not has_app_context():
return grantable
pm = current_app.extensions.get('plugin_manager')
if not pm:
return grantable
known = {name for name, _, _ in catalog}
for name, plugin in pm.get_all_plugins().items():
if not pm.registry.is_enabled(name):
continue
try:
blessed = plugin.get_guest_grantable_permissions() or []
except Exception:
if current_app.config.get('DEBUG') or current_app.config.get('TESTING'):
raise
current_app.logger.exception(
'Plugin %s get_guest_grantable_permissions failed', name)
continue
# A plugin may only bless permissions that exist and that it owns the
# naming of; a typo must not silently widen anything.
grantable |= {p for p in blessed if p in known}
return grantable
class Role(BaseModel): class Role(BaseModel):
"""User role model.""" """User role model."""
__tablename__ = 'roles' __tablename__ = 'roles'
@@ -171,6 +218,16 @@ class Role(BaseModel):
def __repr__(self): def __repr__(self):
return f"<Role {self.rolename}>" return f"<Role {self.rolename}>"
# The role a caller with no account is treated as holding.
#
# Guest access used to be a per-feature boolean setting - one for the
# Secure Send page, one for each kiosk, one proposed for guides - which
# meant every new question about what a signed-out visitor may see was
# answered by writing more code. It is a permissions question, and this app
# already administers permissions per role, so a guest is now simply a role
# holding no permissions until somebody grants it some.
GUEST = 'guest'
def haspermission(self, permission_name: str) -> bool: def haspermission(self, permission_name: str) -> bool:
"""Check if role has a specific permission.""" """Check if role has a specific permission."""
# Admin role has all permissions # Admin role has all permissions
@@ -178,6 +235,31 @@ class Role(BaseModel):
return True return True
return any(p.name == permission_name for p in self.permissions) return any(p.name == permission_name for p in self.permissions)
@classmethod
def guest(cls):
"""The guest role, or None on a site that has not been seeded yet."""
return cls.query.filter_by(rolename=cls.GUEST).first()
@classmethod
def seedguest(cls):
"""Create the guest role if it is missing. Returns True if created.
Seeded with NO permissions, which is the same behaviour every site has
today: an unauthenticated request is refused. What a guest may do is a
decision each site makes in the role grid, not one it inherits from an
upgrade.
"""
if cls.query.filter_by(rolename=cls.GUEST).first() is not None:
return False
db.session.add(cls(
rolename=cls.GUEST,
description=('Anyone who is not signed in. Holds nothing by '
'default; grant it a permission to open that up to '
'people with no account.'),
color='#6C757D',
))
return True
def getpermissionnames(self) -> list: def getpermissionnames(self) -> list:
"""Get list of permission names.""" """Get list of permission names."""
if self.rolename == 'admin': if self.rolename == 'admin':

View File

@@ -104,6 +104,23 @@ class BasePlugin(ABC):
""" """
return [] return []
def get_guest_grantable_permissions(self) -> List[str]:
"""Permissions this plugin allows a site to grant to the GUEST role.
A guest is anyone with no account. Any `.view` or `.read` permission is
grantable without asking a plugin - reading is the safe default. This
hook is for the exception: a WRITE that is genuinely meant to be usable
by somebody who never signs in.
Naming one here does not open it. It makes the checkbox available in
the role grid; a site still has to tick it. Return [] (the default) and
none of this plugin's writes can ever be made anonymous.
The bar: could this action be attributed to nobody, forever, and still
be defensible in the audit log? If not, leave it out.
"""
return []
def get_settings_defaults(self) -> List[Dict]: def get_settings_defaults(self) -> List[Dict]:
"""Declare the Setting rows this plugin owns. """Declare the Setting rows this plugin owns.

View File

@@ -10,13 +10,34 @@ or not a separate @jwt_required is also present. The admin role bypasses every
permission check (see User.haspermission), so an admin never needs individual permission check (see User.haspermission), so an admin never needs individual
permissions granted. permissions granted.
THE GUEST ROLE
Somebody with no token is not nobody: they hold the `guest` role. If that role
has been granted the permission a route asks for, the request proceeds; if it
has not - and by default it holds nothing at all - the answer is 401, exactly
as before.
This replaced a growing pile of per-feature booleans (`securesend_allow_guests`,
one per kiosk, one nearly written for guides). Every one of them answered the
same question in its own vocabulary, in its own settings page, checked by its
own hand-written branch inside a route. What a signed-out visitor may see is a
permissions question, and this app already administers permissions per role.
So: a site opens a door by ticking a box in the role grid, and a plugin needs
no code at all to participate. A feature FLAG is still a flag - whether a kiosk
screen exists at this site is not the same question as who may read it.
Usage: Usage:
@assets_bp.route('/<int:asset_id>', methods=['DELETE']) @assets_bp.route('/<int:asset_id>', methods=['DELETE'])
@jwt_required()
@require_permission('assets.delete') @require_permission('assets.delete')
def delete_asset(asset_id): def delete_asset(asset_id):
... ...
A separate @jwt_required() above these is redundant - they verify the request
themselves - and it is actively wrong now: it refuses a request with no token
before the guest role can be consulted, so a permission granted to guests would
appear to do nothing.
""" """
from functools import wraps from functools import wraps
@@ -26,6 +47,45 @@ from flask_jwt_extended import verify_jwt_in_request, current_user, get_jwt
from shopdb.utils.responses import error_response, ErrorCodes from shopdb.utils.responses import error_response, ErrorCodes
def currentuser():
"""The signed-in user, or None.
`current_user` is a LocalProxy: the proxy object exists whether or not
anybody is behind it, so `current_user is None` is False even for a request
with no token. Under a required JWT that never showed, because the request
was refused before reaching here. With optional verification it shows
immediately, as "'NoneType' object has no attribute 'haspermission'".
"""
try:
return current_user._get_current_object()
except Exception:
return None
def guestholds(permission_name: str) -> bool:
"""Whether the guest role has been granted this permission.
Read every time, not cached. Revoking guest access is what somebody does the
moment they realise what they opened up, and it has to bite on the very next
request - a cache keyed to the app context outlives a request whenever one
is pushed around several (which is exactly how the test client behaves, and
how the revoke test caught it). One small indexed query on the rare path is
worth more than that risk.
A site with no guest role yet - an older database, seeded before this
existed - answers no, which is the behaviour it already had.
"""
from shopdb.core.models import Role
try:
role = Role.guest()
except Exception:
# A database that cannot answer must not turn into an open door.
return False
if role is None:
return False
return any(p.name == permission_name for p in role.permissions)
def require_permission(permission_name: str): def require_permission(permission_name: str):
"""Gate a route behind a single permission. Admin role bypasses. """Gate a route behind a single permission. Admin role bypasses.
@@ -36,10 +96,15 @@ def require_permission(permission_name: str):
def decorator(view_func): def decorator(view_func):
@wraps(view_func) @wraps(view_func)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
# verify jwt first so current_user is loaded (idempotent if the # Optional, so a request with no token reaches the guest check
# route also has @jwt_required) # below rather than being refused by the JWT layer before this
verify_jwt_in_request() # decorator can have an opinion. A request that DOES carry a token
if current_user is None: # is still verified, and a bad one still fails here.
verify_jwt_in_request(optional=True)
user = currentuser()
if user is None:
if guestholds(permission_name):
return view_func(*args, **kwargs)
return error_response( return error_response(
ErrorCodes.UNAUTHORIZED, ErrorCodes.UNAUTHORIZED,
'Authentication required', 'Authentication required',
@@ -53,7 +118,7 @@ def require_permission(permission_name: str):
# everything), so the scope list is the real limiter - the # everything), so the scope list is the real limiter - the
# admin bypass is suspended. # admin bypass is suspended.
allowed = (permission_name in patscopes allowed = (permission_name in patscopes
and current_user.haspermission(permission_name)) and user.haspermission(permission_name))
if not allowed: if not allowed:
return error_response( return error_response(
ErrorCodes.FORBIDDEN, ErrorCodes.FORBIDDEN,
@@ -61,7 +126,54 @@ def require_permission(permission_name: str):
http_code=403 http_code=403
) )
return view_func(*args, **kwargs) return view_func(*args, **kwargs)
if not current_user.haspermission(permission_name): if not user.haspermission(permission_name):
return error_response(
ErrorCodes.FORBIDDEN,
'You do not have permission to perform this action',
http_code=403
)
return view_func(*args, **kwargs)
return wrapper
return decorator
def require_any_permission(*permission_names):
"""Gate a route behind ANY ONE of several permissions. Admin bypasses.
For a read that two different rights should reach. GE-Enforce and Slides
are the cases: a GET was gated on the MANAGE permission, because managing
was the only thing anybody did there. Splitting a read permission out would
have locked out every existing manager, so a read now accepts either, and
the read permission is the one a site can hand to a guest.
A scoped PAT must carry one of the names, and its owner must hold that same
one - the intersection rule of require_permission, applied per name.
"""
def decorator(view_func):
@wraps(view_func)
def wrapper(*args, **kwargs):
verify_jwt_in_request(optional=True)
user = currentuser()
if user is None:
if any(guestholds(name) for name in permission_names):
return view_func(*args, **kwargs)
return error_response(
ErrorCodes.UNAUTHORIZED,
'Authentication required',
http_code=401
)
patscopes = get_jwt().get('patscopes')
if patscopes is not None:
allowed = any(name in patscopes and user.haspermission(name)
for name in permission_names)
if not allowed:
return error_response(
ErrorCodes.FORBIDDEN,
'This API token is not scoped for this action',
http_code=403
)
return view_func(*args, **kwargs)
if not any(user.haspermission(name) for name in permission_names):
return error_response( return error_response(
ErrorCodes.FORBIDDEN, ErrorCodes.FORBIDDEN,
'You do not have permission to perform this action', 'You do not have permission to perform this action',
@@ -83,7 +195,8 @@ def require_role(rolename: str):
@wraps(view_func) @wraps(view_func)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
verify_jwt_in_request() verify_jwt_in_request()
if current_user is None: user = currentuser()
if user is None:
return error_response( return error_response(
ErrorCodes.UNAUTHORIZED, ErrorCodes.UNAUTHORIZED,
'Authentication required', 'Authentication required',
@@ -95,7 +208,7 @@ def require_role(rolename: str):
'Scoped API tokens cannot access role-gated endpoints', 'Scoped API tokens cannot access role-gated endpoints',
http_code=403 http_code=403
) )
if not current_user.hasrole(rolename): if not user.hasrole(rolename):
return error_response( return error_response(
ErrorCodes.FORBIDDEN, ErrorCodes.FORBIDDEN,
f'{rolename.capitalize()} access required', f'{rolename.capitalize()} access required',

View File

@@ -0,0 +1,190 @@
"""The guest role: what somebody with no account may do.
Guest access used to be a per-feature boolean - one for Secure Send, one per
kiosk, one nearly written for guides - each with its own settings page and its
own hand-written branch inside a route. This replaced all of that with a role,
so the question is answered where every other permission question is answered.
The contract these tests hold:
- a guest holds nothing by default, so an upgrade opens no door
- granting the guest role a permission is what opens one
- revoking it closes the door on the next request, not the next restart
- a guest can never be granted a write unless its owner declared it safe
- a signed-in caller is unaffected by any of it
"""
import pytest
from shopdb.core.models import Permission, Role
@pytest.fixture
def guestrole(db):
"""The seeded guest role, holding nothing."""
Permission.seed()
Role.seedguest()
db.session.commit()
return Role.guest()
def grant(db, role, *names):
role.permissions = Permission.query.filter(Permission.name.in_(names)).all()
db.session.commit()
# ---------------------------------------------------------------------------
# The default: nothing
# ---------------------------------------------------------------------------
def test_a_guest_holds_nothing_by_default(guestrole):
"""An upgrade must not open a door a site never asked to open."""
assert guestrole.permissions == []
def test_a_guest_is_refused_a_read_nobody_granted(client, guestrole):
response = client.get('/api/auditlogs')
assert response.status_code == 401
def test_a_guest_is_refused_a_write(client, guestrole):
response = client.post('/api/assets', json={'assetnumber': 'GUEST-1'})
assert response.status_code == 401
# ---------------------------------------------------------------------------
# Granting, and taking it back
# ---------------------------------------------------------------------------
def test_granting_the_guest_role_a_view_opens_that_read(client, db, guestrole):
grant(db, guestrole, 'audit.view')
response = client.get('/api/auditlogs')
assert response.status_code == 200
def test_a_grant_does_not_leak_into_neighbouring_permissions(client, db, guestrole):
"""audit.view is not apitokens.view. The role holds exactly what it was
given."""
grant(db, guestrole, 'audit.view')
assert client.get('/api/apitokens').status_code == 401
def test_a_write_stays_shut_even_when_a_read_is_open(client, db, guestrole):
grant(db, guestrole, 'audit.view')
assert client.post('/api/assets', json={'assetnumber': 'X'}).status_code == 401
def test_revoking_closes_the_door_on_the_next_request(client, db, guestrole):
"""Not on the next restart. Revoking is what somebody does the moment they
realise what they opened up, and it has to take effect then."""
grant(db, guestrole, 'audit.view')
assert client.get('/api/auditlogs').status_code == 200
guestrole.permissions = []
db.session.commit()
assert client.get('/api/auditlogs').status_code == 401
def test_a_site_with_no_guest_role_behaves_as_it_always_did(client, db):
"""An older database, seeded before any of this existed."""
role = Role.guest()
if role is not None:
db.session.delete(role)
db.session.commit()
assert client.get('/api/auditlogs').status_code == 401
# ---------------------------------------------------------------------------
# The guardrail
# ---------------------------------------------------------------------------
def test_a_view_permission_is_grantable(app):
from shopdb.core.models import guest_grantable_permissions
with app.app_context():
grantable = guest_grantable_permissions()
assert 'assets.view' in grantable
assert 'reports.view' in grantable
def test_a_write_permission_is_not_grantable(app):
from shopdb.core.models import guest_grantable_permissions
with app.app_context():
grantable = guest_grantable_permissions()
for name in ('assets.delete', 'assets.create', 'users.create',
'settings.edit'):
assert name not in grantable, name
def test_the_api_refuses_to_grant_a_guest_a_write(client, db, auth_headers,
guestrole):
"""Refused at the door rather than warned about: a checkbox that quietly
makes deleting an asset anonymous is not a warning anybody reads twice."""
response = client.put('/api/users/roles/{}'.format(guestrole.roleid),
headers=auth_headers,
json={'permissions': ['assets.delete']})
assert response.status_code == 400
assert 'assets.delete' in response.get_json()['data']['error']['message']
assert guestrole.permissions == []
def test_the_api_allows_granting_a_guest_a_view(client, db, auth_headers,
guestrole):
response = client.put('/api/users/roles/{}'.format(guestrole.roleid),
headers=auth_headers,
json={'permissions': ['audit.view']})
assert response.status_code == 200
assert [p.name for p in guestrole.permissions] == ['audit.view']
def test_the_guest_role_cannot_be_deleted(client, auth_headers, guestrole):
"""Deleting it does not close the door, it removes the only place the door
is described."""
response = client.delete('/api/users/roles/{}'.format(guestrole.roleid))
assert response.status_code in (401, 403)
response = client.delete('/api/users/roles/{}'.format(guestrole.roleid),
headers=auth_headers)
assert response.status_code == 400
assert Role.guest() is not None
def test_the_role_list_says_what_a_guest_may_hold(client, auth_headers,
guestrole):
"""So the grid can grey the rest out rather than letting somebody tick a
box the API will refuse."""
rows = client.get('/api/users/roles', headers=auth_headers).get_json()['data']
guest = next(r for r in rows if r['rolename'] == 'guest')
assert guest['isguest'] is True
assert 'assets.view' in guest['grantable']
assert 'assets.delete' not in guest['grantable']
other = next((r for r in rows if r['rolename'] != 'guest'), None)
if other is not None:
assert other['grantable'] is None, 'only the guest role is bounded'
# ---------------------------------------------------------------------------
# Signed-in callers are unaffected
# ---------------------------------------------------------------------------
def test_a_member_still_needs_their_own_permission(client, member_headers,
db, guestrole):
"""A grant to guests is not a grant to everybody: a signed-in member
without the permission is still refused, with 403 rather than 401 because
signing in would not change the answer."""
grant(db, guestrole, 'audit.view')
response = client.get('/api/auditlogs', headers=member_headers)
assert response.status_code == 403
def test_an_admin_is_unaffected(client, auth_headers, guestrole):
assert client.get('/api/auditlogs', headers=auth_headers).status_code == 200
def test_a_bad_token_is_still_refused(client, db, guestrole):
"""Optional verification tolerates a MISSING token, not a broken one - a
forged token must not be quietly downgraded to guest access."""
grant(db, guestrole, 'audit.view')
response = client.get('/api/auditlogs',
headers={'Authorization': 'Bearer not.a.token'})
assert response.status_code == 422