roleroster 0.1.0__py3-none-any.whl
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.
- roleroster/__init__.py +2 -0
- roleroster/__main__.py +5 -0
- roleroster/awsconfig.py +235 -0
- roleroster/browsers.py +142 -0
- roleroster/cli.py +56 -0
- roleroster/confluence.py +405 -0
- roleroster/doctor.py +266 -0
- roleroster/granted.py +110 -0
- roleroster/helptext.py +102 -0
- roleroster/init.py +199 -0
- roleroster/onboarding.py +569 -0
- roleroster/paths.py +42 -0
- roleroster/preset.py +182 -0
- roleroster/profiles.py +560 -0
- roleroster/settings.py +46 -0
- roleroster/shell/roleroster.sh +398 -0
- roleroster/ui.py +330 -0
- roleroster/vault.py +83 -0
- roleroster-0.1.0.dist-info/METADATA +124 -0
- roleroster-0.1.0.dist-info/RECORD +23 -0
- roleroster-0.1.0.dist-info/WHEEL +4 -0
- roleroster-0.1.0.dist-info/entry_points.txt +3 -0
- roleroster-0.1.0.dist-info/licenses/LICENSE +21 -0
roleroster/__init__.py
ADDED
roleroster/__main__.py
ADDED
roleroster/awsconfig.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Popula o ~/.aws/config com os perfis de switchRole que estao no Confluence.
|
|
2
|
+
|
|
3
|
+
O script so mexe num bloco delimitado por marcadores, dentro da secao ACCOUNTS.
|
|
4
|
+
Tudo fora dele (sso-session, o perfil base, perfis SSO diretos e a secao MANUAL, onde ficam os
|
|
5
|
+
perfis que voce escreve a mao) fica exatamente como esta. O Granted continua
|
|
6
|
+
lendo o config padrao da AWS, entao nada muda no uso.
|
|
7
|
+
|
|
8
|
+
O arquivo e o de sempre (~/.aws/config), ou o que estiver em AWS_CONFIG_FILE:
|
|
9
|
+
com essa variavel da para testar sem encostar no config que voce ja tem.
|
|
10
|
+
Se o arquivo nao existir, ele e criado.
|
|
11
|
+
|
|
12
|
+
Cada perfil gerado fica assim:
|
|
13
|
+
|
|
14
|
+
[profile <chave que vem do Confluence>]
|
|
15
|
+
source_profile = <perfil base>
|
|
16
|
+
role_arn = arn:aws:iam::<aws_account_id>:role/<role_name>
|
|
17
|
+
region = <region>
|
|
18
|
+
|
|
19
|
+
Antes de gravar, a versao anterior do config fica em
|
|
20
|
+
<pasta do roleroster>/backup/config.prev (fora do ~/.aws).
|
|
21
|
+
|
|
22
|
+
Quem chama isto e o `role sync` (e, antes de escolher o perfil, o `role sso` e o `role console`).
|
|
23
|
+
"""
|
|
24
|
+
import os
|
|
25
|
+
import re
|
|
26
|
+
import shutil
|
|
27
|
+
import tempfile
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
from . import paths, settings
|
|
31
|
+
from .confluence import (
|
|
32
|
+
ConfluenceError,
|
|
33
|
+
fetch_candidates,
|
|
34
|
+
parse_profiles,
|
|
35
|
+
require_config,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
BEGIN = "# >>> confluence-sync (gerado pelo script, nao edite) >>>"
|
|
39
|
+
END = "# <<< confluence-sync <<<"
|
|
40
|
+
ACCOUNTS_HEADER = "# ------------------ ACCOUNTS ------------------"
|
|
41
|
+
MANUAL_HEADER = "# ------------------ MANUAL ------------------"
|
|
42
|
+
MANUAL_NOTE = "# Perfis escritos a mao ficam aqui: o sync nunca altera nem apaga o que esta abaixo."
|
|
43
|
+
CACHE_DIR = paths.backup_dir()
|
|
44
|
+
PROFILE_NAME_RE = re.compile(r"[A-Za-z0-9_.@-]+")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Selection:
|
|
48
|
+
"""Perfis que entram no config e o que ficou de fora, por motivo."""
|
|
49
|
+
|
|
50
|
+
def __init__(self):
|
|
51
|
+
self.profiles = []
|
|
52
|
+
self.duplicates = 0
|
|
53
|
+
self.invalid = []
|
|
54
|
+
self.reserved = []
|
|
55
|
+
self.conflicts = []
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def select_profiles(candidates, reserved_names):
|
|
59
|
+
"""Escolhe um perfil por nome, descartando o que nao e seguro gravar.
|
|
60
|
+
|
|
61
|
+
Os ativos vem antes dos inativos (que so chegam aqui com `role sso -i`).
|
|
62
|
+
|
|
63
|
+
- espacos no nome viram hifen (`Drive Match` -> `Drive-Match`)
|
|
64
|
+
- nome ainda fora de [A-Za-z0-9_.@-]: descartado
|
|
65
|
+
- nome que ja existe fora do bloco gerado: descartado (o manual vence)
|
|
66
|
+
- mesmo nome com ARNs diferentes: descartado por inteiro, para nunca gravar
|
|
67
|
+
o ARN errado
|
|
68
|
+
- mesmo nome e mesmo ARN em varias paginas: conta como duplicado
|
|
69
|
+
"""
|
|
70
|
+
result = Selection()
|
|
71
|
+
chosen = {}
|
|
72
|
+
conflicting = set()
|
|
73
|
+
ordered = sorted(
|
|
74
|
+
candidates,
|
|
75
|
+
key=lambda c: (c.get("inactive", False), c["page_title"], "-".join(c["profile"].split())),
|
|
76
|
+
)
|
|
77
|
+
for candidate in ordered:
|
|
78
|
+
name = "-".join(candidate["profile"].split())
|
|
79
|
+
inactive = candidate.get("inactive", False)
|
|
80
|
+
if not PROFILE_NAME_RE.fullmatch(name):
|
|
81
|
+
_remember(result.invalid, name)
|
|
82
|
+
elif name in reserved_names:
|
|
83
|
+
_remember(result.reserved, name)
|
|
84
|
+
elif name in chosen:
|
|
85
|
+
if chosen[name]["role_arn"] == candidate["role_arn"]:
|
|
86
|
+
result.duplicates += 1
|
|
87
|
+
else:
|
|
88
|
+
conflicting.add(name)
|
|
89
|
+
else:
|
|
90
|
+
chosen[name] = {
|
|
91
|
+
"profile": name,
|
|
92
|
+
"page_title": candidate["page_title"],
|
|
93
|
+
"role_arn": candidate["role_arn"],
|
|
94
|
+
"region": candidate.get("region", ""),
|
|
95
|
+
"inactive": inactive,
|
|
96
|
+
}
|
|
97
|
+
result.conflicts = sorted(conflicting)
|
|
98
|
+
result.profiles = [p for n, p in chosen.items() if n not in conflicting]
|
|
99
|
+
return result
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _remember(items, name):
|
|
103
|
+
if name not in items:
|
|
104
|
+
items.append(name)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def render_block(profiles, source_profile):
|
|
108
|
+
lines = [BEGIN, "# Fonte: paginas do Confluence, secao Switch Role.", ""]
|
|
109
|
+
current_title = None
|
|
110
|
+
for profile in profiles:
|
|
111
|
+
title = " ".join(profile["page_title"].split())
|
|
112
|
+
if profile.get("inactive"):
|
|
113
|
+
title += " [inativo]"
|
|
114
|
+
if title != current_title:
|
|
115
|
+
current_title = title
|
|
116
|
+
lines.append(f"# --- {title}")
|
|
117
|
+
lines.append("")
|
|
118
|
+
lines.append(f"[profile {profile['profile']}]")
|
|
119
|
+
lines.append(f"source_profile = {source_profile}")
|
|
120
|
+
lines.append(f"role_arn = {profile['role_arn']}")
|
|
121
|
+
if profile["region"]:
|
|
122
|
+
lines.append(f"region = {profile['region']}")
|
|
123
|
+
lines.append("")
|
|
124
|
+
lines.append(END)
|
|
125
|
+
return "\n".join(lines) + "\n"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def split_managed(text):
|
|
129
|
+
"""Devolve (antes, depois) do bloco gerado, ou (texto, None) se nao houver."""
|
|
130
|
+
start = text.find(BEGIN)
|
|
131
|
+
end = text.find(END)
|
|
132
|
+
if start == -1 and end == -1:
|
|
133
|
+
return text, None
|
|
134
|
+
if start == -1 or end == -1 or end < start:
|
|
135
|
+
raise ConfluenceError("marcadores do bloco gerado estao corrompidos no config")
|
|
136
|
+
after = text[end + len(END):]
|
|
137
|
+
return text[:start], after[1:] if after.startswith("\n") else after
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def managed_text(text):
|
|
141
|
+
start = text.find(BEGIN)
|
|
142
|
+
end = text.find(END)
|
|
143
|
+
return text[start:end] if start != -1 and end > start else ""
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def source_profile():
|
|
147
|
+
"""Perfil base dos Switch Roles: o que o usuario escolheu, o do preset ou "roleroster-base"."""
|
|
148
|
+
return settings.get("base_profile")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def default_config_path():
|
|
152
|
+
"""~/.aws/config, ou o arquivo de AWS_CONFIG_FILE (a AWS CLI e o Granted leem o mesmo)."""
|
|
153
|
+
return Path(os.environ.get("AWS_CONFIG_FILE") or Path.home() / ".aws" / "config").expanduser()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def apply_block(text, block):
|
|
157
|
+
"""Poe o bloco gerado no config e garante os cabecalhos ACCOUNTS e MANUAL.
|
|
158
|
+
|
|
159
|
+
O bloco novo vai logo abaixo de ACCOUNTS (o cabecalho e criado se faltar) e
|
|
160
|
+
a secao MANUAL logo abaixo do bloco. So o que esta entre os marcadores muda.
|
|
161
|
+
"""
|
|
162
|
+
before, after = split_managed(text)
|
|
163
|
+
if after is None and ACCOUNTS_HEADER in text:
|
|
164
|
+
cut = text.index(ACCOUNTS_HEADER) + len(ACCOUNTS_HEADER)
|
|
165
|
+
tail = text[cut:].lstrip("\n")
|
|
166
|
+
before, after = text[:cut] + "\n\n", ("\n" + tail if tail else "")
|
|
167
|
+
elif after is None:
|
|
168
|
+
head = text.rstrip("\n")
|
|
169
|
+
before, after = head + ("\n\n" if head else "") + ACCOUNTS_HEADER + "\n\n", ""
|
|
170
|
+
if MANUAL_HEADER not in before + after:
|
|
171
|
+
block += f"\n{MANUAL_HEADER}\n{MANUAL_NOTE}\n" + ("\n" if after.strip() else "")
|
|
172
|
+
return before + block + after
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def outside_block_names(text):
|
|
176
|
+
before, after = split_managed(text)
|
|
177
|
+
return {p["profile"] for p in parse_profiles(before + (after or ""))}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def change_counts(old_text, new_text):
|
|
181
|
+
old = {p["profile"]: p for p in parse_profiles(managed_text(old_text))}
|
|
182
|
+
new = {p["profile"]: p for p in parse_profiles(managed_text(new_text))}
|
|
183
|
+
added = len(new.keys() - old.keys())
|
|
184
|
+
removed = len(old.keys() - new.keys())
|
|
185
|
+
changed = sum(1 for n in new.keys() & old.keys() if new[n] != old[n])
|
|
186
|
+
return added, removed, changed
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def write_atomic(path, text):
|
|
190
|
+
mode = path.stat().st_mode & 0o777 if path.exists() else 0o644
|
|
191
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
192
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".config.")
|
|
193
|
+
try:
|
|
194
|
+
with os.fdopen(fd, "w") as handle:
|
|
195
|
+
handle.write(text)
|
|
196
|
+
os.chmod(tmp, mode)
|
|
197
|
+
os.replace(tmp, path)
|
|
198
|
+
except BaseException:
|
|
199
|
+
os.unlink(tmp)
|
|
200
|
+
raise
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class SyncPlan:
|
|
204
|
+
"""O que o sync faria: o texto novo do config e as contagens."""
|
|
205
|
+
|
|
206
|
+
def __init__(self, old_text, new_text, selection, candidates, stats):
|
|
207
|
+
self.old_text = old_text
|
|
208
|
+
self.new_text = new_text
|
|
209
|
+
self.selection = selection
|
|
210
|
+
self.candidates = candidates
|
|
211
|
+
self.stats = stats
|
|
212
|
+
self.added, self.removed, self.changed = change_counts(old_text, new_text)
|
|
213
|
+
|
|
214
|
+
@property
|
|
215
|
+
def has_changes(self):
|
|
216
|
+
return self.new_text != self.old_text
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def plan_sync(config_path, source_profile, squad_ids, include_inactive=False):
|
|
220
|
+
"""Le o Confluence e calcula o novo config. Nao grava nada."""
|
|
221
|
+
old_text = config_path.read_text() if config_path.exists() else ""
|
|
222
|
+
base, auth = require_config()
|
|
223
|
+
candidates, stats = fetch_candidates(base, auth, squad_ids, include_inactive)
|
|
224
|
+
selection = select_profiles(candidates, outside_block_names(old_text))
|
|
225
|
+
new_text = apply_block(old_text, render_block(selection.profiles, source_profile))
|
|
226
|
+
return SyncPlan(old_text, new_text, selection, candidates, stats)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def write_config(config_path, plan):
|
|
230
|
+
"""Guarda a versao anterior fora do ~/.aws (se havia uma) e grava o config novo."""
|
|
231
|
+
if config_path.exists():
|
|
232
|
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
233
|
+
CACHE_DIR.chmod(0o700)
|
|
234
|
+
shutil.copy2(config_path, CACHE_DIR / "config.prev")
|
|
235
|
+
write_atomic(config_path, plan.new_text)
|
roleroster/browsers.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Navegadores do console e do login SSO, e o modo "visitante" do console.
|
|
2
|
+
|
|
3
|
+
Navegadores aceitos por enquanto: Chrome, Brave, Firefox e Edge.
|
|
4
|
+
|
|
5
|
+
Como cada conta abre no console (ROLEROSTER_CONSOLE_MODE):
|
|
6
|
+
|
|
7
|
+
profile um perfil fixo do navegador para todas as contas (--browser-profile do Granted)
|
|
8
|
+
account um perfil por conta, o padrao do Granted (cria um perfil novo para cada conta)
|
|
9
|
+
guest uma janela isolada a cada abertura, num diretorio de dados descartavel:
|
|
10
|
+
nada entra no seletor de perfis e varias contas ficam abertas ao mesmo tempo,
|
|
11
|
+
porque cada janela tem os proprios cookies (so Chrome, Brave e Edge)
|
|
12
|
+
|
|
13
|
+
Firefox nao usa nenhum desses: o Granted abre cada conta num container (extensao Granted).
|
|
14
|
+
"""
|
|
15
|
+
import os
|
|
16
|
+
import shutil
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
import time
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from . import paths
|
|
23
|
+
|
|
24
|
+
BROWSERS = (
|
|
25
|
+
("chrome", "Google Chrome"),
|
|
26
|
+
("brave", "Brave"),
|
|
27
|
+
("firefox", "Firefox"),
|
|
28
|
+
("edge", "Microsoft Edge"),
|
|
29
|
+
)
|
|
30
|
+
LABELS = dict(BROWSERS)
|
|
31
|
+
CHROMIUM_FAMILY = ("chrome", "brave", "edge")
|
|
32
|
+
FIREFOX_ADDON_URL = "https://addons.mozilla.org/en-GB/firefox/addon/granted"
|
|
33
|
+
|
|
34
|
+
MODES = (
|
|
35
|
+
("profile", "Perfil fixo", "um perfil para todas as contas"),
|
|
36
|
+
("guest", "Visitante", "janela isolada, sem perfil"),
|
|
37
|
+
("account", "Um perfil por conta", "padrão do Granted"),
|
|
38
|
+
)
|
|
39
|
+
DEFAULT_MODE = "profile"
|
|
40
|
+
DEFAULT_PROFILE_NAME = "AWS"
|
|
41
|
+
GUEST_MAX_AGE = 2 * 24 * 3600 # diretorios de janelas visitantes mais velhos que isto sao apagados
|
|
42
|
+
|
|
43
|
+
MAC_EXECUTABLES = {
|
|
44
|
+
"chrome": "Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
45
|
+
"brave": "Brave Browser.app/Contents/MacOS/Brave Browser",
|
|
46
|
+
"firefox": "Firefox.app/Contents/MacOS/firefox",
|
|
47
|
+
"edge": "Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
|
48
|
+
}
|
|
49
|
+
LINUX_COMMANDS = {
|
|
50
|
+
"chrome": ("google-chrome", "google-chrome-stable"),
|
|
51
|
+
"brave": ("brave-browser", "brave"),
|
|
52
|
+
"firefox": ("firefox",),
|
|
53
|
+
"edge": ("microsoft-edge", "microsoft-edge-stable"),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def find(key):
|
|
58
|
+
"""Caminho do executavel do navegador, ou None se nao estiver instalado."""
|
|
59
|
+
if sys.platform == "darwin":
|
|
60
|
+
for base in (Path("/Applications"), Path.home() / "Applications"):
|
|
61
|
+
candidate = base / MAC_EXECUTABLES[key]
|
|
62
|
+
if candidate.exists():
|
|
63
|
+
return str(candidate)
|
|
64
|
+
return None
|
|
65
|
+
if sys.platform.startswith("linux"):
|
|
66
|
+
for command in LINUX_COMMANDS[key]:
|
|
67
|
+
found = shutil.which(command)
|
|
68
|
+
if found:
|
|
69
|
+
return found
|
|
70
|
+
return None # Windows: ainda nao suportado
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def installed():
|
|
74
|
+
"""Lista de (chave, rotulo, caminho) dos navegadores encontrados, na ordem de BROWSERS."""
|
|
75
|
+
found = []
|
|
76
|
+
for key, label in BROWSERS:
|
|
77
|
+
path = find(key)
|
|
78
|
+
if path:
|
|
79
|
+
found.append((key, label, path))
|
|
80
|
+
return found
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def mode_label(mode):
|
|
84
|
+
return next((label for key, label, _ in MODES if key == mode), mode)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# ---------------------------------------------------------------- modo visitante
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def guest_dir(base=None, now=None):
|
|
91
|
+
"""Cria o diretorio de dados descartavel de uma janela (permissao 700)."""
|
|
92
|
+
base = base or paths.home() / "browser"
|
|
93
|
+
base.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
94
|
+
stamp = int(now if now is not None else time.time())
|
|
95
|
+
for attempt in range(1000):
|
|
96
|
+
candidate = base / f"visitante-{stamp}-{os.getpid()}-{attempt}"
|
|
97
|
+
try:
|
|
98
|
+
candidate.mkdir(mode=0o700)
|
|
99
|
+
return candidate
|
|
100
|
+
except FileExistsError:
|
|
101
|
+
continue
|
|
102
|
+
raise OSError("não consegui criar o diretório da janela")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def launch_command(browser_path, data_dir, url):
|
|
106
|
+
"""Comando que abre `url` numa instancia nova do navegador, com dados proprios.
|
|
107
|
+
|
|
108
|
+
No macOS, `open -n` abre uma instancia nova e traz a janela para a frente.
|
|
109
|
+
"""
|
|
110
|
+
flags = [f"--user-data-dir={data_dir}", "--no-first-run", "--no-default-browser-check", url]
|
|
111
|
+
if sys.platform == "darwin" and ".app/Contents/MacOS/" in browser_path:
|
|
112
|
+
bundle = browser_path.split("/Contents/MacOS/")[0]
|
|
113
|
+
return ["open", "-n", "-a", bundle, "--args", *flags]
|
|
114
|
+
return [browser_path, *flags]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def cleanup_old(base=None, max_age=GUEST_MAX_AGE, now=None):
|
|
118
|
+
"""Apaga os diretorios de janelas visitantes antigas. Devolve quantos apagou."""
|
|
119
|
+
base = base or paths.home() / "browser"
|
|
120
|
+
if not base.is_dir():
|
|
121
|
+
return 0
|
|
122
|
+
limit = (now if now is not None else time.time()) - max_age
|
|
123
|
+
removed = 0
|
|
124
|
+
for entry in base.iterdir():
|
|
125
|
+
if entry.name.startswith("visitante-") and entry.is_dir() and entry.stat().st_mtime < limit:
|
|
126
|
+
shutil.rmtree(entry, ignore_errors=True)
|
|
127
|
+
removed += 1
|
|
128
|
+
return removed
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def open_guest(url, browser_path, base=None):
|
|
132
|
+
"""Abre `url` numa janela visitante. So Chromium (Chrome, Brave, Edge)."""
|
|
133
|
+
if not url.startswith("https://"):
|
|
134
|
+
raise ValueError("a URL do console precisa começar com https://")
|
|
135
|
+
cleanup_old(base)
|
|
136
|
+
data_dir = guest_dir(base)
|
|
137
|
+
subprocess.Popen(
|
|
138
|
+
launch_command(browser_path, data_dir, url),
|
|
139
|
+
start_new_session=True,
|
|
140
|
+
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
141
|
+
)
|
|
142
|
+
return data_dir
|
roleroster/cli.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Comando `role` (e `roleroster`): ponto de entrada da lib.
|
|
2
|
+
|
|
3
|
+
Os comandos que mudam o terminal (sso, console, assume) vivem numa funcao de
|
|
4
|
+
shell, ligada pelo `role init`. Aqui ficam os demais; o que nao for do
|
|
5
|
+
roleroster vai para o Granted, entao `role <comando do granted>` funciona.
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from . import __version__, helptext, init, profiles
|
|
12
|
+
|
|
13
|
+
PROFILE_COMMANDS = ("sync", "squads", "setup", "status", "browser", "notices", "token", "doctor", "preset")
|
|
14
|
+
INTERNAL_COMMANDS = ("session-save", "pick", "prune-exported", "open-console") # chamados pelo script de shell
|
|
15
|
+
SHELL_COMMANDS = ("sso", "console", "assume")
|
|
16
|
+
EXIT_USAGE = 2
|
|
17
|
+
GRANTED_INSTALL = "brew tap fwdcloudsec/granted && brew install fwdcloudsec/granted/granted"
|
|
18
|
+
|
|
19
|
+
def run_granted(args):
|
|
20
|
+
granted = shutil.which("granted")
|
|
21
|
+
if not granted:
|
|
22
|
+
print(f"role: o Granted nao esta instalado. No macOS: {GRANTED_INSTALL}", file=sys.stderr)
|
|
23
|
+
return 127
|
|
24
|
+
os.execv(granted, [granted, *args])
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def needs_shell(command):
|
|
28
|
+
print(
|
|
29
|
+
f"role {command} precisa do shell do roleroster (ele altera o terminal atual).\n"
|
|
30
|
+
"Se ainda não rodou, use `role init`. Depois abra um terminal novo (ou rode `source ~/.zshrc`,\n"
|
|
31
|
+
f"`source ~/.bash_profile` no bash do macOS) e use `role {command}` de novo.",
|
|
32
|
+
file=sys.stderr,
|
|
33
|
+
)
|
|
34
|
+
return EXIT_USAGE
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def main(argv=None):
|
|
38
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
39
|
+
if not args or args[0] in ("-h", "--help", "help"):
|
|
40
|
+
helptext.show()
|
|
41
|
+
return 0
|
|
42
|
+
command, rest = args[0], args[1:]
|
|
43
|
+
if init.refresh_script():
|
|
44
|
+
print("role: script de shell atualizado; abra um novo terminal para usar a versao nova.", file=sys.stderr)
|
|
45
|
+
if command in ("-V", "--version", "version"):
|
|
46
|
+
print(f"roleroster {__version__}")
|
|
47
|
+
return 0
|
|
48
|
+
if command in PROFILE_COMMANDS + INTERNAL_COMMANDS:
|
|
49
|
+
return profiles.main(args)
|
|
50
|
+
if command == "init":
|
|
51
|
+
return init.main(rest)
|
|
52
|
+
if command in SHELL_COMMANDS:
|
|
53
|
+
return needs_shell(command)
|
|
54
|
+
if command == "granted":
|
|
55
|
+
return run_granted(rest)
|
|
56
|
+
return run_granted(args)
|