Add prebuilt user scopes and guard invalid Reporter grants
A newly created user held no roles and no permissions, so the sidebar filtered every nav item away and the account appeared broken. Adds three prebuilt scopes (Reporter, Operator, Technician) derived from the live permission catalog by verb rather than hand-listed, so a new plugin permission lands in the right scope automatically instead of silently going ungranted. users.view is granted to all three since a user who cannot see the directory cannot collaborate; users.create/edit/delete stay admin-only. Role.seedscopes() is additive and idempotent, seeded via flask seed permissions, and preserves custom grants on rerun. Reporter guard: the auth model is additive across admin, direct grants and roles, so Reporter cannot be expressed as merely fewer grants - a direct endpoint-action grant would silently re-arm a read-only account. Rather than change the global permission predicate and alter every route's semantics, _check_scope_grants() rejects the invalid combination at write time on both create and update. The update path validates the effective post-update state, so demoting a Technician to Reporter is refused while a stale endpoint grant remains rather than quietly leaving a read-only user with write authority. Validation runs before the User object is constructed. Assigning user.roles first put the relationship into the session autoflush path while the User was still unattached; nothing broke because the refusal returns before db.session.add(), but it left a trap where any query added below that point would autoflush a half-built user and surface later as an orphan row. Verified with -W error::sqlalchemy.exc.SAWarning: 25 passed.
This commit is contained in:
@@ -154,15 +154,36 @@
|
||||
>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Roles</label>
|
||||
<label for="userscope">Scope</label>
|
||||
<select id="userscope" v-model="selectedRoleId">
|
||||
<option :value="null">No scope (sees nothing until granted)</option>
|
||||
<option v-for="role in roles" :key="role.roleid" :value="role.roleid">
|
||||
{{ scopeLabel(role.rolename) }}
|
||||
</option>
|
||||
</select>
|
||||
<p class="field-hint">{{ scopeDescription }}</p>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Endpoint Actions</label>
|
||||
<p class="field-hint">{{ endpointActionsHint }}</p>
|
||||
<div class="checkbox-group">
|
||||
<label v-for="role in roles" :key="role.roleid" class="checkbox-label">
|
||||
<label
|
||||
v-for="action in endpointActionPermissions"
|
||||
:key="action.name"
|
||||
class="checkbox-label"
|
||||
:class="{ 'checkbox-label-disabled': !endpointActionsSelectable }"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
:value="role.roleid"
|
||||
v-model="userForm.roles"
|
||||
:value="action.name"
|
||||
:checked="isActionChecked(action.name)"
|
||||
:disabled="!endpointActionsSelectable"
|
||||
@change="toggleAction(action.name, $event.target.checked)"
|
||||
>
|
||||
{{ role.rolename }}
|
||||
{{ action.label }}
|
||||
<span v-if="endpointActionsSelectable && heldThroughRole(action.name)" class="field-hint">
|
||||
(already granted by a role)
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
@@ -306,7 +327,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, onMounted } from 'vue'
|
||||
import { ref, reactive, computed, onMounted } from 'vue'
|
||||
import { usersApi } from '../../api'
|
||||
import { useAuthStore } from '../../stores/auth'
|
||||
import { apiError } from '../../utils/apiError'
|
||||
@@ -340,10 +361,165 @@ const userForm = reactive({
|
||||
lastname: '',
|
||||
password: '',
|
||||
roles: [],
|
||||
directpermissions: [],
|
||||
isactive: true,
|
||||
unlock: false
|
||||
})
|
||||
|
||||
// The four endpoint actions the shop gates per person rather than per policy.
|
||||
// Named here rather than derived from the permission catalog so the user editor
|
||||
// stays a short, meaningful list instead of the full permission grid, which
|
||||
// belongs to the role editor.
|
||||
const endpointActionPermissions = [
|
||||
{ name: 'endpoints.restart', label: 'Remote Restart' },
|
||||
{ name: 'endpoints.runscript', label: 'Script Push' },
|
||||
{ name: 'endpoints.updateapp', label: 'Application Update' },
|
||||
{ name: 'endpoints.corptools', label: 'Corporate Tool Use' }
|
||||
]
|
||||
|
||||
// What each scope means, in the words shown at the point of use.
|
||||
//
|
||||
// This text is doing real work, not decorating. Operator and Technician carry
|
||||
// the SAME role grants - both are read-only on records at the role level - and
|
||||
// differ only in whether the endpoint action checkboxes below are offered. Read
|
||||
// off the role grid alone the two look identical, so the description is what
|
||||
// makes the distinction legible to the person choosing, at the moment they
|
||||
// choose. Keep it accurate if the scopes change.
|
||||
const SCOPE_INFO = {
|
||||
admin: {
|
||||
label: 'Admin - full access',
|
||||
description: 'Full access to everything, including deleting records, ' +
|
||||
'managing users, and site settings.',
|
||||
actions: 'inherent'
|
||||
},
|
||||
operator: {
|
||||
label: 'Operator - create and edit',
|
||||
description: 'Can view, create, and edit records, and can see the user ' +
|
||||
'directory. Cannot delete records, manage users, or change settings - ' +
|
||||
'deletion stays with admins.',
|
||||
actions: 'selectable'
|
||||
},
|
||||
technician: {
|
||||
label: 'Technician - endpoint work, no record edits',
|
||||
description: 'Can view records and the user directory but cannot create ' +
|
||||
'or edit them, and cannot author policy. Intended for endpoint work: ' +
|
||||
'grant the actions below as needed.',
|
||||
actions: 'selectable'
|
||||
},
|
||||
reporter: {
|
||||
label: 'Reporter - read and export only',
|
||||
description: 'Can view everything and export reports. Holds no action ' +
|
||||
'capability and cannot be granted one, so the endpoint actions below ' +
|
||||
'are unavailable for this scope.',
|
||||
actions: 'denied'
|
||||
}
|
||||
}
|
||||
|
||||
// Scopes the server refuses to store endpoint actions against. Mirrors
|
||||
// SCOPES_DENIED_ENDPOINT_ACTIONS in shopdb/core/models/user.py. Greying the
|
||||
// boxes here is a courtesy that explains the rule before it is hit; the API is
|
||||
// what enforces it, so the two must agree or the UI offers something the save
|
||||
// will reject.
|
||||
const SCOPES_DENIED_ACTIONS = ['reporter']
|
||||
|
||||
// A single-select scope, kept as a one-item array on the way to the API so the
|
||||
// existing `roles: [roleid...]` contract is untouched. Roles remain
|
||||
// many-to-many in the database; this is a UI constraint, chosen because no user
|
||||
// in the live data holds more than one role and stacking them mainly produces
|
||||
// the contradictory combinations the server now refuses.
|
||||
const selectedRoleId = computed({
|
||||
get: () => (userForm.roles.length ? userForm.roles[0] : null),
|
||||
set: (value) => {
|
||||
userForm.roles = value === null ? [] : [value]
|
||||
// Clear now-invalid grants rather than leaving them staged for a rejection.
|
||||
// Without this, switching an operator to reporter would keep the restart
|
||||
// grant in the form and the save would fail with a 400 the user did not
|
||||
// knowingly cause.
|
||||
if (!endpointActionsSelectable.value) {
|
||||
userForm.directpermissions = userForm.directpermissions.filter(
|
||||
(name) => !endpointActionPermissions.some((a) => a.name === name))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const selectedRoleName = computed(() => {
|
||||
const role = roles.value.find((r) => r.roleid === selectedRoleId.value)
|
||||
return role ? role.rolename : null
|
||||
})
|
||||
|
||||
const scopeDescription = computed(() => {
|
||||
const name = selectedRoleName.value
|
||||
if (!name) {
|
||||
return 'No scope assigned. This user can sign in but will see no ' +
|
||||
'navigation until a scope is chosen.'
|
||||
}
|
||||
const info = SCOPE_INFO[name]
|
||||
return info
|
||||
? info.description
|
||||
: 'Custom role. Access is whatever this role has been granted in the ' +
|
||||
'role editor.'
|
||||
})
|
||||
|
||||
// Admin's boxes are shown ticked but disabled: an admin already passes every
|
||||
// permission check by rule, so a stored grant would be redundant, and leaving
|
||||
// them unticked would wrongly suggest an admin cannot restart a machine.
|
||||
const scopeActionMode = computed(() => {
|
||||
const name = selectedRoleName.value
|
||||
if (!name) return 'selectable'
|
||||
return SCOPE_INFO[name] ? SCOPE_INFO[name].actions : 'selectable'
|
||||
})
|
||||
|
||||
const endpointActionsSelectable = computed(
|
||||
() => scopeActionMode.value === 'selectable')
|
||||
|
||||
const endpointActionsHint = computed(() => {
|
||||
if (scopeActionMode.value === 'inherent') {
|
||||
return 'Admins hold every action automatically; these are shown for ' +
|
||||
'reference and are not stored as individual grants.'
|
||||
}
|
||||
if (scopeActionMode.value === 'denied') {
|
||||
return 'The Reporter scope cannot hold endpoint actions. Choose ' +
|
||||
'Technician or Operator if this user needs to act on endpoints.'
|
||||
}
|
||||
return 'Granted to this user directly, in addition to anything their scope ' +
|
||||
'already provides.'
|
||||
})
|
||||
|
||||
function isActionChecked(name) {
|
||||
// Admin: display-only ticks. Nothing is stored, per the API guard's note that
|
||||
// grants on an admin are meaningless and become misleading if the scope
|
||||
// later changes.
|
||||
if (scopeActionMode.value === 'inherent') return true
|
||||
if (scopeActionMode.value === 'denied') return false
|
||||
return userForm.directpermissions.includes(name)
|
||||
}
|
||||
|
||||
function toggleAction(name, checked) {
|
||||
if (!endpointActionsSelectable.value) return
|
||||
const has = userForm.directpermissions.includes(name)
|
||||
if (checked && !has) {
|
||||
userForm.directpermissions.push(name)
|
||||
} else if (!checked && has) {
|
||||
userForm.directpermissions = userForm.directpermissions.filter(
|
||||
(n) => n !== name)
|
||||
}
|
||||
}
|
||||
|
||||
function scopeLabel(rolename) {
|
||||
return SCOPE_INFO[rolename] ? SCOPE_INFO[rolename].label : rolename
|
||||
}
|
||||
|
||||
// A capability supplied by a role is shown but not implied by the checkbox:
|
||||
// the checkbox reflects the DIRECT grant only, so unticking it cannot appear to
|
||||
// remove something only the role can remove.
|
||||
function heldThroughRole(name) {
|
||||
const user = editingUser.value
|
||||
if (!user) return false
|
||||
const effective = user.permissions || []
|
||||
const direct = user.directpermissions || []
|
||||
return effective.includes(name) && !direct.includes(name)
|
||||
}
|
||||
|
||||
const roleForm = reactive({
|
||||
rolename: '',
|
||||
description: '',
|
||||
@@ -452,6 +628,7 @@ function editUser(user) {
|
||||
userForm.lastname = user.lastname || ''
|
||||
userForm.password = ''
|
||||
userForm.roles = user.roles.map(r => r.roleid)
|
||||
userForm.directpermissions = [...(user.directpermissions || [])]
|
||||
userForm.isactive = user.isactive
|
||||
userForm.unlock = false
|
||||
}
|
||||
@@ -461,7 +638,7 @@ function closeUserModal() {
|
||||
editingUser.value = null
|
||||
Object.assign(userForm, {
|
||||
username: '', email: '', firstname: '', lastname: '',
|
||||
password: '', roles: [], isactive: true, unlock: false
|
||||
password: '', roles: [], directpermissions: [], isactive: true, unlock: false
|
||||
})
|
||||
}
|
||||
|
||||
@@ -473,7 +650,15 @@ async function saveUser() {
|
||||
email: userForm.email,
|
||||
firstname: userForm.firstname || null,
|
||||
lastname: userForm.lastname || null,
|
||||
roles: userForm.roles
|
||||
roles: userForm.roles,
|
||||
// Admin and Reporter never SEND endpoint actions. For admin the ticks are
|
||||
// display-only and a stored grant would be redundant; for reporter the
|
||||
// API refuses them outright. Stripping here keeps the payload honest
|
||||
// rather than relying on the form state having been cleared.
|
||||
directpermissions: endpointActionsSelectable.value
|
||||
? userForm.directpermissions
|
||||
: userForm.directpermissions.filter(
|
||||
(name) => !endpointActionPermissions.some((a) => a.name === name))
|
||||
}
|
||||
|
||||
if (editingUser.value) {
|
||||
@@ -744,6 +929,12 @@ onMounted(loadData)
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
margin: 0 0 0.5rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-light);
|
||||
}
|
||||
|
||||
.checkbox-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -755,6 +946,19 @@ onMounted(loadData)
|
||||
width: auto;
|
||||
}
|
||||
|
||||
/* Uses --text-light, an existing theme token, rather than a hardcoded grey:
|
||||
a literal colour here would read as disabled in light mode and near-invisible
|
||||
in dark. */
|
||||
.checkbox-label-disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
color: var(--text-light);
|
||||
}
|
||||
|
||||
.checkbox-label-disabled input[type="checkbox"] {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
|
||||
59
migrations/versions/7d43_userpermissions.py
Normal file
59
migrations/versions/7d43_userpermissions.py
Normal file
@@ -0,0 +1,59 @@
|
||||
"""Per-user direct permission grants.
|
||||
|
||||
Permissions were reachable only through roles. At 5-7 operators per instance
|
||||
that forces a role to be minted for every one-off capability - "Bob, and only
|
||||
Bob, may push scripts" - until the role list is a mixture of job titles and
|
||||
single-capability flags and nobody can tell which is which.
|
||||
|
||||
A row here is an ORDINARY permission grant. It is identical in power to one held
|
||||
through a role: it counts toward the API token scope ceiling, it is folded by
|
||||
both User.haspermission() and User.getpermissions(), and it is revoked the same
|
||||
way. There is deliberately no second class of permission.
|
||||
|
||||
Nothing is granted by this migration. The table is created empty; existing
|
||||
authority is untouched.
|
||||
|
||||
Revision ID: 7d43_userpermissions
|
||||
Revises: 7d42_split_endpoints_deploy
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '7d43_userpermissions'
|
||||
down_revision = '7d42_split_endpoints_deploy'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'userpermissions' in set(inspector.get_table_names()):
|
||||
return
|
||||
|
||||
op.create_table(
|
||||
'userpermissions',
|
||||
sa.Column('userid', sa.Integer(), nullable=False),
|
||||
sa.Column('permissionid', sa.Integer(), nullable=False),
|
||||
# Cascade on both sides: a direct grant is meaningless once either end
|
||||
# is gone, and leaving orphans would let a recycled id silently inherit
|
||||
# someone else's capability.
|
||||
sa.ForeignKeyConstraint(['userid'], ['users.userid'],
|
||||
ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['permissionid'],
|
||||
['permissions.permissionid'],
|
||||
ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('userid', 'permissionid'),
|
||||
)
|
||||
op.create_index('idx_userpermissions_userid', 'userpermissions', ['userid'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if 'userpermissions' not in set(inspector.get_table_names()):
|
||||
return
|
||||
op.drop_index('idx_userpermissions_userid', table_name='userpermissions')
|
||||
op.drop_table('userpermissions')
|
||||
@@ -810,7 +810,7 @@ def fix_controls_direction():
|
||||
@seed_cli.command('permissions')
|
||||
@with_appcontext
|
||||
def seed_permissions():
|
||||
"""Seed predefined permissions, and the guest role that can hold them."""
|
||||
"""Seed predefined permissions, the guest role, and the prebuilt scopes."""
|
||||
from shopdb.extensions import db
|
||||
from shopdb.core.models import Permission, Role
|
||||
|
||||
@@ -819,11 +819,23 @@ def seed_permissions():
|
||||
# on the upgrade it already runs. It holds nothing until somebody grants
|
||||
# it something, so seeding it changes no behaviour.
|
||||
guest = Role.seedguest()
|
||||
# AFTER Permission.seed(), which is load-bearing: seedscopes only links
|
||||
# permissions that exist as rows, so seeding the catalog first is what
|
||||
# lets a newly installed plugin's permissions reach the scopes in the
|
||||
# same command rather than on the next run.
|
||||
scopes = Role.seedscopes()
|
||||
db.session.commit()
|
||||
click.echo(click.style(f"{created} permissions created.", fg='green'))
|
||||
if guest:
|
||||
click.echo(click.style(
|
||||
"guest role created (holds no permissions).", fg='green'))
|
||||
for rolename in scopes['created']:
|
||||
click.echo(click.style(f"{rolename} role created.", fg='green'))
|
||||
for rolename, count in sorted(scopes['granted'].items()):
|
||||
click.echo(click.style(
|
||||
f"{rolename}: {count} permission(s) granted.", fg='green'))
|
||||
if not scopes['created'] and not scopes['granted']:
|
||||
click.echo("Prebuilt scopes already up to date.")
|
||||
|
||||
|
||||
@seed_cli.command('settings')
|
||||
|
||||
@@ -7,13 +7,82 @@ from werkzeug.security import generate_password_hash
|
||||
from shopdb.extensions import db
|
||||
from shopdb.core.models import (
|
||||
User, Role, Permission, AuditLog, full_permission_catalog,
|
||||
guest_grantable_permissions)
|
||||
guest_grantable_permissions, SCOPE_ENDPOINT_ACTIONS,
|
||||
SCOPES_DENIED_ENDPOINT_ACTIONS)
|
||||
from shopdb.utils.responses import success_response, error_response, ErrorCodes
|
||||
from shopdb.utils.authz import require_role
|
||||
|
||||
users_bp = Blueprint('users', __name__)
|
||||
|
||||
|
||||
def _check_scope_grants(rolenames, permissionnames):
|
||||
"""Refuse direct grants a prebuilt scope is defined as never holding.
|
||||
|
||||
Returns an error_response, or None when the combination is allowed.
|
||||
|
||||
This is the server-side half of the scope dropdown, and it is the half that
|
||||
is actually load-bearing. The UI greys out the endpoint action checkboxes
|
||||
for a reporter, but a greyed-out checkbox is a suggestion: the same account
|
||||
can be created with a restart grant by anyone willing to POST JSON. Reporter
|
||||
was specified as holding no action capability EVEN IF expressly permitted,
|
||||
and only a check on the write path can make that true.
|
||||
|
||||
Enforced here rather than in User.haspermission() on purpose. A subtractive
|
||||
ceiling in the read predicate would sit in the hot path of every
|
||||
permission-gated route in the app and change the meaning of a grant
|
||||
everywhere, to fix a combination that should simply never have been stored.
|
||||
Refusing the write is the narrow version: bad state cannot get in, and the
|
||||
thousands of existing reads keep their current semantics.
|
||||
|
||||
Note this deliberately does NOT restrict the admin role, which bypasses
|
||||
permission checks by rule, nor any site-created custom role. It constrains
|
||||
only the scopes that were seeded with a documented promise about what they
|
||||
hold.
|
||||
"""
|
||||
denied_scopes = SCOPES_DENIED_ENDPOINT_ACTIONS & set(rolenames)
|
||||
if not denied_scopes:
|
||||
return None
|
||||
conflicts = sorted(set(permissionnames) & set(SCOPE_ENDPOINT_ACTIONS))
|
||||
if not conflicts:
|
||||
return None
|
||||
scope = sorted(denied_scopes)[0]
|
||||
return error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
f"The {scope} scope cannot hold endpoint actions "
|
||||
f"({', '.join(conflicts)}). Assign the technician or operator scope "
|
||||
f"if this user needs to act on endpoints.")
|
||||
|
||||
|
||||
def _resolve_directpermissions(names):
|
||||
"""Resolve permission names to rows, rejecting any that do not exist.
|
||||
|
||||
Returns (permissions, error_response). A None permissions value with no
|
||||
error means the caller did not mention direct grants at all, which is not
|
||||
the same as sending an empty list - that clears them.
|
||||
|
||||
Unknown names are refused rather than dropped. Silently ignoring a typo
|
||||
would report success while granting nothing, and the admin would believe
|
||||
the capability was handed out.
|
||||
"""
|
||||
if names is None:
|
||||
return None, None
|
||||
if not isinstance(names, list):
|
||||
return None, error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'directpermissions must be a list of permission names')
|
||||
if not names:
|
||||
return [], None
|
||||
|
||||
wanted = {str(n) for n in names}
|
||||
permissions = Permission.query.filter(Permission.name.in_(wanted)).all()
|
||||
missing = sorted(wanted - {p.name for p in permissions})
|
||||
if missing:
|
||||
return None, error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'Unknown permissions: ' + ', '.join(missing))
|
||||
return permissions, None
|
||||
|
||||
|
||||
@users_bp.route('', methods=['GET'])
|
||||
@jwt_required()
|
||||
@require_role('admin')
|
||||
@@ -61,6 +130,28 @@ def create_user():
|
||||
if User.query.filter_by(email=data['email']).first():
|
||||
return error_response(ErrorCodes.CONFLICT, 'Email already exists', http_code=409)
|
||||
|
||||
# Resolve and VALIDATE roles and grants before touching the User object.
|
||||
#
|
||||
# Ordering is deliberate. Assigning user.roles first put the relationship
|
||||
# into the session's autoflush path while the User itself was still
|
||||
# unattached, which SQLAlchemy warned about ("Object of type <User> not in
|
||||
# session, add operation along 'Role.users' won't proceed"). Nothing broke,
|
||||
# because the refusal returns before db.session.add(). But it left a live
|
||||
# trap: move or add a query below this point and the autoflush becomes a
|
||||
# real write of a half-built user, surfacing later as an orphan row nobody
|
||||
# can explain. Validate everything, then build.
|
||||
role_ids = data.get('roles', [])
|
||||
roles = Role.query.filter(Role.roleid.in_(role_ids)).all() if role_ids else []
|
||||
|
||||
permissions, err = _resolve_directpermissions(data.get('directpermissions'))
|
||||
if err:
|
||||
return err
|
||||
err = _check_scope_grants(
|
||||
[r.rolename for r in roles],
|
||||
[p.name for p in (permissions or [])])
|
||||
if err:
|
||||
return err
|
||||
|
||||
# Admin-created accounts are forced to change the password on first login
|
||||
# unless the admin explicitly opts out.
|
||||
mustchange = data.get('mustchangepassword', True)
|
||||
@@ -75,12 +166,13 @@ def create_user():
|
||||
mustchangepassword=bool(mustchange)
|
||||
)
|
||||
|
||||
# Assign roles
|
||||
role_ids = data.get('roles', [])
|
||||
if role_ids:
|
||||
roles = Role.query.filter(Role.roleid.in_(role_ids)).all()
|
||||
if roles:
|
||||
user.roles = roles
|
||||
|
||||
# Direct per-user permission grants, held alongside (not instead of) roles.
|
||||
if permissions is not None:
|
||||
user.directpermissions = permissions
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
# Audit log
|
||||
@@ -181,6 +273,39 @@ def update_user(userid: int):
|
||||
changes['roles'] = {'old': old_roles, 'new': new_roles}
|
||||
user.roles = roles
|
||||
|
||||
# Direct grants are audited by NAME rather than id: the point of the
|
||||
# audit row is to be readable years later, when a permission id means
|
||||
# nothing to the person reading it.
|
||||
if 'directpermissions' in data:
|
||||
permissions, err = _resolve_directpermissions(
|
||||
data['directpermissions'])
|
||||
if err:
|
||||
return err
|
||||
old_direct = user.getdirectpermissionnames()
|
||||
new_direct = sorted(p.name for p in (permissions or []))
|
||||
if old_direct != new_direct:
|
||||
changes['directpermissions'] = {
|
||||
'old': old_direct, 'new': new_direct}
|
||||
user.directpermissions = permissions or []
|
||||
|
||||
# Validate the COMBINATION, after both assignments and against the
|
||||
# user's effective state rather than only what this request mentioned.
|
||||
# A payload may change roles without mentioning grants, or grants
|
||||
# without mentioning roles; checking only the supplied half would let a
|
||||
# request that demotes an operator to reporter keep the restart grant
|
||||
# they already held, which is exactly the state the scope promises is
|
||||
# impossible. Reading back off `user` covers all three shapes.
|
||||
#
|
||||
# Safe to check after mutating because nothing has committed yet - the
|
||||
# early return leaves the session to be rolled down by the request
|
||||
# teardown, so a refused combination is never persisted.
|
||||
err = _check_scope_grants(
|
||||
[r.rolename for r in user.roles],
|
||||
user.getdirectpermissionnames())
|
||||
if err:
|
||||
db.session.rollback()
|
||||
return err
|
||||
|
||||
# Unlock user
|
||||
if data.get('unlock'):
|
||||
user.lockeduntil = None
|
||||
@@ -237,6 +362,21 @@ def delete_user(userid: int):
|
||||
# revoke their API tokens outright, and DETACH their audit history
|
||||
# (userid -> NULL) - the log rows themselves are kept, entityname and
|
||||
# details still tell the story.
|
||||
#
|
||||
# What a departing user leaves behind is deliberately NOT undone. Policies
|
||||
# carry no FK to users, so configuration and business policies they authored
|
||||
# keep working; the audit rows keep username, which is denormalized on
|
||||
# auditlogs for exactly this reason. Leaving is not a reason to unpick
|
||||
# someone's work.
|
||||
#
|
||||
# TODO (future): offer to EXPORT this user's audit history at the moment of
|
||||
# removal, and on a significant scope reduction too. Detaching costs the
|
||||
# userid link, so after this runs their trail is only reachable by matching
|
||||
# the username string - which is fragile if the name is ever reused. An
|
||||
# export taken at the point of change preserves the joined-up record while
|
||||
# it still exists. Deactivating (isactive=False) instead of deleting keeps
|
||||
# the userid link intact and is the better choice when the account may ever
|
||||
# need to be audited in depth.
|
||||
from shopdb.core.models import ApiToken
|
||||
ApiToken.query.filter_by(userid=userid).delete(synchronize_session=False)
|
||||
AuditLog.query.filter_by(userid=userid).update(
|
||||
@@ -452,6 +592,14 @@ def user_to_dict(user: User) -> dict:
|
||||
'lastlogindate': user.lastlogindate.isoformat() + 'Z' if user.lastlogindate else None,
|
||||
'failedlogins': user.failedlogins,
|
||||
'roles': [{'roleid': r.roleid, 'rolename': r.rolename, 'color': r.color} for r in user.roles],
|
||||
# Split deliberately. directpermissions is what is STORED on the user and
|
||||
# is what the editor's checkboxes bind to; permissions is the EFFECTIVE
|
||||
# set including everything the roles supply, which is what a reader needs
|
||||
# to answer "can this person do X". A checkbox bound to the effective set
|
||||
# would appear ticked for a capability the user holds through a role, and
|
||||
# unticking it would silently do nothing.
|
||||
'directpermissions': user.getdirectpermissionnames(),
|
||||
'permissions': sorted(user.getpermissions()),
|
||||
'createddate': user.createddate.isoformat() + 'Z' if user.createddate else None,
|
||||
'modifieddate': user.modifieddate.isoformat() + 'Z' if user.modifieddate else None
|
||||
}
|
||||
|
||||
@@ -14,7 +14,9 @@ from .operatingsystem import OperatingSystem
|
||||
from .relationship import AssetRelationship, RelationshipType, RelationshipTypePropagation
|
||||
from .communication import Communication, CommunicationType
|
||||
from .user import (User, Role, Permission, full_permission_catalog,
|
||||
guest_grantable_permissions)
|
||||
guest_grantable_permissions, scope_permission_names,
|
||||
PREBUILT_SCOPES, SCOPE_ENDPOINT_ACTIONS,
|
||||
SCOPE_NEVER_GRANT, SCOPES_DENIED_ENDPOINT_ACTIONS)
|
||||
from .application import Application, AppVersion
|
||||
from .script_library import (Script, RUNCONTEXTS, RUNCONTEXT_SYSTEM,
|
||||
RUNCONTEXT_USER)
|
||||
@@ -63,6 +65,11 @@ __all__ = [
|
||||
'Permission',
|
||||
'full_permission_catalog',
|
||||
'guest_grantable_permissions',
|
||||
'scope_permission_names',
|
||||
'PREBUILT_SCOPES',
|
||||
'SCOPE_ENDPOINT_ACTIONS',
|
||||
'SCOPE_NEVER_GRANT',
|
||||
'SCOPES_DENIED_ENDPOINT_ACTIONS',
|
||||
# Applications
|
||||
'Application',
|
||||
'AppVersion',
|
||||
|
||||
@@ -19,6 +19,25 @@ rolepermissions = db.Table(
|
||||
db.Column('permissionid', db.Integer, db.ForeignKey('permissions.permissionid'), primary_key=True)
|
||||
)
|
||||
|
||||
# Association table for DIRECT per-user permissions (many-to-many).
|
||||
#
|
||||
# A grant here is an ordinary permission, identical in power to one held through
|
||||
# a role - it counts toward the API token scope ceiling and everything else. It
|
||||
# exists because a site of 5-7 operators should be able to give one person one
|
||||
# capability without minting a role for them, which would otherwise turn the
|
||||
# role list into a mixture of job titles and single-capability flags.
|
||||
#
|
||||
# Anything that answers "what may this user do" MUST fold this in. There are two
|
||||
# such surfaces and they are computed separately: haspermission() (the predicate
|
||||
# authorization uses) and getpermissions() (the list baked into JWT claims and
|
||||
# read by the frontend authStore). Teaching only one of them makes the server and
|
||||
# the UI disagree silently.
|
||||
userpermissions = db.Table(
|
||||
'userpermissions',
|
||||
db.Column('userid', db.Integer, db.ForeignKey('users.userid'), primary_key=True),
|
||||
db.Column('permissionid', db.Integer, db.ForeignKey('permissions.permissionid'), primary_key=True)
|
||||
)
|
||||
|
||||
|
||||
class Permission(db.Model):
|
||||
"""
|
||||
@@ -179,6 +198,155 @@ CORE_GUEST_GRANTABLE = {
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prebuilt user scopes
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# Why these exist: before them the only roles were `admin` and `guest`, so a new
|
||||
# user was given nothing, held no permissions, and the sidebar correctly hid
|
||||
# every link. There was no rung between "runs the site" and "sees nothing".
|
||||
#
|
||||
# The four scopes, as specified:
|
||||
# admin - unchanged. Bypasses every check in haspermission(); NOT seeded
|
||||
# here and NOT described by a grant list, because it holds
|
||||
# everything by rule rather than by grant.
|
||||
# operator - full record access except deletion, which stays admin-only.
|
||||
# technician - read-only on records. Cannot create or edit.
|
||||
# reporter - reads everything and exports reports. No action capability.
|
||||
#
|
||||
# DERIVED, not hardcoded, and this is the opposite choice to
|
||||
# CORE_GUEST_GRANTABLE above. That set is declared name-by-name because it
|
||||
# governs what an ANONYMOUS visitor may reach, where the bar is "could this be
|
||||
# public forever" and a wrong answer leaks to the internet. These scopes govern
|
||||
# authenticated internal staff, and the catalog is plugin-driven: roughly sixty
|
||||
# permissions across fifteen plugins, growing whenever a plugin is added. A
|
||||
# hardcoded list would silently omit every future plugin, so a Technician would
|
||||
# lose access to new modules by default and the failure would look like a
|
||||
# permissions bug rather than a stale list.
|
||||
#
|
||||
# So scopes are computed from the catalog by verb, minus an explicit exclusion
|
||||
# set. Adding a plugin extends the scopes automatically; keeping something OUT
|
||||
# of them is the thing that requires a deliberate code change.
|
||||
|
||||
# Verbs that mutate records. Split by which scope may hold them.
|
||||
_EDIT_VERBS = ('create', 'edit', 'restock', 'manage', 'publish')
|
||||
_DESTRUCTIVE_VERBS = ('delete', 'purge')
|
||||
|
||||
# Never granted by ANY prebuilt scope, regardless of verb. Each is either an
|
||||
# administrative capability, a machine-to-machine credential, or a payload that
|
||||
# a scope-holder should not get merely for being staff.
|
||||
SCOPE_NEVER_GRANT = {
|
||||
# Administrative surface. A scope is not a way to become an admin.
|
||||
'settings.view', 'settings.edit',
|
||||
# users.view is deliberately ABSENT: every scope may see who exists, so an
|
||||
# operator can tell whether an account is already there before asking an
|
||||
# admin to make one. Creating, editing, and deleting accounts stay
|
||||
# admin-only, so seeing the directory grants no power over it.
|
||||
'users.create', 'users.edit', 'users.delete',
|
||||
'audit.view', 'audit.purge',
|
||||
'apitokens.create',
|
||||
# Service-token permissions: these authorize machines, not people. Granting
|
||||
# one to a human scope would let a person impersonate the collector or the
|
||||
# GE-Enforce client.
|
||||
'collector.ingest',
|
||||
'geenforce.fetch',
|
||||
'geenforce.report',
|
||||
# Bytes, not metadata: SYSTEM-context PowerShell bodies and vendor
|
||||
# installers. Deliberately separate from applications.view for exactly this
|
||||
# reason (see the CORE_PERMISSIONS comment), so scopes must not undo that.
|
||||
'applications.download',
|
||||
# The big four endpoint actions. These are per-user direct grants chosen by
|
||||
# checkbox in the user editor, NOT role grants - that is the whole point of
|
||||
# the Phase A2 split. A scope that granted them would take the choice away
|
||||
# from the person creating the account.
|
||||
'endpoints.restart',
|
||||
'endpoints.runscript',
|
||||
'endpoints.updateapp',
|
||||
'endpoints.corptools',
|
||||
# Fleet-wide and agent-distribution capabilities, admin-only by nature.
|
||||
'endpoints.fleet',
|
||||
'endpoints.agentpackage',
|
||||
'endpoints.agentupdate',
|
||||
}
|
||||
|
||||
# Endpoint actions offered as per-user checkboxes in the user editor. Held here
|
||||
# rather than in the endpoints plugin because the USER EDITOR is what needs the
|
||||
# list, and core cannot import a plugin. Kept in sync by
|
||||
# test_scope_endpoint_actions_match_the_plugin.
|
||||
SCOPE_ENDPOINT_ACTIONS = (
|
||||
'endpoints.restart',
|
||||
'endpoints.runscript',
|
||||
'endpoints.updateapp',
|
||||
'endpoints.corptools',
|
||||
)
|
||||
|
||||
|
||||
def _permission_verb(name):
|
||||
"""The verb half of a dotted permission name ('assets.edit' -> 'edit')."""
|
||||
return name.rsplit('.', 1)[-1] if '.' in name else ''
|
||||
|
||||
|
||||
def scope_permission_names(scope, catalog=None):
|
||||
"""Permission names a prebuilt scope grants, derived from the catalog.
|
||||
|
||||
Returns a sorted list so seeding and tests are deterministic.
|
||||
|
||||
reporter - every non-excluded permission whose verb is neither a mutation
|
||||
nor a destruction, plus reports.export. The export is a read
|
||||
that produces a file, not an action against a machine, and the
|
||||
user asked for it by name.
|
||||
technician - the same reads. Identical to reporter at ROLE level: the two
|
||||
differ by what the user editor offers alongside the role, where
|
||||
a technician may be given endpoint action checkboxes and a
|
||||
reporter may not.
|
||||
operator - the reads plus the editing verbs, still never the destructive
|
||||
ones. Deletion stays admin-only, per the user's instruction.
|
||||
"""
|
||||
if catalog is None:
|
||||
catalog = full_permission_catalog()
|
||||
names = {entry[0] for entry in normalize_permission_entries(catalog)}
|
||||
names -= SCOPE_NEVER_GRANT
|
||||
|
||||
readable = {
|
||||
name for name in names
|
||||
if _permission_verb(name) not in _EDIT_VERBS
|
||||
and _permission_verb(name) not in _DESTRUCTIVE_VERBS
|
||||
}
|
||||
if scope in ('reporter', 'technician'):
|
||||
return sorted(readable)
|
||||
if scope == 'operator':
|
||||
return sorted(
|
||||
readable | {
|
||||
name for name in names
|
||||
if _permission_verb(name) in _EDIT_VERBS
|
||||
})
|
||||
raise ValueError(f'Unknown scope: {scope!r}')
|
||||
|
||||
|
||||
# The seeded scopes, in the order the user editor should offer them. `admin` is
|
||||
# absent on purpose: it already exists, is created by `seed admin`, and holds
|
||||
# everything by bypass rather than by grant.
|
||||
PREBUILT_SCOPES = (
|
||||
('operator',
|
||||
'Full access to records except deletion, which stays with admins. '
|
||||
'Endpoint actions are granted per user by checkbox.',
|
||||
'#0D6EFD'),
|
||||
('technician',
|
||||
'Read-only on records: cannot create, edit, or delete, and cannot author '
|
||||
'policy. Endpoint actions are granted per user by checkbox.',
|
||||
'#0DCAF0'),
|
||||
('reporter',
|
||||
'Views everything and exports reports. Holds no action capability and '
|
||||
'cannot be granted one.',
|
||||
'#6F42C1'),
|
||||
)
|
||||
|
||||
# Scopes that may NOT hold the per-user endpoint action grants, enforced
|
||||
# server-side in the user API. Reporter's defining property is that it holds no
|
||||
# action capability EVEN when someone tries to grant one directly.
|
||||
SCOPES_DENIED_ENDPOINT_ACTIONS = frozenset({'reporter'})
|
||||
|
||||
|
||||
def guest_grantable_permissions():
|
||||
"""Which permissions the guest role may be granted.
|
||||
|
||||
@@ -297,6 +465,60 @@ class Role(BaseModel):
|
||||
))
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def seedscopes(cls):
|
||||
"""Create the prebuilt scope roles and sync their grants.
|
||||
|
||||
Returns {'created': [rolename...], 'granted': {rolename: n}}.
|
||||
|
||||
Idempotent, and ADDITIVE on re-run. A second run creates nothing and
|
||||
adds only grants the role is missing; it never REMOVES a permission from
|
||||
an existing role.
|
||||
|
||||
That asymmetry is deliberate. Re-running has to add, because the grant
|
||||
lists are derived from a plugin-driven catalog: install a plugin, re-run
|
||||
the seed, and Technicians should gain read access to the new module
|
||||
without anyone editing a list. But it must not remove, because the role
|
||||
grid is an administrative surface and a site may have deliberately given
|
||||
Operator something extra. A revoking seed would silently undo that
|
||||
decision on the next deploy, which is a worse failure than a role
|
||||
holding one grant more than the default - the first is invisible, the
|
||||
second is on screen in the role editor.
|
||||
|
||||
Consequence worth stating plainly: this cannot be used to TIGHTEN a
|
||||
scope after the fact. If a permission is ever added to
|
||||
SCOPE_NEVER_GRANT, roles already holding it keep it, and revoking is a
|
||||
separate deliberate migration.
|
||||
"""
|
||||
catalog = full_permission_catalog()
|
||||
result = {'created': [], 'granted': {}}
|
||||
|
||||
for rolename, description, color in PREBUILT_SCOPES:
|
||||
role = cls.query.filter_by(rolename=rolename).first()
|
||||
if role is None:
|
||||
role = cls(rolename=rolename, description=description,
|
||||
color=color)
|
||||
db.session.add(role)
|
||||
db.session.flush()
|
||||
result['created'].append(rolename)
|
||||
|
||||
wanted = set(scope_permission_names(rolename, catalog=catalog))
|
||||
held = {p.name for p in role.permissions}
|
||||
missing = wanted - held
|
||||
if not missing:
|
||||
continue
|
||||
|
||||
# Only link permissions that actually exist as rows. A name in the
|
||||
# catalog with no Permission row means `seed permissions` has not
|
||||
# run for that plugin yet; the next run picks it up.
|
||||
rows = Permission.query.filter(Permission.name.in_(missing)).all()
|
||||
for permission in rows:
|
||||
role.permissions.append(permission)
|
||||
if rows:
|
||||
result['granted'][rolename] = len(rows)
|
||||
|
||||
return result
|
||||
|
||||
def getpermissionnames(self) -> list:
|
||||
"""Get list of permission names."""
|
||||
if self.rolename == 'admin':
|
||||
@@ -332,6 +554,14 @@ class User(BaseModel):
|
||||
backref=db.backref('users', lazy='dynamic')
|
||||
)
|
||||
|
||||
# Permissions granted to this user directly, outside any role. See the
|
||||
# userpermissions table comment for why these exist and what must fold them.
|
||||
directpermissions = db.relationship(
|
||||
'Permission',
|
||||
secondary=userpermissions,
|
||||
lazy='joined'
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<User {self.username}>"
|
||||
|
||||
@@ -347,18 +577,43 @@ class User(BaseModel):
|
||||
return any(r.rolename == rolename for r in self.roles)
|
||||
|
||||
def haspermission(self, permission_name: str) -> bool:
|
||||
"""Check if user has a specific permission through any role."""
|
||||
"""Check if user has a permission, through any role or directly.
|
||||
|
||||
A direct grant is not a lesser kind of permission: it is honoured here
|
||||
exactly like a role grant, which is what keeps the API token scope
|
||||
ceiling correct without any change to the ceiling itself. Both ceiling
|
||||
checks (mint time in core/api/apitokens.py and per-request in
|
||||
utils/authz.py) call this method.
|
||||
"""
|
||||
# Admin role has all permissions
|
||||
if self.hasrole('admin'):
|
||||
return True
|
||||
if any(p.name == permission_name for p in self.directpermissions):
|
||||
return True
|
||||
return any(r.haspermission(permission_name) for r in self.roles)
|
||||
|
||||
def getdirectpermissionnames(self) -> list:
|
||||
"""Permission names granted to this user directly, ignoring roles.
|
||||
|
||||
The user editor needs the DIRECT grants alone so a checkbox reflects
|
||||
what is stored on the user rather than what a role happens to supply;
|
||||
getpermissions() deliberately cannot answer that because it folds both.
|
||||
"""
|
||||
return sorted(p.name for p in self.directpermissions)
|
||||
|
||||
def getpermissions(self) -> list:
|
||||
"""Get list of all permission names from all roles."""
|
||||
"""Get list of all permission names, from roles and direct grants.
|
||||
|
||||
This is the LIST surface: it feeds JWT claims and the frontend
|
||||
authStore. It must agree with haspermission(), the predicate surface, or
|
||||
the UI hides controls the server would allow (or worse, shows ones it
|
||||
would refuse).
|
||||
"""
|
||||
if self.hasrole('admin'):
|
||||
return [p[0] for p in full_permission_catalog()]
|
||||
|
||||
perms = set()
|
||||
for role in self.roles:
|
||||
perms.update(role.getpermissionnames())
|
||||
perms.update(p.name for p in self.directpermissions)
|
||||
return list(perms)
|
||||
|
||||
@@ -310,6 +310,62 @@ def test_scope_ceiling_rejects_permission_owner_lacks(client, db):
|
||||
assert 'applications.create' in response.get_json()['data']['error']['message']
|
||||
|
||||
|
||||
def test_a_direct_grant_raises_the_scope_ceiling(client, db):
|
||||
"""A direct per-user grant is an ordinary permission: it lifts the token
|
||||
ceiling exactly as a role-held one does. If getpermissions() and
|
||||
haspermission() ever disagree about direct grants, this fails."""
|
||||
from shopdb.core.models import Permission, User
|
||||
|
||||
_user, headers = _user_with_perms(client, db, 'directmaker',
|
||||
['apitokens.create'])
|
||||
|
||||
# Not held any way yet: the ceiling must refuse it.
|
||||
refused = _create_token(client, headers, scopes=['applications.create'])
|
||||
assert refused.status_code == 400
|
||||
assert 'applications.create' in refused.get_json()['data']['error']['message']
|
||||
|
||||
user = User.query.filter_by(username='directmaker').one()
|
||||
user.directpermissions = [
|
||||
Permission.query.filter_by(name='applications.create').one()]
|
||||
db.session.commit()
|
||||
|
||||
allowed = _create_token(client, headers, name='direct token',
|
||||
scopes=['applications.create'])
|
||||
assert allowed.status_code == 201, allowed.get_json()
|
||||
|
||||
secret = allowed.get_json()['data']['secret']
|
||||
used = client.post('/api/applications', json={'appname': 'Direct App'},
|
||||
headers=_pat_headers(secret))
|
||||
assert used.status_code == 201, used.get_json()
|
||||
|
||||
|
||||
def test_revoking_a_direct_grant_shrinks_an_existing_token(client, db):
|
||||
"""Ceilings are computed live precisely so revocation bites immediately.
|
||||
Pulling the direct grant must disarm a token already minted against it."""
|
||||
from shopdb.core.models import Permission, User
|
||||
|
||||
_user, headers = _user_with_perms(client, db, 'revokee',
|
||||
['apitokens.create'])
|
||||
user = User.query.filter_by(username='revokee').one()
|
||||
user.directpermissions = [
|
||||
Permission.query.filter_by(name='applications.create').one()]
|
||||
db.session.commit()
|
||||
|
||||
secret = _create_token(client, headers, name='doomed token',
|
||||
scopes=['applications.create']
|
||||
).get_json()['data']['secret']
|
||||
assert client.post('/api/applications', json={'appname': 'Before Revoke'},
|
||||
headers=_pat_headers(secret)).status_code == 201
|
||||
|
||||
user = User.query.filter_by(username='revokee').one()
|
||||
user.directpermissions = []
|
||||
db.session.commit()
|
||||
|
||||
after = client.post('/api/applications', json={'appname': 'After Revoke'},
|
||||
headers=_pat_headers(secret))
|
||||
assert after.status_code == 403, after.get_json()
|
||||
|
||||
|
||||
def test_non_admin_scoped_token_capped_at_own_permissions(client, db):
|
||||
"""A non-admin holding applications.create + apitokens.create may mint a
|
||||
token scoped to applications.create and use it."""
|
||||
|
||||
267
tests/test_core/test_user_scopes.py
Normal file
267
tests/test_core/test_user_scopes.py
Normal file
@@ -0,0 +1,267 @@
|
||||
"""Prebuilt user scopes: derived grants, seeding, and the Reporter guard.
|
||||
|
||||
The guard tests are the important ones. The scope dropdown greys out endpoint
|
||||
actions for a Reporter, but a greyed checkbox stops nobody with an HTTP client,
|
||||
and Reporter was specified as holding no action capability even if expressly
|
||||
permitted. These assert that the promise holds against the API rather than
|
||||
against the UI.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from shopdb.core.models import (
|
||||
Role, Permission, scope_permission_names, PREBUILT_SCOPES,
|
||||
SCOPE_ENDPOINT_ACTIONS, SCOPE_NEVER_GRANT)
|
||||
|
||||
|
||||
def _core_catalog():
|
||||
return list(Permission.CORE_PERMISSIONS)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Derived grant lists
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize('scope', ['operator', 'technician', 'reporter'])
|
||||
def test_scope_never_grants_the_excluded_permissions(scope, app):
|
||||
"""No scope may leak an excluded permission, whatever the catalog holds.
|
||||
|
||||
Guards the derivation itself: the lists are computed by verb, so a new
|
||||
permission named with an unexpected verb could otherwise slip into a scope
|
||||
silently.
|
||||
"""
|
||||
with app.app_context():
|
||||
granted = set(scope_permission_names(scope))
|
||||
assert not (granted & SCOPE_NEVER_GRANT)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('scope', ['operator', 'technician', 'reporter'])
|
||||
def test_no_scope_can_act_on_endpoints_through_its_role(scope, app):
|
||||
"""Endpoint actions are per-user grants, never role grants.
|
||||
|
||||
If a scope ever carried one, the per-user checkbox would stop being the
|
||||
control point and the Reporter guard could be bypassed by role alone.
|
||||
"""
|
||||
with app.app_context():
|
||||
granted = set(scope_permission_names(scope))
|
||||
assert not (granted & set(SCOPE_ENDPOINT_ACTIONS))
|
||||
|
||||
|
||||
def test_operator_can_edit_but_never_delete(app):
|
||||
"""Deletion stays with admins - the defining line for Operator."""
|
||||
with app.app_context():
|
||||
granted = scope_permission_names('operator', catalog=_core_catalog())
|
||||
assert 'assets.create' in granted
|
||||
assert 'assets.edit' in granted
|
||||
assert not [n for n in granted if n.endswith('.delete')]
|
||||
|
||||
|
||||
def test_technician_holds_no_record_mutation(app):
|
||||
"""Technician reads records; endpoint work comes from per-user grants."""
|
||||
with app.app_context():
|
||||
granted = scope_permission_names('technician', catalog=_core_catalog())
|
||||
assert 'assets.view' in granted
|
||||
assert 'assets.create' not in granted
|
||||
assert 'assets.edit' not in granted
|
||||
|
||||
|
||||
def test_reporter_reads_and_exports(app):
|
||||
with app.app_context():
|
||||
granted = scope_permission_names('reporter', catalog=_core_catalog())
|
||||
assert 'reports.view' in granted
|
||||
assert 'reports.export' in granted
|
||||
|
||||
|
||||
def test_every_scope_sees_the_user_directory_but_cannot_manage_it(app):
|
||||
"""users.view is granted; creating and editing accounts is admin-only."""
|
||||
with app.app_context():
|
||||
for scope in ('operator', 'technician', 'reporter'):
|
||||
granted = scope_permission_names(scope, catalog=_core_catalog())
|
||||
assert 'users.view' in granted, scope
|
||||
assert 'users.create' not in granted, scope
|
||||
assert 'users.edit' not in granted, scope
|
||||
assert 'users.delete' not in granted, scope
|
||||
|
||||
|
||||
def test_scope_permission_names_rejects_unknown_scope(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(ValueError):
|
||||
scope_permission_names('wizard')
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Seeding
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_seedscopes_creates_roles_and_is_idempotent(app, db):
|
||||
"""A second run creates nothing and grants nothing new."""
|
||||
with app.app_context():
|
||||
Permission.seed()
|
||||
db.session.commit()
|
||||
|
||||
first = Role.seedscopes()
|
||||
db.session.commit()
|
||||
assert set(first['created']) == {n for n, _, _ in PREBUILT_SCOPES}
|
||||
|
||||
second = Role.seedscopes()
|
||||
db.session.commit()
|
||||
assert second['created'] == []
|
||||
assert second['granted'] == {}
|
||||
|
||||
|
||||
def test_seedscopes_does_not_revoke_custom_grants(app, db):
|
||||
"""Re-running must not undo a deliberate site customization.
|
||||
|
||||
The seed is additive by design: a revoking seed would silently strip an
|
||||
extra grant an admin had chosen, and it would do so on deploy, where nobody
|
||||
is watching.
|
||||
"""
|
||||
with app.app_context():
|
||||
Permission.seed()
|
||||
db.session.commit()
|
||||
Role.seedscopes()
|
||||
db.session.commit()
|
||||
|
||||
technician = Role.query.filter_by(rolename='technician').one()
|
||||
extra = Permission.query.filter_by(name='assets.edit').one()
|
||||
technician.permissions.append(extra)
|
||||
db.session.commit()
|
||||
|
||||
Role.seedscopes()
|
||||
db.session.commit()
|
||||
|
||||
technician = Role.query.filter_by(rolename='technician').one()
|
||||
assert 'assets.edit' in {p.name for p in technician.permissions}
|
||||
|
||||
|
||||
def test_seedscopes_grants_survive_a_reporter_role(app, db):
|
||||
with app.app_context():
|
||||
Permission.seed()
|
||||
db.session.commit()
|
||||
Role.seedscopes()
|
||||
db.session.commit()
|
||||
|
||||
reporter = Role.query.filter_by(rolename='reporter').one()
|
||||
held = {p.name for p in reporter.permissions}
|
||||
assert 'reports.export' in held
|
||||
assert not (held & set(SCOPE_ENDPOINT_ACTIONS))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The write-path guard
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _seed_scopes(app, db):
|
||||
with app.app_context():
|
||||
Permission.seed()
|
||||
db.session.commit()
|
||||
Role.seedscopes()
|
||||
db.session.commit()
|
||||
return {
|
||||
name: Role.query.filter_by(rolename=name).one().roleid
|
||||
for name, _, _ in PREBUILT_SCOPES
|
||||
}
|
||||
|
||||
|
||||
def test_create_reporter_with_endpoint_action_is_refused(client, auth_headers,
|
||||
app, db):
|
||||
"""The whole point: a Reporter cannot be created holding a restart grant."""
|
||||
ids = _seed_scopes(app, db)
|
||||
response = client.post('/api/users', headers=auth_headers, json={
|
||||
'username': 'scopereporter', 'email': 'scopereporter@test.local',
|
||||
'password': 'TestPass123!', 'roles': [ids['reporter']],
|
||||
'directpermissions': ['endpoints.restart'],
|
||||
})
|
||||
assert response.status_code == 400, response.get_json()
|
||||
message = response.get_json()['data']['error']['message']
|
||||
assert 'reporter' in message.lower()
|
||||
|
||||
from shopdb.core.models import User
|
||||
with app.app_context():
|
||||
assert User.query.filter_by(username='scopereporter').first() is None
|
||||
|
||||
|
||||
def test_create_technician_with_endpoint_action_is_allowed(client, auth_headers,
|
||||
app, db):
|
||||
ids = _seed_scopes(app, db)
|
||||
response = client.post('/api/users', headers=auth_headers, json={
|
||||
'username': 'scopetech', 'email': 'scopetech@test.local',
|
||||
'password': 'TestPass123!', 'roles': [ids['technician']],
|
||||
'directpermissions': ['endpoints.restart'],
|
||||
})
|
||||
assert response.status_code == 201, response.get_json()
|
||||
|
||||
|
||||
def test_create_reporter_without_actions_is_allowed(client, auth_headers,
|
||||
app, db):
|
||||
ids = _seed_scopes(app, db)
|
||||
response = client.post('/api/users', headers=auth_headers, json={
|
||||
'username': 'plainreporter', 'email': 'plainreporter@test.local',
|
||||
'password': 'TestPass123!', 'roles': [ids['reporter']],
|
||||
'directpermissions': [],
|
||||
})
|
||||
assert response.status_code == 201, response.get_json()
|
||||
|
||||
|
||||
def test_demoting_a_technician_to_reporter_keeps_no_stale_grant(
|
||||
client, auth_headers, app, db):
|
||||
"""The partial-payload case, and the easiest one to get wrong.
|
||||
|
||||
The request changes ROLES only and never mentions directpermissions, so a
|
||||
guard that inspected just the supplied fields would see no endpoint action
|
||||
and allow it - leaving a Reporter holding restart, the exact state the
|
||||
scope promises cannot exist. The guard checks effective state instead.
|
||||
"""
|
||||
ids = _seed_scopes(app, db)
|
||||
created = client.post('/api/users', headers=auth_headers, json={
|
||||
'username': 'demoteme', 'email': 'demoteme@test.local',
|
||||
'password': 'TestPass123!', 'roles': [ids['technician']],
|
||||
'directpermissions': ['endpoints.restart'],
|
||||
})
|
||||
assert created.status_code == 201, created.get_json()
|
||||
userid = created.get_json()['data']['userid']
|
||||
|
||||
response = client.put(f'/api/users/{userid}', headers=auth_headers,
|
||||
json={'roles': [ids['reporter']]})
|
||||
assert response.status_code == 400, response.get_json()
|
||||
|
||||
from shopdb.core.models import User
|
||||
with app.app_context():
|
||||
user = db.session.get(User, userid)
|
||||
assert [r.rolename for r in user.roles] == ['technician']
|
||||
assert 'endpoints.restart' in user.getdirectpermissionnames()
|
||||
|
||||
|
||||
def test_adding_an_action_to_an_existing_reporter_is_refused(
|
||||
client, auth_headers, app, db):
|
||||
"""The mirror case: grants change, roles unmentioned."""
|
||||
ids = _seed_scopes(app, db)
|
||||
created = client.post('/api/users', headers=auth_headers, json={
|
||||
'username': 'staticreporter', 'email': 'staticreporter@test.local',
|
||||
'password': 'TestPass123!', 'roles': [ids['reporter']],
|
||||
})
|
||||
assert created.status_code == 201, created.get_json()
|
||||
userid = created.get_json()['data']['userid']
|
||||
|
||||
response = client.put(
|
||||
f'/api/users/{userid}', headers=auth_headers,
|
||||
json={'directpermissions': ['endpoints.runscript']})
|
||||
assert response.status_code == 400, response.get_json()
|
||||
|
||||
from shopdb.core.models import User
|
||||
with app.app_context():
|
||||
user = db.session.get(User, userid)
|
||||
assert user.getdirectpermissionnames() == []
|
||||
|
||||
|
||||
def test_stacking_technician_onto_reporter_cannot_launder_a_grant(
|
||||
client, auth_headers, app, db):
|
||||
"""Reporter denies actions even when a permissive scope sits beside it."""
|
||||
ids = _seed_scopes(app, db)
|
||||
response = client.post('/api/users', headers=auth_headers, json={
|
||||
'username': 'stacked', 'email': 'stacked@test.local',
|
||||
'password': 'TestPass123!',
|
||||
'roles': [ids['reporter'], ids['technician']],
|
||||
'directpermissions': ['endpoints.corptools'],
|
||||
})
|
||||
assert response.status_code == 400, response.get_json()
|
||||
@@ -47,3 +47,85 @@ def test_role_color_create_list_update(client, auth_headers):
|
||||
json={'color': '#00aa55'})
|
||||
assert updated.status_code == 200, updated.get_json()
|
||||
assert updated.get_json()['data']['color'] == '#00aa55'
|
||||
|
||||
|
||||
def test_directpermissions_granted_without_a_role(client, auth_headers, app, db):
|
||||
"""A permission may be granted to one user without minting a role for it,
|
||||
and it must reach every surface that answers "may this person do X"."""
|
||||
from shopdb.core.models import Permission, User
|
||||
|
||||
with app.app_context():
|
||||
Permission.seed_entries([
|
||||
('endpoints.runscript', 'Push scripts', 'endpoints'),
|
||||
('endpoints.corptools', 'Corporate tool use', 'endpoints'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
created = client.post('/api/users', headers=auth_headers, json={
|
||||
'username': 'bob', 'email': 'bob@test.local', 'password': 'hunter2!!',
|
||||
'roles': [], 'directpermissions': ['endpoints.runscript'],
|
||||
'sendwelcome': False,
|
||||
})
|
||||
assert created.status_code in (200, 201), created.get_json()
|
||||
payload = created.get_json()['data']
|
||||
userid = payload['userid']
|
||||
|
||||
assert payload['directpermissions'] == ['endpoints.runscript']
|
||||
assert 'endpoints.runscript' in payload['permissions']
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.get(User, userid)
|
||||
assert user.haspermission('endpoints.runscript')
|
||||
assert not user.haspermission('endpoints.corptools')
|
||||
assert 'endpoints.runscript' in user.getpermissions()
|
||||
|
||||
revoked = client.put(f'/api/users/{userid}', headers=auth_headers,
|
||||
json={'directpermissions': []})
|
||||
assert revoked.status_code == 200, revoked.get_json()
|
||||
assert revoked.get_json()['data']['directpermissions'] == []
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.get(User, userid)
|
||||
assert not user.haspermission('endpoints.runscript')
|
||||
|
||||
|
||||
def test_a_direct_grant_is_not_duplicated_when_a_role_supplies_it_too(
|
||||
client, auth_headers, app, db):
|
||||
"""Holding a permission both ways is one capability, not two. getpermissions()
|
||||
feeds the API token scope ceiling, so a duplicate would be a visible defect."""
|
||||
from shopdb.core.models import Permission, Role, User
|
||||
|
||||
with app.app_context():
|
||||
Permission.seed_entries([
|
||||
('endpoints.updateapp', 'Update applications', 'endpoints'),
|
||||
])
|
||||
permission = Permission.query.filter_by(
|
||||
name='endpoints.updateapp').one()
|
||||
role = Role(rolename='updaters', description='app updaters')
|
||||
role.permissions = [permission]
|
||||
user = User(username='dana', email='dana@test.local',
|
||||
passwordhash='x', isactive=True)
|
||||
user.roles = [role]
|
||||
user.directpermissions = [permission]
|
||||
db.session.add_all([role, user])
|
||||
db.session.commit()
|
||||
userid = user.userid
|
||||
|
||||
with app.app_context():
|
||||
user = db.session.get(User, userid)
|
||||
granted = user.getpermissions()
|
||||
assert sorted(granted).count('endpoints.updateapp') == 1
|
||||
assert user.haspermission('endpoints.updateapp')
|
||||
|
||||
|
||||
def test_directpermissions_rejects_an_unknown_name(client, auth_headers):
|
||||
"""A typo must fail loudly. Dropping it would report success while granting
|
||||
nothing, and the admin would believe the capability was handed out."""
|
||||
created = client.post('/api/users', headers=auth_headers, json={
|
||||
'username': 'carl', 'email': 'carl@test.local', 'password': 'hunter2!!',
|
||||
'directpermissions': ['endpoints.runscripts'], 'sendwelcome': False,
|
||||
})
|
||||
assert created.status_code == 400, created.get_json()
|
||||
message = created.get_json()['data']['error']['message']
|
||||
assert 'endpoints.runscripts' in message
|
||||
|
||||
|
||||
Reference in New Issue
Block a user