Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
247: Secure Coding Practices in Kotlin
When we talk about "secure coding," people often jump straight to encryption algorithms or firewall rules. But as an engineer, I've found that the most dangerous vulnerabilities usually creep in through simple developer mistakes—like swapping two arguments in a function call or accidentally logging a password in a production environment. In Kotlin, we can use the type system to make these mistakes physically impossible.
Starting with a Risky Profile Update
Let's imagine we're building a service to update a user's private settings. We need a user ID and a sensitive API key to authorize the request. Initially, I might write something like this:
fun updateUserSettings(userId: String, apiKey: String, newTheme: String) {
println("Updating settings for user $userId using key $apiKey")
// Database logic here...
}
// Calling the function
updateUserSettings("user_123", "sk_live_51MzXy2", "dark-mode")
At first glance, this is fine. But here is where I usually mess up when I'm tired or rushing. Because both userId and apiKey are just strings, the compiler doesn't care about the order. I might accidentally do this:
// I swapped the arguments by mistake!
updateUserSettings("sk_live_51MzXy2", "user_123", "dark-mode")
The code compiles perfectly. But now, my application is trying to look up a user whose ID is actually my secret API key. Even worse, if I have a logging framework enabled, I've just printed a live secret key into my plaintext logs. This is a classic security failure caused by "Primitive Obsession"—using basic types like String for everything.
Wrapping Sensitive Data in Value Classes
To fix this, I'm going to stop using String for these identifiers. I'll use Kotlin's value classes. These give us type safety without the performance hit of creating a full object on the heap for every single ID.
@JvmInline
value class UserId(val value: String)
@JvmInline
value class ApiKey(val value: String)
fun updateUserSettings(userId: UserId, apiKey: ApiKey, newTheme: String) {
// Now the compiler ensures we can't swap these
}
// This now fails to compile, which is exactly what we want:
// updateUserSettings(ApiKey("secret"), UserId("123"), "dark-mode")
Now, if I try to pass the ApiKey where a UserId is expected, the IDE will scream at me before I even hit "Run." We've moved the security check from "human vigilance" to "compiler enforcement."
Preventing Secrets from Leaking into Logs
We've solved the argument-swapping problem, but we still have the logging issue. If I use a data class or a standard value class, calling println(apiKey) will still print the actual secret. To fix this, I'll move the ApiKey into its own file and override the toString() method.
Wait—I just realized something. I can't override toString() directly inside a @JvmInline value class because it's designed to be inlined as the underlying type. This is a common trap. To properly mask a secret, I should wrap the value in a way that controls its representation.
class SecretKey(private val value: String) {
override fun toString(): String = "********"
fun reveal(): String = value
}
// Now, even if I'm careless with logging:
val key = SecretKey("sk_live_51MzXy2")
println("Updating with key: $key") // Prints: Updating with key: ********
I'll use SecretKey for the actual sensitive material and value classes for non-secret identifiers. This ensures that the "reveal" of a secret is an intentional act in the code, not a side effect of a log statement.
Adding a Guard Layer
Finally, we can't trust that the strings coming into these classes are actually valid. Secure coding means "fail fast." I'll add an init block to my value classes to validate the format immediately upon creation using require().
@JvmInline
value class UserId(val value: String) {
init {
require(value.startsWith("user_")) { "Invalid User ID format" }
}
}
@JvmInline
value class ApiKey(val value: String) {
init {
require(value.length == 32) { "API Key must be exactly 32 characters" }
}
}
By the time the updateUserSettings function receives these objects, we already know they are the correct type, they aren't swapped, and they meet our basic format requirements. We've shrunk the "attack surface" of the function significantly.
📋 Practical Task
Exercise: Build a Secure Payment Token Handler
You need to create a small system to handle payment tokens and merchant IDs. To prevent security leaks and logic errors, implement the following:
- Create a
MerchantIdvalue class that ensures the ID starts with "MID-". - Create a
PaymentTokenclass that wraps a string. Override itstoString()method so that it always returns"[MASKED]"to prevent the token from appearing in logs. - Implement a function
processPayment(merchantId: MerchantId, token: PaymentToken, amount: Double). - In your
mainfunction, demonstrate that you cannot pass aPaymentTokeninto themerchantIdparameter. - Demonstrate that printing the
PaymentTokenobject does not reveal the actual token string.
There are no comments for now.