Skip to content

Commit 3424633

Browse files
authored
fix(twitch): retain native sender identity in execution audits (#130730)
* fix(twitch): retain native sender identity in execution audits Forward the registered channel runtime and actual account identity, keeping native participants distinct from role authorization. Normalize the all role at the Twitch policy producer and preserve unknown and disabled-collection paths. Cover actual registered-plugin ingress and native reply delivery, and drain asynchronous monitor test work before cleanup. Related to #122863; no shared authorization or storage change. * test(twitch): track the registered context builder in inventory * test(twitch): honor host and plugin contract boundaries
1 parent 5f8fd58 commit 3424633

11 files changed

Lines changed: 523 additions & 144 deletions

File tree

‎docs/channels/twitch.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,19 @@ Find yours with the [username to ID converter](https://www.streamweasels.com/too
228228

229229
## Troubleshooting
230230

231+
### Execution identity audit
232+
233+
With [execution identity collection](/gateway/audit#run-identity-inspection) enabled,
234+
a trusted native Twitch plugin attributes the run to the native Twitch sender,
235+
scoped to the configured account. The audit stores an opaque identity, not the raw
236+
Twitch user ID. Roles such as moderator authorize access; they do not replace
237+
the sender's identity. Missing native user IDs remain unknown even when a role or
238+
open policy allows a reply. External plugin installations do not gain trusted
239+
participant evidence through this path. Audit collection never changes these
240+
access decisions.
241+
242+
### Connection and replies
243+
231244
First, run diagnostic commands:
232245

233246
```bash

‎extensions/twitch/src/access-control.test.ts‎

Lines changed: 55 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ describe("checkTwitchAccessControl", () => {
2424
message?: Partial<TwitchChatMessage>;
2525
}) {
2626
return checkTwitchAccessControl({
27+
accountId: "secondary",
2728
message: {
2829
...mockMessage,
2930
...params.message,
@@ -36,21 +37,6 @@ describe("checkTwitchAccessControl", () => {
3637
});
3738
}
3839

39-
async function expectSingleRoleAllowed(params: {
40-
role: NonNullable<TwitchAccountConfig["allowedRoles"]>[number];
41-
message: Partial<TwitchChatMessage>;
42-
}) {
43-
const result = await runAccessCheck({
44-
account: { allowedRoles: [params.role] },
45-
message: {
46-
message: "@testbot hello",
47-
...params.message,
48-
},
49-
});
50-
expect(result.allowed).toBe(true);
51-
return result;
52-
}
53-
5440
async function expectAllowedAccessCheck(params: {
5541
account?: Partial<TwitchAccountConfig>;
5642
message?: Partial<TwitchChatMessage>;
@@ -179,6 +165,7 @@ describe("checkTwitchAccessControl", () => {
179165
};
180166

181167
const result = await checkTwitchAccessControl({
168+
accountId: "secondary",
182169
message,
183170
account,
184171
botUsername: "testbot",
@@ -206,13 +193,30 @@ describe("checkTwitchAccessControl", () => {
206193
});
207194

208195
describe("allowedRoles", () => {
209-
it("allows users with matching role", async () => {
210-
const result = await expectSingleRoleAllowed({
211-
role: "moderator",
212-
message: { isMod: true },
213-
});
214-
expect(result.matchSource).toBe("role");
215-
});
196+
it.each([
197+
{ role: "moderator", flag: "isMod" },
198+
{ role: "owner", flag: "isOwner" },
199+
{ role: "vip", flag: "isVip" },
200+
{ role: "subscriber", flag: "isSub" },
201+
] as const)(
202+
"admits only the matching $role alias, including absent native IDs",
203+
async ({ role, flag }) => {
204+
for (const userId of ["123456", undefined]) {
205+
for (const matching of [false, true]) {
206+
const result = await runAccessCheck({
207+
account: { allowedRoles: [role] },
208+
message: { message: "@testbot hello", userId, [flag]: matching },
209+
});
210+
expect(result.allowed).toBe(matching);
211+
if (matching) {
212+
expect(result.matchSource).toBe("role");
213+
} else {
214+
expect(result.reason).toContain("does not have any of the required roles");
215+
}
216+
}
217+
}
218+
},
219+
);
216220

217221
it("allows users with any of multiple roles", async () => {
218222
const account: TwitchAccountConfig = {
@@ -228,6 +232,7 @@ describe("checkTwitchAccessControl", () => {
228232
};
229233

230234
const result = await checkTwitchAccessControl({
235+
accountId: "secondary",
231236
message,
232237
account,
233238
botUsername: "testbot",
@@ -247,6 +252,7 @@ describe("checkTwitchAccessControl", () => {
247252
};
248253

249254
const result = await checkTwitchAccessControl({
255+
accountId: "secondary",
250256
message,
251257
account,
252258
botUsername: "testbot",
@@ -255,42 +261,36 @@ describe("checkTwitchAccessControl", () => {
255261
expect(result.reason).toContain("does not have any of the required roles");
256262
});
257263

258-
it("allows all users when role is 'all'", async () => {
259-
const result = await expectAllowedAccessCheck({
260-
account: {
261-
allowedRoles: ["all"],
262-
},
263-
});
264-
expect(result.matchKey).toBe("all");
265-
});
266-
267-
it("handles moderator role", async () => {
268-
await expectSingleRoleAllowed({
269-
role: "moderator",
270-
message: { isMod: true },
271-
});
272-
});
273-
274-
it("handles subscriber role", async () => {
275-
await expectSingleRoleAllowed({
276-
role: "subscriber",
277-
message: { isSub: true },
278-
});
279-
});
264+
it.each(["123456", undefined])(
265+
"allows wildcard roles without requiring a native ID (%s)",
266+
async (userId) => {
267+
const result = await expectAllowedAccessCheck({
268+
account: {
269+
allowedRoles: ["all"],
270+
},
271+
message: { userId },
272+
});
273+
expect(result.matchKey).toBe("all");
274+
},
275+
);
280276

281-
it("handles owner role", async () => {
282-
await expectSingleRoleAllowed({
283-
role: "owner",
284-
message: { isOwner: true },
277+
it("does not treat a native ID spelling a role as role membership", async () => {
278+
const result = await runAccessCheck({
279+
account: { allowedRoles: ["moderator"] },
280+
message: { message: "@testbot hello", userId: "moderator" },
285281
});
282+
expect(result.allowed).toBe(false);
286283
});
287284

288-
it("handles vip role", async () => {
289-
await expectSingleRoleAllowed({
290-
role: "vip",
291-
message: { isVip: true },
292-
});
293-
});
285+
it.each([undefined, []])(
286+
"keeps an open policy for absent or empty roles (%s)",
287+
async (allowedRoles) => {
288+
await expectAllowedAccessCheck({
289+
account: { allowedRoles },
290+
message: { userId: undefined },
291+
});
292+
},
293+
);
294294
});
295295

296296
describe("combined restrictions", () => {
@@ -306,6 +306,7 @@ describe("checkTwitchAccessControl", () => {
306306
};
307307

308308
const result = await checkTwitchAccessControl({
309+
accountId: "secondary",
309310
message,
310311
account,
311312
botUsername: "testbot",

‎extensions/twitch/src/access-control.ts‎

Lines changed: 14 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -34,37 +34,33 @@ const twitchUserIdentity = defineStableChannelIngressIdentity({
3434
});
3535

3636
const twitchRoleIdentity = defineStableChannelIngressIdentity({
37-
key: "role-moderator",
38-
kind: "role",
39-
normalizeEntry: normalizeTwitchModeratorRole,
40-
normalizeSubject: normalizeTwitchRole,
41-
aliases: ["owner", "vip", "subscriber"].map((role) => ({
37+
// Roles authorize the sender; only the native user ID identifies the participant.
38+
key: "sender-id",
39+
normalizeEntry: () => null,
40+
aliases: ["moderator", "owner", "vip", "subscriber"].map((role) => ({
4241
key: `role-${role}`,
4342
kind: "role",
44-
normalizeEntry: (value: string) => normalizeSpecificTwitchRole(value, role),
43+
normalizeEntry: (entry) => (normalizeTwitchRole(entry) === role ? role : null),
4544
normalizeSubject: normalizeTwitchRole,
4645
})),
47-
isWildcardEntry: (entry) => normalizeTwitchRole(entry) === "all",
4846
resolveEntryId: ({ entryIndex }) => `twitch-role-entry-${entryIndex + 1}`,
4947
});
5048

5149
export async function checkTwitchAccessControl(params: {
5250
message: TwitchChatMessage;
5351
account: TwitchAccountConfig;
52+
accountId: string;
5453
botUsername: string;
5554
contextBinding?: ChannelIngressContextBinding;
5655
}): Promise<TwitchAccessControlResult> {
5756
const { message, account, botUsername } = params;
5857
const policyKind = resolveTwitchPolicyKind(account);
5958
const resolved = await createChannelIngressResolver({
6059
channelId: "twitch",
61-
accountId: "default",
60+
accountId: params.accountId,
6261
identity: policyKind === "role" ? twitchRoleIdentity : twitchUserIdentity,
6362
}).message({
64-
subject:
65-
policyKind === "role"
66-
? twitchRoleSubject(message)
67-
: ({ stableId: message.userId } satisfies ChannelIngressIdentitySubjectInput),
63+
subject: twitchSubject(message),
6864
conversation: {
6965
kind: "group",
7066
id: message.channel,
@@ -84,11 +80,12 @@ export async function checkTwitchAccessControl(params: {
8480
order: "before-sender",
8581
},
8682
},
83+
// Canonical wildcard input keeps admission and participant evidence aligned.
8784
groupAllowFrom:
8885
policyKind === "allowFrom"
8986
? account.allowFrom
9087
: policyKind === "role"
91-
? account.allowedRoles
88+
? account.allowedRoles?.map((role) => (role === "all" ? "*" : role))
9289
: undefined,
9390
});
9491
const decision = resolved.ingress;
@@ -159,10 +156,11 @@ function resolveTwitchPolicyKind(account: TwitchAccountConfig): TwitchPolicyKind
159156
return "open";
160157
}
161158

162-
function twitchRoleSubject(message: TwitchChatMessage): ChannelIngressIdentitySubjectInput {
159+
function twitchSubject(message: TwitchChatMessage): ChannelIngressIdentitySubjectInput {
163160
return {
164-
stableId: message.isMod ? "moderator" : undefined,
161+
stableId: message.userId,
165162
aliases: {
163+
"role-moderator": message.isMod ? "moderator" : undefined,
166164
"role-owner": message.isOwner ? "owner" : undefined,
167165
"role-vip": message.isVip ? "vip" : undefined,
168166
"role-subscriber": message.isSub ? "subscriber" : undefined,
@@ -172,27 +170,11 @@ function twitchRoleSubject(message: TwitchChatMessage): ChannelIngressIdentitySu
172170

173171
function normalizeTwitchRole(value: string): string | null {
174172
const role = normalizeLowercaseStringOrEmpty(value);
175-
if (role === "*") {
176-
return "all";
177-
}
178-
return role === "moderator" ||
179-
role === "owner" ||
180-
role === "vip" ||
181-
role === "subscriber" ||
182-
role === "all"
173+
return role === "moderator" || role === "owner" || role === "vip" || role === "subscriber"
183174
? role
184175
: null;
185176
}
186177

187-
function normalizeTwitchModeratorRole(value: string): string | null {
188-
return normalizeSpecificTwitchRole(value, "moderator");
189-
}
190-
191-
function normalizeSpecificTwitchRole(value: string, expected: string): string | null {
192-
const role = normalizeTwitchRole(value);
193-
return role === expected ? role : null;
194-
}
195-
196178
function reasonForTwitchIngressDecision(decision: { reasonCode: IngressReasonCode }): string {
197179
switch (decision.reasonCode) {
198180
case "activation_skipped":

‎extensions/twitch/src/monitor.test.ts‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ describe("monitorTwitchProvider", () => {
6969
vi.clearAllMocks();
7070
mocks.getClient.mockResolvedValue({});
7171
mocks.sendMessage.mockResolvedValue({ ok: true, messageId: "message-id" });
72+
mocks.ingressStop.mockImplementation(async () => {
73+
await Promise.allSettled(mocks.ingressAccept.mock.results.map((result) => result.value));
74+
});
7275
mocks.createIngress.mockImplementation(
7376
(options: {
7477
deliver: (
@@ -81,26 +84,19 @@ describe("monitorTwitchProvider", () => {
8184
onAbandoned: () => Promise<void>;
8285
},
8386
) => Promise<void>;
84-
}) => {
85-
mocks.ingressAccept.mockImplementation(async (message: TwitchChatMessage) => {
87+
}) => ({
88+
accept: mocks.ingressAccept.mockImplementation(async (message: TwitchChatMessage) => {
8689
await options.deliver(message, {
8790
admission: "exclusive",
8891
abortSignal: new AbortController().signal,
8992
onAdopted: async () => undefined,
9093
onDeferred: () => undefined,
9194
onAbandoned: async () => undefined,
9295
});
93-
});
94-
// Real ingress stop drains accepted deliveries before the next monitor starts.
95-
mocks.ingressStop.mockImplementation(async () => {
96-
await Promise.all(mocks.ingressAccept.mock.results.map((result) => result.value));
97-
});
98-
return {
99-
accept: mocks.ingressAccept,
100-
start: mocks.ingressStart,
101-
stop: mocks.ingressStop,
102-
};
103-
},
96+
}),
97+
start: mocks.ingressStart,
98+
stop: mocks.ingressStop,
99+
}),
104100
);
105101
mocks.getRuntime.mockReturnValue({
106102
logging: {
@@ -199,6 +195,7 @@ describe("monitorTwitchProvider", () => {
199195
account,
200196
accountId: "default",
201197
config,
198+
channelRuntime: mocks.getRuntime().channel,
202199
runtime: { error: runtimeError },
203200
abortSignal: new AbortController().signal,
204201
});
@@ -212,6 +209,7 @@ describe("monitorTwitchProvider", () => {
212209
channel: "testchannel",
213210
});
214211
expect(mocks.ingressAccept).toHaveBeenCalledOnce();
212+
// Await the owning delivery task, including cold shared-dispatcher startup.
215213
await mocks.ingressAccept.mock.results[0]?.value;
216214
expect(mocks.sendMessage).toHaveBeenCalledOnce();
217215
expect(mocks.sendMessage).toHaveBeenCalledWith(
@@ -304,6 +302,7 @@ describe("monitorTwitchProvider", () => {
304302
account,
305303
accountId: "default",
306304
config: {},
305+
channelRuntime: mocks.getRuntime().channel,
307306
runtime: { error: runtimeError },
308307
abortSignal: new AbortController().signal,
309308
statusSink,

0 commit comments

Comments
 (0)