label
class label 3
classes | code_before
stringlengths 417
269k
| code_after
stringlengths 415
269k
| label_text
stringclasses 3
values | deleted
dict | added
dict | normalized_code_before
stringlengths 316
220k
| normalized_code_after
stringlengths 316
220k
| before_doc_string_pos
sequence | after_doc_string_pos
sequence |
---|---|---|---|---|---|---|---|---|---|
0CWE-22
| from __future__ import annotations
import email.utils
import errno
import os
import sys
import urllib.parse
from abc import abstractmethod
from datetime import datetime
from typing import List, Optional
import attr
import requests
import tenacity
from .Line import Line
@attr.s(auto_attribs=True)
class InputContent:
rawLines: List[str]
date: Optional[datetime.date]
@property
def lines(self) -> List[Line]:
return [Line(i, line) for i, line in enumerate(self.rawLines, 1)]
@property
def content(self) -> str:
return "".join(self.rawLines)
class InputSource:
"""Represents a thing that can produce specification input text.
Input can be read from stdin ("-"), an HTTPS URL, or a file. Other
InputSources can be found relative to URLs and files, and there's a context
manager for temporarily switching to the directory of a file InputSource.
"""
def __new__(cls, sourceName: str):
"""Dispatches to the right subclass."""
if cls != InputSource:
# Only take control of calls to InputSource(...) itself.
return super().__new__(cls)
if sourceName == "-":
return StdinInputSource(sourceName)
if sourceName.startswith("https:"):
return UrlInputSource(sourceName)
return FileInputSource(sourceName)
@abstractmethod
def __str__(self) -> str:
pass
def __repr__(self) -> str:
return "{}({!r})".format(self.__class__.__name__, str(self))
def __hash__(self):
return hash(str(self))
def __eq__(self, other):
return str(self) == str(other)
@abstractmethod
def read(self) -> InputContent:
"""Fully reads the source."""
def hasDirectory(self) -> bool:
"""Only some InputSources have a directory."""
return False
def directory(self) -> str:
"""Suitable for passing to subprocess(cwd=)."""
raise TypeError("{} instances don't have directories.".format(type(self)))
def relative(self, _) -> Optional[InputSource]:
"""Resolves relativePath relative to this InputSource.
For example, InputSource("/foo/bar/baz.txt").relative("quux/fuzzy.txt")
will be InputSource("/foo/bar/quux/fuzzy.txt").
If this source type can't find others relative to itself, returns None.
"""
return None
def mtime(self) -> Optional[float]:
"""Returns the last modification time of this source, if that's known."""
return None
def cheaplyExists(self, _) -> Optional[bool]:
"""If it's cheap to determine, returns whether relativePath exists.
Otherwise, returns None.
"""
return None
def __getattr__(self, name):
"""Hack to make pylint happy, since all the attrs are defined
on the subclasses that __new__ dynamically dispatches to.
See https://stackoverflow.com/a/60731663/455535
"""
print(f"No member '{name}' contained in InputSource.")
return ""
class StdinInputSource(InputSource):
def __init__(self, sourceName: str):
assert sourceName == "-"
self.type = "stdin"
self.sourceName = sourceName
self.content = None
def __str__(self) -> str:
return "-"
def read(self) -> InputContent:
return InputContent(sys.stdin.readlines(), None)
class UrlInputSource(InputSource):
def __init__(self, sourceName: str):
assert sourceName.startswith("https:")
self.sourceName = sourceName
self.type = "url"
def __str__(self) -> str:
return self.sourceName
@tenacity.retry(
reraise=True,
stop=tenacity.stop_after_attempt(3),
wait=tenacity.wait_random(1, 2),
)
def _fetch(self):
response = requests.get(self.sourceName, timeout=10)
if response.status_code == 404:
# This matches the OSErrors expected by older uses of
# FileInputSource. It skips the retry, since the server has given us
# a concrete, expected answer.
raise FileNotFoundError(errno.ENOENT, response.text, self.sourceName)
response.raise_for_status()
return response
def read(self) -> InputContent:
response = self._fetch()
date = None
if "Date" in response.headers:
# Use the response's Date header, although servers don't always set
# this according to the last change to the file.
date = email.utils.parsedate_to_datetime(response.headers["Date"]).date()
return InputContent(response.text.splitlines(True), date)
def relative(self, relativePath) -> UrlInputSource:
return UrlInputSource(urllib.parse.urljoin(self.sourceName, relativePath))
class FileInputSource(InputSource):
def __init__(self, sourceName: str):
self.sourceName = sourceName
self.type = "file"
self.content = None
def __str__(self) -> str:
return self.sourceName
def read(self) -> InputContent:
with open(self.sourceName, encoding="utf-8") as f:
return InputContent(
f.readlines(),
datetime.fromtimestamp(os.path.getmtime(self.sourceName)).date(),
)
def hasDirectory(self) -> bool:
return True
def directory(self) -> str:
return os.path.dirname(os.path.abspath(self.sourceName))
def relative(self, relativePath) -> FileInputSource:
return FileInputSource(os.path.join(self.directory(), relativePath))
def cheaplyExists(self, relativePath) -> bool:
return os.access(self.relative(relativePath).sourceName, os.R_OK)
def mtime(self) -> Optional[float]:
"""Returns the last modification time of this file, or None if it doesn't exist."""
try:
return os.stat(self.sourceName).st_mtime
except FileNotFoundError:
return None
| from __future__ import annotations
import email.utils
import errno
import os
import sys
import urllib.parse
from abc import abstractmethod
from datetime import datetime
from typing import List, Optional
import attr
import requests
import tenacity
from . import config
from .Line import Line
@attr.s(auto_attribs=True)
class InputContent:
rawLines: List[str]
date: Optional[datetime.date]
@property
def lines(self) -> List[Line]:
return [Line(i, line) for i, line in enumerate(self.rawLines, 1)]
@property
def content(self) -> str:
return "".join(self.rawLines)
class InputSource:
"""Represents a thing that can produce specification input text.
Input can be read from stdin ("-"), an HTTPS URL, or a file. Other
InputSources can be found relative to URLs and files, and there's a context
manager for temporarily switching to the directory of a file InputSource.
"""
def __new__(cls, sourceName: str, **kwargs):
"""Dispatches to the right subclass."""
if cls != InputSource:
# Only take control of calls to InputSource(...) itself.
return super().__new__(cls)
if sourceName == "-":
return StdinInputSource(sourceName, **kwargs)
if sourceName.startswith("https:"):
return UrlInputSource(sourceName, **kwargs)
return FileInputSource(sourceName, **kwargs)
@abstractmethod
def __str__(self) -> str:
pass
def __repr__(self) -> str:
return "{}({!r})".format(self.__class__.__name__, str(self))
def __hash__(self):
return hash(str(self))
def __eq__(self, other):
return str(self) == str(other)
@abstractmethod
def read(self) -> InputContent:
"""Fully reads the source."""
def hasDirectory(self) -> bool:
"""Only some InputSources have a directory."""
return False
def directory(self) -> str:
"""Suitable for passing to subprocess(cwd=)."""
raise TypeError("{} instances don't have directories.".format(type(self)))
def relative(self, _) -> Optional[InputSource]:
"""Resolves relativePath relative to this InputSource.
For example, InputSource("/foo/bar/baz.txt").relative("quux/fuzzy.txt")
will be InputSource("/foo/bar/quux/fuzzy.txt").
If this source type can't find others relative to itself, returns None.
"""
return None
def mtime(self) -> Optional[float]:
"""Returns the last modification time of this source, if that's known."""
return None
def cheaplyExists(self, _) -> Optional[bool]:
"""If it's cheap to determine, returns whether relativePath exists.
Otherwise, returns None.
"""
return None
def __getattr__(self, name):
"""Hack to make pylint happy, since all the attrs are defined
on the subclasses that __new__ dynamically dispatches to.
See https://stackoverflow.com/a/60731663/455535
"""
print(f"No member '{name}' contained in InputSource.")
return ""
class StdinInputSource(InputSource):
def __init__(self, sourceName: str):
assert sourceName == "-"
self.type = "stdin"
self.sourceName = sourceName
self.content = None
def __str__(self) -> str:
return "-"
def read(self) -> InputContent:
return InputContent(sys.stdin.readlines(), None)
class UrlInputSource(InputSource):
def __init__(self, sourceName: str):
assert sourceName.startswith("https:")
self.sourceName = sourceName
self.type = "url"
def __str__(self) -> str:
return self.sourceName
@tenacity.retry(
reraise=True,
stop=tenacity.stop_after_attempt(3),
wait=tenacity.wait_random(1, 2),
)
def _fetch(self):
response = requests.get(self.sourceName, timeout=10)
if response.status_code == 404:
# This matches the OSErrors expected by older uses of
# FileInputSource. It skips the retry, since the server has given us
# a concrete, expected answer.
raise FileNotFoundError(errno.ENOENT, response.text, self.sourceName)
response.raise_for_status()
return response
def read(self) -> InputContent:
response = self._fetch()
date = None
if "Date" in response.headers:
# Use the response's Date header, although servers don't always set
# this according to the last change to the file.
date = email.utils.parsedate_to_datetime(response.headers["Date"]).date()
return InputContent(response.text.splitlines(True), date)
def relative(self, relativePath) -> UrlInputSource:
return UrlInputSource(urllib.parse.urljoin(self.sourceName, relativePath))
class FileInputSource(InputSource):
def __init__(self, sourceName: str, *, chroot: bool, chrootPath: Optional[str] = None):
self.sourceName = sourceName
self.chrootPath = chrootPath
self.type = "file"
self.content = None
if chroot and self.chrootPath is None:
self.chrootPath = self.directory()
if self.chrootPath is not None:
self.sourceName = config.chrootPath(self.chrootPath, self.sourceName)
def __str__(self) -> str:
return self.sourceName
def read(self) -> InputContent:
with open(self.sourceName, encoding="utf-8") as f:
return InputContent(
f.readlines(),
datetime.fromtimestamp(os.path.getmtime(self.sourceName)).date(),
)
def hasDirectory(self) -> bool:
return True
def directory(self) -> str:
return os.path.dirname(os.path.abspath(self.sourceName))
def relative(self, relativePath) -> FileInputSource:
return FileInputSource(os.path.join(self.directory(), relativePath), chroot=False, chrootPath=self.chrootPath)
def cheaplyExists(self, relativePath) -> bool:
return os.access(self.relative(relativePath).sourceName, os.R_OK)
def mtime(self) -> Optional[float]:
"""Returns the last modification time of this file, or None if it doesn't exist."""
try:
return os.stat(self.sourceName).st_mtime
except FileNotFoundError:
return None
| path_disclosure | {
"code": [
" def __new__(cls, sourceName: str):",
" return StdinInputSource(sourceName)",
" return UrlInputSource(sourceName)",
" return FileInputSource(sourceName)",
" def __init__(self, sourceName: str):",
" return FileInputSource(os.path.join(self.directory(), relativePath))"
],
"line_no": [
41,
48,
50,
51,
160,
182
]
} | {
"code": [
"from . import config",
" return StdinInputSource(sourceName, **kwargs)",
" return UrlInputSource(sourceName, **kwargs)",
" def __init__(self, sourceName: str, *, chroot: bool, chrootPath: Optional[str] = None):",
" self.chrootPath = chrootPath",
" self.chrootPath = self.directory()",
" if self.chrootPath is not None:",
" self.sourceName = config.chrootPath(self.chrootPath, self.sourceName)",
" return FileInputSource(os.path.join(self.directory(), relativePath), chroot=False, chrootPath=self.chrootPath)"
],
"line_no": [
16,
49,
51,
161,
163,
168,
169,
170,
189
]
} | from __future__ import annotations
import email.utils
import errno
import os
import sys
import urllib.parse
from abc import abstractmethod
from datetime import .datetime
from typing import List, Optional
import attr
import requests
import tenacity
from .Line import Line
@attr.s(auto_attribs=True)
class CLASS_0:
rawLines: List[str]
VAR_7: Optional[datetime.date]
@property
def FUNC_0(self) -> List[Line]:
return [Line(i, line) for i, line in enumerate(self.rawLines, 1)]
@property
def FUNC_1(self) -> str:
return "".join(self.rawLines)
class CLASS_1:
def __new__(VAR_0, VAR_1: str):
if VAR_0 != CLASS_1:
return super().__new__(VAR_0)
if VAR_1 == "-":
return CLASS_2(VAR_1)
if VAR_1.startswith("https:"):
return CLASS_3(VAR_1)
return CLASS_4(VAR_1)
@abstractmethod
def __str__(self) -> str:
pass
def __repr__(self) -> str:
return "{}({!r})".format(self.__class__.__name__, str(self))
def __hash__(self):
return hash(str(self))
def __eq__(self, VAR_2):
return str(self) == str(VAR_2)
@abstractmethod
def FUNC_2(self) -> CLASS_0:
def FUNC_3(self) -> bool:
return False
def FUNC_4(self) -> str:
raise TypeError("{} instances don't have directories.".format(type(self)))
def FUNC_5(self, VAR_3) -> Optional[CLASS_1]:
return None
def FUNC_6(self) -> Optional[float]:
return None
def FUNC_7(self, VAR_3) -> Optional[bool]:
return None
def __getattr__(self, VAR_4):
print(f"No member '{VAR_4}' contained in CLASS_1.")
return ""
class CLASS_2(CLASS_1):
def __init__(self, VAR_1: str):
assert VAR_1 == "-"
self.type = "stdin"
self.sourceName = VAR_1
self.content = None
def __str__(self) -> str:
return "-"
def FUNC_2(self) -> CLASS_0:
return CLASS_0(sys.stdin.readlines(), None)
class CLASS_3(CLASS_1):
def __init__(self, VAR_1: str):
assert VAR_1.startswith("https:")
self.sourceName = VAR_1
self.type = "url"
def __str__(self) -> str:
return self.sourceName
@tenacity.retry(
reraise=True,
stop=tenacity.stop_after_attempt(3),
wait=tenacity.wait_random(1, 2),
)
def FUNC_8(self):
VAR_6 = requests.get(self.sourceName, timeout=10)
if VAR_6.status_code == 404:
raise FileNotFoundError(errno.ENOENT, VAR_6.text, self.sourceName)
VAR_6.raise_for_status()
return VAR_6
def FUNC_2(self) -> CLASS_0:
VAR_6 = self._fetch()
VAR_7 = None
if "Date" in VAR_6.headers:
VAR_7 = email.utils.parsedate_to_datetime(VAR_6.headers["Date"]).date()
return CLASS_0(VAR_6.text.splitlines(True), VAR_7)
def FUNC_5(self, VAR_5) -> CLASS_3:
return CLASS_3(urllib.parse.urljoin(self.sourceName, VAR_5))
class CLASS_4(CLASS_1):
def __init__(self, VAR_1: str):
self.sourceName = VAR_1
self.type = "file"
self.content = None
def __str__(self) -> str:
return self.sourceName
def FUNC_2(self) -> CLASS_0:
with open(self.sourceName, encoding="utf-8") as f:
return CLASS_0(
f.readlines(),
datetime.fromtimestamp(os.path.getmtime(self.sourceName)).date(),
)
def FUNC_3(self) -> bool:
return True
def FUNC_4(self) -> str:
return os.path.dirname(os.path.abspath(self.sourceName))
def FUNC_5(self, VAR_5) -> CLASS_4:
return CLASS_4(os.path.join(self.directory(), VAR_5))
def FUNC_7(self, VAR_5) -> bool:
return os.access(self.relative(VAR_5).sourceName, os.R_OK)
def FUNC_6(self) -> Optional[float]:
try:
return os.stat(self.sourceName).st_mtime
except FileNotFoundError:
return None
| from __future__ import annotations
import email.utils
import errno
import os
import sys
import urllib.parse
from abc import abstractmethod
from datetime import .datetime
from typing import List, Optional
import attr
import requests
import tenacity
from . import config
from .Line import Line
@attr.s(auto_attribs=True)
class CLASS_0:
rawLines: List[str]
VAR_10: Optional[datetime.date]
@property
def FUNC_0(self) -> List[Line]:
return [Line(i, line) for i, line in enumerate(self.rawLines, 1)]
@property
def FUNC_1(self) -> str:
return "".join(self.rawLines)
class CLASS_1:
def __new__(VAR_0, VAR_1: str, **VAR_2):
if VAR_0 != CLASS_1:
return super().__new__(VAR_0)
if VAR_1 == "-":
return CLASS_2(VAR_1, **VAR_2)
if VAR_1.startswith("https:"):
return CLASS_3(VAR_1, **VAR_2)
return CLASS_4(VAR_1, **VAR_2)
@abstractmethod
def __str__(self) -> str:
pass
def __repr__(self) -> str:
return "{}({!r})".format(self.__class__.__name__, str(self))
def __hash__(self):
return hash(str(self))
def __eq__(self, VAR_3):
return str(self) == str(VAR_3)
@abstractmethod
def FUNC_2(self) -> CLASS_0:
def FUNC_3(self) -> bool:
return False
def FUNC_4(self) -> str:
raise TypeError("{} instances don't have directories.".format(type(self)))
def FUNC_5(self, VAR_4) -> Optional[CLASS_1]:
return None
def FUNC_6(self) -> Optional[float]:
return None
def FUNC_7(self, VAR_4) -> Optional[bool]:
return None
def __getattr__(self, VAR_5):
print(f"No member '{VAR_5}' contained in CLASS_1.")
return ""
class CLASS_2(CLASS_1):
def __init__(self, VAR_1: str):
assert VAR_1 == "-"
self.type = "stdin"
self.sourceName = VAR_1
self.content = None
def __str__(self) -> str:
return "-"
def FUNC_2(self) -> CLASS_0:
return CLASS_0(sys.stdin.readlines(), None)
class CLASS_3(CLASS_1):
def __init__(self, VAR_1: str):
assert VAR_1.startswith("https:")
self.sourceName = VAR_1
self.type = "url"
def __str__(self) -> str:
return self.sourceName
@tenacity.retry(
reraise=True,
stop=tenacity.stop_after_attempt(3),
wait=tenacity.wait_random(1, 2),
)
def FUNC_8(self):
VAR_9 = requests.get(self.sourceName, timeout=10)
if VAR_9.status_code == 404:
raise FileNotFoundError(errno.ENOENT, VAR_9.text, self.sourceName)
VAR_9.raise_for_status()
return VAR_9
def FUNC_2(self) -> CLASS_0:
VAR_9 = self._fetch()
VAR_10 = None
if "Date" in VAR_9.headers:
VAR_10 = email.utils.parsedate_to_datetime(VAR_9.headers["Date"]).date()
return CLASS_0(VAR_9.text.splitlines(True), VAR_10)
def FUNC_5(self, VAR_6) -> CLASS_3:
return CLASS_3(urllib.parse.urljoin(self.sourceName, VAR_6))
class CLASS_4(CLASS_1):
def __init__(self, VAR_1: str, *, VAR_7: bool, VAR_8: Optional[str] = None):
self.sourceName = VAR_1
self.chrootPath = VAR_8
self.type = "file"
self.content = None
if VAR_7 and self.chrootPath is None:
self.chrootPath = self.directory()
if self.chrootPath is not None:
self.sourceName = config.chrootPath(self.chrootPath, self.sourceName)
def __str__(self) -> str:
return self.sourceName
def FUNC_2(self) -> CLASS_0:
with open(self.sourceName, encoding="utf-8") as f:
return CLASS_0(
f.readlines(),
datetime.fromtimestamp(os.path.getmtime(self.sourceName)).date(),
)
def FUNC_3(self) -> bool:
return True
def FUNC_4(self) -> str:
return os.path.dirname(os.path.abspath(self.sourceName))
def FUNC_5(self, VAR_6) -> CLASS_4:
return CLASS_4(os.path.join(self.directory(), VAR_6), VAR_7=False, VAR_8=self.chrootPath)
def FUNC_7(self, VAR_6) -> bool:
return os.access(self.relative(VAR_6).sourceName, os.R_OK)
def FUNC_6(self) -> Optional[float]:
try:
return os.stat(self.sourceName).st_mtime
except FileNotFoundError:
return None
| [
2,
11,
15,
17,
18,
23,
27,
31,
32,
35,
40,
44,
46,
52,
56,
59,
62,
65,
69,
73,
77,
80,
83,
87,
91,
94,
98,
106,
107,
114,
117,
120,
121,
127,
130,
139,
140,
141,
145,
150,
151,
154,
157,
158,
164,
167,
174,
177,
180,
183,
186,
193,
34,
35,
36,
37,
38,
39,
42,
68,
71,
75,
79,
80,
81,
82,
83,
84,
85,
89,
93,
94,
95,
96,
100,
101,
102,
103,
188
] | [
2,
11,
15,
18,
19,
24,
28,
32,
33,
36,
41,
45,
47,
53,
57,
60,
63,
66,
70,
74,
78,
81,
84,
88,
92,
95,
99,
107,
108,
115,
118,
121,
122,
128,
131,
140,
141,
142,
146,
151,
152,
155,
158,
159,
166,
171,
174,
181,
184,
187,
190,
193,
200,
35,
36,
37,
38,
39,
40,
43,
69,
72,
76,
80,
81,
82,
83,
84,
85,
86,
90,
94,
95,
96,
97,
101,
102,
103,
104,
195
] |
0CWE-22
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Proxy AMI-related calls from cloud controller to objectstore service."""
import binascii
import os
import shutil
import tarfile
import tempfile
from xml.etree import ElementTree
import boto.s3.connection
import eventlet
from nova import crypto
import nova.db.api
from nova import exception
from nova import flags
from nova import image
from nova import log as logging
from nova import utils
from nova.api.ec2 import ec2utils
LOG = logging.getLogger("nova.image.s3")
FLAGS = flags.FLAGS
flags.DEFINE_string('image_decryption_dir', '/tmp',
'parent dir for tempdir used for image decryption')
flags.DEFINE_string('s3_access_key', 'notchecked',
'access key to use for s3 server for images')
flags.DEFINE_string('s3_secret_key', 'notchecked',
'secret key to use for s3 server for images')
class S3ImageService(object):
"""Wraps an existing image service to support s3 based register."""
def __init__(self, service=None, *args, **kwargs):
self.service = service or image.get_default_image_service()
self.service.__init__(*args, **kwargs)
def get_image_uuid(self, context, image_id):
return nova.db.api.s3_image_get(context, image_id)['uuid']
def get_image_id(self, context, image_uuid):
return nova.db.api.s3_image_get_by_uuid(context, image_uuid)['id']
def _create_image_id(self, context, image_uuid):
return nova.db.api.s3_image_create(context, image_uuid)['id']
def _translate_uuids_to_ids(self, context, images):
return [self._translate_uuid_to_id(context, img) for img in images]
def _translate_uuid_to_id(self, context, image):
def _find_or_create(image_uuid):
if image_uuid is None:
return
try:
return self.get_image_id(context, image_uuid)
except exception.NotFound:
return self._create_image_id(context, image_uuid)
image_copy = image.copy()
try:
image_id = image_copy['id']
except KeyError:
pass
else:
image_copy['id'] = _find_or_create(image_id)
for prop in ['kernel_id', 'ramdisk_id']:
try:
image_uuid = image_copy['properties'][prop]
except (KeyError, ValueError):
pass
else:
image_copy['properties'][prop] = _find_or_create(image_uuid)
return image_copy
def create(self, context, metadata, data=None):
"""Create an image.
metadata['properties'] should contain image_location.
"""
image = self._s3_create(context, metadata)
return image
def delete(self, context, image_id):
image_uuid = self.get_image_uuid(context, image_id)
self.service.delete(context, image_uuid)
def update(self, context, image_id, metadata, data=None):
image_uuid = self.get_image_uuid(context, image_id)
image = self.service.update(context, image_uuid, metadata, data)
return self._translate_uuid_to_id(context, image)
def index(self, context):
#NOTE(bcwaldon): sort asc to make sure we assign lower ids
# to older images
images = self.service.index(context, sort_dir='asc')
return self._translate_uuids_to_ids(context, images)
def detail(self, context):
#NOTE(bcwaldon): sort asc to make sure we assign lower ids
# to older images
images = self.service.detail(context, sort_dir='asc')
return self._translate_uuids_to_ids(context, images)
def show(self, context, image_id):
image_uuid = self.get_image_uuid(context, image_id)
image = self.service.show(context, image_uuid)
return self._translate_uuid_to_id(context, image)
def show_by_name(self, context, name):
image = self.service.show_by_name(context, name)
return self._translate_uuid_to_id(context, image)
def get(self, context, image_id):
image_uuid = self.get_image_uuid(context, image_id)
return self.get(self, context, image_uuid)
@staticmethod
def _conn(context):
# NOTE(vish): access and secret keys for s3 server are not
# checked in nova-objectstore
access = FLAGS.s3_access_key
secret = FLAGS.s3_secret_key
calling = boto.s3.connection.OrdinaryCallingFormat()
return boto.s3.connection.S3Connection(aws_access_key_id=access,
aws_secret_access_key=secret,
is_secure=False,
calling_format=calling,
port=FLAGS.s3_port,
host=FLAGS.s3_host)
@staticmethod
def _download_file(bucket, filename, local_dir):
key = bucket.get_key(filename)
local_filename = os.path.join(local_dir, filename)
key.get_contents_to_filename(local_filename)
return local_filename
def _s3_parse_manifest(self, context, metadata, manifest):
manifest = ElementTree.fromstring(manifest)
image_format = 'ami'
image_type = 'machine'
try:
kernel_id = manifest.find('machine_configuration/kernel_id').text
if kernel_id == 'true':
image_format = 'aki'
image_type = 'kernel'
kernel_id = None
except Exception:
kernel_id = None
try:
ramdisk_id = manifest.find('machine_configuration/ramdisk_id').text
if ramdisk_id == 'true':
image_format = 'ari'
image_type = 'ramdisk'
ramdisk_id = None
except Exception:
ramdisk_id = None
try:
arch = manifest.find('machine_configuration/architecture').text
except Exception:
arch = 'x86_64'
# NOTE(yamahata):
# EC2 ec2-budlne-image --block-device-mapping accepts
# <virtual name>=<device name> where
# virtual name = {ami, root, swap, ephemeral<N>}
# where N is no negative integer
# device name = the device name seen by guest kernel.
# They are converted into
# block_device_mapping/mapping/{virtual, device}
#
# Do NOT confuse this with ec2-register's block device mapping
# argument.
mappings = []
try:
block_device_mapping = manifest.findall('machine_configuration/'
'block_device_mapping/'
'mapping')
for bdm in block_device_mapping:
mappings.append({'virtual': bdm.find('virtual').text,
'device': bdm.find('device').text})
except Exception:
mappings = []
properties = metadata['properties']
properties['project_id'] = context.project_id
properties['architecture'] = arch
def _translate_dependent_image_id(image_key, image_id):
image_id = ec2utils.ec2_id_to_id(image_id)
image_uuid = self.get_image_uuid(context, image_id)
properties['image_id'] = image_uuid
if kernel_id:
_translate_dependent_image_id('kernel_id', kernel_id)
if ramdisk_id:
_translate_dependent_image_id('ramdisk_id', ramdisk_id)
if mappings:
properties['mappings'] = mappings
metadata.update({'disk_format': image_format,
'container_format': image_format,
'status': 'queued',
'is_public': False,
'properties': properties})
metadata['properties']['image_state'] = 'pending'
#TODO(bcwaldon): right now, this removes user-defined ids.
# We need to re-enable this.
image_id = metadata.pop('id', None)
image = self.service.create(context, metadata)
# extract the new uuid and generate an int id to present back to user
image_uuid = image['id']
image['id'] = self._create_image_id(context, image_uuid)
# return image_uuid so the caller can still make use of image_service
return manifest, image, image_uuid
def _s3_create(self, context, metadata):
"""Gets a manifext from s3 and makes an image."""
image_path = tempfile.mkdtemp(dir=FLAGS.image_decryption_dir)
image_location = metadata['properties']['image_location']
bucket_name = image_location.split('/')[0]
manifest_path = image_location[len(bucket_name) + 1:]
bucket = self._conn(context).get_bucket(bucket_name)
key = bucket.get_key(manifest_path)
manifest = key.get_contents_as_string()
manifest, image, image_uuid = self._s3_parse_manifest(context,
metadata,
manifest)
def delayed_create():
"""This handles the fetching and decrypting of the part files."""
log_vars = {'image_location': image_location,
'image_path': image_path}
metadata['properties']['image_state'] = 'downloading'
self.service.update(context, image_uuid, metadata)
try:
parts = []
elements = manifest.find('image').getiterator('filename')
for fn_element in elements:
part = self._download_file(bucket,
fn_element.text,
image_path)
parts.append(part)
# NOTE(vish): this may be suboptimal, should we use cat?
enc_filename = os.path.join(image_path, 'image.encrypted')
with open(enc_filename, 'w') as combined:
for filename in parts:
with open(filename) as part:
shutil.copyfileobj(part, combined)
except Exception:
LOG.exception(_("Failed to download %(image_location)s "
"to %(image_path)s"), log_vars)
metadata['properties']['image_state'] = 'failed_download'
self.service.update(context, image_uuid, metadata)
return
metadata['properties']['image_state'] = 'decrypting'
self.service.update(context, image_uuid, metadata)
try:
hex_key = manifest.find('image/ec2_encrypted_key').text
encrypted_key = binascii.a2b_hex(hex_key)
hex_iv = manifest.find('image/ec2_encrypted_iv').text
encrypted_iv = binascii.a2b_hex(hex_iv)
# FIXME(vish): grab key from common service so this can run on
# any host.
cloud_pk = crypto.key_path(context.project_id)
dec_filename = os.path.join(image_path, 'image.tar.gz')
self._decrypt_image(enc_filename, encrypted_key,
encrypted_iv, cloud_pk,
dec_filename)
except Exception:
LOG.exception(_("Failed to decrypt %(image_location)s "
"to %(image_path)s"), log_vars)
metadata['properties']['image_state'] = 'failed_decrypt'
self.service.update(context, image_uuid, metadata)
return
metadata['properties']['image_state'] = 'untarring'
self.service.update(context, image_uuid, metadata)
try:
unz_filename = self._untarzip_image(image_path, dec_filename)
except Exception:
LOG.exception(_("Failed to untar %(image_location)s "
"to %(image_path)s"), log_vars)
metadata['properties']['image_state'] = 'failed_untar'
self.service.update(context, image_uuid, metadata)
return
metadata['properties']['image_state'] = 'uploading'
self.service.update(context, image_uuid, metadata)
try:
with open(unz_filename) as image_file:
self.service.update(context, image_uuid,
metadata, image_file)
except Exception:
LOG.exception(_("Failed to upload %(image_location)s "
"to %(image_path)s"), log_vars)
metadata['properties']['image_state'] = 'failed_upload'
self.service.update(context, image_uuid, metadata)
return
metadata['properties']['image_state'] = 'available'
metadata['status'] = 'active'
self.service.update(context, image_uuid, metadata)
shutil.rmtree(image_path)
eventlet.spawn_n(delayed_create)
return image
@staticmethod
def _decrypt_image(encrypted_filename, encrypted_key, encrypted_iv,
cloud_private_key, decrypted_filename):
key, err = utils.execute('openssl',
'rsautl',
'-decrypt',
'-inkey', '%s' % cloud_private_key,
process_input=encrypted_key,
check_exit_code=False)
if err:
raise exception.Error(_('Failed to decrypt private key: %s')
% err)
iv, err = utils.execute('openssl',
'rsautl',
'-decrypt',
'-inkey', '%s' % cloud_private_key,
process_input=encrypted_iv,
check_exit_code=False)
if err:
raise exception.Error(_('Failed to decrypt initialization '
'vector: %s') % err)
_out, err = utils.execute('openssl', 'enc',
'-d', '-aes-128-cbc',
'-in', '%s' % (encrypted_filename,),
'-K', '%s' % (key,),
'-iv', '%s' % (iv,),
'-out', '%s' % (decrypted_filename,),
check_exit_code=False)
if err:
raise exception.Error(_('Failed to decrypt image file '
'%(image_file)s: %(err)s') %
{'image_file': encrypted_filename,
'err': err})
@staticmethod
def _untarzip_image(path, filename):
tar_file = tarfile.open(filename, 'r|gz')
tar_file.extractall(path)
image_file = tar_file.getnames()[0]
tar_file.close()
return os.path.join(path, image_file)
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Proxy AMI-related calls from cloud controller to objectstore service."""
import binascii
import os
import shutil
import tarfile
import tempfile
from xml.etree import ElementTree
import boto.s3.connection
import eventlet
from nova import crypto
import nova.db.api
from nova import exception
from nova import flags
from nova import image
from nova import log as logging
from nova import utils
from nova.api.ec2 import ec2utils
LOG = logging.getLogger("nova.image.s3")
FLAGS = flags.FLAGS
flags.DEFINE_string('image_decryption_dir', '/tmp',
'parent dir for tempdir used for image decryption')
flags.DEFINE_string('s3_access_key', 'notchecked',
'access key to use for s3 server for images')
flags.DEFINE_string('s3_secret_key', 'notchecked',
'secret key to use for s3 server for images')
class S3ImageService(object):
"""Wraps an existing image service to support s3 based register."""
def __init__(self, service=None, *args, **kwargs):
self.service = service or image.get_default_image_service()
self.service.__init__(*args, **kwargs)
def get_image_uuid(self, context, image_id):
return nova.db.api.s3_image_get(context, image_id)['uuid']
def get_image_id(self, context, image_uuid):
return nova.db.api.s3_image_get_by_uuid(context, image_uuid)['id']
def _create_image_id(self, context, image_uuid):
return nova.db.api.s3_image_create(context, image_uuid)['id']
def _translate_uuids_to_ids(self, context, images):
return [self._translate_uuid_to_id(context, img) for img in images]
def _translate_uuid_to_id(self, context, image):
def _find_or_create(image_uuid):
if image_uuid is None:
return
try:
return self.get_image_id(context, image_uuid)
except exception.NotFound:
return self._create_image_id(context, image_uuid)
image_copy = image.copy()
try:
image_id = image_copy['id']
except KeyError:
pass
else:
image_copy['id'] = _find_or_create(image_id)
for prop in ['kernel_id', 'ramdisk_id']:
try:
image_uuid = image_copy['properties'][prop]
except (KeyError, ValueError):
pass
else:
image_copy['properties'][prop] = _find_or_create(image_uuid)
return image_copy
def create(self, context, metadata, data=None):
"""Create an image.
metadata['properties'] should contain image_location.
"""
image = self._s3_create(context, metadata)
return image
def delete(self, context, image_id):
image_uuid = self.get_image_uuid(context, image_id)
self.service.delete(context, image_uuid)
def update(self, context, image_id, metadata, data=None):
image_uuid = self.get_image_uuid(context, image_id)
image = self.service.update(context, image_uuid, metadata, data)
return self._translate_uuid_to_id(context, image)
def index(self, context):
#NOTE(bcwaldon): sort asc to make sure we assign lower ids
# to older images
images = self.service.index(context, sort_dir='asc')
return self._translate_uuids_to_ids(context, images)
def detail(self, context):
#NOTE(bcwaldon): sort asc to make sure we assign lower ids
# to older images
images = self.service.detail(context, sort_dir='asc')
return self._translate_uuids_to_ids(context, images)
def show(self, context, image_id):
image_uuid = self.get_image_uuid(context, image_id)
image = self.service.show(context, image_uuid)
return self._translate_uuid_to_id(context, image)
def show_by_name(self, context, name):
image = self.service.show_by_name(context, name)
return self._translate_uuid_to_id(context, image)
def get(self, context, image_id):
image_uuid = self.get_image_uuid(context, image_id)
return self.get(self, context, image_uuid)
@staticmethod
def _conn(context):
# NOTE(vish): access and secret keys for s3 server are not
# checked in nova-objectstore
access = FLAGS.s3_access_key
secret = FLAGS.s3_secret_key
calling = boto.s3.connection.OrdinaryCallingFormat()
return boto.s3.connection.S3Connection(aws_access_key_id=access,
aws_secret_access_key=secret,
is_secure=False,
calling_format=calling,
port=FLAGS.s3_port,
host=FLAGS.s3_host)
@staticmethod
def _download_file(bucket, filename, local_dir):
key = bucket.get_key(filename)
local_filename = os.path.join(local_dir, os.path.basename(filename))
key.get_contents_to_filename(local_filename)
return local_filename
def _s3_parse_manifest(self, context, metadata, manifest):
manifest = ElementTree.fromstring(manifest)
image_format = 'ami'
image_type = 'machine'
try:
kernel_id = manifest.find('machine_configuration/kernel_id').text
if kernel_id == 'true':
image_format = 'aki'
image_type = 'kernel'
kernel_id = None
except Exception:
kernel_id = None
try:
ramdisk_id = manifest.find('machine_configuration/ramdisk_id').text
if ramdisk_id == 'true':
image_format = 'ari'
image_type = 'ramdisk'
ramdisk_id = None
except Exception:
ramdisk_id = None
try:
arch = manifest.find('machine_configuration/architecture').text
except Exception:
arch = 'x86_64'
# NOTE(yamahata):
# EC2 ec2-budlne-image --block-device-mapping accepts
# <virtual name>=<device name> where
# virtual name = {ami, root, swap, ephemeral<N>}
# where N is no negative integer
# device name = the device name seen by guest kernel.
# They are converted into
# block_device_mapping/mapping/{virtual, device}
#
# Do NOT confuse this with ec2-register's block device mapping
# argument.
mappings = []
try:
block_device_mapping = manifest.findall('machine_configuration/'
'block_device_mapping/'
'mapping')
for bdm in block_device_mapping:
mappings.append({'virtual': bdm.find('virtual').text,
'device': bdm.find('device').text})
except Exception:
mappings = []
properties = metadata['properties']
properties['project_id'] = context.project_id
properties['architecture'] = arch
def _translate_dependent_image_id(image_key, image_id):
image_id = ec2utils.ec2_id_to_id(image_id)
image_uuid = self.get_image_uuid(context, image_id)
properties['image_id'] = image_uuid
if kernel_id:
_translate_dependent_image_id('kernel_id', kernel_id)
if ramdisk_id:
_translate_dependent_image_id('ramdisk_id', ramdisk_id)
if mappings:
properties['mappings'] = mappings
metadata.update({'disk_format': image_format,
'container_format': image_format,
'status': 'queued',
'is_public': False,
'properties': properties})
metadata['properties']['image_state'] = 'pending'
#TODO(bcwaldon): right now, this removes user-defined ids.
# We need to re-enable this.
image_id = metadata.pop('id', None)
image = self.service.create(context, metadata)
# extract the new uuid and generate an int id to present back to user
image_uuid = image['id']
image['id'] = self._create_image_id(context, image_uuid)
# return image_uuid so the caller can still make use of image_service
return manifest, image, image_uuid
def _s3_create(self, context, metadata):
"""Gets a manifext from s3 and makes an image."""
image_path = tempfile.mkdtemp(dir=FLAGS.image_decryption_dir)
image_location = metadata['properties']['image_location']
bucket_name = image_location.split('/')[0]
manifest_path = image_location[len(bucket_name) + 1:]
bucket = self._conn(context).get_bucket(bucket_name)
key = bucket.get_key(manifest_path)
manifest = key.get_contents_as_string()
manifest, image, image_uuid = self._s3_parse_manifest(context,
metadata,
manifest)
def delayed_create():
"""This handles the fetching and decrypting of the part files."""
log_vars = {'image_location': image_location,
'image_path': image_path}
metadata['properties']['image_state'] = 'downloading'
self.service.update(context, image_uuid, metadata)
try:
parts = []
elements = manifest.find('image').getiterator('filename')
for fn_element in elements:
part = self._download_file(bucket,
fn_element.text,
image_path)
parts.append(part)
# NOTE(vish): this may be suboptimal, should we use cat?
enc_filename = os.path.join(image_path, 'image.encrypted')
with open(enc_filename, 'w') as combined:
for filename in parts:
with open(filename) as part:
shutil.copyfileobj(part, combined)
except Exception:
LOG.exception(_("Failed to download %(image_location)s "
"to %(image_path)s"), log_vars)
metadata['properties']['image_state'] = 'failed_download'
self.service.update(context, image_uuid, metadata)
return
metadata['properties']['image_state'] = 'decrypting'
self.service.update(context, image_uuid, metadata)
try:
hex_key = manifest.find('image/ec2_encrypted_key').text
encrypted_key = binascii.a2b_hex(hex_key)
hex_iv = manifest.find('image/ec2_encrypted_iv').text
encrypted_iv = binascii.a2b_hex(hex_iv)
# FIXME(vish): grab key from common service so this can run on
# any host.
cloud_pk = crypto.key_path(context.project_id)
dec_filename = os.path.join(image_path, 'image.tar.gz')
self._decrypt_image(enc_filename, encrypted_key,
encrypted_iv, cloud_pk,
dec_filename)
except Exception:
LOG.exception(_("Failed to decrypt %(image_location)s "
"to %(image_path)s"), log_vars)
metadata['properties']['image_state'] = 'failed_decrypt'
self.service.update(context, image_uuid, metadata)
return
metadata['properties']['image_state'] = 'untarring'
self.service.update(context, image_uuid, metadata)
try:
unz_filename = self._untarzip_image(image_path, dec_filename)
except Exception:
LOG.exception(_("Failed to untar %(image_location)s "
"to %(image_path)s"), log_vars)
metadata['properties']['image_state'] = 'failed_untar'
self.service.update(context, image_uuid, metadata)
return
metadata['properties']['image_state'] = 'uploading'
self.service.update(context, image_uuid, metadata)
try:
with open(unz_filename) as image_file:
self.service.update(context, image_uuid,
metadata, image_file)
except Exception:
LOG.exception(_("Failed to upload %(image_location)s "
"to %(image_path)s"), log_vars)
metadata['properties']['image_state'] = 'failed_upload'
self.service.update(context, image_uuid, metadata)
return
metadata['properties']['image_state'] = 'available'
metadata['status'] = 'active'
self.service.update(context, image_uuid, metadata)
shutil.rmtree(image_path)
eventlet.spawn_n(delayed_create)
return image
@staticmethod
def _decrypt_image(encrypted_filename, encrypted_key, encrypted_iv,
cloud_private_key, decrypted_filename):
key, err = utils.execute('openssl',
'rsautl',
'-decrypt',
'-inkey', '%s' % cloud_private_key,
process_input=encrypted_key,
check_exit_code=False)
if err:
raise exception.Error(_('Failed to decrypt private key: %s')
% err)
iv, err = utils.execute('openssl',
'rsautl',
'-decrypt',
'-inkey', '%s' % cloud_private_key,
process_input=encrypted_iv,
check_exit_code=False)
if err:
raise exception.Error(_('Failed to decrypt initialization '
'vector: %s') % err)
_out, err = utils.execute('openssl', 'enc',
'-d', '-aes-128-cbc',
'-in', '%s' % (encrypted_filename,),
'-K', '%s' % (key,),
'-iv', '%s' % (iv,),
'-out', '%s' % (decrypted_filename,),
check_exit_code=False)
if err:
raise exception.Error(_('Failed to decrypt image file '
'%(image_file)s: %(err)s') %
{'image_file': encrypted_filename,
'err': err})
@staticmethod
def _test_for_malicious_tarball(path, filename):
"""Raises exception if extracting tarball would escape extract path"""
tar_file = tarfile.open(filename, 'r|gz')
for n in tar_file.getnames():
if not os.path.abspath(os.path.join(path, n)).startswith(path):
tar_file.close()
raise exception.Error(_('Unsafe filenames in image'))
tar_file.close()
@staticmethod
def _untarzip_image(path, filename):
S3ImageService._test_for_malicious_tarball(path, filename)
tar_file = tarfile.open(filename, 'r|gz')
tar_file.extractall(path)
image_file = tar_file.getnames()[0]
tar_file.close()
return os.path.join(path, image_file)
| path_disclosure | {
"code": [
" local_filename = os.path.join(local_dir, filename)"
],
"line_no": [
158
]
} | {
"code": [
" local_filename = os.path.join(local_dir, os.path.basename(filename))",
" @staticmethod",
" def _test_for_malicious_tarball(path, filename):",
" \"\"\"Raises exception if extracting tarball would escape extract path\"\"\"",
" tar_file = tarfile.open(filename, 'r|gz')",
" for n in tar_file.getnames():",
" if not os.path.abspath(os.path.join(path, n)).startswith(path):",
" tar_file.close()",
" tar_file.close()",
" S3ImageService._test_for_malicious_tarball(path, filename)"
],
"line_no": [
158,
390,
391,
392,
393,
394,
395,
396,
398,
402
]
} |
import binascii
import os
import shutil
import tarfile
import tempfile
from xml.etree import ElementTree
import boto.s3.connection
import eventlet
from nova import crypto
import nova.db.api
from nova import exception
from nova import flags
from nova import .image
from nova import log as logging
from nova import utils
from nova.api.ec2 import ec2utils
VAR_0 = logging.getLogger("nova.image.s3")
VAR_1 = flags.FLAGS
flags.DEFINE_string('image_decryption_dir', '/tmp',
'parent dir for tempdir used for VAR_9 decryption')
flags.DEFINE_string('s3_access_key', 'notchecked',
'access VAR_27 to use for s3 server for images')
flags.DEFINE_string('s3_secret_key', 'notchecked',
'secret VAR_27 to use for s3 server for images')
class CLASS_0(object):
def __init__(self, VAR_2=None, *VAR_3, **VAR_4):
self.service = VAR_2 or VAR_9.get_default_image_service()
self.service.__init__(*VAR_3, **VAR_4)
def FUNC_0(self, VAR_5, VAR_6):
return nova.db.api.s3_image_get(VAR_5, VAR_6)['uuid']
def FUNC_1(self, VAR_5, VAR_7):
return nova.db.api.s3_image_get_by_uuid(VAR_5, VAR_7)['id']
def FUNC_2(self, VAR_5, VAR_7):
return nova.db.api.s3_image_create(VAR_5, VAR_7)['id']
def FUNC_3(self, VAR_5, VAR_8):
return [self._translate_uuid_to_id(VAR_5, img) for img in VAR_8]
def FUNC_4(self, VAR_5, VAR_9):
def FUNC_19(VAR_7):
if VAR_7 is None:
return
try:
return self.get_image_id(VAR_5, VAR_7)
except exception.NotFound:
return self._create_image_id(VAR_5, VAR_7)
VAR_23 = VAR_9.copy()
try:
VAR_6 = VAR_23['id']
except KeyError:
pass
else:
VAR_23['id'] = FUNC_19(VAR_6)
for VAR_48 in ['kernel_id', 'ramdisk_id']:
try:
VAR_7 = VAR_23['properties'][VAR_48]
except (KeyError, ValueError):
pass
else:
VAR_23['properties'][VAR_48] = FUNC_19(VAR_7)
return VAR_23
def FUNC_5(self, VAR_5, VAR_10, VAR_11=None):
VAR_9 = self._s3_create(VAR_5, VAR_10)
return VAR_9
def FUNC_6(self, VAR_5, VAR_6):
VAR_7 = self.get_image_uuid(VAR_5, VAR_6)
self.service.delete(VAR_5, VAR_7)
def FUNC_7(self, VAR_5, VAR_6, VAR_10, VAR_11=None):
VAR_7 = self.get_image_uuid(VAR_5, VAR_6)
VAR_9 = self.service.update(VAR_5, VAR_7, VAR_10, VAR_11)
return self._translate_uuid_to_id(VAR_5, VAR_9)
def FUNC_8(self, VAR_5):
images = self.service.index(VAR_5, sort_dir='asc')
return self._translate_uuids_to_ids(VAR_5, VAR_8)
def FUNC_9(self, VAR_5):
images = self.service.detail(VAR_5, sort_dir='asc')
return self._translate_uuids_to_ids(VAR_5, VAR_8)
def FUNC_10(self, VAR_5, VAR_6):
VAR_7 = self.get_image_uuid(VAR_5, VAR_6)
VAR_9 = self.service.show(VAR_5, VAR_7)
return self._translate_uuid_to_id(VAR_5, VAR_9)
def FUNC_11(self, VAR_5, VAR_12):
VAR_9 = self.service.show_by_name(VAR_5, VAR_12)
return self._translate_uuid_to_id(VAR_5, VAR_9)
def FUNC_12(self, VAR_5, VAR_6):
VAR_7 = self.get_image_uuid(VAR_5, VAR_6)
return self.get(self, VAR_5, VAR_7)
@staticmethod
def FUNC_13(VAR_5):
VAR_24 = VAR_1.s3_access_key
VAR_25 = VAR_1.s3_secret_key
VAR_26 = boto.s3.connection.OrdinaryCallingFormat()
return boto.s3.connection.S3Connection(aws_access_key_id=VAR_24,
aws_secret_access_key=VAR_25,
is_secure=False,
calling_format=VAR_26,
port=VAR_1.s3_port,
host=VAR_1.s3_host)
@staticmethod
def FUNC_14(VAR_13, VAR_14, VAR_15):
VAR_27 = VAR_13.get_key(VAR_14)
VAR_28 = os.path.join(VAR_15, VAR_14)
VAR_27.get_contents_to_filename(VAR_28)
return VAR_28
def FUNC_15(self, VAR_5, VAR_10, VAR_16):
manifest = ElementTree.fromstring(VAR_16)
VAR_29 = 'ami'
VAR_30 = 'machine'
try:
VAR_43 = VAR_16.find('machine_configuration/kernel_id').text
if VAR_43 == 'true':
VAR_29 = 'aki'
VAR_30 = 'kernel'
VAR_43 = None
except Exception:
VAR_43 = None
try:
VAR_44 = VAR_16.find('machine_configuration/ramdisk_id').text
if VAR_44 == 'true':
VAR_29 = 'ari'
VAR_30 = 'ramdisk'
VAR_44 = None
except Exception:
VAR_44 = None
try:
VAR_45 = VAR_16.find('machine_configuration/architecture').text
except Exception:
VAR_45 = 'x86_64'
VAR_31 = []
try:
VAR_46 = VAR_16.findall('machine_configuration/'
'block_device_mapping/'
'mapping')
for bdm in VAR_46:
VAR_31.append({'virtual': bdm.find('virtual').text,
'device': bdm.find('device').text})
except Exception:
VAR_31 = []
VAR_32 = VAR_10['properties']
VAR_32['project_id'] = VAR_5.project_id
VAR_32['architecture'] = VAR_45
def FUNC_20(VAR_33, VAR_6):
VAR_6 = ec2utils.ec2_id_to_id(VAR_6)
VAR_7 = self.get_image_uuid(VAR_5, VAR_6)
VAR_32['image_id'] = VAR_7
if VAR_43:
FUNC_20('kernel_id', VAR_43)
if VAR_44:
FUNC_20('ramdisk_id', VAR_44)
if VAR_31:
VAR_32['mappings'] = VAR_31
VAR_10.update({'disk_format': VAR_29,
'container_format': VAR_29,
'status': 'queued',
'is_public': False,
'properties': VAR_32})
VAR_10['properties']['image_state'] = 'pending'
VAR_6 = VAR_10.pop('id', None)
VAR_9 = self.service.create(VAR_5, VAR_10)
VAR_7 = VAR_9['id']
VAR_9['id'] = self._create_image_id(VAR_5, VAR_7)
return VAR_16, VAR_9, VAR_7
def FUNC_16(self, VAR_5, VAR_10):
VAR_34 = tempfile.mkdtemp(dir=VAR_1.image_decryption_dir)
VAR_35 = VAR_10['properties']['image_location']
VAR_36 = VAR_35.split('/')[0]
VAR_37 = VAR_35[len(VAR_36) + 1:]
VAR_13 = self._conn(VAR_5).get_bucket(VAR_36)
VAR_27 = VAR_13.get_key(VAR_37)
VAR_16 = VAR_27.get_contents_as_string()
VAR_16, VAR_9, VAR_7 = self._s3_parse_manifest(VAR_5,
VAR_10,
VAR_16)
def FUNC_21():
VAR_47 = {'image_location': VAR_35,
'image_path': VAR_34}
VAR_10['properties']['image_state'] = 'downloading'
self.service.update(VAR_5, VAR_7, VAR_10)
try:
VAR_49 = []
VAR_50 = VAR_16.find('image').getiterator('filename')
for fn_element in VAR_50:
VAR_57 = self._download_file(VAR_13,
fn_element.text,
VAR_34)
VAR_49.append(VAR_57)
VAR_51 = os.path.join(VAR_34, 'image.encrypted')
with open(VAR_51, 'w') as combined:
for VAR_14 in VAR_49:
with open(VAR_14) as VAR_57:
shutil.copyfileobj(VAR_57, combined)
except Exception:
VAR_0.exception(_("Failed to download %(VAR_35)s "
"to %(VAR_34)s"), VAR_47)
VAR_10['properties']['image_state'] = 'failed_download'
self.service.update(VAR_5, VAR_7, VAR_10)
return
VAR_10['properties']['image_state'] = 'decrypting'
self.service.update(VAR_5, VAR_7, VAR_10)
try:
VAR_52 = VAR_16.find('image/ec2_encrypted_key').text
VAR_18 = binascii.a2b_hex(VAR_52)
VAR_53 = VAR_16.find('image/ec2_encrypted_iv').text
VAR_19 = binascii.a2b_hex(VAR_53)
VAR_54 = crypto.key_path(VAR_5.project_id)
VAR_55 = os.path.join(VAR_34, 'image.tar.gz')
self._decrypt_image(VAR_51, VAR_18,
VAR_19, VAR_54,
VAR_55)
except Exception:
VAR_0.exception(_("Failed to decrypt %(VAR_35)s "
"to %(VAR_34)s"), VAR_47)
VAR_10['properties']['image_state'] = 'failed_decrypt'
self.service.update(VAR_5, VAR_7, VAR_10)
return
VAR_10['properties']['image_state'] = 'untarring'
self.service.update(VAR_5, VAR_7, VAR_10)
try:
VAR_56 = self._untarzip_image(VAR_34, VAR_55)
except Exception:
VAR_0.exception(_("Failed to untar %(VAR_35)s "
"to %(VAR_34)s"), VAR_47)
VAR_10['properties']['image_state'] = 'failed_untar'
self.service.update(VAR_5, VAR_7, VAR_10)
return
VAR_10['properties']['image_state'] = 'uploading'
self.service.update(VAR_5, VAR_7, VAR_10)
try:
with open(VAR_56) as VAR_42:
self.service.update(VAR_5, VAR_7,
VAR_10, VAR_42)
except Exception:
VAR_0.exception(_("Failed to upload %(VAR_35)s "
"to %(VAR_34)s"), VAR_47)
VAR_10['properties']['image_state'] = 'failed_upload'
self.service.update(VAR_5, VAR_7, VAR_10)
return
VAR_10['properties']['image_state'] = 'available'
VAR_10['status'] = 'active'
self.service.update(VAR_5, VAR_7, VAR_10)
shutil.rmtree(VAR_34)
eventlet.spawn_n(FUNC_21)
return VAR_9
@staticmethod
def FUNC_17(VAR_17, VAR_18, VAR_19,
VAR_20, VAR_21):
VAR_27, VAR_38 = utils.execute('openssl',
'rsautl',
'-decrypt',
'-inkey', '%s' % VAR_20,
process_input=VAR_18,
check_exit_code=False)
if VAR_38:
raise exception.Error(_('Failed to decrypt private VAR_27: %s')
% VAR_38)
VAR_39, VAR_38 = utils.execute('openssl',
'rsautl',
'-decrypt',
'-inkey', '%s' % VAR_20,
process_input=VAR_19,
check_exit_code=False)
if VAR_38:
raise exception.Error(_('Failed to decrypt initialization '
'vector: %s') % VAR_38)
VAR_40, VAR_38 = utils.execute('openssl', 'enc',
'-d', '-aes-128-cbc',
'-in', '%s' % (VAR_17,),
'-K', '%s' % (VAR_27,),
'-iv', '%s' % (VAR_39,),
'-out', '%s' % (VAR_21,),
check_exit_code=False)
if VAR_38:
raise exception.Error(_('Failed to decrypt VAR_9 file '
'%(VAR_42)s: %(VAR_38)s') %
{'image_file': VAR_17,
'err': VAR_38})
@staticmethod
def FUNC_18(VAR_22, VAR_14):
VAR_41 = tarfile.open(VAR_14, 'r|gz')
VAR_41.extractall(VAR_22)
VAR_42 = VAR_41.getnames()[0]
VAR_41.close()
return os.path.join(VAR_22, VAR_42)
|
import binascii
import os
import shutil
import tarfile
import tempfile
from xml.etree import ElementTree
import boto.s3.connection
import eventlet
from nova import crypto
import nova.db.api
from nova import exception
from nova import flags
from nova import .image
from nova import log as logging
from nova import utils
from nova.api.ec2 import ec2utils
VAR_0 = logging.getLogger("nova.image.s3")
VAR_1 = flags.FLAGS
flags.DEFINE_string('image_decryption_dir', '/tmp',
'parent dir for tempdir used for VAR_9 decryption')
flags.DEFINE_string('s3_access_key', 'notchecked',
'access VAR_27 to use for s3 server for images')
flags.DEFINE_string('s3_secret_key', 'notchecked',
'secret VAR_27 to use for s3 server for images')
class CLASS_0(object):
def __init__(self, VAR_2=None, *VAR_3, **VAR_4):
self.service = VAR_2 or VAR_9.get_default_image_service()
self.service.__init__(*VAR_3, **VAR_4)
def FUNC_0(self, VAR_5, VAR_6):
return nova.db.api.s3_image_get(VAR_5, VAR_6)['uuid']
def FUNC_1(self, VAR_5, VAR_7):
return nova.db.api.s3_image_get_by_uuid(VAR_5, VAR_7)['id']
def FUNC_2(self, VAR_5, VAR_7):
return nova.db.api.s3_image_create(VAR_5, VAR_7)['id']
def FUNC_3(self, VAR_5, VAR_8):
return [self._translate_uuid_to_id(VAR_5, img) for img in VAR_8]
def FUNC_4(self, VAR_5, VAR_9):
def FUNC_20(VAR_7):
if VAR_7 is None:
return
try:
return self.get_image_id(VAR_5, VAR_7)
except exception.NotFound:
return self._create_image_id(VAR_5, VAR_7)
VAR_23 = VAR_9.copy()
try:
VAR_6 = VAR_23['id']
except KeyError:
pass
else:
VAR_23['id'] = FUNC_20(VAR_6)
for VAR_48 in ['kernel_id', 'ramdisk_id']:
try:
VAR_7 = VAR_23['properties'][VAR_48]
except (KeyError, ValueError):
pass
else:
VAR_23['properties'][VAR_48] = FUNC_20(VAR_7)
return VAR_23
def FUNC_5(self, VAR_5, VAR_10, VAR_11=None):
VAR_9 = self._s3_create(VAR_5, VAR_10)
return VAR_9
def FUNC_6(self, VAR_5, VAR_6):
VAR_7 = self.get_image_uuid(VAR_5, VAR_6)
self.service.delete(VAR_5, VAR_7)
def FUNC_7(self, VAR_5, VAR_6, VAR_10, VAR_11=None):
VAR_7 = self.get_image_uuid(VAR_5, VAR_6)
VAR_9 = self.service.update(VAR_5, VAR_7, VAR_10, VAR_11)
return self._translate_uuid_to_id(VAR_5, VAR_9)
def FUNC_8(self, VAR_5):
images = self.service.index(VAR_5, sort_dir='asc')
return self._translate_uuids_to_ids(VAR_5, VAR_8)
def FUNC_9(self, VAR_5):
images = self.service.detail(VAR_5, sort_dir='asc')
return self._translate_uuids_to_ids(VAR_5, VAR_8)
def FUNC_10(self, VAR_5, VAR_6):
VAR_7 = self.get_image_uuid(VAR_5, VAR_6)
VAR_9 = self.service.show(VAR_5, VAR_7)
return self._translate_uuid_to_id(VAR_5, VAR_9)
def FUNC_11(self, VAR_5, VAR_12):
VAR_9 = self.service.show_by_name(VAR_5, VAR_12)
return self._translate_uuid_to_id(VAR_5, VAR_9)
def FUNC_12(self, VAR_5, VAR_6):
VAR_7 = self.get_image_uuid(VAR_5, VAR_6)
return self.get(self, VAR_5, VAR_7)
@staticmethod
def FUNC_13(VAR_5):
VAR_24 = VAR_1.s3_access_key
VAR_25 = VAR_1.s3_secret_key
VAR_26 = boto.s3.connection.OrdinaryCallingFormat()
return boto.s3.connection.S3Connection(aws_access_key_id=VAR_24,
aws_secret_access_key=VAR_25,
is_secure=False,
calling_format=VAR_26,
port=VAR_1.s3_port,
host=VAR_1.s3_host)
@staticmethod
def FUNC_14(VAR_13, VAR_14, VAR_15):
VAR_27 = VAR_13.get_key(VAR_14)
VAR_28 = os.path.join(VAR_15, os.path.basename(VAR_14))
VAR_27.get_contents_to_filename(VAR_28)
return VAR_28
def FUNC_15(self, VAR_5, VAR_10, VAR_16):
manifest = ElementTree.fromstring(VAR_16)
VAR_29 = 'ami'
VAR_30 = 'machine'
try:
VAR_43 = VAR_16.find('machine_configuration/kernel_id').text
if VAR_43 == 'true':
VAR_29 = 'aki'
VAR_30 = 'kernel'
VAR_43 = None
except Exception:
VAR_43 = None
try:
VAR_44 = VAR_16.find('machine_configuration/ramdisk_id').text
if VAR_44 == 'true':
VAR_29 = 'ari'
VAR_30 = 'ramdisk'
VAR_44 = None
except Exception:
VAR_44 = None
try:
VAR_45 = VAR_16.find('machine_configuration/architecture').text
except Exception:
VAR_45 = 'x86_64'
VAR_31 = []
try:
VAR_46 = VAR_16.findall('machine_configuration/'
'block_device_mapping/'
'mapping')
for bdm in VAR_46:
VAR_31.append({'virtual': bdm.find('virtual').text,
'device': bdm.find('device').text})
except Exception:
VAR_31 = []
VAR_32 = VAR_10['properties']
VAR_32['project_id'] = VAR_5.project_id
VAR_32['architecture'] = VAR_45
def FUNC_21(VAR_33, VAR_6):
VAR_6 = ec2utils.ec2_id_to_id(VAR_6)
VAR_7 = self.get_image_uuid(VAR_5, VAR_6)
VAR_32['image_id'] = VAR_7
if VAR_43:
FUNC_21('kernel_id', VAR_43)
if VAR_44:
FUNC_21('ramdisk_id', VAR_44)
if VAR_31:
VAR_32['mappings'] = VAR_31
VAR_10.update({'disk_format': VAR_29,
'container_format': VAR_29,
'status': 'queued',
'is_public': False,
'properties': VAR_32})
VAR_10['properties']['image_state'] = 'pending'
VAR_6 = VAR_10.pop('id', None)
VAR_9 = self.service.create(VAR_5, VAR_10)
VAR_7 = VAR_9['id']
VAR_9['id'] = self._create_image_id(VAR_5, VAR_7)
return VAR_16, VAR_9, VAR_7
def FUNC_16(self, VAR_5, VAR_10):
VAR_34 = tempfile.mkdtemp(dir=VAR_1.image_decryption_dir)
VAR_35 = VAR_10['properties']['image_location']
VAR_36 = VAR_35.split('/')[0]
VAR_37 = VAR_35[len(VAR_36) + 1:]
VAR_13 = self._conn(VAR_5).get_bucket(VAR_36)
VAR_27 = VAR_13.get_key(VAR_37)
VAR_16 = VAR_27.get_contents_as_string()
VAR_16, VAR_9, VAR_7 = self._s3_parse_manifest(VAR_5,
VAR_10,
VAR_16)
def FUNC_22():
VAR_47 = {'image_location': VAR_35,
'image_path': VAR_34}
VAR_10['properties']['image_state'] = 'downloading'
self.service.update(VAR_5, VAR_7, VAR_10)
try:
VAR_49 = []
VAR_50 = VAR_16.find('image').getiterator('filename')
for fn_element in VAR_50:
VAR_57 = self._download_file(VAR_13,
fn_element.text,
VAR_34)
VAR_49.append(VAR_57)
VAR_51 = os.path.join(VAR_34, 'image.encrypted')
with open(VAR_51, 'w') as combined:
for VAR_14 in VAR_49:
with open(VAR_14) as VAR_57:
shutil.copyfileobj(VAR_57, combined)
except Exception:
VAR_0.exception(_("Failed to download %(VAR_35)s "
"to %(VAR_34)s"), VAR_47)
VAR_10['properties']['image_state'] = 'failed_download'
self.service.update(VAR_5, VAR_7, VAR_10)
return
VAR_10['properties']['image_state'] = 'decrypting'
self.service.update(VAR_5, VAR_7, VAR_10)
try:
VAR_52 = VAR_16.find('image/ec2_encrypted_key').text
VAR_18 = binascii.a2b_hex(VAR_52)
VAR_53 = VAR_16.find('image/ec2_encrypted_iv').text
VAR_19 = binascii.a2b_hex(VAR_53)
VAR_54 = crypto.key_path(VAR_5.project_id)
VAR_55 = os.path.join(VAR_34, 'image.tar.gz')
self._decrypt_image(VAR_51, VAR_18,
VAR_19, VAR_54,
VAR_55)
except Exception:
VAR_0.exception(_("Failed to decrypt %(VAR_35)s "
"to %(VAR_34)s"), VAR_47)
VAR_10['properties']['image_state'] = 'failed_decrypt'
self.service.update(VAR_5, VAR_7, VAR_10)
return
VAR_10['properties']['image_state'] = 'untarring'
self.service.update(VAR_5, VAR_7, VAR_10)
try:
VAR_56 = self._untarzip_image(VAR_34, VAR_55)
except Exception:
VAR_0.exception(_("Failed to untar %(VAR_35)s "
"to %(VAR_34)s"), VAR_47)
VAR_10['properties']['image_state'] = 'failed_untar'
self.service.update(VAR_5, VAR_7, VAR_10)
return
VAR_10['properties']['image_state'] = 'uploading'
self.service.update(VAR_5, VAR_7, VAR_10)
try:
with open(VAR_56) as VAR_42:
self.service.update(VAR_5, VAR_7,
VAR_10, VAR_42)
except Exception:
VAR_0.exception(_("Failed to upload %(VAR_35)s "
"to %(VAR_34)s"), VAR_47)
VAR_10['properties']['image_state'] = 'failed_upload'
self.service.update(VAR_5, VAR_7, VAR_10)
return
VAR_10['properties']['image_state'] = 'available'
VAR_10['status'] = 'active'
self.service.update(VAR_5, VAR_7, VAR_10)
shutil.rmtree(VAR_34)
eventlet.spawn_n(FUNC_22)
return VAR_9
@staticmethod
def FUNC_17(VAR_17, VAR_18, VAR_19,
VAR_20, VAR_21):
VAR_27, VAR_38 = utils.execute('openssl',
'rsautl',
'-decrypt',
'-inkey', '%s' % VAR_20,
process_input=VAR_18,
check_exit_code=False)
if VAR_38:
raise exception.Error(_('Failed to decrypt private VAR_27: %s')
% VAR_38)
VAR_39, VAR_38 = utils.execute('openssl',
'rsautl',
'-decrypt',
'-inkey', '%s' % VAR_20,
process_input=VAR_19,
check_exit_code=False)
if VAR_38:
raise exception.Error(_('Failed to decrypt initialization '
'vector: %s') % VAR_38)
VAR_40, VAR_38 = utils.execute('openssl', 'enc',
'-d', '-aes-128-cbc',
'-in', '%s' % (VAR_17,),
'-K', '%s' % (VAR_27,),
'-iv', '%s' % (VAR_39,),
'-out', '%s' % (VAR_21,),
check_exit_code=False)
if VAR_38:
raise exception.Error(_('Failed to decrypt VAR_9 file '
'%(VAR_42)s: %(VAR_38)s') %
{'image_file': VAR_17,
'err': VAR_38})
@staticmethod
def FUNC_18(VAR_22, VAR_14):
VAR_41 = tarfile.open(VAR_14, 'r|gz')
for n in VAR_41.getnames():
if not os.path.abspath(os.path.join(VAR_22, n)).startswith(VAR_22):
VAR_41.close()
raise exception.Error(_('Unsafe filenames in image'))
VAR_41.close()
@staticmethod
def FUNC_19(VAR_22, VAR_14):
CLASS_0._test_for_malicious_tarball(VAR_22, VAR_14)
VAR_41 = tarfile.open(VAR_14, 'r|gz')
VAR_41.extractall(VAR_22)
VAR_42 = VAR_41.getnames()[0]
VAR_41.close()
return os.path.join(VAR_22, VAR_42)
| [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
20,
27,
30,
39,
40,
49,
50,
53,
57,
60,
63,
66,
69,
78,
80,
87,
95,
97,
100,
102,
106,
110,
115,
117,
118,
121,
123,
124,
127,
132,
136,
140,
143,
144,
154,
161,
166,
175,
184,
189,
190,
191,
192,
193,
194,
195,
196,
197,
198,
199,
200,
211,
215,
220,
223,
226,
229,
236,
237,
238,
240,
242,
243,
246,
247,
249,
252,
254,
261,
265,
272,
281,
282,
288,
295,
298,
304,
305,
306,
308,
319,
322,
331,
344,
348,
350,
352,
354,
376,
389,
397,
19,
52,
99,
100,
101,
102,
103,
251,
267
] | [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
20,
27,
30,
39,
40,
49,
50,
53,
57,
60,
63,
66,
69,
78,
80,
87,
95,
97,
100,
102,
106,
110,
115,
117,
118,
121,
123,
124,
127,
132,
136,
140,
143,
144,
154,
161,
166,
175,
184,
189,
190,
191,
192,
193,
194,
195,
196,
197,
198,
199,
200,
211,
215,
220,
223,
226,
229,
236,
237,
238,
240,
242,
243,
246,
247,
249,
252,
254,
261,
265,
272,
281,
282,
288,
295,
298,
304,
305,
306,
308,
319,
322,
331,
344,
348,
350,
352,
354,
376,
389,
399,
408,
19,
52,
99,
100,
101,
102,
103,
251,
392,
267
] |
2CWE-601
| # -*- coding: utf-8 -*-
# Copyright 2016 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
# Copyright 2020 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import synapse.api.errors
import synapse.handlers.device
import synapse.storage
from tests import unittest
user1 = "@boris:aaa"
user2 = "@theresa:bbb"
class DeviceTestCase(unittest.HomeserverTestCase):
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver("server", http_client=None)
self.handler = hs.get_device_handler()
self.store = hs.get_datastore()
return hs
def prepare(self, reactor, clock, hs):
# These tests assume that it starts 1000 seconds in.
self.reactor.advance(1000)
def test_device_is_created_with_invalid_name(self):
self.get_failure(
self.handler.check_device_registered(
user_id="@boris:foo",
device_id="foo",
initial_device_display_name="a"
* (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1),
),
synapse.api.errors.SynapseError,
)
def test_device_is_created_if_doesnt_exist(self):
res = self.get_success(
self.handler.check_device_registered(
user_id="@boris:foo",
device_id="fco",
initial_device_display_name="display name",
)
)
self.assertEqual(res, "fco")
dev = self.get_success(self.handler.store.get_device("@boris:foo", "fco"))
self.assertEqual(dev["display_name"], "display name")
def test_device_is_preserved_if_exists(self):
res1 = self.get_success(
self.handler.check_device_registered(
user_id="@boris:foo",
device_id="fco",
initial_device_display_name="display name",
)
)
self.assertEqual(res1, "fco")
res2 = self.get_success(
self.handler.check_device_registered(
user_id="@boris:foo",
device_id="fco",
initial_device_display_name="new display name",
)
)
self.assertEqual(res2, "fco")
dev = self.get_success(self.handler.store.get_device("@boris:foo", "fco"))
self.assertEqual(dev["display_name"], "display name")
def test_device_id_is_made_up_if_unspecified(self):
device_id = self.get_success(
self.handler.check_device_registered(
user_id="@theresa:foo",
device_id=None,
initial_device_display_name="display",
)
)
dev = self.get_success(self.handler.store.get_device("@theresa:foo", device_id))
self.assertEqual(dev["display_name"], "display")
def test_get_devices_by_user(self):
self._record_users()
res = self.get_success(self.handler.get_devices_by_user(user1))
self.assertEqual(3, len(res))
device_map = {d["device_id"]: d for d in res}
self.assertDictContainsSubset(
{
"user_id": user1,
"device_id": "xyz",
"display_name": "display 0",
"last_seen_ip": None,
"last_seen_ts": None,
},
device_map["xyz"],
)
self.assertDictContainsSubset(
{
"user_id": user1,
"device_id": "fco",
"display_name": "display 1",
"last_seen_ip": "ip1",
"last_seen_ts": 1000000,
},
device_map["fco"],
)
self.assertDictContainsSubset(
{
"user_id": user1,
"device_id": "abc",
"display_name": "display 2",
"last_seen_ip": "ip3",
"last_seen_ts": 3000000,
},
device_map["abc"],
)
def test_get_device(self):
self._record_users()
res = self.get_success(self.handler.get_device(user1, "abc"))
self.assertDictContainsSubset(
{
"user_id": user1,
"device_id": "abc",
"display_name": "display 2",
"last_seen_ip": "ip3",
"last_seen_ts": 3000000,
},
res,
)
def test_delete_device(self):
self._record_users()
# delete the device
self.get_success(self.handler.delete_device(user1, "abc"))
# check the device was deleted
self.get_failure(
self.handler.get_device(user1, "abc"), synapse.api.errors.NotFoundError
)
# we'd like to check the access token was invalidated, but that's a
# bit of a PITA.
def test_update_device(self):
self._record_users()
update = {"display_name": "new display"}
self.get_success(self.handler.update_device(user1, "abc", update))
res = self.get_success(self.handler.get_device(user1, "abc"))
self.assertEqual(res["display_name"], "new display")
def test_update_device_too_long_display_name(self):
"""Update a device with a display name that is invalid (too long)."""
self._record_users()
# Request to update a device display name with a new value that is longer than allowed.
update = {
"display_name": "a"
* (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1)
}
self.get_failure(
self.handler.update_device(user1, "abc", update),
synapse.api.errors.SynapseError,
)
# Ensure the display name was not updated.
res = self.get_success(self.handler.get_device(user1, "abc"))
self.assertEqual(res["display_name"], "display 2")
def test_update_unknown_device(self):
update = {"display_name": "new_display"}
self.get_failure(
self.handler.update_device("user_id", "unknown_device_id", update),
synapse.api.errors.NotFoundError,
)
def _record_users(self):
# check this works for both devices which have a recorded client_ip,
# and those which don't.
self._record_user(user1, "xyz", "display 0")
self._record_user(user1, "fco", "display 1", "token1", "ip1")
self._record_user(user1, "abc", "display 2", "token2", "ip2")
self._record_user(user1, "abc", "display 2", "token3", "ip3")
self._record_user(user2, "def", "dispkay", "token4", "ip4")
self.reactor.advance(10000)
def _record_user(
self, user_id, device_id, display_name, access_token=None, ip=None
):
device_id = self.get_success(
self.handler.check_device_registered(
user_id=user_id,
device_id=device_id,
initial_device_display_name=display_name,
)
)
if ip is not None:
self.get_success(
self.store.insert_client_ip(
user_id, access_token, ip, "user_agent", device_id
)
)
self.reactor.advance(1000)
class DehydrationTestCase(unittest.HomeserverTestCase):
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver("server", http_client=None)
self.handler = hs.get_device_handler()
self.registration = hs.get_registration_handler()
self.auth = hs.get_auth()
self.store = hs.get_datastore()
return hs
def test_dehydrate_and_rehydrate_device(self):
user_id = "@boris:dehydration"
self.get_success(self.store.register_user(user_id, "foobar"))
# First check if we can store and fetch a dehydrated device
stored_dehydrated_device_id = self.get_success(
self.handler.store_dehydrated_device(
user_id=user_id,
device_data={"device_data": {"foo": "bar"}},
initial_device_display_name="dehydrated device",
)
)
retrieved_device_id, device_data = self.get_success(
self.handler.get_dehydrated_device(user_id=user_id)
)
self.assertEqual(retrieved_device_id, stored_dehydrated_device_id)
self.assertEqual(device_data, {"device_data": {"foo": "bar"}})
# Create a new login for the user and dehydrated the device
device_id, access_token = self.get_success(
self.registration.register_device(
user_id=user_id, device_id=None, initial_display_name="new device",
)
)
# Trying to claim a nonexistent device should throw an error
self.get_failure(
self.handler.rehydrate_device(
user_id=user_id,
access_token=access_token,
device_id="not the right device ID",
),
synapse.api.errors.NotFoundError,
)
# dehydrating the right devices should succeed and change our device ID
# to the dehydrated device's ID
res = self.get_success(
self.handler.rehydrate_device(
user_id=user_id,
access_token=access_token,
device_id=retrieved_device_id,
)
)
self.assertEqual(res, {"success": True})
# make sure that our device ID has changed
user_info = self.get_success(self.auth.get_user_by_access_token(access_token))
self.assertEqual(user_info.device_id, retrieved_device_id)
# make sure the device has the display name that was set from the login
res = self.get_success(self.handler.get_device(user_id, retrieved_device_id))
self.assertEqual(res["display_name"], "new device")
# make sure that the device ID that we were initially assigned no longer exists
self.get_failure(
self.handler.get_device(user_id, device_id),
synapse.api.errors.NotFoundError,
)
# make sure that there's no device available for dehydrating now
ret = self.get_success(self.handler.get_dehydrated_device(user_id=user_id))
self.assertIsNone(ret)
| # -*- coding: utf-8 -*-
# Copyright 2016 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
# Copyright 2020 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import synapse.api.errors
import synapse.handlers.device
import synapse.storage
from tests import unittest
user1 = "@boris:aaa"
user2 = "@theresa:bbb"
class DeviceTestCase(unittest.HomeserverTestCase):
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver("server", federation_http_client=None)
self.handler = hs.get_device_handler()
self.store = hs.get_datastore()
return hs
def prepare(self, reactor, clock, hs):
# These tests assume that it starts 1000 seconds in.
self.reactor.advance(1000)
def test_device_is_created_with_invalid_name(self):
self.get_failure(
self.handler.check_device_registered(
user_id="@boris:foo",
device_id="foo",
initial_device_display_name="a"
* (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1),
),
synapse.api.errors.SynapseError,
)
def test_device_is_created_if_doesnt_exist(self):
res = self.get_success(
self.handler.check_device_registered(
user_id="@boris:foo",
device_id="fco",
initial_device_display_name="display name",
)
)
self.assertEqual(res, "fco")
dev = self.get_success(self.handler.store.get_device("@boris:foo", "fco"))
self.assertEqual(dev["display_name"], "display name")
def test_device_is_preserved_if_exists(self):
res1 = self.get_success(
self.handler.check_device_registered(
user_id="@boris:foo",
device_id="fco",
initial_device_display_name="display name",
)
)
self.assertEqual(res1, "fco")
res2 = self.get_success(
self.handler.check_device_registered(
user_id="@boris:foo",
device_id="fco",
initial_device_display_name="new display name",
)
)
self.assertEqual(res2, "fco")
dev = self.get_success(self.handler.store.get_device("@boris:foo", "fco"))
self.assertEqual(dev["display_name"], "display name")
def test_device_id_is_made_up_if_unspecified(self):
device_id = self.get_success(
self.handler.check_device_registered(
user_id="@theresa:foo",
device_id=None,
initial_device_display_name="display",
)
)
dev = self.get_success(self.handler.store.get_device("@theresa:foo", device_id))
self.assertEqual(dev["display_name"], "display")
def test_get_devices_by_user(self):
self._record_users()
res = self.get_success(self.handler.get_devices_by_user(user1))
self.assertEqual(3, len(res))
device_map = {d["device_id"]: d for d in res}
self.assertDictContainsSubset(
{
"user_id": user1,
"device_id": "xyz",
"display_name": "display 0",
"last_seen_ip": None,
"last_seen_ts": None,
},
device_map["xyz"],
)
self.assertDictContainsSubset(
{
"user_id": user1,
"device_id": "fco",
"display_name": "display 1",
"last_seen_ip": "ip1",
"last_seen_ts": 1000000,
},
device_map["fco"],
)
self.assertDictContainsSubset(
{
"user_id": user1,
"device_id": "abc",
"display_name": "display 2",
"last_seen_ip": "ip3",
"last_seen_ts": 3000000,
},
device_map["abc"],
)
def test_get_device(self):
self._record_users()
res = self.get_success(self.handler.get_device(user1, "abc"))
self.assertDictContainsSubset(
{
"user_id": user1,
"device_id": "abc",
"display_name": "display 2",
"last_seen_ip": "ip3",
"last_seen_ts": 3000000,
},
res,
)
def test_delete_device(self):
self._record_users()
# delete the device
self.get_success(self.handler.delete_device(user1, "abc"))
# check the device was deleted
self.get_failure(
self.handler.get_device(user1, "abc"), synapse.api.errors.NotFoundError
)
# we'd like to check the access token was invalidated, but that's a
# bit of a PITA.
def test_update_device(self):
self._record_users()
update = {"display_name": "new display"}
self.get_success(self.handler.update_device(user1, "abc", update))
res = self.get_success(self.handler.get_device(user1, "abc"))
self.assertEqual(res["display_name"], "new display")
def test_update_device_too_long_display_name(self):
"""Update a device with a display name that is invalid (too long)."""
self._record_users()
# Request to update a device display name with a new value that is longer than allowed.
update = {
"display_name": "a"
* (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1)
}
self.get_failure(
self.handler.update_device(user1, "abc", update),
synapse.api.errors.SynapseError,
)
# Ensure the display name was not updated.
res = self.get_success(self.handler.get_device(user1, "abc"))
self.assertEqual(res["display_name"], "display 2")
def test_update_unknown_device(self):
update = {"display_name": "new_display"}
self.get_failure(
self.handler.update_device("user_id", "unknown_device_id", update),
synapse.api.errors.NotFoundError,
)
def _record_users(self):
# check this works for both devices which have a recorded client_ip,
# and those which don't.
self._record_user(user1, "xyz", "display 0")
self._record_user(user1, "fco", "display 1", "token1", "ip1")
self._record_user(user1, "abc", "display 2", "token2", "ip2")
self._record_user(user1, "abc", "display 2", "token3", "ip3")
self._record_user(user2, "def", "dispkay", "token4", "ip4")
self.reactor.advance(10000)
def _record_user(
self, user_id, device_id, display_name, access_token=None, ip=None
):
device_id = self.get_success(
self.handler.check_device_registered(
user_id=user_id,
device_id=device_id,
initial_device_display_name=display_name,
)
)
if ip is not None:
self.get_success(
self.store.insert_client_ip(
user_id, access_token, ip, "user_agent", device_id
)
)
self.reactor.advance(1000)
class DehydrationTestCase(unittest.HomeserverTestCase):
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver("server", federation_http_client=None)
self.handler = hs.get_device_handler()
self.registration = hs.get_registration_handler()
self.auth = hs.get_auth()
self.store = hs.get_datastore()
return hs
def test_dehydrate_and_rehydrate_device(self):
user_id = "@boris:dehydration"
self.get_success(self.store.register_user(user_id, "foobar"))
# First check if we can store and fetch a dehydrated device
stored_dehydrated_device_id = self.get_success(
self.handler.store_dehydrated_device(
user_id=user_id,
device_data={"device_data": {"foo": "bar"}},
initial_device_display_name="dehydrated device",
)
)
retrieved_device_id, device_data = self.get_success(
self.handler.get_dehydrated_device(user_id=user_id)
)
self.assertEqual(retrieved_device_id, stored_dehydrated_device_id)
self.assertEqual(device_data, {"device_data": {"foo": "bar"}})
# Create a new login for the user and dehydrated the device
device_id, access_token = self.get_success(
self.registration.register_device(
user_id=user_id, device_id=None, initial_display_name="new device",
)
)
# Trying to claim a nonexistent device should throw an error
self.get_failure(
self.handler.rehydrate_device(
user_id=user_id,
access_token=access_token,
device_id="not the right device ID",
),
synapse.api.errors.NotFoundError,
)
# dehydrating the right devices should succeed and change our device ID
# to the dehydrated device's ID
res = self.get_success(
self.handler.rehydrate_device(
user_id=user_id,
access_token=access_token,
device_id=retrieved_device_id,
)
)
self.assertEqual(res, {"success": True})
# make sure that our device ID has changed
user_info = self.get_success(self.auth.get_user_by_access_token(access_token))
self.assertEqual(user_info.device_id, retrieved_device_id)
# make sure the device has the display name that was set from the login
res = self.get_success(self.handler.get_device(user_id, retrieved_device_id))
self.assertEqual(res["display_name"], "new device")
# make sure that the device ID that we were initially assigned no longer exists
self.get_failure(
self.handler.get_device(user_id, device_id),
synapse.api.errors.NotFoundError,
)
# make sure that there's no device available for dehydrating now
ret = self.get_success(self.handler.get_dehydrated_device(user_id=user_id))
self.assertIsNone(ret)
| open_redirect | {
"code": [
" hs = self.setup_test_homeserver(\"server\", http_client=None)",
" hs = self.setup_test_homeserver(\"server\", http_client=None)"
],
"line_no": [
30,
232
]
} | {
"code": [
" hs = self.setup_test_homeserver(\"server\", federation_http_client=None)",
" hs = self.setup_test_homeserver(\"server\", federation_http_client=None)"
],
"line_no": [
30,
232
]
} |
import synapse.api.errors
import synapse.handlers.device
import synapse.storage
from tests import unittest
VAR_0 = "@boris:aaa"
VAR_1 = "@theresa:bbb"
class CLASS_0(unittest.HomeserverTestCase):
def FUNC_0(self, VAR_2, VAR_3):
VAR_4 = self.setup_test_homeserver("server", http_client=None)
self.handler = VAR_4.get_device_handler()
self.store = VAR_4.get_datastore()
return VAR_4
def FUNC_1(self, VAR_2, VAR_3, VAR_4):
self.reactor.advance(1000)
def FUNC_2(self):
self.get_failure(
self.handler.check_device_registered(
VAR_5="@boris:foo",
VAR_6="foo",
initial_device_display_name="a"
* (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1),
),
synapse.api.errors.SynapseError,
)
def FUNC_3(self):
VAR_10 = self.get_success(
self.handler.check_device_registered(
VAR_5="@boris:foo",
VAR_6="fco",
initial_device_display_name="display name",
)
)
self.assertEqual(VAR_10, "fco")
VAR_11 = self.get_success(self.handler.store.get_device("@boris:foo", "fco"))
self.assertEqual(VAR_11["display_name"], "display name")
def FUNC_4(self):
VAR_12 = self.get_success(
self.handler.check_device_registered(
VAR_5="@boris:foo",
VAR_6="fco",
initial_device_display_name="display name",
)
)
self.assertEqual(VAR_12, "fco")
VAR_13 = self.get_success(
self.handler.check_device_registered(
VAR_5="@boris:foo",
VAR_6="fco",
initial_device_display_name="new display name",
)
)
self.assertEqual(VAR_13, "fco")
VAR_11 = self.get_success(self.handler.store.get_device("@boris:foo", "fco"))
self.assertEqual(VAR_11["display_name"], "display name")
def FUNC_5(self):
VAR_6 = self.get_success(
self.handler.check_device_registered(
VAR_5="@theresa:foo",
VAR_6=None,
initial_device_display_name="display",
)
)
VAR_11 = self.get_success(self.handler.store.get_device("@theresa:foo", VAR_6))
self.assertEqual(VAR_11["display_name"], "display")
def FUNC_6(self):
self._record_users()
VAR_10 = self.get_success(self.handler.get_devices_by_user(VAR_0))
self.assertEqual(3, len(VAR_10))
VAR_14 = {d["device_id"]: d for d in VAR_10}
self.assertDictContainsSubset(
{
"user_id": VAR_0,
"device_id": "xyz",
"display_name": "display 0",
"last_seen_ip": None,
"last_seen_ts": None,
},
VAR_14["xyz"],
)
self.assertDictContainsSubset(
{
"user_id": VAR_0,
"device_id": "fco",
"display_name": "display 1",
"last_seen_ip": "ip1",
"last_seen_ts": 1000000,
},
VAR_14["fco"],
)
self.assertDictContainsSubset(
{
"user_id": VAR_0,
"device_id": "abc",
"display_name": "display 2",
"last_seen_ip": "ip3",
"last_seen_ts": 3000000,
},
VAR_14["abc"],
)
def FUNC_7(self):
self._record_users()
VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc"))
self.assertDictContainsSubset(
{
"user_id": VAR_0,
"device_id": "abc",
"display_name": "display 2",
"last_seen_ip": "ip3",
"last_seen_ts": 3000000,
},
VAR_10,
)
def FUNC_8(self):
self._record_users()
self.get_success(self.handler.delete_device(VAR_0, "abc"))
self.get_failure(
self.handler.get_device(VAR_0, "abc"), synapse.api.errors.NotFoundError
)
def FUNC_9(self):
self._record_users()
VAR_15 = {"display_name": "new display"}
self.get_success(self.handler.update_device(VAR_0, "abc", VAR_15))
VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc"))
self.assertEqual(VAR_10["display_name"], "new display")
def FUNC_10(self):
self._record_users()
VAR_15 = {
"display_name": "a"
* (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1)
}
self.get_failure(
self.handler.update_device(VAR_0, "abc", VAR_15),
synapse.api.errors.SynapseError,
)
VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc"))
self.assertEqual(VAR_10["display_name"], "display 2")
def FUNC_11(self):
VAR_15 = {"display_name": "new_display"}
self.get_failure(
self.handler.update_device("user_id", "unknown_device_id", VAR_15),
synapse.api.errors.NotFoundError,
)
def FUNC_12(self):
self._record_user(VAR_0, "xyz", "display 0")
self._record_user(VAR_0, "fco", "display 1", "token1", "ip1")
self._record_user(VAR_0, "abc", "display 2", "token2", "ip2")
self._record_user(VAR_0, "abc", "display 2", "token3", "ip3")
self._record_user(VAR_1, "def", "dispkay", "token4", "ip4")
self.reactor.advance(10000)
def FUNC_13(
self, VAR_5, VAR_6, VAR_7, VAR_8=None, VAR_9=None
):
VAR_6 = self.get_success(
self.handler.check_device_registered(
VAR_5=user_id,
VAR_6=device_id,
initial_device_display_name=VAR_7,
)
)
if VAR_9 is not None:
self.get_success(
self.store.insert_client_ip(
VAR_5, VAR_8, VAR_9, "user_agent", VAR_6
)
)
self.reactor.advance(1000)
class CLASS_1(unittest.HomeserverTestCase):
def FUNC_0(self, VAR_2, VAR_3):
VAR_4 = self.setup_test_homeserver("server", http_client=None)
self.handler = VAR_4.get_device_handler()
self.registration = VAR_4.get_registration_handler()
self.auth = VAR_4.get_auth()
self.store = VAR_4.get_datastore()
return VAR_4
def FUNC_14(self):
VAR_5 = "@boris:dehydration"
self.get_success(self.store.register_user(VAR_5, "foobar"))
VAR_16 = self.get_success(
self.handler.store_dehydrated_device(
VAR_5=user_id,
VAR_18={"device_data": {"foo": "bar"}},
initial_device_display_name="dehydrated device",
)
)
VAR_17, VAR_18 = self.get_success(
self.handler.get_dehydrated_device(VAR_5=user_id)
)
self.assertEqual(VAR_17, VAR_16)
self.assertEqual(VAR_18, {"device_data": {"foo": "bar"}})
VAR_6, VAR_8 = self.get_success(
self.registration.register_device(
VAR_5=user_id, VAR_6=None, initial_display_name="new device",
)
)
self.get_failure(
self.handler.rehydrate_device(
VAR_5=user_id,
VAR_8=access_token,
VAR_6="not the right device ID",
),
synapse.api.errors.NotFoundError,
)
VAR_10 = self.get_success(
self.handler.rehydrate_device(
VAR_5=user_id,
VAR_8=access_token,
VAR_6=VAR_17,
)
)
self.assertEqual(VAR_10, {"success": True})
VAR_19 = self.get_success(self.auth.get_user_by_access_token(VAR_8))
self.assertEqual(VAR_19.device_id, VAR_17)
VAR_10 = self.get_success(self.handler.get_device(VAR_5, VAR_17))
self.assertEqual(VAR_10["display_name"], "new device")
self.get_failure(
self.handler.get_device(VAR_5, VAR_6),
synapse.api.errors.NotFoundError,
)
VAR_20 = self.get_success(self.handler.get_dehydrated_device(VAR_5=user_id))
self.assertIsNone(VAR_20)
|
import synapse.api.errors
import synapse.handlers.device
import synapse.storage
from tests import unittest
VAR_0 = "@boris:aaa"
VAR_1 = "@theresa:bbb"
class CLASS_0(unittest.HomeserverTestCase):
def FUNC_0(self, VAR_2, VAR_3):
VAR_4 = self.setup_test_homeserver("server", federation_http_client=None)
self.handler = VAR_4.get_device_handler()
self.store = VAR_4.get_datastore()
return VAR_4
def FUNC_1(self, VAR_2, VAR_3, VAR_4):
self.reactor.advance(1000)
def FUNC_2(self):
self.get_failure(
self.handler.check_device_registered(
VAR_5="@boris:foo",
VAR_6="foo",
initial_device_display_name="a"
* (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1),
),
synapse.api.errors.SynapseError,
)
def FUNC_3(self):
VAR_10 = self.get_success(
self.handler.check_device_registered(
VAR_5="@boris:foo",
VAR_6="fco",
initial_device_display_name="display name",
)
)
self.assertEqual(VAR_10, "fco")
VAR_11 = self.get_success(self.handler.store.get_device("@boris:foo", "fco"))
self.assertEqual(VAR_11["display_name"], "display name")
def FUNC_4(self):
VAR_12 = self.get_success(
self.handler.check_device_registered(
VAR_5="@boris:foo",
VAR_6="fco",
initial_device_display_name="display name",
)
)
self.assertEqual(VAR_12, "fco")
VAR_13 = self.get_success(
self.handler.check_device_registered(
VAR_5="@boris:foo",
VAR_6="fco",
initial_device_display_name="new display name",
)
)
self.assertEqual(VAR_13, "fco")
VAR_11 = self.get_success(self.handler.store.get_device("@boris:foo", "fco"))
self.assertEqual(VAR_11["display_name"], "display name")
def FUNC_5(self):
VAR_6 = self.get_success(
self.handler.check_device_registered(
VAR_5="@theresa:foo",
VAR_6=None,
initial_device_display_name="display",
)
)
VAR_11 = self.get_success(self.handler.store.get_device("@theresa:foo", VAR_6))
self.assertEqual(VAR_11["display_name"], "display")
def FUNC_6(self):
self._record_users()
VAR_10 = self.get_success(self.handler.get_devices_by_user(VAR_0))
self.assertEqual(3, len(VAR_10))
VAR_14 = {d["device_id"]: d for d in VAR_10}
self.assertDictContainsSubset(
{
"user_id": VAR_0,
"device_id": "xyz",
"display_name": "display 0",
"last_seen_ip": None,
"last_seen_ts": None,
},
VAR_14["xyz"],
)
self.assertDictContainsSubset(
{
"user_id": VAR_0,
"device_id": "fco",
"display_name": "display 1",
"last_seen_ip": "ip1",
"last_seen_ts": 1000000,
},
VAR_14["fco"],
)
self.assertDictContainsSubset(
{
"user_id": VAR_0,
"device_id": "abc",
"display_name": "display 2",
"last_seen_ip": "ip3",
"last_seen_ts": 3000000,
},
VAR_14["abc"],
)
def FUNC_7(self):
self._record_users()
VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc"))
self.assertDictContainsSubset(
{
"user_id": VAR_0,
"device_id": "abc",
"display_name": "display 2",
"last_seen_ip": "ip3",
"last_seen_ts": 3000000,
},
VAR_10,
)
def FUNC_8(self):
self._record_users()
self.get_success(self.handler.delete_device(VAR_0, "abc"))
self.get_failure(
self.handler.get_device(VAR_0, "abc"), synapse.api.errors.NotFoundError
)
def FUNC_9(self):
self._record_users()
VAR_15 = {"display_name": "new display"}
self.get_success(self.handler.update_device(VAR_0, "abc", VAR_15))
VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc"))
self.assertEqual(VAR_10["display_name"], "new display")
def FUNC_10(self):
self._record_users()
VAR_15 = {
"display_name": "a"
* (synapse.handlers.device.MAX_DEVICE_DISPLAY_NAME_LEN + 1)
}
self.get_failure(
self.handler.update_device(VAR_0, "abc", VAR_15),
synapse.api.errors.SynapseError,
)
VAR_10 = self.get_success(self.handler.get_device(VAR_0, "abc"))
self.assertEqual(VAR_10["display_name"], "display 2")
def FUNC_11(self):
VAR_15 = {"display_name": "new_display"}
self.get_failure(
self.handler.update_device("user_id", "unknown_device_id", VAR_15),
synapse.api.errors.NotFoundError,
)
def FUNC_12(self):
self._record_user(VAR_0, "xyz", "display 0")
self._record_user(VAR_0, "fco", "display 1", "token1", "ip1")
self._record_user(VAR_0, "abc", "display 2", "token2", "ip2")
self._record_user(VAR_0, "abc", "display 2", "token3", "ip3")
self._record_user(VAR_1, "def", "dispkay", "token4", "ip4")
self.reactor.advance(10000)
def FUNC_13(
self, VAR_5, VAR_6, VAR_7, VAR_8=None, VAR_9=None
):
VAR_6 = self.get_success(
self.handler.check_device_registered(
VAR_5=user_id,
VAR_6=device_id,
initial_device_display_name=VAR_7,
)
)
if VAR_9 is not None:
self.get_success(
self.store.insert_client_ip(
VAR_5, VAR_8, VAR_9, "user_agent", VAR_6
)
)
self.reactor.advance(1000)
class CLASS_1(unittest.HomeserverTestCase):
def FUNC_0(self, VAR_2, VAR_3):
VAR_4 = self.setup_test_homeserver("server", federation_http_client=None)
self.handler = VAR_4.get_device_handler()
self.registration = VAR_4.get_registration_handler()
self.auth = VAR_4.get_auth()
self.store = VAR_4.get_datastore()
return VAR_4
def FUNC_14(self):
VAR_5 = "@boris:dehydration"
self.get_success(self.store.register_user(VAR_5, "foobar"))
VAR_16 = self.get_success(
self.handler.store_dehydrated_device(
VAR_5=user_id,
VAR_18={"device_data": {"foo": "bar"}},
initial_device_display_name="dehydrated device",
)
)
VAR_17, VAR_18 = self.get_success(
self.handler.get_dehydrated_device(VAR_5=user_id)
)
self.assertEqual(VAR_17, VAR_16)
self.assertEqual(VAR_18, {"device_data": {"foo": "bar"}})
VAR_6, VAR_8 = self.get_success(
self.registration.register_device(
VAR_5=user_id, VAR_6=None, initial_display_name="new device",
)
)
self.get_failure(
self.handler.rehydrate_device(
VAR_5=user_id,
VAR_8=access_token,
VAR_6="not the right device ID",
),
synapse.api.errors.NotFoundError,
)
VAR_10 = self.get_success(
self.handler.rehydrate_device(
VAR_5=user_id,
VAR_8=access_token,
VAR_6=VAR_17,
)
)
self.assertEqual(VAR_10, {"success": True})
VAR_19 = self.get_success(self.auth.get_user_by_access_token(VAR_8))
self.assertEqual(VAR_19.device_id, VAR_17)
VAR_10 = self.get_success(self.handler.get_device(VAR_5, VAR_17))
self.assertEqual(VAR_10["display_name"], "new device")
self.get_failure(
self.handler.get_device(VAR_5, VAR_6),
synapse.api.errors.NotFoundError,
)
VAR_20 = self.get_success(self.handler.get_dehydrated_device(VAR_5=user_id))
self.assertIsNone(VAR_20)
| [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
21,
23,
26,
27,
34,
36,
38,
49,
59,
62,
72,
81,
84,
93,
96,
99,
101,
134,
137,
149,
152,
153,
155,
156,
160,
161,
162,
163,
166,
169,
172,
176,
177,
186,
187,
190,
197,
199,
200,
205,
207,
209,
220,
228,
229,
238,
241,
243,
244,
252,
256,
259,
260,
266,
267,
276,
277,
278,
286,
288,
289,
291,
293,
294,
296,
298,
299,
304,
305,
307,
309,
174
] | [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
21,
23,
26,
27,
34,
36,
38,
49,
59,
62,
72,
81,
84,
93,
96,
99,
101,
134,
137,
149,
152,
153,
155,
156,
160,
161,
162,
163,
166,
169,
172,
176,
177,
186,
187,
190,
197,
199,
200,
205,
207,
209,
220,
228,
229,
238,
241,
243,
244,
252,
256,
259,
260,
266,
267,
276,
277,
278,
286,
288,
289,
291,
293,
294,
296,
298,
299,
304,
305,
307,
309,
174
] |
2CWE-601
| import logging
from aiohttp import web
import os
logger = logging.getLogger(__package__)
def setup_middlewares(app):
error_middleware = error_pages({404: handle_404,
500: handle_500})
app.middlewares.append(error_middleware)
app.middlewares.append(cache_control_middleware)
# Cache-Control middleware
CACHE_MAX_AGE = int(os.getenv("CACHE_MAX_AGE", "30"))
NO_CACHE_ENDPOINTS = ['/v1/', '/v1/__version__', '/v1/__heartbeat__', '/v1/__lbheartbeat__']
async def cache_control_middleware(app, handler):
async def middleware_handler(request):
response = await handler(request)
cache_control_value = "public; max-age={}".format(CACHE_MAX_AGE)
if request.path in NO_CACHE_ENDPOINTS or CACHE_MAX_AGE <= 0:
cache_control_value = "no-cache"
response.headers.setdefault("Cache-Control", cache_control_value)
return response
return middleware_handler
# Error page middlewares
def error_pages(overrides):
async def middleware(app, handler):
async def middleware_handler(request):
try:
response = await handler(request)
override = overrides.get(response.status)
if override is None:
return response
else:
return await override(request, response)
except web.HTTPException as ex:
override = overrides.get(ex.status)
if override is None:
return await handle_any(request, ex)
else:
return await override(request, ex)
except Exception as ex:
return await handle_500(request, error=ex)
return middleware_handler
return middleware
async def handle_any(request, response):
return web.json_response({
"status": response.status,
"message": response.reason
}, status=response.status)
async def handle_404(request, response):
if 'json' not in response.headers['Content-Type']:
if request.path.endswith('/'):
return web.HTTPFound(request.path.rstrip('/'))
return web.json_response({
"status": 404,
"message": "Page '{}' not found".format(request.path)
}, status=404)
return response
async def handle_500(request, response=None, error=None):
logger.exception(error)
return web.json_response({
"status": 503,
"message": "Service currently unavailable"
}, status=503)
| import logging
from aiohttp import web
import os
logger = logging.getLogger(__package__)
def setup_middlewares(app):
error_middleware = error_pages({404: handle_404,
500: handle_500})
app.middlewares.append(error_middleware)
app.middlewares.append(cache_control_middleware)
# Cache-Control middleware
CACHE_MAX_AGE = int(os.getenv("CACHE_MAX_AGE", "30"))
NO_CACHE_ENDPOINTS = ['/v1/', '/v1/__version__', '/v1/__heartbeat__', '/v1/__lbheartbeat__']
async def cache_control_middleware(app, handler):
async def middleware_handler(request):
response = await handler(request)
cache_control_value = "public; max-age={}".format(CACHE_MAX_AGE)
if request.path in NO_CACHE_ENDPOINTS or CACHE_MAX_AGE <= 0:
cache_control_value = "no-cache"
response.headers.setdefault("Cache-Control", cache_control_value)
return response
return middleware_handler
# Error page middlewares
def error_pages(overrides):
async def middleware(app, handler):
async def middleware_handler(request):
try:
response = await handler(request)
override = overrides.get(response.status)
if override is None:
return response
else:
return await override(request, response)
except web.HTTPException as ex:
override = overrides.get(ex.status)
if override is None:
return await handle_any(request, ex)
else:
return await override(request, ex)
except Exception as ex:
return await handle_500(request, error=ex)
return middleware_handler
return middleware
async def handle_any(request, response):
return web.json_response({
"status": response.status,
"message": response.reason
}, status=response.status)
async def handle_404(request, response):
if 'json' not in response.headers['Content-Type']:
if request.path.endswith('/'):
return web.HTTPFound('/' + request.path.strip('/'))
return web.json_response({
"status": 404,
"message": "Page '{}' not found".format(request.path)
}, status=404)
return response
async def handle_500(request, response=None, error=None):
logger.exception(error)
return web.json_response({
"status": 503,
"message": "Service currently unavailable"
}, status=503)
| open_redirect | {
"code": [
" return web.HTTPFound(request.path.rstrip('/'))"
],
"line_no": [
64
]
} | {
"code": [
" return web.HTTPFound('/' + request.path.strip('/'))"
],
"line_no": [
64
]
} | import logging
from aiohttp import web
import os
VAR_0 = logging.getLogger(__package__)
def FUNC_0(VAR_1):
VAR_9 = FUNC_2({404: FUNC_4,
500: FUNC_5})
VAR_1.middlewares.append(VAR_9)
VAR_1.middlewares.append(FUNC_1)
VAR_2 = int(os.getenv("CACHE_MAX_AGE", "30"))
VAR_3 = ['/v1/', '/v1/__version__', '/v1/__heartbeat__', '/v1/__lbheartbeat__']
async def FUNC_1(VAR_1, VAR_4):
async def FUNC_6(VAR_6):
VAR_7 = await VAR_4(VAR_6)
VAR_10 = "public; max-age={}".format(VAR_2)
if VAR_6.path in VAR_3 or VAR_2 <= 0:
VAR_10 = "no-cache"
VAR_7.headers.setdefault("Cache-Control", VAR_10)
return VAR_7
return FUNC_6
def FUNC_2(VAR_5):
async def FUNC_7(VAR_1, VAR_4):
async def FUNC_6(VAR_6):
try:
VAR_7 = await VAR_4(VAR_6)
VAR_11 = VAR_5.get(VAR_7.status)
if VAR_11 is None:
return VAR_7
else:
return await VAR_11(VAR_6, VAR_7)
except web.HTTPException as ex:
VAR_11 = VAR_5.get(ex.status)
if VAR_11 is None:
return await FUNC_3(VAR_6, ex)
else:
return await VAR_11(VAR_6, ex)
except Exception as ex:
return await FUNC_5(VAR_6, VAR_8=ex)
return FUNC_6
return FUNC_7
async def FUNC_3(VAR_6, VAR_7):
return web.json_response({
"status": VAR_7.status,
"message": VAR_7.reason
}, status=VAR_7.status)
async def FUNC_4(VAR_6, VAR_7):
if 'json' not in VAR_7.headers['Content-Type']:
if VAR_6.path.endswith('/'):
return web.HTTPFound(VAR_6.path.rstrip('/'))
return web.json_response({
"status": 404,
"message": "Page '{}' not found".format(VAR_6.path)
}, status=404)
return VAR_7
async def FUNC_5(VAR_6, VAR_7=None, VAR_8=None):
VAR_0.exception(VAR_8)
return web.json_response({
"status": 503,
"message": "Service currently unavailable"
}, status=503)
| import logging
from aiohttp import web
import os
VAR_0 = logging.getLogger(__package__)
def FUNC_0(VAR_1):
VAR_9 = FUNC_2({404: FUNC_4,
500: FUNC_5})
VAR_1.middlewares.append(VAR_9)
VAR_1.middlewares.append(FUNC_1)
VAR_2 = int(os.getenv("CACHE_MAX_AGE", "30"))
VAR_3 = ['/v1/', '/v1/__version__', '/v1/__heartbeat__', '/v1/__lbheartbeat__']
async def FUNC_1(VAR_1, VAR_4):
async def FUNC_6(VAR_6):
VAR_7 = await VAR_4(VAR_6)
VAR_10 = "public; max-age={}".format(VAR_2)
if VAR_6.path in VAR_3 or VAR_2 <= 0:
VAR_10 = "no-cache"
VAR_7.headers.setdefault("Cache-Control", VAR_10)
return VAR_7
return FUNC_6
def FUNC_2(VAR_5):
async def FUNC_7(VAR_1, VAR_4):
async def FUNC_6(VAR_6):
try:
VAR_7 = await VAR_4(VAR_6)
VAR_11 = VAR_5.get(VAR_7.status)
if VAR_11 is None:
return VAR_7
else:
return await VAR_11(VAR_6, VAR_7)
except web.HTTPException as ex:
VAR_11 = VAR_5.get(ex.status)
if VAR_11 is None:
return await FUNC_3(VAR_6, ex)
else:
return await VAR_11(VAR_6, ex)
except Exception as ex:
return await FUNC_5(VAR_6, VAR_8=ex)
return FUNC_6
return FUNC_7
async def FUNC_3(VAR_6, VAR_7):
return web.json_response({
"status": VAR_7.status,
"message": VAR_7.reason
}, status=VAR_7.status)
async def FUNC_4(VAR_6, VAR_7):
if 'json' not in VAR_7.headers['Content-Type']:
if VAR_6.path.endswith('/'):
return web.HTTPFound('/' + VAR_6.path.strip('/'))
return web.json_response({
"status": 404,
"message": "Page '{}' not found".format(VAR_6.path)
}, status=404)
return VAR_7
async def FUNC_5(VAR_6, VAR_7=None, VAR_8=None):
VAR_0.exception(VAR_8)
return web.json_response({
"status": 503,
"message": "Service currently unavailable"
}, status=503)
| [
4,
6,
7,
13,
14,
15,
18,
19,
29,
30,
31,
52,
53,
59,
60,
70,
71,
78
] | [
4,
6,
7,
13,
14,
15,
18,
19,
29,
30,
31,
52,
53,
59,
60,
70,
71,
78
] |
1CWE-79
| from __future__ import absolute_import, division, unicode_literals
from six import text_type
import re
from ..constants import voidElements, booleanAttributes, spaceCharacters
from ..constants import rcdataElements, entities, xmlEntities
from .. import utils
from xml.sax.saxutils import escape
spaceCharacters = "".join(spaceCharacters)
quoteAttributeSpec = re.compile("[" + spaceCharacters + "\"'=<>`]")
try:
from codecs import register_error, xmlcharrefreplace_errors
except ImportError:
unicode_encode_errors = "strict"
else:
unicode_encode_errors = "htmlentityreplace"
encode_entity_map = {}
is_ucs4 = len("\U0010FFFF") == 1
for k, v in list(entities.items()):
# skip multi-character entities
if ((is_ucs4 and len(v) > 1) or
(not is_ucs4 and len(v) > 2)):
continue
if v != "&":
if len(v) == 2:
v = utils.surrogatePairToCodepoint(v)
else:
v = ord(v)
if v not in encode_entity_map or k.islower():
# prefer < over < and similarly for &, >, etc.
encode_entity_map[v] = k
def htmlentityreplace_errors(exc):
if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)):
res = []
codepoints = []
skip = False
for i, c in enumerate(exc.object[exc.start:exc.end]):
if skip:
skip = False
continue
index = i + exc.start
if utils.isSurrogatePair(exc.object[index:min([exc.end, index + 2])]):
codepoint = utils.surrogatePairToCodepoint(exc.object[index:index + 2])
skip = True
else:
codepoint = ord(c)
codepoints.append(codepoint)
for cp in codepoints:
e = encode_entity_map.get(cp)
if e:
res.append("&")
res.append(e)
if not e.endswith(";"):
res.append(";")
else:
res.append("&#x%s;" % (hex(cp)[2:]))
return ("".join(res), exc.end)
else:
return xmlcharrefreplace_errors(exc)
register_error(unicode_encode_errors, htmlentityreplace_errors)
del register_error
class HTMLSerializer(object):
# attribute quoting options
quote_attr_values = False
quote_char = '"'
use_best_quote_char = True
# tag syntax options
omit_optional_tags = True
minimize_boolean_attributes = True
use_trailing_solidus = False
space_before_trailing_solidus = True
# escaping options
escape_lt_in_attrs = False
escape_rcdata = False
resolve_entities = True
# miscellaneous options
alphabetical_attributes = False
inject_meta_charset = True
strip_whitespace = False
sanitize = False
options = ("quote_attr_values", "quote_char", "use_best_quote_char",
"omit_optional_tags", "minimize_boolean_attributes",
"use_trailing_solidus", "space_before_trailing_solidus",
"escape_lt_in_attrs", "escape_rcdata", "resolve_entities",
"alphabetical_attributes", "inject_meta_charset",
"strip_whitespace", "sanitize")
def __init__(self, **kwargs):
"""Initialize HTMLSerializer.
Keyword options (default given first unless specified) include:
inject_meta_charset=True|False
Whether it insert a meta element to define the character set of the
document.
quote_attr_values=True|False
Whether to quote attribute values that don't require quoting
per HTML5 parsing rules.
quote_char=u'"'|u"'"
Use given quote character for attribute quoting. Default is to
use double quote unless attribute value contains a double quote,
in which case single quotes are used instead.
escape_lt_in_attrs=False|True
Whether to escape < in attribute values.
escape_rcdata=False|True
Whether to escape characters that need to be escaped within normal
elements within rcdata elements such as style.
resolve_entities=True|False
Whether to resolve named character entities that appear in the
source tree. The XML predefined entities < > & " '
are unaffected by this setting.
strip_whitespace=False|True
Whether to remove semantically meaningless whitespace. (This
compresses all whitespace to a single space except within pre.)
minimize_boolean_attributes=True|False
Shortens boolean attributes to give just the attribute value,
for example <input disabled="disabled"> becomes <input disabled>.
use_trailing_solidus=False|True
Includes a close-tag slash at the end of the start tag of void
elements (empty elements whose end tag is forbidden). E.g. <hr/>.
space_before_trailing_solidus=True|False
Places a space immediately before the closing slash in a tag
using a trailing solidus. E.g. <hr />. Requires use_trailing_solidus.
sanitize=False|True
Strip all unsafe or unknown constructs from output.
See `html5lib user documentation`_
omit_optional_tags=True|False
Omit start/end tags that are optional.
alphabetical_attributes=False|True
Reorder attributes to be in alphabetical order.
.. _html5lib user documentation: http://code.google.com/p/html5lib/wiki/UserDocumentation
"""
if 'quote_char' in kwargs:
self.use_best_quote_char = False
for attr in self.options:
setattr(self, attr, kwargs.get(attr, getattr(self, attr)))
self.errors = []
self.strict = False
def encode(self, string):
assert(isinstance(string, text_type))
if self.encoding:
return string.encode(self.encoding, unicode_encode_errors)
else:
return string
def encodeStrict(self, string):
assert(isinstance(string, text_type))
if self.encoding:
return string.encode(self.encoding, "strict")
else:
return string
def serialize(self, treewalker, encoding=None):
self.encoding = encoding
in_cdata = False
self.errors = []
if encoding and self.inject_meta_charset:
from ..filters.inject_meta_charset import Filter
treewalker = Filter(treewalker, encoding)
# WhitespaceFilter should be used before OptionalTagFilter
# for maximum efficiently of this latter filter
if self.strip_whitespace:
from ..filters.whitespace import Filter
treewalker = Filter(treewalker)
if self.sanitize:
from ..filters.sanitizer import Filter
treewalker = Filter(treewalker)
if self.omit_optional_tags:
from ..filters.optionaltags import Filter
treewalker = Filter(treewalker)
# Alphabetical attributes must be last, as other filters
# could add attributes and alter the order
if self.alphabetical_attributes:
from ..filters.alphabeticalattributes import Filter
treewalker = Filter(treewalker)
for token in treewalker:
type = token["type"]
if type == "Doctype":
doctype = "<!DOCTYPE %s" % token["name"]
if token["publicId"]:
doctype += ' PUBLIC "%s"' % token["publicId"]
elif token["systemId"]:
doctype += " SYSTEM"
if token["systemId"]:
if token["systemId"].find('"') >= 0:
if token["systemId"].find("'") >= 0:
self.serializeError("System identifer contains both single and double quote characters")
quote_char = "'"
else:
quote_char = '"'
doctype += " %s%s%s" % (quote_char, token["systemId"], quote_char)
doctype += ">"
yield self.encodeStrict(doctype)
elif type in ("Characters", "SpaceCharacters"):
if type == "SpaceCharacters" or in_cdata:
if in_cdata and token["data"].find("</") >= 0:
self.serializeError("Unexpected </ in CDATA")
yield self.encode(token["data"])
else:
yield self.encode(escape(token["data"]))
elif type in ("StartTag", "EmptyTag"):
name = token["name"]
yield self.encodeStrict("<%s" % name)
if name in rcdataElements and not self.escape_rcdata:
in_cdata = True
elif in_cdata:
self.serializeError("Unexpected child element of a CDATA element")
for (attr_namespace, attr_name), attr_value in token["data"].items():
# TODO: Add namespace support here
k = attr_name
v = attr_value
yield self.encodeStrict(' ')
yield self.encodeStrict(k)
if not self.minimize_boolean_attributes or \
(k not in booleanAttributes.get(name, tuple()) and
k not in booleanAttributes.get("", tuple())):
yield self.encodeStrict("=")
if self.quote_attr_values:
quote_attr = True
else:
quote_attr = len(v) == 0 or quoteAttributeSpec.search(v)
v = v.replace("&", "&")
if self.escape_lt_in_attrs:
v = v.replace("<", "<")
if quote_attr:
quote_char = self.quote_char
if self.use_best_quote_char:
if "'" in v and '"' not in v:
quote_char = '"'
elif '"' in v and "'" not in v:
quote_char = "'"
if quote_char == "'":
v = v.replace("'", "'")
else:
v = v.replace('"', """)
yield self.encodeStrict(quote_char)
yield self.encode(v)
yield self.encodeStrict(quote_char)
else:
yield self.encode(v)
if name in voidElements and self.use_trailing_solidus:
if self.space_before_trailing_solidus:
yield self.encodeStrict(" /")
else:
yield self.encodeStrict("/")
yield self.encode(">")
elif type == "EndTag":
name = token["name"]
if name in rcdataElements:
in_cdata = False
elif in_cdata:
self.serializeError("Unexpected child element of a CDATA element")
yield self.encodeStrict("</%s>" % name)
elif type == "Comment":
data = token["data"]
if data.find("--") >= 0:
self.serializeError("Comment contains --")
yield self.encodeStrict("<!--%s-->" % token["data"])
elif type == "Entity":
name = token["name"]
key = name + ";"
if key not in entities:
self.serializeError("Entity %s not recognized" % name)
if self.resolve_entities and key not in xmlEntities:
data = entities[key]
else:
data = "&%s;" % name
yield self.encodeStrict(data)
else:
self.serializeError(token["data"])
def render(self, treewalker, encoding=None):
if encoding:
return b"".join(list(self.serialize(treewalker, encoding)))
else:
return "".join(list(self.serialize(treewalker)))
def serializeError(self, data="XXX ERROR MESSAGE NEEDED"):
# XXX The idea is to make data mandatory.
self.errors.append(data)
if self.strict:
raise SerializeError
def SerializeError(Exception):
"""Error in serialized tree"""
pass
| from __future__ import absolute_import, division, unicode_literals
from six import text_type
import re
from ..constants import voidElements, booleanAttributes, spaceCharacters
from ..constants import rcdataElements, entities, xmlEntities
from .. import utils
from xml.sax.saxutils import escape
spaceCharacters = "".join(spaceCharacters)
quoteAttributeSpecChars = spaceCharacters + "\"'=<>`"
quoteAttributeSpec = re.compile("[" + quoteAttributeSpecChars + "]")
quoteAttributeLegacy = re.compile("[" + quoteAttributeSpecChars +
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n"
"\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15"
"\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
"\x20\x2f\x60\xa0\u1680\u180e\u180f\u2000"
"\u2001\u2002\u2003\u2004\u2005\u2006\u2007"
"\u2008\u2009\u200a\u2028\u2029\u202f\u205f"
"\u3000]")
try:
from codecs import register_error, xmlcharrefreplace_errors
except ImportError:
unicode_encode_errors = "strict"
else:
unicode_encode_errors = "htmlentityreplace"
encode_entity_map = {}
is_ucs4 = len("\U0010FFFF") == 1
for k, v in list(entities.items()):
# skip multi-character entities
if ((is_ucs4 and len(v) > 1) or
(not is_ucs4 and len(v) > 2)):
continue
if v != "&":
if len(v) == 2:
v = utils.surrogatePairToCodepoint(v)
else:
v = ord(v)
if v not in encode_entity_map or k.islower():
# prefer < over < and similarly for &, >, etc.
encode_entity_map[v] = k
def htmlentityreplace_errors(exc):
if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)):
res = []
codepoints = []
skip = False
for i, c in enumerate(exc.object[exc.start:exc.end]):
if skip:
skip = False
continue
index = i + exc.start
if utils.isSurrogatePair(exc.object[index:min([exc.end, index + 2])]):
codepoint = utils.surrogatePairToCodepoint(exc.object[index:index + 2])
skip = True
else:
codepoint = ord(c)
codepoints.append(codepoint)
for cp in codepoints:
e = encode_entity_map.get(cp)
if e:
res.append("&")
res.append(e)
if not e.endswith(";"):
res.append(";")
else:
res.append("&#x%s;" % (hex(cp)[2:]))
return ("".join(res), exc.end)
else:
return xmlcharrefreplace_errors(exc)
register_error(unicode_encode_errors, htmlentityreplace_errors)
del register_error
class HTMLSerializer(object):
# attribute quoting options
quote_attr_values = "legacy" # be secure by default
quote_char = '"'
use_best_quote_char = True
# tag syntax options
omit_optional_tags = True
minimize_boolean_attributes = True
use_trailing_solidus = False
space_before_trailing_solidus = True
# escaping options
escape_lt_in_attrs = False
escape_rcdata = False
resolve_entities = True
# miscellaneous options
alphabetical_attributes = False
inject_meta_charset = True
strip_whitespace = False
sanitize = False
options = ("quote_attr_values", "quote_char", "use_best_quote_char",
"omit_optional_tags", "minimize_boolean_attributes",
"use_trailing_solidus", "space_before_trailing_solidus",
"escape_lt_in_attrs", "escape_rcdata", "resolve_entities",
"alphabetical_attributes", "inject_meta_charset",
"strip_whitespace", "sanitize")
def __init__(self, **kwargs):
"""Initialize HTMLSerializer.
Keyword options (default given first unless specified) include:
inject_meta_charset=True|False
Whether it insert a meta element to define the character set of the
document.
quote_attr_values="legacy"|"spec"|"always"
Whether to quote attribute values that don't require quoting
per legacy browser behaviour, when required by the standard, or always.
quote_char=u'"'|u"'"
Use given quote character for attribute quoting. Default is to
use double quote unless attribute value contains a double quote,
in which case single quotes are used instead.
escape_lt_in_attrs=False|True
Whether to escape < in attribute values.
escape_rcdata=False|True
Whether to escape characters that need to be escaped within normal
elements within rcdata elements such as style.
resolve_entities=True|False
Whether to resolve named character entities that appear in the
source tree. The XML predefined entities < > & " '
are unaffected by this setting.
strip_whitespace=False|True
Whether to remove semantically meaningless whitespace. (This
compresses all whitespace to a single space except within pre.)
minimize_boolean_attributes=True|False
Shortens boolean attributes to give just the attribute value,
for example <input disabled="disabled"> becomes <input disabled>.
use_trailing_solidus=False|True
Includes a close-tag slash at the end of the start tag of void
elements (empty elements whose end tag is forbidden). E.g. <hr/>.
space_before_trailing_solidus=True|False
Places a space immediately before the closing slash in a tag
using a trailing solidus. E.g. <hr />. Requires use_trailing_solidus.
sanitize=False|True
Strip all unsafe or unknown constructs from output.
See `html5lib user documentation`_
omit_optional_tags=True|False
Omit start/end tags that are optional.
alphabetical_attributes=False|True
Reorder attributes to be in alphabetical order.
.. _html5lib user documentation: http://code.google.com/p/html5lib/wiki/UserDocumentation
"""
if 'quote_char' in kwargs:
self.use_best_quote_char = False
for attr in self.options:
setattr(self, attr, kwargs.get(attr, getattr(self, attr)))
self.errors = []
self.strict = False
def encode(self, string):
assert(isinstance(string, text_type))
if self.encoding:
return string.encode(self.encoding, unicode_encode_errors)
else:
return string
def encodeStrict(self, string):
assert(isinstance(string, text_type))
if self.encoding:
return string.encode(self.encoding, "strict")
else:
return string
def serialize(self, treewalker, encoding=None):
self.encoding = encoding
in_cdata = False
self.errors = []
if encoding and self.inject_meta_charset:
from ..filters.inject_meta_charset import Filter
treewalker = Filter(treewalker, encoding)
# WhitespaceFilter should be used before OptionalTagFilter
# for maximum efficiently of this latter filter
if self.strip_whitespace:
from ..filters.whitespace import Filter
treewalker = Filter(treewalker)
if self.sanitize:
from ..filters.sanitizer import Filter
treewalker = Filter(treewalker)
if self.omit_optional_tags:
from ..filters.optionaltags import Filter
treewalker = Filter(treewalker)
# Alphabetical attributes must be last, as other filters
# could add attributes and alter the order
if self.alphabetical_attributes:
from ..filters.alphabeticalattributes import Filter
treewalker = Filter(treewalker)
for token in treewalker:
type = token["type"]
if type == "Doctype":
doctype = "<!DOCTYPE %s" % token["name"]
if token["publicId"]:
doctype += ' PUBLIC "%s"' % token["publicId"]
elif token["systemId"]:
doctype += " SYSTEM"
if token["systemId"]:
if token["systemId"].find('"') >= 0:
if token["systemId"].find("'") >= 0:
self.serializeError("System identifer contains both single and double quote characters")
quote_char = "'"
else:
quote_char = '"'
doctype += " %s%s%s" % (quote_char, token["systemId"], quote_char)
doctype += ">"
yield self.encodeStrict(doctype)
elif type in ("Characters", "SpaceCharacters"):
if type == "SpaceCharacters" or in_cdata:
if in_cdata and token["data"].find("</") >= 0:
self.serializeError("Unexpected </ in CDATA")
yield self.encode(token["data"])
else:
yield self.encode(escape(token["data"]))
elif type in ("StartTag", "EmptyTag"):
name = token["name"]
yield self.encodeStrict("<%s" % name)
if name in rcdataElements and not self.escape_rcdata:
in_cdata = True
elif in_cdata:
self.serializeError("Unexpected child element of a CDATA element")
for (attr_namespace, attr_name), attr_value in token["data"].items():
# TODO: Add namespace support here
k = attr_name
v = attr_value
yield self.encodeStrict(' ')
yield self.encodeStrict(k)
if not self.minimize_boolean_attributes or \
(k not in booleanAttributes.get(name, tuple()) and
k not in booleanAttributes.get("", tuple())):
yield self.encodeStrict("=")
if self.quote_attr_values == "always" or len(v) == 0:
quote_attr = True
elif self.quote_attr_values == "spec":
quote_attr = quoteAttributeSpec.search(v) is not None
elif self.quote_attr_values == "legacy":
quote_attr = quoteAttributeLegacy.search(v) is not None
else:
raise ValueError("quote_attr_values must be one of: "
"'always', 'spec', or 'legacy'")
v = v.replace("&", "&")
if self.escape_lt_in_attrs:
v = v.replace("<", "<")
if quote_attr:
quote_char = self.quote_char
if self.use_best_quote_char:
if "'" in v and '"' not in v:
quote_char = '"'
elif '"' in v and "'" not in v:
quote_char = "'"
if quote_char == "'":
v = v.replace("'", "'")
else:
v = v.replace('"', """)
yield self.encodeStrict(quote_char)
yield self.encode(v)
yield self.encodeStrict(quote_char)
else:
yield self.encode(v)
if name in voidElements and self.use_trailing_solidus:
if self.space_before_trailing_solidus:
yield self.encodeStrict(" /")
else:
yield self.encodeStrict("/")
yield self.encode(">")
elif type == "EndTag":
name = token["name"]
if name in rcdataElements:
in_cdata = False
elif in_cdata:
self.serializeError("Unexpected child element of a CDATA element")
yield self.encodeStrict("</%s>" % name)
elif type == "Comment":
data = token["data"]
if data.find("--") >= 0:
self.serializeError("Comment contains --")
yield self.encodeStrict("<!--%s-->" % token["data"])
elif type == "Entity":
name = token["name"]
key = name + ";"
if key not in entities:
self.serializeError("Entity %s not recognized" % name)
if self.resolve_entities and key not in xmlEntities:
data = entities[key]
else:
data = "&%s;" % name
yield self.encodeStrict(data)
else:
self.serializeError(token["data"])
def render(self, treewalker, encoding=None):
if encoding:
return b"".join(list(self.serialize(treewalker, encoding)))
else:
return "".join(list(self.serialize(treewalker)))
def serializeError(self, data="XXX ERROR MESSAGE NEEDED"):
# XXX The idea is to make data mandatory.
self.errors.append(data)
if self.strict:
raise SerializeError
def SerializeError(Exception):
"""Error in serialized tree"""
pass
| xss | {
"code": [
"quoteAttributeSpec = re.compile(\"[\" + spaceCharacters + \"\\\"'=<>`]\")",
" quote_attr_values = False",
" per HTML5 parsing rules.",
" if self.quote_attr_values:",
" quote_attr = len(v) == 0 or quoteAttributeSpec.search(v)"
],
"line_no": [
13,
75,
113,
242,
245
]
} | {
"code": [
"quoteAttributeSpecChars = spaceCharacters + \"\\\"'=<>`\"",
"quoteAttributeLegacy = re.compile(\"[\" + quoteAttributeSpecChars +",
" \"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\"",
" \"\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\"",
" \"\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\"",
" \"\\x20\\x2f\\x60\\xa0\\u1680\\u180e\\u180f\\u2000\"",
" \"\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\"",
" \"\\u3000]\")",
" per legacy browser behaviour, when required by the standard, or always.",
" if self.quote_attr_values == \"always\" or len(v) == 0:",
" elif self.quote_attr_values == \"spec\":",
" quote_attr = quoteAttributeSpec.search(v) is not None",
" elif self.quote_attr_values == \"legacy\":",
" quote_attr = quoteAttributeLegacy.search(v) is not None",
" raise ValueError(\"quote_attr_values must be one of: \"",
" \"'always', 'spec', or 'legacy'\")"
],
"line_no": [
13,
15,
16,
17,
18,
19,
20,
22,
122,
251,
253,
254,
255,
256,
258,
259
]
} | from __future__ import absolute_import, division, unicode_literals
from six import text_type
import re
from ..constants import .voidElements, booleanAttributes, VAR_0
from ..constants import rcdataElements, entities, xmlEntities
from .. import utils
from xml.sax.saxutils import .escape
VAR_0 = "".join(VAR_0)
VAR_1 = re.compile("[" + VAR_0 + "\"'=<>`]")
try:
from codecs import register_error, xmlcharrefreplace_errors
except ImportError:
VAR_3 = "strict"
else:
VAR_3 = "htmlentityreplace"
VAR_4 = {}
VAR_5 = len("\U0010FFFF") == 1
for VAR_38, VAR_32 in list(entities.items()):
if ((VAR_5 and len(VAR_32) > 1) or
(not VAR_5 and len(VAR_32) > 2)):
continue
if VAR_32 != "&":
if len(VAR_32) == 2:
VAR_32 = utils.surrogatePairToCodepoint(VAR_32)
else:
VAR_32 = ord(VAR_32)
if VAR_32 not in VAR_4 or VAR_38.islower():
VAR_4[VAR_32] = VAR_38
def FUNC_1(VAR_6):
if isinstance(VAR_6, (UnicodeEncodeError, UnicodeTranslateError)):
VAR_28 = []
VAR_29 = []
VAR_30 = False
for i, c in enumerate(VAR_6.object[VAR_6.start:VAR_6.end]):
if VAR_30:
skip = False
continue
VAR_33 = i + VAR_6.start
if utils.isSurrogatePair(VAR_6.object[VAR_33:min([VAR_6.end, VAR_33 + 2])]):
VAR_36 = utils.surrogatePairToCodepoint(VAR_6.object[VAR_33:index + 2])
VAR_30 = True
else:
VAR_36 = ord(c)
VAR_29.append(VAR_36)
for cp in VAR_29:
VAR_34 = VAR_4.get(cp)
if VAR_34:
VAR_28.append("&")
VAR_28.append(VAR_34)
if not VAR_34.endswith(";"):
VAR_28.append(";")
else:
VAR_28.append("&#x%s;" % (hex(cp)[2:]))
return ("".join(VAR_28), VAR_6.end)
else:
return xmlcharrefreplace_errors(VAR_6)
register_error(VAR_3, FUNC_1)
del register_error
class CLASS_0(object):
VAR_7 = False
VAR_8 = '"'
VAR_9 = True
VAR_10 = True
VAR_11 = True
VAR_12 = False
VAR_13 = True
VAR_14 = False
VAR_15 = False
VAR_16 = True
VAR_17 = False
VAR_18 = True
VAR_19 = False
VAR_20 = False
VAR_21 = ("quote_attr_values", "quote_char", "use_best_quote_char",
"omit_optional_tags", "minimize_boolean_attributes",
"use_trailing_solidus", "space_before_trailing_solidus",
"escape_lt_in_attrs", "escape_rcdata", "resolve_entities",
"alphabetical_attributes", "inject_meta_charset",
"strip_whitespace", "sanitize")
def __init__(self, **VAR_22):
if 'quote_char' in VAR_22:
self.use_best_quote_char = False
for attr in self.options:
setattr(self, attr, VAR_22.get(attr, getattr(self, attr)))
self.errors = []
self.strict = False
def FUNC_2(self, VAR_23):
assert(isinstance(VAR_23, text_type))
if self.encoding:
return VAR_23.encode(self.encoding, VAR_3)
else:
return VAR_23
def FUNC_3(self, VAR_23):
assert(isinstance(VAR_23, text_type))
if self.encoding:
return VAR_23.encode(self.encoding, "strict")
else:
return VAR_23
def FUNC_4(self, VAR_24, VAR_25=None):
self.encoding = VAR_25
VAR_27 = False
self.errors = []
if VAR_25 and self.inject_meta_charset:
from ..filters.inject_meta_charset import Filter
VAR_24 = Filter(VAR_24, VAR_25)
if self.strip_whitespace:
from ..filters.whitespace import Filter
VAR_24 = Filter(VAR_24)
if self.sanitize:
from ..filters.sanitizer import Filter
VAR_24 = Filter(VAR_24)
if self.omit_optional_tags:
from ..filters.optionaltags import Filter
VAR_24 = Filter(VAR_24)
if self.alphabetical_attributes:
from ..filters.alphabeticalattributes import Filter
VAR_24 = Filter(VAR_24)
for token in VAR_24:
VAR_31 = token["type"]
if VAR_31 == "Doctype":
VAR_35 = "<!DOCTYPE %s" % token["name"]
if token["publicId"]:
VAR_35 += ' PUBLIC "%s"' % token["publicId"]
elif token["systemId"]:
VAR_35 += " SYSTEM"
if token["systemId"]:
if token["systemId"].find('"') >= 0:
if token["systemId"].find("'") >= 0:
self.serializeError("System identifer contains both single and double quote characters")
VAR_8 = "'"
else:
VAR_8 = '"'
VAR_35 += " %s%s%s" % (VAR_8, token["systemId"], VAR_8)
VAR_35 += ">"
yield self.encodeStrict(VAR_35)
elif VAR_31 in ("Characters", "SpaceCharacters"):
if VAR_31 == "SpaceCharacters" or VAR_27:
if VAR_27 and token["data"].find("</") >= 0:
self.serializeError("Unexpected </ in CDATA")
yield self.encode(token["data"])
else:
yield self.encode(escape(token["data"]))
elif VAR_31 in ("StartTag", "EmptyTag"):
VAR_37 = token["name"]
yield self.encodeStrict("<%s" % VAR_37)
if VAR_37 in rcdataElements and not self.escape_rcdata:
VAR_27 = True
elif VAR_27:
self.serializeError("Unexpected child element of a CDATA element")
for (attr_namespace, attr_name), attr_value in token["data"].items():
VAR_38 = attr_name
VAR_32 = attr_value
yield self.encodeStrict(' ')
yield self.encodeStrict(VAR_38)
if not self.minimize_boolean_attributes or \
(VAR_38 not in booleanAttributes.get(VAR_37, tuple()) and
VAR_38 not in booleanAttributes.get("", tuple())):
yield self.encodeStrict("=")
if self.quote_attr_values:
VAR_39 = True
else:
VAR_39 = len(VAR_32) == 0 or VAR_1.search(VAR_32)
VAR_32 = VAR_32.replace("&", "&")
if self.escape_lt_in_attrs:
VAR_32 = VAR_32.replace("<", "<")
if VAR_39:
VAR_8 = self.quote_char
if self.use_best_quote_char:
if "'" in VAR_32 and '"' not in VAR_32:
VAR_8 = '"'
elif '"' in VAR_32 and "'" not in VAR_32:
VAR_8 = "'"
if VAR_8 == "'":
VAR_32 = VAR_32.replace("'", "'")
else:
VAR_32 = VAR_32.replace('"', """)
yield self.encodeStrict(VAR_8)
yield self.encode(VAR_32)
yield self.encodeStrict(VAR_8)
else:
yield self.encode(VAR_32)
if VAR_37 in voidElements and self.use_trailing_solidus:
if self.space_before_trailing_solidus:
yield self.encodeStrict(" /")
else:
yield self.encodeStrict("/")
yield self.encode(">")
elif VAR_31 == "EndTag":
VAR_37 = token["name"]
if VAR_37 in rcdataElements:
VAR_27 = False
elif VAR_27:
self.serializeError("Unexpected child element of a CDATA element")
yield self.encodeStrict("</%s>" % VAR_37)
elif VAR_31 == "Comment":
VAR_26 = token["data"]
if VAR_26.find("--") >= 0:
self.serializeError("Comment contains --")
yield self.encodeStrict("<!--%s-->" % token["data"])
elif VAR_31 == "Entity":
VAR_37 = token["name"]
VAR_40 = VAR_37 + ";"
if VAR_40 not in entities:
self.serializeError("Entity %s not recognized" % VAR_37)
if self.resolve_entities and VAR_40 not in xmlEntities:
VAR_26 = entities[VAR_40]
else:
VAR_26 = "&%s;" % VAR_37
yield self.encodeStrict(VAR_26)
else:
self.serializeError(token["data"])
def FUNC_5(self, VAR_24, VAR_25=None):
if VAR_25:
return b"".join(list(self.serialize(VAR_24, VAR_25)))
else:
return "".join(list(self.serialize(VAR_24)))
def FUNC_6(self, VAR_26="XXX ERROR MESSAGE NEEDED"):
self.errors.append(VAR_26)
if self.strict:
raise FUNC_0
def FUNC_0(VAR_2):
pass
| from __future__ import absolute_import, division, unicode_literals
from six import text_type
import re
from ..constants import .voidElements, booleanAttributes, VAR_0
from ..constants import rcdataElements, entities, xmlEntities
from .. import utils
from xml.sax.saxutils import .escape
VAR_0 = "".join(VAR_0)
VAR_1 = VAR_0 + "\"'=<>`"
VAR_2 = re.compile("[" + VAR_1 + "]")
VAR_3 = re.compile("[" + VAR_1 +
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n"
"\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15"
"\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
"\x20\x2f\x60\xa0\u1680\u180e\u180f\u2000"
"\u2001\u2002\u2003\u2004\u2005\u2006\u2007"
"\u2008\u2009\u200a\u2028\u2029\u202f\u205f"
"\u3000]")
try:
from codecs import register_error, xmlcharrefreplace_errors
except ImportError:
VAR_5 = "strict"
else:
VAR_5 = "htmlentityreplace"
VAR_6 = {}
VAR_7 = len("\U0010FFFF") == 1
for VAR_40, VAR_34 in list(entities.items()):
if ((VAR_7 and len(VAR_34) > 1) or
(not VAR_7 and len(VAR_34) > 2)):
continue
if VAR_34 != "&":
if len(VAR_34) == 2:
VAR_34 = utils.surrogatePairToCodepoint(VAR_34)
else:
VAR_34 = ord(VAR_34)
if VAR_34 not in VAR_6 or VAR_40.islower():
VAR_6[VAR_34] = VAR_40
def FUNC_1(VAR_8):
if isinstance(VAR_8, (UnicodeEncodeError, UnicodeTranslateError)):
VAR_30 = []
VAR_31 = []
VAR_32 = False
for i, c in enumerate(VAR_8.object[VAR_8.start:VAR_8.end]):
if VAR_32:
skip = False
continue
VAR_35 = i + VAR_8.start
if utils.isSurrogatePair(VAR_8.object[VAR_35:min([VAR_8.end, VAR_35 + 2])]):
VAR_38 = utils.surrogatePairToCodepoint(VAR_8.object[VAR_35:index + 2])
VAR_32 = True
else:
VAR_38 = ord(c)
VAR_31.append(VAR_38)
for cp in VAR_31:
VAR_36 = VAR_6.get(cp)
if VAR_36:
VAR_30.append("&")
VAR_30.append(VAR_36)
if not VAR_36.endswith(";"):
VAR_30.append(";")
else:
VAR_30.append("&#x%s;" % (hex(cp)[2:]))
return ("".join(VAR_30), VAR_8.end)
else:
return xmlcharrefreplace_errors(VAR_8)
register_error(VAR_5, FUNC_1)
del register_error
class CLASS_0(object):
VAR_9 = "legacy" # be secure by default
VAR_10 = '"'
VAR_11 = True
VAR_12 = True
VAR_13 = True
VAR_14 = False
VAR_15 = True
VAR_16 = False
VAR_17 = False
VAR_18 = True
VAR_19 = False
VAR_20 = True
VAR_21 = False
VAR_22 = False
VAR_23 = ("quote_attr_values", "quote_char", "use_best_quote_char",
"omit_optional_tags", "minimize_boolean_attributes",
"use_trailing_solidus", "space_before_trailing_solidus",
"escape_lt_in_attrs", "escape_rcdata", "resolve_entities",
"alphabetical_attributes", "inject_meta_charset",
"strip_whitespace", "sanitize")
def __init__(self, **VAR_24):
if 'quote_char' in VAR_24:
self.use_best_quote_char = False
for attr in self.options:
setattr(self, attr, VAR_24.get(attr, getattr(self, attr)))
self.errors = []
self.strict = False
def FUNC_2(self, VAR_25):
assert(isinstance(VAR_25, text_type))
if self.encoding:
return VAR_25.encode(self.encoding, VAR_5)
else:
return VAR_25
def FUNC_3(self, VAR_25):
assert(isinstance(VAR_25, text_type))
if self.encoding:
return VAR_25.encode(self.encoding, "strict")
else:
return VAR_25
def FUNC_4(self, VAR_26, VAR_27=None):
self.encoding = VAR_27
VAR_29 = False
self.errors = []
if VAR_27 and self.inject_meta_charset:
from ..filters.inject_meta_charset import Filter
VAR_26 = Filter(VAR_26, VAR_27)
if self.strip_whitespace:
from ..filters.whitespace import Filter
VAR_26 = Filter(VAR_26)
if self.sanitize:
from ..filters.sanitizer import Filter
VAR_26 = Filter(VAR_26)
if self.omit_optional_tags:
from ..filters.optionaltags import Filter
VAR_26 = Filter(VAR_26)
if self.alphabetical_attributes:
from ..filters.alphabeticalattributes import Filter
VAR_26 = Filter(VAR_26)
for token in VAR_26:
VAR_33 = token["type"]
if VAR_33 == "Doctype":
VAR_37 = "<!DOCTYPE %s" % token["name"]
if token["publicId"]:
VAR_37 += ' PUBLIC "%s"' % token["publicId"]
elif token["systemId"]:
VAR_37 += " SYSTEM"
if token["systemId"]:
if token["systemId"].find('"') >= 0:
if token["systemId"].find("'") >= 0:
self.serializeError("System identifer contains both single and double quote characters")
VAR_10 = "'"
else:
VAR_10 = '"'
VAR_37 += " %s%s%s" % (VAR_10, token["systemId"], VAR_10)
VAR_37 += ">"
yield self.encodeStrict(VAR_37)
elif VAR_33 in ("Characters", "SpaceCharacters"):
if VAR_33 == "SpaceCharacters" or VAR_29:
if VAR_29 and token["data"].find("</") >= 0:
self.serializeError("Unexpected </ in CDATA")
yield self.encode(token["data"])
else:
yield self.encode(escape(token["data"]))
elif VAR_33 in ("StartTag", "EmptyTag"):
VAR_39 = token["name"]
yield self.encodeStrict("<%s" % VAR_39)
if VAR_39 in rcdataElements and not self.escape_rcdata:
VAR_29 = True
elif VAR_29:
self.serializeError("Unexpected child element of a CDATA element")
for (attr_namespace, attr_name), attr_value in token["data"].items():
VAR_40 = attr_name
VAR_34 = attr_value
yield self.encodeStrict(' ')
yield self.encodeStrict(VAR_40)
if not self.minimize_boolean_attributes or \
(VAR_40 not in booleanAttributes.get(VAR_39, tuple()) and
VAR_40 not in booleanAttributes.get("", tuple())):
yield self.encodeStrict("=")
if self.quote_attr_values == "always" or len(VAR_34) == 0:
VAR_41 = True
elif self.quote_attr_values == "spec":
VAR_41 = VAR_2.search(VAR_34) is not None
elif self.quote_attr_values == "legacy":
VAR_41 = VAR_3.search(VAR_34) is not None
else:
raise ValueError("quote_attr_values must be one of: "
"'always', 'spec', or 'legacy'")
VAR_34 = v.replace("&", "&")
if self.escape_lt_in_attrs:
VAR_34 = v.replace("<", "<")
if VAR_41:
VAR_10 = self.quote_char
if self.use_best_quote_char:
if "'" in VAR_34 and '"' not in VAR_34:
VAR_10 = '"'
elif '"' in VAR_34 and "'" not in VAR_34:
VAR_10 = "'"
if VAR_10 == "'":
VAR_34 = v.replace("'", "'")
else:
VAR_34 = v.replace('"', """)
yield self.encodeStrict(VAR_10)
yield self.encode(VAR_34)
yield self.encodeStrict(VAR_10)
else:
yield self.encode(VAR_34)
if VAR_39 in voidElements and self.use_trailing_solidus:
if self.space_before_trailing_solidus:
yield self.encodeStrict(" /")
else:
yield self.encodeStrict("/")
yield self.encode(">")
elif VAR_33 == "EndTag":
VAR_39 = token["name"]
if VAR_39 in rcdataElements:
VAR_29 = False
elif VAR_29:
self.serializeError("Unexpected child element of a CDATA element")
yield self.encodeStrict("</%s>" % VAR_39)
elif VAR_33 == "Comment":
VAR_28 = token["data"]
if VAR_28.find("--") >= 0:
self.serializeError("Comment contains --")
yield self.encodeStrict("<!--%s-->" % token["data"])
elif VAR_33 == "Entity":
VAR_39 = token["name"]
VAR_42 = VAR_39 + ";"
if VAR_42 not in entities:
self.serializeError("Entity %s not recognized" % VAR_39)
if self.resolve_entities and VAR_42 not in xmlEntities:
VAR_28 = entities[VAR_42]
else:
VAR_28 = "&%s;" % VAR_39
yield self.encodeStrict(VAR_28)
else:
self.serializeError(token["data"])
def FUNC_5(self, VAR_26, VAR_27=None):
if VAR_27:
return b"".join(list(self.serialize(VAR_26, VAR_27)))
else:
return "".join(list(self.serialize(VAR_26)))
def FUNC_6(self, VAR_28="XXX ERROR MESSAGE NEEDED"):
self.errors.append(VAR_28)
if self.strict:
raise FUNC_0
def FUNC_0(VAR_4):
pass
| [
3,
5,
10,
12,
14,
21,
25,
35,
37,
66,
68,
70,
71,
73,
74,
78,
79,
84,
85,
89,
90,
95,
102,
105,
107,
146,
155,
162,
169,
174,
178,
179,
189,
190,
194,
199,
212,
215,
223,
232,
236,
271,
279,
285,
296,
299,
305,
307,
311,
312,
316,
314,
104,
105,
106,
107,
108,
109,
110,
111,
112,
113,
114,
115,
116,
117,
118,
119,
120,
121,
122,
123,
124,
125,
126,
127,
128,
129,
130,
131,
132,
133,
134,
135,
136,
137,
138,
139,
140,
141,
142,
143,
144,
145,
146,
147,
148
] | [
3,
5,
10,
12,
23,
30,
34,
44,
46,
75,
77,
79,
80,
82,
83,
87,
88,
93,
94,
98,
99,
104,
111,
114,
116,
155,
164,
171,
178,
183,
187,
188,
198,
199,
203,
208,
221,
224,
232,
241,
245,
285,
293,
299,
310,
313,
319,
321,
325,
326,
330,
328,
113,
114,
115,
116,
117,
118,
119,
120,
121,
122,
123,
124,
125,
126,
127,
128,
129,
130,
131,
132,
133,
134,
135,
136,
137,
138,
139,
140,
141,
142,
143,
144,
145,
146,
147,
148,
149,
150,
151,
152,
153,
154,
155,
156,
157
] |
1CWE-79
| "#\n# djblets_js.py -- JavaScript-related template tags\n#\n# Copyright (c) 2007-2009 Christian Ham(...TRUNCATED) | "#\n# djblets_js.py -- JavaScript-related template tags\n#\n# Copyright (c) 2007-2009 Christian Ham(...TRUNCATED) | xss | {
"code": [
" return mark_safe(result)"
],
"line_no": [
78
]
} | {"code":["from django.utils.encoding import force_text","_safe_js_escapes = {"," ord('&'): '\\\\u(...TRUNCATED) | "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom __future__ import unicode_literals\n\nimport(...TRUNCATED) | "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom __future__ import unicode_literals\n\nimport(...TRUNCATED) | [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,27,29,35,37,38,40,41,50,53,58,61,(...TRUNCATED) | [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,27,29,36,38,39,41,47,48,57,60,65,(...TRUNCATED) |
1CWE-79
| "# -*- coding: utf-8 -*-\n# This file is part of Shuup.\n#\n# Copyright (c) 2012-2021, Shuup Commerc(...TRUNCATED) | "# -*- coding: utf-8 -*-\n# This file is part of Shuup.\n#\n# Copyright (c) 2012-2021, Shuup Commerc(...TRUNCATED) | xss | {"code":[" url(r\"^xtheme/(?P<view>.+)/*$\", extra_view_dispatch, name=\"xtheme_extra_view\"),"],(...TRUNCATED) | {"code":[" url(r\"^xtheme/(?P<view>.+)/?$\", extra_view_dispatch, name=\"xtheme_extra_view\"),"],(...TRUNCATED) | "\n\n\n\n\n\n\nfrom django.conf.urls import url\n\nfrom shuup.xtheme.views.command import command_di(...TRUNCATED) | "\n\n\n\n\n\n\nfrom django.conf.urls import url\n\nfrom shuup.xtheme.views.command import command_di(...TRUNCATED) | [
1,
2,
3,
4,
5,
6,
7,
9,
19,
49
] | [
1,
2,
3,
4,
5,
6,
7,
9,
19,
49
] |
2CWE-601
| "# -*- coding: utf-8 -*-\n# Copyright 2015, 2016 OpenMarket Ltd\n# Copyright 2017 Vector Creations L(...TRUNCATED) | "# -*- coding: utf-8 -*-\n# Copyright 2015, 2016 OpenMarket Ltd\n# Copyright 2017 Vector Creations L(...TRUNCATED) | open_redirect | {"code":[" self.addCleanup, http_client=self.mock_http_client, keyring=Mock(),"],"line_no(...TRUNCATED) | {"code":[" self.addCleanup,"," federation_http_client=self.mock_http_client,"](...TRUNCATED) | "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom mock import Mock\n\nimport jsonschema\n\nfrom twisted.inte(...TRUNCATED) | "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom mock import Mock\n\nimport jsonschema\n\nfrom twisted.inte(...TRUNCATED) | [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20,22,24,29,32,34,35,42,43,48,51,55,57,59,74,115,116,1(...TRUNCATED) | [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20,22,24,29,32,34,35,42,43,48,51,57,59,61,76,117,118,1(...TRUNCATED) |
1CWE-79
| "# coding: utf-8\n\"\"\"\n mistune\n ~~~~~~~\n\n The fastest markdown parser in pure Python(...TRUNCATED) | "# coding: utf-8\n\"\"\"\n mistune\n ~~~~~~~\n\n The fastest markdown parser in pure Python(...TRUNCATED) | xss | {"code":["__version__ = '0.8'"," return _key_pattern.sub(' ', key.lower())"," r'<(\\w+(...TRUNCATED) | {"code":["__version__ = '0.8.1'"," key = escape(key.lower(), quote=True)"," r'<(\\w+%s(...TRUNCATED) | "\n\n\n\n\n\n\n\n\n\nimport re\nimport .inspect\n\n__version__ = '0.8'\n__author__ = 'Hsiaoming Yang(...TRUNCATED) | "\n\n\n\n\n\n\n\n\n\nimport re\nimport .inspect\n\n__version__ = '0.8.1'\n__author__ = 'Hsiaoming Ya(...TRUNCATED) | [1,5,7,10,13,22,23,41,42,48,49,52,53,56,59,73,74,78,83,84,91,92,95,107,169,170,174,181,186,192,197,2(...TRUNCATED) | [1,5,7,10,13,22,23,41,42,48,49,53,54,57,60,74,75,79,84,85,92,93,96,108,170,171,175,182,187,193,198,2(...TRUNCATED) |
1CWE-79
| "#\n# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>\n#\n# This file is part of Weblate (...TRUNCATED) | "#\n# Copyright © 2012–2022 Michal Čihař <michal@cihar.com>\n#\n# This file is part of Weblate (...TRUNCATED) | xss | {
"code": [
" label = str(unit.translation.language)"
],
"line_no": [
321
]
} | {"code":["from django.utils.html import escape"," label = escape(unit.translation.languag(...TRUNCATED) | "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport copy\nimport json\nimport re\nfrom datetime import dat(...TRUNCATED) | "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport copy\nimport json\nimport re\nfrom datetime import dat(...TRUNCATED) | [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,25,45,92,108,109,118,119,127,128,134,143,144,147,15(...TRUNCATED) | [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,25,46,93,109,110,119,120,128,129,135,144,145,148,15(...TRUNCATED) |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 1