Skip to content

Commit

Permalink
feat: add url validation to oembed api (#290)
Browse files Browse the repository at this point in the history
  • Loading branch information
smeijer authored Oct 31, 2020
1 parent f644db9 commit 082fd30
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
27 changes: 24 additions & 3 deletions src/lambda/oembed/oembed.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const URL = require('url');

function incorrectParams(error) {
return {
statusCode: 501, // oembed status // 422, // Unprocessable Entity
Expand All @@ -8,19 +10,23 @@ function incorrectParams(error) {

function getHostname(event, context) {
if (event.headers.host) {
return `http://${event.headers.host}`;
return `https://${event.headers.host}`;
}

const { netlify } = context.clientContext.custom || {};

return JSON.parse(Buffer.from(netlify, 'base64').toString('utf-8')).site_url;
}

const allowedPathsRegexp = new RegExp(/^\/(gist|embed)\/.*/);

function handler(event, context, callback) {
const host = getHostname(event, context);

const params = event.queryStringParameters;
const { format, referrer, maxwidth = 900, maxheight = 450 } = params;

if (params.format === 'xml') {
if (format && format !== 'json') {
return callback(
null,
incorrectParams('unsupported format, only json is supported'),
Expand All @@ -34,7 +40,22 @@ function handler(event, context, callback) {
);
}

const { url, referrer, maxwidth = 900, maxheight = 450 } = params;
const { hostname, pathname } = URL.parse(params.url);

// verify if the url is supported, basically we only allow localhost if we're
// running at localhost, and testing-playground.com as host. And either no
// path or /gist and /embed paths.
if (
(!host.includes(hostname) && hostname !== 'testing-playground.com') ||
(pathname && !allowedPathsRegexp.test(pathname))
) {
return callback(null, incorrectParams('unsupported url provided :/'));
}

// map /gist urls to /embed
const url = pathname.startsWith('/gist/')
? params.url.replace('/gist/', '/embed/')
: params.url;

callback(null, {
statusCode: 200,
Expand Down
7 changes: 2 additions & 5 deletions src/lambda/server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,8 @@ function handler(event, context, callback) {
const host = getHostname(event, context);

const embedPath = event.path.replace('/gist/', '/embed/');
const frameSrc = `${host}${embedPath}?${queryString.stringify({
panes,
markup,
query,
})}`;
const frameSearch = queryString.stringify({ panes, markup, query });
const frameSrc = host + embedPath + (frameSearch ? `?${frameSearch}` : '');

const oembedSearch = queryString.stringify({ url: frameSrc });

Expand Down

0 comments on commit 082fd30

Please sign in to comment.