INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Writes the provided graphs to the DB with the given client label.
def WriteClientGraphSeries( self, graph_series, client_label, timestamp, cursor=None, ): """Writes the provided graphs to the DB with the given client label.""" args = { "client_label": client_label, "report_type": graph_series.report_type.SerializeToDataStore(), ...
Reads graph series for the given label and report-type from the DB.
def ReadAllClientGraphSeries( self, client_label, report_type, time_range = None, cursor=None): """Reads graph series for the given label and report-type from the DB.""" query = """ SELECT UNIX_TIMESTAMP(timestamp), graph_series FROM client_report_graphs WHERE cli...
Fetches the latest graph series for a client-label from the DB.
def ReadMostRecentClientGraphSeries( self, client_label, report_type, cursor=None): """Fetches the latest graph series for a client-label from the DB.""" query = """ SELECT graph_series FROM client_report_graphs WHERE client_label = %s AND report_type = %s ORDER B...
Converts given RDFValue to an RDFURN of a file to be downloaded.
def CollectionItemToAff4Path(item, client_id=None): """Converts given RDFValue to an RDFURN of a file to be downloaded.""" if isinstance(item, rdf_flows.GrrMessage): client_id = item.source item = item.payload elif isinstance(item, rdf_flow_objects.FlowResult): client_id = item.client_id item = it...
Converts given RDFValue to a ClientPath of a file to be downloaded.
def CollectionItemToClientPath(item, client_id=None): """Converts given RDFValue to a ClientPath of a file to be downloaded.""" if isinstance(item, rdf_flows.GrrMessage): client_id = item.source item = item.payload elif isinstance(item, rdf_flow_objects.FlowResult): client_id = item.client_id item...
Returns a knowledgebase from an rdf client object.
def GetKnowledgeBase(rdf_client_obj, allow_uninitialized=False): """Returns a knowledgebase from an rdf client object.""" if not allow_uninitialized: if rdf_client_obj is None: raise artifact_utils.KnowledgeBaseUninitializedError( "No client snapshot given.") if rdf_client_obj.knowledge_base...
This generates an artifact knowledge base from a GRR client. Args: client_obj: A GRRClient object which is opened for reading. allow_uninitialized: If True we accept an uninitialized knowledge_base. Returns: A KnowledgeBase semantic value. Raises: ArtifactProcessingError: If called when the kno...
def GetArtifactKnowledgeBase(client_obj, allow_uninitialized=False): """This generates an artifact knowledge base from a GRR client. Args: client_obj: A GRRClient object which is opened for reading. allow_uninitialized: If True we accept an uninitialized knowledge_base. Returns: A KnowledgeBase sema...
Set core values from GRR into the knowledgebase.
def SetCoreGRRKnowledgeBaseValues(kb, client_obj): """Set core values from GRR into the knowledgebase.""" client_schema = client_obj.Schema kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.FQDN, "")) if not kb.fqdn: kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.HOSTNAME, "")) versions...
Parse responses with applicable parsers. Args: parser_factory: A parser factory for specific artifact. responses: A list of responses from the client. flow_obj: An artifact collection flow. Returns: A list of (possibly parsed) responses.
def ApplyParsersToResponses(parser_factory, responses, flow_obj): """Parse responses with applicable parsers. Args: parser_factory: A parser factory for specific artifact. responses: A list of responses from the client. flow_obj: An artifact collection flow. Returns: A list of (possibly parsed) ...
Upload a yaml or json file as an artifact to the datastore.
def UploadArtifactYamlFile(file_content, overwrite=True, overwrite_system_artifacts=False): """Upload a yaml or json file as an artifact to the datastore.""" loaded_artifacts = [] registry_obj = artifact_registry.REGISTRY # Make sure all artifacts are loaded...
Decorator to log and account for a DB call.
def CallLoggedAndAccounted(f): """Decorator to log and account for a DB call.""" @functools.wraps(f) def Decorator(*args, **kwargs): try: start_time = time.time() result = f(*args, **kwargs) latency = time.time() - start_time stats_collector_instance.Get().RecordEvent( "db_...
Escapes wildcard characters for strings intended to be used with `LIKE`. Databases don't automatically escape wildcard characters ('%', '_'), so any non-literal string that is passed to `LIKE` and is expected to match literally has to be manually escaped. Args: string: A string to escape. Returns: ...
def EscapeWildcards(string): """Escapes wildcard characters for strings intended to be used with `LIKE`. Databases don't automatically escape wildcard characters ('%', '_'), so any non-literal string that is passed to `LIKE` and is expected to match literally has to be manually escaped. Args: string: A ...
Convert hunt id string to an integer.
def HuntIDToInt(hunt_id): """Convert hunt id string to an integer.""" # TODO(user): This code is only needed for a brief period of time when we # allow running new rel-db flows with old aff4-based hunts. In this scenario # parent_hunt_id is effectively not used, but it has to be an # integer. Stripping "H:" f...
Write metadata about the client.
def WriteClientMetadata(self, client_id, certificate=None, fleetspeak_enabled=None, first_seen=None, last_ping=None, last_clock=None, last...
Reads ClientMetadata records for a list of clients.
def MultiReadClientMetadata(self, client_ids): """Reads ClientMetadata records for a list of clients.""" res = {} for client_id in client_ids: md = self.metadatas.get(client_id, None) if md is None: continue res[client_id] = rdf_objects.ClientMetadata( certificate=md.get...
Writes new client snapshot.
def WriteClientSnapshot(self, snapshot): """Writes new client snapshot.""" client_id = snapshot.client_id if client_id not in self.metadatas: raise db.UnknownClientError(client_id) startup_info = snapshot.startup_info snapshot.startup_info = None ts = rdfvalue.RDFDatetime.Now() hist...
Reads the latest client snapshots for a list of clients.
def MultiReadClientSnapshot(self, client_ids): """Reads the latest client snapshots for a list of clients.""" res = {} for client_id in client_ids: history = self.clients.get(client_id, None) if not history: res[client_id] = None continue last_timestamp = max(history) ...
Reads full client information for a list of clients.
def MultiReadClientFullInfo(self, client_ids, min_last_ping=None): """Reads full client information for a list of clients.""" res = {} for client_id in client_ids: try: md = self.ReadClientMetadata(client_id) except db.UnknownClientError: continue if md and min_last_ping a...
Reads last-ping timestamps for clients in the DB.
def ReadClientLastPings(self, min_last_ping=None, max_last_ping=None, fleetspeak_enabled=None): """Reads last-ping timestamps for clients in the DB.""" last_pings = {} for client_id, metadata in iteritems(self.metadatas): la...
Writes the full history for a particular client.
def WriteClientSnapshotHistory(self, clients): """Writes the full history for a particular client.""" if clients[0].client_id not in self.metadatas: raise db.UnknownClientError(clients[0].client_id) for client in clients: startup_info = client.startup_info client.startup_info = None ...
Reads the full history for a particular client.
def ReadClientSnapshotHistory(self, client_id, timerange=None): """Reads the full history for a particular client.""" from_time, to_time = self._ParseTimeRange(timerange) history = self.clients.get(client_id) if not history: return [] res = [] for ts in sorted(history, reverse=True): ...
Associates the provided keywords with the client.
def AddClientKeywords(self, client_id, keywords): """Associates the provided keywords with the client.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) for kw in keywords: self.keywords.setdefault(kw, {}) self.keywords[kw][client_id] = rdfvalue.RDFDatetime.Now...
Lists the clients associated with keywords.
def ListClientsForKeywords(self, keywords, start_time=None): """Lists the clients associated with keywords.""" res = {kw: [] for kw in keywords} for kw in keywords: for client_id, timestamp in iteritems(self.keywords.get(kw, {})): if start_time is not None and timestamp < start_time: ...
Removes the association of a particular client to a keyword.
def RemoveClientKeyword(self, client_id, keyword): """Removes the association of a particular client to a keyword.""" if keyword in self.keywords and client_id in self.keywords[keyword]: del self.keywords[keyword][client_id]
Attaches a user label to a client.
def AddClientLabels(self, client_id, owner, labels): """Attaches a user label to a client.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) labelset = self.labels.setdefault(client_id, {}).setdefault(owner, set()) for l in labels: labelset.add(utils.SmartUnicode...
Reads the user labels for a list of clients.
def MultiReadClientLabels(self, client_ids): """Reads the user labels for a list of clients.""" res = {} for client_id in client_ids: res[client_id] = [] owner_dict = self.labels.get(client_id, {}) for owner, labels in iteritems(owner_dict): for l in labels: res[client_id...
Removes a list of user labels from a given client.
def RemoveClientLabels(self, client_id, owner, labels): """Removes a list of user labels from a given client.""" labelset = self.labels.setdefault(client_id, {}).setdefault(owner, set()) for l in labels: labelset.discard(utils.SmartUnicode(l))
Lists all client labels known to the system.
def ReadAllClientLabels(self): """Lists all client labels known to the system.""" result = set() for labels_dict in itervalues(self.labels): for owner, names in iteritems(labels_dict): for name in names: result.add(rdf_objects.ClientLabel(owner=owner, name=name)) return list(res...
Writes a new client startup record.
def WriteClientStartupInfo(self, client_id, startup_info): """Writes a new client startup record.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) ts = rdfvalue.RDFDatetime.Now() self.metadatas[client_id]["startup_info_timestamp"] = ts history = self.startup_histo...
Reads the latest client startup record for a single client.
def ReadClientStartupInfo(self, client_id): """Reads the latest client startup record for a single client.""" history = self.startup_history.get(client_id, None) if not history: return None ts = max(history) res = rdf_client.StartupInfo.FromSerializedString(history[ts]) res.timestamp = ts...
Reads the full startup history for a particular client.
def ReadClientStartupInfoHistory(self, client_id, timerange=None): """Reads the full startup history for a particular client.""" from_time, to_time = self._ParseTimeRange(timerange) history = self.startup_history.get(client_id) if not history: return [] res = [] for ts in sorted(history, ...
Writes a new client crash record.
def WriteClientCrashInfo(self, client_id, crash_info): """Writes a new client crash record.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) ts = rdfvalue.RDFDatetime.Now() self.metadatas[client_id]["last_crash_timestamp"] = ts history = self.crash_history.setdefa...
Reads the latest client crash record for a single client.
def ReadClientCrashInfo(self, client_id): """Reads the latest client crash record for a single client.""" history = self.crash_history.get(client_id, None) if not history: return None ts = max(history) res = rdf_client.ClientCrash.FromSerializedString(history[ts]) res.timestamp = ts r...
Reads the full crash history for a particular client.
def ReadClientCrashInfoHistory(self, client_id): """Reads the full crash history for a particular client.""" history = self.crash_history.get(client_id) if not history: return [] res = [] for ts in sorted(history, reverse=True): client_data = rdf_client.ClientCrash.FromSerializedString(h...
Stores a ClientStats instance.
def WriteClientStats(self, client_id, stats): """Stores a ClientStats instance.""" if client_id not in self.ReadAllClientIDs(): raise db.UnknownClientError(client_id) self.client_stats[client_id][rdfvalue.RDFDatetime.Now()] = stats
Reads ClientStats for a given client and time range.
def ReadClientStats(self, client_id, min_timestamp, max_timestamp ): """Reads ClientStats for a given client and time range.""" results = [] for timestamp, stats in iteritems(self.client_stats[client_id]): if min_timestamp <= timestamp <...
Deletes ClientStats older than a given timestamp.
def DeleteOldClientStats(self, yield_after_count, retention_time ): """Deletes ClientStats older than a given timestamp.""" deleted_count = 0 yielded = False for stats_dict in itervalues(self.client_stats): for timestamp in list(stats_dict.keys...
Computes client-activity stats for all GRR versions in the DB.
def CountClientVersionStringsByLabel(self, day_buckets): """Computes client-activity stats for all GRR versions in the DB.""" def ExtractVersion(client_info): return client_info.last_snapshot.GetGRRVersionString() return self._CountClientStatisticByLabel(day_buckets, ExtractVersion)
Computes client-activity stats for all client platforms in the DB.
def CountClientPlatformsByLabel(self, day_buckets): """Computes client-activity stats for all client platforms in the DB.""" def ExtractPlatform(client_info): return client_info.last_snapshot.knowledge_base.os return self._CountClientStatisticByLabel(day_buckets, ExtractPlatform)
Computes client-activity stats for OS-release strings in the DB.
def CountClientPlatformReleasesByLabel(self, day_buckets): """Computes client-activity stats for OS-release strings in the DB.""" return self._CountClientStatisticByLabel( day_buckets, lambda client_info: client_info.last_snapshot.Uname())
Returns client-activity metrics for a particular statistic. Args: day_buckets: A set of n-day-active buckets. extract_statistic_fn: A function that extracts the statistic's value from a ClientFullInfo object.
def _CountClientStatisticByLabel(self, day_buckets, extract_statistic_fn): """Returns client-activity metrics for a particular statistic. Args: day_buckets: A set of n-day-active buckets. extract_statistic_fn: A function that extracts the statistic's value from a ClientFullInfo object. ...
Start frontend http server.
def CreateServer(frontend=None): """Start frontend http server.""" max_port = config.CONFIG.Get("Frontend.port_max", config.CONFIG["Frontend.bind_port"]) for port in range(config.CONFIG["Frontend.bind_port"], max_port + 1): server_address = (config.CONFIG["Frontend.bind_addres...
Main.
def main(argv): """Main.""" del argv # Unused. if flags.FLAGS.version: print("GRR frontend {}".format(config_server.VERSION["packageversion"])) return config.CONFIG.AddContext("HTTPServer Context") server_startup.Init() httpd = CreateServer() server_startup.DropPrivileges() try: httpd...
Sends a response to the client.
def Send(self, data, status=200, ctype="application/octet-stream", additional_headers=None, last_modified=0): """Sends a response to the client.""" if additional_headers: additional_header_strings = [ "%s: %s\r\n" % (name, val) for...
Serve the server pem with GET requests.
def do_GET(self): # pylint: disable=g-bad-name """Serve the server pem with GET requests.""" self._IncrementActiveCount() try: if self.path.startswith("/server.pem"): stats_collector_instance.Get().IncrementCounter( "frontend_http_requests", fields=["cert", "http"]) self.S...
Generates data for a single chunk.
def _GenerateChunk(self, length): """Generates data for a single chunk.""" while 1: to_read = min(length, self.RECV_BLOCK_SIZE) if to_read == 0: return data = self.rfile.read(to_read) if not data: return yield data length -= len(data)
Generates the file data for a chunk encoded file.
def GenerateFileData(self): """Generates the file data for a chunk encoded file.""" # Handle chunked encoding: # https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1 while 1: line = self.rfile.readline() # We do not support chunked extensions, just ignore them. chunk_size = ...
Process encrypted message bundles.
def do_POST(self): # pylint: disable=g-bad-name """Process encrypted message bundles.""" self._IncrementActiveCount() try: if self.path.startswith("/upload"): stats_collector_instance.Get().IncrementCounter( "frontend_http_requests", fields=["upload", "http"]) logging.err...
Handle POSTS.
def Control(self): """Handle POSTS.""" # Get the api version try: api_version = int(urlparse.parse_qs(self.path.split("?")[1])["api"][0]) except (ValueError, KeyError, IndexError): # The oldest api version we support if not specified. api_version = 3 try: content_length = se...
Initializes the Fleetspeak connector.
def Init(service_client=None): """Initializes the Fleetspeak connector.""" global CONN global label_map global unknown_label if service_client is None: service_client_cls = fs_client.InsecureGRPCServiceClient fleetspeak_message_listen_address = ( config.CONFIG["Server.fleetspeak_message_list...
Writes blob references for a signed binary to the DB.
def WriteSignedBinaryReferences(self, binary_id, references, cursor=None): """Writes blob references for a signed binary to the DB.""" args = { "binary_type": binary_id.binary_type.Serialize...
Reads blob references for the signed binary with the given id.
def ReadSignedBinaryReferences( self, binary_id, cursor=None): """Reads blob references for the signed binary with the given id.""" cursor.execute( """ SELECT blob_references, UNIX_TIMESTAMP(timestamp) FROM signed_binary_references WHERE binary_type = %s AND binary_path_has...
Returns ids for all signed binaries in the DB.
def ReadIDsForAllSignedBinaries(self, cursor=None ): """Returns ids for all signed binaries in the DB.""" cursor.execute( "SELECT binary_type, binary_path FROM signed_binary_references") return [ rdf_objects.SignedBinaryID(binary_type=binary_type, path=binary...
Deletes blob references for the given signed binary from the DB.
def DeleteSignedBinaryReferences(self, binary_id, cursor=None): """Deletes blob references for the given signed binary from the DB.""" cursor.execute( """ DELETE FROM signed_binary_references WHERE binary_type = %s AND bin...
Query the client for available Volume Shadow Copies using a WMI query.
def Start(self): """Query the client for available Volume Shadow Copies using a WMI query.""" self.state.shadows = [] self.state.raw_device = None self.CallClient( server_stubs.WmiQuery, query="SELECT * FROM Win32_ShadowCopy", next_state="ListDeviceDirectories")
Processes the results of the ListDirectory client action. Args: responses: a flow Responses object.
def ProcessListDirectory(self, responses): """Processes the results of the ListDirectory client action. Args: responses: a flow Responses object. """ if not responses.success: raise flow.FlowError("Unable to list directory.") with data_store.DB.GetMutationPool() as pool: for resp...
Parse the found release files.
def ParseMultiple(self, stats, file_objects, knowledge_base): """Parse the found release files.""" _ = knowledge_base # Collate files into path: contents dictionary. found_files = self._Combine(stats, file_objects) # Determine collected files and apply weighting. weights = [w for w in self.WEI...
Verifies the certificate using the given key. Args: public_key: The public key to use. Returns: True: Everything went well. Raises: VerificationError: The certificate did not verify.
def Verify(self, public_key): """Verifies the certificate using the given key. Args: public_key: The public key to use. Returns: True: Everything went well. Raises: VerificationError: The certificate did not verify. """ # TODO(amoser): We have to do this manually for now sin...
Verifies a given message.
def Verify(self, message, signature, hash_algorithm=None): """Verifies a given message.""" # This method accepts both PSS and PKCS1v15 padding. PSS is preferred but # old clients only support PKCS1v15. if hash_algorithm is None: hash_algorithm = hashes.SHA256() last_e = None for padding_...
Creates a new cert for the given common name. Args: csr: A CertificateSigningRequest. Returns: The signed cert.
def ClientCertFromCSR(cls, csr): """Creates a new cert for the given common name. Args: csr: A CertificateSigningRequest. Returns: The signed cert. """ builder = x509.CertificateBuilder() # Use the client CN for a cert serial_id. This will ensure we do # not have clashing cert ...
Verify the data in this blob. Args: public_key: The public key to use for verification. Returns: True when verification succeeds. Raises: rdfvalue.DecodeError if the data is not suitable verified.
def Verify(self, public_key): """Verify the data in this blob. Args: public_key: The public key to use for verification. Returns: True when verification succeeds. Raises: rdfvalue.DecodeError if the data is not suitable verified. """ if self.digest_type != self.HashType.SHA2...
Sign a given message.
def Sign(self, message, use_pss=False): """Sign a given message.""" precondition.AssertType(message, bytes) # TODO(amoser): This should use PSS by default at some point. if not use_pss: padding_algorithm = padding.PKCS1v15() else: padding_algorithm = padding.PSS( mgf=padding.M...
Use the data to sign this blob. Args: data: String containing the blob data. signing_key: The key to sign with. verify_key: Key to verify with. If None we assume the signing key also contains the public key. Returns: self for call chaining.
def Sign(self, data, signing_key, verify_key=None): """Use the data to sign this blob. Args: data: String containing the blob data. signing_key: The key to sign with. verify_key: Key to verify with. If None we assume the signing key also contains the public key. Returns: se...
A convenience method which pads and encrypts at once.
def Encrypt(self, data): """A convenience method which pads and encrypts at once.""" encryptor = self.GetEncryptor() padded_data = self.Pad(data) try: return encryptor.update(padded_data) + encryptor.finalize() except ValueError as e: raise CipherError(e)
A convenience method which pads and decrypts at once.
def Decrypt(self, data): """A convenience method which pads and decrypts at once.""" decryptor = self.GetDecryptor() try: padded_data = decryptor.update(data) + decryptor.finalize() return self.UnPad(padded_data) except ValueError as e: raise CipherError(e)
Calculates the HMAC for a given message.
def HMAC(self, message, use_sha256=False): """Calculates the HMAC for a given message.""" h = self._NewHMAC(use_sha256=use_sha256) h.update(message) return h.finalize()
Verifies the signature for a given message.
def Verify(self, message, signature): """Verifies the signature for a given message.""" siglen = len(signature) if siglen == 20: hash_algorithm = hashes.SHA1() elif siglen == 32: hash_algorithm = hashes.SHA256() else: raise VerificationError("Invalid signature length %d." % siglen)...
Converts collection items to aff4 urns suitable for downloading.
def _ItemsToUrns(self, items): """Converts collection items to aff4 urns suitable for downloading.""" for item in items: try: yield flow_export.CollectionItemToAff4Path(item, self.client_id) except flow_export.ItemNotExportableError: pass
Generates archive from a given collection. Iterates the collection and generates an archive by yielding contents of every referenced AFF4Stream. Args: items: Iterable with items that point to aff4 paths. token: User's ACLToken. Yields: Binary chunks comprising the generated archive.
def Generate(self, items, token=None): """Generates archive from a given collection. Iterates the collection and generates an archive by yielding contents of every referenced AFF4Stream. Args: items: Iterable with items that point to aff4 paths. token: User's ACLToken. Yields: B...
Get available artifact information for rendering.
def Handle(self, args, token=None): """Get available artifact information for rendering.""" # Get all artifacts that aren't Bootstrap and aren't the base class. artifacts_list = sorted( artifact_registry.REGISTRY.GetArtifacts( reload_datastore_artifacts=True), key=lambda art: ar...
Insert a single component at index.
def Insert(self, index, rdfpathspec=None, **kwarg): """Insert a single component at index.""" if rdfpathspec is None: rdfpathspec = self.__class__(**kwarg) if index == 0: # Copy ourselves to a temp copy. nested_proto = self.__class__() nested_proto.SetRawData(self.GetRawData()) ...
Append a new pathspec component to this pathspec.
def Append(self, component=None, **kwarg): """Append a new pathspec component to this pathspec.""" if component is None: component = self.__class__(**kwarg) if self.HasField("pathtype"): self.last.nested_path = component else: for k, v in iteritems(kwarg): setattr(self, k, v) ...
GlobExpression is valid.
def Validate(self): """GlobExpression is valid.""" if len(self.RECURSION_REGEX.findall(self._value)) > 1: raise ValueError("Only one ** is permitted per path: %s." % self._value)
Interpolate inline globbing groups.
def InterpolateGrouping(self, pattern): """Interpolate inline globbing groups.""" components = [] offset = 0 for match in GROUPING_PATTERN.finditer(pattern): components.append([pattern[offset:match.start()]]) # Expand the attribute into the set of possibilities: alternatives = match.g...
Return the current glob as a simple regex. Note: No interpolation is performed. Returns: A RegularExpression() object.
def AsRegEx(self): """Return the current glob as a simple regex. Note: No interpolation is performed. Returns: A RegularExpression() object. """ parts = self.__class__.REGEX_SPLIT_PATTERN.split(self._value) result = u"".join(self._ReplaceRegExPart(p) for p in parts) return rdf_stand...
Add a value to a date.
def dateadd(value: fields.DateTime(), addend: fields.Int(validate=Range(min=1)), unit: fields.Str(validate=OneOf(['minutes', 'days']))='days'): """Add a value to a date.""" value = value or dt.datetime.utcnow() if unit == 'minutes': delta = dt.timedelta(minutes=addend) el...
Returns the name of all arguments a function takes
def arguments(function, extra_arguments=0): """Returns the name of all arguments a function takes""" if not hasattr(function, '__code__'): return () return function.__code__.co_varnames[:function.__code__.co_argcount + extra_arguments]
Dynamically creates a function that when called with dictionary of arguments will produce a kwarg that's compatible with the supplied function
def generate_accepted_kwargs(function, *named_arguments): """Dynamically creates a function that when called with dictionary of arguments will produce a kwarg that's compatible with the supplied function """ if hasattr(function, '__code__') and takes_kwargs(function): function_takes_kwargs = ...
Wraps authentication logic, verify_user through to the authentication function. The verify_user function passed in should accept an API key and return a user object to store in the request context if authentication succeeded.
def authenticator(function, challenges=()): """Wraps authentication logic, verify_user through to the authentication function. The verify_user function passed in should accept an API key and return a user object to store in the request context if authentication succeeded. """ challenges = challenge...
Basic HTTP Authentication
def basic(request, response, verify_user, realm='simple', context=None, **kwargs): """Basic HTTP Authentication""" http_auth = request.auth response.set_header('WWW-Authenticate', 'Basic') if http_auth is None: return if isinstance(http_auth, bytes): http_auth = http_auth.decode('ut...
API Key Header Authentication The verify_user function passed in to ths authenticator shall receive an API key as input, and return a user object to store in the request context if the request was successful.
def api_key(request, response, verify_user, context=None, **kwargs): """API Key Header Authentication The verify_user function passed in to ths authenticator shall receive an API key as input, and return a user object to store in the request context if the request was successful. """ api_key = ...
Returns a simple verification callback that simply verifies that the users and password match that provided
def verify(user, password): """Returns a simple verification callback that simply verifies that the users and password match that provided""" def verify_user(user_name, user_password): if user_name == user and user_password == password: return user_name return False return verify...
Token verification Checks for the Authorization header and verifies using the verify_user function
def token(request, response, verify_user, context=None, **kwargs): """Token verification Checks for the Authorization header and verifies using the verify_user function """ token = request.get_header('Authorization') if token: try: verified_token = verify_user(token) exc...
Get session ID from cookie, load corresponding session data from coupled store and inject session data into the request context.
def process_request(self, request, response): """Get session ID from cookie, load corresponding session data from coupled store and inject session data into the request context. """ sid = request.cookies.get(self.cookie_name, None) data = {} if sid is not None: ...
Save request context in coupled store object. Set cookie containing a session ID.
def process_response(self, request, response, resource, req_succeeded): """Save request context in coupled store object. Set cookie containing a session ID.""" sid = request.cookies.get(self.cookie_name, None) if sid is None or not self.store.exists(sid): sid = self.generate_sid() ...
Given a request/response pair, generate a logging format similar to the NGINX combined style.
def _generate_combined_log(self, request, response): """Given a request/response pair, generate a logging format similar to the NGINX combined style.""" current_time = datetime.utcnow() data_len = '-' if response.data is None else len(response.data) return '{0} - - [{1}] {2} {3} {4} {5} ...
Logs the basic endpoint requested
def process_request(self, request, response): """Logs the basic endpoint requested""" self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type))
Logs the basic data returned by the API
def process_response(self, request, response, resource, req_succeeded): """Logs the basic data returned by the API""" self.logger.info(self._generate_combined_log(request, response))
Match a request with parameter to it's corresponding route
def match_route(self, reqpath): """Match a request with parameter to it's corresponding route""" route_dicts = [routes for _, routes in self.api.http.routes.items()][0] routes = [route for route, _ in route_dicts.items()] if reqpath not in routes: for route in routes: # repl...
Add CORS headers to the response
def process_response(self, request, response, resource, req_succeeded): """Add CORS headers to the response""" response.set_header('Access-Control-Allow-Credentials', str(self.allow_credentials).lower()) origin = request.get_header('ORIGIN') if origin and (origin in self.allow_origins) ...
Creates a new type handler with the specified type-casting handler
def create(doc=None, error_text=None, exception_handlers=empty.dict, extend=Type, chain=True, auto_instance=True, accept_context=False): """Creates a new type handler with the specified type-casting handler""" extend = extend if type(extend) == type else type(extend) def new_type_handler(functio...
Allows quick wrapping of any Python type cast function for use as a hug type annotation
def accept(kind, doc=None, error_text=None, exception_handlers=empty.dict, accept_context=False): """Allows quick wrapping of any Python type cast function for use as a hug type annotation""" return create( doc, error_text, exception_handlers=exception_handlers, chain=False, ...
Redirects to the specified location using the provided http_code (defaults to HTTP_302 FOUND)
def to(location, code=falcon.HTTP_302): """Redirects to the specified location using the provided http_code (defaults to HTTP_302 FOUND)""" raise falcon.http_status.HTTPStatus(code, {'location': location})
Converts text that may be camelcased into an underscored format
def underscore(text): """Converts text that may be camelcased into an underscored format""" return UNDERSCORE[1].sub(r'\1_\2', UNDERSCORE[0].sub(r'\1_\2', text)).lower()
Hug API Development Server
def hug(file: 'A Python file that contains a Hug API'=None, module: 'A Python module that contains a Hug API'=None, host: 'Interface to bind to'='', port: number=8000, no_404_documentation: boolean=False, manual_reload: boolean=False, interval: number=1, command: 'Run a command defined in the gi...
Authenticate and return a token
def token_gen_call(username, password): """Authenticate and return a token""" secret_key = 'super-secret-key-please-change' mockusername = 'User2' mockpassword = 'Mypassword' if mockpassword == password and mockusername == username: # This is an example. Don't do that. return {"token" : jwt....
returns documentation for the current api
def documentation(default=None, api_version=None, api=None, **kwargs): """returns documentation for the current api""" api_version = default or api_version if api: return api.http.documentation(base_url="", api_version=api_version)
Takes JSON formatted data, converting it into native Python objects
def json(body, charset='utf-8', **kwargs): """Takes JSON formatted data, converting it into native Python objects""" return json_converter.loads(text(body, charset=charset))
Converts query strings into native Python objects
def urlencoded(body, charset='ascii', **kwargs): """Converts query strings into native Python objects""" return parse_query_string(text(body, charset=charset), False)
Converts multipart form data into native Python objects
def multipart(body, content_length=0, **header_params): """Converts multipart form data into native Python objects""" header_params.setdefault('CONTENT-LENGTH', content_length) if header_params and 'boundary' in header_params: if type(header_params['boundary']) is str: header_params['bou...