-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflake.nix
More file actions
413 lines (371 loc) · 14.4 KB
/
flake.nix
File metadata and controls
413 lines (371 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
{
description = "Build a cargo project";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
flake-utils.url = "github:numtide/flake-utils";
treefmt-nix = {
url = "github:numtide/treefmt-nix";
inputs.nixpkgs.follows = "nixpkgs";
};
crane.url = "github:ipetkov/crane";
advisory-db = {
url = "github:rustsec/advisory-db";
flake = false;
};
};
outputs =
inputs:
inputs.flake-utils.lib.eachDefaultSystem (
system:
let
pkgs = inputs.nixpkgs.legacyPackages.${system};
inherit (pkgs) lib;
craneLib = inputs.crane.mkLib pkgs;
src = lib.fileset.toSource rec {
root = ./.;
fileset = lib.fileset.unions [
# Default files from crane (Rust and cargo files)
(craneLib.fileset.commonCargoSources root)
# Include all the goldenfile test jsons as well
./golden
];
};
githubSha = builtins.getEnv "GITHUB_SHA";
commitSha =
if inputs.self ? "shortRev" then
inputs.self.shortRev
else if githubSha != "" then
builtins.substring 0 7 githubSha
else
"";
dockerTag = if commitSha != "" then commitSha else "dev";
crateVersion = crateData.package.version;
releaseTag = "v${crateVersion}-${dockerTag}";
commonArgs = {
inherit src;
strictDeps = true;
nativeBuildInputs =
[
# Add additional build inputs here
]
++ lib.optionals pkgs.stdenv.isDarwin [
# Additional darwin specific inputs can be set here
pkgs.libiconv
];
# Additional environment variables can be set directly
# MY_CUSTOM_VAR = "some value";
};
crateData = lib.importTOML ./Cargo.toml;
# Build *just* the cargo dependencies, so we can reuse
# all of that work (e.g. via cachix) when running in CI
cargoArtifacts = craneLib.buildDepsOnly commonArgs;
# Build the actual crate itself, reusing the dependency
# artifacts from above.
aacw = craneLib.buildPackage (
commonArgs
// {
inherit cargoArtifacts;
version = crateVersion;
meta.mainProgram = crateData.package.name;
}
);
sbom = craneLib.mkCargoDerivation (
commonArgs
// {
# Require the caller to specify cargoArtifacts we can use
inherit cargoArtifacts;
# A suffix name used by the derivation, useful for logging
pnameSuffix = "-sbom";
# Set the cargo command we will use and pass through the flags
installPhase = # bash
''mv bom.json $out'';
buildPhaseCargoCommand = # bash
''cargo cyclonedx -f json --all --override-filename bom'';
nativeBuildInputs = (commonArgs.nativeBuildInputs or [ ]) ++ [ pkgs.cargo-cyclonedx ];
}
);
certGenerator = lib.getExe (
pkgs.writeShellApplication {
name = "generate-self-signed-certs";
text = ''
set -euo pipefail
cd /app
step certificate create localhost tls.crt tls.key --profile self-signed --subtle --no-password --insecure
'';
runtimeInputs = [ pkgs.step-cli ];
}
);
serverRunner = lib.getExe (
pkgs.writeShellApplication {
name = "run-aacw-server";
text = ''
set -euo pipefail
cd /app
TLS_CERT_FILE=/app/tls.crt TLS_KEY_FILE=/app/tls.key ${lib.getExe aacw}
'';
runtimeInputs = [ aacw ];
}
);
nixos-vm-test = pkgs.testers.nixosTest {
name = "certificates-integrationtest";
nodes.machine =
{ pkgs, ... }:
{
environment.systemPackages = [
pkgs.curl
pkgs.jq
pkgs.step-cli
aacw
];
systemd.services.aacw = {
description = "AivenApp conversion webhook test server";
wantedBy = [ ];
serviceConfig = {
ExecStart = "${serverRunner}";
Restart = "on-failure";
Environment = "RUST_LOG=info";
};
};
};
testScript = # python
''
cert_cmd = "${certGenerator}"
machine.start()
machine.wait_for_unit("multi-user.target")
machine.succeed("mkdir -p /app")
machine.succeed(cert_cmd)
machine.succeed("systemctl start aacw.service")
machine.wait_for_open_port(3000)
def get(path: str) -> str:
return machine.succeed(f"curl -skf https://localhost:3000/{path}")
assert get("health").strip() == "ok"
assert get("ready").strip() == "ok"
machine.succeed("""cat >/tmp/payload.json <<'EOF'
{"apiVersion":"apiextensions.k8s.io/v1","kind":"ConversionReview","request":{"uid":"123","desiredAPIVersion":"aiven.nais.io/v2","objects":[{"apiVersion":"aiven.nais.io/v1","kind":"AivenApp","spec":{"secretName":"supersecret","kafka":{}}}]}}
EOF
""")
resp = machine.succeed("curl -skf https://localhost:3000/convert -H 'content-type: application/json' --data @/tmp/payload.json")
import json
obj = json.loads(resp)
converted = obj["response"]["convertedObjects"][0]
assert obj["response"]["uid"] == "123"
assert converted["apiVersion"] == "aiven.nais.io/v2"
assert converted["spec"]["kafka"]["secretName"] == "supersecret"
assert "secretName" not in converted["spec"]
# No common secretName: spec.secretName is absent,
# so the converter should not add any nested secretName.
machine.succeed("""cat >/tmp/payload-no-common.json <<'EOF'
{"apiVersion":"apiextensions.k8s.io/v1","kind":"ConversionReview","request":{"uid":"456","desiredAPIVersion":"aiven.nais.io/v2","objects":[{"apiVersion":"aiven.nais.io/v1","kind":"AivenApp","spec":{"kafka":{}}}]}}
EOF
""")
resp_no_common = machine.succeed("curl -skf https://localhost:3000/convert -H 'content-type: application/json' --data @/tmp/payload-no-common.json")
obj_no_common = json.loads(resp_no_common)
converted_no_common = obj_no_common["response"]["convertedObjects"][0]
assert "secretName" not in converted_no_common["spec"]
assert "secretName" not in converted_no_common["spec"]["kafka"]
# v2 -> v2 should be a no-op for the object contents.
machine.succeed("""cat >/tmp/payload-v2.json <<'EOF'
{"apiVersion":"apiextensions.k8s.io/v1","kind":"ConversionReview","request":{"uid":"789","desiredAPIVersion":"aiven.nais.io/v2","objects":[{"apiVersion":"aiven.nais.io/v2","kind":"AivenApp","spec":{"kafka":{"secretName":"keepme"}}}]}}
EOF
""")
resp_v2 = machine.succeed("curl -skf https://localhost:3000/convert -H 'content-type: application/json' --data @/tmp/payload-v2.json")
obj_v2 = json.loads(resp_v2)
converted_v2 = obj_v2["response"]["convertedObjects"][0]
assert obj_v2["response"]["uid"] == "789"
assert converted_v2["apiVersion"] == "aiven.nais.io/v2"
assert converted_v2["spec"]["kafka"]["secretName"] == "keepme"
machine.shutdown()
'';
};
in
{
checks =
{
inherit aacw sbom;
}
// lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux {
inherit nixos-vm-test;
}
// {
# Run clippy (and deny all warnings) on the crate source,
# again, reusing the dependency artifacts from above.
#
# Note that this is done as a separate derivation so that
# we can block the CI if there are issues here, but not
# prevent downstream consumers from building our crate by itself.
my-crate-clippy = craneLib.cargoClippy (
commonArgs
// {
inherit cargoArtifacts;
cargoClippyExtraArgs = "--all-targets -- -D warnings -W clippy::pedantic -W clippy::nursery -W clippy::cargo -A clippy::multiple_crate_versions";
}
);
my-crate-doc = craneLib.cargoDoc (
commonArgs
// {
inherit cargoArtifacts;
# This can be commented out or tweaked as necessary, e.g. set to
# `--deny rustdoc::broken-intra-doc-links` to only enforce that lint
env.RUSTDOCFLAGS = "--deny warnings";
}
);
# Check formatting
# my-crate-fmt = craneLib.cargoFmt {
# inherit src;
# };
# # Audit dependencies
my-crate-audit = craneLib.cargoAudit {
inherit src;
inherit (inputs) advisory-db;
};
# # Audit licenses
# my-crate-deny = craneLib.cargoDeny {
# inherit src;
# };
# Run tests with cargo-nextest
# Consider setting `doCheck = false` on `my-crate` if you do not want
# the tests to run twice
my-crate-nextest = craneLib.cargoNextest (
commonArgs
// {
inherit cargoArtifacts;
partitions = 1;
partitionType = "count";
cargoNextestPartitionsExtraArgs = "--no-tests=pass";
}
);
};
formatter = inputs.treefmt-nix.lib.mkWrapper pkgs {
programs.nixfmt.enable = true;
programs.rustfmt.enable = true;
};
packages =
{
inherit aacw sbom;
default = aacw;
version = pkgs.writeText "version" releaseTag;
fasit-feature =
let
release = {
inherit (crateData.package) name;
imageTag = releaseTag;
namespace = "nais-system";
};
in
lib.pipe
{
chart = import ./fasit-chart/Chart.nix { version = releaseTag; };
feature = import ./fasit-chart/Feature.nix { };
issuer = import ./fasit-chart/certissuer.nix {
inherit lib release;
extraConfig = { };
};
deployment = import ./fasit-chart/deployment.nix {
inherit lib aacw release;
extraConfig = { };
};
service = import ./fasit-chart/service.nix {
inherit lib release;
extraConfig = { };
};
certificate = import ./fasit-chart/certificate.nix {
inherit lib release;
extraConfig = { };
};
}
[
(lib.mapAttrs (
name: data:
pkgs.writeTextFile {
inherit name;
text = builtins.toJSON data;
}
))
(
files:
pkgs.stdenv.mkDerivation {
name = "helm-chart";
dontUnpack = true;
buildPhase = ''
mkdir -p $out/templates
touch $out/values.yaml
cp ${files.chart} $out/Chart.yaml
cp ${files.feature} $out/Feature.yaml
cp ${files.issuer} $out/templates/Issuer.yaml
cp ${files.deployment} $out/templates/Deployment.yaml
cp ${files.service} $out/templates/Service.yaml
cp ${files.certificate} $out/templates/Certificate.yaml
'';
}
)
];
}
// lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux {
vm-test = nixos-vm-test;
image =
(pkgs.dockerTools.buildImage {
name = "aacw";
tag = releaseTag;
copyToRoot = pkgs.buildEnv {
name = "aacw-image";
pathsToLink = [ "/bin" ];
paths = [ aacw ];
};
config = {
User = "1069:1069";
ExposedPorts = {
"3000/tcp" = { };
};
Entrypoint = [ (lib.getExe aacw) ];
Env = [ "RUST_LOG=info" ];
};
}).overrideAttrs
(old: {
imageName = "aacw";
imageTag = releaseTag;
});
};
apps.default =
inputs.flake-utils.lib.mkApp {
drv = aacw;
}
// {
meta.description = "Run aivenapp-conversion-webhooks binary";
};
apps.version =
inputs.flake-utils.lib.mkApp {
drv = pkgs.writeShellApplication {
name = "print-version";
text = ''
printf %s "${releaseTag}"
'';
};
}
// {
meta.description = "Print release tag for aivenapp-conversion-webhooks";
};
apps.mk-cert =
inputs.flake-utils.lib.mkApp {
drv = pkgs.writeShellApplication {
name = "mk-cert";
text = "step certificate create localhost cert.pem key.pem --profile self-signed --subtle --no-password --insecure";
runtimeInputs = [ pkgs.step-cli ];
};
}
// {
meta.description = "Generate self-signed localhost TLS certificate";
};
devShells.default = craneLib.devShell {
# Inherit inputs from checks.
checks = inputs.self.checks.${system};
# Additional dev-shell environment variables can be set directly
# MY_CUSTOM_DEVELOPMENT_VAR = "something else";
packages = [
pkgs.rust-analyzer
pkgs.step-cli
pkgs.kubernetes-helm
];
};
}
);
}