Skip to content

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

Enforce client storage and upload permissions

zohayrslileh276a9ac6ee7f
diff --git a/scripts/contracts/client-system-access.ts b/scripts/contracts/client-system-access.ts
index 3edd4b3..5e06060 100644
--- a/scripts/contracts/client-system-access.ts
+++ b/scripts/contracts/client-system-access.ts
@@ -1,4 +1,6 @@
import assert from "node:assert/strict"
+import { homedir } from "node:os"
+import { resolve } from "node:path"
import type AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
import SystemAccess from "@client/view/components/desktop-host/system-access"
import { permissionCatalog } from "@server/core/permissions"
@@ -20,6 +22,12 @@ const authManager = {
assert.equal(process, owner.identity)
return permissionCatalog.allows(name, permissions.all ?? null, permissions[name] ?? null, values as never)
+ },
+ async grantsStorage(process: string, path: string, operation?: "read" | "write" | "delete") {
+
+ assert.equal(process, owner.identity)
+
+ return permissionCatalog.allowsStorage(permissions.all ?? null, permissions.storage ?? null, path, operation)
}
} as unknown as AuthManager
@@ -45,6 +53,8 @@ await assert.rejects(access.process(outside as never), /Execution is not permitt
await assert.rejects(access.service(outsideService), /Execution is not permitted/)
await assert.rejects(access.requirePrograms(), /Execution is not permitted/)
await assert.rejects(access.requireNetwork("https://api.example.com/v1/users"), /Execution is not permitted/)
+await assert.rejects(access.requireStorage("/Users/person/Documents/report.txt", "read"), /Execution is not permitted/)
+await assert.rejects(access.require("uploads", []), /Execution is not permitted/)
await assert.rejects(access.require("appearance", []), /Execution is not permitted/)
await assert.rejects(access.require("desktopPreferences", []), /Execution is not permitted/)
@@ -80,12 +90,30 @@ await access.require("appearance", [])
await access.require("desktopPreferences", [])
await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)
+permissions = { uploads: [] }
+
+await access.require("uploads", [])
+await assert.rejects(access.requireAll(), /Execution is not permitted/)
+
permissions = { network: ["https://*.example.com/v1/**"] }
await access.requireNetwork("https://api.example.com/v1/users")
await assert.rejects(access.requireNetwork("https://example.com/v1/users"), /Execution is not permitted/)
await assert.rejects(access.requireNetwork("https://api.example.com/v2/users"), /Execution is not permitted/)
+permissions = { storage: ["read:Documents/**", "write:Documents/report.txt"] }
+
+await access.requireStorage(resolve(homedir(), "Documents/report.txt"))
+await access.requireStorage(resolve(homedir(), "Documents/report.txt"), "read")
+await access.requireStorage(resolve(homedir(), "Documents/report.txt"), "write")
+await assert.rejects(access.requireStorage(resolve(homedir(), "Documents/other.txt"), "write"), /Execution is not permitted/)
+await assert.rejects(access.requireStorage(resolve(homedir(), "Documents/report.txt"), "delete"), /Execution is not permitted/)
+await assert.rejects(access.requireStorage(homedir()), /Execution is not permitted/)
+
+permissions = { storage: [] }
+
+await access.requireStorage(homedir())
+
permissions = { all: [] }
assert.equal((await access.program(outsideProgram as never)).identity, "outside")
@@ -95,4 +123,6 @@ await access.requirePrograms()
await access.require("appearance", [])
await access.require("desktopPreferences", [])
await access.requireNetwork("wss://events.example.com/socket")
+await access.requireStorage("/any/native/path", "delete")
+await access.require("uploads", [])
await access.requireAll()
diff --git a/scripts/contracts/permissions.ts b/scripts/contracts/permissions.ts
index eb557fe..778da45 100644
--- a/scripts/contracts/permissions.ts
+++ b/scripts/contracts/permissions.ts
@@ -24,6 +24,16 @@ const catalog = new PermissionCatalog({
title: "Network",
description: "Use System networking with every request target or selected target scopes."
},
+ storage: {
+ default: [],
+ title: "Storage",
+ description: "Use every native filesystem path or selected operation-and-path scopes."
+ },
+ uploads: {
+ default: [],
+ title: "Uploads",
+ description: "Create values in the System uploads collection."
+ },
appearance: {
default: [],
title: "Appearance",
@@ -54,11 +64,25 @@ assert.deepEqual(catalog.definition("network"), {
title: "Network",
description: "Use System networking with every request target or selected target scopes."
})
+assert.deepEqual(catalog.definition("storage"), {
+ valueDomain: "storage",
+ default: [],
+ title: "Storage",
+ description: "Use every native filesystem path or selected operation-and-path scopes."
+})
+assert.deepEqual(catalog.definition("uploads"), {
+ valueDomain: "none",
+ default: [],
+ title: "Uploads",
+ description: "Create values in the System uploads collection."
+})
assert.deepEqual(catalog.resolve("all", true), [])
assert.deepEqual(catalog.resolve("all", []), [])
assert.deepEqual(catalog.resolve("services", true), [])
assert.deepEqual(catalog.resolve("services", ["flambo", "terminal", "flambo"]), ["flambo", "terminal"])
assert.deepEqual(catalog.resolve("network", ["HTTPS://API.Example.com:443/v1/**"]), ["https://api.example.com/v1/**"])
+assert.deepEqual(catalog.resolve("storage", ["delete,read:Documents/**"]), ["read,delete:Documents/**"])
+assert.deepEqual(catalog.resolve("uploads", true), [])
assert.equal(catalog.resolve("all", false), false)
assert.equal(catalog.resolve("all", null), null)
@@ -78,6 +102,10 @@ assert(catalog.grants("network", ["https://api.example.com"], ["https://api.exam
assert(catalog.grants("network", ["https://*.example.com/v1/**"], ["https://eu.example.com/v1/users"]))
assert(!catalog.grants("network", ["https://*.example.com/v1/**"], ["https://example.com/v1/users"]))
assert(!catalog.grants("network", ["https://api.example.com/v1/**"], ["https://api.example.com/v2/users"]))
+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"]))
@@ -110,6 +138,8 @@ 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, []))
@@ -118,6 +148,8 @@ assert.throws(() => catalog.resolve("all", ["unknown"]), /unknown value/)
assert.throws(() => catalog.resolve("appearance", ["flambo"]), /unknown value/)
assert.throws(() => catalog.resolve("services", ["Not a Program"]), /unknown value/)
assert.throws(() => catalog.resolve("network", ["api.example.com"]), /unknown value/)
+assert.throws(() => catalog.resolve("storage", ["all:Documents"]), /unknown value/)
+assert.throws(() => catalog.resolve("storage", ["all,read:Documents"]), /unknown value/)
assert.throws(() => catalog.declarations({ all: ["unknown"] }), /unknown value/)
assert.throws(() => catalog.stored({ all: true }), /unresolved shorthand/)
assert.throws(() => new PermissionCatalog({} as never), /needs a definition/)
@@ -130,6 +162,8 @@ assert.throws(() => new PermissionCatalog({
services: catalog.definition("services"),
programs: catalog.definition("programs"),
network: catalog.definition("network"),
+ storage: catalog.definition("storage"),
+ uploads: catalog.definition("uploads"),
appearance: catalog.definition("appearance"),
desktopPreferences: catalog.definition("desktopPreferences")
} as never), /invalid default/)
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 9be1a30..afea55a 100644
--- a/source/client/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts
@@ -83,6 +83,11 @@ export default class AuthManager extends TheLink {
return await this.$outbound.publishFirst("/permission/grants", process, name, requested) as boolean
}
+ public async grantsStorage(process: string, path: string, operation?: "read" | "write" | "delete") {
+
+ return await this.$outbound.publishFirst("/permission/storage", process, path, operation) as boolean
+ }
+
public async requestPermission<Name extends PermissionName>(
process: string,
request: string,
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index 0ee6008..dadb90e 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -793,6 +793,17 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
const program = await permittedProgram(args[0])
+ if (operation === "path" || operation === "resolve") {
+
+ const path = await programManager.area(address(program), word, operation, args.slice(2))
+
+ if (typeof path !== "string") throw new Error("The System returned an invalid Storage path")
+
+ await access.requireStorage(path)
+
+ return [path]
+ }
+
if (operation === "stream" || operation === "write") {
const joins = args[2]
@@ -853,20 +864,52 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
if (word === "host-storage") {
- await access.requireAll()
+ const operation = String(args[0])
+ const paths = args.slice(1)
+
+ if (paths.some(path => typeof path !== "string")) throw new Error("A storage path is a list of names")
+
+ if (operation === "path") {
+
+ const path = await authManager.storage(operation, [])
+
+ if (typeof path !== "string") throw new Error("The System returned an invalid Storage path")
+
+ await access.requireStorage(path)
+
+ return [path]
+ }
+
+ const path = await authManager.storage("resolve", paths as string[])
+
+ if (typeof path !== "string") throw new Error("The System returned an invalid Storage path")
+
+ if (operation === "resolve") {
- return [await authManager.storage(String(args[0]), args.slice(1).map(String))]
+ await access.requireStorage(path)
+
+ return [path]
+ }
+
+ const required = operation === "delete" || operation === "clear" ? "delete" : "read"
+
+ await access.requireStorage(path, required)
+
+ return [await authManager.storage(operation, paths as string[])]
}
if (word === "host-storage-stream" || word === "host-storage-write") {
- await access.requireAll()
-
const path = args[0]
if (!Array.isArray(path) || path.some(part => typeof part !== "string")) throw new Error("A storage path is a list of names")
const writing = word === "host-storage-write"
+ const resolved = await authManager.storage("resolve", path)
+
+ if (typeof resolved !== "string") throw new Error("The System returned an invalid Storage path")
+
+ await access.requireStorage(resolved, writing ? "write" : "read")
const { control, controller } = cancellation(args[2], word)
const request = { scope: "system" as const, path }
@@ -900,15 +943,20 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
// fact, and the gutter remains private desktop layout state.
if (word === "desktopSurface") return [desktop()]
- // Uploads are one flat public collection. The all permission exposes
- // its native entry point as part of the complete System contract.
+ // Completed uploads are public values. Creating one has its own
+ // permission; exposing the native directory requires complete access.
if (word === "uploads") {
- await access.requireAll()
-
const operation = args[0]
- if (operation === "path") return [await authManager.uploadsPath()]
+ if (operation === "path") {
+
+ const path = await authManager.uploadsPath()
+
+ await access.requireStorage(path)
+
+ return [path]
+ }
if (operation === "stat") {
@@ -946,6 +994,9 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
}
if (operation !== "write") throw new Error(`Uploads does not know the operation "${String(operation)}"`)
+
+ await access.require("uploads", [])
+
if (!clientBody(args[1])) throw new Error("Uploads write takes bytes")
const description = args[2] as Partial<UploadValue> | null
diff --git a/source/client/view/components/desktop-host/system-access.ts b/source/client/view/components/desktop-host/system-access.ts
index 073d6c7..860d7db 100644
--- a/source/client/view/components/desktop-host/system-access.ts
+++ b/source/client/view/components/desktop-host/system-access.ts
@@ -94,6 +94,11 @@ export default class SystemAccess {
await this.require("network", [scope])
}
+ public async requireStorage(path: string, operation?: "read" | "write" | "delete") {
+
+ if (!await this.authManager.grantsStorage(this.pane, path, operation)) throw new Error(denied)
+ }
+
public async require<Name extends PermissionName>(name: Name, values: readonly PermissionValue<Name>[]) {
if (!await this.authManager.grantsPermission(this.pane, name, values)) throw new Error(denied)
diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.ts
index a2adde4..0e13203 100644
--- a/source/server/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -171,6 +171,18 @@ export default class AuthManager extends TheLink {
return this.processManager.grants(process, permission, values)
}
+ @Connect("/permission/storage")
+ protected async grantsStorage(process: unknown, path: unknown, operation: unknown) {
+
+ if (typeof process !== "string"
+ || typeof path !== "string"
+ || operation !== undefined && operation !== "read" && operation !== "write" && operation !== "delete") {
+ throw new Error("A Storage permission check is invalid")
+ }
+
+ return this.processManager.grantsStorage(process, path, operation)
+ }
+
@Connect("/permission/request")
protected async requestPermission(request: unknown, process: unknown, name: unknown, permission: unknown) {
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 5c1e078..d29b1dc 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
@@ -1541,6 +1541,19 @@ export default class ProcessManager extends TheLink {
)
}
+ /** Tests one native Storage target against this Process's effective grants. */
+ public grantsStorage(identity: string, path: string, operation?: "read" | "write" | "delete") {
+
+ const process = this.find(identity)
+
+ return permissionCatalog.allowsStorage(
+ this.effectivePermission(process, "all"),
+ this.effectivePermission(process, "storage"),
+ path,
+ operation
+ )
+ }
+
/** Resolves one permission request through declarations, grants, then the owner. */
public async requestPermission<Name extends PermissionName>(
identity: string,
diff --git a/source/server/core/permissions.ts b/source/server/core/permissions.ts
index 1204714..18abe74 100644
--- a/source/server/core/permissions.ts
+++ b/source/server/core/permissions.ts
@@ -10,8 +10,10 @@ import {
type PermissionName,
type PermissionValue,
type PermissionValueDomain,
- type Permissions
+ type Permissions,
+ type StoragePermissionOperation
} from "@phreshos/core"
+import { nativeStorageScopeAccesses, nativeStorageScopeCovers } from "./storage-permission"
/** Validation and derivation over the one permission domain defined by Core. */
export class PermissionCatalog {
@@ -174,6 +176,21 @@ export class PermissionCatalog {
return this.granted(all) || this.grants(name, permission, requested)
}
+ /** Tests one native Storage path against the complete effective authority. */
+ public allowsStorage(
+ all: PermissionGrant,
+ storage: PermissionGrant,
+ path: string,
+ operation?: StoragePermissionOperation
+ ) {
+
+ if (this.granted(all)) return true
+ if (!Array.isArray(storage)) return false
+ if (storage.length === 0) return true
+
+ return storage.some(scope => nativeStorageScopeAccesses(scope, path, operation))
+ }
+
public combine<Name extends PermissionName>(name: Name, ...grants: PermissionGrant[]): Permission<Name> {
const present = grants.filter((grant): grant is readonly string[] => Array.isArray(grant))
@@ -259,7 +276,7 @@ function unique(values: readonly string[]) {
function valued(domain: PermissionValueDomain) {
- if (domain === "program" || domain === "network") return true
+ if (domain === "program" || domain === "network" || domain === "storage") return true
if (domain === "none") return false
domain satisfies never
@@ -271,6 +288,7 @@ function valueCovers(domain: PermissionValueDomain, grant: string, requested: st
if (domain === "program") return grant === requested
if (domain === "network") return networkScopeCovers(grant, requested)
+ if (domain === "storage") return nativeStorageScopeCovers(grant, requested)
if (domain === "none") return false
domain satisfies never
@@ -301,6 +319,16 @@ export const permissionCatalog = new PermissionCatalog({
title: "Network",
description: "Use System networking with every request target or selected target scopes."
},
+ storage: {
+ default: [],
+ title: "Storage",
+ description: "Use every native filesystem path or selected operation-and-path scopes."
+ },
+ uploads: {
+ default: [],
+ title: "Uploads",
+ description: "Create values in the System uploads collection."
+ },
appearance: {
default: [],
title: "Appearance",
diff --git a/source/server/core/storage-permission.ts b/source/server/core/storage-permission.ts
new file mode 100644
index 0000000..3a17288
--- /dev/null
+++ b/source/server/core/storage-permission.ts
@@ -0,0 +1,80 @@
+import {
+ describeStorageScope,
+ type StoragePermissionOperation,
+ type StorageScope
+} from "@phreshos/core"
+import { existsSync, realpathSync } from "node:fs"
+import { homedir } from "node:os"
+import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path"
+
+type NativeStorageRegion = Readonly<{
+ operations: readonly StoragePermissionOperation[]
+ path: string
+ recursive: boolean
+}>
+
+/** Whether one native Storage grant fully contains another requested scope. */
+export function nativeStorageScopeCovers(grant: StorageScope, requested: StorageScope) {
+
+ const outer = nativeRegion(grant)
+ const inner = nativeRegion(requested)
+
+ return inner.operations.every(operation => outer.operations.includes(operation))
+ && regionCovers(outer, inner.path, inner.recursive)
+}
+
+/** Whether one scope provides any access, or one operation, at an exact path. */
+export function nativeStorageScopeAccesses(
+ grant: StorageScope,
+ path: string,
+ operation?: StoragePermissionOperation
+) {
+
+ const region = nativeRegion(grant)
+
+ return (!operation || region.operations.includes(operation))
+ && regionCovers(region, nativePath(path), false)
+}
+
+function nativeRegion(scope: StorageScope): NativeStorageRegion {
+
+ const description = describeStorageScope(scope)
+
+ return Object.freeze({
+ operations: description.operations,
+ path: nativePath(description.path),
+ recursive: description.recursive
+ })
+}
+
+function nativePath(path: string) {
+
+ const absolute = resolve(homedir(), path)
+ const remaining: string[] = []
+ let current = absolute
+
+ while (!existsSync(current)) {
+
+ const parent = dirname(current)
+
+ if (parent === current) break
+
+ remaining.unshift(basename(current))
+ current = parent
+ }
+
+ const canonical = existsSync(current)
+ ? resolve(realpathSync.native(current), ...remaining)
+ : absolute
+
+ return process.platform === "win32" ? canonical.toLowerCase() : canonical
+}
+
+function regionCovers(grant: NativeStorageRegion, requestedPath: string, requestedRecursive: boolean) {
+
+ if (!grant.recursive) return !requestedRecursive && grant.path === requestedPath
+
+ const step = relative(grant.path, requestedPath)
+
+ return step === "" || step !== ".." && !step.startsWith(`..${sep}`) && !isAbsolute(step)
+}