+ filtered_keys = [key for key in self.resources_to_operations_mapping.keys()
+ if method in key.split()[0]]
+
+ for idx, path_part in enumerate(normalized_url_splitted):
+ tmp_keys = []
+ for tmp_key in filtered_keys:
+ splitted = tmp_key.split()[1].split("/")
+ if idx >= len(splitted):
+ continue
+ elif "<" in splitted[idx] and ">" in splitted[idx]:
+ if splitted[idx] == "<artifactPath>":
+ tmp_keys.append(tmp_key)
+ continue
+ elif idx == len(normalized_url_splitted) - 1 and \
+ len(normalized_url_splitted) != len(splitted):
+ continue
+ else:
+ tmp_keys.append(tmp_key)
+ elif splitted[idx] == path_part:
+ if idx == len(normalized_url_splitted) - 1 and \
+ len(normalized_url_splitted) != len(splitted):
+ continue
+ else:
+ tmp_keys.append(tmp_key)
+ filtered_keys = tmp_keys
+ if len(filtered_keys) == 1 and \
+ filtered_keys[0].split("/")[-1] == "<artifactPath>":
+ break
+
+ if len(filtered_keys) == 0:
+ raise AuthException("Cannot make an authorization decision. URL not found. URL: {0}".format(url))
+ elif len(filtered_keys) > 1:
+ raise AuthException("Cannot make an authorization decision. Multiple URLs found. URL: {0}".format(url))
+
+ filtered_key = filtered_keys[0]
+
+ for idx, path_part in enumerate(filtered_key.split()[1].split("/")):
+ if "<" in path_part and ">" in path_part:
+ if path_part == "<artifactPath>":
+ parameters[path_part[1:-1]] = "/".join(normalized_url_splitted[idx:])
+ else:
+ parameters[path_part[1:-1]] = normalized_url_splitted[idx]
+
+ return filtered_key, parameters
+
+ def _internal_authorize(self, token_id):
+ try:
+ if not token_id:
+ raise AuthException("Needed a token or Authorization http header", http_code=HTTPStatus.UNAUTHORIZED)
+ # try to get from cache first
+ now = time()
+ session = self.tokens_cache.get(token_id)
+ if session and session["expires"] < now:
+ # delete token. MUST be done with care, as another thread maybe already delete it. Do not use del
+ self.tokens_cache.pop(token_id, None)
+ session = None
+ if session:
+ return session
+
+ # get from database if not in cache
+ session = self.db.get_one("tokens", {"_id": token_id})
+ if session["expires"] < now:
+ raise AuthException("Expired Token or Authorization http header", http_code=HTTPStatus.UNAUTHORIZED)
+ self.tokens_cache[token_id] = session
+ return session
+ except DbException as e:
+ if e.http_code == HTTPStatus.NOT_FOUND:
+ raise AuthException("Invalid Token or Authorization http header", http_code=HTTPStatus.UNAUTHORIZED)
+ else:
+ raise
+
+ except AuthException:
+ if self.config["global"].get("test.user_not_authorized"):
+ return {"id": "fake-token-id-for-test",
+ "project_id": self.config["global"].get("test.project_not_authorized", "admin"),
+ "username": self.config["global"]["test.user_not_authorized"], "admin": True}
+ else:
+ raise
+
+ def _internal_new_token(self, session, indata, remote):
+ now = time()
+ user_content = None
+
+ # Try using username/password
+ if indata.get("username"):
+ user_rows = self.db.get_list("users", {"username": indata.get("username")})
+ if user_rows:
+ user_content = user_rows[0]
+ salt = user_content["_admin"]["salt"]
+ shadow_password = sha256(indata.get("password", "").encode('utf-8') + salt.encode('utf-8')).hexdigest()
+ if shadow_password != user_content["password"]:
+ user_content = None
+ if not user_content:
+ raise AuthException("Invalid username/password", http_code=HTTPStatus.UNAUTHORIZED)
+ elif session:
+ user_rows = self.db.get_list("users", {"username": session["username"]})
+ if user_rows:
+ user_content = user_rows[0]
+ else:
+ raise AuthException("Invalid token", http_code=HTTPStatus.UNAUTHORIZED)
+ else:
+ raise AuthException("Provide credentials: username/password or Authorization Bearer token",
+ http_code=HTTPStatus.UNAUTHORIZED)
+
+ token_id = ''.join(random_choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
+ for _ in range(0, 32))
+ project_id = indata.get("project_id")
+ if project_id:
+ if project_id != "admin":
+ # To allow project names in project_id
+ proj = self.db.get_one("projects", {BaseTopic.id_field("projects", project_id): project_id})
+ if proj["_id"] not in user_content["projects"] and proj["name"] not in user_content["projects"]:
+ raise AuthException("project {} not allowed for this user"
+ .format(project_id), http_code=HTTPStatus.UNAUTHORIZED)
+ else:
+ project_id = user_content["projects"][0]
+ if project_id == "admin":
+ session_admin = True
+ else:
+ # To allow project names in project_id
+ project = self.db.get_one("projects", {BaseTopic.id_field("projects", project_id): project_id})
+ session_admin = project.get("admin", False)
+ new_session = {"issued_at": now, "expires": now + 3600,
+ "_id": token_id, "id": token_id, "project_id": project_id, "username": user_content["username"],
+ "remote_port": remote.port, "admin": session_admin}
+ if remote.name:
+ new_session["remote_host"] = remote.name
+ elif remote.ip:
+ new_session["remote_host"] = remote.ip
+
+ self.tokens_cache[token_id] = new_session
+ self.db.create("tokens", new_session)
+ # check if database must be prune
+ self._internal_tokens_prune(now)
+ return deepcopy(new_session)
+
+ def _internal_get_token_list(self, session):
+ now = time()
+ token_list = self.db.get_list("tokens", {"username": session["username"], "expires.gt": now})
+ return token_list
+
+ def _internal_get_token(self, session, token_id):
+ token_value = self.db.get_one("tokens", {"_id": token_id}, fail_on_empty=False)
+ if not token_value:
+ raise AuthException("token not found", http_code=HTTPStatus.NOT_FOUND)
+ if token_value["username"] != session["username"] and not session["admin"]:
+ raise AuthException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
+ return token_value
+
+ def _internal_del_token(self, token_id):
+ try:
+ self.tokens_cache.pop(token_id, None)
+ self.db.del_one("tokens", {"_id": token_id})
+ return "token '{}' deleted".format(token_id)
+ except DbException as e:
+ if e.http_code == HTTPStatus.NOT_FOUND:
+ raise AuthException("Token '{}' not found".format(token_id), http_code=HTTPStatus.NOT_FOUND)
+ else:
+ raise