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
36 changes: 29 additions & 7 deletions docs/connectors/rest.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ OAuth2 connectors use the **Authorization Code + PKCE** flow:
#### Token endpoint authentication (`client_secret_basic`)

By default the client credentials are sent **in the body** of the token request (`client_secret_post`).
Some providers — **Datto RMM** and **DATEV** among them — only accept them as an **HTTP Basic header**
Some providers — **DATEV** among them — only accept them as an **HTTP Basic header**
(`Authorization: Basic base64(client_id:client_secret)`, RFC 6749 §2.3.1) and answer anything else with
`401` at the code-exchange step.

Expand All @@ -316,16 +316,38 @@ Notes:
only `hasClientSecret` / `hasAccessToken` / `hasRefreshToken` booleans.
- After switching the method, re-run **Authorize with Provider** so a token is fetched the new way.

Example — Datto RMM:
#### Grants without a sign-in (`client_credentials`, `password`)

Some APIs issue a token from stored credentials and expect the client to ask again when it expires,
with no refresh token. Choose the grant under **Grant type** in the connector form, or set `grant`:

- **Authorization code** (default): the flow above, renewed with the refresh token.
- **Client credentials** (`client_credentials`): the client ID and secret alone get the token.
- **Password** (`password`, RFC 6749 §4.3): the token request also carries a `username` and `password`.

With the last two there is nothing to authorize: the connector requests a token on its first call, again
shortly before the token expires, and again when the API answers `401`. The client is sent as an HTTP Basic
header by default for these grants; pick **Client secret in body** if the provider wants it in the form.
The username and password, like the client secret, are never returned by `GET .../oauth-config`, only
`hasUsername` / `hasPassword`.

```bash
curl -s -X PATCH http://localhost:4000/api/connectors/$CONNECTOR_ID/oauth-config \
-H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' \
-d '{"grant": "password", "username": "<API key>", "password": "<API secret>"}'
```

Example — Datto RMM. Its tokens last 100 hours and come with no refresh token, so a connector set up with
the authorization-code flow stops working after 100 hours. Use the password grant:

| Field | Value |
|---|---|
| Authorization URL | `https://<zone>-api.centrastage.net/auth/oauth/authorize` |
| Token URL | `https://<zone>-api.centrastage.net/auth/oauth/token` |
| Grant type | **Password** |
| Username / Password | the API key / API secret key of the technical user |
| Client ID / Secret | `public-client` / `public` |
| Token endpoint authentication | **HTTP Basic header** |

The API key and secret key of the technical user are entered on the provider's own consent screen.
| Token URL | `https://<zone>-api.centrastage.net/auth/oauth/token` |
| Token endpoint authentication | **HTTP Basic header** (the default for this grant) |

#### Signed client assertion (`private_key_jwt`)

Expand Down
3 changes: 2 additions & 1 deletion packages/backend/src/adapters/env-var-meta.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isSecretName } from '../connectors/connector-secrets.util';
import { isMachineGrant } from '../connectors/oauth-grant.util';
import type { AdapterDefinition } from './catalog';

/**
Expand Down Expand Up @@ -68,7 +69,7 @@ export function needsBrowserAuthorization(adapter: Pick<AdapterDefinition, 'conn
// An MCP bridge has no authorization URL of its own: the server's OAuth
// metadata names it when the user clicks "Authorize with Provider".
(!!auth.authorizationUrl || adapter.connector.type === 'MCP') &&
String(auth.grant ?? '') !== 'client_credentials'
!isMachineGrant(auth.grant)
);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getAdapter } from '../adapters/catalog';
import { isMachineGrant } from './oauth-grant.util';
import { interpolateDeep, interpolateString } from '../common/env-interpolation.util';
import { CALLER_CONTEXT_PREFIX } from '../common/caller-context.util';
import {
Expand Down Expand Up @@ -108,7 +109,7 @@ export function computeSetupState(input: SetupStatusInput): SetupState {
const authConfig = interpolateDeep(parseAuthConfig(input.authConfig), envVars, options);
const isBrowserOAuth =
input.authType === 'OAUTH2' &&
String(authConfig.grant ?? '') !== 'client_credentials' &&
!isMachineGrant(authConfig.grant) &&
(!!browserAuthorizationUrl(authConfig, input.config) || isCatalogMcpBridge(input.config));

// Tokens of a browser OAuth connector are written by the authorization; a
Expand Down
73 changes: 73 additions & 0 deletions packages/backend/src/connectors/connectors.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,48 @@ describe('OAuth2 config endpoints', () => {
});
});

it('switches a connector to the password grant (Datto RMM)', async () => {
const { controller, connectorsService } = build(oauthConnector());

await controller.updateOAuthConfig(req('ADMIN'), 'c1', {
grant: 'password',
username: 'api-key',
password: 'api-secret',
tokenAuthMethod: 'client_secret_basic',
});

expect(connectorsService.updateAuthConfigMerge).toHaveBeenCalledWith('c1', {
grant: 'password',
username: 'api-key',
password: 'api-secret',
tokenAuthMethod: 'client_secret_basic',
});
});

it('stores the authorization-code flow as no grant, as every authorized connector has', async () => {
const { controller, connectorsService } = build(oauthConnector());

await controller.updateOAuthConfig(req('ADMIN'), 'c1', { grant: 'authorization_code' });

expect(connectorsService.updateAuthConfigMerge).toHaveBeenCalledWith('c1', {
grant: undefined,
});
});

it('stores "in body" explicitly when switching to the password grant, whose default is Basic', async () => {
const { controller, connectorsService } = build(oauthConnector());

await controller.updateOAuthConfig(req('ADMIN'), 'c1', {
grant: 'password',
tokenAuthMethod: '',
});

expect(connectorsService.updateAuthConfigMerge).toHaveBeenCalledWith('c1', {
grant: 'password',
tokenAuthMethod: 'client_secret_post',
});
});

it('carries a corrected Etsy secret into the x-api-key header and the variables', async () => {
// Production, 6 Oct 2026: the keystring was typed as the shared secret
// at install, then corrected in the OAuth editor. authConfig.clientSecret
Expand Down Expand Up @@ -406,6 +448,37 @@ describe('OAuth2 config endpoints', () => {
expect(result.tokenAuthMethod).toBe('client_secret_basic');
});

it('reports the grant, and only whether the password-grant credentials are set', async () => {
const { encrypt } = require('../common/crypto/encryption.util');
const authConfig = encrypt(
JSON.stringify({
grant: 'password',
clientId: 'public-client',
clientSecret: 'public',
username: 'datto-api-key',
password: 'datto-api-secret',
}),
VALID_ENCRYPTION_KEY,
);
const { controller } = build(oauthConnector({ authConfig }));

const result = await controller.getOAuthConfig(req('ADMIN'), 'c1');

expect(result).toMatchObject({
grant: 'password',
tokenAuthMethod: 'client_secret_basic',
hasUsername: true,
hasPassword: true,
});
expect(JSON.stringify(result)).not.toContain('datto-api');
});

it('reports the authorization-code flow when no grant is stored', async () => {
const { controller } = build(oauthConnector({ authConfig: null }));

expect((await controller.getOAuthConfig(req('ADMIN'), 'c1')).grant).toBe('authorization_code');
});

it('degrades gracefully when the stored config cannot be decrypted', async () => {
// e.g. after an encryption-key rotation — the page must still load.
const { controller } = build(oauthConnector({ authConfig: 'not-decryptable' }));
Expand Down
72 changes: 57 additions & 15 deletions packages/backend/src/connectors/connectors.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import { decrypt } from '../common/crypto/encryption.util';
import { getAdapter } from '../adapters/catalog';
import { resolvePkce, resolveRestAuthorizeSettings } from './oauth-authorize-settings';
import { tokenEndpointUserAgent } from './engines/oauth2-token.service';
import { isMachineGrant } from './oauth-grant.util';
import {
DYNAMIC_CLIENT_KEY,
planMcpAuthorization,
Expand Down Expand Up @@ -307,6 +308,34 @@ class UpdateOAuthConfigDto {
@IsIn(['', 'client_secret_post', 'client_secret_basic', 'basic', 'post', 'private_key_jwt'])
tokenAuthMethod?: string;

@ApiPropertyOptional({
description:
'How the connector obtains its access token. `authorization_code` ' +
'(default, also sent as an empty string) signs in at the provider with ' +
'"Authorize with Provider" and renews with the refresh token. ' +
'`client_credentials` asks the token endpoint with the client id and ' +
'secret alone. `password` (RFC 6749 §4.3) sends `username` and ' +
'`password` as well, and asks again whenever the token expires: for ' +
'APIs that issue no refresh token, such as Datto RMM (username = API ' +
'key, password = API secret, client `public-client` / `public` sent as ' +
'HTTP Basic).',
enum: ['', 'authorization_code', 'client_credentials', 'password'],
})
@IsOptional()
@IsString()
@IsIn(['', 'authorization_code', 'client_credentials', 'password'])
grant?: string;

@ApiPropertyOptional({ description: 'Username for the password grant.' })
@IsOptional()
@IsString()
username?: string;

@ApiPropertyOptional({ description: 'Password for the password grant.' })
@IsOptional()
@IsString()
password?: string;

@ApiPropertyOptional({
description:
'Whether "Authorize with Provider" uses PKCE (RFC 7636): a ' +
Expand Down Expand Up @@ -1085,24 +1114,28 @@ export class ConnectorsController {
const adapterSlug = (connector.config as { adapterSlug?: string } | null)?.adapterSlug;
return {
clientId: str(cfg.clientId),
grant: isMachineGrant(cfg.grant) ? String(cfg.grant) : 'authorization_code',
authorizationUrl: str(cfg.authorizationUrl),
tokenUrl: str(cfg.tokenUrl),
scopes: str(cfg.scopes),
// Report what the token service will actually do. With nothing stored,
// the client_credentials grant sends HTTP Basic, not body credentials;
// showing "in body" there made the form misstate every such connector.
// the client_credentials and password grants send HTTP Basic, not body
// credentials; showing "in body" there made the form misstate every
// such connector.
tokenAuthMethod:
str(cfg.tokenAuthMethod) ||
(cfg.grant === 'client_credentials'
? 'client_secret_basic'
: 'client_secret_post'),
(isMachineGrant(cfg.grant) ? 'client_secret_basic' : 'client_secret_post'),
// What the authorization will do: the row's own setting, else the
// catalog adapter's (see resolvePkce).
pkce: resolvePkce(
cfg,
adapterSlug ? getAdapter(adapterSlug)?.connector.authConfig : undefined,
),
hasClientSecret: !!cfg.clientSecret,
// The password grant's credentials (Datto's API key and secret) are
// never returned, like the client secret.
hasUsername: !!cfg.username,
hasPassword: !!cfg.password,
hasAccessToken: !!cfg.accessToken,
hasRefreshToken: !!cfg.refreshToken,
};
Expand All @@ -1117,8 +1150,10 @@ export class ConnectorsController {
'endpoints established during authorization are preserved. Omitted ' +
'fields keep their current value; send an empty string to clear one. ' +
'Use `tokenAuthMethod` when a provider rejects credentials sent in the ' +
'request body (RFC 6749 §2.3.1 client_secret_basic) — Datto RMM and ' +
'DATEV both require it.',
'request body (RFC 6749 §2.3.1 client_secret_basic) — DATEV requires ' +
'it. Use `grant` for APIs that issue tokens without a user sign-in: ' +
'`client_credentials`, or `password` with `username` and `password` ' +
'(Datto RMM, whose 100-hour tokens come with no refresh token).',
})
async updateOAuthConfig(
@Req() req: any,
Expand All @@ -1141,20 +1176,27 @@ export class ConnectorsController {
'authorizationUrl',
'tokenUrl',
'scopes',
'username',
'password',
] as const) {
if (dto[key] !== undefined) patch[key] = dto[key];
}
if (dto.grant !== undefined) {
// The authorization-code flow is the default and is stored as no grant
// at all, which is what every connector authorized so far carries.
patch.grant = isMachineGrant(dto.grant) ? dto.grant : undefined;
}
if (dto.tokenAuthMethod !== undefined) {
// Empty = back to the default (credentials in the body). Except that
// "in the body" is not the default of the client_credentials grant —
// the token service sends HTTP Basic there unless told otherwise — so
// for that grant the form's "in body" choice has to be stored as such,
// or saving the form would quietly switch e.g. Amadeus back to Basic.
// "in the body" is not the default of the client_credentials and
// password grants — the token service sends HTTP Basic there unless
// told otherwise — so for those the form's "in body" choice has to be
// stored as such, or saving the form would quietly switch e.g. Amadeus
// back to Basic.
const grant =
dto.grant !== undefined ? dto.grant : this.readOAuthGrant(connector.authConfig);
patch.tokenAuthMethod =
dto.tokenAuthMethod ||
(this.readOAuthGrant(connector.authConfig) === 'client_credentials'
? 'client_secret_post'
: undefined);
dto.tokenAuthMethod || (isMachineGrant(grant) ? 'client_secret_post' : undefined);
}
if (dto.pkce !== undefined) {
// Stored either way: an explicit `true` must also beat a catalog
Expand Down
7 changes: 4 additions & 3 deletions packages/backend/src/connectors/engines/graphql.engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Injectable, Logger } from '@nestjs/common';
import axios, { AxiosError } from 'axios';
import { createUnblockerProxyAgent } from './unblocker-proxy-agent';
import { OAuth2TokenService } from './oauth2-token.service';
import { canRenewToken } from '../oauth-grant.util';
import {
LoginTokenService,
LoginTokenAuthConfig,
Expand Down Expand Up @@ -202,13 +203,13 @@ export class GraphqlEngine {

return response.data.data;
} catch (error) {
// OAuth2 auto-refresh: retry once on 401
// OAuth2 auto-refresh: retry once on 401 (a refresh token, or a grant
// that asks for a new token by itself, such as Datto's password grant)
if (
error instanceof AxiosError &&
error.response?.status === 401 &&
config.authType === 'OAUTH2' &&
config.authConfig?.refreshToken &&
config.authConfig?.tokenUrl
canRenewToken(config.authConfig)
) {
this.logger.debug(
'OAuth2: access token expired, attempting refresh...',
Expand Down
Loading
Loading