Repository: solid/community-server
Pull request #549 (2021-01-26 09:06:33)

Add MS-Author-Via header
Closes https://github.com/solid/community-server/issues/539


Patch:
diff --git a/config/presets/ldp/response-writer.json b/config/presets/ldp/response-writer.json
index 71bb9f175..3a474dd16 100644
--- a/config/presets/ldp/response-writer.json
+++ b/config/presets/ldp/response-writer.json
@@ -5,16 +5,29 @@
       "@id": "urn:solid-server:default:MetadataSerializer",
       "@type": "SequenceHandler",
       "SequenceHandler:_handlers": [
+        {
+          "@type": "ConstantMetadataWriter",
+          "ConstantMetadataWriter:_headers": [
+            {
+              "ConstantMetadataWriter:_headers_key": "Accept-Patch",
+              "ConstantMetadataWriter:_headers_value": "application/sparql-update"
+            },
+            {
+              "ConstantMetadataWriter:_headers_key": "MS-Author-Via",
+              "ConstantMetadataWriter:_headers_value": "SPARQL"
+            }
+          ]
+        },
         {
           "@type": "MappedMetadataWriter",
           "MappedMetadataWriter:_headerMap": [
             {
               "MappedMetadataWriter:_headerMap_key": "http://www.w3.org/ns/ma-ont#format",
-              "MappedMetadataWriter:_headerMap_value": "content-type"
+              "MappedMetadataWriter:_headerMap_value": "Content-Type"
             },
             {
               "MappedMetadataWriter:_headerMap_key": "urn:solid:http:location",
-              "MappedMetadataWriter:_headerMap_value": "location"
+              "MappedMetadataWriter:_headerMap_value": "Location"
             }
           ]
         },
diff --git a/config/presets/middleware.json b/config/presets/middleware.json
index e1aa24a0e..6aa2c9be3 100644
--- a/config/presets/middleware.json
+++ b/config/presets/middleware.json
@@ -18,7 +18,9 @@
           ],
           "CorsHandler:_options_credentials": true,
           "CorsHandler:_options_exposedHeaders": [
+            "Accept-Patch",
             "Location",
+            "MS-Author-Via",
             "Updates-Via"
           ]
         },
diff --git a/src/index.ts b/src/index.ts
index 6a4c5d7e7..3701496b7 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -24,6 +24,7 @@ export * from './init/ServerInitializer';
 
 // LDP/HTTP/Metadata
 export * from './ldp/http/metadata/BasicMetadataExtractor';
+export * from './ldp/http/metadata/ConstantMetadataWriter';
 export * from './ldp/http/metadata/ContentTypeParser';
 export * from './ldp/http/metadata/LinkRelMetadataWriter';
 export * from './ldp/http/metadata/LinkTypeParser';
diff --git a/src/ldp/http/metadata/ConstantMetadataWriter.ts b/src/ldp/http/metadata/ConstantMetadataWriter.ts
new file mode 100644
index 000000000..58ceebc7d
--- /dev/null
+++ b/src/ldp/http/metadata/ConstantMetadataWriter.ts
@@ -0,0 +1,21 @@
+import type { HttpResponse } from '../../../server/HttpResponse';
+import { addHeader } from '../../../util/HeaderUtil';
+import { MetadataWriter } from './MetadataWriter';
+
+/**
+ * A {@link MetadataWriter} that takes a constant map of header names and values.
+ */
+export class ConstantMetadataWriter extends MetadataWriter {
+  private readonly headers: [string, string][];
+
+  public constructor(headers: Record<string, string>) {
+    super();
+    this.headers = Object.entries(headers);
+  }
+
+  public async handle({ response }: { response: HttpResponse }): Promise<void> {
+    for (const [ key, value ] of this.headers) {
+      addHeader(response, key, value);
+    }
+  }
+}
diff --git a/src/ldp/http/metadata/LinkRelMetadataWriter.ts b/src/ldp/http/metadata/LinkRelMetadataWriter.ts
index e0d590616..fc0ec7658 100644
--- a/src/ldp/http/metadata/LinkRelMetadataWriter.ts
+++ b/src/ldp/http/metadata/LinkRelMetadataWriter.ts
@@ -24,7 +24,7 @@ export class LinkRelMetadataWriter extends MetadataWriter {
       const values = input.metadata.getAll(key).map((term): string => `<${term.value}>; rel="${this.linkRelMap[key]}"`);
       if (values.length > 0) {
         this.logger.debug(`Adding Link header ${values}`);
-        addHeader(input.response, 'link', values);
+        addHeader(input.response, 'Link', values);
       }
     }
   }
diff --git a/src/ldp/http/metadata/MappedMetadataWriter.ts b/src/ldp/http/metadata/MappedMetadataWriter.ts
index af4efb84a..c76e82ed6 100644
--- a/src/ldp/http/metadata/MappedMetadataWriter.ts
+++ b/src/ldp/http/metadata/MappedMetadataWriter.ts
@@ -8,18 +8,18 @@ import { MetadataWriter } from './MetadataWriter';
  * The header value(s) will be the same as the corresponding object value(s).
  */
 export class MappedMetadataWriter extends MetadataWriter {
-  private readonly headerMap: Record<string, string>;
+  private readonly headerMap: [string, string][];
 
   public constructor(headerMap: Record<string, string>) {
     super();
-    this.headerMap = headerMap;
+    this.headerMap = Object.entries(headerMap);
   }
 
   public async handle(input: { response: HttpResponse; metadata: RepresentationMetadata }): Promise<void> {
-    for (const key of Object.keys(this.headerMap)) {
-      const values = input.metadata.getAll(key).map((term): string => term.value);
-      if (values.length > 0) {
-        addHeader(input.response, this.headerMap[key], values);
+    for (const [ predicate, header ] of this.headerMap) {
+      const terms = input.metadata.getAll(predicate);
+      if (terms.length > 0) {
+        addHeader(input.response, header, terms.map((term): string => term.value));
       }
     }
   }
diff --git a/src/server/middleware/WebSocketAdvertiser.ts b/src/server/middleware/WebSocketAdvertiser.ts
index c1fa4e1fb..aa8bc470c 100644
--- a/src/server/middleware/WebSocketAdvertiser.ts
+++ b/src/server/middleware/WebSocketAdvertiser.ts
@@ -16,6 +16,6 @@ export class WebSocketAdvertiser extends HttpHandler {
   }
 
   public async handle({ response }: { response: HttpResponse }): Promise<void> {
-    addHeader(response, 'updates-via', this.socketUrl);
+    addHeader(response, 'Updates-Via', this.socketUrl);
   }
 }


Test patch:
diff --git a/test/integration/LdpHandlerWithoutAuth.test.ts b/test/integration/LdpHandlerWithoutAuth.test.ts
index f8cf0b109..492f7ac67 100644
--- a/test/integration/LdpHandlerWithoutAuth.test.ts
+++ b/test/integration/LdpHandlerWithoutAuth.test.ts
@@ -81,6 +81,8 @@ describe.each(stores)('An LDP handler without auth using %s', (name, { storeUrn,
     expect(response.statusCode).toBe(200);
     expect(response._getBuffer().toString()).toContain('TESTFILE0');
     expect(response.getHeaders().link).toBe(`<${LDP.Resource}>; rel="type"`);
+    expect(response.getHeaders()['accept-patch']).toBe('application/sparql-update');
+    expect(response.getHeaders()['ms-author-via']).toBe('SPARQL');
 
     // DELETE
     await resourceHelper.deleteResource(id);
diff --git a/test/integration/Middleware.test.ts b/test/integration/Middleware.test.ts
index ad73836ad..323260043 100644
--- a/test/integration/Middleware.test.ts
+++ b/test/integration/Middleware.test.ts
@@ -86,12 +86,30 @@ describe('An Express server with middleware', (): void => {
     expect(res.header).toEqual(expect.objectContaining({ 'access-control-allow-origin': 'test.com' }));
   });
 
+  it('exposes the Accept-Patch header via CORS.', async(): Promise<void> => {
+    const res = await request(server).get('/').expect(200);
+    const exposed = res.header['access-control-expose-headers'];
+    expect(exposed.split(/\s*,\s*/u)).toContain('Accept-Patch');
+  });
+
   it('exposes the Location header via CORS.', async(): Promise<void> => {
     const res = await request(server).get('/').expect(200);
     const exposed = res.header['access-control-expose-headers'];
     expect(exposed.split(/\s*,\s*/u)).toContain('Location');
   });
 
+  it('exposes the MS-Author-Via header via CORS.', async(): Promise<void> => {
+    const res = await request(server).get('/').expect(200);
+    const exposed = res.header['access-control-expose-headers'];
+    expect(exposed.split(/\s*,\s*/u)).toContain('MS-Author-Via');
+  });
+
+  it('exposes the Updates-Via header via CORS.', async(): Promise<void> => {
+    const res = await request(server).get('/').expect(200);
+    const exposed = res.header['access-control-expose-headers'];
+    expect(exposed.split(/\s*,\s*/u)).toContain('Updates-Via');
+  });
+
   it('sends incoming requests to the handler.', async(): Promise<void> => {
     const response = request(server).get('/').set('Host', 'test.com');
     expect(response).toBeDefined();
diff --git a/test/unit/ldp/http/metadata/ConstantMetadataWriter.test.ts b/test/unit/ldp/http/metadata/ConstantMetadataWriter.test.ts
new file mode 100644
index 000000000..2323b6791
--- /dev/null
+++ b/test/unit/ldp/http/metadata/ConstantMetadataWriter.test.ts
@@ -0,0 +1,23 @@
+import { createResponse } from 'node-mocks-http';
+import { ConstantMetadataWriter } from '../../../../../src/ldp/http/metadata/ConstantMetadataWriter';
+
+describe('A ConstantMetadataWriter', (): void => {
+  const writer = new ConstantMetadataWriter({ 'custom-Header': 'X', other: 'Y' });
+
+  it('adds new headers.', async(): Promise<void> => {
+    const response = createResponse();
+
+    await expect(writer.handle({ response })).resolves.toBeUndefined();
+
+    expect(response.getHeaders()).toEqual({ 'custom-header': 'X', other: 'Y' });
+  });
+
+  it('extends existing headers.', async(): Promise<void> => {
+    const response = createResponse();
+    response.setHeader('Other', 'A');
+
+    await expect(writer.handle({ response })).resolves.toBeUndefined();
+
+    expect(response.getHeaders()).toEqual({ 'custom-header': 'X', other: [ 'A', 'Y' ]});
+  });
+});