diff --git a/Makefile b/Makefile index 7903d59..d2962b7 100644 --- a/Makefile +++ b/Makefile @@ -29,7 +29,8 @@ check-lint-pin: CHART_REQUIRED := --set config.rpc-url=http://rpc:8545 --set-string config.chain-id=1330 --set captcha.existingSecret=captcha CHART_ALL := $(CHART_REQUIRED) --set httpRoute.enabled=true --set 'httpRoute.hostnames[0]=faucet.example.com' \ - --set 'httpRoute.parentRefs[0].name=gateway' --set serviceMonitor.enabled=true --set prometheusRule.enabled=true + --set 'httpRoute.parentRefs[0].name=gateway' --set serviceMonitor.enabled=true --set prometheusRule.enabled=true \ + --set admin.enabled=true --set 'admin.allowedServiceAccounts[0]=ns/sa' # Lints the chart and renders it with every optional resource on. chart-lint: diff --git a/README.md b/README.md index 415b7d1..bff3cc4 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,11 @@ environment variable: `--rpc-url` is `WELLSPRING_RPC_URL`. Run | `--confirm-timeout` | `30s` | Wait for a receipt before resyncing the nonce | | `--db-path` | `wellspring.db` | SQLite database; put it on a persistent volume | | `--listen-addr` / `--metrics-addr` | `:8080` / `:9090` | HTTP and Prometheus listeners | +| `--admin-addr` | off | Grants API listener; see [Grants](#grants) | +| `--admin-allow` | required with `--admin-addr` | Comma-separated `namespace/serviceaccount` grant callers; wildcards are refused | +| `--admin-audience` | `wellspring` | Audience a caller's token must carry | +| `--grant-max-wei` | 100000 SEI | Most one grant sends | +| `--kube-api-url` / `--kube-token-file` / `--kube-ca-file` | in-cluster defaults | Kubernetes API that reviews callers' tokens | | `--log-level` | `info` | JSON logs to stdout at this level | Secrets are only read from files, such as a mounted Kubernetes secret, so they @@ -78,13 +83,103 @@ On SIGTERM it stops taking claims, stops the sender and closes the database. Claims it had not settled are reconciled from the chain on the next start. `/healthz` is liveness; `/readyz` also checks the RPC and the faucet balance. +## Grants + +The grants API sends any amount up to `--grant-max-wei` to an address, for +partners, load tests and other test workloads. It listens on `--admin-addr`, +apart from the public page, and goes through the same store, signer and nonce +order as claims, so it never competes with them for a nonce. It skips the +captcha, cooldowns and `--max-recipient-balance-wei`, but reads the faucet's +balance afresh and refuses a grant that, with every unsettled claim, would take +it below `--min-faucet-balance-wei`. + +Callers authenticate with a Kubernetes ServiceAccount token whose audience is +`--admin-audience`. wellspring sends it to the Kubernetes TokenReview API and +accepts it only for a ServiceAccount named exactly in `--admin-allow`, with no +wildcards, so there is no shared secret: a human's `wellspring grant` runs +`kubectl create token`, and a pod mounts a projected token. + +``` +POST /admin/grants +Authorization: Bearer +{"id": "acme-2026-11", "address": "0x…", "amountWei": "5000000000000000000000", "reason": "Acme integration tests"} +``` + +Set `topUpToWei` instead of `amountWei` to send only what brings the address to +that balance. While a transfer to the address is still settling its balance is +not final, so a top-up gets 503 and `wellspring grant` retries it. `id` names +the grant within its caller's ServiceAccount: sending the same request again returns the grant already made, with status 200, and +reusing an ID for a different address or amount gets 409. A new grant answers +202. `GET /admin/grants/{id}` reports it; `status` is `queued`, `sent`, +`confirmed` or `failed`, and only a successful receipt confirms it. Each grant +is logged with its caller, recipient, amount and reason, and counted in +`wellspring_grants_total` and `wellspring_granted_wei_total`. + +### Granting from a laptop + +Install the CLI with Go, from Homebrew's `go` or any Go 1.21 or later, which +fetches the toolchain `go.mod` names: + +```bash +go install github.com/sei-protocol/wellspring/cmd/wellspring@v0.2.0 +``` + +Then, with a kubeconfig context for wellspring's cluster: + +```bash +wellspring grant --kube-context --to 0x… --sei 5000 --reason "Acme integration tests" +``` + +It runs your `kubectl`, so EKS and other exec auth plugins work as they do for +you, to mint a short-lived `grants-operator` token for the `wellspring` audience +and to port-forward a free local port to the Service's admin port. It waits for +the receipt, prints the transaction hash with the chain ID and public RPC, and +stops the port-forward. `--top-up-to-sei` tops up instead, and `--amount-wei` +and `--top-up-to-wei` take wei. Without `--id` the grant is named +`
-sei-`, printed, so rerunning the same command that +day resumes it rather than paying twice; pass `--id` to name it yourself or to +resume it on a later day. `--namespace`, `--service`, `--service-account` and +`--admin-port` default to `wellspring`, `wellspring`, `grants-operator` and +`8081`. + +### Funding a test Job + +The image's `wellspring grant` command requests a grant and waits until it +confirms, retrying refusals that can pass, such as an unreachable chain, and +exiting non-zero on ones that cannot. Run it as an init container, with an `--id` +that stays the same across the Job's retries, such as the Job's name, so a +retried pod resumes the grant instead of paying again: + +```yaml +initContainers: + - name: fund + image: ghcr.io/sei-protocol/wellspring: + args: + - grant + - --url=http://wellspring.wellspring.svc:8081 + - --id=my-load-test-1 + - --address=0x… # or --address-file + - --top-up-to-wei=1000000000000000000000 + - --reason=my load test + volumeMounts: + - {name: wellspring-token, mountPath: /var/run/secrets/wellspring, readOnly: true} +volumes: + - name: wellspring-token + projected: + sources: + - serviceAccountToken: {audience: wellspring, path: token, expirationSeconds: 600} +``` + +The Job's ServiceAccount must be in `--admin-allow`, and its namespace admitted +by the chart's NetworkPolicy, which `admin.allowedServiceAccounts` does. + ## Kubernetes The Helm chart in `chart/` runs it the only safe way: a single-replica StatefulSet, which never starts a second pod while the first is still shutting down, since one signer owns the nonce, a PVC at `/data`, and a fixed security context (UID/GID 65532, read-only root filesystem, no -capabilities, no service account token). Merges to main publish a snapshot +capabilities, and no service account token unless the grants API is on). Merges to main publish a snapshot image and chart; a `vX.Y.Z` tag publishes a release, with the chart pinned to its image by digest. @@ -101,6 +196,9 @@ helm install wellspring oci://ghcr.io/sei-protocol/charts/wellspring --version < `config` takes any flag by name as a string, such as `config.amount-wei`. Set `config.trust-proxy-hops` to the number of proxies in front, or every claim -counts against the proxy's IP. See `chart/values.yaml` for the HTTPRoute, -ServiceMonitor, PrometheusRule and NetworkPolicy settings, and +counts against the proxy's IP. `admin.enabled` turns on the grants API on Service port `admin.port`, binds +the ServiceAccount to `system:auth-delegator` so wellspring can review tokens, +and admits the namespaces of `admin.allowedServiceAccounts` to the port. See +`chart/values.yaml` for the HTTPRoute, ServiceMonitor, PrometheusRule and +NetworkPolicy settings, and [RUNBOOK.md](RUNBOOK.md) for what to do when an alert fires. diff --git a/RUNBOOK.md b/RUNBOOK.md index ab5aff1..a5da946 100644 --- a/RUNBOOK.md +++ b/RUNBOOK.md @@ -71,6 +71,47 @@ or the faucet balance cannot cover a transfer. RPC reads are failing. Check the node behind `config.rpc-url` and the NetworkPolicy egress rules, if set. The sender retries on its own. +## WellspringGrantFailed + +A grant's transfer landed with a failed receipt, or was refused for good. The +log line `claim failed` with the grant's claim ID gives the reason. The grant +stays failed: its caller sees `status: failed` and must request again under a +new grant ID. Check the faucet balance and the sender before it does. + +## WellspringGrantAuthUnavailable + +wellspring could not review a grant caller's token, so it refused the grant +with 503. Check `kubectl -n $NS logs sts/-wellspring` for `token review +failed`: the Kubernetes API is unreachable (NetworkPolicy egress, if set, must +allow it), the projected token is missing, or the ClusterRoleBinding to +`system:auth-delegator` is gone. + +## Making a grant by hand + +With `grants-operator` in `admin.allowedServiceAccounts`, install the CLI as in +the README and run, with an `--id` that says what the grant is for: + +```bash +wellspring grant --kube-context --namespace $NS --service -wellspring \ + --id acme-2026-11 --to 0x… --sei 5000 --reason "Acme integration tests" +``` + +It mints the token and port-forwards with your `kubectl`, waits for the receipt +and prints the transaction hash. Rerunning it with the same `--id` is safe: it +returns the same grant. Without the CLI, the same through `curl`: + +```bash +kubectl -n $NS port-forward svc/-wellspring 8081 +TOKEN=$(kubectl -n $NS create token grants-operator --audience wellspring --duration 10m) +curl -s localhost:8081/admin/grants -H "Authorization: Bearer $TOKEN" \ + -d '{"id":"acme-2026-11","address":"0x…","amountWei":"5000000000000000000000","reason":"Acme integration tests"}' +curl -s localhost:8081/admin/grants/acme-2026-11 -H "Authorization: Bearer $TOKEN" +``` + +Anyone allowed to create tokens for an allowed ServiceAccount, or pods under +it, can make grants up to `admin.grantMaxWei` each. The allowlist takes only +exact `namespace/serviceaccount` pairs, so add each caller by name. + ## Rotating the signer key The sender resyncs a new key against its stored in-flight claims, so no claim diff --git a/chart/templates/clusterrolebinding.yaml b/chart/templates/clusterrolebinding.yaml new file mode 100644 index 0000000..ddcca90 --- /dev/null +++ b/chart/templates/clusterrolebinding.yaml @@ -0,0 +1,17 @@ +{{- if .Values.admin.enabled }} +# Lets wellspring create TokenReviews to authenticate grant callers. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ printf "%s-%s-auth-delegator" .Release.Namespace (include "wellspring.fullname" .) | trunc 63 | trimSuffix "-" }} + labels: + {{- include "wellspring.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: system:auth-delegator +subjects: + - kind: ServiceAccount + name: {{ include "wellspring.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/chart/templates/configmap.yaml b/chart/templates/configmap.yaml index 713f3cf..9f8bb88 100644 --- a/chart/templates/configmap.yaml +++ b/chart/templates/configmap.yaml @@ -12,6 +12,17 @@ data: WELLSPRING_METRICS_ADDR: ":9090" WELLSPRING_DB_PATH: /data/wellspring.db WELLSPRING_PRIVATE_KEY_FILE: /var/run/wellspring/signer/private-key + {{- with .Values.admin }} + {{- if .enabled }} + WELLSPRING_ADMIN_ADDR: ":8081" + WELLSPRING_ADMIN_AUDIENCE: {{ .audience | quote }} + {{- if not .allowedServiceAccounts }} + {{- fail "admin.allowedServiceAccounts is required with admin.enabled" }} + {{- end }} + WELLSPRING_ADMIN_ALLOW: {{ .allowedServiceAccounts | join "," | quote }} + WELLSPRING_GRANT_MAX_WEI: {{ .grantMaxWei | quote }} + {{- end }} + {{- end }} {{- if include "wellspring.captchaSecret" . }} WELLSPRING_CAPTCHA_SECRET_FILE: /var/run/wellspring/captcha/secret {{- end }} diff --git a/chart/templates/networkpolicy.yaml b/chart/templates/networkpolicy.yaml index 8c68cf5..2796271 100644 --- a/chart/templates/networkpolicy.yaml +++ b/chart/templates/networkpolicy.yaml @@ -24,6 +24,20 @@ spec: ports: - port: metrics {{- end }} + {{- if .Values.admin.enabled }} + - from: + {{- $namespaces := list }} + {{- range .Values.admin.allowedServiceAccounts }} + {{- $namespaces = append $namespaces (splitList "/" . | first) }} + {{- end }} + {{- range $ns := $namespaces | uniq | sortAlpha }} + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: {{ $ns }} + {{- end }} + ports: + - port: admin + {{- end }} {{- with .Values.networkPolicy.egress }} egress: {{- toYaml . | nindent 4 }} diff --git a/chart/templates/prometheusrule.yaml b/chart/templates/prometheusrule.yaml index 7a55c91..396d30b 100644 --- a/chart/templates/prometheusrule.yaml +++ b/chart/templates/prometheusrule.yaml @@ -58,4 +58,16 @@ spec: annotations: summary: More than one RPC read in ten seconds is failing. runbook_url: {{ .Values.prometheusRule.runbookURL }}#wellspringrpcerrors + - alert: WellspringGrantFailed + expr: increase(wellspring_claims_finished_total{ {{- $target -}}, kind="grant", status="failed"}[15m]) > 0 + labels: {severity: warning} + annotations: + summary: A grant's transfer failed; its caller sees status failed and must retry under a new grant ID. + runbook_url: {{ .Values.prometheusRule.runbookURL }}#wellspringgrantfailed + - alert: WellspringGrantAuthUnavailable + expr: increase(wellspring_grants_total{ {{- $target -}}, outcome="auth_unavailable"}[15m]) > 0 + labels: {severity: warning} + annotations: + summary: wellspring cannot reach the Kubernetes API to review grant callers' tokens. + runbook_url: {{ .Values.prometheusRule.runbookURL }}#wellspringgrantauthunavailable {{- end }} diff --git a/chart/templates/service.yaml b/chart/templates/service.yaml index 3ec0bd6..9256688 100644 --- a/chart/templates/service.yaml +++ b/chart/templates/service.yaml @@ -15,3 +15,8 @@ spec: - name: metrics port: 9090 targetPort: metrics + {{- if .Values.admin.enabled }} + - name: admin + port: {{ .Values.admin.port }} + targetPort: admin + {{- end }} diff --git a/chart/templates/statefulset.yaml b/chart/templates/statefulset.yaml index 57286c8..af975d4 100644 --- a/chart/templates/statefulset.yaml +++ b/chart/templates/statefulset.yaml @@ -69,6 +69,10 @@ spec: containerPort: 8080 - name: metrics containerPort: 9090 + {{- if .Values.admin.enabled }} + - name: admin + containerPort: 8081 + {{- end }} envFrom: - configMapRef: name: {{ include "wellspring.fullname" . }} @@ -99,6 +103,11 @@ spec: mountPath: /var/run/wellspring/captcha readOnly: true {{- end }} + {{- if .Values.admin.enabled }} + - name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true + {{- end }} volumes: {{- with .Values.persistence.existingClaim }} - name: data @@ -121,6 +130,22 @@ spec: - key: {{ .Values.captcha.key }} path: secret {{- end }} + {{- if .Values.admin.enabled }} + # Only to review grant callers' tokens; the ServiceAccount can do + # nothing else. + - name: kube-api-access + projected: + defaultMode: 0440 + sources: + - serviceAccountToken: + path: token + expirationSeconds: 3600 + - configMap: + name: kube-root-ca.crt + items: + - key: ca.crt + path: ca.crt + {{- end }} {{- if not .Values.persistence.existingClaim }} # Kept when the release is uninstalled, and immutable once created. volumeClaimTemplates: diff --git a/chart/values.schema.json b/chart/values.schema.json index d9d75dc..0eef05c 100644 --- a/chart/values.schema.json +++ b/chart/values.schema.json @@ -1,105 +1,286 @@ { "$schema": "http://json-schema.org/draft-07/schema#", "definitions": { - "name": { "type": "string", "minLength": 1 }, - "dnsName": { "anyOf": [{ "const": "" }, { "type": "string", "pattern": "^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$" }] }, - "strings": { "type": "object", "additionalProperties": { "type": "string" } } + "name": { + "type": "string", + "minLength": 1 + }, + "dnsName": { + "anyOf": [ + { + "const": "" + }, + { + "type": "string", + "pattern": "^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$" + } + ] + }, + "strings": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } }, "type": "object", "additionalProperties": false, - "required": ["image", "signer", "captcha", "config", "persistence", "service"], + "required": [ + "image", + "signer", + "captcha", + "config", + "persistence", + "service" + ], "properties": { - "nameOverride": { "$ref": "#/definitions/dnsName" }, - "fullnameOverride": { "$ref": "#/definitions/dnsName" }, + "nameOverride": { + "$ref": "#/definitions/dnsName" + }, + "fullnameOverride": { + "$ref": "#/definitions/dnsName" + }, "image": { "type": "object", "additionalProperties": false, - "required": ["repository"], + "required": [ + "repository" + ], "properties": { - "repository": { "$ref": "#/definitions/name" }, - "tag": { "type": "string", "pattern": "^([A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?$" }, - "digest": { "type": "string", "pattern": "^(sha256:[a-f0-9]{64})?$" }, - "pullPolicy": { "enum": ["Always", "IfNotPresent", "Never"] } + "repository": { + "$ref": "#/definitions/name" + }, + "tag": { + "type": "string", + "pattern": "^([A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?$" + }, + "digest": { + "type": "string", + "pattern": "^(sha256:[a-f0-9]{64})?$" + }, + "pullPolicy": { + "enum": [ + "Always", + "IfNotPresent", + "Never" + ] + } } }, - "imagePullSecrets": { "type": "array" }, + "imagePullSecrets": { + "type": "array" + }, "signer": { "type": "object", "additionalProperties": false, - "required": ["existingSecret", "key"], + "required": [ + "existingSecret", + "key" + ], "properties": { - "existingSecret": { "$ref": "#/definitions/name" }, - "key": { "$ref": "#/definitions/name" } + "existingSecret": { + "$ref": "#/definitions/name" + }, + "key": { + "$ref": "#/definitions/name" + } } }, "captcha": { "type": "object", "additionalProperties": false, - "required": ["existingSecret", "key"], + "required": [ + "existingSecret", + "key" + ], "properties": { - "existingSecret": { "type": "string" }, - "key": { "$ref": "#/definitions/name" } + "existingSecret": { + "type": "string" + }, + "key": { + "$ref": "#/definitions/name" + } } }, "config": { "type": "object", - "required": ["rpc-url", "chain-id"], + "required": [ + "rpc-url", + "chain-id" + ], "propertyNames": { "pattern": "^[a-z][a-z0-9-]*$", - "not": { "enum": ["listen-addr", "metrics-addr", "db-path", "private-key-file", "captcha-secret-file"] } + "not": { + "enum": [ + "listen-addr", + "metrics-addr", + "db-path", + "private-key-file", + "captcha-secret-file", + "admin-addr", + "admin-audience", + "admin-allow", + "grant-max-wei", + "kube-api-url", + "kube-token-file", + "kube-ca-file" + ] + } + }, + "additionalProperties": { + "type": "string" }, - "additionalProperties": { "type": "string" }, "properties": { - "rpc-url": { "type": "string", "minLength": 1 }, - "chain-id": { "type": "string", "pattern": "^[1-9][0-9]*$" }, - "captcha-provider": { "enum": ["turnstile", "hcaptcha", "none"] } + "rpc-url": { + "type": "string", + "minLength": 1 + }, + "chain-id": { + "type": "string", + "pattern": "^[1-9][0-9]*$" + }, + "captcha-provider": { + "enum": [ + "turnstile", + "hcaptcha", + "none" + ] + } } }, "persistence": { "type": "object", "additionalProperties": false, "properties": { - "existingClaim": { "type": "string" }, - "storageClassName": { "type": "string" }, - "size": { "$ref": "#/definitions/name" } + "existingClaim": { + "type": "string" + }, + "storageClassName": { + "type": "string" + }, + "size": { + "$ref": "#/definitions/name" + } } }, "serviceAccount": { "type": "object", "additionalProperties": false, "properties": { - "create": { "type": "boolean" }, - "name": { "type": "string" }, - "annotations": { "$ref": "#/definitions/strings" } + "create": { + "type": "boolean" + }, + "name": { + "type": "string" + }, + "annotations": { + "$ref": "#/definitions/strings" + } } }, - "podAnnotations": { "$ref": "#/definitions/strings" }, - "podLabels": { "$ref": "#/definitions/strings" }, - "terminationGracePeriodSeconds": { "type": "integer", "minimum": 0 }, - "resources": { "type": "object" }, - "nodeSelector": { "$ref": "#/definitions/strings" }, - "tolerations": { "type": "array" }, - "affinity": { "type": "object" }, + "podAnnotations": { + "$ref": "#/definitions/strings" + }, + "podLabels": { + "$ref": "#/definitions/strings" + }, + "terminationGracePeriodSeconds": { + "type": "integer", + "minimum": 0 + }, + "resources": { + "type": "object" + }, + "nodeSelector": { + "$ref": "#/definitions/strings" + }, + "tolerations": { + "type": "array" + }, + "affinity": { + "type": "object" + }, "service": { "type": "object", "additionalProperties": false, - "required": ["port"], - "properties": { "port": { "type": "integer", "minimum": 1, "maximum": 65535, "not": { "const": 9090 } } } + "required": [ + "port" + ], + "properties": { + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535, + "not": { + "const": 9090 + } + } + } + }, + "admin": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + }, + "port": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "audience": { + "type": "string", + "minLength": 1 + }, + "allowedServiceAccounts": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?/[a-z0-9]([-.a-z0-9]{0,251}[a-z0-9])?$" + } + }, + "grantMaxWei": { + "type": "string", + "pattern": "^[1-9][0-9]*$" + } + } }, "httpRoute": { "type": "object", "additionalProperties": false, "properties": { - "enabled": { "type": "boolean" }, - "annotations": { "$ref": "#/definitions/strings" }, - "parentRefs": { "type": "array" }, - "hostnames": { "type": "array", "items": { "type": "string" } } + "enabled": { + "type": "boolean" + }, + "annotations": { + "$ref": "#/definitions/strings" + }, + "parentRefs": { + "type": "array" + }, + "hostnames": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "if": { + "properties": { + "enabled": { + "const": true + } + } }, - "if": { "properties": { "enabled": { "const": true } } }, "then": { "properties": { - "parentRefs": { "minItems": 1 }, - "hostnames": { "minItems": 1 } + "parentRefs": { + "minItems": 1 + }, + "hostnames": { + "minItems": 1 + } } } }, @@ -107,28 +288,50 @@ "type": "object", "additionalProperties": false, "properties": { - "enabled": { "type": "boolean" }, - "labels": { "$ref": "#/definitions/strings" }, - "interval": { "type": "string" } + "enabled": { + "type": "boolean" + }, + "labels": { + "$ref": "#/definitions/strings" + }, + "interval": { + "type": "string" + } } }, "prometheusRule": { "type": "object", "additionalProperties": false, "properties": { - "enabled": { "type": "boolean" }, - "labels": { "$ref": "#/definitions/strings" }, - "lowBalanceSEI": { "type": "number", "exclusiveMinimum": 0 }, - "runbookURL": { "type": "string", "pattern": "^https://" } + "enabled": { + "type": "boolean" + }, + "labels": { + "$ref": "#/definitions/strings" + }, + "lowBalanceSEI": { + "type": "number", + "exclusiveMinimum": 0 + }, + "runbookURL": { + "type": "string", + "pattern": "^https://" + } } }, "networkPolicy": { "type": "object", "additionalProperties": false, "properties": { - "enabled": { "type": "boolean" }, - "metricsNamespaceSelector": { "type": "object" }, - "egress": { "type": "array" } + "enabled": { + "type": "boolean" + }, + "metricsNamespaceSelector": { + "type": "object" + }, + "egress": { + "type": "array" + } } } } diff --git a/chart/values.yaml b/chart/values.yaml index 35d55e3..02cecf1 100644 --- a/chart/values.yaml +++ b/chart/values.yaml @@ -68,6 +68,22 @@ affinity: {} service: port: 80 +# The grants API: operator transfers of any amount up to grantMaxWei, without +# the captcha, cooldowns or recipient balance cap, through the same signer and +# nonce order as claims. It listens on its own container and Service port, +# which the HTTPRoute never routes. Callers send a ServiceAccount token for +# audience; wellspring has the Kubernetes API review it, so the chart binds +# wellspring's ServiceAccount to system:auth-delegator and mounts its token. +admin: + enabled: false + port: 8081 + audience: wellspring + # Exact namespace/serviceaccount pairs; wildcards are refused. The + # NetworkPolicy admits the admin port from these entries' namespaces; + # kubectl port-forward reaches it regardless. + allowedServiceAccounts: [] + grantMaxWei: "100000000000000000000000" + # Routes the page and API through the Gateway API. The metrics port is never # routed. httpRoute: diff --git a/cmd/wellspring/grant.go b/cmd/wellspring/grant.go new file mode 100644 index 0000000..80a13c2 --- /dev/null +++ b/cmd/wellspring/grant.go @@ -0,0 +1,288 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math/big" + "net/http" + "os" + "strings" + "time" + + "github.com/ethereum/go-ethereum/common" + "github.com/urfave/cli/v3" +) + +// grantCommand requests a grant from a running wellspring and waits for its +// transfer to confirm. Every request names the grant, so rerunning the command +// after a crash or a Job retry resumes the same grant instead of paying again. +// +// In-cluster callers pass --url and --token-file. Humans pass --kube-context +// instead: the command then mints a token and port-forwards with their kubectl. +func grantCommand() *cli.Command { + return &cli.Command{ + Name: "grant", + Usage: "request a grant from wellspring's grants API and wait for it to confirm", + Description: "From a laptop:\n\n" + + " wellspring grant --kube-context --to 0x… --sei 5000 --reason \"partner onboarding\"\n\n" + + "From a Job, with a token projected for the wellspring audience:\n\n" + + " wellspring grant --url http://wellspring.wellspring.svc:8081 --id --address-file --top-up-to-wei --reason ", + Flags: []cli.Flag{ + &cli.StringFlag{Name: "kube-context", Usage: "kubeconfig context of wellspring's cluster; mints a token and port-forwards with kubectl instead of --url and --token-file"}, + &cli.StringFlag{Name: "namespace", Value: "wellspring", Usage: "wellspring's namespace, with --kube-context"}, + &cli.StringFlag{Name: "service", Value: "wellspring", Usage: "wellspring's Service, with --kube-context"}, + &cli.IntFlag{Name: "admin-port", Value: 8081, Usage: "the Service's admin port, with --kube-context"}, + &cli.StringFlag{Name: "service-account", Value: "grants-operator", Usage: "ServiceAccount to mint the token for, with --kube-context"}, + &cli.StringFlag{Name: "audience", Value: "wellspring", Usage: "token audience, with --kube-context"}, + &cli.StringFlag{Name: "kubectl", Value: "kubectl", Usage: "kubectl binary, with --kube-context"}, + &cli.StringFlag{Name: "url", Usage: "grants API base URL, e.g. http://wellspring.wellspring.svc:8081"}, + &cli.StringFlag{Name: "token-file", Value: "/var/run/secrets/wellspring/token", Usage: "ServiceAccount token with the wellspring audience, reread on every request", TakesFile: true}, + &cli.StringFlag{Name: "id", Usage: "grant ID; reusing it returns the same grant. With --kube-context it defaults to
--"}, + &cli.StringFlag{Name: "address", Aliases: []string{"to"}, Usage: "recipient 0x address"}, + &cli.StringFlag{Name: "address-file", Usage: "file holding the recipient 0x address", TakesFile: true}, + &cli.StringFlag{Name: "sei", Usage: "SEI to send, e.g. 5000 or 0.5"}, + &cli.StringFlag{Name: "top-up-to-sei", Usage: "send what brings the recipient's balance to this many SEI"}, + &cli.StringFlag{Name: "amount-wei", Usage: "wei to send"}, + &cli.StringFlag{Name: "top-up-to-wei", Usage: "send what brings the recipient's balance to this many wei"}, + &cli.StringFlag{Name: "reason", Usage: "why, recorded in wellspring's audit log", Required: true}, + &cli.DurationFlag{Name: "timeout", Value: 10 * time.Minute, Usage: "give up after this long"}, + &cli.DurationFlag{Name: "poll", Value: 3 * time.Second, Usage: "how often to retry and check the grant"}, + }, + Action: runGrant, + } +} + +func runGrant(ctx context.Context, cmd *cli.Command) error { + address := cmd.String("address") + if f := cmd.String("address-file"); f != "" { + b, err := os.ReadFile(f) //nolint:gosec // the caller sets the path + if err != nil { + return fmt.Errorf("read --address-file: %w", err) + } + address = strings.TrimSpace(string(b)) + } + topUp, wei, err := grantAmount(cmd) + if err != nil { + return err + } + human := cmd.String("kube-context") != "" + id := cmd.String("id") + switch { + case id != "": + case human: + if id, err = defaultGrantID(address, topUp, wei, time.Now()); err != nil { + return err + } + default: + return errors.New("--id is required without --kube-context") + } + req := map[string]string{"id": id, "address": address, "reason": cmd.String("reason")} + if topUp { + req["topUpToWei"] = wei.String() + } else { + req["amountWei"] = wei.String() + } + body, err := json.Marshal(req) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(ctx, cmd.Duration("timeout")) + defer cancel() + + c := &grantClient{base: strings.TrimSuffix(cmd.String("url"), "/"), http: &http.Client{Timeout: 30 * time.Second}} + if human { + if cmd.IsSet("url") || cmd.IsSet("token-file") { + return errors.New("--kube-context replaces --url and --token-file") + } + k := kubectl{bin: cmd.String("kubectl"), context: cmd.String("kube-context"), namespace: cmd.String("namespace")} + // The API server refuses tokens shorter than 10m. + token, err := k.createToken(ctx, cmd.String("service-account"), cmd.String("audience"), max(10*time.Minute, cmd.Duration("timeout")+time.Minute)) + if err != nil { + return err + } + c.token = func() (string, error) { return token, nil } + var stop func() + if c.base, stop, err = k.portForward(ctx, cmd.String("service"), cmd.Int("admin-port")); err != nil { + return err + } + defer stop() + fmt.Fprintf(os.Stderr, "grant %s: rerunning this command today, or with this --id, resumes it instead of paying again\n", id) + } else { + if c.base == "" { + return errors.New("--url or --kube-context is required") + } + file := cmd.String("token-file") + c.token = func() (string, error) { + b, err := os.ReadFile(file) //nolint:gosec // the caller sets the path + if err != nil { + return "", fmt.Errorf("read --token-file: %w", err) + } + return strings.TrimSpace(string(b)), nil + } + } + poll := cmd.Duration("poll") + + method, path, reqBody := http.MethodPost, "/admin/grants", body + for { + g, err := c.do(ctx, method, path, reqBody) + var fatal *fatalError + switch { + case errors.As(err, &fatal): + return err + case err != nil: + fmt.Fprintf(os.Stderr, "grant: %v; retrying\n", err) + case g.Status == "confirmed": + fmt.Fprintf(os.Stderr, "grant %s confirmed: %s wei to %s, tx %s\n", g.ID, g.AmountWei, g.Address, g.TxHash) + if g.TxHash != "" { + fmt.Fprintf(os.Stderr, "chain %s (ID %d), RPC %s\n", g.ChainName, g.ChainID, g.RPCURL) + } + return nil + case g.Status == "failed": + return fmt.Errorf("grant %s failed: %s", g.ID, g.Error) + default: + fmt.Fprintf(os.Stderr, "grant %s %s\n", g.ID, g.Status) + method, path, reqBody = http.MethodGet, "/admin/grants/"+g.ID, nil + } + select { + case <-time.After(poll): + case <-ctx.Done(): + return fmt.Errorf("grant %s did not confirm: %w", id, ctx.Err()) + } + } +} + +// grantAmount reads the one amount flag set, in wei. +func grantAmount(cmd *cli.Command) (topUp bool, wei *big.Int, err error) { + var set []string + for _, f := range []string{"sei", "top-up-to-sei", "amount-wei", "top-up-to-wei"} { + if cmd.String(f) != "" { + set = append(set, f) + } + } + if len(set) != 1 { + return false, nil, errors.New("set exactly one of --sei, --top-up-to-sei, --amount-wei and --top-up-to-wei") + } + f, v := set[0], cmd.String(set[0]) + if strings.HasSuffix(f, "sei") { + wei, err = parseSEI(v) + } else { + wei, err = parseWei(v) + } + if err != nil { + return false, nil, fmt.Errorf("--%s %q: %w", f, v, err) + } + return strings.HasPrefix(f, "top-up-to-"), wei, nil +} + +var weiPerSEI = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil) + +// parseSEI converts a decimal SEI amount with at most 18 decimals to wei. +func parseSEI(s string) (*big.Int, error) { + whole, frac, dot := strings.Cut(s, ".") + if !isDigits(whole) || (dot && !isDigits(frac)) || len(frac) > 18 { + return nil, errors.New("not a decimal SEI amount with at most 18 decimals") + } + wei, _ := new(big.Int).SetString(whole+frac+strings.Repeat("0", 18-len(frac)), 10) + return wei, nil +} + +func parseWei(s string) (*big.Int, error) { + if !isDigits(s) { + return nil, errors.New("not a whole number of wei") + } + wei, _ := new(big.Int).SetString(s, 10) + return wei, nil +} + +func isDigits(s string) bool { + if s == "" || len(s) > 78 { + return false + } + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return true +} + +// defaultGrantID names a grant after what it sends, to whom and on which UTC +// day, so rerunning the same command that day resumes it rather than paying +// again, while the same grant on a later day is a new one. +func defaultGrantID(address string, topUp bool, wei *big.Int, now time.Time) (string, error) { + if !common.IsHexAddress(address) { + return "", fmt.Errorf("--address %q is not a 0x address", address) + } + q, r := new(big.Int).QuoRem(wei, weiPerSEI, new(big.Int)) + amount := q.String() + if r.Sign() != 0 { + amount += "." + strings.TrimRight(fmt.Sprintf("%018s", r), "0") + } + amount += "sei" + if topUp { + amount = "topup" + amount + } + id := fmt.Sprintf("%s-%s-%s", strings.ToLower(address), amount, now.UTC().Format("20060102")) + if len(id) > 128 { + return "", errors.New("the default grant ID is too long; set --id") + } + return id, nil +} + +type grantClient struct { + base string + token func() (string, error) + http *http.Client +} + +type grantStatus struct { + ID string `json:"id"` + Address string `json:"address"` + AmountWei string `json:"amountWei"` + Status string `json:"status"` + ChainID uint64 `json:"chainId"` + ChainName string `json:"chainName"` + RPCURL string `json:"rpcUrl"` + TxHash string `json:"txHash"` + Error string `json:"error"` + Message string `json:"message"` +} + +// fatalError is a refusal that retrying the same request cannot change. +type fatalError struct{ msg string } + +func (e *fatalError) Error() string { return e.msg } + +func (c *grantClient) do(ctx context.Context, method, path string, body []byte) (*grantStatus, error) { + token, err := c.token() + if err != nil { + return nil, &fatalError{err.Error()} + } + req, err := http.NewRequestWithContext(ctx, method, c.base+path, bytes.NewReader(body)) + if err != nil { + return nil, &fatalError{err.Error()} + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + resp, err := c.http.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + var g grantStatus + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<16)).Decode(&g); err != nil { + return nil, fmt.Errorf("%s %s: %s", method, path, resp.Status) + } + switch { + case resp.StatusCode < 300: + return &g, nil + case resp.StatusCode >= 500: + return nil, fmt.Errorf("%s: %s", resp.Status, g.Message) + default: + return nil, &fatalError{fmt.Sprintf("%s: %s", resp.Status, g.Message)} + } +} diff --git a/cmd/wellspring/grant_test.go b/cmd/wellspring/grant_test.go new file mode 100644 index 0000000..0fd7872 --- /dev/null +++ b/cmd/wellspring/grant_test.go @@ -0,0 +1,136 @@ +package main + +import ( + "context" + "encoding/json" + "math/big" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestParseSEI(t *testing.T) { + for in, want := range map[string]string{ + "5000": "5000000000000000000000", + "0.5": "500000000000000000", + "1.000000000000000001": "1000000000000000001", + "0": "0", + } { + if got, err := parseSEI(in); err != nil || got.String() != want { + t.Errorf("parseSEI(%q) = %v, %v; want %s", in, got, err, want) + } + } + for _, in := range []string{"", ".5", "5.", "-1", "1e3", "0x10", "1.0000000000000000001", "1,000"} { + if got, err := parseSEI(in); err == nil { + t.Errorf("parseSEI(%q) = %v; want an error", in, got) + } + } +} + +func TestDefaultGrantID(t *testing.T) { + day := time.Date(2026, 11, 21, 23, 30, 0, 0, time.FixedZone("", -5*3600)) + addr := "0xAbCdEf0123456789aBcDeF0123456789AbCdEf01" + sei, _ := parseSEI("5000") + for _, tc := range []struct { + topUp bool + wei *big.Int + want string + }{ + {false, sei, "0xabcdef0123456789abcdef0123456789abcdef01-5000sei-20261122"}, + {true, sei, "0xabcdef0123456789abcdef0123456789abcdef01-topup5000sei-20261122"}, + {false, big.NewInt(1), "0xabcdef0123456789abcdef0123456789abcdef01-0.000000000000000001sei-20261122"}, + } { + if got, err := defaultGrantID(addr, tc.topUp, tc.wei, day); err != nil || got != tc.want { + t.Errorf("defaultGrantID(%v, %v) = %q, %v; want %q", tc.topUp, tc.wei, got, err, tc.want) + } + } + if _, err := defaultGrantID("0x1234", false, sei, day); err == nil { + t.Error("defaultGrantID accepted a short address") + } +} + +// TestGrantWithKubeContext runs the human flow against a fake kubectl that +// mints a token and "forwards" to a fake grants API. +func TestGrantWithKubeContext(t *testing.T) { + var posted map[string]string + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer minted-token" { + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"error":"unauthenticated"}`)) + return + } + if r.Method == http.MethodPost { + _ = json.NewDecoder(r.Body).Decode(&posted) + w.WriteHeader(http.StatusAccepted) + _, _ = w.Write([]byte(`{"id":"` + posted["id"] + `","status":"queued"}`)) + return + } + _, _ = w.Write([]byte(`{"id":"x","status":"confirmed","txHash":"0xabc","chainId":1330}`)) + })) + defer api.Close() + u, _ := url.Parse(api.URL) + + dir := t.TempDir() + argsLog := filepath.Join(dir, "args") + fake := filepath.Join(dir, "kubectl") + script := `#!/bin/sh +echo "$@" >> ` + argsLog + ` +case "$*" in +*"create token"*) echo minted-token ;; +*port-forward*) echo "Forwarding from 127.0.0.1:` + u.Port() + ` -> 8081"; exec sleep 60 ;; +*) exit 1 ;; +esac +` + if err := os.WriteFile(fake, []byte(script), 0o700); err != nil { //nolint:gosec // an executable test fixture + t.Fatal(err) + } + to := "0x00000000000000000000000000000000000000aA" + err := grantCommand().Run(context.Background(), []string{"grant", + "--kubectl", fake, "--kube-context", "prod", "--to", to, "--sei", "2.5", + "--reason", "partner", "--poll", "10ms", "--timeout", "30s"}) + if err != nil { + t.Fatal(err) + } + want := map[string]string{ + "id": strings.ToLower(to) + "-2.5sei-" + time.Now().UTC().Format("20060102"), + "address": to, + "amountWei": "2500000000000000000", + "reason": "partner", + } + for k, v := range want { + if posted[k] != v { + t.Errorf("posted %s = %q; want %q", k, posted[k], v) + } + } + b, _ := os.ReadFile(argsLog) //nolint:gosec // the test's own file + for _, args := range []string{ + "--context prod --namespace wellspring create token grants-operator --audience wellspring --duration 10m0s", + "--context prod --namespace wellspring port-forward --address 127.0.0.1 svc/wellspring :8081", + } { + if !strings.Contains(string(b), args) { + t.Errorf("kubectl was not run with %q; ran:\n%s", args, b) + } + } +} + +func TestGrantRefusesBadFlags(t *testing.T) { + to := "0x00000000000000000000000000000000000000aA" + for name, args := range map[string][]string{ + "no id in-cluster": {"--url", "http://x", "--to", to, "--sei", "1"}, + "two amounts": {"--kube-context", "c", "--to", to, "--sei", "1", "--amount-wei", "1"}, + "no amount": {"--kube-context", "c", "--to", to}, + "bad wei": {"--url", "http://x", "--id", "a", "--to", to, "--amount-wei", "1.5"}, + "url with kube-context": {"--kube-context", "c", "--url", "http://x", "--to", to, "--sei", "1"}, + "no url": {"--id", "a", "--to", to, "--sei", "1"}, + } { + args = append([]string{"grant", "--reason", "r", "--kubectl", "/nonexistent"}, args...) + if err := grantCommand().Run(context.Background(), args); err == nil { + t.Errorf("%s: no error", name) + } + } +} diff --git a/cmd/wellspring/kubectl.go b/cmd/wellspring/kubectl.go new file mode 100644 index 0000000..b21a102 --- /dev/null +++ b/cmd/wellspring/kubectl.go @@ -0,0 +1,90 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "io" + "os/exec" + "regexp" + "strconv" + "strings" + "time" +) + +// kubectl runs the user's kubectl, so their kubeconfig and its exec auth +// plugins (aws eks get-token, gke-gcloud-auth-plugin) work as they do for them. +type kubectl struct { + bin, context, namespace string +} + +func (k kubectl) command(ctx context.Context, args ...string) *exec.Cmd { + return exec.CommandContext(ctx, k.bin, append([]string{"--context", k.context, "--namespace", k.namespace}, args...)...) //nolint:gosec // the user picks kubectl and its arguments +} + +// createToken mints a token for ServiceAccount sa with audience aud. +func (k kubectl) createToken(ctx context.Context, sa, aud string, d time.Duration) (string, error) { + var stdout, stderr bytes.Buffer + cmd := k.command(ctx, "create", "token", sa, "--audience", aud, "--duration", d.String()) + cmd.Stdout, cmd.Stderr = &stdout, &stderr + if err := cmd.Run(); err != nil { + return "", fmt.Errorf("kubectl create token %s: %w: %s", sa, err, strings.TrimSpace(stderr.String())) + } + token := strings.TrimSpace(stdout.String()) + if token == "" { + return "", fmt.Errorf("kubectl create token %s printed nothing", sa) + } + return token, nil +} + +var forwarding = regexp.MustCompile(`^Forwarding from 127\.0\.0\.1:(\d+) -> `) + +// portForward forwards a free local port to port of Service svc and returns +// its URL, and a stop function that ends the forward. +func (k kubectl) portForward(ctx context.Context, svc string, port int) (string, func(), error) { + ctx, cancel := context.WithCancel(ctx) + var stderr bytes.Buffer + cmd := k.command(ctx, "port-forward", "--address", "127.0.0.1", "svc/"+svc, ":"+strconv.Itoa(port)) + cmd.Stderr = &stderr + out, err := cmd.StdoutPipe() + if err != nil { + cancel() + return "", nil, err + } + if err := cmd.Start(); err != nil { + cancel() + return "", nil, fmt.Errorf("kubectl port-forward: %w", err) + } + stop := func() { + cancel() + _ = cmd.Wait() + } + local := make(chan string, 1) + go func() { + sc := bufio.NewScanner(out) + for sc.Scan() { + if m := forwarding.FindStringSubmatch(sc.Text()); m != nil { + local <- m[1] + break + } + } + close(local) + _, _ = io.Copy(io.Discard, out) + }() + select { + case p, ok := <-local: + if ok { + return "http://127.0.0.1:" + p, stop, nil + } + stop() + return "", nil, fmt.Errorf("kubectl port-forward svc/%s: %s", svc, strings.TrimSpace(stderr.String())) + case <-time.After(30 * time.Second): + stop() + return "", nil, errors.New("kubectl port-forward did not start within 30s") + case <-ctx.Done(): + stop() + return "", nil, ctx.Err() + } +} diff --git a/cmd/wellspring/main.go b/cmd/wellspring/main.go index a60f2cf..4770c39 100644 --- a/cmd/wellspring/main.go +++ b/cmd/wellspring/main.go @@ -21,6 +21,7 @@ import ( "github.com/urfave/cli/v3" "github.com/sei-protocol/wellspring/internal/api" + "github.com/sei-protocol/wellspring/internal/auth" "github.com/sei-protocol/wellspring/internal/config" "github.com/sei-protocol/wellspring/internal/sender" "github.com/sei-protocol/wellspring/internal/store" @@ -35,9 +36,10 @@ func main() { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() cmd := &cli.Command{ - Name: "wellspring", - Usage: "testnet SEI faucet for Sei EVM chains", - Flags: config.Flags(), + Name: "wellspring", + Usage: "testnet SEI faucet for Sei EVM chains", + Flags: config.Flags(), + Commands: []*cli.Command{grantCommand()}, Action: func(ctx context.Context, cmd *cli.Command) error { cfg, err := config.FromCommand(cmd) if err != nil { @@ -94,6 +96,14 @@ func run(ctx context.Context, cfg *config.Config) error { newServer(cfg.ListenAddr, srv.Handler()), newServer(cfg.MetricsAddr, promhttp.HandlerFor(reg, promhttp.HandlerOpts{})), } + if cfg.AdminAddr != "" { + reviewer, err := auth.NewReviewer(cfg.KubeAPIURL, cfg.KubeTokenFile, cfg.KubeCAFile, cfg.AdminAudience, cfg.AdminAllow) + if err != nil { + return err + } + servers = append(servers, newServer(cfg.AdminAddr, api.NewAdmin(srv, reviewer, reg).Handler())) + slog.Info("grants API enabled", "listen", cfg.AdminAddr, "allow", cfg.AdminAllow) + } errc := make(chan error, len(servers)) for _, s := range servers { go func() { diff --git a/internal/api/admin.go b/internal/api/admin.go new file mode 100644 index 0000000..ab318c5 --- /dev/null +++ b/internal/api/admin.go @@ -0,0 +1,250 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "math/big" + "net/http" + "regexp" + "strings" + "time" + "unicode" + + "github.com/ethereum/go-ethereum/common" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" + + "github.com/sei-protocol/wellspring/internal/auth" + "github.com/sei-protocol/wellspring/internal/store" +) + +// Authenticator returns the namespace/name of the ServiceAccount a bearer +// token belongs to, or auth.ErrUnauthenticated or auth.ErrForbidden. +type Authenticator interface { + Authenticate(ctx context.Context, token string) (string, error) +} + +var grantID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$`) + +const maxReason = 256 + +type grantRequest struct { + ID string `json:"id"` + Address string `json:"address"` + AmountWei string `json:"amountWei"` + TopUpToWei string `json:"topUpToWei"` + Reason string `json:"reason"` +} + +// Admin serves the grants API: authenticated transfers of any amount up to the +// per-grant maximum, without the captcha, cooldowns or recipient balance cap of +// public claims. Grants go through the same store and sender as claims. +type Admin struct { + *Server + auth Authenticator + grants *prometheus.CounterVec +} + +// NewAdmin returns the grants API of s. +func NewAdmin(s *Server, a Authenticator, reg prometheus.Registerer) *Admin { + grants := promauto.With(reg).NewCounterVec(prometheus.CounterOpts{ + Name: "wellspring_grants_total", Help: "Grant requests by outcome.", + }, []string{"outcome"}) + // From zero, so increase() sees the first of each. + for _, outcome := range []string{"created", "auth_unavailable"} { + grants.WithLabelValues(outcome) + } + return &Admin{Server: s, auth: a, grants: grants} +} + +// Handler returns the admin HTTP handler. +func (a *Admin) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("POST /admin/grants", a.authenticated(a.createGrant)) + mux.HandleFunc("GET /admin/grants/{id}", a.authenticated(a.getGrant)) + return securityHeaders(mux) +} + +func (a *Admin) authenticated(next func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + if !ok { + a.refuseGrant(w, http.StatusUnauthorized, "unauthenticated", "a bearer ServiceAccount token is required") + return + } + caller, err := a.auth.Authenticate(r.Context(), strings.TrimSpace(token)) + switch { + case errors.Is(err, auth.ErrUnauthenticated): + a.refuseGrant(w, http.StatusUnauthorized, "unauthenticated", err.Error()) + case errors.Is(err, auth.ErrForbidden): + a.refuseGrant(w, http.StatusForbidden, "forbidden", err.Error()) + case err != nil: + slog.Error("token review failed", "err", err) + a.refuseGrant(w, http.StatusServiceUnavailable, "auth_unavailable", "cannot review the token, try again shortly") + default: + next(w, r, caller) + } + } +} + +func (a *Admin) createGrant(w http.ResponseWriter, r *http.Request, caller string) { + var req grantRequest + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil { + a.refuseGrant(w, http.StatusBadRequest, "bad_request", "invalid JSON body") + return + } + if !grantID.MatchString(req.ID) { + a.refuseGrant(w, http.StatusBadRequest, "bad_request", "id must be 1-128 letters, digits, '.', '_', ':' or '-'") + return + } + if req.Reason == "" || len(req.Reason) > maxReason || strings.IndexFunc(req.Reason, unicode.IsControl) >= 0 { + a.refuseGrant(w, http.StatusBadRequest, "bad_request", "reason must be 1-256 bytes without control characters") + return + } + if !strings.HasPrefix(req.Address, "0x") || !common.IsHexAddress(req.Address) { + a.refuseGrant(w, http.StatusBadRequest, "bad_address", "address must be a 0x-prefixed EVM address") + return + } + to := common.HexToAddress(req.Address) + if to == (common.Address{}) || to == a.faucet.Address() { + a.refuseGrant(w, http.StatusBadRequest, "bad_address", "address cannot receive from the faucet") + return + } + var kind string + var wei *big.Int + switch { + case req.AmountWei != "" && req.TopUpToWei == "": + kind, wei = "amount:", parseWei(req.AmountWei) + case req.TopUpToWei != "" && req.AmountWei == "": + kind, wei = "top-up-to:", parseWei(req.TopUpToWei) + } + if wei == nil { + a.refuseGrant(w, http.StatusBadRequest, "bad_amount", "set exactly one of amountWei and topUpToWei, as a positive decimal uint256") + return + } + request := kind + wei.String() + g := &store.Grant{Caller: caller, ID: req.ID, Address: to, Request: request, Reason: req.Reason, TopUp: req.TopUpToWei != ""} + + existing, err := a.store.GetGrant(r.Context(), caller, req.ID) + if err != nil { + slog.Error("read grant failed", "err", err) + a.refuseGrant(w, http.StatusInternalServerError, "internal", "internal error") + return + } + if existing != nil { + a.answerExisting(w, g, existing) + return + } + + readAt := time.Now() + g.Amount = wei + if req.TopUpToWei != "" { + bctx, cancel := context.WithTimeout(r.Context(), rpcTimeout) + held, err := a.balances.BalanceAt(bctx, to, nil) + cancel() + if err != nil { + a.refuseGrant(w, http.StatusServiceUnavailable, "rpc", "chain unavailable, try again shortly") + return + } + g.Amount = new(big.Int).Sub(wei, held) + if g.Amount.Sign() < 0 { + g.Amount.SetInt64(0) + } + } + if g.Amount.Cmp(a.cfg.GrantMax) > 0 { + a.refuseGrant(w, http.StatusBadRequest, "too_large", "grant exceeds the per-grant maximum of "+a.cfg.GrantMax.String()+" wei") + return + } + bctx, cancel := context.WithTimeout(r.Context(), rpcTimeout) + balance, err := a.balances.BalanceAt(bctx, a.faucet.Address(), nil) + cancel() + if err != nil { + a.refuseGrant(w, http.StatusServiceUnavailable, "rpc", "chain unavailable, try again shortly") + return + } + available := new(big.Int).Sub(balance, a.cfg.MinFaucetBalance) + + created, isNew, err := a.store.CreateGrant(r.Context(), g, available, readAt, time.Now()) + switch { + case errors.Is(err, store.ErrGrantNoFunds): + a.refuseGrant(w, http.StatusServiceUnavailable, "no_funds", err.Error()) + case errors.Is(err, store.ErrGrantBusy): + a.refuseGrant(w, http.StatusServiceUnavailable, "busy", err.Error()) + case errors.Is(err, store.ErrGrantConflict): + a.refuseGrant(w, http.StatusConflict, "conflict", err.Error()) + case err != nil: + slog.Error("create grant failed", "err", err) + a.refuseGrant(w, http.StatusInternalServerError, "internal", "internal error") + case !isNew: + a.answerExisting(w, g, created) + default: + a.grants.WithLabelValues("created").Inc() + slog.Info("grant created", "caller", caller, "id", created.ID, "address", to.Hex(), + "amount_wei", created.Amount.String(), "request", request, "reason", created.Reason) + status := http.StatusAccepted + if created.Claim == nil { + status = http.StatusOK + } + writeJSON(w, status, a.grantView(created)) + } +} + +// answerExisting answers a retried request with the grant it already made, or +// refuses one that reuses the grant's ID for a different request. +func (a *Admin) answerExisting(w http.ResponseWriter, req, existing *store.Grant) { + if existing.Address != req.Address || existing.Request != req.Request { + a.refuseGrant(w, http.StatusConflict, "conflict", store.ErrGrantConflict.Error()) + return + } + a.grants.WithLabelValues("repeated").Inc() + writeJSON(w, http.StatusOK, a.grantView(existing)) +} + +func (a *Admin) getGrant(w http.ResponseWriter, r *http.Request, caller string) { + g, err := a.store.GetGrant(r.Context(), caller, r.PathValue("id")) + switch { + case err != nil: + slog.Error("read grant failed", "err", err) + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal", "message": "internal error"}) + case g == nil: + writeJSON(w, http.StatusNotFound, map[string]string{"error": "not_found", "message": "no such grant"}) + default: + writeJSON(w, http.StatusOK, a.grantView(g)) + } +} + +func (a *Admin) refuseGrant(w http.ResponseWriter, status int, code, msg string) { + a.grants.WithLabelValues(code).Inc() + writeJSON(w, status, map[string]string{"error": code, "message": msg}) +} + +// grantView reports a grant, with the chain to look its transfer up on. A +// grant with nothing to send is confirmed at once. +func (a *Admin) grantView(g *store.Grant) map[string]any { + v := map[string]any{ + "chainId": a.cfg.ChainID, + "chainName": a.cfg.ChainName, + "rpcUrl": a.cfg.PublicRPCURL, + "id": g.ID, + "caller": g.Caller, + "address": g.Address.Hex(), + "amountWei": g.Amount.String(), + "reason": g.Reason, + "status": store.StatusConfirmed, + "createdAt": g.CreatedAt.UTC().Format(time.RFC3339), + } + if c := g.Claim; c != nil { + v["status"], v["txHash"], v["error"] = c.Status, c.TxHash, c.Error + } + return v +} + +func parseWei(s string) *big.Int { + v, ok := new(big.Int).SetString(s, 10) + if !ok || v.Sign() <= 0 || v.BitLen() > 256 { + return nil + } + return v +} diff --git a/internal/api/admin_test.go b/internal/api/admin_test.go new file mode 100644 index 0000000..940ef5e --- /dev/null +++ b/internal/api/admin_test.go @@ -0,0 +1,131 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "math/big" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/ethereum/go-ethereum/common" + + "github.com/sei-protocol/wellspring/internal/auth" +) + +type fakeAuth struct{} + +func (fakeAuth) Authenticate(_ context.Context, token string) (string, error) { + switch token { + case "ns-a", "ns-b": + return token + "/sa", nil + case "forbidden": + return "", auth.ErrForbidden + } + return "", auth.ErrUnauthenticated +} + +func (h *harness) grant(token, body string) (*httptest.ResponseRecorder, map[string]any) { + return h.adminDo(http.MethodPost, "/admin/grants", token, body) +} + +func (h *harness) adminDo(method, path, token, body string) (*httptest.ResponseRecorder, map[string]any) { + r := httptest.NewRequestWithContext(context.Background(), method, path, strings.NewReader(body)) + if token != "" { + r.Header.Set("Authorization", "Bearer "+token) + } + w := httptest.NewRecorder() + h.admin.ServeHTTP(w, r) + var v map[string]any + _ = json.Unmarshal(w.Body.Bytes(), &v) + return w, v +} + +func grantBody(id, to, field, wei string) string { + return `{"id":"` + id + `","address":"` + to + `","` + field + `":"` + wei + `","reason":"load test"}` +} + +func TestGrantLifecycle(t *testing.T) { + h := newHarness(t) + body := grantBody("run-1", addr(1), "amountWei", sei(400).String()) + w, v := h.grant("ns-a", body) + if w.Code != http.StatusAccepted || v["status"] != "queued" || v["amountWei"] != sei(400).String() || v["caller"] != "ns-a/sa" || v["chainId"] != 1330.0 { + t.Fatalf("grant: %d %v", w.Code, v) + } + // Grants skip the captcha and the recipient balance cap. + h.captcha.err = errCaptcha + h.balances.held[common.HexToAddress(addr(1))] = sei(1000) + w, again := h.grant("ns-a", body) + if w.Code != http.StatusOK || again["createdAt"] != v["createdAt"] { + t.Fatalf("retry: %d %v", w.Code, again) + } + if w, _ := h.grant("ns-a", grantBody("run-1", addr(1), "amountWei", sei(5).String())); w.Code != http.StatusConflict { + t.Fatalf("ID reused for a different amount: %d", w.Code) + } + if w, v := h.adminDo(http.MethodGet, "/admin/grants/run-1", "ns-a", ""); w.Code != http.StatusOK || v["status"] != "queued" { + t.Fatalf("get: %d %v", w.Code, v) + } + if w, _ := h.adminDo(http.MethodGet, "/admin/grants/run-1", "ns-b", ""); w.Code != http.StatusNotFound { + t.Fatalf("another caller read the grant: %d", w.Code) + } + if w, _ := h.grant("ns-a", grantBody("run-2", addr(2), "amountWei", sei(400).String())); w.Code != http.StatusAccepted { + t.Fatalf("second grant: %d", w.Code) + } + // 1000 SEI balance, 100 SEI floor and 800 SEI promised. + if w, v := h.grant("ns-a", grantBody("run-3", addr(3), "amountWei", new(big.Int).Add(sei(100), big.NewInt(1)).String())); w.Code != http.StatusServiceUnavailable || v["error"] != "no_funds" { + t.Fatalf("grant past the floor: %d %v", w.Code, v) + } +} + +func TestGrantTopUp(t *testing.T) { + h := newHarness(t) + to := common.HexToAddress(addr(1)) + h.balances.held[to] = sei(30) + if w, v := h.grant("ns-a", grantBody("t", addr(1), "topUpToWei", sei(100).String())); w.Code != http.StatusAccepted || v["amountWei"] != sei(70).String() { + t.Fatalf("top-up: %d %v", w.Code, v) + } + // The retry finds the grant even though the balance it was computed from moved. + h.balances.held[to] = sei(100) + if w, v := h.grant("ns-a", grantBody("t", addr(1), "topUpToWei", sei(100).String())); w.Code != http.StatusOK || v["amountWei"] != sei(70).String() { + t.Fatalf("top-up retry: %d %v", w.Code, v) + } + if w, v := h.grant("ns-a", grantBody("t2", addr(1), "topUpToWei", sei(50).String())); w.Code != http.StatusServiceUnavailable || v["error"] != "busy" { + t.Fatalf("top-up while a transfer to the address is queued: %d %v", w.Code, v) + } + h.balances.held[common.HexToAddress(addr(2))] = sei(100) + if w, v := h.grant("ns-a", grantBody("t3", addr(2), "topUpToWei", sei(50).String())); w.Code != http.StatusOK || v["amountWei"] != "0" || v["status"] != "confirmed" { + t.Fatalf("top-up of a funded address: %d %v", w.Code, v) + } +} + +func TestGrantRefusals(t *testing.T) { + h := newHarness(t) + for name, tc := range map[string]struct { + token, body string + code int + }{ + "no token": {"", grantBody("a", addr(1), "amountWei", "1"), http.StatusUnauthorized}, + "bad token": {"nope", grantBody("a", addr(1), "amountWei", "1"), http.StatusUnauthorized}, + "not allowed": {"forbidden", grantBody("a", addr(1), "amountWei", "1"), http.StatusForbidden}, + "bad id": {"ns-a", grantBody("a/b", addr(1), "amountWei", "1"), http.StatusBadRequest}, + "no reason": {"ns-a", `{"id":"a","address":"` + addr(1) + `","amountWei":"1"}`, http.StatusBadRequest}, + "faucet": {"ns-a", grantBody("a", faucetAddr.Hex(), "amountWei", "1"), http.StatusBadRequest}, + "zero address": {"ns-a", grantBody("a", addr(0), "amountWei", "1"), http.StatusBadRequest}, + "zero amount": {"ns-a", grantBody("a", addr(1), "amountWei", "0"), http.StatusBadRequest}, + "negative": {"ns-a", grantBody("a", addr(1), "amountWei", "-1"), http.StatusBadRequest}, + "both amounts": {"ns-a", `{"id":"a","address":"` + addr(1) + `","amountWei":"1","topUpToWei":"1","reason":"r"}`, http.StatusBadRequest}, + "over the max": {"ns-a", grantBody("a", addr(1), "amountWei", new(big.Int).Add(sei(500), big.NewInt(1)).String()), http.StatusBadRequest}, + "over uint256": {"ns-a", grantBody("a", addr(1), "amountWei", new(big.Int).Lsh(big.NewInt(1), 256).String()), http.StatusBadRequest}, + "control chars": {"ns-a", `{"id":"a","address":"` + addr(1) + `","amountWei":"1","reason":"a\nb"}`, http.StatusBadRequest}, + } { + if w, _ := h.grant(tc.token, tc.body); w.Code != tc.code { + t.Errorf("%s: got %d, want %d: %s", name, w.Code, tc.code, w.Body) + } + } + h.balances.err = errors.New("rpc down") + if w, v := h.grant("ns-a", grantBody("a", addr(1), "amountWei", "1")); w.Code != http.StatusServiceUnavailable || v["error"] != "rpc" { + t.Fatalf("grant without the faucet balance: %d %v", w.Code, v) + } +} diff --git a/internal/api/api_test.go b/internal/api/api_test.go index 4542ee0..5088153 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -55,6 +55,7 @@ func (c *fakeCaptcha) Verify(context.Context, string, string) error { return c.e type harness struct { srv http.Handler + admin http.Handler faucet *fakeFaucet balances *fakeBalances captcha *fakeCaptcha @@ -71,14 +72,16 @@ func newHarness(t *testing.T) *harness { ChainID: 1330, ChainName: "Giga testnet", Amount: sei(1), MaxRecipientBalance: sei(10), MinFaucetBalance: sei(100), AddressCooldown: 24 * time.Hour, IPWindow: 24 * time.Hour, IPLimit: 2, MaxQueued: 100, - CaptchaProvider: "turnstile", CaptchaSiteKey: "site", + CaptchaProvider: "turnstile", CaptchaSiteKey: "site", GrantMax: sei(500), } h := &harness{ faucet: &fakeFaucet{balance: sei(1000), at: time.Now()}, - balances: &fakeBalances{held: map[common.Address]*big.Int{}}, + balances: &fakeBalances{held: map[common.Address]*big.Int{faucetAddr: sei(1000)}}, captcha: &fakeCaptcha{}, } - h.srv = New(cfg, st, h.balances, h.faucet, h.captcha, prometheus.NewRegistry()).Handler() + reg := prometheus.NewRegistry() + srv := New(cfg, st, h.balances, h.faucet, h.captcha, reg) + h.srv, h.admin = srv.Handler(), NewAdmin(srv, fakeAuth{}, reg).Handler() return h } diff --git a/internal/auth/auth.go b/internal/auth/auth.go new file mode 100644 index 0000000..bf37fac --- /dev/null +++ b/internal/auth/auth.go @@ -0,0 +1,133 @@ +// Package auth authenticates grant callers by their Kubernetes ServiceAccount +// tokens, which the Kubernetes API reviews, so no shared secret exists. +package auth + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "slices" + "strings" + "time" +) + +// Errors Authenticate returns for a refused caller. +var ( + ErrUnauthenticated = errors.New("token is not a valid ServiceAccount token for this audience") + ErrForbidden = errors.New("ServiceAccount may not make grants") +) + +// maxTokenBytes bounds the tokens sent for review; ServiceAccount tokens are +// about a kilobyte. +const maxTokenBytes = 8 << 10 + +const saPrefix = "system:serviceaccount:" + +// Reviewer authenticates callers through the Kubernetes TokenReview API and +// authorises them against an allowlist. +type Reviewer struct { + url string + tokenFile string + audience string + allow []string + client *http.Client +} + +// NewReviewer returns a Reviewer for the Kubernetes API at apiURL, which it +// calls with the token in tokenFile, read on every review so a rotated token is +// picked up. caFile, when non-empty, holds the CA bundle of the API. allow +// holds namespace/name or namespace/* entries. +func NewReviewer(apiURL, tokenFile, caFile, audience string, allow []string) (*Reviewer, error) { + tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12} + if caFile != "" { + pem, err := os.ReadFile(caFile) //nolint:gosec // the operator sets the path + if err != nil { + return nil, fmt.Errorf("read Kubernetes CA: %w", err) + } + tlsConfig.RootCAs = x509.NewCertPool() + if !tlsConfig.RootCAs.AppendCertsFromPEM(pem) { + return nil, errors.New("kubernetes CA file holds no certificates") + } + } + return &Reviewer{ + url: strings.TrimSuffix(apiURL, "/") + "/apis/authentication.k8s.io/v1/tokenreviews", + tokenFile: tokenFile, + audience: audience, + allow: allow, + client: &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{TLSClientConfig: tlsConfig}}, + }, nil +} + +type tokenReview struct { + APIVersion string `json:"apiVersion"` + Kind string `json:"kind"` + Spec struct { + Token string `json:"token"` + Audiences []string `json:"audiences"` + } `json:"spec"` + Status struct { + Authenticated bool `json:"authenticated"` + Audiences []string `json:"audiences"` + User struct { + Username string `json:"username"` + } `json:"user"` + } `json:"status"` +} + +// Authenticate returns the namespace/name of the ServiceAccount token belongs +// to. It fails with ErrUnauthenticated unless the Kubernetes API vouches for +// token with the configured audience, and with ErrForbidden unless the +// ServiceAccount is allowed. Any other error means the review did not happen. +func (r *Reviewer) Authenticate(ctx context.Context, token string) (string, error) { + if token == "" || len(token) > maxTokenBytes { + return "", ErrUnauthenticated + } + own, err := os.ReadFile(r.tokenFile) + if err != nil { + return "", fmt.Errorf("read Kubernetes token: %w", err) + } + var review tokenReview + review.APIVersion, review.Kind = "authentication.k8s.io/v1", "TokenReview" + review.Spec.Token, review.Spec.Audiences = token, []string{r.audience} + body, err := json.Marshal(review) + if err != nil { + return "", err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.url, bytes.NewReader(body)) + if err != nil { + return "", err + } + req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(string(own))) + req.Header.Set("Content-Type", "application/json") + resp, err := r.client.Do(req) + if err != nil { + return "", fmt.Errorf("token review: %w", err) + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("token review: Kubernetes API answered %s", resp.Status) + } + review = tokenReview{} + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&review); err != nil { + return "", fmt.Errorf("token review: %w", err) + } + st := review.Status + if !st.Authenticated || !slices.Contains(st.Audiences, r.audience) { + return "", ErrUnauthenticated + } + ns, name, ok := strings.Cut(strings.TrimPrefix(st.User.Username, saPrefix), ":") + if !strings.HasPrefix(st.User.Username, saPrefix) || !ok || ns == "" || name == "" { + return "", ErrUnauthenticated + } + if !slices.Contains(r.allow, ns+"/"+name) { + return "", ErrForbidden + } + return ns + "/" + name, nil +} diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go new file mode 100644 index 0000000..a015305 --- /dev/null +++ b/internal/auth/auth_test.go @@ -0,0 +1,99 @@ +package auth + +import ( + "context" + "encoding/json" + "encoding/pem" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" +) + +// fakeAPI answers TokenReviews: a token maps to the review status it gets. +func fakeAPI(t *testing.T, statuses map[string]string) (*httptest.Server, string) { + t.Helper() + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/apis/authentication.k8s.io/v1/tokenreviews" || r.Header.Get("Authorization") != "Bearer reviewer" { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + var review tokenReview + _ = json.NewDecoder(r.Body).Decode(&review) + if len(review.Spec.Audiences) != 1 || review.Spec.Audiences[0] != "wellspring" { + t.Errorf("review asked for audiences %v", review.Spec.Audiences) + } + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"status":` + statuses[review.Spec.Token] + `}`)) + })) + t.Cleanup(srv.Close) + dir := t.TempDir() + ca := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}) + if err := os.WriteFile(filepath.Join(dir, "ca.crt"), ca, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "token"), []byte("reviewer\n"), 0o600); err != nil { + t.Fatal(err) + } + return srv, dir +} + +func sa(user string, audiences ...string) string { + b, _ := json.Marshal(map[string]any{"authenticated": true, "audiences": audiences, "user": map[string]string{"username": user}}) + return string(b) +} + +func TestAuthenticate(t *testing.T) { + srv, dir := fakeAPI(t, map[string]string{ + "exact": sa("system:serviceaccount:wellspring:grants-operator", "wellspring"), + "second": sa("system:serviceaccount:giga-testnet-1:harpoon-setup", "wellspring"), + "same-ns": sa("system:serviceaccount:giga-testnet-1:validator", "wellspring"), + "star": sa("system:serviceaccount:giga-testnet-2:*", "wellspring"), + "other-sa": sa("system:serviceaccount:wellspring:default", "wellspring"), + "other-aud": sa("system:serviceaccount:wellspring:grants-operator", "https://kubernetes.default.svc"), + "user": sa("alice@example.com", "wellspring"), + "invalid": `{"authenticated":false,"error":"token expired"}`, + "unvouched": `{"authenticated":false,"audiences":["wellspring"],"user":{"username":"system:serviceaccount:wellspring:grants-operator"}}`, + "no-name": sa("system:serviceaccount:wellspring", "wellspring"), + "other-ns": sa("system:serviceaccount:giga-testnet-10:harpoon-setup", "wellspring"), + }) + r, err := NewReviewer(srv.URL, filepath.Join(dir, "token"), filepath.Join(dir, "ca.crt"), "wellspring", + []string{"wellspring/grants-operator", "giga-testnet-1/harpoon-setup"}) + if err != nil { + t.Fatal(err) + } + for token, want := range map[string]error{ + "exact": nil, "second": nil, + "other-sa": ErrForbidden, "same-ns": ErrForbidden, "other-ns": ErrForbidden, "star": ErrForbidden, + "other-aud": ErrUnauthenticated, "user": ErrUnauthenticated, "invalid": ErrUnauthenticated, + "unvouched": ErrUnauthenticated, "no-name": ErrUnauthenticated, "": ErrUnauthenticated, + string(make([]byte, maxTokenBytes+1)): ErrUnauthenticated, + } { + if _, err := r.Authenticate(context.Background(), token); !errors.Is(err, want) { + t.Errorf("token %.12q: got %v, want %v", token, err, want) + } + } + if who, _ := r.Authenticate(context.Background(), "second"); who != "giga-testnet-1/harpoon-setup" { + t.Fatalf("caller %q", who) + } +} + +func TestAuthenticateFailsClosed(t *testing.T) { + srv, dir := fakeAPI(t, nil) + r, err := NewReviewer(srv.URL, filepath.Join(dir, "missing"), filepath.Join(dir, "ca.crt"), "wellspring", []string{"a/b"}) + if err != nil { + t.Fatal(err) + } + if who, err := r.Authenticate(context.Background(), "t"); err == nil || who != "" { + t.Fatal("authenticated without reading its own token") + } + untrusted, err := NewReviewer(srv.URL, filepath.Join(dir, "token"), "", "wellspring", []string{"a/b"}) + if err != nil { + t.Fatal(err) + } + if _, err := untrusted.Authenticate(context.Background(), "t"); err == nil || errors.Is(err, ErrUnauthenticated) { + t.Fatalf("API with an untrusted certificate: %v", err) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index d127336..fafa574 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -9,6 +9,7 @@ import ( "log/slog" "math/big" "os" + "regexp" "strings" "time" @@ -49,6 +50,20 @@ type Config struct { CaptchaSiteKey string CaptchaSecret string + // AdminAddr serves the grants API; empty turns it off. + AdminAddr string + // AdminAudience is the audience a caller's ServiceAccount token must carry. + AdminAudience string + // AdminAllow lists the namespace/name ServiceAccounts that may make grants. + AdminAllow []string + // GrantMax is the most one grant sends. + GrantMax *big.Int + // KubeAPIURL, KubeTokenFile and KubeCAFile reach the Kubernetes API that + // reviews callers' tokens. + KubeAPIURL string + KubeTokenFile string + KubeCAFile string + BatchInterval time.Duration BatchSize int GasTipCap *big.Int @@ -56,6 +71,12 @@ type Config struct { ConfirmTimeout time.Duration } +const serviceAccountDir = "/var/run/secrets/kubernetes.io/serviceaccount" + +// allowEntry matches a namespace/serviceaccount allowlist entry. Wildcards are +// refused: every caller is named. +var allowEntry = regexp.MustCompile(`^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?/[a-z0-9]([-.a-z0-9]{0,251}[a-z0-9])?$`) + // Flags returns wellspring's flags. Secrets are only read from files, so they // stay out of the process environment and the pod spec. func Flags() []cli.Flag { @@ -80,6 +101,13 @@ func Flags() []cli.Flag { str("captcha-provider", "turnstile", "turnstile, hcaptcha, or none for local use"), str("captcha-site-key", "", "public captcha site key"), file("captcha-secret-file", "file holding the captcha secret"), + str("admin-addr", "", "grants API listen address; off when empty"), + str("admin-audience", "wellspring", "audience a grant caller's ServiceAccount token must carry"), + str("admin-allow", "", "comma-separated namespace/serviceaccount callers allowed to make grants"), + str("grant-max-wei", "100000000000000000000000", "most wei one grant sends"), + str("kube-api-url", "https://kubernetes.default.svc", "Kubernetes API that reviews grant callers' tokens"), + str("kube-token-file", serviceAccountDir+"/token", "token wellspring authenticates to the Kubernetes API with"), + str("kube-ca-file", serviceAccountDir+"/ca.crt", "CA bundle of the Kubernetes API"), dur("batch-interval", 500*time.Millisecond, "how often queued claims are sent"), num("batch-size", 100, "most claims sent per interval"), str("gas-tip-cap-wei", "1000000000", "EIP-1559 tip cap"), @@ -134,6 +162,12 @@ func FromCommand(cmd *cli.Command) (*Config, error) { TrustProxyHops: cmd.Int("trust-proxy-hops"), CaptchaProvider: cmd.String("captcha-provider"), CaptchaSiteKey: cmd.String("captcha-site-key"), + AdminAddr: cmd.String("admin-addr"), + AdminAudience: cmd.String("admin-audience"), + GrantMax: r.wei("grant-max-wei"), + KubeAPIURL: cmd.String("kube-api-url"), + KubeTokenFile: cmd.String("kube-token-file"), + KubeCAFile: cmd.String("kube-ca-file"), BatchInterval: r.positive("batch-interval"), BatchSize: cmd.Int("batch-size"), GasTipCap: r.wei("gas-tip-cap-wei"), @@ -156,6 +190,19 @@ func FromCommand(cmd *cli.Command) (*Config, error) { r.check(c.GasFeeCap == nil || c.GasTipCap == nil || c.GasFeeCap.Cmp(c.GasTipCap) >= 0, "--gas-fee-cap-wei must be at least --gas-tip-cap-wei") r.check(c.IPLimit > 0 && c.MaxQueued > 0 && c.BatchSize > 0, "--ip-limit, --max-queued and --batch-size must be positive") r.check(c.TrustProxyHops >= 0, "--trust-proxy-hops must not be negative") + if c.AdminAddr != "" { + for _, e := range strings.Split(cmd.String("admin-allow"), ",") { + if e = strings.TrimSpace(e); e != "" { + r.check(!strings.Contains(e, "*"), fmt.Sprintf("--admin-allow entry %q is a wildcard; name each ServiceAccount as namespace/serviceaccount", e)) + r.check(strings.Contains(e, "*") || allowEntry.MatchString(e), fmt.Sprintf("--admin-allow entry %q is not namespace/serviceaccount", e)) + c.AdminAllow = append(c.AdminAllow, e) + } + } + r.check(len(c.AdminAllow) > 0, "--admin-allow is required with --admin-addr") + r.check(c.AdminAudience != "", "--admin-audience is required with --admin-addr") + r.check(c.KubeAPIURL != "", "--kube-api-url is required with --admin-addr") + r.check(c.GrantMax == nil || c.GrantMax.Sign() > 0, "--grant-max-wei must be positive") + } if len(r.errs) > 0 { return nil, errors.Join(r.errs...) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 34f881a..c278fc6 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -111,6 +111,11 @@ func TestInvalid(t *testing.T) { {"negative hops", []string{"--trust-proxy-hops", "-1"}, "must not be negative"}, {"zero duration", []string{"--confirm-timeout", "0s"}, "--confirm-timeout must be positive"}, {"bad log level", []string{"--log-level", "loud"}, "--log-level"}, + {"admin without allowlist", []string{"--admin-addr", ":8081"}, "--admin-allow is required"}, + {"bad allowlist entry", []string{"--admin-addr", ":8081", "--admin-allow", "ns/sa,ns"}, `"ns" is not namespace/serviceaccount`}, + {"wildcard allowlist entry", []string{"--admin-addr", ":8081", "--admin-allow", "ns/sa,giga-testnet-1/*"}, `"giga-testnet-1/*" is a wildcard`}, + {"admin without audience", []string{"--admin-addr", ":8081", "--admin-allow", "ns/sa", "--admin-audience", ""}, "--admin-audience is required"}, + {"zero grant max", []string{"--admin-addr", ":8081", "--admin-allow", "ns/sa", "--grant-max-wei", "0"}, "--grant-max-wei must be positive"}, } { t.Run(tc.name, func(t *testing.T) { _, err := load(t, valid(t, tc.args...)...) @@ -121,6 +126,17 @@ func TestInvalid(t *testing.T) { } } +func TestAdmin(t *testing.T) { + cfg, err := load(t, valid(t, "--admin-addr", ":8081", "--admin-allow", " wellspring/grants-operator, giga-testnet-1/harpoon-setup ")...) + if err != nil { + t.Fatal(err) + } + if cfg.AdminAudience != "wellspring" || cfg.GrantMax.String() != "100000000000000000000000" || + strings.Join(cfg.AdminAllow, ",") != "wellspring/grants-operator,giga-testnet-1/harpoon-setup" { + t.Fatalf("unexpected admin config: %+v", cfg) + } +} + func TestErrorsHideSecrets(t *testing.T) { _, err := load(t, valid(t, "--private-key-file", writeFile(t, testKey+"zz"), "--chain-id", "1329")...) if err == nil || strings.Contains(err.Error(), testKey) || !strings.Contains(err.Error(), "testnet-only") { diff --git a/internal/sender/sender.go b/internal/sender/sender.go index 1f98792..6acfdea 100644 --- a/internal/sender/sender.go +++ b/internal/sender/sender.go @@ -58,6 +58,7 @@ type Config struct { type metrics struct { txsSent, sendErrors, resyncs, rpcErrors prometheus.Counter claimsDone *prometheus.CounterVec + grantedWei prometheus.Counter claimTime prometheus.Histogram queueDepth, oldestUnsettled, nextNonce prometheus.Gauge // balance has no series until the first balance read, so an RPC that is @@ -67,12 +68,13 @@ type metrics struct { func newMetrics(reg prometheus.Registerer) *metrics { f := promauto.With(reg) - return &metrics{ + m := &metrics{ txsSent: f.NewCounter(prometheus.CounterOpts{Name: "wellspring_txs_sent_total", Help: "Transfers broadcast."}), sendErrors: f.NewCounter(prometheus.CounterOpts{Name: "wellspring_send_errors_total", Help: "Broadcasts and rebroadcasts the node refused."}), resyncs: f.NewCounter(prometheus.CounterOpts{Name: "wellspring_nonce_resyncs_total", Help: "Nonce resynchronisations with the chain."}), rpcErrors: f.NewCounter(prometheus.CounterOpts{Name: "wellspring_rpc_errors_total", Help: "Failed RPC reads."}), - claimsDone: f.NewCounterVec(prometheus.CounterOpts{Name: "wellspring_claims_finished_total", Help: "Claims by final status."}, []string{"status"}), + claimsDone: f.NewCounterVec(prometheus.CounterOpts{Name: "wellspring_claims_finished_total", Help: "Claims and grants by final status."}, []string{"status", "kind"}), + grantedWei: f.NewCounter(prometheus.CounterOpts{Name: "wellspring_granted_wei_total", Help: "Wei paid by confirmed grants."}), claimTime: f.NewHistogram(prometheus.HistogramOpts{ Name: "wellspring_claim_seconds", Help: "Time from claim to confirmed transfer.", Buckets: prometheus.ExponentialBuckets(0.25, 2, 10), }), @@ -83,6 +85,13 @@ func newMetrics(reg prometheus.Registerer) *metrics { }), nextNonce: f.NewGauge(prometheus.GaugeOpts{Name: "wellspring_next_nonce", Help: "Nonce the next transfer is signed with."}), } + // From zero, so increase() sees the first of each. + for _, kind := range []string{store.KindClaim, store.KindGrant} { + for _, status := range []store.Status{store.StatusConfirmed, store.StatusFailed} { + m.claimsDone.WithLabelValues(string(status), kind) + } + } + return m } // Sender drains queued claims into transfers. @@ -411,7 +420,11 @@ func (s *Sender) fill(ctx context.Context, nonce uint64) error { } func (s *Sender) finish(ctx context.Context, c *store.Claim, status store.Status, msg string) error { - s.metrics.claimsDone.WithLabelValues(string(status)).Inc() + s.metrics.claimsDone.WithLabelValues(string(status), c.Kind).Inc() + if c.Kind == store.KindGrant && status == store.StatusConfirmed { + f, _ := new(big.Float).SetInt(c.Amount).Float64() + s.metrics.grantedWei.Add(f) + } return s.store.Finish(ctx, c.ID, status, msg, time.Now()) } diff --git a/internal/sender/sender_test.go b/internal/sender/sender_test.go index ba10771..9628062 100644 --- a/internal/sender/sender_test.go +++ b/internal/sender/sender_test.go @@ -409,6 +409,47 @@ func TestGaugesTrackUnsettledClaimsAndBalance(t *testing.T) { } } +func TestGrantsShareTheNonceOrder(t *testing.T) { + h := newHarness(t) + addrs := h.claim(2) + granted := common.HexToAddress("0x00000000000000000000000000000000000ca201") + big5 := new(big.Int).Mul(amount, big.NewInt(5)) + if _, _, err := h.store.CreateGrant(context.Background(), &store.Grant{ + Caller: "ns/sa", ID: "g", Address: granted, Request: "amount:5", Amount: big5, Reason: "r", + }, new(big.Int).Mul(amount, big.NewInt(100)), time.Now(), time.Now()); err != nil { + t.Fatal(err) + } + late := common.BigToAddress(big.NewInt(9)) + if _, _, err := h.store.CreateClaim(context.Background(), late, "ip2", amount, + store.Limits{AddressCooldown: time.Hour, IPWindow: time.Hour, IPLimit: 1, MaxQueued: 10}, time.Now()); err != nil { + t.Fatal(err) + } + reg := prometheus.NewRegistry() + s := New(h.cfg, h.chain, h.store, reg) + h.drain(s) + h.paidOnce(addrs[0], addrs[1], granted, late) + if h.chain.nonce != 4 { + t.Fatalf("chain at nonce %d, want 4", h.chain.nonce) + } + g, _ := h.store.GetGrant(context.Background(), "ns/sa", "g") + if g.Claim.Status != store.StatusConfirmed || g.Claim.Amount.Cmp(big5) != 0 { + t.Fatalf("grant claim %+v", g.Claim) + } + if v := gather(t, reg)["wellspring_granted_wei_total"].GetMetric()[0].GetCounter().GetValue(); v != 5e18 { + t.Fatalf("granted %v wei", v) + } + for _, m := range gather(t, reg)["wellspring_claims_finished_total"].GetMetric() { + l := map[string]string{} + for _, p := range m.GetLabel() { + l[p.GetName()] = p.GetValue() + } + want := map[string]float64{"confirmed/claim": 3, "confirmed/grant": 1}[l["status"]+"/"+l["kind"]] + if m.GetCounter().GetValue() != want { + t.Fatalf("%v finished %v times, want %v", l, m.GetCounter().GetValue(), want) + } + } +} + func gather(t *testing.T, reg *prometheus.Registry) map[string]*dto.MetricFamily { t.Helper() families, err := reg.Gather() diff --git a/internal/store/grants.go b/internal/store/grants.go new file mode 100644 index 0000000..e78942d --- /dev/null +++ b/internal/store/grants.go @@ -0,0 +1,173 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "math/big" + "time" + + "github.com/ethereum/go-ethereum/common" +) + +// Errors CreateGrant returns for a refused grant. +var ( + ErrGrantConflict = errors.New("grant ID already used for a different request") + ErrGrantNoFunds = errors.New("grant would take the faucet below its minimum balance") + ErrGrantBusy = errors.New("a transfer to this address is still settling, try again shortly") +) + +// Grant is an operator's transfer to one address. Callers name their grants, +// so a retried request finds the grant it already made instead of paying again. +type Grant struct { + Caller string + ID string + Address common.Address + // Request is what the caller asked for; a retry must ask for the same. + Request string + // Amount is what is sent: zero when the recipient already held enough. + Amount *big.Int + // TopUp marks Amount as computed from the recipient's balance, which + // CreateGrant refuses to trust while a transfer to it may be missing. + TopUp bool + Reason string + CreatedAt time.Time + // Claim carries the transfer; nil when Amount is zero. + Claim *Claim +} + +// CreateGrant stores g and queues its transfer, unless the caller already has +// a grant with g's ID, which it returns instead with created false. +// +// available is the faucet's spendable balance and readAt is when the balances +// behind it and a top-up's Amount began to be read. A claim confirmed since +// then may be missing from them, so it counts as unsettled: a new grant is +// refused if it would spend more than available together with them, and a +// top-up while one is to its recipient. +func (s *Store) CreateGrant(ctx context.Context, g *Grant, available *big.Int, readAt, now time.Time) (*Grant, bool, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, false, err + } + defer func() { _ = tx.Rollback() }() + + existing, err := getGrant(ctx, tx, g.Caller, g.ID) + if err != nil { + return nil, false, err + } + if existing != nil { + if existing.Address != g.Address || existing.Request != g.Request { + return nil, false, ErrGrantConflict + } + return existing, false, nil + } + + out := *g + out.Amount = new(big.Int).Set(g.Amount) + out.CreatedAt = time.UnixMilli(now.UnixMilli()) + if g.TopUp { + pending, err := unsettledWei(ctx, tx, &g.Address, readAt) + if err != nil { + return nil, false, err + } + if pending.Sign() > 0 { + return nil, false, ErrGrantBusy + } + } + var claimID sql.NullString + if out.Amount.Sign() > 0 { + unsettled, err := unsettledWei(ctx, tx, nil, readAt) + if err != nil { + return nil, false, err + } + if unsettled.Add(unsettled, out.Amount).Cmp(available) > 0 { + return nil, false, ErrGrantNoFunds + } + out.Claim = &Claim{ID: newID(), Kind: KindGrant, Address: g.Address, Amount: out.Amount, Status: StatusQueued, CreatedAt: out.CreatedAt} + if _, err := tx.ExecContext(ctx, + `INSERT INTO claims (id, kind, address, ip, amount, status, created_at) VALUES (?, ?, ?, '', ?, ?, ?)`, + out.Claim.ID, KindGrant, g.Address.Hex(), out.Amount.String(), StatusQueued, now.UnixMilli()); err != nil { + return nil, false, err + } + claimID = sql.NullString{String: out.Claim.ID, Valid: true} + } + if _, err := tx.ExecContext(ctx, + `INSERT INTO grants (caller, id, address, request, amount, claim_id, reason, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + g.Caller, g.ID, g.Address.Hex(), g.Request, out.Amount.String(), claimID, g.Reason, now.UnixMilli()); err != nil { + return nil, false, err + } + return &out, true, tx.Commit() +} + +// GetGrant returns the caller's grant with id, or nil. +func (s *Store) GetGrant(ctx context.Context, caller, id string) (*Grant, error) { + tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback() }() + return getGrant(ctx, tx, caller, id) +} + +type querier interface { + QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row + QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) +} + +func getGrant(ctx context.Context, db querier, caller, id string) (*Grant, error) { + g := Grant{Caller: caller, ID: id} + var address, amount string + var claimID sql.NullString + var created int64 + err := db.QueryRowContext(ctx, + `SELECT address, request, amount, claim_id, reason, created_at FROM grants WHERE caller = ? AND id = ?`, + caller, id).Scan(&address, &g.Request, &amount, &claimID, &g.Reason, &created) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + if err != nil { + return nil, err + } + g.Address = common.HexToAddress(address) + g.Amount, _ = new(big.Int).SetString(amount, 10) + g.CreatedAt = time.UnixMilli(created) + if claimID.Valid { + claims, err := queryClaims(ctx, db, `WHERE id = ?`, claimID.String) + if err != nil { + return nil, err + } + if len(claims) == 1 { + g.Claim = claims[0] + } + } + return &g, nil +} + +// unsettledWei sums the amounts of every queued or sent claim, and of every +// claim confirmed at or after since, to to if it is not nil: what the faucet +// has promised but balances read since may not show. +func unsettledWei(ctx context.Context, db querier, to *common.Address, since time.Time) (*big.Int, error) { + q := `SELECT amount FROM claims WHERE (status IN (?, ?) OR (status = ? AND done_at >= ?))` + args := []any{StatusQueued, StatusSent, StatusConfirmed, since.UnixMilli()} + if to != nil { + q, args = q+` AND address = ?`, append(args, to.Hex()) + } + rows, err := db.QueryContext(ctx, q, args...) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + total := new(big.Int) + for rows.Next() { + var amount string + if err := rows.Scan(&amount); err != nil { + return nil, err + } + v, ok := new(big.Int).SetString(amount, 10) + if !ok { + return nil, errors.New("claim amount is not a decimal integer") + } + total.Add(total, v) + } + return total, rows.Err() +} diff --git a/internal/store/grants_test.go b/internal/store/grants_test.go new file mode 100644 index 0000000..f7ab504 --- /dev/null +++ b/internal/store/grants_test.go @@ -0,0 +1,139 @@ +package store + +import ( + "context" + "errors" + "math/big" + "sync" + "testing" + "time" + + "github.com/ethereum/go-ethereum/common" +) + +func grant(id string, to common.Address, amount *big.Int) *Grant { + return &Grant{Caller: "harpoon/setup", ID: id, Address: to, Request: "amount:" + amount.String(), Amount: amount, Reason: "test"} +} + +func TestGrantIsIdempotent(t *testing.T) { + s, _ := open(t) + ctx := context.Background() + big100 := new(big.Int).Mul(one, big.NewInt(100)) + first, created, err := s.CreateGrant(ctx, grant("g1", alice, one), big100, t0, t0) + if err != nil || !created || first.Claim == nil || first.Claim.Kind != KindGrant { + t.Fatalf("first grant: %+v created=%v err=%v", first, created, err) + } + again, created, err := s.CreateGrant(ctx, grant("g1", alice, one), big100, t0, t0) + if err != nil || created || again.Claim.ID != first.Claim.ID { + t.Fatalf("retry made a new grant: %+v created=%v err=%v", again, created, err) + } + if _, _, err := s.CreateGrant(ctx, grant("g1", bob, one), big100, t0, t0); !errors.Is(err, ErrGrantConflict) { + t.Fatalf("ID reused for another address: %v", err) + } + if _, _, err := s.CreateGrant(ctx, grant("g1", alice, big100), big100, t0, t0); !errors.Is(err, ErrGrantConflict) { + t.Fatalf("ID reused for another amount: %v", err) + } + other := grant("g1", alice, one) + other.Caller = "other/sa" + if _, created, err := s.CreateGrant(ctx, other, big100, t0, t0); err != nil || !created { + t.Fatalf("another caller's grant IDs are its own: created=%v err=%v", created, err) + } + queued, _ := s.Queued(ctx, 10) + if len(queued) != 2 { + t.Fatalf("%d claims queued, want 2", len(queued)) + } + got, err := s.GetGrant(ctx, "harpoon/setup", "g1") + if err != nil || got.Claim.ID != first.Claim.ID || got.Reason != "test" { + t.Fatalf("GetGrant: %+v %v", got, err) + } + if got, _ := s.GetGrant(ctx, "harpoon/setup", "missing"); got != nil { + t.Fatal("found a grant never made") + } +} + +func TestGrantConcurrentRetriesPayOnce(t *testing.T) { + s, _ := open(t) + var wg sync.WaitGroup + var mu sync.Mutex + created := 0 + for range 20 { + wg.Go(func() { + _, isNew, err := s.CreateGrant(context.Background(), grant("g", alice, one), new(big.Int).Mul(one, big.NewInt(100)), t0, t0) + if err != nil { + t.Error(err) + } + if isNew { + mu.Lock() + created++ + mu.Unlock() + } + }) + } + wg.Wait() + queued, _ := s.Queued(context.Background(), 100) + if created != 1 || len(queued) != 1 { + t.Fatalf("created %d grants and queued %d claims, want 1", created, len(queued)) + } +} + +func TestGrantCountsUnsettledClaims(t *testing.T) { + s, _ := open(t) + ctx := context.Background() + claim(t, s, bob, "ip", limits, t0) + three := new(big.Int).Mul(one, big.NewInt(3)) + if _, _, err := s.CreateGrant(ctx, grant("a", alice, one), three, t0, t0); err != nil { + t.Fatal(err) + } + if _, _, err := s.CreateGrant(ctx, grant("b", alice, new(big.Int).Add(one, big.NewInt(1))), three, t0, t0); !errors.Is(err, ErrGrantNoFunds) { + t.Fatalf("grant spending past the floor with unsettled claims: %v", err) + } + if _, _, err := s.CreateGrant(ctx, grant("b", alice, one), three, t0, t0); err != nil { + t.Fatalf("grant spending exactly to the floor: %v", err) + } + nothing := grant("c", alice, new(big.Int)) + if g, created, err := s.CreateGrant(ctx, nothing, new(big.Int), t0, t0); err != nil || !created || g.Claim != nil { + t.Fatalf("grant with nothing to send: %+v %v %v", g, created, err) + } +} + +func TestGrantsSkipPublicCooldown(t *testing.T) { + s, _ := open(t) + if _, _, err := s.CreateGrant(context.Background(), grant("g", alice, one), one, t0, t0); err != nil { + t.Fatal(err) + } + claim(t, s, alice, "ip", limits, t0) +} + +func TestGrantsCountTransfersConfirmedSinceTheBalanceRead(t *testing.T) { + s, _ := open(t) + ctx := context.Background() + two := new(big.Int).Mul(one, big.NewInt(2)) + topUp := grant("top", alice, two) + topUp.Request, topUp.TopUp = "top-up-to:"+two.String(), true + + first, _, err := s.CreateGrant(ctx, grant("a", alice, one), two, t0, t0) + if err != nil { + t.Fatal(err) + } + if _, _, err := s.CreateGrant(ctx, topUp, two, t0, t0); !errors.Is(err, ErrGrantBusy) { + t.Fatalf("top-up with a transfer to the recipient queued: %v", err) + } + settled := t0.Add(time.Second) + if err := s.MarkSent(ctx, first.Claim.ID, 0, common.Hash{1}, []byte{1}, settled); err != nil { + t.Fatal(err) + } + if err := s.Finish(ctx, first.Claim.ID, StatusConfirmed, "", settled); err != nil { + t.Fatal(err) + } + // Balances read before it confirmed may not show it. + if _, _, err := s.CreateGrant(ctx, topUp, two, t0, settled); !errors.Is(err, ErrGrantBusy) { + t.Fatalf("top-up from a balance read before the transfer confirmed: %v", err) + } + if _, _, err := s.CreateGrant(ctx, grant("b", bob, two), two, t0, settled); !errors.Is(err, ErrGrantNoFunds) { + t.Fatalf("grant from a faucet balance read before a transfer confirmed: %v", err) + } + later := settled.Add(time.Second) + if g, _, err := s.CreateGrant(ctx, topUp, two, later, later); err != nil || g.Amount.Cmp(two) != 0 { + t.Fatalf("top-up from a balance read after the transfer confirmed: %+v %v", g, err) + } +} diff --git a/internal/store/store.go b/internal/store/store.go index 6a1b6a0..7da3043 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -28,6 +28,12 @@ const ( StatusFailed Status = "failed" ) +// Kinds of claim: a public claim through the page, or an operator grant. +const ( + KindClaim = "claim" + KindGrant = "grant" +) + // Errors CreateClaim returns for a refused claim. var ( ErrAddressCooldown = errors.New("address claimed recently") @@ -38,6 +44,7 @@ var ( // Claim is one request for funds. type Claim struct { ID string + Kind string Address common.Address IP string Amount *big.Int @@ -93,6 +100,19 @@ CREATE TABLE claim_txs ( CREATE INDEX claim_txs_claim ON claim_txs(claim_id); INSERT INTO claim_txs (hash, claim_id, signed_at) SELECT tx_hash, id, COALESCE(sent_at, created_at) FROM claims WHERE tx_hash != ''; +`, ` +ALTER TABLE claims ADD COLUMN kind TEXT NOT NULL DEFAULT 'claim'; +CREATE TABLE grants ( + caller TEXT NOT NULL, + id TEXT NOT NULL, + address TEXT NOT NULL, + request TEXT NOT NULL, + amount TEXT NOT NULL, + claim_id TEXT UNIQUE REFERENCES claims(id), + reason TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (caller, id) +); `} // Open opens or creates the store at path. @@ -155,8 +175,8 @@ func (s *Store) CreateClaim(ctx context.Context, address common.Address, ip stri var last sql.NullInt64 if err := tx.QueryRowContext(ctx, - `SELECT MAX(created_at) FROM claims WHERE address = ? AND status != ? AND created_at > ?`, - address.Hex(), StatusFailed, now.Add(-limits.AddressCooldown).UnixMilli()).Scan(&last); err != nil { + `SELECT MAX(created_at) FROM claims WHERE address = ? AND kind = ? AND status != ? AND created_at > ?`, + address.Hex(), KindClaim, StatusFailed, now.Add(-limits.AddressCooldown).UnixMilli()).Scan(&last); err != nil { return nil, 0, err } if last.Valid { @@ -179,7 +199,7 @@ func (s *Store) CreateClaim(ctx context.Context, address common.Address, ip stri if queued >= limits.MaxQueued { return nil, time.Minute, ErrQueueFull } - c := &Claim{ID: newID(), Address: address, IP: ip, Amount: new(big.Int).Set(amount), Status: StatusQueued, CreatedAt: time.UnixMilli(now.UnixMilli())} + c := &Claim{ID: newID(), Kind: KindClaim, Address: address, IP: ip, Amount: new(big.Int).Set(amount), Status: StatusQueued, CreatedAt: time.UnixMilli(now.UnixMilli())} if _, err := tx.ExecContext(ctx, `INSERT INTO claims (id, address, ip, amount, status, created_at) VALUES (?, ?, ?, ?, ?, ?)`, c.ID, address.Hex(), ip, amount.String(), c.Status, now.UnixMilli()); err != nil { @@ -318,8 +338,12 @@ func update(ctx context.Context, db execer, from Status, set, id string, args .. } func (s *Store) query(ctx context.Context, where string, args ...any) ([]*Claim, error) { - rows, err := s.db.QueryContext(ctx, - `SELECT id, address, ip, amount, status, nonce, tx_hash, raw_tx, error, created_at, sent_at, done_at FROM claims `+where, args...) //nolint:gosec // where is a constant from this file + return queryClaims(ctx, s.db, where, args...) +} + +func queryClaims(ctx context.Context, db querier, where string, args ...any) ([]*Claim, error) { + rows, err := db.QueryContext(ctx, + `SELECT id, kind, address, ip, amount, status, nonce, tx_hash, raw_tx, error, created_at, sent_at, done_at FROM claims `+where, args...) //nolint:gosec // where is a constant from this file if err != nil { return nil, err } @@ -330,7 +354,7 @@ func (s *Store) query(ctx context.Context, where string, args ...any) ([]*Claim, var address, amount string var created int64 var sent, done sql.NullInt64 - if err := rows.Scan(&c.ID, &address, &c.IP, &amount, &c.Status, &c.Nonce, &c.TxHash, &c.RawTx, &c.Error, &created, &sent, &done); err != nil { + if err := rows.Scan(&c.ID, &c.Kind, &address, &c.IP, &amount, &c.Status, &c.Nonce, &c.TxHash, &c.RawTx, &c.Error, &created, &sent, &done); err != nil { return nil, err } c.Address = common.HexToAddress(address)