diff --git a/changelog.d/105-repo-members.added.md b/changelog.d/105-repo-members.added.md new file mode 100644 index 00000000..6c1abd2f --- /dev/null +++ b/changelog.d/105-repo-members.added.md @@ -0,0 +1,7 @@ +Written-by: HugoXK + +A repository can be shared with its members: the dashboard, repository page, +work items and jobs are visible to every active `repo_members` row, a `viewer` +reads without writing, a `developer` works without changing the merge policy, +and only a `maintainer` writes repository settings, changes the role, deletes +the repository, publishes a release or stops and restarts its workspace. diff --git a/docs/architecture.md b/docs/architecture.md index 6d22b719..da666a93 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2357,8 +2357,34 @@ grants and the legacy `repos.user_id` owner. `maintainer`, `developer` and `admin` gets `grants.manage` and repository capabilities only through a membership or grant. `GET /api/auth/me` is the first read surface: it requires an approved session and returns the user summary, tenant/project roles, -capabilities and platform capabilities without a token or key column. Enforcement -on read and write routes remains a later slice. +capabilities and platform capabilities without a token or key column. + +## Shared repository read path (#105, slice 1) + +Repository membership reaches the product surfaces here. `Store.listRepos`, +`listReposPage` and `countReposForViewer` include every repository with an active +`repo_members` row for the viewer, so the dashboard and its total describe what +the person can see rather than what they connected. The owner-only +`countReposForUser` stays the connection-limit count, because a shared repository +is the owner's connection and must not consume a member's own repository limit. + +Every `/repos/:id` route resolves the viewer through `ownedRepo`: the connection +owner is the maintainer of last resort, an active member row supplies its own +role, and a missing repository and a non-member answer the same 404 so an id does +not leak. A `viewer` reads but any mutating route answers 403; repository +settings (merge policy, target branch, role gate, auto-merge) require +`maintainer`, and so do the routes that are settings in effect or can end the +connection: `POST /repos/:id/role` (it writes the same `repo_role` column as the +settings form and clears `auto_merge`), `/delete`, `/release`, `/enable`, +`/disable`, `/instance`, `/instance/stop` and `/models/apply`. A `developer` +keeps the work routes — `/work`, `/run`, `/plan`, `/triage`, `/review` and the +job actions — and `/run` is resolved through `ownedRepo` like the other starts, +so it answers for a member instead of the 404 a stranger gets. The member write path — `addRepoMember`, `setRepoMemberRole`, +`removeRepoMember` — validates the capability vocabulary and refuses to remove +the connection owner, which is what keeps a repository with a maintainer. +Invitations, accept/leave/transfer, the audit rows for each membership change and +member-aware controls in the views are the following slices; no route shown to a +viewer writes yet. ## Notification webhook egress diff --git a/src/app.ts b/src/app.ts index 07951d61..a1cec54c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -830,11 +830,33 @@ export async function buildApp(options: BuildOptions): Promise { return true } - const ownedRepo = (request: FastifyRequest, id: string, mutating = false) => { + // #105: a repository is shared with its active members. The connection owner + // stays the maintainer of last resort; a member row carries `maintainer`, + // `developer` or `viewer`. Reads are open to every active member, writes need + // developer or better, and repository settings need maintainer. A non-member + // and a missing repository answer the same 404 so an id does not leak. + // `maintainOnly` also covers the destructive and lifecycle routes: the role + // and settings forms write the same `repo_role`/`auto_merge` columns, and + // delete, release, enable/disable, the workspace controls and the model apply + // are settings in effect. A developer keeps the work routes (`/work`, + // `/run`, `/plan`, `/triage`, `/review` and job actions), never the ones that + // can destroy the connection or change who may use it. + const ownedRepo = (request: FastifyRequest, id: string, mutating = false, maintainOnly = false) => { const viewer = mutating ? approvedCsrfGuard(request) : requireApproved(request) const repo = store.getRepo(id) - if (repo === undefined || repo.user_id !== viewer.user.id) throw httpError(404, '仓库不存在。', 'REPO_NOT_FOUND') - return { viewer, repo } + const role = repo === undefined + ? null + : repo.user_id === viewer.user.id + ? 'maintainer' + : store.memberRoleFor(repo.id, viewer.user.id) + if (repo === undefined || role === null) throw httpError(404, '仓库不存在。', 'REPO_NOT_FOUND') + if (mutating && role === 'viewer') { + throw httpError(403, '只读成员不能修改这个仓库。', 'A viewer cannot change this repository.') + } + if (maintainOnly && role !== 'maintainer') { + throw httpError(403, '只有维护者可以修改仓库设置。', 'Only a maintainer can change repository settings.') + } + return { viewer, repo, role } } // #543: a plan carries the SHA it was analysed at. Resolving the default @@ -1395,7 +1417,9 @@ export async function buildApp(options: BuildOptions): Promise { { repo: queryText(request, 'repo'), status: queryText(request, 'status'), kind: queryText(request, 'kind'), priority: queryText(request, 'priority') }, allRepos.map((repo) => repo.id), ) - const reposTotal = store.countReposForUser(viewer.user.id) + // #105: the dashboard lists shared repositories too, so its total counts + // what this viewer can see rather than what they own. + const reposTotal = store.countReposForViewer(viewer.user.id) const jobsTotal = store.countJobsForUser(viewer.user.id, jobFilter) const pageNumber = (name: string, total: number): number => { const pages = Math.max(1, Math.ceil(total / perPage)) @@ -2458,7 +2482,7 @@ export async function buildApp(options: BuildOptions): Promise { // is read-only; only a plan that passes every check reaches the tag write, and // the tag is annotated and created through the repository's installation token. app.post('/repos/:id/release', async (request, reply) => { - const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) + const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true, true) const body = form(request) const version = String(body.version ?? '').trim() const targetSha = String(body.sha ?? '').trim().toLowerCase() @@ -3907,9 +3931,10 @@ export async function buildApp(options: BuildOptions): Promise { // #708: starting a job spends a model budget and a FlyBot slot, so it takes // the expensive window before the repository is read. if (!limits.take('expensive', `job-start:${rateLimitKey(request)}`)) return refuseTooMany(request, reply) - const viewer = approvedCsrfGuard(request) - const repo = store.getRepo(String((request.params as Record).id)) - if (repo === undefined || repo.user_id !== viewer.user.id) throw httpError(404, '仓库不存在。', 'REPO_NOT_FOUND') + // #105 review: this start reads the repository through `ownedRepo` like the + // other four member-facing starts, so a developer member starts work instead + // of getting the 404 a stranger gets. + const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) const t = translator(request.locale ?? 'zh') const outcome = await runCreate(request, viewer, repo, { kind: repo.plan_required === 1 ? 'plan' : 'iterate' }) if (!outcome.ok) { @@ -4033,7 +4058,7 @@ export async function buildApp(options: BuildOptions): Promise { }) app.post('/repos/:id/instance', async (request, reply) => { - const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) + const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true, true) if (config.flybot.instanceImage === '') throw httpError(400, 'FlyBot 实例未配置', 'INSTANCE_DISABLED') // #457 review: the guard used to run before this route knew the repository // already had a row, so a stopped instance counted against its own restart @@ -4049,7 +4074,7 @@ export async function buildApp(options: BuildOptions): Promise { }) app.post('/repos/:id/instance/stop', { config: { rateLimit: destructiveLimit } }, async (request, reply) => { - const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) + const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true, true) if (requireRecentAuth(request, reply, viewer, 'flybot.instance.stop')) return reply await instances.stop(repo.id) await jobs.cancelRepoJobs(repo.id, 'FlyBot 实例已停止', 'BRIDGE_ERROR') @@ -4068,7 +4093,9 @@ export async function buildApp(options: BuildOptions): Promise { }) app.post('/repos/:id/role', { config: { rateLimit: destructiveClassLimit } }, async (request, reply) => { - const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) + // #105 review: this route writes the same `repo_role` column as the settings + // form, so it carries the settings rule. + const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true, true) const body = form(request) const t = translator(request.locale ?? 'zh') const role = parseRepoRole(body.role) @@ -4089,7 +4116,9 @@ export async function buildApp(options: BuildOptions): Promise { }) app.post('/repos/:id/settings', { config: { rateLimit: destructiveLimit } }, async (request, reply) => { - const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) + // #105: settings decide the merge policy and the role gate, so a developer + // member reads them but cannot write them. + const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true, true) const body = form(request) const interval = normalizeInterval(body.interval, repo.interval_minutes) const reviewInterval = normalizeInterval(body.reviewInterval, repo.review_interval_minutes) @@ -4237,7 +4266,7 @@ export async function buildApp(options: BuildOptions): Promise { }) app.post('/repos/:id/models/apply', async (request, reply) => { - const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) + const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true, true) try { const result = await instances.applyModels(repo.id) if (!result.ok) return reply.redirect(`/repos/${repo.id}?error=${encodeURIComponent(result.error ?? '模型应用失败。')}#repo-settings`) @@ -4249,14 +4278,14 @@ export async function buildApp(options: BuildOptions): Promise { }) app.post('/repos/:id/enable', async (request, reply) => { - const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) + const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true, true) store.updateRepo(repo.id, { enabled: 1 }) store.audit(viewer.user.id, 'repo.enabled', `${repo.owner}/${repo.name}`) return reply.redirect(`/repos/${repo.id}?notice=${encodeURIComponent('仓库已启用;自动迭代不会自动打开,需要时在设置里开启。')}`) }) app.post('/repos/:id/disable', async (request, reply) => { - const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) + const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true, true) store.updateRepo(repo.id, { enabled: 0, auto_iterate: 0 }) await jobs.cancelRepoJobs(repo.id, '仓库已停用', 'REPO_DISABLED') store.audit(viewer.user.id, 'repo.disabled', `${repo.owner}/${repo.name}`) @@ -4264,7 +4293,7 @@ export async function buildApp(options: BuildOptions): Promise { }) app.post('/repos/:id/delete', { config: { rateLimit: destructiveLimit } }, async (request, reply) => { - const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) + const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true, true) if (requireRecentAuth(request, reply, viewer, 'repo.delete', `/repos/${repo.id}#danger`)) return reply const confirmName = (form(request).confirmName ?? '').trim() if (confirmName !== repo.name && confirmName !== `${repo.owner}/${repo.name}`) { diff --git a/src/db.ts b/src/db.ts index 650358a9..fa205864 100644 --- a/src/db.ts +++ b/src/db.ts @@ -5102,18 +5102,92 @@ export class Store { return repo } + // #105: a repository is visible to its connection owner and to every active + // member. The owner keeps the credential, the instance and the quota; sharing + // starts with the read path (dashboard, repository page, work items, jobs). listRepos(userId: string): RepoRow[] { - return this.all('SELECT * FROM repos WHERE user_id = ? ORDER BY created_at DESC', userId) + return this.all( + `SELECT * FROM repos + WHERE user_id = ? OR id IN (SELECT repo_id FROM repo_members WHERE user_id = ? AND revoked_at IS NULL) + ORDER BY created_at DESC`, + userId, + userId, + ) } listReposPage(userId: string, limit: number, offset: number): RepoRow[] { - return this.all('SELECT * FROM repos WHERE user_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ? OFFSET ?', userId, limit, offset) + return this.all( + `SELECT * FROM repos + WHERE user_id = ? OR id IN (SELECT repo_id FROM repo_members WHERE user_id = ? AND revoked_at IS NULL) + ORDER BY created_at DESC, rowid DESC LIMIT ? OFFSET ?`, + userId, + userId, + limit, + offset, + ) } + // The connection-limit count stays owner-only: a shared repository is the + // owner's connection and must not consume a member's own repository limit. countReposForUser(userId: string): number { return Number(this.get<{ n: number }>('SELECT COUNT(*) AS n FROM repos WHERE user_id = ?', userId)?.n ?? 0) } + countReposForViewer(userId: string): number { + return Number(this.get<{ n: number }>( + 'SELECT COUNT(*) AS n FROM repos WHERE user_id = ? OR id IN (SELECT repo_id FROM repo_members WHERE user_id = ? AND revoked_at IS NULL)', + userId, + userId, + )?.n ?? 0) + } + + // #105: the member rows already exist (the #541 identity backfill wrote the + // owner's). These methods are the write path a later invite slice exposes; the + // role vocabulary is the capability model's, so a member never gets a role the + // resolver cannot read. + listRepoMembers(repoId: string): RepoMemberRow[] { + return this.all('SELECT * FROM repo_members WHERE repo_id = ? AND revoked_at IS NULL ORDER BY created_at ASC', repoId) + } + + memberRoleFor(repoId: string, userId: string): string | null { + const row = this.get('SELECT * FROM repo_members WHERE repo_id = ? AND user_id = ? AND revoked_at IS NULL', repoId, userId) + return row?.role ?? null + } + + addRepoMember(input: { repoId: string; userId: string; role: string; grantedBy: string | null }): RepoMemberRow | undefined { + if (input.role !== 'maintainer' && input.role !== 'developer' && input.role !== 'viewer') return undefined + if (this.getRepo(input.repoId) === undefined || this.userById(input.userId) === undefined) return undefined + this.run( + `INSERT INTO repo_members (repo_id, user_id, role, granted_by, created_at, revoked_at) VALUES (?, ?, ?, ?, ?, NULL) + ON CONFLICT(repo_id, user_id) DO UPDATE SET role = excluded.role, granted_by = excluded.granted_by, revoked_at = NULL`, + input.repoId, + input.userId, + input.role, + input.grantedBy, + nowIso(), + ) + return this.get('SELECT * FROM repo_members WHERE repo_id = ? AND user_id = ?', input.repoId, input.userId) + } + + setRepoMemberRole(repoId: string, userId: string, role: string): boolean { + if (role !== 'maintainer' && role !== 'developer' && role !== 'viewer') return false + const row = this.get('SELECT * FROM repo_members WHERE repo_id = ? AND user_id = ? AND revoked_at IS NULL', repoId, userId) + if (row === undefined) return false + this.run('UPDATE repo_members SET role = ? WHERE repo_id = ? AND user_id = ?', role, repoId, userId) + return true + } + + removeRepoMember(repoId: string, userId: string): boolean { + const row = this.get('SELECT * FROM repo_members WHERE repo_id = ? AND user_id = ? AND revoked_at IS NULL', repoId, userId) + if (row === undefined) return false + // #105: the connection owner is the maintainer of last resort and cannot be + // removed here; that is what keeps a repository with at least one maintainer. + const repo = this.getRepo(repoId) + if (repo !== undefined && repo.user_id === userId) return false + this.run('UPDATE repo_members SET revoked_at = ? WHERE repo_id = ? AND user_id = ?', nowIso(), repoId, userId) + return true + } + getRepo(id: string): RepoRow | undefined { return this.get('SELECT * FROM repos WHERE id = ?', id) } diff --git a/test/repoMembers.test.ts b/test/repoMembers.test.ts new file mode 100644 index 00000000..d9830e91 --- /dev/null +++ b/test/repoMembers.test.ts @@ -0,0 +1,276 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { buildApp } from '../src/app.js' +import { Store } from '../src/db.js' +import { formBody, makeUser, MemoryMailer, sessionFor, testConfig } from './helpers.js' + +// #105 slice 1: a repository row belongs to its connection owner, but the +// product shares its read path with the members of that repository. The role +// vocabulary is the one the capability model already resolves, so a viewer +// reads and does nothing else, a developer works and cannot change the merge +// policy, and a revoked member falls back to the same 404 as a stranger. + +async function harness() { + const config = testConfig({ githubApp: { id: '1', slug: 'fledge-platform', privateKeyPath: '/tmp/fake.pem', webhookSecret: 'secret', useUserToken: false } }) + const store = new Store(':memory:') + const runner = { name: 'capture', async run() { return { status: 'running' as const } } } + const built = await buildApp({ config, store, mailer: new MemoryMailer(), runner, startScheduler: false }) + const owner = makeUser(store, { login: 'owner105', status: 'approved' }) + const member = makeUser(store, { login: 'member105', status: 'approved' }) + const viewer = makeUser(store, { login: 'viewer105', status: 'approved' }) + const stranger = makeUser(store, { login: 'stranger105', status: 'approved' }) + const repo = store.createRepo({ + id: 'repo105', + userId: owner.id, + owner: 'HugoXK', + name: 'shared105', + defaultBranch: 'main', + tokenEnc: '', + permission: 'admin', + repoRole: 'maintainer', + goal: 'keep this goal', + autoIterate: false, + intervalMinutes: 1440, + }) + return { config, store, built, owner, member, viewer, stranger, repo } +} + +test('member rows accept only the capability roles and revoking removes access', async () => { + const store = new Store(':memory:') + const owner = makeUser(store, { login: 'owner-rows' }) + const other = makeUser(store, { login: 'member-rows' }) + const repo = store.createRepo({ + id: 'repo-rows', + userId: owner.id, + owner: 'HugoXK', + name: 'rows', + defaultBranch: 'main', + tokenEnc: '', + permission: 'admin', + repoRole: 'maintainer', + goal: '', + autoIterate: false, + intervalMinutes: 1440, + }) + + assert.equal(store.addRepoMember({ repoId: repo.id, userId: other.id, role: 'admin', grantedBy: owner.id }), undefined) + const created = store.addRepoMember({ repoId: repo.id, userId: other.id, role: 'viewer', grantedBy: owner.id }) + assert.equal(created?.role, 'viewer') + assert.equal(store.memberRoleFor(repo.id, other.id), 'viewer') + + // The same pair added again is a role change, not a duplicate row or a crash. + assert.equal(store.addRepoMember({ repoId: repo.id, userId: other.id, role: 'developer', grantedBy: owner.id })?.role, 'developer') + assert.equal(store.listRepoMembers(repo.id).filter((row) => row.user_id === other.id).length, 1) + assert.equal(store.setRepoMemberRole(repo.id, other.id, 'viewer'), true) + assert.equal(store.memberRoleFor(repo.id, other.id), 'viewer') + assert.equal(store.setRepoMemberRole(repo.id, other.id, 'admin'), false) + assert.equal(store.memberRoleFor(repo.id, other.id), 'viewer') + + // The connection owner is the maintainer of last resort and cannot be removed. + assert.equal(store.removeRepoMember(repo.id, owner.id), false) + assert.equal(store.removeRepoMember(repo.id, other.id), true) + assert.equal(store.memberRoleFor(repo.id, other.id), null) + // The repository was created with its owner's backfilled maintainer row + // (`system:identity`), and that is the only member left after the revoke. + assert.deepEqual(store.listRepoMembers(repo.id).map((row) => [row.user_id, row.role]), [[owner.id, 'maintainer']]) + await Promise.resolve() +}) + +test('an active member reads the shared repository and a stranger does not', async () => { + const h = await harness() + try { + h.store.addRepoMember({ repoId: h.repo.id, userId: h.member.id, role: 'developer', grantedBy: h.owner.id }) + const memberSession = sessionFor(h.built, h.member) + const strangerSession = sessionFor(h.built, h.stranger) + + const memberDashboard = await h.built.app.inject({ method: 'GET', url: '/dashboard', headers: { cookie: memberSession.cookie } }) + assert.equal(memberDashboard.statusCode, 200) + assert.match(memberDashboard.body, /shared105/) + + const memberRepo = await h.built.app.inject({ method: 'GET', url: `/repos/${h.repo.id}`, headers: { cookie: memberSession.cookie } }) + assert.equal(memberRepo.statusCode, 200) + + const strangerDashboard = await h.built.app.inject({ method: 'GET', url: '/dashboard', headers: { cookie: strangerSession.cookie } }) + assert.equal(strangerDashboard.statusCode, 200) + assert.doesNotMatch(strangerDashboard.body, /shared105/) + + const strangerRepo = await h.built.app.inject({ method: 'GET', url: `/repos/${h.repo.id}`, headers: { cookie: strangerSession.cookie } }) + assert.equal(strangerRepo.statusCode, 404) + } finally { + await h.built.close() + } +}) + +test('a viewer member reads but cannot write', async () => { + const h = await harness() + try { + h.store.addRepoMember({ repoId: h.repo.id, userId: h.viewer.id, role: 'viewer', grantedBy: h.owner.id }) + const session = sessionFor(h.built, h.viewer) + const read = await h.built.app.inject({ method: 'GET', url: `/repos/${h.repo.id}`, headers: { cookie: session.cookie } }) + assert.equal(read.statusCode, 200) + + const write = await h.built.app.inject({ + method: 'POST', + url: `/repos/${h.repo.id}/work`, + headers: { 'content-type': 'application/x-www-form-urlencoded', cookie: session.cookie, 'x-csrf-token': session.csrf }, + payload: formBody({ title: 'viewer should not create this', csrf: session.csrf }), + }) + assert.equal(write.statusCode, 403) + assert.equal(h.store.listWorkItems(h.repo.id).length, 0) + } finally { + await h.built.close() + } +}) + +test('a developer member writes work but cannot change repository settings', async () => { + const h = await harness() + try { + h.store.addRepoMember({ repoId: h.repo.id, userId: h.member.id, role: 'developer', grantedBy: h.owner.id }) + const session = sessionFor(h.built, h.member) + + const created = await h.built.app.inject({ + method: 'POST', + url: `/repos/${h.repo.id}/work`, + headers: { 'content-type': 'application/x-www-form-urlencoded', cookie: session.cookie, 'x-csrf-token': session.csrf }, + payload: formBody({ title: 'member work item', csrf: session.csrf }), + }) + assert.equal(created.statusCode, 302) + assert.deepEqual(h.store.listWorkItems(h.repo.id).map((item) => item.title), ['member work item']) + + const settings = await h.built.app.inject({ + method: 'POST', + url: `/repos/${h.repo.id}/settings`, + headers: { 'content-type': 'application/x-www-form-urlencoded', cookie: session.cookie, 'x-csrf-token': session.csrf }, + payload: formBody({ goal: 'a developer must not rewrite this', csrf: session.csrf }), + }) + assert.equal(settings.statusCode, 403) + assert.equal(h.store.getRepo(h.repo.id)?.goal, 'keep this goal') + } finally { + await h.built.close() + } +}) + +test('a revoked member loses the repository again', async () => { + const h = await harness() + try { + h.store.addRepoMember({ repoId: h.repo.id, userId: h.member.id, role: 'developer', grantedBy: h.owner.id }) + assert.equal(h.store.removeRepoMember(h.repo.id, h.member.id), true) + const session = sessionFor(h.built, h.member) + const page = await h.built.app.inject({ method: 'GET', url: `/repos/${h.repo.id}`, headers: { cookie: session.cookie } }) + assert.equal(page.statusCode, 404) + const dashboard = await h.built.app.inject({ method: 'GET', url: '/dashboard', headers: { cookie: session.cookie } }) + assert.equal(dashboard.statusCode, 200) + assert.doesNotMatch(dashboard.body, /shared105/) + } finally { + await h.built.close() + } +}) + +// #105 review (5914605525): slice 1 handed a developer member every route that +// `ownedRepo` let through with `mutating` only. Those routes write the same +// columns as the settings form and can clear `auto_merge`/`reviewer_enabled` or +// destroy the connection, so they carry the settings rule now: maintainer. +// The refusal is the guard's, which answers before the body is read — a +// malformed release body still gets 403 rather than a body-validation redirect. +async function postForm(built: Awaited>['built'], session: { cookie: string; csrf: string }, url: string, payload: Record) { + return built.app.inject({ + method: 'POST', + url, + headers: { 'content-type': 'application/x-www-form-urlencoded', cookie: session.cookie, 'x-csrf-token': session.csrf }, + payload: formBody({ ...payload, csrf: session.csrf }), + }) +} + +test('a developer member cannot change the repository role', async () => { + const h = await harness() + try { + h.store.addRepoMember({ repoId: h.repo.id, userId: h.member.id, role: 'developer', grantedBy: h.owner.id }) + assert.equal(h.store.getRepo(h.repo.id)?.repo_role, 'maintainer') + const session = sessionFor(h.built, h.member) + // `role` writes the same column as settings, and demoting clears + // `auto_merge`; a developer holding it could turn auto-merge off. + const demote = await postForm(h.built, session, `/repos/${h.repo.id}/role`, { role: 'developer' }) + assert.equal(demote.statusCode, 403) + assert.equal(h.store.getRepo(h.repo.id)?.repo_role, 'maintainer') + + // The maintainer keeps the route; the guard is not a blanket refusal. + const ownerSession = sessionFor(h.built, h.owner) + const ownerDemote = await postForm(h.built, ownerSession, `/repos/${h.repo.id}/role`, { role: 'developer' }) + assert.equal(ownerDemote.statusCode, 302) + assert.equal(h.store.getRepo(h.repo.id)?.repo_role, 'developer') + } finally { + await h.built.close() + } +}) + +test('a developer member cannot delete the repository', async () => { + const h = await harness() + try { + h.store.addRepoMember({ repoId: h.repo.id, userId: h.member.id, role: 'developer', grantedBy: h.owner.id }) + const session = sessionFor(h.built, h.member) + const refused = await postForm(h.built, session, `/repos/${h.repo.id}/delete`, { confirmName: 'shared105' }) + assert.equal(refused.statusCode, 403) + assert.notEqual(h.store.getRepo(h.repo.id), undefined) + assert.equal(h.store.memberRoleFor(h.repo.id, h.member.id), 'developer') + } finally { + await h.built.close() + } +}) + +test('a developer member cannot publish a release', async () => { + const h = await harness() + try { + h.store.addRepoMember({ repoId: h.repo.id, userId: h.member.id, role: 'developer', grantedBy: h.owner.id }) + const session = sessionFor(h.built, h.member) + // Malformed first: the guard answers before the SHA and confirmation are + // parsed, so the refusal is a permission answer and not a body complaint. + const malformed = await postForm(h.built, session, `/repos/${h.repo.id}/release`, { version: '9.9.9', sha: 'abc123', confirm: '1' }) + assert.equal(malformed.statusCode, 403) + // A well-formed body is refused for the same reason. + const wellFormed = await postForm(h.built, session, `/repos/${h.repo.id}/release`, { version: '9.9.9', sha: 'a'.repeat(40), confirm: '1' }) + assert.equal(wellFormed.statusCode, 403) + assert.equal(h.store.releaseByTag(h.repo.id, 'v9.9.9'), undefined) + } finally { + await h.built.close() + } +}) + +test('a developer member cannot stop, disable or restart the repository workspace', async () => { + const h = await harness() + try { + h.store.addRepoMember({ repoId: h.repo.id, userId: h.member.id, role: 'developer', grantedBy: h.owner.id }) + const session = sessionFor(h.built, h.member) + for (const [url, payload] of [ + [`/repos/${h.repo.id}/instance`, {}], + [`/repos/${h.repo.id}/instance/stop`, {}], + [`/repos/${h.repo.id}/models/apply`, {}], + [`/repos/${h.repo.id}/disable`, {}], + [`/repos/${h.repo.id}/enable`, {}], + ] as const) { + const refused = await postForm(h.built, session, url, payload) + assert.equal(refused.statusCode, 403, `${url} must refuse a developer member`) + } + assert.equal(h.store.getRepo(h.repo.id)?.enabled, h.repo.enabled) + } finally { + await h.built.close() + } +}) + +test('a developer member starts work through the same rule as plan and triage', async () => { + const h = await harness() + try { + h.store.addRepoMember({ repoId: h.repo.id, userId: h.member.id, role: 'developer', grantedBy: h.owner.id }) + const session = sessionFor(h.built, h.member) + // `/run` was the only member-facing start still reading `repo.user_id`; the + // four converted routes accept a member, so `/run` answers on the repository + // page instead of the 404 a stranger gets. + const started = await postForm(h.built, session, `/repos/${h.repo.id}/run`, {}) + assert.equal(started.statusCode, 302) + // The banner rides a one-shot flash cookie (#472), so a queued start lands + // on the bare repository page with the message in the cookie, not the query. + assert.equal(String(started.headers.location), `/repos/${h.repo.id}`) + assert.match(String(started.headers['set-cookie']), /fledge_flash=/) + } finally { + await h.built.close() + } +})