diff --git a/src/mms/net/NetService.ts b/src/mms/net/NetService.ts index d8947cb0fc..6ae54da8f6 100644 --- a/src/mms/net/NetService.ts +++ b/src/mms/net/NetService.ts @@ -453,8 +453,9 @@ export class NetService { typeof cfg.features.netSpaces !== 'boolean' || (cfg.features.netBridgeThreads !== undefined && typeof cfg.features.netBridgeThreads !== 'boolean') || + (cfg.features.netTeams !== undefined && typeof cfg.features.netTeams !== 'boolean') || Object.keys(cfg.features).some( - (key) => !['netBridge', 'netSpaces', 'netBridgeThreads'].includes(key) + (key) => !['netBridge', 'netSpaces', 'netBridgeThreads', 'netTeams'].includes(key) )) ) { throw new NetError('storage_corrupt') @@ -489,6 +490,9 @@ export class NetService { identity, executions, clock: this.clock, + // Teammates: the flag, the default directory (it knows no team) and no thread lookup yet, so every + // call from another person is still refused, as before the flag. + teams: { enabled: () => this.featureEnabled('netTeams') }, authorizeMethod: (method, peer) => { this.assertEnabled() if (method.family === 'bridge' || method.family === 'routed') @@ -743,14 +747,18 @@ export class NetService { const { db } = this.runtime() // An earlier version rejects any other key in `features` as corrupt storage and then fails to load Net // at all. The routing flag is on by default, so it is written only while it is off: a profile that - // never turned it off can go back to an earlier build. + // never turned it off can go back to an earlier build. The teams flag is off by default, so it is + // written only while it is on. const { features, ...rest } = this.config const stored: NetConfiguration = features ? { ...rest, - features: features.netBridgeThreads - ? ({ netBridge: features.netBridge, netSpaces: features.netSpaces } as NetFeatureFlags) - : features + features: { + netBridge: features.netBridge, + netSpaces: features.netSpaces, + ...(features.netBridgeThreads ? {} : { netBridgeThreads: features.netBridgeThreads }), + ...(features.netTeams === true ? { netTeams: true } : {}) + } as NetFeatureFlags } : rest const bytes = canonicalJson(stored) @@ -1101,7 +1109,8 @@ export class NetService { this.config.features = { netBridge: true, netSpaces: true, - netBridgeThreads: this.config.features?.netBridgeThreads !== false + netBridgeThreads: this.config.features?.netBridgeThreads !== false, + ...(this.config.features?.netTeams === true ? { netTeams: true } : {}) } if (input.listen) this.config.direct = { @@ -2655,7 +2664,8 @@ export class NetService { this.config.features = { netBridge: true, netSpaces: true, - netBridgeThreads: this.config.features?.netBridgeThreads !== false + netBridgeThreads: this.config.features?.netBridgeThreads !== false, + ...(this.config.features?.netTeams === true ? { netTeams: true } : {}) } this.config.preparedForJoin = false this.saveConfig() @@ -2856,7 +2866,9 @@ export class NetService { !this.stopped && !this.disabled && this.config.enabled && - this.config.features?.[feature] === true + this.config.features?.[feature] === true && + // Teams reach threads through Bridge's routed path, so the flag counts only while Bridge is on. + (feature !== 'netTeams' || this.config.features.netBridge === true) ) } assertFeature(feature: keyof NetFeatureFlags): void { diff --git a/src/mms/net/sync/rpcDispatcher.ts b/src/mms/net/sync/rpcDispatcher.ts index 1afceb1361..6a4a31eb7f 100644 --- a/src/mms/net/sync/rpcDispatcher.ts +++ b/src/mms/net/sync/rpcDispatcher.ts @@ -13,6 +13,25 @@ import type { import type { NetDatabase } from '../store/database' import { canonicalJson } from './codec' import type { SessionRpcPort } from './session' +import { ROUTED_METHODS, routedMethodOf } from '../../../shared/bridge/routed' +import type { TeamAccessDecision, TeamDirectory } from '../../../shared/teams/types' +import { DENY_ALL_TEAM_DIRECTORY, teamAccess } from '../../teams/access' + +/** + * What the access decision for a call from another person reads (`mms/teams/access.ts`). Without it, or with + * the flag off, every such call is refused as it always was. + */ +export interface TeamAccessPort { + /** The `netTeams` flag, read on every call. */ + enabled(): boolean + /** Default: knows no team, so nobody else is let in. */ + directory?: TeamDirectory + /** + * Whether the thread is kept on this computer only (`Thread.localOnly`). Without it every thread counts as + * kept here, so nothing is shared. + */ + localOnly?(threadId: string): boolean +} /** Settled request rows and their aliases are kept this long; no retry window comes close. */ export const LEDGER_RETENTION_MS = 7 * 24 * 60 * 60 * 1000 @@ -58,6 +77,8 @@ export class DurableRpcDispatcher implements RpcDispatcher, SessionRpcPort { peer: SyncSession['peer'], capability: NodeCapability ): void + /** Calls from another person (a teammate); absent refuses them all. */ + teams?: TeamAccessPort } ) { options.db.database.exec( @@ -179,7 +200,7 @@ export class DurableRpcDispatcher implements RpcDispatcher, SessionRpcPort { if (!method) throw new NetError('forbidden') params = method.validate ? method.validate(params) : params const capability = method.capabilityFor?.(params) ?? method.capability - this.authorize(name, context.caller, capability) + this.authorize(name, context.caller, capability, params) method.authorize?.(params, context) if (method.mutating && !method.sequenced && (!idem || idem.length > 256)) throw new NetError('bad_request', 'Mutations need durable idempotency.') @@ -189,7 +210,7 @@ export class DurableRpcDispatcher implements RpcDispatcher, SessionRpcPort { if (context.signal.aborted) throw new NetError('cancelled') if (method.ephemeral || method.sequenced) { const returned = await method.handle(params, context) - this.authorize(name, context.caller, capability) + this.authorize(name, context.caller, capability, params) const result = returned === undefined ? null : returned if (canonicalJson(result).byteLength > 63 * 1024) throw new NetError('too_large') return result @@ -224,7 +245,7 @@ export class DurableRpcDispatcher implements RpcDispatcher, SessionRpcPort { context.signal.addEventListener('abort', abort, { once: true }) this.running.set(id, { controller, caller: context.caller.node }) try { - this.authorize(name, context.caller, capability) + this.authorize(name, context.caller, capability, params) method.authorize?.(params, context) method.authorizeNew?.(params, context) if (context.signal.aborted) throw new NetError('cancelled') @@ -243,7 +264,7 @@ export class DurableRpcDispatcher implements RpcDispatcher, SessionRpcPort { }) throw new NetError('outcome_uncertain') } - this.authorize(name, context.caller, capability) + this.authorize(name, context.caller, capability, params) let publication: { result: unknown; commit(): void } | undefined if (bytes.byteLength > 63 * 1024) { if (!this.resultPublisher) @@ -347,15 +368,26 @@ export class DurableRpcDispatcher implements RpcDispatcher, SessionRpcPort { | { method: string; payload_hash: string; execution: string; capability?: NodeCapability } | undefined } + /** + * `params` is the call's, when there is one: a call from another person is let in only for a call that names + * the thread it acts on, so looking up a result or cancelling (which carry no params) refuses that person. + */ private authorize( name: string, peer: SyncSession['peer'], - capability?: NodeCapability + capability?: NodeCapability, + params?: unknown ): RpcMethod { const method = this.registry.get(name), identity = this.options.identity, self = identity.self() - if (!method || !self || peer.user !== self.user) throw new NetError('forbidden') + if (!method || !self) throw new NetError('forbidden') + // The same-person check. Another person gets the same `forbidden` as always unless the one access decision + // lets them in; then their computer is held to their own roster below, like one of ours. + // Still same-person only, for a later change: the Bridge hub service, artifacts, `nodeAuthority`, and the + // session admission in `NetService`. + if (peer.user !== self.user && this.teamDecision(method, peer, self, params) !== 'allow') + throw new NetError('forbidden') const root = identity.pinnedRootKey(peer.user), signed = identity.roster(peer.user) if (!root || !signed || identity.rosterState(peer.user) !== 'ok') @@ -389,6 +421,33 @@ export class DurableRpcDispatcher implements RpcDispatcher, SessionRpcPort { this.options.authorizeMethod?.(method, peer, required) return method } + private teamDecision( + method: RpcMethod, + peer: SyncSession['peer'], + self: { user: SyncSession['peer']['user']; node: NodeId }, + params: unknown + ): TeamAccessDecision['kind'] { + const teams = this.options.teams + if (!teams) return 'deny' + const routed = method.family === 'routed' ? routedMethodOf(method.method) : undefined + const row = routed !== undefined && Object.hasOwn(ROUTED_METHODS, routed) ? ROUTED_METHODS[routed] : undefined + const named = + row && params && typeof params === 'object' + ? (params as Record)[row.threadIds?.[0] ?? 'threadId'] + : undefined + const target = + typeof named === 'string' + ? { threadId: named, localOnly: teams.localOnly ? teams.localOnly(named) : true } + : undefined + return teamAccess({ + peer, + self, + row, + target, + flags: { netTeams: teams.enabled() }, + directory: teams.directory ?? DENY_ALL_TEAM_DIRECTORY + }).kind + } private terminal(record: ExecutionRecord): unknown { if (record.state === 'completed') { // A large result was not kept; the request did complete, but its answer cannot be replayed. diff --git a/src/mms/protocol/threadVisibility.ts b/src/mms/protocol/threadVisibility.ts index c960a2fca8..928b604db6 100644 --- a/src/mms/protocol/threadVisibility.ts +++ b/src/mms/protocol/threadVisibility.ts @@ -1,5 +1,8 @@ import type { Project, Thread, ThreadActivitySnapshot } from '../../shared/types' import { isLocalOnlyThread, visibleThreads } from '../../shared/threadLineage' +import type { UserId } from '../../shared/net/ids' +import type { TeamDirectory, TeamId } from '../../shared/teams/types' +import { personMaySeeThread } from '../teams/access' import type { RemoteListsPort } from './remoteListsPort' import type { ProtocolClientType, ProtocolEvent } from './types' @@ -38,17 +41,48 @@ export function withoutBotThreads>(threads: r return threads.filter((thread) => !thread.botOwned) } +/** + * A caller who is another person (a teammate), with what this computer knows of its team. Reached only through + * the access decision for teams (`mms/teams/access.ts`), which refuses everyone while `netTeams` is off. + */ +export interface TeamPerson { + readonly user: UserId + /** This computer's team, if it is in one. */ + readonly team: TeamId | undefined + readonly directory: TeamDirectory +} + +/** + * `threads` that `person` may see: only those the team directory opens to them, and never one kept on this + * computer only (`Thread.localOnly`, including a subagent of such a thread), whatever the connection. + */ +export function threadsForPerson>( + person: TeamPerson, + threads: readonly T[], + inventory: readonly Pick[] = threads as unknown as readonly Pick[] +): T[] { + return threads.filter((thread) => + personMaySeeThread(person.directory, person.team, person.user, { + id: thread.id, + localOnly: isLocalOnlyThread(thread, inventory) + }) + ) +} + /** * `threads` as `connection` should see them. `inventory` is the complete list parents are looked up * in; give it whenever `threads` is a slice (one project), so a slice never makes a parent look * missing and a subagent look orphaned. Filtering happens here, before any limit a caller applies. + * `person` is given only for a caller who is another person (`threadsForPerson`). */ export function visibleThreadsFor( connection: { readonly clientType?: ProtocolClientType } | undefined, threads: readonly Thread[], - inventory: readonly Thread[] = threads + inventory: readonly Thread[] = threads, + person?: TeamPerson ): Thread[] { - const shared = withoutLocalOnlyFor(connection, withoutBotThreads(threads), inventory) + const listed = withoutLocalOnlyFor(connection, withoutBotThreads(threads), inventory) + const shared = person ? threadsForPerson(person, listed, inventory) : listed return connectionSeesSubagents(connection) ? shared : visibleThreads(shared, inventory) } diff --git a/src/mms/teams/access.ts b/src/mms/teams/access.ts new file mode 100644 index 0000000000..e860e896c2 --- /dev/null +++ b/src/mms/teams/access.ts @@ -0,0 +1,88 @@ +/** + * The one access decision for a routed call from another person (`docs/plans/teams-architecture.md` §6.5.3). + * Pure: the caller hands in the flag, the row, the target thread and the team directory. + */ +import type { NodeId, UserId } from '../../shared/net/ids' +import type { + TeamAccessDecision, + TeamDirectory, + TeamId, + ThreadAccess +} from '../../shared/teams/types' + +/** Knows no team, so it refuses every other person. The default until a team's Space provides one. */ +export const DENY_ALL_TEAM_DIRECTORY: TeamDirectory = Object.freeze({ + teamOf: () => undefined, + isActiveMember: () => false, + threadAccess: () => undefined +}) + +/** The thread a call acts on, as this computer knows it. */ +export interface TeamAccessTarget { + threadId: string + /** Kept on this computer only (`Thread.localOnly`, including by lineage). */ + localOnly: boolean +} + +export interface TeamAccessInput { + peer: { user: UserId; node: NodeId } + self: { user: UserId; node: NodeId } + /** The routed row the call names; undefined for any other Net method. */ + row: { crossUser?: true } | undefined + /** Undefined when the call names no thread (or it is not known here). */ + target: TeamAccessTarget | undefined + flags: { netTeams?: boolean } + directory: TeamDirectory +} + +const deny = (reason: Extract['reason']): TeamAccessDecision => ({ + kind: 'deny', + reason +}) + +/** Whether `access` lets `user` reach the thread: its owner, a listed person, or any member when it is open to the team. */ +export function threadAccessAllows(access: ThreadAccess | undefined, user: UserId): boolean { + return ( + !!access && (access.owner === user || access.people.includes(user) || access.openToTeam === true) + ) +} + +/** Whether `user`, a member of `team`, may see the thread. A thread kept on this computer only never is. */ +export function personMaySeeThread( + directory: TeamDirectory, + team: TeamId | undefined, + user: UserId, + thread: { id: string; localOnly: boolean } +): boolean { + return ( + !thread.localOnly && + team !== undefined && + directory.isActiveMember(team, user) && + threadAccessAllows(directory.threadAccess(thread.id), user) + ) +} + +/** + * Same person: today's checks, unchanged. Anyone else is refused unless every step passes, in this order: + * the flag is on, the row is marked `crossUser`, the thread is not kept on this computer only, the person is + * an active member of this computer's team, and the thread is open to them. + */ +export function teamAccess({ + peer, + self, + row, + target, + flags, + directory +}: TeamAccessInput): TeamAccessDecision { + if (peer.user === self.user) return { kind: 'same_person' } + if (flags.netTeams !== true) return deny('teams_off') + if (row?.crossUser !== true) return deny('row_not_cross_user') + if (!target) return deny('no_thread_access') + if (target.localOnly) return deny('local_only') + const team = directory.teamOf(self.node) + if (team === undefined || !directory.isActiveMember(team, peer.user)) return deny('not_team_member') + return threadAccessAllows(directory.threadAccess(target.threadId), peer.user) + ? { kind: 'allow' } + : deny('no_thread_access') +} diff --git a/src/shared/bridge/routed.ts b/src/shared/bridge/routed.ts index ccbdbae53d..8e51eac4d6 100644 --- a/src/shared/bridge/routed.ts +++ b/src/shared/bridge/routed.ts @@ -85,6 +85,12 @@ export interface RoutedRow { * the call, so a staged call is held to the row's keys exactly like an inline one. */ stageable?: readonly string[] + /** + * Another person (a teammate, not another of the user's own computers) may call the row, once the access + * decision allows it (`mms/teams/access.ts`). Absent means refused: the table stays deny-by-default for people. + * Set only through `CROSS_USER_METHODS`. + */ + crossUser?: true } const FOLDER = ['threadId', 'projectId'] as const @@ -151,7 +157,41 @@ export const ROUTED_FORBIDDEN_KEYS = [ 'root' ] as const -export const ROUTED_METHODS: Readonly> = Object.freeze({ +/** + * The rows a teammate may call on a shared thread, once `netTeams` is on and the access decision allows it: + * reading the thread, sending, steering, stopping, answering its questions, its queue and its review diff. + * Terminals, the editor, Undo and Publish are not here. `tests/net/bridge/routed/table.test.ts` holds this list. + */ +export const CROSS_USER_METHODS: readonly string[] = Object.freeze([ + 'threads.get', + 'thread.snapshot', + 'thread.messages', + 'thread.changesSince', + 'thread.messageImage', + 'orchestrator.send', + 'orchestrator.steer', + 'orchestrator.abort', + 'orchestrator.answerQuestions', + 'queue.list', + 'queue.enqueue', + 'queue.edit', + 'queue.reorder', + 'queue.remove', + 'queue.promoteToSteer', + 'review.files', + 'review.file' +]) + +function withCrossUser(table: Record): Record { + for (const method of CROSS_USER_METHODS) { + const marked = table[method] + if (!marked) throw new Error(`${method} is not a routed row`) + marked.crossUser = true + } + return table +} + +export const ROUTED_METHODS: Readonly> = Object.freeze(withCrossUser({ // ---------------------------------------------------------------- thread reads 'threads.get': read('thread', ['threadId']), // `transcript: false` leaves out what a computer that reads the thread's stream already has (the @@ -613,7 +653,7 @@ export const ROUTED_METHODS: Readonly> = Object.freeze 'scheduled.pause': write('computer', ['id', 'reason', 'until'], { required: ['id'] }), 'scheduled.resume': write('computer', ['id'], { required: ['id'] }), 'scheduled.delete': write('computer', ['id'], { required: ['id'] }) -} as Record) +} as Record)) /** The routed rows that name one automation (a scheduled job) of the owner by `id`. */ export const ROUTED_JOB_METHODS: readonly string[] = [ diff --git a/src/shared/featureFlags.ts b/src/shared/featureFlags.ts index 7015c59155..89bceaa654 100644 --- a/src/shared/featureFlags.ts +++ b/src/shared/featureFlags.ts @@ -64,6 +64,12 @@ export interface NetFeatureFlags { * only while `netBridge` is on. */ netBridgeThreads: boolean + /** + * Teammates may reach the threads the team shares on this computer (`mms/teams/access.ts`). Off by default and + * absent means off; it has an effect only while `netBridge` is on. Stored only while it is on, so an earlier + * build, which rejects any other key, still loads the profile's Net configuration. + */ + netTeams?: boolean } export const DEFAULT_NET_FEATURE_FLAGS: Readonly = Object.freeze({ netBridge: false, diff --git a/src/shared/teams/types.ts b/src/shared/teams/types.ts new file mode 100644 index 0000000000..39637ca2b1 --- /dev/null +++ b/src/shared/teams/types.ts @@ -0,0 +1,47 @@ +/** + * Teams: the types of the one decision that lets a teammate (another person, not another of the user's own + * computers) reach a thread through Bridge's routed path. Nothing here is reachable while the `netTeams` flag + * is off, and the default directory knows no team, so every call from another person is refused as today. + */ +import type { NodeId, UserId } from '../net/ids' + +/** A team is an identity of its own, not any one member (`docs/plans/teams-architecture.md` §6.2). */ +export type TeamId = UserId + +/** Who may reach one thread: its owner, the people it lists, and, when it is open to the team, every member. */ +export interface ThreadAccess { + owner: UserId + people: UserId[] + openToTeam?: boolean +} + +/** Why a call from another person is refused. */ +export type TeamAccessDenial = + /** The person is not an active member of this computer's team, or the computer is in no team. */ + | 'not_team_member' + /** The thread is not open to the person, or the call names no thread. */ + | 'no_thread_access' + /** The routed row is not one another person may call (`RoutedRow.crossUser`). */ + | 'row_not_cross_user' + /** The thread is kept on this computer only (`Thread.localOnly`): never shared, with anyone. */ + | 'local_only' + /** The `netTeams` flag is off. */ + | 'teams_off' + +export type TeamAccessDecision = + /** The caller is the user of this computer: the usual same-person checks apply, unchanged. */ + | { kind: 'same_person' } + | { kind: 'allow' } + | { kind: 'deny'; reason: TeamAccessDenial } + +/** + * What this computer knows about its team. A later change reads it from the team's Space; until then the + * directory knows no team (`DENY_ALL_TEAM_DIRECTORY`), which refuses every other person. + */ +export interface TeamDirectory { + /** The team the computer `node` belongs to, if any. */ + teamOf(node: NodeId): TeamId | undefined + isActiveMember(team: TeamId, user: UserId): boolean + /** Who may reach the thread, if the team shares it at all. */ + threadAccess(threadId: string): ThreadAccess | undefined +} diff --git a/tests/net/bridge/routed/routedVersions.json b/tests/net/bridge/routed/routedVersions.json index 58c2499e16..d0afe6dd01 100644 --- a/tests/net/bridge/routed/routedVersions.json +++ b/tests/net/bridge/routed/routedVersions.json @@ -317,12 +317,12 @@ "orchestrator.abort": { "version": 1, "digest": "ca4448f42d042129", - "security": "56bf730c16aa9cd1" + "security": "a219373cf6d0c182" }, "orchestrator.answerQuestions": { "version": 1, "digest": "59854b7c16497a61", - "security": "074bdce0c6e26440" + "security": "7437b81dd4fba8d4" }, "orchestrator.contextUsage": { "version": 1, @@ -352,12 +352,12 @@ "orchestrator.send": { "version": 6, "digest": "a8e36c8568d00b5d", - "security": "1447c39a3cdfbf97" + "security": "fc7fbf85d7419930" }, "orchestrator.steer": { "version": 2, "digest": "2f736d5f6a66cf4a", - "security": "da503b52b5c83a71" + "security": "ce104899a8ea0ca7" }, "projects.list": { "version": 1, @@ -532,42 +532,42 @@ "queue.edit": { "version": 2, "digest": "c566e5d7295522f9", - "security": "b4dd46cdf246cfd1" + "security": "b6c298c8ed42bcc6" }, "queue.enqueue": { "version": 2, "digest": "298e9361e4548d6f", - "security": "1447c39a3cdfbf97" + "security": "fc7fbf85d7419930" }, "queue.list": { "version": 1, "digest": "2a27f073e7829290", - "security": "04f7c680ffd36337" + "security": "76c91299ed1d6e00" }, "queue.promoteToSteer": { "version": 1, "digest": "2356256a52e2d640", - "security": "926c4af141d1208d" + "security": "be47d9decd0cab0b" }, "queue.remove": { "version": 1, "digest": "d1ec647bb236cf35", - "security": "926c4af141d1208d" + "security": "be47d9decd0cab0b" }, "queue.reorder": { "version": 1, "digest": "5f3aa347f2d9c8ad", - "security": "926c4af141d1208d" + "security": "be47d9decd0cab0b" }, "review.file": { "version": 1, "digest": "d40f7d8ef72c110a", - "security": "23c8269058d1b9db" + "security": "27c778fb39b742cc" }, "review.files": { "version": 1, "digest": "dd946eaa04f957e3", - "security": "23c8269058d1b9db" + "security": "27c778fb39b742cc" }, "routed.page": { "version": 1, @@ -682,7 +682,7 @@ "thread.changesSince": { "version": 1, "digest": "41a6af7bae317b8f", - "security": "04f7c680ffd36337" + "security": "76c91299ed1d6e00" }, "thread.fork": { "version": 1, @@ -697,17 +697,17 @@ "thread.messageImage": { "version": 1, "digest": "1649e85030d13b65", - "security": "04f7c680ffd36337" + "security": "76c91299ed1d6e00" }, "thread.messages": { "version": 2, "digest": "ca37845da10897d3", - "security": "04f7c680ffd36337" + "security": "76c91299ed1d6e00" }, "thread.snapshot": { "version": 2, "digest": "f27b6fe4a93d6472", - "security": "04f7c680ffd36337" + "security": "76c91299ed1d6e00" }, "threads.approvalRequests": { "version": 1, @@ -747,7 +747,7 @@ "threads.get": { "version": 1, "digest": "2a27f073e7829290", - "security": "04f7c680ffd36337" + "security": "76c91299ed1d6e00" }, "threads.inventory": { "version": 1, diff --git a/tests/net/bridge/routed/table.test.ts b/tests/net/bridge/routed/table.test.ts index fc3c2b907a..285cab4555 100644 --- a/tests/net/bridge/routed/table.test.ts +++ b/tests/net/bridge/routed/table.test.ts @@ -3,6 +3,7 @@ import { readFileSync, writeFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { afterEach, describe, expect, it } from 'vitest' import { + CROSS_USER_METHODS, ROUTED_FORBIDDEN_KEYS, ROUTED_LOCAL_METHODS, ROUTED_METHODS, @@ -53,7 +54,9 @@ function securityOf(row: RoutedRow): string { // Which values a caller may send ahead of the call is part of what the row lets through. ...(row.stageable?.length ? { stageable: [...row.stageable].sort() } : {}), // A numbered change keeps no ledger. - ...(row.sequenced ? { sequenced: true } : {}) + ...(row.sequenced ? { sequenced: true } : {}), + // Another person (a teammate) may call the row. + ...(row.crossUser ? { crossUser: true } : {}) }) } @@ -276,6 +279,43 @@ describe('the routed method table', () => { if (!row.stageable) expect(row.keys, method).not.toContain(ROUTED_STAGED_KEY) }) + it('lets another person call only the rows a shared thread needs', () => { + const marked = Object.entries(ROUTED_METHODS) + .filter(([, row]) => row.crossUser === true) + .map(([method]) => method) + .sort() + // Reading the thread, send, steer, stop, answering its questions, its queue and its review diff. + expect(marked).toEqual( + [ + 'threads.get', + 'thread.snapshot', + 'thread.messages', + 'thread.changesSince', + 'thread.messageImage', + 'orchestrator.send', + 'orchestrator.steer', + 'orchestrator.abort', + 'orchestrator.answerQuestions', + 'queue.list', + 'queue.enqueue', + 'queue.edit', + 'queue.reorder', + 'queue.remove', + 'queue.promoteToSteer', + 'review.files', + 'review.file' + ].sort() + ) + expect([...CROSS_USER_METHODS].sort()).toEqual(marked) + for (const method of marked) { + const row = ROUTED_METHODS[method]! + // Never a terminal, the editor, Undo or Publish, and always one thread (a folder row names it as `threadId`). + expect(row.terminal, method).toBeUndefined() + expect(method, method).not.toMatch(/^(pty|editor|actions|publish)\./) + expect(['thread', 'folder'], method).toContain(row.target) + } + }) + it('matches the versions on record, and a changed row needs a new version', () => { const everyRow = { ...ROUTED_METHODS, ...transportRows() } const fresh = snapshotOf(everyRow) diff --git a/tests/net/rollback/storedFlags.test.ts b/tests/net/rollback/storedFlags.test.ts index 07bd1055e6..3deac35ff9 100644 --- a/tests/net/rollback/storedFlags.test.ts +++ b/tests/net/rollback/storedFlags.test.ts @@ -98,3 +98,62 @@ it('has both switches for other computers on by default, and keeps a choice to t rmSync(root, { recursive: true, force: true }) } }, 60_000) + +it('stores the teams flag only while it is on, reads it back, and still refuses a key it does not know', async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'net-teams-flag-'))), + home = join(root, 'home') + const open = () => + MousseMainService.create({ homeDir: home, repoRoot: root, headless: true, requireOwnership: false }) + let main = await open() + const stored = (): { features: Record } => + JSON.parse( + main.net.runtime().db.database.prepare('SELECT value FROM net_service_config').get()!.value as string + ) + const restart = async () => { + await main.stop() + main = await open() + await main.net.start() + // A profile whose Net configuration did not load refuses the unlock (synchronously). + await Promise.resolve() + .then(() => main.net.request('net.unlock', { passphrase: 'teams-flag-passphrase' })) + .catch(() => {}) + } + try { + await main.net.request('net.init', { listen: true }) + await main.net.request('net.protect', { passphrase: 'teams-flag-passphrase' }) + // Off, the default: nothing is stored for it, so an earlier version reads the configuration. + expect(stored().features).toEqual({ netBridge: true, netSpaces: true }) + expect(main.net.featureEnabled('netTeams')).toBe(false) + // On: it is stored and read back after a restart. + const features = (main.net as unknown as { config: { features: Record } }).config.features + features.netTeams = true + await main.net.request('bridge.workOnThreads', { enabled: true }) + expect(stored().features).toEqual({ netBridge: true, netSpaces: true, netTeams: true }) + await restart() + expect(main.net.status().features).toMatchObject({ netTeams: true }) + expect(main.net.featureEnabled('netTeams')).toBe(true) + // It counts only while Bridge is on. + const live = (main.net as unknown as { config: { features: Record } }).config.features + live.netBridge = false + expect(main.net.featureEnabled('netTeams')).toBe(false) + live.netBridge = true + // Off again: the key goes, and an earlier version reads the configuration once more. + live.netTeams = false + await main.net.request('bridge.workOnThreads', { enabled: true }) + expect(stored().features).toEqual({ netBridge: true, netSpaces: true }) + expect(olderVersionAccepts(stored())).toBe(true) + // A key this version does not know is still corrupt storage, as it always was. + const rt = main.net.runtime() + const config = stored() + config.features.netSomethingNew = true + rt.db.transaction(() => { + rt.db.charge(1) + rt.db.database.prepare('UPDATE net_service_config SET value=?').run(JSON.stringify(config)) + }) + await restart() + expect(main.net.status()).toMatchObject({ enabled: false, error: 'storage_corrupt' }) + } finally { + await main.stop() + rmSync(root, { recursive: true, force: true }) + } +}, 60_000) diff --git a/tests/net/teams/rpcAccess.test.ts b/tests/net/teams/rpcAccess.test.ts new file mode 100644 index 0000000000..f9b93f3b95 --- /dev/null +++ b/tests/net/teams/rpcAccess.test.ts @@ -0,0 +1,146 @@ +/** + * The same-person check of the request dispatcher, with the access decision for teammates behind it: off (or with + * the default directory) another person gets the `forbidden` of today; on, with a directory that lets them in, only + * the routed rows marked `crossUser` are reachable, and never for a thread kept on this computer only. + */ +import { afterEach, describe, expect, it } from 'vitest' +import { systemClock } from '../../../src/mms/net/clock' +import type { IdentityService } from '../../../src/mms/net/contracts' +import { NetDatabase } from '../../../src/mms/net/store/database' +import { SqliteExecutionLedger } from '../../../src/mms/net/store/executions' +import { DurableRpcDispatcher, type TeamAccessPort } from '../../../src/mms/net/sync/rpcDispatcher' +import { CROSS_USER_METHODS, ROUTED_METHODS, routedNetMethod } from '../../../src/shared/bridge/routed' +import { newId, type NodeDelegation, type Roster, type UserId } from '../../../src/shared/net' +import type { TeamDirectory } from '../../../src/shared/teams/types' +import { makeTempDir } from '../harness/tmp' + +const closers: (() => void)[] = [] +afterEach(() => { + for (const close of closers.splice(0).reverse()) close() +}) + +const me = newId('user'), + mate = newId('user'), + team = newId('user'), + here = newId('node') + +/** Lets `mate` reach every thread of the team on this computer. */ +const welcoming: TeamDirectory = { + teamOf: (node) => (node === here ? team : undefined), + isActiveMember: (of, user) => of === team && user === mate, + threadAccess: () => ({ owner: me, people: [mate] }) +} + +/** A dispatcher with every routed row registered as a no-op, and a caller for `me` and for `mate`. */ +function fixture(teams?: TeamAccessPort) { + const dir = makeTempDir('teams-rpc-').path + const db = new NetDatabase({ profileDir: dir }) + closers.push(() => db.close()) + // Roster checks are not under test: every node holds a current delegation in its person's roster. + const node = newId('node') + const delegation = { + subject: node, + keyEpoch: 1, + issuedAt: 0, + expiresAt: Number.MAX_SAFE_INTEGER, + caps: ['read', 'chat', 'write'] + } as unknown as NodeDelegation + const roster = { nodes: [delegation], revoked: [] } as unknown as Roster + const identity = { + self: () => ({ user: me, node: here }), + pinnedRootKey: () => 'root', + roster: () => roster, + rosterState: () => 'ok', + verifySigned: (signed: unknown) => signed + } as unknown as IdentityService + const rpc = new DurableRpcDispatcher({ + db, + executions: new SqliteExecutionLedger(db), + identity, + clock: systemClock, + ...(teams ? { teams } : {}) + }) + for (const [method, row] of Object.entries(ROUTED_METHODS)) + rpc.register({ + method: routedNetMethod(method), + family: 'routed', + capability: row.capability, + ephemeral: true, + handle: async () => ({ ok: true }) + }) + rpc.register({ method: 'bridge.nodes', family: 'bridge', capability: 'read', ephemeral: true, handle: async () => [] }) + const call = (user: UserId, method: string, params: Record = paramsOf(method)) => + rpc.dispatch(method, params, undefined, { + id: newId('rpc'), + caller: { node, user, delegation }, + signal: new AbortController().signal, + deadlineAt: Date.now() + 60_000, + progress() {} + }) + return { call } +} + +/** The params of a call to a routed row on the thread `thr_shared`. */ +function paramsOf(name: string): Record { + const row = ROUTED_METHODS[name.slice('routed.'.length)] + return row ? { [row.threadIds?.[0] ?? 'threadId']: 'thr_shared' } : {} +} + +/** What the call ends with: `ok`, or the error it was refused with, as text, so a changed message shows. */ +const outcome = (pending: Promise): Promise => + pending.then( + () => 'ok', + (error: { code?: string; message?: string; details?: unknown }) => + JSON.stringify({ code: error.code, message: error.message, details: error.details }) + ) + +const routedNames = Object.keys(ROUTED_METHODS).map(routedNetMethod) + +describe('a routed call from another person', () => { + it('is refused the same way as before the flag, without a port, with the flag off, or with the default directory', async () => { + const before = fixture() + const refused = await outcome(before.call(mate, routedNetMethod('threads.get'))) + expect(JSON.parse(refused)).toMatchObject({ code: 'forbidden' }) + const off = fixture({ enabled: () => false, directory: welcoming, localOnly: () => false }) + const denyAll = fixture({ enabled: () => true, localOnly: () => false }) + for (const name of [...routedNames, 'bridge.nodes']) { + expect(await outcome(before.call(mate, name)), name).toBe(refused) + expect(await outcome(off.call(mate, name)), name).toBe(refused) + expect(await outcome(denyAll.call(mate, name)), name).toBe(refused) + } + // The same person still goes through as always. + expect(await outcome(off.call(me, routedNetMethod('threads.get')))).toBe('ok') + expect(await outcome(before.call(me, routedNetMethod('threads.list')))).toBe('ok') + }) + + it('reaches only the rows marked crossUser once the flag is on and the directory lets the person in', async () => { + const before = fixture() + const refused = await outcome(before.call(mate, routedNetMethod('threads.get'))) + const on = fixture({ enabled: () => true, directory: welcoming, localOnly: () => false }) + const reached: string[] = [] + for (const [method, row] of Object.entries(ROUTED_METHODS)) { + const result = await outcome(on.call(mate, routedNetMethod(method))) + if (result === 'ok') reached.push(method) + else expect(result, method).toBe(refused) + expect(result === 'ok', method).toBe(row.crossUser === true) + } + expect(reached.sort()).toEqual([...CROSS_USER_METHODS].sort()) + // A method that is no routed row is never reachable. + expect(await outcome(on.call(mate, 'bridge.nodes'))).toBe(refused) + }) + + it('never reaches a thread kept on this computer only, a call naming no thread, or a thread with no lookup', async () => { + const before = fixture() + const refused = await outcome(before.call(mate, routedNetMethod('threads.get'))) + const kept = fixture({ enabled: () => true, directory: welcoming, localOnly: () => true }) + const noLookup = fixture({ enabled: () => true, directory: welcoming }) + const on = fixture({ enabled: () => true, directory: welcoming, localOnly: () => false }) + for (const method of CROSS_USER_METHODS) { + expect(await outcome(kept.call(mate, routedNetMethod(method))), method).toBe(refused) + expect(await outcome(noLookup.call(mate, routedNetMethod(method))), method).toBe(refused) + } + // A folder row asked for a project, not a thread, names no thread. + expect(await outcome(on.call(mate, routedNetMethod('review.files'), { projectId: 'prj_x' }))).toBe(refused) + expect(await outcome(on.call(mate, routedNetMethod('review.files'), { threadId: 'thr_shared' }))).toBe('ok') + }) +}) diff --git a/tests/teams/access.test.ts b/tests/teams/access.test.ts new file mode 100644 index 0000000000..8c38d8c71e --- /dev/null +++ b/tests/teams/access.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'vitest' +import type { NodeId, UserId } from '../../src/shared/net/ids' +import type { TeamDirectory, ThreadAccess } from '../../src/shared/teams/types' +import { + DENY_ALL_TEAM_DIRECTORY, + teamAccess, + threadAccessAllows, + type TeamAccessInput +} from '../../src/mms/teams/access' + +const me = 'usr_me' as UserId, + mate = 'usr_mate' as UserId, + stranger = 'usr_stranger' as UserId, + team = 'usr_team' as UserId +const self = { user: me, node: 'nod_here' as NodeId } +const peer = { user: mate, node: 'nod_mate' as NodeId } + +/** A team of `me` and `mate` on this computer, with one thread each way. */ +function directory(threads: Record = {}): TeamDirectory { + return { + teamOf: (node) => (node === self.node ? team : undefined), + isActiveMember: (of, user) => of === team && (user === me || user === mate), + threadAccess: (threadId) => threads[threadId] + } +} + +const base = (overrides: Partial = {}): TeamAccessInput => ({ + peer, + self, + row: { crossUser: true }, + target: { threadId: 'thr_shared', localOnly: false }, + flags: { netTeams: true }, + directory: directory({ thr_shared: { owner: me, people: [mate] } }), + ...overrides +}) + +describe('teamAccess', () => { + it('leaves the same person to the checks of today, whatever else it is given', () => { + expect( + teamAccess( + base({ peer: { user: me, node: 'nod_other' as NodeId }, flags: {}, row: undefined, target: undefined }) + ) + ).toEqual({ kind: 'same_person' }) + }) + + it('lets a listed teammate reach a shared thread through a marked row', () => { + expect(teamAccess(base())).toEqual({ kind: 'allow' }) + }) + + it('refuses another person while the flag is off, before anything else', () => { + expect(teamAccess(base({ flags: {} }))).toEqual({ kind: 'deny', reason: 'teams_off' }) + expect(teamAccess(base({ flags: { netTeams: false } }))).toEqual({ kind: 'deny', reason: 'teams_off' }) + }) + + it('refuses a row that is not marked, and a method that is no row', () => { + expect(teamAccess(base({ row: {} }))).toEqual({ kind: 'deny', reason: 'row_not_cross_user' }) + expect(teamAccess(base({ row: undefined }))).toEqual({ kind: 'deny', reason: 'row_not_cross_user' }) + }) + + it('refuses a call that names no thread', () => { + expect(teamAccess(base({ target: undefined }))).toEqual({ kind: 'deny', reason: 'no_thread_access' }) + }) + + it('never shares a thread kept on this computer only, even one the directory opens to the team', () => { + const open = directory({ thr_shared: { owner: mate, people: [mate], openToTeam: true } }) + expect( + teamAccess(base({ directory: open, target: { threadId: 'thr_shared', localOnly: true } })) + ).toEqual({ kind: 'deny', reason: 'local_only' }) + }) + + it('refuses a person who is not an active member, and a computer in no team', () => { + expect(teamAccess(base({ peer: { user: stranger, node: 'nod_x' as NodeId } }))).toEqual({ + kind: 'deny', + reason: 'not_team_member' + }) + expect(teamAccess(base({ self: { user: me, node: 'nod_elsewhere' as NodeId } }))).toEqual({ + kind: 'deny', + reason: 'not_team_member' + }) + }) + + it('refuses a member the thread is not open to', () => { + const mine = directory({ thr_shared: { owner: me, people: [] } }) + expect(teamAccess(base({ directory: mine }))).toEqual({ kind: 'deny', reason: 'no_thread_access' }) + expect(teamAccess(base({ directory: directory() }))).toEqual({ kind: 'deny', reason: 'no_thread_access' }) + }) + + it('lets in the owner, a listed person, or any member of a thread open to the team', () => { + expect(threadAccessAllows({ owner: mate, people: [] }, mate)).toBe(true) + expect(threadAccessAllows({ owner: me, people: [mate] }, mate)).toBe(true) + expect(threadAccessAllows({ owner: me, people: [], openToTeam: true }, mate)).toBe(true) + expect(threadAccessAllows({ owner: me, people: [] }, mate)).toBe(false) + expect(threadAccessAllows(undefined, mate)).toBe(false) + }) + + it('refuses everyone else with the default directory', () => { + expect(teamAccess(base({ directory: DENY_ALL_TEAM_DIRECTORY }))).toEqual({ + kind: 'deny', + reason: 'not_team_member' + }) + }) +}) diff --git a/tests/teams/threadVisibility.test.ts b/tests/teams/threadVisibility.test.ts new file mode 100644 index 0000000000..07474751eb --- /dev/null +++ b/tests/teams/threadVisibility.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from 'vitest' +import type { UserId } from '../../src/shared/net/ids' +import type { TeamDirectory, ThreadAccess } from '../../src/shared/teams/types' +import type { Thread } from '../../src/shared/types' +import { DENY_ALL_TEAM_DIRECTORY } from '../../src/mms/teams/access' +import { threadsForPerson, visibleThreadsFor } from '../../src/mms/protocol/threadVisibility' + +const me = 'usr_me' as UserId, + mate = 'usr_mate' as UserId, + team = 'usr_team' as UserId + +const thread = (id: string, extra: Partial = {}): Thread => + ({ id, name: id, projectId: null, ...extra }) as unknown as Thread + +function directory(threads: Record, members: UserId[] = [me, mate]): TeamDirectory { + return { + teamOf: () => team, + isActiveMember: (of, user) => of === team && members.includes(user), + threadAccess: (threadId) => threads[threadId] + } +} + +const access: Record = { + listed: { owner: me, people: [mate] }, + open: { owner: me, people: [], openToTeam: true }, + theirs: { owner: mate, people: [] }, + mine: { owner: me, people: [] }, + // The directory may open a thread kept on this computer only; the filter still never shows it. + kept: { owner: me, people: [mate], openToTeam: true }, + keptChild: { owner: me, people: [mate], openToTeam: true } +} +const threads = [ + thread('listed'), + thread('open'), + thread('theirs'), + thread('mine'), + thread('unknown'), + thread('kept', { localOnly: true }), + thread('keptChild', { lineage: { rootThreadId: 'kept' } } as Partial) +] +const ids = (rows: readonly Thread[]) => rows.map((row) => row.id) + +describe('the per-person thread filter', () => { + it('keeps only the threads open to the person, and never one kept on this computer only', () => { + const person = { user: mate, team, directory: directory(access) } + expect(ids(threadsForPerson(person, threads))).toEqual(['listed', 'open', 'theirs']) + // A local connection sees kept threads, but a person never does. + expect(ids(visibleThreadsFor({ clientType: 'gui' }, threads, threads, person))).toEqual([ + 'listed', + 'open', + 'theirs' + ]) + }) + + it('shows nothing to someone who is not an active member, in no team, or with the default directory', () => { + expect(threadsForPerson({ user: mate, team, directory: directory(access, [me]) }, threads)).toEqual([]) + expect(threadsForPerson({ user: mate, team: undefined, directory: directory(access) }, threads)).toEqual([]) + expect(threadsForPerson({ user: mate, team, directory: DENY_ALL_TEAM_DIRECTORY }, threads)).toEqual([]) + }) + + it('changes nothing for a caller who is not another person', () => { + expect(ids(visibleThreadsFor({ clientType: 'gui' }, threads))).toEqual(ids(threads)) + expect(ids(visibleThreadsFor({ clientType: 'bridge' }, threads))).toEqual([ + 'listed', + 'open', + 'theirs', + 'mine', + 'unknown' + ]) + }) +})