@fjall/components-infrastructure 39.0.14 → 39.1.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.
@@ -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.1.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.1.0",
91
+ "@fjall/util": "^39.1.0",
92
92
  "constructs": "^10.7.2",
93
93
  "zod": "^4.4.3"
94
94
  },