Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions plugins/tee/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# TEE Plugin for GAME SDK

The TEE Plugin is a plugin designed to obtain an attestation report in a Trusted Execution Environment (TEE).

An attestation report is a document generated by a Trusted Execution Environment (TEE) that serves as cryptographic proof of the environment's integrity and trustworthiness. It is primarily used to assure external parties that:

- The TEE environment is secure: It proves that the execution environment is isolated from other processes and protected from unauthorized access or tampering.

- The code running inside the TEE is legitimate: It verifies that the code or application executed inside the TEE has not been altered and is authentic.

- The environment has not been compromised: It includes evidence that the hardware and software configurations are intact and match a known, trusted state.


## Installation
From this directory (`tee`), run the installation:
```bash
pip install -e .
```

## Usage
This TEE plugin currently supports retrieving attestation reports exclusively from [Google Confidential Space](https://cloud.google.com/docs/security/confidential-space). It is actively under development, and support for attestation reports from AMD SEV-SNP Confidential VMs will be released soon.

1. You should deploy the AI Agent on Google Confidential Space to safeguard sensitive information, such as wallet secrets.
2. Use this plugin to generate an attestation report for Google Confidential Space, demonstrating that the agent is enhanced by TEE and operating in a secure environment. The attestation report also includes the agent's Docker image to verify that it matches the expected configuration.
3. Import and initialize the plugin to use in your worker:
```python
from tee_plugin_gamesdk.tee_plugin import TeePlugin
options = {
"id": "test_tee_worker",
"name": "Test TEE Worker",
"description": "An example TEE Plugin for testing.",
"type": "GCS"
}
# Initialize the TeePlugin with your options
tee_plugin = TeePlugin(options)

# Generate Attestation report
get_attestation_report_fn = tee_plugin.get_function('get_attestation_report')
get_attestation_report_fn("Hello world!") # The input is a nonce releated to the report
```

You can refer to `test_tee.py` for more examples on how to call the twitter functions.
14 changes: 14 additions & 0 deletions plugins/tee/plugin_metadata.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# General Information
plugin_name: "tee_plugin_gamesdk"
author: "Will Jiang"
logo_url: "https://pbs.twimg.com/profile_images/1883754196991942657/BoC1g-Cj_400x400.jpg"
release_date: "2025-04"

# Description
short_description: "TEE (trusted execution environment) Plugin for GAME SDK"
detailed_description: "The TEE Plugin is a plugin designed to obtain an attestation report in a Trusted Execution Environment (TEE). An attestation report is a document generated by a Trusted Execution Environment (TEE) that serves as cryptographic proof of the environment's integrity and trustworthiness."

# Contact & Support
x_account_handle: "@aizel_network"
support_contact: "[email protected]"
community_link: "https://linktr.ee/AizelNetwork"
36 changes: 36 additions & 0 deletions plugins/tee/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "tee_plugin_gamesdk"
version = "0.1.0"
authors = [
{ name = "Will Jiang", email = "[email protected]" },
]
description = "TEE Plugin for Python SDK for GAME by Virtuals"
requires-python = ">=3.8"
classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Python Modules",
]
dependencies = [
"requests>=2.31.0",
"requests_unixsocket2>=0.4.2",
"pyjwt>=2.10"
]

[tool.hatch.build.targets.wheel]
packages = ["tee_plugin_gamesdk"]

[project.urls]
"Homepage" = "https://github.com/game-by-virtuals/game-python"
"Bug Tracker" = "https://github.com/game-by-virtuals/game-python"
93 changes: 93 additions & 0 deletions plugins/tee/tee_plugin_gamesdk/tee_plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import json
import requests_unixsocket
from requests import HTTPError
import hashlib
import jwt
import logging
from typing import Dict, Callable, Any, Optional, List, Callable

Audience = "http://aizel.com"

class CustomToken:
def __init__(self, audience, nonce, token_type="OIDC"):
self.audience = audience
self.nonces = [nonce]
self.token_type = token_type

class GcpConfidentialSpace:
def __init__(self, audience: str):
self.audience = audience

def attestation_report(self, nonce: str) -> str:
try:
hashed_nonce = hashlib.sha256(nonce.encode('utf-8')).hexdigest()
request = CustomToken(self.audience, hashed_nonce)
session = requests_unixsocket.Session()
url = 'http+unix://%2Frun%2Fcontainer_launcher%2Fteeserver.sock/v1/token'
headers = {'Content-Type': 'application/json'}
custom_json = json.dumps(request.__dict__)
response = session.post(url, headers=headers, data=custom_json)
response.raise_for_status()
return response.content.decode('utf-8')
except Exception as err:
raise RuntimeError(f"{err}")


class TeePlugin:
def __init__(self, options: Dict[str, Any]) -> None:
self.id: str = options.get("id", "tee_plugin")
self.name: str = options.get("name", "TEE Plugin")
self.description: str = options.get(
"description",
"A plugin that obtains the attestation report in the Trusted Execution Environment.",
)
# tee plugin type, current only support Google Confidential Space
self.type: str = options.get("tee_type", "GCS")

# Define internal function mappings
self._functions: Dict[str, Callable[..., Any]] = {
"get_attestation_report": self._get_attestation_report,
}

# Configure logging
logging.basicConfig(level=logging.INFO)
self.logger: logging.Logger = logging.getLogger(__name__)

def get_function(self, fn_name: str) -> Callable:
"""
Get a specific function by name.

Args:
fn_name: Name of the function to retrieve

Raises:
ValueError: If function name is not found

Returns:
Function object
"""
if fn_name not in self._functions:
raise ValueError(
f"Function '{fn_name}' not found. Available functions: {', '.join(self.available_functions)}"
)
return self._functions[fn_name]

def _get_attestation_report(self, nonce: str) -> str:
if self.type == "GCS":
try:
gcp = GcpConfidentialSpace(Audience)
gcp.attestation_report(nonce)
except RuntimeError as e:
self.logger.error(f"Failed to get attestation report for Google confidential space: {e}")
return ""
else:
raise ValueError(
f"Unsupport tee backend type '{self.type}'. Available type: GCS"
)

def decode_gcp_attestation_report(report: str) -> dict:
try:
decoded_report = jwt.decode(report, options={"verify_signature": False})
return decoded_report
except jwt.InvalidTokenError:
raise ValueError("Invalid token")
13 changes: 13 additions & 0 deletions plugins/tee/test_tee.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from tee_plugin_gamesdk.tee_plugin import TeePlugin
options = {
"id": "test_tee_worker",
"name": "Test TEE Worker",
"description": "An example TEE Plugin for testing.",
"type": "GCS"
}
# Initialize the TeePlugin with your options
tee_plugin = TeePlugin(options)

# Generate Attestation report
get_attestation_report_fn = tee_plugin.get_function('get_attestation_report')
get_attestation_report_fn("Hello world!")