1password-secrets 0.0.1.dev255__tar.gz → 0.0.1.dev260__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.
Files changed (25) hide show
  1. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/1password_secrets.egg-info/PKG-INFO +1 -1
  2. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/PKG-INFO +1 -1
  3. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/commands.py +66 -22
  4. 1password_secrets-0.0.1.dev260/onepassword_secrets/envs.py +53 -0
  5. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/op.py +8 -1
  6. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/prompts.py +7 -1
  7. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/utils.py +11 -1
  8. 1password_secrets-0.0.1.dev255/onepassword_secrets/envs.py +0 -20
  9. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/1password_secrets.egg-info/SOURCES.txt +0 -0
  10. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/1password_secrets.egg-info/dependency_links.txt +0 -0
  11. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/1password_secrets.egg-info/entry_points.txt +0 -0
  12. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/1password_secrets.egg-info/requires.txt +0 -0
  13. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/1password_secrets.egg-info/top_level.txt +0 -0
  14. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/README.md +0 -0
  15. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/__init__.py +0 -0
  16. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/__main__.py +0 -0
  17. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/cli.py +0 -0
  18. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/constants.py +0 -0
  19. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/errors.py +0 -0
  20. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/fly.py +0 -0
  21. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/git.py +0 -0
  22. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/onepassword_secrets/logs.py +0 -0
  23. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/pyproject.toml +0 -0
  24. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/setup.cfg +0 -0
  25. {1password_secrets-0.0.1.dev255 → 1password_secrets-0.0.1.dev260}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: 1password-secrets
3
- Version: 0.0.1.dev255
3
+ Version: 0.0.1.dev260
4
4
  Summary: 1password-secrets is a set of utilities to sync 1password secrets.
5
5
  Home-page: https://github.com/significa/fly-1password-secrets
6
6
  Author: Significa
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: 1password-secrets
3
- Version: 0.0.1.dev255
3
+ Version: 0.0.1.dev260
4
4
  Summary: 1password-secrets is a set of utilities to sync 1password secrets.
5
5
  Home-page: https://github.com/significa/fly-1password-secrets
6
6
  Author: Significa
@@ -9,7 +9,8 @@ from tempfile import NamedTemporaryFile
9
9
  from rich.panel import Panel
10
10
 
11
11
  from .constants import DATE_FORMAT, DEFAULT_ENV_FILE_NAME, DEFAULT_REMOTE_NAME
12
- from .envs import get_secrets_from_envs
12
+ from .envs import format_duplicate_keys, get_duplicate_keys_from_envs, get_secrets_from_envs
13
+ from .errors import UserError
13
14
  from .fly import update_fly_secrets
14
15
  from .git import get_secret_name_label_from_current_directory
15
16
  from .logs import console, debug_command, logger
@@ -29,7 +30,9 @@ from .utils import get_file_contents
29
30
  def import_1password_secrets_to_fly(app_id, vault=None):
30
31
  item_id = get_1password_env_file_item_id(f"fly:{app_id}", vault=vault)
31
32
 
32
- secrets = get_secrets_from_envs(get_envs_from_1password(item_id, vault=vault))
33
+ secrets = get_secrets_from_envs(
34
+ get_envs_from_1password(item_id, vault=vault), source="the 1Password item"
35
+ )
33
36
 
34
37
  logger.debug(f"Secrets loaded from env: {json.dumps(secrets, indent=2)}\n")
35
38
 
@@ -39,11 +42,48 @@ def import_1password_secrets_to_fly(app_id, vault=None):
39
42
  update_1password_custom_field(item_id, "last imported at", now_formatted, vault=vault)
40
43
 
41
44
 
45
+ def open_editor(file_path):
46
+ console.print()
47
+ console.print(
48
+ Panel(
49
+ "[bold]Edit the secrets in your editor, then save and close the file to continue.[/bold]\n"
50
+ "[dim]Waiting for editor to close...[/dim]",
51
+ title="Editor",
52
+ border_style="cyan",
53
+ )
54
+ )
55
+
56
+ editor_command_args = ["code", "--wait", "--disable-extensions", file_path]
57
+ debug_command(editor_command_args)
58
+ editor_output = subprocess.check_output(editor_command_args) # noqa: S603
59
+ debug_command(editor_command_args, output=editor_output, returncode=0)
60
+
61
+ console.print("[green]Editor closed.[/green]")
62
+ console.print()
63
+
64
+
42
65
  def edit_1password_fly_secrets(app_id, vault=None):
43
66
  item_id = get_1password_env_file_item_id(f"fly:{app_id}", vault=vault)
44
67
 
45
68
  current_raw_secrets = get_envs_from_1password(item_id, vault=vault)
46
69
 
70
+ # Unlike the other commands, editing is how duplicates get fixed, so only warn here.
71
+ # Saving is still blocked until the edited file no longer has duplicates.
72
+ duplicate_keys = get_duplicate_keys_from_envs(current_raw_secrets)
73
+ if duplicate_keys:
74
+ console.print()
75
+ console.print(
76
+ Panel(
77
+ "The 1Password item defines the following keys more than once: "
78
+ f"{format_duplicate_keys(duplicate_keys)}\n"
79
+ "[dim]Remove the duplicates in the editor, saving is blocked until you do.[/dim]",
80
+ title="Warning",
81
+ border_style="yellow",
82
+ )
83
+ )
84
+
85
+ get_secrets_from_envs(current_raw_secrets, source="the 1Password item", allow_duplicates=True)
86
+
47
87
  # delete=False so that the file is still around for the editor to open on every platform,
48
88
  # cleaned up in the finally block below no matter how we leave this function.
49
89
  file = NamedTemporaryFile("w+", suffix=".env", delete=False) # noqa: SIM115
@@ -51,34 +91,29 @@ def edit_1password_fly_secrets(app_id, vault=None):
51
91
  try:
52
92
  with file:
53
93
  file.writelines(current_raw_secrets)
54
- file.flush()
55
-
56
- console.print()
57
- console.print(
58
- Panel(
59
- "[bold]Edit the secrets in your editor, then save and close the file to continue.[/bold]\n"
60
- "[dim]Waiting for editor to close...[/dim]",
61
- title="Editor",
62
- border_style="cyan",
63
- )
64
- )
65
94
 
66
- editor_command_args = ["code", "--wait", "--disable-extensions", file.name]
67
- debug_command(editor_command_args)
68
- editor_output = subprocess.check_output(editor_command_args) # noqa: S603
69
- debug_command(editor_command_args, output=editor_output, returncode=0)
95
+ # Keep reopening the editor on the same file until its contents are valid,
96
+ # so a mistake (e.g. a duplicate key) does not throw away the rest of the edits.
97
+ while True:
98
+ open_editor(file.name)
70
99
 
71
- console.print("[green]Editor closed.[/green]")
72
- console.print()
100
+ with open(file.name) as edited_file:
101
+ new_raw_secrets = edited_file.read()
73
102
 
74
- file.seek(0)
75
- new_raw_secrets = file.read()
103
+ try:
104
+ get_secrets_from_envs(new_raw_secrets, source="the edited file")
105
+ break
106
+ except UserError:
107
+ console.print()
108
+ if not boolean_prompt("Reopen the editor to fix it", default=True):
109
+ raise
76
110
 
77
111
  update_1password_secrets(
78
112
  item_id,
79
113
  new_raw_secrets=new_raw_secrets,
80
114
  previous_raw_secrets=current_raw_secrets,
81
115
  vault=vault,
116
+ allow_previous_duplicates=True,
82
117
  )
83
118
  finally:
84
119
  try:
@@ -96,12 +131,14 @@ def pull_local_secrets(remote=DEFAULT_REMOTE_NAME, vault=None):
96
131
  item_id = get_1password_env_file_item_id(secret_note_label, vault=vault)
97
132
 
98
133
  secrets = get_envs_from_1password(item_id, vault=vault)
134
+ get_secrets_from_envs(secrets, source="the 1Password item")
99
135
 
100
136
  env_file_name = get_filename_from_1password(item_id, vault=vault) or DEFAULT_ENV_FILE_NAME
101
137
 
102
138
  previous_raw_secrets = get_file_contents(env_file_name, raise_if_not_found=False)
103
139
 
104
140
  if previous_raw_secrets:
141
+ get_secrets_from_envs(previous_raw_secrets, source=env_file_name)
105
142
  diff = prompt_secret_diff(
106
143
  previous_raw_secrets=previous_raw_secrets,
107
144
  new_raw_secrets=secrets,
@@ -126,8 +163,14 @@ def push_local_secrets(remote=DEFAULT_REMOTE_NAME, vault=None):
126
163
  env_file_name = get_filename_from_1password(item_id) or DEFAULT_ENV_FILE_NAME
127
164
 
128
165
  secrets = get_file_contents(env_file_name, raise_if_not_found=True)
166
+ get_secrets_from_envs(secrets, source=env_file_name)
129
167
 
130
- update_1password_secrets(item_id, secrets, vault=vault)
168
+ previous_raw_secrets = get_envs_from_1password(item_id, vault=vault)
169
+ get_secrets_from_envs(previous_raw_secrets, source="the 1Password item")
170
+
171
+ update_1password_secrets(
172
+ item_id, secrets, previous_raw_secrets=previous_raw_secrets, vault=vault
173
+ )
131
174
 
132
175
  console.print(
133
176
  f"[bold green]Successfully pushed secrets from {env_file_name} to 1Password[/bold green]"
@@ -138,6 +181,7 @@ def create_local_secrets(secrets_file_path, vault=None, remote=DEFAULT_REMOTE_NA
138
181
  secret_note_label = get_secret_name_label_from_current_directory(remote=remote)
139
182
 
140
183
  raw_secrets = get_file_contents(secrets_file_path, raise_if_not_found=True)
184
+ get_secrets_from_envs(raw_secrets, source=secrets_file_path)
141
185
 
142
186
  title = f"{secrets_file_path} local development {secret_note_label}"
143
187
 
@@ -0,0 +1,53 @@
1
+ from collections import defaultdict
2
+ from io import StringIO
3
+
4
+ from dotenv import dotenv_values
5
+ from dotenv.parser import parse_stream
6
+
7
+ from .errors import raise_error
8
+
9
+
10
+ def get_duplicate_keys_from_envs(input: str) -> dict[str, list[int]]:
11
+ """Map each key defined more than once to the line numbers where it is defined."""
12
+ lines_by_key = defaultdict(list)
13
+
14
+ for binding in parse_stream(StringIO(input)):
15
+ if binding.key is not None:
16
+ # The parser attaches leading blank lines to the binding that follows them,
17
+ # so skip past them to report the line the key is actually on.
18
+ original = binding.original.string
19
+ leading_whitespace = original[: len(original) - len(original.lstrip())]
20
+ line_offset = leading_whitespace.replace("\r\n", "\n").replace("\r", "\n").count("\n")
21
+ lines_by_key[binding.key].append(binding.original.line + line_offset)
22
+
23
+ return {key: lines for key, lines in lines_by_key.items() if len(lines) > 1}
24
+
25
+
26
+ def format_duplicate_keys(duplicate_keys: dict[str, list[int]]) -> str:
27
+ return ", ".join(
28
+ f"{key} (lines {', '.join(str(line) for line in lines)})"
29
+ for key, lines in duplicate_keys.items()
30
+ )
31
+
32
+
33
+ def get_secrets_from_envs(input: str, source: str = "env file", allow_duplicates: bool = False):
34
+ duplicate_keys = get_duplicate_keys_from_envs(input)
35
+
36
+ if len(duplicate_keys) > 0 and not allow_duplicates:
37
+ raise_error(
38
+ f"Failed to parse {source}, the following keys are defined more than once: "
39
+ f"{format_duplicate_keys(duplicate_keys)}. Remove the duplicates before proceeding."
40
+ )
41
+
42
+ secrets = dotenv_values(stream=StringIO(input))
43
+
44
+ keys_with_values_null_values = [key for key, value in secrets.items() if value is None]
45
+
46
+ if len(keys_with_values_null_values) > 0:
47
+ raise_error(
48
+ "Failed to parse {}, values for the following keys are null: {}".format(
49
+ source, ", ".join(keys_with_values_null_values)
50
+ )
51
+ )
52
+
53
+ return secrets
@@ -155,13 +155,20 @@ def create_1password_secrets(file_path, raw_secrets, title, vault=None):
155
155
  )
156
156
 
157
157
 
158
- def update_1password_secrets(item_id, new_raw_secrets, previous_raw_secrets=None, vault=None):
158
+ def update_1password_secrets(
159
+ item_id,
160
+ new_raw_secrets,
161
+ previous_raw_secrets=None,
162
+ vault=None,
163
+ allow_previous_duplicates=False,
164
+ ):
159
165
  if previous_raw_secrets is None:
160
166
  previous_raw_secrets = get_envs_from_1password(item_id)
161
167
 
162
168
  diff = prompt_secret_diff(
163
169
  previous_raw_secrets=previous_raw_secrets,
164
170
  new_raw_secrets=new_raw_secrets,
171
+ allow_previous_duplicates=allow_previous_duplicates,
165
172
  )
166
173
 
167
174
  if diff == SecretDiff.IDENTICAL:
@@ -42,13 +42,19 @@ def prompt_secret_diff(
42
42
  new_raw_secrets,
43
43
  apply_prompt: str = "Apply these changes",
44
44
  cosmetic_prompt: str = "Apply these changes anyway",
45
+ allow_previous_duplicates: bool = False,
45
46
  ) -> SecretDiff:
46
47
  """Show the diff between two env files and ask for confirmation when relevant.
47
48
 
48
49
  Returns the kind of difference found. Nothing is prompted when the contents are
49
50
  equivalent - it is up to the caller to decide what to do in that case.
51
+
52
+ `allow_previous_duplicates` lets the previous contents define a key more than once,
53
+ so that a broken env file can still be replaced with a fixed one.
50
54
  """
51
- previous_parsed_secrets = get_secrets_from_envs(previous_raw_secrets)
55
+ previous_parsed_secrets = get_secrets_from_envs(
56
+ previous_raw_secrets, allow_duplicates=allow_previous_duplicates
57
+ )
52
58
  new_parsed_secrets = get_secrets_from_envs(new_raw_secrets)
53
59
 
54
60
  previous_keys = set(previous_parsed_secrets.keys())
@@ -1,3 +1,5 @@
1
+ from typing import Literal, overload
2
+
1
3
  from .errors import raise_error
2
4
 
3
5
 
@@ -8,7 +10,15 @@ def first(iterable):
8
10
  return None
9
11
 
10
12
 
11
- def get_file_contents(filepath, raise_if_not_found=True):
13
+ @overload
14
+ def get_file_contents(filepath, raise_if_not_found: Literal[True] = True) -> str: ...
15
+
16
+
17
+ @overload
18
+ def get_file_contents(filepath, raise_if_not_found: bool) -> str | None: ...
19
+
20
+
21
+ def get_file_contents(filepath, raise_if_not_found=True) -> str | None:
12
22
  try:
13
23
  with open(filepath) as file:
14
24
  return file.read()
@@ -1,20 +0,0 @@
1
- from io import StringIO
2
-
3
- from dotenv import dotenv_values
4
-
5
- from .errors import raise_error
6
-
7
-
8
- def get_secrets_from_envs(input: str):
9
- secrets = dotenv_values(stream=StringIO(input))
10
-
11
- keys_with_values_null_values = [key for key, value in secrets.items() if value is None]
12
-
13
- if len(keys_with_values_null_values) > 0:
14
- raise_error(
15
- "Failed to parse env file, values for the following keys are null: {}".format(
16
- ", ".join(keys_with_values_null_values)
17
- )
18
- )
19
-
20
- return secrets