├── .editorconfig
├── .envrc
├── .github
└── workflows
│ └── publish.yaml
├── .gitignore
├── LICENSE
├── Readme.md
├── build.nix
├── dag.nix
├── default.nix
├── example
├── configuration.nix
├── default.nix
├── deploy.nix
├── hardware-configuration.nix
└── secret
├── flake.lock
├── flake.nix
├── ip.nix
├── modules
├── deploy.nix
├── dns.nix
├── options.nix
├── public-ip.nix
├── secrets.nix
├── ssh.nix
└── vpn
│ ├── default.nix
│ └── wireguard.nix
├── notes.md
└── scripts
└── switch
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | end_of_line = lf
5 | insert_final_newline = true
6 | trim_trailing_whitespace = true
7 | charset = utf-8
8 | indent_style = space
9 | indent_size = 2
10 |
--------------------------------------------------------------------------------
/.envrc:
--------------------------------------------------------------------------------
1 | use nix
2 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yaml:
--------------------------------------------------------------------------------
1 | name: "Publish a flake to flakestry"
2 | on:
3 | push:
4 | tags:
5 | - "v?[0-9]+.[0-9]+.[0-9]+"
6 | - "v?[0-9]+.[0-9]+"
7 | workflow_dispatch:
8 | inputs:
9 | tag:
10 | description: "The existing tag to publish"
11 | type: "string"
12 | required: true
13 | jobs:
14 | publish-flake:
15 | runs-on: ubuntu-latest
16 | permissions:
17 | id-token: "write"
18 | contents: "read"
19 | steps:
20 | - uses: flakestry/flakestry-publish@main
21 | with:
22 | version: "${{ inputs.tag || github.ref_name }}"
23 |
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | result
2 | .direnv
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Readme.md:
--------------------------------------------------------------------------------
1 | # Nixus: Experimental deployment tool for multiple NixOS systems
2 |
3 | This is an experimental deployment tool I'm using for my own systems.
4 |
5 | ## Features
6 |
7 | ### Multi-host modules
8 |
9 | Nixus is roughly based on a module system evaluation of type `attrsOf nixos`.
10 | That is, the module system is used for the entire evaluation, and not just for each individual NixOS machine.
11 | This most notably allows writing options that influence the configuration of multiple machines.
12 |
13 | These abstraction modules can be written for personal use by anybody, just like any user can write their own NixOS modules.
14 |
15 | #### Example: SSH access
16 |
17 | The [SSH access module](./modules/ssh.nix), included by default,
18 | enables an easy way to configure ssh access between users on different machines.
19 | After configuring the host and user keys, a definition like this:
20 |
21 | ```nix
22 | ssh.access.host1.keys.someHost1User.hasAccessTo.host2.someHost2User = true;
23 | ```
24 |
25 | Will grant `someHost1User@host1` SSH access to `someHost2User@host2`.
26 | More concretely, it does two things:
27 | - Adds `someHost1User`'s SSH key from `host1` to the authorized keys list of `someHost2User` on `host2`
28 | - Adds `host2`'s SSH host key to the known hosts list on `host1`.
29 |
30 | This means that when logged into `someHost1User@host1`, one can run `ssh someHost2User@host2` without any extra steps required.
31 |
32 | For a more complete example, see [my own configuration](https://github.com/infinisil/system/blob/4295f8e8646d8646406604c48e38be69b0759ced/config/multimods/ssh-access.nix).
33 |
34 | #### Example: VPN network
35 |
36 | The [VPN module](./modules/vpn), included by default,
37 | enables an easy way to configure a VPN network between machines.
38 | Such a configuration might look like this:
39 |
40 | ```nix
41 | vpn.networks.network1 = {
42 | backend = "wireguard";
43 | subnet = "10.0.0.0/24";
44 | server = {
45 | node = "host1";
46 | subnetIp = "10.0.0.1";
47 | wireguard.publicKey = "...";
48 | wireguard.privateKeyFile = "/...";
49 | };
50 | clients.host2 = {
51 | subnetIp = "10.0.0.2";
52 | wireguard.publicKey = "...";
53 | wireguard.privateKeyFile = "/...";
54 | };
55 | clients.host3 = {
56 | subnetIp = "10.0.0.3";
57 | wireguard.publicKey = "...";
58 | wireguard.privateKeyFile = "/...";
59 | };
60 | }
61 | ```
62 |
63 | This configures both the server and each client:
64 | - The server will be configured to know the public keys of each client
65 | - The clients will be configured to connect to the server and know its public key
66 |
67 | For another example, see [my own configuration](https://github.com/infinisil/system/blob/4295f8e8646d8646406604c48e38be69b0759ced/config/multimods/vpn-setup.nix)
68 |
69 | #### Other examples
70 |
71 | Other examples include:
72 | - An included by default [DNS record module](./modules/dns.nix) to allow assigning DNS entries
73 | without having to know which server controls the corresponding DNS zone.
74 | This could also be extended to easily support secondary DNS zones for redundancy.
75 | - My personal [`rtcwake` module](https://github.com/infinisil/system/blob/4295f8e8646d8646406604c48e38be69b0759ced/config/multimods/rtcwake.nix),
76 | which allows suspending a machine but having it regularly wake up to check a server whether it should continue being suspending or not.
77 | - My very rough and not self-contained personal [on-demand-minecraft module](https://github.com/infinisil/system/blob/4295f8e8646d8646406604c48e38be69b0759ced/config/multimods/on-demand-minecraft/default.nix),
78 | which runs [`on-demand-minecraft`](https://github.com/infinisil/on-demand-minecraft) on a machine,
79 | but also configures DNS SRV records on the DNS server.
80 |
81 | Generally any NixOS module that interacts with other machines could benefit from being written in such a multi-module abstraction layer.
82 |
83 | ### Auto-rollback
84 |
85 | Auto-rollback if the machine can't be reached via SSH anymore, protecting against a number of configuration mistakes such as
86 | - Messing up the network config
87 | - Removing your SSH key from the authorized keys
88 | - The activation script failing in any way
89 | - The boot activation failing in any way
90 | - The system crashing during the deployment
91 |
92 | #### Example
93 |
94 | ```
95 | [foo.example.com] Connecting to host...
96 | [foo.example.com] Copying closure to host...
97 | [foo.example.com] copying 3 paths...
98 | [foo.example.com] copying path '/nix/store/dh08694j23zbp6rra8wbhr9yy4vri49h-system-units' to 'ssh://root@138.68.83.114'...
99 | [foo.example.com] copying path '/nix/store/xyslp1r2267vsrlrq73h79w31p2na223-etc' to 'ssh://root@138.68.83.114'...
100 | [foo.example.com] copying path '/nix/store/3ndywy808vm6ahbwkmam4sqvxy0hv7hq-nixos-system-test-20.03pre-git' to 'ssh://root@138.68.83.114'...
101 | [foo.example.com] Triggering system switcher...
102 | [foo.example.com] Trying to confirm success...
103 | [foo.example.com] Failed to activate new system! Rolled back to previous one
104 | ```
105 |
106 | ### Secret management
107 |
108 | Tracks secrets through the Nix store,
109 | automatically restarting services if they change,
110 | but without including them in the Nix store.
111 |
112 | ## How to use it
113 |
114 | Write a file like `example/default.nix`, then build the deployment script and call it
115 | ```
116 | $ nix-build example/default.nix
117 | these derivations will be built:
118 | /nix/store/lv8ck2k8b6vmsdp8wlqlpqr4shbkplfa-system-units.drv
119 | /nix/store/azyfd4qhv2hcdagcr8hmzwa2q284f9rh-etc.drv
120 | /nix/store/3kzhmi0flgcnpn6s5rym6hv8rs48hrs2-nixos-system-test-20.03pre-git.drv
121 | /nix/store/q6qx69mzy50llv3i7by5wwqyirqhpijy-deploy-foo.example.com.drv
122 | /nix/store/l7di8hzwa1m784ycqw01hdrybaxdi1jw-deploy.drv
123 | building '/nix/store/lv8ck2k8b6vmsdp8wlqlpqr4shbkplfa-system-units.drv'...
124 | building '/nix/store/azyfd4qhv2hcdagcr8hmzwa2q284f9rh-etc.drv'...
125 | building '/nix/store/3kzhmi0flgcnpn6s5rym6hv8rs48hrs2-nixos-system-test-20.03pre-git.drv'...
126 | building '/nix/store/q6qx69mzy50llv3i7by5wwqyirqhpijy-deploy-foo.example.com.drv'...
127 | building '/nix/store/l7di8hzwa1m784ycqw01hdrybaxdi1jw-deploy.drv'...
128 | /nix/store/z73pjq6d7n6f3xfhx9rycfk9sxqjmcav-deploy
129 | $ ./result
130 | [foo.example.com] Connecting to host...
131 | [foo.example.com] Copying closure to host...
132 | [foo.example.com] copying 3 paths...
133 | [foo.example.com] copying path '/nix/store/f1028ijc3c2654z8ikzd378ryp644h3f-system-units' to 'ssh://root@138.68.83.114'...
134 | [foo.example.com] copying path '/nix/store/9py44f4x9m83pr3j93c1fs95p0qy6175-etc' to 'ssh://root@138.68.83.114'...
135 | [foo.example.com] copying path '/nix/store/8hbnksxrhgwpmia833xp8191a5yxw8ii-nixos-system-test-20.03pre-git' to 'ssh://root@138.68.83.114'...
136 | [foo.example.com] Triggering system switcher...
137 | [foo.example.com] Trying to confirm success...
138 | [foo.example.com] Successfully activated new system!
139 | ```
140 |
--------------------------------------------------------------------------------
/build.nix:
--------------------------------------------------------------------------------
1 | defaults:
2 | {
3 | nixpkgs ? defaults.nixpkgs,
4 | deploySystem ? defaults.deploySystem,
5 | libOverlay ? null,
6 | specialArgs ? { },
7 | }:
8 | let
9 | extendLib = lib:
10 | let
11 | libOverlays = [
12 | (import ./dag.nix)
13 | (import ./ip.nix)
14 | ] ++ lib.optional (libOverlay != null) libOverlay;
15 | combinedLibOverlay = lib.foldl' lib.composeExtensions (self: super: {}) libOverlays;
16 | in lib.extend combinedLibOverlay;
17 |
18 | nixusPkgs = import nixpkgs {
19 | config = {};
20 | overlays = [
21 | (self: super: {
22 | lib = extendLib super.lib;
23 | })
24 | ];
25 | system = deploySystem;
26 | };
27 | in
28 | conf:
29 | let
30 | result = nixusPkgs.lib.evalModules {
31 | modules = [
32 | modules/options.nix
33 | modules/deploy.nix
34 | modules/secrets.nix
35 | modules/ssh.nix
36 | modules/public-ip.nix
37 | modules/dns.nix
38 | modules/vpn
39 | conf
40 | # Not naming it pkgs to avoid confusion and trouble for overriding scopes
41 | {
42 | _module.args.nixus = {
43 | pkgs = nixusPkgs;
44 | inherit extendLib;
45 | };
46 | _module.args.pkgs = throw "You're trying to access the pkgs argument from a Nixus module, use the nixus argument instead and use nixus.pkgs from that.";
47 | }
48 | ];
49 | inherit specialArgs;
50 | };
51 | in
52 | result.config.deployScript
53 | # Since https://github.com/NixOS/nixpkgs/pull/143207, the evalModules result contains a `type` attribute,
54 | # which if we don't remove it here would override the `type = "derivation"` from the above derivation
55 | # which is used by Nix to determine whether it should build the toplevel derivation or recurse
56 | # If we don't remove it, Nix would therefore recurse into this resulting attribute set
57 | // removeAttrs result [ "type" ]
58 | // nixusPkgs.lib.mapAttrs (n: v: v.deployScript) result.config.nodes
59 |
--------------------------------------------------------------------------------
/dag.nix:
--------------------------------------------------------------------------------
1 | # Adjusted from https://gitlab.com/rycee/nur-expressions/blob/b34e2e548da574c7bd4da14d1779c95b62349a3a/lib/dag.nix (MIT)
2 |
3 | # A generalization of Nixpkgs's `strings-with-deps.nix`.
4 | #
5 | # The main differences from the Nixpkgs version are
6 | #
7 | # - not specific to strings, i.e., any payload is OK,
8 | #
9 | # - the addition of the function `entryBefore` indicating a
10 | # "wanted by" relationship.
11 |
12 | self: super: with self; {
13 |
14 | types = super.types // {
15 |
16 | dagOf = subType: types.attrsOf (types.submodule {
17 | options = {
18 | data = mkOption {
19 | type = subType;
20 | };
21 |
22 | before = mkOption {
23 | type = types.listOf types.str;
24 | default = [];
25 | };
26 |
27 | after = mkOption {
28 | type = types.listOf types.str;
29 | default = [];
30 | };
31 | };
32 | });
33 |
34 | };
35 |
36 | dag = {
37 |
38 | # Takes an attribute set containing entries built by
39 | # entryAnywhere, entryAfter, and entryBefore to a
40 | # topologically sorted list of entries.
41 | #
42 | # Internally this function uses the `toposort` function in
43 | # `` and its value is accordingly.
44 | #
45 | # Specifically, the result on success is
46 | #
47 | # { result = [{name = ?; data = ?;} …] }
48 | #
49 | # For example
50 | #
51 | # nix-repl> topoSort {
52 | # a = entryAnywhere "1";
53 | # b = entryAfter ["a" "c"] "2";
54 | # c = entryBefore ["d"] "3";
55 | # d = entryBefore ["e"] "4";
56 | # e = entryAnywhere "5";
57 | # } == {
58 | # result = [
59 | # { data = "1"; name = "a"; }
60 | # { data = "3"; name = "c"; }
61 | # { data = "2"; name = "b"; }
62 | # { data = "4"; name = "d"; }
63 | # { data = "5"; name = "e"; }
64 | # ];
65 | # }
66 | # true
67 | #
68 | # And the result on error is
69 | #
70 | # {
71 | # cycle = [ {after = ?; name = ?; data = ?} … ];
72 | # loops = [ {after = ?; name = ?; data = ?} … ];
73 | # }
74 | #
75 | # For example
76 | #
77 | # nix-repl> topoSort {
78 | # a = entryAnywhere "1";
79 | # b = entryAfter ["a" "c"] "2";
80 | # c = entryAfter ["d"] "3";
81 | # d = entryAfter ["b"] "4";
82 | # e = entryAnywhere "5";
83 | # } == {
84 | # cycle = [
85 | # { after = ["a" "c"]; data = "2"; name = "b"; }
86 | # { after = ["d"]; data = "3"; name = "c"; }
87 | # { after = ["b"]; data = "4"; name = "d"; }
88 | # ];
89 | # loops = [
90 | # { after = ["a" "c"]; data = "2"; name = "b"; }
91 | # ];
92 | # } == {}
93 | # true
94 | topoSort = dag:
95 | let
96 | dagBefore = dag: name:
97 | mapAttrsToList (n: v: n) (
98 | filterAttrs (n: v: any (a: a == name) v.before) dag
99 | );
100 | normalizedDag =
101 | mapAttrs (n: v: {
102 | name = n;
103 | data = v.data;
104 | after = v.after ++ dagBefore dag n;
105 | }) dag;
106 | before = a: b: any (c: a.name == c) b.after;
107 | sorted = toposort before (mapAttrsToList (n: v: v) normalizedDag);
108 | in
109 | if sorted ? result then
110 | { result = map (v: { inherit (v) name data; }) sorted.result; }
111 | else
112 | sorted;
113 |
114 | # Create a DAG entry with no particular dependency information.
115 | entryAnywhere = data: {
116 | inherit data;
117 | before = [];
118 | after = [];
119 | };
120 |
121 | # Ordering of after and before flipped from the original
122 | entryBetween = after: before: data: {
123 | inherit data before after;
124 | };
125 |
126 | entryAfter = after: data: {
127 | inherit data after;
128 | before = [];
129 | };
130 |
131 | entryBefore = before: data: {
132 | inherit data before;
133 | after = [];
134 | };
135 | };
136 | }
137 |
--------------------------------------------------------------------------------
/default.nix:
--------------------------------------------------------------------------------
1 | import ./build.nix {
2 | nixpkgs =
3 | let
4 | nixpkgsInfo = (builtins.fromJSON (builtins.readFile ./flake.lock)).nodes.nixpkgs.locked;
5 | in
6 | fetchTarball {
7 | url = "https://github.com/NixOS/nixpkgs/archive/${nixpkgsInfo.rev}.tar.gz";
8 | sha256 = nixpkgsInfo.narHash;
9 | };
10 | deploySystem = builtins.currentSystem;
11 | }
12 |
--------------------------------------------------------------------------------
/example/configuration.nix:
--------------------------------------------------------------------------------
1 | { lib, pkgs, config, unstable, ... }: {
2 |
3 | imports = [
4 | ./hardware-configuration.nix
5 | (unstable + "/nixos/modules/services/video/photonvision.nix")
6 | ];
7 |
8 | boot.loader.timeout = 10;
9 | boot.loader.grub.device = "/dev/vda";
10 | boot.kernelPackages = pkgs.linuxPackages_latest;
11 |
12 | networking = {
13 | useDHCP = false;
14 | nameservers = [ "1.1.1.1" "1.0.0.1" ];
15 | defaultGateway = "138.68.80.1";
16 | usePredictableInterfaceNames = false;
17 | interfaces.eth0 = {
18 | ipv4.addresses = [{
19 | address = "138.68.83.114";
20 | prefixLength = 20;
21 | }];
22 | };
23 | };
24 |
25 | services.openssh.enable = true;
26 | users.users.root.openssh.authorizedKeys.keys = [
27 | "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHjY4cuUk4IWgBgnEJSULkIHO+njUmIFP+WSWy7IobBs infinisil@vario"
28 | ];
29 |
30 | users.users.bob.group = "users";
31 | users.users.bob.isNormalUser = true;
32 |
33 | secrets.files.foo.file = ./secret;
34 | secrets.files.foo.user = "bob";
35 | environment.etc.foo.source = config.secrets.files.foo.file;
36 |
37 | system.stateVersion = "19.09";
38 | }
39 |
--------------------------------------------------------------------------------
/example/default.nix:
--------------------------------------------------------------------------------
1 | import ../. {} ./deploy.nix
2 |
--------------------------------------------------------------------------------
/example/deploy.nix:
--------------------------------------------------------------------------------
1 | { config, lib, ... }: {
2 |
3 | options.defaults = lib.mkOption {
4 | type = lib.types.submodule {
5 | options.configuration = lib.mkOption {
6 | type = lib.types.submoduleWith {
7 | specialArgs.unstable = fetchTarball "channel:nixpkgs-unstable";
8 | modules = [];
9 | };
10 | };
11 | };
12 | };
13 |
14 | config = {
15 | defaults = { lib, name, ... }: {
16 | configuration = {
17 | networking.hostName = lib.mkDefault name;
18 | };
19 |
20 | # Which nixpkgs version we want to use for this node
21 | nixpkgs = lib.mkDefault (fetchTarball {
22 | url = "https://github.com/NixOS/nixpkgs/tarball/81cef6b70fb5d5cdba5a0fef3f714c2dadaf0d6d";
23 | sha256 = "1mj9psy1hfy3fbalwkdlyw3jmc97sl9g3xj1xh8dmhl68g0pfjin";
24 | });
25 | };
26 |
27 | nodes.foo = { lib, config, ... }: {
28 | # How to reach this node
29 | host = "root@172.20.83.114";
30 |
31 | # What configuration it should have
32 | configuration = ./configuration.nix;
33 | };
34 |
35 | nodes.legacyNixpkgs = { lib, config, ... }: {
36 | # How to reach this node
37 | host = "root@172.20.83.115";
38 |
39 | nixpkgs = fetchTarball {
40 | url = "https://github.com/NixOS/nixpkgs/tarball/38431cf21c59a84c0ddedccc0cd66540a550ec26";
41 | sha256 = "0bi5lkq2a34pij00axsa0l0j43y8688mf41p51b6zyfdzgjgsc42";
42 | };
43 |
44 | # What configuration it should have
45 | configuration = ./configuration.nix;
46 | };
47 | };
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/example/hardware-configuration.nix:
--------------------------------------------------------------------------------
1 | # Do not modify this file! It was generated by ‘nixos-generate-config’
2 | # and may be overwritten by future invocations. Please make changes
3 | # to /etc/nixos/configuration.nix instead.
4 | { modulesPath, config, lib, pkgs, ... }:
5 |
6 | {
7 | imports =
8 | [ (modulesPath + "/profiles/qemu-guest.nix")
9 | ];
10 |
11 | boot.initrd.availableKernelModules = [ "ata_piix" "uhci_hcd" "virtio_pci" "virtio_blk" ];
12 | boot.initrd.kernelModules = [ ];
13 | boot.kernelModules = [ "kvm-intel" ];
14 | boot.extraModulePackages = [ ];
15 |
16 | fileSystems."/" =
17 | { device = "/dev/disk/by-uuid/48e3b830-ff84-4434-ac74-b57b2ca59842";
18 | fsType = "ext4";
19 | };
20 |
21 | fileSystems."/boot/efi" =
22 | { device = "/dev/disk/by-uuid/3EE0-2273";
23 | fsType = "vfat";
24 | };
25 |
26 | swapDevices = [ ];
27 |
28 | nix.maxJobs = lib.mkDefault 1;
29 | }
30 |
--------------------------------------------------------------------------------
/example/secret:
--------------------------------------------------------------------------------
1 | SECRET
2 |
--------------------------------------------------------------------------------
/flake.lock:
--------------------------------------------------------------------------------
1 | {
2 | "nodes": {
3 | "flake-utils": {
4 | "inputs": {
5 | "systems": "systems"
6 | },
7 | "locked": {
8 | "lastModified": 1710146030,
9 | "narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
10 | "owner": "numtide",
11 | "repo": "flake-utils",
12 | "rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
13 | "type": "github"
14 | },
15 | "original": {
16 | "owner": "numtide",
17 | "repo": "flake-utils",
18 | "type": "github"
19 | }
20 | },
21 | "nixpkgs": {
22 | "locked": {
23 | "lastModified": 1721497942,
24 | "narHash": "sha256-EDPL9qJfklXoowl3nEBmjDIqcvXKUZInt5n6CCc1Hn4=",
25 | "owner": "NixOS",
26 | "repo": "nixpkgs",
27 | "rev": "d43f0636fc9492e83be8bbb41f9595d7a87106b8",
28 | "type": "github"
29 | },
30 | "original": {
31 | "owner": "NixOS",
32 | "ref": "nixpkgs-unstable",
33 | "repo": "nixpkgs",
34 | "type": "github"
35 | }
36 | },
37 | "root": {
38 | "inputs": {
39 | "flake-utils": "flake-utils",
40 | "nixpkgs": "nixpkgs"
41 | }
42 | },
43 | "systems": {
44 | "locked": {
45 | "lastModified": 1681028828,
46 | "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
47 | "owner": "nix-systems",
48 | "repo": "default",
49 | "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
50 | "type": "github"
51 | },
52 | "original": {
53 | "owner": "nix-systems",
54 | "repo": "default",
55 | "type": "github"
56 | }
57 | }
58 | },
59 | "root": "root",
60 | "version": 7
61 | }
62 |
--------------------------------------------------------------------------------
/flake.nix:
--------------------------------------------------------------------------------
1 | {
2 | description = "Experimental deployment tool supporting multi-host abstractions";
3 |
4 | inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
5 | inputs.flake-utils.url = "github:numtide/flake-utils";
6 |
7 | outputs = { nixpkgs, flake-utils, self, ... }:
8 | {
9 | buildNixus = import ./build.nix {
10 | # Set the default nixpkgs argument, can be overridden with follows
11 | inherit nixpkgs;
12 | deploySystem = throw "buildNixus: The first argument needs to have the `deploySystem` attribute";
13 | };
14 | }
15 | // flake-utils.lib.eachDefaultSystem (system: {
16 |
17 | packages.example = self.buildNixus {
18 | deploySystem = system;
19 | } ./example/deploy.nix;
20 |
21 | });
22 | }
23 |
--------------------------------------------------------------------------------
/ip.nix:
--------------------------------------------------------------------------------
1 | final: prev: {
2 | ip = {
3 | parseIp = str: map final.toInt (builtins.match "([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)" str);
4 | prettyIp = final.concatMapStringsSep "." toString;
5 |
6 | cidrToMask =
7 | let
8 | # Generate a partial mask for an integer from 0 to 7
9 | # part 1 = 128
10 | # part 7 = 254
11 | part = n:
12 | if n == 0 then 0
13 | else part (n - 1) / 2 + 128;
14 | in cidr:
15 | let
16 | # How many initial parts of the mask are full (=255)
17 | fullParts = cidr / 8;
18 | in final.genList (i:
19 | # Fill up initial full parts
20 | if i < fullParts then 255
21 | # If we're above the first non-full part, fill with 0
22 | else if fullParts < i then 0
23 | # First non-full part generation
24 | else part (final.mod cidr 8)
25 | ) 4;
26 |
27 | parseSubnet = str:
28 | let
29 | splitParts = builtins.split "/" str;
30 | givenIp = final.ip.parseIp (final.elemAt splitParts 0);
31 | cidr = final.toInt (final.elemAt splitParts 2);
32 | mask = final.ip.cidrToMask cidr;
33 | baseIp = final.zipListsWith final.bitAnd givenIp mask;
34 | range = {
35 | from = baseIp;
36 | to = final.zipListsWith (b: m: 255 - m + b) baseIp mask;
37 | };
38 | check = ip: baseIp == final.zipListsWith (b: m: final.bitAnd b m) ip mask;
39 | warn = if baseIp == givenIp then final.id else final.warn
40 | ( "subnet ${str} has a too specific base address ${final.ip.prettyIp givenIp}, "
41 | + "which will get masked to ${final.ip.prettyIp baseIp}, which should be used instead");
42 | in warn {
43 | inherit baseIp cidr mask range check;
44 | subnet = "${final.ip.prettyIp baseIp}/${toString cidr}";
45 | };
46 | };
47 | }
48 |
--------------------------------------------------------------------------------
/modules/deploy.nix:
--------------------------------------------------------------------------------
1 | { nixus, lib, config, extendModules, ... }:
2 | let
3 | inherit (lib) types;
4 |
5 | globalConfig = config;
6 |
7 | nodeOptions = { name, pkgs, config, ... }: let nodeName = name; in {
8 | options = {
9 | enable = lib.mkOption {
10 | type = types.bool;
11 | default = true;
12 | description = ''
13 | Whether this node should be deployed
14 | '';
15 | };
16 |
17 | preparationPhases = lib.mkOption {
18 | type = types.dagOf types.lines;
19 | default = {};
20 | };
21 |
22 | preparationScript = lib.mkOption {
23 | type = types.package;
24 | };
25 |
26 | successTimeout = lib.mkOption {
27 | type = types.ints.unsigned;
28 | default = 20;
29 | description = ''
30 | How many seconds remote hosts should wait for the success
31 | confirmation before rolling back.
32 | '';
33 | };
34 |
35 | switchTimeout = lib.mkOption {
36 | type = types.ints.unsigned;
37 | default = 60;
38 | description = ''
39 | How many seconds remote hosts should wait for the system activation
40 | command to finish before considering it failed.
41 | '';
42 | };
43 |
44 | ignoreFailingSystemdUnits = lib.mkOption {
45 | type = types.bool;
46 | default = false;
47 | description = ''
48 | Whether a system activation should be considered successful despite
49 | failing systemd units.
50 | '';
51 | };
52 |
53 | deployFrom = lib.mkOption {
54 | description = ''
55 | When deploying from a specific hostname given by the `deployHost` option,
56 | the node should be connected to using the values specified here.
57 |
58 | This can be used to e.g. indicate that two machines are in the same network,
59 | so they can deploy to each other using their network-local addresses.
60 | '';
61 | example = {
62 | someDeployHost.host = "172.18.67.46";
63 | someDeployHost.hasFastConnection = true;
64 | };
65 | type = lib.types.attrsOf (lib.types.submodule ({ name, ... }: {
66 |
67 | # TODO: What about different ssh ports? Some access abstraction perhaps?
68 | options.host = lib.mkOption {
69 | type = lib.types.str;
70 | example = "root@172.18.67.46";
71 | description = ''
72 | How to reach the host via ssh. The username must either be root,
73 | or a user that is allowed to do passwordless privilege escalation.
74 | If no username is given, the one that runs the deploy script
75 | is used.
76 | '';
77 | };
78 |
79 | # TODO: Default to true when the address is link-local
80 | options.hasFastConnection = lib.mkOption {
81 | type = lib.types.bool;
82 | default = false;
83 | description = ''
84 | Whether there is a fast connection to this host. If true it will cause
85 | all derivations to be copied directly from the deployment host. If
86 | false, the substituters are used when possible instead.
87 | '';
88 | };
89 |
90 | }));
91 | default = {};
92 | };
93 |
94 | host = lib.mkOption {
95 | type = lib.types.str;
96 | example = "root@172.18.67.46";
97 | description = ''
98 | How to reach the host via ssh. The username must either be root,
99 | or a user that is allowed to do passwordless privilege escalation.
100 | If no username is given, the one that runs the deploy script
101 | is used.
102 | '';
103 | };
104 |
105 | hasFastConnection = lib.mkOption {
106 | type = lib.types.bool;
107 | default = false;
108 | description = ''
109 | Whether there is a fast connection to this host. If true it will cause
110 | all derivations to be copied directly from the deployment host. If
111 | false, the substituters are used when possible instead.
112 | '';
113 | };
114 |
115 | closurePaths = lib.mkOption {
116 | type = lib.types.attrsOf lib.types.package;
117 | default = {};
118 | description = ''
119 | Derivation paths to copy to the host while deploying
120 | '';
121 | };
122 |
123 | postDeployScript = lib.mkOption {
124 | type = lib.types.lines;
125 | description = ''
126 | Script to run after the deployment of this node, whether it was
127 | successful or not. The exit status of the deployment is available in
128 | the `$status` bash variable, which should be either "success" or
129 | "failure" (though it can sometimes be "unknown", that's currently a
130 | bug..)
131 | '';
132 | };
133 |
134 | deployScript = lib.mkOption {
135 | type = lib.types.package;
136 | readOnly = true;
137 | description = ''
138 | The script to deploy this single node. There's also a script to
139 | deploy all nodes, see the `deployScript` option.
140 | '';
141 | };
142 |
143 | };
144 |
145 | config = let
146 | nodeName = name;
147 | nodeConfig = config;
148 | switch = pkgs.runCommand "switch" {
149 | inherit (nodeConfig) switchTimeout successTimeout ignoreFailingSystemdUnits privilegeEscalationCommand;
150 | shell = pkgs.runtimeShell;
151 | } ''
152 | mkdir -p $out/bin
153 | substituteAll ${../scripts/switch} $out/bin/switch
154 | chmod +x $out/bin/switch
155 | '';
156 | system = nodeConfig.configuration.system.build.toplevel;
157 | in {
158 |
159 | # This value is more specific than a generic host, so it should override a host declared by the user with a default priority of 100
160 | # But it should also still allow the user to mkForce this value, which would be priority 50
161 | host = lib.mkIf (globalConfig.deployHost != null && nodeConfig.deployFrom ? ${globalConfig.deployHost})
162 | (lib.mkOverride 75 nodeConfig.deployFrom.${globalConfig.deployHost}.host);
163 |
164 | hasFastConnection = lib.mkIf (globalConfig.deployHost != null && nodeConfig.deployFrom ? ${globalConfig.deployHost})
165 | (lib.mkOverride 75 nodeConfig.deployFrom.${globalConfig.deployHost}.hasFastConnection);
166 |
167 | deployFrom.${nodeName} = {
168 | host = "root@localhost";
169 | hasFastConnection = true;
170 | };
171 |
172 | closurePaths = { inherit system switch; };
173 |
174 | deployScript = (extendModules {
175 | modules = [{
176 | defaults = { name, ... }: {
177 | enable = name == nodeName;
178 | };
179 | }];
180 | }).config.deployScript;
181 |
182 | # TOOD: Prevent garbage collection of closures until the end of the deploy
183 | preparationPhases.copyClosure = lib.dag.entryAnywhere ''
184 | if NIX_SSH_OPTS="-o ServerAliveInterval=15" nix-copy-closure \
185 | ${if nodeConfig.hasFastConnection then "-s" else ""} \
186 | --to ${lib.escapeShellArg nodeConfig.host} \
187 | ${lib.escapeShellArgs (lib.attrValues nodeConfig.closurePaths)}; then
188 | echo "Successfully copied closure"
189 | else
190 | echo -e "\e[31mFailed to copy closure\e[0m"
191 | exit 1
192 | fi
193 | '';
194 |
195 | preparationScript = let
196 | sortedScripts = (lib.dag.topoSort nodeConfig.preparationPhases).result or (throw "Dependency cycle between scripts in nodes.${nodeName}.preparationPhases");
197 | in nixus.pkgs.writeShellScript "prepare-${nodeName}"
198 | (lib.concatMapStringsSep "\n\n" ({ name, data }: ''
199 | # Phase ${name}
200 | ${data}
201 | '') sortedScripts);
202 |
203 | postDeployScript = lib.mkMerge [
204 | (lib.mkBefore ''
205 | case "$status" in
206 | "success")
207 | echo "Successfully activated new system!" >&2
208 | ;;
209 | "failure")
210 | echo -e "\e[31mFailed to activate new system! Rolled back to previous one\e[0m" >&2
211 | echo -e "\e[31mRun the following command to see the logs for the switch:\e[0m" >&2
212 | echo -e "\e[31mssh ''${HOST@Q} ${builtins.concatStringsSep " " config.privilegeEscalationCommand} cat /var/lib/system-switcher/system-$id/log\e[0m" >&2
213 | # TODO: Try to better show what failed
214 | ;;
215 | *)
216 | echo -e "\e[31mThis shouldn't occur, the status is $status!\e[0m" >&2
217 | ;;
218 | esac
219 | '')
220 | (lib.mkAfter ''
221 | if [[ "$status" != "success" ]]; then
222 | exit 1
223 | fi
224 | '')
225 | ];
226 |
227 | };
228 |
229 | };
230 |
231 | in {
232 |
233 | options = {
234 | defaults = lib.mkOption {
235 | type = lib.types.submodule nodeOptions;
236 | };
237 |
238 | deployHost = lib.mkOption {
239 | type = lib.types.nullOr lib.types.str;
240 | default = null;
241 | description = ''
242 | The hostname from which the deployment happens. The only effect this
243 | has is that it uses the `nodes..deployFrom` option to determine
244 | the deploy-host specific target host address. If `null`, no deploy-host
245 | specific addresses are used, and the `nodes..host` option has to
246 | be set.
247 | '';
248 | };
249 |
250 | deployScript = lib.mkOption {
251 | type = lib.types.package;
252 | readOnly = true;
253 | description = ''
254 | The script to deploy all enabled nodes (see the `nodes..enable`
255 | option). There's also scripts to deploy individual nodes under
256 | `nodes..deployScript`.
257 | '';
258 | };
259 | };
260 |
261 | # TODO: What about requiring either all nodes to succeed or all get rolled back?
262 | config.deployScript =
263 | let
264 | nodesToDeploy = lib.filterAttrs (nodeName: nodeConfig: nodeConfig.enable) globalConfig.nodes;
265 | in
266 | # TODO: Handle signals to kill the async command
267 | nixus.pkgs.writeScript "deploy" ''
268 | #!${nixus.pkgs.runtimeShell}
269 | set -euo pipefail
270 |
271 | export SHELLOPTS
272 |
273 | PATH=${lib.makeBinPath
274 | (with nixus.pkgs; [
275 | # Without bash being here deployments to localhost do not work. The
276 | # reason for that is not yet known. Reported in #6.
277 | bash
278 | coreutils
279 | findutils
280 | gnused
281 | jq
282 | openssh
283 | procps
284 | rsync
285 | ])}''${PATH:+:$PATH}
286 |
287 | # Kill all child processes when interrupting/exiting
288 | trap exit INT TERM
289 | trap 'for pid in $(jobs -p) ; do kill -- -$pid ; done' EXIT
290 | # Be sure to use --foreground for all timeouts, therwise a Ctrl-C won't stop them!
291 | # See https://unix.stackexchange.com/a/233685/214651
292 |
293 | echo "Preparing deployment of all nodes.." >&2
294 |
295 | ${lib.concatStringsSep "\n" (lib.mapAttrsToList (nodeName: nodeConfig:
296 | ''
297 | {
298 | exec > >(sed "s/^/[prep ${nodeName}] /")
299 | exec 2> >(sed "s/^/[prep ${nodeName}] /" >&2)
300 |
301 | HOST=${lib.escapeShellArg nodeConfig.host}
302 |
303 | echo "Preparing deployment.." >&2
304 |
305 | . ${nodeConfig.preparationScript}
306 | } &
307 | '') nodesToDeploy)}
308 |
309 | failedCount=0
310 | while true; do
311 | if wait -n; then
312 | :
313 | else
314 | status=$?
315 | if [[ "$status" -eq 127 ]]; then
316 | break
317 | else
318 | ((++failedCount))
319 | fi
320 | fi
321 | done
322 |
323 | if (( "$failedCount" > 0 )); then
324 | echo -e "\e[31mFailed to prepare $failedCount nodes\e[0m" >&2
325 | exit 1
326 | fi
327 |
328 | echo "Successfully prepared all nodes, now deploying.." >&2
329 |
330 | ${lib.concatStringsSep "\n" (lib.mapAttrsToList (nodeName: nodeConfig: ''
331 | {
332 | exec > >(sed "s/^/[deploy ${nodeName}] /")
333 | exec 2> >(sed "s/^/[deploy ${nodeName}] /" >&2)
334 |
335 | HOST=${lib.escapeShellArg nodeConfig.host}
336 |
337 | echo "Deploying.." >&2
338 |
339 | echo "Triggering system switcher..." >&2
340 | id=$(ssh "$HOST" exec "${nodeConfig.closurePaths.switch}/bin/switch" start "${nodeConfig.closurePaths.system}")
341 |
342 | echo "Trying to confirm success..." >&2
343 | active=1
344 | while [ "$active" != 0 ]; do
345 | # TODO: Because of the imperative network-setup script, when e.g. the
346 | # defaultGateway is removed, the previous entry is still persisted on
347 | # a rebuild switch, even though with a reboot it wouldn't. Maybe use
348 | # the more modern and declarative networkd to get around this
349 | set +e
350 | status=$(timeout --foreground 15 ssh -o ControlPath=none "$HOST" exec "${nodeConfig.closurePaths.switch}/bin/switch" active "$id")
351 | active=$?
352 | set -e
353 | sleep 1
354 | done
355 |
356 | ${nodeConfig.postDeployScript}
357 |
358 | } &
359 | '') nodesToDeploy)}
360 |
361 | failedCount=0
362 | while true; do
363 | if wait -n; then
364 | :
365 | else
366 | status=$?
367 | if [[ "$status" -eq 127 ]]; then
368 | break
369 | else
370 | ((++failedCount))
371 | fi
372 | fi
373 | done
374 |
375 | if (( "$failedCount" > 0 )); then
376 | echo -e "\e[31mFailed to deploy $failedCount nodes\e[0m" >&2
377 | exit 1
378 | fi
379 |
380 | echo "Successfully deployed all nodes" >&2
381 | '';
382 |
383 | }
384 |
--------------------------------------------------------------------------------
/modules/dns.nix:
--------------------------------------------------------------------------------
1 | { lib, nixus, config, ... }:
2 | let
3 | inherit (lib) types;
4 |
5 | cfg = config.dns;
6 |
7 | recordTypes = {
8 | A = {
9 | options.address = lib.mkOption {
10 | type = types.str;
11 | };
12 | stringCoerce = s: { address = s; };
13 | toData = v: v.address;
14 | };
15 | AAAA = {
16 | options.address = lib.mkOption {
17 | type = types.str;
18 | };
19 | stringCoerce = s: { address = s; };
20 | toData = v: v.address;
21 | };
22 | NS = {
23 | options.domain = lib.mkOption {
24 | type = types.str;
25 | };
26 | stringCoerce = s: { domain = s; };
27 | toData = v: v.domain;
28 | };
29 | CNAME = {
30 | options.domain = lib.mkOption {
31 | type = types.str;
32 | };
33 | stringCoerce = s: { domain = s; };
34 | toData = v: v.domain;
35 | };
36 | CAA = {
37 | options.flags.issuerCritical = lib.mkOption {
38 | type = types.bool;
39 | default = false;
40 | };
41 | options.tag = lib.mkOption {
42 | type = types.enum [ "issue" "issuewild" "iodef" ];
43 | };
44 | options.value = lib.mkOption {
45 | type = types.str;
46 | };
47 |
48 | stringCoerce = s: { tag = "issue"; value = s; };
49 | toData = v: "${if v.flags.issuerCritical then "128" else "0"} ${v.tag} \"${lib.escape [ "\"" ] v.value}\"";
50 | };
51 | MX = {
52 | options.preference = lib.mkOption {
53 | type = types.int;
54 | default = 10;
55 | };
56 |
57 | options.domain = lib.mkOption {
58 | type = types.str;
59 | };
60 |
61 | stringCoerce = s: { domain = s; };
62 | toData = v: "${toString v.preference} ${v.domain}";
63 | };
64 | TXT = {
65 | options.text = lib.mkOption {
66 | type = types.str;
67 | };
68 |
69 | stringCoerce = s: { text = s; };
70 | toData = v: "\"${lib.escape [ "\"" ] v.text}\"";
71 | };
72 | SRV = {
73 | options.priority = lib.mkOption {
74 | type = types.int;
75 | default = 0;
76 | };
77 | options.weight = lib.mkOption {
78 | type = types.int;
79 | default = 100;
80 | };
81 | options.port = lib.mkOption {
82 | type = types.port;
83 | };
84 | options.target = lib.mkOption {
85 | type = types.str;
86 | };
87 | toData = v: "${toString v.priority} ${toString v.weight} ${toString v.port} ${v.target}";
88 | };
89 | };
90 |
91 | /*
92 | {
93 | "com" = {
94 | "infinisil" = {
95 | _zone = "infinisil.com";
96 | "sub" = {
97 | _zone = "sub.infinisil.com";
98 | };
99 | };
100 | };
101 | }
102 | */
103 | zones =
104 | let
105 | zoneAttr = zone: lib.setAttrByPath (lib.reverseList (lib.splitString "." zone)) { _zone = zone; };
106 | result = lib.foldl' (a: e: lib.recursiveUpdate a (zoneAttr e)) {} (lib.attrNames cfg.zones);
107 | in result;
108 |
109 | getZone = domain:
110 | assert lib.hasSuffix "." domain;
111 | let
112 | go = zones: path:
113 | if path != [] && zones ? ${lib.head path} then go zones.${lib.head path} (lib.tail path)
114 | else zones._zone or null;
115 | elements = lib.reverseList (lib.init (lib.splitString "." domain));
116 | in go zones elements;
117 |
118 | recordSubmodule = { name, ... }: let zone = getZone name; in {
119 | options = lib.mapAttrs (_: value:
120 | let
121 | module = types.submodule ({ options, config, ... }: {
122 | options = value.options // {
123 | ttl = lib.mkOption {
124 | type = types.int;
125 | };
126 |
127 | zone = lib.mkOption {
128 | type = types.str;
129 | };
130 | };
131 |
132 | config.zone = lib.mkIf (zone != null) (lib.mkDefault zone);
133 | config.ttl = lib.mkIf options.zone.isDefined (lib.mkDefault cfg.zones.${config.zone}.ttl);
134 | });
135 | type =
136 | if value ? stringCoerce then
137 | with types; coercedTo (either str attrs) lib.singleton (listOf (coercedTo str value.stringCoerce module))
138 | else
139 | with types; coercedTo attrs lib.singleton (listOf module);
140 | in lib.mkOption {
141 | type = type;
142 | default = [];
143 | }
144 | ) recordTypes;
145 | };
146 |
147 | recordList = lib.concatLists (lib.mapAttrsToList (name: types:
148 | lib.concatLists (lib.mapAttrsToList (type: records:
149 | # TODO: Maybe remove duplicates?
150 | map (record: {
151 | inherit name type;
152 | inherit (record) ttl zone;
153 | data = recordTypes.${type}.toData record;
154 | }) records
155 | ) types)
156 | ) cfg.records);
157 |
158 | recordsByZone = lib.mapAttrs (_: map (record: removeAttrs record [ "zone" ]))
159 | (lib.groupBy (record: record.zone) recordList);
160 |
161 | soaRecord = zoneCfg:
162 | let
163 | inherit (zoneCfg) soa;
164 | serial = if soa.serial == null then "@NIXUS_ZONE_SERIAL@" else toString soa.serial;
165 | in {
166 | name = zoneCfg.name + ".";
167 | type = "SOA";
168 | ttl = soa.ttl;
169 | # TODO: Email escaping and transforming
170 | data = "${soa.master} ${soa.email} ${serial} ${toString soa.refresh} ${toString soa.retry} ${toString soa.expire} ${toString soa.negativeTtl}";
171 | };
172 |
173 |
174 | nodeConfigs = lib.mapAttrs (node: zones: {
175 | configuration = {
176 | networking.firewall.allowedUDPPorts = [ 53 ];
177 | services.bind = {
178 | enable = true;
179 | zones = lib.listToAttrs (lib.forEach zones (zone: lib.nameValuePair zone.name {
180 | master = true;
181 | file = zone.zonefile;
182 | }));
183 | };
184 | };
185 |
186 | }) (lib.groupBy (z: z.primaryNode) (lib.attrValues cfg.zones));
187 |
188 | in {
189 |
190 | # Records that automatically get set to the appropriate zone
191 | options.dns.records = lib.mkOption {
192 | type = types.attrsOf (types.submodule recordSubmodule);
193 | default = {};
194 | };
195 |
196 | options.dns.zones = lib.mkOption {
197 | default = {};
198 | type = types.attrsOf (types.submodule ({ name, config, ... }: {
199 | options.name = lib.mkOption {
200 | type = types.str;
201 | default = name;
202 | };
203 |
204 | options.primaryNode = lib.mkOption {
205 | type = types.str;
206 | description = ''
207 | Nixus node for the primary server
208 | '';
209 | };
210 |
211 | options.ttl = lib.mkOption {
212 | type = types.int;
213 | description = ''
214 | The TTL to use for records in this zone if the records themselves don't specify it.
215 | '';
216 | };
217 |
218 | options.records = lib.mkOption {
219 | type = types.listOf (types.submodule {
220 | options.name = lib.mkOption {
221 | type = types.str;
222 | description = "Record owner name";
223 | };
224 | options.type = lib.mkOption {
225 | type = types.str;
226 | description = "Record type";
227 | };
228 | options.ttl = lib.mkOption {
229 | type = types.int;
230 | description = "Record TTL";
231 | };
232 | options.data = lib.mkOption {
233 | type = types.str;
234 | description = "Record data";
235 | };
236 | });
237 | default = [ (soaRecord config) ] ++ recordsByZone.${config.name};
238 | };
239 |
240 | options.zonefile = lib.mkOption {
241 | type = types.path;
242 | default = nixus.pkgs.runCommand "${config.name}.zone" {
243 | contents = lib.concatMapStrings (record:
244 | "${record.name} ${toString record.ttl} IN ${record.type} ${record.data}\n"
245 | ) config.records;
246 | passAsFile = [ "contents" ];
247 | } ''
248 | substitute "$contentsPath" "$out" --subst-var-by NIXUS_ZONE_SERIAL "$(date +%s)"
249 | ${lib.getBin nixus.pkgs.bind}/bin/named-checkzone ${lib.escapeShellArg config.name} "$out"
250 | '';
251 | };
252 |
253 | options.soa = {
254 |
255 | ttl = lib.mkOption {
256 | type = types.int;
257 | description = "TTL of the SOA record itself.";
258 | };
259 |
260 | master = lib.mkOption {
261 | type = types.str;
262 | description = "The primary master name server for this zone.";
263 | };
264 |
265 | email = lib.mkOption {
266 | type = types.str;
267 | description = "Email address of the person responsible for this zone.";
268 | };
269 |
270 | # TODO: Don't require these 4 fields unless there are secondary servers
271 | serial = lib.mkOption {
272 | type = types.nullOr types.int;
273 | default = null;
274 | description = "Serial number for this zone. Should be updated if any records change so that secondary servers are refreshed. Null indicates a serial number automatically generated from the current unix epoch.";
275 | };
276 |
277 | refresh = lib.mkOption {
278 | type = types.int;
279 | description = "Number of seconds after which secondary name servers should query the master for the SOA record, to detect zone changes";
280 | };
281 |
282 | retry = lib.mkOption {
283 | type = types.int;
284 | description = "Number of seconds after which secondary name servers should retry to request the serial number from the master if the master does not respond.";
285 | };
286 |
287 | expire = lib.mkOption {
288 | type = types.int;
289 | description = "Number of seconds after which secondary name servers should stop answering request for this zone if the master does not respond.";
290 | };
291 |
292 | negativeTtl = lib.mkOption {
293 | type = types.int;
294 | description = "How long negative responses should be cached for.";
295 | };
296 | };
297 |
298 | config.soa.ttl = lib.mkDefault config.ttl;
299 | }));
300 | };
301 |
302 | config.nodes = nodeConfigs;
303 | }
304 |
--------------------------------------------------------------------------------
/modules/options.nix:
--------------------------------------------------------------------------------
1 | { nixus, options, config, lib, ... }:
2 | let
3 | inherit (lib) types;
4 |
5 | extraConfig = { pkgs, lib, config, ... }: {
6 | # Export the pkgs arg because we use it outside the module
7 | # See https://github.com/NixOS/nixpkgs/pull/82751 why that's necessary
8 | options._pkgs = lib.mkOption {
9 | readOnly = true;
10 | internal = true;
11 | default = pkgs;
12 | };
13 |
14 | config.systemd.services = lib.mkIf (!config.services.openssh.startWhenNeeded) {
15 | # By default the sshd service doesn't stop when changed so you don't lose connection to it when misconfigured
16 | # But in Nixus we want to detect a misconfiguration since we can rollback in that case
17 | sshd.stopIfChanged = lib.mkForce true;
18 | };
19 | };
20 |
21 | # Legacy, relies on NixOS internals, makes nixus work with nixpkgs versions
22 | # before https://github.com/NixOS/nixpkgs/pull/143207
23 | pkgsModule = nixpkgs: { lib, config, ... }: {
24 | config.nixpkgs.system = lib.mkDefault nixus.pkgs.system;
25 | # Not using nixpkgs.pkgs because that would apply the overlays again
26 | config._module.args.pkgs = lib.mkDefault (import nixpkgs {
27 | inherit (config.nixpkgs) config overlays localSystem crossSystem;
28 | });
29 | };
30 |
31 | topconfig = config;
32 |
33 | nodeOptions = { name, config, ... }: {
34 |
35 | options = {
36 |
37 | nixpkgs = lib.mkOption {
38 | type = lib.types.path;
39 | example = lib.literalExample ''
40 | fetchTarball {
41 | url = "https://github.com/NixOS/nixpkgs/tarball/a06925d8c608d7ba1d4297dc996c187c37c6b7e9";
42 | sha256 = "0xy6rimd300j5bdqmzizs6l71x1n06pfimbim1952fyjk8a3q4pr";
43 | }
44 | '';
45 | description = ''
46 | The path to the nixpkgs version to use for this host.
47 | '';
48 | };
49 |
50 | configuration = lib.mkOption {
51 | type =
52 | let
53 | baseModules = import (config.nixpkgs + "/nixos/modules/module-list.nix");
54 | legacy = types.submoduleWith {
55 | specialArgs = {
56 | lib = nixus.extendLib (import (config.nixpkgs + "/lib"));
57 | nodes = lib.mapAttrs (name: value: value.configuration) topconfig.nodes;
58 | inherit name baseModules;
59 | modulesPath = config.nixpkgs + "/nixos/modules";
60 | };
61 | modules = baseModules ++ [ (pkgsModule config.nixpkgs) extraConfig ];
62 | };
63 | evalConfig = import (config.nixpkgs + "/nixos/lib/eval-config.nix") {
64 | system = nixus.pkgs.system;
65 | specialArgs.lib = nixus.extendLib (import (config.nixpkgs + "/lib"));
66 | modules = [
67 | extraConfig
68 | {
69 | _module.args = {
70 | nodes = lib.mapAttrs (name: value: value.configuration) topconfig.nodes;
71 | inherit name;
72 | };
73 | }
74 | ];
75 | };
76 | in evalConfig.type or legacy;
77 | default = {};
78 | example = lib.literalExample ''
79 | {
80 | imports = [ ./hardware-configuration.nix ];
81 | boot.loader.grub.device = "/dev/sda";
82 | networking.hostName = "test";
83 | }
84 | '';
85 | description = ''
86 | The NixOS configuration for this host.
87 | '';
88 | };
89 |
90 | privilegeEscalationCommand = lib.mkOption {
91 | type = types.listOf types.str;
92 | default = [ "sudo" ];
93 | example = lib.literalExample ''[ "doas" ]'';
94 | description = ''
95 | The command to use for privilege escalation.
96 | '';
97 | };
98 |
99 | };
100 |
101 | config = {
102 | _module.args.pkgs = config.configuration._pkgs;
103 | };
104 | };
105 |
106 | in {
107 |
108 | options = {
109 | defaults = lib.mkOption {
110 | type = lib.types.submodule nodeOptions;
111 | example = lib.literalExample ''
112 | { name, ... }: {
113 | networking.hostName = name;
114 | }
115 | '';
116 | description = ''
117 | Configuration to apply to all nodes.
118 | '';
119 | };
120 |
121 | nodes = lib.mkOption {
122 | type = lib.types.attrsOf (lib.types.submodule (options.defaults.type.functor.payload.modules ++ options.defaults.definitions));
123 | description = "nodes";
124 | };
125 |
126 | };
127 | }
128 |
--------------------------------------------------------------------------------
/modules/public-ip.nix:
--------------------------------------------------------------------------------
1 | { lib, ... }:
2 | let
3 | inherit (lib) types;
4 | in {
5 |
6 | options.defaults = lib.mkOption {
7 | type = types.submodule {
8 | options.configuration = lib.mkOption {
9 | type = types.submoduleWith {
10 | modules = [({ options, ... }: {
11 | options.networking.public = {
12 |
13 | ipv4 = lib.mkOption {
14 | type = types.str;
15 | description = "Default public IPv4 address.";
16 | };
17 | hasIpv4 = lib.mkOption {
18 | type = types.bool;
19 | readOnly = true;
20 | default = options.networking.public.ipv4.isDefined;
21 | description = "Whether this node has a public ipv4 address.";
22 | };
23 |
24 | ipv6 = lib.mkOption {
25 | type = types.str;
26 | description = "Default public IPv6 address.";
27 | };
28 | hasIpv6 = lib.mkOption {
29 | type = types.bool;
30 | readOnly = true;
31 | default = options.networking.public.ipv6.isDefined;
32 | description = "Whether this node has a public ipv6 address.";
33 | };
34 |
35 | };
36 | })];
37 | };
38 | };
39 | };
40 | };
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/modules/secrets.nix:
--------------------------------------------------------------------------------
1 | { lib, config, options, ... }:
2 | let
3 | inherit (lib) types;
4 | # Ideas (inspiration nixops):
5 | # - Add systemd units for each key
6 | # - persistent/non-persistent keys, send keys after reboot
7 |
8 | # Abstract where the secret is gotten from (different hosts, not only localhost, different commands, not just files)
9 |
10 | secretType = pkgs: baseDir: { name, config, ... }: {
11 | options = {
12 | file = lib.mkOption {
13 | type = types.path;
14 | apply = indirectSecret pkgs baseDir config name;
15 | };
16 | # TODO: Ensure user and group exists at eval time
17 | user = lib.mkOption {
18 | type = types.nullOr types.str;
19 | default = null;
20 | description = ''
21 | The owning user of the secret. If this is set, only that user can
22 | access the secret. Mutually exclusive with setting a group.
23 | By default, root is the owning user.
24 | '';
25 | };
26 | group = lib.mkOption {
27 | type = types.nullOr types.str;
28 | default = null;
29 | description = ''
30 | The owning group of the secret. If this is set, only that group can
31 | access the secret. Mutually exclusive with setting a user.
32 | By default, root is the owning user.
33 | '';
34 | };
35 | };
36 | };
37 |
38 | # Takes a file path and turns it into a derivation
39 | indirectSecret = pkgs: baseDir: config: name: file: pkgs.runCommand "secret-${name}" {
40 | # To find out which file to copy. toString to not import the secret into
41 | # the store
42 | file = toString file;
43 |
44 | # We make this derivation dependent on the secret itself, such that a
45 | # change of it causes a rebuild
46 | secretHash = builtins.hashFile "sha512" file;
47 | } (
48 | let
49 | validSecret = (config.user == null) || (config.group == null);
50 | subdir = if config.group == null
51 | then "per-user/${if config.user == null then "root" else config.user}"
52 | else "per-group/${config.group}";
53 | target = if validSecret
54 | then "${baseDir}/active/${subdir}/${name}"
55 | else throw "nixus: secret.${name} can't have both a user and a group set";
56 | in ''
57 | ln -s ${lib.escapeShellArg target} "$out"
58 | '');
59 |
60 | # Intersects the closure of a system with a set of secrets
61 | requiredSecrets = pkgs: { system, secrets }: pkgs.stdenv.mkDerivation {
62 | name = "required-secrets";
63 |
64 | __structuredAttrs = true;
65 | preferLocalBuild = true;
66 |
67 | exportReferencesGraph.system = system;
68 | secrets = lib.mapAttrsToList (name: value: {
69 | inherit name;
70 | path = value.file;
71 | source = value.file.file;
72 | hash = value.file.secretHash;
73 | user = if value.group == null && value.user == null then "root" else value.user;
74 | inherit (value) group;
75 | }) secrets;
76 |
77 | PATH = lib.makeBinPath [pkgs.buildPackages.jq];
78 |
79 | builder =
80 | let
81 | jqFilter = builtins.toFile "jq-filter" ''
82 | [.system[].path] as $system
83 | | .secrets[]
84 | | select(.path == $system[])
85 | '';
86 | in builtins.toFile "builder" ''
87 | source .attrs.sh
88 | jq -r -c -f ${jqFilter} .attrs.json > ''${outputs[out]}
89 | '';
90 | };
91 |
92 | in {
93 |
94 | options.defaults = lib.mkOption {
95 | type = types.submodule ({ config, pkgs, ... }: {
96 | options.configuration = lib.mkOption {
97 | type = types.submoduleWith {
98 | modules = [({ config, ... }: {
99 | options.secrets = {
100 | baseDirectory = lib.mkOption {
101 | type = types.path;
102 | default = "/var/lib/nixus-secrets";
103 | description = ''
104 | The persistent directory on the target host to store secrets in.
105 | '';
106 | };
107 |
108 | files = lib.mkOption {
109 | type = types.attrsOf (types.submodule (secretType pkgs config.secrets.baseDirectory));
110 | default = {};
111 | };
112 | };
113 | })];
114 | };
115 | };
116 |
117 | # These scripts are intentionally not conditioned on secrets being defined
118 | # This is such that if a user enabled and disables secrets, they won't
119 | # stick around
120 | config =
121 | let
122 | includedSecrets = requiredSecrets pkgs {
123 | system = config.configuration.system.build.toplevel;
124 | secrets = config.configuration.secrets.files;
125 | };
126 |
127 | baseDir = config.configuration.secrets.baseDirectory;
128 |
129 | in {
130 |
131 | /*
132 |
133 | Secret structure:
134 | /var/lib/nixus-secrets/active root:root 0755 # Directory containing all active persisted secrets and data needed to support it
135 | |
136 | + included-secrets root:root 0440 # A file containing line-delimited json values describing all present secrets
137 | |
138 | + per-user root:root 0755 # A directory containing all secrets owned by users
139 | | |
140 | | + :root 0500 # A directory containing all secrets owned by
141 | | | # Permissions are as restrictive as possible, some programs like ssh require this
142 | | |
143 | | + :root 0400 # A file containing the secret
144 | |
145 | + per-group root:root 0755 # A directory containing all secrets owned by groups
146 | |
147 | + root: 0050 # A directory containing all secrets owned by
148 | |
149 | + root: 0040 # A file containing the secret
150 |
151 | /var/lib/nixus-secrets/pending root:root 0755 # The same structure as /active, but this is only used during deployment to make it more atomic and simple to remove unneeded ones later
152 | # The only difference here is that no owners are set yet, since we can't yet know uid and gid
153 | */
154 |
155 | # Configures owners for secrets. This needs to happen during activation since only then the users/groups even exist
156 | # And this can't be done with tmpfiles.d because that would be part of the system closure, which is evaluated to even know which secrets to include
157 | # FIXME: This only works with rollbacks because nixus rolls back by essentially redeploying. So this will probably not work with e.g. grub rollbacks
158 | configuration.system.activationScripts.activate-secrets = lib.stringAfter [ "users" "groups" ] ''
159 | if [[ -d ${baseDir}/pending ]]; then
160 | while read -r json; do
161 | name=$(echo "$json" | ${pkgs.jq}/bin/jq -r '.name')
162 | user=$(echo "$json" | ${pkgs.jq}/bin/jq -r '.user')
163 | group=$(echo "$json" | ${pkgs.jq}/bin/jq -r '.group')
164 |
165 | # If this is a per-user secret
166 | if [[ "$user" != null ]]; then
167 | chown -v -R "$user":root "${baseDir}/pending/per-user/$user"
168 | else
169 | chown -v -R root:"$group" "${baseDir}/pending/per-group/$group"
170 | fi
171 | done < ${baseDir}/pending/included-secrets
172 |
173 | # TOOD: Do this atomically
174 | if [[ -d ${baseDir}/active ]]; then
175 | rm -r ${baseDir}/active
176 | fi
177 | mv -v ${baseDir}/pending ${baseDir}/active
178 | fi
179 | '';
180 |
181 | closurePaths.rsync = pkgs.rsync;
182 |
183 | preparationPhases.secrets =
184 | let
185 | # Safe because we include pkgs.rsync in the remotes closure,
186 | # therefore ensuring it will be there
187 | rsync = builtins.unsafeDiscardStringContext "${pkgs.rsync}/bin/rsync";
188 | privilegeEscalation = builtins.concatStringsSep " " config.privilegeEscalationCommand;
189 | in lib.dag.entryAfter ["copyClosure"] ''
190 | echo "Copying secrets..." >&2
191 |
192 | ssh "$HOST" ${privilegeEscalation} mkdir -p -m 755 ${baseDir}/pending/per-{user,group}
193 | # TODO: I don't think this works if rsync isn't on the remote's shell.
194 | # We really just need a single binary we can execute on the remote, like the switch script
195 | rsync --perms --chmod=440 --rsync-path="${privilegeEscalation} ${rsync}" "${includedSecrets}" "$HOST:${baseDir}/pending/included-secrets"
196 |
197 | while read -r json; do
198 | name=$(echo "$json" | jq -r '.name')
199 | source=$(echo "$json" | jq -r '.source')
200 | user=$(echo "$json" | jq -r '.user')
201 | group=$(echo "$json" | jq -r '.group')
202 |
203 | echo "Copying secret $name..." >&2
204 |
205 | # If this is a per-user secret
206 | if [[ "$user" != null ]]; then
207 | # The -n is very important for ssh to not swallow stdin!
208 | ssh -n "$HOST" ${privilegeEscalation} mkdir -p -m 500 "${baseDir}/pending/per-user/$user"
209 | rsync --perms --chmod=400 --rsync-path="${privilegeEscalation} ${rsync}" "$source" "$HOST:${baseDir}/pending/per-user/$user/$name"
210 | else
211 | ssh -n "$HOST" ${privilegeEscalation} mkdir -p -m 050 "${baseDir}/pending/per-group/$group"
212 | rsync --perms --chmod=040 --rsync-path="${privilegeEscalation} ${rsync}" "$source" "$HOST:${baseDir}/pending/per-group/$group/$name"
213 | fi
214 | done < "${includedSecrets}"
215 |
216 | echo "Finished copying secrets" >&2
217 | '';
218 | };
219 | });
220 | };
221 |
222 | }
223 |
--------------------------------------------------------------------------------
/modules/ssh.nix:
--------------------------------------------------------------------------------
1 | { lib, config, ... }:
2 | let
3 | inherit (lib) types;
4 |
5 | /*
6 | connections :: ListOf { from.host; from.user; to.host; to.user }
7 |
8 | A list of SSH connections that should be allowed as given by the ssh.access option
9 | */
10 | connections = lib.flatten (lib.mapAttrsToList (fromHost: fromHostValue:
11 | lib.mapAttrsToList (fromKey: fromUserValue:
12 | lib.mapAttrsToList (toHost: toHostValue:
13 | lib.mapAttrsToList (toUser: toUserValue:
14 | lib.optional toUserValue {
15 | from.host = fromHost;
16 | from.key = fromKey;
17 | to.host = toHost;
18 | to.user = toUser;
19 | }
20 | ) toHostValue
21 | ) fromUserValue.hasAccessTo
22 | ) fromHostValue.keys
23 | ) config.ssh.access);
24 |
25 | userConfig = lib.mapAttrs (host: hostConnections: {
26 | configuration.users.users = lib.mapAttrs (user: userConnections: {
27 | openssh.authorizedKeys.keys = lib.mkIf (userConnections != []) (map (conn:
28 | config.ssh.access.${conn.from.host}.keys.${conn.from.key}.publicKey
29 | ) userConnections);
30 | }) (lib.groupBy (conn: conn.to.user) hostConnections);
31 | }) (lib.groupBy (conn: conn.to.host) connections);
32 |
33 | knownHostsConfig = lib.mapAttrs (fromHost: fromHostConnections: {
34 | configuration.programs.ssh.knownHosts = lib.mkMerge (lib.mapAttrsToList (toHost: toHostConnections:
35 | if config.ssh.access.${toHost}.hostKeys == {}
36 | then throw "No host keys defined with ssh.access.${toHost}.hostKeys, but we need one to give secure access from ${fromHost}."
37 | else lib.mapAttrs' (hostKeyName: publicKey: {
38 | name = "${toHost}-${hostKeyName}";
39 | value = {
40 | hostNames = [ toHost ] ++ config.ssh.access.${toHost}.hostNames ++ lib.optional (fromHost == toHost) "localhost";
41 | inherit publicKey;
42 | };
43 | }) config.ssh.access.${toHost}.hostKeys
44 | ) (lib.groupBy (conn: conn.to.host) fromHostConnections));
45 | }) (lib.groupBy (conn: conn.from.host) connections);
46 |
47 |
48 | in {
49 |
50 | options.ssh = {
51 |
52 | access = lib.mkOption {
53 | description = ''
54 | A specification for which host/key pair should have access to which
55 | other host/user pair. An entry here essentially makes `ssh user@host`
56 | work smoothly.
57 |
58 | This works by adding the source key to the target users authorized
59 | keys and by adding the target host key to the source hosts known hosts.
60 |
61 | Note that hosts are specified by Nixus node name.
62 | '';
63 | example = lib.literalExample ''
64 | {
65 | sourceHost = {
66 | keys.sourceKey = {
67 | # Generate this with ssh-keygen
68 | publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDOJYDb9isFfFog88Lzvs1CEfAmcVB7F9NUFzC7XXXXX";
69 | hasAccessTo = {
70 | # This allows you to `ssh targetUser@targetHost`
71 | # from a user having sourceKey on sourceHost
72 | targetHost.targetUser = true;
73 | };
74 | };
75 | };
76 |
77 | # The target hosts key needs to be specified
78 | targetHost = {
79 | # Usually autogenerated in /etc/ssh/ssh_host_*_key.pub
80 | hostKeys.ed25519 = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIElTpklo4GfIwPG2/HxUzsov9eW7Z0au0hF9HAzXXXXX";
81 | };
82 | }
83 | '';
84 | default = {};
85 | type = types.attrsOf (types.submodule {
86 |
87 | options.hostKeys = lib.mkOption {
88 | description = ''
89 | The host keys, usually autogenerated in /etc/ssh/ssh_host_*_key.pub.
90 | Generally only a single key is needed. The attribute name can be
91 | arbitrary and doesn't have any effect.
92 |
93 | This needs to be specified if any host/user needs to have SSH
94 | access to this host
95 | '';
96 | default = {};
97 | type = types.attrsOf types.str;
98 | };
99 |
100 | options.hostNames = lib.mkOption {
101 | description = ''
102 | The host names this host is reachable from. Among others, this can include
103 | - local subnet IP addresses
104 | - public IP addresses
105 | - VPN IP addresses
106 | - DNS domains
107 |
108 | Note that the node name itself and localhost (if applicable) are
109 | implicitly in this list.
110 | '';
111 | type = types.listOf types.str;
112 | default = [];
113 | };
114 |
115 | options.keys = lib.mkOption {
116 | description = ''
117 | Which keys this host has and the access they should have to which
118 | hosts. The attribute name can be arbitrary and has no effect on the
119 | result.
120 | '';
121 | default = {};
122 | type = types.attrsOf (types.submodule {
123 | options.publicKey = lib.mkOption {
124 | description = ''
125 | The public key. This can be generated with `ssh-keygen`
126 | or `ssh-keygen -t ed25519`. This needs to be specified if the
127 | keys owner wants to SSH into another host.
128 |
129 | If you have multiple keys for the same user, specify another
130 | attribute for the `keys` option.
131 | '';
132 | type = types.str;
133 | };
134 | options.hasAccessTo = lib.mkOption {
135 | description = ''
136 | Which host/user this key should have access to. A value
137 | of `. = true` allows `ssh @` to work.
138 | '';
139 | example = lib.literalExample ''
140 | {
141 | targetHost.targetUser = true;
142 | }
143 | '';
144 | type = types.attrsOf (types.attrsOf types.bool);
145 | default = {};
146 | };
147 | });
148 | };
149 |
150 | });
151 | };
152 |
153 | };
154 |
155 | config = lib.mkMerge [
156 | { nodes = userConfig; }
157 | { nodes = knownHostsConfig; }
158 | ];
159 |
160 | }
161 |
--------------------------------------------------------------------------------
/modules/vpn/default.nix:
--------------------------------------------------------------------------------
1 | { lib, ... }:
2 | let
3 | inherit (lib) types;
4 |
5 | /*
6 | TODO: Validate subnet IPs and/or allow numbering of them (e.g. server gets 1st IP in range, client A gets 2nd, etc.)
7 | */
8 | in {
9 |
10 | imports = [
11 | ./wireguard.nix
12 | ];
13 |
14 | options.vpn.networks = lib.mkOption {
15 | default = {};
16 | type = types.attrsOf (types.submodule ({ config, ... }: let netConfig = config; in {
17 |
18 | options = {
19 |
20 | enable = lib.mkOption {
21 | type = types.bool;
22 | default = true;
23 | };
24 |
25 | backend = lib.mkOption {
26 | type = types.enum [];
27 | };
28 |
29 | subnet = lib.mkOption {
30 | type = types.str;
31 | };
32 |
33 | server = {
34 | node = lib.mkOption {
35 | type = types.str;
36 | };
37 |
38 | port = lib.mkOption {
39 | type = types.port;
40 | };
41 |
42 | subnetIp = lib.mkOption {
43 | type = types.str;
44 | };
45 |
46 | internetGateway = lib.mkOption {
47 | type = types.bool;
48 | default = false;
49 | };
50 |
51 | internetGatewayInterface = lib.mkOption {
52 | type = types.str;
53 | };
54 | };
55 |
56 | clients = lib.mkOption {
57 | default = {};
58 | type = types.attrsOf (types.submodule {
59 |
60 | options.enable = lib.mkOption {
61 | type = types.bool;
62 | default = true;
63 | };
64 |
65 | options.subnetIp = lib.mkOption {
66 | type = types.nullOr types.str;
67 | };
68 |
69 | options.internetGateway = lib.mkOption {
70 | type = types.bool;
71 | default = netConfig.server.internetGateway;
72 | defaultText = "netConfig.server.internetGateway";
73 | };
74 |
75 | });
76 | };
77 |
78 | };
79 |
80 | }));
81 | };
82 | }
83 |
--------------------------------------------------------------------------------
/modules/vpn/wireguard.nix:
--------------------------------------------------------------------------------
1 | { lib, config, ... }:
2 |
3 | let
4 | inherit (lib) types;
5 |
6 | wireguardNetworks = lib.filterAttrs (name: net: net.enable && net.backend == "wireguard") config.vpn.networks;
7 |
8 | in {
9 |
10 | options.vpn.networks = lib.mkOption {
11 | type = types.attrsOf (types.submodule {
12 |
13 | options.backend = lib.mkOption {
14 | type = types.enum [ "wireguard" ];
15 | };
16 |
17 | options.server.wireguard.publicKey = lib.mkOption {
18 | type = types.str;
19 | };
20 |
21 | options.server.wireguard.privateKeyFile = lib.mkOption {
22 | type = types.path;
23 | };
24 |
25 | options.clients = lib.mkOption {
26 | type = types.attrsOf (types.submodule {
27 |
28 | options.wireguard.publicKey = lib.mkOption {
29 | type = types.str;
30 | };
31 |
32 | options.wireguard.privateKeyFile = lib.mkOption {
33 | type = types.path;
34 | };
35 |
36 | });
37 | };
38 |
39 | config.server.port = lib.mkDefault 51820;
40 |
41 | });
42 | };
43 |
44 | config.nodes = lib.mkMerge (lib.flip lib.mapAttrsToList wireguardNetworks (name: net:
45 | let
46 | interface = "nixus-${name}";
47 | parsedSubnet = lib.ip.parseSubnet net.subnet;
48 | in {
49 |
50 | ${net.server.node}.configuration = lib.mkMerge [
51 | {
52 |
53 | networking.firewall.allowedUDPPorts = [ net.server.port ];
54 |
55 | networking.firewall.trustedInterfaces = [ interface ];
56 |
57 | # Needed for both networking between clients and for client -> internet
58 | boot.kernel.sysctl."net.ipv4.conf.${interface}.forwarding" = true;
59 |
60 | networking.wg-quick.interfaces.${interface} = {
61 | address = [ "${net.server.subnetIp}/${toString parsedSubnet.cidr}" ];
62 | listenPort = net.server.port;
63 | privateKeyFile = net.server.wireguard.privateKeyFile;
64 |
65 | peers = lib.mapAttrsToList (clientNode: clientValue: {
66 | publicKey = clientValue.wireguard.publicKey;
67 | allowedIPs = [ "${clientValue.subnetIp}/32" ];
68 | }) net.clients;
69 | };
70 | }
71 |
72 | (lib.mkIf net.server.internetGateway {
73 |
74 | networking.nat = {
75 | enable = true;
76 | externalInterface = net.server.internetGatewayInterface;
77 | internalInterfaces = [ interface ];
78 | };
79 |
80 | networking.wg-quick.interfaces.${interface} = {
81 | postUp = ''
82 | iptables -t nat -A POSTROUTING -j MASQUERADE \
83 | -s ${parsedSubnet.subnet} -o ${net.server.internetGatewayInterface}
84 | '';
85 |
86 | postDown = ''
87 | iptables -t nat -D POSTROUTING -j MASQUERADE \
88 | -s ${parsedSubnet.subnet} -o ${net.server.internetGatewayInterface}
89 | '';
90 | };
91 |
92 | })
93 | ];
94 | }
95 |
96 | // lib.flip lib.mapAttrs net.clients (clientNode: clientValue: {
97 |
98 | configuration = {
99 |
100 | networking.firewall.trustedInterfaces = [ interface ];
101 |
102 | networking.wg-quick.interfaces.${interface} = {
103 | address = [ "${clientValue.subnetIp}/${toString parsedSubnet.cidr}" ];
104 | privateKeyFile = clientValue.wireguard.privateKeyFile;
105 |
106 | peers = lib.singleton {
107 | publicKey = net.server.wireguard.publicKey;
108 | allowedIPs = if clientValue.internetGateway
109 | then [ "0.0.0.0/0" ]
110 | else [ parsedSubnet.subnet ];
111 | endpoint = "${config.nodes.${net.server.node}.configuration.networking.public.ipv4}:${toString net.server.port}";
112 | persistentKeepalive = 25;
113 | };
114 | };
115 | };
116 |
117 | })));
118 |
119 | }
120 |
--------------------------------------------------------------------------------
/notes.md:
--------------------------------------------------------------------------------
1 | Features I thought of putting in a deployment tool:
2 | - Separate concepts of deployment node and network node. A host can either be a deployment node, a network node, none or both, with state transitions:
3 | - At the start all hosts are neither deployment nor network node
4 | - To get started, you make a host a deployment node by installing the deployment tool on it (or cloning the repository of the network)
5 | - Configuring another host to deploy to in the network config file makes it a network node
6 | - Configuring to deploy to localhost makes the local host both a deployment node and a network node
7 | - A deployment node that's also a network node should always be able to do changes to itself, even when all other nodes are offline
8 | - Track which deployment network a node belongs to, to prevent conflicts. Or perhaps a node could be in multiple networks?
9 | - Automatic decentralized version tracking with git remotes and/or branches.
10 | - All network nodes have a copy of the network git repo with their latest changes
11 | - So if we deploy to a remote network node, we first `git pull` from that host to know of any changes it did to itself, and merge those into our own changes with git
12 | - As a result we could get a git graph of a branch for every network node with merges between them
13 | - This allows both Alice and Bob to do changes to host C independently, without any changes being lost or Alice and Bob coordinating
14 | - TODO: How does this interact with the next point?
15 | - Ability to write multi-host abstraction modules
16 | - E.g. to configure a VPN network with this node as a server and these ones as clients, abstracted away in a single module
17 | - Allows users to write such modules themselves
18 | - Authorization for deployments based on own SSH keys
19 | - If you have root SSH access to a remote machine with your own SSH key, you are allowed to do deployments to it
20 | - Same for root access to the local machine
21 | - To allow other people to do changes to machines, deploy an update to the machine that adds their ssh keys (or set up an SSH CA to give a group of people access at once)
22 | - Ideally have a NixOS module that easily allows doing this (TODO: What about ssh key generation?)
23 | - Evaluate if [SPIFFE workload attestor](https://spiffe.io/docs/latest/spire/understand/concepts/) can procure (rolling) certificate generation and provide the trust network
24 | - Allow different nixpkgs versions for different network nodes
25 |
26 | Some other features I'd like to have, but not thought out as well:
27 | - Ability for it to install NixOS on non-NixOS hosts with already the correct initial configuration, creating a new network node, fully automatically hopefully
28 | - Non-persistent (and persistent?) secret management
29 | - Health checks
30 | - Automatically take care of running nixos-generate-config, so it doesn't have to be called manually which could be forgotten
31 |
32 | - Copy the Nix from the target host to localhost and use that to communicate to the daemon, such that there's no version mismatch
33 |
--------------------------------------------------------------------------------
/scripts/switch:
--------------------------------------------------------------------------------
1 | #! @shell@
2 |
3 |
4 | # TODO: Reboot automatically if kernel update?
5 | # TODO: Take some things from auto-upgrade.nix
6 |
7 | # Have a remote command, with usage:
8 | # switch start ->
9 | # switch active -> success | failure | unknown, exit code 0 when done, 1
10 | # when not done, reports that we can connect to the host
11 | # switch run -> does the actual switch, should be run asynchronously via systemd
12 |
13 | # We store state like this:
14 | # /var/lib/system-switcher
15 | # /next:
16 | # /current -> system- (optional)
17 | # /system-
18 | # /system -> /nix/store/xxx
19 | # /status: success | failure | unknown
20 | # /confirm: (socket, optional)
21 | # /active: 0 | 1
22 | # /log: File where logs are piped to
23 |
24 | set -u
25 |
26 | # This script needs to be run as root
27 | if [[ "$EUID" -ne 0 ]]; then
28 | exec @privilegeEscalationCommand@ "$0" "$@"
29 | fi
30 |
31 | mkdir -p /var/lib/system-switcher
32 | chmod 770 /var/lib/system-switcher
33 | cd /var/lib/system-switcher
34 |
35 | switch-start() {
36 | local system=$1
37 | if ! [ -x "$system/bin/switch-to-configuration" ]; then
38 | echo "$system doesn't appear to be a NixOS system" >&2
39 | exit 1
40 | fi
41 |
42 | local id
43 | if [ -f next ]; then
44 | id=$(cat next)
45 | else
46 | id=0
47 | fi
48 |
49 | local current="system-$id"
50 | if ! ln -sT "system-$id" current; then
51 | echo "Switch $(readlink current) is already in progress" >&2
52 | exit 1
53 | fi
54 |
55 | echo $(( id + 1 )) > next
56 | mkdir "$current"
57 | ln -sT "$system" current/system
58 | echo unknown > current/status
59 | echo 1 > current/active
60 |
61 | nohup "$0" run >>"$current/log" 2>&1 &
62 |
63 | echo "$id"
64 | }
65 |
66 | switch-active() {
67 | local id=$1
68 | cat "system-$id/status"
69 | local active=$(cat "system-$id/active")
70 | # Could also wait for updates after the ping
71 | if [ -p "system-$id/confirm" ]; then
72 | echo PING > "system-$id/confirm"
73 | fi
74 | exit "$active"
75 | }
76 |
77 |
78 | waitConfirm() {
79 | mkfifo current/confirm
80 | echo "Waiting for confirmation.." >&2
81 | read -t @successTimeout@ -r <>current/confirm
82 | confirmed=$?
83 | rm current/confirm
84 | return $confirmed
85 | }
86 |
87 | switch() {
88 | local system=$1
89 | local action=$2
90 | timeout --foreground @switchTimeout@ "$system/bin/switch-to-configuration" "$action"
91 | local code=$?
92 | if [ $code -eq 124 ]; then
93 | echo "Activation of $system timed out" >&2
94 | return $code
95 | elif [ $code -ne 0 ]; then
96 | if [ "@ignoreFailingSystemdUnits@" = 1 ] && [ $code -eq 4 ]; then
97 | echo "During activation of $system, some systemd units failed to activate" >&2
98 | return 0
99 | else
100 | echo "Activation of $system failed" >&2
101 | return $code
102 | fi
103 | fi
104 | }
105 |
106 | fail() {
107 | echo failure > current/status
108 | echo "Rolling back.." >&2
109 | switch "$1" switch
110 |
111 | waitConfirm
112 | code=$?
113 |
114 | echo 0 > current/active
115 | rm current
116 |
117 | if [ "$code" -ne 0 ]; then
118 | echo "Unsuccessfully rolled back without rebooting" >&2
119 | echo "Rebooting to rollback.." >&2
120 | reboot
121 | fi
122 |
123 | echo "Successfully rolled back without rebooting" >&2
124 | exit 1
125 | }
126 |
127 | switch-run() {
128 | if [ ! -d current ]; then
129 | echo "No system to activate" >&2
130 | exit 1
131 | fi
132 |
133 | local newsystem=$(realpath current/system)
134 | local oldsystem=$(realpath /run/current-system)
135 |
136 | if switch "$newsystem" test; then
137 | echo "Activated new system successfully"
138 | if waitConfirm; then
139 | echo "Success confirmation received, activating system" >&2
140 | if switch "$newsystem" boot; then
141 | nix-env -p /nix/var/nix/profiles/system --set "$newsystem"
142 | # We need to run the boot switch again for the new system to be
143 | # available in the boot loader since it uses the system profiles to
144 | # generate that
145 | # TODO: I feel like there should be a better way
146 | switch "$newsystem" boot
147 | echo success > current/status
148 | echo 0 > current/active
149 | rm current
150 | else
151 | echo "Failed to boot switch" >&2
152 | fail "$oldsystem"
153 | fi
154 | else
155 | echo "Success confirmation not received in time" >&2
156 | fail "$oldsystem"
157 | fi
158 | else
159 | echo "System activation failed" >&2
160 | fail "$oldsystem"
161 | fi
162 |
163 | }
164 |
165 | case "$1" in
166 | "start")
167 | switch-start "$2"
168 | ;;
169 | "active")
170 | switch-active "$2"
171 | ;;
172 | "run")
173 | switch-run
174 | ;;
175 | *)
176 | echo "No such command $1" >&2
177 | ;;
178 | esac
179 |
180 |
--------------------------------------------------------------------------------