Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 131 additions & 1 deletion cmd/api/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@ import (
"bytes"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"

"github.com/getkin/kin-openapi/openapi3filter"
"github.com/go-chi/chi/v5"
"github.com/golang-jwt/jwt/v5"
nethttpmiddleware "github.com/oapi-codegen/nethttp-middleware"
mw "github.com/kernel/hypeman/lib/middleware"
"github.com/kernel/hypeman/lib/oapi"
nethttpmiddleware "github.com/oapi-codegen/nethttp-middleware"
"github.com/oapi-codegen/runtime"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -92,3 +94,131 @@ func TestMiddleware_ValidJWT(t *testing.T) {

assert.Equal(t, http.StatusCreated, w.Code)
}

func TestOapiRuntimeBindStyledParameter_URLDecoding(t *testing.T) {
// Test if oapi-codegen's runtime.BindStyledParameterWithOptions URL-decodes path params
tests := []struct {
name string
input string
expected string
}{
{
name: "simple string",
input: "alpine:latest",
expected: "alpine:latest",
},
{
name: "URL-encoded slashes",
input: "docker.io%2Flibrary%2Falpine%3Alatest",
expected: "docker.io/library/alpine:latest", // Should be decoded
},
{
name: "already decoded",
input: "docker.io/library/alpine:latest",
expected: "docker.io/library/alpine:latest",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var dest string
err := runtime.BindStyledParameterWithOptions(
"simple", "name", tt.input, &dest,
runtime.BindStyledParameterOptions{
ParamLocation: runtime.ParamLocationPath,
Explode: false,
Required: true,
},
)
require.NoError(t, err)
assert.Equal(t, tt.expected, dest, "BindStyledParameterWithOptions should URL-decode the input")
})
}
}

func TestImageNameWithSlashes_URLEncoding(t *testing.T) {
// This test verifies how chi router handles image names with slashes.
// Image names like "docker.io/onkernel/chromium-headful:latest" contain slashes
// that need to be URL-encoded to work with the /images/{name} endpoint.
//
// FINDINGS:
// 1. Chi DOES route to the handler when slashes are URL-encoded (%2F)
// 2. Chi's URLParam returns the STILL-ENCODED value (e.g., "docker.io%2Flibrary%2Falpine%3Alatest")
// 3. The handler/middleware must URL-decode the parameter itself
// 4. The oapi-codegen runtime.BindStyledParameterWithOptions MAY handle decoding
//
// This is a server-side documentation issue - users need to know to URL-encode image names
// with slashes, and the server needs to ensure proper URL-decoding.

r := chi.NewRouter()

var capturedRaw string
var capturedDecoded string
r.Get("/images/{name}", func(w http.ResponseWriter, req *http.Request) {
capturedRaw = chi.URLParam(req, "name")
// URL-decode the parameter
decoded, _ := url.QueryUnescape(capturedRaw)
capturedDecoded = decoded
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"name":"` + capturedDecoded + `"}`))
})

token, err := generateValidJWT("user-123")
require.NoError(t, err)

tests := []struct {
name string
path string
expectedStatus int
expectedRaw string
expectedDecoded string
}{
{
name: "simple image name (no slashes)",
path: "/images/alpine:latest",
expectedStatus: http.StatusOK,
expectedRaw: "alpine:latest",
expectedDecoded: "alpine:latest",
},
{
name: "URL-encoded slashes - routes correctly",
path: "/images/docker.io%2Flibrary%2Falpine%3Alatest",
expectedStatus: http.StatusOK,
expectedRaw: "docker.io%2Flibrary%2Falpine%3Alatest", // chi returns encoded
expectedDecoded: "docker.io/library/alpine:latest", // after QueryUnescape
},
{
name: "unencoded slashes - route not matched",
path: "/images/docker.io/library/alpine:latest",
expectedStatus: http.StatusNotFound, // chi won't match this route
expectedRaw: "",
expectedDecoded: "",
},
{
name: "nested image docker.io/onkernel/chromium-headful:latest",
path: "/images/docker.io%2Fonkernel%2Fchromium-headful%3Alatest",
expectedStatus: http.StatusOK,
expectedRaw: "docker.io%2Fonkernel%2Fchromium-headful%3Alatest",
expectedDecoded: "docker.io/onkernel/chromium-headful:latest",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
capturedRaw = ""
capturedDecoded = ""

req := httptest.NewRequest(http.MethodGet, tt.path, nil)
req.Header.Set("Authorization", "Bearer "+token)

w := httptest.NewRecorder()
r.ServeHTTP(w, req)

assert.Equal(t, tt.expectedStatus, w.Code, "status code mismatch for path %s", tt.path)
if tt.expectedStatus == http.StatusOK {
assert.Equal(t, tt.expectedRaw, capturedRaw, "raw captured name mismatch")
assert.Equal(t, tt.expectedDecoded, capturedDecoded, "decoded name mismatch")
}
})
}
}
8 changes: 4 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,24 @@ require (
github.com/cyphar/filepath-securejoin v0.6.1
github.com/digitalocean/go-qemu v0.0.0-20250212194115-ee9b0668d242
github.com/distribution/reference v0.6.0
github.com/docker/distribution v2.8.3+incompatible
github.com/getkin/kin-openapi v0.133.0
github.com/ghodss/yaml v1.0.0
github.com/go-chi/chi/v5 v5.2.3
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/golang/protobuf v1.5.4
github.com/google/go-containerregistry v0.20.6
github.com/google/uuid v1.6.0
github.com/google/wire v0.7.0
github.com/gorilla/mux v1.8.1
github.com/gorilla/websocket v1.5.3
github.com/joho/godotenv v1.5.1
github.com/mdlayher/vsock v1.2.1
github.com/miekg/dns v1.1.68
github.com/nrednav/cuid2 v1.1.0
github.com/oapi-codegen/nethttp-middleware v1.1.2
github.com/oapi-codegen/runtime v1.1.2
github.com/opencontainers/go-digest v1.0.0
github.com/opencontainers/image-spec v1.1.1
github.com/opencontainers/runtime-spec v1.2.1
github.com/opencontainers/umoci v0.6.0
Expand Down Expand Up @@ -61,7 +65,6 @@ require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/digitalocean/go-libvirt v0.0.0-20220804181439-8648fbde413e // indirect
github.com/docker/cli v28.2.2+incompatible // indirect
github.com/docker/distribution v2.8.3+incompatible // indirect
github.com/docker/docker v28.2.2+incompatible // indirect
github.com/docker/docker-credential-helpers v0.9.3 // indirect
github.com/docker/go-connections v0.5.0 // indirect
Expand All @@ -74,8 +77,6 @@ require (
github.com/go-openapi/swag v0.23.0 // indirect
github.com/go-test/deep v1.1.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/klauspost/compress v1.18.0 // indirect
Expand All @@ -90,7 +91,6 @@ require (
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/oasdiff/yaml v0.0.0-20250309154309-f31be36b4037 // indirect
github.com/oasdiff/yaml3 v0.0.0-20250309153720-d2182401db90 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/perimeterx/marshmallow v1.1.5 // indirect
github.com/pierrec/lz4/v4 v4.1.22 // indirect
github.com/pkg/errors v0.9.1 // indirect
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,6 @@ 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/go-containerregistry v0.20.6 h1:cvWX87UxxLgaH76b4hIvya6Dzz9qHB31qAwjAohdSTU=
github.com/google/go-containerregistry v0.20.6/go.mod h1:T0x8MuoAoKX/873bkeSfLD2FAkwCDf9/HZgsFJ02E2Y=
github.com/google/subcommands v1.2.0 h1:vWQspBTo2nEqTUFita5/KeEWlUL8kQObDFbub/EN9oE=
github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
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=
Expand Down
25 changes: 19 additions & 6 deletions lib/middleware/oapi_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,22 @@ import (
"encoding/base64"
"fmt"
"net/http"
"regexp"
"strings"

v2 "github.com/docker/distribution/registry/api/v2"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/golang-jwt/jwt/v5"
"github.com/gorilla/mux"
"github.com/kernel/hypeman/lib/logger"
)

type contextKey string

const userIDKey contextKey = "user_id"

// registryPathPattern matches /v2/{repository}/... paths
var registryPathPattern = regexp.MustCompile(`^/v2/([^/]+(?:/[^/]+)?)/`)
// registryRouter is the OCI Distribution API router from docker/distribution.
// It properly parses repository names (which can contain slashes) from /v2/ paths.
var registryRouter = v2.Router()

// RegistryTokenClaims contains the claims for a scoped registry access token.
// This mirrors the type in lib/builds/registry_token.go to avoid circular imports.
Expand Down Expand Up @@ -201,10 +203,21 @@ func isInternalVMRequest(r *http.Request) bool {

// extractRepoFromPath extracts the repository name from a registry path.
// e.g., "/v2/builds/abc123/manifests/latest" -> "builds/abc123"
// extractRepoFromPath extracts the repository name from a registry path.
// Uses the docker/distribution router which properly handles repository names
// that can contain slashes (e.g., "builds/abc123" from "/v2/builds/abc123/manifests/latest").
func extractRepoFromPath(path string) string {
matches := registryPathPattern.FindStringSubmatch(path)
if len(matches) >= 2 {
return matches[1]
// Create a minimal request for route matching
req, err := http.NewRequest(http.MethodGet, path, nil)
if err != nil {
return ""
}

var match mux.RouteMatch
if registryRouter.Match(req, &match) {
if name, ok := match.Vars["name"]; ok {
return name
}
}
return ""
}
Expand Down
69 changes: 68 additions & 1 deletion lib/middleware/oapi_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,74 @@ func TestJwtAuth_RejectsRegistryTokens(t *testing.T) {
})
}

func TestExtractRepoFromPath(t *testing.T) {
tests := []struct {
name string
path string
expected string
}{
// Simple repository names
{
name: "simple repo with manifests",
path: "/v2/test-alpine/manifests/latest",
expected: "test-alpine",
},
{
name: "simple repo with blobs",
path: "/v2/test-alpine/blobs/sha256:abc123",
expected: "test-alpine",
},
{
name: "simple repo with uploads",
path: "/v2/test-alpine/blobs/uploads/uuid-here",
expected: "test-alpine",
},

// Nested repository names (like builds/abc123)
{
name: "nested repo with manifests",
path: "/v2/builds/abc123/manifests/latest",
expected: "builds/abc123",
},
{
name: "nested repo with blobs",
path: "/v2/builds/abc123/blobs/sha256:def456",
expected: "builds/abc123",
},
{
name: "nested repo with uploads",
path: "/v2/builds/abc123/blobs/uploads/uuid-here",
expected: "builds/abc123",
},

// Base path (no repo)
{
name: "base path",
path: "/v2/",
expected: "",
},

// Edge cases
{
name: "repo named manifests-test",
path: "/v2/manifests-test/manifests/latest",
expected: "manifests-test",
},
{
name: "repo named blobs-data",
path: "/v2/blobs-data/blobs/sha256:abc",
expected: "blobs-data",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := extractRepoFromPath(tt.path)
assert.Equal(t, tt.expected, result, "extractRepoFromPath(%q)", tt.path)
})
}
}

func TestJwtAuth_RequiresAuthorization(t *testing.T) {
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
Expand Down Expand Up @@ -201,4 +269,3 @@ func TestJwtAuth_RequiresAuthorization(t *testing.T) {
assert.Contains(t, rr.Body.String(), "invalid token")
})
}