hoja-cli 0.21.4__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.
- VERSION +1 -0
- google_workspace/__init__.py +19 -0
- google_workspace/client.py +253 -0
- google_workspace/config.py +39 -0
- google_workspace/errors.py +19 -0
- google_workspace/mcp_server.py +100 -0
- google_workspace/oauth.py +131 -0
- google_workspace/principal.py +83 -0
- google_workspace/py.typed +0 -0
- google_workspace/tools.py +64 -0
- google_workspace/writes.py +44 -0
- hoja/__init__.py +29 -0
- hoja/__main__.py +6 -0
- hoja/auth.py +42 -0
- hoja/cli.py +161 -0
- hoja/cli_state.py +55 -0
- hoja/client.py +268 -0
- hoja/commands/__init__.py +4 -0
- hoja/commands/auth_cmd.py +271 -0
- hoja/commands/comment.py +149 -0
- hoja/commands/cycle.py +75 -0
- hoja/commands/init.py +108 -0
- hoja/commands/issue.py +398 -0
- hoja/commands/label.py +163 -0
- hoja/commands/memory.py +240 -0
- hoja/commands/project.py +56 -0
- hoja/commands/raw.py +50 -0
- hoja/commands/team.py +102 -0
- hoja/commands/update.py +162 -0
- hoja/config.py +362 -0
- hoja/errors.py +107 -0
- hoja/filters.py +150 -0
- hoja/graphql/__init__.py +5 -0
- hoja/graphql/fragments.py +138 -0
- hoja/graphql/mutations.py +160 -0
- hoja/graphql/queries.py +245 -0
- hoja/mcp/__init__.py +27 -0
- hoja/mcp/content.py +151 -0
- hoja/mcp/prompts.py +298 -0
- hoja/mcp/resources.py +213 -0
- hoja/mcp/server.py +189 -0
- hoja/memory_board.py +370 -0
- hoja/models/__init__.py +37 -0
- hoja/models/base.py +64 -0
- hoja/models/cycle.py +32 -0
- hoja/models/enums.py +62 -0
- hoja/models/issue.py +99 -0
- hoja/models/label.py +17 -0
- hoja/models/project.py +60 -0
- hoja/models/team.py +31 -0
- hoja/models/user.py +32 -0
- hoja/models/workflow.py +65 -0
- hoja/output.py +410 -0
- hoja/skill_content/commands.md +222 -0
- hoja/skill_content/examples.md +193 -0
- hoja/skill_content/filters.md +101 -0
- hoja/skill_content/output-formats.md +92 -0
- hoja/skill_content/overview.md +123 -0
- hoja/skill_content/workflows.md +174 -0
- hoja_cli-0.21.4.dist-info/METADATA +279 -0
- hoja_cli-0.21.4.dist-info/RECORD +107 -0
- hoja_cli-0.21.4.dist-info/WHEEL +4 -0
- hoja_cli-0.21.4.dist-info/entry_points.txt +4 -0
- hoja_cli-0.21.4.dist-info/licenses/LICENSE +21 -0
- hoja_server/README.md +135 -0
- hoja_server/__init__.py +11 -0
- hoja_server/abac.py +116 -0
- hoja_server/agent_chat.py +280 -0
- hoja_server/agent_conversations.py +91 -0
- hoja_server/agent_durable.py +332 -0
- hoja_server/agent_prompt.py +117 -0
- hoja_server/agent_threads.py +96 -0
- hoja_server/agent_uploads.py +60 -0
- hoja_server/app.py +2189 -0
- hoja_server/cadence.py +231 -0
- hoja_server/cli.py +191 -0
- hoja_server/cloudflare_realtime.py +110 -0
- hoja_server/comment_policy.py +70 -0
- hoja_server/connector_actions.py +119 -0
- hoja_server/connectors_api.py +375 -0
- hoja_server/db.py +1816 -0
- hoja_server/denials.py +18 -0
- hoja_server/deployment.py +28 -0
- hoja_server/email_adapter.py +94 -0
- hoja_server/google_login.py +217 -0
- hoja_server/google_oidc.py +342 -0
- hoja_server/identity_transfer.py +210 -0
- hoja_server/mcp_oauth.py +623 -0
- hoja_server/mcp_tools.py +579 -0
- hoja_server/meeting_policy.py +179 -0
- hoja_server/meetings.py +1332 -0
- hoja_server/meetings_api.py +909 -0
- hoja_server/model_providers.py +205 -0
- hoja_server/realtime.py +690 -0
- hoja_server/resolvers.py +1281 -0
- hoja_server/schema.graphql +477 -0
- hoja_server/schema_sdl.py +8 -0
- hoja_server/secrets_box.py +39 -0
- hoja_server/signup_config.py +292 -0
- hoja_server/signup_gate.py +393 -0
- hoja_server/signup_policy.py +97 -0
- hoja_server/signup_store.py +577 -0
- hoja_server/store.py +2179 -0
- hoja_server/sync.py +249 -0
- hoja_server/tenant_context.py +131 -0
- hoja_server/turnstile.py +81 -0
- hoja_server/writer.py +1262 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Approval queue for connector write actions. A write is never executed on request; it waits here
|
|
2
|
+
until the requesting user explicitly approves it. Approval claims the row atomically so a double
|
|
3
|
+
click or retry cannot run the same write twice."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import uuid
|
|
9
|
+
from collections.abc import Awaitable, Callable
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from sqlalchemy import update
|
|
14
|
+
from sqlalchemy.engine import Connection, Engine, RowMapping
|
|
15
|
+
|
|
16
|
+
from hoja_server.db import connector_action
|
|
17
|
+
|
|
18
|
+
PENDING = "pending"
|
|
19
|
+
EXECUTING = "executing"
|
|
20
|
+
APPROVED = "approved"
|
|
21
|
+
REJECTED = "rejected"
|
|
22
|
+
FAILED = "failed"
|
|
23
|
+
|
|
24
|
+
Executor = Callable[[str, dict[str, Any], str, str], Awaitable[str]]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _now() -> str:
|
|
28
|
+
return datetime.now(timezone.utc).isoformat()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def queue_action(
|
|
32
|
+
conn: Connection,
|
|
33
|
+
*,
|
|
34
|
+
org_id: str,
|
|
35
|
+
account_id: str,
|
|
36
|
+
user_id: str,
|
|
37
|
+
tool: str,
|
|
38
|
+
args: dict[str, Any],
|
|
39
|
+
) -> str:
|
|
40
|
+
action_id = f"cact_{uuid.uuid4().hex}"
|
|
41
|
+
conn.execute(
|
|
42
|
+
connector_action.insert().values(
|
|
43
|
+
id=action_id,
|
|
44
|
+
organization_id=org_id,
|
|
45
|
+
account_id=account_id,
|
|
46
|
+
requested_by_user_id=user_id,
|
|
47
|
+
tool=tool,
|
|
48
|
+
args_json=json.dumps(args, sort_keys=True),
|
|
49
|
+
status=PENDING,
|
|
50
|
+
created_at=_now(),
|
|
51
|
+
)
|
|
52
|
+
)
|
|
53
|
+
return action_id
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _owned_pending(
|
|
57
|
+
conn: Connection, org_id: str, user_id: str, action_id: str
|
|
58
|
+
) -> RowMapping | None:
|
|
59
|
+
row = (
|
|
60
|
+
conn.execute(
|
|
61
|
+
connector_action.select().where(
|
|
62
|
+
connector_action.c.id == action_id,
|
|
63
|
+
connector_action.c.organization_id == org_id,
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
.mappings()
|
|
67
|
+
.first()
|
|
68
|
+
)
|
|
69
|
+
if row is None or row["requested_by_user_id"] != user_id:
|
|
70
|
+
return None
|
|
71
|
+
return row
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def reject_action(engine: Engine, org_id: str, user_id: str, action_id: str) -> bool:
|
|
75
|
+
with engine.begin() as conn:
|
|
76
|
+
row = _owned_pending(conn, org_id, user_id, action_id)
|
|
77
|
+
if row is None or row["status"] != PENDING:
|
|
78
|
+
return False
|
|
79
|
+
conn.execute(
|
|
80
|
+
update(connector_action)
|
|
81
|
+
.where(connector_action.c.id == action_id, connector_action.c.status == PENDING)
|
|
82
|
+
.values(status=REJECTED, resolved_at=_now())
|
|
83
|
+
)
|
|
84
|
+
return True
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def approve_action(
|
|
88
|
+
engine: Engine, org_id: str, user_id: str, action_id: str, executor: Executor
|
|
89
|
+
) -> str | None:
|
|
90
|
+
"""Run a pending action once. Returns the final status, or None when not approvable."""
|
|
91
|
+
with engine.begin() as conn:
|
|
92
|
+
row = _owned_pending(conn, org_id, user_id, action_id)
|
|
93
|
+
if row is None or row["status"] != PENDING:
|
|
94
|
+
return None
|
|
95
|
+
claimed = conn.execute(
|
|
96
|
+
update(connector_action)
|
|
97
|
+
.where(connector_action.c.id == action_id, connector_action.c.status == PENDING)
|
|
98
|
+
.values(status=EXECUTING)
|
|
99
|
+
).rowcount
|
|
100
|
+
if claimed != 1:
|
|
101
|
+
return None
|
|
102
|
+
tool, args = row["tool"], json.loads(row["args_json"])
|
|
103
|
+
account_id, requester = row["account_id"], row["requested_by_user_id"]
|
|
104
|
+
try:
|
|
105
|
+
summary = await executor(tool, args, account_id, requester)
|
|
106
|
+
except Exception as exc:
|
|
107
|
+
_finish(engine, action_id, FAILED, f"{type(exc).__name__}")
|
|
108
|
+
return FAILED
|
|
109
|
+
_finish(engine, action_id, APPROVED, summary)
|
|
110
|
+
return APPROVED
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _finish(engine: Engine, action_id: str, status: str, summary: str) -> None:
|
|
114
|
+
with engine.begin() as conn:
|
|
115
|
+
conn.execute(
|
|
116
|
+
update(connector_action)
|
|
117
|
+
.where(connector_action.c.id == action_id)
|
|
118
|
+
.values(status=status, result_summary=summary, resolved_at=_now())
|
|
119
|
+
)
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""Google Workspace connector routes: connect, callback, list, and revoke connected accounts.
|
|
2
|
+
|
|
3
|
+
Pending OAuth state (user, org, scope, PKCE verifier, expiry) is carried in an AES-GCM sealed
|
|
4
|
+
`state` value, so the callback cannot be forged; a hashed nonce in `oauth_state_nonce` makes each state single-use.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
import uuid
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
from google_workspace import ConnectorAuthError, ConnectorConfigError, GoogleOAuthConfig
|
|
19
|
+
from google_workspace.oauth import (
|
|
20
|
+
READ_SCOPES,
|
|
21
|
+
authorization_url,
|
|
22
|
+
exchange_code,
|
|
23
|
+
pkce_pair,
|
|
24
|
+
)
|
|
25
|
+
from google_workspace.principal import sign_principal
|
|
26
|
+
from sqlalchemy import and_, or_, select, update
|
|
27
|
+
from sqlalchemy.engine import Engine
|
|
28
|
+
from sqlalchemy.exc import IntegrityError
|
|
29
|
+
from starlette.requests import Request
|
|
30
|
+
from starlette.responses import JSONResponse, RedirectResponse
|
|
31
|
+
from starlette.routing import Route
|
|
32
|
+
|
|
33
|
+
from hoja_server.connector_actions import Executor, approve_action, reject_action
|
|
34
|
+
from hoja_server.db import connector_account, connector_action, oauth_state_nonce
|
|
35
|
+
from hoja_server.secrets_box import SecretBoxError, decrypt_secret, encrypt_secret
|
|
36
|
+
|
|
37
|
+
PROVIDER = "google_workspace"
|
|
38
|
+
STATE_TTL_SECONDS = 600
|
|
39
|
+
GMAIL_PROFILE_URL = "https://gmail.googleapis.com/gmail/v1/users/me/profile"
|
|
40
|
+
GOOGLE_REVOKE_URL = "https://oauth2.googleapis.com/revoke"
|
|
41
|
+
|
|
42
|
+
def _consume_state(engine: Engine, nonce: str, expires_at: int) -> bool:
|
|
43
|
+
"""Mark an OAuth state nonce as used. False if it was already used (by any worker)."""
|
|
44
|
+
if not nonce:
|
|
45
|
+
return False
|
|
46
|
+
try:
|
|
47
|
+
with engine.begin() as conn:
|
|
48
|
+
conn.execute(oauth_state_nonce.delete().where(oauth_state_nonce.c.expires_at < time.time()))
|
|
49
|
+
conn.execute(oauth_state_nonce.insert().values(
|
|
50
|
+
nonce_hash=hashlib.sha256(nonce.encode()).hexdigest(), expires_at=float(expires_at)))
|
|
51
|
+
except IntegrityError:
|
|
52
|
+
return False
|
|
53
|
+
return True
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _now() -> str:
|
|
57
|
+
return datetime.now(timezone.utc).isoformat()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _error(message: str, status: int, hint: str | None = None) -> JSONResponse:
|
|
61
|
+
body: dict = {"error": message}
|
|
62
|
+
if hint:
|
|
63
|
+
body["hint"] = hint
|
|
64
|
+
return JSONResponse(body, status_code=status)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _serialize(row) -> dict:
|
|
68
|
+
return {
|
|
69
|
+
"id": row["id"],
|
|
70
|
+
"provider": row["provider"],
|
|
71
|
+
"externalAccount": row["external_account"],
|
|
72
|
+
"scopes": row["scopes"].split(),
|
|
73
|
+
"scope": "org" if row["owner_user_id"] is None else "user",
|
|
74
|
+
"ownerUserId": row["owner_user_id"],
|
|
75
|
+
"status": row["status"],
|
|
76
|
+
"createdAt": row["created_at"],
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def connector_binding_for(engine: Engine, org: str, uid: str):
|
|
81
|
+
"""Return the MCP binding for this user when they have an active Google account, else None."""
|
|
82
|
+
url = os.environ.get("HOJA_CONNECTOR_MCP_URL", "").strip()
|
|
83
|
+
key = os.environ.get("HOJA_CONNECTOR_SIGNING_KEY", "").strip()
|
|
84
|
+
if not url or not key:
|
|
85
|
+
return None
|
|
86
|
+
with engine.connect() as conn:
|
|
87
|
+
active = conn.execute(
|
|
88
|
+
select(connector_account.c.id).where(
|
|
89
|
+
and_(
|
|
90
|
+
connector_account.c.organization_id == org,
|
|
91
|
+
connector_account.c.provider == PROVIDER,
|
|
92
|
+
connector_account.c.status == "active",
|
|
93
|
+
or_(
|
|
94
|
+
connector_account.c.owner_user_id == uid,
|
|
95
|
+
connector_account.c.owner_user_id.is_(None),
|
|
96
|
+
),
|
|
97
|
+
)
|
|
98
|
+
).limit(1)
|
|
99
|
+
).first()
|
|
100
|
+
if active is None:
|
|
101
|
+
return None
|
|
102
|
+
from hoja_server.agent_chat import ConnectorBinding
|
|
103
|
+
|
|
104
|
+
return ConnectorBinding(
|
|
105
|
+
url=url,
|
|
106
|
+
principal=sign_principal(uid, org, "read", key=key),
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def make_write_executor(engine: Engine, http: httpx.AsyncClient, config: GoogleOAuthConfig):
|
|
111
|
+
"""Build the approval executor. It runs an approved write only with the account the action was
|
|
112
|
+
queued against, and only while that account is still active and owned by the same requester."""
|
|
113
|
+
|
|
114
|
+
async def execute(tool: str, args: dict[str, Any], account_id: str, requester: str) -> str:
|
|
115
|
+
from google_workspace.oauth import refresh_access_token
|
|
116
|
+
from google_workspace.tools import AccountGrant
|
|
117
|
+
from google_workspace.writes import run_write
|
|
118
|
+
|
|
119
|
+
with engine.connect() as conn:
|
|
120
|
+
row = conn.execute(
|
|
121
|
+
select(connector_account).where(
|
|
122
|
+
and_(
|
|
123
|
+
connector_account.c.id == account_id,
|
|
124
|
+
connector_account.c.status == "active",
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
).mappings().one_or_none()
|
|
128
|
+
if row is None or row["owner_user_id"] != requester:
|
|
129
|
+
raise ConnectorAuthError("The account for this action is no longer available.")
|
|
130
|
+
refresh = decrypt_secret(row["encrypted_refresh_token"])
|
|
131
|
+
|
|
132
|
+
async def access_token() -> str:
|
|
133
|
+
tokens = await refresh_access_token(http, config, refresh_token=refresh)
|
|
134
|
+
return tokens.access_token
|
|
135
|
+
|
|
136
|
+
grant = AccountGrant(
|
|
137
|
+
account_id=row["id"],
|
|
138
|
+
external_account=row["external_account"],
|
|
139
|
+
access_token=access_token,
|
|
140
|
+
)
|
|
141
|
+
return await run_write(http, grant, tool, args)
|
|
142
|
+
|
|
143
|
+
return execute
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def connector_routes(engine: Engine, store, auth, execute_write: Executor | None = None) -> list[Route]:
|
|
147
|
+
"""Build connector routes. `auth(request)` returns (user_id, org_id, identity_id, is_browser)."""
|
|
148
|
+
|
|
149
|
+
async def _require_user(request: Request):
|
|
150
|
+
uid, org, _identity, _browser = auth(request)
|
|
151
|
+
if not uid:
|
|
152
|
+
return None, None, _error("Authentication required", 401)
|
|
153
|
+
return uid, org, None
|
|
154
|
+
|
|
155
|
+
def _is_admin(org: str, uid: str) -> bool:
|
|
156
|
+
actor = store.get_user(org, uid)
|
|
157
|
+
return bool(actor and actor.get("admin"))
|
|
158
|
+
|
|
159
|
+
async def google_start(request: Request):
|
|
160
|
+
uid, org, failure = await _require_user(request)
|
|
161
|
+
if failure:
|
|
162
|
+
return failure
|
|
163
|
+
scope = request.query_params.get("scope", "user")
|
|
164
|
+
if scope not in {"user", "org"}:
|
|
165
|
+
return _error("scope must be 'user' or 'org'", 400)
|
|
166
|
+
if scope == "org" and not _is_admin(org, uid):
|
|
167
|
+
return _error("Only workspace admins can connect organization accounts.", 403)
|
|
168
|
+
try:
|
|
169
|
+
config = GoogleOAuthConfig.from_env()
|
|
170
|
+
verifier, challenge = pkce_pair()
|
|
171
|
+
state = encrypt_secret(
|
|
172
|
+
json.dumps(
|
|
173
|
+
{
|
|
174
|
+
"uid": uid,
|
|
175
|
+
"org": org,
|
|
176
|
+
"scope": scope,
|
|
177
|
+
"verifier": verifier,
|
|
178
|
+
"exp": int(time.time()) + STATE_TTL_SECONDS,
|
|
179
|
+
"nonce": uuid.uuid4().hex,
|
|
180
|
+
}
|
|
181
|
+
)
|
|
182
|
+
)
|
|
183
|
+
except (ConnectorConfigError, SecretBoxError) as exc:
|
|
184
|
+
return _error(str(exc), 503, getattr(exc, "hint", None))
|
|
185
|
+
url = authorization_url(
|
|
186
|
+
config,
|
|
187
|
+
scopes=list(READ_SCOPES.values()),
|
|
188
|
+
state=state,
|
|
189
|
+
code_challenge=challenge,
|
|
190
|
+
)
|
|
191
|
+
return RedirectResponse(url, status_code=302)
|
|
192
|
+
|
|
193
|
+
async def google_callback(request: Request):
|
|
194
|
+
uid, org, failure = await _require_user(request)
|
|
195
|
+
if failure:
|
|
196
|
+
return failure
|
|
197
|
+
if request.query_params.get("error"):
|
|
198
|
+
return _error("Google did not grant access.", 400)
|
|
199
|
+
code = request.query_params.get("code", "")
|
|
200
|
+
sealed = request.query_params.get("state", "")
|
|
201
|
+
if not code or not sealed:
|
|
202
|
+
return _error("code and state are required", 400)
|
|
203
|
+
try:
|
|
204
|
+
pending = json.loads(decrypt_secret(sealed))
|
|
205
|
+
config = GoogleOAuthConfig.from_env()
|
|
206
|
+
except (SecretBoxError, ValueError, ConnectorConfigError) as exc:
|
|
207
|
+
return _error("Invalid or expired connection request.", 400, getattr(exc, "hint", None))
|
|
208
|
+
if pending.get("exp", 0) < time.time():
|
|
209
|
+
return _error("Connection request expired. Start again.", 400)
|
|
210
|
+
if pending.get("uid") != uid or pending.get("org") != org:
|
|
211
|
+
return _error("Connection request belongs to a different session.", 403)
|
|
212
|
+
if pending["scope"] == "org" and not _is_admin(org, uid):
|
|
213
|
+
return _error("Only workspace admins can connect organization accounts.", 403)
|
|
214
|
+
if not _consume_state(engine, str(pending.get("nonce", "")), int(pending["exp"])):
|
|
215
|
+
return _error("Connection request was already used. Start again.", 400)
|
|
216
|
+
|
|
217
|
+
async with httpx.AsyncClient(timeout=15) as http:
|
|
218
|
+
try:
|
|
219
|
+
tokens = await exchange_code(
|
|
220
|
+
http, config, code=code, code_verifier=pending["verifier"]
|
|
221
|
+
)
|
|
222
|
+
if not tokens.refresh_token:
|
|
223
|
+
raise ConnectorAuthError(
|
|
224
|
+
"Google did not return a refresh token.",
|
|
225
|
+
hint="Remove the app from your Google account permissions and connect again.",
|
|
226
|
+
)
|
|
227
|
+
profile = await http.get(
|
|
228
|
+
GMAIL_PROFILE_URL,
|
|
229
|
+
headers={"Authorization": f"Bearer {tokens.access_token}"},
|
|
230
|
+
)
|
|
231
|
+
except ConnectorAuthError as exc:
|
|
232
|
+
return _error(str(exc), 400, exc.hint)
|
|
233
|
+
|
|
234
|
+
if profile.status_code != 200:
|
|
235
|
+
return _error("Could not read the connected Google account.", 502)
|
|
236
|
+
email = profile.json().get("emailAddress")
|
|
237
|
+
if not isinstance(email, str) or not email:
|
|
238
|
+
return _error("Could not read the connected Google account.", 502)
|
|
239
|
+
|
|
240
|
+
row = {
|
|
241
|
+
"id": uuid.uuid4().hex,
|
|
242
|
+
"organization_id": org,
|
|
243
|
+
"owner_user_id": None if pending["scope"] == "org" else uid,
|
|
244
|
+
"provider": PROVIDER,
|
|
245
|
+
"external_account": email,
|
|
246
|
+
"scopes": tokens.scope or " ".join(READ_SCOPES.values()),
|
|
247
|
+
"encrypted_refresh_token": encrypt_secret(tokens.refresh_token),
|
|
248
|
+
"status": "active",
|
|
249
|
+
"created_at": _now(),
|
|
250
|
+
"updated_at": _now(),
|
|
251
|
+
}
|
|
252
|
+
with engine.begin() as conn:
|
|
253
|
+
conn.execute(connector_account.insert().values(**row))
|
|
254
|
+
return RedirectResponse("/?connector=google-connected", status_code=302)
|
|
255
|
+
|
|
256
|
+
async def accounts_list(request: Request):
|
|
257
|
+
uid, org, failure = await _require_user(request)
|
|
258
|
+
if failure:
|
|
259
|
+
return failure
|
|
260
|
+
with engine.connect() as conn:
|
|
261
|
+
rows = conn.execute(
|
|
262
|
+
select(connector_account).where(
|
|
263
|
+
and_(
|
|
264
|
+
connector_account.c.organization_id == org,
|
|
265
|
+
connector_account.c.provider == PROVIDER,
|
|
266
|
+
connector_account.c.status == "active",
|
|
267
|
+
or_(
|
|
268
|
+
connector_account.c.owner_user_id == uid,
|
|
269
|
+
connector_account.c.owner_user_id.is_(None),
|
|
270
|
+
),
|
|
271
|
+
)
|
|
272
|
+
).order_by(connector_account.c.created_at)
|
|
273
|
+
).mappings().all()
|
|
274
|
+
return JSONResponse({"accounts": [_serialize(row) for row in rows]})
|
|
275
|
+
|
|
276
|
+
async def account_revoke(request: Request):
|
|
277
|
+
uid, org, failure = await _require_user(request)
|
|
278
|
+
if failure:
|
|
279
|
+
return failure
|
|
280
|
+
account_id = request.path_params["account_id"]
|
|
281
|
+
with engine.connect() as conn:
|
|
282
|
+
row = conn.execute(
|
|
283
|
+
select(connector_account).where(
|
|
284
|
+
and_(
|
|
285
|
+
connector_account.c.id == account_id,
|
|
286
|
+
connector_account.c.organization_id == org,
|
|
287
|
+
connector_account.c.status == "active",
|
|
288
|
+
)
|
|
289
|
+
)
|
|
290
|
+
).mappings().one_or_none()
|
|
291
|
+
if row is None:
|
|
292
|
+
return _error("Connected account not found.", 404)
|
|
293
|
+
is_owner = row["owner_user_id"] == uid
|
|
294
|
+
if not (is_owner or (row["owner_user_id"] is None and _is_admin(org, uid))):
|
|
295
|
+
# Same response as a missing account, so callers cannot probe for other users' accounts.
|
|
296
|
+
return _error("Connected account not found.", 404)
|
|
297
|
+
|
|
298
|
+
try:
|
|
299
|
+
refresh = decrypt_secret(row["encrypted_refresh_token"])
|
|
300
|
+
except SecretBoxError:
|
|
301
|
+
return _error("Stored credential is unreadable; contact an administrator.", 500)
|
|
302
|
+
async with httpx.AsyncClient(timeout=15) as http:
|
|
303
|
+
response = await http.post(GOOGLE_REVOKE_URL, data={"token": refresh})
|
|
304
|
+
# Google answers 200 on success and 400 if the token is already invalid; both end the grant.
|
|
305
|
+
if response.status_code not in (200, 400):
|
|
306
|
+
return _error("Google did not confirm revocation. Try again.", 502)
|
|
307
|
+
|
|
308
|
+
with engine.begin() as conn:
|
|
309
|
+
conn.execute(
|
|
310
|
+
update(connector_account)
|
|
311
|
+
.where(connector_account.c.id == account_id)
|
|
312
|
+
.values(status="revoked", revoked_at=_now(), updated_at=_now(), encrypted_refresh_token="")
|
|
313
|
+
)
|
|
314
|
+
return JSONResponse({"revoked": True})
|
|
315
|
+
|
|
316
|
+
async def actions_list(request: Request):
|
|
317
|
+
uid, org, failure = await _require_user(request)
|
|
318
|
+
if failure:
|
|
319
|
+
return failure
|
|
320
|
+
with engine.connect() as conn:
|
|
321
|
+
rows = conn.execute(
|
|
322
|
+
select(connector_action)
|
|
323
|
+
.where(
|
|
324
|
+
and_(
|
|
325
|
+
connector_action.c.organization_id == org,
|
|
326
|
+
connector_action.c.requested_by_user_id == uid,
|
|
327
|
+
connector_action.c.status == "pending",
|
|
328
|
+
)
|
|
329
|
+
)
|
|
330
|
+
.order_by(connector_action.c.created_at)
|
|
331
|
+
).mappings().all()
|
|
332
|
+
return JSONResponse(
|
|
333
|
+
{
|
|
334
|
+
"actions": [
|
|
335
|
+
{
|
|
336
|
+
"id": row["id"],
|
|
337
|
+
"tool": row["tool"],
|
|
338
|
+
"args": json.loads(row["args_json"]),
|
|
339
|
+
"createdAt": row["created_at"],
|
|
340
|
+
}
|
|
341
|
+
for row in rows
|
|
342
|
+
]
|
|
343
|
+
}
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
async def action_approve(request: Request):
|
|
347
|
+
uid, org, failure = await _require_user(request)
|
|
348
|
+
if failure:
|
|
349
|
+
return failure
|
|
350
|
+
action_id = request.path_params["action_id"]
|
|
351
|
+
if execute_write is None:
|
|
352
|
+
return _error("No connector write tools are enabled on this server.", 409)
|
|
353
|
+
status = await approve_action(engine, org, uid, action_id, execute_write)
|
|
354
|
+
if status is None:
|
|
355
|
+
return _error("Action not found or no longer pending.", 404)
|
|
356
|
+
return JSONResponse({"status": status})
|
|
357
|
+
|
|
358
|
+
async def action_reject(request: Request):
|
|
359
|
+
uid, org, failure = await _require_user(request)
|
|
360
|
+
if failure:
|
|
361
|
+
return failure
|
|
362
|
+
action_id = request.path_params["action_id"]
|
|
363
|
+
if not reject_action(engine, org, uid, action_id):
|
|
364
|
+
return _error("Action not found or no longer pending.", 404)
|
|
365
|
+
return JSONResponse({"status": "rejected"})
|
|
366
|
+
|
|
367
|
+
return [
|
|
368
|
+
Route("/api/connectors/google/start", google_start, methods=["GET"]),
|
|
369
|
+
Route("/api/connectors/google/callback", google_callback, methods=["GET"]),
|
|
370
|
+
Route("/api/connectors/accounts", accounts_list, methods=["GET"]),
|
|
371
|
+
Route("/api/connectors/accounts/{account_id}/revoke", account_revoke, methods=["POST"]),
|
|
372
|
+
Route("/api/connectors/actions", actions_list, methods=["GET"]),
|
|
373
|
+
Route("/api/connectors/actions/{action_id}/approve", action_approve, methods=["POST"]),
|
|
374
|
+
Route("/api/connectors/actions/{action_id}/reject", action_reject, methods=["POST"]),
|
|
375
|
+
]
|