Skip to Content
Course content

247: Secure Coding Practices in Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 MerchantId value class that ensures the ID starts with "MID-".
  • Create a PaymentToken class that wraps a string. Override its toString() 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 main function, demonstrate that you cannot pass a PaymentToken into the merchantId parameter.
  • Demonstrate that printing the PaymentToken object does not reveal the actual token string.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.