SPB Git

Repository Public

SecretRedactor.swift 6.4 KB 134 lines swift

1import Foundation23/// Category of secret recognised by ``SecretRedactor``.4public enum SecretKind: String, Sendable, Codable, CaseIterable, Hashable {5    case privateKeyBlock = "private-key"6    case urlCredentials = "url-credentials"7    case authorizationHeader = "authorization"8    case anthropicAPIKey = "anthropic-key"9    case openAIAPIKey = "openai-key"10    case awsAccessKeyID = "aws-access-key-id"11    case awsSecretKey = "aws-secret-key"12    case githubToken = "github-token"13    case slackToken = "slack-token"14    case jsonWebToken = "jwt"15    case otherToken = "token"16    case genericAssignment = "assignment"17    /// A literal the caller asked to mask (for example the stored provider key).18    case knownSecret = "known-secret"19}2021/// How many secrets of one kind were masked. Never contains the secret itself.22public struct RedactionFinding: Sendable, Equatable, Hashable, Codable {23    public let kind: SecretKind24    public let count: Int2526    public init(kind: SecretKind, count: Int) {27        self.kind = kind28        self.count = count29    }30}3132/// Output of ``SecretRedactor/redact(_:)``.33public struct RedactionResult: Sendable, Equatable {34    /// Text with every detected secret replaced by `[REDACTED:<kind>]`.35    public let text: String36    /// One entry per kind found, in detection order.37    public let findings: [RedactionFinding]38    /// Total number of masked secrets.39    public var totalCount: Int { findings.reduce(0) { $0 + $1.count } }40}4142/// Masks secrets in text before it can be sent to a provider or exported.43///44/// Detection is pattern based and intentionally biased towards false positives:45/// a harmless value that looks like a secret is masked rather than risk a leak.46/// It is a safety net, not a proof that the text is free of secrets.47public struct SecretRedactor: Sendable {48    private let additionalSecrets: [SecretValue]4950    /// - Parameter additionalSecrets: literal values to mask wherever they appear51    ///   (typically the keys held in the ``SecretStore``). Values shorter than 6 characters are ignored.52    public init(additionalSecrets: [SecretValue] = []) {53        self.additionalSecrets = additionalSecrets.filter { $0.reveal().count >= 6 }54    }5556    /// The marker substituted for a secret of `kind`.57    public static func marker(for kind: SecretKind) -> String { "[REDACTED:\(kind.rawValue)]" }5859    /// Returns `text` with secrets masked, plus per-kind counts.60    public func redact(_ text: String) -> RedactionResult {61        var current = text62        var counts: [(SecretKind, Int)] = []6364        func record(_ kind: SecretKind, _ n: Int) {65            guard n > 0 else { return }66            if let i = counts.firstIndex(where: { $0.0 == kind }) { counts[i].1 += n } else { counts.append((kind, n)) }67        }6869        var known = 070        for secret in additionalSecrets {71            let raw = secret.reveal()72            let parts = current.components(separatedBy: raw)73            if parts.count > 1 {74                known += parts.count - 175                current = parts.joined(separator: Self.marker(for: .knownSecret))76            }77        }78        record(.knownSecret, known)7980        for rule in Self.rules {81            let ns = current as NSString82            let range = NSRange(location: 0, length: ns.length)83            let n = rule.regex.numberOfMatches(in: current, range: range)84            guard n > 0 else { continue }85            current = rule.regex.stringByReplacingMatches(in: current, range: range, withTemplate: rule.template)86            record(rule.kind, n)87        }88        return RedactionResult(text: current, findings: counts.map { RedactionFinding(kind: $0.0, count: $0.1) })89    }9091    private struct Rule: Sendable {92        let kind: SecretKind93        let regex: NSRegularExpression94        let template: String95    }9697    private static func rule(_ kind: SecretKind, _ pattern: String, prefixGroup: Bool = false) -> Rule {98        // Patterns are compile-time constants; a failure here is a programming error.99        let regex = try! NSRegularExpression(pattern: pattern, options: [])100        return Rule(kind: kind, regex: regex, template: (prefixGroup ? "$1" : "") + "[REDACTED:\(kind.rawValue)]")101    }102103    private static let notRedacted = "(?![\"']?\\[REDACTED)"104105    /// Ordered from most to least specific; later rules never re-match a marker.106    private static let rules: [Rule] = [107        rule(.privateKeyBlock,108             "-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\\s\\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|\\z)"),109        rule(.urlCredentials,110             "([A-Za-z][A-Za-z0-9+.-]*://)[^\\s/:@]+:[^\\s/@]+(?=@)", prefixGroup: true),111        rule(.authorizationHeader,112             "((?i:(?:proxy-)?authorization)[\"']?\\s*[:=]\\s*[\"']?(?i:bearer|basic|token|digest|negotiate)\\s+)[^\\s\"']+", prefixGroup: true),113        rule(.authorizationHeader,114             "(\\b(?i:bearer)\\s+)\(notRedacted)[A-Za-z0-9._~+/=-]{16,}", prefixGroup: true),115        rule(.authorizationHeader,116             "((?:^|\\s)(?:-u|--user)[ =])\(notRedacted)[^\\s:\"']+:[^\\s\"']+", prefixGroup: true),117        rule(.anthropicAPIKey, "\\bsk-ant-[A-Za-z0-9_-]{8,}"),118        rule(.openAIAPIKey, "\\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{16,}"),119        rule(.awsAccessKeyID, "\\b(?:AKIA|ASIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA)[A-Z0-9]{16}\\b"),120        rule(.awsSecretKey,121             "((?i:aws_?secret_?access_?key|aws_?session_?token|secret_?access_?key)[\"']?\\s*[:=]\\s*[\"']?)\(notRedacted)[A-Za-z0-9/+=]{16,}", prefixGroup: true),122        rule(.githubToken, "\\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})"),123        rule(.slackToken, "\\b(?:xox[abeoprs]-[A-Za-z0-9-]{10,}|xapp-[A-Za-z0-9-]{10,})"),124        rule(.slackToken, "https://hooks\\.slack\\.com/services/[A-Za-z0-9/_-]+"),125        rule(.jsonWebToken, "\\beyJ[A-Za-z0-9_-]{5,}\\.eyJ[A-Za-z0-9_-]{5,}\\.[A-Za-z0-9_-]*"),126        rule(.otherToken,127             "\\b(?:AIza[0-9A-Za-z_-]{35}|[sr]k_(?:live|test)_[A-Za-z0-9]{16,}|npm_[A-Za-z0-9]{36}|glpat-[A-Za-z0-9_-]{20,})"),128        rule(.genericAssignment,129             "((?i:[A-Za-z0-9_.-]*(?:password|passwd|passphrase|pwd|secret|token(?!s|ize)|api[_-]?key|access[_-]?key|private[_-]?key|credentials?)[A-Za-z0-9_.-]*)[\"']?\\s*[:=]\\s*)\(notRedacted)(?:\"[^\"\\n]*\"|'[^'\\n]*'|[^\\s\"',;&|)]+)", prefixGroup: true),130        rule(.genericAssignment,131             "((?:^|\\s)--?(?i:password|passwd|passphrase|token|secret|api-?key)\\s+)\(notRedacted)(?!-)[^\\s]+", prefixGroup: true),132    ]133}134
Files main
Menu

Theme