Skip to content
Open
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
28 changes: 20 additions & 8 deletions src/mms/net/NetService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 {
Expand Down
71 changes: 65 additions & 6 deletions src/mms/net/sync/rpcDispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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.')
Expand All @@ -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
Expand Down Expand Up @@ -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')
Expand All @@ -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)
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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<string, unknown>)[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.
Expand Down
38 changes: 36 additions & 2 deletions src/mms/protocol/threadVisibility.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -38,17 +41,48 @@ export function withoutBotThreads<T extends Pick<Thread, 'botOwned'>>(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<T extends Pick<Thread, 'id' | 'localOnly' | 'lineage'>>(
person: TeamPerson,
threads: readonly T[],
inventory: readonly Pick<Thread, 'id' | 'localOnly'>[] = threads as unknown as readonly Pick<Thread, 'id' | 'localOnly'>[]
): T[] {
return threads.filter((thread) =>
personMaySeeThread(person.directory, person.team, person.user, {
id: thread.id,
localOnly: isLocalOnlyThread(thread, inventory)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

R1. Keep a child hidden when its lineage root is unknown.

Older child records can lack their own localOnly flag. The new filter defaults inventory to the supplied rows, so if the root is missing from that inventory, isLocalOnlyThread() returns false. An otherwise eligible child can then appear despite the filter’s local-only guarantee. Require full inventory at this boundary and treat unresolved root IDs as unshareable. Add a visibility test where the existing keptChild fixture is passed without its root.

})
)
}

/**
* `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)
}

Expand Down
88 changes: 88 additions & 0 deletions src/mms/teams/access.ts
Original file line number Diff line number Diff line change
@@ -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<TeamAccessDecision, { kind: 'deny' }>['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')
}
Loading
Loading