diff --git a/src/backend/controllers/fs/sharedFolderWrites.http.test.ts b/src/backend/controllers/fs/sharedFolderWrites.http.test.ts index 01c94e622..9fc195f49 100644 --- a/src/backend/controllers/fs/sharedFolderWrites.http.test.ts +++ b/src/backend/controllers/fs/sharedFolderWrites.http.test.ts @@ -277,4 +277,124 @@ describe('writes inside a folder shared with write', () => { expect(JSON.stringify(res.json)).not.toContain(s.realDir); } }, 180_000); + + describe('a file the recipient opened with an app', () => { + const makeApp = (ownerUserId: number) => + ( + env.server.stores.app.create as unknown as ( + fields: Record, + opts: { ownerUserId: number }, + ) => Promise<{ uid: string; id: number }> + )( + { + name: `sfw-app-${Math.random().toString(36).slice(2, 9)}`, + title: 'Shared folder app', + index_url: `https://sfw-${Math.random().toString(36).slice(2, 9)}.test/`, + }, + { ownerUserId }, + ); + + /** Opens `note.txt` with a new app, as a launch does. */ + const openWithApp = async ( + s: Awaited>, + ) => { + const recipientId = (await env.server.stores.user.getByUsername( + s.recipient.username, + ))!.id; + const app = await makeApp(recipientId); + const signed = await post('/sign', s.recipient.token, { + items: [{ uid: s.noteUid, action: 'write' }], + app_uid: app.uid, + }); + expect(signed.status).toBe(200); + return { app, appToken: signed.json!.token as string }; + }; + + const read = async (token: string, query: Record) => { + const res = await fetch( + new URL(`/read?${new URLSearchParams(query)}`, env.apiOrigin), + { headers: { authorization: `Bearer ${token}` } }, + ); + return { status: res.status, text: await res.text() }; + }; + + const write = (token: string, path: string, content: string) => + post('/fs/write', token, { + fileMetadata: { + path, + size: content.length, + contentType: 'text/plain', + overwrite: true, + }, + fileContent: content, + }); + + it('reads and saves it by path and uid', async () => { + const s = await shareAFolder(); + const { appToken } = await openWithApp(s); + const masked = `${s.maskedDir}/note.txt`; + const real = `${s.realDir}/note.txt`; + + expect((await write(appToken, masked, 'one')).status).toBe(200); + expect(await read(appToken, { uid: s.noteUid })).toEqual({ + status: 200, + text: 'one', + }); + expect((await write(appToken, real, 'two')).status).toBe(200); + expect(await read(appToken, { file: real })).toEqual({ + status: 200, + text: 'two', + }); + expect( + (await post('/stat', appToken, { uid: s.noteUid })).status, + ).toBe(200); + }, 180_000); + + it('only reads it once the share drops to read', async () => { + const s = await shareAFolder(); + const { appToken } = await openWithApp(s); + const dir = await post('/stat', s.owner.token, { path: s.realDir }); + const reshared = await post('/share', s.owner.token, { + recipients: [s.recipient.username], + items: [{ uid: dir.json!.uid }], + mode: 'read', + }); + expect(reshared.status).toBe(200); + + expect((await read(appToken, { uid: s.noteUid })).status).toBe(200); + expect( + (await write(appToken, `${s.maskedDir}/note.txt`, 'x')).status, + ).toBe(403); + }, 180_000); + + it('gives nothing to another app of the recipient', async () => { + const s = await shareAFolder(); + const { appToken } = await openWithApp(s); + const recipientId = (await env.server.stores.user.getByUsername( + s.recipient.username, + ))!.id; + const other = await makeApp(recipientId); + const minted = await post( + '/auth/get-user-app-token', + s.recipient.token, + { app_uid: other.uid }, + ); + expect(minted.status).toBe(200); + const otherToken = minted.json!.token as string; + + // The same requests the opened app gets through. + const real = `${s.realDir}/note.txt`; + expect((await read(appToken, { uid: s.noteUid })).status).toBe(200); + expect((await write(appToken, real, 'one')).status).toBe(200); + + expect((await read(otherToken, { uid: s.noteUid })).status).toBe( + 404, + ); + expect((await write(otherToken, real, 'x')).status).toBe(404); + expect(await read(appToken, { uid: s.noteUid })).toEqual({ + status: 200, + text: 'one', + }); + }, 180_000); + }); }); diff --git a/src/backend/services/acl/ACLService.test.ts b/src/backend/services/acl/ACLService.test.ts index 29336b92b..7a720648a 100644 --- a/src/backend/services/acl/ACLService.test.ts +++ b/src/backend/services/acl/ACLService.test.ts @@ -83,6 +83,8 @@ function makeService() { permission: { // Default: token carries no explicit fs grant rows. hasAnyAccessTokenPerm: vi.fn().mockResolvedValue(false), + // Default: the user granted the app nothing. + readUserAppPerms: vi.fn().mockResolvedValue([]), }, user: { getByUsername: vi.fn().mockResolvedValue(null), @@ -1450,6 +1452,252 @@ describe('ACLService.statUserUser / setUserUser (integration)', () => { ).toBe(false); }); + describe('a file opened with the app inside a shared folder', () => { + /** `Documents/` of an issuer, shared with a holder at `mode`. */ + const sharedFile = async (mode: 'read' | 'write') => { + const issuer = await makeUser(); + const holder = await makeUser(); + const folder = await ownedResource(issuer); + const path = `${folder.path}/note-${uuidv4()}.txt`; + const entry = await server.services.fs.touch(issuer.user.id!, { + path, + }); + await runWithContext({ actor: issuer }, () => + acl.setUserUser(issuer, holder, folder, mode), + ); + return { issuer, holder, folder, path, uid: entry.uuid }; + }; + + const open = (user: Actor, app: { uid: string }, uid: string) => + runWithContext({ actor: user }, () => + server.services.permission.grantUserAppPermission( + user, + app.uid, + `fs:${uid}:write`, + ), + ); + + it('reads and writes it', async () => { + const { holder, path, uid } = await sharedFile('write'); + const app = await makeApp(holder.user.id!); + await open(holder, app, uid); + + const file = () => acl.fsDescriptor(path); + expect( + await acl.check(asApp(holder, app), file(), 'read'), + ).toBe(true); + expect( + await acl.check(asApp(holder, app), file(), 'write'), + ).toBe(true); + }); + + it('can only read it once the share drops to read', async () => { + const { issuer, holder, folder, path, uid } = + await sharedFile('write'); + const app = await makeApp(holder.user.id!); + await open(holder, app, uid); + await runWithContext({ actor: issuer }, () => + acl.setUserUser(issuer, holder, folder, 'read'), + ); + + const file = () => acl.fsDescriptor(path); + expect(await acl.check(holder, file(), 'write')).toBe(false); + expect( + await acl.check(asApp(holder, app), file(), 'read'), + ).toBe(true); + expect( + await acl.check(asApp(holder, app), file(), 'write'), + ).toBe(false); + }); + + it('gives nothing to another app of the same user', async () => { + const { holder, path, uid } = await sharedFile('write'); + const opened = await makeApp(holder.user.id!); + const other = await makeApp(holder.user.id!); + await open(holder, opened, uid); + + expect( + await acl.check( + asApp(holder, other), + acl.fsDescriptor(path), + 'read', + ), + ).toBe(false); + }); + + it('reaches it through a token the app issued', async () => { + const { holder, path, uid } = await sharedFile('write'); + const app = await makeApp(holder.user.id!); + await open(holder, app, uid); + const tokenUid = `tok-${uuidv4()}`; + await server.clients.db.write( + 'INSERT INTO `access_token_permissions` (`token_uid`, `permission`) VALUES (?, ?)', + [tokenUid, `fs:${uid}:read`], + ); + const token = makeActor({ + user: holder.user, + accessToken: { + uid: tokenUid, + issuer: asApp(holder, app), + authorized: null, + fullAccess: false, + }, + }); + + const file = () => acl.fsDescriptor(path); + expect(await acl.check(token, file(), 'read')).toBe(true); + expect(await acl.check(token, file(), 'write')).toBe(false); + }); + + it('reaches a file below a folder it was granted, and no sibling of a granted file', async () => { + const { issuer, holder, folder, path, uid } = + await sharedFile('write'); + const sub = `${folder.path}/sub-${uuidv4()}`; + const dir = await server.services.fs.mkdir(issuer.user.id!, { + path: sub, + } as never); + const below = `${sub}/below.txt`; + await server.services.fs.touch(issuer.user.id!, { + path: below, + }); + const folderApp = await makeApp(holder.user.id!); + const fileApp = await makeApp(holder.user.id!); + await open(holder, folderApp, (dir as { uuid: string }).uuid); + await open(holder, fileApp, uid); + + const at = (p: string) => acl.fsDescriptor(p); + expect( + await acl.check( + asApp(holder, folderApp), + at(below), + 'write', + ), + ).toBe(true); + expect( + await acl.check(asApp(holder, fileApp), at(path), 'write'), + ).toBe(true); + expect( + await acl.check(asApp(holder, fileApp), at(below), 'read'), + ).toBe(false); + }); + + it('is refused once the share is withdrawn, though its grant stays', async () => { + const { issuer, holder, folder, path, uid } = + await sharedFile('write'); + const app = await makeApp(holder.user.id!); + await open(holder, app, uid); + await runWithContext({ actor: issuer }, () => + server.services.permission.revokeUserUserPermission( + issuer, + holder.user.username!, + `fs:${folder.uid}:write`, + ), + ); + + const file = () => acl.fsDescriptor(path); + expect(await acl.check(holder, file(), 'read')).toBe(false); + expect( + await acl.check(asApp(holder, app), file(), 'read'), + ).toBe(false); + }); + + it('cannot write with a read grant while its user can write', async () => { + const { holder, path, uid } = await sharedFile('write'); + const app = await makeApp(holder.user.id!); + await runWithContext({ actor: holder }, () => + server.services.permission.grantUserAppPermission( + holder, + app.uid, + `fs:${uid}:read`, + ), + ); + + const file = () => acl.fsDescriptor(path); + expect(await acl.check(holder, file(), 'write')).toBe(true); + expect( + await acl.check(asApp(holder, app), file(), 'read'), + ).toBe(true); + expect( + await acl.check(asApp(holder, app), file(), 'write'), + ).toBe(false); + }); + + const shareFile = (issuer: Actor, holder: Actor, path: string) => + runWithContext({ actor: issuer }, () => + acl.setUserUser( + issuer, + holder, + acl.fsDescriptor(path), + 'write', + ), + ); + + it('counts a folder grant only while the user holds that folder', async () => { + const { issuer, holder, folder, path } = + await sharedFile('write'); + const app = await makeApp(holder.user.id!); + await open(holder, app, folder.uid); + await runWithContext({ actor: issuer }, () => + server.services.permission.revokeUserUserPermission( + issuer, + holder.user.username!, + `fs:${folder.uid}:write`, + ), + ); + await shareFile(issuer, holder, path); + + const file = () => acl.fsDescriptor(path); + expect(await acl.check(holder, folder, 'see')).toBe(false); + expect(await acl.check(holder, file(), 'write')).toBe(true); + expect( + await acl.check(asApp(holder, app), file(), 'read'), + ).toBe(false); + + await runWithContext({ actor: issuer }, () => + acl.setUserUser(issuer, holder, folder, 'write'), + ); + expect( + await acl.check(asApp(holder, app), file(), 'write'), + ).toBe(true); + }); + + it('does not count a grant on a folder the user never held', async () => { + const issuer = await makeUser(); + const holder = await makeUser(); + const folder = await ownedResource(issuer); + const path = `${folder.path}/note-${uuidv4()}.txt`; + await server.services.fs.touch(issuer.user.id!, { path }); + const app = await makeApp(holder.user.id!); + await open(holder, app, folder.uid); + await shareFile(issuer, holder, path); + + const file = () => acl.fsDescriptor(path); + expect(await acl.check(holder, file(), 'write')).toBe(true); + expect( + await acl.check(asApp(holder, app), file(), 'read'), + ).toBe(false); + }); + + it('leaves a file the user owns as it was', async () => { + const user = await makeUser(); + const path = `/${user.user.username}/Documents/own-${uuidv4()}.txt`; + const entry = await server.services.fs.touch(user.user.id!, { + path, + }); + const opened = await makeApp(user.user.id!); + const other = await makeApp(user.user.id!); + await open(user, opened, entry.uuid); + + const file = () => acl.fsDescriptor(path); + expect( + await acl.check(asApp(user, opened), file(), 'write'), + ).toBe(true); + expect( + await acl.check(asApp(user, other), file(), 'read'), + ).toBe(false); + }); + }); + describe("another app's AppData", () => { /** `//AppData//inner`, as the app would leave it. */ const seedAppData = async (user: Actor, appUid: string) => { @@ -1499,6 +1747,36 @@ describe('ACLService.statUserUser / setUserUser (integration)', () => { ).toBe(true); }); + it('stays closed to an app granted the home or AppData of a user who shared them', async () => { + const issuer = await makeUser(); + const holder = await makeUser(); + const closed = await makeApp(issuer.user.id!, { + metadata: JSON.stringify({ share_app_data: false }), + }); + const root = await seedAppData(issuer, closed.uid); + const inner = acl.fsDescriptor(`${root}/inner`); + const home = `/${issuer.user.username}`; + await runWithContext({ actor: issuer }, () => + acl.setUserUser( + issuer, + holder, + acl.fsDescriptor(home), + 'write', + ), + ); + expect(await acl.check(holder, inner, 'read')).toBe(true); + + for (const target of [home, `${home}/AppData`]) { + const entry = + await server.stores.fsEntry.getEntryByPath(target); + const reader = await makeApp(holder.user.id!); + await grantTo(holder, reader, `fs:${entry!.uuid}:read`); + expect( + await acl.check(asApp(holder, reader), inner, 'read'), + ).toBe(false); + } + }); + it('opens to an fs grant while that app shares', async () => { const user = await makeUser(); const open = await makeApp(user.user.id!); diff --git a/src/backend/services/acl/ACLService.ts b/src/backend/services/acl/ACLService.ts index c0af2d4a7..31adf4166 100644 --- a/src/backend/services/acl/ACLService.ts +++ b/src/backend/services/acl/ACLService.ts @@ -57,11 +57,7 @@ export interface ResourceDescriptor { } export type AclMode = - | 'see' - | 'list' - | 'read' - | 'write' - | typeof MANAGE_PERM_PREFIX; + 'see' | 'list' | 'read' | 'write' | typeof MANAGE_PERM_PREFIX; /** Duck-typed error shape compatible with APIError consumers (fsv2). */ export interface AclError { @@ -296,6 +292,10 @@ export class ACLService extends PuterService { ) { return true; } + + // Capped by the user check above, given the app's own grant. + if (await this.#userAppGrantReaches(actor, await ancestors(), mode)) + return true; } // Fall back to the permission scan: walk ancestors, any hit wins. @@ -329,6 +329,47 @@ export class ACLService extends PuterService { return this.#anyoneWithLinkAllows(actor, ancestry, mode); } + /** + * Whether the user granted this app `mode` on the node, or on a folder + * above it that the user holds `mode` on too. + */ + async #userAppGrantReaches( + actor: Actor, + ancestors: ReadonlyArray<{ uid: string; path: string }>, + mode: AclMode, + ): Promise { + const appId = actor.app?.id; + const userId = actor.user?.id; + if (typeof appId !== 'number' || typeof userId !== 'number') { + return false; + } + const rows = await this.stores.permission.readUserAppPerms( + userId, + appId, + ancestors.flatMap((ancestor) => + this.permissionsFor(ancestor.uid, mode), + ), + ); + if (rows.length === 0) return false; + + const granted = new Set(rows.map((row) => row.permission)); + const userActor: Actor = { user: actor.user, effectiveApp: null }; + for (const [depth, ancestor] of ancestors.entries()) { + const grantedHere = this.permissionsFor(ancestor.uid, mode).some( + (permission) => granted.has(permission), + ); + if (!grantedHere) continue; + // The caller already checked the user on the node itself. + if (depth === 0) return true; + const folder: ResourceDescriptor = { + path: ancestor.path, + resolveAncestors: async () => ancestors.slice(depth), + }; + if (await this.check(userActor, folder, mode)) return true; + } + return false; + } + /** * "Anyone with the link": the owner switched the node open to every * signed-in account, at `read` or `write`. Honoured only while the owner's diff --git a/src/backend/services/permission/PermissionService.test.ts b/src/backend/services/permission/PermissionService.test.ts index d3518234d..aa392e144 100644 --- a/src/backend/services/permission/PermissionService.test.ts +++ b/src/backend/services/permission/PermissionService.test.ts @@ -2017,6 +2017,42 @@ describe('PermissionService — scan paths', () => { ).toBe(true); }); + it('scans the user for an app only when an option is implied for it', async () => { + const { row, actor } = await makeGroupedUser(); + const app = await makeApp(row.id); + const appActor: Actor = makeActor({ + user: actor.user, + app: { uid: app.uid, id: app.id }, + }); + const scan = vi.spyOn(permService, 'scan'); + const userScans = () => + scan.mock.calls.filter( + ([scanned]) => !scanned.app && !scanned.accessToken, + ).length; + const scanAsApp = (permission: string) => + permService.scan(appActor, permission, undefined, { + noCache: true, + }); + try { + expect( + await scanAsApp(`zztest:none-${uuidv4()}:ii:read`), + ).not.toContainEqual( + expect.objectContaining({ source: 'user-app-implied' }), + ); + expect(userScans()).toBe(0); + + expect(await scanAsApp('driver:puter-kvstore')).toContainEqual( + expect.objectContaining({ + source: 'user-app-implied', + has_terminal: true, + }), + ); + expect(userScans()).toBeGreaterThan(0); + } finally { + scan.mockRestore(); + } + }); + it('resolves a user-to-app grant, and stops once revoked', async () => { const { row, actor } = await makeGroupedUser(); const app = await makeApp(row.id); diff --git a/src/backend/services/permission/PermissionService.ts b/src/backend/services/permission/PermissionService.ts index 78dbd7df7..a09ba02a5 100644 --- a/src/backend/services/permission/PermissionService.ts +++ b/src/backend/services/permission/PermissionService.ts @@ -735,26 +735,16 @@ export class PermissionService extends PuterService { // `#scanAccessToken`, bounded by its own rows. Reading the chain here // would hand it the issuing app's grants unbounded. if (!actor.app) return; - const issuerActor = userRelatedActor(actor); - const issuerReading = await this.scan(issuerActor, options); - const hasTerminal = readingHasTerminal(issuerReading); const appUid = actor.app.uid; + const found: Array<{ permission: string; by: string; data: unknown }> = + []; for (const permission of options) { const implied = ( default_implicit_user_app_permissions as Record )[permission]; if (implied) { - reading.push({ - $: 'path', - permission, - has_terminal: hasTerminal, - source: 'user-app-implied', - by: 'user-app-hc-1', - data: implied, - issuer_username: actor.user?.username, - reading: issuerReading, - }); + found.push({ permission, by: 'user-app-hc-1', data: implied }); } // per-app hardcoded overrides @@ -768,18 +758,30 @@ export class PermissionService extends PuterService { } } if (hits[permission]) { - reading.push({ - $: 'path', + found.push({ permission, - has_terminal: hasTerminal, - source: 'user-app-implied', by: 'user-app-hc-2', data: hits[permission], - issuer_username: actor.user?.username, - reading: issuerReading, }); } } + // The user is scanned only when an option is implied for the app. + if (found.length === 0) return; + + const issuerReading = await this.scan(userRelatedActor(actor), options); + const hasTerminal = readingHasTerminal(issuerReading); + for (const { permission, by, data } of found) { + reading.push({ + $: 'path', + permission, + has_terminal: hasTerminal, + source: 'user-app-implied', + by, + data, + issuer_username: actor.user?.username, + reading: issuerReading, + }); + } } async #scanUserApp(