pax_global_header00006660000000000000000000000064150251462540014516gustar00rootroot0000000000000052 comment=6bd63f15c220f1620789569060f918bcb614c12a apt-transport-oci-0.1.1/000077500000000000000000000000001502514625400151035ustar00rootroot00000000000000apt-transport-oci-0.1.1/.github/000077500000000000000000000000001502514625400164435ustar00rootroot00000000000000apt-transport-oci-0.1.1/.github/dependabot.yml000066400000000000000000000003651502514625400212770ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: gomod directory: "/" schedule: interval: weekly open-pull-requests-limit: 10 - package-ecosystem: github-actions directory: "/" schedule: interval: weekly open-pull-requests-limit: 10 apt-transport-oci-0.1.1/.github/workflows/000077500000000000000000000000001502514625400205005ustar00rootroot00000000000000apt-transport-oci-0.1.1/.github/workflows/main.yml000066400000000000000000000014741502514625400221550ustar00rootroot00000000000000name: CI on: push: branches: - master - 'release/**' pull_request: jobs: main: env: GOTOOLCHAIN: local strategy: fail-fast: false matrix: go: ["stable", "oldstable"] runs-on: ubuntu-24.04 timeout-minutes: 10 steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: go-version: ${{ matrix.go }} - run: go test -v ./... - run: go build ./cmd/usr-lib-apt-methods-oci - run: sudo cp -a usr-lib-apt-methods-oci /usr/lib/apt/methods/oci - run: echo "deb [trusted=yes] oci://ghcr.io/akihirosuda/hello-apt-transport-oci:latest /" | sudo tee /etc/apt/sources.list.d/oci.list - run: sudo apt-get update - run: sudo apt-get install hello-apt-transport-oci - run: hello-apt-transport-oci apt-transport-oci-0.1.1/LICENSE000066400000000000000000000261361502514625400161200ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. apt-transport-oci-0.1.1/README.md000066400000000000000000000054321502514625400163660ustar00rootroot00000000000000# apt-transport-oci: OCI transport plugin for `apt-get` (i.e., `apt-get` over `ghcr.io`) `apt-transport-oci` is an `apt-get` plugin to support distributing `*.deb` packages over an OCI registry such as `ghcr.io` . ## Motivation The motivation is to distribute `*.deb` packages without running a web server but using a popular fully-managed service such as `ghcr.io`. If GitHub could offer fully-managed apt repo, this plugin wouldn't be needed. ## Usage - Install the `apt-transport-oci` plugin onto `/usr/lib/apt/methods/oci`: ``` sudo go build -o /usr/lib/apt/methods/oci ./cmd/usr-lib-apt-methods-oci ``` - Create `/etc/apt/sources.list.d/oci.list` with the following content to enable [`oci://ghcr.io/akihirosuda/hello-apt-transport-oci`](https://ghcr.io/akihirosuda/hello-apt-transport-oci) repo: ``` deb [trusted=yes] oci://ghcr.io/akihirosuda/hello-apt-transport-oci:latest / ``` - Run `sudo apt-get update && sudo apt-get install hello-apt-transport-oci` ```console $ sudo apt-get update ... Get:7 oci://ghcr.io/akihirosuda/hello-apt-transport-oci:latest Packages [478 B] ... Reading package lists... Done ``` ```console $ sudo apt-get install hello-apt-transport-oci Reading package lists... Done Building dependency tree... Done Reading state information... Done The following NEW packages will be installed: hello-apt-transport-oci 0 upgraded, 1 newly installed, 0 to remove and 1 not upgraded. Need to get 1,106 B of archives. After this operation, 0 B of additional disk space will be used. Get:1 oci://ghcr.io/akihirosuda/hello-apt-transport-oci:latest hello-apt-transport-oci 0.0 [1,106 B] Selecting previously unselected package hello-apt-transport-oci. (Reading database ... 249739 files and directories currently installed.) Preparing to unpack .../hello-apt-transport-oci_0.0_amd64.deb ... Unpacking hello-apt-transport-oci (0.0) ... Setting up hello-apt-transport-oci (0.0) ... ``` - Make sure `hello-apt-transport-oci` is installed ```console $ hello-apt-transport-oci Hello, apt-transport-oci ``` ### Hints - Create `/root/.docker/config.json` to enable authentication. - Non-TLS registry is supported only for 127.0.0.1 - Troubleshooting: Run `apt-get -o Debug::pkgAcquire::Worker=1 update 2>&1` and grep `FailReason` ## Creating an apt repo See [`./examples`](./examples) . ## Specification The spec corresponds to the behavior of `oras push IMAGE FILE1:application/octet-stream FILE2:application/octet-stream ...` (ORAS v0.12). - An image index MAY have multiple manifests, but all the manifests SHOULD refer to the same set of layers (because `apt-get` itself supports multi-arch repo). - A layer MUST have `org.opencontainers.image.title` annotation that corresponds to the file name. - A layer SHOULD have one of the following media types: - `application/octet-stream` - `application/x-binary` apt-transport-oci-0.1.1/cmd/000077500000000000000000000000001502514625400156465ustar00rootroot00000000000000apt-transport-oci-0.1.1/cmd/usr-lib-apt-methods-oci/000077500000000000000000000000001502514625400222165ustar00rootroot00000000000000apt-transport-oci-0.1.1/cmd/usr-lib-apt-methods-oci/main.go000066400000000000000000000002561502514625400234740ustar00rootroot00000000000000package main import ( "context" "os" "github.com/AkihiroSuda/apt-transport-oci/pkg/method" ) func main() { method.New(os.Stdout, os.Stdin).Run(context.Background()) } apt-transport-oci-0.1.1/examples/000077500000000000000000000000001502514625400167215ustar00rootroot00000000000000apt-transport-oci-0.1.1/examples/.gitignore000066400000000000000000000000171502514625400207070ustar00rootroot00000000000000*.deb Packages apt-transport-oci-0.1.1/examples/README.md000066400000000000000000000030231502514625400201760ustar00rootroot00000000000000# Creating an apt repo on an OCI registry ## Step 1: Create dpkg Create `hello-apt-transport-oci_0.0_amd64.deb` from [`helloapt-transport-oci` directory](./hello-apt-transport-oci). The easiest way is to use [fpm](https://fpm.readthedocs.io/). ```bash sudo gem install fpm ``` ```bash fpm -s dir -t deb -m example@example.com -n hello-apt-transport-oci -v 0.0 ./hello-apt-transport-oci/usr/bin/hello-apt-transport-oci=/usr/bin/hello-apt-transport-oci ``` ## Step 2: Create metadata Create `Packages` file ``` dpkg-scanpackages -m . > Packages ``` Hint: to create GPG-signed repo, use [`apt-ftparchive`](https://www.google.com/search?q=apt-ftparchive+gpg) . ## Step 3: Push to an OCI registry Push the deb file and the `Packages` file to an OCI registry (e.g., `ghcr.io`). The easiest way is to use [ORAS](https://github.com/oras-project/oras) CLI. ```bash curl -fsSL https://github.com/oras-project/oras/releases/download/v0.12.0/oras_0.12.0_linux_amd64.tar.gz | sudo tar Cxzv /usr/local/bin/ oras ``` ```bash echo YOUR_GITHUB_PERSONAL_ACCESS_TOKEN | docker login ghcr.io -u USERNAME --password-stdin ``` ```bash oras push ghcr.io/USERNAME/hello-apt-transport-oci:latest hello-apt-transport-oci_0.0_amd64.deb:application/octet-stream Packages:application/octet-stream` ``` - See [GHCR documentation](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry) to learn how to create a GitHub Personal Access Token (PAT) for `ghcr.io`. - Use GitHub Web UI to make the image public / private. apt-transport-oci-0.1.1/examples/hello-apt-transport-oci/000077500000000000000000000000001502514625400234105ustar00rootroot00000000000000apt-transport-oci-0.1.1/examples/hello-apt-transport-oci/usr/000077500000000000000000000000001502514625400242215ustar00rootroot00000000000000apt-transport-oci-0.1.1/examples/hello-apt-transport-oci/usr/bin/000077500000000000000000000000001502514625400247715ustar00rootroot00000000000000apt-transport-oci-0.1.1/examples/hello-apt-transport-oci/usr/bin/hello-apt-transport-oci000077500000000000000000000000521502514625400314030ustar00rootroot00000000000000#!/bin/sh echo "Hello, apt-transport-oci" apt-transport-oci-0.1.1/go.mod000066400000000000000000000031351502514625400162130ustar00rootroot00000000000000module github.com/AkihiroSuda/apt-transport-oci go 1.23.0 require ( github.com/containerd/containerd/v2 v2.1.3 github.com/distribution/reference v0.6.0 github.com/docker/cli v28.2.2+incompatible github.com/opencontainers/go-digest v1.0.0 github.com/opencontainers/image-spec v1.1.1 github.com/sirupsen/logrus v1.9.3 ) require ( github.com/containerd/errdefs v1.0.0 // indirect github.com/containerd/log v0.1.0 // indirect github.com/containerd/platforms v1.0.0-rc.1 // indirect github.com/containerd/typeurl/v2 v2.2.3 // indirect github.com/docker/docker-credential-helpers v0.9.3 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/klauspost/compress v1.18.0 // indirect github.com/moby/locker v1.0.1 // indirect github.com/pkg/errors v0.9.1 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect go.opentelemetry.io/otel v1.36.0 // indirect go.opentelemetry.io/otel/metric v1.36.0 // indirect go.opentelemetry.io/otel/trace v1.36.0 // indirect golang.org/x/sync v0.15.0 // indirect golang.org/x/sys v0.33.0 // indirect google.golang.org/protobuf v1.36.6 // indirect gotest.tools/v3 v3.5.1 // indirect ) // LICENSE: // - containerd/{containerd, nerdctl}: Apache License 2.0 https://github.com/containerd/containerd/blob/main/LICENSE // - opencontainers/{go-digest, image-spec}: Apache License 2.0 https://github.com/opencontainers/go-digest/blob/master/LICENSE apt-transport-oci-0.1.1/go.sum000066400000000000000000000234721502514625400162460ustar00rootroot00000000000000github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk= github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= github.com/containerd/containerd/v2 v2.1.3 h1:eMD2SLcIQPdMlnlNF6fatlrlRLAeDaiGPGwmRKLZKNs= github.com/containerd/containerd/v2 v2.1.3/go.mod h1:8C5QV9djwsYDNhxfTCFjWtTBZrqjditQ4/ghHSYjnHM= github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/containerd/platforms v1.0.0-rc.1 h1:83KIq4yy1erSRgOVHNk1HYdPvzdJ5CnsWaRoJX4C41E= github.com/containerd/platforms v1.0.0-rc.1/go.mod h1:J71L7B+aiM5SdIEqmd9wp6THLVRzJGXfNuWCZCllLA4= github.com/containerd/typeurl/v2 v2.2.3 h1:yNA/94zxWdvYACdYO8zofhrTVuQY73fFU1y++dYSw40= github.com/containerd/typeurl/v2 v2.2.3/go.mod h1:95ljDnPfD3bAbDJRugOiShd/DlAAsxGtUBhJxIn7SCk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/docker/cli v28.2.2+incompatible h1:qzx5BNUDFqlvyq4AHzdNB7gSyVTmU4cgsyN9SdInc1A= github.com/docker/cli v28.2.2+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/docker-credential-helpers v0.9.3 h1:gAm/VtF9wgqJMoxzT3Gj5p4AqIjCBS4wrsOh9yRqcz8= github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/moby/locker v1.0.1 h1:fOXqR41zeveg4fFODix+1Ch4mj/gT0NE1XJbp/epuBg= github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= go.opentelemetry.io/otel v1.36.0 h1:UumtzIklRBY6cI/lllNZlALOF5nNIzJVb16APdvgTXg= go.opentelemetry.io/otel v1.36.0/go.mod h1:/TcFMXYjyRNh8khOAO9ybYkqaDBb/70aVwkNML4pP8E= go.opentelemetry.io/otel/metric v1.36.0 h1:MoWPKVhQvJ+eeXWHFBOPoBOi20jh6Iq2CcCREuTYufE= go.opentelemetry.io/otel/metric v1.36.0/go.mod h1:zC7Ks+yeyJt4xig9DEw9kuUFe5C3zLbVjV2PzT6qzbs= go.opentelemetry.io/otel/sdk v1.36.0 h1:b6SYIuLRs88ztox4EyrvRti80uXIFy+Sqzoh9kFULbs= go.opentelemetry.io/otel/sdk v1.36.0/go.mod h1:+lC+mTgD+MUWfjJubi2vvXWcVxyr9rmlshZni72pXeY= go.opentelemetry.io/otel/sdk/metric v1.36.0 h1:r0ntwwGosWGaa0CrSt8cuNuTcccMXERFwHX4dThiPis= go.opentelemetry.io/otel/sdk/metric v1.36.0/go.mod h1:qTNOhFDfKRwX0yXOqJYegL5WRaW376QbB7P4Pb0qva4= go.opentelemetry.io/otel/trace v1.36.0 h1:ahxWNuqZjpdiFAyrIoQ4GIiAIhxAunQR6MUoKrsNd4w= go.opentelemetry.io/otel/trace v1.36.0/go.mod h1:gQ+OnDZzrybY4k4seLzPAWNwVBBVlF2szhehOBB/tGA= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8= golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= apt-transport-oci-0.1.1/pkg/000077500000000000000000000000001502514625400156645ustar00rootroot00000000000000apt-transport-oci-0.1.1/pkg/apt/000077500000000000000000000000001502514625400164505ustar00rootroot00000000000000apt-transport-oci-0.1.1/pkg/apt/message.go000066400000000000000000000313241502514625400204260ustar00rootroot00000000000000/* Copyright the cloudflare Authors. Original source: https://github.com/cloudflare/apt-transport-cloudflared/blob/042a4c0e142f1fbd81aaf1a14f1e7f74f59109cd/apt/message.go We copy the source from upstream apt-transport-cloudflared for easier packaging on debian system. We can delete this file and add upstream apt-transport-cloudflared back when: 1, apt-transport-cloudflared is packaged in debian 2, apt-transport-oci can use the packaged apt-transport-cloudflared in debian Licensed under the BSD 3-clause License; you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/license/bsd-3-clause Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package apt import ( "bufio" "errors" "fmt" "io" "strconv" "strings" ) // CapFlags represents a set of Apt Capabilities. type CapFlags int const ( // CapSingleInstance indicates to Apt that the method may only have one // instance running at any given time. CapSingleInstance CapFlags = 0x01 // CapPipeline indicates to Apt that it may send multiple requests to the // method without waiting for each one to finish. CapPipeline CapFlags = 0x02 // CapSendConfig tells Apt to send a configuration message back with the // config values. CapSendConfig CapFlags = 0x04 // CapLocalOnly indicates to Apt that the resources are fetched locally. CapLocalOnly CapFlags = 0x08 // CapNeedsCleanup tells Apt not to terminate the process when done. CapNeedsCleanup CapFlags = 0x10 // CapRemovable tells Apt the method is working on a removable medium such // as a CDROM or USB drive. CapRemovable CapFlags = 0x20 // CapAuxRequests indicates to Apt that the method handles AuxRequests. CapAuxRequests CapFlags = 0x40 ) // Message represents a generic message as read from os.Stdin. type Message struct { StatusCode uint64 Description string Fields map[string]string } // Field represents a value field in a mesage. type Field struct { Key string Value string } // NewMessage creates a new message with the given fields. func NewMessage(statusCode uint64, description string, fields ...Field) *Message { fieldmap := make(map[string]string) for _, field := range fields { fieldmap[field.Key] = field.Value } return &Message{ statusCode, description, fieldmap, } } // MessageReader implements an interface for reading messages from an input // stream. type MessageReader struct { reader *bufio.Reader message *Message } // NewMessageReader creates a new MessageReader instance. // // This function sets the underlying bufio.Reader and sets the state such that // there is no currently processing message. func NewMessageReader(reader *bufio.Reader) *MessageReader { return &MessageReader{ reader, nil, } } // errorGroup is a helper function for creating an error that represents // several errors. func errorGroup(header string, errs []error) error { var sb strings.Builder sb.WriteString(header) for _, e := range errs { sb.WriteString("\n ") sb.WriteString(e.Error()) } return errors.New(sb.String()) } // ReadMessage reads a full message from the input. // // This function calls MessageReader.ReadLine() until a Message is returned // and then returns that. func (r *MessageReader) ReadMessage() (*Message, error) { var errs []error var err error var msg *Message for msg == nil { msg, err = r.ReadLine() if err != nil { if msg != nil || err == io.EOF { if len(errs) > 0 { errs = append(errs, err) return msg, errorGroup("Errors while reading message:", errs) } return msg, err } errs = append(errs, err) } } if len(errs) > 0 { return msg, errorGroup("Errors while reading message:", errs) } return msg, nil } // ReadLine reads a line from the input and processes it. // // This function will read exactly 1 line from the input Reader, and do one of // a few things depending on state and the value of the line. // If no Message is currently being parsed, then this method will attempt to // read a header line and start a new Message instance. // If there is a Message being processed, then it will attempt to parse the // line as a Field (Name: Value). If the line is empty, then the message is // considered done and is returned. func (r *MessageReader) ReadLine() (*Message, error) { if r.message == nil { msg, err := r.readHeader() if err != nil { return nil, err } r.message = msg return nil, nil } line, err := r.reader.ReadString('\n') if err != nil { // EOF or other stream error return r.commitMessage(nil), err } line = strings.TrimSpace(line) if line == "" { // Blank line in input signals end of message return r.commitMessage(nil), nil } parts := strings.SplitN(line, ":", 2) if len(parts) != 2 { // Bad field format - continue parsing? // Test for header msg, err := ParseHeader(line) if err != nil { return nil, fmt.Errorf("invalid field format in \"%s\"", line) } return r.commitMessage(msg), errors.New("new message started without old message ending") } key := strings.TrimSpace(parts[0]) value := strings.TrimSpace(parts[1]) r.message.Fields[key] = value return nil, nil } // readHeader reads a header from the input. // // This function will attempt to read a header line from the input. If the // line read is empty, this function returns (nil, nil). Otherwise it will // attempt to read an unsigned integer and then a description. Both must be // present for the method to succeed. If a header is parsed, this method will // return it without setting the state to reflect that. func (r *MessageReader) readHeader() (*Message, error) { line, err := r.reader.ReadString('\n') if err != nil { return nil, err } return ParseHeader(line) } // ParseHeader attempts to parse a header out of the given string. func ParseHeader(line string) (*Message, error) { line = strings.TrimSpace(line) if line == "" { return nil, errors.New("not a header spec: Empty line") } parts := strings.SplitN(line, " ", 2) if len(parts) != 2 { return nil, fmt.Errorf("not a header spec: \"%s\"", line) } codeStr := strings.TrimSpace(parts[0]) code, err := strconv.ParseUint(codeStr, 10, 64) if err != nil { return nil, fmt.Errorf("could not parse Status Code: %v", err) } desc := strings.TrimSpace(parts[1]) if desc == "" { return nil, fmt.Errorf("empty description header for \"%s\"", line) } msg := &Message{ StatusCode: code, Description: desc, Fields: make(map[string]string), } return msg, nil } // commitMessage returns the current message and sets the message pointer to // nil. func (r *MessageReader) commitMessage(newmsg *Message) *Message { msg := r.message r.message = newmsg return msg } // MessageWriter is a wrapper around an io.Writer which writes APT messages. type MessageWriter struct { w io.Writer } // NewMessageWriter creates a new MessageWriter. func NewMessageWriter(w io.Writer) *MessageWriter { return &MessageWriter{w} } // WriteMessage writes a generic Message object as created by NewMessage. // // This method is less efficient than the dedicated message functions, as it // has to format every part of the message. func (mw *MessageWriter) WriteMessage(msg *Message) { fmt.Fprintf(mw.w, "%d %s\n", msg.StatusCode, msg.Description) for k, v := range msg.Fields { if k != "" && v != "" { fmt.Fprintf(mw.w, "%s: %s\n", k, v) } } mw.w.Write([]byte("\n")) } // Capabilities writes a '100 Capabilities' message. // // Version must be non-empty. caps may be 0 for no capabilities, though // it probably should at least be CapSendConfig (or CapDefault) func (mw *MessageWriter) Capabilities(version string, caps CapFlags) { fmt.Fprintf(mw.w, "100 Capabilities\nVersion: %s\n", version) if caps&CapSendConfig != 0 { mw.w.Write([]byte("Send-Config: true\n")) } if caps&CapPipeline != 0 { mw.w.Write([]byte("Pipeline: true\n")) } if caps&CapSingleInstance != 0 { mw.w.Write([]byte("Single-Instance: true\n")) } if caps&CapLocalOnly != 0 { mw.w.Write([]byte("Local-Only: true\n")) } if caps&CapNeedsCleanup != 0 { mw.w.Write([]byte("Needs-Cleanup: true\n")) } if caps&CapRemovable != 0 { mw.w.Write([]byte("Removable: true\n")) } if caps&CapAuxRequests != 0 { mw.w.Write([]byte("AuxRequests: true\n")) } mw.w.Write([]byte("\n")) } // Log writes a '101 Log' message. func (mw *MessageWriter) Log(msg string) { fmt.Fprintf(mw.w, "101 Log\nMessage: %s\n\n", msg) } // Logf writes a '101 Log' message and formats the arguments into it. func (mw *MessageWriter) Logf(fmtspec string, args ...interface{}) { mw.Log(fmt.Sprintf(fmtspec, args...)) } // Status writes a '102 status' message. func (mw *MessageWriter) Status(msg string) { fmt.Fprintf(mw.w, "102 Status\nMessage: %s\n\n", msg) } // Statusf writes a '102 status' message and formats the arguments into if. func (mw *MessageWriter) Statusf(fmtspec string, args ...interface{}) { mw.Status(fmt.Sprintf(fmtspec, args...)) } // Redirect writes a '103 Redirect' message func (mw *MessageWriter) Redirect(uri, newURI, altURIs string, usedMirror bool) { fmt.Fprintf(mw.w, "103 Redirect\nURI: %s\nNew-URI: %s\n", uri, newURI) if usedMirror { mw.w.Write([]byte("UsedMirror: true\n")) } if altURIs != "" { fmt.Fprintf(mw.w, "Alt-URIs: %s\n", altURIs) } mw.w.Write([]byte("\n")) } // Warning writes a '104 Warning' message. func (mw *MessageWriter) Warning(msg string) { fmt.Fprintf(mw.w, "104 Warning\nMessage: %s\n\n", msg) } // Warningf writes a '104 Warning' message and formats the arguments into it. func (mw *MessageWriter) Warningf(fmtspec string, args ...interface{}) { mw.Warning(fmt.Sprintf(fmtspec, args...)) } // StartURI writes a '200 URI Start' message. func (mw *MessageWriter) StartURI(uri, resumePoint string, size int64, usedMirror bool) { fmt.Fprintf(mw.w, "200 URI Start\nURI: %s\n", uri) if resumePoint != "" { fmt.Fprintf(mw.w, "Resume-Point: %s\n", resumePoint) } if size > 0 { fmt.Fprintf(mw.w, "Size: %d\n", size) } if usedMirror { mw.w.Write([]byte("UsedMirror: true\n")) } mw.w.Write([]byte("\n")) } // FinishURI writes a '201 URI Done' message. func (mw *MessageWriter) FinishURI(uri, filename, resumePoint, altIMSHit string, imsHit, usedMirror bool, extra ...Field) { fmt.Fprintf(mw.w, "201 URI Done\nURI: %s\nFilename: %s\n", uri, filename) if resumePoint != "" { fmt.Fprintf(mw.w, "Resume-Point: %s\n", resumePoint) } if imsHit { mw.w.Write([]byte("IMS-Hit: true\n")) } if altIMSHit != "" { fmt.Fprintf(mw.w, "Alt-IMS-Hit: %s\n", altIMSHit) } if usedMirror { mw.w.Write([]byte("UsedMirror: true\n")) } // TODO: Make this better... for _, s := range extra { fmt.Fprintf(mw.w, "%s: %s\n", s.Key, s.Value) } mw.w.Write([]byte("\n")) } // AuxRequest writes a '351 Aux Request' message. func (mw *MessageWriter) AuxRequest(uri, auxURI, descShort, descLong string, maximumSize uint64, usedMirror bool) { fmt.Fprintf(mw.w, "351 Aux Request\nURI: %s\n", uri) if auxURI != "" { fmt.Fprintf(mw.w, "Aux-URI: %s\n", auxURI) } if maximumSize > 0 { fmt.Fprintf(mw.w, "MaximumSize: %d\n", maximumSize) } if descShort != "" { fmt.Fprintf(mw.w, "Aux-ShortDesc: %s\n", descShort) } if descLong != "" { fmt.Fprintf(mw.w, "Aux-Description: %s\n", descLong) } if usedMirror { mw.w.Write([]byte("UsedMirror: true\n")) } mw.w.Write([]byte("\n")) } // FailedURI writes a '400 URI Failure' message. // // The message parameter should be "" unless the intent is to send a malformed // URI Failure message // failReason is only used if transientError is false func (mw *MessageWriter) FailedURI(uri, message, failReason string, transientError, usedMirror bool) { mw.w.Write([]byte("400 URI Failure\n")) if uri == "" { fmt.Fprintf(mw.w, "Message: %s\n\n", message) return } fmt.Fprintf(mw.w, "URI: %s\n", uri) if transientError { mw.w.Write([]byte("Transient-Failure: true\n")) } else { fmt.Fprintf(mw.w, "FailReason: %s\n", failReason) } if usedMirror { mw.w.Write([]byte("UsedMirror: true\n")) } mw.w.Write([]byte("\n")) } // GeneralFailure writes a '401 General Failure' message. func (mw *MessageWriter) GeneralFailure(msg string) { fmt.Fprintf(mw.w, "401 General Failure\nMessage: %s\n\n", msg) } // GeneralFailuref writes a '401 General Failure' message and formats the // arguments into it. func (mw *MessageWriter) GeneralFailuref(fmtspec string, args ...interface{}) { mw.GeneralFailure(fmt.Sprintf(fmtspec, args...)) } // MediaChange writes a '403 Media Change' message. func (mw *MessageWriter) MediaChange(media, drive string) { fmt.Fprintf(mw.w, "403 Media Change\nMedia: %s\nDrive: %s\n\n", media, drive) } apt-transport-oci-0.1.1/pkg/dockerconfigresolver/000077500000000000000000000000001502514625400221035ustar00rootroot00000000000000apt-transport-oci-0.1.1/pkg/dockerconfigresolver/dockerconfigresolver.go000066400000000000000000000135611502514625400266570ustar00rootroot00000000000000/* Copyright The containerd Authors. Original source: https://github.com/containerd/nerdctl/blob/v0.9.0/pkg/imgutil/dockerconfigresolver/dockerconfigresolver.go We copy the source from upstream nerdctl v0.9.0 for easier packageing on debian system. We can delete this file and add upstream nerdctl back when: 1, nerdctl is packaged in debian 2, apt-transport-oci can use the packaged nerdctl in debian Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package dockerconfigresolver import ( "crypto/tls" "fmt" "net/http" "github.com/containerd/containerd/v2/core/remotes" "github.com/containerd/containerd/v2/core/remotes/docker" dockercliconfig "github.com/docker/cli/cli/config" "github.com/docker/cli/cli/config/credentials" dockercliconfigtypes "github.com/docker/cli/cli/config/types" "github.com/sirupsen/logrus" ) type opts struct { plainHTTP bool skipVerifyCerts bool } // Opt for New type Opt func(*opts) // WithPlainHTTP enables insecure plain HTTP func WithPlainHTTP(b bool) Opt { return func(o *opts) { o.plainHTTP = b } } // WithSkipVerifyCerts skips verifying TLS certs func WithSkipVerifyCerts(b bool) Opt { return func(o *opts) { o.skipVerifyCerts = b } } // New instantiates a resolver using $DOCKER_CONFIG/config.json . // // $DOCKER_CONFIG defaults to "~/.docker". // // refHostname is like "docker.io". func New(refHostname string, optFuncs ...Opt) (remotes.Resolver, error) { var o opts for _, of := range optFuncs { of(&o) } var authzOpts []docker.AuthorizerOpt if authCreds, err := NewAuthCreds(refHostname); err != nil { return nil, err } else { authzOpts = append(authzOpts, docker.WithAuthCreds(authCreds)) } authz := docker.NewDockerAuthorizer(authzOpts...) plainHTTPFunc := docker.MatchLocalhost if o.plainHTTP { plainHTTPFunc = docker.MatchAllHosts } regOpts := []docker.RegistryOpt{ docker.WithAuthorizer(authz), docker.WithPlainHTTP(plainHTTPFunc), } if o.skipVerifyCerts { tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, } client := &http.Client{ Transport: tr, } regOpts = append(regOpts, docker.WithClient(client)) } resovlerOpts := docker.ResolverOptions{ Hosts: docker.ConfigureDefaultRegistries(regOpts...), } resolver := docker.NewResolver(resovlerOpts) return resolver, nil } // AuthCreds is for docker.WithAuthCreds type AuthCreds func(string) (string, string, error) // NewAuthCreds returns AuthCreds that uses $DOCKER_CONFIG/config.json . // AuthCreds can be nil. func NewAuthCreds(refHostname string) (AuthCreds, error) { // Load does not raise an error on ENOENT dockerConfigFile, err := dockercliconfig.Load("") if err != nil { return nil, err } // DefaultHost converts "docker.io" to "registry-1.docker.io", // which is wanted by credFunc . credFuncExpectedHostname, err := docker.DefaultHost(refHostname) if err != nil { return nil, err } var credFunc AuthCreds authConfigHostnames := []string{refHostname} if refHostname == "docker.io" || refHostname == "registry-1.docker.io" { // "docker.io" appears as ""https://index.docker.io/v1/" in ~/.docker/config.json . // GetAuthConfig takes the hostname part as the argument: "index.docker.io" authConfigHostnames = append([]string{"index.docker.io"}, refHostname) } for _, authConfigHostname := range authConfigHostnames { // GetAuthConfig does not raise an error on ENOENT ac, err := dockerConfigFile.GetAuthConfig(authConfigHostname) if err != nil { logrus.WithError(err).Warnf("cannot get auth config for authConfigHostname=%q (refHostname=%q)", authConfigHostname, refHostname) } else { // When refHostname is "docker.io": // - credFuncExpectedHostname: "registry-1.docker.io" // - credFuncArg: "registry-1.docker.io" // - authConfigHostname: "index.docker.io" // - ac.ServerAddress: "https://index.docker.io/v1/". if !isAuthConfigEmpty(ac) { if ac.ServerAddress == "" { // Can this happen? logrus.Warnf("failed to get ac.ServerAddress for authConfigHostname=%q (refHostname=%q)", authConfigHostname, refHostname) } else { acsaHostname := credentials.ConvertToHostname(ac.ServerAddress) if acsaHostname != authConfigHostname { return nil, fmt.Errorf("expected the hostname part of ac.ServerAddress (%q) to be authConfigHostname=%q, got %q", ac.ServerAddress, authConfigHostname, acsaHostname) } } if ac.RegistryToken != "" { // Even containerd/CRI does not support RegistryToken as of v1.4.3, // so, nobody is actually using RegistryToken? logrus.Warnf("ac.RegistryToken (for %q) is not supported yet (FIXME)", authConfigHostname) } credFunc = func(credFuncArg string) (string, string, error) { // credFuncArg should be like "registry-1.docker.io" if credFuncArg != credFuncExpectedHostname { return "", "", fmt.Errorf("expected credFuncExpectedHostname=%q (refHostname=%q), got credFuncArg=%q", credFuncExpectedHostname, refHostname, credFuncArg) } if ac.IdentityToken != "" { return "", ac.IdentityToken, nil } return ac.Username, ac.Password, nil } break } } } // credsFunc can be nil here return credFunc, nil } func isAuthConfigEmpty(ac dockercliconfigtypes.AuthConfig) bool { if ac.IdentityToken != "" || ac.Username != "" || ac.Password != "" || ac.RegistryToken != "" { return false } return true } apt-transport-oci-0.1.1/pkg/method/000077500000000000000000000000001502514625400171445ustar00rootroot00000000000000apt-transport-oci-0.1.1/pkg/method/method.go000066400000000000000000000237021502514625400207570ustar00rootroot00000000000000package method import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "io/ioutil" "os" "path" "strconv" "strings" "github.com/AkihiroSuda/apt-transport-oci/pkg/apt" "github.com/AkihiroSuda/apt-transport-oci/pkg/dockerconfigresolver" "github.com/AkihiroSuda/apt-transport-oci/pkg/version" "github.com/containerd/containerd/v2/core/images" "github.com/containerd/containerd/v2/core/remotes" refdocker "github.com/distribution/reference" "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" ) // Protocol: see https://justi.cz/security/2019/01/22/apt-rce.html // See also the output of `apt-get -o Debug::pkgAcquire::Worker=1 update` const ( CodeURIAcquire = 600 FieldURI = "URI" FieldMessage = "Message" FieldTargetRepoURI = "Target-Repo-URI" FieldFilename = "Filename" FieldSize = "Size" FieldSHA256Hash = "SHA256-Hash" ) const ( MediaTypeApplicationXBinary = "application/x-binary" MediaTypeApplicationOctetStream = "application/octet-stream" ) func New(out io.Writer, in io.Reader) *Method { m := &Method{ w: apt.NewMessageWriter(out), r: apt.NewMessageReader(bufio.NewReader(in)), cacheByOCIRef: make(map[string]cacheByOCIRef), } return m } type cacheByOCIRef struct { fetcher remotes.Fetcher fileMap map[string]ocispec.Descriptor } type Method struct { w *apt.MessageWriter r *apt.MessageReader // no need to consider cache invalidation, as the process lifecycle is short cacheByOCIRef map[string]cacheByOCIRef // TODO: add multi-threading with mutex to support CapPipeLine } // Run is based on https://github.com/cloudflare/apt-transport-cloudflared/blob/96e1417f9c54/apt/method.go#L77-L108 func (m *Method) Run(ctx context.Context) { version := fmt.Sprintf("%d.%d", version.Major, version.Minor) // TODO: enable apt.CapPipeline var caps apt.CapFlags m.w.Capabilities(version, caps) for { msg, err := m.r.ReadMessage() if err != nil { switch { case errors.Is(err, io.EOF), errors.Is(err, io.ErrClosedPipe): return case errors.Is(err, io.ErrNoProgress), errors.Is(err, io.ErrShortBuffer): // NOP default: m.w.GeneralFailuref("Error reading message: %v", err) return } } switch msg.StatusCode { case CodeURIAcquire: m.handleURIAcquire(ctx, msg) default: m.w.Logf("Unknown message: %d %s", msg.StatusCode, msg.Description) } } } func (m *Method) handleURIAcquire(ctx context.Context, msg *apt.Message) { if started, err := m.acquire(ctx, msg); err != nil { const ( transientError = false usedMirror = false ) uri := msg.Fields[FieldURI] if !started { m.w.StartURI(uri, "", 0, usedMirror) } m.w.FailedURI(uri, err.Error(), err.Error(), transientError, usedMirror) } } func (m *Method) ociResolver(named refdocker.Named) (remotes.Resolver, error) { ref := named.String() refDomain := refdocker.Domain(named) var dOpts []dockerconfigresolver.Opt // TODO: support insecure non-TLS registry resolver, err := dockerconfigresolver.New(refDomain, dOpts...) if err != nil { return nil, fmt.Errorf("failed to create a resolver for refDomain=%q (ref=%q): %w", refDomain, ref, err) } return resolver, err } func (m *Method) ociFetcher(ctx context.Context, named refdocker.Named, resolver remotes.Resolver) (remotes.Fetcher, ocispec.Descriptor, error) { ref := named.String() ociName, rootDesc, err := resolver.Resolve(ctx, ref) if err != nil { return nil, ocispec.Descriptor{}, fmt.Errorf("failed to resolve ref=%q: %w", ref, err) } fetcher, err := resolver.Fetcher(ctx, ociName) if err != nil { return nil, ocispec.Descriptor{}, err } return fetcher, rootDesc, nil } func buildFileMap(ctx context.Context, fetcher remotes.Fetcher, rootDesc ocispec.Descriptor) (map[string]ocispec.Descriptor, error) { files := make(map[string]ocispec.Descriptor) handler := images.HandlerFunc( func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) { switch desc.MediaType { case images.MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest: r, err := fetcher.Fetch(ctx, desc) if err != nil { return nil, err } defer r.Close() b, err := ioutil.ReadAll(r) if err != nil { return nil, err } var manifest ocispec.Manifest if err := json.Unmarshal(b, &manifest); err != nil { return nil, err } for _, l := range manifest.Layers { if title := l.Annotations[ocispec.AnnotationTitle]; title != "" { cleanPath := path.Clean(title) files[cleanPath] = l } } case images.MediaTypeDockerSchema2ManifestList, ocispec.MediaTypeImageIndex: r, err := fetcher.Fetch(ctx, desc) if err != nil { return nil, err } defer r.Close() b, err := ioutil.ReadAll(r) if err != nil { return nil, err } var index ocispec.Index if err := json.Unmarshal(b, &index); err != nil { return nil, err } return index.Manifests, nil } return nil, nil }) if err := images.Dispatch(ctx, handler, nil, rootDesc); err != nil { return nil, err } return files, nil } func parseURI(uri string) (repo, path string, _ error) { // The format here would be something like: registry.somehost.com/some/repo:tag/SomeFile trimmed := strings.TrimPrefix(uri, "oci://") if trimmed == uri { return "", "", fmt.Errorf("missing oci:// protocol in uri") } split := strings.SplitN(trimmed, ":", 2) if len(split) < 2 { return "", "", fmt.Errorf("uri is missing repo tag") } // Combine everything up to but not including the tag // We don't quite have the tag yet because it (should) have a file path added // to the end that we need to split off first. repo = "oci://" + split[0] + ":" tagAndFile := strings.SplitN(split[1], "/", 2) // We add "/" here, otherwise we'll end up with an extra preceding "/" on the // file name later which we don't want and will cause the file to not be found. repo += tagAndFile[0] + "/" if len(tagAndFile) > 1 { path = tagAndFile[1] } return repo, path, nil } func parseURIFields(msg *apt.Message) (ociRef refdocker.Named, title string, err error) { repoURI := msg.Fields[FieldTargetRepoURI] if repoURI == "" { uri := msg.Fields[FieldURI] if uri == "" { return ociRef, "", fmt.Errorf("missing field %q", FieldTargetRepoURI) } repoURI, _, err = parseURI(uri) if err != nil { return ociRef, "", err } } if !strings.HasPrefix(repoURI, "oci://") { return ociRef, "", fmt.Errorf("field %s lacks \"oci://\" prefix: %q", FieldTargetRepoURI, repoURI) } refTmp := strings.TrimPrefix(repoURI, "oci://") refTmp = strings.TrimSuffix(refTmp, "/") ociRef, err = refdocker.ParseDockerRef(refTmp) if err != nil { return ociRef, "", fmt.Errorf("failed to parse %q (%s=%q) as Docker reference: %w", refTmp, FieldTargetRepoURI, repoURI, err) } title = strings.TrimPrefix(msg.Fields[FieldURI], repoURI) // not robust, but no security issue (cuz not referring to the actual filesystem) title = strings.TrimPrefix(title, "./") return ociRef, title, nil } func (m *Method) Status(uri, s string) { msg := &apt.Message{ StatusCode: 102, Description: "Status", Fields: map[string]string{ FieldURI: uri, FieldMessage: s, }, } m.w.WriteMessage(msg) } func (m *Method) Statusf(uri, fmtspec string, args ...interface{}) { m.Status(uri, fmt.Sprintf(fmtspec, args...)) } func (m *Method) doCacheStuff(ctx context.Context, uri string, ociRef refdocker.Named) (*cacheByOCIRef, error) { if x, ok := m.cacheByOCIRef[ociRef.String()]; ok { return &x, nil } m.Statusf(uri, "Creating a resolver for ociRef=%q", ociRef) resolver, err := m.ociResolver(ociRef) if err != nil { return nil, err } m.Statusf(uri, "Creating a fetcher for ociRef=%q", ociRef) fetcher, rootDesc, err := m.ociFetcher(ctx, ociRef, resolver) if err != nil { return nil, err } m.Statusf(uri, "Building file map for rootDesc=%+v", rootDesc) fileMap, err := buildFileMap(ctx, fetcher, rootDesc) if err != nil { return nil, err } c := cacheByOCIRef{ fetcher: fetcher, fileMap: fileMap, } m.cacheByOCIRef[ociRef.String()] = c return &c, nil } func (m *Method) acquire(ctx context.Context, msg *apt.Message) (started bool, err error) { uri := msg.Fields[FieldURI] filename := msg.Fields[FieldFilename] // TODO: support "Expected-SHA256" m.Statusf(uri, "Parsing msg: %+v", msg) ociRef, title, err := parseURIFields(msg) if err != nil { return started, err } c, err := m.doCacheStuff(ctx, uri, ociRef) if err != nil { return started, err } desc, ok := c.fileMap[title] if !ok { return started, fmt.Errorf("file not found in %q: %q", ociRef, title) } m.Statusf(uri, "Found descriptor for %q: %+v", title, desc) switch desc.MediaType { case MediaTypeApplicationOctetStream, MediaTypeApplicationXBinary: // NOP default: m.w.Warningf("expected media type of %q to be %q, got %q", title, MediaTypeApplicationXBinary, desc.MediaType) } const ( resumePoint = "" usedMirror = false ) m.w.StartURI(uri, resumePoint, desc.Size, usedMirror) started = true r, err := c.fetcher.Fetch(ctx, desc) if err != nil { return started, err } defer r.Close() w, err := os.Create(filename) if err != nil { return started, err } defer w.Close() digester := digest.SHA256.Digester() hasher := digester.Hash() mw := io.MultiWriter(w, hasher) if _, err := io.Copy(mw, r); err != nil { // TODO: show progress return started, err } if err := w.Close(); err != nil { return started, err } if err := r.Close(); err != nil { return started, err } dig := digester.Digest() if desc.Digest.Algorithm() == dig.Algorithm() && desc.Digest.Encoded() != dig.Encoded() { return started, fmt.Errorf("expected digest of %q to be %s, got %s", title, desc.Digest, dig) } const ( altIMSHit = "" imsHit = false ) fields := []apt.Field{ {Key: FieldSize, Value: strconv.Itoa(int(desc.Size))}, {Key: FieldSHA256Hash, Value: dig.Encoded()}, } m.w.FinishURI(uri, filename, resumePoint, altIMSHit, imsHit, usedMirror, fields...) return started, nil } apt-transport-oci-0.1.1/pkg/method/method_test.go000066400000000000000000000033001502514625400220060ustar00rootroot00000000000000package method import "testing" func TestParseURI(t *testing.T) { type testCase struct { v string xRepo string xPath string err bool } for name, uri := range map[string]testCase{ "no proto just host": { v: "foo.bar", err: true, }, "no proto host and path": { v: "foo.bar/baz", err: true, }, "no proto host and tag": { v: "foo.bar:latest", err: true, }, "with proto just host": { v: "oci://foo.bar", err: true, }, "with proto host and path": { v: "oci://foo.bar/baz", err: true, }, "with proto host and tag": { v: "oci://foo.bar:latest/", xRepo: "oci://foo.bar:latest/", }, "with proto host, tag, and path": { v: "oci://foo.bar:latest/File", xRepo: "oci://foo.bar:latest/", xPath: "File", }, "with proto host, tag, and nested path": { v: "oci://foo.bar:latest/Nested/File", xRepo: "oci://foo.bar:latest/", xPath: "Nested/File", }, "with proto host, namespace, tag, and path": { v: "oci://foo.bar/namespace:latest/File", xRepo: "oci://foo.bar/namespace:latest/", xPath: "File", }, "with proto host, namespace, tag, and nested path": { v: "oci://foo.bar/namespace:latest/Nested/File", xRepo: "oci://foo.bar/namespace:latest/", xPath: "Nested/File", }, } { t.Run(name, func(t *testing.T) { uri := uri repo, path, err := parseURI(uri.v) if uri.err { if err == nil { t.Fatal("expected error") } } else { if err != nil { t.Fatal(err) } } if repo != uri.xRepo { t.Fatalf("expected repo %q, got %q", uri.xRepo, repo) } if path != uri.xPath { t.Fatalf("expected path %q, got %q", uri.xPath, path) } }) } } apt-transport-oci-0.1.1/pkg/version/000077500000000000000000000000001502514625400173515ustar00rootroot00000000000000apt-transport-oci-0.1.1/pkg/version/version.go000066400000000000000000000000571502514625400213670ustar00rootroot00000000000000package version var ( Major = 0 Minor = 1 )