code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''Build the documentation'''
header(doc.__doc__)
with ctx.cd(os.path.join(ROOT, 'doc')):
ctx.run('make html', pty=True)
success('Documentation available in doc/_build/html') | def doc(ctx) | Build the documentation | 5.963365 | 6.091884 | 0.978903 |
'''Generate bash completion script'''
header(completion.__doc__)
with ctx.cd(ROOT):
ctx.run('_bumpr_COMPLETE=source bumpr > bumpr-complete.sh', pty=True)
success('Completion generated in bumpr-complete.sh') | def completion(ctx) | Generate bash completion script | 15.084373 | 14.507184 | 1.039786 |
security = get_service("security")
return security.has_permission(current_user, view.permission, self.obj) | def _check_view_permission(self, view) | :param view: a :class:`ObjectView` class or instance | 9.594598 | 8.107435 | 1.183432 |
if not issubclass(cls, Entity):
raise ValueError("Class must be a subclass of abilian.core.entities.Entity")
SupportTagging.register(cls)
return cls | def register(cls) | Register an :class:`~.Entity` as a taggable class.
Can be used as a class decorator:
.. code-block:: python
@tag.register
class MyContent(Entity):
.... | 9.36909 | 13.712592 | 0.683247 |
if isinstance(obj, type):
return issubclass(obj, SupportTagging)
if not isinstance(obj, SupportTagging):
return False
if obj.id is None:
return False
return True | def supports_tagging(obj) | :param obj: a class or instance | 4.555643 | 3.462037 | 1.315885 |
if not issubclass(cls, Entity):
raise ValueError("Class must be a subclass of abilian.core.entities.Entity")
SupportAttachment.register(cls)
return cls | def register(cls) | Register an :class:`~.Entity` as a attachmentable class.
Can be used as a class decorator:
.. code-block:: python
@attachment.register
class MyContent(Entity):
.... | 8.884147 | 12.539244 | 0.708507 |
if isinstance(obj, type):
return issubclass(obj, SupportAttachment)
if not isinstance(obj, SupportAttachment):
return False
if obj.id is None:
return False
return True | def supports_attachments(obj) | :param obj: a class or instance
:returns: True is obj supports attachments. | 3.943413 | 3.826373 | 1.030588 |
if check_support_attachments and not supports_attachments(obj):
return []
return getattr(obj, ATTRIBUTE) | def for_entity(obj, check_support_attachments=False) | Return attachments on an entity. | 7.086302 | 5.145982 | 1.377055 |
if target.label is not None:
target.label = target.label.strip() | def strip_label(mapper, connection, target) | Strip labels at ORM level so the unique=True means something. | 3.333447 | 3.032547 | 1.099224 |
if target.position is None:
func = sa.sql.func
stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)])
target.position = connection.execute(stmt).scalar() + 1 | def _before_insert(mapper, connection, target) | Set item to last position if position not defined. | 3.768742 | 3.000254 | 1.256141 |
# don't use .first(), so that MultipleResultsFound can be raised
try:
return self.filter_by(label=label).one()
except sa.orm.exc.NoResultFound:
return None | def by_label(self, label) | Like `.get()`, but by label. | 5.197074 | 4.719105 | 1.101284 |
# don't use .first(), so that MultipleResultsFound can be raised
try:
return self.filter_by(position=position).one()
except sa.orm.exc.NoResultFound:
return None | def by_position(self, position) | Like `.get()`, but by position number. | 5.867929 | 5.593874 | 1.048992 |
if self.testing:
return
# Before destroying the session, get all instances to be attached to the
# new session. Without this, we get DetachedInstance errors, like when
# tryin to get user's attribute in the error page...
old_session = db.session()
g_o... | def _remove_session_save_objects(self) | Used during exception handling in case we need to remove() session:
keep instances and merge them in the new session. | 5.338134 | 5.066132 | 1.05369 |
dsn = self.config.get("SENTRY_DSN")
if not dsn:
super().log_exception(exc_info) | def log_exception(self, exc_info) | Log exception only if Sentry is not used (this avoids getting error
twice in Sentry). | 4.634789 | 3.035526 | 1.526849 |
dsn = self.config.get("SENTRY_DSN")
if not dsn:
return
try:
import sentry_sdk
except ImportError:
logger.error(
'SENTRY_DSN is defined in config but package "sentry-sdk"'
" is not installed."
)
... | def init_sentry(self) | Install Sentry handler if config defines 'SENTRY_DSN'. | 2.493791 | 2.167394 | 1.150594 |
logger.debug(
"Set Default HTTP error handler for status code %d", http_error_code
)
handler = partial(self.handle_http_error, http_error_code)
self.errorhandler(http_error_code)(handler) | def install_default_handler(self, http_error_code) | Install a default error handler for `http_error_code`.
The default error handler renders a template named error404.html
for http_error_code 404. | 3.792986 | 3.834358 | 0.98921 |
# 5xx code: error on server side
if (code // 100) == 5:
# ensure rollback if needed, else error page may
# have an error, too, resulting in raw 500 page :-(
db.session.rollback()
template = f"error{code:d}.html"
return render_template(templat... | def handle_http_error(self, code, error) | Helper that renders `error{code}.html`.
Convenient way to use it::
from functools import partial
handler = partial(app.handle_http_error, code)
app.errorhandler(code)(handler) | 9.780354 | 9.417379 | 1.038543 |
if not inspect.isclass(entity):
entity = entity.__class__
assert issubclass(entity, db.Model)
self._map[entity.entity_type] = url_func | def register(self, entity, url_func) | Associate a `url_func` with entity's type.
:param:entity: an :class:`abilian.core.extensions.db.Model` class or
instance.
:param:url_func: any callable that accepts an entity instance and
return an url for it. | 4.338499 | 4.774372 | 0.908706 |
if object_type is None:
assert isinstance(entity, (db.Model, Hit, dict))
getter = attrgetter if isinstance(entity, db.Model) else itemgetter
object_id = getter("id")(entity)
object_type = getter("object_type")(entity)
url_func = self._map.get(obj... | def url_for(self, entity=None, object_type=None, object_id=None, **kwargs) | Return canonical view URL for given entity instance.
If no view has been registered the registry will try to find an
endpoint named with entity's class lowercased followed by '.view'
and that accepts `object_id=entity.id` to generates an url.
:param entity: a instance of a subclass of
... | 3.348638 | 3.012069 | 1.11174 |
from abilian.services.repository import session_repository as repository
return repository.get(self, self.uuid) | def file(self) | Return :class:`pathlib.Path` object used for storing value. | 20.78739 | 17.137363 | 1.212986 |
# type: () -> bytes
v = self.file
return v.open("rb").read() if v is not None else v | def value(self) | Binary value content. | 13.432588 | 10.446829 | 1.285805 |
from abilian.services.repository import session_repository as repository
repository.set(self, self.uuid, value)
self.meta["md5"] = str(hashlib.md5(self.value).hexdigest())
if hasattr(value, "filename"):
filename = value.filename
if isinstance(filename, ... | def value(self, value, encoding="utf-8") | Store binary content to applications's repository and update
`self.meta['md5']`.
:param:content: string, bytes, or any object with a `read()` method
:param:encoding: encoding to use when content is Unicode | 3.72544 | 3.569225 | 1.043767 |
from abilian.services.repository import session_repository as repository
repository.delete(self, self.uuid) | def value(self) | Remove value from repository. | 30.018539 | 16.640854 | 1.803906 |
md5 = self.meta.get("md5")
if md5 is None:
md5 = str(hashlib.md5(self.value).hexdigest())
return md5 | def md5(self) | Return md5 from meta, or compute it if absent. | 3.64848 | 2.554555 | 1.428225 |
email = request.form.get("email", "").lower()
action = request.form.get("action")
if action == "cancel":
return redirect(url_for("login.login_form"))
if not email:
flash(_("You must provide your email address."), "error")
return render_template("login/forgotten_password.ht... | def forgotten_pw(new_user=False) | Reset password for users who have already activated their accounts. | 2.384445 | 2.388738 | 0.998203 |
# type: (User) -> None
token = generate_reset_password_token(user)
url = url_for("login.reset_password", token=token)
reset_link = request.url_root[:-1] + url
subject = _("Password reset instruction for {site_name}").format(
site_name=current_app.config.get("SITE_NAME")
)
mail_... | def send_reset_password_instructions(user) | Send the reset password instructions email for the specified user.
:param user: The user to send the instructions to | 2.575942 | 3.513083 | 0.733243 |
# type: (User) -> Any
data = [str(user.id), md5(user.password)]
return get_serializer("reset").dumps(data) | def generate_reset_password_token(user) | Generate a unique reset password token for the specified user.
:param user: The user to work with | 9.222548 | 18.977798 | 0.485965 |
config = current_app.config
sender = config["MAIL_SENDER"]
msg = Message(subject, sender=sender, recipients=[recipient])
template_name = f"login/email/{template}.txt"
msg.body = render_template_i18n(template_name, **context)
# msg.html = render_template('%s/%s.html' % ctx, **context)
... | def send_mail(subject, recipient, template, **context) | Send an email using the Flask-Mail extension.
:param subject: Email subject
:param recipient: Email recipient
:param template: The name of the email template
:param context: The context to render the template with | 3.364607 | 3.358734 | 1.001749 |
logger.info("Registering plugin: " + name)
module = importlib.import_module(name)
module.register_plugin(self) | def register_plugin(self, name) | Load and register a plugin given its package name. | 3.133574 | 3.19837 | 0.979741 |
registered = set()
for plugin_fqdn in chain(self.APP_PLUGINS, self.config["PLUGINS"]):
if plugin_fqdn not in registered:
self.register_plugin(plugin_fqdn)
registered.add(plugin_fqdn) | def register_plugins(self) | Load plugins listed in config variable 'PLUGINS'. | 3.916609 | 3.407967 | 1.149251 |
g.breadcrumb.append(BreadcrumbItem(icon="home", url="/" + request.script_root)) | def init_breadcrumbs(self) | Insert the first element in breadcrumbs.
This happens during `request_started` event, which is triggered
before any url_value_preprocessor and `before_request` handlers. | 19.887375 | 19.531025 | 1.018245 |
path = Path(self.instance_path)
err = None
eno = 0
if not path.exists():
if create:
logger.info("Create instance folder: %s", path)
path.mkdir(0o775, parents=True)
else:
err = "Instance folder does not exis... | def check_instance_folder(self, create=False) | Verify instance folder exists, is a directory, and has necessary
permissions.
:param:create: if `True`, creates directory hierarchy
:raises: OSError with relevant errno if something is wrong. | 2.683024 | 2.696463 | 0.995016 |
extensions.redis.init_app(self)
extensions.mail.init_app(self)
extensions.deferred_js.init_app(self)
extensions.upstream_info.extension.init_app(self)
actions.init_app(self)
# auth_service installs a `before_request` handler (actually it's
# flask-login)... | def init_extensions(self) | Initialize flask extensions, helpers and services. | 5.08305 | 5.067577 | 1.003053 |
super().add_url_rule(rule, endpoint, view_func, **options)
if roles:
self.add_access_controller(
endpoint, allow_access_for_roles(roles), endpoint=True
) | def add_url_rule(self, rule, endpoint=None, view_func=None, roles=None, **options) | See :meth:`Flask.add_url_rule`.
If `roles` parameter is present, it must be a
:class:`abilian.service.security.models.Role` instance, or a list of
Role instances. | 5.336637 | 6.499238 | 0.821117 |
auth_state = self.extensions[auth_service.name]
adder = auth_state.add_bp_access_controller
if endpoint:
adder = auth_state.add_endpoint_access_controller
if not isinstance(name, str):
msg = "{} is not a valid endpoint name".format(repr(name))
... | def add_access_controller(self, name: str, func: Callable, endpoint: bool = False) | Add an access controller.
If `name` is None it is added at application level, else if is
considered as a blueprint name. If `endpoint` is True then it is
considered as an endpoint. | 4.676203 | 4.202653 | 1.112679 |
url_path = self.static_url_path + "/" + url_path + "/<path:filename>"
self.add_url_rule(
url_path,
endpoint=endpoint,
view_func=partial(send_file_from_directory, directory=directory),
roles=roles,
)
self.add_access_controller(
... | def add_static_url(self, url_path, directory, endpoint=None, roles=None) | Add a new url rule for static files.
:param url_path: subpath from application static url path. No heading
or trailing slash.
:param directory: directory to serve content from.
:param endpoint: flask endpoint name for this url rule.
Example::
app.add_static_url(... | 4.022279 | 5.492117 | 0.732373 |
sender = current_app.config["MAIL_SENDER"]
if not self.extra_headers:
self.extra_headers = {}
self.extra_headers["Sender"] = sender
connection.send(self, sender) | def _message_send(self, connection) | Send a single message instance.
If TESTING is True the message will not actually be sent.
:param self: a Message instance. | 4.716871 | 5.365829 | 0.879057 |
engine = connection.engine.name
default_engines = (engine,)
tables = target if isinstance(target, sa.Table) else kw.get("tables", [])
for table in tables:
indexes = list(table.indexes)
for idx in indexes:
if engine not in idx.info.get("engines", default_engines):
... | def _filter_metadata_for_connection(target, connection, **kw) | Listener to control what indexes get created.
Useful for skipping postgres-specific indexes on a sqlite for example.
It's looking for info entry `engines` on an index
(`Index(info=dict(engines=['postgresql']))`), an iterable of engine names. | 4.703155 | 3.987936 | 1.179346 |
if isinstance(obj, str):
return flask_url_for(obj, **kw)
try:
return current_app.default_view.url_for(obj, **kw)
except KeyError:
if hasattr(obj, "_url"):
return obj._url
elif hasattr(obj, "url"):
return obj.url
raise BuildError(repr(obj), k... | def url_for(obj, **kw) | Polymorphic variant of Flask's `url_for` function.
Behaves like the original function when the first argument is a
string. When it's an object, it | 4.231553 | 5.19801 | 0.814072 |
if app is None:
app = current_app
cache_timeout = app.get_send_file_max_age(filename)
return send_from_directory(directory, filename, cache_timeout=cache_timeout) | def send_file_from_directory(filename, directory, app=None) | Helper to add static rules, like in `abilian.app`.app.
Example use::
app.add_url_rule(
app.static_url_path + '/abilian/<path:filename>',
endpoint='abilian_static',
view_func=partial(send_file_from_directory,
directory='/path/to/static/files/dir')) | 2.119879 | 2.761697 | 0.7676 |
# type: (Text, int, int, int, int, datetime) -> Query
query = AuditEntry.query
if since:
query = query.filter(AuditEntry.happened_at >= since)
if year:
query = query.filter(extract("year", AuditEntry.happened_at) == year)
if month:
query = query.filter(extract("month",... | def get_model_changes(
entity_type, year=None, month=None, day=None, hour=None, since=None
) | Get models modified at the given date with the Audit service.
:param entity_type: string like "extranet_medicen.apps.crm.models.Compte".
Beware the typo, there won't be a warning message.
:param since: datetime
:param year: int
:param month: int
:param day: int
:param hour: int
:retu... | 1.825019 | 1.925092 | 0.948017 |
for change in changes:
change.diff = []
elt_changes = change.get_changes()
if elt_changes:
change.diff = elt_changes.columns
return changes | def get_columns_diff(changes) | Add the changed columns as a diff attribute.
- changes: a list of changes (get_model_changes query.all())
Return: the same list, to which elements we added a "diff"
attribute containing the changed columns. Diff defaults to []. | 5.730276 | 5.319869 | 1.077146 |
if hasattr(inspect, 'signature'):
# New way in python 3.3
sig = inspect.signature(func)
return bool(sig.parameters)
else:
# Old way
return bool(inspect.getargspec(func).args) | def _has_argument(func) | Test whether a function expects an argument.
:param func:
The function to be tested for existence of an argument. | 2.70422 | 3.541385 | 0.763605 |
# Coerce search to an absolute path if it is not already
if not os.path.isabs(searchpath):
# TODO: Determine if there is a better way to write do this
calling_module = inspect.getmodule(inspect.stack()[-1][0])
# Absolute path to project
project_pa... | def make_site(cls,
searchpath="templates",
outpath=".",
contexts=None,
rules=None,
encoding="utf8",
followlinks=True,
extensions=None,
staticpaths=None,
filte... | Create a :class:`Site <Site>` object.
:param searchpath:
A string representing the absolute path to the directory that the
Site should search to discover templates. Defaults to
``'templates'``.
If a relative path is provided, it will be coerced to an absolute
... | 2.399706 | 2.407961 | 0.996572 |
context = {}
for regex, context_generator in self.contexts:
if re.match(regex, template.name):
if inspect.isfunction(context_generator):
if _has_argument(context_generator):
context.update(context_generator(template))
... | def get_context(self, template) | Get the context for a template.
If no matching value is found, an empty context is returned.
Otherwise, this returns either the matching value if the value is
dictionary-like or the dictionary returned by calling it with
*template* if the value is a function.
If several matchin... | 3.428899 | 3.369294 | 1.017691 |
for regex, render_func in self.rules:
if re.match(regex, template_name):
return render_func
raise ValueError("no matching rule") | def get_rule(self, template_name) | Find a matching compilation rule for a function.
Raises a :exc:`ValueError` if no matching rule can be found.
:param template_name: the name of the template | 4.336789 | 6.711168 | 0.646205 |
if self.staticpaths is None:
# We're not using static file support
return False
for path in self.staticpaths:
if filename.startswith(path):
return True
return False | def is_static(self, filename) | Check if a file is a static file (which should be copied, rather
than compiled using Jinja2).
A file is considered static if it lives in any of the directories
specified in ``staticpaths``.
:param filename: the name of the file to check | 4.316805 | 4.990994 | 0.864919 |
return any((x.startswith("_") for x in filename.split(os.path.sep))) | def is_partial(self, filename) | Check if a file is a partial.
Partial files are not rendered, but they are used in rendering
templates.
A file is considered a partial if it or any of its parent directories
are prefixed with an ``'_'``.
:param filename: the name of the file to check | 6.538516 | 9.151727 | 0.714457 |
if self.is_partial(filename):
return False
if self.is_ignored(filename):
return False
if self.is_static(filename):
return False
return True | def is_template(self, filename) | Check if a file is a template.
A file is a considered a template if it is neither a partial nor
ignored.
:param filename: the name of the file to check | 3.299194 | 3.147649 | 1.048145 |
head = os.path.dirname(template_name)
if head:
file_dirpath = os.path.join(self.outpath, head)
if not os.path.exists(file_dirpath):
os.makedirs(file_dirpath) | def _ensure_dir(self, template_name) | Ensure the output directory for a template exists. | 2.646461 | 2.552508 | 1.036808 |
self.logger.info("Rendering %s..." % template.name)
if context is None:
context = self.get_context(template)
if not os.path.exists(self.outpath):
os.makedirs(self.outpath)
self._ensure_dir(template.name)
try:
rule = self.get_rule(te... | def render_template(self, template, context=None, filepath=None) | Render a single :class:`jinja2.Template` object.
If a Rule matching the template is found, the rendering task is
delegated to the rule.
:param template:
A :class:`jinja2.Template` to render.
:param context:
Optional. A dictionary representing the context to ren... | 2.972075 | 2.40521 | 1.235682 |
for template in templates:
self.render_template(template, filepath) | def render_templates(self, templates, filepath=None) | Render a collection of :class:`jinja2.Template` objects.
:param templates:
A collection of Templates to render.
:param filepath:
Optional. A file or file-like object to dump the complete template
stream into. Defaults to to ``os.path.join(self.outpath,
t... | 4.064162 | 7.45469 | 0.545182 |
if self.is_partial(filename):
return self.templates
elif self.is_template(filename):
return [self.get_template(filename)]
elif self.is_static(filename):
return [filename]
else:
return [] | def get_dependencies(self, filename) | Get a list of files that depends on the file named *filename*.
:param filename: the name of the file to find dependencies of | 3.408899 | 4.254858 | 0.801178 |
self.render_templates(self.templates)
self.copy_static(self.static_names)
if use_reloader:
self.logger.info("Watching '%s' for changes..." %
self.searchpath)
self.logger.info("Press Ctrl+C to stop.")
Reloader(self).watch(... | def render(self, use_reloader=False) | Generate the site.
:param use_reloader: if given, reload templates on modification | 4.633402 | 5.065343 | 0.914726 |
if not hasattr(self, "_jinja_loaders"):
raise ValueError(
"Cannot register new jinja loaders after first template rendered"
)
self._jinja_loaders.extend(loaders) | def register_jinja_loaders(self, *loaders) | Register one or many `jinja2.Loader` instances for templates lookup.
During application initialization plugins can register a loader so that
their templates are available to jinja2 renderer.
Order of registration matters: last registered is first looked up (after
standard Flask lookup ... | 5.692066 | 6.334316 | 0.898608 |
loaders = self._jinja_loaders
del self._jinja_loaders
loaders.append(Flask.jinja_loader.func(self))
loaders.reverse()
return jinja2.ChoiceLoader(loaders) | def jinja_loader(self) | Search templates in custom app templates dir (default Flask
behaviour), fallback on abilian templates. | 5.524589 | 4.645809 | 1.189155 |
srcpath = (
os.path.join(os.getcwd(), 'templates') if args['--srcpath'] is None
else args['--srcpath'] if os.path.isabs(args['--srcpath'])
else os.path.join(os.getcwd(), args['--srcpath'])
)
if not os.path.isdir(srcpath):
print("The templates directory '%s' is invalid."... | def render(args) | Render a site.
:param args:
A map from command-line options to their values. For example:
{
'--help': False,
'--outpath': None,
'--srcpath': None,
'--static': None,
'--version': False,
'build': True... | 2.195519 | 2.039671 | 1.076408 |
principal = unwrap(principal)
if hasattr(principal, "is_anonymous") and principal.is_anonymous:
# transform anonymous user to anonymous role
principal = Anonymous
if isinstance(principal, Role):
return f"role:{principal.name}"
elif isinstance(principal, User):
fmt ... | def indexable_role(principal) | Return a string suitable for query against `allowed_roles_and_users`
field.
:param principal: It can be :data:`Anonymous`, :data:`Authenticated`,
or an instance of :class:`User` or :class:`Group`. | 3.363099 | 3.514575 | 0.956901 |
# Special case, for now (XXX).
if mime_type.startswith("image/"):
return ""
cache_key = "txt:" + digest
text = self.cache.get(cache_key)
if text:
return text
# Direct conversion possible
for handler in self.handlers:
... | def to_text(self, digest, blob, mime_type) | Convert a file to plain text.
Useful for full-text indexing. Returns a Unicode string. | 3.323106 | 3.304276 | 1.005699 |
cache_key = f"img:{index}:{size}:{digest}"
return mime_type.startswith("image/") or cache_key in self.cache | def has_image(self, digest, mime_type, index, size=500) | Tell if there is a preview image. | 6.922431 | 6.538073 | 1.058788 |
# Special case, for now (XXX).
if mime_type.startswith("image/"):
return ""
cache_key = f"img:{index}:{size}:{digest}"
return self.cache.get(cache_key) | def get_image(self, digest, blob, mime_type, index, size=500) | Return an image for the given content, only if it already exists in
the image cache. | 7.384413 | 6.680229 | 1.105413 |
# Special case, for now (XXX).
if mime_type.startswith("image/"):
return ""
cache_key = f"img:{index}:{size}:{digest}"
converted = self.cache.get(cache_key)
if converted:
return converted
# Direct conversion possible
for handler ... | def to_image(self, digest, blob, mime_type, index, size=500) | Convert a file to a list of images.
Returns image at the given index. | 2.644975 | 2.636508 | 1.003212 |
# XXX: ad-hoc for now, refactor later
if mime_type.startswith("image/"):
img = Image.open(BytesIO(content))
ret = {}
if not hasattr(img, "_getexif"):
return {}
info = img._getexif()
if not info:
return ... | def get_metadata(self, digest, content, mime_type) | Get a dictionary representing the metadata embedded in the given
content. | 3.05009 | 3.061378 | 0.996313 |
lc = self.InternalEncodeLc()
out = bytearray(4) # will extend
out[0] = self.cla
out[1] = self.ins
out[2] = self.p1
out[3] = self.p2
if self.data:
out.extend(lc)
out.extend(self.data)
out.extend([0x00, 0x00]) # Le
else:
out.extend([0x00, 0x00, 0x00]) # Le
... | def ToByteArray(self) | Serialize the command.
Encodes the command as per the U2F specs, using the standard
ISO 7816-4 extended encoding. All Commands expect data, so
Le is always present.
Returns:
Python bytearray of the encoded command. | 3.53534 | 2.920751 | 1.210422 |
# Ensure environment variable is present
plugin_cmd = os.environ.get(SK_SIGNING_PLUGIN_ENV_VAR)
if plugin_cmd is None:
raise errors.PluginError('{} env var is not set'
.format(SK_SIGNING_PLUGIN_ENV_VAR))
# Prepare input to signer
client_data_map, signing_i... | def Authenticate(self, app_id, challenge_data,
print_callback=sys.stderr.write) | See base class. | 5.79235 | 5.683736 | 1.01911 |
client_data_map = {}
encoded_challenges = []
app_id_hash_encoded = self._Base64Encode(self._SHA256(app_id))
for challenge_item in challenge_data:
key = challenge_item['key']
key_handle_encoded = self._Base64Encode(key.key_handle)
raw_challenge = challenge_item['challenge']
... | def _BuildPluginRequest(self, app_id, challenge_data, origin) | Builds a JSON request in the form that the plugin expects. | 3.515281 | 3.507688 | 1.002165 |
encoded_client_data = self._Base64Encode(client_data)
signature_data = str(plugin_response['signatureData'])
key_handle = str(plugin_response['keyHandle'])
response = {
'clientData': encoded_client_data,
'signatureData': signature_data,
'applicationId': app_id,
'key... | def _BuildAuthenticatorResponse(self, app_id, client_data, plugin_response) | Builds the response to return to the caller. | 2.616749 | 2.508875 | 1.042997 |
# Calculate length of input
input_length = len(input_json)
length_bytes_le = struct.pack('<I', input_length)
request = length_bytes_le + input_json.encode()
# Call plugin
sign_process = subprocess.Popen(cmd,
stdin=subprocess.PIPE,
... | def _CallPlugin(self, cmd, input_json) | Calls the plugin and validates the response. | 2.555491 | 2.514577 | 1.016271 |
self.cid = UsbHidTransport.U2FHID_BROADCAST_CID
nonce = bytearray(os.urandom(8))
r = self.InternalExchange(UsbHidTransport.U2FHID_INIT, nonce)
if len(r) < 17:
raise errors.HidError('unexpected init reply len')
if r[0:8] != nonce:
raise errors.HidError('nonce mismatch')
self.cid ... | def InternalInit(self) | Initializes the device and obtains channel id. | 5.336421 | 4.9428 | 1.079635 |
# make a copy because we destroy it below
self.logger.debug('payload: ' + str(list(payload_in)))
payload = bytearray()
payload[:] = payload_in
for _ in range(2):
self.InternalSend(cmd, payload)
ret_cmd, ret_payload = self.InternalRecv()
if ret_cmd == UsbHidTransport.U2FHID_ER... | def InternalExchange(self, cmd, payload_in) | Sends and receives a message from the device. | 4.596821 | 4.592918 | 1.00085 |
length_to_send = len(payload)
max_payload = self.packet_size - 7
first_frame = payload[0:max_payload]
first_packet = UsbHidTransport.InitPacket(self.packet_size, self.cid, cmd,
len(payload), first_frame)
del payload[0:max_payload]
length_to_sen... | def InternalSend(self, cmd, payload) | Sends a message to the device, including fragmenting it. | 2.972658 | 2.910992 | 1.021184 |
first_read = self.InternalReadFrame()
first_packet = UsbHidTransport.InitPacket.FromWireFormat(self.packet_size,
first_read)
data = first_packet.payload
to_read = first_packet.size - len(first_packet.payload)
seq = 0
while to_re... | def InternalRecv(self) | Receives a message from the device, including defragmenting it. | 6.21404 | 6.138044 | 1.012381 |
# If authenticator is not plugged in, prompt
try:
device = u2f.GetLocalU2FInterface(origin=self.origin)
except errors.NoDeviceFoundError:
print_callback('Please insert your security key and press enter...')
six.moves.input()
device = u2f.GetLocalU2FInterface(origin=self.origin)
... | def Authenticate(self, app_id, challenge_data,
print_callback=sys.stderr.write) | See base class. | 3.174911 | 3.165329 | 1.003027 |
# pylint: disable=g-import-not-at-top
clz = None
if sys.platform.startswith('linux'):
from pyu2f.hid import linux
clz = linux.LinuxHidDevice
elif sys.platform.startswith('win32'):
from pyu2f.hid import windows
clz = windows.WindowsHidDevice
elif sys.platform.startswith('darwin'):
from p... | def InternalPlatformSwitch(funcname, *args, **kwargs) | Determine, on a platform-specific basis, which module to use. | 2.172685 | 2.133864 | 1.018193 |
# The U2F Raw Messages specification specifies that the challenge is encoded
# with URL safe Base64 without padding encoding specified in RFC 4648.
# Python does not natively support a paddingless encoding, so we simply
# remove the padding from the end of the string.
server_challenge_b64 = ba... | def GetJson(self) | Returns JSON version of ClientData compatible with FIDO spec. | 5.320393 | 4.59474 | 1.157931 |
rd = bytearray(rd)
key = rd[pos]
if key == LONG_ITEM_ENCODING:
# If the key is tagged as a long item (0xfe), then the format is
# [key (1 byte)] [data len (1 byte)] [item tag (1 byte)] [data (n # bytes)].
# Thus, the entire key record is 3 bytes long.
if pos + 1 < len(rd):
return (3, rd[p... | def GetValueLength(rd, pos) | Get value length for a key in rd.
For a key at position pos in the Report Descriptor rd, return the length
of the associated value. This supports both short and long format
values.
Args:
rd: Report Descriptor
pos: The position of the key in rd.
Returns:
(key_size, data_len) where key_size is t... | 5.53902 | 5.264455 | 1.052155 |
encoding = None
if value_size == 1:
encoding = '<B'
elif value_size == 2:
encoding = '<H'
elif value_size == 4:
encoding = '<L'
else:
raise errors.HidError('Invalid value size specified')
ret, = struct.unpack(encoding, rd[offset:offset + value_size])
return ret | def ReadLsbBytes(rd, offset, value_size) | Reads value_size bytes from rd at offset, least signifcant byte first. | 2.616677 | 2.549634 | 1.026295 |
rd = bytearray(rd)
pos = 0
report_count = None
report_size = None
usage_page = None
usage = None
while pos < len(rd):
key = rd[pos]
# First step, determine the value encoding (either long or short).
key_size, value_length = GetValueLength(rd, pos)
if key & REPORT_DESCRIPTOR_KEY_MASK... | def ParseReportDescriptor(rd, desc) | Parse the binary report descriptor.
Parse the binary report descriptor into a DeviceDescriptor object.
Args:
rd: The binary report descriptor
desc: The DeviceDescriptor object to update with the results
from parsing the descriptor.
Returns:
None | 2.007748 | 2.008492 | 0.99963 |
out = bytearray([0] + packet) # Prepend the zero-byte (report ID)
os.write(self.dev, out) | def Write(self, packet) | See base class. | 15.795869 | 13.234293 | 1.193556 |
raw_in = os.read(self.dev, self.GetInReportDataLength())
decoded_in = list(bytearray(raw_in))
return decoded_in | def Read(self) | See base class. | 9.724108 | 9.142214 | 1.063649 |
attributes = HidAttributes()
result = hid.HidD_GetAttributes(device, ctypes.byref(attributes))
if not result:
raise ctypes.WinError()
buf = ctypes.create_string_buffer(1024)
result = hid.HidD_GetProductString(device, buf, 1024)
if not result:
raise ctypes.WinError()
descriptor.vendor_id = at... | def FillDeviceAttributes(device, descriptor) | Fill out the attributes of the device.
Fills the devices HidAttributes and product string
into the descriptor.
Args:
device: A handle to the open device
descriptor: The DeviceDescriptor to populate with the
attributes.
Returns:
None
Raises:
WindowsError when unable to obtain attribut... | 2.431291 | 2.315962 | 1.049797 |
preparsed_data = PHIDP_PREPARSED_DATA(0)
ret = hid.HidD_GetPreparsedData(device, ctypes.byref(preparsed_data))
if not ret:
raise ctypes.WinError()
try:
caps = HidCapabilities()
ret = hid.HidP_GetCaps(preparsed_data, ctypes.byref(caps))
if ret != HIDP_STATUS_SUCCESS:
raise ctypes.WinEr... | def FillDeviceCapabilities(device, descriptor) | Fill out device capabilities.
Fills the HidCapabilitites of the device into descriptor.
Args:
device: A handle to the open device
descriptor: DeviceDescriptor to populate with the
capabilities
Returns:
none
Raises:
WindowsError when unable to obtain capabilitites. | 3.259573 | 3.414767 | 0.954552 |
desired_access = GENERIC_WRITE | GENERIC_READ
share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE
if enum:
desired_access = 0
h = kernel32.CreateFileA(path,
desired_access,
share_mode,
None, OPEN_EXISTING, 0, None)
if h == IN... | def OpenDevice(path, enum=False) | Open the device and return a handle to it. | 2.511777 | 2.52907 | 0.993162 |
hid_guid = GUID()
hid.HidD_GetHidGuid(ctypes.byref(hid_guid))
devices = setupapi.SetupDiGetClassDevsA(
ctypes.byref(hid_guid), None, None, 0x12)
index = 0
interface_info = DeviceInterfaceData()
interface_info.cbSize = ctypes.sizeof(DeviceInterfaceData) # pylint: disable=invalid-na... | def Enumerate() | See base class. | 4.120254 | 4.137839 | 0.99575 |
if len(packet) != self.GetOutReportDataLength():
raise errors.HidError("Packet length must match report data length.")
packet_data = [0] + packet # Prepend the zero-byte (report ID)
out = bytes(bytearray(packet_data))
num_written = wintypes.DWORD()
ret = (
kernel32.WriteFile(
... | def Write(self, packet) | See base class. | 4.525544 | 4.312984 | 1.049284 |
buf = ctypes.create_string_buffer(self.desc.internal_max_in_report_len)
num_read = wintypes.DWORD()
ret = kernel32.ReadFile(
self.dev, buf, len(buf), ctypes.byref(num_read), None)
if num_read.value != self.desc.internal_max_in_report_len:
raise errors.HidError("Failed to read full le... | def Read(self) | See base class. | 4.438024 | 4.337367 | 1.023207 |
for authenticator in self.authenticators:
if authenticator.IsAvailable():
result = authenticator.Authenticate(app_id,
challenge_data,
print_callback)
return result
raise ValueError('No valid authe... | def Authenticate(self, app_id, challenge_data,
print_callback=sys.stderr.write) | See base class. | 3.3172 | 3.324435 | 0.997824 |
hid_transports = hidtransport.DiscoverLocalHIDU2FDevices()
for t in hid_transports:
try:
return U2FInterface(security_key=hardware.SecurityKey(transport=t),
origin=origin)
except errors.UnsupportedVersionException:
# Skip over devices that don't speak the proper vers... | def GetLocalU2FInterface(origin=socket.gethostname()) | Obtains a U2FInterface for the first valid local U2FHID device found. | 7.603749 | 7.037704 | 1.08043 |
client_data = model.ClientData(model.ClientData.TYP_REGISTRATION, challenge,
self.origin)
challenge_param = self.InternalSHA256(client_data.GetJson())
app_param = self.InternalSHA256(app_id)
for key in registered_keys:
try:
# skip non U2F_V2 keys
... | def Register(self, app_id, challenge, registered_keys) | Registers app_id with the security key.
Executes the U2F registration flow with the security key.
Args:
app_id: The app_id to register the security key against.
challenge: Server challenge passed to the security key.
registered_keys: List of keys already registered for this app_id+user.
... | 4.445968 | 4.501285 | 0.987711 |
client_data = model.ClientData(model.ClientData.TYP_AUTHENTICATION,
challenge, self.origin)
app_param = self.InternalSHA256(app_id)
challenge_param = self.InternalSHA256(client_data.GetJson())
num_invalid_keys = 0
for key in registered_keys:
try:
... | def Authenticate(self, app_id, challenge, registered_keys) | Authenticates app_id with the security key.
Executes the U2F authentication/signature flow with the security key.
Args:
app_id: The app_id to register the security key against.
challenge: Server challenge passed to the security key as a bytes object.
registered_keys: List of keys already reg... | 4.087367 | 4.102302 | 0.996359 |
self.logger.debug('CmdRegister')
if len(challenge_param) != 32 or len(app_param) != 32:
raise errors.InvalidRequestError()
body = bytearray(challenge_param + app_param)
response = self.InternalSendApdu(apdu.CommandApdu(
0,
apdu.CMD_REGISTER,
0x03, # Per the U2F refer... | def CmdRegister(self, challenge_param, app_param) | Register security key.
Ask the security key to register with a particular origin & client.
Args:
challenge_param: Arbitrary 32 byte challenge string.
app_param: Arbitrary 32 byte applciation parameter.
Returns:
A binary structure containing the key handle, attestation, and a
signa... | 6.377639 | 5.987414 | 1.065174 |
self.logger.debug('CmdAuthenticate')
if len(challenge_param) != 32 or len(app_param) != 32:
raise errors.InvalidRequestError()
control = 0x07 if check_only else 0x03
body = bytearray(challenge_param + app_param +
bytearray([len(key_handle)]) + key_handle)
response = ... | def CmdAuthenticate(self,
challenge_param,
app_param,
key_handle,
check_only=False) | Attempt to obtain an authentication signature.
Ask the security key to sign a challenge for a particular key handle
in order to authenticate the user.
Args:
challenge_param: SHA-256 hash of client_data object as a bytes
object.
app_param: SHA-256 hash of the app id as a bytes object.... | 4.467565 | 4.533796 | 0.985392 |
self.logger.debug('CmdVersion')
response = self.InternalSendApdu(apdu.CommandApdu(
0, apdu.CMD_VERSION, 0x00, 0x00))
if not response.IsSuccess():
raise errors.ApduError(response.sw1, response.sw2)
return response.body | def CmdVersion(self) | Obtain the version of the device and test transport format.
Obtains the version of the device and determines whether to use ISO
7816-4 or the U2f variant. This function should be called at least once
before CmdAuthenticate or CmdRegister to make sure the object is using the
proper transport for the de... | 5.380927 | 5.132554 | 1.048392 |
response = None
if not self.use_legacy_format:
response = apdu.ResponseApdu(self.transport.SendMsgBytes(
apdu_to_send.ToByteArray()))
if response.sw1 == 0x67 and response.sw2 == 0x00:
# If we failed using the standard format, retry with the
# legacy format.
sel... | def InternalSendApdu(self, apdu_to_send) | Send an APDU to the device.
Sends an APDU to the device, possibly falling back to the legacy
encoding format that is not ISO7816-4 compatible.
Args:
apdu_to_send: The CommandApdu object to send
Returns:
The ResponseApdu object constructed out of the devices reply. | 3.196955 | 2.94874 | 1.084177 |
cf_key = CFStr(key)
type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key)
cf.CFRelease(cf_key)
if not type_ref:
return None
if cf.CFGetTypeID(type_ref) != cf.CFNumberGetTypeID():
raise errors.OsHidError('Expected number type, got {}'.format(
cf.CFGetTypeID(type_ref)))
out = ctypes.c_... | def GetDeviceIntProperty(dev_ref, key) | Reads int property from the HID device. | 4.181665 | 4.161049 | 1.004955 |
cf_key = CFStr(key)
type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key)
cf.CFRelease(cf_key)
if not type_ref:
return None
if cf.CFGetTypeID(type_ref) != cf.CFStringGetTypeID():
raise errors.OsHidError('Expected string type, got {}'.format(
cf.CFGetTypeID(type_ref)))
type_ref = ctyp... | def GetDeviceStringProperty(dev_ref, key) | Reads string property from the HID device. | 3.510071 | 3.47341 | 1.010555 |
# Obtain device path from IO Registry
io_service_obj = iokit.IOHIDDeviceGetService(device_handle)
str_buffer = ctypes.create_string_buffer(DEVICE_PATH_BUFFER_SIZE)
iokit.IORegistryEntryGetPath(io_service_obj, K_IO_SERVICE_PLANE, str_buffer)
return str_buffer.value | def GetDevicePath(device_handle) | Obtains the unique path for the device.
Args:
device_handle: reference to the device
Returns:
A unique path for the device, obtained from the IO Registry | 7.089375 | 6.6193 | 1.071016 |
del result, sender, report_type, report_id # Unused by the callback function
incoming_bytes = [report[i] for i in range(report_length)]
read_queue.put(incoming_bytes) | def HidReadCallback(read_queue, result, sender, report_type, report_id, report,
report_length) | Handles incoming IN report from HID device. | 4.772461 | 5.357176 | 0.890854 |
# Schedule device events with run loop
hid_device.run_loop_ref = cf.CFRunLoopGetCurrent()
if not hid_device.run_loop_ref:
logger.error('Failed to get current run loop')
return
iokit.IOHIDDeviceScheduleWithRunLoop(hid_device.device_handle,
hid_device.run_loop_r... | def DeviceReadThread(hid_device) | Binds a device to the thread's run loop, then starts the run loop.
Args:
hid_device: The MacOsHidDevice object
The HID manager requires a run loop to handle Report reads. This thread
function serves that purpose. | 3.068068 | 2.92739 | 1.048056 |
# Init a HID manager
hid_mgr = iokit.IOHIDManagerCreate(None, None)
if not hid_mgr:
raise errors.OsHidError('Unable to obtain HID manager reference')
iokit.IOHIDManagerSetDeviceMatching(hid_mgr, None)
# Get devices from HID manager
device_set_ref = iokit.IOHIDManagerCopyDevices(hid_m... | def Enumerate() | See base class. | 3.181885 | 3.170861 | 1.003477 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.