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:
Joachim Van Herwegen
2021-09-20 11:24:38 +02:00
parent e8dedf5c23
commit bf28c83ffa
50 changed files with 714 additions and 445 deletions

View File

@@ -89,7 +89,7 @@ describe.each(stores)('An LDP handler with auth using %s', (name, { storeConfig,
// GET
const response = await getResource(document);
await expect(response.text()).resolves.toBe('TESTDATA');
expect(response.headers.get('wac-allow')).toBe('user="read write append",public="read write append"');
expect(response.headers.get('wac-allow')).toBe('user="append read write",public="append read write"');
// DELETE
await deleteResource(document);

View File

@@ -0,0 +1,34 @@
import { CredentialGroup } from '../../../src/authentication/Credentials';
import { AllStaticReader } from '../../../src/authorization/AllStaticReader';
import type { Permission } from '../../../src/ldp/permissions/Permissions';
function getPermissions(allow: boolean): Permission {
return {
read: allow,
write: allow,
append: allow,
control: allow,
};
}
describe('An AllStaticReader', (): void => {
const credentials = { [CredentialGroup.agent]: {}, [CredentialGroup.public]: undefined };
const identifier = { path: 'http://test.com/resource' };
it('can handle everything.', async(): Promise<void> => {
const authorizer = new AllStaticReader(true);
await expect(authorizer.canHandle({} as any)).resolves.toBeUndefined();
});
it('always returns permissions matching the given allow parameter.', async(): Promise<void> => {
let authorizer = new AllStaticReader(true);
await expect(authorizer.handle({ credentials, identifier })).resolves.toEqual({
[CredentialGroup.agent]: getPermissions(true),
});
authorizer = new AllStaticReader(false);
await expect(authorizer.handle({ credentials, identifier })).resolves.toEqual({
[CredentialGroup.agent]: getPermissions(false),
});
});
});

View File

@@ -1,23 +0,0 @@
import { AllowAllAuthorizer } from '../../../src/authorization/AllowAllAuthorizer';
import type { PermissionSet } from '../../../src/ldp/permissions/PermissionSet';
describe('An AllowAllAuthorizer', (): void => {
const authorizer = new AllowAllAuthorizer();
const allowAll: PermissionSet = {
read: true,
write: true,
append: true,
control: true,
};
it('can handle everything.', async(): Promise<void> => {
await expect(authorizer.canHandle({} as any)).resolves.toBeUndefined();
});
it('always returns a full access Authorization.', async(): Promise<void> => {
await expect(authorizer.handle()).resolves.toEqual({
user: allowAll,
everyone: allowAll,
});
});
});

View File

@@ -1,27 +1,26 @@
import type { Authorizer } from '../../../src/authorization/Authorizer';
import { AuxiliaryAuthorizer } from '../../../src/authorization/AuxiliaryAuthorizer';
import { CredentialGroup } from '../../../src/authentication/Credentials';
import { AuxiliaryReader } from '../../../src/authorization/AuxiliaryReader';
import type { PermissionReader } from '../../../src/authorization/PermissionReader';
import type { AuxiliaryIdentifierStrategy } from '../../../src/ldp/auxiliary/AuxiliaryIdentifierStrategy';
import { AccessMode } from '../../../src/ldp/permissions/PermissionSet';
import type { PermissionSet } from '../../../src/ldp/permissions/Permissions';
import type { ResourceIdentifier } from '../../../src/ldp/representation/ResourceIdentifier';
import { NotImplementedHttpError } from '../../../src/util/errors/NotImplementedHttpError';
describe('An AuxiliaryAuthorizer', (): void => {
describe('An AuxiliaryReader', (): void => {
const suffix = '.dummy';
const credentials = {};
const associatedIdentifier = { path: 'http://test.com/foo' };
const auxiliaryIdentifier = { path: 'http://test.com/foo.dummy' };
let modes: Set<AccessMode>;
let source: Authorizer;
const permissionSet: PermissionSet = { [CredentialGroup.agent]: { read: true }};
let source: PermissionReader;
let strategy: AuxiliaryIdentifierStrategy;
let authorizer: AuxiliaryAuthorizer;
let reader: AuxiliaryReader;
beforeEach(async(): Promise<void> => {
modes = new Set([ AccessMode.read, AccessMode.write, AccessMode.append ]);
source = {
canHandle: jest.fn(),
handle: jest.fn(),
handleSafe: jest.fn(),
handle: jest.fn().mockResolvedValue(permissionSet),
handleSafe: jest.fn().mockResolvedValue(permissionSet),
};
strategy = {
@@ -29,43 +28,43 @@ describe('An AuxiliaryAuthorizer', (): void => {
getAssociatedIdentifier: jest.fn((identifier: ResourceIdentifier): ResourceIdentifier =>
({ path: identifier.path.slice(0, -suffix.length) })),
} as any;
authorizer = new AuxiliaryAuthorizer(source, strategy);
reader = new AuxiliaryReader(source, strategy);
});
it('can handle auxiliary resources if the source supports the associated resource.', async(): Promise<void> => {
await expect(authorizer.canHandle({ identifier: auxiliaryIdentifier, credentials, modes }))
await expect(reader.canHandle({ identifier: auxiliaryIdentifier, credentials }))
.resolves.toBeUndefined();
expect(source.canHandle).toHaveBeenLastCalledWith(
{ identifier: associatedIdentifier, credentials, modes },
{ identifier: associatedIdentifier, credentials },
);
await expect(authorizer.canHandle({ identifier: associatedIdentifier, credentials, modes }))
await expect(reader.canHandle({ identifier: associatedIdentifier, credentials }))
.rejects.toThrow(NotImplementedHttpError);
source.canHandle = jest.fn().mockRejectedValue(new Error('no source support'));
await expect(authorizer.canHandle({ identifier: auxiliaryIdentifier, credentials, modes }))
await expect(reader.canHandle({ identifier: auxiliaryIdentifier, credentials }))
.rejects.toThrow('no source support');
});
it('handles resources by sending the updated parameters to the source.', async(): Promise<void> => {
await expect(authorizer.handle({ identifier: auxiliaryIdentifier, credentials, modes }))
.resolves.toBeUndefined();
await expect(reader.handle({ identifier: auxiliaryIdentifier, credentials }))
.resolves.toBe(permissionSet);
expect(source.handle).toHaveBeenLastCalledWith(
{ identifier: associatedIdentifier, credentials, modes },
{ identifier: associatedIdentifier, credentials },
);
// Safety checks are not present when calling `handle`
await expect(authorizer.handle({ identifier: associatedIdentifier, credentials, modes }))
await expect(reader.handle({ identifier: associatedIdentifier, credentials }))
.rejects.toThrow(NotImplementedHttpError);
});
it('combines both checking and handling when calling handleSafe.', async(): Promise<void> => {
await expect(authorizer.handleSafe({ identifier: auxiliaryIdentifier, credentials, modes }))
.resolves.toBeUndefined();
await expect(reader.handleSafe({ identifier: auxiliaryIdentifier, credentials }))
.resolves.toBe(permissionSet);
expect(source.handleSafe).toHaveBeenLastCalledWith(
{ identifier: associatedIdentifier, credentials, modes },
{ identifier: associatedIdentifier, credentials },
);
await expect(authorizer.handleSafe({ identifier: associatedIdentifier, credentials, modes }))
await expect(reader.handleSafe({ identifier: associatedIdentifier, credentials }))
.rejects.toThrow(NotImplementedHttpError);
source.handleSafe = jest.fn().mockRejectedValue(new Error('no source support'));
await expect(authorizer.handleSafe({ identifier: auxiliaryIdentifier, credentials, modes }))
await expect(reader.handleSafe({ identifier: auxiliaryIdentifier, credentials }))
.rejects.toThrow('no source support');
});
});

View File

@@ -1,14 +0,0 @@
import { DenyAllAuthorizer } from '../../../src/authorization/DenyAllAuthorizer';
import { ForbiddenHttpError } from '../../../src/util/errors/ForbiddenHttpError';
describe('A DenyAllAuthorizer', (): void => {
const authorizer = new DenyAllAuthorizer();
it('can handle all requests.', async(): Promise<void> => {
await expect(authorizer.canHandle({} as any)).resolves.toBeUndefined();
});
it('rejects all requests.', async(): Promise<void> => {
await expect(authorizer.handle()).rejects.toThrow(ForbiddenHttpError);
});
});

View File

@@ -1,52 +0,0 @@
import type { Authorizer, AuthorizerInput } from '../../../src/authorization/Authorizer';
import { PathBasedAuthorizer } from '../../../src/authorization/PathBasedAuthorizer';
import { AccessMode } from '../../../src/ldp/permissions/PermissionSet';
import { NotImplementedHttpError } from '../../../src/util/errors/NotImplementedHttpError';
describe('A PathBasedAuthorizer', (): void => {
const baseUrl = 'http://test.com/foo/';
let input: AuthorizerInput;
let authorizers: jest.Mocked<Authorizer>[];
let authorizer: PathBasedAuthorizer;
beforeEach(async(): Promise<void> => {
input = {
identifier: { path: `${baseUrl}first` },
modes: new Set([ AccessMode.read ]),
credentials: {},
};
authorizers = [
{ canHandle: jest.fn(), handle: jest.fn() },
{ canHandle: jest.fn(), handle: jest.fn() },
] as any;
const paths = {
'/first': authorizers[0],
'/second': authorizers[1],
};
authorizer = new PathBasedAuthorizer(baseUrl, paths);
});
it('can only handle requests with a matching path.', async(): Promise<void> => {
input.identifier.path = 'http://wrongsite/';
await expect(authorizer.canHandle(input)).rejects.toThrow(NotImplementedHttpError);
input.identifier.path = `${baseUrl}third`;
await expect(authorizer.canHandle(input)).rejects.toThrow(NotImplementedHttpError);
input.identifier.path = `${baseUrl}first`;
await expect(authorizer.canHandle(input)).resolves.toBeUndefined();
input.identifier.path = `${baseUrl}second`;
await expect(authorizer.canHandle(input)).resolves.toBeUndefined();
});
it('can only handle requests supported by the stored authorizers.', async(): Promise<void> => {
await expect(authorizer.canHandle(input)).resolves.toBeUndefined();
authorizers[0].canHandle.mockRejectedValueOnce(new Error('not supported'));
await expect(authorizer.canHandle(input)).rejects.toThrow('not supported');
});
it('passes the handle requests to the matching authorizer.', async(): Promise<void> => {
await expect(authorizer.handle(input)).resolves.toBeUndefined();
expect(authorizers[0].handle).toHaveBeenCalledTimes(1);
expect(authorizers[0].handle).toHaveBeenLastCalledWith(input);
});
});

View File

@@ -0,0 +1,53 @@
import { CredentialGroup } from '../../../src/authentication/Credentials';
import { PathBasedReader } from '../../../src/authorization/PathBasedReader';
import type { PermissionReader, PermissionReaderInput } from '../../../src/authorization/PermissionReader';
import type { PermissionSet } from '../../../src/ldp/permissions/Permissions';
import { NotImplementedHttpError } from '../../../src/util/errors/NotImplementedHttpError';
describe('A PathBasedReader', (): void => {
const baseUrl = 'http://test.com/foo/';
const permissionSet: PermissionSet = { [CredentialGroup.agent]: { read: true }};
let input: PermissionReaderInput;
let readers: jest.Mocked<PermissionReader>[];
let reader: PathBasedReader;
beforeEach(async(): Promise<void> => {
input = {
identifier: { path: `${baseUrl}first` },
credentials: {},
};
readers = [
{ canHandle: jest.fn(), handle: jest.fn().mockResolvedValue(permissionSet) },
{ canHandle: jest.fn(), handle: jest.fn().mockResolvedValue(permissionSet) },
] as any;
const paths = {
'/first': readers[0],
'/second': readers[1],
};
reader = new PathBasedReader(baseUrl, paths);
});
it('can only handle requests with a matching path.', async(): Promise<void> => {
input.identifier.path = 'http://wrongsite/';
await expect(reader.canHandle(input)).rejects.toThrow(NotImplementedHttpError);
input.identifier.path = `${baseUrl}third`;
await expect(reader.canHandle(input)).rejects.toThrow(NotImplementedHttpError);
input.identifier.path = `${baseUrl}first`;
await expect(reader.canHandle(input)).resolves.toBeUndefined();
input.identifier.path = `${baseUrl}second`;
await expect(reader.canHandle(input)).resolves.toBeUndefined();
});
it('can only handle requests supported by the stored readers.', async(): Promise<void> => {
await expect(reader.canHandle(input)).resolves.toBeUndefined();
readers[0].canHandle.mockRejectedValueOnce(new Error('not supported'));
await expect(reader.canHandle(input)).rejects.toThrow('not supported');
});
it('passes the handle requests to the matching reader.', async(): Promise<void> => {
await expect(reader.handle(input)).resolves.toBe(permissionSet);
expect(readers[0].handle).toHaveBeenCalledTimes(1);
expect(readers[0].handle).toHaveBeenLastCalledWith(input);
});
});

View File

@@ -0,0 +1,71 @@
import { CredentialGroup } from '../../../src/authentication/Credentials';
import type { AuthorizerInput } from '../../../src/authorization/Authorizer';
import { PermissionBasedAuthorizer } from '../../../src/authorization/PermissionBasedAuthorizer';
import type { PermissionReader } from '../../../src/authorization/PermissionReader';
import { WebAclAuthorization } from '../../../src/authorization/WebAclAuthorization';
import { AccessMode } from '../../../src/ldp/permissions/Permissions';
import { ForbiddenHttpError } from '../../../src/util/errors/ForbiddenHttpError';
import { UnauthorizedHttpError } from '../../../src/util/errors/UnauthorizedHttpError';
describe('A PermissionBasedAuthorizer', (): void => {
let input: AuthorizerInput;
let authorization: WebAclAuthorization;
let reader: jest.Mocked<PermissionReader>;
let authorizer: PermissionBasedAuthorizer;
beforeEach(async(): Promise<void> => {
input = {
identifier: { path: 'http://test.com/foo' },
modes: new Set<AccessMode>(),
credentials: {},
};
authorization = new WebAclAuthorization({}, {});
reader = {
canHandle: jest.fn(),
handle: jest.fn().mockResolvedValue({}),
} as any;
authorizer = new PermissionBasedAuthorizer(reader);
});
it('can handle any input supported by its reader.', async(): Promise<void> => {
await expect(authorizer.canHandle(input)).resolves.toBeUndefined();
reader.canHandle.mockRejectedValue(new Error('bad request'));
await expect(authorizer.canHandle(input)).rejects.toThrow('bad request');
});
it('allows access if the permissions are matched by the reader output.', async(): Promise<void> => {
input.modes = new Set([ AccessMode.read, AccessMode.write ]);
reader.handle.mockResolvedValueOnce({
[CredentialGroup.public]: { read: true, write: false },
[CredentialGroup.agent]: { write: true },
});
Object.assign(authorization.everyone, { read: true, write: false });
Object.assign(authorization.user, { write: true });
await expect(authorizer.handle(input)).resolves.toEqual(authorization);
});
it('throws an UnauthorizedHttpError when an unauthenticated request has no access.', async(): Promise<void> => {
input.modes = new Set([ AccessMode.read, AccessMode.write ]);
reader.handle.mockResolvedValueOnce({
[CredentialGroup.public]: { read: true, write: false },
});
await expect(authorizer.handle(input)).rejects.toThrow(UnauthorizedHttpError);
});
it('throws a ForbiddenHttpError when an authenticated request has no access.', async(): Promise<void> => {
input.credentials = { agent: { webId: 'http://test.com/#me' }};
input.modes = new Set([ AccessMode.read, AccessMode.write ]);
reader.handle.mockResolvedValueOnce({
[CredentialGroup.public]: { read: true, write: false },
});
await expect(authorizer.handle(input)).rejects.toThrow(ForbiddenHttpError);
});
it('defaults to empty permissions for the Authorization.', async(): Promise<void> => {
await expect(authorizer.handle(input)).resolves.toEqual(authorization);
});
});

View File

@@ -0,0 +1,56 @@
import { CredentialGroup } from '../../../src/authentication/Credentials';
import type { PermissionReader, PermissionReaderInput } from '../../../src/authorization/PermissionReader';
import { UnionPermissionReader } from '../../../src/authorization/UnionPermissionReader';
describe('A UnionPermissionReader', (): void => {
const input: PermissionReaderInput = { credentials: {}, identifier: { path: 'http://test.com/foo' }};
let readers: jest.Mocked<PermissionReader>[];
let unionReader: UnionPermissionReader;
beforeEach(async(): Promise<void> => {
readers = [
{
canHandle: jest.fn(),
handle: jest.fn().mockResolvedValue({}),
} as any,
{
canHandle: jest.fn(),
handle: jest.fn().mockResolvedValue({}),
} as any,
];
unionReader = new UnionPermissionReader(readers);
});
it('only uses the results of readers that can handle the input.', async(): Promise<void> => {
readers[0].canHandle.mockRejectedValue(new Error('bad request'));
readers[0].handle.mockResolvedValue({ [CredentialGroup.agent]: { read: true }});
readers[1].handle.mockResolvedValue({ [CredentialGroup.agent]: { write: true }});
await expect(unionReader.handle(input)).resolves.toEqual({ [CredentialGroup.agent]: { write: true }});
});
it('combines results.', async(): Promise<void> => {
readers[0].handle.mockResolvedValue(
{ [CredentialGroup.agent]: { read: true }, [CredentialGroup.public]: undefined },
);
readers[1].handle.mockResolvedValue(
{ [CredentialGroup.agent]: { write: true }, [CredentialGroup.public]: { read: false }},
);
await expect(unionReader.handle(input)).resolves.toEqual({
[CredentialGroup.agent]: { read: true, write: true },
[CredentialGroup.public]: { read: false },
});
});
it('merges same fields using false > true > undefined.', async(): Promise<void> => {
readers[0].handle.mockResolvedValue(
{ [CredentialGroup.agent]: { read: true, write: false, append: undefined, control: true }},
);
readers[1].handle.mockResolvedValue(
{ [CredentialGroup.agent]: { read: false, write: true, append: true, control: true }},
);
await expect(unionReader.handle(input)).resolves.toEqual({
[CredentialGroup.agent]: { read: false, write: false, append: true, control: true },
});
});
});

View File

@@ -2,18 +2,17 @@ import { namedNode, quad } from '@rdfjs/data-model';
import { CredentialGroup } from '../../../src/authentication/Credentials';
import type { CredentialSet } from '../../../src/authentication/Credentials';
import type { AccessChecker } from '../../../src/authorization/access-checkers/AccessChecker';
import { WebAclAuthorization } from '../../../src/authorization/WebAclAuthorization';
import { WebAclAuthorizer } from '../../../src/authorization/WebAclAuthorizer';
import { WebAclReader } from '../../../src/authorization/WebAclReader';
import type { AuxiliaryIdentifierStrategy } from '../../../src/ldp/auxiliary/AuxiliaryIdentifierStrategy';
import { AccessMode } from '../../../src/ldp/permissions/PermissionSet';
import { BasicRepresentation } from '../../../src/ldp/representation/BasicRepresentation';
import type { Representation } from '../../../src/ldp/representation/Representation';
import type { ResourceIdentifier } from '../../../src/ldp/representation/ResourceIdentifier';
import type { ResourceStore } from '../../../src/storage/ResourceStore';
import { INTERNAL_QUADS } from '../../../src/util/ContentTypes';
import { ForbiddenHttpError } from '../../../src/util/errors/ForbiddenHttpError';
import { InternalServerError } from '../../../src/util/errors/InternalServerError';
import { NotFoundHttpError } from '../../../src/util/errors/NotFoundHttpError';
import { NotImplementedHttpError } from '../../../src/util/errors/NotImplementedHttpError';
import { UnauthorizedHttpError } from '../../../src/util/errors/UnauthorizedHttpError';
import { SingleRootIdentifierStrategy } from '../../../src/util/identifiers/SingleRootIdentifierStrategy';
import { guardedStreamFrom } from '../../../src/util/StreamUtil';
@@ -22,8 +21,8 @@ const nn = namedNode;
const acl = 'http://www.w3.org/ns/auth/acl#';
const rdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
describe('A WebAclAuthorizer', (): void => {
let authorizer: WebAclAuthorizer;
describe('A WebAclReader', (): void => {
let reader: WebAclReader;
const aclStrategy: AuxiliaryIdentifierStrategy = {
getAuxiliaryIdentifier: (id: ResourceIdentifier): ResourceIdentifier => ({ path: `${id.path}.acl` }),
isAuxiliaryIdentifier: (id: ResourceIdentifier): boolean => id.path.endsWith('.acl'),
@@ -31,138 +30,143 @@ describe('A WebAclAuthorizer', (): void => {
} as any;
let store: jest.Mocked<ResourceStore>;
const identifierStrategy = new SingleRootIdentifierStrategy('http://test.com/');
let modes: Set<AccessMode>;
let credentials: CredentialSet;
let identifier: ResourceIdentifier;
let authorization: WebAclAuthorization;
let accessChecker: jest.Mocked<AccessChecker>;
beforeEach(async(): Promise<void> => {
modes = new Set([ AccessMode.read, AccessMode.write ]);
credentials = { [CredentialGroup.public]: {}, [CredentialGroup.agent]: {}};
identifier = { path: 'http://test.com/foo' };
authorization = new WebAclAuthorization(
{
read: false,
append: false,
write: false,
control: false,
},
{
read: false,
append: false,
write: false,
control: false,
},
);
store = {
getRepresentation: jest.fn(),
getRepresentation: jest.fn().mockResolvedValue(new BasicRepresentation([
quad(nn('auth'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
], INTERNAL_QUADS)),
} as any;
accessChecker = {
handleSafe: jest.fn().mockResolvedValue(true),
} as any;
authorizer = new WebAclAuthorizer(aclStrategy, store, identifierStrategy, accessChecker);
reader = new WebAclReader(aclStrategy, store, identifierStrategy, accessChecker);
});
it('handles all non-acl inputs.', async(): Promise<void> => {
await expect(authorizer.canHandle({ identifier, credentials, modes })).resolves.toBeUndefined();
await expect(authorizer.canHandle({ identifier: aclStrategy.getAuxiliaryIdentifier(identifier) } as any))
await expect(reader.canHandle({ identifier, credentials })).resolves.toBeUndefined();
await expect(reader.canHandle({ identifier: aclStrategy.getAuxiliaryIdentifier(identifier) } as any))
.rejects.toThrow(NotImplementedHttpError);
});
it('returns undefined permissions for undefined credentials.', async(): Promise<void> => {
credentials = {};
await expect(reader.handle({ identifier, credentials })).resolves.toEqual({
[CredentialGroup.public]: {},
[CredentialGroup.agent]: {},
});
});
it('reads the accessTo value of the acl resource.', async(): Promise<void> => {
credentials.agent = { webId: 'http://test.com/user' };
store.getRepresentation.mockResolvedValue({ data: guardedStreamFrom([
quad(nn('auth'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth'), nn(`${acl}accessTo`), nn(identifier.path)),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}Read`)),
]) } as Representation);
await expect(reader.handle({ identifier, credentials })).resolves.toEqual({
[CredentialGroup.public]: { read: true },
[CredentialGroup.agent]: { read: true },
});
});
it('ignores accessTo fields pointing to different resources.', async(): Promise<void> => {
credentials.agent = { webId: 'http://test.com/user' };
store.getRepresentation.mockResolvedValue({ data: guardedStreamFrom([
quad(nn('auth'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth'), nn(`${acl}accessTo`), nn('somewhereElse')),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}Read`)),
]) } as Representation);
await expect(reader.handle({ identifier, credentials })).resolves.toEqual({
[CredentialGroup.public]: {},
[CredentialGroup.agent]: {},
});
});
it('handles all valid modes and ignores other ones.', async(): Promise<void> => {
credentials.agent = { webId: 'http://test.com/user' };
store.getRepresentation.mockResolvedValue({ data: guardedStreamFrom([
quad(nn('auth'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth'), nn(`${acl}accessTo`), nn(identifier.path)),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}Read`)),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}Write`)),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}fakeMode1`)),
]) } as Representation);
Object.assign(authorization.everyone, { read: true, write: true, append: true, control: false });
Object.assign(authorization.user, { read: true, write: true, append: true, control: false });
await expect(authorizer.handle({ identifier, modes, credentials })).resolves.toEqual(authorization);
await expect(reader.handle({ identifier, credentials })).resolves.toEqual({
[CredentialGroup.public]: { read: true },
[CredentialGroup.agent]: { read: true },
});
});
it('allows access if the acl file allows all agents.', async(): Promise<void> => {
store.getRepresentation.mockResolvedValue({ data: guardedStreamFrom([
quad(nn('auth'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth'), nn(`${acl}agentClass`), nn('http://xmlns.com/foaf/0.1/Agent')),
quad(nn('auth'), nn(`${acl}accessTo`), nn(identifier.path)),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}Read`)),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}Write`)),
]) } as Representation);
Object.assign(authorization.everyone, { read: true, write: true, append: true });
Object.assign(authorization.user, { read: true, write: true, append: true });
await expect(authorizer.handle({ identifier, modes, credentials })).resolves.toEqual(authorization);
});
it('allows access if there is a parent acl file allowing all agents.', async(): Promise<void> => {
it('reads the default value of a parent if there is no direct acl resource.', async(): Promise<void> => {
store.getRepresentation.mockImplementation(async(id: ResourceIdentifier): Promise<Representation> => {
if (id.path.endsWith('foo.acl')) {
throw new NotFoundHttpError();
}
return {
data: guardedStreamFrom([
quad(nn('auth'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth'), nn(`${acl}agentClass`), nn('http://xmlns.com/foaf/0.1/Agent')),
quad(nn('auth'), nn(`${acl}default`), nn(identifierStrategy.getParentContainer(identifier).path)),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}Read`)),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}Write`)),
]),
} as Representation;
return new BasicRepresentation([
quad(nn('auth'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth'), nn(`${acl}agentClass`), nn('http://xmlns.com/foaf/0.1/Agent')),
quad(nn('auth'), nn(`${acl}default`), nn(identifierStrategy.getParentContainer(identifier).path)),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}Read`)),
], INTERNAL_QUADS);
});
await expect(reader.handle({ identifier, credentials })).resolves.toEqual({
[CredentialGroup.public]: { read: true },
[CredentialGroup.agent]: { read: true },
});
Object.assign(authorization.everyone, { read: true, write: true, append: true });
Object.assign(authorization.user, { read: true, write: true, append: true });
await expect(authorizer.handle({ identifier, modes, credentials })).resolves.toEqual(authorization);
});
it('throws a ForbiddenHttpError if access is not granted and credentials have a WebID.', async(): Promise<void> => {
accessChecker.handleSafe.mockResolvedValue(false);
store.getRepresentation.mockResolvedValue({ data: guardedStreamFrom([
quad(nn('auth'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth'), nn(`${acl}accessTo`), nn(identifier.path)),
]) } as Representation);
credentials.agent = { webId: 'http://test.com/alice/profile/card#me' };
await expect(authorizer.handle({ identifier, modes, credentials })).rejects.toThrow(ForbiddenHttpError);
});
it('throws an UnauthorizedHttpError if access is not granted there are no credentials.', async(): Promise<void> => {
credentials = {};
accessChecker.handleSafe.mockResolvedValue(false);
store.getRepresentation.mockResolvedValue({ data: guardedStreamFrom([
quad(nn('auth'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth'), nn(`${acl}accessTo`), nn(identifier.path)),
]) } as Representation);
await expect(authorizer.handle({ identifier, modes, credentials })).rejects.toThrow(UnauthorizedHttpError);
});
it('re-throws ResourceStore errors as internal errors.', async(): Promise<void> => {
store.getRepresentation.mockRejectedValue(new Error('TEST!'));
const promise = authorizer.handle({ identifier, modes, credentials });
const promise = reader.handle({ identifier, credentials });
await expect(promise).rejects.toThrow(`Error reading ACL for ${identifier.path}: TEST!`);
await expect(promise).rejects.toThrow(InternalServerError);
});
it('errors if the root container has no corresponding acl document.', async(): Promise<void> => {
store.getRepresentation.mockRejectedValue(new NotFoundHttpError());
const promise = authorizer.handle({ identifier, modes, credentials });
const promise = reader.handle({ identifier, credentials });
await expect(promise).rejects.toThrow('No ACL document found for root container');
await expect(promise).rejects.toThrow(ForbiddenHttpError);
});
it('allows an agent to append if they have write access.', async(): Promise<void> => {
modes = new Set([ AccessMode.append ]);
store.getRepresentation.mockResolvedValue({ data: guardedStreamFrom([
quad(nn('auth'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth'), nn(`${acl}accessTo`), nn(identifier.path)),
quad(nn('auth'), nn(`${acl}mode`), nn(`${acl}Write`)),
]) } as Representation);
Object.assign(authorization.everyone, { write: true, append: true });
Object.assign(authorization.user, { write: true, append: true });
await expect(authorizer.handle({ identifier, modes, credentials })).resolves.toEqual(authorization);
await expect(reader.handle({ identifier, credentials })).resolves.toEqual({
[CredentialGroup.public]: { write: true, append: true },
[CredentialGroup.agent]: { write: true, append: true },
});
});
it('ignores rules where no access is granted.', async(): Promise<void> => {
credentials.agent = { webId: 'http://test.com/user' };
// CredentialGroup.public gets true on auth1, CredentialGroup.agent on auth2
accessChecker.handleSafe.mockImplementation(async({ rule, credential: cred }): Promise<boolean> =>
(rule.value === 'auth1') === !cred.webId);
store.getRepresentation.mockResolvedValue({ data: guardedStreamFrom([
quad(nn('auth1'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth1'), nn(`${acl}accessTo`), nn(identifier.path)),
quad(nn('auth1'), nn(`${acl}mode`), nn(`${acl}Read`)),
quad(nn('auth2'), nn(`${rdf}type`), nn(`${acl}Authorization`)),
quad(nn('auth2'), nn(`${acl}accessTo`), nn(identifier.path)),
quad(nn('auth2'), nn(`${acl}mode`), nn(`${acl}Control`)),
]) } as Representation);
await expect(reader.handle({ identifier, credentials })).resolves.toEqual({
[CredentialGroup.public]: { read: true },
[CredentialGroup.agent]: { control: true },
});
});
});

View File

@@ -16,17 +16,17 @@ describe('A AgentAccessChecker', (): void => {
});
it('returns true if a match is found for the given WebID.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('match'), credentials: { webId }};
const input: AccessCheckerArgs = { acl, rule: namedNode('match'), credential: { webId }};
await expect(checker.handle(input)).resolves.toBe(true);
});
it('returns false if no match is found.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('noMatch'), credentials: { webId }};
const input: AccessCheckerArgs = { acl, rule: namedNode('noMatch'), credential: { webId }};
await expect(checker.handle(input)).resolves.toBe(false);
});
it('returns false if the credentials contain no WebID.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('match'), credentials: {}};
const input: AccessCheckerArgs = { acl, rule: namedNode('match'), credential: {}};
await expect(checker.handle(input)).resolves.toBe(false);
});
});

View File

@@ -16,22 +16,22 @@ describe('An AgentClassAccessChecker', (): void => {
});
it('returns true if the rule contains foaf:agent as supported class.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('agentMatch'), credentials: {}};
const input: AccessCheckerArgs = { acl, rule: namedNode('agentMatch'), credential: {}};
await expect(checker.handle(input)).resolves.toBe(true);
});
it('returns true for authenticated users with an acl:AuthenticatedAgent rule.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('authenticatedMatch'), credentials: { webId }};
const input: AccessCheckerArgs = { acl, rule: namedNode('authenticatedMatch'), credential: { webId }};
await expect(checker.handle(input)).resolves.toBe(true);
});
it('returns false for unauthenticated users with an acl:AuthenticatedAgent rule.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('authenticatedMatch'), credentials: {}};
const input: AccessCheckerArgs = { acl, rule: namedNode('authenticatedMatch'), credential: {}};
await expect(checker.handle(input)).resolves.toBe(false);
});
it('returns false if no class rule is found.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('noMatch'), credentials: {}};
const input: AccessCheckerArgs = { acl, rule: namedNode('noMatch'), credential: {}};
await expect(checker.handle(input)).resolves.toBe(false);
});
});

View File

@@ -39,22 +39,22 @@ describe('An AgentGroupAccessChecker', (): void => {
});
it('returns true if the WebID is a valid group member.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('groupMatch'), credentials: { webId }};
const input: AccessCheckerArgs = { acl, rule: namedNode('groupMatch'), credential: { webId }};
await expect(checker.handle(input)).resolves.toBe(true);
});
it('returns false if the WebID is not a valid group member.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('noMatch'), credentials: { webId }};
const input: AccessCheckerArgs = { acl, rule: namedNode('noMatch'), credential: { webId }};
await expect(checker.handle(input)).resolves.toBe(false);
});
it('returns false if there are no WebID credentials.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('groupMatch'), credentials: {}};
const input: AccessCheckerArgs = { acl, rule: namedNode('groupMatch'), credential: {}};
await expect(checker.handle(input)).resolves.toBe(false);
});
it('caches fetched results.', async(): Promise<void> => {
const input: AccessCheckerArgs = { acl, rule: namedNode('groupMatch'), credentials: { webId }};
const input: AccessCheckerArgs = { acl, rule: namedNode('groupMatch'), credential: { webId }};
await expect(checker.handle(input)).resolves.toBe(true);
await expect(checker.handle(input)).resolves.toBe(true);
expect(fetchMock).toHaveBeenCalledTimes(1);

View File

@@ -5,7 +5,7 @@ import { AuthenticatedLdpHandler } from '../../../src/ldp/AuthenticatedLdpHandle
import { ResetResponseDescription } from '../../../src/ldp/http/response/ResetResponseDescription';
import type { ResponseDescription } from '../../../src/ldp/http/response/ResponseDescription';
import type { Operation } from '../../../src/ldp/operations/Operation';
import { AccessMode } from '../../../src/ldp/permissions/PermissionSet';
import { AccessMode } from '../../../src/ldp/permissions/Permissions';
import type { RepresentationPreferences } from '../../../src/ldp/representation/RepresentationPreferences';
import * as LogUtil from '../../../src/logging/LogUtil';
import type { HttpRequest } from '../../../src/server/HttpRequest';

View File

@@ -40,4 +40,15 @@ describe('A WacAllowMetadataWriter', (): void => {
'wac-allow': 'user="read write"',
});
});
it('applies public modes to user modes.', async(): Promise<void> => {
const metadata = new RepresentationMetadata({
[AUTH.publicMode]: [ ACL.terms.Read, ACL.terms.Write ],
});
await expect(writer.handle({ response, metadata })).resolves.toBeUndefined();
expect(response.getHeaders()).toEqual({
'wac-allow': 'user="read write",public="read write"',
});
});
});

View File

@@ -1,6 +1,6 @@
import type { AuxiliaryIdentifierStrategy } from '../../../../src/ldp/auxiliary/AuxiliaryIdentifierStrategy';
import { AclModesExtractor } from '../../../../src/ldp/permissions/AclModesExtractor';
import { AccessMode } from '../../../../src/ldp/permissions/PermissionSet';
import { AccessMode } from '../../../../src/ldp/permissions/Permissions';
import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError';
describe('An AclModesExtractor', (): void => {

View File

@@ -1,6 +1,6 @@
import type { Operation } from '../../../../src/ldp/operations/Operation';
import { MethodModesExtractor } from '../../../../src/ldp/permissions/MethodModesExtractor';
import { AccessMode } from '../../../../src/ldp/permissions/PermissionSet';
import { AccessMode } from '../../../../src/ldp/permissions/Permissions';
import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError';
describe('A MethodModesExtractor', (): void => {

View File

@@ -1,7 +1,7 @@
import { Factory } from 'sparqlalgebrajs';
import type { SparqlUpdatePatch } from '../../../../src/ldp/http/SparqlUpdatePatch';
import type { Operation } from '../../../../src/ldp/operations/Operation';
import { AccessMode } from '../../../../src/ldp/permissions/PermissionSet';
import { AccessMode } from '../../../../src/ldp/permissions/Permissions';
import { SparqlPatchModesExtractor } from '../../../../src/ldp/permissions/SparqlPatchModesExtractor';
import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError';

View File

@@ -1,4 +1,4 @@
import type { ResourceStore, PermissionSet } from '../../src/';
import type { ResourceStore, Permission } from '../../src/';
import { BasicRepresentation } from '../../src/';
export class AclHelper {
@@ -11,7 +11,7 @@ export class AclHelper {
public async setSimpleAcl(
resource: string,
options: {
permissions: Partial<PermissionSet>;
permissions: Partial<Permission>;
agentClass?: 'agent' | 'authenticated';
agent?: string;
accessTo?: boolean;
@@ -32,7 +32,7 @@ export class AclHelper {
];
for (const perm of [ 'Read', 'Append', 'Write', 'Control' ]) {
if (options.permissions[perm.toLowerCase() as keyof PermissionSet]) {
if (options.permissions[perm.toLowerCase() as keyof Permission]) {
acl.push(`;\n acl:mode acl:${perm}`);
}
}