Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/extensions/replica-prototype/assets/renderer.js

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions hub/client/components/mention-input/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,23 @@ describe("MentionInput()", () => {
expect(submit).toHaveBeenCalledOnce()
})

it("keeps suggestions open through a managed username suffix and inserts the complete account", async () => {
const submit = vi.fn()
const load = vi.fn().mockResolvedValue([
{ githubId: 1002, login: "mona_enterprise", avatarUrl: null },
{ githubId: 1001, login: "octocat", avatarUrl: null },
])
render(<Composer load={load} submit={submit} />)
const input = screen.getByRole("textbox")
fireEvent.change(input, { target: { value: "Please @mona_ent" } })
await screen.findByRole("option", { name: "@mona_enterprise" })
expect(screen.queryByRole("option", { name: "@octocat" })).not.toBeInTheDocument()
fireEvent.keyDown(input, { key: "Enter" })
expect(input).toHaveValue("Please @mona_enterprise ")
expect(submit).not.toHaveBeenCalled()
expect(load).toHaveBeenLastCalledWith("mona_ent", expect.any(AbortSignal))
})

it("filters a reused collaborator list before limiting suggestions", async () => {
vi.useFakeTimers()
const load = vi.fn().mockResolvedValue([
Expand Down
2 changes: 1 addition & 1 deletion hub/client/components/mention-input/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function MentionInput({ value, onValueChange, onKeyDown, ref, ...props }:
const [retry, setRetry] = useState(0)
const [selected, setSelected] = useState(0)
const [position, setPosition] = useState({ left: 0, top: 0, width: 0 })
const match = value.slice(0, caret).match(/(?:^|[\s(])@([a-zA-Z0-9-]{0,39})$/)
const match = value.slice(0, caret).match(/(?:^|[\s(])@([a-zA-Z0-9_-]{0,39})$/)
const query = match?.[1]?.toLowerCase()
const open = source !== null && query !== undefined && !dismissed && !props.disabled
const lookup = open && source.searchesByQuery === false ? "" : query
Expand Down
36 changes: 36 additions & 0 deletions hub/client/components/mention-input/stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,39 @@ type Story = StoryObj<typeof meta>
export const People: Story = {}
export const MatchingCollaborator: Story = { args: { value: "Please review @mon" } }
export const PlainText: Story = { args: { value: "Please review the spacing." } }

export const ManagedUser: Story = {
args: { value: "Please review @mona_ent" },
decorators: [
(Story) => (
<div style={{ width: "28rem" }}>
<Story />
</div>
),
],
render: function ManagedUserStory(args) {
const [value, setValue] = useState(args.value)
const source = useMemo(
() => ({
load: () => Promise.resolve([{ ...mona, login: "mona_enterprise", githubId: 1002 }]),
copy: {
suggestions: "Mention suggestions",
error: "Unavailable",
loading: "Loading people...",
empty: "No matches",
retry: "Retry",
limit: "Each message can mention at most 10 distinct people.",
},
}),
[],
)
return (
<MentionProvider source={source}>
<MentionInput {...args} value={value} onValueChange={setValue} />
</MentionProvider>
)
},
play: async ({ canvas, userEvent }) => {
await userEvent.click(canvas.getByRole("textbox", { name: "Comment" }))
},
}
15 changes: 15 additions & 0 deletions hub/client/components/mention-text/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,19 @@ describe("MentionText()", () => {
expect(container.querySelector("script")).toBeNull()
expect(screen.getByText(/<script>unsafe<\/script>/)).toBeInTheDocument()
})

it("highlights the complete verified managed username without matching an unverified prefix", () => {
const { container } = render(
<MentionText
comment={{
...octocatRootComment,
body: "@mona_enterprise @mona @mona_enterprise_extra",
mentions: [{ login: "mona_enterprise", githubId: 1002 }],
}}
/>,
)
expect(container.querySelectorAll(".mention-text")).toHaveLength(1)
expect(container.querySelector(".mention-text")).toHaveTextContent("@mona_enterprise")
expect(container).toHaveTextContent("@mona_enterprise @mona @mona_enterprise_extra")
})
})
2 changes: 1 addition & 1 deletion hub/client/components/mention-text/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function MentionText({ comment }: { comment: ReviewComment }) {
const body = comment.body ?? ""
const mentions = new Set(comment.mentions?.map((mention) => mention.login.toLowerCase()) ?? [])
const tokens = body.matchAll(
/(?<![A-Za-z0-9_@/])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?)(?![A-Za-z0-9_-])/g,
/(?<![A-Za-z0-9_@/])@([A-Za-z0-9](?:[A-Za-z0-9_-]{0,37}[A-Za-z0-9])?)(?![A-Za-z0-9_-])/g,
)
const parts: ReactNode[] = []
let start = 0
Expand Down
11 changes: 11 additions & 0 deletions hub/client/features/review-thread-message/stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ type Story = StoryObj<typeof meta>

export const Root: Story = {}

export const ManagedUserMention: Story = {
args: {
comment: {
...octocatRootComment,
author: { ...octocatRootComment.author, login: "octocat_enterprise" },
body: "Please review this change, @mona_enterprise.",
mentions: [{ login: "mona_enterprise", githubId: 1002 }],
},
},
}

export const ActionsDisabled: Story = {
args: {
actionsDisabled: true,
Expand Down
8 changes: 8 additions & 0 deletions hub/client/utils/get-mention-logins/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,12 @@ describe("getMentionLogins()", () => {
expect(getMentionLogins(`${ten} @eleventh`)).toHaveLength(11)
expect(getMentionLogins(ten)).toHaveLength(10)
})

it("counts a managed account as one complete mention without truncating overlong names", () => {
expect(
getMentionLogins(
`@reviewer_enterprise @REVIEWER_ENTERPRISE @ordinary @${"r".repeat(35)}_corp`,
),
).toEqual(["reviewer_enterprise", "ordinary"])
})
})
2 changes: 1 addition & 1 deletion hub/client/utils/get-mention-logins/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export function getMentionLogins(body: string) {
const matches = body.matchAll(
/(?<![A-Za-z0-9_@/])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?)(?![A-Za-z0-9_-])/g,
/(?<![A-Za-z0-9_@/])@([A-Za-z0-9](?:[A-Za-z0-9_-]{0,37}[A-Za-z0-9])?)(?![A-Za-z0-9_-])/g,
)
return Array.from(
new Set(Array.from(matches).flatMap((token) => (token[1] ? [token[1].toLowerCase()] : []))),
Expand Down
2 changes: 2 additions & 0 deletions hub/docs/review-collaboration.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Resolution is thread state, not message state. Each real resolve or reopen trans

Local sessions can view and change reviews only for active repositories with a configured local path. The local sign-in still uses one fixed identity; collaborators in automated tests are separate saved identities, not another sign-in mode. GitHub sessions can review only non-local repositories included in their current installation access. Hub verifies the signed-in GitHub subject's current repository permission through the configured App. The route also rechecks the live session and persisted repository visibility. These checks do not grant any Hub or Entra role.

GitHub review access and mentions support Enterprise Managed User logins, including their underscore and enterprise shortcode. Permission checks still bind the returned account to its numeric GitHub identity.

Every query also binds prototype, Build, thread, and comment identifiers back to the requested repository, so an identifier from another repository or prototype is not usable through the route. The workspace advertises review and sharing capabilities on each repository instead of inferring them from the sign-in provider.

## Product API
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest"

import { reviewMentionLogins } from "."

describe("reviewMentionLogins()", () => {
it("extracts a whole managed account, deduplicates its casing, and preserves ordinary mentions", () => {
expect(
reviewMentionLogins(
"Please ask @Reviewer_Enterprise, @ordinary-reviewer, and @reviewer_enterprise.",
),
).toEqual(["reviewer_enterprise", "ordinary-reviewer"])
})

it("accepts a 39-character managed mention without truncating an overlong account", () => {
const login = `${"r".repeat(34)}_corp`
const overlong = `${"s".repeat(34)}_corpx`

expect(reviewMentionLogins(`Ask @${login} and @${overlong}, then @reviewer.`)).toEqual([
login,
"reviewer",
])
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import type { ReviewMentionRecipient, ReviewMutationScope } from "../types.ts"

type Database = Pick<PrismaClient, "repository" | "reviewComment" | "userProfile">

const validLogin = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/
const validLogin = /^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,37}[A-Za-z0-9])?$/
const mentionToken =
/(?<![A-Za-z0-9_@/])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?)(?![A-Za-z0-9_-])/g
/(?<![A-Za-z0-9_@/])@([A-Za-z0-9](?:[A-Za-z0-9_-]{0,37}[A-Za-z0-9])?)(?![A-Za-z0-9_-])/g

export function reviewMentionLogins(body: string) {
const logins = [
Expand Down
178 changes: 142 additions & 36 deletions hub/server/integrations/github/create-review-directory/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { generateKeyPairSync } from "node:crypto"
import { expect, it, vi } from "vitest"
import { describe, expect, it, vi } from "vitest"

import { GitHubProviderRequestError } from "../errors"

import { createReviewDirectory } from "."

Expand Down Expand Up @@ -85,43 +87,147 @@ it("uses the immutable repository ID when checking a collaborator after a rename
expect(request).toHaveBeenCalledTimes(1)
})

it("shares only the pending verification for the same repository and GitHub user", async () => {
let startVerification!: () => void
let finishVerification!: () => void
const verifying = new Promise<void>((resolve) => (startVerification = resolve))
const pending = new Promise<void>((resolve) => (finishVerification = resolve))
let permission = "read"
const { directory, request } = directoryWith((path) => {
switch (path) {
case permissionPath:
startVerification()
return pending.then(() => Response.json({ user: { id: 501 }, permission }))
case oldPermissionPath:
return new Response(null, { status: 404 })
case "/user/501":
return Response.json({ id: 501, login: "reviewer" })
default:
throw new Error(`Unexpected request: ${path}`)
}
describe("createReviewDirectory()", () => {
it.each(["reviewer_enterprise", `${"r".repeat(34)}_corp`])(
"resolves managed account %s by numeric identity and live repository permission",
async (login) => {
const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 })
const request = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
Response.json({
token: "synthetic",
expires_at: new Date(Date.now() + 10 * 60_000).toISOString(),
}),
)
.mockResolvedValueOnce(Response.json({ id: 42, full_name: "sandbox/renamed" }))
.mockResolvedValueOnce(Response.json({ id: 501, login }))
.mockResolvedValueOnce(Response.json({ user: { id: 501 }, permission: "read" }))
const directory = createReviewDirectory(
{ appId: "16", installationId: "17", privateKey },
request,
)

await expect(directory.find(42n, "old-login", 501)).resolves.toEqual({
githubId: 501,
login,
avatarUrl: null,
})
expect(
request.mock.calls.map(
([input]) => new URL(input instanceof Request ? input.url : input).pathname,
),
).toEqual([
"/app/installations/17/access_tokens",
"/repositories/42",
"/user/501",
`/repos/sandbox/renamed/collaborators/${login}/permission`,
])
expect(request.mock.calls[0]?.[1]?.body).toBe(JSON.stringify({ repository_ids: [42] }))
},
)

it.each([
{
reason: "a different profile identity",
profileId: 502,
collaboratorId: 501,
permission: "read",
},
{
reason: "a different collaborator identity",
profileId: 501,
collaboratorId: 502,
permission: "read",
},
{ reason: "no repository permission", profileId: 501, collaboratorId: 501, permission: "none" },
])("denies a managed account with $reason", async ({ profileId, collaboratorId, permission }) => {
const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 })
const request = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
Response.json({
token: "synthetic",
expires_at: new Date(Date.now() + 10 * 60_000).toISOString(),
}),
)
.mockResolvedValueOnce(Response.json({ id: 42, full_name: "sandbox/private" }))
.mockResolvedValueOnce(Response.json({ id: profileId, login: "reviewer_enterprise" }))
.mockResolvedValueOnce(Response.json({ user: { id: collaboratorId }, permission }))
const directory = createReviewDirectory(
{ appId: "16", installationId: "17", privateKey },
request,
)

await expect(directory.find(42n, "reviewer_enterprise", 501)).resolves.toBeNull()
})
const first = directory.canRead(42n, "reviewer", 501)
try {
await Promise.race([verifying, first])
const concurrent = directory.canRead(42n, "old-login", 501)
finishVerification()
await expect(Promise.all([first, concurrent])).resolves.toEqual([true, true])
} finally {
finishVerification()
}
const requests = request.mock.calls
.map(([input]) => new URL(input instanceof Request ? input.url : input).pathname)
.filter((path) => path !== installationTokenPath)
expect(requests).toEqual([repositoryPath, permissionPath])

permission = "none"
await expect(directory.canRead(42n, "reviewer", 501)).resolves.toBe(false)
it("reports an unavailable collaborator directory instead of an empty search", async () => {
const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 })
const request = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
Response.json({
token: "synthetic",
expires_at: new Date(Date.now() + 10 * 60_000).toISOString(),
}),
)
.mockResolvedValueOnce(Response.json({ id: 42, full_name: "sandbox/private" }))
.mockResolvedValueOnce(new Response(null, { status: 503 }))
const directory = createReviewDirectory(
{ appId: "16", installationId: "17", privateKey },
request,
)

await expect(directory.search(42n, "reviewer_enterprise")).rejects.toBeInstanceOf(
GitHubProviderRequestError,
)
})
})

it.each(["reviewer", "reviewer_enterprise", `${"r".repeat(34)}_corp`])(
"shares only pending verification for the same repository and GitHub user with login %s",
async (login) => {
let startVerification!: () => void
let finishVerification!: () => void
const verifying = new Promise<void>((resolve) => (startVerification = resolve))
const pending = new Promise<void>((resolve) => (finishVerification = resolve))
let permission = "read"
const { directory, request } = directoryWith((path) => {
switch (path) {
case `/repos/sandbox/renamed/collaborators/${login}/permission`:
startVerification()
return pending.then(() => Response.json({ user: { id: 501 }, permission }))
case oldPermissionPath:
return new Response(null, { status: 404 })
case "/user/501":
return Response.json({ id: 501, login })
default:
throw new Error(`Unexpected request: ${path}`)
}
})
const first = directory.canRead(42n, login, 501)
try {
await Promise.race([verifying, first])
const concurrent = directory.canRead(42n, "old-login", 501)
finishVerification()
await expect(Promise.all([first, concurrent])).resolves.toEqual([true, true])
} finally {
finishVerification()
}
const requests = request.mock.calls
.map(([input]) => new URL(input instanceof Request ? input.url : input).pathname)
.filter((path) => path !== installationTokenPath)
expect(requests).toEqual([
repositoryPath,
`/repos/sandbox/renamed/collaborators/${login}/permission`,
])

permission = "none"
await expect(directory.canRead(42n, login, 501)).resolves.toBe(false)
},
)

it.each([
["has no permission record", null],
["belongs to another account", 502],
Expand All @@ -134,8 +240,8 @@ it.each([
? new Response(null, { status: 404 })
: Response.json({ user: { id: oldOwner }, permission: "admin" })
case "/user/501":
return Response.json({ id: 501, login: "reviewer" })
case permissionPath:
return Response.json({ id: 501, login: "reviewer_enterprise" })
case "/repos/sandbox/renamed/collaborators/reviewer_enterprise/permission":
return Response.json({ user: { id: currentOwner }, permission: "read" })
default:
throw new Error(`Unexpected request: ${path}`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { GitHubReviewDirectory } from "./types.ts"

const profileSchema = z.object({
id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
login: z.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/),
login: z.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,37}[A-Za-z0-9])?$/),
avatar_url: z
.url({ protocol: /^https$/ })
.nullable()
Expand Down
Loading
Loading