Skip to content
This repository was archived by the owner on Jun 18, 2024. It is now read-only.

Updated all dependencies and fixing typing issues #57

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 5 additions & 9 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
{
"python.linting.enabled": true,
"python.formatting.provider": "none",
"editor.formatOnSave": true,
"python.linting.mypyEnabled": true,
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
"source.organizeImports.ruff": true
},
"editor.defaultFormatter": "ms-python.black-formatter"
},
"ruff.organizeImports": false,
"ruff.fixAll": false,
"python.analysis.typeCheckingMode": "strict",
"mypy.runUsingActiveInterpreter": true,
"ruff.importStrategy": "fromEnvironment",
"autoDocstring.docstringFormat": "sphinx-notypes",
"python.analysis.typeCheckingMode": "strict"
"autoDocstring.docstringFormat": "sphinx-notypes"
}
4 changes: 2 additions & 2 deletions infisical/api/create_secret.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ def create_secret_req(api_request: Session, options: CreateSecretDTO) -> SecretR
"secretPath": options.path,
},
)
return SecretResponse.parse_obj(response.json())

return SecretResponse.model_validate_json(response.text)
2 changes: 1 addition & 1 deletion infisical/api/delete_secret.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ def delete_secret_req(api_request: Session, options: DeleteSecretDTO) -> SecretR
},
)

return SecretResponse.parse_obj(response.json())
return SecretResponse.model_validate_json(response.text)
2 changes: 1 addition & 1 deletion infisical/api/get_secret.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ def get_secret_req(api_request: Session, options: GetSecretDTO) -> SecretRespons
},
)

return SecretResponse.parse_obj(response.json())
return SecretResponse.model_validate_json(response.text)
14 changes: 9 additions & 5 deletions infisical/api/get_secrets.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
from infisical.models.api import GetSecretsDTO, SecretsResponse
from typing import List, Tuple

from infisical.models.api import GetSecretsDTO, SecretImport, SecretsResponse
from infisical.models.models import Secret
from requests import Session


def get_secrets_req(api_request: Session, options: GetSecretsDTO) -> SecretsResponse:
def get_secrets_req(
api_request: Session, options: GetSecretsDTO
) -> Tuple[List[Secret], List[SecretImport]]:
"""Send request again Infisical API to fetch secrets.
See more information on https://infisical.com/docs/api-reference/endpoints/secrets/read

Expand All @@ -18,10 +23,9 @@ def get_secrets_req(api_request: Session, options: GetSecretsDTO) -> SecretsResp
"environment": options.environment,
"workspaceId": options.workspace_id,
"secretPath": options.path,
"include_imports": str(options.include_imports).lower()
"include_imports": str(options.include_imports).lower(),
},
)
data = SecretsResponse.parse_obj(response.json())
data = SecretsResponse.model_validate_json(response.text)

return (data.secrets if data.secrets else [], data.imports if data.imports else [])

2 changes: 1 addition & 1 deletion infisical/api/get_service_token_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ def get_service_token_data_req(
"""
response = api_request.get("/api/v2/service-token")

return GetServiceTokenDetailsResponse.parse_obj(response.json())
return GetServiceTokenDetailsResponse.model_validate_json(response.text)
2 changes: 1 addition & 1 deletion infisical/api/get_service_token_data_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ def get_service_token_data_key_req(
"""
response = api_request.get("/api/v3/service-token/me/key")

return GetServiceTokenKeyResponse.parse_obj(response.json())
return GetServiceTokenKeyResponse.model_validate_json(response.text)
6 changes: 4 additions & 2 deletions infisical/api/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import datetime
from typing import List, Optional
from typing import Optional

from pydantic import BaseModel, Field

Expand Down Expand Up @@ -27,12 +27,14 @@ class GetServiceTokenDetailsResponse(BaseModel):
updated_at: datetime = Field(..., alias="updatedAt")
v: int = Field(..., alias="__v")


class KeyData(BaseModel):
id: str = Field(..., alias="_id")
workspace: str
encrypted_key: str = Field(..., alias="encryptedKey")
public_key: str = Field(..., alias="publicKey")
nonce: str


class GetServiceTokenKeyResponse(BaseModel):
key: KeyData
key: KeyData
2 changes: 1 addition & 1 deletion infisical/api/update_secret.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ def update_secret_req(api_request: Session, options: UpdateSecretDTO) -> SecretR
},
)

return SecretResponse.parse_obj(response.json())
return SecretResponse.model_validate_json(response.text)
61 changes: 41 additions & 20 deletions infisical/client/infisicalclient.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from typing import Dict, Optional
from typing import Dict, List, Optional, Tuple

from infisical.api import create_api_request_with_auth
from infisical.constants import (
Expand All @@ -17,8 +17,13 @@
update_secret_helper,
)
from infisical.models.models import SecretBundle
from infisical.models.secret_service import ClientConfig
from infisical.models.secret_service import (
ClientConfig,
ServiceTokenCredentials,
ServiceTokenV3Credentials,
)
from infisical.utils.crypto import (
Base64String,
create_symmetric_key_helper,
decrypt_symmetric_helper,
encrypt_symmetric_helper,
Expand Down Expand Up @@ -49,37 +54,45 @@ def __init__(

self.client_config = ClientConfig(
auth_mode=AUTH_MODE_SERVICE_TOKEN,
credentials={"service_token_key": service_token_key},
credentials=ServiceTokenCredentials(
service_token_key=service_token_key
),
workspace_config=None,
cache_ttl=cache_ttl,
)

self.api_request = create_api_request_with_auth(site_url, service_token)

if token_json and token_json != "":
token_dict = json.loads(token_json)

self.client_config = ClientConfig(
auth_mode=AUTH_MODE_SERVICE_TOKEN_V3,
credentials={
"public_key": token_dict["publicKey"],
"private_key": token_dict["privateKey"]
},
cache_ttl=cache_ttl
credentials=ServiceTokenV3Credentials(
public_key=token_dict["publicKey"],
private_key=token_dict["privateKey"],
),
workspace_config=None,
cache_ttl=cache_ttl,
)

self.api_request = create_api_request_with_auth(site_url, token_dict["serviceToken"])
self.api_request = create_api_request_with_auth(
site_url, token_dict["serviceToken"]
)

self.debug = debug

def get_all_secrets(
self,
environment: str = "dev",
path: str = "/",
self,
environment: str = "dev",
path: str = "/",
include_imports: bool = True,
attach_to_os_environ: bool = False
):
attach_to_os_environ: bool = False,
) -> List[SecretBundle]:
"""Return all the secrets accessible by the instance of Infisical"""
return get_all_secrets_helper(self, environment, path, include_imports, attach_to_os_environ)
return get_all_secrets_helper(
self, environment, path, include_imports, attach_to_os_environ
)

def get_secret(
self,
Expand Down Expand Up @@ -140,7 +153,7 @@ def delete_secret(
type: Literal["shared", "personal"] = "shared",
environment: str = "dev",
path: str = "/",
):
) -> SecretBundle:
"""Delete secret with name `secret_name`

:param secret_name: Name of secret to delete
Expand All @@ -153,10 +166,18 @@ def create_symmetric_key(self) -> str:
"""Create a base64-encoded, 256-bit symmetric key"""
return create_symmetric_key_helper()

def encrypt_symmetric(self, plaintext: str, key: str):
def encrypt_symmetric(
self, plaintext: str, key: Base64String
) -> Tuple[Base64String, Base64String, Base64String]:
"""Encrypt the plaintext `plaintext` with the (base64) 256-bit secret key `key`"""
return encrypt_symmetric_helper(plaintext, key)

def decrypt_symmetric(self, ciphertext: str, key: str, iv: str, tag: str):
def decrypt_symmetric(
self,
ciphertext: Base64String,
key: Base64String,
iv: Base64String,
tag: Base64String,
) -> str:
"""Decrypt the ciphertext `ciphertext` with the (base64) 256-bit secret key `key`, provided `iv` and `tag`"""
return decrypt_symmetric_helper(ciphertext, key, iv, tag)
22 changes: 14 additions & 8 deletions infisical/helpers/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import os
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Union
from typing import TYPE_CHECKING, List, Union

from typing_extensions import Literal

Expand All @@ -12,7 +12,13 @@
from infisical.services.secret_service import SecretService


def get_all_secrets_helper(instance: "InfisicalClient", environment: str, path: str, include_imports: bool, attach_to_os_environ: bool):
def get_all_secrets_helper(
instance: "InfisicalClient",
environment: str,
path: str,
include_imports: bool,
attach_to_os_environ: bool,
) -> List[SecretBundle]:
try:
if not instance.client_config:
raise Exception("Failed to find client config")
Expand All @@ -31,14 +37,14 @@ def get_all_secrets_helper(instance: "InfisicalClient", environment: str, path:
environment=environment,
path=path,
workspace_key=instance.client_config.workspace_config.workspace_key,
include_imports=include_imports
include_imports=include_imports,
)

for secret_bundle in secret_bundles:
cache_key = f"{secret_bundle.type}-{secret_bundle.secret_name}"
instance.cache[cache_key] = secret_bundle
if attach_to_os_environ:
os.environ[secret_bundle.secret_name] = secret_bundle.secret_value
os.environ[secret_bundle.secret_name] = secret_bundle.secret_value or ""

return secret_bundles
except Exception as exc:
Expand All @@ -54,7 +60,7 @@ def get_secret_helper(
type: Literal["shared", "personal"],
environment: str,
path: str,
):
) -> SecretBundle:
cache_key = f"{type}-{secret_name}"
cached_secret: Union[SecretBundle, None] = None
try:
Expand Down Expand Up @@ -117,7 +123,7 @@ def create_secret_helper(
type: Literal["shared", "personal"],
environment: str,
path: str,
):
) -> SecretBundle:
try:
if not instance.client_config:
raise Exception("Failed to find client config")
Expand Down Expand Up @@ -159,7 +165,7 @@ def update_secret_helper(
type: Literal["shared", "personal"],
environment: str,
path: str,
):
) -> SecretBundle:
try:
if not instance.client_config:
raise Exception("Failed to find client config")
Expand Down Expand Up @@ -200,7 +206,7 @@ def delete_secret_helper(
type: Literal["shared", "personal"],
environment: str,
path: str,
):
) -> SecretBundle:
try:
if not instance.client_config:
raise Exception("Failed to find client config")
Expand Down
3 changes: 0 additions & 3 deletions infisical/helpers/secrets.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from datetime import datetime

from infisical.models.models import Secret, SecretBundle


Expand All @@ -16,5 +14,4 @@ def transform_secret_to_secret_bundle(
updated_at=secret.updated_at,
created_at=secret.created_at,
is_fallback=False,
last_fetched_at=datetime.now(),
)
1 change: 1 addition & 0 deletions infisical/models/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class SecretImport(BaseModel):
environment: str
secrets: List[Secret]


class SecretsResponse(BaseModel):
secrets: List[Secret]
imports: Optional[List[SecretImport]]
Expand Down
16 changes: 8 additions & 8 deletions infisical/models/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ class Secret(BaseModel):
id: str = Field(..., alias="_id")
version: int
workspace: str
user: Optional[str]
type: Literal["shared", "personal"]
environment: str
secret_key_ciphertext: str = Field(..., alias="secretKeyCiphertext")
Expand All @@ -20,19 +19,20 @@ class Secret(BaseModel):
secret_value_tag: str = Field(..., alias="secretValueTag")
created_at: datetime = Field(..., alias="createdAt")
updated_at: datetime = Field(..., alias="updatedAt")
user: Optional[str] = None


class SecretBundle(BaseModel):
secret_name: str
secret_value: Optional[str]
version: Optional[int]
workspace: Optional[str]
environment: Optional[str]
type: Optional[Literal["shared", "personal"]]
secret_value: Optional[str] = None
version: Optional[int] = None
workspace: Optional[str] = None
environment: Optional[str] = None
type: Optional[Literal["shared", "personal"]] = None
created_at: Optional[datetime] = Field(None, alias="createdAt")
updated_at: Optional[datetime] = Field(None, alias="updatedAt")
is_fallback: bool
last_fetched_at: datetime
is_fallback: bool = False
last_fetched_at: datetime = Field(default_factory=datetime.now)


class ServiceTokenData(BaseModel):
Expand Down
7 changes: 5 additions & 2 deletions infisical/models/secret_service.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
from typing import Dict, Optional, Union
from typing import Optional, Union

from pydantic import BaseModel
from requests import Session
from typing_extensions import Literal


class WorkspaceConfig(BaseModel):
workspace_id: str
workspace_key: str


class ServiceTokenCredentials(BaseModel):
service_token_key: str


class ServiceTokenV3Credentials(BaseModel):
public_key: str
private_key: str


class ClientConfig(BaseModel):
auth_mode: Literal["service_token", "service_token_v3"]
credentials: Union[ServiceTokenCredentials, ServiceTokenV3Credentials]
Expand Down
Loading