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

cache: Add in ExpirationTime to local caches. #46

Merged
merged 3 commits into from
Apr 13, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
40 changes: 40 additions & 0 deletions src/cache/client/npm/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,26 @@ describe('vulnRegexDetector', () => {
const response3 = vulnRegexDetector.testSync(pattern, invalidConfig);
assert.ok(response3 === vulnRegexDetector.responses.invalid, `Query succeeded? response ${response3}`);
});
it('should not return an expired cache value', () => {
const pattern = 'abcde'; // TODO perhaps make some temporary cache for all of the tests and clear it each time.
// Make sync query to prime local persistent cache, but use negative cache value to ensure expiration.
let validConfig = { cache: { type: vulnRegexDetector.cacheTypes.persistent, expirationTime: -1 } };
const response1 = vulnRegexDetector.testSync(pattern, validConfig);
assert.ok(response1 === vulnRegexDetector.responses.safe, `Error, unexpected response for sync query: ${response1}`);

let invalidConfig = {
server: {
hostname: 'no such host',
port: 1
},
cache: {
type: vulnRegexDetector.cacheTypes.persistent,
expirationTime: -1
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggest you declare a cacheConfig variable at the top of the function and use it here and above.

}
};
const response2 = vulnRegexDetector.testSync(pattern, invalidConfig);
assert.ok(response2 === vulnRegexDetector.responses.invalid, `Query succeeded? response ${response2}. Unless 'no such host' is a valid hostname we must have a cache hit on an expired entry`);
});
});

describe('memory', () => {
Expand All @@ -292,6 +312,26 @@ describe('vulnRegexDetector', () => {
const response2 = vulnRegexDetector.testSync(pattern, invalidConfig);
assert.ok(response2 === vulnRegexDetector.responses.safe, `Query failed: response ${response2}, probably due to my invalid config.server (so cache failed)`);
});
it('should not return an expired cache value', () => {
const pattern = 'abcde'; // TODO perhaps make some temporary cache for all of the tests and clear it each time.
// Make sync query to prime local in-memory cache, but use negative cache value to ensure expiration.
let validConfig = { cache: { type: vulnRegexDetector.cacheTypes.memory, expirationTime: -1 } };
const response1 = vulnRegexDetector.testSync(pattern, validConfig);
assert.ok(response1 === vulnRegexDetector.responses.safe, `Error, unexpected response for sync query: ${response1}`);

let invalidConfig = {
server: {
hostname: 'no such host',
port: 1
},
cache: {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor into a cacheConfig as in persistent case.

type: vulnRegexDetector.cacheTypes.memory,
expirationTime: -1
}
};
const response2 = vulnRegexDetector.testSync(pattern, invalidConfig);
assert.ok(response2 === vulnRegexDetector.responses.invalid, `Query succeeded? response ${response2}. Unless 'no such host' is a valid hostname we must have a cache hit on an expired entry`);
});
});
});
});
Expand Down
44 changes: 32 additions & 12 deletions src/cache/client/npm/vuln-regex-detector-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ const defaultServerConfig = {

const defaultCacheConfig = {
type: CACHE_TYPES.persistent,
persistentDir: path.join(os.tmpdir(), 'vuln-regex-detector-client-persistentCache')
persistentDir: path.join(os.tmpdir(), 'vuln-regex-detector-client-persistentCache'),
expirationTime: 60 * 60 * 24 * 7 // 7 days
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change comment to // 7 days in seconds

};

/**********
Expand Down Expand Up @@ -276,6 +277,11 @@ function handleCacheConfig (cacheConfig) {
cacheConfig.persistentDir = defaultCacheConfig.persistentDir;
}

// expirationTime must be an integer value
if (!cacheConfig.hasOwnProperty('expirationTime') || !Number.isInteger(cacheConfig.expirationTime)) {
cacheConfig.expirationTime = defaultCacheConfig.expirationTime;
}

return cacheConfig;
}

Expand Down Expand Up @@ -341,8 +347,19 @@ function updateCache (config, pattern, response) {
if (!useCache(config)) {
return;
}
/* Only cache VULNERABLE|SAFE responses. */
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a newline before and after this block.

if (response !== RESPONSE_VULNERABLE && response !== RESPONSE_SAFE) {
return;
}
/* This entry will expire config.expirationTime seconds from now. */
let expirationTimeInMilliseconds = 1000 * config.cache.expirationTime;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declare these variables const

let expiryDate = new Date(Date.now() + expirationTimeInMilliseconds);
let wrappedResponse = {
response: response,
validUntil: expiryDate.toISOString()
};

return kvPut(config, pattern, response);
return kvPut(config, pattern, wrappedResponse);
}

/* Returns RESPONSE_{VULNERABLE|SAFE} on hit, else RESPONSE_UNKNOWN on miss or disabled. */
Expand All @@ -351,15 +368,20 @@ function checkCache (config, pattern) {
return RESPONSE_UNKNOWN;
}

return kvGet(config, pattern);
let valueRetrieved = kvGet(config, pattern);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declare these variables const

if (valueRetrieved === RESPONSE_UNKNOWN) {
return RESPONSE_UNKNOWN;
}
/* Check if the cache entry has expired. */
let lastValidDate = new Date(valueRetrieved.validUntil);
if (Date.now() > lastValidDate) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to write comparisons as smaller < larger.

/* The entry in the cache has expired. */
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For consistency, The cache entry has expired.

return RESPONSE_UNKNOWN;
}
return valueRetrieved.response;
}

function kvPut (config, key, value) {
/* Only cache VULNERABLE|SAFE responses. */
if (value !== RESPONSE_VULNERABLE && value !== RESPONSE_SAFE) {
return;
}

/* Put in the appropriate cache. */
switch (config.cache.type) {
case CACHE_TYPES.persistent:
Expand Down Expand Up @@ -418,7 +440,7 @@ function kvPersistentFname (config, key) {
* Using a hash might give us false reports on collisions, but this is
* exceedingly unlikely in typical use cases (a few hundred regexes tops). */
const hash = crypto.createHash('md5').update(key).digest('hex');
const fname = path.join(config.cache.persistentDir, `${hash}.json`);
const fname = path.join(config.cache.persistentDir, `${hash}-v2.json`);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think we should the number "2" a global CACHE_VERSION variable? Then a comment on that variable can indicate history better.

return fname;
}

Expand Down Expand Up @@ -463,9 +485,7 @@ function kvGetPersistent (config, key) {
let pattern2response = {};

function kvPutMemory (key, value) {
if (!pattern2response.hasOwnProperty(key)) {
pattern2response[key] = value;
}
pattern2response[key] = value;
}

function kvGetMemory (key) {
Expand Down