Skip to content

Client and auth

Two packages talk to the platform’s identity and API surface. client is the HTTP client for the platform’s REST API. auth obtains tokens, validates tokens your service receives, runs the OAuth authorization-code login and verifies field-worker tokens.

import (
"github.com/flowcatalyst/go-sdk/auth"
"github.com/flowcatalyst/go-sdk/client"
)
cc := auth.NewClientCredentialsProvider(auth.ClientCredentialsConfig{
IssuerURL: "https://auth.example.com",
ClientID: "svc-orders",
ClientSecret: secret,
})
c := client.New("https://platform.example.com", client.WithTokenProvider(cc.Token))
types, err := c.EventTypes().List(ctx, &client.EventTypeFilters{Application: "orders"})

client.New(baseURL, opts...) returns a *client.FlowCatalystClient. Each aggregate is reached through an accessor that returns a resource with List, Get, Create, Update, Delete, Sync and the aggregate’s own operations.

Option Meaning
WithToken(token) A static bearer token. For tokens that do not expire.
WithTokenProvider(fn) func(ctx) (string, error), called before every request. It must be safe for concurrent use. Pass cc.Token.
WithHTTPClient(h) Replace the *http.Client (transport, proxy, TLS).
WithTimeout(d) The timeout of each attempt of a call. Default 30 seconds. Retries and the waits between them are not counted, so a call can take longer than d in all. To bound the whole call, pass a context with a deadline.
WithRetry(attempts, baseDelay) Total attempts including the first, and the base delay. Default 3 attempts, 100 ms, doubling.
WithRouterBaseURL(u) The message router’s base URL, for Router(). Default: the platform’s.

EventTypes, Subscriptions, DispatchPools, Applications, Processes, Principals, Roles, Permissions, AuditLogs, Clients, Connections, Me, Router, ScheduledJobs, OpenAPI, Docs, ServiceAccounts, PlatformConfig, Ingestions, IngestionSets, FieldWorkers, FieldDevices, FieldPolicies and FieldTokens.

The client follows the platform’s OpenAPI lock method by method, and go test ./client/ checks it:

  • A route that answers 204 No Content (update, suspend, activate, archive, delete, pause, resume, enable, disable) returns only an error.
  • A create route that answers { "id" } returns *client.CreatedResponse; call Get for the record. Connections().Create is the exception: the platform answers 201 with the whole connection.
  • A route that answers a body returns it.

There is no accessor for GET /api/events or the dispatch-job batch endpoint. To create events and jobs, use the outbox; the outbox relay sends them.

A request is repeatable when its method is GET, HEAD, OPTIONS, PUT or DELETE, or when it is a POST the SDK marks repeatable with PostRepeatable: the declarative Sync calls, the field-token introspection, the router’s read-only in-flight check. A plain POST (a create, a provision, a state change) is not repeatable. Retries use exponential backoff and follow one rule:

  • 408, 425 and 429 (refused before the platform processed the request) are retried for every request. So is a transport failure before anything was sent: DNS, connection refused, a dial or TLS handshake failure.
  • 502, 503 and 504, and a transport failure after the request may have been sent (a reset, EOF, the attempt’s timeout), are retried only for a repeatable request. Any other request is not sent again and the call returns a *client.OutcomeUnknownError: the platform may have applied it. Read the state (for example Get the record) before deciding to send it again. client.IsOutcomeUnknown(err) tests for it, and errors.As still finds the *APIError for a gateway status.
  • 500 is retried for a repeatable request and returned as the *APIError for any other.
  • A DELETE that answers 404 after an earlier attempt’s outcome was unknown succeeds, because that attempt most likely deleted the record.
  • Cancelling the caller’s context, or its deadline passing, is never retried.

A plain create is therefore never sent twice by the client. If you retry it yourself, use an idempotency key where the endpoint offers one.

c.PlatformConfig() has Get, Set, Delete and RevealSecret. Reads and the answer to Set return the literal "***" (client.SecretMask) as the value of every SECRET property, for every caller. The only way to read the plaintext is RevealSecret:

s, err := c.PlatformConfig().RevealSecret(ctx, "orders", "smtp", "password", "" /* clientID, optional */)

Reveal always needs a permission: platform:admin:config:reveal (a platform administrator) or platform:application-service:config:reveal (an application’s service account, which the platform confines to its own applications and to the clients it is linked to). Every reveal is audited. The SDK does not cache or log the value, and SecretResponse prints as redacted under %v, %+v, %#v and slog. Writing "***" or an empty value to a SECRET is refused (400 SECRET_VALUE_MASKED or SECRET_VALUE_REQUIRED); to keep a secret, do not set it. A property that is not a secret answers 400 NOT_A_SECRET; use Get.

A service account acting for a person can have the audit row name them:

ctx = client.WithOnBehalfOf(ctx, person.ID) // sent as X-On-Behalf-Of
err := c.PlatformConfig().Set(ctx, "orders", "smtp", "password", req)

The value is at most 256 characters with no control characters; otherwise the call fails with client.ErrInvalidOnBehalfOf before anything is sent. The platform honours it from service accounts only, and only on config Set, Delete and RevealSecret. See platform configuration.

c.Ingestions() covers ingestions, source kinds and connection tests; c.IngestionSets() covers sets. An ingestion needs an Application code (an INTEGRATION application) and a Client (id or identifier). The source and split are typed unions (client.HTTPSource, client.CSVSplit, and so on); client.CustomSource{Type, Settings} is the escape hatch for a runtime extension’s kind, and a kind this SDK does not know reads back as client.Unrecognized and is written back unchanged. Secrets are client.SecretRef names, never values. Lists are cursor-paged: pass the answer’s NextCursor as After. Definition returns the YAML that fcdev ingest apply reads.

Without the promote permission, Create, Update and SaveVersion save a draft, not an error. The answer’s Save.Outcome is DRAFT and Save.AwaitingPromote is true until someone who holds promote calls MakeVersionLive. A definition an existing version already says is not saved again (UNCHANGED, MADE_LIVE, DRAFT_EXISTS). Notices are failures the platform refused (Category rejected): list them with Failures(ctx, id, client.IngestionFailureFilters{Category: "rejected", Undismissed: true}) and dismiss one with DismissFailure. Secrets lists the secret names the live definition binds and each runtime’s last fetch, never a value. The runtime API (/api/ingestion-runtime/v1/*) is not in this SDK. See ingestion.

FieldWorkers, FieldDevices, FieldPolicies and FieldTokens are the admin API for field workers:

w, _ := c.FieldWorkers().Ensure(ctx, &client.EnsureFieldWorkerRequest{
ClientID: "clt_1", WorkerCode: "driver-42", Name: "Sam", AppCodes: []string{"deliveries"},
})
pin, _ := c.FieldWorkers().ResetPin(ctx, w.ID, nil) // nil: the platform generates a PIN
if pin.TemporaryPin != nil { /* shown once: hand it to the worker */ }
code, _ := c.FieldDevices().CreateEnrolmentCode(ctx, &client.CreateEnrolmentCodeRequest{
ClientID: "clt_1", Mode: "SHARED", AppCodes: []string{"deliveries"},
}) // render code.QrPayload as a QR code
res, _ := c.FieldTokens().Introspect(ctx, accessToken) // res.Active

Workers: Ensure, List, Get, Update, Delete, ResetPin, Unlock, Suspend, Activate, Link, Unlink, GrantApp, RevokeApp, SignIns, IssueBadge, ListBadges, RevokeBadge, BulkIssueBadges, CreateSignInCode. Devices: CreateEnrolmentCode, List, Get, Suspend, Activate, Revoke. Policies: Get, Put. The action methods return only an error. Offline verification of a field access token is auth.FieldTokenVerifier; Introspect is the online check that the session is still live.

auth.NewClientCredentialsProvider(cfg) obtains and caches service-account access tokens through the OAuth2 client_credentials grant at {IssuerURL}/oauth/token.

ClientCredentialsConfig
IssuerURL, ClientID, ClientSecret Required. Use the service account’s credentials, not a login client’s.
Scopes, Audience Optional.
SafetyWindow How long before expiry to refresh. Default 60 seconds.
HTTPClient Optional transport.

Token(ctx) returns a valid token, refreshing when the cached one is within the safety window. It is safe for concurrent use and serialises refreshes behind a mutex. Invalidate() clears the cache, for example after the platform answers 401. Pass cc.Token to client.WithTokenProvider.

Use these when your service is the resource server: it receives a bearer token and decides whether to trust it.

TokenValidator (RS256, the production choice)

Section titled “TokenValidator (RS256, the production choice)”
v := auth.NewTokenValidator(auth.TokenValidatorConfig{
IssuerURL: "https://auth.example.com",
Audience: "flowcatalyst", // default
})
ac, err := v.ValidateBearer(r.Context(), r.Header.Get("Authorization"))

The first call performs OIDC discovery to find the JWKS, which is then cached and refreshed hourly (JWKSRefreshInterval). Validate checks the signature, issuer, audience and exp/nbf with a 60 second clock skew (ClockSkew). RefreshJWKS forces a refetch after a known key rotation.

It accepts a token_use of api, identity or none. A field token, or any other class, is refused as ErrInvalidToken. The result is an *auth.AuthContext with PrincipalID(), Email(), Name(), IsAnchor(), IsService(), HasClientAccess(id), HasRole(role), ClientIDs(), Roles() and BearerToken() (the raw JWT, for forwarding), and the decoded Claims.

auth.NewHmacTokenValidator(secret, issuer, audience) validates HS256 tokens against a shared secret. Use it for development or when your application shares a signing secret with the platform; prefer TokenValidator for production. It does not check token_use.

auth.NewOAuthClient drives a browser login with PKCE.

oc := auth.NewOAuthClient(auth.OAuthConfig{
IssuerURL: "https://auth.example.com",
ClientID: "orders-web",
ClientSecret: secret, // omit for a public client
RedirectURI: "https://orders.example.com/auth/callback",
// Scopes default to openid, profile, email.
})
authorizeURL, params := oc.AuthorizeURL() // store params.PKCE, params.State, params.Nonce in the session
// redirect the browser to authorizeURL ...
// in the callback, after checking state:
tokens, err := oc.ExchangeCode(ctx, code, params.PKCE.CodeVerifier)
Method Does
AuthorizeURL() Builds the /oauth/authorize URL with a fresh PKCE challenge (S256), state and nonce, and returns the values to keep in the session.
ExchangeCode(ctx, code, verifier) Exchanges the code for a *TokenResponse (access, refresh and ID tokens, expiry, scope).
RefreshToken(ctx, refresh) Exchanges a refresh token.
RevokeToken(ctx, token) RFC 7009 revocation.
IntrospectToken(ctx, token) RFC 7662 introspection.
UserInfo(ctx, accessToken) The OIDC userinfo document.
LogoutURL(postLogoutRedirectURI, idTokenHint, state) The RP-initiated logout URL. An idTokenHint is required when you pass a redirect URI, because the platform checks the hint’s audience against the client’s registered post-logout URIs.

The package offers the pieces; it does not manage sessions or cookies. The login flow, the role of the ID token and which token to use for what are in OIDC login and tokens.

A field worker signs in from a device with a PIN or a badge, and the platform issues a short access token bound to the device key. Your backend verifies, per request, the token and a DPoP proof signed by the same key. Nothing here handles a PIN.

v := auth.NewFieldTokenVerifier(auth.FieldTokenVerifierConfig{
Issuer: "https://auth.example.com", // the platform base URL (the token's iss)
AppCode: "deliveries", // tokens must be addressed to this app (aud)
BaseURL: "https://deliveries.example.com", // this service's public base URL
})
mux.Handle("/api/", auth.FieldMiddleware(v)(apiHandler))
// in a handler:
p, ok := auth.FieldPrincipalFrom(r.Context())

FieldMiddleware puts an *auth.FieldPrincipal in the request context. A refused request is a 401 with WWW-Authenticate: DPoP and a JSON body {"error": "<reason>"}; a key-fetch failure is 503. Without the middleware, call v.Verify(ctx, authorization, dpop, method, fullURL) yourself.

  • BaseURL is required for the middleware, which panics at construction without it. The proof’s htu is compared against BaseURL plus the request path. The Host header and X-Forwarded-* headers are never used, because a client can set them. A direct Verify caller passes the full URL and may leave BaseURL empty.
  • The access token must be RS256 and the proof ES256; other algorithms are refused. A token with no exp is refused. A PIN-change-only token is refused.
  • ProofMaxAge (default 5 minutes) bounds the proof’s iat; widen it for devices with bad clocks.
  • Keys come from OIDC discovery, or from JWKSURL if you set it, and are cached for an hour.
  • Nonce checking is not done. If you need replay protection beyond the proof’s iat window, use the framework’s stateless nonce.

FieldPrincipal carries the worker (WorkerID, ClientID, ClientIdentifier, WorkerCode, Name), the DeviceID and DeviceMode (empty and UNENROLLED when the key is not an enrolled device), SessionID, AMR, timestamps, the key thumbprint JKT, an Actor (non-nil when someone else, such as a supervisor, is signed in as the worker), Test for test identities and LinkedPrincipalID for audit correlation only (it grants nothing). A refusal is an *auth.FieldError whose Reason is one of malformed, wrong_typ, wrong_token_use, wrong_aud, expired, invalid_token, pcr, missing_proof, invalid_proof, jkt_mismatch, htm_mismatch, htu_mismatch, ath_mismatch or stale_proof (the auth.FieldReason* constants), and it also satisfies errors.Is(err, auth.ErrInvalidToken). See field workers for the backend guide.