Skip to content

Commit

Permalink
Revert "Submit Account Request form and data to DynamoDB (#566)"
Browse files Browse the repository at this point in the history
This reverts commit 9c6fdfd.
  • Loading branch information
sylviamclaughlin authored Jun 28, 2024
1 parent 9c6fdfd commit ee0d808
Show file tree
Hide file tree
Showing 16 changed files with 96 additions and 947 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,24 +36,6 @@ def get_active_account_names():
)


def get_account_id_by_name(account_name):
"""Retrieves the account ID for a given account name.
Args:
account_name (str): The name of the account.
Returns:
str: The account ID.
"""
response = list_organization_accounts()

# Return the account ID for the account with the given name
return next(
(account["Id"] for account in response if account.get("Name") == account_name),
None,
)


def healthcheck():
"""Check the health of the AWS integration.
Expand Down
38 changes: 0 additions & 38 deletions app/modules/aws/aws.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from server.utils import log_ops_message
from modules.aws import aws_sso, aws_account_health, aws_access_requests
from integrations.slack import commands as slack_commands, users as slack_users
from integrations.aws.organizations import get_account_id_by_name
from modules.permissions import handler as permissions
from modules.aws.identity_center import provision_aws_users

Expand Down Expand Up @@ -326,40 +325,3 @@ def request_user_provisioning(client, body, respond, args, logger):
)

logger.info("Completed user provisioning request")


def request_aws_account_access(
account_name, rationale, start_date, end_date, user_email, access_type
):
"""
Request AWS account access for a user.
This function initiates a request for access to an AWS account for a specified user.
It performs the following steps:
1. Retrieves the account ID associated with the given account name.
2. Retrieves the user ID associated with the given user email.
3. Creates an AWS access request with the provided details.
Args:
account_name (str): The name of the AWS account to which access is requested.
rationale (str): The reason for requesting access to the AWS account.
start_date (datetime): The start date and time for the requested access period.
end_date (datetime): The end date and time for the requested access period.
user_email (str): The email address of the user requesting access.
access_type (str): The type of access requested (e.g., 'read', 'write').
Returns:
bool: True if the access request was successfully created, False otherwise.
"""
account_id = get_account_id_by_name(account_name)
user_id = aws_sso.get_user_id(user_email)
return aws_access_requests.create_aws_access_request(
account_id,
account_name,
user_id,
user_email,
start_date,
end_date,
access_type,
rationale,
)
14 changes: 1 addition & 13 deletions app/modules/aws/aws_access_requests.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import boto3
import datetime
import os
import uuid

client = boto3.client(
"dynamodb",
Expand Down Expand Up @@ -48,28 +47,17 @@ def already_has_access(account_id, user_id, access_type):


def create_aws_access_request(
account_id,
account_name,
user_id,
email,
start_date_time,
end_date_time,
access_type,
rationale,
account_id, account_name, user_id, email, access_type, rationale
):
id = str(uuid.uuid4())
response = client.put_item(
TableName=table,
Item={
"id": {"S": id},
"account_id": {"S": account_id},
"account_name": {"S": account_name},
"user_id": {"S": user_id},
"email": {"S": email},
"access_type": {"S": access_type},
"rationale": {"S": rationale},
"start_date_time": {"S": str(start_date_time.timestamp())},
"end_date_time": {"S": str(end_date_time.timestamp())},
"created_at": {"N": str(datetime.datetime.now().timestamp())},
"expired": {"BOOL": False},
},
Expand Down
116 changes: 1 addition & 115 deletions app/server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,7 @@
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from models import webhooks
from server.utils import (
log_ops_message,
create_access_token,
get_current_user,
get_user_email_from_request,
)
from server.utils import log_ops_message, create_access_token
from integrations.sentinel import log_to_sentinel
from integrations import maxmind
from server.event_handlers import aws
Expand All @@ -33,10 +28,6 @@
InvalidSignatureVersionException,
SignatureVerificationFailureException,
)
from fastapi import Depends
from datetime import datetime, timezone, timedelta
from integrations.aws.organizations import get_active_account_names
from modules.aws.aws import request_aws_account_access

logging.basicConfig(level=logging.INFO)
sns_message_validator = SNSMessageValidator()
Expand Down Expand Up @@ -81,23 +72,6 @@ class Config:
extra = Extra.forbid


class AccessRequest(BaseModel):
"""
AccessRequest represents a request for access to an AWS account.
This class defines the schema for an access request, which includes the following fields:
- account: The name of the AWS account to which access is requested.
- reason: The reason for requesting access to the AWS account.
- startDate: The start date and time for the requested access period.
- endDate: The end date and time for the requested access period.
"""

account: str
reason: str
startDate: datetime
endDate: datetime


# initialize the limiter
limiter = Limiter(key_func=get_remote_address)

Expand Down Expand Up @@ -224,75 +198,6 @@ async def user(request: Request):
return JSONResponse({"error": "Not logged in"})


@handler.post("/request_access")
@limiter.limit("10/minute")
async def create_access_request(
request: Request,
access_request: AccessRequest,
use: dict = Depends(get_current_user),
):
"""
Endpoint to create an AWS access request.
This asynchronous function handles POST requests to the "/request_access" endpoint. It performs several validation checks on the provided access request data and then attempts to create an access request in the system. The function is protected by a rate limiter and requires user authentication.
Args:
request (Request): The FastAPI request object.
access_request (AccessRequest): The data model representing the access request.
use (dict, optional): Dependency that provides the current user context. Defaults to Depends(get_current_user).
Raises:
HTTPException: If any validation checks fail or if the request creation fails.
Returns:
dict: A dictionary containing a success message and the access request data if the request is successfully created.
"""
# Check if the account and reason fields are provided
if not access_request.account or not access_request.reason:
raise HTTPException(status_code=400, detail="Account and reason are required")

# Check if the start date is at least 5 minutes in the future
if (
access_request.startDate.replace(tzinfo=timezone.utc) + timedelta(minutes=5)
) < datetime.now().replace(tzinfo=timezone.utc):
raise HTTPException(status_code=400, detail="Start date must be in the future")

# Check if the end date is after the start date
if access_request.endDate.replace(tzinfo=timezone.utc) <= access_request.startDate:
raise HTTPException(status_code=400, detail="End date must be after start date")

# If the request is for more than 24 hours in the future, this is not allowed
if access_request.endDate.replace(tzinfo=timezone.utc) > datetime.now().replace(
tzinfo=timezone.utc
) + timedelta(days=1):
raise HTTPException(
status_code=400,
detail="The access request cannot be for more than 24 hours",
)

# get the user email from the request
user_email = get_user_email_from_request(request)

# Store the request in the database
response = request_aws_account_access(
access_request.account,
access_request.reason,
access_request.startDate,
access_request.endDate,
user_email,
"read",
)
# Return a success message and the access request data if the request is created successfully
if response:
return {
"message": "Access request created successfully",
"data": access_request,
}
else:
# Raise an HTTP 500 error if the request creation fails
raise HTTPException(status_code=500, detail="Failed to create access request")


# Geolocate route. Returns the country, city, latitude, and longitude of the IP address.
@handler.get("/geolocate/{ip}")
def geolocate(ip):
Expand All @@ -309,25 +214,6 @@ def geolocate(ip):
}


@handler.get("/accounts")
@limiter.limit("5/minute")
async def get_accounts(request: Request, user: dict = Depends(get_current_user)):
"""
Endpoint to retrieve active AWS account names.
This asynchronous function handles GET requests to the "/accounts" endpoint.
It retrieves a list of active AWS account names. The function is protected by a rate limiter and requires user authentication.
Args:
request (Request): The FastAPI request object.
user (dict, optional): Dependency that provides the current user context. Defaults to Depends(get_current_user).
Returns:
list: A list of active AWS account names.
"""
return get_active_account_names()


@handler.post("/hook/{id}")
@limiter.limit(
"30/minute"
Expand Down
27 changes: 0 additions & 27 deletions app/server/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,30 +89,3 @@ async def get_current_user(request: Request):
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token"
)
return user


def get_user_email_from_request(request: Request):
"""
Retrieve the user's email address from the request session.
This function extracts the user's email address from the session data stored in the request.
It performs necessary checks to ensure the request and session data are valid.
Args:
request (Request): The FastAPI request object containing session data.
Raises:
HTTPException: If the request or session data is missing or invalid.
Returns:
str or None: The user's email address if found, otherwise None.
"""
if not request or not request.session:
raise HTTPException(
status_code=400, detail="Invalid request or missing session data"
)

user_email = request.session.get("user").get("email")
if user_email:
return user_email
return None
Loading

0 comments on commit ee0d808

Please sign in to comment.