Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions apps/farm/app/pages/integracoes.vue
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ const scopeLabels: Record<IntegrationScope, string> = {
'inventory:write': 'Registrar e retirar carretéis',
'environment:control': 'Controlar ambiente',
'alerts:manage': 'Gerenciar regras de alerta e testar notificações',
'control:emergency': 'Parada de emergência',
}
const scopeOptions = INTEGRATION_SCOPES.map(
(scope) => [scope, scopeLabels[scope]] as const,
Expand Down Expand Up @@ -527,10 +528,21 @@ function grantDraft(appId: string) {
v-model="grantDraft(app.id).scopes"
type="checkbox"
:value="scope"
:aria-describedby="
scope === 'control:emergency'
? `emergency-consent-${app.id}`
: undefined
"
/>
<span>{{ label }} ({{ scope }})</span>
</label>
</div>
<p :id="`emergency-consent-${app.id}`" class="meta">
Ao conceder “Parada de emergência”, o aplicativo poderá parar a
impressora imediatamente. A API não consegue recuperar a
impressora: depois da parada, será preciso agir na própria
impressora ou no OpenFarm pelo navegador (reiniciar o firmware).
</p>
</fieldset>
<div class="field">
<label :for="`printer-${app.id}`"
Expand Down
1 change: 1 addition & 0 deletions apps/farm/app/utils/integration-scopes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ export const INTEGRATION_SCOPES = [
'inventory:write',
'environment:control',
'alerts:manage',
'control:emergency',
] as const
export type IntegrationScope = (typeof INTEGRATION_SCOPES)[number]
35 changes: 33 additions & 2 deletions apps/farm/server/services/fleet-mode-http.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { createError, type RequestEvent } from 'nuxt/server'
import { readMemberFleetMode } from '../storage/fleet-mode-postgres.ts'
import { uuidPattern } from '../utils/integration-auth.ts'
import { integrationAuthPool } from '../utils/integration-auth-runtime.ts'
import {
integrationAuthConfigured,
integrationAuthPool,
} from '../utils/integration-auth-runtime.ts'
import { printerAssignmentsRuntime } from '../utils/printer-assignments/runtime.ts'
import { authRuntime } from '../utils/auth/runtime.ts'
import { authenticatedSession, authResponse } from './authenticated-session.ts'
import {
authenticatedSession,
authResponse,
sealedSessionRecordId,
} from './authenticated-session.ts'

/** Read availability only for an authenticated member of the assignment's farm. */
export async function farmFleetMode(
Expand All @@ -15,6 +23,29 @@ export async function farmFleetMode(
if (!uuidPattern.test(farmId) || !uuidPattern.test(printerId))
throw createError({ status: 404, message: 'Impressora não encontrada.' })
const { accountId } = await authenticatedSession(event, authRuntime())
if (!integrationAuthConfigured()) {
const auth = authRuntime()
const sessionRecordId = await sealedSessionRecordId(event, auth)
const { profiles } = await printerAssignmentsRuntime()
const result = await profiles.read({
sessionRecordId,
policy: { idleTimeoutMs: auth.idleTimeoutMs },
farmId,
assignmentId: printerId,
})
if (!result.ok) {
if (result.reason === 'forbidden' || result.reason === 'not-found')
throw createError({
status: 404,
message: 'Impressora não encontrada.',
})
throw createError({
status: result.reason === 'unauthorized' ? 401 : 503,
message: 'Impressora indisponível.',
})
}
return { mode: 'in-service' as const }
}
const row = await readMemberFleetMode(
integrationAuthPool(),
farmId,
Expand Down
5 changes: 4 additions & 1 deletion apps/farm/server/services/integration-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ export interface NewAction {
action: ApiEnvelopeAction
requiredScope: Extract<
IntegrationScope,
'control:basic' | 'control:extended' | 'plates:confirm'
| 'control:basic'
| 'control:extended'
| 'control:emergency'
| 'plates:confirm'
>
status: 'held' | 'submitted'
}
Expand Down
1 change: 1 addition & 0 deletions apps/farm/server/services/integration-delivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export type RequiredScope =
| 'jobs:write'
| 'control:basic'
| 'control:extended'
| 'control:emergency'
| 'plates:confirm'
/** What the Connector can report, in the order a command can progress. */
export type ConnectorOutcome =
Expand Down
7 changes: 6 additions & 1 deletion apps/farm/server/storage/integration-delivery-postgres.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ const columns = (sql: Sql) =>
const returning = (sql: Sql) =>
sql`cmd_id::text AS "cmdId", app_id::text AS "appId", grant_id::text AS "grantId", farm_id::text AS "farmId", agent_id::text AS "agentId", printer_assignment_id::text AS "printerAssignmentId", kind, resource_id::text AS "resourceId", required_scope AS "requiredScope", nonce, wire, issued_at::float8 AS "issuedAt", expires_at::float8 AS "expiresAt", status, refusal_code AS "refusalCode", result_detail AS "resultDetail", result_message AS "resultMessage", history_entry_id AS "historyEntryId", created_at::float8 AS "createdAt", updated_at::float8 AS "updatedAt"`

/** True while the envelope's app, grant and assignment still allow delivery. */
/**
* True while the envelope's app, grant and assignment still allow delivery.
* The stored scope is not trusted for emergency stop: the action in the signed
* frame (canonical JSON) decides, so one stored as `control:extended` is dead.
*/
const authorityActive = (sql: Sql) => sql`
EXISTS (
SELECT 1 FROM farm.integration_app_grants g
Expand All @@ -27,6 +31,7 @@ const authorityActive = (sql: Sql) => sql`
WHERE g.id = e.grant_id AND g.app_id = e.app_id AND g.farm_id = e.farm_id
AND (g.printer_assignment_id IS NULL OR g.printer_assignment_id = p.id)
AND e.required_scope = ANY(g.scopes)
AND (e.required_scope = 'control:emergency' OR strpos(e.wire, '"action":"emergency_stop"') = 0)
AND (NOT a.sandbox OR f.sandbox)
AND g.disabled_at IS NULL AND a.revoked_at IS NULL
AND p.revoked_at IS NULL AND p.farm_id = e.farm_id AND p.agent_id = e.agent_id)`
Expand Down
29 changes: 26 additions & 3 deletions apps/farm/server/utils/integration-auth-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,12 @@ const policies: RoutePolicy[] = [
{
method: 'POST',
path: /^\/printers\/[^/]+\/actions$/,
scopes: ['control:basic', 'control:extended', 'plates:confirm'],
scopes: [
'control:basic',
'control:extended',
'control:emergency',
'plates:confirm',
],
},
{
method: 'GET',
Expand Down Expand Up @@ -356,7 +361,12 @@ const policies: RoutePolicy[] = [
{
method: 'GET',
path: /^\/actions\/[^/]+$/,
scopes: ['control:basic', 'control:extended', 'plates:confirm'],
scopes: [
'control:basic',
'control:extended',
'control:emergency',
'plates:confirm',
],
},
{ method: 'GET', path: /^\/webhooks$/, scopes: ['events:subscribe'] },
{
Expand Down Expand Up @@ -430,6 +440,7 @@ async function readActionScope(request: Request) {
}
if (typeof action !== 'string') return 'invalid-request'
if (action === 'confirm_collection') return 'plates:confirm'
if (action === 'emergency_stop') return 'control:emergency'
return ['pause', 'resume', 'cancel'].includes(action)
? 'control:basic'
: 'control:extended'
Expand Down Expand Up @@ -587,7 +598,19 @@ export async function authorizeIntegrationRequest(
if ((targetFarm || printerId) && !grants.length)
return integrationProblem('not-found', headers)

return { principal: { ...principal, scopes, grants }, headers }
// The printer list offers emergency_stop only where the token may use it.
const emergency =
path === '/printers'
? {
emergencyGrants: principal.grants.filter((grant) =>
grant.scopes.includes('control:emergency'),
),
}
: {}
return {
principal: { ...principal, ...emergency, scopes, grants },
headers,
}
} catch {
return integrationProblem('service-unavailable', headers)
}
Expand Down
22 changes: 19 additions & 3 deletions apps/farm/server/utils/integration-auth-runtime.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { flagEnabled } from '@open3dfarmmanager/shared'
import postgres from 'postgres'
import { useRuntimeConfig } from 'nuxt/server'
import { PostgresIntegrationApps } from '../storage/integration-apps-postgres.ts'
Expand All @@ -9,20 +10,35 @@ import {
let active:
{ pool: ReturnType<typeof postgres>; auth: IntegrationAuth } | undefined

// Off values of the runtime flag; undefined, null and '' mean it is not set.
const disabledFlags: unknown[] = [undefined, null, '', false, 'false', '0', 0]

/** False only when disabled or absent; a malformed flag throws. */
export function integrationAuthConfigured() {
const config: unknown = useRuntimeConfig().integrationAuth
if (config === undefined || config === null) return false
if (typeof config === 'object') {
const enabled = 'enabled' in config ? config.enabled : undefined
if (flagEnabled(enabled)) return true
if (disabledFlags.includes(enabled)) return false
}
throw new Error('Configuração de autenticação de integrações inválida.')
}

function integrationRuntime() {
if (active) return active
const config = useRuntimeConfig().integrationAuth
if (!integrationAuthConfigured())
throw new Error('Autenticação de integrações indisponível.')
if (
typeof config !== 'object' ||
config === null ||
!('enabled' in config) ||
config.enabled !== true ||
!('signingKey' in config) ||
!('tokenTtlSeconds' in config) ||
!('databaseUrl' in config) ||
typeof config.databaseUrl !== 'string'
)
throw new Error('Autenticação de integrações indisponível.')
throw new Error('Configuração de autenticação de integrações inválida.')
const token = parseIntegrationTokenConfig(config)
const url = new URL(config.databaseUrl)
if (
Expand Down
2 changes: 2 additions & 0 deletions apps/farm/server/utils/integration-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ export interface IntegrationPrincipal {
appId: string
scopes: readonly IntegrationScope[]
grants: readonly IntegrationGrant[]
/** Grants with control:emergency, kept where a route narrows `grants`. */
emergencyGrants?: readonly IntegrationGrant[]
}

const context = 'openfarm-integrations-v1.'
Expand Down
23 changes: 20 additions & 3 deletions apps/farm/server/utils/integration-printers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,15 +140,19 @@ export function printerSpecs(
return Object.keys(specs).length ? specs : undefined
}

function toPrinter(row: IntegrationPrinterRow) {
function toPrinter(row: IntegrationPrinterRow, mayStop: boolean) {
const parsed = parsedState(row)
const data = {
id: row.id,
farmId: row.farmId,
printerKey: row.printerKey,
// `clear_hold` is a browser-only operator action, never an API action.
// `emergency_stop` is offered only to an app granted control:emergency.
controls: parsed.success
? (parsed.data.controls ?? []).filter((action) => action !== 'clear_hold')
? (parsed.data.controls ?? []).filter(
(action) =>
action !== 'clear_hold' && (mayStop || action !== 'emergency_stop'),
)
: [],
sandbox: row.sandbox,
} as Record<string, unknown>
Expand Down Expand Up @@ -198,7 +202,20 @@ export async function listIntegrationPrinters(
const hasMore = rows.length > limit
const page = rows.slice(0, limit)
return {
data: page.map(toPrinter),
data: page.map((row) =>
toPrinter(
row,
!!integrationGrantFor(
{
...principal,
grants: principal.emergencyGrants ?? principal.grants,
},
'control:emergency',
row.farmId,
row.id,
),
),
),
nextCursor: hasMore
? encodedCursor(page[page.length - 1]!.id, snapshotAt)
: null,
Expand Down
9 changes: 9 additions & 0 deletions docs/COMMAND-SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ When receiving an API-originated command envelope, the Connector executes the fo
5. **Owner-granted scope authorization (`unauthorized`, `scope-denied`):**
- Verifies that the envelope carries an owner-granted scope authorizing the specific action; library print starts use `jobs:write`.
- Refuses commands if the required scope was not granted by the farm owner for the calling application.
- API `emergency_stop` requires `control:emergency`; see [API emergency stop](#api-emergency-stop).

6. **Freshness and clock validation (`invalid-clock`, `command-expired`, `clock-window`):**
- Validates monotonic time against system wall clock; detects and fails closed on backwards clock regression.
Expand All @@ -69,6 +70,14 @@ When receiving an API-originated command envelope, the Connector executes the fo
- Consumes the replay claim exactly once; no automatic retry of uncertain commands.
- If the physical dispatch result or connection to the printer driver fails or is ambiguous, the Connector records and reports uncertainty explicitly rather than retrying.

## API emergency stop

An API `emergency_stop` needs its own owner-granted scope, `control:emergency`. `control:extended` does not cover it, and a grant made before the scope existed does not gain it: the owner must grant it again. The server and the database action guard require the scope. The Connector refuses, before any write and with a pt-BR reason, an `emergency_stop` envelope whose signed or inbox scope is anything else. Browser capabilities are unchanged.

Recovery limitation: the API cannot recover a stopped printer, because `firmware_restart` is never an API action. Someone must act at the printer or send the firmware restart from the OpenFarm browser.

Deploy order: apply the database migration and deploy the server first, then the Connectors. A new Connector refuses an `emergency_stop` envelope from an older server, which signs it as `control:extended`; this fails closed. An older Connector does not know `control:emergency` and does not execute the stop from a newer server, so upgrade Connectors before relying on it.

## Full printer control rules

These action rules apply at the Connector immediately before dispatch. They supplement envelope identity, scope, freshness, replay, and state checks above and never replace them. Roles come from authenticated local membership data, never command fields. Role order is operator < admin < owner; "operator or higher" means all three roles. Every action is refused in `unknown` state except `emergency_stop` and `clear_hold`; in `error` state only `emergency_stop`, `firmware_restart`, `confirm_collection` and `clear_hold` are admitted. `run_macro` stays owner or admin. This section does not grant any role access beyond what the issue or documented current behavior already allows.
Expand Down
25 changes: 23 additions & 2 deletions docs/INTEGRATION-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Owners can grant one or more scopes across a farm or limit them to a printer ass
| `inventory:write` | Register and withdraw physical spools. |
| `environment:control` | Control drying programs, smart plugs and extraction. |
| `alerts:manage` | Change alert rules and configure or test notification channels. |
| `control:emergency` | Emergency stop. The API cannot recover the printer afterwards. |

Each scope in the table authorizes the operations listed above.
`environment:control` is used by the environment control endpoints below.
Expand Down Expand Up @@ -532,8 +533,8 @@ another request. The service never automatically retries an uncertain write.
## Request actions

`POST /printers/{printerId}/actions` also requires an `Idempotency-Key`.
`pause`, `resume` and `cancel` require `control:basic`; other supported actions
require `control:extended`. Send the action and its `args` as specified by the
`pause`, `resume` and `cancel` require `control:basic`; `emergency_stop` requires
`control:emergency`; other supported actions require `control:extended`. Send the action and its `args` as specified by the
OpenAPI schema (use `{}` for actions without arguments), then track the result
with `GET /actions/{actionId}`. The printer must advertise the action. Check
printer state immediately before each command and account for the possibility
Expand All @@ -544,6 +545,26 @@ and identical body only when intentionally retrying a request whose outcome is
known to be safe; changed bodies with a reused key receive
`idempotency-key-reused`.

### Emergency stop

`emergency_stop` has its own scope, `control:emergency`. `control:extended` does
not include it, and grants made before this scope existed do not receive it: the
owner must make a new grant that names it. `GET /printers` lists
`emergency_stop` in a printer's `controls` only when the access token holds
`control:emergency` for that printer.

The command stops the printer immediately. **The API cannot recover the
printer.** `firmware_restart` is never an API action, so after an emergency stop
someone must act at the printer or send the firmware restart from the OpenFarm
browser.

Deploy order: apply the database migration and deploy the server first, then the
Connectors. A new Connector refuses an `emergency_stop` envelope from an older
server, which signs it as `control:extended`, so it fails closed. An older
Connector does not know the new scope and does not execute an `emergency_stop`
from a newer server; the action does not complete, so upgrade the Connector
before relying on it.

## Handle errors and Connector refusals

For API errors, branch on the problem `code`, not its human-readable `title` or
Expand Down
9 changes: 8 additions & 1 deletion docs/api/openapi-v1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,11 @@ paths:
`pause`, `resume` and `cancel` require `control:basic`.
`confirm_collection` requires `plates:confirm` and the current plate
attempt id (`plate.attemptId` on the printer status, or the job plate
read). Confirming the current attempt again is safe. Every other
read). Confirming the current attempt again is safe.
`emergency_stop` requires `control:emergency`, a separate owner grant
that `control:extended` does not include. It stops the printer
immediately. The API cannot recover the printer: someone must act at
the printer or in the OpenFarm browser (firmware restart). Every other
action requires `control:extended`. An action the printer does not
advertise answers 422 `unsupported` and is never delivered. Otherwise
the action is delivered to the Connector or, when the grant requires
Expand All @@ -653,6 +657,7 @@ paths:
security:
- clientCredentials: ['control:basic']
- clientCredentials: ['control:extended']
- clientCredentials: ['control:emergency']
- clientCredentials: ['plates:confirm']
parameters:
- $ref: '#/components/parameters/PrinterId'
Expand Down Expand Up @@ -2213,6 +2218,7 @@ paths:
security:
- clientCredentials: ['control:basic']
- clientCredentials: ['control:extended']
- clientCredentials: ['control:emergency']
- clientCredentials: ['plates:confirm']
parameters:
- name: actionId
Expand Down Expand Up @@ -3001,6 +3007,7 @@ components:
inventory:write: Register and withdraw physical spools.
environment:control: Control drying programs, smart plugs and extraction.
alerts:manage: Change alert rules and configure or test notification channels.
control:emergency: Emergency stop. The API cannot recover the printer afterwards.
parameters:
PhysicalSpoolFarmId:
name: farmId
Expand Down
Loading
Loading