Masking data

Question:

How can you mask fields in a Kafka topic?

Edit this page

Example use case:

Suppose you have a topic that contains personally identifiable information (PII), and you want to mask those fields. In this tutorial, we'll write a program that persists the events in the original topic to a new Kafka topic with the PII removed or obfuscated.

Hands-on code example:

Short Answer

Use the ksqlDB MASK function to obfuscate fields.

CREATE STREAM purchases_pii_obfuscated
    WITH (kafka_topic='purchases_pii_obfuscated', value_format='json', partitions=1) AS
    SELECT MASK(CUSTOMER_NAME) AS CUSTOMER_NAME,
           MASK(DATE_OF_BIRTH) AS DATE_OF_BIRTH,
           ORDER_ID, PRODUCT, ORDER_TOTAL_USD, TOWN, COUNTRY
    FROM PURCHASES;

Run it

Prerequisites

1

This tutorial installs Confluent Platform using Docker. Before proceeding:

  • • Install Docker Desktop (version 4.0.0 or later) or Docker Engine (version 19.03.0 or later) if you don’t already have it

  • • Install the Docker Compose plugin if you don’t already have it. This isn’t necessary if you have Docker Desktop since it includes Docker Compose.

  • • Start Docker if it’s not already running, either by starting Docker Desktop or, if you manage Docker Engine with systemd, via systemctl

  • • Verify that Docker is set up properly by ensuring no errors are output when you run docker info and docker compose version on the command line

Initialize the project

2

To get started, make a new directory anywhere you’d like for this project:

mkdir masking-data && cd masking-data

Then make the following directories to set up its structure:

mkdir src test

Get Confluent Platform

3

Next, create the following docker-compose.yml file to obtain Confluent Platform (for Kafka in the cloud, see Confluent Cloud):

version: '2'
services:
  broker:
    image: confluentinc/cp-kafka:7.4.1
    hostname: broker
    container_name: broker
    ports:
    - 29092:29092
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,CONTROLLER:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_NODE_ID: 1
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@broker:29093
      KAFKA_LISTENERS: PLAINTEXT://broker:9092,CONTROLLER://broker:29093,PLAINTEXT_HOST://0.0.0.0:29092
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_LOG_DIRS: /tmp/kraft-combined-logs
      CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk
  schema-registry:
    image: confluentinc/cp-schema-registry:7.3.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
    - broker
    ports:
    - 8081:8081
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: broker:9092
  ksqldb-server:
    image: confluentinc/ksqldb-server:0.28.2
    hostname: ksqldb-server
    container_name: ksqldb-server
    depends_on:
    - broker
    - schema-registry
    ports:
    - 8088:8088
    environment:
      KSQL_CONFIG_DIR: /etc/ksqldb
      KSQL_LOG4J_OPTS: -Dlog4j.configuration=file:/etc/ksqldb/log4j.properties
      KSQL_BOOTSTRAP_SERVERS: broker:9092
      KSQL_HOST_NAME: ksqldb-server
      KSQL_LISTENERS: http://0.0.0.0:8088
      KSQL_CACHE_MAX_BYTES_BUFFERING: 0
      KSQL_KSQL_SCHEMA_REGISTRY_URL: http://schema-registry:8081
  ksqldb-cli:
    image: confluentinc/ksqldb-cli:0.28.2
    container_name: ksqldb-cli
    depends_on:
    - broker
    - ksqldb-server
    entrypoint: /bin/sh
    environment:
      KSQL_CONFIG_DIR: /etc/ksqldb
    tty: true
    volumes:
    - ./src:/opt/app/src
    - ./test:/opt/app/test

And launch it by running:

docker compose up -d

Write the program interactively using the CLI

4

To begin developing interactively, open up the ksqlDB CLI:

docker exec -it ksqldb-cli ksql http://ksqldb-server:8088

First, you’ll need to create a Kafka topic and stream to represent the purchases data. The following creates both in one shot.

CREATE STREAM purchases (order_id INT, customer_name VARCHAR, date_of_birth VARCHAR,
                         product VARCHAR, order_total_usd DOUBLE, town VARCHAR, country VARCHAR)
    WITH (kafka_topic='purchases', value_format='json', partitions=1);

Then insert the purchase data using the following commands:

INSERT INTO purchases (order_id, customer_name, date_of_birth, product, order_total_usd, town, country) VALUES (1, 'Britney', '02/29/2000', 'Heart Rate Monitor', 119.93, 'Denver', 'USA');
INSERT INTO purchases (order_id, customer_name, date_of_birth, product, order_total_usd, town, country) VALUES (2, 'Michael', '06/08/1981', 'Foam Roller', 34.95, 'Los Angeles', 'USA');
INSERT INTO purchases (order_id, customer_name, date_of_birth, product, order_total_usd, town, country) VALUES (3, 'Kimmy', '05/19/1978', 'Hydration Belt', 50.00, 'Tuscan', 'USA');
INSERT INTO purchases (order_id, customer_name, date_of_birth, product, order_total_usd, town, country) VALUES (4, 'Samantha', '08/05/1983', 'Wireless Headphones', 175.93, 'Tulsa', 'USA');
INSERT INTO purchases (order_id, customer_name, date_of_birth, product, order_total_usd, town, country) VALUES (5, 'Jonathon', '01/31/1981', 'Comfort Insoles', 49.95, 'Portland', 'USA');
INSERT INTO purchases (order_id, customer_name, date_of_birth, product, order_total_usd, town, country) VALUES (6, 'Raymond', '07/29/2001', 'Running Beanie', 13.73, 'Omaha', 'USA');

Our purchases stream is created and should be populated with data. Prior to querying the purchases data, let’s tell ksqlDB to query data from the beginning of the topic.

SET 'auto.offset.reset'='earliest';

Now we should be able to see all of the purchases data we just entered with the following command:

SELECT *
    FROM purchases
    EMIT CHANGES
    LIMIT 6;

This should yield roughly the following output. The order will be different depending on how the records were actually inserted. Note that PII like name, birthdate, city, and country are present.

+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
|ORDER_ID            |CUSTOMER_NAME       |DATE_OF_BIRTH       |PRODUCT             |ORDER_TOTAL_USD     |TOWN                |COUNTRY             |
+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
|1                   |Britney             |02/29/2000          |Heart Rate Monitor  |119.93              |Denver              |USA                 |
|2                   |Michael             |06/08/1981          |Foam Roller         |34.95               |Los Angeles         |USA                 |
|3                   |Kimmy               |05/19/1978          |Hydration Belt      |50.0                |Tuscan              |USA                 |
|4                   |Samantha            |08/05/1983          |Wireless Headphones |175.93              |Tulsa               |USA                 |
|5                   |Jonathon            |01/31/1981          |Comfort Insoles     |49.95               |Portland            |USA                 |
|6                   |Raymond             |07/29/2001          |Running Beanie      |13.73               |Omaha               |USA                 |
Limit Reached
Query terminated

Next we will highlight two ways to mask PII data, both methods will result in new streams.
Our first masking technique will be to create a derived topic in which all PII is excluded. This technique masks data by refraining from pulling in PII fields like CUSTOMER_NAME and DATE_OF_BIRTH.

CREATE STREAM purchases_pii_removed
    WITH (kafka_topic='purchases_pii_removed', value_format='json', partitions=1) AS
    SELECT ORDER_ID, PRODUCT, ORDER_TOTAL_USD, TOWN, COUNTRY
    FROM PURCHASES;

Let’s verify that the derived topic we just created does not have any PII related to CUSTOMER_NAME or DATE_OF_BIRTH. You can see the contents of the stream by executing the following:

SELECT *
    FROM purchases_pii_removed
    EMIT CHANGES
    LIMIT 6;

Your results should look like what is below. Take note of the lack of PII fields like CUSTOMER_NAME or DATE_OF_BIRTH.

+--------------------+--------------------+--------------------+--------------------+--------------------+
|ORDER_ID            |PRODUCT             |ORDER_TOTAL_USD     |TOWN                |COUNTRY             |
+--------------------+--------------------+--------------------+--------------------+--------------------+
|1                   |Heart Rate Monitor  |119.93              |Denver              |USA                 |
|2                   |Foam Roller         |34.95               |Los Angeles         |USA                 |
|3                   |Hydration Belt      |50.0                |Tuscan              |USA                 |
|4                   |Wireless Headphones |175.93              |Tulsa               |USA                 |
|5                   |Comfort Insoles     |49.95               |Portland            |USA                 |
|6                   |Running Beanie      |13.73               |Omaha               |USA                 |
Limit Reached
Query terminated

The second technique for masking data utilizes ksqlDB’s built in MASK functions. Here we retain the customer name and date of birth, but obfuscated.

CREATE STREAM purchases_pii_obfuscated
    WITH (kafka_topic='purchases_pii_obfuscated', value_format='json', partitions=1) AS
    SELECT MASK(CUSTOMER_NAME) AS CUSTOMER_NAME,
           MASK(DATE_OF_BIRTH) AS DATE_OF_BIRTH,
           ORDER_ID, PRODUCT, ORDER_TOTAL_USD, TOWN, COUNTRY
    FROM PURCHASES;

Use the command below to query the contents of the purchases_pii_obfuscated stream:

SELECT *
    FROM purchases_pii_obfuscated
    EMIT CHANGES
    LIMIT 6;

We can see that the sensitive data is masked with x’s or n’s.

+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
|CUSTOMER_NAME       |DATE_OF_BIRTH       |ORDER_ID            |PRODUCT             |ORDER_TOTAL_USD     |TOWN                |COUNTRY             |
+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+--------------------+
|Xxxxxxx             |nn-nn-nnnn          |1                   |Heart Rate Monitor  |119.93              |Denver              |USA                 |
|Xxxxxxx             |nn-nn-nnnn          |2                   |Foam Roller         |34.95               |Los Angeles         |USA                 |
|Xxxxx               |nn-nn-nnnn          |3                   |Hydration Belt      |50.0                |Tuscan              |USA                 |
|Xxxxxxxx            |nn-nn-nnnn          |4                   |Wireless Headphones |175.93              |Tulsa               |USA                 |
|Xxxxxxxx            |nn-nn-nnnn          |5                   |Comfort Insoles     |49.95               |Portland            |USA                 |
|Xxxxxxx             |nn-nn-nnnn          |6                   |Running Beanie      |13.73               |Omaha               |USA                 |
Limit Reached
Query terminated
MASK Function Options

There are a few types of masking functions and optional parameters that may be of use to you.

Optional arguments:
MASK(CUSTOMER_NAME, 'X', 'x', 'n', '-')
In the example above, the following types of characters in CUSTOMER_NAME would be masked: upper-case letters would become X, lower-case letters would become x, numbers would become n, and other characters would become -. This is the default setting if no mask characters are present. Set a given mask character to NULL to prevent any masking of that character type.

Other types of MASK Functions:
ksqlDB offers a variety of different masking functions that allow you to mask the farthest or nearest x number of characters on right or left. Check out the ksqlDB documentation for more information.

Type 'exit' and hit enter to shutdown the ksqlDB CLI.

Write your statements to a file

5

Now that you have a series of statements that’s doing the right thing, the last step is to put them into a file so that they can be used outside the CLI session. Create a file at src/statements.sql with the following content:

CREATE STREAM purchases (order_id INT, customer_name VARCHAR, date_of_birth VARCHAR,
                         product VARCHAR, order_total_usd DOUBLE, town VARCHAR, country VARCHAR)
    WITH (kafka_topic='purchases', value_format='json', partitions=1);

CREATE STREAM purchases_pii_removed
    WITH (kafka_topic='purchases_pii_removed', value_format='json', partitions=1) AS
    SELECT ORDER_ID, PRODUCT, ORDER_TOTAL_USD, TOWN, COUNTRY
    FROM PURCHASES;

CREATE STREAM purchases_pii_obfuscated
    WITH (kafka_topic='purchases_pii_obfuscated', value_format='json', partitions=1) AS
    SELECT MASK(CUSTOMER_NAME) AS CUSTOMER_NAME,
           MASK(DATE_OF_BIRTH) AS DATE_OF_BIRTH,
           ORDER_ID, PRODUCT, ORDER_TOTAL_USD, TOWN, COUNTRY
    FROM PURCHASES;

Test it

Create the test data

1

Create a file at test/input.json with the inputs for testing:

{
  "inputs": [
    {
      "topic": "purchases",
      "value": {
        "order_id": 1,
        "customer_name": "Britney",
        "date_of_birth":  "02/29/2000",
        "product":  "Heart Rate Monitor",
        "order_total_usd":  119.93,
        "town": "Denver",
        "country": "USA"
      }
    },
    {
      "topic": "purchases",
      "value": {
        "order_id": 2,
        "customer_name": "Michael",
        "date_of_birth":  "06/08/1981",
        "product":  "Foam Roller",
        "order_total_usd":  34.95,
        "town": "Los Angeles",
        "country": "USA"
      }
    },
    {
      "topic": "purchases",
      "value": {
        "order_id": 3,
        "customer_name": "Kimmy",
        "date_of_birth": "05/19/1978",
        "product": "Hydration Belt",
        "order_total_usd": 50.00,
        "town": "Tuscan",
        "country": "USA"
      }
    },
    {
      "topic": "purchases",
      "value": {
        "order_id": 4,
        "customer_name": "Samantha",
        "date_of_birth":  "08/05/1983",
        "product": "Wireless Headphones",
        "order_total_usd": 175.93,
        "town": "Tulsa",
        "country": "USA"
      }
    },
    {
      "topic": "purchases",
      "value": {
        "order_id": 5,
        "customer_name": "Jonathon",
        "date_of_birth": "01/31/1981",
        "product": "Comfort Insoles",
        "order_total_usd": 49.95,
        "town": "Portland",
        "country": "USA"
      }
    },
    {
      "topic": "purchases",
      "value": {
        "order_id": 6,
        "customer_name": "Raymond",
        "date_of_birth": "07/29/2001",
        "product": "Running Beanie",
        "order_total_usd": 13.73,
        "town": "Omaha",
        "country": "USA"
      }
    }
  ]
}

Similarly, create a file at test/output.json with the expected outputs:

{
  "outputs": [
    {
      "topic": "purchases_pii_removed",
      "value": {
        "ORDER_ID": 1,
        "PRODUCT":  "Heart Rate Monitor",
        "ORDER_TOTAL_USD":  119.93,
        "TOWN": "Denver",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_removed",
      "value": {
        "ORDER_ID": 2,
        "PRODUCT":  "Foam Roller",
        "ORDER_TOTAL_USD":  34.95,
        "TOWN": "Los Angeles",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_removed",
      "value": {
        "ORDER_ID": 3,
        "PRODUCT": "Hydration Belt",
        "ORDER_TOTAL_USD": 50.0,
        "TOWN": "Tuscan",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_removed",
      "value": {
        "ORDER_ID": 4,
        "PRODUCT": "Wireless Headphones",
        "ORDER_TOTAL_USD": 175.93,
        "TOWN": "Tulsa",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_removed",
      "value": {
        "ORDER_ID": 5,
        "PRODUCT": "Comfort Insoles",
        "ORDER_TOTAL_USD": 49.95,
        "TOWN": "Portland",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_removed",
      "value": {
        "ORDER_ID": 6,
        "PRODUCT": "Running Beanie",
        "ORDER_TOTAL_USD": 13.73,
        "TOWN": "Omaha",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_obfuscated",
      "value": {
        "ORDER_ID": 1,
        "CUSTOMER_NAME": "Xxxxxxx",
        "DATE_OF_BIRTH":  "nn-nn-nnnn",
        "PRODUCT":  "Heart Rate Monitor",
        "ORDER_TOTAL_USD":  119.93,
        "TOWN": "Denver",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_obfuscated",
      "value": {
        "ORDER_ID": 2,
        "CUSTOMER_NAME": "Xxxxxxx",
        "DATE_OF_BIRTH":  "nn-nn-nnnn",
        "PRODUCT":  "Foam Roller",
        "ORDER_TOTAL_USD":  34.95,
        "TOWN": "Los Angeles",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_obfuscated",
      "value": {
        "ORDER_ID": 3,
        "CUSTOMER_NAME": "Xxxxx",
        "DATE_OF_BIRTH": "nn-nn-nnnn",
        "PRODUCT": "Hydration Belt",
        "ORDER_TOTAL_USD": 50.0,
        "TOWN": "Tuscan",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_obfuscated",
      "value": {
        "ORDER_ID": 4,
        "CUSTOMER_NAME": "Xxxxxxxx",
        "DATE_OF_BIRTH":  "nn-nn-nnnn",
        "PRODUCT": "Wireless Headphones",
        "ORDER_TOTAL_USD": 175.93,
        "TOWN": "Tulsa",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_obfuscated",
      "value": {
        "ORDER_ID": 5,
        "CUSTOMER_NAME": "Xxxxxxxx",
        "DATE_OF_BIRTH": "nn-nn-nnnn",
        "PRODUCT": "Comfort Insoles",
        "ORDER_TOTAL_USD": 49.95,
        "TOWN": "Portland",
        "COUNTRY": "USA"
      }
    },
    {
      "topic": "purchases_pii_obfuscated",
      "value": {
        "ORDER_ID": 6,
        "CUSTOMER_NAME": "Xxxxxxx",
        "DATE_OF_BIRTH": "nn-nn-nnnn",
        "PRODUCT": "Running Beanie",
        "ORDER_TOTAL_USD": 13.73,
        "TOWN": "Omaha",
        "COUNTRY": "USA"
      }
    }
  ]
}

Invoke the tests

2

Lastly, invoke the tests using the test runner and the statements file that you created earlier:

docker exec ksqldb-cli ksql-test-runner -i /opt/app/test/input.json -s /opt/app/src/statements.sql -o /opt/app/test/output.json

Which should pass:

	 >>> Test passed!

Deploy on Confluent Cloud

Run your app with Confluent Cloud

1

Instead of running a local Kafka cluster, you may use Confluent Cloud, a fully managed Apache Kafka service.

  1. Sign up for Confluent Cloud, a fully managed Apache Kafka service.

  2. After you log in to Confluent Cloud Console, click Environments in the lefthand navigation, click on Add cloud environment, and name the environment learn-kafka. Using a new environment keeps your learning resources separate from your other Confluent Cloud resources.

  3. From the Billing & payment section in the menu, apply the promo code CC100KTS to receive an additional $100 free usage on Confluent Cloud (details). To avoid having to enter a credit card, add an additional promo code CONFLUENTDEV1. With this promo code, you will not have to enter a credit card for 30 days or until your credits run out.

  4. Click on LEARN and follow the instructions to launch a Kafka cluster and enable Schema Registry.

Confluent Cloud

Next, from the Confluent Cloud Console, click on Clients to get the cluster-specific configurations, e.g., Kafka cluster bootstrap servers and credentials, Confluent Cloud Schema Registry and credentials, etc., and set the appropriate parameters in your client application.

Now you’re all set to run your streaming application locally, backed by a Kafka cluster fully managed by Confluent Cloud.