cloudron-e2e-test/cloudron.js
Girish Ramakrishnan 5c2f3394a1 no callback needed
2017-04-15 09:20:47 -07:00

810 lines
31 KiB
JavaScript

#!/usr/bin/env node
'use strict';
var assert = require('assert'),
async = require('async'),
common = require('./common.js'),
debug = require('debug')('e2e:cloudron'),
dns = require('dns'),
ImapProbe = require('./imap-probe.js'),
querystring = require('querystring'),
net = require('net'),
nodemailer = require('nodemailer'),
once = require('once'),
request = require('superagent-sync'),
smtpTransport = require('nodemailer-smtp-transport'),
sleep = require('./shell.js').sleep,
superagent = require('superagent'),
tcpBomb = require('./tcpbomb.js'),
tls = require('tls'),
url = require('url'),
util = require('util');
exports = module.exports = Cloudron;
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
function Cloudron(box) {
this._box = box;
this._setDomain(box.domain);
this._credentials = {
password: null,
accessToken: null
};
}
Cloudron.prototype._setDomain = function (domain) {
this._isCustomDomain = domain === process.env.CUSTOM_DOMAIN || domain === process.env.EC2_SELFHOST_DOMAIN || domain === process.env.DO_SELFHOST_DOMAIN;
this._adminFqdn = this._isCustomDomain ? 'my.' + domain : 'my-' + domain;
this._origin = this._isCustomDomain ? 'https://my.' + domain : 'https://my-' + domain;
};
Cloudron.prototype.fqdn = function () {
return this._box.domain;
};
Cloudron.prototype.adminFqdn = function () {
return 'my' + (this._isCustomDomain ? '.' : '-') + this._box.domain;
};
Cloudron.prototype.appFqdn = function (location) {
return location + (this._isCustomDomain ? '.' : '-') + this._box.domain;
};
// get oauth token for logged in as certain user { username, password, email }
Cloudron.prototype.getOauthToken = function (user) {
var username = user.username;
var password = user.password;
////////// try to authorize without a session
var res = request.get(this._origin + '/api/v1/oauth/dialog/authorize').query({ redirect_uri: 'https://self', client_id: 'cid-webadmin', response_type: 'token', scope: 'root,profile,apps,roleAdmin' }).end();
var sessionCookies = res.headers['set-cookie']; // always an array
///////// should get redirected to login form with a script tag (to workaround chrome issue with redirects+cookies)
var redirectUrl = res.text.match(/window.location.href = "(.*)"/);
if (!redirectUrl) {
debug('Could not determine redirected url', res.text, res.headers);
assert(false);
}
var urlp = url.parse(redirectUrl[1]);
////////// get the login form (api/v1/session/login)
res = request.get(this._origin + urlp.pathname).set('cookie', sessionCookies[0]).query(urlp.query).end();
var csrfs = res.text.match(/name="_csrf" value="(.*)"/);
if (!csrfs) {
debug('Could not determine csrf', res.text, res.headers);
assert(false);
}
var csrf = csrfs[1];
sessionCookies = res.headers['set-cookie']; // always an array
assert.notStrictEqual(sessionCookies.length, 0);
////////// submit the login form with credentials
res = request.post(this._origin + urlp.pathname).set('cookie', sessionCookies[0]).send({ _csrf: csrf, username: username, password: password }).redirects(0).end();
if (res.statusCode !== 302) {
debug('Failed to submit the login for.', res.statusCode, res.text);
assert(false);
}
sessionCookies = res.headers['set-cookie']; // always an array
assert.notStrictEqual(sessionCookies.length, 0);
////////// authorize now with cookies
res = request.get(this._origin + '/api/v1/oauth/dialog/authorize').set('cookie', sessionCookies[0]).query({ redirect_uri: 'https://self', client_id: 'cid-webadmin', response_type: 'token', scope: 'root,profile,apps,roleAdmin' }).redirects(0).end();
common.verifyResponse(res, 'Unable to authorize');
assert.strictEqual(res.statusCode, 302);
sessionCookies = res.headers['set-cookie']; // always an array
assert.notStrictEqual(sessionCookies.length, 0);
////////// success will get redirect to callback?redirectURI=xx#access_token=yy&token_type=Bearer' (content is a <script>)
urlp = url.parse(res.headers.location);
res = request.get(this._origin + urlp.pathname).set('cookie', sessionCookies[0]).query(urlp.query).redirects(0).end();
assert.strictEqual(res.statusCode, 200);
////////// simulate what the the script of callback call does
var accessToken = querystring.parse(urlp.hash.substr(1)).access_token;
return accessToken;
};
// setup dns for selfhosters
Cloudron.prototype.setupDns = function (dnsConfig) {
var res = request.post('https://' + this._box.ip + '/api/v1/cloudron/dns_setup').send(dnsConfig).end();
common.verifyResponse2xx(res, 'Could not setup Cloudron dns');
for (var i = 0; i < 60; ++i) {
sleep(5);
res = request.get(this._origin + '/api/v1/cloudron/status').end();
common.verifyResponse2xx(res, 'Could not get Cloudron status');
if (res.body.adminFqdn) return;
}
};
// activate the box
Cloudron.prototype.activate = function (user) {
var setupToken = this._box.setupToken;
////////// activation
var res;
for (var i = 0; i < 60; ++i) {
sleep(20);
res = request.post(this._origin + '/api/v1/cloudron/activate').query({ setupToken: setupToken }).send(user).end();
if (res.statusCode === 201) break;
if (res.statusCode === 307) continue;
if (res.statusCode === 409) {
debug('Response error statusCode:%s error:%s body:%j', res.statusCode, res.error, res.body);
throw new Error('Cloudron already activated! This should not happen');
} else {
debug('Response error will retry. statusCode:%s error:%s body:%j', res.statusCode, res.error, res.body);
}
}
// final verification will fail if retries do not succeed
common.verifyResponse2xx(res, 'Could not activate the box');
res = request.get(this._origin + '/api/v1/cloudron/status').end();
common.verifyResponse2xx(res, 'Could not get Cloudron status');
assert.strictEqual(res.body.version, this._box.version);
};
Cloudron.prototype.waitForApp = function (appId, version) {
// wait for app to come up
process.stdout.write('Waiting for app to come up.');
var res;
for (var i = 0; i < 60; i++) {
sleep(30);
process.stdout.write('.');
res = request.get(this._origin + '/api/v1/apps/'+ appId).query({ access_token: this._credentials.accessToken }).end();
// if app still redirects, wait a bit
if (res.statusCode === 307) continue;
common.verifyResponse2xx(res, 'Could not query app status');
if (res.body.installationState === 'installed' && res.body.runState === 'running' && res.body.health === 'healthy') {
console.log();
break;
}
}
assert.strictEqual(res.body.installationState, 'installed');
assert.strictEqual(res.body.runState, 'running');
assert.strictEqual(res.body.runState, 'running');
if (version) assert.strictEqual(res.body.manifest.version, version);
return res.body;
};
Cloudron.prototype.waitForBox = function (byIp) {
process.stdout.write('Waiting for box.');
var res;
for (var i = 0; i < 60; i++) {
sleep(20);
res = request.get((byIp ? ('https://' + this._box.ip) : this._origin) + '/api/v1/cloudron/status').end();
if (res.statusCode === 200) {
console.log();
return;
}
process.stdout.write('.');
}
throw new Error('waitForBox failed');
};
Cloudron.prototype.setCredentials = function (password, accessToken) {
this._credentials = {
password: password,
accessToken: accessToken
};
};
Cloudron.prototype.installApp = function (location, manifestOrAppstoreId, portBindings) {
portBindings = portBindings || null; // null binds nothing
var version = typeof manifestOrAppstoreId === 'object' ? manifestOrAppstoreId.version : manifestOrAppstoreId.split('@')[1];
var data = {
manifest: typeof manifestOrAppstoreId === 'object' ? manifestOrAppstoreId : null,
appStoreId: typeof manifestOrAppstoreId === 'string' ? manifestOrAppstoreId : '',
location: location,
accessRestriction: null,
oauthProxy: false,
portBindings: portBindings
};
var res = request.post(this._origin + '/api/v1/apps/install')
.query({ access_token: this._credentials.accessToken })
.send(data)
.end();
common.verifyResponse2xx(res, 'Cannot install app');
debug('App installed at %s'.green, location);
var appId = res.body.id;
var app = this.waitForApp(appId, version);
debug('App is running'.green);
res = request.get('https://' + app.fqdn).end();
common.verifyResponse2xx(res, 'App is unreachable');
console.log('App is reachable'.green);
return appId;
};
Cloudron.prototype.configureApp = function (appId, newLocation, altDomain /* optional */, portBindings) {
portBindings = portBindings || null;
var data = { location: newLocation, accessRestriction: null, oauthProxy: false, password: this._credentials.password, portBindings: portBindings };
if (altDomain) data.altDomain = altDomain;
var res = request.post(this._origin + '/api/v1/apps/' + appId + '/configure').query({ access_token: this._credentials.accessToken }).send(data).end();
common.verifyResponse2xx(res, 'App could not be configured');
console.log('App moved to different location'.green);
var app = this.waitForApp(appId);
res = request.get('https://' + app.fqdn).end();
common.verifyResponse2xx(res, 'App is unreachable');
console.log('App is reachable'.green);
};
Cloudron.prototype.cloneApp = function (appId, newLocation, portBindings) {
portBindings = portBindings || null;
var backups = this.listAppBackups(appId);
console.log('Backups are ', backups);
var data = { location: newLocation, password: this._credentials.password, portBindings: portBindings, backupId: backups[0].id };
var res = request.post(this._origin + '/api/v1/apps/' + appId + '/clone').query({ access_token: this._credentials.accessToken }).send(data).end();
common.verifyResponse2xx(res, 'App could not be clone');
console.log('App cloned to different location'.green);
var app = this.waitForApp(res.body.id);
res = request.get('https://' + app.fqdn).end();
common.verifyResponse2xx(res, 'App is unreachable');
console.log('App is reachable'.green);
};
Cloudron.prototype.uninstallApp = function (appId) {
process.stdout.write('Uninstalling app');
var res = request.post(this._origin + '/api/v1/apps/' + appId + '/uninstall').query({ access_token: this._credentials.accessToken }).send({ password: this._credentials.password }).end();
common.verifyResponse2xx(res, 'Cannot uninstall app');
for (var i = 0; i < 60; i++) {
sleep(20);
process.stdout.write('.');
res = request.get(this._origin + '/api/v1/apps/'+ appId).query({ access_token: this._credentials.accessToken }).retry(0).end();
if (res.statusCode === 404) {
console.log();
debug('App is uninstalled'.green);
return;
}
}
assert(false, 'uninstallApp failed');
};
Cloudron.prototype.updateApp = function (appId, manifestOrAppstoreId) {
process.stdout.write('Trying to update');
var version = typeof manifestOrAppstoreId === 'object' ? manifestOrAppstoreId.version : manifestOrAppstoreId.split('@')[1];
var data = {
password: this._credentials.password,
manifest: typeof manifestOrAppstoreId === 'object' ? manifestOrAppstoreId : null,
appStoreId: typeof manifestOrAppstoreId === 'string' ? manifestOrAppstoreId : ''
};
var res = request.post(this._origin + '/api/v1/apps/' + appId + '/update')
.query({ access_token: this._credentials.accessToken })
.send(data)
.end();
common.verifyResponse2xx(res, 'Could not update');
console.log('Update started'.green);
var app = this.waitForApp(appId, version);
debug('App is running'.green);
res = request.get('https://' + app.fqdn).end();
common.verifyResponse2xx(res, 'App is unreachable');
console.log('App updated'.green);
};
Cloudron.prototype.restoreApp = function (appId, backup) {
process.stdout.write('Trying to restore to ' + JSON.stringify(backup));
var data = {
backupId: backup.id,
password: this._credentials.password
};
var res = request.post(this._origin + '/api/v1/apps/' + appId + '/restore')
.query({ access_token: this._credentials.accessToken })
.send(data)
.end();
common.verifyResponse2xx(res, 'Could not restore');
console.log('Restore started'.green);
var app = this.waitForApp(appId, backup.version);
debug('App is running'.green);
res = request.get('https://' + app.fqdn).end();
common.verifyResponse2xx(res, 'App is unreachable');
console.log('App restored'.green);
};
Cloudron.prototype.listAppBackups = function (appId) {
var res = request.get(this._origin + '/api/v1/apps/' + appId + '/backups').query({ access_token: this._credentials.accessToken }).end();
common.verifyResponse2xx(res, 'Could not list backups');
return res.body.backups;
};
Cloudron.prototype.update = function (toVersion) {
process.stdout.write('Trying to update');
var res;
for (var i = 0; i < 60; i++) {
sleep(20);
process.stdout.write('.');
res = request.post(this._origin + '/api/v1/cloudron/update').query({ access_token: this._credentials.accessToken }).send({ password: this._credentials.password }).end();
if (res.statusCode === 422) continue; // box has not seen the update yet
if (res.statusCode === 409) break; // update is in progress, lock was acquired
common.verifyResponse2xx(res, 'Could not update');
break;
}
console.log('Update started'.green);
this.waitForUpdate(toVersion);
};
Cloudron.prototype.waitForUpdate = function (toVersion) {
process.stdout.write('Waiting for update.');
var res;
for (var i = 0; i < 60; i++) {
sleep(30);
res = request.get(this._origin + '/api/v1/cloudron/status').end();
if (res.statusCode === 200 && res.body.version === toVersion) {
console.log();
break;
}
process.stdout.write('.');
}
assert.strictEqual(res.body.version, toVersion);
assert.strictEqual(res.body.activated, true);
console.log('Updated successfully'.green);
};
Cloudron.prototype.addUser = function (username, email) {
var res = request.post(this._origin + '/api/v1/users').query({ access_token: this._credentials.accessToken }).send({ username: username, email: email, invite: true }).end();
common.verifyResponse2xx(res, 'Could not add user');
return res.body;
};
Cloudron.prototype.setAliases = function (aliases) {
var res = request.get(this._origin + '/api/v1/profile').query({ access_token: this._credentials.accessToken }).end();
common.verifyResponse2xx(res, 'Could not get profile');
console.log('user id is ', res.body.id);
res = request.put(this._origin + '/api/v1/users/' + res.body.id + '/aliases')
.query({ access_token: this._credentials.accessToken })
.send({ aliases: aliases })
.end();
common.verifyResponse2xx(res, 'Could not set aliases');
return res.body;
};
Cloudron.prototype.resetPassword = function (resetToken, password) {
var res = request.get(this._origin + '/api/v1/session/password/reset.html').query({ reset_token: resetToken }).end();
common.verifyResponse2xx(res, 'Could not get password setup site');
var sessionCookies = res.headers['set-cookie']; // always an array
var csrf = res.text.match(/name="_csrf" value="(.*)"/)[1];
res = request.post(this._origin + '/api/v1/session/password/reset')
.set('cookie', sessionCookies[0])
.type('form').send({ _csrf: csrf, resetToken: resetToken, password: password, passwordRepeat: password }).end();
common.verifyResponse(res, 'Could not setup password for user');
assert.strictEqual(res.statusCode, 302);
};
Cloudron.prototype.backupApp = function (appId) {
var res = request.post(this._origin + '/api/v1/apps/' + appId + '/backup').query({ access_token: this._credentials.accessToken }).end();
common.verifyResponse2xx(res, 'Could not schedule a backup');
this.waitForApp(appId);
};
Cloudron.prototype.backup = function () {
var res = request.get(this._origin + '/api/v1/backups').query({ access_token: this._credentials.accessToken }).end();
common.verifyResponse2xx(res, 'Could not get backups');
var existingBackups = res.body.backups;
res = request.post(this._origin + '/api/v1/backups').query({ access_token: this._credentials.accessToken }).end();
common.verifyResponse2xx(res, 'Could not schedule backup');
for (var i = 0; i < 60; i++) {
sleep(20); // backup sometimes takes a while to start
res = request.get(this._origin + '/api/v1/cloudron/progress').end();
if (res.body.backup === null || res.body.backup.percent === 100) {
debug('backup done');
break;
}
debug('Backing up: %s %s', res.body.backup.percent, res.body.backup.message);
}
if (res.body.backup !== null && res.body.backup.percent !== 100) throw new Error('backup: timedout');
res = request.get(this._origin + '/api/v1/backups').query({ access_token: this._credentials.accessToken }).end();
common.verifyResponse2xx(res, 'Could not get backups');
var latestBackups = res.body.backups;
assert.strictEqual(latestBackups.length, existingBackups.length + 1);
return latestBackups[0]; // { creationTime, boxVersion, id, dependsOn }
};
Cloudron.prototype.reboot = function () {
var res = request.post(this._origin + '/api/v1/cloudron/reboot').query({ access_token: this._credentials.accessToken }).send({ }).end();
common.verifyResponse2xx(res, 'Box could not be rebooted');
this.waitForBox();
};
Cloudron.prototype.migrate = function (options) {
options.password = this._credentials.password;
var res = request.post(this._origin + '/api/v1/cloudron/migrate')
.query({ access_token: this._credentials.accessToken })
.send(options)
.end();
common.verifyResponse2xx(res, 'Box could not be migrated');
if (options.domain) this._setDomain(options.domain);
};
Cloudron.prototype.setEmailEnabled = function (enabled) {
var res = request
.post(this._origin + '/api/v1/settings/mail_config').query({ access_token: this._credentials.accessToken })
.send({ enabled: enabled })
.end();
common.verifyResponse2xx(res, 'Could not enable email');
sleep(60); // generously wait for the mail server to restart. it takes 10 seconds to stop it... and then there is DNS propagation
};
Cloudron.prototype.setCloudronName = function (name) {
var res = request
.post(this._origin + '/api/v1/settings/cloudron_name').query({ access_token: this._credentials.accessToken })
.send({ name: name})
.end();
common.verifyResponse2xx(res, 'Could not enable email');
};
Cloudron.prototype.checkTimeZone = function (tz) {
var res = request.get(this._origin + '/api/v1/settings/time_zone').query({ access_token: this._credentials.accessToken }).end();
common.verifyResponse2xx(res, 'Could not query timezone');
if (tz !== res.body.timeZone) throw new Error('timezone does not match. expecting: ' + tz + ' got ' + res.body.timeZone);
};
Cloudron.prototype.setAutoupdatePattern = function (pattern) {
var res = request.post(this._origin + '/api/v1/settings/autoupdate_pattern')
.query({ access_token: this._credentials.accessToken })
.send({ pattern: pattern })
.end();
common.verifyResponse2xx(res, 'Could not set autoupdate pattern');
};
Cloudron.prototype.checkA = function (callback) {
var expectedIp = this._box.ip;
dns.resolve4(this._box.domain, function (error, records) {
if (error) return callback(error);
if (records.length !== 1) return callback(new Error('Got ' + JSON.stringify(records) + ' A records. Expecting 1 length array'));
if (records[0] !== expectedIp) return callback(new Error('Bad A record. ' + records[0] + '. Expecting ' + expectedIp));
callback(null, records);
});
};
Cloudron.prototype._checkGraphs = function (targets, from) {
var params = {
target: targets.length === 1 ? targets[0] : targets,
format: 'json',
from: from,
access_token: this._credentials.accessToken
};
var res;
for (var i = 0; i < 60; i++) {
sleep(20);
res = request.get(this._origin + '/api/v1/cloudron/graphs').query(params).end();
process.stdout.write('.');
if (res.statusCode !== 200) continue;
if (!util.isArray(res.body) || res.body.length !== targets.length) continue;
for (var j = 0; j < res.body.length; j++) {
if (res.body[j].datapoints.length === 0) break; // no data
console.log();
console.log(res.body);
return; // success
}
}
assert(false, 'Graphs are not populated');
};
Cloudron.prototype.checkAppGraphs = function (appId) {
var timePeriod = 2 * 60; // in minutes
var timeBucketSize = 30; // in minutes
var target = 'summarize(collectd.localhost.table-' + appId + '-memory.gauge-rss, "' + timeBucketSize + 'min", "avg")';
this._checkGraphs([target], '-' + timePeriod + 'min');
};
Cloudron.prototype.checkDiskGraphs = function () {
var targets = [
'averageSeries(collectd.localhost.df-loop*.df_complex-free)',
'averageSeries(collectd.localhost.df-loop*.df_complex-reserved)',
'averageSeries(collectd.localhost.df-loop*.df_complex-used)'
];
this._checkGraphs(targets, '-1min');
};
Cloudron.prototype.checkSPF = function (callback) {
var that = this;
dns.resolveTxt(this._box.domain, function (error, records) {
if (error) return callback(error);
if (records.length !== 1 || records[0].length !== 1) return callback(new Error('Got ' + JSON.stringify(records) + ' TXT records. Expecting 1 length 2d array'));
if (records[0][0].search(new RegExp('^v=spf1 a:' + that._adminFqdn + ' ~all$')) !== 0) return callback(new Error('Bad SPF record. ' + records[0][0]));
callback(null, records);
});
};
Cloudron.prototype.checkMX = function (callback) {
var that = this;
dns.resolveMx(this._box.domain, function (error, records) {
if (error) return callback(error);
if (records.length !== 1) return callback(new Error('Got ' + JSON.stringify(records) + ' MX records. Expecting 1 length array'));
if (records[0].exchange !== that._adminFqdn) return callback(new Error('Bad MX record. ' + JSON.stringify(records[0])));
callback(null, records);
});
};
Cloudron.prototype.checkDKIM = function (callback) {
dns.resolveTxt('cloudron._domainkey.' + this._box.domain, function (error, records) {
if (error) return callback(error);
if (records.length !== 1 || records[0].length !== 1) return callback(new Error('Got ' + JSON.stringify(records) + ' TXT records. Expecting 1 length 2d array'));
// node removes the quotes or maybe this is why a 2d-array?
if (records[0][0].search(/^v=DKIM1; t=s; p=.*$/) !== 0) return callback(new Error('Bad DKIM record. ' + records[0][0]));
callback(null, records);
});
};
Cloudron.prototype.checkDMARC = function (callback) {
dns.resolveTxt('_dmarc.' + this._box.domain, function (error, records) {
if (error) return callback(error);
if (records.length !== 1 || records[0].length !== 1) return callback(new Error('Got ' + JSON.stringify(records) + ' TXT records. Expecting 1 length 2d array'));
// node removes the quotes or maybe this is why a 2d-array?
if (records[0][0].search(/^v=DMARC1; p=reject; pct=100$/) !== 0) return callback(new Error('Bad DMARC record. ' + records[0][0]));
callback(null, records);
});
};
Cloudron.prototype.populateAddons = function (domain) {
var res = request.post('https://' + domain + '/populate_addons').end();
assert.strictEqual(res.statusCode, 200);
for (var addon in res.body) {
assert.strictEqual(res.body[addon], 'OK');
}
};
Cloudron.prototype.checkAddons = function (domain, owner) {
var lastError;
// try many times because the scheduler takes sometime to run
for (var i = 0; i < 100; i++) {
var res = request.post('https://' + domain + '/check_addons').query({ username: owner.username, password: owner.password }).end();
try {
assert.strictEqual(res.statusCode, 200);
for (var addon in res.body) {
assert.strictEqual(res.body[addon], 'OK');
}
return;
} catch (e) {
lastError = e;
console.error(e);
console.log('Attempt %s failed. Trying again in 10 seconds', i);
sleep(10);
}
}
throw lastError;
};
Cloudron.prototype.checkAppRateLimit = function (domain) {
var res = request.post('https://' + domain + '/ratelimit').end();
assert.strictEqual(res.statusCode, 200);
for (var addon in res.body) {
assert.strictEqual(res.body[addon], 'OK');
}
};
Cloudron.prototype.checkDnsbl = function (domain) {
var res = request.post('https://' + domain + '/check_dnsbl').end();
common.verifyResponse2xx(res, 'Could not query dnsbl');
assert.strictEqual(res.body.status, 'OK');
};
Cloudron.prototype.setDnsConfig = function (dnsConfig) {
var res = request.post(this._origin + '/api/v1/settings/dns_config').query({ access_token: this._credentials.accessToken }).send(dnsConfig).end();
common.verifyResponse2xx(res, 'Could not set dns config');
};
Cloudron.prototype.setBackupConfig = function (backupConfig) {
var res = request.post(this._origin + '/api/v1/settings/backup_config').query({ access_token: this._credentials.accessToken }).send(backupConfig).end();
common.verifyResponse2xx(res, 'Could not set backup config');
};
Cloudron.prototype.saveSieveScript = function (owner, callback) {
var authString = 'AUTHENTICATE "PLAIN" "' + new Buffer('\0' + owner.username + '\0' + owner.password).toString('base64') + '"';
var data = '';
callback = once(callback);
var socket = tls.connect(4190, this._adminFqdn, { rejectUnauthorized: false }, function (error) {
if (error) return callback(error);
socket.write(authString + '\n');
socket.write('PUTSCRIPT "hutsefluts" {6+}\nkeep;\n\nLOGOUT\n');
setTimeout(function () {
socket.end();
callback(new Error('Could not auth with sieve with ' + authString + '.\n' + data));
}, 5000); // give it 5 seconds
});
socket.on('data', function (chunk) {
data += chunk.toString('utf8');
if (data.toString('utf8').indexOf('OK "PUTSCRIPT completed."') !== -1) return callback();
});
socket.on('end', function () { });
socket.on('error', callback);
};
Cloudron.prototype.checkSieveScript = function (owner, callback) {
var authString = 'AUTHENTICATE "PLAIN" "' + new Buffer('\0' + owner.username + '\0' + owner.password).toString('base64') + '"';
var data = '';
callback = once(callback);
var socket = tls.connect(4190, this._adminFqdn, { rejectUnauthorized: false }, function (error) {
if (error) return callback(error);
socket.write(authString + '\n');
socket.write('LISTSCRIPTS\nLOGOUT\n');
setTimeout(function () {
socket.end();
callback(new Error('Could not auth with sieve with ' + authString + '.\n' + data));
}, 5000); // give it 5 seconds
});
socket.on('data', function (chunk) {
data += chunk.toString('utf8');
if (data.toString('utf8').indexOf('"hutsefluts"') !== -1) return callback();
});
socket.on('end', function () { });
socket.on('error', callback);
};
Cloudron.prototype.checkForUpdates = function () {
request.post(this._origin + '/api/v1/cloudron/check_for_updates')
.query({ access_token: this._credentials.accessToken })
.end();
};
Cloudron.prototype.sendMail = function (account, to, callback) {
var transport = nodemailer.createTransport(smtpTransport({
host: this._adminFqdn,
port: 587,
auth: {
user: account.username,
pass: account.password
}
}));
var mailOptions = {
from: (account.from || account.username) + '@'+ this._box.domain,
to: to,
subject: 'Hi from e2e test - ' + this._box.domain,
text: 'This release depends on you' // keep in sync with mailer.sendMailToCloudronUser
};
debug('Sending mail with options %j', mailOptions);
transport.sendMail(mailOptions, callback);
};
Cloudron.prototype.checkMail = function (account, callback) {
var imap = new ImapProbe({
user: account.username,
password: account.password,
host: this._adminFqdn,
port: 993, // imap port
tls: true,
tlsOptions: { rejectUnauthorized: false },
readOnly: true
});
imap.probe({
subject: common.regexp('Hi from e2e test - ' + this._box.domain),
to: common.regexp((account.to || account.username) + '@' + this._box.domain),
body: common.regexp('This release depends on you')
}, callback);
};
Cloudron.prototype.checkTcpRateLimit = function (port, times, callback) {
tcpBomb(this._adminFqdn, port, times, 900 /* timeout */, function (error, result) {
if (error) return callback(new Error(port + ':' + error.message));
if (result.timeout) return callback(null, { status: 'OK' }); // something timedout, this is good enough
return callback(new Error(port + ':' + JSON.stringify(result, null, 4)));
});
};
Cloudron.prototype.checkNginxRateLimit = function (owner, times, callback) {
var ok = 0;
var that = this;
async.times(times, function (n, done) {
superagent.post('https://' + that._adminFqdn + '/api/v1/developer/login').send({ username: owner.username, password: owner.password }).end(function (error, result) {
if (!error && result.statusCode === 200) ++ok;
done();
});
}, function () {
callback(ok == times ? new Error('All requests succeeded') : null);
});
};
Cloudron.prototype.setAppstoreConfig = function (id, token) {
var res = request.post('https://' + this._adminFqdn + '/api/v1/settings/appstore_config')
.send({ userId: id, token: token })
.query({ access_token: this._credentials.accessToken })
.end();
common.verifyResponse2xx(res, 'Could not set appstore config');
};