File size: 13,871 Bytes
d864d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import os
import tempfile

from dotenv import load_dotenv

# Set or retrieve configuration variables for CDK redaction deployment


def convert_string_to_boolean(value: str) -> bool:
    """Convert string to boolean, handling various formats."""
    if isinstance(value, bool):
        return value
    elif value in ["True", "1", "true", "TRUE"]:
        return True
    elif value in ["False", "0", "false", "FALSE"]:
        return False
    else:
        raise ValueError(f"Invalid boolean value: {value}")


def get_or_create_env_var(var_name: str, default_value: str, print_val: bool = False):
    """
    Get an environmental variable, and set it to a default value if it doesn't exist
    """
    # Get the environment variable if it exists
    value = os.environ.get(var_name)

    # If it doesn't exist, set the environment variable to the default value
    if value is None:
        os.environ[var_name] = default_value
        value = default_value

    if print_val is True:
        print(f"The value of {var_name} is {value}")

    return value


def ensure_folder_exists(output_folder: str):
    """Checks if the specified folder exists, creates it if not."""

    if not os.path.exists(output_folder):
        # Create the folder if it doesn't exist
        os.makedirs(output_folder, exist_ok=True)
        print(f"Created the {output_folder} folder.")
    else:
        print(f"The {output_folder} folder already exists.")


def add_folder_to_path(folder_path: str):
    """
    Check if a folder exists on your system. If so, get the absolute path and then add it to the system Path variable if it doesn't already exist. Function is only relevant for locally-created executable files based on this app (when using pyinstaller it creates a _internal folder that contains tesseract and poppler. These need to be added to the system path to enable the app to run)
    """

    if os.path.exists(folder_path) and os.path.isdir(folder_path):
        print(folder_path, "folder exists.")

        # Resolve relative path to absolute path
        absolute_path = os.path.abspath(folder_path)

        current_path = os.environ["PATH"]
        if absolute_path not in current_path.split(os.pathsep):
            full_path_extension = absolute_path + os.pathsep + current_path
            os.environ["PATH"] = full_path_extension
            # print(f"Updated PATH with: ", full_path_extension)
        else:
            print(f"Directory {folder_path} already exists in PATH.")
    else:
        print(f"Folder not found at {folder_path} - not added to PATH")


###
# LOAD CONFIG FROM ENV FILE
###
CONFIG_FOLDER = get_or_create_env_var("CONFIG_FOLDER", "config/")

ensure_folder_exists(CONFIG_FOLDER)

# If you have an aws_config env file in the config folder, you can load in app variables this way, e.g. 'config/cdk_config.env'
CDK_CONFIG_PATH = get_or_create_env_var(
    "CDK_CONFIG_PATH", "config/cdk_config.env"
)  # e.g. config/cdk_config.env

if CDK_CONFIG_PATH:
    if os.path.exists(CDK_CONFIG_PATH):
        print(f"Loading CDK variables from config file {CDK_CONFIG_PATH}")
        load_dotenv(CDK_CONFIG_PATH)
    else:
        print("CDK config file not found at location:", CDK_CONFIG_PATH)

###
# AWS OPTIONS
###
AWS_REGION = get_or_create_env_var("AWS_REGION", "")
AWS_ACCOUNT_ID = get_or_create_env_var("AWS_ACCOUNT_ID", "")

###
# CDK OPTIONS
###
CDK_PREFIX = get_or_create_env_var("CDK_PREFIX", "")
CONTEXT_FILE = get_or_create_env_var(
    "CONTEXT_FILE", "cdk.context.json"
)  # Define the CDK output context file name
CDK_FOLDER = get_or_create_env_var(
    "CDK_FOLDER", ""
)  # FULL_PATH_TO_CDK_FOLDER_HERE (with forward slash)
RUN_USEAST_STACK = get_or_create_env_var("RUN_USEAST_STACK", "False")

### VPC and connections
VPC_NAME = get_or_create_env_var("VPC_NAME", "")
NEW_VPC_DEFAULT_NAME = get_or_create_env_var("NEW_VPC_DEFAULT_NAME", f"{CDK_PREFIX}vpc")
NEW_VPC_CIDR = get_or_create_env_var("NEW_VPC_CIDR", "")  # "10.0.0.0/24"


EXISTING_IGW_ID = get_or_create_env_var("EXISTING_IGW_ID", "")
SINGLE_NAT_GATEWAY_ID = get_or_create_env_var("SINGLE_NAT_GATEWAY_ID", "")

### SUBNETS / ROUTE TABLES / NAT GATEWAY
PUBLIC_SUBNETS_TO_USE = get_or_create_env_var(
    "PUBLIC_SUBNETS_TO_USE", ""
)  # e.g. ['PublicSubnet1', 'PublicSubnet2']
PUBLIC_SUBNET_CIDR_BLOCKS = get_or_create_env_var(
    "PUBLIC_SUBNET_CIDR_BLOCKS", ""
)  # e.g. ["10.0.1.0/24", "10.0.2.0/24"]
PUBLIC_SUBNET_AVAILABILITY_ZONES = get_or_create_env_var(
    "PUBLIC_SUBNET_AVAILABILITY_ZONES", ""
)  # e.g. ["eu-east-1b", "eu-east1b"]

PRIVATE_SUBNETS_TO_USE = get_or_create_env_var(
    "PRIVATE_SUBNETS_TO_USE", ""
)  # e.g. ['PrivateSubnet1', 'PrivateSubnet2']
PRIVATE_SUBNET_CIDR_BLOCKS = get_or_create_env_var(
    "PRIVATE_SUBNET_CIDR_BLOCKS", ""
)  # e.g. ["10.0.1.0/24", "10.0.2.0/24"]
PRIVATE_SUBNET_AVAILABILITY_ZONES = get_or_create_env_var(
    "PRIVATE_SUBNET_AVAILABILITY_ZONES", ""
)  # e.g. ["eu-east-1b", "eu-east1b"]

ROUTE_TABLE_BASE_NAME = get_or_create_env_var(
    "ROUTE_TABLE_BASE_NAME", f"{CDK_PREFIX}PrivateRouteTable"
)
NAT_GATEWAY_EIP_NAME = get_or_create_env_var(
    "NAT_GATEWAY_EIP_NAME", f"{CDK_PREFIX}NatGatewayEip"
)
NAT_GATEWAY_NAME = get_or_create_env_var("NAT_GATEWAY_NAME", f"{CDK_PREFIX}NatGateway")

# IAM roles
AWS_MANAGED_TASK_ROLES_LIST = get_or_create_env_var(
    "AWS_MANAGED_TASK_ROLES_LIST",
    '["AmazonCognitoReadOnly", "service-role/AmazonECSTaskExecutionRolePolicy", "AmazonS3FullAccess", "AmazonTextractFullAccess", "ComprehendReadOnly", "AmazonDynamoDBFullAccess", "service-role/AWSAppSyncPushToCloudWatchLogs"]',
)
POLICY_FILE_LOCATIONS = get_or_create_env_var(
    "POLICY_FILE_LOCATIONS", ""
)  # e.g. '["config/sts_permissions.json"]'
POLICY_FILE_ARNS = get_or_create_env_var("POLICY_FILE_ARNS", "")

# GITHUB REPO
GITHUB_REPO_USERNAME = get_or_create_env_var("GITHUB_REPO_USERNAME", "seanpedrick-case")
GITHUB_REPO_NAME = get_or_create_env_var("GITHUB_REPO_NAME", "doc_redaction")
GITHUB_REPO_BRANCH = get_or_create_env_var("GITHUB_REPO_BRANCH", "main")

### CODEBUILD
CODEBUILD_ROLE_NAME = get_or_create_env_var(
    "CODEBUILD_ROLE_NAME", f"{CDK_PREFIX}CodeBuildRole"
)
CODEBUILD_PROJECT_NAME = get_or_create_env_var(
    "CODEBUILD_PROJECT_NAME", f"{CDK_PREFIX}CodeBuildProject"
)

### ECR
ECR_REPO_NAME = get_or_create_env_var(
    "ECR_REPO_NAME", "doc-redaction"
)  # Beware - cannot have underscores and must be lower case
ECR_CDK_REPO_NAME = get_or_create_env_var(
    "ECR_CDK_REPO_NAME", f"{CDK_PREFIX}{ECR_REPO_NAME}".lower()
)

### S3
S3_LOG_CONFIG_BUCKET_NAME = get_or_create_env_var(
    "S3_LOG_CONFIG_BUCKET_NAME", f"{CDK_PREFIX}s3-logs".lower()
)  # S3 bucket names need to be lower case
S3_OUTPUT_BUCKET_NAME = get_or_create_env_var(
    "S3_OUTPUT_BUCKET_NAME", f"{CDK_PREFIX}s3-output".lower()
)

### KMS KEYS FOR S3 AND SECRETS MANAGER
USE_CUSTOM_KMS_KEY = get_or_create_env_var("USE_CUSTOM_KMS_KEY", "1")
CUSTOM_KMS_KEY_NAME = get_or_create_env_var(
    "CUSTOM_KMS_KEY_NAME", f"alias/{CDK_PREFIX}kms-key".lower()
)

### ECS
FARGATE_TASK_DEFINITION_NAME = get_or_create_env_var(
    "FARGATE_TASK_DEFINITION_NAME", f"{CDK_PREFIX}FargateTaskDefinition"
)
TASK_DEFINITION_FILE_LOCATION = get_or_create_env_var(
    "TASK_DEFINITION_FILE_LOCATION", CDK_FOLDER + CONFIG_FOLDER + "task_definition.json"
)

CLUSTER_NAME = get_or_create_env_var("CLUSTER_NAME", f"{CDK_PREFIX}Cluster")
ECS_SERVICE_NAME = get_or_create_env_var("ECS_SERVICE_NAME", f"{CDK_PREFIX}ECSService")
ECS_TASK_ROLE_NAME = get_or_create_env_var(
    "ECS_TASK_ROLE_NAME", f"{CDK_PREFIX}TaskRole"
)
ECS_TASK_EXECUTION_ROLE_NAME = get_or_create_env_var(
    "ECS_TASK_EXECUTION_ROLE_NAME", f"{CDK_PREFIX}ExecutionRole"
)
ECS_SECURITY_GROUP_NAME = get_or_create_env_var(
    "ECS_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupECS"
)
ECS_LOG_GROUP_NAME = get_or_create_env_var(
    "ECS_LOG_GROUP_NAME", f"/ecs/{ECS_SERVICE_NAME}-logs".lower()
)

ECS_TASK_CPU_SIZE = get_or_create_env_var("ECS_TASK_CPU_SIZE", "1024")
ECS_TASK_MEMORY_SIZE = get_or_create_env_var("ECS_TASK_MEMORY_SIZE", "4096")
ECS_USE_FARGATE_SPOT = get_or_create_env_var("USE_FARGATE_SPOT", "False")
ECS_READ_ONLY_FILE_SYSTEM = get_or_create_env_var("ECS_READ_ONLY_FILE_SYSTEM", "True")

### Cognito
COGNITO_USER_POOL_NAME = get_or_create_env_var(
    "COGNITO_USER_POOL_NAME", f"{CDK_PREFIX}UserPool"
)
COGNITO_USER_POOL_CLIENT_NAME = get_or_create_env_var(
    "COGNITO_USER_POOL_CLIENT_NAME", f"{CDK_PREFIX}UserPoolClient"
)
COGNITO_USER_POOL_CLIENT_SECRET_NAME = get_or_create_env_var(
    "COGNITO_USER_POOL_CLIENT_SECRET_NAME", f"{CDK_PREFIX}ParamCognitoSecret"
)
COGNITO_USER_POOL_DOMAIN_PREFIX = get_or_create_env_var(
    "COGNITO_USER_POOL_DOMAIN_PREFIX", "redaction-app-domain"
)  # Should change this to something unique or you'll probably hit an error

COGNITO_REFRESH_TOKEN_VALIDITY = int(
    get_or_create_env_var("COGNITO_REFRESH_TOKEN_VALIDITY", "480")
)  # Minutes
COGNITO_ID_TOKEN_VALIDITY = int(
    get_or_create_env_var("COGNITO_ID_TOKEN_VALIDITY", "60")
)  # Minutes
COGNITO_ACCESS_TOKEN_VALIDITY = int(
    get_or_create_env_var("COGNITO_ACCESS_TOKEN_VALIDITY", "60")
)  # Minutes

# Application load balancer
ALB_NAME = get_or_create_env_var(
    "ALB_NAME", f"{CDK_PREFIX}Alb"[-32:]
)  # Application load balancer name can be max 32 characters, so taking the last 32 characters of the suggested name
ALB_NAME_SECURITY_GROUP_NAME = get_or_create_env_var(
    "ALB_SECURITY_GROUP_NAME", f"{CDK_PREFIX}SecurityGroupALB"
)
ALB_TARGET_GROUP_NAME = get_or_create_env_var(
    "ALB_TARGET_GROUP_NAME", f"{CDK_PREFIX}-tg"[-32:]
)  # Max 32 characters
EXISTING_LOAD_BALANCER_ARN = get_or_create_env_var("EXISTING_LOAD_BALANCER_ARN", "")
EXISTING_LOAD_BALANCER_DNS = get_or_create_env_var(
    "EXISTING_LOAD_BALANCER_ARN", "placeholder_load_balancer_dns.net"
)

## CLOUDFRONT
USE_CLOUDFRONT = get_or_create_env_var("USE_CLOUDFRONT", "True")
CLOUDFRONT_PREFIX_LIST_ID = get_or_create_env_var(
    "CLOUDFRONT_PREFIX_LIST_ID", "pl-93a247fa"
)
CLOUDFRONT_GEO_RESTRICTION = get_or_create_env_var(
    "CLOUDFRONT_GEO_RESTRICTION", ""
)  # A country that Cloudfront restricts access to. See here: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/georestrictions.html
CLOUDFRONT_DISTRIBUTION_NAME = get_or_create_env_var(
    "CLOUDFRONT_DISTRIBUTION_NAME", f"{CDK_PREFIX}CfDist"
)
CLOUDFRONT_DOMAIN = get_or_create_env_var(
    "CLOUDFRONT_DOMAIN", "cloudfront_placeholder.net"
)


# Certificate for Application load balancer (optional, for HTTPS and logins through the ALB)
ACM_SSL_CERTIFICATE_ARN = get_or_create_env_var("ACM_SSL_CERTIFICATE_ARN", "")
SSL_CERTIFICATE_DOMAIN = get_or_create_env_var(
    "SSL_CERTIFICATE_DOMAIN", ""
)  # e.g. example.com or www.example.com

# This should be the CloudFront domain, the domain linked to your ACM certificate, or the DNS of your application load balancer in console afterwards
if USE_CLOUDFRONT == "True":
    COGNITO_REDIRECTION_URL = get_or_create_env_var(
        "COGNITO_REDIRECTION_URL", "https://" + CLOUDFRONT_DOMAIN
    )
elif SSL_CERTIFICATE_DOMAIN:
    COGNITO_REDIRECTION_URL = get_or_create_env_var(
        "COGNITO_REDIRECTION_URL", "https://" + SSL_CERTIFICATE_DOMAIN
    )
else:
    COGNITO_REDIRECTION_URL = get_or_create_env_var(
        "COGNITO_REDIRECTION_URL", "https://" + EXISTING_LOAD_BALANCER_DNS
    )

# Custom headers e.g. if routing traffic through Cloudfront
CUSTOM_HEADER = get_or_create_env_var(
    "CUSTOM_HEADER", ""
)  # Retrieving or setting CUSTOM_HEADER
CUSTOM_HEADER_VALUE = get_or_create_env_var(
    "CUSTOM_HEADER_VALUE", ""
)  # Retrieving or setting CUSTOM_HEADER_VALUE

# Firewall on top of load balancer
LOAD_BALANCER_WEB_ACL_NAME = get_or_create_env_var(
    "LOAD_BALANCER_WEB_ACL_NAME", f"{CDK_PREFIX}alb-web-acl"
)

# Firewall on top of CloudFront
WEB_ACL_NAME = get_or_create_env_var("WEB_ACL_NAME", f"{CDK_PREFIX}cloudfront-web-acl")

###
# File I/O options
###

OUTPUT_FOLDER = get_or_create_env_var("GRADIO_OUTPUT_FOLDER", "output/")  # 'output/'
INPUT_FOLDER = get_or_create_env_var("GRADIO_INPUT_FOLDER", "input/")  # 'input/'

# Allow for files to be saved in a temporary folder for increased security in some instances
if OUTPUT_FOLDER == "TEMP" or INPUT_FOLDER == "TEMP":
    # Create a temporary directory
    with tempfile.TemporaryDirectory() as temp_dir:
        print(f"Temporary directory created at: {temp_dir}")

        if OUTPUT_FOLDER == "TEMP":
            OUTPUT_FOLDER = temp_dir + "/"
        if INPUT_FOLDER == "TEMP":
            INPUT_FOLDER = temp_dir + "/"

###
# LOGGING OPTIONS
###

SAVE_LOGS_TO_CSV = get_or_create_env_var("SAVE_LOGS_TO_CSV", "True")

### DYNAMODB logs. Whether to save to DynamoDB, and the headers of the table
SAVE_LOGS_TO_DYNAMODB = get_or_create_env_var("SAVE_LOGS_TO_DYNAMODB", "True")
ACCESS_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
    "ACCESS_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-access-logs".lower()
)
FEEDBACK_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
    "FEEDBACK_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-feedback-logs".lower()
)
USAGE_LOG_DYNAMODB_TABLE_NAME = get_or_create_env_var(
    "USAGE_LOG_DYNAMODB_TABLE_NAME", f"{CDK_PREFIX}dynamodb-usage-logs".lower()
)

###
# REDACTION OPTIONS
###

# Get some environment variables and Launch the Gradio app
COGNITO_AUTH = get_or_create_env_var("COGNITO_AUTH", "0")

GRADIO_SERVER_PORT = int(get_or_create_env_var("GRADIO_SERVER_PORT", "7860"))

###
# WHOLE DOCUMENT API OPTIONS
###

DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS = get_or_create_env_var(
    "DAYS_TO_DISPLAY_WHOLE_DOCUMENT_JOBS", "7"
)  # How many days into the past should whole document Textract jobs be displayed? After that, the data is not deleted from the Textract jobs csv, but it is just filtered out. Included to align with S3 buckets where the file outputs will be automatically deleted after X days.