Period Spoofing software by Luminosity-e

Nov 11, 2024 16:55

# Import necessary libraries
import requests
import json
import datetime
import os
import random
from dotenv import load_dotenv
import base64
import shutil

# Load environment variables
load_dotenv()

# Terra API Configuration
TERRA_API_KEY = os.getenv("TERRA_API_KEY")
TERRA_BASE_URL = "https://api.tryterra.co/v2"

# GitHub Integration - Personal Access Token for Repository Access
GITHUB_ACCESS_TOKEN = os.getenv("GITHUB_ACCESS_TOKEN")
GITHUB_REPO_NAME = "user/period-tracker-integration"

# Emergency Deletion Directory
EMERGENCY_DELETION_DIR = "emergency_backup"

# Helper Function: Get authorization headers for API requests
def get_auth_headers(api_key):
return {
'accept': 'application/json',
'Authorization': f'Bearer {api_key}'
}

# Function to get menstrual data from Terra API
def get_menstrual_data(user_id):
headers = get_auth_headers(TERRA_API_KEY)
endpoint = f"{TERRA_BASE_URL}/menstrual?user_id={user_id}"
try:
response = requests.get(endpoint, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error fetching data for user {user_id}: {e}")
return None

# Function to update a repository on GitHub
def update_github_repo(file_name, file_content, commit_message):
url = f"https://api.github.com/repos/{GITHUB_REPO_NAME}/contents/{file_name}"
headers = {
'Authorization': f'token {GITHUB_ACCESS_TOKEN}',
'Accept': 'application/vnd.github.v3+json'
}
# Fetch the current file SHA to allow for update
try:
response = requests.get(url, headers=headers)
sha = None
if response.status_code == 200:
sha = response.json()['sha']
elif response.status_code != 404:
response.raise_for_status()

data = {
"message": commit_message,
"content": file_content,
"sha": sha
}
response = requests.put(url, headers=headers, data=json.dumps(data))
response.raise_for_status()
print(f"Successfully updated GitHub repository for file: {file_name}")
except requests.exceptions.RequestException as e:
print(f"Error updating GitHub repository: {e}")

# Function to encode content to base64 (needed by GitHub API)
def encode_content_to_base64(content):
return base64.b64encode(content.encode("utf-8")).decode("utf-8")

# Function to create an emergency backup of the data
def create_emergency_backup(file_name, file_content):
if not os.path.exists(EMERGENCY_DELETION_DIR):
os.makedirs(EMERGENCY_DELETION_DIR)
backup_path = os.path.join(EMERGENCY_DELETION_DIR, file_name)
with open(backup_path, 'w') as backup_file:
backup_file.write(file_content)
print(f"Emergency backup created for file: {file_name}")

# Function to trigger emergency data deletion
def emergency_delete():
if os.path.exists(EMERGENCY_DELETION_DIR):
shutil.rmtree(EMERGENCY_DELETION_DIR)
print("Emergency deletion triggered. All backup data has been deleted.")
else:
print("No backup data found to delete.")

# Function to obfuscate menstrual data
def obfuscate_menstrual_data(data):
obfuscated_data = data.copy()
# Introduce plausible false data for obfuscation
obfuscated_data['cycle_length'] = random.randint(25, 35) # Randomize cycle length within typical range
obfuscated_data['period_length'] = random.randint(3, 7) # Randomize period length within typical range
obfuscated_data['symptoms'] = random.sample(['cramps', 'headache', 'nausea', 'fatigue', 'mood_swings'], k=random.randint(1, 3))
return obfuscated_data

# Main Function
if __name__ == "__main__":
# Generate a list of 10,000 random user IDs for testing
user_ids = [f"user_{i}" for i in range(1, 10001)]
random.shuffle(user_ids)

for user_id in user_ids:
# Get menstrual data for a user
menstrual_data = get_menstrual_data(user_id)

if menstrual_data:
# Obfuscate menstrual data for additional privacy
menstrual_data = obfuscate_menstrual_data(menstrual_data)

# Process menstrual data and prepare for GitHub update
today = datetime.date.today().strftime("%Y-%m-%d")
file_name = f"menstrual_data/{user_id}_{today}.json" # Organize files in a directory for better management
file_content = json.dumps(menstrual_data, indent=4)
base64_content = encode_content_to_base64(file_content)
commit_message = f"Updated menstrual data for {user_id} on {today}"

# Create an emergency backup of the data
create_emergency_backup(file_name, file_content)

# Update the data to GitHub repository
update_github_repo(file_name, base64_content, commit_message)
else:
print(f"No data retrieved for user {user_id}.")

# Example trigger for emergency deletion (could be tied to a specific user action)
# emergency_delete()

# Period Tracker Integration Documentation

## Overview
This software integrates with the Terra API to fetch menstrual data for users and then updates this data to a GitHub repository. The software includes privacy features such as emergency data deletion and data obfuscation to ensure user safety and minimize technical debt.

## Features
1. **Data Retrieval**: Retrieves menstrual data from the Terra API for thousands of users.
2. **Data Obfuscation**: Introduces plausible false data to obfuscate sensitive information.
3. **GitHub Integration**: Stores menstrual data in a GitHub repository to ensure data can be tracked and shared securely.
4. **Emergency Backup**: Creates emergency backups of the data to a local directory for added data security.
5. **Emergency Deletion**: Provides an emergency data deletion feature to remove all local backups in the event of a data security threat.

## Configuration
The software relies on environment variables for sensitive information such as API keys. The following environment variables need to be set:
- `TERRA_API_KEY`: The API key for accessing Terra API.
- `GITHUB_ACCESS_TOKEN`: The GitHub personal access token for repository access.

Use a `.env` file to store these variables securely and load them using `dotenv`.

## Dependencies
The software uses the following Python libraries:
- `requests`: For making HTTP requests to Terra API and GitHub.
- `json`: For handling JSON data.
- `datetime`: For managing and formatting dates.
- `os`: For environment variable access and file operations.
- `random`: For random number generation used in obfuscation.
- `dotenv`: For loading environment variables.
- `base64`: For encoding data in base64 format.
- `shutil`: For file and directory operations (used in emergency deletion).

Install dependencies using the following command:
```sh
pip install requests python-dotenv
```

## Functions
### 1. `get_auth_headers(api_key)`
Returns authorization headers for API requests.
- **Parameters**: `api_key` (string) - The API key for authorization.
- **Returns**: Dictionary containing headers.

### 2. `get_menstrual_data(user_id)`
Fetches menstrual data for a specific user from the Terra API.
- **Parameters**: `user_id` (string) - The unique identifier for the user.
- **Returns**: JSON object with menstrual data or `None` if an error occurs.

### 3. `update_github_repo(file_name, file_content, commit_message)`
Updates a file in the specified GitHub repository.
- **Parameters**:
- `file_name` (string) - The name of the file to update.
- `file_content` (string) - The content to be added to the file, encoded in base64.
- `commit_message` (string) - The commit message for the GitHub update.
- **Returns**: None. Prints success or error messages.

### 4. `encode_content_to_base64(content)`
Encodes content in base64 format (required by GitHub API).
- **Parameters**: `content` (string) - The content to encode.
- **Returns**: Base64-encoded string.

### 5. `create_emergency_backup(file_name, file_content)`
Creates an emergency backup of the menstrual data in a local directory.
- **Parameters**:
- `file_name` (string) - The name of the backup file.
- `file_content` (string) - The content to store in the backup.
- **Returns**: None. Prints confirmation of backup creation.

### 6. `emergency_delete()`
Deletes all emergency backup data to ensure privacy.
- **Parameters**: None.
- **Returns**: None. Prints confirmation of deletion.

### 7. `obfuscate_menstrual_data(data)`
Obfuscates menstrual data to add privacy and mitigate potential misuse.
- **Parameters**: `data` (dict) - The menstrual data to obfuscate.
- **Returns**: A modified version of the menstrual data with plausible false values.

## Main Function Workflow
1. **User ID Generation**: Generates a list of 10,000 random user IDs.
2. **Data Retrieval and Obfuscation**:
- For each user, retrieve menstrual data from the Terra API.
- Obfuscate the menstrual data to enhance privacy.
3. **GitHub Update**:
- Format the data and create a base64-encoded JSON file.
- Create an emergency backup of the data.
- Update the GitHub repository with the obfuscated data.
4. **Emergency Deletion**: Optionally trigger emergency deletion of all backup data.

## File Structure
- **`main.py`**: Contains the main script logic.
- **`emergency_backup/`**: Directory where emergency backups are stored.

## Usage
Run the script using Python:
```sh
python main.py
```
This will process menstrual data for 10,000 users, obfuscate the data for privacy, create local backups, and upload it to a GitHub repository.

To trigger an emergency deletion of all backup data, you can call the `emergency_delete()` function. This can be tied to a specific user action if needed.

## Security Considerations
- **Sensitive Data**: Ensure that `TERRA_API_KEY` and `GITHUB_ACCESS_TOKEN` are stored securely and not hardcoded.
- **Data Obfuscation**: The obfuscation mechanism reduces the risk of data misuse if unauthorized access occurs.
- **Emergency Deletion**: Provides a quick mechanism to delete all backups, ensuring that no sensitive data remains if there is a potential breach.

## Future Improvements
- **User Consent Management**: Implement a consent management system to allow users to decide how their data is used.
- **Advanced Encryption**: Encrypt backups to further enhance the security of the stored data.
- **Federated Learning**: Allow users to contribute to improving predictions without sharing raw data, ensuring complete privacy.

## Conclusion
This software aims to protect user privacy while providing valuable tracking features. With the emergency deletion and data obfuscation, users are given direct control over their data, reducing risks associated with tracking sensitive health information.

For any questions or contributions, please refer to the GitHub repository or contact the development team.
Previous post Next post
Up