Skip to content

Commit 405d447

Browse files
committed
feat(service-datasource): a code-defined datasource reads its credential from OS_DATASOURCE_<NAME>_PASSWORD
A datasource declared in code has no route to its password: the driver contracts refuse it inline, the Setup form cannot edit a code datasource and nothing mints a sys_secret handle for one. Per the maintainer ruling, the connection service now reads a variable derived from the datasource name at the boot's declared connect, for names in the host's code-datasource set, when the host switch OS_DATASOURCE_ENV_CREDENTIALS is on. os serve turns it on by default; every other composition leaves it off. A declared credentialsRef or connector wins, an unset variable's failure names the variable, and two names deriving one variable are refused. The credential refusals and the two password guidance strings end with one shared sentence naming the route, and the docs teach the slot, the switch and who can read the variable. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufziLJNDCTSUH9pVN32p
1 parent d70e94a commit 405d447

18 files changed

Lines changed: 989 additions & 28 deletions
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/service-datasource': patch
3+
'@objectstack/cli': patch
4+
'@objectstack/spec': patch
5+
---
6+
7+
feat(service-datasource): a datasource defined in code reads its credential at connect from `OS_DATASOURCE_<NAME>_PASSWORD`
8+
9+
Clause-②: yes (widening) — `@objectstack/service-datasource` exports `datasourceEnvCredentialVar`, `resolveDatasourceEnvCredentialsSwitch`, `DATASOURCE_ENV_CREDENTIALS_SWITCH` and the `DatasourceEnvCredentialSource` type, and `DatasourceConnectionServiceConfig` gains the optional `envCredentials`; `@objectstack/spec/data` exports `CODE_DEFINED_CREDENTIAL_ROUTE`. Nothing an author writes is added or refused.
10+
Metadata-protocol: none
11+
12+
A datasource declared in code (`defineDatasource`, or a package's `*.datasource.ts`) had no way to get its password: the driver contracts refuse `config.password` and a `user:password@` URL, the Setup → Datasources form cannot edit a code datasource, and nothing mints a `sys_secret:` handle for one. Now the credential stays out of the declaration and is read at connect from a variable derived from the datasource name: `warehouse` reads `OS_DATASOURCE_WAREHOUSE_PASSWORD` (upper-cased; every character outside `A-Z0-9` becomes `_`). The value is the connection's secret: the password for postgres, mysql and mongodb, the `authToken` for turso.
13+
14+
- **A host switch.** `OS_DATASOURCE_ENV_CREDENTIALS` takes `on` or `off`; any other value refuses the boot with a sentence. `os serve` (and so `os start` and `os dev`) turns it on unless the operator set it. Every other composition leaves it off, so a host that loads several tenants' artifacts into one process never reads the variable.
15+
- **Code datasources only, by provenance.** The variable is read on the boot's declared connect, for a name in the host's code-datasource set: the booted artifact's datasources and those of a package installed locally. A datasource created through Setup or the API under the same name never reads it, and neither does the `default` datasource, which keeps `OS_DATABASE_URL`. A record's own `origin` is never consulted.
16+
- **A declared credential wins.** With `external.credentialsRef` or `external.connector` declared the variable is not read, and a reference that fails to resolve stays fail-closed.
17+
- **Unset.** The connect goes ahead without a secret as before; when the database then refuses, the reason names the variable to set.
18+
- **Two names deriving one variable** are refused at their connect.
19+
- **Who can read it.** Any code datasource the host registers under a name reads that name's variable, including one in an installed package. Install only packages you trust with the credentials in the process environment.
20+
21+
The credential refusals (`config.password`, a URL userinfo password, a credential query parameter, the mongo `options` passthrough) and the two `password` guidance entries on `DatasourceSchema` / `ExternalDatasourceSettingsSchema` end with one shared sentence naming this route, after the Setup and `external.credentialsRef` routes they already name. `planCredentialMigration`'s remedy for a code-defined row names the row's variable.

‎content/docs/data-modeling/drivers.mdx‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -944,11 +944,13 @@ export default defineStack({
944944
```
945945

946946
Each `url` must be credential-free when the stack is published: a
947-
`user:password@` URL is refused, like an inline `config.password`. Bind the
948-
password through `external.credentialsRef` instead, keeping the user in the URL
949-
(`mongodb://svc@host/db`): the bound secret is injected beside it at connect. The
950-
[read-only example](#read-only-grant-it-at-the-database-not-in-metadata) below
951-
shows the binding.
947+
`user:password@` URL is refused, like an inline `config.password`. Keep the user
948+
in the URL (`mongodb://svc@host/db`) and supply the password at runtime: a
949+
datasource declared in code reads it at connect from `OS_DATASOURCE_<NAME>_PASSWORD`
950+
(`OS_DATASOURCE_ANALYTICS_PASSWORD` here), which `os serve` / `os start` honour by
951+
default, and the value is injected beside the user. A datasource created through
952+
Setup binds it through `external.credentialsRef` instead. See
953+
[Credentials](/docs/data-modeling/external-datasources#4-credentials).
952954

953955
Then in your object definition:
954956

@@ -990,19 +992,21 @@ export const Analytics = defineDatasource({
990992
driver: 'postgres',
991993
// The connection itself cannot write. Nothing in the app can talk past it.
992994
config: { host: 'db.internal', database: 'analytics', username: 'analytics_ro' },
993-
// The account's password, bound through the secret store (see below).
994-
external: { credentialsRef: 'sys_secret:9f2c…' },
995+
// The account's password is read at connect from OS_DATASOURCE_ANALYTICS_PASSWORD.
995996
active: true,
996997
});
997998
```
998999

9991000
The read-only account's password never goes in `config`: the driver contract
1000-
refuses `config.password`, and a `user:password@` URL, at publish. Bind it
1001-
instead. The Setup → Datasources connection form's secret field encrypts it into
1002-
`sys_secret` and stores the opaque handle at `external.credentialsRef`, or you
1003-
write a handle the secret store minted there yourself. `credentialsRef` is the
1004-
one `external` key a `managed` datasource may carry; every federation key is
1005-
still refused there. See
1001+
refuses `config.password`, and a `user:password@` URL, at publish. Because this
1002+
datasource is defined in code, the runtime reads the password at connect from
1003+
`OS_DATASOURCE_ANALYTICS_PASSWORD`, derived from its name. The CLI host
1004+
(`os serve` / `os start`) reads it by default; elsewhere the host turns it on
1005+
with `OS_DATASOURCE_ENV_CREDENTIALS=on`. The same datasource created through
1006+
Setup → Datasources binds the password instead: the connection form's secret
1007+
field encrypts it into `sys_secret` and stores the opaque handle at
1008+
`external.credentialsRef`. `credentialsRef` is the one `external` key a `managed`
1009+
datasource may carry; every federation key is still refused there. See
10061010
[Credentials](/docs/data-modeling/external-datasources#4-credentials).
10071011

10081012
Note that a read-only account also refuses **DDL**, so such a datasource cannot

‎content/docs/data-modeling/external-datasources.mdx‎

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,9 @@ const policy: DatasourceConnectPolicy = {
258258
Never inline a password. Put a reference in `external.credentialsRef` and store the
259259
secret in the secret store (the same `SecretBinder` / `ICryptoProvider` the
260260
runtime-admin "Add Datasource" wizard uses). The credential is resolved to
261-
cleartext **at connect, before the driver is built**.
261+
cleartext **at connect, before the driver is built**. A datasource defined in code
262+
reads an environment variable instead; see
263+
[A datasource defined in code](#a-datasource-defined-in-code-the-environment-variable).
262264

263265
The shipped binder encrypts the cleartext into a `sys_secret` row and mints an
264266
**opaque** handle — `sys_secret:<id>` — as the `credentialsRef`; that is the only
@@ -274,6 +276,77 @@ for the datasources listed under [When auto-connect fails](#when-auto-connect-fa
274276
and degrades with a warning otherwise. (Credential-less drivers such as SQLite
275277
simply have no `credentialsRef`.)
276278

279+
### A datasource defined in code: the environment variable
280+
281+
The handle above is minted by the Setup → Datasources form, which cannot edit a
282+
datasource defined in code (`defineDatasource`, or a `*.datasource.ts` file in a
283+
package). A code author leaves the credential out of the declaration entirely,
284+
and the runtime reads it **at connect** from an environment variable whose name
285+
the platform derives from the datasource name:
286+
287+
| Datasource name | Variable read at connect |
288+
| :--- | :--- |
289+
| `warehouse` | `OS_DATASOURCE_WAREHOUSE_PASSWORD` |
290+
| `crm_replica` | `OS_DATASOURCE_CRM_REPLICA_PASSWORD` |
291+
292+
The name is upper-cased and every character outside `A-Z0-9` becomes `_`. The
293+
value is handed to the driver as the connection's secret: the password for
294+
`postgres`, `mysql` and `mongodb`, the `authToken` for `turso`. It is never
295+
logged, stored or answered.
296+
297+
```typescript
298+
import { defineDatasource } from '@objectstack/spec/data';
299+
300+
export const Warehouse = defineDatasource({
301+
name: 'warehouse',
302+
driver: 'postgres',
303+
// No password here: it is read from OS_DATASOURCE_WAREHOUSE_PASSWORD at connect.
304+
config: { host: 'db.internal', database: 'warehouse', username: 'svc_app' },
305+
});
306+
```
307+
308+
```bash
309+
OS_DATASOURCE_WAREHOUSE_PASSWORD='…' os start
310+
```
311+
312+
What the slot does and does not do:
313+
314+
- **It is a host switch, `OS_DATASOURCE_ENV_CREDENTIALS`, which takes `on` or
315+
`off`.** `os serve`, `os start` and `os dev` turn it on unless you set it
316+
yourself. Every other composition (a host that builds its own kernel, a cloud
317+
runtime) leaves it off, so the variable is never read there. Any other value
318+
is refused at boot.
319+
- **It only serves datasources the host registers from code.** That means the
320+
ones in the booted artifact and in packages installed locally. A datasource
321+
created through Setup or the API under the same name never reads the
322+
variable. Nor does the `default` datasource, which keeps `OS_DATABASE_URL`.
323+
- **A declared credential wins.** With `external.credentialsRef` or
324+
`external.connector` declared, the variable is not consulted. If that
325+
reference fails to resolve, the datasource stays unconnected (fail-closed, as
326+
above) and does not fall back to the environment.
327+
- **An unset variable leaves the connect as it was.** The driver connects
328+
without a secret; if the database refuses, the datasource is unconnected and
329+
its reason names the variable to set.
330+
- **Two datasources that derive one variable are refused.** Valid datasource
331+
names are lower-case, so this cannot happen between two declarations that
332+
pass the schema; the guard covers a host that hands `connect()` other names.
333+
- **A plugin driver that resolves its credential per request** (the OData
334+
driver resolves `credentialsRef` that way) does not read this slot: it feeds
335+
only the secret a driver receives when its connection is built.
336+
337+
<Callout type="warn">
338+
**Who can read the variable.** The derived name is the only key, so any code
339+
datasource the host registers under that name reads it. Under `os serve` that
340+
includes every package installed into the environment: **a package can declare
341+
a datasource of any free name and so read the matching
342+
`OS_DATASOURCE_<NAME>_PASSWORD`**. Install only packages you trust with the
343+
credentials in that process's environment. On a host where several tenants'
344+
artifacts share one process, a process-wide variable would be readable by every
345+
tenant artifact that declares the name. That is why the switch is off outside the
346+
CLI host; turn it on there only when one operator owns every artifact the process
347+
loads.
348+
</Callout>
349+
277350
### Borrowing a connector instance's credential
278351

279352
An **API-backed** datasource, one served by a plugin driver such as the

‎packages/cli/src/commands/serve.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import fs from 'fs';
66
import net from 'net';
77
import chalk, { chalkStderr } from 'chalk';
88
import { bundleRequire } from 'bundle-require';
9+
import { stampDatasourceEnvCredentialsDefault } from '../utils/datasource-env-credentials-default.js';
910
import { loadConfig, BUNDLE_REQUIRE_EXTERNALS } from '../utils/config.js';
1011
import { mergeBootConfig } from '../utils/merge-boot-config.js';
1112
import { provisionTelemetryDatasource, standaloneTelemetryPrimary } from '../utils/telemetry-datasource.js';
@@ -5279,6 +5280,14 @@ export default class Serve extends Command {
52795280
registerDatasourceAdminRoutes,
52805281
} = adminMod;
52815282

5283+
// [#27687] This host boots one operator's artifact, so a code-defined
5284+
// datasource may read its credential from OS_DATASOURCE_{NAME}_PASSWORD
5285+
// at connect. Stamped before the admin plugin's `init()` reads the
5286+
// switch; an explicit operator value (`off` included) wins.
5287+
if (typeof adminMod.DATASOURCE_ENV_CREDENTIALS_SWITCH === 'string') {
5288+
stampDatasourceEnvCredentialsDefault(process.env, adminMod.DATASOURCE_ENV_CREDENTIALS_SWITCH);
5289+
}
5290+
52825291
if (
52835292
DatasourceAdminServicePlugin &&
52845293
!hasPluginMatching(['com.objectstack.service-datasource-admin', 'DatasourceAdminServicePlugin'])
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #27687 — the CLI host turns the code-datasource env-credential switch on by
5+
* default; every other composition leaves it off. Two halves: the stamp keeps
6+
* an operator's explicit value, and `os serve` (which `os start` and `os dev`
7+
* run) stamps it before the datasource admin plugin is built, whose `init()`
8+
* reads the switch.
9+
*/
10+
11+
import { readFileSync } from 'node:fs';
12+
import { dirname, join } from 'node:path';
13+
import { fileURLToPath } from 'node:url';
14+
import { describe, expect, it } from 'vitest';
15+
import { stampDatasourceEnvCredentialsDefault } from './datasource-env-credentials-default.js';
16+
17+
const SWITCH = 'OS_DATASOURCE_ENV_CREDENTIALS';
18+
19+
describe('stampDatasourceEnvCredentialsDefault', () => {
20+
it('stamps `on` when the switch is unset or empty', () => {
21+
for (const env of [{}, { [SWITCH]: '' }, { [SWITCH]: ' ' }] as Record<string, string | undefined>[]) {
22+
expect(stampDatasourceEnvCredentialsDefault(env, SWITCH)).toBe(true);
23+
expect(env[SWITCH]).toBe('on');
24+
}
25+
});
26+
27+
it("keeps an operator's explicit value — `off`, `on`, and an invalid one the boot then refuses", () => {
28+
for (const value of ['off', 'OFF', 'on', 'true']) {
29+
const env: Record<string, string | undefined> = { [SWITCH]: value };
30+
expect(stampDatasourceEnvCredentialsDefault(env, SWITCH)).toBe(false);
31+
expect(env[SWITCH]).toBe(value);
32+
}
33+
});
34+
});
35+
36+
describe('`os serve` stamps the default before the datasource admin plugin is built', () => {
37+
const source = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'commands', 'serve.ts'), 'utf8');
38+
39+
it('stamps once, into the process environment, under the name the admin module exports', () => {
40+
const calls = source.match(/stampDatasourceEnvCredentialsDefault\(/g) ?? [];
41+
expect(calls).toHaveLength(1);
42+
expect(source).toContain(
43+
'stampDatasourceEnvCredentialsDefault(process.env, adminMod.DATASOURCE_ENV_CREDENTIALS_SWITCH);',
44+
);
45+
});
46+
47+
it('the stamp precedes the plugin construction', () => {
48+
const stamp = source.indexOf('stampDatasourceEnvCredentialsDefault(process.env');
49+
const construct = source.indexOf('new DatasourceAdminServicePlugin(');
50+
expect(stamp).toBeGreaterThan(0);
51+
expect(construct).toBeGreaterThan(stamp);
52+
});
53+
});
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#27687] The CLI host's default for the code-datasource env-credential
5+
* switch (`OS_DATASOURCE_ENV_CREDENTIALS`, owned by
6+
* `@objectstack/service-datasource`).
7+
*
8+
* The switch is off in every composition that does not opt in, because on a
9+
* host where several tenants' artifacts share one process a process-wide
10+
* `OS_DATASOURCE_{NAME}_PASSWORD` would be readable by every tenant artifact
11+
* declaring that name. `os serve` (and `os start` / `os dev`, which run it)
12+
* boots ONE operator's artifact plus the packages that operator installs, so
13+
* it opts in — by stamping the default into the environment the datasource
14+
* admin plugin reads at `init()`, the same seam `os start` uses for
15+
* `OS_CRYPTO_AUTOKEY`. An operator's explicit value, `off` included, always
16+
* wins: only an unset or empty switch is stamped.
17+
*
18+
* Returns whether it stamped.
19+
*/
20+
export function stampDatasourceEnvCredentialsDefault(
21+
env: Record<string, string | undefined>,
22+
switchName: string,
23+
): boolean {
24+
const current = env[switchName];
25+
if (current !== undefined && current.trim() !== '') return false;
26+
env[switchName] = 'on';
27+
return true;
28+
}

0 commit comments

Comments
 (0)