24 KiB
24 KiB
Subtask: Access Control System
Parent Task: Decomp/005 Subtask ID: Decomp-005-05 Dependencies: Decomp-005-01 (Storage Architecture)
Description
Implement access control system for buckets and objects. Support ACLs (Access Control Lists), presigned URLs with limited permissions, bucket policies, and authentication/authorization.
Requirements
- Bucket-level access control
- Object-level ACLs
- Permission types: read, write, delete, list
- User and group-based grants
- Public access support
- Presigned URL authentication
- Policy validation and enforcement
- Access logging
Technical Specifications
Permission definitions:
from enum import Enum
from typing import List, Dict, Any, Optional, Set
from dataclasses import dataclass
from datetime import datetime, timezone
import logging
logger = logging.getLogger(__name__)
class Permission(Enum):
"""Permission types."""
READ = "read"
WRITE = "write"
DELETE = "delete"
LIST = "list"
READ_ACL = "read_acl" # Read ACL permissions
WRITE_ACL = "write_acl" # Write ACL permissions
FULL_CONTROL = "full_control"
class GranteeType(Enum):
"""Types of grantees."""
USER = "user" # Specific user ID
GROUP = "group" # User group
ALL = "all" # Public (everyone)
AUTHENTICATED = "authenticated" # Any authenticated user
@dataclass
class Grant:
"""An access control grant."""
grantee_type: GranteeType
grantee_id: Optional[str] # None for ALL/AUTHENTICATED
permission: Permission
resource_type: str # 'bucket' or 'object'
resource_id: int
@dataclass
class AccessPolicy:
"""Access policy for a resource."""
resource_type: str
resource_id: int
owner_id: str
public_read: bool = False
grants: List[Grant] = None
def __post_init__(self):
if self.grants is None:
self.grants = []
Access control service:
class AccessControlService:
"""Service for managing access control."""
def __init__(self, db):
self.db = db
async def check_permission(
self,
user_id: str,
resource_type: str,
resource_id: int,
required_permission: Permission
) -> bool:
"""
Check if user has permission on a resource.
Args:
user_id: User ID (or None for anonymous)
resource_type: 'bucket' or 'object'
resource_id: Bucket or object ID
required_permission: Permission being checked
Returns:
True if user has permission
"""
# Get resource owner
async with self.db.acquire() as conn:
if resource_type == "bucket":
owner = await conn.fetchval(
"SELECT owner_id FROM buckets WHERE id = $1",
resource_id
)
else:
owner = await conn.fetchval(
"""SELECT b.owner_id
FROM objects o
JOIN buckets b ON b.id = o.bucket_id
WHERE o.id = $1""",
resource_id
)
# Owner has full control
if owner and user_id == owner:
return True
# Check public access first
if await self._has_public_access(conn, resource_type, resource_id, required_permission):
return True
# No user = only check public access
if not user_id:
return False
# Check user's direct grants
if await self._check_grant(conn, user_id, resource_type, resource_id, required_permission):
return True
# Check group memberships
if await self._check_group_grants(conn, user_id, resource_type, resource_id, required_permission):
return True
# Check bucket policy for objects
if resource_type == "object":
bucket_id = await conn.fetchval(
"SELECT bucket_id FROM objects WHERE id = $1",
resource_id
)
if bucket_id and await self._check_bucket_policy(conn, bucket_id, required_permission):
return True
return False
async def _has_public_access(
self,
conn,
resource_type: str,
resource_id: int,
permission: Permission
) -> bool:
"""Check if resource allows public access."""
# Check for public grants
public_grants = await conn.fetchval(
"""SELECT EXISTS(
SELECT 1 FROM acls
WHERE resource_type = $1
AND resource_id = $2
AND grantee_type = 'all'
AND permission = $3
)""",
resource_type, resource_id, permission.value
)
return public_grants
async def _check_grant(
self,
conn,
user_id: str,
resource_type: str,
resource_id: int,
required_permission: Permission
) -> bool:
"""Check direct user grants."""
# Check for FULL_CONTROL first
has_full_control = await conn.fetchval(
"""SELECT EXISTS(
SELECT 1 FROM acls
WHERE resource_type = $1
AND resource_id = $2
AND grantee_type = 'user'
AND grantee_id = $3
AND permission = 'full_control'
)""",
resource_type, resource_id, user_id
)
if has_full_control:
return True
# Check for specific permission
has_permission = await conn.fetchval(
"""SELECT EXISTS(
SELECT 1 FROM acls
WHERE resource_type = $1
AND resource_id = $2
AND grantee_type = 'user'
AND grantee_id = $3
AND permission = $4
)""",
resource_type, resource_id, user_id, required_permission.value
)
return has_permission
async def _check_group_grants(
self,
conn,
user_id: str,
resource_type: str,
resource_id: int,
required_permission: Permission
) -> bool:
"""Check group-based grants."""
# Get user's groups
user_groups = await conn.fetch(
"SELECT group_id FROM user_group_members WHERE user_id = $1",
user_id
)
if not user_groups:
return False
group_ids = [g["group_id"] for g in user_groups]
# Check for FULL_CONTROL in any group
has_full_control = await conn.fetchval(
"""SELECT EXISTS(
SELECT 1 FROM acls
WHERE resource_type = $1
AND resource_id = $2
AND grantee_type = 'group'
AND grantee_id = ANY($3)
AND permission = 'full_control'
)""",
resource_type, resource_id, group_ids
)
if has_full_control:
return True
# Check for specific permission
has_permission = await conn.fetchval(
"""SELECT EXISTS(
SELECT 1 FROM acls
WHERE resource_type = $1
AND resource_id = $2
AND grantee_type = 'group'
AND grantee_id = ANY($3)
AND permission = $4
)""",
resource_type, resource_id, group_ids, required_permission.value
)
return has_permission
async def _check_bucket_policy(
self,
conn,
bucket_id: int,
required_permission: Permission
) -> bool:
"""Check bucket-wide policy for objects."""
# Implementation would check bucket policy statements
# For now, return False
return False
async def grant_access(
self,
grantee_type: GranteeType,
grantee_id: Optional[str],
resource_type: str,
resource_id: int,
permission: Permission
) -> bool:
"""Grant access to a resource."""
async with self.db.acquire() as conn:
# Check if grantor has permission
# (This would be called with the requesting user's context)
# Create grant
await conn.execute(
"""INSERT INTO acls
(resource_type, resource_id, grantee_type, grantee_id, permission)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (resource_type, resource_id, grantee_type, grantee_id, permission)
DO NOTHING""",
resource_type, resource_id, grantee_type.value, grantee_id, permission.value
)
logger.info(
f"Granted {permission.value} to {grantee_type.value}:{grantee_id} "
f"on {resource_type}:{resource_id}"
)
return True
async def revoke_access(
self,
grantee_type: GranteeType,
grantee_id: Optional[str],
resource_type: str,
resource_id: int,
permission: Permission = None
) -> bool:
"""Revoke access to a resource."""
async with self.db.acquire() as conn:
if permission:
result = await conn.execute(
"""DELETE FROM acls
WHERE resource_type = $1
AND resource_id = $2
AND grantee_type = $3
AND grantee_id = $4
AND permission = $5""",
resource_type, resource_id, grantee_type.value, grantee_id, permission.value
)
else:
# Revoke all permissions
result = await conn.execute(
"""DELETE FROM acls
WHERE resource_type = $1
AND resource_id = $2
AND grantee_type = $3
AND grantee_id = $4""",
resource_type, resource_id, grantee_type.value, grantee_id
)
deleted = int(result.split()[-1]) if result else 0
logger.info(f"Revoked {deleted} grants from {grantee_type.value}:{grantee_id}")
return deleted > 0
async def get_acl(
self,
resource_type: str,
resource_id: int
) -> List[Dict[str, Any]]:
"""Get ACL for a resource."""
async with self.db.acquire() as conn:
grants = await conn.fetch(
"""SELECT * FROM acls
WHERE resource_type = $1 AND resource_id = $2
ORDER BY grantee_type, grantee_id, permission""",
resource_type, resource_id
)
return [
{
"grantee_type": g["grantee_type"],
"grantee_id": g["grantee_id"],
"permission": g["permission"]
}
for g in grants
]
async def set_acl(
self,
resource_type: str,
resource_id: int,
grants: List[Grant]
) -> bool:
"""Replace ACL for a resource."""
async with self.db.acquire() as conn:
async with conn.transaction():
# Delete existing ACLs
await conn.execute(
"DELETE FROM acls WHERE resource_type = $1 AND resource_id = $2",
resource_type, resource_id
)
# Insert new grants
for grant in grants:
await conn.execute(
"""INSERT INTO acls
(resource_type, resource_id, grantee_type, grantee_id, permission)
VALUES ($1, $2, $3, $4, $5)""",
resource_type, resource_id,
grant.grantee_type.value, grant.grantee_id, grant.permission.value
)
logger.info(f"Set ACL for {resource_type}:{resource_id} with {len(grants)} grants")
return True
async def make_public(
self,
resource_type: str,
resource_id: int,
read_only: bool = True
) -> bool:
"""Make a resource publicly accessible."""
permission = Permission.READ if read_only else Permission.FULL_CONTROL
return await self.grant_access(
grantee_type=GranteeType.ALL,
grantee_id=None,
resource_type=resource_type,
resource_id=resource_id,
permission=permission
)
async def make_private(
self,
resource_type: str,
resource_id: int
) -> bool:
"""Remove all public access."""
return await self.revoke_access(
grantee_type=GranteeType.ALL,
grantee_id=None,
resource_type=resource_type,
resource_id=resource_id
)
Authentication middleware:
from fastapi import Request, HTTPException, Header
from typing import Optional
class AuthContext:
"""Authentication context for requests."""
def __init__(
self,
user_id: Optional[str] = None,
access_key: Optional[str] = None,
is_authenticated: bool = False
):
self.user_id = user_id
self.access_key = access_key
self.is_authenticated = is_authenticated
async def get_auth_context(
request: Request,
authorization: Optional[str] = Header(None)
) -> AuthContext:
"""
Extract authentication context from request.
Supports:
- AWS SigV4 style signatures (via Authorization header)
- Presigned URL access keys
"""
# Check presigned URL first
if "presigned" in request.query_params:
access_key = request.query_params["presigned"]
# Verify presigned URL
upload_service = get_upload_service()
presigned = await upload_service.verify_presigned_url(access_key, "get")
if presigned:
return AuthContext(
user_id=None,
access_key=access_key,
is_authenticated=True
)
# Check Authorization header
if authorization:
# Parse Authorization header (AWS SigV4 format)
# Authorization: AWS4-HMAC-SHA256 Credential=access_key/...
try:
parts = authorization.split(" ")
if len(parts) >= 2:
scheme, credentials = parts[0], parts[1]
if scheme == "AWS4-HMAC-SHA256":
# Extract access key
for part in credentials.split(","):
if part.startswith("Credential="):
access_key = part.split("=")[1].split("/")[0]
# Validate access key and get user
user_id = await _validate_access_key(access_key)
return AuthContext(
user_id=user_id,
access_key=access_key,
is_authenticated=True
)
except Exception as e:
logger.warning(f"Failed to parse Authorization header: {e}")
# No valid authentication
return AuthContext()
async def _validate_access_key(access_key: str) -> Optional[str]:
"""Validate an access key and return user ID."""
# In production, this would check against the database
# For now, mock implementation
return "user_123"
def require_auth(permission: Permission = None):
"""Decorator to require authentication for an endpoint."""
async def dependency(
auth_context: AuthContext = Depends(get_auth_context)
):
if not auth_context.is_authenticated:
raise HTTPException(
status_code=401,
detail="Authentication required"
)
return auth_context
return dependency
Access control middleware:
class AccessControlMiddleware:
"""Middleware for enforcing access control."""
def __init__(self, access_service: AccessControlService):
self.access_service = access_service
async def require_permission(
self,
resource_type: str,
permission: Permission,
resource_id_param: str = "id"
):
"""Dependency factory to require specific permission."""
async def check(
resource_id: int,
auth_context: AuthContext = Depends(get_auth_context)
):
if not await self.access_service.check_permission(
user_id=auth_context.user_id,
resource_type=resource_type,
resource_id=resource_id,
required_permission=permission
):
raise HTTPException(
status_code=403,
detail=f"Permission denied: {permission.value} required"
)
return {"resource_id": resource_id}
return check
async def require_bucket_permission(
self,
permission: Permission
):
"""Require bucket-level permission."""
return await self.require_permission("bucket", permission, "bucket_id")
async def require_object_permission(
self,
permission: Permission
):
"""Require object-level permission."""
return await self.require_permission("object", permission, "object_id")
ACL API endpoints:
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
router = APIRouter(prefix="/v1/acl", tags=["acl"])
class GrantModel(BaseModel):
grantee_type: str # 'user', 'group', 'all'
grantee_id: Optional[str] = None
permission: str # 'read', 'write', 'delete', 'full_control'
@router.get("/{resource_type}/{resource_id}")
async def get_acl(
resource_type: str,
resource_id: int,
auth_context: AuthContext = Depends(get_auth_context)
):
"""Get ACL for a resource."""
if not auth_context.is_authenticated:
raise HTTPException(status_code=401, detail="Authentication required")
access_service = get_access_service()
# Check if user can read ACL
if not await access_service.check_permission(
user_id=auth_context.user_id,
resource_type=resource_type,
resource_id=resource_id,
required_permission=Permission.READ_ACL
):
raise HTTPException(status_code=403, detail="Cannot read ACL")
grants = await access_service.get_acl(resource_type, resource_id)
return {"resource_type": resource_type, "resource_id": resource_id, "grants": grants}
@router.put("/{resource_type}/{resource_id}")
async def set_acl(
resource_type: str,
resource_id: int,
grants: List[GrantModel],
auth_context: AuthContext = Depends(get_auth_context)
):
"""Set ACL for a resource."""
if not auth_context.is_authenticated:
raise HTTPException(status_code=401, detail="Authentication required")
access_service = get_access_service()
# Check if user can write ACL
if not await access_service.check_permission(
user_id=auth_context.user_id,
resource_type=resource_type,
resource_id=resource_id,
required_permission=Permission.WRITE_ACL
):
raise HTTPException(status_code=403, detail="Cannot modify ACL")
# Convert to Grant objects
grant_objects = [
Grant(
grantee_type=GranteeType(g.grantee_type),
grantee_id=g.grantee_id,
permission=Permission(g.permission),
resource_type=resource_type,
resource_id=resource_id
)
for g in grants
]
success = await access_service.set_acl(resource_type, resource_id, grant_objects)
if not success:
raise HTTPException(status_code=500, detail="Failed to set ACL")
return {"message": "ACL updated"}
@router.post("/{resource_type}/{resource_id}/grants")
async def add_grant(
resource_type: str,
resource_id: int,
grant: GrantModel,
auth_context: AuthContext = Depends(get_auth_context)
):
"""Add a grant to a resource."""
if not auth_context.is_authenticated:
raise HTTPException(status_code=401, detail="Authentication required")
access_service = get_access_service()
if not await access_service.check_permission(
user_id=auth_context.user_id,
resource_type=resource_type,
resource_id=resource_id,
required_permission=Permission.WRITE_ACL
):
raise HTTPException(status_code=403, detail="Cannot modify ACL")
success = await access_service.grant_access(
grantee_type=GranteeType(grant.grantee_type),
grantee_id=grant.grantee_id,
resource_type=resource_type,
resource_id=resource_id,
permission=Permission(grant.permission)
)
if not success:
raise HTTPException(status_code=500, detail="Failed to add grant")
return {"message": "Grant added"}
@router.delete("/{resource_type}/{resource_id}/grants")
async def revoke_grant(
resource_type: str,
resource_id: int,
grantee_type: str,
grantee_id: Optional[str] = None,
permission: Optional[str] = None,
auth_context: AuthContext = Depends(get_auth_context)
):
"""Revoke a grant from a resource."""
if not auth_context.is_authenticated:
raise HTTPException(status_code=401, detail="Authentication required")
access_service = get_access_service()
if not await access_service.check_permission(
user_id=auth_context.user_id,
resource_type=resource_type,
resource_id=resource_id,
required_permission=Permission.WRITE_ACL
):
raise HTTPException(status_code=403, detail="Cannot modify ACL")
perm = Permission(permission) if permission else None
success = await access_service.revoke_access(
grantee_type=GranteeType(grantee_type),
grantee_id=grantee_id,
resource_type=resource_type,
resource_id=resource_id,
permission=perm
)
if not success:
raise HTTPException(status_code=404, detail="Grant not found")
return {"message": "Grant revoked"}
@router.post("/{resource_type}/{resource_id}/public")
async def make_public(
resource_type: str,
resource_id: int,
read_only: bool = True,
auth_context: AuthContext = Depends(get_auth_context)
):
"""Make a resource publicly accessible."""
if not auth_context.is_authenticated:
raise HTTPException(status_code=401, detail="Authentication required")
access_service = get_access_service()
if not await access_service.check_permission(
user_id=auth_context.user_id,
resource_type=resource_type,
resource_id=resource_id,
required_permission=Permission.WRITE_ACL
):
raise HTTPException(status_code=403, detail="Cannot modify ACL")
success = await access_service.make_public(resource_type, resource_id, read_only)
return {"message": f"Resource is now public (read_only={read_only})"}
@router.delete("/{resource_type}/{resource_id}/public")
async def make_private(
resource_type: str,
resource_id: int,
auth_context: AuthContext = Depends(get_auth_context)
):
"""Make a resource private."""
if not auth_context.is_authenticated:
raise HTTPException(status_code=401, detail="Authentication required")
access_service = get_access_service()
if not await access_service.check_permission(
user_id=auth_context.user_id,
resource_type=resource_type,
resource_id=resource_id,
required_permission=Permission.WRITE_ACL
):
raise HTTPException(status_code=403, detail="Cannot modify ACL")
success = await access_service.make_private(resource_type, resource_id)
return {"message": "Resource is now private"}
Acceptance Criteria
- Permissions are enforced correctly
- Public access works
- Owner has full control
- ACL can be read and modified
- Group membership grants work
- Presigned URLs bypass auth
- Unauthorized requests are rejected
Notes
Trade-offs:
- ACL vs policy-based: ACL simpler for direct object access
- Deny vs allow-only: Allow-only simpler and less error-prone
Performance:
- Cache permission checks in Redis
- Batch permission checks for list operations
Alternatives considered:
- AWS IAM-style policies: More complex but more flexible
- OAuth2 scopes: Different model, harder to map