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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## Unreleased

### App

- **Admins can star any project.** Starring was for members only, so an admin who looks after a project without being in it could not keep it in the sidebar. The star button now shows on every project an admin can open, on All Projects and on the project page.
- **Becoming an admin takes effect without signing in again.** The app went on treating a newly made admin as a regular user until they signed out and back in: no admin menu, and no "Add people" in projects they were not a member of, although the server already allowed it. It now picks up the change on the next page load, and an admin who is demoted loses the admin controls the same way.

## v0.20.0

### App
Expand Down
8 changes: 4 additions & 4 deletions app/pages/projects/[slug]/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -232,11 +232,11 @@ async function confirmDeleteTag(tagId: string) {
</span>
</template>

<!-- The member check is on the slot, not the button: UiPage spaces the
description by whether this slot exists, so an empty one left an
admin outside the project with an 8px gap where 14 belongs. -->
<!-- Everyone who can open the project may star it, an admin outside it
included. The check stays on the slot, not the button: UiPage spaces the
description by whether this slot exists. -->
<template
v-if="project?.isMember"
v-if="project"
#title-trailing
>
<!-- No project key, for the reason on the All Projects card: this page
Expand Down
1 change: 0 additions & 1 deletion app/pages/projects/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,6 @@ const totalBoards = computed(() => projects.value?.reduce((sum, p) => sum + (p.b
/>
</UTooltip>
<ProjectStarButton
v-if="project.role !== 'admin'"
:project-id="project.id"
:project-name="project.name"
:starred="project.starred"
Expand Down
11 changes: 6 additions & 5 deletions server/api/projects/[id].get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,12 +172,13 @@ export default defineEventHandler(async (event) => {
createdBy: l.createdById ? creatorsMap.get(l.createdById) || null : null
}))

// Against real membership, not `membership`: that is a synthetic owner row for
// an admin, and a star left behind by a removed member must not count.
// `isMember` goes out too, because `role` cannot tell an admin who is not in the
// project from an owner, and only members may star.
// A star counts for a member and for an admin (who sees every project). A row
// left behind by a removed member who is not an admin must not count, so this is
// checked against real membership, not `membership`, which is a synthetic owner
// row for an admin. `isMember` goes out too, because `role` cannot tell an admin
// who is not in the project from an owner.
const isMember = isProjectMember(project.id, user.id)
const starred = isMember && !!db.select({ id: schema.projectStars.id })
const starred = (isMember || user.isAdmin) && !!db.select({ id: schema.projectStars.id })
.from(schema.projectStars)
.where(and(eq(schema.projectStars.userId, user.id), eq(schema.projectStars.projectId, project.id)))
.get()
Expand Down
14 changes: 6 additions & 8 deletions server/api/projects/[id]/star.put.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
/**
* Star a project, putting it in the caller's sidebar. Idempotent.
*
* Members only. `resolveProject` lets an admin through to any project, so the
* real membership is checked separately: an admin can open a project they are
* not in, but the sidebar is for the projects you work in. 403 rather than 404
* there, because the admin can already see the project exists.
* Anyone who can see the project may star it: its members, and an admin, who sees
* every project. Admins were refused here (403) on the reasoning that the sidebar
* is for the projects you work in, but an admin who looks after a project without
* being in it then had no way to keep it at hand. `resolveProject` already answers
* 404 to everyone else. The star is re-checked on every read, so it stops counting
* when the caller leaves the project or loses admin (see `projectStars`).
*/
export default defineEventHandler(async (event) => {
const { user, project } = await resolveProject(event)

if (!isProjectMember(project.id, user.id)) {
throw createError({ statusCode: 403, message: 'Only members can star a project' })
}

db.insert(schema.projectStars)
.values({ userId: user.id, projectId: project.id })
.onConflictDoNothing()
Expand Down
9 changes: 5 additions & 4 deletions server/api/projects/index.get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@ export default defineEventHandler(async (event) => {

const projectIds = projects.map(p => p.project.id)

// A star counts only where the caller is a real member: an admin's synthetic
// 'admin' role is not membership, and a removed member's row is left behind
// on purpose (see `projectStars` in the schema).
// A star counts for every project listed here, because the list is exactly the
// projects the caller can see (their memberships, or all of them for an admin).
// A removed member's row is left behind on purpose (see `projectStars` in the
// schema) and drops out with the project.
const starredIds = new Set(db.select({ projectId: schema.projectStars.projectId })
.from(schema.projectStars)
.where(eq(schema.projectStars.userId, userId))
Expand Down Expand Up @@ -118,7 +119,7 @@ export default defineEventHandler(async (event) => {
return projects.map(({ project, role }) => ({
...project,
role,
starred: role !== 'admin' && starredIds.has(project.id),
starred: starredIds.has(project.id),
boardCount: allBoards.filter(b => b.projectId === project.id).length,
listCount: allLists.filter(l => l.projectId === project.id).length,
totalCards: cardCountByProject.get(project.id) || 0,
Expand Down
9 changes: 3 additions & 6 deletions server/assets/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@
},
"starred": {
"type": "boolean",
"description": "Whether the caller has starred this project, which puts it in their sidebar. Always false where the caller is not a member, including an admin's non-member projects."
"description": "Whether the caller has starred this project, which puts it in their sidebar. Counts where the caller is a member or an admin."
}
}
}
Expand Down Expand Up @@ -612,7 +612,7 @@
},
"starred": {
"type": "boolean",
"description": "Whether the caller has starred this project, which puts it in their sidebar. Always false where the caller is not a member, including an admin's non-member projects."
"description": "Whether the caller has starred this project, which puts it in their sidebar. Counts where the caller is a member or an admin."
}
}
}
Expand Down Expand Up @@ -756,7 +756,7 @@
"Projects"
],
"summary": "Star project",
"description": "Stars the project for the caller, which puts it in their sidebar. Idempotent. Members only: an admin who is not a member gets 403.",
"description": "Stars the project for the caller, which puts it in their sidebar. Idempotent. Open to the project's members and to admins.",
"operationId": "starProject",
"parameters": [
{
Expand All @@ -783,9 +783,6 @@
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"403": {
"$ref": "#/components/responses/Forbidden"
},
"404": {
"$ref": "#/components/responses/NotFound"
}
Expand Down
11 changes: 6 additions & 5 deletions server/database/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -362,11 +362,12 @@ export const cardReads = sqliteTable('card_reads', {
uniqueIndex('card_reads_user_card_unique').on(table.userId, table.cardId)
])

// The projects a person keeps in their sidebar. Only members may star, and a
// row outlives a membership on purpose: `starred` is computed against current
// membership on every read (`/api/projects`, `/api/projects/[id]`), so a person
// removed from a project loses it from the sidebar without every removal path —
// member delete, agent pruning, transfers — having to remember this table.
// The projects a person keeps in their sidebar. Anyone who can see a project may
// star it (its members, and admins), and a row outlives that access on purpose:
// `starred` is computed against current membership or admin rights on every read
// (`/api/projects`, `/api/projects/[id]`), so a person removed from a project, or
// no longer an admin, loses it from the sidebar without every removal path —
// member delete, agent pruning, transfers, a demotion — having to remember this table.
export const projectStars = sqliteTable('project_stars', {
id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
Expand Down
12 changes: 10 additions & 2 deletions server/plugins/session-capabilities.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { eq } from 'drizzle-orm'

/**
* `canManageAgents` on the client's session user, read fresh on every session fetch.
* `isAdmin` and `canManageAgents` on the client's session user, read fresh on every
* session fetch.
*
* The sidebar's Agents entry and the `/agents` route guard need to know whether
* the signed-in person may create agents. The sealed session cookie cannot carry
Expand All @@ -12,10 +13,16 @@ import { eq } from 'drizzle-orm'
* cookie, so it is as fresh as the last page load. The server still decides every
* request on its own (`requireAgentCreator`, `resolveManagedAgent`); this only
* decides what the client offers.
*
* `isAdmin` has the same problem and the cookie copy was all the client had: an
* admin granted after sign-in saw no admin menu, no "Add people" in projects they
* were not in, and no star, until they signed out and back in, while the server
* (which reads it fresh in `requireActiveSession`) already let them do all of it.
* A demoted admin kept the controls the server then refused.
*/
export default defineNitroPlugin(() => {
sessionHooks.hook('fetch', (session) => {
const user = session.user as { id?: string, canManageAgents?: boolean } | undefined
const user = session.user as { id?: string, canManageAgents?: boolean, isAdmin?: boolean } | undefined
if (!user?.id) return

const row = db.select({
Expand All @@ -29,5 +36,6 @@ export default defineNitroPlugin(() => {
.get()

user.canManageAgents = !!row && canManageAgents(row)
user.isAdmin = !!row && row.kind === 'human' && !!row.isAdmin
})
})
29 changes: 29 additions & 0 deletions tests/integration/auth/session-admin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { describe, it, expect } from 'vitest'
import { $fetch } from '../../setup/server'
import { registerTestUser, createAdminUser } from '../../setup/auth'

/**
* The client reads `isAdmin` from `/api/_auth/session`. The sealed cookie holds the
* value from sign-in, so without the fetch hook in `server/plugins/session-capabilities.ts`
* an admin granted later saw the app as a non-admin until they signed in again
* (no "Add people" in projects they were not in, no star, no admin menu), and a
* demoted admin kept the controls.
*/
async function sessionIsAdmin(headers: Record<string, string>) {
const session = await $fetch('/api/_auth/session', { headers }) as { user?: { isAdmin?: boolean } }
return session.user?.isAdmin
}

describe('isAdmin in the session the client reads', () => {
it('follows a promotion and a demotion without signing in again', async () => {
const admin = await createAdminUser()
const user = await registerTestUser()
expect(await sessionIsAdmin(user.headers)).toBe(false)

await $fetch(`/api/admin/users/${user.id}`, { method: 'PATCH', body: { isAdmin: true }, headers: admin.headers })
expect(await sessionIsAdmin(user.headers)).toBe(true)

await $fetch(`/api/admin/users/${user.id}`, { method: 'PATCH', body: { isAdmin: false }, headers: admin.headers })
expect(await sessionIsAdmin(user.headers)).toBe(false)
})
})
50 changes: 36 additions & 14 deletions tests/integration/projects/star.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,28 +73,50 @@ describe('project stars', () => {
await expectError(unstar(outsider, project.id), 404)
})

it('refuses an admin who is not a member with 403, and never reports one as starred', async () => {
await expectError(star(admin, project.id), 403)
it('lets an admin who is not a member star it, and reports it starred', async () => {
// Admins see every project; one they look after without being in it belongs
// in their sidebar as much as their own.
const p = await createTestProject(owner)
expect(await star(admin, p.id)).toEqual({ starred: true })

expect((await listed(admin)).find(x => x.id === p.id)).toMatchObject({ role: 'admin', starred: true })
const detail = await $fetch(`/api/projects/${p.id}`, { headers: admin.headers }) as { starred: boolean, isMember: boolean }
expect(detail).toMatchObject({ starred: true, isMember: false })

const row = (await listed(admin)).find(p => p.id === project.id)
expect(row).toMatchObject({ role: 'admin', starred: false })
const detail = await $fetch(`/api/projects/${project.id}`, { headers: admin.headers }) as { starred: boolean, isMember: boolean }
expect(detail).toMatchObject({ starred: false, isMember: false })
expect(await unstar(admin, p.id)).toEqual({ starred: false })
expect((await listed(admin)).find(x => x.id === p.id)?.starred).toBe(false)
})

it('stops counting a star once its owner leaves the project', async () => {
// An admin, so the project stays visible after removal: the read has to
// check membership, not just find the row that was left behind.
it('keeps an admin\'s star after they leave the project, since they still see it', async () => {
const p = await createTestProject(owner)
await addMember(owner, p.id, admin.id)
await star(admin, p.id)
expect((await listed(admin)).find(x => x.id === p.id)?.starred).toBe(true)

await $fetch(`/api/projects/${p.id}/members/${admin.id}`, { method: 'DELETE', headers: owner.headers })

expect((await listed(admin)).find(x => x.id === p.id)).toMatchObject({ role: 'admin', starred: false })
const detail = await $fetch(`/api/projects/${p.id}`, { headers: admin.headers }) as { starred: boolean }
expect(detail.starred).toBe(false)
expect((await listed(admin)).find(x => x.id === p.id)).toMatchObject({ role: 'admin', starred: true })
})

it('stops counting a star once its owner can no longer see the project', async () => {
// A star on a project the person was removed from, or starred as an admin who
// is no longer one, is left in the table; the read must not count it.
const removed = await createAdminUser()
const p = await createTestProject(owner)
await addMember(owner, p.id, removed.id)
await star(removed, p.id)
const q = await createTestProject(owner)
await star(removed, q.id)

await $fetch(`/api/projects/${p.id}/members/${removed.id}`, { method: 'DELETE', headers: owner.headers })
await $fetch(`/api/admin/users/${removed.id}`, { method: 'PATCH', body: { isAdmin: false }, headers: admin.headers })

const ids = (await listed(removed)).map(x => x.id)
expect(ids).not.toContain(p.id)
expect(ids).not.toContain(q.id)
await expectError($fetch(`/api/projects/${q.id}`, { headers: removed.headers }), 404)

// The row was kept on purpose, so re-admitted as a member they find it starred again.
await addMember(owner, p.id, removed.id)
expect((await listed(removed)).find(x => x.id === p.id)?.starred).toBe(true)
})

it('lists projects alphabetically, ignoring case and reading numbers as numbers', async () => {
Expand Down
Loading