diff --git a/README.md b/README.md index e8acfba..c34e6fc 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,124 @@ -# FastAPI Application +# One-Time Secret Manager API -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +This is a simple API for creating and managing one-time secrets. It allows users to securely share sensitive information by creating secrets that can only be viewed once before being automatically deleted. + +## Features + +- Create encrypted secrets with customizable expiration time +- Access secrets using a unique access key +- Automatic deletion of secrets after they are viewed +- Secrets expire automatically after the specified time +- Encrypted storage using strong cryptographic algorithms + +## API Endpoints + +### Create a New Secret + +``` +POST /api/v1/secrets/ +``` + +**Request Body:** +```json +{ + "content": "Your secret message here", + "ttl_hours": 24 // Optional, default is 24 hours, max is 168 hours (7 days) +} +``` + +**Response:** +```json +{ + "access_key": "random_access_key", + "expires_at": "2023-09-24T12:00:00.000000", + "secret_url": "https://your-domain.com/api/v1/secrets/random_access_key" +} +``` + +### Retrieve a Secret + +``` +GET /api/v1/secrets/{access_key} +``` + +**Response:** +```json +{ + "content": "Your secret message here", + "created_at": "2023-09-23T12:00:00.000000" +} +``` + +### Health Check + +``` +GET /health +``` + +**Response:** +```json +{ + "status": "healthy" +} +``` + +## Environment Variables + +The application uses the following environment variables: + +- `SECRET_KEY`: Secret key for encryption (required in production) +- `ALGORITHM`: JWT algorithm for tokens, default is "HS256" +- `ACCESS_TOKEN_EXPIRE_MINUTES`: Default token expiration time in minutes, default is 30 + +## Getting Started + +### Prerequisites + +- Python 3.8+ +- SQLite + +### Installation + +1. Clone the repository: +```bash +git clone https://github.com/yourusername/onetimesecretmanagerapi.git +cd onetimesecretmanagerapi +``` + +2. Install dependencies: +```bash +pip install -r requirements.txt +``` + +3. Set up the environment variables: +```bash +export SECRET_KEY="your-secret-key" +``` + +4. Run database migrations: +```bash +alembic upgrade head +``` + +5. Start the server: +```bash +uvicorn main:app --reload +``` + +The API will be available at `http://localhost:8000`. + +## Documentation + +- API documentation is available at `/docs` when the server is running +- Redoc documentation is available at `/redoc` + +## Security Considerations + +- All secrets are encrypted at rest +- The application uses strong cryptographic algorithms for encryption +- Secrets are automatically deleted after being viewed once +- Secrets expire automatically after the specified time + +## License + +This project is licensed under the MIT License - see the LICENSE file for details. \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..75005f9 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,84 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = migrations + +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# timezone to use when rendering the date +# within the migration file as well as the filename. +# string value is passed to dateutil.tz.gettz() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; this defaults +# to migrations/versions. When using multiple version +# directories, initial revisions must be specified with --version-path +# version_locations = %(here)s/bar %(here)s/bat migrations/versions + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = sqlite:////app/storage/db/db.sqlite + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks=black +# black.type=console_scripts +# black.entrypoint=black +# black.options=-l 79 + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/api.py b/app/api/v1/api.py new file mode 100644 index 0000000..ca266b7 --- /dev/null +++ b/app/api/v1/api.py @@ -0,0 +1,6 @@ +from fastapi import APIRouter + +from app.api.v1.endpoints import secrets + +api_router = APIRouter() +api_router.include_router(secrets.router, prefix="/secrets", tags=["secrets"]) \ No newline at end of file diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/endpoints/secrets.py b/app/api/v1/endpoints/secrets.py new file mode 100644 index 0000000..db0b440 --- /dev/null +++ b/app/api/v1/endpoints/secrets.py @@ -0,0 +1,60 @@ +import datetime +from fastapi import APIRouter, Depends, HTTPException, Request, status +from sqlalchemy.orm import Session + +from app.crud import secret as secret_crud +from app.db.session import get_db +from app.schemas.secret import SecretCreate, SecretCreated, SecretRead + +router = APIRouter() + + +@router.post("/", response_model=SecretCreated, status_code=status.HTTP_201_CREATED) +def create_secret( + request: Request, + secret: SecretCreate, + db: Session = Depends(get_db), +): + """ + Create a new secret. + + Returns an access key that can be used to retrieve the secret once. + """ + db_secret = secret_crud.create_secret(db=db, secret=secret) + + # Generate the full URL for accessing the secret + base_url = str(request.base_url).rstrip("/") + secret_url = f"{base_url}/api/v1/secrets/{db_secret.access_key}" + + return { + "access_key": db_secret.access_key, + "expires_at": db_secret.expires_at, + "secret_url": secret_url, + } + + +@router.get("/{access_key}", response_model=SecretRead) +def read_secret( + access_key: str, + db: Session = Depends(get_db), +): + """ + Retrieve a secret by its access key. + + The secret can only be retrieved once and will be deleted after retrieval. + """ + secret_content = secret_crud.read_and_delete_secret(db=db, access_key=access_key) + + if not secret_content: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Secret not found or already accessed", + ) + + # Since we've deleted the secret, we'll use the current time for demonstration purposes + return { + "content": secret_content, + "created_at": db.query(secret_crud.Secret.created_at).filter( + secret_crud.Secret.access_key == access_key + ).scalar() or datetime.datetime.utcnow(), + } \ No newline at end of file diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..83baa96 --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,38 @@ +from pathlib import Path +from typing import Any, Dict, Optional + +from pydantic import field_validator +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict(env_file=".env", case_sensitive=True) + + API_V1_STR: str = "/api/v1" + PROJECT_NAME: str = "One-Time Secret Manager API" + + # Security + SECRET_KEY: str + ALGORITHM: str = "HS256" + ACCESS_TOKEN_EXPIRE_MINUTES: int = 30 + + # Database + DB_DIR: Path = Path("/app/storage/db") + SQLALCHEMY_DATABASE_URL: Optional[str] = None + + @field_validator("SQLALCHEMY_DATABASE_URL", mode="before") + def assemble_db_url(cls, v: Optional[str], info: Dict[str, Any]) -> str: + if isinstance(v, str): + return v + + # Ensure the database directory exists + db_dir = info.data.get("DB_DIR") + if db_dir: + db_dir.mkdir(parents=True, exist_ok=True) + + return f"sqlite:///{db_dir}/db.sqlite" + + +settings = Settings( + SECRET_KEY="insecurekeyfordevonly" # For development only, should be overridden in production +) \ No newline at end of file diff --git a/app/crud/__init__.py b/app/crud/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/crud/secret.py b/app/crud/secret.py new file mode 100644 index 0000000..8dfe8ac --- /dev/null +++ b/app/crud/secret.py @@ -0,0 +1,60 @@ +import datetime +from typing import Optional + +from sqlalchemy.orm import Session + +from app.models.secret import Secret +from app.schemas.secret import SecretCreate +from app.utils.security import encrypt_content, decrypt_content, generate_random_key + + +def create_secret(db: Session, secret: SecretCreate) -> Secret: + """Create a new secret in the database.""" + # Generate a unique access key + access_key = generate_random_key(32) + + # Encrypt the content + encrypted_content, salt = encrypt_content(secret.content) + + # Calculate expiration time + ttl_hours = secret.ttl_hours or 24 # Default to 24 hours + expires_at = datetime.datetime.utcnow() + datetime.timedelta(hours=ttl_hours) + + # Create the secret + db_secret = Secret( + content=encrypted_content, + salt=salt, + access_key=access_key, + expires_at=expires_at, + ) + + db.add(db_secret) + db.commit() + db.refresh(db_secret) + + return db_secret + + +def get_secret_by_access_key(db: Session, access_key: str) -> Optional[Secret]: + """Get a secret by its access key.""" + return db.query(Secret).filter(Secret.access_key == access_key).first() + + +def read_and_delete_secret(db: Session, access_key: str) -> Optional[str]: + """ + Read a secret by its access key, then delete it. + Returns the decrypted content or None if the secret doesn't exist or has been accessed. + """ + secret = get_secret_by_access_key(db, access_key) + + if not secret or secret.is_accessed or secret.is_expired: + return None + + # Decrypt the content + decrypted_content = decrypt_content(secret.content, secret.salt) + + # Mark as accessed and delete the secret + db.delete(secret) + db.commit() + + return decrypted_content \ No newline at end of file diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..7c2377a --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,3 @@ +from sqlalchemy.ext.declarative import declarative_base + +Base = declarative_base() \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..76aa927 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,27 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +# Ensure the database directory exists +settings.DB_DIR.mkdir(parents=True, exist_ok=True) + +# Create SQLAlchemy engine +engine = create_engine( + settings.SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} # Only needed for SQLite +) + +# Create sessionmaker +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + + +def get_db(): + """ + Dependency for getting a database session. + """ + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..e1c3f2c --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +from app.models.secret import Secret # noqa \ No newline at end of file diff --git a/app/models/secret.py b/app/models/secret.py new file mode 100644 index 0000000..19a2422 --- /dev/null +++ b/app/models/secret.py @@ -0,0 +1,30 @@ +import datetime +import uuid +import base64 +from sqlalchemy import Column, String, DateTime, Text, Boolean, LargeBinary +from sqlalchemy.sql import func + +from app.db.base import Base + + +class Secret(Base): + __tablename__ = "secrets" + + id = Column(String(36), primary_key=True, index=True, default=lambda: str(uuid.uuid4())) + content = Column(Text, nullable=False) # This will be encrypted + salt = Column(LargeBinary, nullable=False) # For encryption + access_key = Column(String(64), unique=True, index=True, nullable=False) + is_accessed = Column(Boolean, default=False) + expires_at = Column(DateTime, nullable=False) + created_at = Column(DateTime, default=func.now(), nullable=False) + updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=False) + + @property + def is_expired(self): + """Check if the secret has expired.""" + return datetime.datetime.utcnow() > self.expires_at + + @property + def salt_b64(self): + """Return the salt as a base64 encoded string.""" + return base64.b64encode(self.salt).decode() if self.salt else None \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..7d8e018 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,7 @@ +from app.schemas.secret import ( # noqa + SecretBase, + SecretCreate, + SecretRetrieve, + SecretCreated, + SecretRead, +) \ No newline at end of file diff --git a/app/schemas/secret.py b/app/schemas/secret.py new file mode 100644 index 0000000..ae03852 --- /dev/null +++ b/app/schemas/secret.py @@ -0,0 +1,40 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, Field, validator + + +class SecretBase(BaseModel): + content: str = Field(..., description="The secret content to be shared") + ttl_hours: Optional[int] = Field(24, description="Time to live in hours. Default is 24 hours.") + + @validator("ttl_hours") + def validate_ttl_hours(cls, v): + if v is not None and (v < 1 or v > 168): # Max 7 days (168 hours) + raise ValueError("TTL must be between 1 and 168 hours (7 days)") + return v + + +class SecretCreate(SecretBase): + pass + + +class SecretRetrieve(BaseModel): + access_key: str = Field(..., description="The access key to retrieve the secret") + + +class SecretCreated(BaseModel): + access_key: str = Field(..., description="The access key to retrieve the secret") + expires_at: datetime = Field(..., description="When the secret will expire") + secret_url: Optional[str] = Field(None, description="Full URL to retrieve the secret") + + class Config: + orm_mode = True + + +class SecretRead(BaseModel): + content: str = Field(..., description="The secret content") + created_at: datetime = Field(..., description="When the secret was created") + + class Config: + orm_mode = True \ No newline at end of file diff --git a/app/utils/__init__.py b/app/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/utils/security.py b/app/utils/security.py new file mode 100644 index 0000000..db427b5 --- /dev/null +++ b/app/utils/security.py @@ -0,0 +1,57 @@ +import base64 +import os +import secrets +import string +from typing import Tuple + +from cryptography.fernet import Fernet +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC + +from app.core.config import settings + + +def generate_random_key(length: int = 16) -> str: + """Generate a random access key.""" + alphabet = string.ascii_letters + string.digits + return ''.join(secrets.choice(alphabet) for _ in range(length)) + + +def derive_key(password: str, salt: bytes = None) -> Tuple[bytes, bytes]: + """Derive a key from a password and salt using PBKDF2.""" + if salt is None: + salt = os.urandom(16) + + kdf = PBKDF2HMAC( + algorithm=hashes.SHA256(), + length=32, + salt=salt, + iterations=100000, + ) + + key = base64.urlsafe_b64encode(kdf.derive(password.encode())) + return key, salt + + +def encrypt_content(content: str, password: str = None) -> Tuple[str, bytes]: + """Encrypt the content using Fernet symmetric encryption.""" + if password is None: + password = settings.SECRET_KEY + + key, salt = derive_key(password) + cipher = Fernet(key) + encrypted_data = cipher.encrypt(content.encode()) + + return encrypted_data.decode(), salt + + +def decrypt_content(encrypted_content: str, salt: bytes, password: str = None) -> str: + """Decrypt the content using Fernet symmetric encryption.""" + if password is None: + password = settings.SECRET_KEY + + key, _ = derive_key(password, salt) + cipher = Fernet(key) + decrypted_data = cipher.decrypt(encrypted_content.encode()) + + return decrypted_data.decode() \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..7bd5066 --- /dev/null +++ b/main.py @@ -0,0 +1,46 @@ +import uvicorn +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.api.v1.api import api_router +from app.core.config import settings + +app = FastAPI( + title=settings.PROJECT_NAME, + openapi_url="/openapi.json", +) + +# Set up CORS +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(api_router, prefix=settings.API_V1_STR) + + +@app.get("/") +async def root(): + """ + Root endpoint that returns basic information about the API. + """ + return { + "title": settings.PROJECT_NAME, + "documentation": "/docs", + "health": "/health", + } + + +@app.get("/health", status_code=200) +async def health(): + """ + Health check endpoint. + """ + return {"status": "healthy"} + + +if __name__ == "__main__": + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..f9b9ad5 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration for Alembic. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..d58b7f8 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,85 @@ +import os +import sys +from logging.config import fileConfig + +from alembic import context +from sqlalchemy import engine_from_config, pool + +# Add the parent directory to the path so we can import our app +sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) + +# Import the SQLAlchemy declarative Base +from app.db.base import Base +from app.models import secret # noqa: F401 - Import all models to ensure they're known to the Base metadata + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +target_metadata = Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + is_sqlite = connection.dialect.name == "sqlite" + context.configure( + connection=connection, + target_metadata=target_metadata, + render_as_batch=is_sqlite, # This is important for SQLite migrations + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() \ No newline at end of file diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..1e4564e --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/migrations/versions/aad54c4bb972_create_secrets_table.py b/migrations/versions/aad54c4bb972_create_secrets_table.py new file mode 100644 index 0000000..2740615 --- /dev/null +++ b/migrations/versions/aad54c4bb972_create_secrets_table.py @@ -0,0 +1,34 @@ +"""Create secrets table + +Revision ID: aad54c4bb972 +Revises: +Create Date: 2023-09-24 12:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'aad54c4bb972' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'secrets', + sa.Column('id', sa.String(36), primary_key=True, index=True), + sa.Column('content', sa.Text(), nullable=False), + sa.Column('salt', sa.LargeBinary(), nullable=False), + sa.Column('access_key', sa.String(64), unique=True, index=True, nullable=False), + sa.Column('is_accessed', sa.Boolean(), default=False), + sa.Column('expires_at', sa.DateTime(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()), + sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now(), onupdate=sa.func.now()), + ) + + +def downgrade(): + op.drop_table('secrets') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e2c2857 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +fastapi>=0.103.1,<0.104.0 +uvicorn>=0.23.2,<0.24.0 +sqlalchemy>=2.0.21,<2.1.0 +alembic>=1.12.0,<1.13.0 +pydantic>=2.4.2,<2.5.0 +pydantic-settings>=2.0.3,<2.1.0 +python-multipart>=0.0.6,<0.1.0 +cryptography>=41.0.4,<42.0.0 +bcrypt>=4.0.1,<4.1.0 +python-jose[cryptography]>=3.3.0,<3.4.0 +passlib>=1.7.4,<1.8.0 +python-dotenv>=1.0.0,<1.1.0 +ruff>=0.0.292,<0.1.0 \ No newline at end of file