Skip to content

Commit

Permalink
feat: Handle OPTIONS requests in OperationHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
joachimvh committed Mar 18, 2022
1 parent 87147e0 commit 61b9ad4
Show file tree
Hide file tree
Showing 10 changed files with 110 additions and 13 deletions.
1 change: 1 addition & 0 deletions config/http/middleware/handlers/cors.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"DELETE"
],
"options_credentials": true,
"options_preflightContinue": true,
"options_exposedHeaders": [
"Accept-Patch",
"ETag",
Expand Down
8 changes: 6 additions & 2 deletions config/ldp/handler/components/operation-handler.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@
"@id": "urn:solid-server:default:OperationHandler",
"@type": "WaterfallHandler",
"handlers": [
{
"@type": "OptionsOperationHandler",
"resourceSet": { "@id": "urn:solid-server:default:CachedResourceSet" }
},
{
"@type": "GetOperationHandler",
"store": { "@id": "urn:solid-server:default:ResourceStore" },
"store": { "@id": "urn:solid-server:default:ResourceStore" }
},
{
"@type": "PostOperationHandler",
Expand All @@ -23,7 +27,7 @@
},
{
"@type": "HeadOperationHandler",
"store": { "@id": "urn:solid-server:default:ResourceStore" },
"store": { "@id": "urn:solid-server:default:ResourceStore" }
},
{
"@type": "PatchOperationHandler",
Expand Down
2 changes: 1 addition & 1 deletion src/authorization/permissions/MethodModesExtractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { isContainerIdentifier } from '../../util/PathUtil';
import { ModesExtractor } from './ModesExtractor';
import { AccessMode } from './Permissions';

const READ_METHODS = new Set([ 'GET', 'HEAD' ]);
const READ_METHODS = new Set([ 'OPTIONS', 'GET', 'HEAD' ]);
const SUPPORTED_METHODS = new Set([ ...READ_METHODS, 'PUT', 'POST', 'DELETE' ]);

/**
Expand Down
36 changes: 36 additions & 0 deletions src/http/ldp/OptionsOperationHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { ResourceSet } from '../../storage/ResourceSet';
import { NotFoundHttpError } from '../../util/errors/NotFoundHttpError';
import { NotImplementedHttpError } from '../../util/errors/NotImplementedHttpError';
import { NoContentResponseDescription } from '../output/response/NoContentResponseDescription';
import type { ResponseDescription } from '../output/response/ResponseDescription';
import type { OperationHandlerInput } from './OperationHandler';
import { OperationHandler } from './OperationHandler';

/**
* Handles OPTIONS {@link Operation}s by always returning a 204.
*/
export class OptionsOperationHandler extends OperationHandler {
private readonly resourceSet: ResourceSet;

/**
* Uses a {@link ResourceSet} to determine the existence of the target resource which impacts the response code.
* @param resourceSet - {@link ResourceSet} that knows if the target resource exists or not.
*/
public constructor(resourceSet: ResourceSet) {
super();
this.resourceSet = resourceSet;
}

public async canHandle({ operation }: OperationHandlerInput): Promise<void> {
if (operation.method !== 'OPTIONS') {
throw new NotImplementedHttpError('This handler only supports OPTIONS operations');
}
}

public async handle({ operation }: OperationHandlerInput): Promise<ResponseDescription> {
if (!await this.resourceSet.hasResource(operation.target)) {
throw new NotFoundHttpError();
}
return new NoContentResponseDescription();
}
}
10 changes: 10 additions & 0 deletions src/http/output/response/NoContentResponseDescription.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ResponseDescription } from './ResponseDescription';

/**
* Corresponds to a 204 response.
*/
export class NoContentResponseDescription extends ResponseDescription {
public constructor() {
super(204);
}
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export * from './http/ldp/DeleteOperationHandler';
export * from './http/ldp/GetOperationHandler';
export * from './http/ldp/HeadOperationHandler';
export * from './http/ldp/OperationHandler';
export * from './http/ldp/OptionsOperationHandler';
export * from './http/ldp/PatchOperationHandler';
export * from './http/ldp/PostOperationHandler';
export * from './http/ldp/PutOperationHandler';
Expand All @@ -103,6 +104,7 @@ export * from './http/output/metadata/WwwAuthMetadataWriter';

// HTTP/Output/Response
export * from './http/output/response/CreatedResponseDescription';
export * from './http/output/response/NoContentResponseDescription';
export * from './http/output/response/OkResponseDescription';
export * from './http/output/response/ResetResponseDescription';
export * from './http/output/response/ResponseDescription';
Expand Down
11 changes: 6 additions & 5 deletions src/server/middleware/CorsHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@ interface SimpleCorsOptions {

/**
* Handler that sets CORS options on the response.
* In case of an OPTIONS request this handler will close the connection after adding its headers.
* In case of an OPTIONS request this handler will close the connection after adding its headers
* if `preflightContinue` is set to `false`.
*
* Solid, §7.1: "A data pod MUST implement the CORS protocol [FETCH] such that, to the extent possible,
* the browser allows Solid apps to send any request and combination of request headers to the data pod,
* and the Solid app can read any response and response headers received from the data pod."
* Full details: https://solid.github.io/specification/protocol#cors-server
* Solid, §8.1: "A server MUST implement the CORS protocol [FETCH] such that, to the extent possible,
* the browser allows Solid apps to send any request and combination of request headers to the server,
* and the Solid app can read any response and response headers received from the server."
* Full details: https://solidproject.org/TR/2021/protocol-20211217#cors-server
*/
export class CorsHandler extends HttpHandler {
private readonly corsHandler: (
Expand Down
2 changes: 1 addition & 1 deletion test/integration/Middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ describe('An http server with middleware', (): void => {
.set('Access-Control-Request-Headers', 'content-type')
.set('Access-Control-Request-Method', 'POST')
.set('Host', 'test.com')
.expect(204);
.expect(200);
expect(res.header).toEqual(expect.objectContaining({
'access-control-allow-origin': '*',
'access-control-allow-headers': 'content-type',
Expand Down
7 changes: 3 additions & 4 deletions test/integration/PermissionTable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,9 @@ const allModes = [ AM.read, AM.append, AM.create, AM.write, AM.delete ];
// For PUT/PATCH/DELETE we return 205 instead of 200/204
/* eslint-disable no-multi-spaces */
const table: [string, string, AM[], AM[] | undefined, string, string, number, number][] = [
// We currently handle OPTIONS before authorization
// [ 'OPTIONS', 'C/R', [], undefined, '', '', 401, 401 ],
// [ 'OPTIONS', 'C/R', [], [ AM.read ], '', '', 200, 404 ],
// [ 'OPTIONS', 'C/R', [ AM.read ], undefined, '', '', 200, 404 ],
[ 'OPTIONS', 'C/R', [], undefined, '', '', 401, 401 ],
[ 'OPTIONS', 'C/R', [], [ AM.read ], '', '', 204, 404 ],
[ 'OPTIONS', 'C/R', [ AM.read ], undefined, '', '', 204, 404 ],

[ 'HEAD', 'C/R', [], undefined, '', '', 401, 401 ],
[ 'HEAD', 'C/R', [], [ AM.read ], '', '', 200, 404 ],
Expand Down
44 changes: 44 additions & 0 deletions test/unit/http/ldp/OptionsOperationHandler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { OptionsOperationHandler } from '../../../../src/http/ldp/OptionsOperationHandler';
import type { Operation } from '../../../../src/http/Operation';
import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation';
import { BasicConditions } from '../../../../src/storage/BasicConditions';
import type { ResourceSet } from '../../../../src/storage/ResourceSet';
import { NotFoundHttpError } from '../../../../src/util/errors/NotFoundHttpError';
import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError';

describe('An OptionsOperationHandler', (): void => {
let operation: Operation;
const conditions = new BasicConditions({});
const preferences = {};
const body = new BasicRepresentation();
let resourceSet: jest.Mocked<ResourceSet>;
let handler: OptionsOperationHandler;

beforeEach(async(): Promise<void> => {
operation = { method: 'OPTIONS', target: { path: 'http://test.com/foo' }, preferences, conditions, body };
resourceSet = {
hasResource: jest.fn().mockResolvedValue(true),
};
handler = new OptionsOperationHandler(resourceSet);
});

it('only supports Options operations.', async(): Promise<void> => {
await expect(handler.canHandle({ operation })).resolves.toBeUndefined();
operation.method = 'GET';
await expect(handler.canHandle({ operation })).rejects.toThrow(NotImplementedHttpError);
operation.method = 'HEAD';
await expect(handler.canHandle({ operation })).rejects.toThrow(NotImplementedHttpError);
});

it('returns a 204 response.', async(): Promise<void> => {
const result = await handler.handle({ operation });
expect(result.statusCode).toBe(204);
expect(result.metadata).toBeUndefined();
expect(result.data).toBeUndefined();
});

it('returns a 404 if the target resource does not exist.', async(): Promise<void> => {
resourceSet.hasResource.mockResolvedValueOnce(false);
await expect(handler.handle({ operation })).rejects.toThrow(NotFoundHttpError);
});
});

0 comments on commit 61b9ad4

Please sign in to comment.