@cyc-seattle/platform 0.0.0-stage → 0.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,114 @@
1
- # Temporary Holding Version
1
+ # platform
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Pulumi stacks for CYC Community Sailing Center's shared Google Cloud platform: the things no single
4
+ app owns. The apps that run on it live in their own repos, such as
5
+ [isthmia](https://github.com/cyc-seattle/isthmia).
6
+
7
+ ## Stacks
8
+
9
+ | Stack | Holds | Applied by |
10
+ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
11
+ | [`bootstrap`](stacks/bootstrap) | Service accounts and project IAM, the Pulumi state buckets and KMS keys, and the org's GitHub repos and settings | A human with project Owner and `gh` `admin:org`. Never CI. |
12
+ | [`cloud`](stacks/cloud) | The VPC, the cluster subnet and its Cloud NAT, the private services peering, the prod and dev Cloud SQL instances, the DNS zones, and Artifact Registry | `deploy-runner`, from Actions after approval. A deployer, with `mise run deploy`, when breaking glass. |
13
+ | [`cluster`](stacks/cluster) | The GKE Autopilot cluster, the shared Gateway, its address, certificates, and DNS records, the `dev` namespace with its RBAC, quota, and network policy, and each environment's `platform/outputs.json` | `deploy-runner`, from Actions after approval. A deployer, with `mise run deploy`, when breaking glass. |
14
+ | [`smoke`](stacks/smoke) | One `WebService` in dev, at `smoke.dev.cycsail.team`, for the integration tests | `deploy-dev`, from Actions on every PR. A deployer, with `PULUMI_STACK=dev mise run deploy`, when breaking glass. |
15
+
16
+ ## @cyc-seattle/platform
17
+
18
+ `src/` is the `@cyc-seattle/platform` package, which the stacks here and the apps' stacks import:
19
+
20
+ - `getPlatformOutputs()` reads an environment's `platform/outputs.json` from its state bucket. The
21
+ `cluster` stack writes it. Dev stacks can't read prod's backend, so this replaces a
22
+ StackReference for platform values (cyc-seattle/isthmia#215).
23
+ - `clusterProvider(platform)` builds a Kubernetes provider for the cluster. Its kubeconfig runs
24
+ `gke-gcloud-auth-plugin` with Application Default Credentials, so Pulumi must run under mise,
25
+ where `mise run install` puts the plugin on `PATH`.
26
+ - `WebService` runs an HTTP service behind the environment's Gateway, with secure defaults. Its pods
27
+ get no IAM; grant roles to its `member`, a Workload Identity principal.
28
+ - `enableService` enables a Google Cloud API.
29
+
30
+ `mise run build` builds it into `dist/`, which is all it publishes.
31
+
32
+ ## Setup
33
+
34
+ [mise](https://mise.jdx.dev/) provides the tools.
35
+
36
+ ```sh
37
+ mise trust
38
+ mise run install
39
+ mise run auth-adc
40
+ ```
41
+
42
+ `mise run auth-adc` logs Application Default Credentials in as your own account. Pulumi uses them
43
+ for GCP and for the state bucket. [docs/manual-setup.md](docs/manual-setup.md) lists the access a
44
+ deployer needs first.
45
+
46
+ ## Deploy
47
+
48
+ ### From Actions
49
+
50
+ `.github/workflows/pull-request.yml` deploys through the org's reusable `deploy.yml`, which
51
+ authenticates with Workload Identity Federation and stores no credentials. Each job runs in a
52
+ GitHub environment that holds its identity and state bucket:
53
+
54
+ | Event | Jobs, in order |
55
+ | -------------- | ----------------------------------------------------------------------------------------- |
56
+ | Pull request | `ci`, then `dev`: `mise run deploy` as `deploy-dev`, then `mise run integration` |
57
+ | Push to `main` | `ci`, `dev`, then `prod-preview`, then `prod`, which waits for the `maintainers` approval |
58
+
59
+ `prod-preview` runs `mise run preview` as `deploy-runner` and writes the diff to the job summary.
60
+ `prod` runs `mise run deploy` on the same commit once approved. A PR from a fork gets no OIDC token,
61
+ so its `dev` job is skipped.
62
+
63
+ `PULUMI_STACK` picks what the tasks run (`scripts/each-stack`): `dev` is `smoke`, and `prod` is
64
+ `cloud`, then `cluster`. `integration` is dev only.
65
+
66
+ `bootstrap` is never deployed from Actions (cyc-seattle/isthmia#118). It holds the identities that
67
+ CI assumes, and a human with project Owner and `gh` `admin:org` applies it with the tasks below.
68
+
69
+ ### From a laptop
70
+
71
+ Local deploys stay as the break-glass path. A deployer applies with the same tasks:
72
+
73
+ ```sh
74
+ mise run preview-bootstrap
75
+ mise run deploy-bootstrap
76
+ mise run preview
77
+ mise run deploy
78
+ PULUMI_STACK=dev mise run deploy
79
+ ```
80
+
81
+ `mise run deploy` applies `cloud`, then `cluster`. Prod stacks read `cloud`'s outputs through a
82
+ StackReference. Dev stacks can't read prod state, so `cluster` writes each environment's platform
83
+ values to `platform/outputs.json` in that environment's state bucket.
84
+
85
+ `bootstrap`'s GitHub provider uses `gh auth token`, so log `gh` in as a cyc-seattle org owner with
86
+ the `admin:org` scope: `gh auth refresh -h github.com -s admin:org`. Deploys refresh first, so they
87
+ delete a label added by hand.
88
+
89
+ ## State
90
+
91
+ Each environment's state lives in its own bucket, `gs://cyc-admin-scripts-pulumi-<stack>`, with its
92
+ secrets encrypted by the `state-<stack>` KMS key. `stacks/bootstrap/state.ts` creates both.
93
+ `mise.toml` picks the bucket from `PULUMI_STACK`, which defaults to `prod`, so stack names are
94
+ `organization/<project>/<stack>`. It sets `GOOGLE_APPLICATION_CREDENTIALS` to the shared `.gcloud/`
95
+ login only when it isn't already set, so Actions' credentials win.
96
+
97
+ `bootstrap`'s own state lives in the bucket it creates. Both the bucket and the key are protected.
98
+
99
+ ## Development
100
+
101
+ ```sh
102
+ mise run ci
103
+ ```
104
+
105
+ Runs the type check, Prettier, ESLint, and the unit tests. Tests mock Pulumi with
106
+ `pulumi.runtime.setMocks` and never call a live API.
107
+
108
+ ```sh
109
+ mise run integration
110
+ ```
111
+
112
+ Runs the Gherkin scenarios in `features/` against dev, after `PULUMI_STACK=dev mise run deploy`. They run as
113
+ whatever identity Application Default Credentials hold. The isolation scenarios expect `deploy-dev`,
114
+ so as a human, log Application Default Credentials in with `--impersonate-service-account` first.
@@ -0,0 +1,4 @@
1
+ export { clusterProvider, type ClusterProviderArgs } from "./kubernetes";
2
+ export { getPlatformOutputs, parsePlatformOutputs, platformOutputsSchema, readPlatformOutputs, stateBucket, type PlatformOutputs, type PlatformOutputsArgs, } from "./outputs";
3
+ export { enableService } from "./services";
4
+ export { WebService, type WebServiceArgs } from "./web-service";
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebService = exports.enableService = exports.stateBucket = exports.readPlatformOutputs = exports.platformOutputsSchema = exports.parsePlatformOutputs = exports.getPlatformOutputs = exports.clusterProvider = void 0;
4
+ var kubernetes_1 = require("./kubernetes");
5
+ Object.defineProperty(exports, "clusterProvider", { enumerable: true, get: function () { return kubernetes_1.clusterProvider; } });
6
+ var outputs_1 = require("./outputs");
7
+ Object.defineProperty(exports, "getPlatformOutputs", { enumerable: true, get: function () { return outputs_1.getPlatformOutputs; } });
8
+ Object.defineProperty(exports, "parsePlatformOutputs", { enumerable: true, get: function () { return outputs_1.parsePlatformOutputs; } });
9
+ Object.defineProperty(exports, "platformOutputsSchema", { enumerable: true, get: function () { return outputs_1.platformOutputsSchema; } });
10
+ Object.defineProperty(exports, "readPlatformOutputs", { enumerable: true, get: function () { return outputs_1.readPlatformOutputs; } });
11
+ Object.defineProperty(exports, "stateBucket", { enumerable: true, get: function () { return outputs_1.stateBucket; } });
12
+ var services_1 = require("./services");
13
+ Object.defineProperty(exports, "enableService", { enumerable: true, get: function () { return services_1.enableService; } });
14
+ var web_service_1 = require("./web-service");
15
+ Object.defineProperty(exports, "WebService", { enumerable: true, get: function () { return web_service_1.WebService; } });
@@ -0,0 +1,19 @@
1
+ import * as k8s from "@pulumi/kubernetes";
2
+ import * as pulumi from "@pulumi/pulumi";
3
+ import type { PlatformOutputs } from "./outputs";
4
+ export interface ClusterProviderArgs {
5
+ /**
6
+ * Keeps a kubeconfig that is unknown or changes, such as during a cluster update, from replacing
7
+ * the provider and with it every Kubernetes resource it manages.
8
+ */
9
+ clusterIdentifier?: pulumi.Input<string>;
10
+ }
11
+ /**
12
+ * A Kubernetes provider for the environment's cluster. Its kubeconfig runs gke-gcloud-auth-plugin
13
+ * with Application Default Credentials, so it is the same on every run, unlike one that embeds an
14
+ * access token. The plugin must be on PATH: `mise run install` adds it. The cluster stack passes
15
+ * only the endpoint, because it writes the rest.
16
+ */
17
+ export declare function clusterProvider(platform: pulumi.Input<{
18
+ clusterEndpoint: pulumi.Input<PlatformOutputs["clusterEndpoint"]>;
19
+ }>, name?: string, opts?: pulumi.CustomResourceOptions, args?: ClusterProviderArgs): k8s.Provider;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.clusterProvider = clusterProvider;
37
+ const k8s = __importStar(require("@pulumi/kubernetes"));
38
+ const pulumi = __importStar(require("@pulumi/pulumi"));
39
+ /**
40
+ * A Kubernetes provider for the environment's cluster. Its kubeconfig runs gke-gcloud-auth-plugin
41
+ * with Application Default Credentials, so it is the same on every run, unlike one that embeds an
42
+ * access token. The plugin must be on PATH: `mise run install` adds it. The cluster stack passes
43
+ * only the endpoint, because it writes the rest.
44
+ */
45
+ function clusterProvider(platform, name = "cluster", opts, args = {}) {
46
+ // The DNS-based endpoint serves a publicly trusted certificate, so the kubeconfig needs no CA.
47
+ const kubeconfig = pulumi.output(platform).clusterEndpoint.apply((endpoint) => JSON.stringify({
48
+ apiVersion: "v1",
49
+ kind: "Config",
50
+ clusters: [{ name: "cluster", cluster: { server: `https://${endpoint}` } }],
51
+ users: [
52
+ {
53
+ name: "user",
54
+ user: {
55
+ exec: {
56
+ apiVersion: "client.authentication.k8s.io/v1beta1",
57
+ command: "gke-gcloud-auth-plugin",
58
+ args: ["--use_application_default_credentials"],
59
+ installHint: "Run `mise run install`, and run Pulumi under mise.",
60
+ provideClusterInfo: true,
61
+ },
62
+ },
63
+ },
64
+ ],
65
+ contexts: [{ name: "cluster", context: { cluster: "cluster", user: "user" } }],
66
+ "current-context": "cluster",
67
+ }));
68
+ return new k8s.Provider(name, { kubeconfig, clusterIdentifier: args.clusterIdentifier }, opts);
69
+ }
@@ -0,0 +1,34 @@
1
+ import * as pulumi from "@pulumi/pulumi";
2
+ import { z } from "zod";
3
+ export declare const platformOutputsSchema: z.ZodObject<{
4
+ project: z.ZodString;
5
+ projectNumber: z.ZodString;
6
+ region: z.ZodString;
7
+ cluster: z.ZodString;
8
+ clusterEndpoint: z.ZodString;
9
+ namespace: z.ZodString;
10
+ gateway: z.ZodObject<{
11
+ name: z.ZodString;
12
+ namespace: z.ZodString;
13
+ }, z.core.$strip>;
14
+ domain: z.ZodString;
15
+ sqlConnectionName: z.ZodString;
16
+ registry: z.ZodString;
17
+ }, z.core.$strip>;
18
+ /** One environment's platform values: where its cluster, Gateway, database, and registry are. */
19
+ export type PlatformOutputs = z.infer<typeof platformOutputsSchema>;
20
+ export declare const outputsObject = "platform/outputs.json";
21
+ /** The state bucket of an environment, as `stacks/bootstrap/state.ts` names it. */
22
+ export declare function stateBucket(project: string, environment: string): string;
23
+ /** Parses and validates the outputs file's text. `source` names the file in error messages. */
24
+ export declare function parsePlatformOutputs(text: string, source: string): PlatformOutputs;
25
+ export interface PlatformOutputsArgs {
26
+ /** The environment, which names the state bucket. Defaults to the stack's name. */
27
+ environment?: string;
28
+ /** The project that holds the state bucket. Defaults to `gcp:project`. */
29
+ project?: string;
30
+ }
31
+ /** Reads this environment's platform values from its state bucket. Most programs want `getPlatformOutputs`. */
32
+ export declare function readPlatformOutputs(args?: PlatformOutputsArgs): Promise<PlatformOutputs>;
33
+ /** Reads this environment's platform values from its state bucket. */
34
+ export declare function getPlatformOutputs(args?: PlatformOutputsArgs): pulumi.Output<PlatformOutputs>;
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.outputsObject = exports.platformOutputsSchema = void 0;
37
+ exports.stateBucket = stateBucket;
38
+ exports.parsePlatformOutputs = parsePlatformOutputs;
39
+ exports.readPlatformOutputs = readPlatformOutputs;
40
+ exports.getPlatformOutputs = getPlatformOutputs;
41
+ const gcp = __importStar(require("@pulumi/gcp"));
42
+ const pulumi = __importStar(require("@pulumi/pulumi"));
43
+ const zod_1 = require("zod");
44
+ // The cluster stack writes this object to each environment's state bucket, because a StackReference
45
+ // can't cross from a dev stack into prod's backend (cyc-seattle/isthmia#215).
46
+ exports.platformOutputsSchema = zod_1.z.object({
47
+ project: zod_1.z.string().min(1),
48
+ projectNumber: zod_1.z.string().regex(/^\d+$/),
49
+ region: zod_1.z.string().min(1),
50
+ cluster: zod_1.z.string().min(1),
51
+ clusterEndpoint: zod_1.z.string().min(1),
52
+ namespace: zod_1.z.string().min(1),
53
+ gateway: zod_1.z.object({ name: zod_1.z.string().min(1), namespace: zod_1.z.string().min(1) }),
54
+ domain: zod_1.z.string().min(1),
55
+ sqlConnectionName: zod_1.z.string().min(1),
56
+ registry: zod_1.z.string().min(1),
57
+ });
58
+ exports.outputsObject = "platform/outputs.json";
59
+ /** The state bucket of an environment, as `stacks/bootstrap/state.ts` names it. */
60
+ function stateBucket(project, environment) {
61
+ return `${project}-pulumi-${environment}`;
62
+ }
63
+ /** Parses and validates the outputs file's text. `source` names the file in error messages. */
64
+ function parsePlatformOutputs(text, source) {
65
+ let json;
66
+ try {
67
+ json = JSON.parse(text);
68
+ }
69
+ catch (e) {
70
+ throw new Error(`${source} is not valid JSON: ${e.message}`);
71
+ }
72
+ const result = exports.platformOutputsSchema.safeParse(json);
73
+ if (!result.success) {
74
+ throw new Error(`${source} doesn't hold the platform outputs:\n${zod_1.z.prettifyError(result.error)}`);
75
+ }
76
+ return result.data;
77
+ }
78
+ /** Reads this environment's platform values from its state bucket. Most programs want `getPlatformOutputs`. */
79
+ async function readPlatformOutputs(args = {}) {
80
+ const project = args.project ?? new pulumi.Config("gcp").require("project");
81
+ const bucket = stateBucket(project, args.environment ?? pulumi.getStack());
82
+ const source = `gs://${bucket}/${exports.outputsObject}`;
83
+ let content;
84
+ try {
85
+ ({ content } = await gcp.storage.getBucketObjectContent({ bucket, name: exports.outputsObject }));
86
+ }
87
+ catch (e) {
88
+ throw new Error(`Can't read ${source}. The cluster stack writes it.\n${e.message}`);
89
+ }
90
+ if (!content) {
91
+ throw new Error(`${source} is empty. The cluster stack writes it.`);
92
+ }
93
+ return parsePlatformOutputs(content, source);
94
+ }
95
+ /** Reads this environment's platform values from its state bucket. */
96
+ function getPlatformOutputs(args = {}) {
97
+ return pulumi.output(readPlatformOutputs(args));
98
+ }
@@ -0,0 +1,8 @@
1
+ import * as gcp from "@pulumi/gcp";
2
+ /**
3
+ * Enables a Google Cloud API, memoized so repeated calls for the same API return the same resource.
4
+ * Returns the {@link gcp.projects.Service} so the resources that need the API can `dependsOn` it and
5
+ * therefore be created only after it is enabled. Enable each API from the file that uses it, rather
6
+ * than maintaining a central list.
7
+ */
8
+ export declare function enableService(service: string): gcp.projects.Service;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.enableService = enableService;
37
+ const gcp = __importStar(require("@pulumi/gcp"));
38
+ const enabled = new Map();
39
+ /**
40
+ * Enables a Google Cloud API, memoized so repeated calls for the same API return the same resource.
41
+ * Returns the {@link gcp.projects.Service} so the resources that need the API can `dependsOn` it and
42
+ * therefore be created only after it is enabled. Enable each API from the file that uses it, rather
43
+ * than maintaining a central list.
44
+ */
45
+ function enableService(service) {
46
+ const existing = enabled.get(service);
47
+ if (existing) {
48
+ return existing;
49
+ }
50
+ const svc = new gcp.projects.Service(`enable-${service}`, {
51
+ service,
52
+ // Leave the API enabled if the resource is torn down — other things may rely on it.
53
+ disableOnDestroy: false,
54
+ });
55
+ enabled.set(service, svc);
56
+ return svc;
57
+ }
@@ -0,0 +1,41 @@
1
+ import * as k8s from "@pulumi/kubernetes";
2
+ import * as pulumi from "@pulumi/pulumi";
3
+ import type { PlatformOutputs } from "./outputs";
4
+ type Probe = k8s.types.input.core.v1.Probe;
5
+ export interface WebServiceArgs {
6
+ /** The environment's platform values, from `getPlatformOutputs`. */
7
+ platform: pulumi.Input<PlatformOutputs>;
8
+ /** The environment's cluster, from `clusterProvider`. Required, so it never uses a local kubeconfig. */
9
+ provider: k8s.Provider;
10
+ /** The public hostname. It must be in the environment's domain. */
11
+ hostname: string;
12
+ image: pulumi.Input<string>;
13
+ /** The port the container serves HTTP on. */
14
+ port: number;
15
+ requests: {
16
+ cpu: pulumi.Input<string>;
17
+ memory: pulumi.Input<string>;
18
+ };
19
+ /** An HTTP GET probe. The load balancer's health check uses the same path. */
20
+ readinessProbe: Probe & {
21
+ httpGet: pulumi.Input<k8s.types.input.core.v1.HTTPGetAction>;
22
+ };
23
+ livenessProbe?: Probe;
24
+ env?: pulumi.Input<k8s.types.input.core.v1.EnvVar>[];
25
+ replicas?: number;
26
+ /** Needed when the image's user is a name, which `runAsNonRoot` can't check. */
27
+ runAsUser?: number;
28
+ }
29
+ /** Returns `hostname` if it is the environment's domain or a name under it, and throws otherwise. */
30
+ export declare function checkHostname(hostname: string, domain: string): string;
31
+ /**
32
+ * An HTTP service behind the environment's shared Gateway: a Deployment, a Service, an HTTPRoute, a
33
+ * Kubernetes ServiceAccount, and a HealthCheckPolicy. Its pods get no IAM; grant roles to `member`.
34
+ */
35
+ export declare class WebService extends pulumi.ComponentResource {
36
+ /** The pods' Workload Identity principal, for IAM grants. */
37
+ readonly member: pulumi.Output<string>;
38
+ readonly url: pulumi.Output<string>;
39
+ constructor(name: string, args: WebServiceArgs, opts?: pulumi.ComponentResourceOptions);
40
+ }
41
+ export {};
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.WebService = void 0;
37
+ exports.checkHostname = checkHostname;
38
+ const k8s = __importStar(require("@pulumi/kubernetes"));
39
+ const pulumi = __importStar(require("@pulumi/pulumi"));
40
+ /** Returns `hostname` if it is the environment's domain or a name under it, and throws otherwise. */
41
+ function checkHostname(hostname, domain) {
42
+ const host = hostname.toLowerCase();
43
+ const base = domain.toLowerCase();
44
+ if (host !== base && !host.endsWith(`.${base}`)) {
45
+ throw new Error(`Hostname ${hostname} isn't in the environment's domain, ${domain}.`);
46
+ }
47
+ return hostname;
48
+ }
49
+ /**
50
+ * An HTTP service behind the environment's shared Gateway: a Deployment, a Service, an HTTPRoute, a
51
+ * Kubernetes ServiceAccount, and a HealthCheckPolicy. Its pods get no IAM; grant roles to `member`.
52
+ */
53
+ class WebService extends pulumi.ComponentResource {
54
+ /** The pods' Workload Identity principal, for IAM grants. */
55
+ member;
56
+ url;
57
+ constructor(name, args, opts) {
58
+ super("cyc-seattle:platform:WebService", name, {}, opts);
59
+ // The types already require these, but a JavaScript caller or a cast can skip them.
60
+ if (!args.requests?.cpu || !args.requests?.memory) {
61
+ throw new Error(`WebService "${name}" needs CPU and memory requests.`);
62
+ }
63
+ if (!args.readinessProbe?.httpGet) {
64
+ throw new Error(`WebService "${name}" needs an HTTP readiness probe.`);
65
+ }
66
+ const platform = pulumi.output(args.platform);
67
+ const namespace = platform.namespace;
68
+ // A bad hostname fails the HTTPRoute's registration, so preview fails before anything applies.
69
+ const hostname = platform.domain.apply((domain) => checkHostname(args.hostname, domain));
70
+ // The namespace is the environment's name.
71
+ const spot = namespace.apply((ns) => ns === "dev");
72
+ const labels = { "app.kubernetes.io/name": name };
73
+ const metadata = { name, namespace, labels };
74
+ const child = { parent: this, provider: args.provider };
75
+ const serviceAccount = new k8s.core.v1.ServiceAccount(name, { metadata, automountServiceAccountToken: false }, child);
76
+ new k8s.apps.v1.Deployment(name, {
77
+ metadata,
78
+ spec: {
79
+ replicas: args.replicas ?? 1,
80
+ selector: { matchLabels: labels },
81
+ template: {
82
+ metadata: { labels },
83
+ spec: {
84
+ serviceAccountName: serviceAccount.metadata.name,
85
+ automountServiceAccountToken: false,
86
+ // Autopilot schedules a pod with this selector on Spot capacity.
87
+ nodeSelector: spot.apply((s) => (s ? { "cloud.google.com/gke-spot": "true" } : {})),
88
+ securityContext: {
89
+ runAsNonRoot: true,
90
+ seccompProfile: { type: "RuntimeDefault" },
91
+ ...(args.runAsUser !== undefined && { runAsUser: args.runAsUser, runAsGroup: args.runAsUser }),
92
+ },
93
+ containers: [
94
+ {
95
+ name,
96
+ image: args.image,
97
+ ports: [{ name: "http", containerPort: args.port }],
98
+ resources: { requests: args.requests },
99
+ readinessProbe: args.readinessProbe,
100
+ ...(args.livenessProbe && { livenessProbe: args.livenessProbe }),
101
+ ...(args.env && { env: args.env }),
102
+ securityContext: {
103
+ allowPrivilegeEscalation: false,
104
+ readOnlyRootFilesystem: true,
105
+ capabilities: { drop: ["ALL"] },
106
+ },
107
+ },
108
+ ],
109
+ },
110
+ },
111
+ },
112
+ }, child);
113
+ const service = new k8s.core.v1.Service(name, {
114
+ metadata,
115
+ spec: {
116
+ selector: labels,
117
+ ports: [{ name: "http", port: 80, targetPort: "http" }],
118
+ },
119
+ }, child);
120
+ new k8s.apiextensions.CustomResource(name, {
121
+ apiVersion: "gateway.networking.k8s.io/v1",
122
+ kind: "HTTPRoute",
123
+ metadata,
124
+ spec: {
125
+ parentRefs: [{ name: platform.gateway.name, namespace: platform.gateway.namespace }],
126
+ hostnames: [hostname],
127
+ rules: [{ backendRefs: [{ name: service.metadata.name, port: 80 }] }],
128
+ },
129
+ }, child);
130
+ // Without it, the load balancer checks `/` on the serving port, which an app may not answer.
131
+ new k8s.apiextensions.CustomResource(name, {
132
+ apiVersion: "networking.gke.io/v1",
133
+ kind: "HealthCheckPolicy",
134
+ metadata,
135
+ spec: {
136
+ default: {
137
+ config: {
138
+ type: "HTTP",
139
+ httpHealthCheck: {
140
+ portSpecification: "USE_SERVING_PORT",
141
+ requestPath: pulumi.output(args.readinessProbe.httpGet).apply((get) => get?.path ?? "/"),
142
+ },
143
+ },
144
+ },
145
+ targetRef: { group: "", kind: "Service", name: service.metadata.name },
146
+ },
147
+ }, child);
148
+ this.member = pulumi.interpolate `principal://iam.googleapis.com/projects/${platform.projectNumber}/locations/global/workloadIdentityPools/${platform.project}.svc.id.goog/subject/ns/${namespace}/sa/${serviceAccount.metadata.name}`;
149
+ this.url = pulumi.interpolate `https://${hostname}/`;
150
+ this.registerOutputs({ member: this.member, url: this.url });
151
+ }
152
+ }
153
+ exports.WebService = WebService;
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@cyc-seattle/platform",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Pulumi components for CYC's shared Google Cloud platform: WebService, the platform outputs reader, and the stacks that build the platform",
5
+ "author": "CYC Community Sailing Center",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://github.com/cyc-seattle/platform#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/cyc-seattle/platform/issues"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/cyc-seattle/platform.git"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "engines": {
19
+ "node": ">=22"
20
+ },
21
+ "packageManager": "pnpm@10.34.6",
22
+ "prettier": "@cyc-seattle/ts-config/prettier",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.build.json",
35
+ "prepack": "pnpm run build"
36
+ },
37
+ "dependencies": {
38
+ "zod": "4.6.7"
39
+ },
40
+ "peerDependencies": {
41
+ "@pulumi/gcp": "^8",
42
+ "@pulumi/kubernetes": "^4",
43
+ "@pulumi/pulumi": "^3"
44
+ },
45
+ "devDependencies": {
46
+ "@amiceli/vitest-cucumber": "7.0.0",
47
+ "@cyc-seattle/ts-config": "^0.1.2",
48
+ "@pulumi/command": "1.2.1",
49
+ "@pulumi/gcp": "8.41.1",
50
+ "@pulumi/github": "6.15.0",
51
+ "@pulumi/kubernetes": "4.34.2",
52
+ "@pulumi/pulumi": "3.264.0",
53
+ "@types/js-yaml": "4.0.9",
54
+ "@types/node": "^22.19.1",
55
+ "eslint": "^9.39.5",
56
+ "google-auth-library": "^11.3.0",
57
+ "js-yaml": "^5.4.3",
58
+ "prettier": "^3.9.10",
59
+ "typescript": "~5.9.3",
60
+ "vitest": "^4.1.11"
61
+ }
62
+ }