Coverage for src/main/python/okta_api_script/main.py: 92%

1"""Main module for Okta API interactions."""

2

3 import json

4 import os

5 import sys

6

7 import requests

8 from services.enrollment import generate_server_enrollment_token

9 from services.resource_groups import (

10 get_projects_by_resource_group,

11 get_resource_groups_by_team,

12)

13 from services.service_token import get_service_token

14

15

16 def execute_api_cycle(

17 org_name: str | None = None,

18 team_name: str | None = None,

19 target_project: str | None = None,

20 key_id: str | None = None,

21 key_secret: str | None = None,

22 output_json: bool = False,

23) -> None:

24 """Execute the Okta API cycle."""

25 # Use provided values or read from environment

26 org_name = org_name or os.getenv("OKTA_ORG")

27 team_name = team_name or os.getenv("OKTA_TEAM")

28 target_project = target_project or os.getenv("OKTA_TARGET_PROJECT")

29

30 if not team_name or not org_name or not target_project:

31 raise ValueError(

32 "org_name, team_name, and target_project variables must be set"

33 )

34

35 key_id = key_id or os.getenv("KEY_ID")

36 key_secret = key_secret or os.getenv("KEY_SECRET")

37

38 if not key_id or not key_secret: 38 ↛ 39line 38 didn't jump to line 39 because the condition on line 38 was never true

39 raise ValueError("key_id and key_secret variables must be set")

40

41 try:

42 data = get_service_token(org_name, team_name, key_id, key_secret)

43 bearer_token = data["bearer_token"]

44 # print(f"Obtained bearer token: \n{bearer_token}\n")

45 # print(data)

46 resource_groups = get_resource_groups_by_team(bearer_token, org_name, team_name)

47 for rg in resource_groups:

48 # print(rg)

49 projects = get_projects_by_resource_group(

50 bearer_token, org_name, team_name, rg["id"]

51 )

52 rg["__projects"] = projects

53

54 # print(json.dumps(resource_groups, indent=2))

55

56 et = generate_server_enrollment_token(

57 team_name,

58 target_project,

59 org_name,

60 bearer_token,

61 resource_group_id=resource_groups[0]["id"],

62 project_id=resource_groups[0]["__projects"][0]["id"],

63 description="Generated by script",

64 )

65 token = et["token"]

66 if not token:

67 raise ValueError("No token received")

68 if output_json:

69 print(json.dumps(et, indent=2))

70 else:

71 print(f"{et['token']}")

72

73 # projects = get_projects_by_team(bearer_token, org_name, team_name)

74 # print(projects)

75 except requests.exceptions.RequestException as e:

76 print(f"Error making API request: {e}", file=sys.stderr)

77 except ValueError as e:

78 print(f"Configuration error: {e}", file=sys.stderr)

79

80

81 if __name__ == "__main__": 81 ↛ 82line 81 didn't jump to line 82 because the condition on line 81 was never true

82 execute_api_cycle()