"""Credentials masked in text that leaves the server (DEF-60862).

Package-manager output names repository URLs, and some carry the server's
credentials: CloudLinux mirrors sign their URLs (?token=HS256-...&expires=),
the hardened-PHP repositories put a license token in the path
(repo.alt.cloudlinux.com/el/<token>/), TuxCare ELS repositories a
subscription token (repo.els.tuxcare.com/<repository>-els/<token>/), and
yum 3 prints URLs with a JWT as the user name. Command output can also hold
an Authorization header, a netrc entry or a .repo file's password=.

The text is read once, from left to right: plain substring searches find the
places a credential can follow ("://", an escaped ":\\/\\/", "=", an encoded
"%3A%2F%2F"), and each one is read only as far as it runs, so the work grows
with the length of the text and no part of it is read again. A text longer
than MAX_LENGTH is cut at a line break first.

imunify-common masks the same forms in the events of its Go programs
(reporter.RedactCredentials); the tests of both pin the same cases. Only the
standard library: sentry_filter imports it in every process that reports to
Sentry.
"""

import bisect
import re
from urllib.parse import unquote, unquote_plus

MASK = "***"
# a text longer than this is cut, at a line break, before it is masked
MAX_LENGTH = 256 * 1024

# ASCII whitespace, as in the Go code: both read a text the same way
_WS = " \t\n\r\x0b\x0c"
_W = r" \t\n\r\x0b\x0c"


def _run(ends):
    """A pattern for a run of characters up to one of ends, an escaped
    apostrophe of a rendered value (\\') among them; written so that each
    run of plain characters is one step of the regular expression."""
    return r"[^%s]*(?:\\'[^%s]*)*" % (ends, ends)


def _slash_run(ends):
    """_run, JSON's escaped slashes (\\/) part of it too: a backslash run
    is read once, whatever follows it."""
    return r"[^%s]*(?:(?:\\'|\\+/)[^%s]*)*" % (ends, ends)


# a URL's authority runs to '/', '?', '#', a space, '"', '<', '>' or a
# backslash that starts an escape of a rendered value (\n, \"); user info may
# hold an apostrophe, also escaped, and a '&', also as JSON's \u0026 (Go's
# encoding/json writes one so)
_AUTHORITY = re.compile(
    r"[^{e}]*(?:(?:\\'|\\+u0026)[^{e}]*)*".format(e=r"/?#%s\"<>\\" % _W)
)


def _json_escape(ends):
    """A pattern for JSON's \\u escape, or Python's \\x, of a character that
    is none of ends, its backslash escaped again any number of times:
    \\u0027 (PHP's JSON_HEX_APOS writes an apostrophe so), \\u00e4
    (json.dumps any character past ASCII), \\xc3 (%r a byte past ASCII)."""
    ends = sorted(set(ends))
    return r"\\+(?:u(?!(?i:%s))[0-9a-fA-F]{4}|x(?!(?i:%s))[0-9a-fA-F]{2})" % (
        "|".join("%04x" % ord(c) for c in ends),
        "|".join("%02x" % ord(c) for c in ends),
    )


# an authority as _AUTHORITY reads it, a JSON escape of a character that does
# not end it part of it
_ESCAPED_AUTHORITY = re.compile(
    r"[^{e}]*(?:(?:\\'|{j})[^{e}]*)*".format(
        e=r"/?#%s\"<>\\" % _W, j=_json_escape('/?#"<>\\ \t\n\r\x0b\x0c')
    )
)
# its path, from its first slash, runs further to '&' too, where a URL nested
# in a query meets the next parameter; an apostrophe does not end it (see
# _mask_segment), and its slashes may be escaped as JSON may write them
# (https://h\/x-els\/<token>)
_PATH = re.compile(r"\\*/" + _slash_run(r"?#&%s\"<>\\" % _W))
# so is one read on over JSON escapes of characters that do not end it
_ESCAPED_PATH = re.compile(
    r"\\*/[^{e}]*(?:(?:\\'|\\+/|{j})[^{e}]*)*".format(
        e=r"?#&%s\"<>\\" % _W, j=_json_escape('?#&"<>\\ \t\n\r\x0b\x0c')
    )
)
# a parameter's value, JSON's escaped slashes (\/) part of it; an encoded
# URL runs as far
_VALUE = re.compile(_slash_run(r"&%s\"<>\\" % _W))
# a JSON escape of a character that does not end a value (\u0027, \u00e4;
# \u0026 is a query's "&"); a value read on over such escapes
_VALUE_ESCAPE = re.compile(_json_escape('&"<>\\ \t\n\r\x0b\x0c'))
_ESCAPED_VALUE = re.compile(
    r"[^{e}]*(?:(?:\\'|\\+/|{j})[^{e}]*)*".format(
        e=r"&%s\"<>\\" % _W, j=_json_escape('&"<>\\ \t\n\r\x0b\x0c')
    )
)
# a value of a .repo or config file line runs to the end of the line; in a
# rendered value to \n or \r, or on the rendered string's last line to the
# quote that ends it (one before a character that can follow it): its other
# escapes (\", \\) and quotes are part of it
_LINE_VALUE = re.compile(r"[^\n\r]*")
# a rendered line, to its \n or \r, escapes and quotes in it
_RENDERED_LINE = re.compile(r"(?:[^\n\r\\]|\\[^nr\n\r])*")
# a rendered string's last line, to the first quote q before a character
# that can follow it
_LAST_LINE_VALUE = {
    q: re.compile(
        r"(?:[^\n\r\\{q}]|\\[^nr\n\r]|{q}(?![,)\]}}:;{w}]|\Z))*".format(
            q=q, w=_W
        )
    )
    for q in "\"'"
}
# a value quoted with " or ': to its closing quote on the line, a backslash
# escaping the character after it (a shell's \"), or to the end of the line
# when it is not closed; in a rendered value the
# quotes are \" or \': to the next one, \n or \r, or the quote that ends the
# rendered string, its other escapes part of it, \\\" (the shell's \"
# rendered) too
_QUOTED_VALUE = {
    q: re.compile(
        r"[^{q}\n\r\\]*(?:\\(?:[^\n\r]|(?=[\n\r]|\Z))[^{q}\n\r\\]*)*".format(
            q=q
        )
    )
    for q in "\"'"
}
# what a shell word holds between its quoted segments; an argument of a list
# ends at its separator too
_WORD_REST = re.compile(r"[^&\"<>\\;'%s]*" % _W)
_ELEMENT_REST = re.compile(r"[^&\"<>\]\\;,)}'%s]*" % _W)
_WORD_ENDS = frozenset('&"<>\\;' + _WS)
_VALUE_ENDS = frozenset('&"<>\\' + _WS)
# what follows the quote that ends a rendered string
_STRING_CLOSERS = frozenset(",)]}:;" + _WS)
# plain characters of a rendered shell word (stopped at by _rendered_word_end)
_RENDERED_RUN = re.compile(r"[^\\&\"'<>;%s]*" % _W)
# what follows an argument's closing quote; a quote there goes on with the
# word ('--password=a'"b")
_ARGUMENT_ENDS = frozenset("&<>];,)}" + _WS)
# a segment quoted with a literal quote in a string rendered with the other
# one: escapes are part of it, \n and \r too; a line break and the rendered
# string's end stop it
_RENDERED_SEGMENT = {
    quote: re.compile(
        r"(?:[^{q}{d}\n\r\\]|\\[^\n\r])*".format(q=quote, d=delim)
    )
    for quote, delim in (("'", '"'), ('"', "'"))
}
# word characters of a shell value: not a quote, a backslash, a line break
# or a character that can end it (stopped at by _shell_value one by one)
_WORD_RUN = re.compile(r"[^\"'\\&<>\];,)}%s]*" % _W)
_ESCAPED_QUOTED_VALUE = {
    q: re.compile(
        r"[^{q}\n\r\\]*(?:(?:\\\\\\{q}|\\[^{q}nr\n\r]|\\(?=[\n\r]|\Z))"
        r"[^{q}\n\r\\]*)*".format(q=q)
    )
    for q in "\"'"
}
# a segment quoted with \q in a rendered value, as _quoted_value reads it: to
# its closing \q; its escapes are part of it, \n and \r (a line break in what
# was rendered) and \\\q (the shell's \q rendered) too; the q that ends the
# rendered string or a line break stops it
_ESCAPED_SEGMENT = {
    q: re.compile(
        r"[^{q}\n\r\\]*(?:(?:\\\\\\{q}|\\[^{q}\n\r]|\\(?=[\n\r]|\Z))"
        r"[^{q}\n\r\\]*)*".format(q=q)
    )
    for q in "\"'"
}
# letters and digits: a quote after one closes a value
_WORD_CHARS = frozenset(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
)
_NAME_CHARACTERS = (
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.%-"
)
_NAME_CHARS = frozenset(_NAME_CHARACTERS)
# the ASCII characters of a field's name read for its words: a URL or other
# text is no name
_FIELD_NAME_CHARS = frozenset(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.- "
)
_SCHEME_CHARS = frozenset(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+.-"
)
# names whose values are credentials in text, after "=": token, api_key,
# password, X-Amz-Signature, a .repo file's username, ... and a signed URL's
# expires; but a .repo file's gpgkey, a public key's URL, which is read as a
# URL
_SENSITIVE_SUFFIXES = (
    "token",
    "key",
    "secret",
    "passwd",
    "password",
    "auth",
    "sig",
    "signature",
    "credential",
    "username",
)
# the names of an event's fields whose values are credentials, masked whole
# whatever they hold (a bare token has no mark of one): a secret word as the
# name or a part of it (X-Auth-Token, HTTP_AUTH_PASSWD, accessToken; the
# secret parameters of rpc_tools/middleware.py: jwt, token, password; HTTP's
# Authorization, Proxy-Authorization, Cookie, Set-Cookie), or a key that is
# a secret (api_key, X-Api-Key, apikey, private_key, license_key, the
# registration key: regkey, encryption_key, access_key, session_key,
# signing_key, master_key, ssh_key, hmac_key). A name that only ends as one
# (gpgkey, monkey, signature, primary_key, username, expires) is none: its
# value is read as text.
_CREDENTIAL_WORDS = frozenset(
    (
        "password",
        "passwords",
        "passwd",
        "pass",
        "passphrase",
        "secret",
        "secrets",
        "token",
        "tokens",
        "jwt",
        "auth",
        "authorization",
        "cookie",
        "cookies",
        "credential",
        "credentials",
    )
)
# the secret words that also end a name's last word run into the word
# before them (accesstoken, dbpassword, clientsecret, basicauth), as the
# secret keys do (myapikey): an ordinary word ends as none of them (key,
# pass and jwt do: monkey, bypass)
_CREDENTIAL_ENDINGS = (
    "token",
    "tokens",
    "password",
    "passwords",
    "passwd",
    "passphrase",
    "secret",
    "secrets",
    "auth",
    "authorization",
    "cookie",
    "cookies",
    "credential",
    "credentials",
)
_SECRET_KEYS = (
    "apikey",
    "privatekey",
    "secretkey",
    "licensekey",
    "regkey",
    "registrationkey",
    "encryptionkey",
    "accesskey",
    "sessionkey",
    "signingkey",
    "masterkey",
    "sshkey",
    "hmackey",
)
# JSON as PHP writes it escapes '/', a rendered value escapes it again
# "//" after ":" as it is with one or both slashes %-encoded (https:%2F%2F...,
# as Go's url.PathEscape writes a URL), the other as it is or escaped (\/)
_COLON_ENCODED_SEP = re.compile(
    r":(?:%(?:25)*2[Ff](?:%(?:25)*2[Ff]|\\{0,8}/)|\\{0,8}/%(?:25)*2[Ff])"
)
# "//" after ":" with one or both slashes escaped (\/, as JSON may write a
# slash, up to 8 backslashes each)
_ESCAPED_SEP = re.compile(r":(?:\\{1,8}/\\{0,8}|/\\{1,8})/")
# either
_NESTED_SEP = re.compile("://|" + _ESCAPED_SEP.pattern)
_ESCAPED_SLASH = re.compile(r"\\+/")
# where an encoded URL's authority may end or hold its user info's "@": an
# end as it is, "%" (%2F, %3F, %23, %40), "@", JSON's \u0026; a %-encoded
# byte and how often past once it is encoded; a %-encoded slash
_ENCODED_STOP = re.compile(r"[/?#%s\"<>\\%%@]" % _W)
_ENCODED_BYTE = re.compile("%((?:25)*)([0-9A-Fa-f]{2})")
_ENCODED_SLASH = re.compile("%((?:25)*)2[Ff]")
_ENCODED_AT = re.compile("%(?:25)*40")
# JSON's escaped "&", its backslash escaped again any number of times
_ESCAPED_AMPERSAND = re.compile(r"\\+u0026")
# any JSON escape of a character that does not end an authority
_ESCAPED_CHARACTER = re.compile(_json_escape('/?#"<>\\ \t\n\r\x0b\x0c'))
# an escape the SDK's cut parts, before the "..." it ends a text with: a
# run of backslashes, a JSON or Python escape cut short
_CUT_JSON_ESCAPE = re.compile(
    r"\\+(?:u[0-9a-fA-F]{0,3}|x[0-9a-fA-F]?)?\.\.\.\Z"
)
# where a "://" may start, escaped or encoded
_SEP_START = re.compile("[:%]")
_PATH_SLASH = re.compile(r"\\*/")
_ESCAPED_URL = re.compile(r"[^%s\"<>]*" % _W)
# "://" percent-encoded any number of times; either "/" may be left as it is
# (%3A//, as quote() writes a URL) or escaped (%3A\/\/, JSON's)
_ENCODED_SEP = re.compile(r"%(?:25)*3[Aa](?:%(?:25)*2[Ff]|\\{0,8}/){2}")
# either, in a URL's path (/redirect/https%3A//..., https:/%2F...)
_NESTED_ENCODED_SEP = re.compile(
    "%s|%s" % (_ENCODED_SEP.pattern, _COLON_ENCODED_SEP.pattern)
)
_PERCENT_ESCAPE = re.compile(r"%[0-9A-Fa-f]{2}")
# a value decoded more than this many times is masked whole when it is still
# encoded: one encoded again and again could hide anything
_MAX_DECODING = 3
# how much of a name is read back from its "=": the longest sensitive suffix
# (credential) %-encoded _MAX_DECODING times (%252563 a character), 10 x 7
_MAX_NAME_LENGTH = 70
# where a credential can follow: a URL, an escaped one, "=", an encoded URL
_ANCHORS = re.compile(
    r"://|:(?:\\{1,8}/\\{0,8}|/\\{1,8})/|=|%(?:25)*3[Aa](?:%(?:25)*2[Ff]|\\{0,8}/){2}"
    r"|:(?:%(?:25)*2[Ff](?:%(?:25)*2[Ff]|\\{0,8}/)|\\{0,8}/%(?:25)*2[Ff])"
)
_ANCHORS_DECODED = re.compile(r"://|:(?:\\{1,8}/\\{0,8}|/\\{1,8})/|=")
# what can matter after an "=" that does nothing, up to where its value
# ends: a URL, an escaped one, a sensitive name (also percent-encoded)
_LIVE_ANCHORS = re.compile(
    r"(?i)://|:(?:\\{1,8}/\\{0,8}|/\\{1,8})/|(?:token|key|secret|passwd"
    r"|password|auth|sig"
    r"|signature|credential|username|expires)(?:[ \t]|\\t)*="
    r"|%[0-9a-f]{2}[a-z0-9_.%-]{0,62}(?:[ \t]|\\t)*="
)
_BASE64URL = re.compile(r"[A-Za-z0-9_-]*")

# Path segments that are tokens, by the repository layouts that carry one
# (90 days of Sentry data, DEF-60862): the segment after a TuxCare ELS
# repository name (<name>-els/<token>/), the hardened-PHP license token
# (/el/<token>/), any token on els-rollout.tuxcare.com and Freexian's
# /c/<token>/. Any other path segment is kept, whatever it looks like.
_HARDENED_PHP_HOSTS = frozenset(
    ("repo.alt.cloudlinux.com", "repo.alt.tuxcare.com")
)
# hosts where any path segment may be a token
_TOKEN_HOSTS = ("els-rollout.tuxcare.com", "php.freexian.com")
_TOKEN_CHARS = frozenset(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_=+.-"
)
_DECODED_TOKEN_CHARS = _TOKEN_CHARS | {"/"}
# what a path segment that may be a token is read over: its escapes too
_SEGMENT_CHARS = _TOKEN_CHARS | {"%"}
# a hardened-PHP license token: 16 or more of these on its own hosts, 64 or
# more (a mirror) anywhere else; it runs to the end of its segment
_EL_TOKEN = re.compile(r"(?:[A-Za-z0-9_=-]|%[0-9A-Fa-f]{2})*")
_TRAILING = ".,;:!)]}'\\"

# Authorization: Basic <credential>, also in JSON or a curl -H argument
_AUTH_SCHEMES = frozenset(
    (
        "basic",
        "bearer",
        "digest",
        "token",
        "negotiate",
        "ntlm",
        "apikey",
        "oauth",
        "aws4-hmac-sha256",
    )
)
# its value runs to the end of the line (also \n or \r in a rendered value),
# or to the quote that encloses the header; escaped quotes (\") and other
# escapes are part of it (a Digest header's fields, as JSON or %q write them)
_HEADER_VALUE = {
    quote: re.compile(
        r"[^\n\r\\{q}]*(?:\\[^nr\n\r][^\n\r\\{q}]*)*".format(q=quote)
    )
    for quote in ("", '"', "'")
}
_WORD = re.compile(r"[A-Za-z0-9-]*")
# a path parameter's value (/x;token=a)
_PATH_VALUE = re.compile(r"[^/;,&]*")
# a JSON escape of a character that does not end it, and its value read on
# over such escapes
_PATH_VALUE_ESCAPE = re.compile(_json_escape('/;,&?#"<>\\ \t\n\r\x0b\x0c'))
_ESCAPED_PATH_VALUE = re.compile(
    r"[^{e}]*(?:{j}[^{e}]*)*".format(
        e=r"/;,&?#%s\"<>\\" % _W, j=_PATH_VALUE_ESCAPE.pattern
    )
)
# spaces around a header's ':'; in JSON line breaks too, raw or rendered
_LINE_SPACE = re.compile(r"[ \t]*")
_JSON_SPACE = re.compile(r"(?:[ \t\n\r]|\\[nrt])*")
# the header's name in any case, as HTTP has it (ASCII: as in the Go code)
_AUTHORIZATION_NAME = re.compile("uthorization", re.IGNORECASE | re.ASCII)
_NON_SPACE = re.compile(r"[^%s]*" % _W)
_SPACE = re.compile(r"[%s]*" % _W)
# in a rendered value the escapes \n, \r and \t separate the words of a
# netrc entry too, and a quote before a character that can follow the end of
# the rendered string ends them
_ESCAPES = ("\\n", "\\r", "\\t")
# a netrc value quoted with '"' in a rendered value (b'... password "a b"\n'):
# \\ is a backslash and \\" a quote in it (the netrc's \"), \n or \r end
# the line
_RENDERED_NETRC_QUOTED = re.compile(
    r'(?:[^"\n\r\\]|\\\\"|\\(?=[\n\r]|\Z)|\\[^nr\n\r])*'
)
# a comment line between the words of an entry, to its end
_COMMENT = re.compile(r"#[^\n\r]*")
_RENDERED_COMMENT = re.compile(r"#(?:[^\n\r\\]|\\\\|\\(?![nr]))*")
_RENDERED_SPACE = re.compile(r"(?:[%s]|\\[nrt])*" % _W)
# (an escaped backslash is one character: rendered a\\n is a, \ and n)
_RENDERED_WORD = re.compile(
    r"(?:[^%s\\\"']|\\\\|\\(?![nrt])|[\"'](?![,)\]}:;%s]|\Z))*" % (_W, _W)
)


def redact_credentials(text: str) -> str:
    """Mask the credentials in text with MASK and keep the rest of it.

    User info and token-like parameters of URLs (their names decoded), the
    path tokens of the ELS and hardened-PHP repository layouts, URLs that
    are percent-encoded or JSON-escaped, JWTs, Authorization headers, netrc
    entries and the passwords of .repo files. A text with none of the marks
    a credential needs ("://", "=", "%", ...) is returned as it is.
    """
    return _mask(_bound(text))


def _bound(text):
    """text, cut at a line break before MAX_LENGTH when longer: what is
    masked and sent is bounded, and no credential is cut in two."""
    if len(text) <= MAX_LENGTH:
        return text
    cut = text.rfind("\n", 0, MAX_LENGTH)
    if cut <= 0:
        cut = max(text.rfind(c, 0, MAX_LENGTH) for c in " \t\r")
    if cut <= 0:
        return "[omitted: %d characters without a line break]" % len(text)
    return text[:cut] + "\n[cut: %d more characters]" % (len(text) - cut)


def _mask(text, decode=True, cut=False, escaped=True):
    """redact_credentials of a bounded text.

    decode is False for a decoded level of an encoded value, which its
    caller decodes one level at a time; cut is True for a text the SDK cut
    at its length limit (it ends with "..."); escaped is False for the
    unescaped form of a JSON-escaped URL.
    """
    if not (
        "://" in text
        or "=" in text
        or "%" in text
        or ":\\" in text
        or ":/\\" in text
        or "eyJ" in text
        or _AUTHORIZATION_NAME.search(text)
        or "machine" in text
        or "default" in text
    ):
        return text
    masked = _mask_cut_tail(text) if cut and text.endswith("...") else text
    # netrc entries and Authorization headers first: a value _scan masks
    # may be an entry's machine word or a header's name
    # (auth=machine h login u password p, auth=Authorization: Bearer a)
    if "machine" in masked or "default" in masked:
        masked = _mask_netrc(masked)
    covers = ()
    if _AUTHORIZATION_NAME.search(masked):
        masked, covers = _mask_authorization(masked)
    masked = _scan(masked, decode, cut, escaped, covers)
    if "eyJ" in masked:
        masked = _mask_jwts(masked)
    return text if masked == text else masked


def _scan(text, decode, cut, escaped, covers=()):
    n = len(text)
    anchors = _ANCHORS if decode else _ANCHORS_DECODED
    # parts and done: the masked text so far; floor: where the last place a
    # credential can follow was read to, so the name of an "=" or the scheme
    # of an encoded URL starts no earlier
    parts, done, pos, floor = [], 0, 0, 0
    # the first value delimiter and '%' at or after a position: the values
    # of "=" after "=" (?a=?b=?c=...) share them, so each is searched once
    delim_from, delim = 0, -1
    percent_from, percent = 0, -1
    # values up to checked were decoded already, and held no credential
    checked = 0
    # the end of a value read over JSON escapes (_ESCAPED_VALUE) from a
    # position: the values of "=" in it share it, so it is read once; an
    # encoded URL read so to escaped_checked was checked already
    escaped_from, escaped_end, escaped_checked = 0, -1, -1
    # whether it holds a JSON escape
    json_escapes = "\\u" in text or "\\x" in text
    # the last word an encoded URL past an over-deep escape is read to
    # (_encoded_url_end)
    words = [0, -1] if json_escapes else None
    # spans masked whole as well as what is read in them, from cover_from to
    # cover: a value to its line's end (see _first_line), past a JSON escape
    # (_ESCAPED_VALUE), a URL whose user info runs past one (_escaped_url_end).
    # covered: whether its own mask is written. spans: the spans the
    # Authorization pass reports (_mask_authorization) and those _url reports,
    # masked as the scan meets them (_report); None when there are none
    cover_from = cover = -1
    covered = False
    spans = _Spans(covers) if covers else None
    while True:
        match = anchors.search(text, pos)
        if match is None:
            break
        p = match.start()
        c = text[p]
        if text.startswith("://", p):
            end, edits, whole, param = _url(text, p, decode, cut)
            if param:
                # the spans before the URL first: its own come after them
                if spans and spans.first() <= p:
                    done, cover_from, cover, covered = _report(
                        text,
                        parts,
                        spans,
                        p + 1,
                        done,
                        cover_from,
                        cover,
                        covered,
                    )
                if spans is None:
                    spans = _Spans(())
                spans.params.append(param)
            if whole > 0:
                # as well as the URL is read here, from the escape on as text
                a = p + 3
                if spans and spans.first() <= a:
                    done, cover_from, cover, covered = _report(
                        text,
                        parts,
                        spans,
                        a + 1,
                        done,
                        cover_from,
                        cover,
                        covered,
                    )
                if a >= cover:
                    # a span after the one before: that one is read past
                    done = max(done, cover)
                    cover_from, covered = a, False
                cover = max(cover, whole)
                if not edits or edits[0][0] > a:
                    edits.insert(0, (a, a, MASK))
        elif c == "=":
            k, j = _name_before(text, p, floor)
            if k == j:
                pos = p + 1
                continue
            v = p + 1
            if _sensitive(text[k:j]):
                # a config file's "password   = secret"
                while v < n and text[v] in " \t":
                    v += 1
                value = v
                # the argument the name is in, when it is quoted
                enclosing, escaped_enclosing = _element_quote(text, k, floor)
                line = _at_line_start(text, k)
                if line:
                    end = _line_value_end(text, v, line == _ESCAPED_LINE, cut)
                elif text.startswith(('\\"', "\\'"), v):
                    # a quoted value in a rendered one: password=\"a b\"
                    v, end = _quoted_value(
                        text, v + 2, text[v + 1], _WORD_REST
                    )
                elif escaped_enclosing:
                    # [\"--setopt=repo.password=a b\"]: to the argument's end
                    end = _quoted_value(text, v, enclosing, _ELEMENT_REST)[1]
                elif enclosing or (v < n and text[v] in "\"'"):
                    # --setopt=repo.password="a b", 'a'"b", ['--x.password=a b']
                    v, end = _shell_value(text, v, enclosing, _WORD_ENDS)
                else:
                    end = _VALUE.match(text, v).end()
                    # outside a query the value is the shell word it starts
                    # (prefix"a b", prefix'a b', also rendered prefix\\"a b\\");
                    # in a query a quote closes the string the URL is in
                    # (?token=x"). The word only ever adds to the value.
                    if end < n and not _query_separator_before(text, k):
                        word = _shell_value(text, v, "", _VALUE_ENDS)[1]
                        end = max(end, word, _rendered_word_end(text, v))
                # a URL in it whose user info runs past its end ("&" in a
                # password) is masked whole, its path's tokens with it
                end = max(end, _crossing_url_end(text, v, end, decode))
                # a name that starts a file-like text starts its first
                # line: all of its value to the line's end is masked as well
                # as what the value is read as here, which the rest of the
                # line is still read past (a value there may run on). So is
                # that of a name longer than _name_before keeps, at a line's
                # start (its start is read past what it keeps)
                whole = v
                if not line:
                    start = _name_start(text, k, j, floor)
                    first = (
                        start < k and _at_line_start(text, start)
                    ) or _first_line(text, start)
                    if first:
                        whole = _line_value_end(
                            text, value, first == _ESCAPED_LINE, cut
                        )
                further, escaped_from, escaped_end = _value_whole(
                    text,
                    v,
                    end,
                    decode,
                    json_escapes,
                    escaped_from,
                    escaped_end,
                    words,
                )
                whole = max(whole, further)
                if whole > v:
                    if spans and spans.first() <= v:
                        done, cover_from, cover, covered = _report(
                            text,
                            parts,
                            spans,
                            v + 1,
                            done,
                            cover_from,
                            cover,
                            covered,
                        )
                    if v >= cover:
                        done = max(done, cover)
                        cover_from, covered = v, False
                    cover = max(cover, whole)
                    end = max(end, v)
                edits = [(v, end, MASK)] if end > v or cover_from == v else []
            elif not decode:
                # only a sensitive name or a URL can matter further on
                live = _LIVE_ANCHORS.search(text, p + 1)
                if live is None:
                    break
                pos = live.start()
                continue
            else:
                if not delim_from <= v <= delim:
                    delim_from, delim = v, _VALUE.match(text, v).end()
                if not percent_from <= v <= percent:
                    percent_from, percent = v, text.find("%", v)
                    if percent < 0:
                        percent = n
                if percent >= delim:
                    # no escape in the value, nor in that of any "=" up to
                    # its end: only a sensitive name or a URL can matter there
                    # (an escaped "://" may begin before it: its backslash
                    # ends the value)
                    live = _LIVE_ANCHORS.search(text, p + 1, delim + 19)
                    pos = (
                        delim
                        if live is None or live.start() >= delim
                        else live.start()
                    )
                    continue
                if v < checked:
                    # an escape decoded already: what it holds is found later
                    pos = p + 1
                    continue
                end = delim
                if not _encoded_credential(
                    text[v:end], unquote_plus, cut and end == n
                ):
                    # what it holds as written is found as the scan reads on,
                    # also a URL that runs past its end ("&" in user info)
                    checked = end
                    pos = p + 1
                    continue
                # a URL in it whose user info runs past its end ("&" in a
                # password) is masked whole, its path's tokens with it
                end = max(end, _crossing_url_end(text, v, end, decode))
                # in a quoted argument ("--setopt=repo.password=a%41 b")
                # the credential runs to the argument's closing quote, as
                # the value of a sensitive name does (outside a query,
                # the shell word it is in: a%41"b c")
                enclosing, escaped_enclosing = _element_quote(text, k, floor)
                if escaped_enclosing:
                    end = max(
                        end,
                        _quoted_value(text, v, enclosing, _ELEMENT_REST)[1],
                    )
                elif enclosing:
                    end = max(
                        end, _shell_value(text, v, enclosing, _WORD_ENDS)[1]
                    )
                elif not _query_separator_before(text, k):
                    end = max(
                        end,
                        _shell_value(text, v, "", _VALUE_ENDS)[1],
                        _rendered_word_end(text, v),
                    )
                edits = [(v, end, MASK)]
                whole, escaped_from, escaped_end = _value_whole(
                    text,
                    v,
                    end,
                    decode,
                    json_escapes,
                    escaped_from,
                    escaped_end,
                    words,
                )
                if whole > v:
                    if spans and spans.first() <= v:
                        done, cover_from, cover, covered = _report(
                            text,
                            parts,
                            spans,
                            v + 1,
                            done,
                            cover_from,
                            cover,
                            covered,
                        )
                    if v >= cover:
                        done = max(done, cover)
                        cover_from, covered = v, False
                    cover = max(cover, whole)
        elif c == ":" and not _COLON_ENCODED_SEP.match(text, p):
            if not escaped:
                pos = p + 1
                continue
            end = _ESCAPED_URL.match(text, p).end()
            region = text[p:end]
            plain = _unescape_slashes(region)
            masked = _mask(plain, decode, cut and end == n, False)
            edits = []
            if masked != plain:
                slash = _ESCAPED_SLASH.search(region).group()
                edits = [(p, end, masked.replace("/", slash))]
        else:  # "%3A%2F%2F", ":%2F%2F": "://" encoded
            start = _scheme_start(text, p, floor)
            end = _VALUE.match(text, match.end()).end()
            # written as url.PathEscape writes it (https:%2F%2Fuser:a&b@h),
            # its password may hold a "&": the URL runs on to its user info
            if c == ":":
                end = max(
                    end,
                    _encoded_url_end(
                        text, match.end(), end, _sep_depth(match.group())
                    ),
                )
            if cut and end < n:
                end = _cut_url_end(
                    text, match.end(), end, _sep_depth(match.group()), c == ":"
                )
            url = text[start:end]
            masked = _mask_encoded(url, unquote, cut and end == n)
            edits = []
            if masked == MASK:
                edits = [(match.end(), end, MASK)]
            elif masked != url:
                edits = [(start, end, masked)]
            # read on over JSON escapes (encodeURIComponent keeps "'", which
            # JSON_HEX_APOS writes \u0027; a hand-built url.PathEscape-like
            # URL may hold one in a password with a "&"), it is masked whole
            # as well when it holds a credential so
            a = match.end()
            further = -1
            if _VALUE_ESCAPE.match(text, end):
                if not escaped_from <= end <= escaped_end:
                    escaped_from = end
                    escaped_end = _ESCAPED_VALUE.match(text, end).end()
                further = escaped_end
            if c == ":" and json_escapes:
                further = max(
                    further,
                    _encoded_url_end(
                        text, a, end, _sep_depth(match.group()), True, words
                    ),
                )
            # an escape the SDK's cut parts where it stops: to the cut
            if (
                cut
                and 0 <= further < n
                and _CUT_JSON_ESCAPE.match(text, further)
            ):
                further = n
            if further > max(end, escaped_checked, cover):
                escaped_checked = further
                if (
                    _mask_encoded(
                        text[start:further], unquote, cut and further == n
                    )
                    == MASK
                ):
                    edits = [(a, end, MASK)]
                    if spans and spans.first() <= a:
                        done, cover_from, cover, covered = _report(
                            text,
                            parts,
                            spans,
                            a + 1,
                            done,
                            cover_from,
                            cover,
                            covered,
                        )
                    if a >= cover:
                        done = max(done, cover)
                        cover_from, covered = a, False
                    cover = max(cover, further)
        for start, stop, replacement in edits:
            if spans and spans.first() <= start:
                done, cover_from, cover, covered = _report(
                    text,
                    parts,
                    spans,
                    start + 1,
                    done,
                    cover_from,
                    cover,
                    covered,
                )
            if cover_from <= start < cover and (start > cover_from or covered):
                # in a span masked whole: what masks past it masks on
                done = max(done, stop)
                continue
            parts.append(
                text[done if start < cover or done >= cover else cover : start]
            )
            if spans and spans.first() < stop:
                # a reported span starts in it: what is replaced up to there
                # when that is as it was, then the span, the rest of the
                # replaced text with it
                at, span_stop = spans.take()
                if replacement.startswith(text[start:at]):
                    parts.append(text[start:at])
                else:
                    at = start
                done = at
                if at >= cover:
                    cover_from = at
                cover = max(cover, stop, span_stop)
                parts.append(MASK)
                covered = True
                continue
            parts.append(replacement)
            done = stop
            covered = covered or start == cover_from
        pos = floor = max(end, p + 1)
    if spans:
        done, cover_from, cover, covered = _report(
            text, parts, spans, n + 1, done, cover_from, cover, covered
        )
    if not parts:
        return text
    parts.append(text[done if done >= cover else cover :])
    return "".join(parts)


def _value_whole(
    text, v, end, decode, json_escapes, escaped_from, escaped_end, words
):
    """How far the value from v, read to end, is masked whole as well: a URL
    in it whose user info runs past a JSON escape on past end, to its
    path's end, and the value past a JSON escape its reading ends at, read
    on from there (_ESCAPED_VALUE, its end shared from escaped_from to
    escaped_end; words: see _encoded_url_end); v when neither. (whole,
    escaped_from, escaped_end)."""
    whole = v
    if json_escapes:
        whole = max(
            whole, _crossing_url_end(text, v, end, decode, True, words)
        )
    if _VALUE_ESCAPE.match(text, end):
        if not escaped_from <= end <= escaped_end:
            escaped_from = end
            escaped_end = _ESCAPED_VALUE.match(text, end).end()
        whole = max(whole, escaped_end)
    return whole, escaped_from, escaped_end


class _Spans:
    """The spans _scan masks whole as it meets them: those the
    Authorization pass reports, in order, merged with those _url adds, in
    order too."""

    __slots__ = ("covers", "params", "reported", "taken")

    def __init__(self, covers):
        self.covers, self.params, self.reported, self.taken = covers, [], 0, 0

    def __bool__(self):
        return self.reported < len(self.covers) or self.taken < len(
            self.params
        )

    def _next(self):
        if self.reported < len(self.covers) and (
            self.taken == len(self.params)
            or self.covers[self.reported] <= self.params[self.taken]
        ):
            return self.covers, self.reported
        return self.params, self.taken

    def first(self):
        """Where the next span starts."""
        spans, i = self._next()
        return spans[i][0]

    def take(self):
        """The next span, taken."""
        spans, i = self._next()
        if spans is self.covers:
            self.reported += 1
        else:
            self.taken += 1
        return spans[i]


def _report(text, parts, spans, before, done, cover_from, cover, covered):
    """The spans (_Spans) that start before before, masked whole: a span
    after the one before starts anew (that one is read past) and its mask
    is written to parts; one that overlaps it extends it. _scan's state
    (done, cover_from, cover, covered) after them."""
    while spans and spans.first() < before:
        start, stop = spans.take()
        if start >= cover:
            done = max(done, cover)
            cover_from, covered = start, False
        cover = max(cover, stop)
        if not covered:
            parts.extend((text[done:start], MASK))
            done, covered = max(done, start), True
    return done, cover_from, cover, covered


def _url(text, p, decode, cut=False):
    """The end of the URL whose "://" is at p, its edits (user info to the
    last '@' of the authority, the tokens of its path), where it ends when
    it is masked whole as well (_escaped_url_end) or -1, and the span of a
    path parameter's value masked whole as well, or None. cut: the SDK cut
    text (see _mask)."""
    a = p + 3
    # a URL nested in this one (https://web.archive.org/web/2020/https://...,
    # 'https://h','https://...') is one of its own: this one ends before it,
    # or before the sensitive name whose value it is (/r/password=a://...).
    # It is nested only in this one's authority, after its user info, or in
    # its path: a later URL (https://u:p=x@h https://...) is none
    limit = len(text)
    inner = text.find("://", a)
    if inner < 0:
        authority = _AUTHORITY.match(text, a).end()
        at, after = _user_info_end(text, a, authority)
    else:
        authority = _AUTHORITY.match(text, a, inner).end()
        # its user info's end; a cut lies after it
        at, after = _user_info_end(text, a, authority)
        if authority == inner:
            # the authority runs on to the nested URL: to its cut
            limit = _nested_start(text, inner, after if at >= 0 else a)
            authority = _cut_authority(text, a, limit)
        else:
            path = _PATH.match(text, authority, inner)
            if path and path.end() == inner:
                limit = _nested_start(text, inner, authority)
    # so is one in the authority, after its user info, whose "://" is
    # escaped or encoded (['https://h','https%3A%2F%2Fu%3Ap%40h'])
    low = after if at >= 0 else a
    q = _first_separator(text, low, authority, decode)
    if q >= 0:
        limit = _nested_start(text, q, low)
        authority = _cut_authority(text, a, limit)
    b = authority
    path = _PATH.match(text, b, limit)
    e = path.end() if path else b
    if decode and e > b:
        # a URL %-encoded in the path with a slash as it is
        # (/redirect/https%3A//..., https:/%2F..., %3A\/\/), which the path's
        # segments split, is one of its own, as a nested one is: the path
        # ends before its scheme. Its separator lies in the path, which a
        # later URL's scheme may end
        for sep in _NESTED_ENCODED_SEP.finditer(text, b, e):
            if "/" in sep.group():
                e = _nested_start(text, sep.start(), b)
                break
    # so is a URL nested in the path with escaped slashes
    # (/redirect/https:\/\/...)
    sep = _ESCAPED_SEP.search(text, b, e) if e > b else None
    if sep:
        e = _nested_start(text, sep.start(), b)
    # (a backslash where the authority or the path ends: either needs one)
    n = len(text)
    whole = -1
    if b < n and text[b] == "\\":
        whole = _escaped_url_end(text, a, b, limit, cut)
    # a sensitive path parameter whose value runs on past a JSON escape that
    # ends the path (/x;password=a\u0027b) is masked to its end as well
    param = None
    if b < e < n and text[e] == "\\" and _PATH_VALUE_ESCAPE.match(text, e):
        # the last parameter, after the path's last "/", ";", "," or "&": the
        # first "=" of a sensitive name in it governs it (a=b in its value)
        seg = max(b, *(text.rfind(c, b, e) + 1 for c in "/;,&"))
        q = text.find("=", seg, e)
        while q >= 0:
            k, j = _name_before(text, q, seg)
            if k < j and _sensitive(text[k:j]):
                param = (q + 1, _ESCAPED_PATH_VALUE.match(text, e).end())
                break
            q = text.find("=", q + 1, e)
    edits = []
    if at > a:
        # a separator in the user info may be a sibling URL's whose own user
        # info holds the "@" ('https://h','https%3A%2F%2Fu%3Ap@h2%2Fx-els%2Ft'):
        # the authority, which then holds that URL's host and path, is
        # masked whole
        user_info_end = b if _first_separator(text, a, at, decode) >= 0 else at
        edits = [(a, user_info_end, MASK)]
    if b == e:
        return e, edits, whole, param
    path = text[b:e]
    # its escaped slashes are read as "/" and written back as they were
    plain = _unescape_slashes(path) if "\\" in path else path
    h = after if at >= a else a
    masked = plain
    host = _host_name(text[h:b])
    # a path with an escape may hide its layout (-els as %2Dels), in a level
    # of an encoded URL too: its tokens are checked whatever is decoded
    if (
        "/el/" in plain
        or "-els/" in plain.lower()
        or "%" in plain
        or host.startswith(_TOKEN_HOSTS)
    ):
        # the path runs into the SDK's cut: its last segment was cut
        masked = _mask_path(plain, host, decode, cut and e == len(text))
    if "=" in masked:
        masked = _mask_path_parameters(masked)
    if masked != plain:
        if plain != path:
            masked = _escape_slashes(masked, path)
        edits.append((b, e, masked))
    return e, edits, whole, param


def _escaped_authority(text, a, b):
    """The authority from a, which _AUTHORITY ends at b, read on over the
    JSON escapes it holds (\\u0027 as PHP's JSON_HEX_APOS writes an
    apostrophe, \\u00e4 as json.dumps any character past ASCII), before a URL
    nested in it: (its end, its user info's last "@" or -1). (b, -1) when b
    is no backslash."""
    if b == len(text) or text[b] != "\\":
        return b, -1
    end = _ESCAPED_AUTHORITY.match(text, a).end()
    # the "://" of a URL nested in it ends it before its "/" does: it is
    # looked for there only, not in the whole text
    inner = text.find("://", a, end + 2)
    if inner >= 0:
        end = inner
    return end, _user_info_end(text, a, end)[0]


def _escaped_url_end(text, a, b, limit, cut=False):
    """Where the URL whose authority from a _AUTHORITY ends at b ends when
    its user info runs past a JSON escape there to its last "@"
    (_escaped_authority): with the path after that authority, before limit.
    It is masked whole, its host and path's tokens with it. In a text the SDK
    cut (cut), so is such an authority without an "@" that runs on to the
    cut, also into an escape it parts (\\u00e...), as a URL cut in its
    authority is (_mask_cut_url): to the cut. -1 otherwise."""
    end, at = _escaped_authority(text, a, b)
    if at > b:
        # its path too, over the JSON escapes it holds
        return _escaped_path_end(text, end, limit)
    n = len(text)
    if (
        cut
        and at < 0
        and b < n
        and text.endswith("...")
        and (end == n or _CUT_JSON_ESCAPE.match(text, end))
    ):
        return n - 3
    return -1


def _cut_authority(text, a, limit):
    """Where an authority from a ends when a nested URL cuts it at limit: at
    limit, or at the backslash of an escape the cut parts (\\u0026 whose
    u0026 reads as the nested URL's scheme). The cut, a scheme's or a name's
    start, is no backslash: one before it is such an escape's."""
    if limit > a and text[limit - 1] == "\\":
        return _AUTHORITY.match(text, a, limit).end()
    return limit


def _first_separator(text, start, end, decode):
    """Where the first "://" in text[start:end] starts that is escaped
    (:\\/\\/) or, when decoding, encoded (%3A%2F%2F, :%2F%2F, %3A//), or -1."""
    sep = _SEP_START.search(text, start, end) if start < end else None
    while sep:
        q = sep.start()
        if _ESCAPED_SEP.match(text, q) or (
            decode
            and (
                _ENCODED_SEP.match(text, q)
                or _COLON_ENCODED_SEP.match(text, q)
            )
        ):
            return q
        sep = _SEP_START.search(text, q + 1, end)
    return -1


def _user_info_spans(text):
    """The user infos of the URLs in text ("://", also escaped or encoded:
    :%2F%2F as url.PathEscape writes it, %3A%2F%2F, %3A//) as _scan reads
    them: from the authority's start to its last "@", in order; and those
    that run past a JSON escape to a later "@" (_escaped_authority, also of
    an encoded URL, whose "'" encodeURIComponent keeps), with where their
    URL ends read so. Each authority is read once: it ends at the next URL's
    slash."""
    spans, escaped = [], []
    # whether it holds a JSON escape
    escapes = "\\u" in text or "\\x" in text
    value_from = value_end = -1
    start = _SEP_START.search(text)
    while start:
        c = start.start()
        plain = encoded = None
        if text[c] == "%":
            # its ":" encoded too
            encoded = _ENCODED_SEP.match(text, c)
        elif text.startswith("://", c):
            plain = c + 3
        else:
            sep = _ESCAPED_SEP.match(text, c)
            if sep:
                plain = sep.end()
            else:
                # written as url.PathEscape writes it, its ":" as it is
                encoded = _COLON_ENCODED_SEP.match(text, c)
        if plain is not None:
            a = nxt = plain
            b = _AUTHORITY.match(text, a).end()
            at = _user_info_end(text, a, b)[0]
            url_end, escaped_at = _escaped_authority(text, a, b)
            if escaped_at > b:
                url_end = _escaped_path_end(text, url_end, len(text))
        elif encoded:
            a = encoded.end()
            depth = _sep_depth(encoded.group())
            at, nxt = _encoded_user_info(text, a, depth, text[c] == ":")
            b, escaped_at = a, -1
            if escapes:
                b = _encoded_authority(text, a, depth)[0]
                if b < len(text) and text[b] == "\\":
                    escaped_at = _encoded_authority(
                        text, a, depth, None, True
                    )[1]
                    # the value's end, shared by those it holds
                    url_end = max(escaped_at, a)
                    if not value_from <= url_end <= value_end:
                        value_from = url_end
                        value_end = _ESCAPED_VALUE.match(text, url_end).end()
                    url_end = value_end
        else:
            start = _SEP_START.search(text, c + 1)
            continue
        if at > a:
            spans.append((a, at))
        if escaped_at > b:
            escaped.append((a, escaped_at, url_end))
        start = _SEP_START.search(text, nxt)
    return spans, escaped


def _crossing_url_end(text, v, end, decode, escaped=False, words=None):
    """Where the last URL that starts in text[v:end] ends when its user info
    (to its authority's last "@") runs past end ("&" in a password): its
    authority and path. A URL as it is, escaped (:\\/\\/), or when decoding
    written as url.PathEscape writes one (https:%2F%2Fu:a&b@h, its "&" and
    "@" as they are). With escaped, one whose user info does so past a JSON
    escape (_plain_url_end, _encoded_url_end; words: see there). 0
    otherwise."""
    c = text.rfind(":", v, end)
    while c >= 0:
        if text.startswith("://", c):
            return _plain_url_end(text, c + 3, end, escaped)
        sep = _ESCAPED_SEP.match(text, c)
        if sep:
            return _plain_url_end(text, sep.end(), end, escaped)
        if decode:
            sep = _COLON_ENCODED_SEP.match(text, c)
            if sep:
                return _encoded_url_end(
                    text,
                    sep.end(),
                    end,
                    _sep_depth(sep.group()),
                    escaped,
                    words,
                )
        c = text.rfind(":", v, c)
    return 0


def _plain_url_end(text, a, end, escaped=False):
    """Where the URL whose authority starts at a ends, its path read on,
    when the authority's last "@" lies at or past end; with escaped, also
    past a JSON escape (_escaped_authority, its path read on over them
    too). 0 otherwise."""
    b = _AUTHORITY.match(text, a).end()
    at = _user_info_end(text, a, b)[0]
    if at >= end:
        path = _PATH.match(text, b)
        return path.end() if path else b
    if not escaped:
        return 0
    b, at = _escaped_authority(text, a, b)
    if at < end:
        return 0
    return _escaped_path_end(text, b, len(text))


def _escaped_path_end(text, end, limit):
    """Where the path whose first slash (also escaped) is at end ends, read
    over JSON escapes (_ESCAPED_PATH), before limit and before a URL nested
    in it (_nested_start): a run of such URLs is read once. end when no path
    starts there."""
    if not _PATH_SLASH.match(text, end, limit):
        return end
    # the next "://", also escaped: the next URL's, close by
    inner = _NESTED_SEP.search(text, end, limit)
    if inner:
        limit = _nested_start(text, inner.start(), end)
    path = _ESCAPED_PATH.match(text, end, limit)
    return path.end() if path else end


def _encoded_url_end(text, a, end, depth, escapes=False, words=None):
    """Where the encoded URL whose authority starts at a ends when its
    authority has an "@" (also %-encoded) at or past end: to an encoded
    URL's end; 0 otherwise. An escape in it encoded past the decoding ends
    the reading of it: the URL is then taken to the end of the word it is
    in, which a password's "&" does not end. With escapes, the authority
    and the rest are read on over JSON escapes (_encoded_authority), the
    rest before the next encoded URL (whose separator is looked for from
    there: the next URL's, close by). words, [start, end] of the last word
    read so, shares the word's end among the URLs in it."""
    i, at, past = _encoded_authority(text, a, depth, escapes=escapes)
    if past:
        if words is None:
            return _ESCAPED_URL.match(text, i).end()
        if not words[0] <= i <= words[1]:
            words[0], words[1] = i, _ESCAPED_URL.match(text, i).end()
        return words[1]
    if at < end:
        return 0
    if not escapes:
        return _VALUE.match(text, i).end()
    limit = len(text)
    sep = _NESTED_ENCODED_SEP.search(text, i)
    if sep:
        limit = _nested_start(text, sep.start(), i)
    return _ESCAPED_VALUE.match(text, i, limit).end()


def _cut_url_end(text, a, end, depth, colon):
    """Where an encoded URL whose authority starts at a, read to end, runs
    to in a text the SDK cut (it ends with "..."): to the cut, len(text),
    over an escape the cut parts (a run of backslashes, a JSON or Python
    escape cut short: \\u00, \\u00e, \\xc), or when its authority runs on to
    the cut, a "&" in it as it is
    or as \\u0026, as its user info may hold one when written as
    url.PathEscape writes it (colon); to end otherwise."""
    n = len(text)
    if colon:
        i = _encoded_authority(text, a, depth)[0]
        if i == n or _CUT_JSON_ESCAPE.match(text, i):
            return n
    return n if _CUT_JSON_ESCAPE.match(text, end) else end


def _encoded_authority(text, a, depth, end=None, escapes=False):
    """Where the authority of an encoded URL from a (to end) ends, where its
    last "@" (also %-encoded) is, or -1, and whether an escape encoded past the
    decoding ended it. It ends at an end as it is, or %-encoded (%2F, %3F, %23)
    no deeper than the URL's "//" is (depth: how often past once; %252F in a
    once-encoded password is a character of it). A delimiter encoded deeper
    than the decoding goes (_MAX_DECODING) ends the reading too, so that a
    position is read by one authority of each depth at most; what follows it is
    masked whole (_encoded_url_end). JSON's escaped "&" (\\u0026) and a
    rendered value's escaped apostrophe (\\') are part of it, as of a URL's
    (_AUTHORITY); with escapes, so is any JSON escape of a character that
    does not end it (_escaped_authority)."""
    at, i, n = -1, a, len(text) if end is None else end
    while True:
        stop = _ENCODED_STOP.search(text, i, n)
        if stop is None:
            return n, at, False
        i = stop.start()
        c = text[i]
        if c == "@":
            at, i = i, i + 1
            continue
        if c == "%":
            byte = _ENCODED_BYTE.match(text, i, n)
            if byte:
                value = byte.group(2).lower()
                if value == "40":
                    at, i = i, byte.end()
                    continue
                level = len(byte.group(1)) // 2
                if value in ("2f", "3f", "23") and (
                    level <= depth or level > _MAX_DECODING
                ):
                    return i, at, level > depth
            i += 1
            continue
        escaped = (
            _ESCAPED_CHARACTER if escapes else _ESCAPED_AMPERSAND
        ).match(text, i, n)
        if escaped:
            i = escaped.end()
            continue
        if text.startswith("\\'", i, n):
            i += 2
            continue
        return i, at, False


def _encoded_user_info(text, a, depth, colon):
    """Where the user info of the encoded URL whose authority starts at a
    ends as _scan reads the URL, its last "@" (also %-encoded), or -1, and
    where to read on from. Its ":" as it is (colon, as url.PathEscape
    writes a URL), its password may hold a "&"; its ":" encoded too, a "&"
    as it is (also \\u0026) ends it, as it ends a query's value. Past an
    escape encoded deeper than the decoding _scan masks the URL whole, to
    where it reads it: all of that is taken for its user info, and read
    past."""
    i, at, past = _encoded_authority(text, a, depth)
    if not colon:
        end = _VALUE.match(text, a, i).end()
        if end < i:
            i, at, past = _encoded_authority(text, a, depth, end)
    if not past:
        return at, a
    end = _VALUE.match(text, a).end()
    if colon:
        end = max(end, _ESCAPED_URL.match(text, i).end())
    return end, end


def _user_info_end(text, a, b):
    """Where the user info of the URL whose authority is text[a:b] ends and
    what follows it starts: at its last "@", or when it has none as it is
    at its last %-encoded one (https://user:pw%40h/x, as
    quote(url, safe=":/") writes a URL); (-1, -1) when it has none."""
    at = text.rfind("@", a, b)
    return (at, at + 1) if at >= 0 else _encoded_at(text, a, b)


def _encoded_at(text, a, b):
    """Where the last %-encoded "@" (%40, also encoded again: %2540) in
    text[a:b] starts and ends, or (-1, -1)."""
    start = end = -1
    for at in _ENCODED_AT.finditer(text, a, b):
        start, end = at.start(), at.end()
    return start, end


def _sep_depth(sep):
    """How often past once the first %-encoded slash of a "://" is encoded
    (%2F: 0, %252F: 1)."""
    slash = _ENCODED_SLASH.search(sep)
    return len(slash.group(1)) // 2 if slash else 0


def _host_name(host):
    """The host name of an authority's host and port as the token layouts
    compare it, once per URL: %-decoded (repo.alt.cloudlinux%2Ecom, up to
    _MAX_DECODING times), in lower case, without its port, and without the
    dot of a fully qualified name (repo.alt.cloudlinux.com.)."""
    for _ in range(_MAX_DECODING):
        if not _PERCENT_ESCAPE.search(host):
            break
        host = unquote(host)
    host = host.lower()
    if "]" not in host:
        host = host.rsplit(":", 1)[0]
    return host.rstrip(".")


def _unescape_slashes(text):
    """text with each run of backslashes before a "/" replaced by the "/",
    in one pass: a regular expression would read a long run again from each
    of its backslashes."""
    parts = text.split("/")
    return "/".join([part.rstrip("\\") for part in parts[:-1]] + parts[-1:])


def _escape_slashes(masked, path):
    """masked, which is path masked with its escaped slashes (\\/) read as
    "/", its slashes written as path writes them: masking keeps the "/"s of
    a path, or those before what it masks to the end, so the n-th of masked
    is the n-th of path. Each "/" of path is found from the one before, its
    backslashes read back to that one: a run of backslashes is read once,
    and no further than the last "/" masked keeps."""
    parts = masked.split("/")
    out = [parts[0]]
    j = 0
    for part in parts[1:]:
        k = path.find("/", j)
        if k < 0:
            break
        i = k
        while i > j and path[i - 1] == "\\":
            i -= 1
        out += (path[i : k + 1], part)
        j = k + 1
    return "".join(out)


def _nested_start(text, sep, b):
    """Where a URL nested in a path from b, its separator at sep, ends that
    path: at its scheme, or at the sensitive name whose value the "scheme"
    is (/r/token=https:/%2F..., /r/username=secret:/%2F...), which _scan
    then reads as one."""
    start = _scheme_start(text, sep, b)
    # the assignment of its path segment (password=a_b://..., a value of any
    # length or characters; x=password=..., --setopt=repo.password=...): the
    # first sensitive name before an "=" of the segment
    segment = start
    while segment > b and text[segment - 1] not in "/;,&?":
        segment -= 1
    eq = text.find("=", segment, start)
    while eq >= 0:
        k, j = _name_before(text, eq, segment)
        if k < j and _sensitive(text[k:j]):
            return k
        eq = text.find("=", eq + 1, start)
    return start


def _scheme_start(text, i, low):
    j = i
    while j > low and i - j < 32 and text[j - 1] in _SCHEME_CHARS:
        j -= 1
    return j


def _name_before(text, p, low):
    """The name before the '=' at p, spaces between allowed, as (start,
    end), its last _MAX_NAME_LENGTH characters when longer; start == end
    when there is none."""
    j = p
    # an aligned config line (password    = x; tabs rendered as \t too)
    while j > low:
        if text[j - 1] in " \t":
            j -= 1
        elif j - 2 >= low and text[j - 2 : j] == "\\t":
            j -= 2
        else:
            break
    k = j
    while k > low and text[k - 1] in _NAME_CHARS:
        if j - k == _MAX_NAME_LENGTH:
            # a longer name (--setopt=<repository id>.password): its end
            break
        # a rendered value's line break (\n) is no part of the name; a
        # rendered tab is (\tpassword reads tpassword, still sensitive, and
        # C:\token keeps its t), _at_line_start reads it as indentation
        if text[k - 1] in "nr" and k - 2 >= low and text[k - 2] == "\\":
            break
        k -= 1
    # \texpires: a rendered tab's t, which the name keeps (\tpassword reads
    # tpassword, C:\token keeps its t), is left out when only the name
    # without it is sensitive (expires matches as a whole)
    if (
        k + 1 < j
        and text[k] == "t"
        and k > low
        and text[k - 1] == "\\"
        and not _sensitive(text[k:j])
        and _sensitive(text[k + 1 : j])
    ):
        k += 1
    return k, j


def _name_start(text, k, j, low):
    """Where the name (k, j) _name_before gives starts: at k, or further
    back when it kept only its last characters."""
    if j - k < _MAX_NAME_LENGTH:
        return k
    start = low + len(text[low:k].rstrip(_NAME_CHARACTERS))
    # a rendered line break (\n) before it is no part of it
    if start > low and text[start - 1] == "\\" and text[start] in "nr":
        start += 1
    return start


def _sensitive(name):
    """Whether the value after name and "=" in text is a credential: name,
    %-decoded, in any case, is "expires" or ends with one of
    _SENSITIVE_SUFFIXES, but as a public key's URL (gpgkey)."""
    name = _decoded_name(name).lower()
    return name == "expires" or (
        name.endswith(_SENSITIVE_SUFFIXES) and not name.endswith("gpgkey")
    )


def _credential_name(key):
    """Whether the values of key, an event's field, are credentials that may
    be no URL (Basic, a bare token, a session, a password): key, %-decoded,
    a name (of _FIELD_NAME_CHARS and other alphabets' letters: a URL is
    none), is one of _CREDENTIAL_WORDS or has one as a part, its last word
    ends with one of _CREDENTIAL_ENDINGS or _SECRET_KEYS (accesstoken,
    myapikey), or it names a key of _SECRET_KEYS (api_key, X-Api-Key,
    regkey)."""
    name = _decoded_name(key)
    if any(c < "\x80" and c not in _FIELD_NAME_CHARS for c in name):
        return False
    # its words between separators, whole (a header's name in any case:
    # AuthoriZation), and those words parted where a capital starts one
    pieces = [part.lower() for part in _name_parts(name, False)]
    parts = [part.lower() for part in _name_parts(name, True)]
    return (
        any(
            word in _CREDENTIAL_WORDS or word in _SECRET_KEYS
            for word in pieces + parts
        )
        or any(
            a + b in _SECRET_KEYS
            for words in (pieces, parts)
            for a, b in zip(words, words[1:])
        )
        or bool(pieces)
        and pieces[-1].endswith(_CREDENTIAL_ENDINGS + _SECRET_KEYS)
    )


def _name_parts(name, camel):
    """The words of name: parted where it has no ASCII letter or digit, and
    when camel where a capital starts a word (accessToken, HTTPAuth: HTTP,
    Auth)."""
    parts, start = [], 0
    for i, c in enumerate(name):
        if c < "\x80" and not c.isalnum():
            if start < i:
                parts.append(name[start:i])
            start = i + 1
        elif (
            camel
            and "A" <= c <= "Z"
            and start < i
            and (
                "a" <= name[i - 1] <= "z"
                or "0" <= name[i - 1] <= "9"
                or "A" <= name[i - 1] <= "Z"
                and i + 1 < len(name)
                and "a" <= name[i + 1] <= "z"
            )
        ):
            parts.append(name[start:i])
            start = i
    if start < len(name):
        parts.append(name[start:])
    return parts


def _pair_name(name):
    """Whether name is the name of a [name, value] pair whose value is a
    credential: a plain name (Authorization, X-Auth-Token), not text that
    ends as one (https://h/x?key=a)."""
    return (
        bool(name) and _NAME_CHARS.issuperset(name) and _credential_name(name)
    )


def _decoded_name(name):
    """name %-decoded, _MAX_DECODING times at most."""
    if "%" in name:
        for _ in range(_MAX_DECODING):
            decoded = unquote(name)
            if decoded == name:
                break
            name = decoded
    return name


# how a line before a name breaks: a rendered value writes it as \n
_RAW_LINE, _ESCAPED_LINE = 1, 2
_RAW_BREAK = re.compile("[\n\r]")
_RENDERED_BREAK = re.compile(r"\\[nr]")
# a rendered line break after a position, its escapes read in pairs as
# _RENDERED_LINE reads them: \\n is a backslash and an n
_PAIRED_BREAK = re.compile(r"[^\\]*(?:\\[^nr][^\\]*)*\\[nr]")


def _at_line_start(text, k):
    """Whether the name at k follows a line break, as in a .repo or config
    file, and how the line breaks (_RAW_LINE, _ESCAPED_LINE; 0: no line). A
    raw query string starts the text and is no such line (see
    _first_line)."""
    i = _line_start(text, k)
    if i > 0 and text[i - 1] in "\n\r":
        return _RAW_LINE
    if i >= 2 and text[i - 2 : i] in ("\\n", "\\r"):
        return _ESCAPED_LINE
    return 0


def _first_line(text, k):
    """How a file-like text breaks its lines when the name at k starts it
    (past indentation): as it is (_RAW_LINE) when a line break follows the
    name, else rendered (\\n, \\r: _ESCAPED_LINE) when one of those does; 0
    when the name does not start the text, or the text is one line, which
    may be a raw query or a shell word. A raw line covers the rendered
    reading too: its value runs to the break, past any \\n before it (a raw
    password may hold those two characters)."""
    if _line_start(text, k):
        return 0
    if _RAW_BREAK.search(text, k):
        return _RAW_LINE
    # the search is quick, the match reads the escapes in pairs
    if _RENDERED_BREAK.search(text, k) and _PAIRED_BREAK.match(text, k):
        return _ESCAPED_LINE
    return 0


def _line_start(text, k):
    """Where the content of the line the name at k is on starts: before the
    name, past the indentation before it."""
    i = k
    # a rendered tab the name starts with (\tpassword), then any
    # indentation, tabs rendered as \t too
    if 1 <= i < len(text) and text[i] == "t" and text[i - 1] == "\\":
        i -= 1
    while i > 0:
        if text[i - 1] in " \t":
            i -= 1
        elif i >= 2 and text[i - 2 : i] == "\\t":
            i -= 2
        else:
            break
    return i


def _query_separator_before(text, k):
    """Whether the name at k is a parameter of a query: '?', '&' or ';' go
    before it, or JSON's \\u0026 (whose u0026 the name starts with: they are
    name characters)."""
    return k > 0 and (
        text[k - 1] in "?&;"
        or (text[k - 1] == "\\" and text.startswith("u0026", k))
    )


def _element_quote(text, k, low):
    """The quote an argument that holds the name at k starts with ("--setopt=
    repo.password=a b" as %q writes an argument, in a rendered list or in
    JSON), and whether it is escaped (\\" in a rendered value), or "": the
    value of the name then runs to the argument's closing quote, spaces in
    it. A URL's query is no argument: the walk back stops at '/', '?', '&'
    (and at a space, a ';' or a backslash)."""
    # no further back than low, where the last place a credential can
    # follow was read to: each character is walked over once in a text,
    # however long the argument (a repository id of any length)
    t = k
    while t > low:
        c = text[t - 1]
        if c in "\"'":
            escaped = t >= 2 and text[t - 2] == "\\"
            # one a letter or a digit goes before closes a value
            # (Password="a";Username="b"); a lone b is a bytes literal's
            # (b'...', as Python writes bytes)
            before = t - 2 - escaped
            if (
                before >= 0
                and text[before] in _WORD_CHARS
                and not (
                    text[before] == "b"
                    and (before == 0 or text[before - 1] not in _WORD_CHARS)
                )
            ):
                return "", False
            return c, escaped
        if c in _WS or c in "/?&;\\":
            return "", False
        t -= 1
    return "", False


def _quoted_value(text, v, quote, rest):
    """The start and the end of a value quoted with \\quote in a rendered
    value, from v after the quote: the shell word it starts, each of its
    segments (\\"a\\"\\"b\\", \\"a\\"\\'b\\', and '...' in a "-rendered string,
    as %q writes a shell's 'a'"b") and what is between them, up to where
    rest ends (_WORD_REST, _ELEMENT_REST: an argument of a list ends at its
    separator too); to where a segment stops when it is not closed. When
    nothing follows the last closing quote, it is kept."""
    # a quote of the other kind is a literal one in the rendered string
    literal = "'" if quote == '"' else '"'
    n = len(text)
    i, seg, escaped_seg = v, quote, True
    while True:
        if escaped_seg:
            closing = _ESCAPED_SEGMENT[seg].match(text, i).end()
            closed = text.startswith("\\" + seg, closing)
        else:
            closing = _RENDERED_SEGMENT[seg].match(text, i).end()
            closed = closing < n and text[closing] == seg
        if not closed:
            return v, closing
        after = closing + (2 if escaped_seg else 1)
        j = rest.match(text, after).end()
        # the shell's \x rendered (\\x): x is part of the word
        while _rendered_escape(text, j) > j:
            j = rest.match(text, _rendered_escape(text, j)).end()
        if text.startswith(('\\"', "\\'"), j):
            i, seg, escaped_seg = j + 2, text[j + 1], True
        elif j < n and text[j] == literal:
            i, seg, escaped_seg = j + 1, literal, False
        elif j == after:
            return v, closing
        else:
            return v, j


def _rendered_escape(text, i):
    """Where the shell's backslash escape at i ends in a rendered value
    (\\\\x: the rendered backslash and the character it escapes, which may
    be rendered as an escape too, \\\\\\" or \\\\\\\\), or i when there is
    none: a line break, or a quote before one of _STRING_CLOSERS (the quote
    that ends the rendered string), is not escaped."""
    if i + 2 >= len(text) or not text.startswith("\\\\", i):
        return i
    c = text[i + 2]
    if c in "\n\r":
        return i
    if c == "\\" and i + 3 < len(text):
        return i + 4
    if c in "\"'" and (i + 3 == len(text) or text[i + 3] in _STRING_CLOSERS):
        return i
    return i + 3


def _rendered_word_end(text, v):
    """Where a shell word that starts unquoted at v ends when it is rendered
    (b'...password=a\\'b c\\'...', JSON's \\"): its \\"...\\" and \\'...\\' are
    its quoted segments (see _quoted_value); it ends where a value ends, at
    a ';', at \\n, \\r, \\t, or at a quote that is not escaped."""
    n = len(text)
    i = v
    while i < n:
        c = text[i]
        if c == "\\" and i + 1 < n and text[i + 1] in "\"'":
            return _quoted_value(text, i + 2, text[i + 1], _WORD_REST)[1]
        if _rendered_escape(text, i) > i:
            # the shell's \x rendered (\\x): x is part of the word
            i = _rendered_escape(text, i)
        elif c == "\\" and i + 1 < n and text[i + 1] not in "nrt\n\r":
            i += 2
        elif c in _WORD_ENDS or c == "'":
            return i
        else:
            i = _RENDERED_RUN.match(text, i + 1).end()
    return n


def _shell_value(text, v, enclosing, ends):
    """The start and the end of a sensitive name's value at v that is
    quoted, or sits in a quoted argument (enclosing: its quote, or ""): the
    shell word it is, segments quoted with either quote ('a'"b" is ab), a
    backslash escaping the character after it, up to where a value ends or a
    ';'; in an argument up to the argument's closing quote, spaces in it (a
    quote that a word character follows is a shell quote, the word goes on).
    A quote that is not closed on its line runs to the end of the line (the
    SDK may have cut it). The value's opening quote is kept, and its last
    closing quote when the word ends there. ends: where a word ends outside
    quotes (_WORD_ENDS; _VALUE_ENDS, without ';', for a value that starts
    unquoted)."""
    n = len(text)
    start = v
    if v < n and text[v] in "\"'" and text[v] != enclosing:
        start = v + 1
    i, last_close = v, -1
    while i < n:
        c = text[i]
        if c in "\n\r":
            break
        if enclosing and c == enclosing:
            if i + 1 == n or text[i + 1] in _ARGUMENT_ENDS:
                break
            enclosing = ""
            i += 1
        elif c in "\"'":
            closing, closed = _quoted_segment(text, i + 1, c, False)
            if not closed:
                return start, closing
            i, last_close = closing + 1, closing
            continue
        elif (
            c == "\\"
            and i + 1 < n
            and text[i + 1] not in "\n\r"
            and (enclosing or text[i + 1] not in "nrt")
        ):
            # an escaped character; \n, \r, \t of a rendered value end the
            # word, but not in an argument's quotes ("--x=a\tb", as %q
            # writes it), as a space does not
            i += 2
        elif (not enclosing and c in ends) or c == "\\":
            break
        else:
            # a run of word characters at once
            i = _WORD_RUN.match(text, i + 1).end()
        last_close = -1
    return start, last_close if last_close == i - 1 else i


def _quoted_segment(text, i, quote, escaped):
    """Where a segment quoted with quote that starts at i ends, and whether
    at its closing quote (see _QUOTED_VALUE)."""
    if escaped:
        end = _ESCAPED_QUOTED_VALUE[quote].match(text, i).end()
        return end, text.startswith("\\" + quote, end)
    end = _QUOTED_VALUE[quote].match(text, i).end()
    return end, end < len(text) and text[end] == quote


def _line_value_end(text, v, escaped, cut=False):
    """Where the value of a .repo or config file line at v ends: at the end
    of the line, whatever it holds (a password may hold "&x="). In a
    rendered value the line ends at \\n or \\r; its escapes and quotes are
    part of the value. On the rendered string's last line (no \\n or \\r
    follows on the raw line) it ends where the string does: see
    _LAST_LINE_VALUE."""
    if not escaped:
        return _LINE_VALUE.match(text, v).end()
    end = _RENDERED_LINE.match(text, v).end()
    if text.startswith(("\\n", "\\r"), end):
        return end
    # the SDK cut the string on this line: its closing quote may be gone
    if cut and end == len(text):
        return end
    # its own quote never stands in the string as it is, the other may
    # (JSON's "a'b"): of the first of each kind before a closer, the later
    ends = [
        e
        for quote, e in (
            (q, _LAST_LINE_VALUE[q].match(text, v).end()) for q in "\"'"
        )
        if e < end and text[e] == quote
    ]
    return max(ends) if ends else end


def _mask_encoded(value, decode_level, cut):
    """value masked whole (MASK) when it is an encoded credential, otherwise
    value masked as it is."""
    if _encoded_credential(value, decode_level, cut):
        return MASK
    return _mask(value, False, cut)


def _encoded_credential(value, decode_level, cut):
    """Whether one of value's decoded levels holds a credential, or it is
    still encoded past them: decoding further could turn an escaped
    delimiter of a password (%252F) into a real one, so each level is
    checked as it is. "+" is a space in a query, itself elsewhere (a value
    may be no query, and url.PathEscape keeps a "+"): what either reading
    finds counts."""
    if (
        decode_level is unquote_plus
        and "+" in value
        and _encoded_credential(value, unquote, cut)
    ):
        return True
    decoded = value
    for _ in range(_MAX_DECODING):
        if not _PERCENT_ESCAPE.search(decoded):
            return False
        decoded = decode_level(decoded)
        if _mask(decoded, False, cut) != decoded:
            return True
    return bool(_PERCENT_ESCAPE.search(decoded))


def _mask_path(path, host, decode, cut=False):
    """path with its tokens masked, and the segments that hold a
    %-encoded URL with a credential. cut: the SDK cut the text in the last
    segment (it ends with "..."), which is read as cut (see _mask)."""
    segments = path.split("/")
    changed = False
    for i in range(1, len(segments)):
        segment = segments[i]
        if not segment:
            continue
        masked = segment
        need = _token_need(segments[i - 1], host)
        if need:
            masked = _mask_segment(segment, need)
        if masked is segment and decode and "%" in segment:
            # a URL percent-encoded in the path; the one the SDK cut keeps
            # its "..." for the cut rules
            token = segment.rstrip(_TRAILING)
            last = cut and i == len(segments) - 1 and segment.endswith("...")
            if (
                _mask_encoded(segment if last else token, unquote, last)
                == MASK
            ):
                masked = MASK + segment[len(token) :]
        if masked is segment and "%" in segment:
            masked = _mask_after_encoded_slash(segment, host)
        if masked is not segment:
            segments[i] = masked
            changed = True
    return "/".join(segments) if changed else path


def _mask_after_encoded_slash(segment, host):
    """segment with a token masked that follows one of its %-encoded slashes
    in a repository layout (<name>-els%2F<token>, el%2F<token>): what
    follows the first such slash is read as the segment after a "/" would
    be, all of it (a token's base64 may hold a %2F of its own), once."""
    start = 0
    for slash in _ENCODED_SLASH.finditer(segment):
        need = _token_need(segment[start : slash.start()], host)
        if need:
            rest = segment[slash.end() :]
            masked = _mask_segment(rest, need)
            return (
                segment if masked is rest else segment[: slash.end()] + masked
            )
        start = slash.end()
    return segment


def _mask_path_parameters(path):
    """path with the values of its sensitive names masked, a matrix parameter
    (/x;token=a) or a segment that is one (/token=a/): to the next "/", ";",
    "," or "&", which the "="s before it share (found once)."""
    parts, done, end = [], 0, -1
    q = path.find("=")
    while q >= 0:
        if end <= q:
            end = _PATH_VALUE.match(path, q + 1).end()
        k, j = _name_before(path, q, done)
        if k < j and end > q + 1 and _sensitive(path[k:j]):
            parts += [path[done : q + 1], MASK]
            done = end
        q = path.find("=", q + 1)
    if not parts:
        return path
    parts.append(path[done:])
    return "".join(parts)


def _token_need(previous, host):
    """What a path segment after previous must be to be a token on host
    (lowercased, without its port and trailing dots): "els" (a subscription
    token), a number (a hardened-PHP license token of at least that many
    characters) or None (it is no token)."""
    # a %-encoded segment is the same path (/%65l/ is /el/)
    for _ in range(_MAX_DECODING):
        if not _PERCENT_ESCAPE.search(previous):
            break
        previous = unquote(previous)
    if previous.lower().endswith("-els") or host == "els-rollout.tuxcare.com":
        return "els"
    if previous == "c" and host == "php.freexian.com":
        return "els"
    if previous == "el":
        return 16 if host in _HARDENED_PHP_HOSTS else 64
    return None


def _mask_segment(segment, need):
    """segment masked when it is a token, or each of its parts between
    apostrophes that is one: an apostrophe may close a quote around the URL
    (.../<token>'s) or be part of the path, so both are checked. Matrix
    parameters after a token (<token>;arch=x86_64) are no part of it."""
    semicolon = segment.find(";")
    if semicolon > 0:
        head = segment[:semicolon]
        masked = _mask_segment(head, need)
        if masked != head:
            return masked + segment[semicolon:]
    token = segment.rstrip(_TRAILING)
    if _is_token(token, need):
        return MASK + segment[len(token) :]
    if "'" not in segment:
        return segment
    parts = segment.split("'")
    changed = False
    for i, part in enumerate(parts):
        token = part.rstrip(_TRAILING)
        if _is_token(token, need):
            parts[i] = MASK + part[len(token) :]
            changed = True
    return "'".join(parts) if changed else segment


def _is_token(token, need):
    if need != "els":
        return _EL_TOKEN.match(token).end() >= need
    chars = _TOKEN_CHARS
    # decoded whatever its URL's reader decodes: in a URL that is itself
    # %-encoded, the token keeps an escape of its own (%252F) when that URL
    # is decoded a level
    if "%" in token:
        for _ in range(_MAX_DECODING):
            if not _PERCENT_ESCAPE.search(token):
                break
            token = unquote(token)
            # base64 holds '/', %-encoded in a path segment
            chars = _DECODED_TOKEN_CHARS
        else:
            if _PERCENT_ESCAPE.search(token):
                return True
    return (
        len(token) >= 16
        and chars.issuperset(token)
        and any(c.isdigit() for c in token)
        and any(c.isalpha() for c in token)
    )


def _mask_jwts(text):
    """Every JWT (eyJ<8 or more>.<part>.<part>) masked whole. A failed
    candidate is skipped with the run it starts: any eyJ in that run fails
    the same way."""
    n = len(text)
    parts, done, pos = [], 0, 0
    while True:
        p = text.find("eyJ", pos)
        if p < 0:
            break
        q1 = _BASE64URL.match(text, p).end()
        pos = q1
        if q1 - p < 11 or q1 >= n or text[q1] != ".":
            continue
        q2 = _BASE64URL.match(text, q1 + 1).end()
        if q2 == q1 + 1 or q2 >= n or text[q2] != ".":
            continue
        q3 = _BASE64URL.match(text, q2 + 1).end()
        if q3 == q2 + 1:
            continue
        parts += [text[done:p], MASK]
        done = pos = q3
    if not parts:
        return text
    parts.append(text[done:])
    return "".join(parts)


def _array_end(text, i, escaped):
    """Where a JSON array of strings from i, after its "[", ends, and whether
    it is one: at its "]". Its strings are read to their closing quote (a "]"
    or "," in one is part of it); line breaks may separate them
    (pretty-printed JSON; \\n, \\r, \\t in a rendered value, also when its
    quotes are not escaped, as %r writes bytes; escaped: its strings quoted
    with \\"). A string that is not closed ends it where the
    string stops, anything else after a string at the end of its line. It is
    none when neither a string nor "]" follows the "["."""
    n = len(text)
    read = False
    while i < n:
        c = text[i]
        if c in " \t," or not escaped and c in "\n\r":
            i += 1
        elif c == "\\" and i + 1 < n and text[i + 1] in "nrt":
            i += 2
        elif c == "]":
            return i, True
        elif not escaped and c in "\"'":
            closing, closed = _quoted_segment(text, i + 1, c, False)
            if not closed:
                return closing, True
            i, read = closing + 1, True
        elif escaped and text.startswith(('\\"', "\\'"), i):
            closing = _ESCAPED_SEGMENT[text[i + 1]].match(text, i + 2).end()
            if not text.startswith("\\" + text[i + 1], closing):
                return closing, True
            i, read = closing + 2, True
        elif not read:
            return i, False
        else:
            return _HEADER_VALUE[""].match(text, i).end(), True
    return i, read


def _mask_authorization(text):
    """The credential of an (Proxy-)Authorization header masked, its name in
    any case, its scheme kept: Authorization: Basic ***, also as JSON or in
    a curl -H argument; and the spans of the masked text _scan masks whole as
    well: from the start of user info that runs past a JSON escape
    (_escaped_url_end) to the mask of a header in it, which took its "@"
    away; from the start of a path segment the header's name ends
    (.../<token>Authorization=..., _glued_segment) to its mask, which took
    the token's end away."""
    n = len(text)
    parts, done, pos = [], 0, 0
    # covers: those spans, as (start, stop, where their URL ends in text);
    # out: the length of the masked text so far; replaced: the spans of text
    # replaced, (start, end, where its mask starts and ends in the masked
    # text)
    covers, out, replaced = [], 0, []
    # a header's name in a URL's user info (https://u:a:Authorization:b@h)
    # is a part of its password, which the user info rule masks whole: a
    # "value" masked from there would take the URL's "@" away
    (infos, escaped_infos), info, escaped = _user_info_spans(text), 0, 0
    found = _AUTHORIZATION_NAME.search(text)
    p = found.start() if found else -1
    while True:
        if 0 <= p < pos:
            found = _AUTHORIZATION_NAME.search(text, pos)
            p = found.start() if found else -1
        if p < 0:
            break
        if p < 1 or text[p - 1] not in "Aa":
            pos = p + 12
            continue
        name = p - 1
        if name >= 6 and text[name - 6 : name].lower() == "proxy-":
            name -= 6
        while info < len(infos) and infos[info][1] <= name:
            info += 1
        if info < len(infos) and infos[info][0] <= name:
            pos = p + 12
            continue
        while (
            escaped < len(escaped_infos) and escaped_infos[escaped][1] <= name
        ):
            escaped += 1
        start = url_end = -1
        if escaped < len(escaped_infos) and escaped_infos[escaped][0] <= name:
            start, _, url_end = escaped_infos[escaped]
        # the header in quotes, also escaped ({\\"Authorization\\": \\"...\\"})
        quote = text[name - 1] if name > 0 and text[name - 1] in "\"'" else ""
        escaped_quote = bool(quote) and name >= 2 and text[name - 2] == "\\"
        i = p + 12
        # a quoted name is a JSON key: the value may follow on another line
        space = _JSON_SPACE
        if i < n and text[i] in "\"'":
            i += 1
        elif text.startswith(('\\"', "\\'"), i):
            i += 2
        else:
            space = _LINE_SPACE
        i = space.match(text, i).end()
        if i >= n or text[i] not in ":=":
            pos = p + 12
            continue
        # "=" right after the name: it may end a path segment's token
        glued = i == p + 12 and text[i] == "="
        i = space.match(text, i + 1).end()
        if i < n and text[i] in "\"'":
            quote, escaped_quote = text[i], False
            i += 1
        elif text.startswith(('\\"', "\\'"), i):
            quote, escaped_quote = text[i + 1], True
            i += 2
        if i < n and text[i] == "[":
            # several values ({"Authorization":["Bearer a"]}, http.Header as
            # JSON): the array to its end. Anything else (fmt's
            # map[Authorization:[Bearer a] Cookie:[b]]) is masked to the end
            # of the line below, as any value.
            end, array = _array_end(text, i + 1, escaped_quote)
            if array:
                if end > i + 1:
                    if start >= 0:
                        covers.append(
                            (
                                out + max(start - done, 0),
                                out + i + 1 - done + len(MASK),
                                url_end,
                            )
                        )
                    parts += [text[done : i + 1], MASK]
                    out += i + 1 - done
                    replaced.append((i + 1, end, out, out + len(MASK)))
                    out += len(MASK)
                    done = end
                pos = max(end, p + 12)
                continue
        scheme = _WORD.match(text, i).end()
        if (
            scheme < n
            and text[scheme] == " "
            and text[i:scheme].lower() in _AUTH_SCHEMES
        ):
            i = scheme + 1
        # in quotes the value runs to the closing quote and on through the
        # shell word it is in ('Bearer a'"b")
        if escaped_quote:
            end = _quoted_value(text, i, quote, _ELEMENT_REST)[1]
        else:
            end = _HEADER_VALUE[quote].match(text, i).end()
            if (
                quote
                and end + 1 < n
                and text[end] == quote
                and text[end + 1] not in _ARGUMENT_ENDS
            ):
                end = max(end, _shell_value(text, end + 1, "", _WORD_ENDS)[1])
        if end > i:
            if start < 0 and glued:
                start = _glued_segment(text, name, done)
            if start >= 0:
                covers.append(
                    (
                        out + max(start - done, 0),
                        out + i - done + len(MASK),
                        url_end,
                    )
                )
            parts += [text[done:i], MASK]
            out += i - done
            replaced.append((i, end, out, out + len(MASK)))
            out += len(MASK)
            done = end
        pos = max(end, p + 12)
    if not parts:
        return text, []
    parts.append(text[done:])
    # a span runs on to its URL's end, in the masked text: after the last
    # span replaced that starts at or before it (found by its start)
    spans, starts = [], [region[0] for region in replaced]
    for start, stop, url_end in covers:
        before = after = 0
        r = bisect.bisect_right(starts, url_end) - 1
        if r >= 0:
            before, after = replaced[r][1], replaced[r][3]
        spans.append((start, max(stop, after + max(url_end - before, 0))))
    return "".join(parts), spans


def _glued_segment(text, name, floor):
    """Where the path segment that a header's name at name ends starts
    (.../<token>Authorization=...), or -1: its token, which the header's
    mask breaks, is masked whole with it. Its token characters and escapes
    (%2B) from a "/" or an apostrophe, back to floor; in an encoded URL its
    decoded level has it."""
    k = name
    while k > floor and text[k - 1] in _SEGMENT_CHARS:
        k -= 1
    return k if k < name and k > 0 and text[k - 1] in "/'" else -1


def _mask_netrc(text):
    """The login, password and account of a netrc entry (machine <host>
    login <name> password <secret>, or default login ..., also over several
    lines, as apt's auth.conf has them, comment lines between) masked. In a
    rendered value (b'machine h\\nlogin u\\n...': the entry follows a quote
    or an escape, or its host runs into one) the escapes separate its words
    too (_RENDERED_WORD)."""
    n = len(text)
    # an entry may be raw text or a rendered value (b'machine h\nlogin
    # u\n...', JSON's "...\t..."): a quote or an escape before it tells it
    # is rendered; otherwise either reading may be right (a raw path may hold
    # \n, a rendered entry may follow a space), and a host whose quote is not
    # closed on its line may be the rest of the line or a word. The text is
    # read each way on its own, entry after entry, and the credentials any
    # reading finds are masked. A rendered reading of text without a
    # backslash, or a word host without a quote, finds nothing more.
    spans = []
    for rendered_pass, word_host in (
        (False, False),
        (True, False),
        (False, True),
        (True, True),
    ):
        if rendered_pass and "\\" not in text or word_host and '"' not in text:
            continue
        pos = 0
        machine, default = text.find("machine"), text.find("default")
        while True:
            if 0 <= machine < pos:
                machine = text.find("machine", pos)
            if 0 <= default < pos:
                default = text.find("default", pos)
            p, has_host = machine, True
            if p < 0 or 0 <= default < p:
                p, has_host = default, False
            if p < 0:
                break
            pos = p + 7
            quoted = p > 0 and text[p - 1] in "\"'"
            escaped = p >= 2 and text[p - 2] == "\\" and text[p - 1] in "nrt"
            # an entry starts a line, a quoted string, or a value
            # (auth=machine ...; an inner one of ?a=b=machine ... too, which
            # _scan decodes with the outer one)
            if (
                (
                    p > 0
                    and text[p - 1] not in _WS
                    and text[p - 1] != "="
                    and not quoted
                    and not escaped
                )
                or pos >= n
                or (
                    text[pos] not in _WS and not text.startswith(_ESCAPES, pos)
                )
            ):
                continue
            rendered = (
                rendered_pass
                or quoted
                or escaped
                or text.startswith(_ESCAPES, pos)
            )
            word = _RENDERED_WORD if rendered else _NON_SPACE
            i = pos
            if has_host:
                host = _netrc_space(text, pos, rendered)
                i = _netrc_value(text, host, rendered, word, word_host)
            # what was read is not read again in this pass
            pos = max(pos, _netrc_pairs(text, i, rendered, word, spans))
    # what is masked: the spans in order, those that overlap as one
    parts, done = [], 0
    for start, end in sorted(spans):
        if start >= done:
            parts += [text[done:start], MASK]
            done = end
        elif end > done:
            done = end
    if not parts:
        return text
    parts.append(text[done:])
    return "".join(parts)


def _netrc_pairs(text, i, rendered, word, spans):
    """The keyword and value pairs of a netrc entry from i (8 at most), the
    spans of their credentials added to spans; where they were read to."""
    stop = i
    for _ in range(8):
        k = _netrc_space(text, i, rendered)
        stop = k
        kw_end = word.match(text, k).end()
        keyword = text[k:kw_end]
        if keyword not in ("login", "password", "account", "port"):
            break
        v = _netrc_space(text, kw_end, rendered, True)
        if v == kw_end:
            break
        i = _netrc_value(text, v, rendered, word)
        stop = i
        if keyword != "port" and i > v:
            spans.append((v, i))
    return stop


def _netrc_space(text, i, rendered, value=False):
    """The space between two words of a netrc entry from i: whitespace, the
    escapes of a rendered value, and comments (a '#' to the end of its
    line), also before a value when the '#' starts a line (login\\n#
    ...\\nname); a '#' after a keyword on its line starts the value
    (password #x)."""
    space = _RENDERED_SPACE if rendered else _SPACE
    comment = _RENDERED_COMMENT if rendered else _COMMENT
    line_start = False
    while True:
        j = space.match(text, i).end()
        if not line_start:
            run = text[i:j]
            line_start = "\n" in run or "\r" in run
            if rendered and not line_start:
                line_start = "\\n" in run or "\\r" in run
        if j < len(text) and text[j] == "#" and (line_start or not value):
            i = comment.match(text, j).end()
            continue
        return j


def _netrc_value(text, i, rendered, word, word_if_open=False):
    """Where a netrc value at i ends: a quoted one, spaces in it ("a b",
    \\"a b\\" rendered), at its closing quote or the end of the line
    (word_if_open: a quote not closed on its line is read as a word)."""
    if i < len(text) and text[i] == '"':
        if rendered:
            end = _RENDERED_NETRC_QUOTED.match(text, i + 1).end()
            closed = end < len(text) and text[end] == '"'
        else:
            end, closed = _quoted_segment(text, i + 1, '"', False)
        if closed or not word_if_open:
            return end + 1 if closed else end
    elif rendered and text.startswith('\\"', i):
        end, closed = _quoted_segment(text, i + 2, '"', True)
        if closed or not word_if_open:
            return end + 2 if closed else end
    return word.match(text, i).end()


def _mask_cut_tail(text):
    """text, which the SDK cut at its length limit and ended with "...",
    with what the cut may have hidden from the other rules masked: a URL cut
    in its authority after "://" (the user info may hold any of :=&), one
    cut in a path segment that would be a token, a JWT all but eyJ. Of
    several URLs in that tail (a raw query), the last one is cut."""
    end = len(text) - 3
    start = max(text.rfind(c, 0, end) for c in ' \t\n\r\x0b\x0c"<>') + 1
    # a backslash ends it too, but for an escaped apostrophe of a rendered
    # value, an escaped slash (\\/, JSON's, its backslashes all) and one the
    # cut left alone
    slash = text.rfind("\\", start, end - 1)
    while slash >= start:
        if (
            text[slash + 1] in "/\\"
            or text.startswith("u0026", slash + 1)
            or end - slash <= 5
            and "u0026".startswith(text[slash + 1 : end])
        ):
            # JSON's escaped "/" or "&" (which user info may hold), also
            # rendered again: its backslashes all; or one the cut parts
            # (\u00, a run of backslashes)
            while slash > start and text[slash - 1] == "\\":
                slash -= 1
        elif text[slash + 1] != "'":
            start = slash + 1
            break
        slash = text.rfind("\\", start, slash)
    tail = text[start:end]
    # read with its escaped slashes as "/", which are written back as they
    # were (the cut rules mask what follows a slash they keep)
    plain = _unescape_slashes(tail) if "\\" in tail else tail
    masked = _mask_cut_url(plain)
    if masked == plain:
        return text
    if plain != tail:
        masked = _escape_slashes(masked, tail)
    return text[:start] + masked + text[end:]


def _mask_cut_url(tail):
    u = tail.rfind("://")
    if u < 0:
        return _mask_cut_jwt(tail, 0)
    rest = tail[u + 3 :]
    b = min(
        (
            x
            for x in (rest.find("/"), rest.find("?"), rest.find("#"))
            if x >= 0
        ),
        default=-1,
    )
    if b < 0:
        return tail[: u + 3] + MASK if rest else tail
    if rest[b] == "/" and "?" not in rest[b:] and "#" not in rest[b:]:
        segments = rest[b:].split("/")
        at, after = _user_info_end(rest, 0, b)
        host = _host_name(rest[after:b] if at >= 0 else rest[:b])
        if (
            len(segments) >= 2
            and segments[-1]
            and _token_need(segments[-2], host)
        ):
            return tail[: u + 3 + b] + "/".join(segments[:-1] + [MASK])
        # or after a %-encoded slash of the last segment (-els%2F<token>)
        start = 0
        for slash in _ENCODED_SLASH.finditer(segments[-1]):
            if slash.end() < len(segments[-1]) and _token_need(
                segments[-1][start : slash.start()], host
            ):
                last = segments[-1][: slash.end()] + MASK
                return tail[: u + 3 + b] + "/".join(segments[:-1] + [last])
            start = slash.end()
    # cut in the query or in another path segment: a token-like value is
    # masked anyway, a JWT under any name is not
    return _mask_cut_jwt(tail, u + 3 + b)


def _mask_cut_jwt(tail, start):
    """tail with a JWT the cut left in it, from start on, masked all but its
    eyJ."""
    e = tail.find("eyJ", start)
    return tail if e < 0 else tail[: e + 3] + MASK


# The walk through an event is bounded: a dictionary or list that holds
# itself, data deeper than _MAX_DEPTH, past _MAX_CONTAINERS visited
# containers or past _MAX_ENTRIES of their entries is replaced by a
# placeholder.
_MAX_DEPTH = 32
_MAX_CONTAINERS = 10000
_MAX_ENTRIES = 100000
_OMITTED_CYCLE = "[omitted: holds itself]"
_OMITTED_TOO_MUCH = "[omitted: too deep or too large]"


def redact_event(event):
    """Mask the credentials in every string of a Sentry event, in place.

    Every string and dictionary key, at any depth, goes through
    redact_credentials: the message, log parameters, exception values, the
    local variables of the stack, tags, the fingerprint, extra data,
    contexts, breadcrumbs, the request, the SDK's notes (_meta). The value of
    a key that names a credential (_credential_name: Authorization, Cookie,
    X-Auth-Token, api_key, ...) is masked whole wherever it is. A string the
    SDK cut at its length limit (_meta "!limit") is masked as described in
    _mask_cut_tail. An event without credentials is left as it is.
    """
    request = event.get("request")
    if isinstance(request, dict) and request.get("cookies"):
        request["cookies"] = MASK
    meta = event.get("_meta")
    _Walk().container(event, meta if isinstance(meta, dict) else None)
    return event


class _Walk:
    def __init__(self):
        # the containers being walked, outermost first
        self.path = []
        self.budget = _MAX_CONTAINERS
        self.entries = _MAX_ENTRIES

    def container(self, container, meta, by_name=True, whole=False):
        """Mask container in place; by_name: the values of credential names
        whole; whole: it is (in) the value of one, its strings and numbers
        are masked whole, also in the lists in it (a dictionary in it is
        read by its own keys)."""
        is_dict = isinstance(container, dict)
        items = list(container.items() if is_dict else enumerate(container))
        # a [name, value] pair (request headers as a list of them,
        # [["Authorization", "Bearer a"]]): a credential name's value whole
        pair = (
            by_name
            and not is_dict
            and len(container) == 2
            and isinstance(container[0], str)
            and _pair_name(container[0])
        )
        renamed = []
        top = not self.path
        self.path.append(id(container))
        for key, value in items:
            if top and key == "_meta":
                continue
            child = meta.get(str(key)) if meta is not None else None
            masked = self.value(
                key,
                value,
                child if isinstance(child, dict) else None,
                # the names of the modules are packages, their values
                # versions
                by_name and not (top and key == "modules"),
                whole and not is_dict or pair and key == 1,
            )
            if masked is not value:
                container[key] = masked
            if is_dict and isinstance(key, str):
                masked_key = _redact_string(key)
                if masked_key is not key:
                    renamed.append((key, masked_key))
        if top and isinstance(container.get("_meta"), dict):
            # the SDK's notes, read above, name the keys of what it cut
            container["_meta"] = self.value(
                "_meta", container["_meta"], None, True
            )
        self.path.pop()
        if renamed:
            _rename(container, renamed)

    def value(self, key, value, meta, by_name, whole=False):
        if by_name and isinstance(key, str) and _credential_name(key):
            whole = True
        if isinstance(value, str):
            if whole:
                return MASK if value else value
            return _redact_string(value, _was_cut(meta))
        if whole and isinstance(value, (int, float)):
            # a boolean is no credential
            return value if isinstance(value, bool) else MASK
        if isinstance(value, (dict, list)):
            if len(self.path) > _MAX_DEPTH or self.budget <= 0:
                return _OMITTED_TOO_MUCH
            if id(value) in self.path:
                return _OMITTED_CYCLE
            if len(value) > self.entries:
                return _OMITTED_TOO_MUCH
            self.budget -= 1
            self.entries -= len(value)
            self.container(value, meta, by_name, whole)
        return value


def _was_cut(meta):
    """Whether _meta says the SDK cut the string at its length limit."""
    annotations = meta.get("") if meta is not None else None
    if not isinstance(annotations, dict):
        return False
    return any(
        isinstance(rule, list) and rule and rule[0] == "!limit"
        for rule in annotations.get("rem") or ()
    )


def _rename(container, renamed):
    """Two keys that differ only in their credentials keep both values:
    key, key#2, key#3, ... Each masked key remembers its next free number,
    so many keys that mask the same cost one lookup each."""
    values = [(masked, container.pop(key)) for key, masked in renamed]
    next_free = {}
    for masked, value in values:
        free = masked
        if free in container:
            number = next_free.get(masked, 2)
            free = "%s#%d" % (masked, number)
            while free in container:
                number += 1
                free = "%s#%d" % (masked, number)
            next_free[masked] = number + 1
        container[free] = value


def _redact_string(value, cut=False):
    bounded = value if len(value) <= MAX_LENGTH else _bound(value)
    masked = _mask(bounded, True, cut and value.endswith("..."))
    return value if masked == value else masked


# what a stand-in for an event whose masking failed keeps: fields the SDK
# and our code set, tag values of a shape that cannot hold a URL or a
# credential, exception types and modules
_KEPT_FIELDS = (
    "event_id",
    "timestamp",
    "level",
    "platform",
    "sdk",
    "release",
    "environment",
    "logger",
)
_KEPT_TAGS = frozenset(
    (
        "name",
        "version",
        "core_version",
        "av_version",
        "common_version",
        "component",
        "firewall",
        "hosting_panel",
        "strategy",
        "virtualization",
        "pkg_tool",
        "pkg_action",
        "pkg_cause",
        "pkg_owner",
        "exit_code",
    )
)
_SAFE_TAG = re.compile(r"[A-Za-z0-9_.:+ -]{0,64}\Z")
_SAFE_NAME = re.compile(r"[A-Za-z0-9_.]{1,128}\Z")


def masking_failed_event(event, error):
    """A credential-free stand-in for an event whose masking raised error:
    no text of the event, only what classifies it (its exception types, the
    tags our code sets, the exit code of a command) and the tag
    masking_failed, so that the failure is still seen in Sentry."""
    minimal = {key: event[key] for key in _KEPT_FIELDS if key in event}
    tags = event.get("tags")
    pairs = (
        tags.items()
        if isinstance(tags, dict)
        else tags
        if isinstance(tags, list)
        else ()
    )
    kept = {}
    for pair in pairs:
        if isinstance(pair, (list, tuple)) and len(pair) == 2:
            name, value = pair
            if (
                name in _KEPT_TAGS
                and isinstance(value, str)
                and _SAFE_TAG.match(value)
            ):
                kept[name] = value
    kept["masking_failed"] = "true"
    kept["masking_error"] = type(error).__name__
    minimal["tags"] = kept
    types = []
    exception = event.get("exception")
    values = exception.get("values") if isinstance(exception, dict) else None
    for value in values if isinstance(values, list) else ():
        if isinstance(value, dict):
            kept_value = {
                field: value[field]
                for field in ("type", "module")
                if isinstance(value.get(field), str)
                and _SAFE_NAME.match(value[field])
            }
            if kept_value:
                types.append(kept_value)
    if types:
        minimal["exception"] = {"values": types}
    minimal["message"] = (
        "Event not sent: masking its credentials failed (%s)"
        % type(error).__name__
    )
    minimal["fingerprint"] = [
        "masking-failed",
        types[-1].get("type", "message") if types else "message",
    ]
    return minimal
