norman/telescope — pull request #17 by Odie (2012-04-08 13:33:52+00:00)
Title: Fixed problem with load_contexts sandboxing

Hi there,

Found an interesting bug in telescope.lua
If a unit test script were to try to access an undeclared global variable, an error would be thrown on that line saying "loop in gettable". This would not ordinarily be a problem, unless the unit test being constructed involves loading a 3rd party library that depends lua answer nil to any undeclared globals.

Upon investigating (and spending some time getting my head around function environments), it appears that load_contexts is trying to do sandboxing incorrectly.

# Condense description of load_context
Looking at line 271 in the original file
```lua
local env = getfenv()
```
The code grabs the calling function's environment. It proceeds to inject variables into the environment.
Later on, in line 306, it is chained with _G again.
```lua
setmetatable(env, {__index = _G})
```
Finally, the carefully prepared env is set on the returned value/function of loadfile.

# What's the problem?
1) getfenv() on line 271 returns _G
That means line 306 is saying to chain _G with _G. That's why any lookups to undeclared globals fail with "loop in gettable" error.

2) There is no sandboxing
Because when we run the loaded contents of the target file, all globals declared in that file would end up in _G.

# The Solution?
It's just to provide a empty table on line 271. Everything still works, but now access to undeclared globals work. Sandboxing works correctly also.