├── .gitignore ├── LICENSE.md ├── README.md ├── config.ml ├── justfile ├── le.ml ├── pkce.ml ├── recycler.ml ├── resource.ml ├── unikernel.ml └── webapp.ml /.gitignore: -------------------------------------------------------------------------------- 1 | *.chamelon 2 | *.hvt 3 | myocamlbuild* 4 | dune* 5 | Makefile 6 | _build/** 7 | .mirage.config 8 | main.ml 9 | key_gen.ml 10 | *.opam 11 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU Affero General Public License 2 | ================================= 3 | 4 | _Version 3, 19 November 2007_ 5 | _Copyright © 2007 Free Software Foundation, Inc. <>_ 6 | 7 | Everyone is permitted to copy and distribute verbatim copies 8 | of this license document, but changing it is not allowed. 9 | 10 | ## Preamble 11 | 12 | The GNU Affero General Public License is a free, copyleft license for 13 | software and other kinds of works, specifically designed to ensure 14 | cooperation with the community in the case of network server software. 15 | 16 | The licenses for most software and other practical works are designed 17 | to take away your freedom to share and change the works. By contrast, 18 | our General Public Licenses are intended to guarantee your freedom to 19 | share and change all versions of a program--to make sure it remains free 20 | software for all its users. 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 | Developers that use our General Public Licenses protect your rights 30 | with two steps: **(1)** assert copyright on the software, and **(2)** offer 31 | you this License which gives you legal permission to copy, distribute 32 | and/or modify the software. 33 | 34 | A secondary benefit of defending all users' freedom is that 35 | improvements made in alternate versions of the program, if they 36 | receive widespread use, become available for other developers to 37 | incorporate. Many developers of free software are heartened and 38 | encouraged by the resulting cooperation. However, in the case of 39 | software used on network servers, this result may fail to come about. 40 | The GNU General Public License permits making a modified version and 41 | letting the public access it on a server without ever releasing its 42 | source code to the public. 43 | 44 | The GNU Affero General Public License is designed specifically to 45 | ensure that, in such cases, the modified source code becomes available 46 | to the community. It requires the operator of a network server to 47 | provide the source code of the modified version running there to the 48 | users of that server. Therefore, public use of a modified version, on 49 | a publicly accessible server, gives the public access to the source 50 | code of the modified version. 51 | 52 | An older license, called the Affero General Public License and 53 | published by Affero, was designed to accomplish similar goals. This is 54 | a different license, not a version of the Affero GPL, but Affero has 55 | released a new version of the Affero GPL which permits relicensing under 56 | this license. 57 | 58 | The precise terms and conditions for copying, distribution and 59 | modification follow. 60 | 61 | ## TERMS AND CONDITIONS 62 | 63 | ### 0. Definitions 64 | 65 | “This License” refers to version 3 of the GNU Affero General Public License. 66 | 67 | “Copyright” also means copyright-like laws that apply to other kinds of 68 | works, such as semiconductor masks. 69 | 70 | “The Program” refers to any copyrightable work licensed under this 71 | License. Each licensee is addressed as “you”. “Licensees” and 72 | “recipients” may be individuals or organizations. 73 | 74 | To “modify” a work means to copy from or adapt all or part of the work 75 | in a fashion requiring copyright permission, other than the making of an 76 | exact copy. The resulting work is called a “modified version” of the 77 | earlier work or a work “based on” the earlier work. 78 | 79 | A “covered work” means either the unmodified Program or a work based 80 | on the Program. 81 | 82 | To “propagate” a work means to do anything with it that, without 83 | permission, would make you directly or secondarily liable for 84 | infringement under applicable copyright law, except executing it on a 85 | computer or modifying a private copy. Propagation includes copying, 86 | distribution (with or without modification), making available to the 87 | public, and in some countries other activities as well. 88 | 89 | To “convey” a work means any kind of propagation that enables other 90 | parties to make or receive copies. Mere interaction with a user through 91 | a computer network, with no transfer of a copy, is not conveying. 92 | 93 | An interactive user interface displays “Appropriate Legal Notices” 94 | to the extent that it includes a convenient and prominently visible 95 | feature that **(1)** displays an appropriate copyright notice, and **(2)** 96 | tells the user that there is no warranty for the work (except to the 97 | extent that warranties are provided), that licensees may convey the 98 | work under this License, and how to view a copy of this License. If 99 | the interface presents a list of user commands or options, such as a 100 | menu, a prominent item in the list meets this criterion. 101 | 102 | ### 1. Source Code 103 | 104 | The “source code” for a work means the preferred form of the work 105 | for making modifications to it. “Object code” means any non-source 106 | form of a work. 107 | 108 | A “Standard Interface” means an interface that either is an official 109 | standard defined by a recognized standards body, or, in the case of 110 | interfaces specified for a particular programming language, one that 111 | is widely used among developers working in that language. 112 | 113 | The “System Libraries” of an executable work include anything, other 114 | than the work as a whole, that **(a)** is included in the normal form of 115 | packaging a Major Component, but which is not part of that Major 116 | Component, and **(b)** serves only to enable use of the work with that 117 | Major Component, or to implement a Standard Interface for which an 118 | implementation is available to the public in source code form. A 119 | “Major Component”, in this context, means a major essential component 120 | (kernel, window system, and so on) of the specific operating system 121 | (if any) on which the executable work runs, or a compiler used to 122 | produce the work, or an object code interpreter used to run it. 123 | 124 | The “Corresponding Source” for a work in object code form means all 125 | the source code needed to generate, install, and (for an executable 126 | work) run the object code and to modify the work, including scripts to 127 | control those activities. However, it does not include the work's 128 | System Libraries, or general-purpose tools or generally available free 129 | programs which are used unmodified in performing those activities but 130 | which are not part of the work. For example, Corresponding Source 131 | includes interface definition files associated with source files for 132 | the work, and the source code for shared libraries and dynamically 133 | linked subprograms that the work is specifically designed to require, 134 | such as by intimate data communication or control flow between those 135 | subprograms and other parts of the work. 136 | 137 | The Corresponding Source need not include anything that users 138 | can regenerate automatically from other parts of the Corresponding 139 | Source. 140 | 141 | The Corresponding Source for a work in source code form is that 142 | same work. 143 | 144 | ### 2. Basic Permissions 145 | 146 | All rights granted under this License are granted for the term of 147 | copyright on the Program, and are irrevocable provided the stated 148 | conditions are met. This License explicitly affirms your unlimited 149 | permission to run the unmodified Program. The output from running a 150 | covered work is covered by this License only if the output, given its 151 | content, constitutes a covered work. This License acknowledges your 152 | rights of fair use or other equivalent, as provided by copyright law. 153 | 154 | You may make, run and propagate covered works that you do not 155 | convey, without conditions so long as your license otherwise remains 156 | in force. You may convey covered works to others for the sole purpose 157 | of having them make modifications exclusively for you, or provide you 158 | with facilities for running those works, provided that you comply with 159 | the terms of this License in conveying all material for which you do 160 | not control copyright. Those thus making or running the covered works 161 | for you must do so exclusively on your behalf, under your direction 162 | and control, on terms that prohibit them from making any copies of 163 | your copyrighted material outside their relationship with you. 164 | 165 | Conveying under any other circumstances is permitted solely under 166 | the conditions stated below. Sublicensing is not allowed; section 10 167 | makes it unnecessary. 168 | 169 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law 170 | 171 | No covered work shall be deemed part of an effective technological 172 | measure under any applicable law fulfilling obligations under article 173 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 174 | similar laws prohibiting or restricting circumvention of such 175 | measures. 176 | 177 | When you convey a covered work, you waive any legal power to forbid 178 | circumvention of technological measures to the extent such circumvention 179 | is effected by exercising rights under this License with respect to 180 | the covered work, and you disclaim any intention to limit operation or 181 | modification of the work as a means of enforcing, against the work's 182 | users, your or third parties' legal rights to forbid circumvention of 183 | technological measures. 184 | 185 | ### 4. Conveying Verbatim Copies 186 | 187 | You may convey verbatim copies of the Program's source code as you 188 | receive it, in any medium, provided that you conspicuously and 189 | appropriately publish on each copy an appropriate copyright notice; 190 | keep intact all notices stating that this License and any 191 | non-permissive terms added in accord with section 7 apply to the code; 192 | keep intact all notices of the absence of any warranty; and give all 193 | recipients a copy of this License along with the Program. 194 | 195 | You may charge any price or no price for each copy that you convey, 196 | and you may offer support or warranty protection for a fee. 197 | 198 | ### 5. Conveying Modified Source Versions 199 | 200 | You may convey a work based on the Program, or the modifications to 201 | produce it from the Program, in the form of source code under the 202 | terms of section 4, provided that you also meet all of these conditions: 203 | 204 | * **a)** The work must carry prominent notices stating that you modified 205 | it, and giving a relevant date. 206 | * **b)** The work must carry prominent notices stating that it is 207 | released under this License and any conditions added under section 7. 208 | This requirement modifies the requirement in section 4 to 209 | “keep intact all notices”. 210 | * **c)** You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | * **d)** If the work has interactive user interfaces, each must display 218 | Appropriate Legal Notices; however, if the Program has interactive 219 | interfaces that do not display Appropriate Legal Notices, your 220 | work need not make them do so. 221 | 222 | A compilation of a covered work with other separate and independent 223 | works, which are not by their nature extensions of the covered work, 224 | and which are not combined with it such as to form a larger program, 225 | in or on a volume of a storage or distribution medium, is called an 226 | “aggregate” if the compilation and its resulting copyright are not 227 | used to limit the access or legal rights of the compilation's users 228 | beyond what the individual works permit. Inclusion of a covered work 229 | in an aggregate does not cause this License to apply to the other 230 | parts of the aggregate. 231 | 232 | ### 6. Conveying Non-Source Forms 233 | 234 | You may convey a covered work in object code form under the terms 235 | of sections 4 and 5, provided that you also convey the 236 | machine-readable Corresponding Source under the terms of this License, 237 | in one of these ways: 238 | 239 | * **a)** Convey the object code in, or embodied in, a physical product 240 | (including a physical distribution medium), accompanied by the 241 | Corresponding Source fixed on a durable physical medium 242 | customarily used for software interchange. 243 | * **b)** Convey the object code in, or embodied in, a physical product 244 | (including a physical distribution medium), accompanied by a 245 | written offer, valid for at least three years and valid for as 246 | long as you offer spare parts or customer support for that product 247 | model, to give anyone who possesses the object code either **(1)** a 248 | copy of the Corresponding Source for all the software in the 249 | product that is covered by this License, on a durable physical 250 | medium customarily used for software interchange, for a price no 251 | more than your reasonable cost of physically performing this 252 | conveying of source, or **(2)** access to copy the 253 | Corresponding Source from a network server at no charge. 254 | * **c)** Convey individual copies of the object code with a copy of the 255 | written offer to provide the Corresponding Source. This 256 | alternative is allowed only occasionally and noncommercially, and 257 | only if you received the object code with such an offer, in accord 258 | with subsection 6b. 259 | * **d)** Convey the object code by offering access from a designated 260 | place (gratis or for a charge), and offer equivalent access to the 261 | Corresponding Source in the same way through the same place at no 262 | further charge. You need not require recipients to copy the 263 | Corresponding Source along with the object code. If the place to 264 | copy the object code is a network server, the Corresponding Source 265 | may be on a different server (operated by you or a third party) 266 | that supports equivalent copying facilities, provided you maintain 267 | clear directions next to the object code saying where to find the 268 | Corresponding Source. Regardless of what server hosts the 269 | Corresponding Source, you remain obligated to ensure that it is 270 | available for as long as needed to satisfy these requirements. 271 | * **e)** Convey the object code using peer-to-peer transmission, provided 272 | you inform other peers where the object code and Corresponding 273 | Source of the work are being offered to the general public at no 274 | charge under subsection 6d. 275 | 276 | A separable portion of the object code, whose source code is excluded 277 | from the Corresponding Source as a System Library, need not be 278 | included in conveying the object code work. 279 | 280 | A “User Product” is either **(1)** a “consumer product”, which means any 281 | tangible personal property which is normally used for personal, family, 282 | or household purposes, or **(2)** anything designed or sold for incorporation 283 | into a dwelling. In determining whether a product is a consumer product, 284 | doubtful cases shall be resolved in favor of coverage. For a particular 285 | product received by a particular user, “normally used” refers to a 286 | typical or common use of that class of product, regardless of the status 287 | of the particular user or of the way in which the particular user 288 | actually uses, or expects or is expected to use, the product. A product 289 | is a consumer product regardless of whether the product has substantial 290 | commercial, industrial or non-consumer uses, unless such uses represent 291 | the only significant mode of use of the product. 292 | 293 | “Installation Information” for a User Product means any methods, 294 | procedures, authorization keys, or other information required to install 295 | and execute modified versions of a covered work in that User Product from 296 | a modified version of its Corresponding Source. The information must 297 | suffice to ensure that the continued functioning of the modified object 298 | code is in no case prevented or interfered with solely because 299 | modification has been made. 300 | 301 | If you convey an object code work under this section in, or with, or 302 | specifically for use in, a User Product, and the conveying occurs as 303 | part of a transaction in which the right of possession and use of the 304 | User Product is transferred to the recipient in perpetuity or for a 305 | fixed term (regardless of how the transaction is characterized), the 306 | Corresponding Source conveyed under this section must be accompanied 307 | by the Installation Information. But this requirement does not apply 308 | if neither you nor any third party retains the ability to install 309 | modified object code on the User Product (for example, the work has 310 | been installed in ROM). 311 | 312 | The requirement to provide Installation Information does not include a 313 | requirement to continue to provide support service, warranty, or updates 314 | for a work that has been modified or installed by the recipient, or for 315 | the User Product in which it has been modified or installed. Access to a 316 | network may be denied when the modification itself materially and 317 | adversely affects the operation of the network or violates the rules and 318 | protocols for communication across the network. 319 | 320 | Corresponding Source conveyed, and Installation Information provided, 321 | in accord with this section must be in a format that is publicly 322 | documented (and with an implementation available to the public in 323 | source code form), and must require no special password or key for 324 | unpacking, reading or copying. 325 | 326 | ### 7. Additional Terms 327 | 328 | “Additional permissions” are terms that supplement the terms of this 329 | License by making exceptions from one or more of its conditions. 330 | Additional permissions that are applicable to the entire Program shall 331 | be treated as though they were included in this License, to the extent 332 | that they are valid under applicable law. If additional permissions 333 | apply only to part of the Program, that part may be used separately 334 | under those permissions, but the entire Program remains governed by 335 | this License without regard to the additional permissions. 336 | 337 | When you convey a copy of a covered work, you may at your option 338 | remove any additional permissions from that copy, or from any part of 339 | it. (Additional permissions may be written to require their own 340 | removal in certain cases when you modify the work.) You may place 341 | additional permissions on material, added by you to a covered work, 342 | for which you have or can give appropriate copyright permission. 343 | 344 | Notwithstanding any other provision of this License, for material you 345 | add to a covered work, you may (if authorized by the copyright holders of 346 | that material) supplement the terms of this License with terms: 347 | 348 | * **a)** Disclaiming warranty or limiting liability differently from the 349 | terms of sections 15 and 16 of this License; or 350 | * **b)** Requiring preservation of specified reasonable legal notices or 351 | author attributions in that material or in the Appropriate Legal 352 | Notices displayed by works containing it; or 353 | * **c)** Prohibiting misrepresentation of the origin of that material, or 354 | requiring that modified versions of such material be marked in 355 | reasonable ways as different from the original version; or 356 | * **d)** Limiting the use for publicity purposes of names of licensors or 357 | authors of the material; or 358 | * **e)** Declining to grant rights under trademark law for use of some 359 | trade names, trademarks, or service marks; or 360 | * **f)** Requiring indemnification of licensors and authors of that 361 | material by anyone who conveys the material (or modified versions of 362 | it) with contractual assumptions of liability to the recipient, for 363 | any liability that these contractual assumptions directly impose on 364 | those licensors and authors. 365 | 366 | All other non-permissive additional terms are considered “further 367 | restrictions” within the meaning of section 10. If the Program as you 368 | received it, or any part of it, contains a notice stating that it is 369 | governed by this License along with a term that is a further 370 | restriction, you may remove that term. If a license document contains 371 | a further restriction but permits relicensing or conveying under this 372 | License, you may add to a covered work material governed by the terms 373 | of that license document, provided that the further restriction does 374 | not survive such relicensing or conveying. 375 | 376 | If you add terms to a covered work in accord with this section, you 377 | must place, in the relevant source files, a statement of the 378 | additional terms that apply to those files, or a notice indicating 379 | where to find the applicable terms. 380 | 381 | Additional terms, permissive or non-permissive, may be stated in the 382 | form of a separately written license, or stated as exceptions; 383 | the above requirements apply either way. 384 | 385 | ### 8. Termination 386 | 387 | You may not propagate or modify a covered work except as expressly 388 | provided under this License. Any attempt otherwise to propagate or 389 | modify it is void, and will automatically terminate your rights under 390 | this License (including any patent licenses granted under the third 391 | paragraph of section 11). 392 | 393 | However, if you cease all violation of this License, then your 394 | license from a particular copyright holder is reinstated **(a)** 395 | provisionally, unless and until the copyright holder explicitly and 396 | finally terminates your license, and **(b)** permanently, if the copyright 397 | holder fails to notify you of the violation by some reasonable means 398 | prior to 60 days after the cessation. 399 | 400 | Moreover, your license from a particular copyright holder is 401 | reinstated permanently if the copyright holder notifies you of the 402 | violation by some reasonable means, this is the first time you have 403 | received notice of violation of this License (for any work) from that 404 | copyright holder, and you cure the violation prior to 30 days after 405 | your receipt of the notice. 406 | 407 | Termination of your rights under this section does not terminate the 408 | licenses of parties who have received copies or rights from you under 409 | this License. If your rights have been terminated and not permanently 410 | reinstated, you do not qualify to receive new licenses for the same 411 | material under section 10. 412 | 413 | ### 9. Acceptance Not Required for Having Copies 414 | 415 | You are not required to accept this License in order to receive or 416 | run a copy of the Program. Ancillary propagation of a covered work 417 | occurring solely as a consequence of using peer-to-peer transmission 418 | to receive a copy likewise does not require acceptance. However, 419 | nothing other than this License grants you permission to propagate or 420 | modify any covered work. These actions infringe copyright if you do 421 | not accept this License. Therefore, by modifying or propagating a 422 | covered work, you indicate your acceptance of this License to do so. 423 | 424 | ### 10. Automatic Licensing of Downstream Recipients 425 | 426 | Each time you convey a covered work, the recipient automatically 427 | receives a license from the original licensors, to run, modify and 428 | propagate that work, subject to this License. You are not responsible 429 | for enforcing compliance by third parties with this License. 430 | 431 | An “entity transaction” is a transaction transferring control of an 432 | organization, or substantially all assets of one, or subdividing an 433 | organization, or merging organizations. If propagation of a covered 434 | work results from an entity transaction, each party to that 435 | transaction who receives a copy of the work also receives whatever 436 | licenses to the work the party's predecessor in interest had or could 437 | give under the previous paragraph, plus a right to possession of the 438 | Corresponding Source of the work from the predecessor in interest, if 439 | the predecessor has it or can get it with reasonable efforts. 440 | 441 | You may not impose any further restrictions on the exercise of the 442 | rights granted or affirmed under this License. For example, you may 443 | not impose a license fee, royalty, or other charge for exercise of 444 | rights granted under this License, and you may not initiate litigation 445 | (including a cross-claim or counterclaim in a lawsuit) alleging that 446 | any patent claim is infringed by making, using, selling, offering for 447 | sale, or importing the Program or any portion of it. 448 | 449 | ### 11. Patents 450 | 451 | A “contributor” is a copyright holder who authorizes use under this 452 | License of the Program or a work on which the Program is based. The 453 | work thus licensed is called the contributor's “contributor version”. 454 | 455 | A contributor's “essential patent claims” are all patent claims 456 | owned or controlled by the contributor, whether already acquired or 457 | hereafter acquired, that would be infringed by some manner, permitted 458 | by this License, of making, using, or selling its contributor version, 459 | but do not include claims that would be infringed only as a 460 | consequence of further modification of the contributor version. For 461 | purposes of this definition, “control” includes the right to grant 462 | patent sublicenses in a manner consistent with the requirements of 463 | this License. 464 | 465 | Each contributor grants you a non-exclusive, worldwide, royalty-free 466 | patent license under the contributor's essential patent claims, to 467 | make, use, sell, offer for sale, import and otherwise run, modify and 468 | propagate the contents of its contributor version. 469 | 470 | In the following three paragraphs, a “patent license” is any express 471 | agreement or commitment, however denominated, not to enforce a patent 472 | (such as an express permission to practice a patent or covenant not to 473 | sue for patent infringement). To “grant” such a patent license to a 474 | party means to make such an agreement or commitment not to enforce a 475 | patent against the party. 476 | 477 | If you convey a covered work, knowingly relying on a patent license, 478 | and the Corresponding Source of the work is not available for anyone 479 | to copy, free of charge and under the terms of this License, through a 480 | publicly available network server or other readily accessible means, 481 | then you must either **(1)** cause the Corresponding Source to be so 482 | available, or **(2)** arrange to deprive yourself of the benefit of the 483 | patent license for this particular work, or **(3)** arrange, in a manner 484 | consistent with the requirements of this License, to extend the patent 485 | license to downstream recipients. “Knowingly relying” means you have 486 | actual knowledge that, but for the patent license, your conveying the 487 | covered work in a country, or your recipient's use of the covered work 488 | in a country, would infringe one or more identifiable patents in that 489 | country that you have reason to believe are valid. 490 | 491 | If, pursuant to or in connection with a single transaction or 492 | arrangement, you convey, or propagate by procuring conveyance of, a 493 | covered work, and grant a patent license to some of the parties 494 | receiving the covered work authorizing them to use, propagate, modify 495 | or convey a specific copy of the covered work, then the patent license 496 | you grant is automatically extended to all recipients of the covered 497 | work and works based on it. 498 | 499 | A patent license is “discriminatory” if it does not include within 500 | the scope of its coverage, prohibits the exercise of, or is 501 | conditioned on the non-exercise of one or more of the rights that are 502 | specifically granted under this License. You may not convey a covered 503 | work if you are a party to an arrangement with a third party that is 504 | in the business of distributing software, under which you make payment 505 | to the third party based on the extent of your activity of conveying 506 | the work, and under which the third party grants, to any of the 507 | parties who would receive the covered work from you, a discriminatory 508 | patent license **(a)** in connection with copies of the covered work 509 | conveyed by you (or copies made from those copies), or **(b)** primarily 510 | for and in connection with specific products or compilations that 511 | contain the covered work, unless you entered into that arrangement, 512 | or that patent license was granted, prior to 28 March 2007. 513 | 514 | Nothing in this License shall be construed as excluding or limiting 515 | any implied license or other defenses to infringement that may 516 | otherwise be available to you under applicable patent law. 517 | 518 | ### 12. No Surrender of Others' Freedom 519 | 520 | If conditions are imposed on you (whether by court order, agreement or 521 | otherwise) that contradict the conditions of this License, they do not 522 | excuse you from the conditions of this License. If you cannot convey a 523 | covered work so as to satisfy simultaneously your obligations under this 524 | License and any other pertinent obligations, then as a consequence you may 525 | not convey it at all. For example, if you agree to terms that obligate you 526 | to collect a royalty for further conveying from those to whom you convey 527 | the Program, the only way you could satisfy both those terms and this 528 | License would be to refrain entirely from conveying the Program. 529 | 530 | ### 13. Remote Network Interaction; Use with the GNU General Public License 531 | 532 | Notwithstanding any other provision of this License, if you modify the 533 | Program, your modified version must prominently offer all users 534 | interacting with it remotely through a computer network (if your version 535 | supports such interaction) an opportunity to receive the Corresponding 536 | Source of your version by providing access to the Corresponding Source 537 | from a network server at no charge, through some standard or customary 538 | means of facilitating copying of software. This Corresponding Source 539 | shall include the Corresponding Source for any work covered by version 3 540 | of the GNU General Public License that is incorporated pursuant to the 541 | following paragraph. 542 | 543 | Notwithstanding any other provision of this License, you have 544 | permission to link or combine any covered work with a work licensed 545 | under version 3 of the GNU General Public License into a single 546 | combined work, and to convey the resulting work. The terms of this 547 | License will continue to apply to the part which is the covered work, 548 | but the work with which it is combined will remain governed by version 549 | 3 of the GNU General Public License. 550 | 551 | ### 14. Revised Versions of this License 552 | 553 | The Free Software Foundation may publish revised and/or new versions of 554 | the GNU Affero General Public License from time to time. Such new versions 555 | will be similar in spirit to the present version, but may differ in detail to 556 | address new problems or concerns. 557 | 558 | Each version is given a distinguishing version number. If the 559 | Program specifies that a certain numbered version of the GNU Affero General 560 | Public License “or any later version” applies to it, you have the 561 | option of following the terms and conditions either of that numbered 562 | version or of any later version published by the Free Software 563 | Foundation. If the Program does not specify a version number of the 564 | GNU Affero General Public License, you may choose any version ever published 565 | by the Free Software Foundation. 566 | 567 | If the Program specifies that a proxy can decide which future 568 | versions of the GNU Affero General Public License can be used, that proxy's 569 | public statement of acceptance of a version permanently authorizes you 570 | to choose that version for the Program. 571 | 572 | Later license versions may give you additional or different 573 | permissions. However, no additional obligations are imposed on any 574 | author or copyright holder as a result of your choosing to follow a 575 | later version. 576 | 577 | ### 15. Disclaimer of Warranty 578 | 579 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 580 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 581 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY 582 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 583 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 584 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 585 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 586 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 587 | 588 | ### 16. Limitation of Liability 589 | 590 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 591 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 592 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 593 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 594 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 595 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 596 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 597 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 598 | SUCH DAMAGES. 599 | 600 | ### 17. Interpretation of Sections 15 and 16 601 | 602 | If the disclaimer of warranty and limitation of liability provided 603 | above cannot be given local legal effect according to their terms, 604 | reviewing courts shall apply local law that most closely approximates 605 | an absolute waiver of all civil liability in connection with the 606 | Program, unless a warranty or assumption of liability accompanies a 607 | copy of the Program in return for a fee. 608 | 609 | _END OF TERMS AND CONDITIONS_ 610 | 611 | ## How to Apply These Terms to Your New Programs 612 | 613 | If you develop a new program, and you want it to be of the greatest 614 | possible use to the public, the best way to achieve this is to make it 615 | free software which everyone can redistribute and change under these terms. 616 | 617 | To do so, attach the following notices to the program. It is safest 618 | to attach them to the start of each source file to most effectively 619 | state the exclusion of warranty; and each file should have at least 620 | the “copyright” line and a pointer to where the full notice is found. 621 | 622 | 623 | Copyright (C) 624 | 625 | This program is free software: you can redistribute it and/or modify 626 | it under the terms of the GNU Affero General Public License as published by 627 | the Free Software Foundation, either version 3 of the License, or 628 | (at your option) any later version. 629 | 630 | This program is distributed in the hope that it will be useful, 631 | but WITHOUT ANY WARRANTY; without even the implied warranty of 632 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 633 | GNU Affero General Public License for more details. 634 | 635 | You should have received a copy of the GNU Affero General Public License 636 | along with this program. If not, see . 637 | 638 | Also add information on how to contact you by electronic and paper mail. 639 | 640 | If your software can interact with users remotely through a computer 641 | network, you should also make sure that it provides a way for users to 642 | get its source. For example, if your program is a web application, its 643 | interface could display a “Source” link that leads users to an archive 644 | of the code. There are many ways you could offer source, and different 645 | solutions will be better for different programs; see section 13 for the 646 | specific requirements. 647 | 648 | You should also get your employer (if you work as a programmer) or school, 649 | if any, to sign a “copyright disclaimer” for the program, if necessary. 650 | For more information on this, and how to apply and follow the GNU AGPL, see 651 | <>. 652 | 653 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # what is this? 2 | 3 | An OAuth2 authorization server for communicating with etsy.com implemented in MirageOS. [Etsy's authentication flow](https://developer.etsy.com/documentation/essentials/authentication/) may be similar enough to other OAuth2 resource servers to make this server useful for them as well. 4 | 5 | TLS is provided via Let's Encrypt. Credentials are stored in a separate Chamelon data store and automatically renewed when required. 6 | 7 | # what's weird about it? 8 | 9 | Most systems using OAuth2 in this way have some sort of local authentication which is then connected to a remote system's authentication information as a form of identity federation. This server has no notion of local identity and merely serves as an intermediary for access to the resource server. Authentication requests to Etsy are differentiated by 128-bit random numbers, which are generated by the authorization server and presented to the client. Guessing the random number yields access to the tokens. 10 | 11 | This server is a low-effort proof-of-concept implementation, and as such probably responds in unhelpful ways to lots of inputs. 12 | 13 | There is currently no rate-limiting on requests, which might give the potential user some pause when combined with the first item in this list. Given an adequate entropy source and CSPRNG, states shouldn't be guessable. The more likely problem is the ease of resource exhaustion attacks, since storage is allocated for each new `state` and, in the default configuration, not removed for many days. 14 | 15 | # what's implemented? 16 | 17 | ## endpoints and their happy paths 18 | 19 | * `/auth` : POST `uuid=16randombytes` 20 | * server generates and stores a new `state` and accompanying PKCE verifier 21 | * server redirects the client to Etsy's `oauth/connect` endpoint with `state`, `code_challenge`, etc 22 | * `/etsy` : GET `?code=etsycode&state=somestate` 23 | * server retrieves the PKCE verifier for `somestate` 24 | * server stores `etsycode` for `somestate` 25 | * server initiates a token request to Etsy with `etsycode` and the PKCE verifier for `somestate` 26 | * server stores the `access_token` and `refresh_token` for `etsycode` and `somestate` 27 | * `/token` : POST `state=somestate` 28 | * server retrieves `access_token` for `somestate` 29 | * if `access_token` is too old, server gets a new one with `refresh_token` 30 | * if `access_token` is still valid, server gives it to client 31 | 32 | # what's not implemented, but hopefully someday will be? 33 | 34 | * quicker garbage collection of `state`s that never receive a valid code 35 | * rate limiting 36 | * a nice service on port 80 that redirects you to the TLS server 37 | * user-friendly HTTP bodies for browser rendering 38 | * useful errors in responses for bad state 39 | * any kind of storage optimization 40 | 41 | # what do I need to run this? 42 | 43 | * an Etsy developer key 44 | * a publicly-registered FQDN corresponding to a public IP where you can run a unikernel 45 | * a registered callback URI for your application corresponding to the above FQDN with the /etsy endpoint 46 | * two block devices formatted for Chamelon data storage 47 | * a small one for credentials (mine is 16K) with your developer key saved at `/keystring` 48 | * a larger one for state, code, token, etc. storage 49 | 50 | Several targets are provided for convenience in the included `justfile`. Users will want to make substitutions in the initial variable definitions, particularly `fqdn`, as appropriate. 51 | 52 | # AGPL? WTF? 53 | 54 | If you want a release of this under a different license, feel free to contact the e-mail address in the commit messages associated with `yomimono` to arrange something. 55 | -------------------------------------------------------------------------------- /config.ml: -------------------------------------------------------------------------------- 1 | (* this is a fancy interface between a filesystem and a web server *) 2 | 3 | open Mirage 4 | 5 | let packages = [ 6 | Functoria.package "letsencrypt"; 7 | Functoria.package "uri"; 8 | Functoria.package "base64"; 9 | Functoria.package "yojson"; 10 | Functoria.package ~sublibs:["kv"] "chamelon"; 11 | Functoria.package ~sublibs:["ocaml"] "digestif"; 12 | Functoria.package ~sublibs:["ocaml"] "checkseum"; 13 | ] 14 | 15 | let stack = generic_stackv4v6 default_network 16 | let conduit = conduit_direct ~tls:true stack 17 | let http_srv = cohttp_server conduit 18 | let http_client_imp = cohttp_client (resolver_dns stack) conduit 19 | let webapp_block = block_of_file "webapp" 20 | let certs_block = block_of_file "certs" 21 | 22 | let host = 23 | let doc = Key.Arg.info ~doc:"Fully-qualified domain name for the server. Certificates will be requested from Let's Encrypt for this name." ["host"] in 24 | Key.(create "host" Arg.(required string doc)) 25 | 26 | let redirect_uri_path = 27 | let doc = Key.Arg.info ~doc:"Path to use with [host] as redirect_uri in outgoing requests. This should look like the path component of a URI, e.g. /oauth/connect" ["path"] in 28 | Key.(create "path" Arg.(required string doc)) 29 | 30 | let keys = List.map Key.v [ host; redirect_uri_path ] 31 | 32 | let main = 33 | foreign ~packages ~keys "Unikernel.Main" (block @-> block @-> pclock @-> time @-> random @-> http @-> http_client @-> job) 34 | 35 | let () = 36 | register "oauth2" [ main $ certs_block $ webapp_block $ default_posix_clock $ default_time $ default_random $ http_srv $ http_client_imp ] 37 | -------------------------------------------------------------------------------- /justfile: -------------------------------------------------------------------------------- 1 | cert_fs := "credstore.chamelon" 2 | webapp_fs := "webapp.chamelon" 3 | guest_ip := "10.0.0.2" 4 | fqdn := "we-have.legitcreds.us" 5 | hypervisor_ip := "10.0.0.1" 6 | hypervisor_uplink := "eth0" 7 | hypervisor_tap := "tap100" 8 | path := "/etsy" 9 | 10 | start : 11 | sudo solo5-hvt --mem=64 --net:service={{hypervisor_tap}} --block:webapp={{webapp_fs}} --block:certs={{cert_fs}} -- dist/oauth2.hvt --backtrace=true -l "application:debug" --host={{fqdn}} --path={{path}} --ipv4-gateway={{hypervisor_ip}} 12 | 13 | creds : 14 | dd if=/dev/zero of={{cert_fs}} bs=4K count=4 15 | chamelon format --block-size=512 {{cert_fs}} 16 | cat ~/oauth2_test_creds/keystring | tr -d '\n' | chamelon write --verbosity=debug {{cert_fs}} 512 /keystring - 17 | 18 | newdb : 19 | dd if=/dev/zero of={{webapp_fs}} bs=1M count=1 20 | chamelon format --block-size=512 {{webapp_fs}} 21 | 22 | tap : 23 | sudo ip tuntap add {{hypervisor_tap}} mode tap 24 | sudo ip addr add {{hypervisor_ip}}/24 dev tap100 25 | sudo ip link set dev {{hypervisor_tap}} up 26 | 27 | forward : 28 | # kernel: allow ipv4 forwarding 29 | sudo sysctl net.ipv4.ip_forward=1 30 | # set up NAT 31 | sudo iptables -t nat -A POSTROUTING -o {{hypervisor_uplink}} -j MASQUERADE 32 | # forward traffic on 80/443 to the guest IP 33 | sudo iptables -t nat -A PREROUTING -i {{hypervisor_uplink}} -p tcp --dport 443 -j DNAT --to-destination {{guest_ip}}:443 34 | sudo iptables -t nat -A PREROUTING -i {{hypervisor_uplink}} -p tcp --dport 80 -j DNAT --to-destination {{guest_ip}}:80 35 | # allow the forwarded traffic to reach the guest IP 36 | sudo iptables -A FORWARD -i {{hypervisor_uplink}} -o {{hypervisor_tap}} -p tcp --dport 443 -j ACCEPT 37 | sudo iptables -A FORWARD -i {{hypervisor_uplink}} -o {{hypervisor_tap}} -p tcp --dport 80 -j ACCEPT 38 | sudo iptables -A FORWARD -i {{hypervisor_uplink}} -o {{hypervisor_tap}} -p udp --sport 53 -j ACCEPT 39 | # allow any return traffic for connections initiated by the guest 40 | sudo iptables -A FORWARD -i {{hypervisor_uplink}} -o {{hypervisor_tap}} -p tcp -m state --state RELATED,ESTABLISHED -j ACCEPT 41 | # allow any traffic from the guest 42 | sudo iptables -A FORWARD -o {{hypervisor_uplink}} -i {{hypervisor_tap}} -s {{guest_ip}} -j ACCEPT 43 | 44 | unforward : 45 | sudo sysctl net.ipv4.ip_forward=0 46 | sudo iptables -t nat -F POSTROUTING 47 | sudo iptables -t nat -F PREROUTING 48 | sudo iptables -F FORWARD 49 | 50 | churn : 51 | make clean 52 | mirage configure -t hvt 53 | make 54 | 55 | new : 56 | #!/bin/bash 57 | loc=$(curl -v -k --data uuid=$(dd if=/dev/urandom bs=16 count=1|base64) https://{{guest_ip}}/auth 2>&1 | grep location|cut -f3 -d' ') 58 | echo "loc: $loc" 59 | 60 | extant : 61 | #!/bin/bash 62 | id=$(chamelon ls {{webapp_fs}} 512 /|head -1|cut -d' ' -f1) 63 | curl -k --data state=${id} https://{{guest_ip}}/token 64 | 65 | loadtest : 66 | #!/bin/bash 67 | echo "uuid=16charsnwdyaget" > loadtest 68 | vegeta_content="POST https://{{fqdn}}/auth" 69 | echo "$vegeta_content" | vegeta attack -body loadtest -duration 5s | vegeta report 70 | rm loadtest || true 71 | -------------------------------------------------------------------------------- /le.ml: -------------------------------------------------------------------------------- 1 | module Shim(Cohttp_client : Cohttp_lwt.S.Client) = struct 2 | module Headers = Cohttp.Header 3 | module Response = struct 4 | include Cohttp.Response 5 | let status t = Cohttp.Response.status t |> Cohttp.Code.code_of_status 6 | end 7 | module Body = Cohttp_lwt__.Body 8 | include Cohttp_client 9 | end 10 | 11 | module Make 12 | (Kv : Mirage_kv.RW) 13 | (Time : Mirage_time.S) 14 | (Http_server : Cohttp_mirage.Server.S) 15 | (Http_client : Cohttp_lwt.S.Client) 16 | = struct 17 | module Http_client_shim = Shim(Http_client) 18 | module Acme = Letsencrypt.Client.Make(Http_client_shim) 19 | 20 | let cert_key = Mirage_kv.Key.v "certificate" 21 | let pk_key = Mirage_kv.Key.v "pk" 22 | let http_port = 80 23 | let https_port = 443 24 | 25 | let prefix = ".well-known", "acme-challenge" 26 | let tokens = Hashtbl.create 1 27 | 28 | let cn host = X509.[Distinguished_name.(Relative_distinguished_name.singleton (CN host))] 29 | 30 | let csr host key = 31 | X509.Signing_request.create (cn host) key 32 | 33 | let solver _host ~prefix:_ ~token ~content = 34 | Hashtbl.replace tokens token content; 35 | Lwt.return (Ok ()) 36 | 37 | (* It's important (more so than normal) that this function terminate, 38 | * because we call it with Lwt.async later *) 39 | let letsencrypt_dispatch request _body = 40 | let path = Uri.path (Cohttp.Request.uri request) in 41 | Logs.debug (fun m -> m "let's encrypt dispatcher %s" path); 42 | (* we expect very particular incoming requests from the LE web client. 43 | * Only if the incoming URI matches the right form should we 44 | * even check to see whether the token's in the store. *) 45 | match Astring.String.cuts ~sep:"/" ~empty:false path with 46 | | [p1; p2; token] when 47 | String.equal p1 (fst prefix) && String.equal p2 (snd prefix) -> begin 48 | (* anyone trying .well-known/acme-challenge/not-the-token gets a 404 *) 49 | match Hashtbl.find_opt tokens token with 50 | | None -> Http_server.respond ~status:`Not_found ~body:`Empty () 51 | | Some data -> 52 | let headers = 53 | Cohttp.Header.init_with "content-type" "application/octet-stream" 54 | in 55 | (* respond to the challenge with the data we have available *) 56 | Http_server.respond ~headers ~status:`OK ~body:(`String data) () 57 | 58 | end 59 | | _ -> 60 | (* TODO: we could refer this to another dispatcher, 61 | * which might know what to do *) 62 | Http_server.respond ~status:`Not_found ~body:`Empty () 63 | 64 | let provision_certificate host ctx = 65 | let open Lwt_result.Infix in 66 | let endpoint = 67 | (* the example code contains a switch here for a production key, 68 | * so we can use Letsencrypt.letsencrypt_production_url 69 | * or the staging one as appropriate. 70 | * We test in prod ;) 71 | *) 72 | Letsencrypt.letsencrypt_production_url 73 | in 74 | 75 | (* email and seed are provided arguments in the example code; 76 | * let's see if we can get by without them *) 77 | 78 | (* the example code does some contortions to inject the seed 79 | * here if it's been provided. We DGAF so just let generate 80 | * handle it. *) 81 | let priv = `RSA (Mirage_crypto_pk.Rsa.generate ~bits:4096 ()) in 82 | match csr host priv with 83 | | Error (`Msg err) -> 84 | Logs.err (fun m -> m "couldn't create signing request for our key: %s" err); 85 | (* The choice to `exit` here is debatable - we could return and serve on HTTP only *) 86 | exit 1 87 | | Ok csr -> 88 | let http_connection_pk = Mirage_crypto_pk.Rsa.generate ~bits:4096 () in 89 | Logs.debug (fun f -> f "keys made; initializing acme server"); 90 | Acme.initialise ~ctx ~endpoint (`RSA http_connection_pk) >>= fun lets_encrypt -> 91 | let sleep sec = Time.sleep_ns (Duration.of_sec sec) in 92 | let solver = Letsencrypt.Client.http_solver solver in 93 | Logs.debug (fun f -> f "attempting to get certificate signed"); 94 | Acme.sign_certificate ~ctx solver lets_encrypt sleep csr >|= fun certs -> (certs, priv) 95 | 96 | let serve cb = 97 | let callback _ = cb 98 | and conn_closed _ = () 99 | in 100 | Http_server.make ~conn_closed ~callback () 101 | 102 | let retrieve kv = 103 | let open Lwt.Infix in 104 | Lwt_result.both (Kv.get kv cert_key) (Kv.get kv pk_key) >>= function 105 | | Error e -> Lwt.return @@ Error (`Msg (Format.asprintf "%a" Kv.pp_error e)) 106 | | Ok (certs, pk) -> 107 | match 108 | (X509.Certificate.decode_pem_multiple @@ Cstruct.of_string certs), 109 | (X509.Private_key.decode_pem @@ Cstruct.of_string pk) 110 | with 111 | | Ok cert_list, Ok private_key -> 112 | Lwt.return @@ Ok (cert_list, private_key) 113 | | Error (`Msg s), _ -> Lwt.return @@ Error (`Msg (Format.asprintf "error decoding certificate list: %s" s)) 114 | | _, Error (`Msg s) -> Lwt.return @@ Error (`Msg (Format.asprintf "error decoding certificate list: %s" s)) 115 | 116 | let rec provision host kv http_server_impl http_client start_time = 117 | let open Lwt.Infix in 118 | retrieve kv >>= function 119 | | Ok (certs, pk) -> begin 120 | let soonest time_a time_b = 121 | if Ptime.is_earlier ~than:time_a time_b then time_b else time_a 122 | in 123 | let first_expiration = List.fold_left (fun acc c -> 124 | soonest acc @@ snd @@ X509.Certificate.validity c 125 | ) Ptime.max certs 126 | in 127 | let default_duration = Duration.of_day 7 in 128 | match Ptime.sub_span first_expiration start_time with 129 | | None -> Lwt.return ((certs, pk), default_duration) 130 | | Some wait_time -> 131 | match Ptime.to_span wait_time |> Ptime.Span.to_int_s with 132 | | None -> Lwt.return ((certs, pk), default_duration) 133 | | Some n when n < 0 -> Lwt.return ((certs, pk), default_duration) 134 | | Some expiration -> Lwt.return ((certs, pk), (Duration.of_sec expiration)) 135 | end 136 | | Error (`Msg s) -> 137 | Logs.debug (fun f -> f "error getting cert and pk from the cert store: %s" s); 138 | Logs.info (fun m -> m "listening on tcp/%d for Let's Encrypt provisioning" http_port); 139 | (* "this should be cancelled once certificates are retrieved", 140 | * says the source material *) 141 | let letsencrypt_http_server = http_server_impl (`TCP http_port) @@ serve letsencrypt_dispatch in 142 | Lwt.dont_wait (fun () -> letsencrypt_http_server) (fun _ex -> ()); 143 | provision_certificate host http_client >>= function 144 | | Error (`Msg s) -> 145 | let wait_duration = 15 in 146 | Logs.err (fun f -> f "error provisioning TLS certificate: %s" s); 147 | (* Since the error may be transient, wait a bit and try again *) 148 | Logs.err (fun f -> f "waiting %d minutes, then trying again" wait_duration); 149 | Time.sleep_ns (Duration.of_min wait_duration) >>= fun () -> 150 | provision host kv http_server_impl http_client start_time 151 | | Ok (certificates, pk) -> 152 | let certs_to_save = X509.Certificate.encode_pem_multiple certificates in 153 | let pk_to_save = X509.Private_key.encode_pem pk in 154 | Lwt_result.both 155 | (Kv.set kv cert_key @@ Cstruct.to_string certs_to_save) 156 | (Kv.set kv pk_key @@ Cstruct.to_string pk_to_save) >>= function 157 | | Ok ((), ()) -> 158 | Logs.debug (fun f -> f "saved private key and certs in the cert store"); 159 | Lwt.return ((certificates, pk), Duration.of_day 80) 160 | | Error e -> 161 | Logs.err (fun f -> f "error saving private key and certs: %a" Kv.pp_write_error e); 162 | Lwt.return ((certificates, pk), Duration.of_day 80) 163 | 164 | end 165 | -------------------------------------------------------------------------------- /pkce.ml: -------------------------------------------------------------------------------- 1 | module Make(Random : Mirage_random.S) = struct 2 | 3 | let alphabet = Base64.uri_safe_alphabet 4 | 5 | let challenge verifier = 6 | Base64.encode_string ~pad:false ~alphabet @@ 7 | Cstruct.to_string @@ 8 | Mirage_crypto.Hash.SHA256.(digest (Cstruct.of_string verifier)) 9 | 10 | let verifier () = 11 | Random.generate 32 |> Cstruct.to_string |> Base64.(encode_string ~pad:false ~alphabet:uri_safe_alphabet) 12 | 13 | end 14 | -------------------------------------------------------------------------------- /recycler.ml: -------------------------------------------------------------------------------- 1 | open Lwt.Infix 2 | 3 | module Make(Clock : Mirage_clock.PCLOCK)(Kv : Mirage_kv.RW) = struct 4 | let older_than kv ptime = 5 | Kv.list kv Mirage_kv.Key.empty >>= function 6 | | Error e -> 7 | Logs.err (fun f -> f "error listing /: %a" Kv.pp_error e); 8 | Lwt.return [] 9 | | Ok l -> 10 | (* for any entry in the list where we can't get last_modified info, 11 | * or the last_modified isn't parseable, 12 | * return true -- if we don't, these entries will just stick around forever *) 13 | Lwt_list.filter_p (fun (name, value_or_dict) -> 14 | Kv.last_modified kv (Mirage_kv.Key.v name) >>= function 15 | | Error _ -> Lwt.return true 16 | | Ok (d, ps) -> 17 | try 18 | let write_time = Ptime.v (d, ps) in 19 | Lwt.return @@ Ptime.is_earlier ~than:ptime write_time 20 | with 21 | | Invalid_argument _ -> Lwt.return true 22 | ) l 23 | 24 | let prune kv expiration_span = 25 | let now = Clock.now_d_ps () |> Ptime.v in 26 | match Ptime.sub_span now expiration_span with 27 | | None -> 28 | Logs.err (fun f -> f "failed to calculate cutoff time for recycling items"); 29 | Lwt.return_unit 30 | | Some cutoff -> 31 | Logs.debug (fun f -> f "deleting entries with no updates since %a" Ptime.pp cutoff); 32 | older_than kv cutoff >>= fun to_prune -> 33 | Logs.debug (fun f -> f "deleting %d expired entries" (List.length to_prune)); 34 | Lwt_list.iter_p (fun (item, _) -> 35 | Kv.remove kv (Mirage_kv.Key.v item) >>= function 36 | | Error e -> Logs.err (fun f -> f "error removing item to be pruned: %s" item); 37 | Lwt.return_unit 38 | | Ok () -> Lwt.return_unit 39 | ) to_prune 40 | 41 | end 42 | -------------------------------------------------------------------------------- /resource.ml: -------------------------------------------------------------------------------- 1 | (* URL to hit for initial redirect URL generation and access token refreshing *) 2 | let auth_url = Uri.of_string "https://api.etsy.com/v3/public/oauth/token" 3 | 4 | (* how long should we assume access tokens are valid for, if their expiration 5 | * time can't be looked up? *) 6 | let default_access_expiration = Ptime.Span.of_int_s 3600 7 | 8 | (* which scopes should we request? *) 9 | let requested_scopes = String.concat " " ["listings_r"; "listings_w"] 10 | 11 | (* how long should we assume *refresh* tokens are valid for? *) 12 | let expiration_span = Ptime.Span.v (90, 0L) 13 | 14 | (* once the resource server has verified the access, 15 | * what URL should we serve the code verifier back to? *) 16 | (* This is expressed as a series of components to be fed to Uri.Make 17 | * because the query portion needs to be added, and it's easier 18 | * to just construct the Uri.t in situ with this info provided *) 19 | module Verify_url = struct 20 | let host = "etsy.com" 21 | let path = "/oauth/connect" 22 | let scheme = "https" 23 | end 24 | -------------------------------------------------------------------------------- /unikernel.ml: -------------------------------------------------------------------------------- 1 | open Lwt.Infix 2 | 3 | let gc_interval = Duration.of_hour 1 4 | 5 | module Main 6 | (Cert_block : Mirage_block.S) 7 | (App_block : Mirage_block.S) 8 | (Clock : Mirage_clock.PCLOCK) 9 | (Time : Mirage_time.S) 10 | (Random : Mirage_random.S) 11 | (Http : Cohttp_mirage.Server.S) 12 | (Client : Cohttp_lwt.S.Client) 13 | = struct 14 | module Logs_reporter = Mirage_logs.Make(Clock) 15 | module Cert_database = Kv.Make(Cert_block)(Clock) 16 | module App_database = Kv.Make(App_block)(Clock) 17 | module LE = Le.Make(Cert_database)(Time)(Http)(Client) 18 | module OAuth2 = Webapp.Make(Random)(Clock)(App_database)(Http)(Client) 19 | module Recycle = Recycler.Make(Clock)(App_database) 20 | 21 | let start cert_block app_block pclock _time _random http_server http_client = 22 | let open Lwt.Infix in 23 | let host = Key_gen.host () in 24 | let path = Key_gen.path () in 25 | Logs_reporter.(create pclock |> run) @@ fun () -> 26 | (* solo5 requires us to use a block size of, at maximum, 512 *) 27 | Cert_database.connect ~program_block_size:16 cert_block >>= function 28 | | Error e -> Logs.err (fun f -> f "failed to initialize block-backed key-value store for certs: %a" Cert_database.pp_error e); 29 | Lwt.return_unit 30 | | Ok cert_kv -> 31 | Logs.info (fun f -> f "block-backed key-value store for certs up and running"); 32 | Cert_database.get cert_kv (Mirage_kv.Key.v "keystring") >>= function 33 | | Error e -> Logs.err (fun f -> f "Couldn't retrieve the keystring from the cert store: %a" Cert_database.pp_error e); 34 | Lwt.return_unit 35 | | Ok keystring -> 36 | App_database.connect ~program_block_size:16 app_block >>= function 37 | | Error e -> Logs.err (fun f -> f "failed to initialize block-backed key-value store for appplication: %a" App_database.pp_error e); 38 | Lwt.return_unit 39 | | Ok kv -> 40 | let start_time = Clock.now_d_ps () |> Ptime.Span.v in 41 | LE.provision host cert_kv http_server http_client start_time >>= fun ((certificates, pk), renew_after) -> 42 | Logs.debug (fun f -> f "usable certificates found in the cert store (valid for %Ld ns)" renew_after); 43 | let rec provision () = 44 | let tls_cfg = Tls.Config.server ~certificates:(`Single (certificates, pk)) () in 45 | let tls = `TLS (tls_cfg, `TCP 443) in 46 | let https = 47 | Logs.info (fun f -> f "(re-)initialized https listener"); 48 | http_server tls @@ OAuth2.serve ~keystring ~host ~path kv http_client 49 | in 50 | let expire = Time.sleep_ns renew_after in 51 | let http = 52 | (* replacement service on port 80 is a tarpit *) 53 | let tarpit _ _ _ = Lwt.return @@ 54 | (Cohttp.Response.make ~status:Cohttp.Code.(`Internal_server_error) (), 55 | Cohttp_lwt__.Body.of_string "Internal server error") 56 | in 57 | let port = `TCP 80 in 58 | http_server port @@ 59 | Http.make ~conn_closed:(fun _ -> ()) ~callback:tarpit () 60 | in 61 | let gc = Recycle.prune kv Resource.expiration_span in 62 | let rec keep_pruning () = 63 | gc >>= fun () -> 64 | Time.sleep_ns gc_interval >>= fun () -> 65 | keep_pruning () 66 | in 67 | Lwt.pick [ 68 | https ; 69 | http ; 70 | expire; 71 | keep_pruning (); 72 | ] >>= fun () -> 73 | provision () 74 | in 75 | provision () 76 | end 77 | -------------------------------------------------------------------------------- /webapp.ml: -------------------------------------------------------------------------------- 1 | open Lwt.Infix 2 | 3 | type verifier = string (* code_verifier from PKCE *) 4 | type state = string (* "state" from Etsy OpenAPI 3.0 *) 5 | type code = string (* "code" from Etsy OpenAPI 3.0, returned from resource server after a successful grant from the end user *) 6 | type token = string 7 | 8 | type authentication_step = 9 | | None 10 | | Began of state * verifier 11 | | Awaiting_tokens of code 12 | | Has_tokens of token (* returns only the refresh token, I guess? *) 13 | 14 | module Make 15 | (Random : Mirage_random.S) 16 | (Clock : Mirage_clock.PCLOCK) 17 | (Kv : Mirage_kv.RW) 18 | (H : Cohttp_mirage.Server.S) 19 | (Client : Cohttp_lwt.S.Client) = struct 20 | 21 | module PKCE = Pkce.Make(Random) 22 | 23 | let code = Mirage_kv.Key.v "code" 24 | let state = Mirage_kv.Key.v "state" 25 | let verifier = Mirage_kv.Key.v "verifier" 26 | let access = Mirage_kv.Key.v "access" 27 | let refresh = Mirage_kv.Key.v "refresh" 28 | let expiration = Mirage_kv.Key.v "expires_in" 29 | 30 | let not_found = ( 31 | Cohttp.Response.make ~status:Cohttp.Code.(`Not_found) (), 32 | Cohttp_lwt__.Body.of_string "Not found") 33 | 34 | let ise = ( 35 | Cohttp.Response.make ~status:Cohttp.Code.(`Internal_server_error) (), 36 | Cohttp_lwt__.Body.of_string "Internal server error") 37 | 38 | let bad_request = ( 39 | Cohttp.Response.make ~status:Cohttp.Code.(`Bad_request) (), 40 | Cohttp_lwt__.Body.of_string "Bad request") 41 | 42 | let ok_empty = ( 43 | Cohttp.Response.make ~status:Cohttp.Code.(`OK) (), 44 | Cohttp_lwt__.Body.empty) 45 | 46 | let start_auth kv = 47 | let new_state = PKCE.verifier () in 48 | let new_verifier = PKCE.verifier () in 49 | Kv.set kv Mirage_kv.Key.(v new_state // verifier) new_verifier >>= function 50 | | Error e -> Logs.err (fun f -> f "error storing new state and verifier: %a" Kv.pp_write_error e); 51 | Lwt.return @@ Error `Storage 52 | | Ok () -> Lwt.return @@ Ok (new_state, new_verifier) 53 | 54 | let maybe_store_tokens kv state body = 55 | let store kv state access_token refresh_token seconds = 56 | Lwt_result.both 57 | (Lwt_result.both 58 | (Kv.set kv Mirage_kv.Key.(v state // access) access_token) 59 | (Kv.set kv Mirage_kv.Key.(v state // refresh) refresh_token)) 60 | (Kv.set kv Mirage_kv.Key.(v state // expiration) seconds) >>= function 61 | | Error e -> 62 | Logs.err (fun f -> f "error writing tokens: %a" Kv.pp_write_error e); 63 | Lwt.return_unit 64 | | Ok _ -> Lwt.return_unit 65 | in 66 | try 67 | let result = Yojson.Safe.from_string body in 68 | let open Yojson.Safe.Util in 69 | match member "access_token" result, member "refresh_token" result, member "expires_in" result with 70 | | `String access_token, `String refresh_token, `Int expires_in -> 71 | store kv state access_token refresh_token (string_of_int expires_in) 72 | | _, _, _ -> Logs.err (fun f -> f "response did not contain usable tokens & expiration"); 73 | Lwt.return_unit 74 | with 75 | | Yojson.Json_error s -> 76 | Logs.debug (fun f -> f "exception handling token response from remote server: %s" s); 77 | Lwt.return_unit 78 | 79 | let request_token ~keystring ~host ~path kv http_client state = 80 | Lwt_result.both 81 | (Kv.get kv Mirage_kv.Key.(v state // verifier)) @@ 82 | Kv.get kv Mirage_kv.Key.(v state // code) >>= function 83 | | Error e -> Logs.err (fun f -> f "error retrieving verifier or code when attempting to get a token: %a" Kv.pp_error e); 84 | Lwt.return_unit 85 | | Ok (this_verifier, this_code) -> 86 | Logs.debug (fun f -> f "constructing request for tokens"); 87 | (* this is where we have to make our own request to the remote server *) 88 | let redirect_uri = "https://" ^ host ^ path in 89 | let params = [ 90 | "grant_type", ["authorization_code"]; 91 | "client_id", [keystring]; 92 | "redirect_uri", [redirect_uri]; 93 | "code", [this_code]; 94 | "code_verifier", [this_verifier] 95 | ] in 96 | let uri = Resource.auth_url in 97 | Logs.debug (fun f -> f "asking for %s" (Uri.to_string uri)); 98 | Client.post_form ~ctx:http_client ~params uri >>= fun (response, body) -> 99 | Cohttp_lwt__.Body.to_string body >>= fun bstr -> 100 | Logs.debug (fun f -> f "response from token get: %s" bstr); 101 | maybe_store_tokens kv state bstr 102 | 103 | let maybe_initiate_state ~keystring ~host ~path kv http_client request = 104 | Logs.debug (fun f -> f "HI ETSY: %s" @@ Uri.to_string @@ Cohttp.Request.uri request); 105 | let request = Cohttp.Request.uri request in 106 | match Uri.get_query_param request "code", Uri.get_query_param request "state" with 107 | | None, None | None, _ | _, None -> 108 | Logs.debug (fun f -> f "GET from /etsy without required params"); 109 | Lwt.return @@ bad_request 110 | | Some this_code, Some this_state -> begin 111 | let this_code = Uri.pct_decode this_code in 112 | let this_state = Uri.pct_decode this_state in 113 | Kv.exists kv @@ Mirage_kv.Key.v this_state >>= function 114 | | Error e -> Logs.err (fun f -> f "error retrieving a state: %a" Kv.pp_error e); 115 | Lwt.return @@ ise 116 | | Ok None -> Lwt.return @@ bad_request 117 | | Ok (Some `Value) -> Logs.err (fun f -> f "state was a value, not a dictionary; refusing to store code"); 118 | Lwt.return @@ ise 119 | | Ok (Some `Dictionary) -> begin 120 | Kv.set kv Mirage_kv.Key.(v this_state // code) this_code >>= function 121 | | Error e -> Logs.err (fun f -> f 122 | "got a valid looking code for a real state, \ 123 | but failed to save it: %a" Kv.pp_write_error e); 124 | Lwt.return @@ ise 125 | | Ok () -> 126 | Logs.debug (fun f -> f "code retrieved and saved; requesting tokens"); 127 | Lwt.dont_wait (fun () -> request_token ~keystring ~path ~host kv http_client this_state) (fun _ -> ()); 128 | Lwt.return @@ ok_empty 129 | end 130 | end 131 | 132 | let refresh_access kv ~keystring http_client this_state = 133 | Kv.get kv Mirage_kv.Key.(v this_state // refresh) >>= function 134 | | Error (`Not_found _) -> Lwt.return_unit 135 | | Error e -> Logs.err (fun f -> f "getting refresh token: %a" Kv.pp_error e); 136 | Lwt.return_unit 137 | | Ok this_refresh -> 138 | let params = [ 139 | "grant_type", ["refresh_token"]; 140 | "client_id", [keystring]; 141 | "refresh_token", [this_refresh]; 142 | ] in 143 | let url = Resource.auth_url in 144 | Logs.debug (fun f -> f "asking for token refresh"); 145 | Client.post_form ~ctx:http_client ~params url >>= fun (response, body) -> 146 | Cohttp_lwt__.Body.to_string body >>= fun bstr -> 147 | Logs.debug (fun f -> f "response from token refresh: %d" @@ Cohttp.Code.code_of_status @@ Cohttp.Response.status response); 148 | match Cohttp.Code.code_of_status @@ Cohttp.Response.status response with 149 | | 200 -> maybe_store_tokens kv this_state bstr 150 | | n -> 151 | Logs.err (fun f -> f "error %d from remote host when requesting refresh token" n); 152 | Lwt.return_unit 153 | 154 | let rec maybe_serve_token kv ~can_refresh ~keystring http_client this_state = 155 | Lwt_result.both 156 | (Kv.get kv Mirage_kv.Key.(v this_state // expiration)) 157 | @@ 158 | Lwt_result.both 159 | (Kv.get kv Mirage_kv.Key.(v this_state // access)) 160 | (Kv.last_modified kv Mirage_kv.Key.(v this_state // access)) 161 | >>= function 162 | | Error (`Not_found _) -> Lwt.return not_found 163 | | Error e -> Logs.err (fun f -> f "getting access code for client: %a" Kv.pp_error e); 164 | Lwt.return ise 165 | | Ok (expiration, (access_token, modified_time)) -> 166 | let valid_duration = 167 | try Ptime.Span.of_int_s @@ int_of_string expiration with 168 | | Invalid_argument _ -> Resource.default_access_expiration 169 | in 170 | (* we don't have any particularly good reason to assume that last_modified 171 | * isn't some malicious-ass garbage, so make sure we handle that case *) 172 | try 173 | let valid_time_start = Ptime.Span.v modified_time in 174 | let now = Clock.now_d_ps () |> Ptime.v in 175 | match Ptime.(of_span @@ Span.add valid_duration valid_time_start) with 176 | | None -> Lwt.return not_found 177 | | Some end_valid_time -> 178 | if Ptime.(is_later ~than:now end_valid_time) then 179 | Lwt.return @@ (Cohttp.Response.make ~status:Cohttp.Code.(`OK) (), 180 | Cohttp_lwt__.Body.of_string access_token) 181 | else if can_refresh then begin 182 | refresh_access kv ~keystring http_client this_state >>= fun () -> 183 | maybe_serve_token kv ~can_refresh:false ~keystring http_client this_state 184 | end else 185 | Lwt.return not_found 186 | with 187 | | Invalid_argument _ -> Lwt.return ise 188 | 189 | let serve ~keystring ~host ~path kv http_client = 190 | let callback _connection request body = 191 | (* Cohttp_lwt says we need to always "drain" the body, 192 | * even though in most cases we won't look at it *) 193 | Cohttp_lwt__.Body.to_form body >>= fun entries -> 194 | let endpoint = Mirage_kv.Key.v @@ Uri.path @@ Cohttp.Request.uri request in 195 | let meth = Cohttp.Request.meth request in 196 | 197 | (* we define handlers only for the method/endpoint pairs we expect to serve, 198 | * which is a pretty constrained set *) 199 | match meth with 200 | | `GET when Mirage_kv.Key.equal endpoint @@ Mirage_kv.Key.v path -> 201 | maybe_initiate_state ~keystring ~host ~path kv http_client request 202 | | `POST when Mirage_kv.Key.equal endpoint @@ Mirage_kv.Key.v "/token" -> 203 | begin 204 | Logs.debug (fun f -> f "entries: %a" Fmt.(list string) (List.map fst entries)); 205 | match List.assoc_opt "state" entries with 206 | | None -> Logs.debug (fun f -> f "no state"); Lwt.return bad_request 207 | | Some [] | Some (_::_::_) -> Lwt.return bad_request 208 | | Some (this_state::[]) -> 209 | maybe_serve_token kv ~can_refresh:true ~keystring http_client this_state 210 | end 211 | | `POST when Mirage_kv.Key.equal endpoint @@ Mirage_kv.Key.v "/auth" -> 212 | Logs.debug (fun f -> f "entries: %a" Fmt.(list string) (List.map fst entries)); 213 | match List.assoc_opt "uuid" entries with 214 | | None | Some [] | Some (_::_::_) -> Lwt.return bad_request 215 | | Some (uuid::[]) -> 216 | start_auth kv >>= function 217 | | Error `Lookup -> Logs.err (fun f -> f "error looking up uuid, failing"); 218 | Lwt.return ise 219 | | Error `Storage -> Logs.err (fun f -> f "error retrieving uuid-related information from storage, failing"); 220 | Lwt.return ise 221 | | Ok (state, verifier) -> 222 | Logs.debug (fun f -> f "state and verifier found or made for request; generating redirect URI for resource server"); 223 | let parameters = [ 224 | "response_type", ["code"]; 225 | "client_id", [keystring]; 226 | "redirect_uri", ["https://" ^ host ^ path ]; 227 | "scope", [Resource.requested_scopes]; 228 | "state", [state]; 229 | "code_challenge", [PKCE.challenge verifier]; 230 | "code_challenge_method", ["S256"]; 231 | ] in 232 | let url = 233 | let open Resource.Verify_url in 234 | Uri.make ~scheme ~host ~path ~query:parameters () 235 | in 236 | let headers = Cohttp.Header.init_with "Location" (Uri.to_string url) in 237 | let response = Cohttp.Response.make ~status:Cohttp.Code.(`Temporary_redirect) ~headers () in 238 | let body = Cohttp_lwt__.Body.of_string state in 239 | Lwt.return (response, body) 240 | | _ -> Lwt.return @@ ise 241 | in 242 | H.make ~conn_closed:(fun _ -> ()) ~callback () 243 | end 244 | --------------------------------------------------------------------------------