@fjall/components-infrastructure 39.0.14 → 39.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib/app.d.ts CHANGED
@@ -17,6 +17,8 @@ import { type ServiceRegistrationProps } from "./resources/aws/networking/servic
17
17
  import { type IPrivateDnsNamespace, type IService } from "aws-cdk-lib/aws-servicediscovery";
18
18
  import { type AnyCompute } from "./patterns/aws/compute.js";
19
19
  import { type Buildkite, type BuildkiteFactoryFn, type BuildkitePropsInput } from "./patterns/aws/buildkite.js";
20
+ import { type CiIdentity, type CiIdentityProps } from "./resources/aws/iam/ciIdentity.js";
21
+ import { type CiIdentityFactoryFn } from "./resources/aws/iam/ciIdentityFactory.js";
20
22
  import { DevSubstrate, type IDevSubstrateProps } from "./patterns/aws/devSubstrate.js";
21
23
  import { type Storage, type StorageFactoryFn } from "./patterns/aws/storage.js";
22
24
  import { type AnyPattern, type PatternFactoryFn } from "./patterns/aws/pattern.js";
@@ -372,6 +374,17 @@ export declare class App extends CdkApp {
372
374
  */
373
375
  addBuildkite(props: BuildkitePropsInput): Buildkite;
374
376
  addBuildkite(fn: BuildkiteFactoryFn): Buildkite;
377
+ /**
378
+ * Place a CI identity, an IAM role a CI provider's jobs assume through
379
+ * OIDC, on the default compute stack, for the reason `addBuildkite` gives:
380
+ * deploy-core deploys only the fixed stack categories.
381
+ *
382
+ * The props overload pins construct id `"CiIdentity"`, and the factory
383
+ * overload takes `CiIdentityFactory.build(id, props)`, which is how a stack
384
+ * holds more than one identity.
385
+ */
386
+ addCiIdentity(props: CiIdentityProps): CiIdentity;
387
+ addCiIdentity(fn: CiIdentityFactoryFn): CiIdentity;
375
388
  /**
376
389
  * Add a database resource to the default database stack using the factory pattern.
377
390
  * Returns the appropriate database type based on the factory used.
package/dist/lib/app.js CHANGED
@@ -10,6 +10,7 @@ import { MessagingFactory } from "./patterns/aws/messaging.js";
10
10
  import { Schedule } from "./resources/aws/messaging/schedule.js";
11
11
  import { ServiceDiscoveryNamespace } from "./resources/aws/networking/serviceDiscovery.js";
12
12
  import { BuildkiteFactory } from "./patterns/aws/buildkite.js";
13
+ import { CiIdentityFactory } from "./resources/aws/iam/ciIdentityFactory.js";
13
14
  import { DevSubstrate } from "./patterns/aws/devSubstrate.js";
14
15
  import { StandardTagsAspect } from "./utils/standardTagsAspect.js";
15
16
  import { DeployTimeWriterMarkerAspect } from "./utils/deployTimeWriterMarkerAspect.js";
@@ -575,6 +576,15 @@ export class App extends CdkApp {
575
576
  computeStack.addConstruct(fleet);
576
577
  return fleet;
577
578
  }
579
+ addCiIdentity(input) {
580
+ const fn = typeof input === "function"
581
+ ? input
582
+ : CiIdentityFactory.build("CiIdentity", input);
583
+ const computeStack = this.getDefaultComputeStack();
584
+ const identity = fn(this, computeStack.getStack());
585
+ computeStack.addConstruct(identity);
586
+ return identity;
587
+ }
578
588
  /**
579
589
  * Add a database resource to the default database stack using the factory pattern.
580
590
  * Returns the appropriate database type based on the factory used.
@@ -4,6 +4,7 @@ import { type IBucket } from "aws-cdk-lib/aws-s3";
4
4
  import { Construct } from "constructs";
5
5
  import { Secret, type SecretImport } from "../../resources/aws/secrets/secret.js";
6
6
  import { type BackupTier } from "../../utils/backupTierMapping.js";
7
+ import { type ClickHouseOptimiseTables } from "../../resources/aws/database/clickhouseOptimiseScript.js";
7
8
  import { type ClickHouseAlarmThresholds } from "../../resources/aws/monitoring/index.js";
8
9
  import { type ClickHouseSchemaAdmin, type ProfileSpec } from "../../resources/aws/database/clickhouseSchemas.js";
9
10
  import { type ISecret } from "aws-cdk-lib/aws-secretsmanager";
@@ -152,11 +153,22 @@ export interface ClickHouseDatabaseProps {
152
153
  /** Tier 4 escape hatch (D16): bring-your-own cold-tier bucket. */
153
154
  coldTierBucket?: IBucket;
154
155
  /**
155
- * OPTIMIZE TABLE FINAL schedule (D19). Schedule string validated by CDK
156
- * `Schedule.expression(...)` at synth time. `false` disables the sidecar.
156
+ * When the optimise sidecar runs (D19), while `optimiseTables` names a
157
+ * table. CDK's `Schedule.expression(...)` reads the string at synth only
158
+ * while the sidecar exists. `false` disables the sidecar.
157
159
  * Default: `OPTIMISE_FINAL_SCHEDULE` from `clickhouseConstants.ts`.
158
160
  */
159
161
  optimiseSchedule?: string | false;
162
+ /**
163
+ * The tables the optimise sidecar merges (FJL-2911). Left out, the sidecar
164
+ * merges the Fjall web app's own tables, `REPLACING_MERGE_TREE_TABLES` and
165
+ * `OPTIMISE_MV_TABLES`, and a database without them fails, and pages, on
166
+ * every run. Set, it names the only tables merged, and a list it leaves out
167
+ * is empty. A value that names no table, such as `{}`, removes the sidecar,
168
+ * its task log group and its maintenance filters. 40.0.0 names none by
169
+ * default.
170
+ */
171
+ optimiseTables?: ClickHouseOptimiseTables;
160
172
  /**
161
173
  * BACKUP DATABASE TO S3 schedule (D19). Schedule string validated by CDK
162
174
  * `Schedule.expression(...)` at synth time. `false` disables the sidecar
@@ -309,12 +321,16 @@ export interface ClickHouseDatabaseProps {
309
321
  * `alarms:` from the patterns layer (same convention as `ServiceLogAlarm`).
310
322
  */
311
323
  export type { ClickHouseAlarmThresholds };
324
+ /** Public re-export of the optimise sidecar's table lists, so factory
325
+ * consumers can type `optimiseTables:` from the patterns layer. */
326
+ export type { ClickHouseOptimiseTables };
312
327
  /**
313
328
  * ClickHouse analytics database wrapper implementing IClickHouseDatabase.
314
329
  *
315
330
  * Composes `EcsCompute` directly per Phase 5e D7 — one EC2-pinned service
316
- * (single-instance, AWS_VPC mode, Cloud Map registered) plus two scheduled
317
- * tasks (optimise + backup). Per-role secrets, dual S3 buckets, and 10
331
+ * (single-instance, AWS_VPC mode, Cloud Map registered) plus a scheduled
332
+ * backup task, and a scheduled optimise task while `optimiseTables` names a
333
+ * table. Per-role secrets, dual S3 buckets, and 10
318
334
  * CfnOutputs are owned by `ClickHouseDatabase` itself; every taggable
319
335
  * resource routes through its Fjall wrapper (AC45d-g).
320
336
  */
@@ -18,7 +18,7 @@ import { LogGroup } from "../../resources/aws/logging/logGroup.js";
18
18
  import { StackEncryptionKey } from "../../resources/aws/secrets/stackEncryptionKey.js";
19
19
  import { createClickHouseSecurityGroup } from "../../resources/aws/database/clickhouseSecurityGroup.js";
20
20
  import { buildMaintenancePreamble } from "../../resources/aws/database/clickhouseMaintenanceScript.js";
21
- import { buildClickHouseOptimiseScript } from "../../resources/aws/database/clickhouseOptimiseScript.js";
21
+ import { buildClickHouseOptimiseScript, refuseOffShapeOptimiseTables } from "../../resources/aws/database/clickhouseOptimiseScript.js";
22
22
  import { buildClickHouseEntrypointWrapper, buildClickHouseUserData, generateUsersConfigXml } from "../../resources/aws/database/clickhouseUserData.js";
23
23
  import { toPascalCase } from "../../utils/capitaliseString.js";
24
24
  import { resolveAlertsTopic } from "../../utils/resolveAlertsTopic.js";
@@ -187,8 +187,9 @@ function createClickHouseUserSecret(scope, name) {
187
187
  * ClickHouse analytics database wrapper implementing IClickHouseDatabase.
188
188
  *
189
189
  * Composes `EcsCompute` directly per Phase 5e D7 — one EC2-pinned service
190
- * (single-instance, AWS_VPC mode, Cloud Map registered) plus two scheduled
191
- * tasks (optimise + backup). Per-role secrets, dual S3 buckets, and 10
190
+ * (single-instance, AWS_VPC mode, Cloud Map registered) plus a scheduled
191
+ * backup task, and a scheduled optimise task while `optimiseTables` names a
192
+ * table. Per-role secrets, dual S3 buckets, and 10
192
193
  * CfnOutputs are owned by `ClickHouseDatabase` itself; every taggable
193
194
  * resource routes through its Fjall wrapper (AC45d-g).
194
195
  */
@@ -289,7 +290,15 @@ export class ClickHouseDatabase extends Construct {
289
290
  ...managedPasswords
290
291
  ];
291
292
  const desiredCount = resolveClickHouseDesiredCount(this.node.tryGetContext("clickhouseDesiredCount"), props.desiredCount);
292
- const optimiseEnabled = props.optimiseSchedule !== false;
293
+ refuseOffShapeOptimiseTables(id, props.optimiseTables ?? {});
294
+ const optimiseTables = props.optimiseTables ?? {
295
+ replacingMergeTree: REPLACING_MERGE_TREE_TABLES,
296
+ compact: OPTIMISE_MV_TABLES
297
+ };
298
+ const optimiseReplacingTables = optimiseTables.replacingMergeTree ?? [];
299
+ const optimiseCompactTables = optimiseTables.compact ?? [];
300
+ const optimiseEnabled = props.optimiseSchedule !== false &&
301
+ optimiseReplacingTables.length + optimiseCompactTables.length > 0;
293
302
  const backupEnabled = props.backupSchedule !== false;
294
303
  const backupVerifyEnabled = props.backupVerify !== false;
295
304
  const optimiseSchedule = typeof props.optimiseSchedule === "string"
@@ -482,7 +491,7 @@ export class ClickHouseDatabase extends Construct {
482
491
  : {};
483
492
  // One clickhouse-client invocation per statement: a single multi-statement
484
493
  // --query aborts on the first failure, so one missing table (a migration
485
- // deploy-order window, or a dropped table lingering in the constants)
494
+ // deploy-order window, or a dropped table still named in optimiseTables)
486
495
  // would permanently skip every optimise after it. Each failure emits its
487
496
  // own status marker and the task still exits non-zero so they stay
488
497
  // visible in the task history. Both scheduled tasks authenticate as the
@@ -495,8 +504,8 @@ export class ClickHouseDatabase extends Construct {
495
504
  const backupClient = `${clickHouseClient} --receive_timeout=${clickHouseBackupVerifyTimeoutSeconds(storageGb)}`;
496
505
  const optimiseScript = buildClickHouseOptimiseScript({
497
506
  databaseName: CLICKHOUSE_DATABASE_NAME,
498
- replacingTables: REPLACING_MERGE_TREE_TABLES,
499
- mvTables: OPTIMISE_MV_TABLES
507
+ replacingTables: optimiseReplacingTables,
508
+ mvTables: optimiseCompactTables
500
509
  });
501
510
  const optimisePreamble = buildMaintenancePreamble({
502
511
  client: optimiseClient,
@@ -4,7 +4,7 @@ import type { ITopic } from "aws-cdk-lib/aws-sns";
4
4
  import type { RdsAlarmThresholds } from "../../resources/aws/monitoring/index.js";
5
5
  import type App from "../../app.js";
6
6
  import { type DynamoDBKeySchema, type DynamoDBGlobalSecondaryIndex } from "../../resources/aws/database/dynamodb.js";
7
- import { ClickHouseDatabase, type ClickHouseDatabaseProps, type ClickHouseAlarmThresholds } from "./clickhouseDatabase.js";
7
+ import { ClickHouseDatabase, type ClickHouseDatabaseProps, type ClickHouseAlarmThresholds, type ClickHouseOptimiseTables } from "./clickhouseDatabase.js";
8
8
  import { type BackupTier } from "../../utils/backupTierMapping.js";
9
9
  import { type Connections, type IConnectable, type IVpc } from "aws-cdk-lib/aws-ec2";
10
10
  import { type ITable } from "aws-cdk-lib/aws-dynamodb";
@@ -350,7 +350,7 @@ export declare class RelationalDatabase extends Construct implements IRelational
350
350
  */
351
351
  grantIamConnect(grantee: IGrantable, dbUsername: string): Grant;
352
352
  }
353
- export { ClickHouseDatabase, type ClickHouseDatabaseProps, type ClickHouseAlarmThresholds };
353
+ export { ClickHouseDatabase, type ClickHouseDatabaseProps, type ClickHouseAlarmThresholds, type ClickHouseOptimiseTables };
354
354
  export { ClickHouseDefaultProfiles, ClickHouseSchemaAdminSchema, ManagedPasswordNameSchema, ProfileSpecSchema, SettingConstraintSchema, type ClickHouseSchemaAdmin, type FrozenProfileSpec, type ManagedPasswordName, type ProfileSpec, type SettingConstraint } from "../../resources/aws/database/clickhouseSchemas.js";
355
355
  export { renderUsersXml } from "../../resources/aws/database/clickhouseXmlRenderer.js";
356
356
  export type { RenderUsersXmlOptions } from "../../resources/aws/database/clickhouseXmlRenderer.js";
@@ -282,7 +282,8 @@ export declare const CLICKHOUSE_DEFAULT_DISK_NAME = "default";
282
282
  * about five times the worst observed. */
283
283
  export declare const OPTIMISE_STATEMENT_RECEIVE_TIMEOUT_SECONDS = 1200;
284
284
  /** ReplacingMergeTree tables the optimise task settles, partition by
285
- * partition (`buildClickHouseOptimiseScript`).
285
+ * partition (`buildClickHouseOptimiseScript`), for a database that leaves
286
+ * `optimiseTables` out.
286
287
  *
287
288
  * Coupled with the webapp, whose tenant table manifest marks the same tables
288
289
  * `replacingMergeTree`; a webapp test compares the two lists, reading this
@@ -315,9 +316,10 @@ export declare const CLICKHOUSE_SERVICE_NAME = "ClickHouseService";
315
316
  * These are not ReplacingMergeTree (no dedup needed) but un-merged parts force
316
317
  * read-time aggregation which degrades query performance.
317
318
  *
318
- * Coupled with webapp/clickhouse-init: every name here must exist in the live
319
- * schema. A migration that DROPs a table must remove it here in the same
320
- * change (log_severity_hourly_mv was dropped by 012-log-events-dedup.sql). */
319
+ * They are the `compact` list for a database that leaves `optimiseTables`
320
+ * out, so every name here must exist in such a database's live schema. A
321
+ * database that names its own lists can drop a table without a fjall release
322
+ * (FJL-2911). */
321
323
  export declare const OPTIMISE_MV_TABLES: readonly ["metrics_hourly_mv", "metrics_daily_mv", "response_time_quantiles_hourly_mv", "deployment_duration_quantiles_daily_mv", "compliance_score_daily_mv", "ai_usage_daily_mv", "finding_daily_aggregate", "insight_pattern_dismissals"];
322
324
  /** Resource allocation for the lightweight optimise task. */
323
325
  export declare const OPTIMISE_TASK_MEMORY_MIB = 256;
@@ -308,7 +308,8 @@ export const CLICKHOUSE_DEFAULT_DISK_NAME = "default";
308
308
  * about five times the worst observed. */
309
309
  export const OPTIMISE_STATEMENT_RECEIVE_TIMEOUT_SECONDS = 1200;
310
310
  /** ReplacingMergeTree tables the optimise task settles, partition by
311
- * partition (`buildClickHouseOptimiseScript`).
311
+ * partition (`buildClickHouseOptimiseScript`), for a database that leaves
312
+ * `optimiseTables` out.
312
313
  *
313
314
  * Coupled with the webapp, whose tenant table manifest marks the same tables
314
315
  * `replacingMergeTree`; a webapp test compares the two lists, reading this
@@ -348,9 +349,10 @@ export const CLICKHOUSE_SERVICE_NAME = "ClickHouseService";
348
349
  * These are not ReplacingMergeTree (no dedup needed) but un-merged parts force
349
350
  * read-time aggregation which degrades query performance.
350
351
  *
351
- * Coupled with webapp/clickhouse-init: every name here must exist in the live
352
- * schema. A migration that DROPs a table must remove it here in the same
353
- * change (log_severity_hourly_mv was dropped by 012-log-events-dedup.sql). */
352
+ * They are the `compact` list for a database that leaves `optimiseTables`
353
+ * out, so every name here must exist in such a database's live schema. A
354
+ * database that names its own lists can drop a table without a fjall release
355
+ * (FJL-2911). */
354
356
  export const OPTIMISE_MV_TABLES = [
355
357
  "metrics_hourly_mv",
356
358
  "metrics_daily_mv",
@@ -41,8 +41,9 @@
41
41
  * - `skip_projections`: the parts carry different projection sets, which the
42
42
  * engine refuses to merge together (Code 388). The job says so rather than
43
43
  * issuing a statement that could only report a no-op as success.
44
- * - `skip_partition_id`: the partition id is not purely `[0-9A-Za-z_]`, so
45
- * the job will not place it inside a statement.
44
+ * - `skip_partition_id`: the partition id holds a character other than a
45
+ * digit, a letter, `_` or `-` (`PARTITION_ID_CHARACTERS`), so the job will
46
+ * not place it inside a statement.
46
47
  *
47
48
  * A partition the job skips is logged every run as a
48
49
  * `fjall:maintenance:skipped` line. It is never a status marker: it neither
@@ -51,8 +52,8 @@
51
52
  * A listed ReplacingMergeTree table that does not exist fails the job with
52
53
  * `cause=missing_table`, naming the table. The enumeration alone would read a
53
54
  * missing table as one with nothing to settle, and a dropped table left in
54
- * the constants must stay as visible as it was when the whole-table statement
55
- * raised `UNKNOWN_TABLE`. A missing materialised view still fails through its
55
+ * `optimiseTables` must stay as visible as it was when the whole-table
56
+ * statement raised `UNKNOWN_TABLE`. A missing materialised view still fails through its
56
57
  * own statement, as `reason=optimise_<view>`.
57
58
  *
58
59
  * `sh` only (the image's `/bin/sh` is dash), and nothing relies on `set -e`:
@@ -79,6 +80,44 @@ export declare const OPTIMISE_PARTITION_ACTION: {
79
80
  readonly skipProjections: "skip_projections";
80
81
  readonly skipPartitionId: "skip_partition_id";
81
82
  };
83
+ /**
84
+ * The characters a partition id may hold for the sweep to place it inside a
85
+ * statement. It is the body of a bracket expression that the enumeration's
86
+ * RE2 class (`[^…]`) and the shell's `case` pattern (`[!…]`) read the same
87
+ * way, since a trailing `-` is literal in both. On clickhouse-server
88
+ * 26.3.17.56 a date or integer key gives digits, a tuple of them joins its
89
+ * values with `-` (`202611-3`, `202611--5`), a negative integer starts with
90
+ * `-`, and a key holding a string is hashed to hex (FJL-2919).
91
+ */
92
+ export declare const PARTITION_ID_CHARACTERS = "0-9A-Za-z_-";
93
+ /**
94
+ * The tables a ClickHouse database's optimise task merges, by how it merges
95
+ * them. Each name is a table or view in the database the construct creates
96
+ * (`CLICKHOUSE_DATABASE_NAME`), and matches `^[a-z][a-z0-9_]*$`.
97
+ */
98
+ export interface ClickHouseOptimiseTables {
99
+ /**
100
+ * ReplacingMergeTree tables. The task settles each partition that holds
101
+ * more than one part, or rows a lightweight delete has masked, with
102
+ * `OPTIMIZE TABLE … PARTITION ID … FINAL`, so rows that share a sorting key
103
+ * collapse into one. It leaves to the engine, and logs, a partition whose id
104
+ * holds a character other than a digit, a letter, `_` or `-`, one whose
105
+ * parts carry different projections, and one with a part off the local disk
106
+ * unless a lightweight delete has masked rows in it.
107
+ */
108
+ readonly replacingMergeTree?: readonly string[];
109
+ /**
110
+ * Materialised views and any other table whose parts should be merged. The
111
+ * task merges each with a plain `OPTIMIZE TABLE`, without `FINAL`.
112
+ */
113
+ readonly compact?: readonly string[];
114
+ }
115
+ /**
116
+ * Refuses an `optimiseTables` name outside `^[a-z][a-z0-9_]*$`, naming the
117
+ * list and the database it came from. The name itself is withheld, because
118
+ * one that fails the shape could be anything.
119
+ */
120
+ export declare function refuseOffShapeOptimiseTables(databaseId: string, tables: ClickHouseOptimiseTables): void;
82
121
  export interface ClickHouseOptimiseScriptParams {
83
122
  /** Database the listed tables live in. */
84
123
  readonly databaseName: string;
@@ -89,8 +128,9 @@ export interface ClickHouseOptimiseScriptParams {
89
128
  }
90
129
  /**
91
130
  * The optimise job body, to follow `buildMaintenancePreamble`. Globbing is
92
- * switched off because the sweep word-splits the enumeration's output; every
93
- * word is already `[0-9A-Za-z_:]`, so this is defence in depth. Exits 0 with
94
- * `status=ok` only when every table and view settled without a failure.
131
+ * switched off because the sweep word splits the enumeration's output. Every
132
+ * word is already digits, letters, `_`, `-` and `:`, so this is defence in
133
+ * depth. Exits 0 with `status=ok` only when every table and view settled
134
+ * without a failure.
95
135
  */
96
136
  export declare function buildClickHouseOptimiseScript(params: ClickHouseOptimiseScriptParams): string;
@@ -41,8 +41,9 @@
41
41
  * - `skip_projections`: the parts carry different projection sets, which the
42
42
  * engine refuses to merge together (Code 388). The job says so rather than
43
43
  * issuing a statement that could only report a no-op as success.
44
- * - `skip_partition_id`: the partition id is not purely `[0-9A-Za-z_]`, so
45
- * the job will not place it inside a statement.
44
+ * - `skip_partition_id`: the partition id holds a character other than a
45
+ * digit, a letter, `_` or `-` (`PARTITION_ID_CHARACTERS`), so the job will
46
+ * not place it inside a statement.
46
47
  *
47
48
  * A partition the job skips is logged every run as a
48
49
  * `fjall:maintenance:skipped` line. It is never a status marker: it neither
@@ -51,8 +52,8 @@
51
52
  * A listed ReplacingMergeTree table that does not exist fails the job with
52
53
  * `cause=missing_table`, naming the table. The enumeration alone would read a
53
54
  * missing table as one with nothing to settle, and a dropped table left in
54
- * the constants must stay as visible as it was when the whole-table statement
55
- * raised `UNKNOWN_TABLE`. A missing materialised view still fails through its
55
+ * `optimiseTables` must stay as visible as it was when the whole-table
56
+ * statement raised `UNKNOWN_TABLE`. A missing materialised view still fails through its
56
57
  * own statement, as `reason=optimise_<view>`.
57
58
  *
58
59
  * `sh` only (the image's `/bin/sh` is dash), and nothing relies on `set -e`:
@@ -82,7 +83,32 @@ export const OPTIMISE_PARTITION_ACTION = {
82
83
  skipProjections: "skip_projections",
83
84
  skipPartitionId: "skip_partition_id"
84
85
  };
86
+ /**
87
+ * The characters a partition id may hold for the sweep to place it inside a
88
+ * statement. It is the body of a bracket expression that the enumeration's
89
+ * RE2 class (`[^…]`) and the shell's `case` pattern (`[!…]`) read the same
90
+ * way, since a trailing `-` is literal in both. On clickhouse-server
91
+ * 26.3.17.56 a date or integer key gives digits, a tuple of them joins its
92
+ * values with `-` (`202611-3`, `202611--5`), a negative integer starts with
93
+ * `-`, and a key holding a string is hashed to hex (FJL-2919).
94
+ */
95
+ export const PARTITION_ID_CHARACTERS = "0-9A-Za-z_-";
85
96
  const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
97
+ const OPTIMISE_TABLE_LIST_PRESENCE = { replacingMergeTree: true, compact: true };
98
+ const OPTIMISE_TABLE_LISTS = Object.keys(OPTIMISE_TABLE_LIST_PRESENCE);
99
+ /**
100
+ * Refuses an `optimiseTables` name outside `^[a-z][a-z0-9_]*$`, naming the
101
+ * list and the database it came from. The name itself is withheld, because
102
+ * one that fails the shape could be anything.
103
+ */
104
+ export function refuseOffShapeOptimiseTables(databaseId, tables) {
105
+ for (const list of OPTIMISE_TABLE_LISTS) {
106
+ const names = tables[list] ?? [];
107
+ if (names.some((name) => !IDENTIFIER_PATTERN.test(name))) {
108
+ throw new Error(`ClickHouse database ${databaseId}: every name in optimiseTables.${list} must match ${IDENTIFIER_PATTERN}. The name that does not is withheld.`);
109
+ }
110
+ }
111
+ }
86
112
  function assertIdentifier(kind, value) {
87
113
  if (!IDENTIFIER_PATTERN.test(value)) {
88
114
  throw new Error(`ClickHouse optimise ${kind} must match ${IDENTIFIER_PATTERN}.`);
@@ -91,14 +117,14 @@ function assertIdentifier(kind, value) {
91
117
  /**
92
118
  * One row per partition that needs attention, as `<id>:<verdict>`.
93
119
  *
94
- * A partition id that is not purely `[0-9A-Za-z_]` is never returned as
95
- * itself: it comes back hex-encoded with the `skip_partition_id` verdict, so
96
- * nothing but an id the statement can quote safely ever reaches the shell.
97
- * Every partition key in the webapp schema yields a digits-only id, so this
98
- * arm exists for a future key rather than a present one.
120
+ * A partition id holding a character outside `PARTITION_ID_CHARACTERS` is
121
+ * never returned as itself. It comes back hex encoded with the
122
+ * `skip_partition_id` verdict, so nothing but an id the statement can quote
123
+ * safely ever reaches the shell. None of the key shapes measured on
124
+ * clickhouse-server 26.3.17.56 gives such an id.
99
125
  */
100
126
  function enumerationQuery(databaseName, table) {
101
- const safeId = "length(partition_id) > 0 AND NOT match(partition_id, '[^0-9A-Za-z_]')";
127
+ const safeId = `length(partition_id) > 0 AND NOT match(partition_id, '[^${PARTITION_ID_CHARACTERS}]')`;
102
128
  const verdict = `multiIf(NOT (${safeId}), '${OPTIMISE_PARTITION_ACTION.skipPartitionId}',` +
103
129
  ` uniqExact(arrayStringConcat(arraySort(projections), ',')) > 1, '${OPTIMISE_PARTITION_ACTION.skipProjections}',` +
104
130
  ` max(has_lightweight_delete) = 1, '${OPTIMISE_PARTITION_ACTION.purge}',` +
@@ -123,7 +149,7 @@ function sweepFunction(databaseName) {
123
149
  ` FJALL_SWEEP_PARTS=$(${MAINTENANCE_RUN_FN} "enumerate_$FJALL_SWEEP_TABLE" "${enumeration}") || return 1`,
124
150
  ` for FJALL_SWEEP_ENTRY in $FJALL_SWEEP_PARTS; do`,
125
151
  ` FJALL_SWEEP_ID=\${FJALL_SWEEP_ENTRY%%:*}; FJALL_SWEEP_ACTION=\${FJALL_SWEEP_ENTRY#*:}`,
126
- ` case "$FJALL_SWEEP_ID" in ''|*[!0-9A-Za-z_]*) FJALL_SWEEP_ID=unreadable; FJALL_SWEEP_ACTION=${skipPartitionId} ;; esac`,
152
+ ` case "$FJALL_SWEEP_ID" in ''|*[!${PARTITION_ID_CHARACTERS}]*) FJALL_SWEEP_ID=unreadable; FJALL_SWEEP_ACTION=${skipPartitionId} ;; esac`,
127
153
  ` case "$FJALL_SWEEP_ACTION" in`,
128
154
  ` ${merge}|${purge})`,
129
155
  ` echo "${OPTIMISE_PARTITION_LOG_TOKEN} table=$FJALL_SWEEP_TABLE partition=$FJALL_SWEEP_ID action=$FJALL_SWEEP_ACTION job=$FJALL_JOB" >&2`,
@@ -138,9 +164,10 @@ function sweepFunction(databaseName) {
138
164
  }
139
165
  /**
140
166
  * The optimise job body, to follow `buildMaintenancePreamble`. Globbing is
141
- * switched off because the sweep word-splits the enumeration's output; every
142
- * word is already `[0-9A-Za-z_:]`, so this is defence in depth. Exits 0 with
143
- * `status=ok` only when every table and view settled without a failure.
167
+ * switched off because the sweep word splits the enumeration's output. Every
168
+ * word is already digits, letters, `_`, `-` and `:`, so this is defence in
169
+ * depth. Exits 0 with `status=ok` only when every table and view settled
170
+ * without a failure.
144
171
  */
145
172
  export function buildClickHouseOptimiseScript(params) {
146
173
  const { databaseName, replacingTables, mvTables } = params;
@@ -0,0 +1,48 @@
1
+ import { Construct } from "constructs";
2
+ import { z } from "zod";
3
+ /**
4
+ * Each refusal names the prop and its rule, and never the value, so a
5
+ * secret pasted into a prop is not printed back.
6
+ */
7
+ export declare const CI_IDENTITY_REFUSALS: {
8
+ readonly provider: `provider must be one of ${string}`;
9
+ readonly unknownProp: "a buildkite ciIdentity takes only provider, roleName, organisation, pipelines, branches and grants";
10
+ readonly roleName: "roleName must be an IAM role name of 1 to 64 letters, digits or + = , . @ _ -";
11
+ readonly organisation: "organisation must start with a letter or digit and hold at most 255 letters, digits, underscores or dashes";
12
+ readonly pipelines: "pipelines must name at least one Buildkite pipeline";
13
+ readonly pipeline: "each of pipelines must start with a letter or digit and hold at most 255 letters, digits, underscores or dashes";
14
+ readonly branches: "branches, when set, must name at least one branch";
15
+ readonly branch: "each of branches must be a branch name of at most 200 letters, digits or . _ / -, starting with a letter or digit";
16
+ readonly grants: "grants must name at least one grant";
17
+ readonly grant: `each of grants must be one of ${string}`;
18
+ readonly trustSize: "the trust must fit IAM's default trust policy quota of 2048 characters, so name fewer pipelines or branches, or split them across identities";
19
+ };
20
+ declare const CiIdentityPropsSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
21
+ provider: z.ZodLiteral<"buildkite">;
22
+ roleName: z.ZodString;
23
+ organisation: z.ZodString;
24
+ pipelines: z.ZodReadonly<z.ZodArray<z.ZodString>>;
25
+ branches: z.ZodOptional<z.ZodReadonly<z.ZodArray<z.ZodString>>>;
26
+ grants: z.ZodReadonly<z.ZodArray<z.ZodEnum<{
27
+ ecrPublicPull: "ecrPublicPull";
28
+ }>>>;
29
+ }, z.core.$strict>], "provider">;
30
+ export type CiIdentityProps = z.input<typeof CiIdentityPropsSchema>;
31
+ /**
32
+ * Refuses props the identity can't render, naming every broken rule at once.
33
+ * The trust's size is measured only once every prop is valid.
34
+ */
35
+ export declare function validateCiIdentityProps(props: CiIdentityProps, id: string): void;
36
+ /**
37
+ * An IAM role a CI provider's jobs assume through OIDC, holding only the
38
+ * grants it names and the fence. The construct offers no handle on its role,
39
+ * so it adds nothing past those grants itself, though code that looks the
40
+ * role up by name can still attach a policy to it. Its account's OIDC
41
+ * provider is adopted or created once a stack, and outlives the stack.
42
+ */
43
+ export declare class CiIdentity extends Construct {
44
+ readonly roleArn: string;
45
+ readonly roleName: string;
46
+ constructor(scope: Construct, id: string, props: CiIdentityProps);
47
+ }
48
+ export {};
@@ -0,0 +1,178 @@
1
+ import { BUILDKITE_SLUG_PATTERN, BUILDKITE_SLUG_RULE, CI_IDENTITY_GRANTS, CI_IDENTITY_PROVIDERS, CI_OIDC_ISSUERS } from "@fjall/util";
2
+ import * as iam from "aws-cdk-lib/aws-iam";
3
+ import { Construct } from "constructs";
4
+ import { z } from "zod";
5
+ import { buildCiIdentityTrust, ciIdentityTrustCharacters, IAM_TRUST_POLICY_DEFAULT_MAX_CHARACTERS } from "./ciIdentityTrust.js";
6
+ import { OidcProviderAdoption } from "./oidcProviderAdoption.js";
7
+ import { Role } from "./role.js";
8
+ /** IAM's role name grammar. */
9
+ const ROLE_NAME_PATTERN = /^[\w+=,.@-]{1,64}$/;
10
+ const BRANCH_MAX_LENGTH = 200;
11
+ const BRANCH_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._/-]{0,${BRANCH_MAX_LENGTH - 1}}$`);
12
+ /**
13
+ * Each refusal names the prop and its rule, and never the value, so a
14
+ * secret pasted into a prop is not printed back.
15
+ */
16
+ export const CI_IDENTITY_REFUSALS = {
17
+ provider: `provider must be one of ${CI_IDENTITY_PROVIDERS.join(", ")}`,
18
+ unknownProp: "a buildkite ciIdentity takes only provider, roleName, organisation, pipelines, branches and grants",
19
+ roleName: "roleName must be an IAM role name of 1 to 64 letters, digits or + = , . @ _ -",
20
+ organisation: `organisation ${BUILDKITE_SLUG_RULE}`,
21
+ pipelines: "pipelines must name at least one Buildkite pipeline",
22
+ pipeline: `each of pipelines ${BUILDKITE_SLUG_RULE}`,
23
+ branches: "branches, when set, must name at least one branch",
24
+ branch: `each of branches must be a branch name of at most ${BRANCH_MAX_LENGTH} letters, digits or . _ / -, starting with a letter or digit`,
25
+ grants: "grants must name at least one grant",
26
+ grant: `each of grants must be one of ${CI_IDENTITY_GRANTS.join(", ")}`,
27
+ trustSize: `the trust must fit IAM's default trust policy quota of ${IAM_TRUST_POLICY_DEFAULT_MAX_CHARACTERS} characters, so name fewer pipelines or branches, or split them across identities`
28
+ };
29
+ function counted(count, singular, plural) {
30
+ return `${count} ${count === 1 ? singular : plural}`;
31
+ }
32
+ /** The size refusal names the counts it rendered, and never a pipeline or branch. */
33
+ function trustSizeRefusal(pipelines, branches, characters) {
34
+ const branchText = branches === undefined
35
+ ? "every branch"
36
+ : counted(branches, "branch", "branches");
37
+ return `${CI_IDENTITY_REFUSALS.trustSize} (${counted(pipelines, "pipeline", "pipelines")} on ${branchText} render ${characters})`;
38
+ }
39
+ const buildkiteSlug = (refusal) => z.string({ error: refusal }).regex(BUILDKITE_SLUG_PATTERN, refusal);
40
+ const BuildkiteCiIdentityPropsSchema = z
41
+ .object({
42
+ provider: z.literal("buildkite"),
43
+ /** Used verbatim, so a pipeline can hold the role's ARN as a literal. */
44
+ roleName: z
45
+ .string({ error: CI_IDENTITY_REFUSALS.roleName })
46
+ .regex(ROLE_NAME_PATTERN, CI_IDENTITY_REFUSALS.roleName),
47
+ /** The Buildkite organisation whose pipelines the role trusts. */
48
+ organisation: buildkiteSlug(CI_IDENTITY_REFUSALS.organisation),
49
+ pipelines: z
50
+ .array(buildkiteSlug(CI_IDENTITY_REFUSALS.pipeline), {
51
+ error: CI_IDENTITY_REFUSALS.pipelines
52
+ })
53
+ .min(1, CI_IDENTITY_REFUSALS.pipelines)
54
+ .readonly(),
55
+ /** Absent, the role trusts every ref of each pipeline. */
56
+ branches: z
57
+ .array(z
58
+ .string({ error: CI_IDENTITY_REFUSALS.branch })
59
+ .regex(BRANCH_PATTERN, CI_IDENTITY_REFUSALS.branch), { error: CI_IDENTITY_REFUSALS.branches })
60
+ .min(1, CI_IDENTITY_REFUSALS.branches)
61
+ .readonly()
62
+ .optional(),
63
+ grants: z
64
+ .array(z.enum(CI_IDENTITY_GRANTS, { error: CI_IDENTITY_REFUSALS.grant }), {
65
+ error: CI_IDENTITY_REFUSALS.grants
66
+ })
67
+ .min(1, CI_IDENTITY_REFUSALS.grants)
68
+ .readonly()
69
+ }, {
70
+ error: (issue) => issue.code === "unrecognized_keys"
71
+ ? CI_IDENTITY_REFUSALS.unknownProp
72
+ : undefined
73
+ })
74
+ .strict();
75
+ const CiIdentityPropsSchema = z.discriminatedUnion("provider", [BuildkiteCiIdentityPropsSchema], { error: CI_IDENTITY_REFUSALS.provider });
76
+ function refusalsOf(props) {
77
+ const result = CiIdentityPropsSchema.safeParse(props);
78
+ if (!result.success) {
79
+ return [...new Set(result.error.issues.map((issue) => issue.message))];
80
+ }
81
+ const characters = ciIdentityTrustCharacters(result.data);
82
+ if (characters <= IAM_TRUST_POLICY_DEFAULT_MAX_CHARACTERS)
83
+ return [];
84
+ return [
85
+ trustSizeRefusal(result.data.pipelines.length, result.data.branches?.length, characters)
86
+ ];
87
+ }
88
+ /**
89
+ * Refuses props the identity can't render, naming every broken rule at once.
90
+ * The trust's size is measured only once every prop is valid.
91
+ */
92
+ export function validateCiIdentityProps(props, id) {
93
+ const refusals = refusalsOf(props);
94
+ if (refusals.length === 0)
95
+ return;
96
+ throw new Error(`CiIdentity ${id} refused its props\n${refusals.map((refusal) => ` - ${refusal}`).join("\n")}`);
97
+ }
98
+ const CI_IDENTITY_GRANT_POLICIES = {
99
+ ecrPublicPull: {
100
+ narrowedTrust: false,
101
+ statements: [
102
+ {
103
+ Sid: "EcrPublicAuthorizationToken",
104
+ Effect: "Allow",
105
+ Action: "ecr-public:GetAuthorizationToken",
106
+ Resource: "*"
107
+ },
108
+ // `IfExists`, because ECR Public's own call sends no `sts:AWSServiceName`,
109
+ // so `StringEquals` denied every sign in (FJL-1812 S4,
110
+ // aws/containers-roadmap#2896). A service that names itself other than
111
+ // ECR Public is still refused.
112
+ {
113
+ Sid: "EcrPublicServiceBearerToken",
114
+ Effect: "Allow",
115
+ Action: "sts:GetServiceBearerToken",
116
+ Resource: "*",
117
+ Condition: {
118
+ StringEqualsIfExists: {
119
+ "sts:AWSServiceName": "ecr-public.amazonaws.com"
120
+ }
121
+ }
122
+ }
123
+ ]
124
+ }
125
+ };
126
+ /**
127
+ * Every identity carries this deny whatever its grants. A role in the same
128
+ * account whose trust names this one could be assumed from it with no allow
129
+ * here, so the deny is explicit.
130
+ */
131
+ const CI_IDENTITY_FENCE = {
132
+ Sid: "CiIdentityFence",
133
+ Effect: "Deny",
134
+ Action: [
135
+ "ssm:GetParameter*",
136
+ "sts:AssumeRole",
137
+ "sts:TagSession",
138
+ "iam:PassRole"
139
+ ],
140
+ Resource: "*"
141
+ };
142
+ const CI_IDENTITY_POLICY_NAME = "FjallCiIdentity";
143
+ /**
144
+ * An IAM role a CI provider's jobs assume through OIDC, holding only the
145
+ * grants it names and the fence. The construct offers no handle on its role,
146
+ * so it adds nothing past those grants itself, though code that looks the
147
+ * role up by name can still attach a policy to it. Its account's OIDC
148
+ * provider is adopted or created once a stack, and outlives the stack.
149
+ */
150
+ export class CiIdentity extends Construct {
151
+ roleArn;
152
+ roleName;
153
+ constructor(scope, id, props) {
154
+ super(scope, id);
155
+ validateCiIdentityProps(props, id);
156
+ const grants = [...new Set(props.grants)];
157
+ const providerArn = OidcProviderAdoption.of(this).providerArnFor(CI_OIDC_ISSUERS[props.provider]);
158
+ const role = new Role(this, "Role", {
159
+ roleName: props.roleName,
160
+ description: `Fjall CI identity for Buildkite organisation ${props.organisation}, granted ${grants.join(", ")}`,
161
+ // Replaced below by the whole trust document.
162
+ assumedBy: new iam.FederatedPrincipal(providerArn, {}, "sts:AssumeRoleWithWebIdentity"),
163
+ inlinePolicies: {
164
+ [CI_IDENTITY_POLICY_NAME]: iam.PolicyDocument.fromJson({
165
+ Version: "2012-10-17",
166
+ Statement: [
167
+ ...grants.flatMap((grant) => CI_IDENTITY_GRANT_POLICIES[grant].statements),
168
+ CI_IDENTITY_FENCE
169
+ ]
170
+ })
171
+ }
172
+ });
173
+ role.node.defaultChild.assumeRolePolicyDocument =
174
+ buildCiIdentityTrust(providerArn, props);
175
+ this.roleArn = role.roleArn;
176
+ this.roleName = role.roleName;
177
+ }
178
+ }
@@ -0,0 +1,17 @@
1
+ import { type Construct } from "constructs";
2
+ import type App from "../../../app.js";
3
+ import { CiIdentity, type CiIdentityProps } from "./ciIdentity.js";
4
+ /**
5
+ * Thunk returned by `CiIdentityFactory.build`, materialised only by
6
+ * `App.addCiIdentity`, which places the identity on the default compute
7
+ * stack.
8
+ */
9
+ export type CiIdentityFactoryFn = (app: App, scope: Construct) => CiIdentity;
10
+ /**
11
+ * Factory for a CI identity, for
12
+ * `app.addCiIdentity(CiIdentityFactory.build("Id", { … }))`. Validation lives
13
+ * in the `CiIdentity` constructor, so it fires on every path.
14
+ */
15
+ export declare class CiIdentityFactory {
16
+ static build(id: string, props: CiIdentityProps): CiIdentityFactoryFn;
17
+ }
@@ -0,0 +1,11 @@
1
+ import { CiIdentity } from "./ciIdentity.js";
2
+ /**
3
+ * Factory for a CI identity, for
4
+ * `app.addCiIdentity(CiIdentityFactory.build("Id", { … }))`. Validation lives
5
+ * in the `CiIdentity` constructor, so it fires on every path.
6
+ */
7
+ export class CiIdentityFactory {
8
+ static build(id, props) {
9
+ return (_app, scope) => new CiIdentity(scope, id, props);
10
+ }
11
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The trust document of a CI identity, and its size as IAM counts it.
3
+ *
4
+ * Limits, dated 3 November 2026. A branch narrowed identity refuses a build
5
+ * whose commit is not yet a full SHA, such as one created with the commit
6
+ * HEAD, because its subjects take exactly 40 characters where the commit
7
+ * goes. That fails closed. Narrowing by branch also guards only against
8
+ * builds GitHub triggers. Anyone who can create a build through the Buildkite
9
+ * API or dashboard chooses its branch, so it is no fence against them.
10
+ */
11
+ import { type CiIdentityProvider } from "@fjall/util";
12
+ /** IAM's default quota on a role's trust policy, in characters. */
13
+ export declare const IAM_TRUST_POLICY_DEFAULT_MAX_CHARACTERS = 2048;
14
+ /** What a CI identity's trust is rendered from. */
15
+ export interface CiIdentityTrustInput {
16
+ readonly provider: CiIdentityProvider;
17
+ readonly organisation: string;
18
+ readonly pipelines: readonly string[];
19
+ readonly branches?: readonly string[] | undefined;
20
+ }
21
+ export interface CiIdentityTrustStatement {
22
+ readonly Effect: "Allow";
23
+ readonly Principal: {
24
+ readonly Federated: string;
25
+ };
26
+ readonly Action: "sts:AssumeRoleWithWebIdentity";
27
+ readonly Condition: {
28
+ readonly StringEquals: Readonly<Record<string, string>>;
29
+ readonly StringLike: Readonly<Record<string, readonly string[]>>;
30
+ };
31
+ }
32
+ export interface CiIdentityTrustDocument {
33
+ readonly Version: "2012-10-17";
34
+ readonly Statement: readonly [CiIdentityTrustStatement];
35
+ }
36
+ /**
37
+ * The whole trust document of a CI identity, naming the provider's OIDC
38
+ * principal, the CI audience and the subjects of the jobs it trusts. Pure, so
39
+ * a test can compare it with a document, and the construct renders it
40
+ * verbatim.
41
+ */
42
+ export declare function buildCiIdentityTrust(providerArn: string, identity: CiIdentityTrustInput): CiIdentityTrustDocument;
43
+ /**
44
+ * The characters IAM counts in the trust this identity renders, with the
45
+ * provider ARN at its longest. The document is the one the construct writes
46
+ * into the role, and its JSON carries no white space IAM would skip.
47
+ */
48
+ export declare function ciIdentityTrustCharacters(identity: CiIdentityTrustInput): number;
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The trust document of a CI identity, and its size as IAM counts it.
3
+ *
4
+ * Limits, dated 3 November 2026. A branch narrowed identity refuses a build
5
+ * whose commit is not yet a full SHA, such as one created with the commit
6
+ * HEAD, because its subjects take exactly 40 characters where the commit
7
+ * goes. That fails closed. Narrowing by branch also guards only against
8
+ * builds GitHub triggers. Anyone who can create a build through the Buildkite
9
+ * API or dashboard chooses its branch, so it is no fence against them.
10
+ */
11
+ import { CI_OIDC_AUDIENCE, CI_OIDC_ISSUERS } from "@fjall/util";
12
+ import { ciOidcProviderPath } from "../../../utils/ciOidcProviderHandler.js";
13
+ /** IAM's default quota on a role's trust policy, in characters. */
14
+ export const IAM_TRUST_POLICY_DEFAULT_MAX_CHARACTERS = 2048;
15
+ /**
16
+ * IAM's StringLike reads * as any run of characters, colons included, so a
17
+ * commit slot of * would let a fork's branch, which Buildkite renders as
18
+ * login:branch, pass for a named branch. No login or branch name holds a
19
+ * colon, so a slot of exactly one full SHA can't absorb one.
20
+ */
21
+ const FULL_COMMIT_SHA = "?".repeat(40);
22
+ /**
23
+ * The longest ARN a provider can resolve to, with the longest partition name
24
+ * (aws-us-gov, as of 3 November 2026) and a 12 digit account, so a trust
25
+ * measured with it is never shorter than the one IAM receives.
26
+ */
27
+ function longestProviderArn(provider) {
28
+ return `arn:aws-us-gov:iam::000000000000:oidc-provider/${ciOidcProviderPath(CI_OIDC_ISSUERS[provider])}`;
29
+ }
30
+ /**
31
+ * The subjects a Buildkite job's token carries for each pipeline the
32
+ * identity trusts. With no branches named that is every ref and commit of
33
+ * the pipeline, and otherwise each named branch at one full commit.
34
+ */
35
+ function buildkiteSubjects(identity) {
36
+ const { branches, organisation, pipelines } = identity;
37
+ return pipelines.flatMap((pipeline) => {
38
+ const prefix = `organization:${organisation}:pipeline:${pipeline}`;
39
+ if (branches === undefined)
40
+ return [`${prefix}:ref:*:commit:*:step:*`];
41
+ return branches.map((branch) => `${prefix}:ref:refs/heads/${branch}:commit:${FULL_COMMIT_SHA}:step:*`);
42
+ });
43
+ }
44
+ function subjectsFor(identity) {
45
+ switch (identity.provider) {
46
+ case "buildkite":
47
+ return buildkiteSubjects(identity);
48
+ default:
49
+ return unknownProvider(identity.provider);
50
+ }
51
+ }
52
+ function unknownProvider(provider) {
53
+ throw new Error(`A CI identity's trust has no subject rule for the provider ${String(provider)}`);
54
+ }
55
+ /**
56
+ * The whole trust document of a CI identity, naming the provider's OIDC
57
+ * principal, the CI audience and the subjects of the jobs it trusts. Pure, so
58
+ * a test can compare it with a document, and the construct renders it
59
+ * verbatim.
60
+ */
61
+ export function buildCiIdentityTrust(providerArn, identity) {
62
+ const conditionKeyPrefix = ciOidcProviderPath(CI_OIDC_ISSUERS[identity.provider]);
63
+ return {
64
+ Version: "2012-10-17",
65
+ Statement: [
66
+ {
67
+ Effect: "Allow",
68
+ Principal: { Federated: providerArn },
69
+ Action: "sts:AssumeRoleWithWebIdentity",
70
+ Condition: {
71
+ StringEquals: { [`${conditionKeyPrefix}:aud`]: CI_OIDC_AUDIENCE },
72
+ StringLike: {
73
+ [`${conditionKeyPrefix}:sub`]: subjectsFor(identity)
74
+ }
75
+ }
76
+ }
77
+ ]
78
+ };
79
+ }
80
+ /**
81
+ * The characters IAM counts in the trust this identity renders, with the
82
+ * provider ARN at its longest. The document is the one the construct writes
83
+ * into the role, and its JSON carries no white space IAM would skip.
84
+ */
85
+ export function ciIdentityTrustCharacters(identity) {
86
+ return JSON.stringify(buildCiIdentityTrust(longestProviderArn(identity.provider), identity)).length;
87
+ }
@@ -1,5 +1,9 @@
1
+ export * from "./ciIdentity.js";
2
+ export * from "./ciIdentityFactory.js";
3
+ export * from "./ciIdentityTrust.js";
1
4
  export * from "./delegationRole.js";
2
5
  export * from "./instanceProfile.js";
3
6
  export * from "./managedPolicy.js";
7
+ export * from "./oidcProviderAdoption.js";
4
8
  export * from "./policy.js";
5
9
  export * from "./role.js";
@@ -1,5 +1,9 @@
1
+ export * from "./ciIdentity.js";
2
+ export * from "./ciIdentityFactory.js";
3
+ export * from "./ciIdentityTrust.js";
1
4
  export * from "./delegationRole.js";
2
5
  export * from "./instanceProfile.js";
3
6
  export * from "./managedPolicy.js";
7
+ export * from "./oidcProviderAdoption.js";
4
8
  export * from "./policy.js";
5
9
  export * from "./role.js";
@@ -0,0 +1,22 @@
1
+ import { Construct } from "constructs";
2
+ /**
3
+ * The stack's one CI OIDC provider handler, and one custom resource for each
4
+ * issuer an identity in the stack trusts. Each custom resource adopts or
5
+ * creates the account's provider for its issuer and answers its ARN
6
+ * (`CI_OIDC_PROVIDER_HANDLER`). The handler may write only the providers of
7
+ * the issuers the stack names.
8
+ */
9
+ export declare class OidcProviderAdoption extends Construct {
10
+ /** The stack's adoption, made on first use. */
11
+ static of(scope: Construct): OidcProviderAdoption;
12
+ private readonly handler;
13
+ private readonly serviceToken;
14
+ private readonly providerArns;
15
+ private constructor();
16
+ /**
17
+ * The ARN of the account's OIDC provider for `issuerUrl`, with the CI
18
+ * audience among its client ids. A reference to it orders a role after the
19
+ * adoption.
20
+ */
21
+ providerArnFor(issuerUrl: string): string;
22
+ }
@@ -0,0 +1,93 @@
1
+ import { CI_OIDC_AUDIENCE } from "@fjall/util";
2
+ import { Aws, CustomResource, Duration, Stack } from "aws-cdk-lib";
3
+ import { PolicyStatement } from "aws-cdk-lib/aws-iam";
4
+ import { Code, Runtime } from "aws-cdk-lib/aws-lambda";
5
+ import { Construct } from "constructs";
6
+ import { CI_OIDC_PROVIDER_HANDLER, ciOidcProviderPath } from "../../../utils/ciOidcProviderHandler.js";
7
+ import { markDeployTimeWriter } from "../../../utils/resourceTypeTags.js";
8
+ import { LambdaFunction } from "../compute/lambda.js";
9
+ import { DEFAULT_FRAMEWORK_LOG_RETENTION, LogGroup } from "../logging/logGroup.js";
10
+ import { CustomResourceProvider } from "../utilities/customResourceProvider.js";
11
+ const ADOPTION_ID = "FjallCiOidcProviderAdoption";
12
+ const CI_OIDC_PROVIDER_RESOURCE_TYPE = "Custom::FjallCiOidcProvider";
13
+ /** The OIDC connector's own handler budget. */
14
+ const HANDLER_TIMEOUT = Duration.minutes(5);
15
+ /**
16
+ * The stack's one CI OIDC provider handler, and one custom resource for each
17
+ * issuer an identity in the stack trusts. Each custom resource adopts or
18
+ * creates the account's provider for its issuer and answers its ARN
19
+ * (`CI_OIDC_PROVIDER_HANDLER`). The handler may write only the providers of
20
+ * the issuers the stack names.
21
+ */
22
+ export class OidcProviderAdoption extends Construct {
23
+ /** The stack's adoption, made on first use. */
24
+ static of(scope) {
25
+ const stack = Stack.of(scope);
26
+ const existing = stack.node.tryFindChild(ADOPTION_ID);
27
+ if (existing instanceof OidcProviderAdoption)
28
+ return existing;
29
+ if (existing !== undefined) {
30
+ throw new Error(`${stack.node.path}/${ADOPTION_ID} is taken by a construct that is not the CI OIDC provider adoption`);
31
+ }
32
+ return new OidcProviderAdoption(stack, ADOPTION_ID);
33
+ }
34
+ handler;
35
+ serviceToken;
36
+ providerArns = new Map();
37
+ constructor(scope, id) {
38
+ super(scope, id);
39
+ this.handler = new LambdaFunction(this, "Handler", {
40
+ runtime: Runtime.NODEJS_24_X,
41
+ handler: "index.handler",
42
+ code: Code.fromInline(CI_OIDC_PROVIDER_HANDLER),
43
+ stackOutputs: "none",
44
+ timeout: HANDLER_TIMEOUT.toSeconds(),
45
+ lambdaDescription: "Fjall CI identity: adopts or creates the IAM OIDC provider of a CI issuer",
46
+ roleDescription: "Execution role for the Fjall CI OIDC provider adoption handler",
47
+ inlinePolicy: [
48
+ // ListOpenIDConnectProviders supports no resource level permission.
49
+ new PolicyStatement({
50
+ actions: ["iam:ListOpenIDConnectProviders"],
51
+ resources: ["*"]
52
+ })
53
+ ]
54
+ });
55
+ const provider = new CustomResourceProvider(this, "Provider", {
56
+ onEventHandler: this.handler,
57
+ logGroup: new LogGroup(this, "ProviderLogGroup", {
58
+ retention: DEFAULT_FRAMEWORK_LOG_RETENTION
59
+ })
60
+ });
61
+ this.serviceToken = provider.serviceToken;
62
+ markDeployTimeWriter(this);
63
+ }
64
+ /**
65
+ * The ARN of the account's OIDC provider for `issuerUrl`, with the CI
66
+ * audience among its client ids. A reference to it orders a role after the
67
+ * adoption.
68
+ */
69
+ providerArnFor(issuerUrl) {
70
+ const known = this.providerArns.get(issuerUrl);
71
+ if (known !== undefined)
72
+ return known;
73
+ const providerPath = ciOidcProviderPath(issuerUrl);
74
+ this.handler.addToRolePolicy(new PolicyStatement({
75
+ actions: [
76
+ "iam:GetOpenIDConnectProvider",
77
+ "iam:CreateOpenIDConnectProvider",
78
+ "iam:AddClientIDToOpenIDConnectProvider"
79
+ ],
80
+ resources: [
81
+ `arn:${Aws.PARTITION}:iam::${Aws.ACCOUNT_ID}:oidc-provider/${providerPath}`
82
+ ]
83
+ }));
84
+ const resource = new CustomResource(this, providerPath.replace(/\//g, "-"), {
85
+ serviceToken: this.serviceToken,
86
+ resourceType: CI_OIDC_PROVIDER_RESOURCE_TYPE,
87
+ properties: { IssuerUrl: issuerUrl, ClientId: CI_OIDC_AUDIENCE }
88
+ });
89
+ const arn = resource.getAttString("ProviderArn");
90
+ this.providerArns.set(issuerUrl, arn);
91
+ return arn;
92
+ }
93
+ }
@@ -5,3 +5,4 @@ export * from "./backup/index.js";
5
5
  export * from "./cdn/index.js";
6
6
  export * from "./messaging/index.js";
7
7
  export * from "./organisation/index.js";
8
+ export { CiIdentity, CiIdentityFactory, type CiIdentityFactoryFn, type CiIdentityProps } from "./iam/index.js";
@@ -5,3 +5,5 @@ export * from "./backup/index.js";
5
5
  export * from "./cdn/index.js";
6
6
  export * from "./messaging/index.js";
7
7
  export * from "./organisation/index.js";
8
+ // Named, so the rest of the IAM wrappers stay off the root surface.
9
+ export { CiIdentity, CiIdentityFactory } from "./iam/index.js";
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The part of an issuer URL IAM names its OIDC provider by, and keys the
3
+ * trust's condition keys on: the URL without its scheme. The handler below
4
+ * spells the same rule inline, since it runs as a string.
5
+ */
6
+ export declare function ciOidcProviderPath(issuerUrl: string): string;
7
+ /**
8
+ * Creates the account's IAM OIDC provider for one CI issuer, or adopts the
9
+ * one already there, and makes sure the audience is one of its client ids.
10
+ * The provider is an account global singleton that another stack can be
11
+ * creating at the same moment, so a create that loses that race lists again
12
+ * and checks the audience on the provider the winner made.
13
+ *
14
+ * A failed read never reads as absent. A refused list creates nothing, a
15
+ * refused get adds nothing, and a list after a lost race that still misses
16
+ * the provider refuses rather than answer with no ARN. A refusal names the
17
+ * step, the issuer and the SDK error's class name, never the error's text.
18
+ *
19
+ * The create sends no ThumbprintList, so IAM reads the issuer's certificate
20
+ * itself. Adding a client id is idempotent in IAM, so a provider whose get
21
+ * answers without a list gets the add. Delete does nothing: the provider
22
+ * outlives the stack, and so does a client id added to a shared provider.
23
+ */
24
+ export declare const CI_OIDC_PROVIDER_HANDLER = "const { IAMClient, ListOpenIDConnectProvidersCommand, GetOpenIDConnectProviderCommand, CreateOpenIDConnectProviderCommand, AddClientIDToOpenIDConnectProviderCommand } = require('@aws-sdk/client-iam');\n\nconst HTTPS_PREFIX = 'https://';\n\nfunction errorName(err) {\n const name = err && err.name;\n return typeof name === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(name) ? name : 'an unnamed error';\n}\n\nasync function step(failure, call) {\n try {\n return await call();\n } catch (err) {\n throw new Error(failure + ' (' + errorName(err) + ')');\n }\n}\n\nasync function findProvider(iam, issuer) {\n const listed = await step('Listing the OIDC providers of the account failed, so the provider of ' + issuer + ' was neither adopted nor created', () => iam.send(new ListOpenIDConnectProvidersCommand({})));\n const providers = listed && listed.OpenIDConnectProviderList;\n if (!Array.isArray(providers)) {\n throw new Error('IAM answered the list of OIDC providers without a list, so the provider of ' + issuer + ' was neither adopted nor created');\n }\n const suffix = ':oidc-provider/' + issuer.slice(HTTPS_PREFIX.length);\n return providers.map((provider) => provider && provider.Arn).find((arn) => typeof arn === 'string' && arn.endsWith(suffix));\n}\n\nasync function ensureAudience(iam, issuer, arn, clientId) {\n const got = await step('Reading the OIDC provider of ' + issuer + ' failed, so its audience was not checked', () => iam.send(new GetOpenIDConnectProviderCommand({ OpenIDConnectProviderArn: arn })));\n const clientIds = got && got.ClientIDList;\n if (Array.isArray(clientIds) && clientIds.includes(clientId)) return;\n await step('Adding the audience to the OIDC provider of ' + issuer + ' failed', () => iam.send(new AddClientIDToOpenIDConnectProviderCommand({ OpenIDConnectProviderArn: arn, ClientID: clientId })));\n}\n\nasync function converge(iam, issuer, clientId) {\n const found = await findProvider(iam, issuer);\n if (found !== undefined) {\n await ensureAudience(iam, issuer, found, clientId);\n return found;\n }\n let created;\n try {\n created = await iam.send(new CreateOpenIDConnectProviderCommand({ Url: issuer, ClientIDList: [clientId] }));\n } catch (err) {\n if (!err || err.name !== 'EntityAlreadyExistsException') {\n throw new Error('Creating the OIDC provider of ' + issuer + ' failed (' + errorName(err) + ')');\n }\n const raced = await findProvider(iam, issuer);\n if (raced === undefined) {\n throw new Error('IAM refused to create the OIDC provider of ' + issuer + ' because it exists, but a fresh list does not show it, so the deploy stops rather than answer with no ARN');\n }\n await ensureAudience(iam, issuer, raced, clientId);\n return raced;\n }\n const arn = created && created.OpenIDConnectProviderArn;\n if (typeof arn !== 'string' || arn === '') {\n throw new Error('IAM created the OIDC provider of ' + issuer + ' but answered with no ARN');\n }\n return arn;\n}\n\nexports.handler = async (event) => {\n if (event.RequestType === 'Delete') {\n return { PhysicalResourceId: event.PhysicalResourceId || event.LogicalResourceId };\n }\n const props = event.ResourceProperties || {};\n const issuer = props.IssuerUrl;\n const clientId = props.ClientId;\n if (typeof issuer !== 'string' || !issuer.startsWith(HTTPS_PREFIX) || issuer.length === HTTPS_PREFIX.length) {\n throw new Error('IssuerUrl must be an https URL');\n }\n if (typeof clientId !== 'string' || clientId === '') {\n throw new Error('ClientId must be a non empty string');\n }\n const arn = await converge(new IAMClient({}), issuer, clientId);\n return { PhysicalResourceId: arn, Data: { ProviderArn: arn } };\n};";
@@ -0,0 +1,106 @@
1
+ const HTTPS_PREFIX = "https://";
2
+ /**
3
+ * The part of an issuer URL IAM names its OIDC provider by, and keys the
4
+ * trust's condition keys on: the URL without its scheme. The handler below
5
+ * spells the same rule inline, since it runs as a string.
6
+ */
7
+ export function ciOidcProviderPath(issuerUrl) {
8
+ if (!issuerUrl.startsWith(HTTPS_PREFIX)) {
9
+ throw new Error("A CI OIDC issuer must be an https URL");
10
+ }
11
+ return issuerUrl.slice(HTTPS_PREFIX.length);
12
+ }
13
+ /**
14
+ * Creates the account's IAM OIDC provider for one CI issuer, or adopts the
15
+ * one already there, and makes sure the audience is one of its client ids.
16
+ * The provider is an account global singleton that another stack can be
17
+ * creating at the same moment, so a create that loses that race lists again
18
+ * and checks the audience on the provider the winner made.
19
+ *
20
+ * A failed read never reads as absent. A refused list creates nothing, a
21
+ * refused get adds nothing, and a list after a lost race that still misses
22
+ * the provider refuses rather than answer with no ARN. A refusal names the
23
+ * step, the issuer and the SDK error's class name, never the error's text.
24
+ *
25
+ * The create sends no ThumbprintList, so IAM reads the issuer's certificate
26
+ * itself. Adding a client id is idempotent in IAM, so a provider whose get
27
+ * answers without a list gets the add. Delete does nothing: the provider
28
+ * outlives the stack, and so does a client id added to a shared provider.
29
+ */
30
+ export const CI_OIDC_PROVIDER_HANDLER = `const { IAMClient, ListOpenIDConnectProvidersCommand, GetOpenIDConnectProviderCommand, CreateOpenIDConnectProviderCommand, AddClientIDToOpenIDConnectProviderCommand } = require('@aws-sdk/client-iam');
31
+
32
+ const HTTPS_PREFIX = '${HTTPS_PREFIX}';
33
+
34
+ function errorName(err) {
35
+ const name = err && err.name;
36
+ return typeof name === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(name) ? name : 'an unnamed error';
37
+ }
38
+
39
+ async function step(failure, call) {
40
+ try {
41
+ return await call();
42
+ } catch (err) {
43
+ throw new Error(failure + ' (' + errorName(err) + ')');
44
+ }
45
+ }
46
+
47
+ async function findProvider(iam, issuer) {
48
+ const listed = await step('Listing the OIDC providers of the account failed, so the provider of ' + issuer + ' was neither adopted nor created', () => iam.send(new ListOpenIDConnectProvidersCommand({})));
49
+ const providers = listed && listed.OpenIDConnectProviderList;
50
+ if (!Array.isArray(providers)) {
51
+ throw new Error('IAM answered the list of OIDC providers without a list, so the provider of ' + issuer + ' was neither adopted nor created');
52
+ }
53
+ const suffix = ':oidc-provider/' + issuer.slice(HTTPS_PREFIX.length);
54
+ return providers.map((provider) => provider && provider.Arn).find((arn) => typeof arn === 'string' && arn.endsWith(suffix));
55
+ }
56
+
57
+ async function ensureAudience(iam, issuer, arn, clientId) {
58
+ const got = await step('Reading the OIDC provider of ' + issuer + ' failed, so its audience was not checked', () => iam.send(new GetOpenIDConnectProviderCommand({ OpenIDConnectProviderArn: arn })));
59
+ const clientIds = got && got.ClientIDList;
60
+ if (Array.isArray(clientIds) && clientIds.includes(clientId)) return;
61
+ await step('Adding the audience to the OIDC provider of ' + issuer + ' failed', () => iam.send(new AddClientIDToOpenIDConnectProviderCommand({ OpenIDConnectProviderArn: arn, ClientID: clientId })));
62
+ }
63
+
64
+ async function converge(iam, issuer, clientId) {
65
+ const found = await findProvider(iam, issuer);
66
+ if (found !== undefined) {
67
+ await ensureAudience(iam, issuer, found, clientId);
68
+ return found;
69
+ }
70
+ let created;
71
+ try {
72
+ created = await iam.send(new CreateOpenIDConnectProviderCommand({ Url: issuer, ClientIDList: [clientId] }));
73
+ } catch (err) {
74
+ if (!err || err.name !== 'EntityAlreadyExistsException') {
75
+ throw new Error('Creating the OIDC provider of ' + issuer + ' failed (' + errorName(err) + ')');
76
+ }
77
+ const raced = await findProvider(iam, issuer);
78
+ if (raced === undefined) {
79
+ throw new Error('IAM refused to create the OIDC provider of ' + issuer + ' because it exists, but a fresh list does not show it, so the deploy stops rather than answer with no ARN');
80
+ }
81
+ await ensureAudience(iam, issuer, raced, clientId);
82
+ return raced;
83
+ }
84
+ const arn = created && created.OpenIDConnectProviderArn;
85
+ if (typeof arn !== 'string' || arn === '') {
86
+ throw new Error('IAM created the OIDC provider of ' + issuer + ' but answered with no ARN');
87
+ }
88
+ return arn;
89
+ }
90
+
91
+ exports.handler = async (event) => {
92
+ if (event.RequestType === 'Delete') {
93
+ return { PhysicalResourceId: event.PhysicalResourceId || event.LogicalResourceId };
94
+ }
95
+ const props = event.ResourceProperties || {};
96
+ const issuer = props.IssuerUrl;
97
+ const clientId = props.ClientId;
98
+ if (typeof issuer !== 'string' || !issuer.startsWith(HTTPS_PREFIX) || issuer.length === HTTPS_PREFIX.length) {
99
+ throw new Error('IssuerUrl must be an https URL');
100
+ }
101
+ if (typeof clientId !== 'string' || clientId === '') {
102
+ throw new Error('ClientId must be a non empty string');
103
+ }
104
+ const arn = await converge(new IAMClient({}), issuer, clientId);
105
+ return { PhysicalResourceId: arn, Data: { ProviderArn: arn } };
106
+ };`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fjall/components-infrastructure",
3
- "version": "39.0.14",
3
+ "version": "39.2.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/fjall-tech/fjall.git",
@@ -87,8 +87,8 @@
87
87
  },
88
88
  "dependencies": {
89
89
  "@aws-sdk/client-organizations": "^3.1098.0",
90
- "@fjall/generator": "^39.0.14",
91
- "@fjall/util": "^39.0.14",
90
+ "@fjall/generator": "^39.2.0",
91
+ "@fjall/util": "^39.2.0",
92
92
  "constructs": "^10.7.2",
93
93
  "zod": "^4.4.3"
94
94
  },