Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: protect failing due to missing auth #550

Merged
merged 1 commit into from
Jun 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/cli/commands/monitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module.exports = monitor;

import * as _ from 'lodash';
import * as fs from 'then-fs';
import {exists as apiTokenExists} from '../../lib/api-token';
import {apiTokenExists} from '../../lib/api-token';
import snyk = require('../../lib/'); // TODO(kyegupov): fix import
import {monitor as snykMonitor} from '../../lib/monitor';
import * as config from '../../lib/config';
Expand Down Expand Up @@ -73,7 +73,9 @@ async function monitor(...args0: MethodArgs): Promise<any> {
if (options['all-sub-projects'] && options['project-name']) {
throw new Error('`--all-sub-projects` is currently not compatible with `--project-name`');
}
await apiTokenExists('snyk monitor');

apiTokenExists();

// Part 1: every argument is a scan target; process them sequentially
for (const path of args as string[]) {
try {
Expand Down
4 changes: 2 additions & 2 deletions src/cli/commands/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import chalk from 'chalk';
import * as snyk from '../../lib/';
import * as config from '../../lib/config';
import {isCI} from '../../lib/is-ci';
import {exists as apiTokenExists} from '../../lib/api-token';
import {apiTokenExists} from '../../lib/api-token';
import {SEVERITIES, WIZARD_SUPPORTED_PMS} from '../../lib/snyk-test/common';
import * as Debug from 'debug';
import {TestOptions} from '../../lib/types';
Expand Down Expand Up @@ -45,7 +45,7 @@ async function test(...args: MethodArgs): Promise<string> {
return Promise.reject(new Error('INVALID_SEVERITY_THRESHOLD'));
}

await apiTokenExists('snyk test');
apiTokenExists();

// Promise waterfall to test all other paths sequentially
for (const path of args as string[]) {
Expand Down
17 changes: 0 additions & 17 deletions src/lib/api-token.js

This file was deleted.

17 changes: 17 additions & 0 deletions src/lib/api-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { MissingApiTokenError } from '../lib/errors';

import * as config from './config';
import * as userConfig from './user-config';

export function api() {
// note: config.TOKEN will potentially come via the environment
return config.api || config.TOKEN || userConfig.get('api');
}

export function apiTokenExists() {
const configured = api();
if (!configured) {
throw new MissingApiTokenError();
}
return configured;
}
2 changes: 2 additions & 0 deletions src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import * as url from 'url';
const DEFAULT_TIMEOUT = 5 * 60; // in seconds
interface Config {
API: string;
api: string;
disableSuggestions: string;
org: string;
ROOT: string;
timeout: number;
PROJECT_NAME: string;
TOKEN: string;
}

const config: Config = snykConfig(__dirname + '/../..');
Expand Down
1 change: 1 addition & 0 deletions src/lib/errors/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export {MissingApiTokenError} from './missing-api-token';
export {FileFlagBadInputError} from './file-flag-bad-input';
export {MissingTargetFileError} from './missing-targetfile-error';
export {NoSupportedManifestsFoundError} from './no-supported-manifests-found';
15 changes: 15 additions & 0 deletions src/lib/errors/missing-api-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {CustomError} from './custom-error';

export class MissingApiTokenError extends CustomError {
private static ERROR_CODE: number = 401;
private static ERROR_STRING_CODE: string = 'NO_API_TOKEN';
private static ERROR_MESSAGE: string =
'`snyk` requires an authenticated account. Please run `snyk auth` and try again.';

constructor() {
super(MissingApiTokenError.ERROR_MESSAGE);
this.code = MissingApiTokenError.ERROR_CODE;
dkontorovskyy marked this conversation as resolved.
Show resolved Hide resolved
this.strCode = MissingApiTokenError.ERROR_STRING_CODE;
this.userMessage = MissingApiTokenError.ERROR_MESSAGE;
}
}
4 changes: 2 additions & 2 deletions src/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ module.exports = snyk;

snyk.id = snykConfig.id;

var apiToken = require('./api-token');
const apiToken = require('./api-token');

// make snyk.api *always* get the latest api token from the config store
Object.defineProperty(snyk, 'api', {
enumerable: true,
configurable: true,
get: function () {
return apiToken();
return apiToken.api();
dkontorovskyy marked this conversation as resolved.
Show resolved Hide resolved
},
set: function (value) {
snykConfig.api = value;
Expand Down
148 changes: 70 additions & 78 deletions src/lib/monitor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as snyk from '../lib';
import {exists as apiTokenExists} from './api-token';
import {apiTokenExists} from './api-token';
import * as request from './request';
import * as config from './config';
import * as os from 'os';
Expand Down Expand Up @@ -39,91 +39,83 @@ interface Meta {
projectName: string;
}

export function monitor(root, meta, info: SingleDepRootResult, targetFile): Promise<any> {
export async function monitor(root, meta, info: SingleDepRootResult, targetFile): Promise<any> {
apiTokenExists();
const pkg = info.package;
const pluginMeta = info.plugin;
let policyPath = meta['policy-path'];
if (!meta.isDocker) {
policyPath = policyPath || root;
}
let policy;
const policyPath = meta['policy-path'] || root;
const policyLocations = [policyPath].concat(pluckPolicies(pkg))
.filter(Boolean);
const opts = {loose: true};
const packageManager = meta.packageManager || 'npm';
return apiTokenExists('snyk monitor')
.then(() => {
if (policyLocations.length === 0) {
return snyk.policy.create();
}
return snyk.policy.load(policyLocations, opts);
}).then(async (policy) => {
analytics.add('packageManager', packageManager);
.filter(Boolean);
// docker doesn't have a policy as it can be run from anywhere
if (!meta.isDocker || !policyLocations.length) {
await snyk.policy.create();
}
policy = await snyk.policy.load(policyLocations, {loose: true});

const target = await projectMetadata.getInfo(pkg);
const targetFileRelativePath = targetFile ? path.relative(root, targetFile) : '';
const packageManager = meta.packageManager;
analytics.add('packageManager', packageManager);

if (target && target.branch) {
analytics.add('targetBranch', target.branch);
}
const target = await projectMetadata.getInfo(pkg);
const targetFileRelativePath = targetFile ? path.relative(root, targetFile) : '';

// TODO(kyegupov): async/await
return new Promise((resolve, reject) => {
request({
body: {
meta: {
method: meta.method,
hostname: os.hostname(),
id: meta.id || snyk.id || pkg.name,
ci: isCI(),
pid: process.pid,
node: process.version,
master: snyk.config.isMaster,
name: pkg.name,
version: pkg.version,
org: config.org ? decodeURIComponent(config.org) : undefined,
pluginName: pluginMeta.name,
pluginRuntime: pluginMeta.runtime,
dockerImageId: pluginMeta.dockerImageId,
dockerBaseImage: pkg.docker ? pkg.docker.baseImage : undefined,
dockerfileLayers: pkg.docker ? pkg.docker.dockerfileLayers : undefined,
projectName: meta['project-name'],
},
policy: policy ? policy.toString() : undefined,
package: pkg,
// we take the targetFile from the plugin,
// because we want to send it only for specific package-managers
target,
targetFile: pluginMeta.targetFile,
targetFileRelativePath,
} as MonitorBody,
gzip: true,
method: 'PUT',
headers: {
'authorization': 'token ' + snyk.api,
'content-encoding': 'gzip',
},
url: config.API + '/monitor/' + packageManager,
json: true,
}, (error, res, body) => {
if (error) {
return reject(error);
}
// TODO(kyegupov): async/await
return new Promise((resolve, reject) => {
request({
body: {
meta: {
method: meta.method,
hostname: os.hostname(),
id: meta.id || snyk.id || pkg.name,
ci: isCI(),
pid: process.pid,
node: process.version,
master: snyk.config.isMaster,
name: pkg.name,
version: pkg.version,
org: config.org ? decodeURIComponent(config.org) : undefined,
pluginName: pluginMeta.name,
pluginRuntime: pluginMeta.runtime,
dockerImageId: pluginMeta.dockerImageId,
dockerBaseImage: pkg.docker ? pkg.docker.baseImage : undefined,
dockerfileLayers: pkg.docker ? pkg.docker.dockerfileLayers : undefined,
projectName: meta['project-name'],
},
policy: policy ? policy.toString() : undefined,
package: pkg,
// we take the targetFile from the plugin,
// because we want to send it only for specific package-managers
target,
targetFile: pluginMeta.targetFile,
targetFileRelativePath,
} as MonitorBody,
gzip: true,
method: 'PUT',
headers: {
'authorization': 'token ' + snyk.api,
'content-encoding': 'gzip',
},
url: config.API + '/monitor/' + packageManager,
json: true,
}, (error, res, body) => {
if (error) {
return reject(error);
}

if (res.statusCode === 200 || res.statusCode === 201) {
resolve(body);
} else {
const e = new MonitorError('Server returned unexpected error for the monitor request. ' +
`Status code: ${res.statusCode}, response: ${res.body.userMessage || res.body.message}`);
e.code = res.statusCode;
e.userMessage = body && body.userMessage;
if (!e.userMessage && res.statusCode === 504) {
e.userMessage = 'Connection Timeout';
}
reject(e);
}
});
});
if (res.statusCode === 200 || res.statusCode === 201) {
resolve(body);
} else {
const e = new MonitorError('Server returned unexpected error for the monitor request. ' +
`Status code: ${res.statusCode}, response: ${res.body.userMessage || res.body.message}`);
e.code = res.statusCode;
e.userMessage = body && body.userMessage;
if (!e.userMessage && res.statusCode === 504) {
e.userMessage = 'Connection Timeout';
}
reject(e);
}
});
});
}

function pluckPolicies(pkg) {
Expand Down
4 changes: 2 additions & 2 deletions test/acceptance/cli.acceptance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2606,7 +2606,7 @@ test('`monitor foo:latest --docker` doesnt send policy from cwd', async (t) => {
}], 'calls docker plugin with expected arguments');

const emptyPolicy = await snykPolicy.create();
t.same(req.body.policy, emptyPolicy.toString(), 'empty policy is sent');
t.deepEqual(req.body.policy, emptyPolicy.toString(), 'empty policy is sent');
});

test('`monitor foo:latest --docker` with custom policy path', async (t) => {
Expand Down Expand Up @@ -2647,7 +2647,7 @@ test('`monitor foo:latest --docker` with custom policy path', async (t) => {
path.join('custom-location', '.snyk'),
'utf8');
const policyString = req.body.policy;
t.equal(policyString, expected, 'sends correct policy');
t.deepEqual(policyString, expected, 'sends correct policy');
});

test('`wizard` for unsupported package managers', async (t) => {
Expand Down
18 changes: 18 additions & 0 deletions test/acceptance/protect.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import {test} from 'tap';
import {exec} from 'child_process';
import * as userConfig from '../../src/lib/user-config';

test('`protect` should not fail for unauthorized users', (t) => {
t.plan(1);

const apiUserConfig = userConfig.get('api');
// temporally remove api param in userConfig to test for unauthenticated users
userConfig.delete('api');

exec('node ./dist/cli/index.js protect', (_, stdout) => {
dkontorovskyy marked this conversation as resolved.
Show resolved Hide resolved
t.equal(stdout.trim(), 'Successfully applied Snyk patches', 'correct output for unauthenticated user');

// Restore api param
userConfig.set('api', apiUserConfig);
});
});
22 changes: 11 additions & 11 deletions test/cli.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,18 +249,18 @@ test('snyk ignore - not authorized', function (t) {
.catch((err) => t.pass('no policy file saved'));
});

test('test without authentication', function (t) {
t.plan(1);
return cli.config('unset', 'api').then(function () {
return cli.test('semver@2');
}).then(function (res) {
test('test without authentication', async (t) => {
await cli.config('unset', 'api');
try {
await cli.test('semver@2');
t.fail('test should not pass if not authenticated');
}).catch(function (error) {
t.equals(error.code, 'NO_API_TOKEN', 'test requires authentication');
})
.then(function () {
return cli.config('set', 'api=' + apiKey);
});
} catch (error) {
t.deepEquals(error.strCode, 'NO_API_TOKEN', 'string code is as expected');
t.match(error.message,
'`snyk` requires an authenticated account. Please run `snyk auth` and try again.',
'error message is shown as expected');
}
await cli.config('set', 'api=' + apiKey);
});

test('auth via key', function (t) {
Expand Down