fsanyoto commited on
Commit
b7acda1
·
verified ·
1 Parent(s): ecc3360

Prune files not in the deploy set (stale build context)

Browse files
Files changed (1) hide show
  1. platform/core/test_accounts.py +0 -398
platform/core/test_accounts.py DELETED
@@ -1,398 +0,0 @@
1
- """Test accounts: an exact copy of one member's permissions that takes no seat and sends nothing.
2
-
3
- S79-T63 (QI34, rulings R28 and R42). The copy carries the source's role, business units, modules,
4
- agent, permission block (row filters and field walls stay locks, rule 3) and every share entry
5
- that names the source. It never carries a password, MFA, email, WhatsApp, avatar or epoch.
6
- Creation is all or nothing: a failure removes every part already written.
7
- """
8
- import copy
9
- import datetime as _dt
10
- import re
11
-
12
- import core.shares as shares
13
- import core.store as store
14
- import core.users as users
15
-
16
- PREFIX = 'test-'
17
- #: `routes_admin._UNAME_RE` admits 2 to 32 characters; a generated name stays inside it.
18
- _NAME_MAX = 32
19
- _RETRIES = 3
20
-
21
- #: The record fields a copy takes verbatim from its source.
22
- COPIED_FIELDS = ('role', 'bus', 'modules', 'agent', 'perms', 'perms_v')
23
-
24
-
25
- class CopyRefused(ValueError):
26
- """The request names a source or target this door does not copy or remove."""
27
-
28
- def __init__(self, code, message, status=400):
29
- self.code, self.status = code, status
30
- super().__init__(message)
31
-
32
-
33
- class CopyFailed(RuntimeError):
34
- """A copy or removal stopped part way. `leftovers` names what cleanup could not remove."""
35
-
36
- def __init__(self, cause, leftovers=()):
37
- self.cause, self.leftovers = cause, list(leftovers)
38
- super().__init__(cause)
39
-
40
-
41
- def is_test(record):
42
- """Whether this stored record is a copied test account."""
43
- return users.is_test_account(record)
44
-
45
-
46
- def _tenant_of(record):
47
- return str((record or {}).get('tenant') or 'royal-imports').strip().lower()
48
-
49
-
50
- def paid_seats(registry, tenant):
51
- """Active accounts in `tenant` that take a paid seat. A test account takes none (R42)."""
52
- want = str(tenant or '').strip().lower()
53
- return sum(1 for record in (registry or {}).values()
54
- if isinstance(record, dict) and record.get('active', True)
55
- and _tenant_of(record) == want and not is_test(record))
56
-
57
-
58
- def test_username(source, registry):
59
- """`test-<source>` cut to fit the username rule, with a numeric suffix on a collision."""
60
- base = re.sub(r'[^a-z0-9._-]+', '-', str(source or '').strip().lower()).strip('.-_')
61
- stem = (PREFIX + base)[:_NAME_MAX].rstrip('.-_')
62
- taken = set(registry or {})
63
- if stem not in taken:
64
- return stem
65
- for n in range(2, 1000):
66
- suffix = f'-{n}'
67
- candidate = stem[:_NAME_MAX - len(suffix)].rstrip('.-_') + suffix
68
- if candidate not in taken:
69
- return candidate
70
- raise CopyRefused('no_free_username', 'No free name is left for another test account.', 409)
71
-
72
-
73
- class _Doc:
74
- """A read-only store over one already-read shares document."""
75
-
76
- def __init__(self, doc):
77
- self._doc = doc if isinstance(doc, dict) else {}
78
-
79
- def get(self, name, *args, **kwargs):
80
- return self._doc if name == shares.SHARES_KEY else None
81
-
82
-
83
- class _Batch:
84
- """Stage `shares.set_grants` writes in memory, then replay them all in ONE store update.
85
-
86
- Every staged closure keeps its `expect` check, so the replay refuses if any record changed.
87
- """
88
-
89
- def __init__(self, st, doc):
90
- self._st, self._doc, self._fns = st, copy.deepcopy(doc or {}), []
91
-
92
- def get(self, name, *args, **kwargs):
93
- if name != shares.SHARES_KEY:
94
- raise RuntimeError(f'a staged grant write cannot read {name!r}')
95
- return self._doc
96
-
97
- def update(self, name, fn, flush='sync'):
98
- if name != shares.SHARES_KEY:
99
- raise RuntimeError(f'a staged grant write cannot write {name!r}')
100
- self._doc = fn(self._doc)
101
- self._fns.append(fn)
102
- return self._doc
103
-
104
- def commit(self):
105
- if not self._fns:
106
- return
107
- fns = list(self._fns)
108
-
109
- def replay(data):
110
- data = data if isinstance(data, dict) else {}
111
- for fn in fns:
112
- data = fn(data)
113
- return data
114
-
115
- self._st.update(shares.SHARES_KEY, replay, flush='sync')
116
-
117
-
118
- def _read_shares(st):
119
- """The tenant's shares document, read strictly: an unreadable bucket stops the copy."""
120
- doc = st.get(shares.SHARES_KEY, fresh=True)
121
- if doc is None:
122
- return {}
123
- if not isinstance(doc, dict):
124
- raise RuntimeError('the sharing records could not be read')
125
- return doc
126
-
127
-
128
- def grants_naming(username, doc):
129
- """`[{kind, oid, role}]` for every share entry that names `username`, from one document."""
130
- username = str(username or '').strip().lower()
131
- found = []
132
- view = _Doc(doc)
133
- for kind in shares.KINDS:
134
- for oid, record in sorted(shares.grants_bulk(kind, st=view).items()):
135
- for entry in record['entries']:
136
- if entry['user'] == username:
137
- found.append({'kind': kind, 'oid': oid, 'role': entry['role']})
138
- return found
139
-
140
-
141
- def _check_source(source, registry, tenant):
142
- uname = str(source or '').strip().lower()
143
- record = (registry or {}).get(uname)
144
- if not uname or not isinstance(record, dict) or _tenant_of(record) != tenant:
145
- raise CopyRefused('no_such_user', f'No account named {uname or "(blank)"}.', 404)
146
- if is_test(record):
147
- raise CopyRefused('source_is_test', 'A test account cannot be copied. Copy a member.')
148
- if str(record.get('role') or 'user').strip().lower() != 'user':
149
- raise CopyRefused('source_is_admin',
150
- 'An administrator cannot be copied. Copy a member account.')
151
- if not record.get('active', True):
152
- raise CopyRefused('source_inactive', 'This account is turned off. Turn it on first.')
153
- return uname, record
154
-
155
-
156
- def plan(source, registry, *, tenant, st):
157
- """What a copy of `source` would carry, read now: the access fields and every share entry."""
158
- tenant = str(tenant or '').strip().lower()
159
- uname, record = _check_source(source, registry, tenant)
160
- access = {key: copy.deepcopy(record[key]) for key in COPIED_FIELDS if key in record}
161
- return {'source': uname,
162
- 'sourceName': str(record.get('name') or uname),
163
- 'username': test_username(uname, registry),
164
- 'name': f'Test copy of {record.get("name") or uname}',
165
- 'access': access,
166
- 'grants': grants_naming(uname, _read_shares(st))}
167
-
168
-
169
- def _password(username, name):
170
- for _ in range(8):
171
- candidate = users.generate_password()
172
- if not users.password_failures(candidate, username=username, name=name):
173
- return candidate
174
- raise RuntimeError('could not generate a password for the test account')
175
-
176
-
177
- def copy_grants(username, grants, *, st, granter):
178
- """Add `username` beside each listed share entry, same role, in one store update."""
179
- batch = _Batch(st, _read_shares(st))
180
- for grant in grants:
181
- current = shares.grants(grant['kind'], grant['oid'], st=batch)
182
- if any(entry['user'] == username for entry in current['entries']):
183
- continue
184
- entries = current['entries'] + [{'user': username, 'role': grant['role']}]
185
- shares.set_grants(grant['kind'], grant['oid'], entries, st=batch,
186
- granter=granter, expect=current['entries'])
187
- batch.commit()
188
-
189
-
190
- def remove_grants(username, *, st, granter):
191
- """Remove every share entry naming `username`, retrying if a record changes meanwhile."""
192
- for attempt in range(_RETRIES):
193
- doc = _read_shares(st)
194
- batch = _Batch(st, doc)
195
- for grant in grants_naming(username, doc):
196
- current = shares.grants(grant['kind'], grant['oid'], st=batch)
197
- entries = [entry for entry in current['entries'] if entry['user'] != username]
198
- shares.set_grants(grant['kind'], grant['oid'], entries, st=batch,
199
- granter=granter, expect=current['entries'])
200
- try:
201
- batch.commit()
202
- return
203
- except shares.GrantsChanged:
204
- if attempt == _RETRIES - 1:
205
- raise
206
-
207
-
208
- def _fresh_registry():
209
- registry = store.get('users', fresh=True)
210
- if not isinstance(registry, dict):
211
- raise RuntimeError('the account registry could not be read')
212
- return registry
213
-
214
-
215
- def _confirm(username, plan_, marker, st):
216
- record = _fresh_registry().get(username) or {}
217
- if record.get(users.TEST_ACCOUNT_KEY) != marker:
218
- raise RuntimeError('the account was not saved')
219
- if any(record.get(key) != plan_['access'].get(key) for key in plan_['access']):
220
- raise RuntimeError('the copied permissions were not saved')
221
- held = {(g['kind'], g['oid'], g['role']) for g in grants_naming(username, _read_shares(st))}
222
- missing = [g for g in plan_['grants'] if (g['kind'], g['oid'], g['role']) not in held]
223
- if missing:
224
- raise RuntimeError(f'{len(missing)} shared items were not saved')
225
-
226
-
227
- def _cleanup(username, tenant, marker, st, granter, steps):
228
- """Undo every part of a copy. Returns the names of the parts that could not be removed."""
229
- leftovers = []
230
- for name, _do, undo in reversed(list(steps)):
231
- try:
232
- undo(username)
233
- except Exception: # noqa: BLE001
234
- leftovers.append(name)
235
- try:
236
- remove_grants(username, st=st, granter=granter)
237
- except Exception: # noqa: BLE001
238
- leftovers.append('shared items')
239
- try:
240
- users.delete_test_account(username, tenant=tenant, marker=marker)
241
- left = _fresh_registry().get(username)
242
- if is_test(left) and left.get(users.TEST_ACCOUNT_KEY) == marker:
243
- leftovers.append('sign in')
244
- except Exception: # noqa: BLE001
245
- leftovers.append('sign in')
246
- return leftovers
247
-
248
-
249
- def _cause(exc):
250
- text = str(exc).strip() or type(exc).__name__
251
- return text[:1].upper() + text[1:]
252
-
253
-
254
- def create(source, *, admin, tenant, st, steps=(), now=None):
255
- """Copy `source` into a new test account. Returns `{username, password, plan}`.
256
-
257
- `steps` are `(name, do(username, source), undo(username))` for grant stores outside core.
258
- Any failure removes what was written and raises `CopyFailed`.
259
- """
260
- tenant = str(tenant or '').strip().lower()
261
- admin = str(admin or '').strip().lower()
262
- for attempt in range(_RETRIES):
263
- plan_ = plan(source, _fresh_registry(), tenant=tenant, st=st)
264
- username = plan_['username']
265
- marker = {'copied_from': plan_['source'], 'created_by': admin,
266
- 'created_at': (now or _dt.datetime.now(_dt.timezone.utc)).isoformat(
267
- timespec='seconds')}
268
- password = _password(username, plan_['name'])
269
- try:
270
- users.create_test_account(username, password, name=plan_['name'],
271
- access=plan_['access'], marker=marker, tenant=tenant)
272
- except users.TestAccountExists:
273
- if attempt == _RETRIES - 1:
274
- raise CopyFailed('Another account took the test account name. Try again.')
275
- continue
276
- except Exception as exc: # noqa: BLE001
277
- # The write may have landed before it reported failure: clean up as for any step.
278
- leftovers = _cleanup(username, tenant, marker, st, admin, ())
279
- raise CopyFailed(_cause(exc), leftovers) from exc
280
- try:
281
- copy_grants(username, plan_['grants'], st=st, granter=admin)
282
- for _name, do, _undo in steps:
283
- do(username, plan_['source'])
284
- _confirm(username, plan_, marker, st)
285
- except Exception as exc: # noqa: BLE001
286
- leftovers = _cleanup(username, tenant, marker, st, admin, steps)
287
- raise CopyFailed(_cause(exc), leftovers) from exc
288
- return {'username': username, 'password': password, 'plan': plan_}
289
- raise CopyFailed('The test account could not be created. Try again.')
290
-
291
-
292
- def remove(username, *, tenant, st, granter, steps=()):
293
- """Delete a test account and every grant naming it. Refuses a real account."""
294
- tenant = str(tenant or '').strip().lower()
295
- uname = str(username or '').strip().lower()
296
- record = _fresh_registry().get(uname)
297
- if not isinstance(record, dict) or _tenant_of(record) != tenant:
298
- raise CopyRefused('no_such_user', f'No account named {uname or "(blank)"}.', 404)
299
- if not is_test(record):
300
- raise CopyRefused('not_a_test_account',
301
- 'This is a real account. Only a test account can be removed here.')
302
- leftovers = _cleanup(uname, tenant, record.get(users.TEST_ACCOUNT_KEY), st, granter, steps)
303
- if leftovers:
304
- raise CopyFailed('Some parts are still saved', leftovers)
305
-
306
-
307
- # ------------------------------------------------------------------ preview
308
- def _label(key, defs):
309
- import core.perms as perms
310
- import core.registry as registry
311
- definition = (defs or {}).get(key) or {}
312
- # The editor's surface rows (Assistant, Agents, AI apps (MCP)) are named by perms, not the registry.
313
- surfaces = {m['key']: m['label'] for m in perms.governable_surface_modules()}
314
- return str(definition.get('label') or (registry.BY_KEY.get(key) or {}).get('label')
315
- or surfaces.get(key) or key)
316
-
317
-
318
- def _plural(n, one, many):
319
- return f'{n} {one if n == 1 else many}'
320
-
321
-
322
- def preview(plan_, *, st=None, limits=None):
323
- """The contract body for GET .../test-account/preview, built from `plan`.
324
-
325
- `st` is a definitions store (`user_tables.lend_defs`) for the database lock checks.
326
- `limits` is `perm_scope.scope_limits` for the source; it names each row limit, business units included.
327
- """
328
- from core import user_tables
329
- access = plan_['access']
330
- try:
331
- defs = user_tables.all_defs(st=st, schema_only=True) or {}
332
- except Exception: # noqa: BLE001
333
- defs = {}
334
- block = access.get('perms') if isinstance(access.get('perms'), dict) else {}
335
- locks, reached = [], set()
336
- said = {}
337
- for limit in limits or ():
338
- text = str(limit.get('text') or '').strip().rstrip('.')
339
- if limit.get('database') and text:
340
- said[str(limit['database'])] = text
341
- for key in sorted(said):
342
- locks.append({'kind': 'row_scope', 'label': f'{_label(key, defs)}: {said[key]}'})
343
- for key, entry in sorted(block.items()):
344
- if not isinstance(entry, dict) or not entry.get('access', True):
345
- continue
346
- reached.add(key)
347
- if entry.get('filter') and key not in said:
348
- locks.append({'kind': 'row_scope', 'label': f'Rows are limited in {_label(key, defs)}'})
349
- hidden = [f for f in entry.get('hiddenFields') or () if f]
350
- if hidden:
351
- locks.append({'kind': 'field_wall',
352
- 'label': f'{_plural(len(hidden), "field is", "fields are")} hidden in '
353
- f'{_label(key, defs)}'})
354
- if not access.get('perms_v') and not said:
355
- bus = access.get('bus', 'all')
356
- if bus != 'all' and isinstance(bus, list):
357
- names = ', '.join(users.BU_LABELS.get(b, str(b)) for b in bus)
358
- locks.append({'kind': 'row_scope', 'label': f'Rows are limited to {names}'})
359
- if access.get('agent'):
360
- locks.append({'kind': 'row_scope', 'label': "Rows are limited to one salesperson's book"})
361
- for grant in plan_['grants']:
362
- if grant['kind'] == 'cohort':
363
- scope, _cid = shares.split_cohort_oid(grant['oid'])
364
- where = _label(scope, defs) if scope else 'a database'
365
- locks.append({'kind': 'locked_view', 'label': f'A locked view in {where}'})
366
- if grant['kind'] == 'database':
367
- reached.add(grant['oid'])
368
- for key in sorted(k for k in reached if str(k).startswith(user_tables.KEY_PREFIX)):
369
- definition = defs.get(key)
370
- if not isinstance(definition, dict):
371
- continue
372
- if not user_tables.records_mutable(key, st=st):
373
- locks.append({'kind': 'locked_database',
374
- 'label': f'{_label(key, defs)} is locked for record changes'})
375
- preset = [f for f in definition.get('fields') or ()
376
- if isinstance(f, dict) and isinstance(f.get('automation'), dict)
377
- and f['automation'].get('preset') is True
378
- and not user_tables.preset_editable(f)]
379
- if preset:
380
- locks.append({'kind': 'preset_field',
381
- 'label': f'{_plural(len(preset), "pre-set field", "pre-set fields")} '
382
- f'in {_label(key, defs)}'})
383
- grants = []
384
- for grant in plan_['grants']:
385
- row = dict(grant)
386
- if grant['kind'] == 'database':
387
- row['label'] = _label(grant['oid'], defs)
388
- grants.append(row)
389
- database_access = [{'key': key, 'label': _label(key, defs),
390
- 'access': bool(entry.get('access', True))}
391
- for key, entry in sorted(block.items()) if isinstance(entry, dict)]
392
- return {'source': {'username': plan_['source'], 'name': plan_['sourceName']},
393
- 'testUsername': plan_['username'],
394
- 'copy': {'role': access.get('role', 'user'), 'bus': access.get('bus', 'all'),
395
- 'buLabels': users.allowed_bus_labels(access),
396
- 'modules': access.get('modules', 'all'), 'agent': access.get('agent'),
397
- 'grants': grants, 'databaseAccess': database_access, 'locks': locks},
398
- 'counts': {'grants': len(grants), 'locks': len(locks)}}