Skip to content

Instantly share code, notes, and snippets.

@ppeelen
Last active December 11, 2023 07:43
Show Gist options
  • Save ppeelen/7e84fdfe0b5fcb4418ff7f85eaf5e118 to your computer and use it in GitHub Desktop.
Save ppeelen/7e84fdfe0b5fcb4418ff7f85eaf5e118 to your computer and use it in GitHub Desktop.
A simple sanitiser for Swift strings. Removed certain sensitive information; great for using in logs.
extension String {
/**
Sanitizes the string by obscuring sensitive information.
- Returns: A sanitized version of the string where sensitive information is replaced with `*******`.
This method searches for specific keys (namely `access_token`, `refresh_token`, and `id_token`) in various formats including JSON-like strings, query strings, HTTP headers, plain text, and also searches for email addresses. It replaces their associated values or the email addresses with a placeholder string to obscure sensitive information.
## Examples:
```swift
let exampleString = "{\"access_token\":\"sensitive_data\"} or email@example.com"
let sanitizedString = exampleString.sanitized()
print(sanitizedString)
// Prints a string where sensitive data and email addresses are replaced with `*******`
```
- Note: The method uses regular expressions to find and replace sensitive information such as tokens and email addresses. It only works for certain patterns and it may not work as intended for strings with different or unusual formats.
*/
func sanitized() -> String {
let patterns = [
"(\"access_token\":)\\s*\"[^\"]+\"", // JSON format
"(\"refresh_token\":)\\s*\"[^\"]+\"",
"(\"id_token\":)\\s*\"[^\"]+\"",
"(access_token=)[^&\\s]+", // Query string format
"(refresh_token=)[^&\\s]+",
"(id_token=)[^&\\s]+",
"(Authorization:\\s*Bearer\\s)[^\\s]+", // HTTP Header format
"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}" // Email addresses
]
var sanitizedString = self
for pattern in patterns {
let regex = try! NSRegularExpression(pattern: pattern, options: [])
sanitizedString = regex.stringByReplacingMatches(in: sanitizedString, options: [], range: NSRange(location: 0, length: sanitizedString.utf16.count), withTemplate: "$1*******")
}
return sanitizedString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment