feat: the Tiny probe lists the account's users with their type and marks the integration's
All checks were successful
Build and deploy / Validate source (push) Successful in 7s
Build and deploy / Integration suite on a real stack (push) Successful in 3m28s
Build and deploy / Secret scan and release gate (push) Successful in 5s
Build and deploy / Publish images (push) Successful in 58s

Read-only. Tiny's API does what the user who connected the integration may
do, so knowing which user that is, and its type, points at the permission.
The name and e-mail come from the access token's claims; the token is never
printed. It needs the app's Usuarios (Leitura) and a reconnect, and says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-27 16:02:55 -03:00
parent 1ad761ec53
commit 874e53ae46
2 changed files with 69 additions and 0 deletions

View File

@@ -12,6 +12,9 @@ Tiny has no sandbox, so this is how the adapter is proven on the real account.
python -m app.tiny_probe pedido --cnpj ... --email ... --celular ... [--modo file] [--metros 1.3]
show the test order; --confirmar creates it, then cancels it
python -m app.tiny_probe cancelar TINY_ID cancel a test order (DTF-TESTE-...) left open; nothing else
python -m app.tiny_probe usuarios the account's users and their type, and which one the
integration is connected as (read-only; needs the app's
Usuários (Leitura) and a reconnect)
python -m app.tiny_probe diagnostico --cpf ... --email ... --celular ...
when Tiny refuses the order: sends it again without one
part at a time, stops at the first it accepts (cancelled)
@@ -25,6 +28,7 @@ test order is then cancelled through the API (Tiny has no delete, and the
team's users may not cancel by hand), and read back to show it is.
"""
import argparse
import base64
import json
import sys
import time
@@ -219,6 +223,40 @@ def pedido(orders, payload, confirm, out, wait=time.sleep):
cancelar(orders, first['tiny_id'], out)
def connected_as(orders):
"""Who logged in when the integration was connected: the name and e-mail
in the access token's claims (an OpenID token), never the token itself."""
try:
part = orders.auth.access_token().split('.')[1]
claims = json.loads(base64.urlsafe_b64decode(part + '=' * (-len(part) % 4)))
except Exception:
return {}
return {key: claims[key] for key in ('name', 'email', 'preferred_username') if claims.get(key)}
def usuarios(orders, out):
"""The account's users, with their type, and the one the integration
acts as: the API does what that user may do (read-only)."""
me = connected_as(orders)
if me:
out('Integração conectada como: ' + ' · '.join(str(v) for v in me.values()))
try:
found = orders.request('GET', '/usuarios', params={'limit': 100}).get('itens') or []
except tiny.TinyError as exc:
if ': 403 ' in str(exc) or ': 401 ' in str(exc):
out(f'Tiny recusou a lista de usuários ({exc}). Marque Usuários (Leitura) nas permissões do '
'aplicativo e conecte o Tiny de novo no Kanban (Integrações).')
return False
raise
ours = {str(v).lower() for v in me.values()}
for user in found:
mine = str(user.get('email') or '').lower() in ours or str(user.get('emailComunicacao') or '').lower() in ours
out(f"{user.get('id')}\t{user.get('tipo') or '-'}\t{user.get('nome')}\t{user.get('email')}"
+ ('\t<- integração' if mine else ''))
out(f'{len(found)} usuário(s).')
return True
def diagnostico(orders, payload, out):
"""Which part of the order Tiny refuses, when it says only 403. The same
test order is sent whole, then without one part at a time, then with only
@@ -296,6 +334,7 @@ def main(argv=None, orders=None, out=print):
order.add_argument('--modo', choices=sorted(tiny.PRODUCT_SETTINGS), default='file')
order.add_argument('--metros', default='1', help='metragem cobrada, em passos de 10 cm (ex.: 1.3)')
order.add_argument('--confirmar', action='store_true')
commands.add_parser('usuarios')
probe = commands.add_parser('diagnostico')
probe.add_argument('--cnpj', '--cpf', dest='cnpj', required=True, help='CNPJ ou CPF de um contato que já existe')
probe.add_argument('--email', required=True)
@@ -321,6 +360,8 @@ def main(argv=None, orders=None, out=print):
return 0 if exemplo(orders, args.numero, out) else 1
if args.command == 'cancelar':
return 0 if cancelar(orders, args.tiny_id, out) else 1
if args.command == 'usuarios':
return 0 if usuarios(orders, out) else 1
cnpj = ''.join(ch for ch in args.cnpj if ch.isdigit())
if len(cnpj) not in (11, 14):
out('Informe um CPF (11 dígitos) ou um CNPJ (14 dígitos).')

View File

@@ -584,6 +584,34 @@ class TinyProbeTests(FakeTinyCase):
self.assertIn('77\t6\tRetirar pessoalmente', text)
self.assertTrue(all(method == 'GET' for method, _ in self.calls))
def test_usuarios_lists_the_types_and_marks_the_integration_user(self):
import base64 as b64
handler = self.handler
allowed = {'on': True}
def account(request):
if request.url.path.endswith('/usuarios'):
if not allowed['on']:
return httpx.Response(403, text='')
return httpx.Response(200, json={'itens': [
{'id': 1, 'nome': 'Marcus', 'email': 'marcus@example.test', 'tipo': 'administrador'},
{'id': 2, 'nome': 'Integração', 'email': 'dev@example.test', 'tipo': 'usuario'}]})
return handler(request)
self.tiny.http = httpx.Client(base_url=tiny_module.API, transport=httpx.MockTransport(account))
claims = b64.urlsafe_b64encode(json.dumps({'name': 'Integração', 'email': 'dev@example.test'}).encode()).decode().rstrip('=')
with mock.patch.object(self.tiny.auth, 'access_token', return_value=f'h.{claims}.s'):
code, text = self.probe('usuarios')
self.assertEqual(code, 0, text)
self.assertIn('Integração conectada como: Integração · dev@example.test', text)
self.assertIn('2\tusuario\tIntegração\tdev@example.test\t<- integração', text)
self.assertIn('1\tadministrador\tMarcus\tmarcus@example.test', text)
self.assertNotIn(claims, text)
# Without the app's Usuários permission: says what to tick.
allowed['on'] = False
code, text = self.probe('usuarios')
self.assertEqual(code, 1)
self.assertIn('Marque Usuários (Leitura)', text)
def test_diagnostico_finds_the_part_tiny_refuses(self):
handler = self.handler