open-consul/ui-v2/app/adapters/application.js
John Cowen 6ec6530e03
UI: [BUGFIX] Decode/encode urls (#5206)
In 858b05fc31 (diff-46ef88aa04507fb9b039344277531584)
we removed encoding values in pathnames as we thought they were
eventually being encoded by `ember`. It looks like this isn't the case.

Turns out sometimes they are encoded sometimes they aren't. It's complicated.
If at all possible refer to the PR https://github.com/hashicorp/consul/pull/5206.

It's related to the difference between `dynamic` routes and `wildcard` routes.

Partly related to this is a decision on whether we urlencode the slashes within service names or not. Whilst historically we haven't done this, we feel its a good time to change this behaviour, so we'll also be changing services to use dynamic routes instead of wildcard routes. So service links will then look like /ui/dc-1/services/application%2Fservice rather than /ui/dc-1/services/application/service

Here, we define our routes in a declarative format (for the moment at least JSON) outside of Router.map, and loop through this within Router.map to set all our routes using the standard this.route method. We essentially configure our Router from the outside. As this configuration is now done declaratively outside of Router.map we can also make this data available to href-to and paramsFor, allowing us to detect wildcard routes and therefore apply urlencoding/decoding.

Where I mention 'conditionally' below, this is detection is what is used for the decision.

We conditionally add url encoding to the `{{href-to}}` helper/addon. The
reasoning here is, if we are asking for a 'href/url' then whatever we
receive back should always be urlencoded. We've done this by reusing as much
code from the original `ember-href-to` addon as possible, after this
change every call to the `{{href-to}}` helper will be urlencoded.

As all links using `{{href-to}}` are now properly urlencoded. We also
need to decode them in the correct place 'on the other end', so..

We also override the default `Route.paramsFor` method to conditionally decode all
params before passing them to the `Route.model` hook.

Lastly (the revert), as we almost consistently use url params to
construct API calls, we make sure we re-encode any slugs that have been
passed in by the user/developer. The original API for the `createURL`
function was to allow you to pass values that didn't need encoding,
values that **did** need encoding, followed by query params (which again
require url encoding)

All in all this should make the entire ember app url encode/decode safe.
2019-01-23 13:46:59 +00:00

118 lines
4 KiB
JavaScript

import Adapter from 'ember-data/adapters/rest';
import { inject as service } from '@ember/service';
import URL from 'url';
import createURL from 'consul-ui/utils/createURL';
import { FOREIGN_KEY as DATACENTER_KEY } from 'consul-ui/models/dc';
export const REQUEST_CREATE = 'createRecord';
export const REQUEST_READ = 'queryRecord';
export const REQUEST_UPDATE = 'updateRecord';
export const REQUEST_DELETE = 'deleteRecord';
// export const REQUEST_READ_MULTIPLE = 'query';
export const DATACENTER_QUERY_PARAM = 'dc';
export default Adapter.extend({
namespace: 'v1',
repo: service('settings'),
headersForRequest: function(params) {
return {
...this.get('repo').findHeaders(),
...this._super(...arguments),
};
},
handleBooleanResponse: function(url, response, primary, slug) {
return {
// consider a check for a boolean, also for future me,
// response[slug] // this will forever be null, response should be boolean
[primary]: this.uidForURL(url /* response[slug]*/),
};
},
// could always consider an extra 'dc' arg on the end here?
handleSingleResponse: function(url, response, primary, slug, _dc) {
const dc =
typeof _dc !== 'undefined' ? _dc : url.searchParams.get(DATACENTER_QUERY_PARAM) || '';
return {
...response,
...{
[DATACENTER_KEY]: dc,
[primary]: this.uidForURL(url, response[slug]),
},
};
},
handleBatchResponse: function(url, response, primary, slug) {
const dc = url.searchParams.get(DATACENTER_QUERY_PARAM) || '';
return response.map((item, i, arr) => {
return this.handleSingleResponse(url, item, primary, slug, dc);
});
},
cleanQuery: function(_query) {
if (typeof _query.id !== 'undefined') {
delete _query.id;
}
const query = { ..._query };
delete _query[DATACENTER_QUERY_PARAM];
return query;
},
isUpdateRecord: function(url, method) {
return false;
},
isCreateRecord: function(url, method) {
return false;
},
isQueryRecord: function(url, method) {
// this is ONLY if ALL api's using it
// follow the 'last part of the url is the id' rule
const pathname = url.pathname
.split('/') // unslashify
// remove the last
.slice(0, -1)
// add and empty to ensure a trailing slash
.concat([''])
// slashify
.join('/');
// compare with empty id against empty id
return pathname === this.parseURL(this.urlForQueryRecord({ id: '' })).pathname;
},
getHost: function() {
return this.host || `${location.protocol}//${location.host}`;
},
slugFromURL: function(url, decode = decodeURIComponent) {
// follow the 'last part of the url is the id' rule
return decode(url.pathname.split('/').pop());
},
parseURL: function(str) {
return new URL(str, this.getHost());
},
uidForURL: function(url, _slug = '', hash = JSON.stringify) {
const dc = url.searchParams.get(DATACENTER_QUERY_PARAM) || '';
const slug = _slug === '' ? this.slugFromURL(url) : _slug;
if (dc.length < 1) {
throw new Error('Unable to create unique id, missing datacenter');
}
if (slug.length < 1) {
throw new Error('Unable to create unique id, missing slug');
}
// TODO: we could use a URL here? They are unique AND useful
// but probably slower to create?
return hash([dc, slug]);
},
// appendURL in turn calls createURL
// createURL ensures that all `parts` are URL encoded
// and all `query` values are URL encoded
// `this.buildURL()` with no arguments will give us `${host}/${namespace}`
// `path` is the user configurable 'urlsafe' string to append on `buildURL`
// `parts` is an array of possibly non 'urlsafe parts' to be encoded and
// appended onto the url
// `query` will populate the query string. Again the values of which will be
// url encoded
appendURL: function(path, parts = [], query = {}) {
// path can be a string or an array of parts that will be slash joined
return createURL([this.buildURL()].concat(path), parts, query);
},
});