mirror of
https://github.com/trustgraph-ai/trustgraph.git
synced 2026-04-29 10:26:21 +02:00
feat: IAM service, gateway auth middleware, capability model, and CLIs (#849)
Replaces the legacy GATEWAY_SECRET shared-token gate with an IAM-backed
identity and authorisation model. The gateway no longer has an
"allow-all" or "no auth" mode; every request is authenticated via the
IAM service, authorised against a capability model that encodes both
the operation and the workspace it targets, and rejected with a
deliberately-uninformative 401 / 403 on any failure.
IAM service (trustgraph-flow/trustgraph/iam, trustgraph-base/schema/iam)
-----------------------------------------------------------------------
* New backend service (iam-svc) owning users, workspaces, API keys,
passwords and JWT signing keys in Cassandra. Reached over the
standard pub/sub request/response pattern; gateway is the only
caller.
* Operations: bootstrap, resolve-api-key, login, get-signing-key-public,
rotate-signing-key, create/list/get/update/disable/delete/enable-user,
change-password, reset-password, create/list/get/update/disable-
workspace, create/list/revoke-api-key.
* Ed25519 JWT signing (alg=EdDSA). Key rotation writes a new kid and
retires the previous one; validation is grace-period friendly.
* Passwords: PBKDF2-HMAC-SHA-256, 600k iterations, per-user salt.
* API keys: 128-bit random, SHA-256 hashed. Plaintext returned once.
* Bootstrap is explicit: --bootstrap-mode {token,bootstrap} is a
required startup argument with no permissive default. Masked
"auth failure" errors hide whether a refused bootstrap request was
due to mode, state, or authorisation.
Gateway authentication (trustgraph-flow/trustgraph/gateway/auth.py)
-------------------------------------------------------------------
* IamAuth replaces the legacy Authenticator. Distinguishes JWTs
(three-segment dotted) from API keys by shape; verifies JWTs
locally using the cached IAM public key; resolves API keys via
IAM with a short-TTL hash-keyed cache. Every failure path
surfaces the same 401 body ("auth failure") so callers cannot
enumerate credential state.
* Public key is fetched at gateway startup with a bounded retry loop;
traffic does not begin flowing until auth has started.
Capability model (trustgraph-flow/trustgraph/gateway/capabilities.py)
---------------------------------------------------------------------
* Roles have two dimensions: a capability set and a workspace scope.
OSS ships reader / writer / admin; the first two are workspace-
assigned, admin is cross-workspace ("*"). No "cross-workspace"
pseudo-capability — workspace permission is a property of the role.
* check(identity, capability, target_workspace=None) is the single
authorisation test: some role must grant the capability *and* be
active in the target workspace.
* enforce_workspace validates a request-body workspace against the
caller's role scopes and injects the resolved value. Cross-
workspace admin is permitted by role scope, not by a bypass.
* Gateway endpoints declare a required capability explicitly — no
permissive default. Construction fails fast if omitted. Enterprise
editions can replace the role table without changing the wire
protocol.
WebSocket first-frame auth (dispatch/mux.py, endpoint/socket.py)
----------------------------------------------------------------
* /api/v1/socket handshake unconditionally accepts; authentication
runs on the first WebSocket frame ({"type":"auth","token":"..."})
with {"type":"auth-ok","workspace":"..."} / {"type":"auth-failed"}.
The socket stays open on failure so the client can re-authenticate
— browsers treat a handshake-time 401 as terminal, breaking
reconnection.
* Mux.receive rejects every non-auth frame before auth succeeds,
enforces the caller's workspace (envelope + inner payload) using
the role-scope resolver, and supports mid-session re-auth.
* Flow import/export streaming endpoints keep the legacy ?token=
handshake (URL-scoped short-lived transfers; no re-auth need).
Auth surface
------------
* POST /api/v1/auth/login — public, returns a JWT.
* POST /api/v1/auth/bootstrap — public; forwards to IAM's bootstrap
op which itself enforces mode + tables-empty.
* POST /api/v1/auth/change-password — any authenticated user.
* POST /api/v1/iam — admin-only generic forwarder for the rest of
the IAM API (per-op REST endpoints to follow in a later change).
Removed / breaking
------------------
* GATEWAY_SECRET / --api-token / default_api_token and the legacy
Authenticator.permitted contract. The gateway cannot run without
IAM.
* ?token= on /api/v1/socket.
* DispatcherManager and Mux both raise on auth=None — no silent
downgrade path.
CLI tools (trustgraph-cli)
--------------------------
tg-bootstrap-iam, tg-login, tg-create-user, tg-list-users,
tg-disable-user, tg-enable-user, tg-delete-user, tg-change-password,
tg-reset-password, tg-create-api-key, tg-list-api-keys,
tg-revoke-api-key, tg-create-workspace, tg-list-workspaces. Passwords
read via getpass; tokens / one-time secrets written to stdout with
operator context on stderr so shell composition works cleanly.
AsyncSocketClient / SocketClient updated to the first-frame auth
protocol.
Specifications
--------------
* docs/tech-specs/iam.md updated with the error policy, workspace
resolver extension point, and OSS role-scope model.
* docs/tech-specs/iam-protocol.md (new) — transport, dataclasses,
operation table, error taxonomy, bootstrap modes.
* docs/tech-specs/capabilities.md (new) — capability vocabulary, OSS
role bundles, agent-as-composition note, enforcement-boundary
policy, enterprise extensibility.
Tests
-----
* test_auth.py (rewritten) — IamAuth + JWT round-trip with real
Ed25519 keypairs + API-key cache behaviour.
* test_capabilities.py (new) — role table sanity, check across
role x workspace combinations, enforce_workspace paths,
unknown-cap / unknown-role fail-closed.
* Every endpoint test construction now names its capability
explicitly (no permissive defaults relied upon). New tests pin
the fail-closed invariants: DispatcherManager / Mux refuse
auth=None; i18n path-traversal defense is exercised.
* test_socket_graceful_shutdown rewritten against IamAuth.
This commit is contained in:
parent
ae9936c9cc
commit
67b2fc448f
61 changed files with 6474 additions and 792 deletions
|
|
@ -40,6 +40,20 @@ tg-get-flow-blueprint = "trustgraph.cli.get_flow_blueprint:main"
|
|||
tg-get-kg-core = "trustgraph.cli.get_kg_core:main"
|
||||
tg-get-document-content = "trustgraph.cli.get_document_content:main"
|
||||
tg-graph-to-turtle = "trustgraph.cli.graph_to_turtle:main"
|
||||
tg-bootstrap-iam = "trustgraph.cli.bootstrap_iam:main"
|
||||
tg-login = "trustgraph.cli.login:main"
|
||||
tg-create-user = "trustgraph.cli.create_user:main"
|
||||
tg-list-users = "trustgraph.cli.list_users:main"
|
||||
tg-disable-user = "trustgraph.cli.disable_user:main"
|
||||
tg-enable-user = "trustgraph.cli.enable_user:main"
|
||||
tg-delete-user = "trustgraph.cli.delete_user:main"
|
||||
tg-change-password = "trustgraph.cli.change_password:main"
|
||||
tg-reset-password = "trustgraph.cli.reset_password:main"
|
||||
tg-create-api-key = "trustgraph.cli.create_api_key:main"
|
||||
tg-list-api-keys = "trustgraph.cli.list_api_keys:main"
|
||||
tg-revoke-api-key = "trustgraph.cli.revoke_api_key:main"
|
||||
tg-list-workspaces = "trustgraph.cli.list_workspaces:main"
|
||||
tg-create-workspace = "trustgraph.cli.create_workspace:main"
|
||||
tg-invoke-agent = "trustgraph.cli.invoke_agent:main"
|
||||
tg-invoke-document-rag = "trustgraph.cli.invoke_document_rag:main"
|
||||
tg-invoke-graph-rag = "trustgraph.cli.invoke_graph_rag:main"
|
||||
|
|
|
|||
75
trustgraph-cli/trustgraph/cli/_iam.py
Normal file
75
trustgraph-cli/trustgraph/cli/_iam.py
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
"""
|
||||
Shared helpers for IAM CLI tools.
|
||||
|
||||
All IAM operations go through the gateway's ``/api/v1/iam`` forwarder,
|
||||
with the three public auth operations (``login``, ``bootstrap``,
|
||||
``change-password``) served via ``/api/v1/auth/...`` instead. These
|
||||
helpers encapsulate the HTTP plumbing so each CLI can stay focused
|
||||
on its own argument parsing and output formatting.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
DEFAULT_URL = os.getenv("TRUSTGRAPH_URL", "http://localhost:8088/")
|
||||
DEFAULT_TOKEN = os.getenv("TRUSTGRAPH_TOKEN", None)
|
||||
|
||||
|
||||
def _fmt_error(resp_json):
|
||||
err = resp_json.get("error", {})
|
||||
if isinstance(err, dict):
|
||||
t = err.get("type", "")
|
||||
m = err.get("message", "")
|
||||
return f"{t}: {m}" if t else m or "error"
|
||||
return str(err)
|
||||
|
||||
|
||||
def _post(url, path, token, body):
|
||||
endpoint = url.rstrip("/") + path
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
|
||||
resp = requests.post(
|
||||
endpoint, headers=headers, data=json.dumps(body),
|
||||
)
|
||||
|
||||
if resp.status_code != 200:
|
||||
try:
|
||||
payload = resp.json()
|
||||
detail = _fmt_error(payload)
|
||||
except Exception:
|
||||
detail = resp.text
|
||||
raise RuntimeError(f"HTTP {resp.status_code}: {detail}")
|
||||
|
||||
body = resp.json()
|
||||
if "error" in body:
|
||||
raise RuntimeError(_fmt_error(body))
|
||||
return body
|
||||
|
||||
|
||||
def call_iam(url, token, request):
|
||||
"""Forward an IAM request through ``/api/v1/iam``. ``request`` is
|
||||
the ``IamRequest`` dict shape."""
|
||||
return _post(url, "/api/v1/iam", token, request)
|
||||
|
||||
|
||||
def call_auth(url, path, token, body):
|
||||
"""Hit one of the public auth endpoints
|
||||
(``/api/v1/auth/login``, ``/api/v1/auth/change-password``, etc.).
|
||||
``token`` is optional — login and bootstrap don't need one."""
|
||||
return _post(url, path, token, body)
|
||||
|
||||
|
||||
def run_main(fn, parser):
|
||||
"""Standard error-handling wrapper for CLI main() bodies."""
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
fn(args)
|
||||
except Exception as e:
|
||||
print("Exception:", e, file=sys.stderr, flush=True)
|
||||
sys.exit(1)
|
||||
94
trustgraph-cli/trustgraph/cli/bootstrap_iam.py
Normal file
94
trustgraph-cli/trustgraph/cli/bootstrap_iam.py
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
"""
|
||||
Bootstraps the IAM service. Only works when iam-svc is running in
|
||||
bootstrap mode with empty tables. Prints the initial admin API key
|
||||
to stdout.
|
||||
|
||||
This is a one-time, trust-sensitive operation. The resulting token
|
||||
is shown once and never again — capture it on use. Rotate and
|
||||
revoke it as soon as a real admin API key has been issued.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import requests
|
||||
|
||||
default_url = os.getenv("TRUSTGRAPH_URL", "http://localhost:8088/")
|
||||
|
||||
|
||||
def bootstrap(url):
|
||||
|
||||
# Unauthenticated public endpoint — IAM refuses the bootstrap
|
||||
# operation unless the service is running in bootstrap mode with
|
||||
# empty tables, so the safety gate lives on the server side.
|
||||
endpoint = url.rstrip("/") + "/api/v1/auth/bootstrap"
|
||||
|
||||
headers = {"Content-Type": "application/json"}
|
||||
|
||||
resp = requests.post(
|
||||
endpoint,
|
||||
headers=headers,
|
||||
data=json.dumps({}),
|
||||
)
|
||||
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(
|
||||
f"HTTP {resp.status_code}: {resp.text}"
|
||||
)
|
||||
|
||||
body = resp.json()
|
||||
|
||||
if "error" in body:
|
||||
raise RuntimeError(
|
||||
f"IAM {body['error'].get('type', 'error')}: "
|
||||
f"{body['error'].get('message', '')}"
|
||||
)
|
||||
|
||||
api_key = body.get("bootstrap_admin_api_key")
|
||||
user_id = body.get("bootstrap_admin_user_id")
|
||||
|
||||
if not api_key:
|
||||
raise RuntimeError(
|
||||
"IAM response did not contain a bootstrap token — the "
|
||||
"service may already be bootstrapped, or may be running "
|
||||
"in token mode."
|
||||
)
|
||||
|
||||
return user_id, api_key
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-bootstrap-iam",
|
||||
description=__doc__,
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-u", "--api-url",
|
||||
default=default_url,
|
||||
help=f"API URL (default: {default_url})",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
user_id, api_key = bootstrap(args.api_url)
|
||||
except Exception as e:
|
||||
print("Exception:", e, file=sys.stderr, flush=True)
|
||||
sys.exit(1)
|
||||
|
||||
# Stdout gets machine-readable output (the key). Any operator
|
||||
# context goes to stderr.
|
||||
print(f"Admin user id: {user_id}", file=sys.stderr)
|
||||
print(
|
||||
"Admin API key (shown once, capture now):",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(api_key)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
46
trustgraph-cli/trustgraph/cli/change_password.py
Normal file
46
trustgraph-cli/trustgraph/cli/change_password.py
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
"""
|
||||
Change your own password. Requires the current password.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_auth, run_main
|
||||
|
||||
|
||||
def do_change_password(args):
|
||||
current = args.current or getpass.getpass("Current password: ")
|
||||
new = args.new or getpass.getpass("New password: ")
|
||||
|
||||
call_auth(
|
||||
args.api_url, "/api/v1/auth/change-password", args.token,
|
||||
{"current_password": current, "new_password": new},
|
||||
)
|
||||
print("Password changed.")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-change-password", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--current", default=None,
|
||||
help="Current password (prompted if omitted)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--new", default=None,
|
||||
help="New password (prompted if omitted)",
|
||||
)
|
||||
run_main(do_change_password, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
71
trustgraph-cli/trustgraph/cli/create_api_key.py
Normal file
71
trustgraph-cli/trustgraph/cli/create_api_key.py
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
"""
|
||||
Create an API key for a user. Prints the plaintext key to stdout —
|
||||
shown once only.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_create_api_key(args):
|
||||
key = {
|
||||
"user_id": args.user_id,
|
||||
"name": args.name,
|
||||
}
|
||||
if args.expires:
|
||||
key["expires"] = args.expires
|
||||
|
||||
req = {"operation": "create-api-key", "key": key}
|
||||
if args.workspace:
|
||||
req["workspace"] = args.workspace
|
||||
resp = call_iam(args.api_url, args.token, req)
|
||||
|
||||
plaintext = resp.get("api_key_plaintext", "")
|
||||
rec = resp.get("api_key", {})
|
||||
print(f"Key id: {rec.get('id', '')}", file=sys.stderr)
|
||||
print(f"Name: {rec.get('name', '')}", file=sys.stderr)
|
||||
print(f"Prefix: {rec.get('prefix', '')}", file=sys.stderr)
|
||||
print(
|
||||
"API key (shown once, capture now):", file=sys.stderr,
|
||||
)
|
||||
print(plaintext)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-create-api-key", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--user-id", required=True,
|
||||
help="Owner user id",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--name", required=True,
|
||||
help="Operator-facing label (e.g. 'laptop', 'ci')",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--expires", default=None,
|
||||
help="ISO-8601 expiry (optional; empty = no expiry)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--workspace", default=None,
|
||||
help=(
|
||||
"Target workspace (admin only; defaults to caller's "
|
||||
"assigned workspace)"
|
||||
),
|
||||
)
|
||||
run_main(do_create_api_key, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
87
trustgraph-cli/trustgraph/cli/create_user.py
Normal file
87
trustgraph-cli/trustgraph/cli/create_user.py
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
"""
|
||||
Create a user in the caller's workspace. Prints the new user id.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
import sys
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_create_user(args):
|
||||
password = args.password
|
||||
if not password:
|
||||
password = getpass.getpass(
|
||||
f"Password for new user {args.username}: "
|
||||
)
|
||||
|
||||
user = {
|
||||
"username": args.username,
|
||||
"password": password,
|
||||
"roles": args.roles,
|
||||
}
|
||||
if args.name:
|
||||
user["name"] = args.name
|
||||
if args.email:
|
||||
user["email"] = args.email
|
||||
if args.must_change_password:
|
||||
user["must_change_password"] = True
|
||||
|
||||
req = {"operation": "create-user", "user": user}
|
||||
if args.workspace:
|
||||
req["workspace"] = args.workspace
|
||||
resp = call_iam(args.api_url, args.token, req)
|
||||
|
||||
rec = resp.get("user", {})
|
||||
print(f"User id: {rec.get('id', '')}", file=sys.stderr)
|
||||
print(f"Username: {rec.get('username', '')}", file=sys.stderr)
|
||||
print(f"Roles: {', '.join(rec.get('roles', []))}", file=sys.stderr)
|
||||
print(rec.get("id", ""))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-create-user", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--username", required=True, help="Username (unique in workspace)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--password", default=None,
|
||||
help="Password (prompted if omitted)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--name", default=None, help="Display name",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--email", default=None, help="Email",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--roles", nargs="+", default=["reader"],
|
||||
help="One or more role names (default: reader)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--must-change-password", action="store_true",
|
||||
help="Force password change on next login",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--workspace", default=None,
|
||||
help=(
|
||||
"Target workspace (admin only; defaults to caller's "
|
||||
"assigned workspace)"
|
||||
),
|
||||
)
|
||||
run_main(do_create_user, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
46
trustgraph-cli/trustgraph/cli/create_workspace.py
Normal file
46
trustgraph-cli/trustgraph/cli/create_workspace.py
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
"""
|
||||
Create a workspace (system-level; requires admin).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_create_workspace(args):
|
||||
ws = {"id": args.workspace_id, "enabled": True}
|
||||
if args.name:
|
||||
ws["name"] = args.name
|
||||
|
||||
resp = call_iam(args.api_url, args.token, {
|
||||
"operation": "create-workspace",
|
||||
"workspace_record": ws,
|
||||
})
|
||||
rec = resp.get("workspace", {})
|
||||
print(f"Workspace created: {rec.get('id', '')}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-create-workspace", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--workspace-id", required=True,
|
||||
help="New workspace id (must not start with '_')",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--name", default=None, help="Display name",
|
||||
)
|
||||
run_main(do_create_workspace, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
62
trustgraph-cli/trustgraph/cli/delete_user.py
Normal file
62
trustgraph-cli/trustgraph/cli/delete_user.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
"""
|
||||
Delete a user. Removes the user record, their username lookup,
|
||||
and all their API keys. The freed username becomes available for
|
||||
re-use.
|
||||
|
||||
Irreversible. Use tg-disable-user if you want to preserve the
|
||||
record (audit trail, username squatting protection).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_delete_user(args):
|
||||
if not args.yes:
|
||||
confirm = input(
|
||||
f"Delete user {args.user_id}? This is irreversible. "
|
||||
f"[type 'yes' to confirm]: "
|
||||
)
|
||||
if confirm.strip() != "yes":
|
||||
print("Aborted.")
|
||||
return
|
||||
|
||||
req = {"operation": "delete-user", "user_id": args.user_id}
|
||||
if args.workspace:
|
||||
req["workspace"] = args.workspace
|
||||
call_iam(args.api_url, args.token, req)
|
||||
print(f"Deleted user {args.user_id}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-delete-user", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--user-id", required=True, help="User id to delete",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--workspace", default=None,
|
||||
help=(
|
||||
"Target workspace (admin only; defaults to caller's "
|
||||
"assigned workspace)"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--yes", action="store_true",
|
||||
help="Skip the interactive confirmation prompt",
|
||||
)
|
||||
run_main(do_delete_user, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
45
trustgraph-cli/trustgraph/cli/disable_user.py
Normal file
45
trustgraph-cli/trustgraph/cli/disable_user.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"""
|
||||
Disable a user. Soft-deletes (enabled=false) and revokes all their
|
||||
API keys.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_disable_user(args):
|
||||
req = {"operation": "disable-user", "user_id": args.user_id}
|
||||
if args.workspace:
|
||||
req["workspace"] = args.workspace
|
||||
call_iam(args.api_url, args.token, req)
|
||||
print(f"Disabled user {args.user_id}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-disable-user", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--user-id", required=True, help="User id to disable",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--workspace", default=None,
|
||||
help=(
|
||||
"Target workspace (admin only; defaults to caller's "
|
||||
"assigned workspace)"
|
||||
),
|
||||
)
|
||||
run_main(do_disable_user, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
45
trustgraph-cli/trustgraph/cli/enable_user.py
Normal file
45
trustgraph-cli/trustgraph/cli/enable_user.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"""
|
||||
Re-enable a previously disabled user. Does not restore their API
|
||||
keys — those must be re-issued by an admin.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_enable_user(args):
|
||||
req = {"operation": "enable-user", "user_id": args.user_id}
|
||||
if args.workspace:
|
||||
req["workspace"] = args.workspace
|
||||
call_iam(args.api_url, args.token, req)
|
||||
print(f"Enabled user {args.user_id}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-enable-user", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--user-id", required=True, help="User id to enable",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--workspace", default=None,
|
||||
help=(
|
||||
"Target workspace (admin only; defaults to caller's "
|
||||
"assigned workspace)"
|
||||
),
|
||||
)
|
||||
run_main(do_enable_user, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
69
trustgraph-cli/trustgraph/cli/list_api_keys.py
Normal file
69
trustgraph-cli/trustgraph/cli/list_api_keys.py
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
"""
|
||||
List the API keys for a user.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import tabulate
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_list_api_keys(args):
|
||||
req = {"operation": "list-api-keys", "user_id": args.user_id}
|
||||
if args.workspace:
|
||||
req["workspace"] = args.workspace
|
||||
resp = call_iam(args.api_url, args.token, req)
|
||||
|
||||
keys = resp.get("api_keys", [])
|
||||
if not keys:
|
||||
print("No keys.")
|
||||
return
|
||||
|
||||
rows = [
|
||||
[
|
||||
k.get("id", ""),
|
||||
k.get("name", ""),
|
||||
k.get("prefix", ""),
|
||||
k.get("created", ""),
|
||||
k.get("last_used", "") or "—",
|
||||
k.get("expires", "") or "never",
|
||||
]
|
||||
for k in keys
|
||||
]
|
||||
print(tabulate.tabulate(
|
||||
rows,
|
||||
headers=["id", "name", "prefix", "created", "last used", "expires"],
|
||||
tablefmt="pretty",
|
||||
stralign="left",
|
||||
))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-list-api-keys", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--user-id", required=True,
|
||||
help="Owner user id",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--workspace", default=None,
|
||||
help=(
|
||||
"Target workspace (admin only; defaults to caller's "
|
||||
"assigned workspace)"
|
||||
),
|
||||
)
|
||||
run_main(do_list_api_keys, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
65
trustgraph-cli/trustgraph/cli/list_users.py
Normal file
65
trustgraph-cli/trustgraph/cli/list_users.py
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
"""
|
||||
List users in the caller's workspace.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import tabulate
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_list_users(args):
|
||||
req = {"operation": "list-users"}
|
||||
if args.workspace:
|
||||
req["workspace"] = args.workspace
|
||||
resp = call_iam(args.api_url, args.token, req)
|
||||
|
||||
users = resp.get("users", [])
|
||||
if not users:
|
||||
print("No users.")
|
||||
return
|
||||
|
||||
rows = [
|
||||
[
|
||||
u.get("id", ""),
|
||||
u.get("username", ""),
|
||||
u.get("name", ""),
|
||||
", ".join(u.get("roles", [])),
|
||||
"yes" if u.get("enabled") else "no",
|
||||
"yes" if u.get("must_change_password") else "no",
|
||||
]
|
||||
for u in users
|
||||
]
|
||||
print(tabulate.tabulate(
|
||||
rows,
|
||||
headers=["id", "username", "name", "roles", "enabled", "change-pw"],
|
||||
tablefmt="pretty",
|
||||
stralign="left",
|
||||
))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-list-users", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--workspace", default=None,
|
||||
help=(
|
||||
"Target workspace (admin only; defaults to caller's "
|
||||
"assigned workspace)"
|
||||
),
|
||||
)
|
||||
run_main(do_list_users, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
53
trustgraph-cli/trustgraph/cli/list_workspaces.py
Normal file
53
trustgraph-cli/trustgraph/cli/list_workspaces.py
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
"""
|
||||
List workspaces (system-level; requires admin).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
import tabulate
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_list_workspaces(args):
|
||||
resp = call_iam(
|
||||
args.api_url, args.token, {"operation": "list-workspaces"},
|
||||
)
|
||||
workspaces = resp.get("workspaces", [])
|
||||
if not workspaces:
|
||||
print("No workspaces.")
|
||||
return
|
||||
rows = [
|
||||
[
|
||||
w.get("id", ""),
|
||||
w.get("name", ""),
|
||||
"yes" if w.get("enabled") else "no",
|
||||
w.get("created", ""),
|
||||
]
|
||||
for w in workspaces
|
||||
]
|
||||
print(tabulate.tabulate(
|
||||
rows,
|
||||
headers=["id", "name", "enabled", "created"],
|
||||
tablefmt="pretty",
|
||||
stralign="left",
|
||||
))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-list-workspaces", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
run_main(do_list_workspaces, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
62
trustgraph-cli/trustgraph/cli/login.py
Normal file
62
trustgraph-cli/trustgraph/cli/login.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
"""
|
||||
Log in with username / password. Prints the resulting JWT to
|
||||
stdout so it can be captured for subsequent CLI use.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
import sys
|
||||
|
||||
from ._iam import DEFAULT_URL, call_auth, run_main
|
||||
|
||||
|
||||
def do_login(args):
|
||||
password = args.password
|
||||
if not password:
|
||||
password = getpass.getpass(f"Password for {args.username}: ")
|
||||
|
||||
body = {
|
||||
"username": args.username,
|
||||
"password": password,
|
||||
}
|
||||
if args.workspace:
|
||||
body["workspace"] = args.workspace
|
||||
|
||||
resp = call_auth(args.api_url, "/api/v1/auth/login", None, body)
|
||||
|
||||
jwt = resp.get("jwt", "")
|
||||
expires = resp.get("jwt_expires", "")
|
||||
|
||||
if expires:
|
||||
print(f"JWT expires: {expires}", file=sys.stderr)
|
||||
# Machine-readable on stdout.
|
||||
print(jwt)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-login", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--username", required=True, help="Username",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--password", default=None,
|
||||
help="Password (prompted if omitted)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--workspace", default=None,
|
||||
help=(
|
||||
"Optional workspace to log in against. Defaults to "
|
||||
"the user's assigned workspace."
|
||||
),
|
||||
)
|
||||
run_main(do_login, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
54
trustgraph-cli/trustgraph/cli/reset_password.py
Normal file
54
trustgraph-cli/trustgraph/cli/reset_password.py
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
"""
|
||||
Admin: reset another user's password. Prints a one-time temporary
|
||||
password to stdout. The user is forced to change it on next login.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_reset_password(args):
|
||||
req = {"operation": "reset-password", "user_id": args.user_id}
|
||||
if args.workspace:
|
||||
req["workspace"] = args.workspace
|
||||
resp = call_iam(args.api_url, args.token, req)
|
||||
|
||||
tmp = resp.get("temporary_password", "")
|
||||
if not tmp:
|
||||
raise RuntimeError(
|
||||
"IAM returned no temporary password — unexpected"
|
||||
)
|
||||
print("Temporary password (shown once, capture now):", file=sys.stderr)
|
||||
print(tmp)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-reset-password", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--user-id", required=True,
|
||||
help="Target user id",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--workspace", default=None,
|
||||
help=(
|
||||
"Target workspace (admin only; defaults to caller's "
|
||||
"assigned workspace)"
|
||||
),
|
||||
)
|
||||
run_main(do_reset_password, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
44
trustgraph-cli/trustgraph/cli/revoke_api_key.py
Normal file
44
trustgraph-cli/trustgraph/cli/revoke_api_key.py
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"""
|
||||
Revoke an API key by id.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
|
||||
from ._iam import DEFAULT_URL, DEFAULT_TOKEN, call_iam, run_main
|
||||
|
||||
|
||||
def do_revoke_api_key(args):
|
||||
req = {"operation": "revoke-api-key", "key_id": args.key_id}
|
||||
if args.workspace:
|
||||
req["workspace"] = args.workspace
|
||||
call_iam(args.api_url, args.token, req)
|
||||
print(f"Revoked key {args.key_id}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="tg-revoke-api-key", description=__doc__,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--api-url", default=DEFAULT_URL,
|
||||
help=f"API URL (default: {DEFAULT_URL})",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t", "--token", default=DEFAULT_TOKEN,
|
||||
help="Auth token (default: $TRUSTGRAPH_TOKEN)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--key-id", required=True, help="Key id to revoke",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w", "--workspace", default=None,
|
||||
help=(
|
||||
"Target workspace (admin only; defaults to caller's "
|
||||
"assigned workspace)"
|
||||
),
|
||||
)
|
||||
run_main(do_revoke_api_key, parser)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Add table
Add a link
Reference in a new issue