api-foundry 0.8.4__tar.gz → 0.8.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: api-foundry
3
- Version: 0.8.4
3
+ Version: 0.8.6
4
4
  Summary: The `api_foundry` project is a powerful tool designed to automate the deployment of REST APIs on AWS using Lambda services to access and interact with relational databases (RDBMS). This project leverages the OpenAPI specification to define and manage the APIs
5
5
  Project-URL: Documentation, https://github.com/DanRepik/api-foundry
6
6
  Project-URL: Source, https://github.com/DanRepik/api-foundry
@@ -17,6 +17,7 @@ class APISpecEditor:
17
17
  function: Optional[Function]
18
18
  integrations: list[dict]
19
19
  batch_path: Optional[str]
20
+ token_validators: list[dict]
20
21
 
21
22
  def __init__(
22
23
  self,
@@ -24,14 +25,36 @@ class APISpecEditor:
24
25
  open_api_spec: Optional[dict],
25
26
  function: Optional[Function],
26
27
  batch_path: Optional[str] = None,
28
+ token_validators: Optional[list[dict]] = None,
27
29
  ):
28
30
  self.function = function
29
31
  self.batch_path = batch_path
32
+ self.token_validators = token_validators or []
30
33
  self.integrations = []
31
34
  self.editor = AWSOpenAPISpecEditor(
32
35
  copy.deepcopy(open_api_spec) if open_api_spec else None
33
36
  )
34
37
 
38
+ def _get_validators_for_schema(self, schema_object: dict) -> list[str]:
39
+ """Extract validator names from schema object.
40
+
41
+ Extracts provider/validator names from x-af-permissions keys.
42
+ """
43
+ validators = []
44
+
45
+ # Defensive: ensure schema_object is actually a dict
46
+ if not isinstance(schema_object, dict):
47
+ return validators
48
+
49
+ # Extract from x-af-permissions provider keys
50
+ if "x-af-permissions" in schema_object:
51
+ permissions = schema_object["x-af-permissions"]
52
+ if isinstance(permissions, dict):
53
+ # Keys are validator names like "default", "my-oauth"
54
+ validators = list(permissions.keys())
55
+
56
+ return validators
57
+
35
58
  def rest_api_spec(self) -> str:
36
59
  schemas = self.editor.get_spec_part(["components", "schemas"], create=False)
37
60
  if schemas:
@@ -62,13 +85,25 @@ class APISpecEditor:
62
85
  schema_object: dict,
63
86
  function: Optional[Function] = None,
64
87
  ):
65
- # Ensure any schema-level permissions are carried onto the operation if not set.
88
+ # Ensure schema-level permissions carry onto operation if not set.
66
89
  if "x-af-permissions" not in operation and isinstance(schema_object, dict):
67
90
  permissions = schema_object.get("x-af-permissions")
68
91
  if permissions:
69
92
  operation["x-af-permissions"] = permissions
93
+
94
+ # Add security requirements based on validators
95
+ if "security" not in operation and isinstance(schema_object, dict):
96
+ validators = self._get_validators_for_schema(schema_object)
97
+ if validators:
98
+ # Build security array: [{validator_name: []}]
99
+ operation["security"] = [{v: []} for v in validators]
100
+
70
101
  self.integrations.append(
71
- {"path": path, "method": method, "function": function or self.function}
102
+ {
103
+ "path": path,
104
+ "method": method,
105
+ "function": function or self.function,
106
+ }
72
107
  )
73
108
  self.editor.add_operation(
74
109
  path=path,
@@ -96,16 +131,19 @@ class APISpecEditor:
96
131
 
97
132
  elif property["type"] == "string" and property.get("format", None) == "date":
98
133
  # Assuming ISO 8601 date format (YYYY-MM-DD)
99
- regex_pattern = r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])" # Date part: YYYY-MM-DD
134
+ regex_pattern = r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])"
100
135
 
101
136
  elif (
102
137
  property["type"] == "string" and property.get("format", None) == "date-time"
103
138
  ):
104
139
  regex_pattern = (
105
- r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])" # Date part: YYYY-MM-DD
140
+ r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])"
141
+ # Date part: YYYY-MM-DD
106
142
  r"T" # Separator: T
107
- r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])" # Time part: HH:MM:SS
108
- r"(?:\.\d+)?(?:Z|[+-](?:0[0-9]|1[0-4]):[0-5][0-9])?" # Optional: fractional seconds and timezone
143
+ r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])"
144
+ # Time part: HH:MM:SS
145
+ r"(?:\.\d+)?(?:Z|[+-](?:0[0-9]|1[0-4]):[0-5][0-9])?"
146
+ # Optional: fractional seconds and timezone
109
147
  )
110
148
 
111
149
  elif property["type"] == "string":
@@ -114,7 +152,8 @@ class APISpecEditor:
114
152
  else:
115
153
  max_length = property.get("max_length", 200)
116
154
  min_length = property.get("min_length", 0)
117
- regex_pattern = rf"[\w\s]{min_length},{max_length}" # Allows letters, numbers, and underscores
155
+ regex_pattern = rf"[\w\s]{min_length},{max_length}"
156
+ # Allows letters, numbers, and underscores
118
157
 
119
158
  elif property["type"] == "integer":
120
159
  signed = property.get("signed", True)
@@ -584,7 +623,7 @@ class APISpecEditor:
584
623
 
585
624
  def generate_batch_operation(self, path: str):
586
625
  """Generate batch operations endpoint with full schema definitions."""
587
-
626
+
588
627
  # Define batch component schemas
589
628
  batch_schemas = {
590
629
  "BatchRequest": {
@@ -595,9 +634,7 @@ class APISpecEditor:
595
634
  "type": "array",
596
635
  "minItems": 1,
597
636
  "maxItems": 100,
598
- "items": {
599
- "$ref": "#/components/schemas/BatchOperation"
600
- },
637
+ "items": {"$ref": "#/components/schemas/BatchOperation"},
601
638
  },
602
639
  "options": {
603
640
  "type": "object",
@@ -610,9 +647,7 @@ class APISpecEditor:
610
647
  "continueOnError": {
611
648
  "type": "boolean",
612
649
  "default": False,
613
- "description": (
614
- "Continue executing after errors"
615
- ),
650
+ "description": ("Continue executing after errors"),
616
651
  },
617
652
  },
618
653
  },
@@ -655,9 +690,7 @@ class APISpecEditor:
655
690
  "depends_on": {
656
691
  "type": "array",
657
692
  "items": {"type": "string"},
658
- "description": (
659
- "IDs of operations that must complete first"
660
- ),
693
+ "description": ("IDs of operations that must complete first"),
661
694
  },
662
695
  "claims": {
663
696
  "type": "object",
@@ -675,15 +708,11 @@ class APISpecEditor:
675
708
  "results": {
676
709
  "type": "object",
677
710
  "additionalProperties": True,
678
- "description": (
679
- "Map of operation IDs to results or errors"
680
- ),
711
+ "description": ("Map of operation IDs to results or errors"),
681
712
  },
682
713
  "errors": {
683
714
  "type": "array",
684
- "items": {
685
- "$ref": "#/components/schemas/OperationError"
686
- },
715
+ "items": {"$ref": "#/components/schemas/OperationError"},
687
716
  "description": "List of errors that occurred",
688
717
  },
689
718
  },
@@ -723,16 +752,17 @@ class APISpecEditor:
723
752
  # Add schemas to the editor's spec by directly accessing components
724
753
  # The editor will handle this when generating the final YAML
725
754
  import yaml as yaml_lib
755
+
726
756
  current_spec = yaml_lib.safe_load(self.editor.yaml)
727
757
  if "components" not in current_spec:
728
758
  current_spec["components"] = {}
729
759
  if "schemas" not in current_spec["components"]:
730
760
  current_spec["components"]["schemas"] = {}
731
-
761
+
732
762
  # Add batch schemas
733
763
  for schema_name, schema_def in batch_schemas.items():
734
764
  current_spec["components"]["schemas"][schema_name] = schema_def
735
-
765
+
736
766
  # Update the editor with the modified spec
737
767
  self.editor = AWSOpenAPISpecEditor(current_spec)
738
768
 
@@ -752,9 +782,7 @@ class APISpecEditor:
752
782
  "required": True,
753
783
  "content": {
754
784
  "application/json": {
755
- "schema": {
756
- "$ref": "#/components/schemas/BatchRequest"
757
- }
785
+ "schema": {"$ref": "#/components/schemas/BatchRequest"}
758
786
  }
759
787
  },
760
788
  },
@@ -764,9 +792,7 @@ class APISpecEditor:
764
792
  "content": {
765
793
  "application/json": {
766
794
  "schema": {
767
- "$ref": (
768
- "#/components/schemas/BatchResponse"
769
- )
795
+ "$ref": ("#/components/schemas/BatchResponse")
770
796
  }
771
797
  }
772
798
  },
@@ -776,9 +802,7 @@ class APISpecEditor:
776
802
  "content": {
777
803
  "application/json": {
778
804
  "schema": {
779
- "$ref": (
780
- "#/components/schemas/ErrorResponse"
781
- )
805
+ "$ref": ("#/components/schemas/ErrorResponse")
782
806
  }
783
807
  }
784
808
  },
@@ -152,18 +152,30 @@ class APIFoundry(ComponentResource):
152
152
  env_vars["SECRETS"] = secrets
153
153
  requirements = []
154
154
 
155
- # Grant read access to referenced secrets (single broad stmt)
156
- if json.loads(secrets):
157
- policy_statements.append(
158
- {
159
- "Effect": "Allow",
160
- "Actions": ["secretsmanager:GetSecretValue"],
161
- "Resources": ["*"],
162
- }
163
- )
155
+ # Grant read access to referenced secrets
156
+ if secrets:
157
+ try:
158
+ secret_arns = list(json.loads(secrets).values())
159
+ policy_statements.append(
160
+ {
161
+ "Effect": "Allow",
162
+ "Actions": ["secretsmanager:GetSecretValue"],
163
+ "Resources": secret_arns,
164
+ }
165
+ )
166
+ except (json.JSONDecodeError, AttributeError):
167
+ # If secrets is an Output or invalid JSON, we can't parse it yet
168
+ # Add a broad policy (will be restricted during deployment)
169
+ policy_statements.append(
170
+ {
171
+ "Effect": "Allow",
172
+ "Actions": ["secretsmanager:GetSecretValue"],
173
+ "Resources": "*",
174
+ }
175
+ )
164
176
 
165
177
  requirements.extend(
166
- ["psycopg2-binary", "pyyaml", "../api_foundry_query_engine"]
178
+ ["psycopg2-binary", "pyyaml", "api_foundry_query_engine"]
167
179
  )
168
180
  if env_vars.get("JWKS_HOST"):
169
181
  requirements.extend(["PyJWT", "cryptography", "requests"])
@@ -183,7 +195,10 @@ class APIFoundry(ComponentResource):
183
195
  )
184
196
 
185
197
  gateway_spec = APISpecEditor(
186
- open_api_spec=api_spec_dict, function=self.api_function, batch_path=batch_path
198
+ open_api_spec=api_spec_dict,
199
+ function=self.api_function,
200
+ batch_path=batch_path,
201
+ token_validators=token_validators,
187
202
  )
188
203
 
189
204
  # Merge gateway_spec.integrations with user-provided integrations
@@ -303,12 +303,66 @@ class SchemaObjectAssociation(OpenAPIElement):
303
303
  def __init__(self, name: str, prop: Dict[str, Any], parent_key):
304
304
  super().__init__()
305
305
  self.api_name = name
306
+
307
+ # Validate type attribute exists
308
+ if "type" not in prop:
309
+ raise ApplicationException(
310
+ 500,
311
+ (
312
+ f"Association property '{name}' is missing 'type' "
313
+ f"attribute. Schema associations must specify "
314
+ f"'type: object' or 'type: array'."
315
+ ),
316
+ )
306
317
  self.api_type = prop["type"]
307
318
 
308
- self.schema_name = (
309
- prop["items"]["$ref"] if self.api_type == "array" else prop["$ref"]
310
- ).split("/")[-1]
319
+ # Extract and validate schema reference
320
+ if self.api_type == "array":
321
+ if "items" not in prop:
322
+ raise ApplicationException(
323
+ 500,
324
+ (
325
+ f"Association property '{name}' has type 'array' but "
326
+ f"is missing 'items' attribute. Array associations "
327
+ f"must specify items with a $ref to the target schema."
328
+ ),
329
+ )
330
+ items = prop["items"]
331
+ if "$ref" not in items:
332
+ raise ApplicationException(
333
+ 500,
334
+ (
335
+ f"Association property '{name}' array items are "
336
+ f"missing '$ref' attribute. Use '$ref: "
337
+ f"#/components/schemas/YourSchema' to reference the "
338
+ f"target schema."
339
+ ),
340
+ )
341
+ ref = items["$ref"]
342
+ else:
343
+ if "$ref" not in prop:
344
+ raise ApplicationException(
345
+ 500,
346
+ (
347
+ f"Association property '{name}' is missing '$ref' "
348
+ f"attribute. Use '$ref: #/components/schemas/YourSchema' "
349
+ f"to reference the target schema."
350
+ ),
351
+ )
352
+ ref = prop["$ref"]
353
+
354
+ # Validate $ref format
355
+ if not ref.startswith("#/components/schemas/"):
356
+ raise ApplicationException(
357
+ 500,
358
+ (
359
+ f"Association property '{name}' has invalid $ref format: "
360
+ f"'{ref}'. References must use the format "
361
+ f"'#/components/schemas/SchemaName'."
362
+ ),
363
+ )
311
364
 
365
+ self.schema_name = ref.split("/")[-1]
312
366
  self.child_property = prop.get("x-af-child-property", None)
313
367
  self.parent_property = prop.get("x-af-parent-property", parent_key)
314
368
 
@@ -319,7 +373,20 @@ class SchemaObject(OpenAPIElement):
319
373
  def __init__(self, api_name: str, schema_object: Dict[str, Any]):
320
374
  super().__init__()
321
375
  self.api_name = api_name
376
+
377
+ # Get database name (should always exist as caller filters)
322
378
  self.database = schema_object.get("x-af-database", "").lower()
379
+
380
+ # Validate database name is not empty
381
+ if not self.database:
382
+ raise ApplicationException(
383
+ 500,
384
+ (
385
+ f"Schema object '{api_name}' has empty 'x-af-database' "
386
+ f"value. Provide a valid database connection name."
387
+ ),
388
+ )
389
+
323
390
  self.table_name = self._get_table_name(schema_object)
324
391
  self.properties = self._resolve_properties(schema_object)
325
392
  self.primary_key = self._get_primary_key(schema_object)
@@ -438,40 +505,59 @@ class SchemaObject(OpenAPIElement):
438
505
  return concurrency_property_name
439
506
 
440
507
  def _get_primary_key(self, schema_object: dict) -> Optional[str]:
508
+ primary_keys = []
441
509
  for property_name, properties in schema_object.get("properties", {}).items():
442
510
  if "x-af-primary-key" in properties:
443
- prop_obj = self.properties[property_name]
444
- prop_obj.key_type = properties.get("x-af-primary-key", "auto")
445
-
446
- if prop_obj.key_type not in [
447
- "manual",
448
- "uuid",
449
- "auto",
450
- "sequence",
451
- ]:
452
- raise ApplicationException(
453
- 500,
454
- (
455
- f"Invalid primary key type '{prop_obj.key_type}' "
456
- + f"in schema object '{self.api_name}'"
457
- + f", property '{property_name}'"
458
- ),
459
- )
511
+ primary_keys.append(property_name)
460
512
 
461
- if prop_obj.key_type == "sequence":
462
- prop_obj.sequence_name = properties.get("x-af-sequence-name", None)
463
- if not prop_obj.sequence_name:
464
- raise ApplicationException(
465
- 500,
466
- (
467
- "Sequence-based primary keys must have a "
468
- "sequence name "
469
- + f"in schema object '{self.api_name}', "
470
- + f"property '{property_name}'"
471
- ),
472
- )
473
- return property_name
474
- return None
513
+ # Validate only one primary key is defined
514
+ if len(primary_keys) > 1:
515
+ raise ApplicationException(
516
+ 500,
517
+ (
518
+ f"Schema object '{self.api_name}' has multiple primary "
519
+ f"keys defined: {', '.join(primary_keys)}. Only one "
520
+ f"property can be marked with 'x-af-primary-key'."
521
+ ),
522
+ )
523
+
524
+ if not primary_keys:
525
+ return None
526
+
527
+ property_name = primary_keys[0]
528
+ properties = schema_object["properties"][property_name]
529
+ prop_obj = self.properties[property_name]
530
+ prop_obj.key_type = properties.get("x-af-primary-key", "auto")
531
+
532
+ if prop_obj.key_type not in [
533
+ "manual",
534
+ "uuid",
535
+ "auto",
536
+ "sequence",
537
+ ]:
538
+ raise ApplicationException(
539
+ 500,
540
+ (
541
+ f"Invalid primary key type '{prop_obj.key_type}' "
542
+ f"in schema object '{self.api_name}', "
543
+ f"property '{property_name}'. Valid types are: "
544
+ f"'manual', 'uuid', 'auto', 'sequence'."
545
+ ),
546
+ )
547
+
548
+ if prop_obj.key_type == "sequence":
549
+ prop_obj.sequence_name = properties.get("x-af-sequence-name", None)
550
+ if not prop_obj.sequence_name:
551
+ raise ApplicationException(
552
+ 500,
553
+ (
554
+ f"Sequence-based primary key '{property_name}' in "
555
+ f"schema object '{self.api_name}' is missing "
556
+ f"'x-af-sequence-name' attribute. Specify the "
557
+ f"database sequence name to use."
558
+ ),
559
+ )
560
+ return property_name
475
561
 
476
562
  def _get_permissions(self, schema_object: dict) -> dict:
477
563
  """Extract permissions from schema using x-af-permissions only.
@@ -536,8 +622,37 @@ class PathOperation(OpenAPIElement):
536
622
  super().__init__()
537
623
  self.entity = path.lower().rsplit("/", 1)[-1]
538
624
  self.action = METHODS_TO_ACTIONS[method]
625
+
626
+ # Validate required x-af-database attribute
627
+ if "x-af-database" not in path_operation:
628
+ raise ApplicationException(
629
+ 500,
630
+ (
631
+ f"Path operation '{method.upper()} {path}' is missing "
632
+ f"required 'x-af-database' attribute. Custom path operations "
633
+ f"must specify which database connection to use."
634
+ ),
635
+ )
539
636
  self.database = path_operation["x-af-database"]
637
+
638
+ # Validate required x-af-sql attribute for custom operations
639
+ if "x-af-sql" not in path_operation:
640
+ raise ApplicationException(
641
+ 500,
642
+ (
643
+ f"Path operation '{method.upper()} {path}' is missing "
644
+ f"required 'x-af-sql' attribute. Custom path operations must "
645
+ f"provide the SQL query/statement to execute.\n\n"
646
+ f"Note: If you intended to create CRUD endpoints, define a "
647
+ f"schema object in components/schemas with 'x-af-database' "
648
+ f"instead of creating custom path operations. API Foundry "
649
+ f"auto-generates CRUD endpoints from schema objects.\n\n"
650
+ f"For custom SQL operations, add:\n"
651
+ f" x-af-sql: 'SELECT ...' or 'INSERT ...' etc."
652
+ ),
653
+ )
540
654
  self.sql = path_operation["x-af-sql"]
655
+
541
656
  self.inputs = self.get_inputs(path_operation)
542
657
  self.outputs = self._extract_properties(path_operation, "responses")
543
658
  self.permissions = self._get_permissions(path_operation)
@@ -670,12 +785,18 @@ class ModelFactory:
670
785
  return resolve(spec)
671
786
 
672
787
  def _load_schema_objects(self) -> Dict[str, SchemaObject]:
673
- """Loads all schema objects from the OpenAPI specification."""
788
+ """Loads all schema objects from the OpenAPI specification.
789
+
790
+ Only schemas with x-af-database attribute are loaded. Other schemas
791
+ (like DTOs, enums, or reference-only types) are silently skipped.
792
+ """
674
793
  schema_objects = {}
675
794
  schemas = self.spec.get("components", {}).get("schemas", {})
676
795
  for name, schema in schemas.items():
677
796
  if "x-af-database" in schema:
678
797
  schema_objects[name] = SchemaObject(name, schema)
798
+ else:
799
+ log.debug(f"Skipping schema '{name}' - no x-af-database attribute")
679
800
  return schema_objects
680
801
 
681
802
  def _load_path_operations(self) -> Dict[str, PathOperation]:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "api-foundry"
7
- version = "0.8.4"
7
+ version = "0.8.6"
8
8
  authors = [
9
9
  { name="Daniel Repik", email="danrepik@icloud.com" },
10
10
  ]
File without changes
File without changes