# Connecting an external application (#264) An external application, such as a research portal or a product backend, can hand calculations to a vibe-scheduler authority. The user stays in the application and later opens the job on the scheduler dashboard. This page is the contract between the application and the [submission gateway](gateway.md). It is generic: the scheduler knows the application only by the name, callbacks and secret digest the operator configures, and it holds none of the application's data or rules. Everything here is opt-in. Without `[gateway.identity_providers]`, `[gateway.applications]` and `[[gateway.identity_bindings]]`, the gateway behaves as before. Machine keys from **My machines** and operator-issued keys keep working unchanged. ## Roles and identities Three identities stay separate in every grant, job record and view: | Identity | Where it comes from | What it means | |---|---|---| | **Application** | `[gateway.applications.NAME]`, authenticated by its client secret | Which product asked. Two applications acting for one principal have separate idempotency namespaces. | | **Requesting user** | The verified OIDC `iss` and `sub` of the person who connected | Who authorized it. Opaque; an email address or domain is never used. | | **Executing principal** | The operator's identity binding: project and principal | Whose quota, ownership and execution policy apply. | Several subjects may be bound to one principal. They then share its jobs and quotas, and `GET /v1/connection` reports `per_user_isolation: false`. A shared service principal is never labelled per-user isolation. `per_user_isolation` reports configuration only; target isolation is qualified separately (#236, #247). ## Discovery `GET /v1/discovery` and `GET /.well-known/vq-gateway` return the same public document, without authentication. Use `/v1/discovery` when a reverse proxy routes only `/v1/` to the gateway, for example when the gateway shares the dashboard's origin. ```json { "schema": "vq.gateway-discovery/1", "api_versions": ["1"], "gateway_url": "https://gateway.example", "discovery_url": "https://gateway.example/v1/discovery", "authority": "authority-one", "mode": "local", "capabilities": ["whoami", "usage", "connection", "uploads.resumable-sha256", "jobs.idempotent", "jobs.provenance", "jobs.lifecycle", "jobs.logs", "jobs.cancel", "results.manifest-sha256", "results.range"], "submission": {"configured": true, "reasons": [], "credential": "Authorization: Bearer vqk_...", "detail": "..."}, "connect": { "available": true, "reasons": [], "authorization_endpoint": "https://gateway.example/v1/connect/authorize", "token_endpoint": "https://gateway.example/v1/connect/token", "rotation_endpoint": "https://gateway.example/v1/connect/rotate", "revocation_endpoint": "https://gateway.example/v1/connect/revoke", "response_types_supported": ["code"], "grant_types_supported": ["authorization_code"], "code_challenge_methods_supported": ["S256"], "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"], "scopes_supported": ["submit", "read", "cancel", "download"], "authorization_response_iss_parameter_supported": true }, "dashboard": {"job_url_template": "https://console.example/my/jobs/{job_id}"} } ``` All URLs come from the gateway's configuration (`public_url`, `dashboard_url`), never from request headers. A missing `public_url` gives `gateway_url: null` and `connect.available: false` with the reason. A disabled gateway answers 503 with its reasons. A dashboard URL alone never means that submission is available. `GET /v1/connection` needs any valid credential. It returns what this credential may do now: ```json { "schema": "vq.gateway-connection/1", "api_version": "1", "gateway_url": "https://gateway.example", "authority": "authority-one", "mode": "local", "credential": {"id": "0123456789abcdef", "kind": "application-grant", "scopes": ["submit", "read", "download"], "expires_at": "..."}, "application": {"id": "research-app", "display_name": "Research app", "grant_id": "fedcba9876543210", "grant_expires_at": "...", "return_origins": ["https://app.example"]}, "requested_by": {"issuer": "https://id.example", "subject": "opaque-subject"}, "executing_principal": {"project": "group-a", "principal": "alice", "execution_identity": "bound", "subjects_bound_to_principal": 1, "per_user_isolation": true, "note": "..."}, "policy": {"programs": ["vibeqc-release"], "runtime_pins": {"vibeqc-release": ["<40-hex commit>"]}, "quota_limits": {"max_cpus": 8, "max_mem_mb": 8192, "max_wall_time_seconds": 3600, "max_active_jobs": 10, "storage_quota_mb": 1024}, "result_retention_days": 14}, "submission": {"available": true, "reasons": [], "notices": []}, "dashboard": {"job_url_template": "https://console.example/my/jobs/{job_id}"} } ``` A machine key gives `kind: "machine-key"` with `application` and `requested_by` set to null. `submission.available` is false, with reasons, when the credential lacks `submit`, the principal has no required execution binding, a quota is zero or the gateway has no broker. Pin `authority` and `gateway_url` when you connect. If either changes, stop submitting and reconnect, because grants issued by another authority are refused. ## Connecting a user The flow is OAuth 2.0 authorization code with PKCE between the application and the gateway. The gateway itself signs the user in through OpenID Connect (authorization code + PKCE, `max_age`) at the configured provider. 1. **The application's backend** creates a random `state` and a PKCE verifier. It keeps both server-side and sends the browser to: ``` GET /v1/connect/authorize?response_type=code&client_id=research-app &redirect_uri=https%3A%2F%2Fapp.example%2Fscheduler%2Fcallback &state=STATE&code_challenge=S256(VERIFIER)&code_challenge_method=S256 [&scope=submit+read+download] ``` An unknown `client_id`, or a `redirect_uri` that is not an exact registered value, is answered with 400 and never redirected. Other errors are redirected to the callback as `error`, `error_description` and `state`. 2. **The gateway** sets a short-lived, path-scoped `HttpOnly; Secure; SameSite=Lax` cookie that binds the sign-in to this browser. It then sends the browser to the provider with its own `state`, `nonce` and PKCE challenge. 3. **At the callback** the gateway consumes the state once and requires the same browser cookie. It redeems the provider's code server-to-server and verifies the ID token: - an RS256 or ES256 signature against the provider's JWKS; - the exact `iss` and an audience containing its `client_id` (`azp` when present); - `exp`, `iat` and `nonce`; - an `auth_time` within `max_auth_age_seconds`, plus `required_amr` and `required_acr` when configured. It then looks up the identity binding for that `iss`/`sub` and checks that it lists this application. The project's `allowed_principals` still apply. Email, name and domain claims are ignored. 4. **The application's callback** receives `?code=vqac_...&state=STATE&iss=https://gateway.example`. Check that `state` matches and that `iss` equals the pinned `gateway_url`. 5. **The application's backend** redeems the code within 60 seconds, once: ``` POST /v1/connect/token Authorization: Basic base64(client_id:client_secret) Content-Type: application/x-www-form-urlencoded grant_type=authorization_code&code=vqac_...&redirect_uri=...&code_verifier=VERIFIER ``` ```json {"access_token": "vqk__", "token_type": "Bearer", "expires_in": 2591999, "expires_at": "...", "scope": "submit read download", "credential_id": "...", "grant_id": "...", "application": "research-app", "project": "group-a", "principal": "alice", "requested_by": {"issuer": "...", "subject": "..."}, "authority": "authority-one", "gateway_url": "https://gateway.example", "connection_url": "https://gateway.example/v1/connection", "dashboard": {"job_url_template": "..."}} ``` The response is `Cache-Control: no-store`. Store `access_token` in the backend's secret store, never in a browser, URL, log or source file. If a code is redeemed twice, the second attempt fails, and the grant from the first is revoked as possibly stolen. The granted scopes are the intersection of the application's `scopes`, the binding's optional `scopes` and the requested `scope`. ## Credential lifetime | Operation | Endpoint or command | Effect on the credential | Effect on accepted jobs | |---|---|---|---| | Expiry | `grant_max_days` after issue | Refused on the next request | None | | Rotation | `POST /v1/connect/rotate` (client auth, `token=`) | New `vqk_` with the same grant and expiry; the old one is refused at once | None; replays keep the same jobs | | Disconnect | `POST /v1/connect/revoke` (client auth, `token=` or `grant_id=`) | The grant and all its credentials are refused | None; jobs keep running and stay owned by the principal | | Operator revoke | `vq gateway application revoke GRANT_ID` | Same as disconnect | None | | Binding removed or changed | Configuration | Refused on the next request; restoring the binding restores access | None | | Application removed | Configuration | Refused | None | | Authority or `public_url` changed | Configuration | Refused: "issued by a different authority; reconnect" | None | | Principal removed from `allowed_principals` | Configuration | Refused (403) | None | A new connection of the same user and application sees the same jobs, because ownership belongs to the project and principal, not to the credential. ## Submitting Use the existing [upload and submission API](gateway.md#submit-a-calculation) with `Authorization: Bearer vqk_...`. `POST /v1/jobs` accepts two optional provenance fields: - `application_request_id`: the application's stable ID for this request (1 to 128 characters from `A-Z a-z 0-9 . _ : -`). Using it as the `idempotency_key` too is recommended. - `external_ref`: an opaque reference, such as a URN or record ID (1 to 512 printable ASCII characters). These fields never reach the broker, a connector or a target. The job's owner record keeps a `provenance` object: ```json {"schema": "vq.gateway-provenance/1", "application": "research-app", "requested_by": {"issuer": "...", "subject": "..."}, "executing_principal": {"project": "group-a", "principal": "alice"}, "credential_id": "...", "grant_id": "...", "application_request_id": "req-0001", "external_ref": "urn:example:run:1", "payload_sha256": "", "request_sha256": "", "runtime": {"program": "vibeqc-release", "expected_sha": "<40-hex>"}, "recorded_at": "..."} ``` **Idempotency.** The key is namespaced by project, principal and application. It does not include the credential, so the same request returns the same job after lost responses, gateway restarts, rotation or reconnection. That answer is 200 with `replayed: true`. A different payload, command, resources, program, pin, `application_request_id`, `external_ref` or requesting user under the same key is a 409, and the original job is untouched. **Policy stays with the scheduler.** Programs, resource ceilings, quotas, `runtime_pins` and execution bindings are checked on the gateway. A project may set `runtime_pins = {"program" = ["<40-hex>", ...]}`; a listed program then requires one of those commits as `expected_sha` (403 otherwise). ## Status Every job view (`GET /v1/jobs`, `GET /v1/jobs/{id}`, the submit response) adds `lifecycle`, `provenance` and `dashboard_url` to its existing fields: ```json "lifecycle": {"schema": "vq.job-lifecycle/1", "phase": "running", "terminal": false, "reason": "the target reported running", "source": "target", "observed_at": "...", "changed_at": "...", "stale": false, "results_ready": false, "target_state": "running", "execution_outcome": null, "scientific_validation": "not-performed"} ``` | `phase` | Meaning | |---|---| | `accepted` | Durably recorded by the gateway (relay mode); not yet delivered to the broker. | | `transferring` | Being delivered: the connector has claimed it, or the broker is transferring it. | | `waiting` | At the broker, waiting for capacity or a hold; `reason` lists the blockers. | | `placed` | Handed to the target. Running or queued there, not yet observed. **Not a completion verdict.** | | `running` | The target last reported it running or suspended. | | `completed` | The target reported success and the results are collected. | | `failed` | Refused at delivery, or the target reported a failure state (`reason`, `target_state`). | | `cancelling` | Cancellation requested and not yet confirmed. | | `cancelled` | Cancelled. | | `uncertain` | Delivery or cancellation is in doubt. Nothing is resubmitted; the operator resolves it. | - `terminal` is true only for `completed`, `failed` and `cancelled`. - `observed_at` is when the information was observed: now for a broker read, or the connector's or result probe's time. - `stale` is true when a non-terminal observation may be out of date: the relay connector is not fresh, or the last target report is more than 15 minutes old. - `source` is one of `broker`, `gateway`, `connector`, `target` or `results`. Target states are observed when a result request probes the target, so poll `GET /v1/jobs/{id}/results` with backoff (for example every 30 to 120 seconds) until `ready`. Webhooks are not provided. Polling covers the current needs, and webhooks would need outbound network access and new credentials. **Execution is not validation.** `completed` and `execution_outcome: "succeeded"` mean only that the target reported a successful exit. `scientific_validation` is always `not-performed`. Numerical checks, reference comparisons and scientific intake belong to the consuming application. ## Results `GET /v1/jobs/{id}/results` (`download` scope) answers `ready: false` until the results are collected. Then it returns the manifest with completeness fields: ```json {"ready": true, "job_id": "...", "collected_at": "...", "target_state": "completed", "files": [{"path": "out.json", "size": 17, "sha256": "..."}], "skipped": [], "complete": true, "file_count": 1, "total_bytes": 17, "execution_outcome": "succeeded", "scientific_validation": "not-performed"} ``` - `complete` is false when anything was skipped, such as links or unsafe paths. - `GET /v1/jobs/{id}/results/{path}` downloads one file. It sends `X-Content-SHA256` and supports HTTP `Range` requests (206), so a download can resume. Verify every file against the manifest digest before using it, and reject any mismatch. ## Dashboard handoff `dashboard_url` is `/my/jobs/{job_id}`, when the operator sets `[gateway] dashboard_url`. Opening it requires the user's own dashboard login: a hosted submitter account bound to the same project and principal. A deep link never grants access. Another principal's job, or an unauthenticated visitor, gets the same not-found or login answer as any other URL. Append `?return_to=` to offer a **Return to the application** link. The link is shown only when the URL's origin exactly matches one of the application's `return_origins`. Any other value is dropped silently. Users can sign in to the dashboard through the same provider when the operator enables [console single sign-on](hosted_console.md#single-sign-on-through-an-identity-provider-264). It replaces the dashboard password; the account's own authenticator is still required. ## Operator configuration All values below are synthetic. Add them to the gateway's external configuration. The browser console needs the same `[gateway]` sections to validate `return_to`. ```toml [gateway] enabled = true public_url = "https://gateway.example" # exact HTTPS origin clients use execution_authority = "authority-one" dashboard_url = "https://console.example" # optional [gateway.identity_providers.portal] issuer = "https://id.example" # exact iss client_id = "vq-gateway" client_secret_file = "/absolute/private/oidc-client-secret" # omit for a public PKCE client redirect_uri = "https://gateway.example/v1/connect/callback" # register exactly this max_auth_age_seconds = 300 required_amr = ["mfa"] # optional [gateway.applications.research-app] display_name = "Research app" identity_provider = "portal" client_secret_sha256 = "" redirect_uris = ["https://app.example/scheduler/callback"] return_origins = ["https://app.example"] scopes = ["submit", "read", "download"] grant_max_days = 30 [[gateway.identity_bindings]] issuer = "https://id.example" subject = "" project = "group-a" principal = "alice" applications = ["research-app"] # scopes = ["read", "download"] # optional narrowing ``` - `vq gateway application new-secret` prints a client secret once, for the application's secret store, and the `client_secret_sha256` to configure. - `vq gateway application grants` lists grants, without credentials. - `vq gateway application revoke GRANT_ID` disconnects one grant. - The gateway host needs `cryptography` for ID-token signatures. It ships in the `mfa` extra (`vibescheduler[web,mfa]`) and is imported only when a provider is used. - `client_secret_file` is an owner-only regular file. - Pending sign-ins, codes and grants are kept in `/connect/` (owner-only). The audit log records connection events, without secrets. ## Minimal client ```python import base64, hashlib, secrets, urllib.parse import requests GATEWAY = "https://gateway.example" disc = requests.get(f"{GATEWAY}/v1/discovery", timeout=10).json() pinned = (disc["authority"], disc["gateway_url"]) # 1. Start: keep state and verifier server-side, e.g. in the user's session row. state, verifier = secrets.token_urlsafe(16), secrets.token_urlsafe(48) challenge = base64.urlsafe_b64encode( hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() authorize = disc["connect"]["authorization_endpoint"] + "?" + urllib.parse.urlencode({ "response_type": "code", "client_id": CLIENT_ID, "redirect_uri": CALLBACK, "state": state, "code_challenge": challenge, "code_challenge_method": "S256"}) # ... redirect the browser to `authorize` ... # 2. Callback handler: check state and iss, then redeem server-to-server. def on_callback(params): assert params["state"] == state and params["iss"] == pinned[1] token = requests.post(disc["connect"]["token_endpoint"], auth=(CLIENT_ID, CLIENT_SECRET), data={"grant_type": "authorization_code", "code": params["code"], "redirect_uri": CALLBACK, "code_verifier": verifier}, timeout=10).json() return token["access_token"] # store in the backend secret store # 3. Submit and follow. def submit(key, tar_bytes, request_id, ref): h = {"Authorization": f"Bearer {key}"} up = requests.post(f"{GATEWAY}/v1/uploads", headers=h, timeout=30, json={ "size": len(tar_bytes), "sha256": hashlib.sha256(tar_bytes).hexdigest()}).json() requests.put(f"{GATEWAY}/v1/uploads/{up['upload_id']}", data=tar_bytes, timeout=300, headers={**h, "Content-Range": f"bytes 0-{len(tar_bytes)-1}/{len(tar_bytes)}"}) requests.post(f"{GATEWAY}/v1/uploads/{up['upload_id']}/finalize", headers=h, timeout=60) return requests.post(f"{GATEWAY}/v1/jobs", headers=h, timeout=60, json={ "upload_id": up["upload_id"], "command": ["python3", "run.py"], "program": "vibeqc-release", "expected_sha": PIN, "cpus": 1, "mem_mb": 512, "wall_time_seconds": 600, "idempotency_key": request_id, "application_request_id": request_id, "external_ref": ref}).json() ``` Retry uploads from `GET /v1/uploads/{id}` → `received`. Retry `POST /v1/jobs` with the identical body. The `vq remote` client implements the same steps for machine keys. ## Bounded live canary Run this only with the maintainer's approval, on a release that contains #264, with one consenting user and one disposable application registration. 1. Configure one provider, one application and one identity binding for the pilot user's existing project and principal, then restart the gateway. Confirm that `GET /v1/discovery` reports `connect.available: true` and the expected `authority` and `gateway_url`. 2. Connect once from the application. Confirm that `GET /v1/connection` shows the expected application, subject and principal, with `submission.available`. 3. Submit the [single-user pilot payload](machine_keys.md#finish-a-single-user-pbs-pilot-243) (one CPU, 512 MiB, 120 s) with `application_request_id=canary-264-001`. Replay the identical request and confirm the same job ID. 4. Follow the job to `completed`, fetch and verify the results, and open `dashboard_url` with `return_to` as the same user. 5. Confirm that a second identity, or the same job ID used with another principal's credential, is denied. 6. Rotate the credential, replay again (same job), then disconnect. Confirm that the credential is refused and that the job remains listed after a reconnect. 7. Record the job ID, phases, timestamps and outcome on #264, without credentials. Remove the binding afterwards if the pilot is not continuing. This is a connection check, not scientific qualification.