@app-vitals/agent-admin 1.61.0 → 1.63.0
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.
- package/package.json +2 -2
- package/prisma/client/browser.ts +5 -0
- package/prisma/client/client.ts +5 -0
- package/prisma/client/internal/class.ts +14 -4
- package/prisma/client/internal/prismaNamespace.ts +94 -1
- package/prisma/client/internal/prismaNamespaceBrowser.ts +18 -0
- package/prisma/client/models/Account.ts +164 -0
- package/prisma/client/models/SlackConfigToken.ts +1574 -0
- package/prisma/client/models.ts +1 -0
- package/prisma/migrations/20261115000000_add_slack_config_token/migration.sql +34 -0
- package/prisma/schema/schema.prisma +33 -1
- package/src/slack-config-token.integration.test.ts +605 -0
- package/src/slack-config-token.ts +433 -0
package/prisma/client/models.ts
CHANGED
|
@@ -23,6 +23,7 @@ export type * from './models/AgentMember.ts'
|
|
|
23
23
|
export type * from './models/Account.ts'
|
|
24
24
|
export type * from './models/AgentTemplate.ts'
|
|
25
25
|
export type * from './models/AgentTemplateItem.ts'
|
|
26
|
+
export type * from './models/SlackConfigToken.ts'
|
|
26
27
|
export type * from './models/AccountMember.ts'
|
|
27
28
|
export type * from './models/AccountInvite.ts'
|
|
28
29
|
export type * from './models/AgentCronRun.ts'
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
-- SlackConfigToken: Slack app-configuration token per scope (account or
|
|
2
|
+
-- deployment-wide default). Additive only: one new table.
|
|
3
|
+
-- CreateTable
|
|
4
|
+
CREATE TABLE "SlackConfigToken" (
|
|
5
|
+
"id" TEXT NOT NULL,
|
|
6
|
+
"accountId" TEXT,
|
|
7
|
+
"refreshTokenEncrypted" TEXT NOT NULL,
|
|
8
|
+
"accessTokenEncrypted" TEXT,
|
|
9
|
+
"accessTokenExpiresAt" TIMESTAMP(3),
|
|
10
|
+
"slackTeamId" TEXT,
|
|
11
|
+
"slackUserId" TEXT,
|
|
12
|
+
"lastRotatedAt" TIMESTAMP(3),
|
|
13
|
+
"lastError" TEXT,
|
|
14
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
15
|
+
"updatedAt" TIMESTAMP(3) NOT NULL,
|
|
16
|
+
|
|
17
|
+
CONSTRAINT "SlackConfigToken_pkey" PRIMARY KEY ("id")
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
-- CreateIndex
|
|
21
|
+
CREATE INDEX "SlackConfigToken_accountId_idx" ON "SlackConfigToken"("accountId");
|
|
22
|
+
|
|
23
|
+
-- AddForeignKey
|
|
24
|
+
ALTER TABLE "SlackConfigToken" ADD CONSTRAINT "SlackConfigToken_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
25
|
+
|
|
26
|
+
-- Partial unique indexes (not expressible in Prisma; see the SlackConfigToken
|
|
27
|
+
-- comment in schema.prisma). Together they allow at most one row per scope with
|
|
28
|
+
-- NULL treated as a value, which a plain UNIQUE index would not do since NULLs
|
|
29
|
+
-- compare distinct.
|
|
30
|
+
-- CreateIndex
|
|
31
|
+
CREATE UNIQUE INDEX "SlackConfigToken_accountId_key" ON "SlackConfigToken"("accountId") WHERE "accountId" IS NOT NULL;
|
|
32
|
+
|
|
33
|
+
-- CreateIndex
|
|
34
|
+
CREATE UNIQUE INDEX "SlackConfigToken_global_key" ON "SlackConfigToken"((1)) WHERE "accountId" IS NULL;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Shipwright — Admin Service Schema
|
|
2
2
|
// Owns: Agent, AgentEnv, AgentCronJob, AgentTool, AgentToken, AgentPlugin,
|
|
3
|
-
// AgentMarketplace, AgentTemplate, AgentTemplateItem,
|
|
3
|
+
// AgentMarketplace, AgentTemplate, AgentTemplateItem, SlackConfigToken,
|
|
4
4
|
// plus the coding-owned models in coding.prisma (AgentWorkQueueSnapshot,
|
|
5
5
|
// AgentPhaseMethodology, SessionFollow, SessionAlertState).
|
|
6
6
|
// Agent is a first-class model (standalone, not embedded in a User model).
|
|
@@ -293,6 +293,7 @@ model Account {
|
|
|
293
293
|
invites AccountInvite[]
|
|
294
294
|
templates AgentTemplate[]
|
|
295
295
|
githubEnterpriseApps GitHubEnterpriseApp[]
|
|
296
|
+
slackConfigTokens SlackConfigToken[]
|
|
296
297
|
}
|
|
297
298
|
|
|
298
299
|
// ─── Agent Templates ──────────────────────────────────────────────────────────
|
|
@@ -343,6 +344,37 @@ model AgentTemplateItem {
|
|
|
343
344
|
@@unique([templateId, kind, key])
|
|
344
345
|
}
|
|
345
346
|
|
|
347
|
+
// ─── Slack Config Token ───────────────────────────────────────────────────────
|
|
348
|
+
// Slack app-configuration token pair (refresh + short-lived access token) used
|
|
349
|
+
// to manage Slack apps. accountId null = deployment-wide default; an account
|
|
350
|
+
// row overrides the default for that account. Tokens are AES-256-GCM encrypted
|
|
351
|
+
// at the service layer (admin/src/slack-config-token.ts) and never read back.
|
|
352
|
+
//
|
|
353
|
+
// UNIQUENESS: at most one row per scope, with NULL treated as a value. Prisma
|
|
354
|
+
// cannot express partial unique indexes, so they are hand-written in
|
|
355
|
+
// 20261115000000_add_slack_config_token/migration.sql:
|
|
356
|
+
// SlackConfigToken_accountId_key (accountId set)
|
|
357
|
+
// SlackConfigToken_global_key (accountId NULL)
|
|
358
|
+
// Prisma's schema diff does not see them, so keep them when editing this
|
|
359
|
+
// model and re-create them by hand if the table is ever rebuilt.
|
|
360
|
+
|
|
361
|
+
model SlackConfigToken {
|
|
362
|
+
id String @id @default(cuid())
|
|
363
|
+
accountId String?
|
|
364
|
+
account Account? @relation(fields: [accountId], references: [id], onDelete: Cascade)
|
|
365
|
+
refreshTokenEncrypted String
|
|
366
|
+
accessTokenEncrypted String?
|
|
367
|
+
accessTokenExpiresAt DateTime?
|
|
368
|
+
slackTeamId String?
|
|
369
|
+
slackUserId String?
|
|
370
|
+
lastRotatedAt DateTime?
|
|
371
|
+
lastError String?
|
|
372
|
+
createdAt DateTime @default(now())
|
|
373
|
+
updatedAt DateTime @updatedAt
|
|
374
|
+
|
|
375
|
+
@@index([accountId])
|
|
376
|
+
}
|
|
377
|
+
|
|
346
378
|
model AccountMember {
|
|
347
379
|
id String @id @default(cuid())
|
|
348
380
|
accountId String
|
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration tests for SlackConfigTokenService against a real PostgreSQL DB.
|
|
3
|
+
*
|
|
4
|
+
* Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
|
8
|
+
import type { PrismaClient } from "../prisma/client/client.ts";
|
|
9
|
+
import type { Clock } from "./clock.ts";
|
|
10
|
+
import { createAdminPrismaClient } from "./prisma-client.ts";
|
|
11
|
+
import {
|
|
12
|
+
isSlackConfigTokenRevokedError,
|
|
13
|
+
SlackConfigRefreshTokenInvalidError,
|
|
14
|
+
SlackConfigTokenEncryptionUnavailableError,
|
|
15
|
+
SlackConfigTokenNotConfiguredError,
|
|
16
|
+
SlackConfigTokenService,
|
|
17
|
+
toSlackConfigTokenMetadata,
|
|
18
|
+
} from "./slack-config-token.ts";
|
|
19
|
+
import {
|
|
20
|
+
type SlackConfigTokenClient,
|
|
21
|
+
SlackConfigTokenError,
|
|
22
|
+
} from "./slack-provisioning-client.ts";
|
|
23
|
+
import { makeStrictTokenCrypto, type TokenCrypto } from "./token-crypto.ts";
|
|
24
|
+
|
|
25
|
+
const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
|
|
26
|
+
const describeOrSkip = TEST_DB ? describe : describe.skip;
|
|
27
|
+
|
|
28
|
+
const KEY = "a".repeat(64);
|
|
29
|
+
const REFRESH = "test-refresh-SUPERSECRET";
|
|
30
|
+
const ACCESS = "test-access-SUPERSECRET";
|
|
31
|
+
|
|
32
|
+
describeOrSkip("SlackConfigTokenService (integration)", () => {
|
|
33
|
+
let prisma: PrismaClient;
|
|
34
|
+
let service: SlackConfigTokenService;
|
|
35
|
+
let acctA: string;
|
|
36
|
+
let acctB: string;
|
|
37
|
+
|
|
38
|
+
beforeEach(async () => {
|
|
39
|
+
prisma = createAdminPrismaClient(TEST_DB as string);
|
|
40
|
+
await prisma.slackConfigToken.deleteMany();
|
|
41
|
+
await prisma.agentTemplateItem.deleteMany();
|
|
42
|
+
await prisma.agentTemplate.deleteMany();
|
|
43
|
+
await prisma.agent.deleteMany();
|
|
44
|
+
await prisma.accountInvite.deleteMany();
|
|
45
|
+
await prisma.accountMember.deleteMany();
|
|
46
|
+
await prisma.account.deleteMany();
|
|
47
|
+
acctA = (await prisma.account.create({ data: { name: "A" } })).id;
|
|
48
|
+
acctB = (await prisma.account.create({ data: { name: "B" } })).id;
|
|
49
|
+
service = new SlackConfigTokenService(prisma, makeStrictTokenCrypto(KEY));
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
afterEach(async () => {
|
|
53
|
+
await prisma.$disconnect();
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("returns null / empty when nothing is saved", async () => {
|
|
57
|
+
expect(await service.get(null)).toBeNull();
|
|
58
|
+
expect(await service.get(acctA)).toBeNull();
|
|
59
|
+
expect(await service.resolveForAccount(acctA)).toBeNull();
|
|
60
|
+
expect(await service.list()).toEqual([]);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("saves, gets and clears per scope; metadata only", async () => {
|
|
64
|
+
const exp = new Date("2030-01-01T00:00:00Z");
|
|
65
|
+
const saved = await service.save(acctA, {
|
|
66
|
+
refreshToken: REFRESH,
|
|
67
|
+
accessToken: ACCESS,
|
|
68
|
+
accessTokenExpiresAt: exp,
|
|
69
|
+
slackTeamId: "T1",
|
|
70
|
+
slackUserId: "U1",
|
|
71
|
+
});
|
|
72
|
+
expect(saved).toMatchObject({
|
|
73
|
+
accountId: acctA,
|
|
74
|
+
refreshTokenSet: true,
|
|
75
|
+
accessTokenSet: true,
|
|
76
|
+
slackTeamId: "T1",
|
|
77
|
+
slackUserId: "U1",
|
|
78
|
+
});
|
|
79
|
+
expect(saved.accessTokenExpiresAt).toEqual(exp);
|
|
80
|
+
expect(saved.lastRotatedAt).not.toBeNull();
|
|
81
|
+
const got = await service.get(acctA);
|
|
82
|
+
expect(got?.id).toBe(saved.id);
|
|
83
|
+
for (const out of [saved, got, await service.list()]) {
|
|
84
|
+
const json = JSON.stringify(out);
|
|
85
|
+
expect(json).not.toContain("SUPERSECRET");
|
|
86
|
+
expect(json).not.toContain("Encrypted");
|
|
87
|
+
}
|
|
88
|
+
// stored encrypted, not plain
|
|
89
|
+
const raw = await prisma.slackConfigToken.findFirstOrThrow({
|
|
90
|
+
where: { accountId: acctA },
|
|
91
|
+
});
|
|
92
|
+
expect(raw.refreshTokenEncrypted).not.toContain("SUPERSECRET");
|
|
93
|
+
expect(raw.accessTokenEncrypted).not.toContain("SUPERSECRET");
|
|
94
|
+
|
|
95
|
+
await service.clear(acctA);
|
|
96
|
+
expect(await service.get(acctA)).toBeNull();
|
|
97
|
+
await service.clear(acctA); // no-op
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("allows a token with no access token", async () => {
|
|
101
|
+
const saved = await service.save(null, { refreshToken: REFRESH });
|
|
102
|
+
expect(saved.accessTokenSet).toBe(false);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it("upserts one row per scope, including two NULL-scope saves", async () => {
|
|
106
|
+
const first = await service.save(null, { refreshToken: REFRESH });
|
|
107
|
+
const second = await service.save(null, {
|
|
108
|
+
refreshToken: "test-refresh-OTHER",
|
|
109
|
+
slackTeamId: "T2",
|
|
110
|
+
});
|
|
111
|
+
expect(second.id).toBe(first.id);
|
|
112
|
+
expect(second.slackTeamId).toBe("T2");
|
|
113
|
+
expect(
|
|
114
|
+
await prisma.slackConfigToken.count({ where: { accountId: null } }),
|
|
115
|
+
).toBe(1);
|
|
116
|
+
|
|
117
|
+
const a1 = await service.save(acctA, { refreshToken: REFRESH });
|
|
118
|
+
const a2 = await service.save(acctA, { refreshToken: REFRESH });
|
|
119
|
+
expect(a2.id).toBe(a1.id);
|
|
120
|
+
await service.save(acctB, { refreshToken: REFRESH });
|
|
121
|
+
expect(await prisma.slackConfigToken.count()).toBe(3);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("enforces both partial unique indexes at the database", async () => {
|
|
125
|
+
const base = { refreshTokenEncrypted: "x" };
|
|
126
|
+
await prisma.slackConfigToken.create({
|
|
127
|
+
data: { ...base, accountId: null },
|
|
128
|
+
});
|
|
129
|
+
await expect(
|
|
130
|
+
(async () =>
|
|
131
|
+
prisma.slackConfigToken.create({
|
|
132
|
+
data: { ...base, accountId: null },
|
|
133
|
+
}))(),
|
|
134
|
+
).rejects.toThrow();
|
|
135
|
+
await prisma.slackConfigToken.create({
|
|
136
|
+
data: { ...base, accountId: acctA },
|
|
137
|
+
});
|
|
138
|
+
await expect(
|
|
139
|
+
(async () =>
|
|
140
|
+
prisma.slackConfigToken.create({
|
|
141
|
+
data: { ...base, accountId: acctA },
|
|
142
|
+
}))(),
|
|
143
|
+
).rejects.toThrow();
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("resolveForAccount prefers the account row, then default, then null", async () => {
|
|
147
|
+
expect(await service.resolveForAccount(acctA)).toBeNull();
|
|
148
|
+
const def = await service.save(null, { refreshToken: REFRESH });
|
|
149
|
+
expect((await service.resolveForAccount(acctA))?.id).toBe(def.id);
|
|
150
|
+
const own = await service.save(acctA, { refreshToken: REFRESH });
|
|
151
|
+
expect((await service.resolveForAccount(acctA))?.id).toBe(own.id);
|
|
152
|
+
expect((await service.resolveForAccount(acctB))?.id).toBe(def.id);
|
|
153
|
+
await service.clear(null);
|
|
154
|
+
await service.clear(acctA);
|
|
155
|
+
expect(await service.resolveForAccount(acctA)).toBeNull();
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
it("clears only the targeted scope", async () => {
|
|
159
|
+
await service.save(null, { refreshToken: REFRESH });
|
|
160
|
+
await service.save(acctA, { refreshToken: REFRESH });
|
|
161
|
+
await service.clear(acctA);
|
|
162
|
+
expect(await service.get(null)).not.toBeNull();
|
|
163
|
+
expect(await service.get(acctA)).toBeNull();
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("deleting an account cascades its token", async () => {
|
|
167
|
+
await service.save(acctA, { refreshToken: REFRESH });
|
|
168
|
+
await prisma.account.delete({ where: { id: acctA } });
|
|
169
|
+
expect(await prisma.slackConfigToken.count()).toBe(0);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it("refuses to save without an encryption key", async () => {
|
|
173
|
+
const noKey = new SlackConfigTokenService(prisma, null);
|
|
174
|
+
await expect(
|
|
175
|
+
noKey.save(null, { refreshToken: REFRESH }),
|
|
176
|
+
).rejects.toBeInstanceOf(SlackConfigTokenEncryptionUnavailableError);
|
|
177
|
+
expect(await prisma.slackConfigToken.count()).toBe(0);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
describe("toSlackConfigTokenMetadata", () => {
|
|
182
|
+
it("never includes secret fields", () => {
|
|
183
|
+
const now = new Date();
|
|
184
|
+
const out = toSlackConfigTokenMetadata({
|
|
185
|
+
id: "i",
|
|
186
|
+
accountId: null,
|
|
187
|
+
refreshTokenEncrypted: "SECRETREFRESHCIPHER",
|
|
188
|
+
accessTokenEncrypted: "SECRETACCESSCIPHER",
|
|
189
|
+
accessTokenExpiresAt: now,
|
|
190
|
+
slackTeamId: "T",
|
|
191
|
+
slackUserId: "U",
|
|
192
|
+
lastRotatedAt: now,
|
|
193
|
+
lastError: null,
|
|
194
|
+
createdAt: now,
|
|
195
|
+
updatedAt: now,
|
|
196
|
+
});
|
|
197
|
+
expect(Object.keys(out).sort()).toEqual(
|
|
198
|
+
[
|
|
199
|
+
"id",
|
|
200
|
+
"accountId",
|
|
201
|
+
"refreshTokenSet",
|
|
202
|
+
"accessTokenSet",
|
|
203
|
+
"accessTokenExpiresAt",
|
|
204
|
+
"slackTeamId",
|
|
205
|
+
"slackUserId",
|
|
206
|
+
"lastRotatedAt",
|
|
207
|
+
"lastError",
|
|
208
|
+
"createdAt",
|
|
209
|
+
"updatedAt",
|
|
210
|
+
].sort(),
|
|
211
|
+
);
|
|
212
|
+
expect(JSON.stringify(out)).not.toContain("SECRET");
|
|
213
|
+
expect(out.refreshTokenSet).toBe(true);
|
|
214
|
+
expect(out.accessTokenSet).toBe(true);
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
// ─── getAccessToken / withSlackConfigAccessToken ─────────────────────────────
|
|
219
|
+
|
|
220
|
+
class MutableClock implements Clock {
|
|
221
|
+
constructor(public current: Date) {}
|
|
222
|
+
now(): Date {
|
|
223
|
+
return new Date(this.current);
|
|
224
|
+
}
|
|
225
|
+
advance(ms: number): void {
|
|
226
|
+
this.current = new Date(this.current.getTime() + ms);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
type RotateResult = Awaited<
|
|
231
|
+
ReturnType<SlackConfigTokenClient["rotateConfigToken"]>
|
|
232
|
+
>;
|
|
233
|
+
|
|
234
|
+
/** Rotate client double: hands out a fresh numbered pair per call. */
|
|
235
|
+
class FakeRotateClient implements SlackConfigTokenClient {
|
|
236
|
+
calls: string[] = [];
|
|
237
|
+
delayMs = 0;
|
|
238
|
+
failWith: SlackConfigTokenError | null = null;
|
|
239
|
+
constructor(private clock: Clock) {}
|
|
240
|
+
async rotateConfigToken(refreshToken: string): Promise<RotateResult> {
|
|
241
|
+
this.calls.push(refreshToken);
|
|
242
|
+
const n = this.calls.length;
|
|
243
|
+
if (this.delayMs) await new Promise((r) => setTimeout(r, this.delayMs));
|
|
244
|
+
if (this.failWith) throw this.failWith;
|
|
245
|
+
const iat = Math.floor(this.clock.now().getTime() / 1000);
|
|
246
|
+
return {
|
|
247
|
+
accessToken: `rotated-access-${n}-SUPERSECRET`,
|
|
248
|
+
refreshToken: `rotated-refresh-${n}-SUPERSECRET`,
|
|
249
|
+
teamId: `T${n}`,
|
|
250
|
+
userId: `U${n}`,
|
|
251
|
+
iat,
|
|
252
|
+
exp: iat + 12 * 3600,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const MIN = 60_000;
|
|
258
|
+
|
|
259
|
+
describeOrSkip("SlackConfigTokenService.getAccessToken (integration)", () => {
|
|
260
|
+
let prisma: PrismaClient;
|
|
261
|
+
let crypto: TokenCrypto;
|
|
262
|
+
let clock: MutableClock;
|
|
263
|
+
let rotate: FakeRotateClient;
|
|
264
|
+
let service: SlackConfigTokenService;
|
|
265
|
+
let acctA: string;
|
|
266
|
+
|
|
267
|
+
const row = (accountId: string | null) =>
|
|
268
|
+
prisma.slackConfigToken.findFirstOrThrow({ where: { accountId } });
|
|
269
|
+
|
|
270
|
+
beforeEach(async () => {
|
|
271
|
+
prisma = createAdminPrismaClient(TEST_DB as string);
|
|
272
|
+
await prisma.slackConfigToken.deleteMany();
|
|
273
|
+
await prisma.agentTemplateItem.deleteMany();
|
|
274
|
+
await prisma.agentTemplate.deleteMany();
|
|
275
|
+
await prisma.agent.deleteMany();
|
|
276
|
+
await prisma.accountInvite.deleteMany();
|
|
277
|
+
await prisma.accountMember.deleteMany();
|
|
278
|
+
await prisma.account.deleteMany();
|
|
279
|
+
acctA = (await prisma.account.create({ data: { name: "A" } })).id;
|
|
280
|
+
crypto = makeStrictTokenCrypto(KEY) as TokenCrypto;
|
|
281
|
+
// Whole seconds so exp (unix seconds) round-trips exactly.
|
|
282
|
+
clock = new MutableClock(new Date("2030-01-01T00:00:00Z"));
|
|
283
|
+
rotate = new FakeRotateClient(clock);
|
|
284
|
+
service = new SlackConfigTokenService(prisma, crypto, clock, rotate);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
afterEach(async () => {
|
|
288
|
+
await prisma.$disconnect();
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
it("cache hit: returns the stored access token without calling Slack", async () => {
|
|
292
|
+
await service.save(acctA, {
|
|
293
|
+
refreshToken: REFRESH,
|
|
294
|
+
accessToken: ACCESS,
|
|
295
|
+
accessTokenExpiresAt: new Date(clock.now().getTime() + 11 * MIN),
|
|
296
|
+
});
|
|
297
|
+
expect(await service.getAccessToken(acctA)).toBe(ACCESS);
|
|
298
|
+
expect(rotate.calls).toEqual([]);
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it("rotates when the cached token has 10 minutes or less left, persisting the new pair", async () => {
|
|
302
|
+
await service.save(null, {
|
|
303
|
+
refreshToken: REFRESH,
|
|
304
|
+
accessToken: ACCESS,
|
|
305
|
+
accessTokenExpiresAt: new Date(clock.now().getTime() + 10 * MIN),
|
|
306
|
+
});
|
|
307
|
+
clock.advance(MIN);
|
|
308
|
+
const token = await service.getAccessToken(null);
|
|
309
|
+
expect(token).toBe("rotated-access-1-SUPERSECRET");
|
|
310
|
+
expect(rotate.calls).toEqual([REFRESH]);
|
|
311
|
+
|
|
312
|
+
const r = await row(null);
|
|
313
|
+
expect(crypto.decrypt(r.refreshTokenEncrypted)).toBe(
|
|
314
|
+
"rotated-refresh-1-SUPERSECRET",
|
|
315
|
+
);
|
|
316
|
+
expect(crypto.decrypt(r.accessTokenEncrypted as string)).toBe(token);
|
|
317
|
+
expect(r.accessTokenExpiresAt).toEqual(
|
|
318
|
+
new Date(clock.now().getTime() + 12 * 3600 * 1000),
|
|
319
|
+
);
|
|
320
|
+
expect(r.slackTeamId).toBe("T1");
|
|
321
|
+
expect(r.slackUserId).toBe("U1");
|
|
322
|
+
expect(r.lastRotatedAt).toEqual(clock.now());
|
|
323
|
+
expect(r.lastError).toBeNull();
|
|
324
|
+
|
|
325
|
+
// The persisted token is now a cache hit.
|
|
326
|
+
expect(await service.getAccessToken(null)).toBe(token);
|
|
327
|
+
expect(rotate.calls.length).toBe(1);
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
it("rotates when no access token is cached", async () => {
|
|
331
|
+
await service.save(acctA, { refreshToken: REFRESH });
|
|
332
|
+
expect(await service.getAccessToken(acctA)).toBe(
|
|
333
|
+
"rotated-access-1-SUPERSECRET",
|
|
334
|
+
);
|
|
335
|
+
expect(rotate.calls).toEqual([REFRESH]);
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
it("uses the exact scope row only", async () => {
|
|
339
|
+
await service.save(null, { refreshToken: REFRESH });
|
|
340
|
+
await expect(service.getAccessToken(acctA)).rejects.toBeInstanceOf(
|
|
341
|
+
SlackConfigTokenNotConfiguredError,
|
|
342
|
+
);
|
|
343
|
+
expect(rotate.calls).toEqual([]);
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
it("serializes concurrent callers on a stale token: exactly one rotate, same token for all", async () => {
|
|
347
|
+
await service.save(acctA, {
|
|
348
|
+
refreshToken: REFRESH,
|
|
349
|
+
accessToken: ACCESS,
|
|
350
|
+
accessTokenExpiresAt: new Date(clock.now().getTime() - MIN),
|
|
351
|
+
});
|
|
352
|
+
rotate.delayMs = 150;
|
|
353
|
+
const results = await Promise.all(
|
|
354
|
+
Array.from({ length: 5 }, () => service.getAccessToken(acctA)),
|
|
355
|
+
);
|
|
356
|
+
expect(rotate.calls).toEqual([REFRESH]);
|
|
357
|
+
expect(new Set(results)).toEqual(new Set(["rotated-access-1-SUPERSECRET"]));
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
it("serializes across service instances (replicas) too", async () => {
|
|
361
|
+
await service.save(acctA, { refreshToken: REFRESH });
|
|
362
|
+
rotate.delayMs = 150;
|
|
363
|
+
const other = new SlackConfigTokenService(
|
|
364
|
+
createAdminPrismaClient(TEST_DB as string),
|
|
365
|
+
crypto,
|
|
366
|
+
clock,
|
|
367
|
+
rotate,
|
|
368
|
+
);
|
|
369
|
+
const results = await Promise.all([
|
|
370
|
+
service.getAccessToken(acctA),
|
|
371
|
+
other.getAccessToken(acctA),
|
|
372
|
+
service.getAccessToken(acctA),
|
|
373
|
+
]);
|
|
374
|
+
expect(rotate.calls.length).toBe(1);
|
|
375
|
+
expect(new Set(results).size).toBe(1);
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
it("does not return the token when persisting the rotated pair fails", async () => {
|
|
379
|
+
// A crypto whose ciphertext for the new refresh token contains a NUL byte,
|
|
380
|
+
// which Postgres rejects in a TEXT column: a real write failure.
|
|
381
|
+
const failing: TokenCrypto = {
|
|
382
|
+
encrypt: (t) =>
|
|
383
|
+
t.startsWith("rotated-refresh-")
|
|
384
|
+
? "bad\u0000cipher"
|
|
385
|
+
: crypto.encrypt(t),
|
|
386
|
+
decrypt: (t) => crypto.decrypt(t),
|
|
387
|
+
};
|
|
388
|
+
await service.save(acctA, { refreshToken: REFRESH });
|
|
389
|
+
const broken = new SlackConfigTokenService(prisma, failing, clock, rotate);
|
|
390
|
+
let caught: unknown;
|
|
391
|
+
try {
|
|
392
|
+
await broken.getAccessToken(acctA);
|
|
393
|
+
} catch (err) {
|
|
394
|
+
caught = err;
|
|
395
|
+
}
|
|
396
|
+
expect(caught).toBeInstanceOf(Error);
|
|
397
|
+
expect(String((caught as Error).message)).not.toContain("SUPERSECRET");
|
|
398
|
+
expect(rotate.calls.length).toBe(1);
|
|
399
|
+
// Rolled back: the original pair is still stored.
|
|
400
|
+
const r = await row(acctA);
|
|
401
|
+
expect(crypto.decrypt(r.refreshTokenEncrypted)).toBe(REFRESH);
|
|
402
|
+
expect(r.accessTokenEncrypted).toBeNull();
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
it("invalid_refresh_token records lastError and surfaces a regenerate error", async () => {
|
|
406
|
+
await service.save(acctA, {
|
|
407
|
+
refreshToken: REFRESH,
|
|
408
|
+
accessToken: ACCESS,
|
|
409
|
+
accessTokenExpiresAt: new Date(clock.now().getTime() - MIN),
|
|
410
|
+
});
|
|
411
|
+
const before = await row(acctA);
|
|
412
|
+
rotate.failWith = new SlackConfigTokenError(
|
|
413
|
+
"invalid_refresh_token",
|
|
414
|
+
"Slack tooling.tokens.rotate failed: invalid_refresh_token",
|
|
415
|
+
);
|
|
416
|
+
let caught: unknown;
|
|
417
|
+
try {
|
|
418
|
+
await service.getAccessToken(acctA);
|
|
419
|
+
} catch (err) {
|
|
420
|
+
caught = err;
|
|
421
|
+
}
|
|
422
|
+
expect(caught).toBeInstanceOf(SlackConfigRefreshTokenInvalidError);
|
|
423
|
+
const msg = (caught as Error).message;
|
|
424
|
+
expect(msg).toMatch(/regenerate/i);
|
|
425
|
+
expect(msg).not.toContain("SUPERSECRET");
|
|
426
|
+
const after = await row(acctA);
|
|
427
|
+
expect(after.lastError).toContain("invalid_refresh_token");
|
|
428
|
+
expect(after.lastError).not.toContain("SUPERSECRET");
|
|
429
|
+
// Token material untouched.
|
|
430
|
+
expect(after.refreshTokenEncrypted).toBe(before.refreshTokenEncrypted);
|
|
431
|
+
expect(after.accessTokenEncrypted).toBe(before.accessTokenEncrypted);
|
|
432
|
+
expect((await service.get(acctA))?.lastError).toBe(after.lastError);
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
it("other rotate errors record the code without touching tokens", async () => {
|
|
436
|
+
await service.save(null, { refreshToken: REFRESH });
|
|
437
|
+
const before = await row(null);
|
|
438
|
+
rotate.failWith = new SlackConfigTokenError(
|
|
439
|
+
"http_error",
|
|
440
|
+
"Slack tooling.tokens.rotate HTTP error: 503 Service Unavailable",
|
|
441
|
+
);
|
|
442
|
+
await expect(service.getAccessToken(null)).rejects.toThrow(/http_error/);
|
|
443
|
+
const after = await row(null);
|
|
444
|
+
expect(after.lastError).toContain("http_error");
|
|
445
|
+
expect(after.refreshTokenEncrypted).toBe(before.refreshTokenEncrypted);
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
it("a successful rotate clears a previous lastError", async () => {
|
|
449
|
+
await service.save(null, { refreshToken: REFRESH });
|
|
450
|
+
rotate.failWith = new SlackConfigTokenError("http_error", "boom");
|
|
451
|
+
await expect(service.getAccessToken(null)).rejects.toThrow();
|
|
452
|
+
rotate.failWith = null;
|
|
453
|
+
await service.getAccessToken(null);
|
|
454
|
+
expect((await row(null)).lastError).toBeNull();
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
it("forceRotate rotates even with a valid cached token", async () => {
|
|
458
|
+
await service.save(acctA, {
|
|
459
|
+
refreshToken: REFRESH,
|
|
460
|
+
accessToken: ACCESS,
|
|
461
|
+
accessTokenExpiresAt: new Date(clock.now().getTime() + 11 * 3600 * 1000),
|
|
462
|
+
});
|
|
463
|
+
expect(await service.getAccessToken(acctA, { forceRotate: true })).toBe(
|
|
464
|
+
"rotated-access-1-SUPERSECRET",
|
|
465
|
+
);
|
|
466
|
+
expect(rotate.calls).toEqual([REFRESH]);
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
it("forceRotate with rejectedAccessToken reuses a token another caller already rotated to", async () => {
|
|
470
|
+
await service.save(acctA, { refreshToken: REFRESH, accessToken: ACCESS });
|
|
471
|
+
// Another caller already rotated past the rejected token.
|
|
472
|
+
await service.save(acctA, {
|
|
473
|
+
refreshToken: "test-refresh-NEWER",
|
|
474
|
+
accessToken: "test-access-NEWER",
|
|
475
|
+
accessTokenExpiresAt: new Date(clock.now().getTime() + 11 * 3600 * 1000),
|
|
476
|
+
});
|
|
477
|
+
expect(
|
|
478
|
+
await service.getAccessToken(acctA, {
|
|
479
|
+
forceRotate: true,
|
|
480
|
+
rejectedAccessToken: ACCESS,
|
|
481
|
+
}),
|
|
482
|
+
).toBe("test-access-NEWER");
|
|
483
|
+
expect(rotate.calls).toEqual([]);
|
|
484
|
+
// Rejected token is still the stored one -> rotate.
|
|
485
|
+
expect(
|
|
486
|
+
await service.getAccessToken(acctA, {
|
|
487
|
+
forceRotate: true,
|
|
488
|
+
rejectedAccessToken: "test-access-NEWER",
|
|
489
|
+
}),
|
|
490
|
+
).toBe("rotated-access-1-SUPERSECRET");
|
|
491
|
+
expect(rotate.calls).toEqual(["test-refresh-NEWER"]);
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
it("clear errors for a missing row, a missing key and a missing rotate client", async () => {
|
|
495
|
+
await expect(service.getAccessToken(acctA)).rejects.toBeInstanceOf(
|
|
496
|
+
SlackConfigTokenNotConfiguredError,
|
|
497
|
+
);
|
|
498
|
+
await service.save(acctA, { refreshToken: REFRESH });
|
|
499
|
+
await expect(
|
|
500
|
+
new SlackConfigTokenService(prisma, null, clock, rotate).getAccessToken(
|
|
501
|
+
acctA,
|
|
502
|
+
),
|
|
503
|
+
).rejects.toBeInstanceOf(SlackConfigTokenEncryptionUnavailableError);
|
|
504
|
+
await expect(
|
|
505
|
+
new SlackConfigTokenService(prisma, crypto, clock).getAccessToken(acctA),
|
|
506
|
+
).rejects.toThrow(/SlackConfigTokenClient/);
|
|
507
|
+
expect(rotate.calls).toEqual([]);
|
|
508
|
+
});
|
|
509
|
+
|
|
510
|
+
describe("withSlackConfigAccessToken", () => {
|
|
511
|
+
beforeEach(async () => {
|
|
512
|
+
await service.save(acctA, {
|
|
513
|
+
refreshToken: REFRESH,
|
|
514
|
+
accessToken: ACCESS,
|
|
515
|
+
accessTokenExpiresAt: new Date(
|
|
516
|
+
clock.now().getTime() + 11 * 3600 * 1000,
|
|
517
|
+
),
|
|
518
|
+
});
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
it("runs fn with the cached token", async () => {
|
|
522
|
+
const seen: string[] = [];
|
|
523
|
+
const out = await service.withSlackConfigAccessToken(acctA, async (t) => {
|
|
524
|
+
seen.push(t);
|
|
525
|
+
return 42;
|
|
526
|
+
});
|
|
527
|
+
expect(out).toBe(42);
|
|
528
|
+
expect(seen).toEqual([ACCESS]);
|
|
529
|
+
expect(rotate.calls).toEqual([]);
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
it("on token_revoked force-rotates once and retries, then passes", async () => {
|
|
533
|
+
const seen: string[] = [];
|
|
534
|
+
const out = await service.withSlackConfigAccessToken(acctA, async (t) => {
|
|
535
|
+
seen.push(t);
|
|
536
|
+
if (t === ACCESS) {
|
|
537
|
+
// Shape thrown by HttpSlackProvisioningClient manifest calls.
|
|
538
|
+
throw new Error("Slack apps.manifest.update failed: token_revoked");
|
|
539
|
+
}
|
|
540
|
+
return "ok";
|
|
541
|
+
});
|
|
542
|
+
expect(out).toBe("ok");
|
|
543
|
+
expect(seen).toEqual([ACCESS, "rotated-access-1-SUPERSECRET"]);
|
|
544
|
+
expect(rotate.calls).toEqual([REFRESH]);
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
it("retries at most once: a second auth failure propagates, no loop", async () => {
|
|
548
|
+
let n = 0;
|
|
549
|
+
await expect(
|
|
550
|
+
service.withSlackConfigAccessToken(acctA, async () => {
|
|
551
|
+
n++;
|
|
552
|
+
throw new Error("Slack apps.manifest.delete failed: invalid_auth");
|
|
553
|
+
}),
|
|
554
|
+
).rejects.toThrow(/invalid_auth/);
|
|
555
|
+
expect(n).toBe(2);
|
|
556
|
+
expect(rotate.calls.length).toBe(1);
|
|
557
|
+
});
|
|
558
|
+
|
|
559
|
+
it("does not retry on unrelated errors", async () => {
|
|
560
|
+
let n = 0;
|
|
561
|
+
await expect(
|
|
562
|
+
service.withSlackConfigAccessToken(acctA, async () => {
|
|
563
|
+
n++;
|
|
564
|
+
throw new Error(
|
|
565
|
+
"Slack apps.manifest.create failed: invalid_manifest",
|
|
566
|
+
);
|
|
567
|
+
}),
|
|
568
|
+
).rejects.toThrow(/invalid_manifest/);
|
|
569
|
+
expect(n).toBe(1);
|
|
570
|
+
expect(rotate.calls).toEqual([]);
|
|
571
|
+
});
|
|
572
|
+
});
|
|
573
|
+
});
|
|
574
|
+
|
|
575
|
+
describe("isSlackConfigTokenRevokedError", () => {
|
|
576
|
+
it("matches manifest-call errors and coded errors for token_revoked / invalid_auth", () => {
|
|
577
|
+
expect(
|
|
578
|
+
isSlackConfigTokenRevokedError(
|
|
579
|
+
new Error("Slack apps.manifest.update failed: token_revoked"),
|
|
580
|
+
),
|
|
581
|
+
).toBe(true);
|
|
582
|
+
expect(
|
|
583
|
+
isSlackConfigTokenRevokedError(
|
|
584
|
+
new Error("Slack apps.manifest.create failed: invalid_auth"),
|
|
585
|
+
),
|
|
586
|
+
).toBe(true);
|
|
587
|
+
expect(
|
|
588
|
+
isSlackConfigTokenRevokedError(
|
|
589
|
+
new SlackConfigTokenError("token_revoked", "x"),
|
|
590
|
+
),
|
|
591
|
+
).toBe(true);
|
|
592
|
+
expect(
|
|
593
|
+
isSlackConfigTokenRevokedError(
|
|
594
|
+
new Error("Slack apps.manifest.create failed: invalid_manifest"),
|
|
595
|
+
),
|
|
596
|
+
).toBe(false);
|
|
597
|
+
expect(
|
|
598
|
+
isSlackConfigTokenRevokedError(
|
|
599
|
+
new Error("Slack apps.manifest.update failed: not_authed_revoked_x"),
|
|
600
|
+
),
|
|
601
|
+
).toBe(false);
|
|
602
|
+
expect(isSlackConfigTokenRevokedError("token_revoked")).toBe(false);
|
|
603
|
+
expect(isSlackConfigTokenRevokedError(null)).toBe(false);
|
|
604
|
+
});
|
|
605
|
+
});
|