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
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ file new ones at cinc-project/cinc-server-ng):
cinc-server-ng answers a non-numeric requested version with a 400 whose
header says `request_version`/`response_version` are the minimum, where
erchef sends a 406 with both `-1`.
- **cinc-server-ng** returns every file of a cookbook or cookbook artifact
on a GET at server API version 1. erchef rebuilds the nine classic
segments there and silently drops any file outside them (ohai/,
compliance/, …; `chef_cookbook_version:populate_segments`), which is why
`Cookbooks.Get` and `CookbookArtifacts.Get` ask for version 2
(`manifestAPIVersion`), as chef-client does (cinc-server-ng#297).
- **Neither server** rejects a cookbook manifest with bare file names
(`default.rb` instead of `recipes/default.rb`), but chef-client misfiles
every such entry, so only a converge would show it.
Expand Down
6 changes: 4 additions & 2 deletions cookbook_artifacts.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,11 @@ func (s *CookbookArtifactsService) GetVersions(ctx context.Context, name string)
return &entry, resp, nil
}

// Get retrieves a single cookbook artifact by name and identifier.
// Get retrieves a single cookbook artifact by name and identifier. Like
// Cookbooks.Get it asks for server API version 2, so the files come back in
// AllFilesManifest, including those outside the classic segments.
func (s *CookbookArtifactsService) Get(ctx context.Context, name, identifier string) (*Cookbook, *Response, error) {
cb, resp, err := do[Cookbook](ctx, s.client, "GET",
cb, resp, err := do[Cookbook](withServerAPIVersion(ctx, manifestAPIVersion), s.client, "GET",
s.client.orgPath("/cookbook_artifacts/"+esc(name)+"/"+esc(identifier)), nil)
return ptrOrNil(cb, err), resp, err
}
Expand Down
68 changes: 68 additions & 0 deletions cookbook_manifest_version_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package cinc

import (
"context"
"net/http"
"path/filepath"
"testing"

"github.com/cinc-project/cinc-api/internal/cinctest"
)

// A cookbook or artifact manifest is fetched at server API version 2. At 0
// and 1 erchef rebuilds the nine classic segments from the stored all_files
// and drops every file outside them (ohai/, compliance/, spec/, ...), so a
// download would silently miss those files. The cinctest harness re-checks
// the signature against the version header, so this also proves the request
// is signed for version 2.
func TestManifestGet_AsksForServerAPIVersion2(t *testing.T) {
const manifest = `{"cookbook_name":"nginx","version":"1.2.0","name":"nginx-1.2.0",
"all_files":[{"name":"ohai/plugins/x.rb","path":"ohai/plugins/x.rb","checksum":"","url":"http://x"}]}`
assertV2 := func(t *testing.T, r *http.Request, _ []byte) {
if v := r.Header.Get("X-Ops-Server-API-Version"); v != "2" {
t.Errorf("manifest GET API version = %q, want 2", v)
}
}
for _, tc := range []struct {
desc, route string
get func(*Client) (*Cookbook, *Response, error)
}{
{"cookbook", "GET /organizations/o/cookbooks/nginx/1.2.0",
func(c *Client) (*Cookbook, *Response, error) {
return c.Cookbooks.Get(context.Background(), "nginx", "1.2.0")
}},
{"artifact", "GET /organizations/o/cookbook_artifacts/nginx/abc123",
func(c *Client) (*Cookbook, *Response, error) {
return c.CookbookArtifacts.Get(context.Background(), "nginx", "abc123")
}},
} {
t.Run(tc.desc, func(t *testing.T) {
srv := cinctest.New(t)
srv.Handle(tc.route, cinctest.Route{Body: manifest, Assert: assertV2})
cb, _, err := tc.get(newTestClient(t, srv.Server))
if err != nil {
t.Fatalf("Get: %v", err)
}
if files := cb.AllFiles(); len(files) != 1 || files[0].Path != "ohai/plugins/x.rb" {
t.Fatalf("AllFiles = %+v, want the ohai plugin", files)
}
})
}
}

// Download fetches its manifest through Get, so it asks for version 2 too.
func TestCookbooksDownload_AsksForServerAPIVersion2(t *testing.T) {
srv := cinctest.New(t)
srv.Handle("GET /organizations/o/cookbooks/nginx/1.2.0", cinctest.Route{
Body: `{"cookbook_name":"nginx","version":"1.2.0","all_files":[]}`,
Assert: func(t *testing.T, r *http.Request, _ []byte) {
if v := r.Header.Get("X-Ops-Server-API-Version"); v != "2" {
t.Errorf("Download manifest GET API version = %q, want 2", v)
}
},
})
c := newTestClient(t, srv.Server)
if err := c.Cookbooks.Download(context.Background(), "nginx", "1.2.0", filepath.Join(t.TempDir(), "out")); err != nil {
t.Fatalf("Download: %v", err)
}
}
34 changes: 22 additions & 12 deletions cookbooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,11 @@ type CookbookMetadata struct {
}

// Cookbook is a single cookbook version's manifest as returned by the server.
// A server returns files in one of two shapes: the per-segment slices (the
// classic cookbook_version layout) or the flat AllFilesManifest ("all_files",
// used by Policyfile-era cookbook and cookbook_artifact manifests). AllFiles
// merges whichever the server populated.
// A server returns files in one of two shapes: the flat AllFilesManifest
// ("all_files", server API version 2, which Get asks for) or the per-segment
// slices (the classic cookbook_version layout, returned at API version 0 or 1
// and by servers older than version 2). AllFiles merges whichever the server
// populated.
type Cookbook struct {
CookbookName string `json:"cookbook_name"`
Name string `json:"name"`
Expand All @@ -97,10 +98,13 @@ type Cookbook struct {
Metadata CookbookMetadata `json:"metadata,omitzero"`

// AllFilesManifest is the flat "all_files" file list. Cookbooks uploaded by
// this client use it, and modern servers return it on Get.
// this client use it, and a server that speaks API version 2 returns it on
// Get. It holds every file, including those in no classic segment.
AllFilesManifest []CookbookFileRef `json:"all_files,omitempty"`

// Per-segment slices (classic cookbook_version layout).
// Per-segment slices (classic cookbook_version layout), populated only by a
// server that predates API version 2. They cannot hold a file outside the
// nine segments.
Files []CookbookFileRef `json:"files"`
Definitions []CookbookFileRef `json:"definitions"`
Libraries []CookbookFileRef `json:"libraries"`
Expand Down Expand Up @@ -235,9 +239,12 @@ func (s *CookbooksService) GetVersions(ctx context.Context, name, numVersions st
return &entry, resp, nil
}

// Get retrieves a single cookbook version manifest.
// Get retrieves a single cookbook version manifest. It asks for server API
// version 2 (manifestAPIVersion), so the files come back in AllFilesManifest:
// at version 0 or 1 Chef Server returns only the nine classic segments and
// drops every file outside them, such as ohai/ and compliance/.
func (s *CookbooksService) Get(ctx context.Context, name, version string) (*Cookbook, *Response, error) {
cb, resp, err := do[Cookbook](ctx, s.client, "GET",
cb, resp, err := do[Cookbook](withServerAPIVersion(ctx, manifestAPIVersion), s.client, "GET",
s.client.orgPath("/cookbooks/"+esc(name)+"/"+esc(version)), nil)
return ptrOrNil(cb, err), resp, err
}
Expand Down Expand Up @@ -436,10 +443,13 @@ func createTemp(root *os.Root, rel string) (string, *os.File, error) {
return name, f, err
}

// manifestAPIVersion is the server API version the manifest PUT asks for.
// The manifest lists files in the flat all_files form, which Chef Server only
// accepts from API version 2 on: at 0 or 1 erchef validates the body against
// the per-segment schema and rejects the all_files key.
// manifestAPIVersion is the server API version cookbook and artifact
// manifests are sent and fetched at. The manifest lists files in the flat
// all_files form, which Chef Server only accepts from API version 2 on: at 0
// or 1 erchef validates the body against the per-segment schema and rejects
// the all_files key. On a GET at 0 or 1 erchef rebuilds the segments from the
// stored all_files and silently drops any file outside them
// (chef_cookbook_version:populate_segments), so the manifest is read at 2 too.
const manifestAPIVersion = "2"

// uploadCookbook implements the three-step upload, shared with cookbook_artifacts.
Expand Down
68 changes: 64 additions & 4 deletions integration/suite/cookbooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,9 @@ func testCookbookUploadDownload(t *testing.T, _ Target, c *cinc.Client) {
t.Errorf("metadata dependencies = %v", md.Dependencies)
}
// Each file is classified into the segment chef-client looks in, so it
// can find the recipe. How that shows depends on the server API version:
// the per-segment layout (erchef at API v0/v1) lists the file in the
// segment's slice under its bare name, while all_files (API v2, and
// cinc-server-ng at any version) prefixes the name with the segment.
// can find the recipe. Get asks for API v2, where the server returns
// all_files and prefixes each name with its segment; a server older than
// v2 lists the file in the segment's slice under its bare name instead.
segments := fileSegments(got)
for path, segment := range map[string]string{
"recipes/default.rb": "recipes",
Expand All @@ -106,6 +105,67 @@ func testCookbookUploadDownload(t *testing.T, _ Target, c *cinc.Client) {
}
}

// testCookbookNonSegmentFiles uploads a cookbook and a cookbook artifact with
// files outside the nine classic segments (ohai/, compliance/) and checks
// that both download intact. erchef returns such files only in a manifest
// fetched at server API version 2: at 0 or 1 it rebuilds the segments and
// drops the rest (chef_cookbook_version:populate_segments).
func testCookbookNonSegmentFiles(t *testing.T, _ Target, c *cinc.Client) {
ctx := t.Context()
name := uniqueName(t, "nonsegment")
identifier := randomHex(t, 20)
cleanup(t, "cookbook "+name, func(ctx context.Context) error {
_, err := c.Cookbooks.Delete(ctx, name, "1.0.0")
return err
})
cleanup(t, "cookbook artifact "+name, func(ctx context.Context) error {
_, err := c.CookbookArtifacts.Delete(ctx, name, identifier)
return err
})

src := filepath.Join(t.TempDir(), "src")
files := map[string]string{
"metadata.rb": "name '" + name + "'\nversion '1.0.0'\n",
"recipes/default.rb": uniqueContent(name, "package 'nginx'\n"),
"ohai/plugins/x.rb": uniqueContent(name, "Ohai.plugin(:X) { provides 'x' }\n"),
"compliance/inspec.yml": uniqueContent(name, "name: x\n"),
"compliance/profiles/x.rb": uniqueContent(name, "control 'x' do\nend\n"),
}
for rel, content := range files {
writeFile(t, filepath.Join(src, filepath.FromSlash(rel)), content)
}
cb, err := cinc.LocalCookbookFromDir(src, "")
if err != nil {
t.Fatalf("LocalCookbookFromDir: %v", err)
}

if err := c.Cookbooks.Upload(ctx, cb); err != nil {
t.Fatalf("Upload: %v", err)
}
dest := t.TempDir()
if err := c.Cookbooks.Download(ctx, name, "1.0.0", dest); err != nil {
t.Fatalf("Download: %v", err)
}
for rel, want := range files {
assertFile(t, filepath.Join(dest, filepath.FromSlash(rel)), want)
}

if err := c.CookbookArtifacts.Upload(ctx, cb, identifier); err != nil {
t.Fatalf("CookbookArtifacts.Upload: %v", err)
}
artifact, _, err := c.CookbookArtifacts.Get(ctx, name, identifier)
if err != nil {
t.Fatalf("CookbookArtifacts.Get: %v", err)
}
dest = t.TempDir()
if err := c.Cookbooks.DownloadFiles(ctx, artifact, dest); err != nil {
t.Fatalf("DownloadFiles(artifact): %v", err)
}
for rel, want := range files {
assertFile(t, filepath.Join(dest, filepath.FromSlash(rel)), want)
}
}

// testCookbookArtifactUpload uploads a content-addressed cookbook artifact
// (Policyfile mode) and reads it back by identifier.
func testCookbookArtifactUpload(t *testing.T, _ Target, c *cinc.Client) {
Expand Down
1 change: 1 addition & 0 deletions integration/suite/suite.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ var cases = []testCase{
{"search/query", testSearchQuery},
{"clients/lifecycle", testClientLifecycle},
{"cookbooks/upload-download", testCookbookUploadDownload},
{"cookbooks/non-segment-files", testCookbookNonSegmentFiles},
{"cookbook-artifacts/upload", testCookbookArtifactUpload},
{"policies/push-revision-two-groups", testPushRevisionToTwoGroups},
{"roles/lifecycle", testRoleLifecycle},
Expand Down