How can I restrict what's being imported in a template?
Here's why I'd like to have this capability. I've got site-level templates (authored by me) and user-authored templates. I plan to let users create the content for their automatically-generated home pages using their user-authored templates. "The system" will run those templates using the compiled site templates and runtime evaluation of the user templates. I don't want this process doing arbitrary things.
Since #from ... import ... is the only way to get code into Cheetah, perhaps all I'd need is an "allowedImports" list of allowed modules and functions. Something like:
(("string", ("strip, "rstrip")), ("ModuleName_", ("function1", ...)))
A wildcard "*" would match anything, an empty list nothing. The default could be ("*", ("*",)) -- or maybe just None, to match current behavior.
#from would just validate off the list. While not offered any bulletproof protections, this mechanism would cut down on most of the major allowable monkey business.
-- MikeOrr - 25 Nov 2001 for Michael Halle
There is no way to restrict imports currently. Tavis wanted to add some restricted-execution features later, borrowing ideas from Velocity, WebMacro, Zope, etc, but we never spec'd out exactly what.
One issue is whether Python's Bastion module would offer a more comprehensive security solution. But where to incorporate Bastion?
Another would be to throw the problem onto Webware and say that it's in charge of security.
Possibly we could have a compiler setting 'RestrictedImport' that, if not empty, would prevail upon #import and #from as you suggest. The directives could wrap the import in an if-test and raise an exception (RestrictedImportError) if ineligible. Or use __import__ if they need more flexibility.
Of course, if the user specifies #import, it'll be trickier to prevent ineligible objects from being imported. You'd have to import, then check all the imported objects.
You'd have to set the compiler setting yourself for the restricted templates, since Cheetah doesn't know which ones should be restricted. How are you instantiating the user templates? Are you using #include, calling the Template constructor by hand, or instantiating a cheetah-compile'd class?
Your specification was a list of 2-tuples, but it may be more natural to have a dictionary of:
"module name": list/tuple of "allowed objects"
then you could have nested dictionaries for packages/submodules.
Tavis made a mysterious note somewhere in the User's Guide about how a future version of Cheetah would have more restricted-execution features. I can't find the quote now so maybe he removed it.
In any case, before we make any restricted-use changes, we should compare how Velocity, WebMacro and Zope do it, so we don't go making something that's useful for the short term but is unscalable in the long term.
-- MikeOrr - 25 Nov 2001