Skip to content
Merged
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
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "solid-logic",
"version": "6.0.0",
"version": "6.0.0-1",
"description": "Core business logic of SolidOS",
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
Expand Down
95 changes: 95 additions & 0 deletions src/acl/accessControlSubjects.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { LiveStore, sym } from 'rdflib'
import { ns } from '../util/ns'

export type AccessControlSubjectKind = 'agent' | 'agentGroup' | 'agentClass' | 'origin'

export type AccessControlSubject = {
kind: AccessControlSubjectKind
subjectValue: string
}

const ACCESS_CONTROL_SUBJECT_GROUPS = {
agentClass: [ns.foaf('Agent'), ns.acl('AuthenticatedAgent'), ns.rdf('Resource'), ns.owl('Thing')],
agent: [ns.vcard('WebID'), ns.vcard('Individual'), ns.foaf('Person'), ns.foaf('Agent')],
agentGroup: [ns.vcard('Group')],
origin: [ns.solid('AppProvider'), ns.solid('AppProviderClass')]
} as const

function hasKnownTypes (types: Record<string, unknown>): boolean {
return Object.keys(types).length > 0
}

function isHttpUrl (value: string): boolean {
return value.startsWith('http://') || value.startsWith('https://')
}

function isBareOriginUrl (value: string): boolean {
try {
const parsed = new URL(value)
return (parsed.protocol === 'http:' || parsed.protocol === 'https:') &&
parsed.pathname === '/' &&
!parsed.search &&
!parsed.hash
} catch (_error) {
return false
}
}

function normalizeOriginUrl (value: string): string {
try {
const parsed = new URL(value)
if (
(parsed.protocol === 'http:' || parsed.protocol === 'https:') &&
parsed.pathname === '/' &&
!parsed.search &&
!parsed.hash
) {
return `${parsed.protocol}//${parsed.host}`
}
} catch (_error) {
// Return the original value below when parsing fails.
}

return value
}

export async function classifyAccessControlSubject (store: LiveStore, principle: string): Promise<AccessControlSubject | undefined> {
const subject = sym(principle)
let types = store.findTypeURIs(subject)

if (isBareOriginUrl(principle)) {
return { kind: 'origin', subjectValue: normalizeOriginUrl(principle) }
}

if (!hasKnownTypes(types) && isHttpUrl(principle)) {
try {
await store.fetcher.load(subject.doc())
} catch (error) {
console.error(`Failed to load access target ${principle}`, error)
}

types = store.findTypeURIs(subject)
}

if (ACCESS_CONTROL_SUBJECT_GROUPS.origin.some(term => term.uri in types)) {
return { kind: 'origin', subjectValue: principle }
}

if (ACCESS_CONTROL_SUBJECT_GROUPS.agent.some(term => term.uri in types)) {
const preferredURI = store.any(subject, ns.foaf('preferredURI'))
return {
kind: 'agent',
subjectValue: preferredURI?.value ?? principle
}
}

if (ACCESS_CONTROL_SUBJECT_GROUPS.agentGroup.some(term => term.uri in types)) {
return { kind: 'agentGroup', subjectValue: principle }
}

if (ACCESS_CONTROL_SUBJECT_GROUPS.agentClass.some(term => subject.sameTerm(term))) {
return { kind: 'agentClass', subjectValue: principle }
}

return undefined
}
31 changes: 31 additions & 0 deletions src/acl/aclLogic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { applyPlan as applyAuthorizationPlan, findEffectiveACL, planGrant as pla
import { graph, NamedNode, Namespace, serialize, sym } from 'rdflib'
import type { AclLogic } from '../types'
import { ns as namespace } from '../util/ns'
import * as accessControlSubjects from './accessControlSubjects'

// Will remove the below comment when i'm done with the manage access work
// Helpers available from @dokieli/web-access-control:
// - Discovery: findEffectiveACL, parentContainer
// - ACL context and parsing: buildACLContext, authorizationsFromDataset, parseTurtle
Expand All @@ -12,6 +14,9 @@ import { ns as namespace } from '../util/ns'
// - Link and allow parsing: allows, parseWacAllow, linkTargets, parseLinkHeader
// - Terms and constants: ACCESS_MODES, ACL, Authenticated, FOAF, modeFromIRI, modeIRI, namedNode, Public, quad, RDF_TYPE, variable

export const ACCESS_ROLES = ['Owner', 'Editor', 'No Access', 'Viewer', 'Poster', 'Submitter'] as const

export type AccessRole = typeof ACCESS_ROLES[number]

export const ACL_LINK = sym(
'http://www.iana.org/assignments/link-relations/acl'
Expand All @@ -20,6 +25,25 @@ export const ACL_LINK = sym(
export function createAclLogic(store): AclLogic {

const ns = namespace
const ACCESS_ROLE_RULES: Array<{ label: AccessRole, modes: AccessMode[] }> = [
{ label: 'Owner', modes: ['Read', 'Write', 'Control'] },
{ label: 'Editor', modes: ['Read', 'Write'] },
{ label: 'Poster', modes: ['Append', 'Read'] },
{ label: 'Submitter', modes: ['Append'] },
{ label: 'Viewer', modes: ['Read'] },
{ label: 'No Access', modes: [] }
]

function roleFromModes (modes: Iterable<AccessMode>): AccessRole {
const modeSet = new Set(modes)
const matchingRule = ACCESS_ROLE_RULES.find(rule => rule.label !== 'No Access' && rule.modes.every(mode => modeSet.has(mode)))

return matchingRule?.label ?? 'No Access'
}

function modesFromRole (role: AccessRole): AccessMode[] {
return [...(ACCESS_ROLE_RULES.find(rule => rule.label === role)?.modes ?? [])]
}

function getFetch() {
const fetcher = store.fetcher as {
Expand Down Expand Up @@ -70,6 +94,10 @@ export function createAclLogic(store): AclLogic {
async function applyPlan(plan: PatchPlan): Promise<Response> {
return applyAuthorizationPlan(plan, { fetch: getFetch() })
}

async function classifyAccessControlSubject(principle: string) {
return accessControlSubjects.classifyAccessControlSubject(store, principle)
}
/**
* Simple Access Control
*
Expand Down Expand Up @@ -202,10 +230,13 @@ export function createAclLogic(store): AclLogic {
findAclDocUrl,
findEffectiveAcl,
findAccessGrants,
roleFromModes,
modesFromRole,
planGrant,
planRevoke,
planPublicRead,
applyPlan,
classifyAccessControlSubject,
setACLUserPublic,
genACLText
}
Expand Down
90 changes: 90 additions & 0 deletions src/directory/catalogDirectory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { type DirectoryEntry } from '../types'
import { graph, type LiveStore, NamedNode, parse } from 'rdflib'
import { ns } from '../util/ns'
import * as debug from '../util/debug'
import { isHttpUri } from './directoryHelpers'

const CATALOG_VOCAB = 'http://example.org#'

export function createCatalogDirectoryDiscovery () {
const catalogEntriesCache = new Map<string, Promise<DirectoryEntry[]>>()

async function discoverCatalogEntries (
catalogUrl: string,
onEntry: (entry: DirectoryEntry) => void | Promise<void>
): Promise<void> {
const entries = await fetchCatalogEntries(catalogUrl)
for (const entry of entries) {
await onEntry(entry)
}
}

async function fetchCatalogEntries (catalogUrl: string): Promise<DirectoryEntry[]> {
const cached = catalogEntriesCache.get(catalogUrl)
if (cached) {
return cached
}

const promise = loadCatalogEntries(catalogUrl).catch(error => {
catalogEntriesCache.delete(catalogUrl)
throw error
})

catalogEntriesCache.set(catalogUrl, promise)
try {
return await promise
} catch (error) {
debug.warn('[Directory] Error fetching directory catalog:', error)
return []
}
}

async function loadCatalogEntries (catalogUrl: string): Promise<DirectoryEntry[]> {
if (typeof fetch !== 'function') {
throw new Error('Fetch API is unavailable')
}

const response = await fetch(catalogUrl, {
headers: { accept: 'text/turtle' }
})

if (!response.ok) {
throw new Error(`Failed to fetch ${catalogUrl}: ${response.status}`)
}

const turtle = await response.text()
const catalogStore = graph() as LiveStore
parse(turtle, catalogStore, catalogUrl, 'text/turtle')

const personType = new NamedNode(`${CATALOG_VOCAB}Person`)
const webIdPredicate = new NamedNode(`${CATALOG_VOCAB}webid`)
const namePredicate = new NamedNode(`${CATALOG_VOCAB}name`)
const catalogPeople = new Map<string, DirectoryEntry>()

const statements = catalogStore.statementsMatching(undefined, ns.rdf('type'), personType)
for (const statement of statements) {
const subject = statement.subject
const webIdNode = catalogStore.any(subject, webIdPredicate)
if (webIdNode && webIdNode.termType === 'NamedNode') {
const webId = webIdNode.value
const personName = catalogStore.anyValue(subject, namePredicate)
if (isHttpUri(webId) && personName) {
catalogPeople.set(webId, {
kind: 'person',
uri: webId,
label: personName,
subjectType: 'agent',
relationshipLabel: 'People',
sources: ['catalog']
})
}
}
}

return Array.from(catalogPeople.values())
}

return {
discoverCatalogEntries
}
}
Loading
Loading