sra-riskgate-cloud 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.
- sra_riskgate_cloud/__init__.py +2 -0
- sra_riskgate_cloud/app.py +271 -0
- sra_riskgate_cloud/cli.py +84 -0
- sra_riskgate_cloud/dashboard.py +64 -0
- sra_riskgate_cloud/db.py +287 -0
- sra_riskgate_cloud-0.1.0.dist-info/METADATA +113 -0
- sra_riskgate_cloud-0.1.0.dist-info/RECORD +11 -0
- sra_riskgate_cloud-0.1.0.dist-info/WHEEL +5 -0
- sra_riskgate_cloud-0.1.0.dist-info/entry_points.txt +2 -0
- sra_riskgate_cloud-0.1.0.dist-info/licenses/LICENSE +202 -0
- sra_riskgate_cloud-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""SRA-RiskGate Cloud: the hosted service behind ``sra_riskgate.cloud``.
|
|
2
|
+
|
|
3
|
+
What it adds to the free, offline library, for teams whose agents run on more than one machine:
|
|
4
|
+
|
|
5
|
+
- ``POST /v1/check``: the library's ``check_payment`` on the payment fields, with the organisation's policy, a
|
|
6
|
+
**shared spend ledger** (budgets hold across every machine), the **threat feed** as a blocklist, and a **signed,
|
|
7
|
+
chained receipt** kept in the vault. The payment's free text never reaches the service: the client checks it
|
|
8
|
+
locally first.
|
|
9
|
+
- ``POST /v1/ledger/release``: give back budget for an approved payment that was never sent.
|
|
10
|
+
- ``GET/PUT /v1/policy``: the organisation's policy, in the library's policy format (no ``ledger``, no ``screening``).
|
|
11
|
+
- ``GET /v1/feed``, ``POST /v1/feed/report``: look-alike addresses reported by scans. An address enters everyone's
|
|
12
|
+
feed only when ``SRA_CLOUD_FEED_MIN_ORGS`` (default 2) organisations reported it or an operator approved it.
|
|
13
|
+
- ``GET /v1/receipts``, ``GET /v1/report``: the receipt vault and an audit report built from it.
|
|
14
|
+
- ``GET /v1/usage``: checks used this month against the plan.
|
|
15
|
+
- ``POST /v1/x402/check``: pay per check in USDC with x402, no account (when ``SRA_CLOUD_X402_PAY_TO`` is set).
|
|
16
|
+
- ``GET /``: a small dashboard; ``GET /healthz``.
|
|
17
|
+
|
|
18
|
+
Authentication: ``Authorization: Bearer sra_live_...`` (create organisations and keys with ``sra-cloud``).
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import time
|
|
25
|
+
from typing import Any, Dict, List, Optional
|
|
26
|
+
|
|
27
|
+
from fastapi import Depends, FastAPI, Header, HTTPException, Request
|
|
28
|
+
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
|
|
29
|
+
from pydantic import BaseModel, Field
|
|
30
|
+
|
|
31
|
+
from sra_riskgate import (ReceiptSigner, __version__ as LIB_VERSION, audit_report, audit_report_markdown,
|
|
32
|
+
check_payment, issue_receipt, load_policy)
|
|
33
|
+
from sra_riskgate.sanctions import _normalise
|
|
34
|
+
from sra_riskgate.spend import SpendGuard
|
|
35
|
+
|
|
36
|
+
from sra_riskgate_cloud import __version__
|
|
37
|
+
from sra_riskgate_cloud.db import DBLedger, Store, plans, row_policy
|
|
38
|
+
|
|
39
|
+
MAX_BODY = 64 * 1024
|
|
40
|
+
FORBIDDEN_POLICY_KEYS = {"ledger", "screening"}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class CheckIn(BaseModel):
|
|
44
|
+
chain_id: int = Field(..., description="EVM chain id, e.g. 8453 for Base")
|
|
45
|
+
sender: str = Field(..., description="The paying wallet")
|
|
46
|
+
recipient: str = Field(..., description="The payee")
|
|
47
|
+
amount: float = Field(..., description="Amount in whole token units, e.g. 25 for 25 USDC")
|
|
48
|
+
token: str = Field("USDC", description="Token symbol")
|
|
49
|
+
peg_deviation_pct: Optional[float] = Field(None, description="Current depeg in percent, if known")
|
|
50
|
+
payment_id: Optional[str] = Field(None, max_length=200, description="Your id, to release budget later")
|
|
51
|
+
known_recipients: Optional[List[str]] = Field(None, max_length=10_000,
|
|
52
|
+
description="Added to the policy's known payees")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ReleaseIn(BaseModel):
|
|
56
|
+
payment_id: str = Field(..., min_length=1, max_length=200)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class ReportIn(BaseModel):
|
|
60
|
+
address: str
|
|
61
|
+
imitates: Optional[str] = None
|
|
62
|
+
chain_id: Optional[int] = None
|
|
63
|
+
tx: Optional[str] = Field(None, max_length=100)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _feed_min_orgs() -> int:
|
|
67
|
+
v = int(os.environ.get("SRA_CLOUD_FEED_MIN_ORGS", "2"))
|
|
68
|
+
if v < 2:
|
|
69
|
+
raise ValueError("SRA_CLOUD_FEED_MIN_ORGS must be at least 2, so no single organisation controls the feed")
|
|
70
|
+
return v
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _validate_policy(data: Any):
|
|
74
|
+
if not isinstance(data, dict):
|
|
75
|
+
raise ValueError("policy must be a JSON object")
|
|
76
|
+
bad = sorted(FORBIDDEN_POLICY_KEYS & set(data))
|
|
77
|
+
if bad:
|
|
78
|
+
raise ValueError(f"{', '.join(bad)} cannot be set on the cloud service (the ledger is shared and kept by "
|
|
79
|
+
"the service; screening keys stay on your machines)")
|
|
80
|
+
return load_policy(data)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _guard(policy, store: Store, org_id: str) -> Optional[SpendGuard]:
|
|
84
|
+
g = policy.spend_guard
|
|
85
|
+
if g is None:
|
|
86
|
+
return None
|
|
87
|
+
return SpendGuard(DBLedger(store, org_id), total_limit=g.total_limit, per_payee_limit=g.per_payee_limit,
|
|
88
|
+
window_seconds=g.window_seconds, max_payments_per_hour=g.max_payments_per_hour,
|
|
89
|
+
amount_spike_factor=g.amount_spike_factor, spike_min_history=g.spike_min_history)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _run_check(store: Store, org: Any, body: CheckIn, *, feed_addresses: List[str]) -> Dict[str, Any]:
|
|
93
|
+
"""The check, its ledger entry and its receipt, atomically for this organisation."""
|
|
94
|
+
org_id = org["id"]
|
|
95
|
+
policy = _validate_policy(row_policy(org))
|
|
96
|
+
kw = policy.check_kwargs()
|
|
97
|
+
kw.pop("spend_guard", None)
|
|
98
|
+
guard = _guard(policy, store, org_id)
|
|
99
|
+
known = list(kw.pop("known_recipients", []) or []) + list(body.known_recipients or [])
|
|
100
|
+
blocked = list(kw.pop("blocked_addresses", []) or []) + feed_addresses
|
|
101
|
+
payment = {"chain_id": body.chain_id, "sender": body.sender, "recipient": body.recipient,
|
|
102
|
+
"amount": body.amount, "token": body.token}
|
|
103
|
+
signer = ReceiptSigner.hmac(bytes(org["receipt_key"]), key_id=org_id)
|
|
104
|
+
with store.org_lock(org_id):
|
|
105
|
+
result = check_payment(**payment, peg_deviation_pct=body.peg_deviation_pct,
|
|
106
|
+
known_recipients=known or None, blocked_addresses=blocked or None,
|
|
107
|
+
spend_guard=guard, payment_id=body.payment_id, **kw)
|
|
108
|
+
prev = store.last_receipt(org_id)
|
|
109
|
+
receipt = issue_receipt(result, signer, payment=payment, policy=policy,
|
|
110
|
+
**({"previous": prev} if prev else {"chain_start": True}))
|
|
111
|
+
seq = store.add_receipt(org_id, receipt)
|
|
112
|
+
out = result.model_dump(mode="json")
|
|
113
|
+
out.update({"receipt": receipt, "receipt_seq": seq, "source": "sra-riskgate-cloud"})
|
|
114
|
+
return out
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def create_app(store: Optional[Store] = None, *, x402_facilitator: Any = None) -> FastAPI:
|
|
118
|
+
"""The app. ``x402_facilitator`` replaces the HTTP facilitator client (for tests)."""
|
|
119
|
+
store = store or Store(os.environ.get("SRA_CLOUD_DB", "sra-cloud.db"))
|
|
120
|
+
min_orgs = _feed_min_orgs()
|
|
121
|
+
plan_limits = plans()
|
|
122
|
+
app = FastAPI(title="SRA-RiskGate Cloud", version=__version__,
|
|
123
|
+
description="Shared budgets, threat feed and receipt vault for agents that pay.")
|
|
124
|
+
app.state.store = store
|
|
125
|
+
|
|
126
|
+
@app.middleware("http")
|
|
127
|
+
async def limit_body(request: Request, call_next):
|
|
128
|
+
size = request.headers.get("content-length")
|
|
129
|
+
if size is not None and (not size.isdigit() or int(size) > MAX_BODY):
|
|
130
|
+
return JSONResponse({"detail": "request body too large"}, status_code=413)
|
|
131
|
+
return await call_next(request)
|
|
132
|
+
|
|
133
|
+
def org_dep(authorization: Optional[str] = Header(None)) -> Any:
|
|
134
|
+
if not authorization or not authorization.startswith("Bearer "):
|
|
135
|
+
raise HTTPException(401, "missing API key: send Authorization: Bearer sra_live_...")
|
|
136
|
+
org = store.org_for_key(authorization[7:].strip())
|
|
137
|
+
if org is None:
|
|
138
|
+
raise HTTPException(401, "invalid or revoked API key")
|
|
139
|
+
return org
|
|
140
|
+
|
|
141
|
+
def feed_addresses() -> List[str]:
|
|
142
|
+
return [x["address"] for x in store.feed(min_orgs)]
|
|
143
|
+
|
|
144
|
+
@app.get("/healthz")
|
|
145
|
+
def healthz():
|
|
146
|
+
return {"ok": True, "service": f"sra-riskgate-cloud {__version__}", "library": f"sra-riskgate {LIB_VERSION}"}
|
|
147
|
+
|
|
148
|
+
@app.post("/v1/check")
|
|
149
|
+
def check(body: CheckIn, org=Depends(org_dep)):
|
|
150
|
+
limit = plan_limits.get(org["plan"], 0)
|
|
151
|
+
used = store.use_check(org["id"], limit)
|
|
152
|
+
if used is None:
|
|
153
|
+
raise HTTPException(429, f"monthly check limit reached for plan {org['plan']} ({limit}); "
|
|
154
|
+
"the client treats this as hold")
|
|
155
|
+
try:
|
|
156
|
+
out = _run_check(store, org, body, feed_addresses=feed_addresses())
|
|
157
|
+
except ValueError as e: # a stored policy that no longer validates
|
|
158
|
+
raise HTTPException(409, f"organisation policy is invalid: {e}") from e
|
|
159
|
+
out["usage"] = {"checks_this_month": used, "limit": limit, "plan": org["plan"]}
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
@app.post("/v1/ledger/release")
|
|
163
|
+
def release(body: ReleaseIn, org=Depends(org_dep)):
|
|
164
|
+
with store.org_lock(org["id"]):
|
|
165
|
+
n = DBLedger(store, org["id"]).remove(body.payment_id)
|
|
166
|
+
return {"released": n}
|
|
167
|
+
|
|
168
|
+
@app.get("/v1/policy")
|
|
169
|
+
def get_policy(org=Depends(org_dep)):
|
|
170
|
+
p = row_policy(org)
|
|
171
|
+
return {"policy": p, "sha256": load_policy(p).sha256}
|
|
172
|
+
|
|
173
|
+
@app.put("/v1/policy")
|
|
174
|
+
def put_policy(policy: Dict[str, Any], org=Depends(org_dep)):
|
|
175
|
+
try:
|
|
176
|
+
p = _validate_policy(policy)
|
|
177
|
+
except ValueError as e:
|
|
178
|
+
raise HTTPException(422, str(e)) from e
|
|
179
|
+
store.set_policy(org["id"], policy)
|
|
180
|
+
return {"policy": policy, "sha256": p.sha256}
|
|
181
|
+
|
|
182
|
+
@app.get("/v1/feed")
|
|
183
|
+
def get_feed(org=Depends(org_dep)):
|
|
184
|
+
items = store.feed(min_orgs)
|
|
185
|
+
return {"addresses": [x["address"] for x in items], "entries": items, "min_orgs": min_orgs,
|
|
186
|
+
"updated": time.time()}
|
|
187
|
+
|
|
188
|
+
@app.post("/v1/feed/report")
|
|
189
|
+
def report(body: ReportIn, org=Depends(org_dep)):
|
|
190
|
+
a, i = _normalise(body.address), _normalise(body.imitates) if body.imitates else None
|
|
191
|
+
if a is None or (body.imitates and i is None):
|
|
192
|
+
raise HTTPException(422, "address and imitates must be EVM addresses")
|
|
193
|
+
store.report(org["id"], a, i, body.chain_id, body.tx)
|
|
194
|
+
listed = a in {x["address"] for x in store.feed(min_orgs)}
|
|
195
|
+
return {"reported": a, "in_feed": listed}
|
|
196
|
+
|
|
197
|
+
@app.get("/v1/receipts")
|
|
198
|
+
def receipts(after: int = 0, limit: int = 1000, org=Depends(org_dep)):
|
|
199
|
+
return {"receipts": store.receipts(org["id"], after=max(0, after), limit=max(1, min(limit, 5000)))}
|
|
200
|
+
|
|
201
|
+
@app.get("/v1/report")
|
|
202
|
+
def report_view(format: str = "json", org=Depends(org_dep)):
|
|
203
|
+
rows = [r["receipt"] for r in store.receipts(org["id"], limit=1_000_000)]
|
|
204
|
+
rep = audit_report(rows, key=bytes(org["receipt_key"]), title=f"{org['name']}: agent payment decisions")
|
|
205
|
+
if format == "md":
|
|
206
|
+
return PlainTextResponse(audit_report_markdown(rep), media_type="text/markdown")
|
|
207
|
+
return rep
|
|
208
|
+
|
|
209
|
+
@app.get("/v1/usage")
|
|
210
|
+
def usage(org=Depends(org_dep)):
|
|
211
|
+
return {"org": org["name"], "plan": org["plan"], "checks_this_month": store.usage(org["id"]),
|
|
212
|
+
"limit": plan_limits.get(org["plan"], 0)}
|
|
213
|
+
|
|
214
|
+
@app.get("/", response_class=HTMLResponse)
|
|
215
|
+
def dashboard():
|
|
216
|
+
from sra_riskgate_cloud.dashboard import PAGE
|
|
217
|
+
return PAGE
|
|
218
|
+
|
|
219
|
+
_mount_x402(app, store, feed_addresses, x402_facilitator)
|
|
220
|
+
return app
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _mount_x402(app: FastAPI, store: Store, feed_addresses, facilitator: Any = None) -> None:
|
|
224
|
+
"""Pay-per-check with x402 on POST /v1/x402/check, if SRA_CLOUD_X402_PAY_TO is set.
|
|
225
|
+
|
|
226
|
+
Uses the official x402 SDK middleware (verification and settlement through the facilitator). Paid checks are
|
|
227
|
+
stateless: no shared ledger, since there is no account; the result carries a receipt signed with the service's
|
|
228
|
+
own key (SRA_CLOUD_X402_RECEIPT_KEY, hex), and the threat feed applies.
|
|
229
|
+
"""
|
|
230
|
+
pay_to = os.environ.get("SRA_CLOUD_X402_PAY_TO")
|
|
231
|
+
if not pay_to:
|
|
232
|
+
return
|
|
233
|
+
if _normalise(pay_to) is None:
|
|
234
|
+
raise ValueError("SRA_CLOUD_X402_PAY_TO must be an EVM address")
|
|
235
|
+
key_hex = os.environ.get("SRA_CLOUD_X402_RECEIPT_KEY")
|
|
236
|
+
if not key_hex:
|
|
237
|
+
raise ValueError("SRA_CLOUD_X402_RECEIPT_KEY (hex) is required with SRA_CLOUD_X402_PAY_TO")
|
|
238
|
+
receipt_key = bytes.fromhex(key_hex)
|
|
239
|
+
try:
|
|
240
|
+
from x402 import x402ResourceServer
|
|
241
|
+
from x402.http import FacilitatorConfig, HTTPFacilitatorClient
|
|
242
|
+
from x402.http.middleware.fastapi import payment_middleware
|
|
243
|
+
from x402.mechanisms.evm.exact import register_exact_evm_server
|
|
244
|
+
except ImportError as e: # pragma: no cover
|
|
245
|
+
raise ImportError("pay-per-check needs the x402 SDK: pip install 'sra-riskgate-cloud[x402]' (x402[fastapi,evm])") from e
|
|
246
|
+
network = os.environ.get("SRA_CLOUD_X402_NETWORK", "eip155:8453")
|
|
247
|
+
price = os.environ.get("SRA_CLOUD_X402_PRICE", "$0.002")
|
|
248
|
+
cfg = {"url": os.environ["SRA_CLOUD_FACILITATOR_URL"]} if os.environ.get("SRA_CLOUD_FACILITATOR_URL") else {}
|
|
249
|
+
facilitator = facilitator or HTTPFacilitatorClient(FacilitatorConfig(**cfg))
|
|
250
|
+
server = register_exact_evm_server(x402ResourceServer(facilitator), network)
|
|
251
|
+
routes = {"POST /v1/x402/check": {"accepts": {"scheme": "exact", "payTo": pay_to, "price": price,
|
|
252
|
+
"network": network},
|
|
253
|
+
"description": "One SRA-RiskGate payment check"}}
|
|
254
|
+
mw = payment_middleware(routes, server)
|
|
255
|
+
|
|
256
|
+
@app.middleware("http")
|
|
257
|
+
async def x402_mw(request, call_next):
|
|
258
|
+
return await mw(request, call_next)
|
|
259
|
+
|
|
260
|
+
signer = ReceiptSigner.hmac(receipt_key, key_id="sra-cloud-x402")
|
|
261
|
+
|
|
262
|
+
@app.post("/v1/x402/check")
|
|
263
|
+
def x402_check(body: CheckIn):
|
|
264
|
+
payment = {"chain_id": body.chain_id, "sender": body.sender, "recipient": body.recipient,
|
|
265
|
+
"amount": body.amount, "token": body.token}
|
|
266
|
+
result = check_payment(**payment, peg_deviation_pct=body.peg_deviation_pct,
|
|
267
|
+
known_recipients=body.known_recipients or None,
|
|
268
|
+
blocked_addresses=feed_addresses() or None, lookalike_check="strict")
|
|
269
|
+
out = result.model_dump(mode="json")
|
|
270
|
+
out.update({"receipt": issue_receipt(result, signer, payment=payment), "source": "sra-riskgate-cloud x402"})
|
|
271
|
+
return out
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""``sra-cloud``: run and administer SRA-RiskGate Cloud.
|
|
2
|
+
|
|
3
|
+
sra-cloud serve [--host 0.0.0.0] [--port 8080]
|
|
4
|
+
sra-cloud create-org "Acme Agents" [--plan team] # prints the org id, its first API key and its receipt key
|
|
5
|
+
sra-cloud new-key ORG_ID [--label ci]
|
|
6
|
+
sra-cloud revoke-key sra_live_XXXXXXX # the first 16 characters shown by list-keys / at creation
|
|
7
|
+
sra-cloud set-plan ORG_ID team
|
|
8
|
+
sra-cloud orgs
|
|
9
|
+
sra-cloud feed [--pending]
|
|
10
|
+
sra-cloud feed-approve 0xADDRESS [--note "..."] / sra-cloud feed-reject 0xADDRESS [--note "..."]
|
|
11
|
+
|
|
12
|
+
The database is SRA_CLOUD_DB (default ./sra-cloud.db).
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
|
|
21
|
+
from sra_riskgate.sanctions import _normalise
|
|
22
|
+
|
|
23
|
+
from sra_riskgate_cloud.db import Store
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _store() -> Store:
|
|
27
|
+
return Store(os.environ.get("SRA_CLOUD_DB", "sra-cloud.db"))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def main(argv=None) -> int:
|
|
31
|
+
p = argparse.ArgumentParser(prog="sra-cloud", description="Run and administer SRA-RiskGate Cloud.")
|
|
32
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
33
|
+
s = sub.add_parser("serve"); s.add_argument("--host", default="0.0.0.0"); s.add_argument("--port", type=int,
|
|
34
|
+
default=8080)
|
|
35
|
+
c = sub.add_parser("create-org"); c.add_argument("name"); c.add_argument("--plan", default="free")
|
|
36
|
+
k = sub.add_parser("new-key"); k.add_argument("org_id"); k.add_argument("--label")
|
|
37
|
+
r = sub.add_parser("revoke-key"); r.add_argument("prefix")
|
|
38
|
+
sp = sub.add_parser("set-plan"); sp.add_argument("org_id"); sp.add_argument("plan")
|
|
39
|
+
sub.add_parser("orgs")
|
|
40
|
+
f = sub.add_parser("feed"); f.add_argument("--pending", action="store_true")
|
|
41
|
+
for name in ("feed-approve", "feed-reject"):
|
|
42
|
+
x = sub.add_parser(name); x.add_argument("address"); x.add_argument("--note")
|
|
43
|
+
a = p.parse_args(argv)
|
|
44
|
+
try:
|
|
45
|
+
if a.cmd == "serve":
|
|
46
|
+
import uvicorn
|
|
47
|
+
from sra_riskgate_cloud.app import create_app
|
|
48
|
+
uvicorn.run(create_app(_store()), host=a.host, port=a.port, proxy_headers=True)
|
|
49
|
+
return 0
|
|
50
|
+
st = _store()
|
|
51
|
+
if a.cmd == "create-org":
|
|
52
|
+
out = st.create_org(a.name, a.plan)
|
|
53
|
+
print(json.dumps(out, indent=2))
|
|
54
|
+
print("Save the API key and receipt key now: they are not shown again.", file=sys.stderr)
|
|
55
|
+
elif a.cmd == "new-key":
|
|
56
|
+
print(st.new_key(a.org_id, a.label))
|
|
57
|
+
elif a.cmd == "revoke-key":
|
|
58
|
+
n = st.revoke_key(a.prefix[:16])
|
|
59
|
+
print(f"revoked {n} key(s)")
|
|
60
|
+
return 0 if n else 1
|
|
61
|
+
elif a.cmd == "set-plan":
|
|
62
|
+
st.set_plan(a.org_id, a.plan)
|
|
63
|
+
print(f"{a.org_id}: {a.plan}")
|
|
64
|
+
elif a.cmd == "orgs":
|
|
65
|
+
for o in st.orgs():
|
|
66
|
+
print(f"{o['id']} {o['plan']:<6} {o['name']}")
|
|
67
|
+
elif a.cmd == "feed":
|
|
68
|
+
from sra_riskgate_cloud.app import _feed_min_orgs
|
|
69
|
+
rows = st.pending_reports(_feed_min_orgs()) if a.pending else st.feed(_feed_min_orgs())
|
|
70
|
+
print(json.dumps(rows, indent=2))
|
|
71
|
+
else:
|
|
72
|
+
addr = _normalise(a.address)
|
|
73
|
+
if addr is None:
|
|
74
|
+
raise ValueError("not an EVM address")
|
|
75
|
+
st.review(addr, "approved" if a.cmd == "feed-approve" else "rejected", a.note)
|
|
76
|
+
print(f"{addr}: {'approved' if a.cmd == 'feed-approve' else 'rejected'}")
|
|
77
|
+
return 0
|
|
78
|
+
except ValueError as e:
|
|
79
|
+
print(f"sra-cloud: {e}", file=sys.stderr)
|
|
80
|
+
return 3
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
if __name__ == "__main__": # pragma: no cover
|
|
84
|
+
sys.exit(main())
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""A one-page dashboard. The API key stays in the browser tab (sessionStorage) and is sent only to this service."""
|
|
2
|
+
|
|
3
|
+
PAGE = """<!DOCTYPE html>
|
|
4
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
5
|
+
<title>SRA-RiskGate Cloud</title>
|
|
6
|
+
<style>
|
|
7
|
+
:root { --ink:#1a2a44; --mid:#556578; --rule:#d4dce8; --panel:#f4f6f9; --accent:#1a5cc8; }
|
|
8
|
+
body { font: 15px/1.5 system-ui, sans-serif; color: var(--ink); margin: 0; background: #fff; }
|
|
9
|
+
main { max-width: 960px; margin: 0 auto; padding: 32px 20px; }
|
|
10
|
+
h1 { font-size: 22px; margin: 0 0 4px; } p.sub { color: var(--mid); margin: 0 0 24px; }
|
|
11
|
+
.row { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin-bottom: 24px; }
|
|
12
|
+
.tile { background: var(--panel); border-radius: 8px; padding: 14px 16px; }
|
|
13
|
+
.tile b { display: block; font-size: 24px; } .tile span { color: var(--mid); font-size: 13px; }
|
|
14
|
+
table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
|
15
|
+
th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--rule); }
|
|
16
|
+
code { font-size: 12px; } input { width: 340px; max-width: 100%; padding: 8px; border: 1px solid var(--rule);
|
|
17
|
+
border-radius: 6px; } button { padding: 8px 14px; border: 0; border-radius: 6px; background: var(--accent);
|
|
18
|
+
color: #fff; cursor: pointer; } .err { color: #b42318; } .approve { color: #067647 } .hold { color: #b54708 }
|
|
19
|
+
.reject { color: #b42318 }
|
|
20
|
+
</style></head><body><main>
|
|
21
|
+
<h1>SRA-RiskGate Cloud</h1><p class="sub">Shared budgets, threat feed and signed decisions for your agents.</p>
|
|
22
|
+
<form id="f"><input id="k" type="password" placeholder="sra_live_..." autocomplete="off">
|
|
23
|
+
<button>Open</button></form><p id="msg"></p>
|
|
24
|
+
<section id="out" hidden>
|
|
25
|
+
<div class="row"><div class="tile"><b id="plan"></b><span>plan</span></div>
|
|
26
|
+
<div class="tile"><b id="used"></b><span>checks this month</span></div>
|
|
27
|
+
<div class="tile"><b id="verified"></b><span>receipts verified</span></div>
|
|
28
|
+
<div class="tile"><b id="feed"></b><span>addresses in threat feed</span></div></div>
|
|
29
|
+
<h2>Recent decisions</h2>
|
|
30
|
+
<table><thead><tr><th>#</th><th>When</th><th>Decision</th><th>Payee</th><th>Amount</th><th>Flags</th></tr></thead>
|
|
31
|
+
<tbody id="rows"></tbody></table>
|
|
32
|
+
</section>
|
|
33
|
+
<script>
|
|
34
|
+
const $ = (id) => document.getElementById(id);
|
|
35
|
+
let key = null; try { key = sessionStorage.getItem("sra_key"); } catch (e) {}
|
|
36
|
+
async function api(path) {
|
|
37
|
+
const r = await fetch(path, { headers: { Authorization: "Bearer " + key } });
|
|
38
|
+
if (!r.ok) throw new Error((await r.json()).detail || r.status);
|
|
39
|
+
return r.json();
|
|
40
|
+
}
|
|
41
|
+
function text(el, v) { el.textContent = v; return el; }
|
|
42
|
+
async function load() {
|
|
43
|
+
$("msg").textContent = "";
|
|
44
|
+
try {
|
|
45
|
+
const [u, rep, feed, rec] = await Promise.all([api("/v1/usage"), api("/v1/report"), api("/v1/feed"),
|
|
46
|
+
api("/v1/receipts?limit=5000")]);
|
|
47
|
+
text($("plan"), u.plan); text($("used"), u.checks_this_month + " / " + u.limit);
|
|
48
|
+
text($("verified"), rep.verified + " / " + rep.receipts); text($("feed"), feed.addresses.length);
|
|
49
|
+
const body = $("rows"); body.replaceChildren();
|
|
50
|
+
rec.receipts.slice(-50).reverse().forEach((x) => {
|
|
51
|
+
const r = x.receipt, p = r.payment || {}, tr = document.createElement("tr");
|
|
52
|
+
[x.seq, r.issued_at, r.decision, p.recipient || "", (p.amount ?? "") + " " + (p.token || ""),
|
|
53
|
+
(r.flags || []).join(", ")].forEach((v, i) => { const td = text(document.createElement("td"), v);
|
|
54
|
+
if (i === 2) td.className = v; tr.appendChild(td); });
|
|
55
|
+
body.appendChild(tr);
|
|
56
|
+
});
|
|
57
|
+
$("out").hidden = false;
|
|
58
|
+
} catch (e) { $("out").hidden = true; $("msg").className = "err"; text($("msg"), "Could not load: " + e.message); }
|
|
59
|
+
}
|
|
60
|
+
$("f").addEventListener("submit", (ev) => { ev.preventDefault(); key = $("k").value.trim();
|
|
61
|
+
try { sessionStorage.setItem("sra_key", key); } catch (e) {} load(); });
|
|
62
|
+
if (key) load();
|
|
63
|
+
</script></main></body></html>
|
|
64
|
+
"""
|
sra_riskgate_cloud/db.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""SQLite storage for SRA-RiskGate Cloud: organisations, API keys, the shared spend ledger, the receipt vault,
|
|
2
|
+
usage and the threat feed.
|
|
3
|
+
|
|
4
|
+
One process, one database file. Writes that must be atomic (a budget check plus its ledger entry, a receipt and its
|
|
5
|
+
place in the chain) run under a per-organisation lock inside one transaction. Run a single instance; see README.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import secrets
|
|
14
|
+
import sqlite3
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from typing import Any, Dict, Iterator, List, Optional
|
|
18
|
+
|
|
19
|
+
from sra_riskgate.spend import SpendLedger
|
|
20
|
+
|
|
21
|
+
SCHEMA = """
|
|
22
|
+
PRAGMA journal_mode=WAL;
|
|
23
|
+
CREATE TABLE IF NOT EXISTS orgs (
|
|
24
|
+
id TEXT PRIMARY KEY, name TEXT NOT NULL, plan TEXT NOT NULL, created REAL NOT NULL,
|
|
25
|
+
receipt_key BLOB NOT NULL, policy TEXT NOT NULL DEFAULT '{"version": 1}'
|
|
26
|
+
);
|
|
27
|
+
CREATE TABLE IF NOT EXISTS api_keys (
|
|
28
|
+
hash TEXT PRIMARY KEY, prefix TEXT NOT NULL, org_id TEXT NOT NULL REFERENCES orgs(id), label TEXT,
|
|
29
|
+
created REAL NOT NULL, revoked REAL
|
|
30
|
+
);
|
|
31
|
+
CREATE TABLE IF NOT EXISTS ledger (
|
|
32
|
+
org_id TEXT NOT NULL, t REAL NOT NULL, chain_id INTEGER, sender TEXT NOT NULL, recipient TEXT NOT NULL,
|
|
33
|
+
token TEXT, amount REAL NOT NULL, pid TEXT
|
|
34
|
+
);
|
|
35
|
+
CREATE INDEX IF NOT EXISTS ledger_org_sender_t ON ledger(org_id, sender, t);
|
|
36
|
+
CREATE TABLE IF NOT EXISTS receipts (
|
|
37
|
+
org_id TEXT NOT NULL, seq INTEGER NOT NULL, t REAL NOT NULL, receipt TEXT NOT NULL, PRIMARY KEY (org_id, seq)
|
|
38
|
+
);
|
|
39
|
+
CREATE TABLE IF NOT EXISTS usage (
|
|
40
|
+
org_id TEXT NOT NULL, month TEXT NOT NULL, checks INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (org_id, month)
|
|
41
|
+
);
|
|
42
|
+
CREATE TABLE IF NOT EXISTS feed_reports (
|
|
43
|
+
address TEXT NOT NULL, org_id TEXT NOT NULL, imitates TEXT, chain_id INTEGER, tx TEXT, t REAL NOT NULL,
|
|
44
|
+
PRIMARY KEY (address, org_id)
|
|
45
|
+
);
|
|
46
|
+
CREATE TABLE IF NOT EXISTS feed_review (
|
|
47
|
+
address TEXT PRIMARY KEY, status TEXT NOT NULL CHECK (status IN ('approved', 'rejected')), note TEXT,
|
|
48
|
+
t REAL NOT NULL
|
|
49
|
+
);
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
DEFAULT_PLANS = {"free": 1_000, "team": 100_000, "scale": 2_000_000}
|
|
53
|
+
KEY_PREFIX = "sra_live_"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def plans() -> Dict[str, int]:
|
|
57
|
+
"""Monthly check limits per plan, from SRA_CLOUD_PLANS (JSON) or the defaults."""
|
|
58
|
+
raw = os.environ.get("SRA_CLOUD_PLANS")
|
|
59
|
+
if not raw:
|
|
60
|
+
return dict(DEFAULT_PLANS)
|
|
61
|
+
data = json.loads(raw)
|
|
62
|
+
if not isinstance(data, dict) or not all(isinstance(k, str) and isinstance(v, int) and v > 0
|
|
63
|
+
for k, v in data.items()):
|
|
64
|
+
raise ValueError("SRA_CLOUD_PLANS must be a JSON object of plan name to a positive monthly check limit")
|
|
65
|
+
return data
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def hash_key(key: str) -> str:
|
|
69
|
+
return hashlib.sha256(key.encode("utf-8")).hexdigest()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def month(t: Optional[float] = None) -> str:
|
|
73
|
+
return time.strftime("%Y-%m", time.gmtime(time.time() if t is None else t))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Store:
|
|
77
|
+
"""All database access. Thread-safe: each call opens its own connection."""
|
|
78
|
+
|
|
79
|
+
def __init__(self, path: str):
|
|
80
|
+
self.path = path
|
|
81
|
+
self._locks: Dict[str, threading.Lock] = {}
|
|
82
|
+
self._locks_guard = threading.Lock()
|
|
83
|
+
d = os.path.dirname(os.path.abspath(path))
|
|
84
|
+
os.makedirs(d, exist_ok=True)
|
|
85
|
+
with self.conn() as c:
|
|
86
|
+
c.executescript(SCHEMA)
|
|
87
|
+
|
|
88
|
+
@contextlib.contextmanager
|
|
89
|
+
def conn(self) -> Iterator[sqlite3.Connection]:
|
|
90
|
+
c = sqlite3.connect(self.path, timeout=30, isolation_level=None)
|
|
91
|
+
c.row_factory = sqlite3.Row
|
|
92
|
+
try:
|
|
93
|
+
yield c
|
|
94
|
+
finally:
|
|
95
|
+
c.close()
|
|
96
|
+
|
|
97
|
+
@contextlib.contextmanager
|
|
98
|
+
def org_lock(self, org_id: str) -> Iterator[None]:
|
|
99
|
+
with self._locks_guard:
|
|
100
|
+
lock = self._locks.setdefault(org_id, threading.Lock())
|
|
101
|
+
with lock:
|
|
102
|
+
yield
|
|
103
|
+
|
|
104
|
+
# ------------------------------------------------------------ orgs and keys
|
|
105
|
+
|
|
106
|
+
def create_org(self, name: str, plan: str = "free") -> Dict[str, str]:
|
|
107
|
+
if not isinstance(name, str) or not name.strip():
|
|
108
|
+
raise ValueError("name is required")
|
|
109
|
+
if plan not in plans():
|
|
110
|
+
raise ValueError(f"unknown plan {plan!r}; plans: {', '.join(plans())}")
|
|
111
|
+
org_id = "org_" + secrets.token_hex(8)
|
|
112
|
+
receipt_key = secrets.token_bytes(32)
|
|
113
|
+
with self.conn() as c:
|
|
114
|
+
c.execute("INSERT INTO orgs (id, name, plan, created, receipt_key) VALUES (?,?,?,?,?)",
|
|
115
|
+
(org_id, name.strip(), plan, time.time(), receipt_key))
|
|
116
|
+
key = self.new_key(org_id, label="first key")
|
|
117
|
+
return {"org_id": org_id, "api_key": key, "receipt_key_hex": receipt_key.hex()}
|
|
118
|
+
|
|
119
|
+
def new_key(self, org_id: str, label: Optional[str] = None) -> str:
|
|
120
|
+
key = KEY_PREFIX + secrets.token_urlsafe(32)
|
|
121
|
+
with self.conn() as c:
|
|
122
|
+
if c.execute("SELECT 1 FROM orgs WHERE id=?", (org_id,)).fetchone() is None:
|
|
123
|
+
raise ValueError(f"no organisation {org_id}")
|
|
124
|
+
c.execute("INSERT INTO api_keys (hash, prefix, org_id, label, created) VALUES (?,?,?,?,?)",
|
|
125
|
+
(hash_key(key), key[:16], org_id, label, time.time()))
|
|
126
|
+
return key
|
|
127
|
+
|
|
128
|
+
def revoke_key(self, prefix: str) -> int:
|
|
129
|
+
with self.conn() as c:
|
|
130
|
+
return c.execute("UPDATE api_keys SET revoked=? WHERE prefix=? AND revoked IS NULL",
|
|
131
|
+
(time.time(), prefix)).rowcount
|
|
132
|
+
|
|
133
|
+
def org_for_key(self, key: str) -> Optional[sqlite3.Row]:
|
|
134
|
+
if not isinstance(key, str) or not key.startswith(KEY_PREFIX):
|
|
135
|
+
return None
|
|
136
|
+
with self.conn() as c:
|
|
137
|
+
return c.execute("SELECT o.* FROM api_keys k JOIN orgs o ON o.id=k.org_id "
|
|
138
|
+
"WHERE k.hash=? AND k.revoked IS NULL", (hash_key(key),)).fetchone()
|
|
139
|
+
|
|
140
|
+
def org(self, org_id: str) -> Optional[sqlite3.Row]:
|
|
141
|
+
with self.conn() as c:
|
|
142
|
+
return c.execute("SELECT * FROM orgs WHERE id=?", (org_id,)).fetchone()
|
|
143
|
+
|
|
144
|
+
def orgs(self) -> List[sqlite3.Row]:
|
|
145
|
+
with self.conn() as c:
|
|
146
|
+
return c.execute("SELECT id, name, plan, created FROM orgs ORDER BY created").fetchall()
|
|
147
|
+
|
|
148
|
+
def set_plan(self, org_id: str, plan: str) -> None:
|
|
149
|
+
if plan not in plans():
|
|
150
|
+
raise ValueError(f"unknown plan {plan!r}; plans: {', '.join(plans())}")
|
|
151
|
+
with self.conn() as c:
|
|
152
|
+
if c.execute("UPDATE orgs SET plan=? WHERE id=?", (plan, org_id)).rowcount != 1:
|
|
153
|
+
raise ValueError(f"no organisation {org_id}")
|
|
154
|
+
|
|
155
|
+
def set_policy(self, org_id: str, policy: dict) -> None:
|
|
156
|
+
with self.conn() as c:
|
|
157
|
+
c.execute("UPDATE orgs SET policy=? WHERE id=?", (json.dumps(policy, sort_keys=True), org_id))
|
|
158
|
+
|
|
159
|
+
# ------------------------------------------------------------ usage
|
|
160
|
+
|
|
161
|
+
def use_check(self, org_id: str, limit: int, now: Optional[float] = None) -> Optional[int]:
|
|
162
|
+
"""Count one check this month. Returns the new count, or None if the limit was already reached."""
|
|
163
|
+
m = month(now)
|
|
164
|
+
with self.conn() as c:
|
|
165
|
+
c.execute("BEGIN IMMEDIATE")
|
|
166
|
+
row = c.execute("SELECT checks FROM usage WHERE org_id=? AND month=?", (org_id, m)).fetchone()
|
|
167
|
+
n = row["checks"] if row else 0
|
|
168
|
+
if n >= limit:
|
|
169
|
+
c.execute("ROLLBACK")
|
|
170
|
+
return None
|
|
171
|
+
c.execute("INSERT INTO usage (org_id, month, checks) VALUES (?,?,1) ON CONFLICT(org_id, month) "
|
|
172
|
+
"DO UPDATE SET checks=checks+1", (org_id, m))
|
|
173
|
+
c.execute("COMMIT")
|
|
174
|
+
return n + 1
|
|
175
|
+
|
|
176
|
+
def usage(self, org_id: str, now: Optional[float] = None) -> int:
|
|
177
|
+
with self.conn() as c:
|
|
178
|
+
row = c.execute("SELECT checks FROM usage WHERE org_id=? AND month=?", (org_id, month(now))).fetchone()
|
|
179
|
+
return row["checks"] if row else 0
|
|
180
|
+
|
|
181
|
+
# ------------------------------------------------------------ receipts
|
|
182
|
+
|
|
183
|
+
def last_receipt(self, org_id: str) -> Optional[dict]:
|
|
184
|
+
with self.conn() as c:
|
|
185
|
+
row = c.execute("SELECT receipt FROM receipts WHERE org_id=? ORDER BY seq DESC LIMIT 1",
|
|
186
|
+
(org_id,)).fetchone()
|
|
187
|
+
return json.loads(row["receipt"]) if row else None
|
|
188
|
+
|
|
189
|
+
def add_receipt(self, org_id: str, receipt: dict) -> int:
|
|
190
|
+
with self.conn() as c:
|
|
191
|
+
c.execute("BEGIN IMMEDIATE")
|
|
192
|
+
seq = (c.execute("SELECT MAX(seq) FROM receipts WHERE org_id=?", (org_id,)).fetchone()[0] or 0) + 1
|
|
193
|
+
c.execute("INSERT INTO receipts (org_id, seq, t, receipt) VALUES (?,?,?,?)",
|
|
194
|
+
(org_id, seq, time.time(), json.dumps(receipt, sort_keys=True)))
|
|
195
|
+
c.execute("COMMIT")
|
|
196
|
+
return seq
|
|
197
|
+
|
|
198
|
+
def receipts(self, org_id: str, after: int = 0, limit: int = 1000) -> List[dict]:
|
|
199
|
+
with self.conn() as c:
|
|
200
|
+
rows = c.execute("SELECT seq, receipt FROM receipts WHERE org_id=? AND seq>? ORDER BY seq LIMIT ?",
|
|
201
|
+
(org_id, after, limit)).fetchall()
|
|
202
|
+
return [{"seq": r["seq"], "receipt": json.loads(r["receipt"])} for r in rows]
|
|
203
|
+
|
|
204
|
+
# ------------------------------------------------------------ threat feed
|
|
205
|
+
|
|
206
|
+
def report(self, org_id: str, address: str, imitates: Optional[str], chain_id: Optional[int],
|
|
207
|
+
tx: Optional[str]) -> None:
|
|
208
|
+
with self.conn() as c:
|
|
209
|
+
c.execute("INSERT INTO feed_reports (address, org_id, imitates, chain_id, tx, t) VALUES (?,?,?,?,?,?) "
|
|
210
|
+
"ON CONFLICT(address, org_id) DO UPDATE SET imitates=excluded.imitates, "
|
|
211
|
+
"chain_id=excluded.chain_id, tx=excluded.tx, t=excluded.t",
|
|
212
|
+
(address, org_id, imitates, chain_id, tx, time.time()))
|
|
213
|
+
|
|
214
|
+
def review(self, address: str, status: str, note: Optional[str] = None) -> None:
|
|
215
|
+
if status not in ("approved", "rejected"):
|
|
216
|
+
raise ValueError("status must be approved or rejected")
|
|
217
|
+
with self.conn() as c:
|
|
218
|
+
c.execute("INSERT INTO feed_review (address, status, note, t) VALUES (?,?,?,?) ON CONFLICT(address) "
|
|
219
|
+
"DO UPDATE SET status=excluded.status, note=excluded.note, t=excluded.t",
|
|
220
|
+
(address, status, note, time.time()))
|
|
221
|
+
|
|
222
|
+
def feed(self, min_orgs: int) -> List[dict]:
|
|
223
|
+
"""Addresses in the feed: approved by an operator, or reported by at least ``min_orgs`` organisations and
|
|
224
|
+
not rejected by an operator. One organisation alone can never put an address in everyone's feed."""
|
|
225
|
+
with self.conn() as c:
|
|
226
|
+
rows = c.execute(
|
|
227
|
+
"SELECT r.address, COUNT(DISTINCT r.org_id) AS orgs, MIN(r.t) AS first_seen, "
|
|
228
|
+
"MAX(r.imitates) AS imitates, MAX(r.chain_id) AS chain_id, v.status "
|
|
229
|
+
"FROM feed_reports r LEFT JOIN feed_review v ON v.address=r.address GROUP BY r.address "
|
|
230
|
+
"UNION SELECT v.address, 0, v.t, NULL, NULL, v.status FROM feed_review v "
|
|
231
|
+
"WHERE v.status='approved' AND v.address NOT IN (SELECT address FROM feed_reports)").fetchall()
|
|
232
|
+
out = []
|
|
233
|
+
for r in rows:
|
|
234
|
+
if r["status"] == "rejected":
|
|
235
|
+
continue
|
|
236
|
+
if r["status"] == "approved" or r["orgs"] >= min_orgs:
|
|
237
|
+
out.append({"address": r["address"], "reports": r["orgs"], "imitates": r["imitates"],
|
|
238
|
+
"chain_id": r["chain_id"], "first_seen": r["first_seen"],
|
|
239
|
+
"reviewed": r["status"] == "approved"})
|
|
240
|
+
return sorted(out, key=lambda x: x["address"])
|
|
241
|
+
|
|
242
|
+
def pending_reports(self, min_orgs: int) -> List[dict]:
|
|
243
|
+
listed = {x["address"] for x in self.feed(min_orgs)}
|
|
244
|
+
with self.conn() as c:
|
|
245
|
+
rows = c.execute("SELECT r.address, COUNT(DISTINCT r.org_id) AS orgs, MAX(r.imitates) AS imitates "
|
|
246
|
+
"FROM feed_reports r LEFT JOIN feed_review v ON v.address=r.address "
|
|
247
|
+
"WHERE v.status IS NULL GROUP BY r.address").fetchall()
|
|
248
|
+
return [dict(r) for r in rows if r["address"] not in listed]
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class DBLedger(SpendLedger):
|
|
252
|
+
"""A ``SpendLedger`` kept in the cloud database for one organisation, so every machine shares one budget."""
|
|
253
|
+
|
|
254
|
+
def __init__(self, store: Store, org_id: str):
|
|
255
|
+
super().__init__(None)
|
|
256
|
+
self.store, self.org_id = store, org_id
|
|
257
|
+
|
|
258
|
+
def entries(self, sender: str, since: float) -> List[dict]:
|
|
259
|
+
with self.store.conn() as c:
|
|
260
|
+
rows = c.execute("SELECT t, chain_id, sender, recipient, token, amount, pid FROM ledger "
|
|
261
|
+
"WHERE org_id=? AND sender=? AND t>=? ORDER BY t", (self.org_id, sender.lower(), since))
|
|
262
|
+
return [{"t": r["t"], "chain_id": r["chain_id"], "sender": r["sender"], "recipient": r["recipient"],
|
|
263
|
+
"token": r["token"], "amount": r["amount"], "id": r["pid"]} for r in rows]
|
|
264
|
+
|
|
265
|
+
def append(self, entry: dict) -> None:
|
|
266
|
+
with self.store.conn() as c:
|
|
267
|
+
c.execute("INSERT INTO ledger (org_id, t, chain_id, sender, recipient, token, amount, pid) "
|
|
268
|
+
"VALUES (?,?,?,?,?,?,?,?)",
|
|
269
|
+
(self.org_id, entry["t"], entry.get("chain_id"), entry["sender"], entry["recipient"],
|
|
270
|
+
entry.get("token"), entry["amount"], entry.get("id")))
|
|
271
|
+
|
|
272
|
+
def remove(self, payment_id: str) -> int:
|
|
273
|
+
with self.store.conn() as c:
|
|
274
|
+
return c.execute("DELETE FROM ledger WHERE org_id=? AND pid=?", (self.org_id, payment_id)).rowcount
|
|
275
|
+
|
|
276
|
+
def compact(self, now: Optional[float] = None) -> int:
|
|
277
|
+
cutoff = (now if now is not None else time.time()) - 31 * 86_400
|
|
278
|
+
with self.store.conn() as c:
|
|
279
|
+
return c.execute("DELETE FROM ledger WHERE org_id=? AND t<?", (self.org_id, cutoff)).rowcount
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def row_policy(row: Any) -> dict:
|
|
283
|
+
return json.loads(row["policy"]) if row is not None else {"version": 1}
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def as_dict(row: Any) -> Dict[str, Any]:
|
|
287
|
+
return {k: row[k] for k in row.keys()} if row is not None else {}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sra-riskgate-cloud
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SRA-RiskGate Cloud: shared spend budgets, a threat feed and a signed receipt vault for AI agents that pay.
|
|
5
|
+
Author: Sriram Ramakrishnan
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/sriram1983007-dev/sra-riskgate/tree/main/cloud
|
|
8
|
+
Keywords: stablecoin,payments,ai-agents,x402,risk,budgets,audit
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: sra-riskgate>=2.0.0
|
|
13
|
+
Requires-Dist: fastapi>=0.110
|
|
14
|
+
Requires-Dist: uvicorn>=0.29
|
|
15
|
+
Provides-Extra: x402
|
|
16
|
+
Requires-Dist: x402[evm,fastapi]<3,>=2.25; extra == "x402"
|
|
17
|
+
Provides-Extra: test
|
|
18
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
19
|
+
Requires-Dist: httpx>=0.27; extra == "test"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# SRA-RiskGate Cloud
|
|
23
|
+
|
|
24
|
+
The hosted service behind `sra_riskgate.cloud` (sra-riskgate 2.0.0+). The library stays free, offline and open
|
|
25
|
+
source. The cloud adds what one machine cannot do alone:
|
|
26
|
+
|
|
27
|
+
| Feature | What it does |
|
|
28
|
+
| --- | --- |
|
|
29
|
+
| Shared budgets | One spend ledger for every machine an organisation's agents run on. The budget check and its ledger entry happen together, so eight workers racing for the last $30 of a budget cannot all win. |
|
|
30
|
+
| Threat feed | Look-alike addresses reported by poisoning scans. An address enters everyone's feed only when at least two organisations report it (`SRA_CLOUD_FEED_MIN_ORGS`, never below 2) or an operator approves it, so no single customer can block an address for everyone. |
|
|
31
|
+
| Receipt vault | Every cloud decision is signed with the organisation's own key, chained to the one before and stored. `GET /v1/report` builds the audit report. |
|
|
32
|
+
| Pay per check (x402) | `POST /v1/x402/check`: agents with no account pay per check in USDC, through the official x402 SDK and a facilitator. Stateless: no shared ledger, since there is no account. |
|
|
33
|
+
| Dashboard | `GET /`: plan, usage, verified receipts, feed size and recent decisions. The API key stays in the browser tab. |
|
|
34
|
+
|
|
35
|
+
The payment's free text never reaches the service: `CloudClient.check_payment` checks it locally first and sends
|
|
36
|
+
only the payment fields.
|
|
37
|
+
|
|
38
|
+
## API
|
|
39
|
+
|
|
40
|
+
All `/v1` routes except `/v1/x402/check` need `Authorization: Bearer sra_live_...`.
|
|
41
|
+
|
|
42
|
+
| Route | |
|
|
43
|
+
| --- | --- |
|
|
44
|
+
| `POST /v1/check` | `{chain_id, sender, recipient, amount, token?, peg_deviation_pct?, payment_id?, known_recipients?}`: the decision, flags, signed `receipt`, `usage`. 429 when the plan's monthly limit is reached. |
|
|
45
|
+
| `POST /v1/ledger/release` | `{payment_id}`: give back the budget of an approved payment that was never sent. |
|
|
46
|
+
| `GET /v1/policy`, `PUT /v1/policy` | The organisation's policy, in the library's [policy format](../README.md); `ledger` and `screening` are refused. |
|
|
47
|
+
| `GET /v1/feed`, `POST /v1/feed/report` | The threat feed; report `{address, imitates?, chain_id?, tx?}`. |
|
|
48
|
+
| `GET /v1/receipts?after=&limit=`, `GET /v1/report?format=json\|md` | The vault and its audit report. |
|
|
49
|
+
| `GET /v1/usage` | Checks used this month and the plan's limit. |
|
|
50
|
+
| `POST /v1/x402/check` | Pay-per-check (when configured). |
|
|
51
|
+
| `GET /healthz`, `GET /` | Health and dashboard. |
|
|
52
|
+
|
|
53
|
+
## Run it locally
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pip install -e . -e "./cloud[x402]" # from the repository root
|
|
57
|
+
export SRA_CLOUD_DB=./sra-cloud.db
|
|
58
|
+
sra-cloud create-org "My team" --plan free # prints org id, API key and receipt key: save them
|
|
59
|
+
sra-cloud serve --port 8080
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from sra_riskgate import CloudClient
|
|
64
|
+
cloud = CloudClient(api_key="sra_live_...", base_url="http://localhost:8080")
|
|
65
|
+
cloud.set_policy({"version": 1, "budgets": {"window_hours": 24, "total": 500}})
|
|
66
|
+
r = cloud.check_payment(chain_id=8453, sender=agent, recipient=payee, amount=25, peg_deviation_pct=0.0)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Deploy on Fly.io
|
|
70
|
+
|
|
71
|
+
From the repository root, with [flyctl](https://fly.io/docs/flyctl/install/) installed and `fly auth login` done:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
fly apps create YOUR-APP-NAME # then set app = "YOUR-APP-NAME" in cloud/fly.toml
|
|
75
|
+
fly volumes create sra_data --size 1 --region iad --config cloud/fly.toml
|
|
76
|
+
fly deploy --config cloud/fly.toml --dockerfile cloud/Dockerfile
|
|
77
|
+
fly ssh console --config cloud/fly.toml -C 'sra-cloud create-org "First customer" --plan free'
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Optional settings (`fly secrets set NAME=value --config cloud/fly.toml`):
|
|
81
|
+
|
|
82
|
+
| Variable | Default | |
|
|
83
|
+
| --- | --- | --- |
|
|
84
|
+
| `SRA_CLOUD_PLANS` | `{"free": 1000, "team": 100000, "scale": 2000000}` | Monthly check limit per plan |
|
|
85
|
+
| `SRA_CLOUD_FEED_MIN_ORGS` | `2` | Organisations that must report an address before it enters the feed (2 or more) |
|
|
86
|
+
| `SRA_CLOUD_X402_PAY_TO` | unset | Your USDC address: turns on pay-per-check |
|
|
87
|
+
| `SRA_CLOUD_X402_RECEIPT_KEY` | unset | Hex key that signs pay-per-check receipts (required with the above): `python -c "import secrets; print(secrets.token_hex(32))"` |
|
|
88
|
+
| `SRA_CLOUD_X402_PRICE` | `$0.002` | Price per check |
|
|
89
|
+
| `SRA_CLOUD_X402_NETWORK` | `eip155:8453` | Base mainnet. `eip155:84532` for Base Sepolia while testing |
|
|
90
|
+
| `SRA_CLOUD_FACILITATOR_URL` | x402 SDK default | Facilitator for verify and settle |
|
|
91
|
+
|
|
92
|
+
## Operate it
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
sra-cloud orgs # list organisations
|
|
96
|
+
sra-cloud new-key ORG_ID --label ci # another key; revoke with: sra-cloud revoke-key sra_live_XXXXXXX
|
|
97
|
+
sra-cloud set-plan ORG_ID team
|
|
98
|
+
sra-cloud feed --pending # reports not yet in the feed
|
|
99
|
+
sra-cloud feed-approve 0x... / sra-cloud feed-reject 0x... --note "false positive"
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Back up `/data/sra-cloud.db` (Fly volume snapshots are on by default; copy it off-site too). It holds API key
|
|
103
|
+
hashes, organisation receipt keys, the ledger and the vault.
|
|
104
|
+
|
|
105
|
+
## Limits of this version (0.1.0)
|
|
106
|
+
|
|
107
|
+
- **One instance.** Atomic budgets rely on one process and one SQLite file. Keep `min_machines_running = 1` and do
|
|
108
|
+
not scale out until the ledger moves to Postgres.
|
|
109
|
+
- **No self-serve signup or card billing yet.** You create organisations with `sra-cloud create-org` and invoice by
|
|
110
|
+
hand; x402 pay-per-check needs no account.
|
|
111
|
+
- **Receipt keys are held by the service** so it can sign; the organisation gets a copy at creation to verify
|
|
112
|
+
receipts independently. Treat the database as secret.
|
|
113
|
+
- **Get an independent security review before taking money**: the service holds budgets, keys and decision records.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
sra_riskgate_cloud/__init__.py,sha256=N1fTzHnRmm-Ugq-7tQzEHooM87jGceH5hqgXSW8q8DU,119
|
|
2
|
+
sra_riskgate_cloud/app.py,sha256=W4HewHIz0rcNzd9ziccq3KR4xFsIeULRznxCL9a9B_0,13474
|
|
3
|
+
sra_riskgate_cloud/cli.py,sha256=OVLfweLIaPIFAR_4MATy1pmPmEl2J9y-Tq_troMLmCY,3621
|
|
4
|
+
sra_riskgate_cloud/dashboard.py,sha256=z07Wd81dGSGuAA_KHgbx3z3l9kvzNcPsMJHwK27iZF8,3932
|
|
5
|
+
sra_riskgate_cloud/db.py,sha256=SY5yOLLKeRY0WTOrr-XQN3AIVk1_z-PPH_JmAHffyCw,13799
|
|
6
|
+
sra_riskgate_cloud-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
7
|
+
sra_riskgate_cloud-0.1.0.dist-info/METADATA,sha256=9_DtWMZkj2IJueJb2yuw72NINDqbTEM0gp-9b2WAEGU,6271
|
|
8
|
+
sra_riskgate_cloud-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
sra_riskgate_cloud-0.1.0.dist-info/entry_points.txt,sha256=_koMnr-lKHr1sWdk7OzdNQDr2MzsQ1DOv1R65Cp_264,58
|
|
10
|
+
sra_riskgate_cloud-0.1.0.dist-info/top_level.txt,sha256=B9atKA7JlzCf6GmoQTWl33NrhbviAGq474u8VXkEWtY,19
|
|
11
|
+
sra_riskgate_cloud-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sra_riskgate_cloud
|