Docs Menu
Docs Home
/ /

チュートリアル: Diango MongoDBバックエンドを使用したQueryable Encryption

このチュートリアルでは、 DlangoアプリケーションでQueryable Encryption (QE) を使用する方法を学習できます。

MongoDB のQueryable Encryption機能は、アプリケーションが暗号化されたデータをやり取りできるようにしながら、機密データを自動的に暗号化して保護するのに役立ちます。このチュートリアルでは、アプリケーション設定で暗号化を有効にし、暗号化するモデル フィールドを選択することで、Diango MongoDBバックエンドでQueryable Encryption を使用する方法を学習できます。

このチュートリアルを開始する前に、次の前提条件タスクを完了してください。

  • MongoDB Atlasアカウントを作成し、クラスターを構成します。クラスターがMongoDB Serverバージョン7.0 以降で実行されていることを確認します。詳しくは、 MongoDB の使用開始ガイドをご覧ください。

  • 自動暗号化共有ライブラリをダウンロードします。手順を表示するには、「 クエリ分析コンポーネントのインストールと構成 」ガイドを参照してください。次の手順では、 MongoDBダウンロード センター に移動し、ライブラリをダウンロードするために必要なフォームに入力する方法を示します。

  • Python3.10 以降をインストールします。

このチュートリアルでは、Dpango MongoDBバックエンドを使用するQueryable Encryptionアプリケーションを作成します。このアプリケーションは医療レコードを安全に処理し、機密性の高い医療情報を暗号化、復号化、クエリを実行します。

Tip

完全なアプリケーション

このチュートリアルの完全なサンプルアプリケーションを表示するには、GitHub の diango_qe フォルダーを参照してください。

このセクションの手順に従って、プロジェクトの依存関係のインストール、環境を構成し、アプリケーション構造を作成します。

1

オペレーティング システムに対応するタブを選択し、次のコマンドを実行して仮想環境をアクティブ化し、Diango MongoDBバックエンドをインストールして、 Queryable Encryption の依存関係をインストールします。

python -m venv venv
source venv/bin/activate
pip install 'django-mongodb-backend[encryption]'
python -m venv venv
. venv\Scripts\activate
pip install 'django-mongodb-backend[encryption]'

pip install 'django-mongodb-backend[encryption]' コマンドは、Diango MongoDBバックエンド、最新のPyMongoバージョン、および必要なPython依存関係をインストールします。

注意

v6.0.1 で利用可能

Queryable Encryptionには Dpango MongoDBバックエンド v6.0.1 以降が必要です。上記のコマンドは、必要なバージョンをインストールします。

2

シェルから次のコマンドを実行し、カスタム テンプレートに基づいて django_qe という新しい Diangoプロジェクトを作成します。

django-admin startproject django_qe --template https://github.com/mongodb-labs/django-mongodb-project/archive/refs/heads/6.0.x.zip

このコマンドは、django_qeプロジェクトディレクトリを作成し、初期ファイルスキャフォールディングを追加します。

3

django_qeディレクトリから、次のコマンドを実行して medical_records というアプリケーションを作成します。

python manage.py startapp medical_records

このコマンドは、プロジェクトに medical_recordsアプリケーションディレクトリを作成し、モデルや設定のファイルを含むデフォルトのアプリファイルを追加します。

4

django_qeディレクトリ内の settings.pyファイルに移動し、INSTALLED_APPS の設定を次のコードのように編集します。

INSTALLED_APPS = [
'medical_records.apps.MedicalRecordsConfig',
'django_qe.apps.MongoAdminConfig',
'django_qe.apps.MongoAuthConfig',
'django_qe.apps.MongoContentTypesConfig',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_mongodb_backend',
]

この設定により、プロジェクトで medical_recordsアプリが有効になるようにします。

プロジェクトを設定した 後、このセクションの手順に従ってMongoDBに接続し、暗号化されたデータを保存するモデルを作成します。

1

django_qeディレクトリで、settings.pyファイルに移動します。 DATABASES の設定を次のコードで置き換えます。

DATABASES = {
'default': {
'ENGINE': 'django_mongodb_backend',
'HOST': '<connection string>',
'NAME': 'db',
},
}

<connection string> プレースホルダーを、クラスターに接続する接続文字列に置き換えます。

このコードはMongoDBに接続し、デフォルトで という名前のデータベースにアクセスするようにdb Diangoアプリケーションを構成します。この構成は、暗号化されていないモデルに適用されます。

2

settings.pyファイルでは、DATABASES 設定で encrypted キーを指定して、 Queryable Encryptionを有効にし、キー管理システム(KMS)プロバイダーを設定できます。 Dlango MongoDBバックエンドは、 AWS、 Azure、 GCP、 KMIP 、およびローカル KMS プロバイダーをサポートしています。

警告

ローカル CMK ストレージ

CMK(Customer Master Key)をローカルに保存する場合は、このアプリケーションを本番環境では使用しないでください。リモート KMS を使用しないと、暗号化のキーへの不正アクセスや、データの復号に必要なキーが失われるリスクがあります。

Tip

キー管理システム

KMS に対応するタブを選択し、DATABASES の設定を次の例のように変更します。

DATABASES = {
'default': {
# ... Your default configuration
},
'encrypted': {
'ENGINE': 'django_mongodb_backend',
'HOST': '<connection string>',
'NAME': 'medical_records',
# ...
'OPTIONS': {
'auto_encryption_opts': AutoEncryptionOpts(
key_vault_namespace='medical_records.__keyVault',
kms_providers={
'local': {
# Generated by os.urandom(96)
'key': (
b'-\xc3\x0c\xe3\x93\xc3\x8b\xc0\xf8\x12\xc5#b'
b'\x19\xf3\xbc\xccR\xc8\xedI\xda\\ \xfb\x9cB'
b'\x7f\xab5\xe7\xb5\xc9x\xb8\xd4d\xba\xdc\x9c'
b'\x9a\xdb9J]\xe6\xce\x104p\x079q.=\xeb\x9dK*'
b'\x97\xea\xf8\x1e\xc3\xd49K\x18\x81\xc3\x1a"'
b'\xdc\x00U\xc4u"X\xe7xy\xa5\xb2\x0e\xbc\xd6+-'
b'\x80\x03\xef\xc2\xc4\x9bU'
)
},
},
crypt_shared_lib_path='<Automatic Encryption Shared Library path>',
crypt_shared_lib_required=True,
)
},
},
}

以下のプレースホルダー値を置き換えます。

  • <connection string>: default キーで指定したのと同じ接続文字列

  • <Automatic Encryption Shared Library path>: 自動暗号化共有ライブラリへのフルパス

DATABASES = {
'default': {
# ... Your default configuration
},
'encrypted': {
'ENGINE': 'django_mongodb_backend',
'HOST': '<connection string>',
'NAME': 'medical_records',
# ...
'OPTIONS': {
'auto_encryption_opts': AutoEncryptionOpts(
key_vault_namespace='medical_records.__keyVault',
kms_providers={
'aws': {
'accessKeyId': '<AWS Access Key ID>',
'secretAccessKey': '<AWS Secret Access Key>',
},
},
crypt_shared_lib_path='<Automatic Encryption Shared Library path>',
crypt_shared_lib_required=True,
)
},
'KMS_CREDENTIALS': {
'aws': {
'key': '<AWS Key ARN>',
'region': '<AWS Key Region>',
},
},
},
}

以下のプレースホルダー値を置き換えます。

  • <connection string>: default キーで指定したのと同じ接続文字列

  • <AWS Access Key ID>: Amazon Web ServicesアクセスキーID

  • <AWS Secret Access Key>: Amazon Web Servicesシークレット アクセスキー

  • <Automatic Encryption Shared Library path>: 自動暗号化共有ライブラリへのフルパス

  • <AWS Key ARN>: AWSカスタマーへのAmazonリソース名 。

  • <AWS Key Region>: AWSリージョン(例: 'us-east-1'

DATABASES = {
'default': {
# ... Your default configuration
},
'encrypted': {
'ENGINE': 'django_mongodb_backend',
'HOST': '<connection string>',
'NAME': 'medical_records',
# ...
'OPTIONS': {
'auto_encryption_opts': AutoEncryptionOpts(
key_vault_namespace='medical_records.__keyVault',
kms_providers={
'azure': {
'tenantId': '<Azure Tenant ID>',
'clientId': '<Azure Client ID>',
'clientSecret': '<Azure Client Secret>',
},
},
crypt_shared_lib_path='<Automatic Encryption Shared Library path>',
crypt_shared_lib_required=True,
)
},
'KMS_CREDENTIALS': {
'azure': {
'keyVaultEndpoint': '<Azure Key Vault Endpoint>',
'keyName': '<Azure Key Name>',
# Optional: 'keyVersion': '<Azure Key Version>',
},
},
},
}

以下のプレースホルダー値を置き換えます。

  • <connection string>: default キーで指定したのと同じ接続文字列

  • <Azure Tenant ID>: Azure Active Directory テナントID

  • <Azure Client ID>: AzureアプリケーションクライアントID

  • <Azure Client Secret>: Azureアプリケーションクライアントシークレット

  • <Automatic Encryption Shared Library path>: 自動暗号化共有ライブラリへのフルパス

  • <Azure Key Vault Endpoint>: Azure Key Vault エンドポイントURL。

  • <Azure Key Name>: Azure Key Vault でのキーの名前

  • <Azure Key Version>:(任意)使用するキーのバージョン

DATABASES = {
'default': {
# ... Your default configuration
},
'encrypted': {
'ENGINE': 'django_mongodb_backend',
'HOST': '<connection string>',
'NAME': 'medical_records',
# ...
'OPTIONS': {
'auto_encryption_opts': AutoEncryptionOpts(
key_vault_namespace='medical_records.__keyVault',
kms_providers={
'gcp': {
'email': '<GCP Service Account Email>',
'privateKey': '<GCP Service Account Private Key>',
},
},
crypt_shared_lib_path='<Automatic Encryption Shared Library path>',
crypt_shared_lib_required=True,
)
},
'KMS_CREDENTIALS': {
'gcp': {
'projectId': '<GCP Project ID>',
'location': '<GCP Key Ring Location>',
'keyRing': '<GCP Key Ring Name>',
'keyName': '<GCP Key Name>',
},
},
},
}

以下のプレースホルダー値を置き換えます。

  • <connection string>: default キーで指定したのと同じ接続文字列

  • <GCP Service Account Email>: Google Cloud サービス アカウントのメール

  • <GCP Service Account Private Key>: Google Cloud サービス アカウントの秘密キー

  • <Automatic Encryption Shared Library path>: 自動暗号化共有ライブラリへのフルパス

  • <GCP Project ID>: Google CloudプロジェクトID

  • <GCP Key Ring Location>: キー リングのロケーション(例: 'global'

  • <GCP Key Ring Name>: キー リングの名前

  • <GCP Key Name>: キーの名前

DATABASES = {
'default': {
# ... Your default configuration
},
'encrypted': {
'ENGINE': 'django_mongodb_backend',
'HOST': '<connection string>',
'NAME': 'medical_records',
# ...
'OPTIONS': {
'auto_encryption_opts': AutoEncryptionOpts(
key_vault_namespace='medical_records.__keyVault',
kms_providers={
'kmip': {
'endpoint': '<KMIP Server Endpoint>',
},
},
crypt_shared_lib_path='<Automatic Encryption Shared Library path>',
crypt_shared_lib_required=True,
)
},
'KMS_CREDENTIALS': {
'kmip': {
# Optional: 'keyId': '<KMIP Key Identifier>',
},
},
},
}

以下のプレースホルダー値を置き換えます。

  • <connection string>: default キーで指定したのと同じ接続文字列。

  • <KMIP Server Endpoint>: ポートを持つ KMIPサーバーのエンドポイント('example.com:443' など)。

  • <Automatic Encryption Shared Library path>: 自動暗号化共有ライブラリへのフルパス。

  • <KMIP Key Identifier>: (任意)96 バイトの KMIP 秘密データ管理オブジェクトへの KMIP ユニーク識別子 。この値を省略すると、Diango MongoDBバックエンドはランダムな 96 バイトのオブジェクトを作成します。

このコードは、暗号化された medical_recordsデータベースに接続し、 データキーを medical_records.__keyVaultコレクションに保存し、 KMS プロバイダーを構成します。

3

medical_recordsディレクトリに、routers.py という名前のファイルを作成し、次のコードをそのファイルに貼り付けます。

class EncryptedRouter:
def allow_migrate(self, db, app_label, model_name=None, **hints):
# Create medical_records models only in the encrypted database.
if app_label == "medical_records":
return db == "encrypted"
# Don't create collections for other apps in the encrypted db.
if db == "encrypted":
return False
return None
def db_for_read(self, model, **hints):
# All reads and writes for medical_records models go to the encrypted db.
if model._meta.app_label == "medical_records":
return "encrypted"
return None
db_for_write = db_for_read

このファイルは、medical_recordsアプリケーション内のすべてのモデルのデータベース操作を暗号化された medical_recordsデータベースにルーティングします。

次に、settings.pyファイルに移動し、DATABASE_ROUTERS の設定を次のコードで置き換えて、カスタム ルーターを追加します。

DATABASE_ROUTERS = [
'django_mongodb_backend.routers.MongoRouter',
'medical_records.routers.EncryptedRouter',
]
4

medical_recordsディレクトリで、models.pyファイルに移動し、次のコードを貼り付けます。

from django.db import models
from django_mongodb_backend.models import EmbeddedModel
from django_mongodb_backend.fields import (
EmbeddedModelField,
EncryptedCharField,
EncryptedEmbeddedModelField,
)
class Patient(models.Model):
patient_name = models.CharField(max_length=255)
patient_id = models.BigIntegerField()
patient_record = EmbeddedModelField("PatientRecord")
class Meta:
db_table = "patients"
def __str__(self):
return f"{self.patient_name} ({self.patient_id})"
class PatientRecord(EmbeddedModel):
ssn = EncryptedCharField(max_length=11, queries={"queryType": "equality"})
billing = EncryptedEmbeddedModelField("Billing")
bill_amount = models.DecimalField(max_digits=10, decimal_places=2)
class Billing(EmbeddedModel):
cc_type = models.CharField(max_length=50)
cc_number = models.CharField(max_length=20)

このコードでは、medical_recordsデータベース内の patientsコレクションに対応する Patient モデルが作成されます。また、コレクション内のネストされたフィールドを表すために、PatientRecordBilling の 2 つの埋め込みモデルも作成します。

このコードでは、次の暗号化されたフィールドが構成されます。

  • patient_record.ssn: 暗号化と等価クエリ用の構成

  • patient_record.billing.cc_type: 暗号化されていますが、クエリはできません

  • patient_record.billing.cc_number: 暗号化されていますが、クエリはできません

アプリケーションとデータベースの接続を構成したら、このセクションの手順に従って暗号化されたドキュメントの挿入とクエリを行います。

1

django_qeディレクトリから次のコマンドを実行してモデルの移行を作成し、データベースに適用します。

python manage.py makemigrations medical_records
python manage.py migrate --database encrypted
2

次のコマンドを実行して、 Python シェルを入力します。

python manage.py shell

次に、 シェルで次のコマンドを実行して、必要なモデルをインポートします。

from medical_records.models import Patient, PatientRecord, Billing
3

シェルから次のコマンドを実行して Patientインスタンスを作成し、対応する暗号化されたドキュメントをデータベースに挿入します。

billing = Billing(cc_type="Visa", cc_number="4111111111111111")
record = PatientRecord(ssn="987-65-4320", billing=billing, bill_amount=1500)
patient = Patient.objects.create(
name="John Doe",
patient_id=12345678,
patient_record=record
)

MongoDB Atlasのmedical_records.patients コレクションに移動すると、ドキュメントの フィールドとpatient_record.ssn patient_record.billingフィールドが暗号化されていることが確認できます。

4

次のコマンドを実行して、暗号化された patient_record.ssnフィールドに対して等価クエリを実行します。

Patient.objects.get(patient_record__ssn="987-65-4320")

成功した場合、コマンドは次の検査データを返します。

<Patient: John Doe (12345678)>

Queryable Encryption のチュートリアルが完了しました。これで、 Queryable Encryptionを使用してドキュメントフィールドを自動的に暗号化および復号化するサンプルDiangoアプリケーションができました。アプリケーションはサーバー側で機密データを暗号化し、クライアント側でデータをクエリします。

Queryable Encryptionと Diango MongoDBバックエンドの詳細については、次のリソースを参照してください。

  • MongoDB Serverマニュアルで、ドライバーQueryable Encryption のチュートリアルをさらに見る

  • APIドキュメントの「Diango MongoDBバックエンドによるQueryable Encryptionの詳細」

戻る

トランザクション

項目一覧