Skip to content

An open-source, self-hosted system for apps built with web technologies.

Simplify permission request results and unify grant coverage

zohayrslileh6745cd4fe628
diff --git a/scripts/contracts/client-sandbox.ts b/scripts/contracts/client-sandbox.ts
index b66a86b..e47af9d 100644
--- a/scripts/contracts/client-sandbox.ts
+++ b/scripts/contracts/client-sandbox.ts
@@ -38,6 +38,7 @@ process.startClient(new Window(
assert.equal(process.hosted().client?.sameOrigin, false)
-process.setClientSameOrigin(true)
+assert.equal(process.setClientSameOrigin(true), true)
+assert.equal(process.setClientSameOrigin(true), false)
assert.equal(process.hosted().client?.sameOrigin, true)
diff --git a/scripts/contracts/client-system-access.ts b/scripts/contracts/client-system-access.ts
index 6a02207..e549fe6 100644
--- a/scripts/contracts/client-system-access.ts
+++ b/scripts/contracts/client-system-access.ts
@@ -21,7 +21,7 @@ const authManager = {
assert.equal(process, owner.identity)
- return permissionCatalog.allows(name, permissions.all ?? null, permissions[name] ?? null, values as never)
+ return permissionCatalog.allows(name, values as never, permissions)
},
async grantsStorage(process: string, path: string, operation?: "read" | "write" | "delete") {
diff --git a/scripts/contracts/permission-requests.ts b/scripts/contracts/permission-requests.ts
new file mode 100644
index 0000000..8b6bdad
--- /dev/null
+++ b/scripts/contracts/permission-requests.ts
@@ -0,0 +1,120 @@
+import assert from "node:assert/strict"
+import { mkdtempSync, readFileSync, rmSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import type { PermissionName, PermissionRequest, Permissions } from "@phreshos/core"
+import Program from "@server/core/link-manager/auth-manager/program-manager/program"
+import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"
+import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"
+import Process from "@server/core/link-manager/auth-manager/process-manager/process"
+import Window from "@server/core/link-manager/auth-manager/process-manager/window"
+import type HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"
+import { readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"
+
+const temporary = mkdtempSync(join(tmpdir(), "phresh-permission-requests-"))
+
+try {
+ const program = new Program({ identity: "example", storage: temporary, client: { location: "." } })
+ let dialogs = 0
+ let choice: boolean | null = null
+ let whilePending: (() => void) | undefined
+ let accessUpdates = 0
+
+ const process = new Process("process", null, program, {}, { server: null, client: null, options: {} }, null, {} as HostTraffic, false)
+ process.startClient(new Window({ title: "Client", layer: "window", location: "/" }, { x: 0, y: 0 }, { width: 640, height: 480 }, 1, false), false)
+
+ const authManager = {
+ dialogManager: {
+ async requestPermission() {
+ dialogs++
+ whilePending?.()
+ return choice
+ }
+ }
+ }
+ const programManager = Object.assign(Object.create(ProgramManager.prototype), { authManager }) as ProgramManager
+ const processManager = Object.assign(Object.create(ProcessManager.prototype), {
+ authManager,
+ processes: new Map([["process", process]]),
+ $outbound: { async publish(event: string) {
+ assert.equal(event, "/client-access")
+ accessUpdates++
+ } }
+ }) as ProcessManager
+ Object.assign(authManager, { programManager, processManager })
+
+ const request = <Name extends PermissionName>(name: Name, value: PermissionRequest<Name> = true) => (
+ processManager.requestPermission("process", "request", name, value)
+ )
+ async function covered<Name extends PermissionName>(permissions: Permissions, name: Name, requested: PermissionRequest<Name>, expected: unknown) {
+ writePermissions(program, permissions)
+ const stored = readFileSync(join(temporary, "permissions.json"), "utf8")
+ const before = dialogs
+ assert.deepEqual(await request(name, requested), expected)
+ assert.equal(dialogs, before)
+ assert.equal(readFileSync(join(temporary, "permissions.json"), "utf8"), stored)
+ }
+
+ await covered({ services: [] }, "services", ["browser"], ["browser"])
+ await covered({ services: ["browser", "editor"] }, "services", ["browser"], ["browser"])
+ await covered({ programs: [] }, "services", ["browser"], ["browser"])
+ await covered({ programs: ["browser"] }, "services", ["browser"], ["browser"])
+ await covered({ programs: ["browser"], services: ["editor"] }, "services", ["browser", "editor"], ["browser", "editor"])
+ await covered({ programs: [], services: false }, "services", ["browser"], ["browser"])
+ await covered({ all: [] }, "services", ["browser"], ["browser"])
+ await covered({ all: [] }, "network", ["https://example.test"], ["https://example.test"])
+ await covered({ network: ["https://example.test/**"] }, "network", ["https://example.test/api"], ["https://example.test/api"])
+ await covered({ storage: ["Documents/**"] }, "storage", ["read:Documents/report.txt"], ["read:Documents/report.txt"])
+ await covered({ services: [] }, "services", true, [])
+ await covered({}, "services", ["example"], ["example"])
+ await covered({}, "programs", ["example"], ["example"])
+
+ writePermissions(program, { services: false })
+ assert.equal(await request("services", ["browser"]), false)
+ assert.equal(dialogs, 0)
+
+ writePermissions(program, {})
+ assert.equal(await request("services", ["browser"]), null)
+ assert.equal(dialogs, 1)
+ assert.deepEqual(readPermissions(program), {})
+
+ choice = false
+ assert.equal(await request("services", ["browser"]), false)
+ assert.equal(dialogs, 2)
+ assert.deepEqual(readPermissions(program), {})
+
+ choice = true
+ writePermissions(program, { services: ["editor"] })
+ assert.deepEqual(await request("services", ["browser"]), ["browser"])
+ assert.equal(dialogs, 3)
+ assert.deepEqual(readPermissions(program), { services: ["editor", "browser"] })
+
+ // A pending request must not overwrite a grant saved by another request.
+ writePermissions(program, {})
+ whilePending = () => writePermissions(program, { services: ["editor"] })
+ assert.deepEqual(await request("services", ["browser"]), ["browser"])
+ assert.deepEqual(readPermissions(program), { services: ["editor", "browser"] })
+ whilePending = undefined
+
+ const declared = new Program({ identity: "declared", storage: temporary, client: { location: ".", permissions: { programs: ["browser"] } } })
+ writePermissions(declared, { services: ["editor"] })
+ assert(programManager.grantsPermission(declared, "services", ["browser", "editor"]))
+ assert(!programManager.allowsPermission(declared, "services", ["browser"]))
+ assert(programManager.allowsPermission(declared, "services", ["editor"]))
+ writePermissions(declared, { programs: ["browser"] })
+ assert(programManager.allowsPermission(declared, "services", ["browser"]))
+
+ // The iframe policy is synchronized independently of permission request results.
+ writePermissions(program, {})
+ assert.deepEqual(await request("all"), [])
+ assert.equal(process.hosted().client?.sameOrigin, true)
+ assert.equal(accessUpdates, 1)
+ await programManager.setPermission(program, "all", [])
+ assert.equal(accessUpdates, 1)
+ await programManager.deletePermission(program, "all")
+ assert.equal(process.hosted().client?.sameOrigin, false)
+ assert.equal(accessUpdates, 2)
+}
+finally {
+ rmSync(temporary, { recursive: true, force: true })
+}
diff --git a/scripts/contracts/permissions.ts b/scripts/contracts/permissions.ts
index 778da45..a6a53cd 100644
--- a/scripts/contracts/permissions.ts
+++ b/scripts/contracts/permissions.ts
@@ -6,8 +6,7 @@ const catalog = new PermissionCatalog({
all: {
default: [],
title: "All permissions",
- description: "Grant every available Client permission.",
- requiresReload: (before, permission) => Array.isArray(before) !== Array.isArray(permission)
+ description: "Grant every available Client permission."
},
services: {
default: [],
@@ -106,10 +105,19 @@ assert(catalog.grants("storage", ["Documents/**"], ["read:Documents/report.txt"]
assert(catalog.grants("storage", ["read,delete:Documents/**"], ["delete:Documents/old.txt"]))
assert(!catalog.grants("storage", ["read:Documents/**"], ["write:Documents/report.txt"]))
assert(!catalog.grants("storage", ["Documents/report.txt"], ["read:Documents/**"]))
-assert(catalog.allows("all", [], null, []))
-assert(!catalog.allows("all", null, null, []))
-assert(catalog.allows("services", [], null, ["flambo"]))
-assert(catalog.allows("services", null, ["flambo"], ["flambo"]))
+assert(catalog.allows("all", [], { all: [] }))
+assert(!catalog.allows("all", [], {}))
+assert(catalog.allows("services", ["browser"], { all: [] }))
+assert(catalog.allows("services", ["browser"], { services: ["browser"] }))
+assert(catalog.allows("services", ["browser"], { programs: [] }))
+assert(catalog.allows("services", [], { programs: [] }))
+assert(catalog.allows("services", ["browser"], { programs: ["browser"] }))
+assert(catalog.allows("services", ["browser", "editor"], { programs: ["browser"], services: ["editor"] }))
+assert(catalog.allows("services", ["browser", "editor"], { programs: ["browser"] }, { services: ["editor"] }))
+assert(!catalog.allows("services", ["editor"], { programs: ["browser"] }))
+assert(!catalog.allows("services", [], { programs: ["browser"] }))
+assert(!catalog.allows("programs", ["browser"], { services: [] }))
+assert(catalog.allows("services", ["browser"], { programs: [], services: false }))
assert.equal(catalog.combine("all", null, false), null)
assert.deepEqual(catalog.combine("all", []), [])
assert.deepEqual(catalog.combine("services", ["flambo"], ["terminal"]), ["flambo", "terminal"])
@@ -132,17 +140,6 @@ assert(!catalog.changed([], []))
assert(!catalog.changed(["flambo", "terminal"], ["terminal", "flambo"]))
assert(catalog.changed(["flambo"], []))
-assert(catalog.needReload("all", null, []))
-assert(catalog.needReload("all", [], null))
-assert(!catalog.needReload("all", [], []))
-assert(!catalog.needReload("services", null, []))
-assert(!catalog.needReload("programs", ["flambo"], []))
-assert(!catalog.needReload("network", null, []))
-assert(!catalog.needReload("storage", null, []))
-assert(!catalog.needReload("uploads", null, []))
-assert(!catalog.needReload("appearance", null, []))
-assert(!catalog.needReload("desktopPreferences", null, []))
-
assert.throws(() => parsePermissionName("files"), /does not know/)
assert.throws(() => catalog.resolve("all", ["unknown"]), /unknown value/)
assert.throws(() => catalog.resolve("appearance", ["flambo"]), /unknown value/)
diff --git a/source/client/core/link-manager/auth-manager/auth-manager.ts b/source/client/core/link-manager/auth-manager/auth-manager.ts
index 4eaa466..fc82aa9 100644
--- a/source/client/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts
@@ -6,7 +6,7 @@ import DialogManager from "./dialog-manager"
import { TheLink } from "@the-link/core"
import LinkManager from "../link-manager"
import {
- type PermissionChange,
+ type Permission,
type PermissionName,
type PermissionRequest
} from "@phreshos/core"
@@ -92,9 +92,9 @@ export default class AuthManager extends TheLink {
request: string,
name: Name,
permission: PermissionRequest<Name>
- ): Promise<PermissionChange<Name>> {
+ ): Promise<Permission<Name>> {
- return await this.$outbound.publishFirst("/permission/request", request, process, name, permission) as PermissionChange<Name>
+ return await this.$outbound.publishFirst("/permission/request", request, process, name, permission) as Permission<Name>
}
public async cancelPermission(process: string, request: string) {
diff --git a/source/client/view/components/desktop-host/system-access.ts b/source/client/view/components/desktop-host/system-access.ts
index b377e9c..225e4c4 100644
--- a/source/client/view/components/desktop-host/system-access.ts
+++ b/source/client/view/components/desktop-host/system-access.ts
@@ -54,8 +54,7 @@ export default class SystemAccess {
if (program === null) return await this.all()
if (program === this.owner().program) return true
- return await this.authManager.grantsPermission(this.pane, "programs", [program])
- || await this.authManager.grantsPermission(this.pane, "services", [program])
+ return await this.authManager.grantsPermission(this.pane, "services", [program])
}
public async program(program: Program) {
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
index 464f9c2..23e8eb3 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -22,7 +22,6 @@ import {
type ClientLaunch,
type Launch,
type Permission,
- type PermissionChange,
type PermissionInput,
type PermissionName,
type PermissionRequest,
@@ -1548,7 +1547,7 @@ export default class ProcessManager extends TheLink {
request: string,
name: Name,
input: PermissionRequest<Name>
- ): Promise<PermissionChange<Name>> {
+ ): Promise<Permission<Name>> {
const process = this.find(identity)
@@ -1558,58 +1557,36 @@ export default class ProcessManager extends TheLink {
if (!Array.isArray(requested)) throw new Error("A permission request must be true or a list of values")
- const declared = process.program.clientPermissions[name] ?? null
+ if (this.authManager.programManager.grantsPermission(process.program, name, requested)) return requested
+
const stored = this.authManager.programManager.permission(process.program, name)
const effective = this.authManager.programManager.effectivePermission(process.program, name, stored)
- if (name !== "all" && permissionCatalog.granted(this.authManager.programManager.effectivePermission(process.program, "all"))) {
-
- return permissionChange([...permissionCatalog.definition(name).default], false)
- }
-
- if (permissionCatalog.grants(name, effective, requested)) return permissionChange(effective, false)
- if (effective === false) return Object.freeze({ permission: false, needReload: false })
+ if (effective === false) return false
const choice = await this.authManager.dialogManager.requestPermission(process, request, name, requested)
if (choice === true) {
- const permission = permissionCatalog.merge(name, stored, requested)
- const next = permissionCatalog.effective(name, declared, permission)
-
+ const permission = permissionCatalog.merge(name, this.authManager.programManager.permission(process.program, name), requested)
await this.authManager.programManager.setPermission(process.program, name, permission)
- return permissionChange(next, permissionCatalog.needReload(name, effective, next))
+ return requested
}
- return Object.freeze({ permission: choice, needReload: false })
+ return choice
}
- /** Publishes the Client access shape changed by one stored grant. */
- public async storedPermissionChanged<Name extends PermissionName>(
- program: Program,
- name: Name,
- before: Permission<Name>,
- permission: Permission<Name>
- ) {
+ /** Keeps each live Client's iframe access policy aligned with its Program. */
+ public async updateClientAccess(program: Program) {
+
+ const sameOrigin = permissionCatalog.granted(this.authManager.programManager.effectivePermission(program, "all"))
for (const process of this.processes.values()) {
if (process.program !== program || !process.client) continue
- const declared = program.clientPermissions[name] ?? null
- const changed = permissionCatalog.needReload(
-
- name,
-
- permissionCatalog.effective(name, declared, before),
-
- permissionCatalog.effective(name, declared, permission)
- )
-
- if (!changed) continue
-
- if (name === "all") process.setClientSameOrigin(permissionCatalog.granted(this.authManager.programManager.effectivePermission(program, name, permission)))
+ if (!process.setClientSameOrigin(sameOrigin)) continue
await this.$outbound.publish("/client-access", process.identity, process.hosted())
}
@@ -2767,14 +2744,6 @@ interface ProcessRegistration {
created?: (process: Process) => void
}
-function permissionChange<Name extends PermissionName>(permission: Permission<Name>, needReload: boolean): PermissionChange<Name> {
-
- return Object.freeze({
- permission: Array.isArray(permission) ? [...permission] : permission,
- needReload
- })
-}
-
// Where an answer goes, read out of the question itself.
//
// A question is named by its asker before it leaves — which half of
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process.ts b/source/server/core/link-manager/auth-manager/process-manager/process.ts
index 05f8dbd..d6f6b69 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process.ts
@@ -114,7 +114,11 @@ export default class Process {
public setClientSameOrigin(sameOrigin: boolean) {
+ if (this.clientSameOrigin === sameOrigin) return false
+
this.clientSameOrigin = sameOrigin
+
+ return true
}
public startServer(runtime: ServerRuntime, service: boolean, ended: (boundary: ServerProcessBoundary, code: number | null, signal: NodeJS.Signals | null) => Promise<void> | void, unanswered: (values: unknown[], reason: string) => void, appearance: Tunnel) {
diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
index e793534..afca76c 100644
--- a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
+++ b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts
@@ -185,9 +185,8 @@ export default class ProgramManager extends TheLink {
return permissionCatalog.allows(
name,
- permissions.all ?? null,
- permissions[name] ?? null,
- requested
+ requested,
+ permissions
)
}
@@ -210,9 +209,10 @@ export default class ProgramManager extends TheLink {
return permissionCatalog.allows(
name,
- this.effectivePermission(program, "all"),
- this.effectivePermission(program, name),
- requested
+ requested,
+ { programs: [program.identity] },
+ program.clientPermissions,
+ readPermissions(program)
)
}
@@ -242,24 +242,22 @@ export default class ProgramManager extends TheLink {
if (permissionCatalog.changed(before, permission)) {
writePermissions(program, { ...permissions, [name]: permission })
- }
- await this.authManager.processManager.storedPermissionChanged(program, name, before, permission)
+ if (name === "all") await this.authManager.processManager.updateClientAccess(program)
+ }
}
/** Removes one stored user grant without changing Program declarations. */
public async deletePermission<Name extends PermissionName>(program: Program, name: Name): Promise<void> {
const permissions = readPermissions(program)
- const before = permissions[name] ?? null
-
if (Object.hasOwn(permissions, name)) {
delete permissions[name]
writePermissions(program, permissions)
- }
- await this.authManager.processManager.storedPermissionChanged(program, name, before, null)
+ if (name === "all") await this.authManager.processManager.updateClientAccess(program)
+ }
}
@Connect("/permissions")
diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.ts
index 18abe74..f2868fd 100644
--- a/source/server/core/permissions.ts
+++ b/source/server/core/permissions.ts
@@ -20,12 +20,9 @@ export class PermissionCatalog {
private readonly definitions: PermissionDefinitions
- private readonly reloads: Readonly<Partial<Record<PermissionName, PermissionReload>>>
-
public constructor(rules: PermissionRules) {
const validated: Partial<Record<PermissionName, StoredDefinition>> = {}
- const reloads: Partial<Record<PermissionName, PermissionReload>> = {}
for (const unknownName of Object.keys(rules)) {
@@ -33,7 +30,6 @@ export class PermissionCatalog {
const rule = rules[name]
if (!rule || typeof rule !== "object") throw new Error(`Permission "${name}" needs a definition`)
- if (rule.requiresReload !== undefined && typeof rule.requiresReload !== "function") throw new Error(`Permission "${name}" has an invalid reload resolver`)
if (typeof rule.title !== "string" || !rule.title.trim()) throw new Error(`Permission "${name}" needs a title`)
if (typeof rule.description !== "string" || !rule.description.trim()) throw new Error(`Permission "${name}" needs a description`)
@@ -60,7 +56,6 @@ export class PermissionCatalog {
description: rule.description
})
- if (rule.requiresReload) reloads[name] = rule.requiresReload as PermissionReload
}
for (const name of Object.keys(clientPermissionCatalog) as PermissionName[]) {
@@ -69,7 +64,6 @@ export class PermissionCatalog {
}
this.definitions = Object.freeze(validated) as PermissionDefinitions
- this.reloads = Object.freeze(reloads)
}
public definition<Name extends PermissionName>(name: Name): PermissionDefinition<Name> {
@@ -163,17 +157,24 @@ export class PermissionCatalog {
return Array.isArray(permission)
}
- /** Applies the value-less all grant before one permission's own values. */
+ /** Tests complete authority, including grants implied by another permission. */
public allows<Name extends PermissionName>(
name: Name,
- all: PermissionGrant,
- permission: PermissionGrant,
- requested: readonly PermissionValue<Name>[]
+ requested: readonly PermissionValue<Name>[],
+ ...sources: PermissionGrants[]
) {
this.definition(name)
- return this.granted(all) || this.grants(name, permission, requested)
+ const effective = (key: PermissionName) => this.effective(key, ...sources.map(source => source[key] ?? null))
+
+ if (this.granted(effective("all"))) return true
+
+ const permission = name === "services"
+ ? this.combine("services", effective("services"), effective("programs"))
+ : effective(name)
+
+ return this.grants(name, permission, requested)
}
/** Tests one native Storage path against the complete effective authority. */
@@ -226,25 +227,13 @@ export class PermissionCatalog {
return left.length !== right.length || left.some(value => !right.includes(value))
}
- /** Resolves one concrete effective-grant transition when it occurs. */
- public needReload<Name extends PermissionName>(name: Name, before: Permission<Name>, permission: Permission<Name>) {
-
- if (!this.changed(before, permission)) return false
-
- return this.reloads[name]?.(clone(before), clone(permission)) === true
- }
}
type PermissionGrant = readonly string[] | false | null
-type PermissionReload<Name extends PermissionName = PermissionName> = (
- before: Permission<Name>,
- permission: Permission<Name>
-) => boolean
+type PermissionGrants = Readonly<Partial<Record<PermissionName, PermissionGrant>>>
-type PermissionRule<Name extends PermissionName> = Omit<PermissionDefinition<Name>, "valueDomain"> & Readonly<{
- requiresReload?: PermissionReload<Name>
-}>
+type PermissionRule<Name extends PermissionName> = Omit<PermissionDefinition<Name>, "valueDomain">
type PermissionRules = Readonly<{
[Name in PermissionName]: PermissionRule<Name>
@@ -257,11 +246,6 @@ type StoredDefinition = Readonly<{
description: string
}>
-function clone<Name extends PermissionName>(permission: Permission<Name>): Permission<Name> {
-
- return Array.isArray(permission) ? [...permission] : permission
-}
-
function strings(value: unknown, subject: string): string[] {
if (!Array.isArray(value) || value.some(entry => typeof entry !== "string")) throw new Error(`${subject} must be a list of strings`)
@@ -296,13 +280,12 @@ function valueCovers(domain: PermissionValueDomain, grant: string, requested: st
return false
}
-/** The presentation and activation rules for every Core-defined permission. */
+/** The presentation and defaults for every Core-defined permission. */
export const permissionCatalog = new PermissionCatalog({
all: {
default: [],
title: "All permissions",
- description: "Grant every available Client permission.",
- requiresReload: (before, permission) => Array.isArray(before) !== Array.isArray(permission)
+ description: "Grant every available Client permission."
},
services: {
default: [],