mirror of
https://github.com/CommunitySolidServer/CommunitySolidServer.git
synced 2024-10-03 14:55:10 +00:00
feat: Use PermissionReaders to determine available permissions
These readers will determine which permissions are available for the incoming credentials. Their results then get combined in a UnionReader and authorized in a PermissionBasedAuthorizer
This commit is contained in:
32
src/authorization/AllStaticReader.ts
Normal file
32
src/authorization/AllStaticReader.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { CredentialGroup } from '../authentication/Credentials';
|
||||
import type { Permission, PermissionSet } from '../ldp/permissions/Permissions';
|
||||
import type { PermissionReaderInput } from './PermissionReader';
|
||||
import { PermissionReader } from './PermissionReader';
|
||||
|
||||
/**
|
||||
* PermissionReader which sets all permissions to true or false
|
||||
* independently of the identifier and requested permissions.
|
||||
*/
|
||||
export class AllStaticReader extends PermissionReader {
|
||||
private readonly permissions: Permission;
|
||||
|
||||
public constructor(allow: boolean) {
|
||||
super();
|
||||
this.permissions = Object.freeze({
|
||||
read: allow,
|
||||
write: allow,
|
||||
append: allow,
|
||||
control: allow,
|
||||
});
|
||||
}
|
||||
|
||||
public async handle({ credentials }: PermissionReaderInput): Promise<PermissionSet> {
|
||||
const result: PermissionSet = {};
|
||||
for (const [ key, value ] of Object.entries(credentials) as [CredentialGroup, Permission][]) {
|
||||
if (value) {
|
||||
result[key] = this.permissions;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import type { PermissionSet } from '../ldp/permissions/PermissionSet';
|
||||
import { Authorizer } from './Authorizer';
|
||||
import { WebAclAuthorization } from './WebAclAuthorization';
|
||||
|
||||
const allowAll: PermissionSet = {
|
||||
read: true,
|
||||
write: true,
|
||||
append: true,
|
||||
control: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Authorizer which allows all access independent of the identifier and requested permissions.
|
||||
*/
|
||||
export class AllowAllAuthorizer extends Authorizer {
|
||||
public async handle(): Promise<WebAclAuthorization> {
|
||||
return new WebAclAuthorization(allowAll, allowAll);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { CredentialSet } from '../authentication/Credentials';
|
||||
import type { AccessMode } from '../ldp/permissions/PermissionSet';
|
||||
import type { AccessMode } from '../ldp/permissions/Permissions';
|
||||
import type { ResourceIdentifier } from '../ldp/representation/ResourceIdentifier';
|
||||
import { AsyncHandler } from '../util/handlers/AsyncHandler';
|
||||
import type { Authorization } from './Authorization';
|
||||
@@ -20,7 +20,7 @@ export interface AuthorizerInput {
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies if the given credentials have access to the given permissions on the given resource.
|
||||
* Verifies if the credentials provide access with the given permissions on the resource.
|
||||
* An {@link Error} with the necessary explanation will be thrown when permissions are not granted.
|
||||
*/
|
||||
export abstract class Authorizer extends AsyncHandler<AuthorizerInput, Authorization> {}
|
||||
|
||||
@@ -1,45 +1,46 @@
|
||||
import type { AuxiliaryIdentifierStrategy } from '../ldp/auxiliary/AuxiliaryIdentifierStrategy';
|
||||
import type { PermissionSet } from '../ldp/permissions/Permissions';
|
||||
import { getLoggerFor } from '../logging/LogUtil';
|
||||
import { NotImplementedHttpError } from '../util/errors/NotImplementedHttpError';
|
||||
import type { Authorization } from './Authorization';
|
||||
import type { AuthorizerInput } from './Authorizer';
|
||||
import { Authorizer } from './Authorizer';
|
||||
|
||||
import type { PermissionReaderInput } from './PermissionReader';
|
||||
import { PermissionReader } from './PermissionReader';
|
||||
|
||||
/**
|
||||
* An authorizer for auxiliary resources such as acl or shape resources.
|
||||
* A PermissionReader for auxiliary resources such as acl or shape resources.
|
||||
* The access permissions of an auxiliary resource depend on those of the resource it is associated with.
|
||||
* This authorizer calls the source authorizer with the identifier of the associated resource.
|
||||
*/
|
||||
export class AuxiliaryAuthorizer extends Authorizer {
|
||||
export class AuxiliaryReader extends PermissionReader {
|
||||
protected readonly logger = getLoggerFor(this);
|
||||
|
||||
private readonly resourceAuthorizer: Authorizer;
|
||||
private readonly resourceReader: PermissionReader;
|
||||
private readonly auxiliaryStrategy: AuxiliaryIdentifierStrategy;
|
||||
|
||||
public constructor(resourceAuthorizer: Authorizer, auxiliaryStrategy: AuxiliaryIdentifierStrategy) {
|
||||
public constructor(resourceReader: PermissionReader, auxiliaryStrategy: AuxiliaryIdentifierStrategy) {
|
||||
super();
|
||||
this.resourceAuthorizer = resourceAuthorizer;
|
||||
this.resourceReader = resourceReader;
|
||||
this.auxiliaryStrategy = auxiliaryStrategy;
|
||||
}
|
||||
|
||||
public async canHandle(auxiliaryAuth: AuthorizerInput): Promise<void> {
|
||||
public async canHandle(auxiliaryAuth: PermissionReaderInput): Promise<void> {
|
||||
const resourceAuth = this.getRequiredAuthorization(auxiliaryAuth);
|
||||
return this.resourceAuthorizer.canHandle(resourceAuth);
|
||||
return this.resourceReader.canHandle(resourceAuth);
|
||||
}
|
||||
|
||||
public async handle(auxiliaryAuth: AuthorizerInput): Promise<Authorization> {
|
||||
public async handle(auxiliaryAuth: PermissionReaderInput): Promise<PermissionSet> {
|
||||
const resourceAuth = this.getRequiredAuthorization(auxiliaryAuth);
|
||||
this.logger.debug(`Checking auth request for ${auxiliaryAuth.identifier.path} on ${resourceAuth.identifier.path}`);
|
||||
return this.resourceAuthorizer.handle(resourceAuth);
|
||||
return this.resourceReader.handle(resourceAuth);
|
||||
}
|
||||
|
||||
public async handleSafe(auxiliaryAuth: AuthorizerInput): Promise<Authorization> {
|
||||
public async handleSafe(auxiliaryAuth: PermissionReaderInput): Promise<PermissionSet> {
|
||||
const resourceAuth = this.getRequiredAuthorization(auxiliaryAuth);
|
||||
this.logger.debug(`Checking auth request for ${auxiliaryAuth.identifier.path} to ${resourceAuth.identifier.path}`);
|
||||
return this.resourceAuthorizer.handleSafe(resourceAuth);
|
||||
return this.resourceReader.handleSafe(resourceAuth);
|
||||
}
|
||||
|
||||
private getRequiredAuthorization(auxiliaryAuth: AuthorizerInput): AuthorizerInput {
|
||||
private getRequiredAuthorization(auxiliaryAuth: PermissionReaderInput): PermissionReaderInput {
|
||||
if (!this.auxiliaryStrategy.isAuxiliaryIdentifier(auxiliaryAuth.identifier)) {
|
||||
throw new NotImplementedHttpError('AuxiliaryAuthorizer only supports auxiliary resources.');
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { ForbiddenHttpError } from '../util/errors/ForbiddenHttpError';
|
||||
import { Authorizer } from './Authorizer';
|
||||
|
||||
/**
|
||||
* An authorizer that rejects all requests.
|
||||
*/
|
||||
export class DenyAllAuthorizer extends Authorizer {
|
||||
public async handle(): Promise<never> {
|
||||
throw new ForbiddenHttpError();
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { NotImplementedHttpError } from '../util/errors/NotImplementedHttpError';
|
||||
import { ensureTrailingSlash, trimTrailingSlashes } from '../util/PathUtil';
|
||||
import type { Authorization } from './Authorization';
|
||||
import type { AuthorizerInput } from './Authorizer';
|
||||
import { Authorizer } from './Authorizer';
|
||||
|
||||
/**
|
||||
* Redirects requests to specific authorizers based on their identifier.
|
||||
* The keys in the input map will be converted to regular expressions.
|
||||
* The regular expressions should all start with a slash
|
||||
* and will be evaluated relative to the base URL.
|
||||
*
|
||||
* Will error if no match is found.
|
||||
*/
|
||||
export class PathBasedAuthorizer extends Authorizer {
|
||||
private readonly baseUrl: string;
|
||||
private readonly paths: Map<RegExp, Authorizer>;
|
||||
|
||||
public constructor(baseUrl: string, paths: Record<string, Authorizer>) {
|
||||
super();
|
||||
this.baseUrl = ensureTrailingSlash(baseUrl);
|
||||
const entries = Object.entries(paths).map(([ key, val ]): [RegExp, Authorizer] => [ new RegExp(key, 'u'), val ]);
|
||||
this.paths = new Map(entries);
|
||||
}
|
||||
|
||||
public async canHandle(input: AuthorizerInput): Promise<void> {
|
||||
const authorizer = this.findAuthorizer(input.identifier.path);
|
||||
await authorizer.canHandle(input);
|
||||
}
|
||||
|
||||
public async handle(input: AuthorizerInput): Promise<Authorization> {
|
||||
const authorizer = this.findAuthorizer(input.identifier.path);
|
||||
return authorizer.handle(input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the authorizer corresponding to the given path.
|
||||
* Errors if there is no match.
|
||||
*/
|
||||
private findAuthorizer(path: string): Authorizer {
|
||||
if (path.startsWith(this.baseUrl)) {
|
||||
// We want to keep the leading slash
|
||||
const relative = path.slice(trimTrailingSlashes(this.baseUrl).length);
|
||||
for (const [ regex, authorizer ] of this.paths) {
|
||||
if (regex.test(relative)) {
|
||||
return authorizer;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new NotImplementedHttpError('No regex matches the given path.');
|
||||
}
|
||||
}
|
||||
54
src/authorization/PathBasedReader.ts
Normal file
54
src/authorization/PathBasedReader.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import type { PermissionSet } from '../ldp/permissions/Permissions';
|
||||
import { NotImplementedHttpError } from '../util/errors/NotImplementedHttpError';
|
||||
import { ensureTrailingSlash, trimTrailingSlashes } from '../util/PathUtil';
|
||||
|
||||
import type { PermissionReaderInput } from './PermissionReader';
|
||||
import { PermissionReader } from './PermissionReader';
|
||||
|
||||
/**
|
||||
* Redirects requests to specific PermissionReaders based on their identifier.
|
||||
* The keys in the input map will be converted to regular expressions.
|
||||
* The regular expressions should all start with a slash
|
||||
* and will be evaluated relative to the base URL.
|
||||
*
|
||||
* Will error if no match is found.
|
||||
*/
|
||||
export class PathBasedReader extends PermissionReader {
|
||||
private readonly baseUrl: string;
|
||||
private readonly paths: Map<RegExp, PermissionReader>;
|
||||
|
||||
public constructor(baseUrl: string, paths: Record<string, PermissionReader>) {
|
||||
super();
|
||||
this.baseUrl = ensureTrailingSlash(baseUrl);
|
||||
const entries = Object.entries(paths)
|
||||
.map(([ key, val ]): [RegExp, PermissionReader] => [ new RegExp(key, 'u'), val ]);
|
||||
this.paths = new Map(entries);
|
||||
}
|
||||
|
||||
public async canHandle(input: PermissionReaderInput): Promise<void> {
|
||||
const reader = this.findReader(input.identifier.path);
|
||||
await reader.canHandle(input);
|
||||
}
|
||||
|
||||
public async handle(input: PermissionReaderInput): Promise<PermissionSet> {
|
||||
const reader = this.findReader(input.identifier.path);
|
||||
return reader.handle(input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the PermissionReader corresponding to the given path.
|
||||
* Errors if there is no match.
|
||||
*/
|
||||
private findReader(path: string): PermissionReader {
|
||||
if (path.startsWith(this.baseUrl)) {
|
||||
// We want to keep the leading slash
|
||||
const relative = path.slice(trimTrailingSlashes(this.baseUrl).length);
|
||||
for (const [ regex, reader ] of this.paths) {
|
||||
if (regex.test(relative)) {
|
||||
return reader;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new NotImplementedHttpError('No regex matches the given path.');
|
||||
}
|
||||
}
|
||||
92
src/authorization/PermissionBasedAuthorizer.ts
Normal file
92
src/authorization/PermissionBasedAuthorizer.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import type { CredentialSet } from '../authentication/Credentials';
|
||||
import type { AccessMode, PermissionSet } from '../ldp/permissions/Permissions';
|
||||
|
||||
import { getLoggerFor } from '../logging/LogUtil';
|
||||
import { ForbiddenHttpError } from '../util/errors/ForbiddenHttpError';
|
||||
import { UnauthorizedHttpError } from '../util/errors/UnauthorizedHttpError';
|
||||
import type { Authorization } from './Authorization';
|
||||
import type { AuthorizerInput } from './Authorizer';
|
||||
import { Authorizer } from './Authorizer';
|
||||
import type { PermissionReader } from './PermissionReader';
|
||||
import { WebAclAuthorization } from './WebAclAuthorization';
|
||||
|
||||
/**
|
||||
* Authorizer that bases its decision on the output it gets from its PermissionReader.
|
||||
* For each permission it checks if the reader allows that for at least one credential type,
|
||||
* if yes authorization is granted.
|
||||
* `undefined` values for reader results are interpreted as `false`.
|
||||
*/
|
||||
export class PermissionBasedAuthorizer extends Authorizer {
|
||||
protected readonly logger = getLoggerFor(this);
|
||||
|
||||
private readonly reader: PermissionReader;
|
||||
|
||||
public constructor(reader: PermissionReader) {
|
||||
super();
|
||||
this.reader = reader;
|
||||
}
|
||||
|
||||
public async canHandle(input: AuthorizerInput): Promise<void> {
|
||||
return this.reader.canHandle(input);
|
||||
}
|
||||
|
||||
public async handle(input: AuthorizerInput): Promise<Authorization> {
|
||||
const { credentials, modes, identifier } = input;
|
||||
|
||||
// Read out the permissions
|
||||
const permissions = await this.reader.handle(input);
|
||||
const authorization = new WebAclAuthorization(permissions.agent ?? {}, permissions.public ?? {});
|
||||
|
||||
const modeString = [ ...modes ].join(',');
|
||||
this.logger.debug(`Checking if ${credentials.agent?.webId} has ${modeString} permissions for ${identifier.path}`);
|
||||
|
||||
for (const mode of modes) {
|
||||
this.requireModePermission(credentials, permissions, mode);
|
||||
}
|
||||
this.logger.debug(`${JSON.stringify(credentials)} has ${modeString} permissions for ${identifier.path}`);
|
||||
return authorization;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that at least one of the credentials provides permissions for the given mode.
|
||||
* Throws a {@link ForbiddenHttpError} or {@link UnauthorizedHttpError} depending on the credentials
|
||||
* if access is not allowed.
|
||||
* @param credentials - Credentials that require access.
|
||||
* @param permissionSet - PermissionSet describing the available permissions of the credentials.
|
||||
* @param mode - Which mode is requested.
|
||||
*/
|
||||
private requireModePermission(credentials: CredentialSet, permissionSet: PermissionSet, mode: AccessMode): void {
|
||||
if (!this.hasModePermission(permissionSet, mode)) {
|
||||
if (this.isAuthenticated(credentials)) {
|
||||
this.logger.warn(`Agent ${credentials.agent!.webId} has no ${mode} permissions`);
|
||||
throw new ForbiddenHttpError();
|
||||
} else {
|
||||
// Solid, §2.1: "When a client does not provide valid credentials when requesting a resource that requires it,
|
||||
// the data pod MUST send a response with a 401 status code (unless 404 is preferred for security reasons)."
|
||||
// https://solid.github.io/specification/protocol#http-server
|
||||
this.logger.warn(`Unauthenticated agent has no ${mode} permissions`);
|
||||
throw new UnauthorizedHttpError();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if one of the Permissions in the PermissionSet grants permission to use the given mode.
|
||||
*/
|
||||
private hasModePermission(permissionSet: PermissionSet, mode: AccessMode): boolean {
|
||||
for (const permissions of Object.values(permissionSet)) {
|
||||
if (permissions[mode]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the agent is authenticated (logged in) or not (public/anonymous).
|
||||
* @param credentials - Credentials to check.
|
||||
*/
|
||||
private isAuthenticated(credentials: CredentialSet): boolean {
|
||||
return typeof credentials.agent?.webId === 'string';
|
||||
}
|
||||
}
|
||||
20
src/authorization/PermissionReader.ts
Normal file
20
src/authorization/PermissionReader.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { CredentialSet } from '../authentication/Credentials';
|
||||
import type { PermissionSet } from '../ldp/permissions/Permissions';
|
||||
import type { ResourceIdentifier } from '../ldp/representation/ResourceIdentifier';
|
||||
import { AsyncHandler } from '../util/handlers/AsyncHandler';
|
||||
|
||||
export interface PermissionReaderInput {
|
||||
/**
|
||||
* Credentials of the entity that wants to use the resource.
|
||||
*/
|
||||
credentials: CredentialSet;
|
||||
/**
|
||||
* Identifier of the resource that will be read/modified.
|
||||
*/
|
||||
identifier: ResourceIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discovers the permissions of the given credentials on the given identifier.
|
||||
*/
|
||||
export abstract class PermissionReader extends AsyncHandler<PermissionReaderInput, PermissionSet> {}
|
||||
40
src/authorization/UnionPermissionReader.ts
Normal file
40
src/authorization/UnionPermissionReader.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import type { CredentialGroup } from '../authentication/Credentials';
|
||||
import type { Permission, PermissionSet } from '../ldp/permissions/Permissions';
|
||||
import { UnionHandler } from '../util/handlers/UnionHandler';
|
||||
import type { PermissionReader } from './PermissionReader';
|
||||
|
||||
/**
|
||||
* Combines the results of multiple PermissionReaders.
|
||||
* Every permission in every credential type is handled according to the rule `false` \> `true` \> `undefined`.
|
||||
*/
|
||||
export class UnionPermissionReader extends UnionHandler<PermissionReader> {
|
||||
public constructor(readers: PermissionReader[]) {
|
||||
super(readers);
|
||||
}
|
||||
|
||||
protected async combine(results: PermissionSet[]): Promise<PermissionSet> {
|
||||
const result: PermissionSet = {};
|
||||
for (const permissionSet of results) {
|
||||
for (const [ key, value ] of Object.entries(permissionSet) as [ CredentialGroup, Permission | undefined ][]) {
|
||||
result[key] = this.applyPermissions(value, result[key]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the given permissions to the result object according to the combination rules of the class.
|
||||
*/
|
||||
private applyPermissions(permissions?: Permission, result: Permission = {}): Permission {
|
||||
if (!permissions) {
|
||||
return result;
|
||||
}
|
||||
|
||||
for (const [ key, value ] of Object.entries(permissions) as [ keyof Permission, boolean | undefined ][]) {
|
||||
if (typeof value !== 'undefined' && result[key] !== false) {
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PermissionSet } from '../ldp/permissions/PermissionSet';
|
||||
import type { Permission } from '../ldp/permissions/Permissions';
|
||||
import type { RepresentationMetadata } from '../ldp/representation/RepresentationMetadata';
|
||||
import { ACL, AUTH } from '../util/Vocabularies';
|
||||
import type { Authorization } from './Authorization';
|
||||
@@ -10,19 +10,20 @@ export class WebAclAuthorization implements Authorization {
|
||||
/**
|
||||
* Permissions granted to the agent requesting the resource.
|
||||
*/
|
||||
public user: PermissionSet;
|
||||
public user: Permission;
|
||||
/**
|
||||
* Permissions granted to the public.
|
||||
*/
|
||||
public everyone: PermissionSet;
|
||||
public everyone: Permission;
|
||||
|
||||
public constructor(user: PermissionSet, everyone: PermissionSet) {
|
||||
public constructor(user: Permission, everyone: Permission) {
|
||||
this.user = user;
|
||||
this.everyone = everyone;
|
||||
}
|
||||
|
||||
public addMetadata(metadata: RepresentationMetadata): void {
|
||||
for (const mode of (Object.keys(this.user) as (keyof PermissionSet)[])) {
|
||||
const modes = new Set([ ...Object.keys(this.user), ...Object.keys(this.everyone) ] as (keyof Permission)[]);
|
||||
for (const mode of modes) {
|
||||
const capitalizedMode = mode.charAt(0).toUpperCase() + mode.slice(1) as 'Read' | 'Write' | 'Append' | 'Control';
|
||||
if (this.user[mode]) {
|
||||
metadata.add(AUTH.terms.userMode, ACL.terms[capitalizedMode]);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import type { Quad, Term } from 'n3';
|
||||
import { Store } from 'n3';
|
||||
import { CredentialGroup } from '../authentication/Credentials';
|
||||
import type { Credential, CredentialSet } from '../authentication/Credentials';
|
||||
import type { AuxiliaryIdentifierStrategy } from '../ldp/auxiliary/AuxiliaryIdentifierStrategy';
|
||||
import type { PermissionSet } from '../ldp/permissions/PermissionSet';
|
||||
import { AccessMode } from '../ldp/permissions/PermissionSet';
|
||||
import type { Permission, PermissionSet } from '../ldp/permissions/Permissions';
|
||||
import { AccessMode } from '../ldp/permissions/Permissions';
|
||||
import type { Representation } from '../ldp/representation/Representation';
|
||||
import type { ResourceIdentifier } from '../ldp/representation/ResourceIdentifier';
|
||||
import { getLoggerFor } from '../logging/LogUtil';
|
||||
@@ -14,14 +15,12 @@ import { ForbiddenHttpError } from '../util/errors/ForbiddenHttpError';
|
||||
import { InternalServerError } from '../util/errors/InternalServerError';
|
||||
import { NotFoundHttpError } from '../util/errors/NotFoundHttpError';
|
||||
import { NotImplementedHttpError } from '../util/errors/NotImplementedHttpError';
|
||||
import { UnauthorizedHttpError } from '../util/errors/UnauthorizedHttpError';
|
||||
import type { IdentifierStrategy } from '../util/identifiers/IdentifierStrategy';
|
||||
import { readableToQuads } from '../util/StreamUtil';
|
||||
import { ACL, RDF } from '../util/Vocabularies';
|
||||
import type { AccessChecker } from './access-checkers/AccessChecker';
|
||||
import type { AuthorizerInput } from './Authorizer';
|
||||
import { Authorizer } from './Authorizer';
|
||||
import { WebAclAuthorization } from './WebAclAuthorization';
|
||||
import type { PermissionReaderInput } from './PermissionReader';
|
||||
import { PermissionReader } from './PermissionReader';
|
||||
|
||||
const modesMap: Record<string, AccessMode> = {
|
||||
[ACL.Read]: AccessMode.read,
|
||||
@@ -31,10 +30,10 @@ const modesMap: Record<string, AccessMode> = {
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Handles authorization according to the WAC specification.
|
||||
* Handles permissions according to the WAC specification.
|
||||
* Specific access checks are done by the provided {@link AccessChecker}.
|
||||
*/
|
||||
export class WebAclAuthorizer extends Authorizer {
|
||||
export class WebAclReader extends PermissionReader {
|
||||
protected readonly logger = getLoggerFor(this);
|
||||
|
||||
private readonly aclStrategy: AuxiliaryIdentifierStrategy;
|
||||
@@ -51,7 +50,7 @@ export class WebAclAuthorizer extends Authorizer {
|
||||
this.accessChecker = accessChecker;
|
||||
}
|
||||
|
||||
public async canHandle({ identifier }: AuthorizerInput): Promise<void> {
|
||||
public async canHandle({ identifier }: PermissionReaderInput): Promise<void> {
|
||||
if (this.aclStrategy.isAuxiliaryIdentifier(identifier)) {
|
||||
throw new NotImplementedHttpError('WebAclAuthorizer does not support permissions on auxiliary resources.');
|
||||
}
|
||||
@@ -62,30 +61,14 @@ export class WebAclAuthorizer extends Authorizer {
|
||||
* Will throw an error if this is not the case.
|
||||
* @param input - Relevant data needed to check if access can be granted.
|
||||
*/
|
||||
public async handle({ identifier, modes, credentials }: AuthorizerInput):
|
||||
Promise<WebAclAuthorization> {
|
||||
const modeString = [ ...modes ].join(',');
|
||||
this.logger.debug(`Checking if ${credentials.agent?.webId} has ${modeString} permissions for ${identifier.path}`);
|
||||
public async handle({ identifier, credentials }: PermissionReaderInput):
|
||||
Promise<PermissionSet> {
|
||||
// Determine the required access modes
|
||||
this.logger.debug(`Retrieving permissions of ${credentials.agent?.webId} for ${identifier.path}`);
|
||||
|
||||
// Determine the full authorization for the agent granted by the applicable ACL
|
||||
const acl = await this.getAclRecursive(identifier);
|
||||
const authorization = await this.createAuthorization(credentials, acl);
|
||||
|
||||
// Verify that the authorization allows all required modes
|
||||
const agent = credentials.agent ?? credentials.public ?? {};
|
||||
for (const mode of modes) {
|
||||
this.requirePermission(agent, authorization, mode);
|
||||
}
|
||||
this.logger.debug(`${agent.webId} has ${modeString} permissions for ${identifier.path}`);
|
||||
return authorization;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the agent is authenticated (logged in) or not (public/anonymous).
|
||||
* @param agent - Agent whose credentials will be checked.
|
||||
*/
|
||||
private isAuthenticated(agent: Credential): agent is ({ webId: string }) {
|
||||
return typeof agent.webId === 'string';
|
||||
return this.createPermissions(credentials, acl);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,18 +76,15 @@ export class WebAclAuthorizer extends Authorizer {
|
||||
* @param credentials - Credentials to check permissions for.
|
||||
* @param acl - Store containing all relevant authorization triples.
|
||||
*/
|
||||
private async createAuthorization(credentials: CredentialSet, acl: Store):
|
||||
Promise<WebAclAuthorization> {
|
||||
private async createPermissions(credentials: CredentialSet, acl: Store):
|
||||
Promise<PermissionSet> {
|
||||
const publicPermissions = await this.determinePermissions(acl, credentials.public);
|
||||
const agentPermissions = await this.determinePermissions(acl, credentials.agent);
|
||||
|
||||
// Agent at least has the public permissions
|
||||
// This can be relevant when no agent is provided
|
||||
for (const [ key, value ] of Object.entries(agentPermissions) as [keyof PermissionSet, boolean][]) {
|
||||
agentPermissions[key] = value || publicPermissions[key];
|
||||
}
|
||||
|
||||
return new WebAclAuthorization(agentPermissions, publicPermissions);
|
||||
return {
|
||||
[CredentialGroup.agent]: agentPermissions,
|
||||
[CredentialGroup.public]: publicPermissions,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -113,13 +93,8 @@ export class WebAclAuthorizer extends Authorizer {
|
||||
* @param acl - Store containing all relevant authorization triples.
|
||||
* @param credentials - Credentials to find the permissions for.
|
||||
*/
|
||||
private async determinePermissions(acl: Store, credentials?: Credential): Promise<PermissionSet> {
|
||||
const permissions = {
|
||||
read: false,
|
||||
write: false,
|
||||
append: false,
|
||||
control: false,
|
||||
};
|
||||
private async determinePermissions(acl: Store, credentials?: Credential): Promise<Permission> {
|
||||
const permissions: Permission = {};
|
||||
if (!credentials) {
|
||||
return permissions;
|
||||
}
|
||||
@@ -127,7 +102,7 @@ export class WebAclAuthorizer extends Authorizer {
|
||||
// Apply all ACL rules
|
||||
const aclRules = acl.getSubjects(RDF.type, ACL.Authorization, null);
|
||||
for (const rule of aclRules) {
|
||||
const hasAccess = await this.accessChecker.handleSafe({ acl, rule, credentials });
|
||||
const hasAccess = await this.accessChecker.handleSafe({ acl, rule, credential: credentials });
|
||||
if (hasAccess) {
|
||||
// Set all allowed modes to true
|
||||
const modes = acl.getObjects(rule, ACL.mode, null);
|
||||
@@ -147,29 +122,6 @@ export class WebAclAuthorizer extends Authorizer {
|
||||
return permissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the authorization grants the agent permission to use the given mode.
|
||||
* Throws a {@link ForbiddenHttpError} or {@link UnauthorizedHttpError} depending on the credentials
|
||||
* if access is not allowed.
|
||||
* @param agent - Agent that wants access.
|
||||
* @param authorization - An Authorization containing the permissions the agent has on the resource.
|
||||
* @param mode - Which mode is requested.
|
||||
*/
|
||||
private requirePermission(agent: Credential, authorization: WebAclAuthorization, mode: keyof PermissionSet): void {
|
||||
if (!authorization.user[mode]) {
|
||||
if (this.isAuthenticated(agent)) {
|
||||
this.logger.warn(`Agent ${agent.webId} has no ${mode} permissions`);
|
||||
throw new ForbiddenHttpError();
|
||||
} else {
|
||||
// Solid, §2.1: "When a client does not provide valid credentials when requesting a resource that requires it,
|
||||
// the data pod MUST send a response with a 401 status code (unless 404 is preferred for security reasons)."
|
||||
// https://solid.github.io/specification/protocol#http-server
|
||||
this.logger.warn(`Unauthenticated agent has no ${mode} permissions`);
|
||||
throw new UnauthorizedHttpError();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the ACL triples that are relevant for the given identifier.
|
||||
* These can either be from a corresponding ACL document or an ACL document higher up with defaults.
|
||||
@@ -19,7 +19,7 @@ export interface AccessCheckerArgs {
|
||||
rule: Term;
|
||||
|
||||
/**
|
||||
* Credentials of the entity that wants to use the resource.
|
||||
* Credential of the entity that wants to use the resource.
|
||||
*/
|
||||
credentials: Credential;
|
||||
credential: Credential;
|
||||
}
|
||||
|
||||
@@ -6,9 +6,9 @@ import { AccessChecker } from './AccessChecker';
|
||||
* Checks if the given WebID has been given access.
|
||||
*/
|
||||
export class AgentAccessChecker extends AccessChecker {
|
||||
public async handle({ acl, rule, credentials }: AccessCheckerArgs): Promise<boolean> {
|
||||
if (typeof credentials.webId === 'string') {
|
||||
return acl.countQuads(rule, ACL.terms.agent, credentials.webId, null) !== 0;
|
||||
public async handle({ acl, rule, credential }: AccessCheckerArgs): Promise<boolean> {
|
||||
if (typeof credential.webId === 'string') {
|
||||
return acl.countQuads(rule, ACL.terms.agent, credential.webId, null) !== 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -6,13 +6,13 @@ import { AccessChecker } from './AccessChecker';
|
||||
* Checks access based on the agent class.
|
||||
*/
|
||||
export class AgentClassAccessChecker extends AccessChecker {
|
||||
public async handle({ acl, rule, credentials }: AccessCheckerArgs): Promise<boolean> {
|
||||
public async handle({ acl, rule, credential }: AccessCheckerArgs): Promise<boolean> {
|
||||
// Check if unauthenticated agents have access
|
||||
if (acl.countQuads(rule, ACL.terms.agentClass, FOAF.terms.Agent, null) !== 0) {
|
||||
return true;
|
||||
}
|
||||
// Check if the agent is authenticated and if authenticated agents have access
|
||||
if (typeof credentials.webId === 'string') {
|
||||
if (typeof credential.webId === 'string') {
|
||||
return acl.countQuads(rule, ACL.terms.agentClass, ACL.terms.AuthenticatedAgent, null) !== 0;
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -32,9 +32,9 @@ export class AgentGroupAccessChecker extends AccessChecker {
|
||||
this.expiration = expiration * 1000;
|
||||
}
|
||||
|
||||
public async handle({ acl, rule, credentials }: AccessCheckerArgs): Promise<boolean> {
|
||||
if (typeof credentials.webId === 'string') {
|
||||
const { webId } = credentials;
|
||||
public async handle({ acl, rule, credential }: AccessCheckerArgs): Promise<boolean> {
|
||||
if (typeof credential.webId === 'string') {
|
||||
const { webId } = credential;
|
||||
const groups = acl.getObjects(rule, ACL.terms.agentGroup, null);
|
||||
|
||||
return await promiseSome(groups.map(async(group: Term): Promise<boolean> =>
|
||||
|
||||
Reference in New Issue
Block a user