pax_global_header00006660000000000000000000000064151713325370014521gustar00rootroot0000000000000052 comment=cf29cc85871ee8c19a648554d2b8950c0e04864a apt-transport-oci-0.1.2/000077500000000000000000000000001517133253700151075ustar00rootroot00000000000000apt-transport-oci-0.1.2/.github/000077500000000000000000000000001517133253700164475ustar00rootroot00000000000000apt-transport-oci-0.1.2/.github/dependabot.yml000066400000000000000000000003651517133253700213030ustar00rootroot00000000000000version: 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.2/.github/workflows/000077500000000000000000000000001517133253700205045ustar00rootroot00000000000000apt-transport-oci-0.1.2/.github/workflows/main.yml000066400000000000000000000021071517133253700221530ustar00rootroot00000000000000name: 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@v6 - uses: actions/setup-go@v6 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: | sudo tee /etc/apt/sources.list.d/oci.sources < [!NOTE] > "OCI" here refers to the "[Open Container Initiative](https://opencontainers.org/)", not to the "Oracle Cloud Infrastructure". ## 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. ## Install The `apt-transport-oci` plugin is officially [packaged](https://repology.org/project/apt-transport-oci/versions) in Debian and Ubuntu, since Debian 14 and Ubuntu 26.04. ```bash sudo apt install apt-transport-oci ```
Build from source

```bash sudo go build -o /usr/lib/apt/methods/oci ./cmd/usr-lib-apt-methods-oci ```

## Example The following example installs the `hello-apt-transport-oci` package from the [`oci://ghcr.io/akihirosuda/hello-apt-transport-oci`](https://ghcr.io/akihirosuda/hello-apt-transport-oci) repo. > [!TIP] > See [`./examples`](./examples) for how to build and push this package to your own registry. - Create `/etc/apt/sources.list.d/oci.sources` with the following content: ``` Types: deb URIs: oci://ghcr.io/akihirosuda/hello-apt-transport-oci:latest Suites: stable Components: main Signed-By: /etc/apt/keyrings/AkihiroSuda.gpg ``` - Register a GPG key: ```bash curl -fsSL https://github.com/AkihiroSuda.gpg | sudo gpg --dearmor -o /etc/apt/keyrings/AkihiroSuda.gpg ``` - Run: ```bash sudo apt update sudo apt install hello-apt-transport-oci ``` - 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` ## Specification The spec corresponds to the behavior of `oras push --image-spec=v1.0 IMAGE FILE1:application/octet-stream FILE2:application/octet-stream ...`. - 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.2/cmd/000077500000000000000000000000001517133253700156525ustar00rootroot00000000000000apt-transport-oci-0.1.2/cmd/usr-lib-apt-methods-oci/000077500000000000000000000000001517133253700222225ustar00rootroot00000000000000apt-transport-oci-0.1.2/cmd/usr-lib-apt-methods-oci/main.go000066400000000000000000000002561517133253700235000ustar00rootroot00000000000000package 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.2/examples/000077500000000000000000000000001517133253700167255ustar00rootroot00000000000000apt-transport-oci-0.1.2/examples/.gitignore000066400000000000000000000000171517133253700207130ustar00rootroot00000000000000*.deb Packages apt-transport-oci-0.1.2/examples/README.md000066400000000000000000000065251517133253700202140ustar00rootroot00000000000000# Creating an apt repo on an OCI registry ## Step 1: Create dpkg Create `hello-apt-transport-oci_0.1_all.deb` from [`helloapt-transport-oci` directory](./hello-apt-transport-oci). ```bash dpkg-deb --build --root-owner-group hello-apt-transport-oci hello-apt-transport-oci_0.1_all.deb ``` ## Step 2: Create repository data Use [aptly](https://www.aptly.info) to create the repository data. ```bash sudo apt-get install aptly ``` ```bash aptly repo create hello-apt-transport-oci aptly repo add hello-apt-transport-oci hello-apt-transport-oci_0.1_all.deb aptly publish repo -distribution=stable -architectures=all,amd64,arm64 hello-apt-transport-oci ``` The repository data will be locally published on `~/.aptly/public`. ```console $ tree ~/.aptly/public /home/USER/.aptly/public ├── dists │   └── stable │   ├── Contents-all.gz │   ├── Contents-amd64.gz │   ├── Contents-arm64.gz │   ├── InRelease │   ├── main │   │   ├── binary-all │   │   │   ├── Packages │   │   │   ├── Packages.bz2 │   │   │   ├── Packages.gz │   │   │   └── Release │   │   ├── binary-amd64 │   │   │   ├── Packages │   │   │   ├── Packages.bz2 │   │   │   ├── Packages.gz │   │   │   └── Release │   │   ├── binary-arm64 │   │   │   ├── Packages │   │   │   ├── Packages.bz2 │   │   │   ├── Packages.gz │   │   │   └── Release │   │   ├── Contents-all.gz │   │   ├── Contents-amd64.gz │   │   └── Contents-arm64.gz │   ├── Release │   └── Release.gpg └── pool └── main └── h └── hello-apt-transport-oci └── hello-apt-transport-oci_0.1_all.deb 11 directories, 22 files ``` ## 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 sudo apt-get install oras ``` ```bash echo YOUR_GITHUB_PERSONAL_ACCESS_TOKEN | docker login ghcr.io -u USERNAME --password-stdin ``` ```bash cd ~/.aptly/public find . -type f -printf "%p:application/octet-stream\n" | xargs oras push --image-spec=v1.0 ghcr.io/USERNAME/hello-apt-transport:latest ``` - 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](https://github.com/settings/personal-access-tokens) (PAT) for `ghcr.io`. - Use GitHub Web UI to make the image public / private. ## Step 4: Tell users the instruction Tell your users how to install your package: > - Create `/etc/apt/sources.list.d/oci.sources` with the following content: > ``` > Types: deb > URIs: oci://ghcr.io/USERNAME/hello-apt-transport-oci:latest > Suites: stable > Components: main > Signed-By: /etc/apt/keyrings/USERNAME.gpg > ``` > > - Register a GPG key: > ```bash > curl -fsSL https://github.com/USERNAME.gpg | sudo gpg --dearmor -o /etc/apt/keyrings/USERNAME.gpg > ``` apt-transport-oci-0.1.2/examples/hello-apt-transport-oci/000077500000000000000000000000001517133253700234145ustar00rootroot00000000000000apt-transport-oci-0.1.2/examples/hello-apt-transport-oci/DEBIAN/000077500000000000000000000000001517133253700243365ustar00rootroot00000000000000apt-transport-oci-0.1.2/examples/hello-apt-transport-oci/DEBIAN/control000066400000000000000000000002051517133253700257360ustar00rootroot00000000000000Package: hello-apt-transport-oci Version: 0.1 Architecture: all Maintainer: example@example.com Description: hello apt-transport-oci apt-transport-oci-0.1.2/examples/hello-apt-transport-oci/usr/000077500000000000000000000000001517133253700242255ustar00rootroot00000000000000apt-transport-oci-0.1.2/examples/hello-apt-transport-oci/usr/bin/000077500000000000000000000000001517133253700247755ustar00rootroot00000000000000apt-transport-oci-0.1.2/examples/hello-apt-transport-oci/usr/bin/hello-apt-transport-oci000077500000000000000000000000521517133253700314070ustar00rootroot00000000000000#!/bin/sh echo "Hello, apt-transport-oci" apt-transport-oci-0.1.2/go.mod000066400000000000000000000030641517133253700162200ustar00rootroot00000000000000module github.com/AkihiroSuda/apt-transport-oci go 1.24.3 require ( github.com/containerd/containerd/v2 v2.2.3 github.com/distribution/reference v0.6.0 github.com/docker/cli v29.4.0+incompatible github.com/opencontainers/go-digest v1.0.0 github.com/opencontainers/image-spec v1.1.1 github.com/sirupsen/logrus v1.9.4 ) 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.2 // 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.5 // indirect github.com/moby/locker v1.0.1 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect go.opentelemetry.io/otel v1.38.0 // indirect go.opentelemetry.io/otel/metric v1.38.0 // indirect go.opentelemetry.io/otel/trace v1.38.0 // indirect golang.org/x/sync v0.18.0 // indirect golang.org/x/sys v0.38.0 // indirect google.golang.org/protobuf v1.36.10 // 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.2/go.sum000066400000000000000000000221171517133253700162450ustar00rootroot00000000000000github.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.2.3 h1:mOBRLaHGvmgy0bRo1Sg6OD8ugMKZIvCoWWMeMMygliA= github.com/containerd/containerd/v2 v2.2.3/go.mod h1:ns24cwt+p36mRnuKE3hLRxVBpuSP+a/Y25AMki1t/RY= 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.2 h1:0SPgaNZPVWGEi4grZdV8VRYQn78y+nm6acgLGv/QzE4= github.com/containerd/platforms v1.0.0-rc.2/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.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 v29.4.0+incompatible h1:+IjXULMetlvWJiuSI0Nbor36lcJ5BTcVpUmB21KBoVM= github.com/docker/cli v29.4.0+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.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE= github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= 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/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.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= 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.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= 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.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA= go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI= go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E= go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg= 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.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE= go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs= 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.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= 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.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= 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.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= 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.2/pkg/000077500000000000000000000000001517133253700156705ustar00rootroot00000000000000apt-transport-oci-0.1.2/pkg/apt/000077500000000000000000000000001517133253700164545ustar00rootroot00000000000000apt-transport-oci-0.1.2/pkg/apt/message.go000066400000000000000000000313241517133253700204320ustar00rootroot00000000000000/* 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.2/pkg/dockerconfigresolver/000077500000000000000000000000001517133253700221075ustar00rootroot00000000000000apt-transport-oci-0.1.2/pkg/dockerconfigresolver/dockerconfigresolver.go000066400000000000000000000135611517133253700266630ustar00rootroot00000000000000/* 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.2/pkg/method/000077500000000000000000000000001517133253700171505ustar00rootroot00000000000000apt-transport-oci-0.1.2/pkg/method/method.go000066400000000000000000000237021517133253700207630ustar00rootroot00000000000000package 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.2/pkg/method/method_test.go000066400000000000000000000033001517133253700220120ustar00rootroot00000000000000package 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.2/pkg/version/000077500000000000000000000000001517133253700173555ustar00rootroot00000000000000apt-transport-oci-0.1.2/pkg/version/version.go000066400000000000000000000000571517133253700213730ustar00rootroot00000000000000package version var ( Major = 0 Minor = 1 )