1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "remote/filterutility.hpp"
4 #include "remote/httputility.hpp"
5 #include "config/configcompiler.hpp"
6 #include "config/expression.hpp"
7 #include "base/namespace.hpp"
8 #include "base/json.hpp"
9 #include "base/configtype.hpp"
10 #include "base/logger.hpp"
11 #include "base/utility.hpp"
12 #include <boost/algorithm/string/case_conv.hpp>
14 using namespace icinga;
16 Type::Ptr FilterUtility::TypeFromPluralName(const String& pluralName)
18 String uname = pluralName;
19 boost::algorithm::to_lower(uname);
21 for (const Type::Ptr& type : Type::GetAllTypes()) {
22 String pname = type->GetPluralName();
23 boost::algorithm::to_lower(pname);
32 void ConfigObjectTargetProvider::FindTargets(const String& type, const std::function<void (const Value&)>& addTarget) const
34 Type::Ptr ptype = Type::GetByName(type);
35 auto *ctype = dynamic_cast<ConfigType *>(ptype.get());
38 for (const ConfigObject::Ptr& object : ctype->GetObjects()) {
44 Value ConfigObjectTargetProvider::GetTargetByName(const String& type, const String& name) const
46 ConfigObject::Ptr obj = ConfigObject::GetObject(type, name);
49 BOOST_THROW_EXCEPTION(std::invalid_argument("Object does not exist."));
54 bool ConfigObjectTargetProvider::IsValidType(const String& type) const
56 Type::Ptr ptype = Type::GetByName(type);
61 return ConfigObject::TypeInstance->IsAssignableFrom(ptype);
64 String ConfigObjectTargetProvider::GetPluralName(const String& type) const
66 return Type::GetByName(type)->GetPluralName();
69 bool FilterUtility::EvaluateFilter(ScriptFrame& frame, Expression *filter,
70 const Object::Ptr& target, const String& variableName)
75 Type::Ptr type = target->GetReflectionType();
78 if (variableName.IsEmpty())
79 varName = type->GetName().ToLower();
81 varName = variableName;
83 Namespace::Ptr frameNS;
85 if (frame.Self.IsEmpty()) {
86 frameNS = new Namespace();
89 /* Enforce a namespace object for 'frame.self'. */
90 ASSERT(frame.Self.IsObjectType<Namespace>());
94 ASSERT(frameNS != ScriptGlobal::GetGlobals());
97 frameNS->Set("obj", target);
98 frameNS->Set(varName, target);
100 for (int fid = 0; fid < type->GetFieldCount(); fid++) {
101 Field field = type->GetFieldInfo(fid);
103 if ((field.Attributes & FANavigation) == 0)
106 Object::Ptr joinedObj = target->NavigateField(fid);
108 if (field.NavigationName)
109 frameNS->Set(field.NavigationName, joinedObj);
111 frameNS->Set(field.Name, joinedObj);
114 return Convert::ToBool(filter->Evaluate(frame));
117 static void FilteredAddTarget(ScriptFrame& permissionFrame, Expression *permissionFilter,
118 ScriptFrame& frame, Expression *ufilter, std::vector<Value>& result, const String& variableName, const Object::Ptr& target)
120 if (FilterUtility::EvaluateFilter(permissionFrame, permissionFilter, target, variableName)) {
121 if (FilterUtility::EvaluateFilter(frame, ufilter, target, variableName)) {
122 result.emplace_back(std::move(target));
127 void FilterUtility::CheckPermission(const ApiUser::Ptr& user, const String& permission, Expression **permissionFilter)
129 if (permissionFilter)
130 *permissionFilter = nullptr;
132 if (permission.IsEmpty())
135 bool foundPermission = false;
136 String requiredPermission = permission.ToLower();
138 Array::Ptr permissions = user->GetPermissions();
140 ObjectLock olock(permissions);
141 for (const Value& item : permissions) {
143 Function::Ptr filter;
144 if (item.IsObjectType<Dictionary>()) {
145 Dictionary::Ptr dict = item;
146 permission = dict->Get("permission");
147 filter = dict->Get("filter");
151 permission = permission.ToLower();
153 if (!Utility::Match(permission, requiredPermission))
156 foundPermission = true;
158 if (filter && permissionFilter) {
159 std::vector<std::unique_ptr<Expression> > args;
160 args.emplace_back(new GetScopeExpression(ScopeThis));
161 std::unique_ptr<Expression> indexer{new IndexerExpression(std::unique_ptr<Expression>(MakeLiteral(filter)), std::unique_ptr<Expression>(MakeLiteral("call")))};
162 FunctionCallExpression *fexpr = new FunctionCallExpression(std::move(indexer), std::move(args));
164 if (!*permissionFilter)
165 *permissionFilter = fexpr;
167 *permissionFilter = new LogicalOrExpression(std::unique_ptr<Expression>(*permissionFilter), std::unique_ptr<Expression>(fexpr));
172 if (!foundPermission) {
173 Log(LogWarning, "FilterUtility")
174 << "Missing permission: " << requiredPermission;
176 BOOST_THROW_EXCEPTION(ScriptError("Missing permission: " + requiredPermission));
180 std::vector<Value> FilterUtility::GetFilterTargets(const QueryDescription& qd, const Dictionary::Ptr& query, const ApiUser::Ptr& user, const String& variableName)
182 std::vector<Value> result;
184 TargetProvider::Ptr provider;
187 provider = qd.Provider;
189 provider = new ConfigObjectTargetProvider();
191 Expression *permissionFilter;
192 CheckPermission(user, qd.Permission, &permissionFilter);
194 Namespace::Ptr permissionFrameNS = new Namespace();
195 ScriptFrame permissionFrame(false, permissionFrameNS);
197 for (const String& type : qd.Types) {
199 boost::algorithm::to_lower(attr);
204 if (query && query->Contains(attr)) {
205 String name = HttpUtility::GetLastParameter(query, attr);
206 Object::Ptr target = provider->GetTargetByName(type, name);
208 if (!FilterUtility::EvaluateFilter(permissionFrame, permissionFilter, target, variableName))
209 BOOST_THROW_EXCEPTION(ScriptError("Access denied to object '" + name + "' of type '" + type + "'"));
211 result.emplace_back(std::move(target));
214 attr = provider->GetPluralName(type);
215 boost::algorithm::to_lower(attr);
217 if (query && query->Contains(attr)) {
218 Array::Ptr names = query->Get(attr);
220 ObjectLock olock(names);
221 for (const String& name : names) {
222 Object::Ptr target = provider->GetTargetByName(type, name);
224 if (!FilterUtility::EvaluateFilter(permissionFrame, permissionFilter, target, variableName))
225 BOOST_THROW_EXCEPTION(ScriptError("Access denied to object '" + name + "' of type '" + type + "'"));
227 result.emplace_back(std::move(target));
233 if ((query && query->Contains("filter")) || result.empty()) {
234 if (!query->Contains("type"))
235 BOOST_THROW_EXCEPTION(std::invalid_argument("Type must be specified when using a filter."));
237 String type = HttpUtility::GetLastParameter(query, "type");
239 if (!provider->IsValidType(type))
240 BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid type specified."));
242 if (qd.Types.find(type) == qd.Types.end())
243 BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid type specified for this query."));
245 Namespace::Ptr frameNS = new Namespace();
246 ScriptFrame frame(false, frameNS);
247 frame.Sandboxed = true;
249 if (query->Contains("filter")) {
250 String filter = HttpUtility::GetLastParameter(query, "filter");
251 std::unique_ptr<Expression> ufilter = ConfigCompiler::CompileText("<API query>", filter);
253 Dictionary::Ptr filter_vars = query->Get("filter_vars");
255 ObjectLock olock(filter_vars);
256 for (const Dictionary::Pair& kv : filter_vars) {
257 frameNS->Set(kv.first, kv.second);
261 provider->FindTargets(type, std::bind(&FilteredAddTarget,
262 std::ref(permissionFrame), permissionFilter,
263 std::ref(frame), &*ufilter, std::ref(result), variableName, _1));
265 /* Ensure to pass a nullptr as filter expression.
266 * GCC 8.1.1 on F28 causes problems, see GH #6533.
268 provider->FindTargets(type, std::bind(&FilteredAddTarget,
269 std::ref(permissionFrame), permissionFilter,
270 std::ref(frame), nullptr, std::ref(result), variableName, _1));