@things-factory/auth-base 10.1.79 → 10.1.107

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist-client/tsconfig.tsbuildinfo +1 -1
  2. package/dist-server/ai-entry/access-assistant.d.ts +50 -0
  3. package/dist-server/ai-entry/access-assistant.js +145 -0
  4. package/dist-server/ai-entry/access-assistant.js.map +1 -0
  5. package/dist-server/ai-entry/access-entry-targets.d.ts +32 -0
  6. package/dist-server/ai-entry/access-entry-targets.js +196 -0
  7. package/dist-server/ai-entry/access-entry-targets.js.map +1 -0
  8. package/dist-server/ai-entry/entry-target-shape.d.ts +82 -0
  9. package/dist-server/ai-entry/entry-target-shape.js +3 -0
  10. package/dist-server/ai-entry/entry-target-shape.js.map +1 -0
  11. package/dist-server/controllers/access-request.d.ts +57 -0
  12. package/dist-server/controllers/access-request.js +373 -0
  13. package/dist-server/controllers/access-request.js.map +1 -0
  14. package/dist-server/index.d.ts +3 -0
  15. package/dist-server/index.js +3 -0
  16. package/dist-server/index.js.map +1 -1
  17. package/dist-server/service/access-request/access-request-mutation.d.ts +17 -0
  18. package/dist-server/service/access-request/access-request-mutation.js +65 -0
  19. package/dist-server/service/access-request/access-request-mutation.js.map +1 -0
  20. package/dist-server/service/access-request/access-request-query.d.ts +16 -0
  21. package/dist-server/service/access-request/access-request-query.js +100 -0
  22. package/dist-server/service/access-request/access-request-query.js.map +1 -0
  23. package/dist-server/service/access-request/access-request-types.d.ts +32 -0
  24. package/dist-server/service/access-request/access-request-types.js +115 -0
  25. package/dist-server/service/access-request/access-request-types.js.map +1 -0
  26. package/dist-server/service/access-request/access-request.d.ts +33 -0
  27. package/dist-server/service/access-request/access-request.js +160 -0
  28. package/dist-server/service/access-request/access-request.js.map +1 -0
  29. package/dist-server/service/access-request/index.d.ts +5 -0
  30. package/dist-server/service/access-request/index.js +9 -0
  31. package/dist-server/service/access-request/index.js.map +1 -0
  32. package/dist-server/service/index.d.ts +3 -1
  33. package/dist-server/service/index.js +42 -37
  34. package/dist-server/service/index.js.map +1 -1
  35. package/dist-server/service/open-fields.js +5 -1
  36. package/dist-server/service/open-fields.js.map +1 -1
  37. package/dist-server/service/privilege/privilege-directive.js +6 -6
  38. package/dist-server/service/privilege/privilege-directive.js.map +1 -1
  39. package/dist-server/service/privilege/privilege-rejection.d.ts +10 -2
  40. package/dist-server/service/privilege/privilege-rejection.js +23 -10
  41. package/dist-server/service/privilege/privilege-rejection.js.map +1 -1
  42. package/dist-server/service/user/user-mutation.js +5 -4
  43. package/dist-server/service/user/user-mutation.js.map +1 -1
  44. package/dist-server/service/user/user-query.js +5 -17
  45. package/dist-server/service/user/user-query.js.map +1 -1
  46. package/dist-server/tsconfig.tsbuildinfo +1 -1
  47. package/dist-server/utils/access-request-review.d.ts +69 -0
  48. package/dist-server/utils/access-request-review.js +119 -0
  49. package/dist-server/utils/access-request-review.js.map +1 -0
  50. package/dist-server/utils/assignable-roles.d.ts +23 -0
  51. package/dist-server/utils/assignable-roles.js +89 -0
  52. package/dist-server/utils/assignable-roles.js.map +1 -0
  53. package/dist-server/utils/check-permission.d.ts +29 -2
  54. package/dist-server/utils/check-permission.js +48 -14
  55. package/dist-server/utils/check-permission.js.map +1 -1
  56. package/package.json +4 -4
  57. package/tests/access-assistant-db.test.ts +155 -0
  58. package/tests/access-entry-targets-db.test.ts +138 -0
  59. package/tests/access-request-db.test.ts +273 -0
  60. package/tests/access-request-pg.test.ts +72 -0
  61. package/tests/access-request-review.test.ts +155 -0
  62. package/tests/assignable-roles-db.test.ts +141 -0
  63. package/tests/permission-gate.test.ts +5 -7
  64. package/tests/privilege-directive.test.ts +39 -0
  65. package/tests/privilege-rejection.test.ts +32 -0
  66. package/tests/refusal-cause.test.ts +80 -0
  67. package/translations/en.json +28 -1
  68. package/translations/ja.json +28 -1
  69. package/translations/ko.json +28 -1
  70. package/translations/ms.json +28 -1
  71. package/translations/zh.json +28 -1
@@ -0,0 +1,155 @@
1
+ /**
2
+ * What the assistant reads to draft access decisions (ADR-0103 decision 6).
3
+ *
4
+ * Two facts are held here. The read tool answers only this domain, only to someone who may decide, never the
5
+ * caller's own requests. And a pending request handed over as the screen's context does not reach the model's
6
+ * prompt - which is why the tool exists; if that ever changes, this file says so.
7
+ */
8
+ import { registryAssistantChat } from '../../ai-client-base/server/service/assistant/registry-assistant'
9
+ import { clearToolRegistry, registerToolCategory } from '../../ai-client-base/server/service/tool-registry/index.js'
10
+
11
+ import { closeAuthDatabase, Domain, getRepository, openAuthDatabase, resetAuthDatabase } from './db'
12
+ import { loadCompiled } from './compiled'
13
+
14
+ import uiEn from '../../auth-ui/translations/en.json'
15
+ import uiKo from '../../auth-ui/translations/ko.json'
16
+
17
+ const { Role } = loadCompiled('service/role/role')
18
+ const { Privilege } = loadCompiled('service/privilege/privilege')
19
+ const { User } = loadCompiled('service/user/user')
20
+ const { DomainOwner } = loadCompiled('service/domain-owner/domain-owner')
21
+ const { AccessRequest } = loadCompiled('service/access-request/access-request')
22
+ const access = loadCompiled('controllers/access-request')
23
+ const assistant = loadCompiled('ai-entry/access-assistant')
24
+ const targets = loadCompiled('ai-entry/access-entry-targets')
25
+
26
+ let domain: any
27
+ let other: any
28
+ let kim: any
29
+ let lee: any
30
+ let park: any
31
+ let owner: any
32
+ let worker: any
33
+ let otherAdmin: any
34
+
35
+ async function makeUser(name: string, domains: any[], roles: any[] = []) {
36
+ return await getRepository(User).save({
37
+ username: name, email: `${name}@example.com`, name, salt: User.generateSalt(), status: 'activated', domains, roles
38
+ })
39
+ }
40
+
41
+ const ask = (user: any, privilege = 'mutation', inDomain = domain) =>
42
+ access.requestAccess({ category: 'warehouse', privilege, reason: 'needed for work' }, { state: { domain: inDomain, user, afterCommit: [] } } as any)
43
+
44
+ beforeAll(async () => {
45
+ await openAuthDatabase()
46
+ })
47
+
48
+ afterAll(async () => {
49
+ await closeAuthDatabase()
50
+ })
51
+
52
+ beforeEach(async () => {
53
+ await resetAuthDatabase()
54
+ ;(process as any).domainOwnerGranted = async (d: any, u: any) =>
55
+ !!(await getRepository(DomainOwner).findOne({ where: { domain: { id: d.id }, user: { id: u.id } } }))
56
+ ;(process as any).superUserGranted = async () => false
57
+
58
+ domain = await getRepository(Domain).findOneBy({ id: (await getRepository(Domain).save({ name: 'Plant A', subdomain: 'plant-a' })).id })
59
+ other = await getRepository(Domain).findOneBy({ id: (await getRepository(Domain).save({ name: 'Other', subdomain: 'other' })).id })
60
+
61
+ const mutation = await getRepository(Privilege).save({ name: 'mutation', category: 'warehouse' })
62
+ await getRepository(Privilege).save({ name: 'query', category: 'warehouse' })
63
+ const grant = await getRepository(Privilege).save({ name: 'mutation', category: 'user' })
64
+ await getRepository(Role).save({ name: 'inbound', domain, privileges: [mutation] })
65
+ const admins = await getRepository(Role).save({ name: 'admins', domain, privileges: [grant] })
66
+ const otherAdmins = await getRepository(Role).save({ name: 'admins', domain: other, privileges: [grant] })
67
+
68
+ kim = await makeUser('kim', [domain])
69
+ lee = await makeUser('lee', [domain])
70
+ park = await makeUser('park', [domain], [admins])
71
+ owner = await makeUser('owner', [domain])
72
+ worker = await makeUser('worker', [domain])
73
+ otherAdmin = await makeUser('otheradmin', [other], [otherAdmins])
74
+ await getRepository(DomainOwner).save({ domain, user: owner })
75
+ })
76
+
77
+ afterEach(() => {
78
+ delete (process as any).domainOwnerGranted
79
+ delete (process as any).superUserGranted
80
+ })
81
+
82
+ describe('listPendingAccessRequests', () => {
83
+ it('★ a decider reads this domain\'s waiting requests with the roles that grant each', async () => {
84
+ await ask(kim)
85
+ const answer = await assistant.pendingRequestsToDecide({ domain, user: park })
86
+ expect(answer.requests).toEqual([
87
+ expect.objectContaining({ requester: 'kim', privilege: 'warehouse:mutation', roles: [{ name: 'inbound', privilegeCount: 1 }] })
88
+ ])
89
+ })
90
+
91
+ it('★ another domain\'s requests are not read - even by a decider there', async () => {
92
+ await ask(kim)
93
+ const there = await assistant.pendingRequestsToDecide({ domain: other, user: otherAdmin })
94
+ expect(there.requests).toEqual([])
95
+ })
96
+
97
+ it('★ someone who may not decide is refused - nothing is read', async () => {
98
+ await ask(kim)
99
+ expect(await assistant.pendingRequestsToDecide({ domain, user: worker })).toEqual({ refused: 'not-a-decider' })
100
+ })
101
+
102
+ it('★ the caller\'s own requests are left out - they cannot decide them', async () => {
103
+ await ask(kim)
104
+ await ask(owner, 'query')
105
+ const answer = await assistant.pendingRequestsToDecide({ domain, user: owner })
106
+ expect(answer.requests.map((r: any) => r.requester)).toEqual(['kim'])
107
+ })
108
+
109
+ it('decided and expired requests are left out', async () => {
110
+ const decided = await ask(kim)
111
+ await access.decideAccessRequest({ requestId: decided.id, decision: 'DENY', reason: 'no' }, { state: { domain, user: park, afterCommit: [] } } as any)
112
+ const late = await ask(lee)
113
+ await getRepository(AccessRequest).update({ id: late.id }, { expiresAt: new Date(Date.now() - 1000) })
114
+ expect((await assistant.pendingRequestsToDecide({ domain, user: park })).requests).toEqual([])
115
+ })
116
+ })
117
+
118
+ describe('the declarations fit together', () => {
119
+ afterEach(() => clearToolRegistry())
120
+
121
+ it('the category registers, the mode names it and the decision target, the words exist', () => {
122
+ const category = assistant.accessToolCategory()
123
+ expect(() => registerToolCategory(category)).not.toThrow()
124
+ const mode = assistant.accessAssistantMode()
125
+ expect(mode.toolCategories).toEqual([category.name])
126
+ expect(mode.entryTargets).toEqual([targets.AUTH_ACCESS_DECISION])
127
+ expect(mode.subjects).toEqual([assistant.ACCESS_REQUESTS_SUBJECT])
128
+ for (const dict of [uiEn, uiKo] as Record<string, string>[])
129
+ for (const key of [mode.labelKey, mode.placeholderKey]) expect([key, typeof dict[key]]).toEqual([key, 'string'])
130
+ })
131
+
132
+ it('★ requests handed over as the screen\'s context do not reach the model\'s prompt - the tool is how it reads them', async () => {
133
+ registerToolCategory(assistant.accessToolCategory())
134
+ const seen: any[] = []
135
+ const client = {
136
+ chatWithTools: async (messages: any, tools: any[], options: any) => {
137
+ seen.push({ messages, tools, options })
138
+ return { text: 'ok', toolCalls: [], stopReason: 'end_turn' }
139
+ }
140
+ }
141
+ await registryAssistantChat({
142
+ client,
143
+ messages: [{ role: 'user', content: 'sort out the access requests' }],
144
+ systemPrompt: assistant.accessAssistantMode().systemPrompt,
145
+ toolCategories: [assistant.AUTH_ACCESS_TOOLS],
146
+ hostContext: { pendingRequests: ['MARKER-kim-warehouse-mutation'] },
147
+ state: { domain, user: park },
148
+ toolAccess: async () => true
149
+ } as any)
150
+
151
+ expect(JSON.stringify(seen[0].options)).not.toContain('MARKER-kim')
152
+ expect(JSON.stringify(seen[0].messages)).not.toContain('MARKER-kim')
153
+ expect(seen[0].tools.map((t: any) => t.name)).toEqual(['listPendingAccessRequests'])
154
+ })
155
+ })
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The access request's AI 입력 declarations (ADR-0103 decision 4).
3
+ *
4
+ * The model drafts and a person presses; the card's check is the review the list screen asks. That last point is
5
+ * what this file holds above all: the card's findings for a decision equal `reviewDecision` for the same decision.
6
+ *
7
+ * The declarations are read from the compiled package so their check reaches the same entities as the database.
8
+ * The assistant's own validation is asked through its source file, which needs only `graphql`.
9
+ */
10
+ import { parse } from 'graphql'
11
+
12
+ import { clearEntryTargets, declareEntryTarget } from '../../ai-assistant/server/service/data-entry/entry-target'
13
+
14
+ import { closeAuthDatabase, Domain, getRepository, openAuthDatabase, resetAuthDatabase } from './db'
15
+ import { loadCompiled } from './compiled'
16
+
17
+ import uiEn from '../../auth-ui/translations/en.json'
18
+ import uiKo from '../../auth-ui/translations/ko.json'
19
+
20
+ const { Role } = loadCompiled('service/role/role')
21
+ const { Privilege } = loadCompiled('service/privilege/privilege')
22
+ const { User } = loadCompiled('service/user/user')
23
+ const access = loadCompiled('controllers/access-request')
24
+ const targets = loadCompiled('ai-entry/access-entry-targets')
25
+
26
+ const rootFields = (document: string) =>
27
+ ((parse(document).definitions[0] as any).selectionSet.selections as any[]).map(one => one.name.value)
28
+
29
+ const row = (values: Record<string, unknown>, index = 0) => ({ index, values, sources: [], issues: [] })
30
+
31
+ describe('the declarations', () => {
32
+ afterEach(() => clearEntryTargets())
33
+
34
+ it('are accepted by the assistant as declared', () => {
35
+ for (const target of targets.accessEntryTargets()) expect(() => declareEntryTarget(target)).not.toThrow()
36
+ })
37
+
38
+ it('★ the decision card writes through decideAccessRequest - the person presses it; nothing else is a door', () => {
39
+ const decision = targets.accessDecisionEntryTarget()
40
+ expect(rootFields(decision.mutation)).toEqual(['decideAccessRequest'])
41
+ expect(rootFields(decision.fields.find((f: any) => f.name === 'request').reference.query)).toEqual(['accessRequests'])
42
+ expect(rootFields(targets.accessRequestEntryTarget().mutation)).toEqual(['requestAccess'])
43
+ })
44
+
45
+ it('a denial carries no role, a grant carries its role id', () => {
46
+ expect(targets.decisionOf(row({ request: { id: 'q' }, decision: 'DENY', role: { id: 'r' }, reason: 'no' }))).toEqual({
47
+ requestId: 'q',
48
+ decision: 'DENY',
49
+ roleId: undefined,
50
+ reason: 'no'
51
+ })
52
+ expect(targets.decisionOf(row({ request: { id: 'q' }, decision: 'GRANT', role: { id: 'r' } })).roleId).toBe('r')
53
+ })
54
+
55
+ it('a request is named by person or privilege; only pending ones; several stay several', () => {
56
+ const items = [
57
+ { id: '1', state: 'PENDING', category: 'warehouse', privilege: 'mutation', requester: { name: '김민수' } },
58
+ { id: '2', state: 'PENDING', category: 'board', privilege: 'query', requester: { name: '김민지' } },
59
+ { id: '3', state: 'GRANTED', category: 'warehouse', privilege: 'mutation', requester: { name: '김민수' } }
60
+ ]
61
+ expect(targets.requestsNamed(items, '김민수').map((r: any) => r.id)).toEqual(['1'])
62
+ expect(targets.requestsNamed(items, '김민').map((r: any) => r.id)).toEqual(['1', '2'])
63
+ expect(targets.requestsNamed(items, 'board:query').map((r: any) => r.label)).toEqual(['김민지 · board:query'])
64
+ })
65
+
66
+ it('every word the card shows is in the screen words', () => {
67
+ const decision = targets.accessDecisionEntryTarget()
68
+ const keys = [
69
+ decision.labelKey,
70
+ targets.accessRequestEntryTarget().labelKey,
71
+ ...[...decision.fields, ...targets.accessRequestEntryTarget().fields].map((f: any) => f.labelKey),
72
+ 'access-request.decision.grant',
73
+ 'access-request.decision.deny',
74
+ 'access-request.issue.not-by-role'
75
+ ]
76
+ for (const dict of [uiEn, uiKo] as Record<string, string>[]) for (const key of keys) expect([key, typeof dict[key]]).toEqual([key, 'string'])
77
+ })
78
+ })
79
+
80
+ describe('the card says what the screen says', () => {
81
+ let domain: any
82
+ let kim: any
83
+ let park: any
84
+ let inbound: any
85
+ let manager: any
86
+
87
+ beforeAll(async () => {
88
+ await openAuthDatabase()
89
+ })
90
+
91
+ afterAll(async () => {
92
+ await closeAuthDatabase()
93
+ })
94
+
95
+ beforeEach(async () => {
96
+ await resetAuthDatabase()
97
+ const saved = await getRepository(Domain).save({ name: 'Plant A', subdomain: 'plant-a' })
98
+ domain = await getRepository(Domain).findOneBy({ id: saved.id })
99
+ const mutation = await getRepository(Privilege).save({ name: 'mutation', category: 'warehouse' })
100
+ const query = await getRepository(Privilege).save({ name: 'query', category: 'warehouse' })
101
+ const grant = await getRepository(Privilege).save({ name: 'mutation', category: 'user' })
102
+ inbound = await getRepository(Role).save({ name: 'inbound', domain, privileges: [mutation] })
103
+ manager = await getRepository(Role).save({ name: 'manager', domain, privileges: [mutation, query, grant] })
104
+ const admins = await getRepository(Role).save({ name: 'admins', domain, privileges: [grant] })
105
+ const make = (name: string, roles: any[]) =>
106
+ getRepository(User).save({ username: name, email: `${name}@example.com`, name, salt: User.generateSalt(), status: 'activated', domains: [domain], roles })
107
+ kim = await make('kim', [])
108
+ park = await make('park', [admins])
109
+ })
110
+
111
+ const state = (user: any) => ({ domain, user })
112
+
113
+ it('★ the card\'s findings are reviewDecision\'s, for grant and for deny', async () => {
114
+ const request = await access.requestAccess({ category: 'warehouse', privilege: 'mutation', reason: 'inbound' }, { state: { ...state(kim), afterCommit: [] } } as any)
115
+ const rows = [
116
+ row({ request: { id: request.id }, decision: 'GRANT', role: { id: manager.id } }, 0),
117
+ row({ request: { id: request.id }, decision: 'GRANT', role: { id: inbound.id } }, 1),
118
+ row({ request: { id: request.id }, decision: 'DENY', reason: '' }, 2)
119
+ ]
120
+
121
+ const card = await targets.accessDecisionEntryTarget().check(rows, { state: state(park) })
122
+
123
+ for (const [index, one] of rows.entries()) {
124
+ const screen = await access.reviewDecision(targets.decisionOf(one), { state: state(park) } as any)
125
+ expect(card[index].map((issue: any) => [issue.code, issue.blocking])).toEqual(screen.map((issue: any) => [issue.code, issue.blocking]))
126
+ }
127
+ expect(card[0].map((issue: any) => issue.code)).toContain('role-grants-admin')
128
+ expect(card[2].map((issue: any) => issue.code)).toEqual(['deny-needs-reason'])
129
+ })
130
+
131
+ it('★ the request card refuses what the door would - already held', async () => {
132
+ const lee = await getRepository(User).save({
133
+ username: 'lee', email: 'lee@example.com', name: 'lee', salt: User.generateSalt(), status: 'activated', domains: [domain], roles: [inbound]
134
+ })
135
+ const [issues] = await targets.accessRequestEntryTarget().check([row({ category: 'warehouse', privilege: 'mutation' })], { state: state(lee) })
136
+ expect(issues).toEqual([expect.objectContaining({ code: 'already-holds', blocking: true })])
137
+ })
138
+ })
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Asking, deciding, telling - the access request end to end on the database (ADR-0103).
3
+ *
4
+ * The controller is called with a request state as the doors receive it. `notify` is a spy: the notification
5
+ * module is optional and the row is the record.
6
+ */
7
+
8
+ import { closeAuthDatabase, Domain, getRepository, openAuthDatabase, resetAuthDatabase } from './db'
9
+ import { loadCompiled } from './compiled'
10
+
11
+ const { Role } = loadCompiled('service/role/role')
12
+ const { Privilege } = loadCompiled('service/privilege/privilege')
13
+ const { User } = loadCompiled('service/user/user')
14
+ const { DomainOwner } = loadCompiled('service/domain-owner/domain-owner')
15
+ const { AccessRequest } = loadCompiled('service/access-request/access-request')
16
+ const access = loadCompiled('controllers/access-request')
17
+
18
+ let domain: any
19
+ let other: any
20
+ let warehouseMutation: any
21
+ let warehouseQuery: any
22
+ let userMutation: any
23
+ let inbound: any
24
+ let manager: any
25
+ let admins: any
26
+ let kim: any
27
+ let park: any
28
+ let owner: any
29
+
30
+ async function makeUser(name: string, domains: any[], roles: any[] = [], over: any = {}) {
31
+ const tag = Math.random().toString(36).slice(2, 8)
32
+ return await getRepository(User).save({
33
+ username: `${name}-${tag}`,
34
+ email: `${name}-${tag}@example.com`,
35
+ name,
36
+ salt: User.generateSalt(),
37
+ status: 'activated',
38
+ domains,
39
+ roles,
40
+ ...over
41
+ })
42
+ }
43
+
44
+ function contextOf(user: any, over: any = {}) {
45
+ const notify = jest.fn().mockResolvedValue(undefined)
46
+ const afterCommit: any[] = []
47
+ return {
48
+ state: { domain, user, afterCommit, notify, ...over },
49
+ t: (key: string) => key,
50
+ afterCommit,
51
+ notify
52
+ } as any
53
+ }
54
+
55
+ async function commit(context: any) {
56
+ for (const step of context.afterCommit) await step.run()
57
+ }
58
+
59
+ async function holds(user: any, category: string, privilege: string) {
60
+ return await User.hasPrivilege(privilege, category, domain, user)
61
+ }
62
+
63
+ beforeAll(async () => {
64
+ await openAuthDatabase()
65
+ })
66
+
67
+ afterAll(async () => {
68
+ await closeAuthDatabase()
69
+ })
70
+
71
+ beforeEach(async () => {
72
+ await resetAuthDatabase()
73
+
74
+ const saved = await getRepository(Domain).save({ name: 'Plant A', subdomain: 'plant-a' })
75
+ domain = await getRepository(Domain).findOneBy({ id: saved.id })
76
+ other = await getRepository(Domain).save({ name: 'Other', subdomain: 'other' })
77
+
78
+ warehouseMutation = await getRepository(Privilege).save({ name: 'mutation', category: 'warehouse' })
79
+ warehouseQuery = await getRepository(Privilege).save({ name: 'query', category: 'warehouse' })
80
+ userMutation = await getRepository(Privilege).save({ name: 'mutation', category: 'user' })
81
+
82
+ inbound = await getRepository(Role).save({ name: 'inbound', domain, privileges: [warehouseMutation] })
83
+ manager = await getRepository(Role).save({ name: 'manager', domain, privileges: [warehouseMutation, warehouseQuery, userMutation] })
84
+ admins = await getRepository(Role).save({ name: 'admins', domain, privileges: [userMutation, warehouseQuery] })
85
+
86
+ kim = await makeUser('kim', [domain])
87
+ park = await makeUser('park', [domain], [admins])
88
+ owner = await makeUser('owner', [domain])
89
+ await getRepository(DomainOwner).save({ domain, user: owner })
90
+ })
91
+
92
+ const ASK = { category: 'warehouse', privilege: 'mutation', operationName: 'updateInboundPlan', reason: 'inbound from today' }
93
+
94
+ describe('asking', () => {
95
+ it('★ a request is a row - pending, fourteen days, and the people who decide are told once', async () => {
96
+ const context = contextOf(kim)
97
+ const request = await access.requestAccess(ASK, context)
98
+ await commit(context)
99
+
100
+ expect(request).toMatchObject({ state: 'PENDING', category: 'warehouse', privilege: 'mutation', count: 1, reason: 'inbound from today' })
101
+ expect(context.notify).toHaveBeenCalledTimes(1)
102
+ expect([...context.notify.mock.calls[0][0].receivers].sort()).toEqual([owner.id, park.id].sort())
103
+ expect(context.notify.mock.calls[0][0].url).toBe(`access-requests?id=${request.id}`)
104
+ })
105
+
106
+ it('★ asking again adds to the pending one - no second row, nobody told again', async () => {
107
+ await access.requestAccess(ASK, contextOf(kim))
108
+ const again = contextOf(kim)
109
+ const merged = await access.requestAccess({ ...ASK, reason: 'still needed' }, again)
110
+ await commit(again)
111
+
112
+ expect(merged.count).toBe(2)
113
+ expect(merged.reason).toBe('still needed')
114
+ expect(await getRepository(AccessRequest).count()).toBe(1)
115
+ expect(again.notify).not.toHaveBeenCalled()
116
+ })
117
+
118
+ it('★ a privilege the caller holds is not asked for', async () => {
119
+ const kimWithRole = await makeUser('lee', [domain], [inbound])
120
+ await expect(access.requestAccess(ASK, contextOf(kimWithRole))).rejects.toMatchObject({ code: 'access-request-already-holds' })
121
+ })
122
+
123
+ it('★ refused by the license, not by a role - not taken, whatever the screen sent', async () => {
124
+ const context = contextOf(kim, { prohibitedPrivileges: [{ category: 'warehouse', privilege: 'mutation', by: 'license' }] })
125
+ await expect(access.requestAccess(ASK, context)).rejects.toMatchObject({ code: 'access-request-not-by-role', params: { because: 'license' } })
126
+ })
127
+
128
+ it('a privilege nobody declared is not asked for', async () => {
129
+ await expect(access.requestAccess({ category: 'nothing', privilege: 'here', reason: 'x' }, contextOf(kim))).rejects.toMatchObject({
130
+ code: 'access-request-unknown-privilege'
131
+ })
132
+ })
133
+
134
+ it('the requester withdraws their own, and nobody else can', async () => {
135
+ const request = await access.requestAccess(ASK, contextOf(kim))
136
+ await expect(access.withdrawAccessRequest(request.id, contextOf(park))).rejects.toMatchObject({ code: 'access-request-not-withdrawable' })
137
+ expect((await access.withdrawAccessRequest(request.id, contextOf(kim))).state).toBe('WITHDRAWN')
138
+ })
139
+ })
140
+
141
+ describe('who decides', () => {
142
+ it('★ owners and holders of user:mutation in this domain, never the requester', async () => {
143
+ const outsider = await makeUser('outsider', [other], [admins])
144
+ const ids = await access.findDeciderIds(domain, park.id)
145
+ expect(ids).toEqual([owner.id].sort())
146
+ expect(ids).not.toContain(outsider.id)
147
+ })
148
+ })
149
+
150
+ describe('deciding', () => {
151
+ it('★ grant puts the requester into the role - they pass the gate on the next request', async () => {
152
+ const request = await access.requestAccess(ASK, contextOf(kim))
153
+ const context = contextOf(park)
154
+ const decided = await access.decideAccessRequest({ requestId: request.id, decision: 'GRANT', roleId: inbound.id }, context)
155
+ await commit(context)
156
+
157
+ expect(decided).toMatchObject({ state: 'GRANTED', grantedRole: { id: inbound.id } })
158
+ expect(await holds(kim, 'warehouse', 'mutation')).toBe(true)
159
+ expect(context.notify).toHaveBeenCalledWith(
160
+ expect.objectContaining({ receivers: [kim.id], title: 'access-request.notify.granted.title', url: 'my-access-requests' })
161
+ )
162
+ })
163
+
164
+ it('★ deny keeps the reason and tells the requester', async () => {
165
+ const request = await access.requestAccess(ASK, contextOf(kim))
166
+ const context = contextOf(park)
167
+ const decided = await access.decideAccessRequest({ requestId: request.id, decision: 'DENY', reason: 'IT only' }, context)
168
+ await commit(context)
169
+
170
+ expect(decided).toMatchObject({ state: 'DENIED', decisionReason: 'IT only' })
171
+ expect(await holds(kim, 'warehouse', 'mutation')).toBe(false)
172
+ expect(context.notify).toHaveBeenCalledWith(expect.objectContaining({ title: 'access-request.notify.denied.title' }))
173
+ })
174
+
175
+ it('★ the second decision is refused - the first one stands', async () => {
176
+ const request = await access.requestAccess(ASK, contextOf(kim))
177
+ await access.decideAccessRequest({ requestId: request.id, decision: 'DENY', reason: 'no' }, contextOf(owner))
178
+ await expect(access.decideAccessRequest({ requestId: request.id, decision: 'GRANT', roleId: inbound.id }, contextOf(park))).rejects.toMatchObject({
179
+ code: 'access-decision-request-not-pending'
180
+ })
181
+ expect(await holds(kim, 'warehouse', 'mutation')).toBe(false)
182
+ })
183
+
184
+ it('★ two people deciding at once - exactly one wins (both reviews read PENDING before either writes)', async () => {
185
+ const request = await access.requestAccess(ASK, contextOf(kim))
186
+ const results = await Promise.allSettled([
187
+ access.decideAccessRequest({ requestId: request.id, decision: 'DENY', reason: 'no' }, contextOf(owner)),
188
+ access.decideAccessRequest({ requestId: request.id, decision: 'GRANT', roleId: inbound.id }, contextOf(park))
189
+ ])
190
+
191
+ expect(results.map(r => r.status).sort()).toEqual(['fulfilled', 'rejected'])
192
+ const lost = results.find(r => r.status === 'rejected') as PromiseRejectedResult
193
+ expect(lost.reason).toMatchObject({ code: 'access-decision-request-not-pending' })
194
+ })
195
+
196
+ it('★ the review blocks inside the door too - a role without the privilege is refused', async () => {
197
+ const request = await access.requestAccess(ASK, contextOf(kim))
198
+ await expect(access.decideAccessRequest({ requestId: request.id, decision: 'GRANT', roleId: admins.id }, contextOf(park))).rejects.toMatchObject({
199
+ code: 'access-decision-role-does-not-grant'
200
+ })
201
+ expect((await getRepository(AccessRequest).findOneBy({ id: request.id })).state).toBe('PENDING')
202
+ })
203
+
204
+ it('★ another tenant\'s role is refused - it is not this domain\'s to give', async () => {
205
+ const foreign = await getRepository(Role).save({ name: 'foreign', domain: other, privileges: [warehouseMutation] })
206
+ const request = await access.requestAccess(ASK, contextOf(kim))
207
+ await expect(access.decideAccessRequest({ requestId: request.id, decision: 'GRANT', roleId: foreign.id }, contextOf(park))).rejects.toMatchObject({
208
+ code: 'access-decision-role-not-assignable'
209
+ })
210
+ })
211
+
212
+ it('a request of another domain is not found from this one', async () => {
213
+ const request = await access.requestAccess(ASK, contextOf(kim))
214
+ const stranger = await makeUser('stranger', [other], [admins])
215
+ const fromThere = contextOf(stranger, { domain: await getRepository(Domain).findOneBy({ id: other.id }) })
216
+ await expect(access.decideAccessRequest({ requestId: request.id, decision: 'DENY', reason: 'x' }, fromThere)).rejects.toMatchObject({
217
+ code: 'access-decision-access-request-not-found'
218
+ })
219
+ })
220
+
221
+ it('★ a grant closes the same person\'s other requests it now answers', async () => {
222
+ const first = await access.requestAccess(ASK, contextOf(kim))
223
+ const second = await access.requestAccess({ category: 'warehouse', privilege: 'query', reason: 'checking stock' }, contextOf(kim))
224
+ await access.decideAccessRequest({ requestId: first.id, decision: 'GRANT', roleId: manager.id }, contextOf(owner))
225
+
226
+ expect((await getRepository(AccessRequest).findOneBy({ id: second.id })).state).toBe('GRANTED')
227
+ })
228
+ })
229
+
230
+ describe('the review as the screen asks it', () => {
231
+ it('★ candidates smallest first, and the review of a big role names what else it gives', async () => {
232
+ const request = await access.requestAccess(ASK, contextOf(kim))
233
+ const candidates = await access.rolesGranting('warehouse', 'mutation', domain)
234
+ expect(candidates.map((c: any) => c.name)).toEqual(['inbound', 'manager'])
235
+
236
+ const issues = await access.reviewDecision({ requestId: request.id, decision: 'GRANT', roleId: manager.id }, contextOf(park))
237
+ expect(issues.map((i: any) => i.code).sort()).toEqual(['decider-lacks-it', 'role-grants-admin', 'role-grants-more', 'smaller-role-exists'])
238
+ })
239
+ })
240
+
241
+ describe('asking is not a reflex (questions Q9)', () => {
242
+ it('★ no reason, no request - blank is no reason', async () => {
243
+ for (const reason of [undefined, '', ' ']) {
244
+ await expect(access.requestAccess({ ...ASK, reason }, contextOf(kim))).rejects.toMatchObject({ code: 'access-request-needs-reason' })
245
+ }
246
+ expect(await getRepository(AccessRequest).count()).toBe(0)
247
+ })
248
+
249
+ it('★ denied lately: the same words are refused, new words are taken', async () => {
250
+ const first = await access.requestAccess(ASK, contextOf(kim))
251
+ await access.decideAccessRequest({ requestId: first.id, decision: 'DENY', reason: 'IT only' }, contextOf(park))
252
+
253
+ await expect(access.requestAccess(ASK, contextOf(kim))).rejects.toMatchObject({
254
+ code: 'access-request-same-reason-as-denied',
255
+ params: { reason: 'IT only' }
256
+ })
257
+ const again = await access.requestAccess({ ...ASK, reason: 'moved to the inbound team this week' }, contextOf(kim))
258
+ expect(again.state).toBe('PENDING')
259
+ })
260
+
261
+ it('a denial older than seven days holds nothing against the same words', async () => {
262
+ const first = await access.requestAccess(ASK, contextOf(kim))
263
+ await access.decideAccessRequest({ requestId: first.id, decision: 'DENY', reason: 'not now' }, contextOf(park))
264
+ await getRepository(AccessRequest).update({ id: first.id }, { decidedAt: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000) })
265
+ expect((await access.requestAccess(ASK, contextOf(kim))).state).toBe('PENDING')
266
+ })
267
+
268
+ it('★ the popup can say how many people a request reaches - not who', async () => {
269
+ const { AccessRequestQuery } = loadCompiled('service/access-request/access-request-query')
270
+ expect(await new AccessRequestQuery().accessRequestDeciderCount(contextOf(kim))).toBe(2)
271
+ expect(await new AccessRequestQuery().accessRequestDeciderCount(contextOf(park))).toBe(1)
272
+ })
273
+ })
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The access request under real concurrency - postgres only (`AUTH_TEST_PG`). sqlite holds one connection and
3
+ * cannot show two transactions racing (feedback: verify concurrency on postgres).
4
+ *
5
+ * Each call runs in its own transaction, as the `@transaction` door gives it.
6
+ */
7
+ import { authDataSource, closeAuthDatabase, Domain, getRepository, openAuthDatabase, resetAuthDatabase } from './db'
8
+ import { loadCompiled } from './compiled'
9
+
10
+ const { Role } = loadCompiled('service/role/role')
11
+ const { Privilege } = loadCompiled('service/privilege/privilege')
12
+ const { User } = loadCompiled('service/user/user')
13
+ const { AccessRequest } = loadCompiled('service/access-request/access-request')
14
+ const access = loadCompiled('controllers/access-request')
15
+
16
+ const onPostgres = process.env.AUTH_TEST_PG ? describe : describe.skip
17
+
18
+ onPostgres('on postgres', () => {
19
+ let domain: any
20
+ let kim: any
21
+ let park: any
22
+ let owner: any
23
+ let inbound: any
24
+
25
+ const inTransaction = <T>(user: any, run: (context: any) => Promise<T>) =>
26
+ authDataSource().transaction(tx => run({ state: { domain, user, tx, afterCommit: [] }, t: (key: string) => key }))
27
+
28
+ beforeAll(async () => {
29
+ await openAuthDatabase()
30
+ })
31
+
32
+ afterAll(async () => {
33
+ await closeAuthDatabase()
34
+ })
35
+
36
+ beforeEach(async () => {
37
+ await resetAuthDatabase()
38
+ domain = await getRepository(Domain).findOneBy({ id: (await getRepository(Domain).save({ name: 'Plant A', subdomain: 'plant-a' })).id })
39
+ const mutation = await getRepository(Privilege).save({ name: 'mutation', category: 'warehouse' })
40
+ const grant = await getRepository(Privilege).save({ name: 'mutation', category: 'user' })
41
+ inbound = await getRepository(Role).save({ name: 'inbound', domain, privileges: [mutation] })
42
+ const admins = await getRepository(Role).save({ name: 'admins', domain, privileges: [grant] })
43
+ const make = (name: string, roles: any[] = []) =>
44
+ getRepository(User).save({ username: name, email: `${name}@example.com`, name, salt: User.generateSalt(), status: 'activated', domains: [domain], roles })
45
+ kim = await make('kim')
46
+ park = await make('park', [admins])
47
+ owner = await make('owner', [admins])
48
+ })
49
+
50
+ it('★ two people deciding at once, each in a transaction - exactly one wins, and the loser leaves nothing', async () => {
51
+ const request = await inTransaction(kim, context => access.requestAccess({ category: 'warehouse', privilege: 'mutation', reason: 'inbound' }, context))
52
+
53
+ const results = await Promise.allSettled([
54
+ inTransaction(owner, context => access.decideAccessRequest({ requestId: request.id, decision: 'DENY', reason: 'no' }, context)),
55
+ inTransaction(park, context => access.decideAccessRequest({ requestId: request.id, decision: 'GRANT', roleId: inbound.id }, context))
56
+ ])
57
+
58
+ expect(results.map(r => r.status).sort()).toEqual(['fulfilled', 'rejected'])
59
+ const stored = await getRepository(AccessRequest).findOne({ where: { id: request.id }, relations: ['grantedRole'] })
60
+ const holds = await User.hasPrivilege('mutation', 'warehouse', domain, kim)
61
+ /* The role is given exactly when the stored decision is a grant - a losing grant does not leave the role behind. */
62
+ expect(holds).toBe(stored.state === 'GRANTED')
63
+ })
64
+
65
+ it('★ the same person asking twice at once - one pending request, not two', async () => {
66
+ await Promise.allSettled([
67
+ inTransaction(kim, context => access.requestAccess({ category: 'warehouse', privilege: 'mutation', reason: 'inbound' }, context)),
68
+ inTransaction(kim, context => access.requestAccess({ category: 'warehouse', privilege: 'mutation', reason: 'inbound' }, context))
69
+ ])
70
+ expect(await getRepository(AccessRequest).count({ where: { state: 'PENDING' } })).toBe(1)
71
+ })
72
+ })