diff --git a/README.md b/README.md index 89eb83b..fe405c0 100644 --- a/README.md +++ b/README.md @@ -243,6 +243,7 @@ Flags: --local-path string use a local directory containing the RO-Crate metadata instead of fetching it from GitHub --owner string GitHub owner that hosts the curated services (default "grycap") --path string subdirectory inside the repository that contains the services + --preview show the resolved service FDL in YAML (secrets redacted) without accessing a cluster --ref string Git reference (branch, tag, or commit) to query (default "main") -n, --name string override the OSCAR service and primary bucket names during deployment --repo string GitHub repository that hosts the curated services (default "oscar-hub") @@ -255,6 +256,28 @@ When `--env-file` is provided, matching keys override values declared under `environment.variables` and `environment.secrets` in the service FDL. Keys that are not declared by the service are ignored. +For OSCAR Agent Profile 1.1 crates, `hub deploy` resolves `agentSoul` and +`agentSkills` from the crate's local RO-Crate files into declared `AGENT_SOUL` +and `AGENT_SKILLS` variables. Skills are sorted by `@id` and joined with two +newlines. `--env-file` values take precedence over the crate defaults. Use +`--preview` to inspect the resolved FDL, including embedded script and guidance +as readable multiline YAML. It applies `--name` to the service and storage paths, +redacts declared secrets and fields with credential-like names, and neither +requires a cluster configuration nor contacts the OSCAR API. If the FDL has +multiple services, preview and deploy use the same one: the first nonempty +entry in FDL order, choosing the lexicographically first cluster key within +that entry. It shows the source FDL prepared for deployment, not the +cluster-enriched HTTP payload. +Free-form text such as scripts or agent guidance may still contain sensitive +instructions; redirect preview output only to a safe location. An unresolved +`YOUR_AGENT_SOUL` or `YOUR_AGENT_SKILLS` blocks deploy. + +For example, to inspect an agent from the local oscar-agents checkout: + +``` +oscar-cli hub deploy pdf-summarizer --local-path ../oscar-agents/crates --preview +``` + Default curated source: https://github.com/grycap/oscar-hub/tree/main ##### validate diff --git a/cmd/hub_agent_deploy_test.go b/cmd/hub_agent_deploy_test.go new file mode 100644 index 0000000..6a0071a --- /dev/null +++ b/cmd/hub_agent_deploy_test.go @@ -0,0 +1,88 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/grycap/oscar/v4/pkg/types" +) + +func TestHubAgentDeploySendsMaterializedGuidance(t *testing.T) { + const metadata = `{"@graph":[{"@id":"./","@type":["Dataset","Agent"],"conformsTo":{"@id":"https://github.com/grycap/oscar-agents/tree/devel/profiles/oscar-agent-1.1"},"agentSoul":{"@id":"SOUL.md"},"agentSkills":[{"@id":"skills/a/SKILL.md"}],"hasPart":[{"@id":"SOUL.md"},{"@id":"skills/a/SKILL.md"}]},{"@id":"SOUL.md","@type":["File","AgentSoul"],"encodingFormat":"text/markdown"},{"@id":"skills/a/SKILL.md","@type":["File","AgentSkill"],"encodingFormat":"text/markdown"}]}` + const fdl = `functions: + oscar: + - default: + name: agent-demo + script: script.sh + environment: + variables: + AGENT_SOUL: YOUR_AGENT_SOUL + AGENT_SKILLS: YOUR_AGENT_SKILLS +` + gitServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("ref") != "devel" { + t.Errorf("unexpected Git ref: %q", r.URL.RawQuery) + } + switch r.URL.Path { + case "/repos/grycap/oscar-agents/contents/crates/agent-demo": + fmt.Fprint(w, `[{"name":"fdl.yml","type":"file"},{"name":"script.sh","type":"file"}]`) + case "/repos/grycap/oscar-agents/contents/crates/agent-demo/fdl.yml": + fmt.Fprint(w, fdl) + case "/repos/grycap/oscar-agents/contents/crates/agent-demo/script.sh": + fmt.Fprint(w, "#!/bin/sh\n") + case "/repos/grycap/oscar-agents/contents/crates/agent-demo/ro-crate-metadata.json": + fmt.Fprint(w, metadata) + case "/repos/grycap/oscar-agents/contents/crates/agent-demo/SOUL.md": + fmt.Fprint(w, "agent identity\n") + case "/repos/grycap/oscar-agents/contents/crates/agent-demo/skills/a/SKILL.md": + fmt.Fprint(w, "agent ability\n") + default: + t.Errorf("unexpected GitHub request: %s", r.URL.Path) + http.NotFound(w, r) + } + })) + defer gitServer.Close() + + var deployed types.Service + cluster := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && r.URL.Path == "/system/config": + fmt.Fprint(w, `{"name":"oscar","namespace":"oscar","services_namespace":"oscar-svc"}`) + case r.Method == http.MethodGet && r.URL.Path == "/system/services/agent-demo": + http.NotFound(w, r) + case r.Method == http.MethodPost && r.URL.Path == "/system/services": + if err := json.NewDecoder(r.Body).Decode(&deployed); err != nil { + t.Errorf("decoding payload: %v", err) + } + w.WriteHeader(http.StatusCreated) + default: + t.Errorf("unexpected OSCAR request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } + })) + defer cluster.Close() + + config := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(config, []byte(fmt.Sprintf("oscar:\n test:\n endpoint: %s\ndefault: test\n", cluster.URL)), 0600); err != nil { + t.Fatal(err) + } + oldConfig := configPath + configPath = config + t.Cleanup(func() { configPath = oldConfig }) + cmd := makeHubDeployCmd() + cmd.SetOut(&bytes.Buffer{}) + cmd.SetArgs([]string{"agent-demo", "--repo", "oscar-agents", "--ref", "devel", "--api-base", gitServer.URL, "--cluster", "test"}) + if err := cmd.Execute(); err != nil { + t.Fatal(err) + } + if deployed.Environment.Vars["AGENT_SOUL"] != "agent identity\n" || deployed.Environment.Vars["AGENT_SKILLS"] != "agent ability\n" || !strings.Contains(deployed.Script, "#!/bin/sh") { + t.Fatalf("deployment payload missing resolved guidance/script: %#v", deployed.Environment.Vars) + } +} diff --git a/cmd/hub_agent_test.go b/cmd/hub_agent_test.go new file mode 100644 index 0000000..5939673 --- /dev/null +++ b/cmd/hub_agent_test.go @@ -0,0 +1,130 @@ +package cmd + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "gopkg.in/yaml.v3" +) + +func TestHubAgentPreviewAndOverrideWithoutCluster(t *testing.T) { + crate := filepath.Join(t.TempDir(), "demo") + if err := os.MkdirAll(crate, 0700); err != nil { + t.Fatal(err) + } + files := map[string]string{ + "fdl.yml": `functions: + oscar: + - default: + name: demo + script: script.sh + environment: + variables: + AGENT_SOUL: YOUR_AGENT_SOUL + AGENT_SKILLS: YOUR_AGENT_SKILLS + secrets: + OPENAI_API_KEY: not-for-preview + input: + - storage_provider: minio.default + path: demo/input +`, + "script.sh": "#!/bin/sh\n", + "SOUL.md": "soul\nline two\n", + "ro-crate-metadata.json": `{"@graph":[{"@id":"./","@type":["Dataset","Agent"],"conformsTo":{"@id":"https://github.com/grycap/oscar-agents/tree/devel/profiles/oscar-agent-1.1"},"agentSoul":{"@id":"SOUL.md"},"hasPart":[{"@id":"SOUL.md"}]},{"@id":"SOUL.md","@type":["File","AgentSoul"],"encodingFormat":"text/markdown"}]}`, + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(crate, name), []byte(content), 0600); err != nil { + t.Fatal(err) + } + } + envFile := filepath.Join(t.TempDir(), ".env") + if err := os.WriteFile(envFile, []byte("OPENAI_API_KEY=secret-override\n"), 0600); err != nil { + t.Fatal(err) + } + oldConfig := configPath + configPath = filepath.Join(t.TempDir(), "nonexistent-config.yaml") + t.Cleanup(func() { configPath = oldConfig }) + cmd := makeHubDeployCmd() + var output bytes.Buffer + cmd.SetOut(&output) + cmd.SetArgs([]string{"demo", "--local-path", crate, "--preview", "--env-file", envFile, "--name", "renamed"}) + if err := cmd.Execute(); err != nil { + t.Fatal(err) + } + text := output.String() + if !strings.Contains(text, "AGENT_SOUL: |") || !strings.Contains(text, "script: |") || !strings.Contains(text, "line two\n") { + t.Fatalf("expected multiline YAML in preview: %s", text) + } + if strings.Contains(text, "not-for-preview") || strings.Contains(text, "secret-override") || strings.Contains(text, "YOUR_AGENT_") { + t.Fatal("preview leaked secrets or unresolved placeholders") + } + var preview map[string]any + if err := yaml.Unmarshal(output.Bytes(), &preview); err != nil { + t.Fatalf("preview is not valid YAML: %v", err) + } + entry := preview["functions"].(map[string]any)["oscar"].([]any)[0].(map[string]any)["default"].(map[string]any) + if entry["name"] != "renamed" || entry["script"] != "#!/bin/sh\n" { + t.Fatalf("preview does not represent effective service: %#v", entry) + } + if _, ok := entry["alpine"]; ok { + t.Fatal("preview includes unconfigured zero-value service fields") + } + env := entry["environment"].(map[string]any) + if env["variables"].(map[string]any)["AGENT_SOUL"] != "soul\nline two\n" || env["secrets"].(map[string]any)["OPENAI_API_KEY"] != "[REDACTED]" { + t.Fatalf("unexpected guidance or secret handling: %#v", env) + } + if entry["input"].([]any)[0].(map[string]any)["path"] != "renamed/input" { + t.Fatal("preview did not apply name override to storage paths") + } +} + +func TestHubPreviewRedactsCredentialFields(t *testing.T) { + data := map[string]any{ + "environment": map[string]any{ + "variables": map[string]any{"API_KEY": "var-sensitive", "SAFE": "visible"}, + "secrets": map[string]any{"GENERIC": "secret-sensitive"}, + }, + "clusters": map[string]any{"example": map[string]any{"auth_password": "password-sensitive", "endpoint": "https://example.invalid"}}, + "storage_providers": map[string]any{"minio": map[string]any{"access_key": "access-sensitive", "secret_key": "key-sensitive"}}, + } + redactPreview(data, "") + encoded, err := yaml.Marshal(data) + if err != nil { + t.Fatal(err) + } + text := string(encoded) + for _, value := range []string{"var-sensitive", "secret-sensitive", "password-sensitive", "access-sensitive", "key-sensitive"} { + if strings.Contains(text, value) { + t.Fatalf("credential leaked in preview: %s", value) + } + } + if !strings.Contains(text, "https://example.invalid") || !strings.Contains(text, "visible") { + t.Fatal("preview removed non-secret configuration") + } +} + +func TestHubAgentPreviewRejectsUnresolvedGuidance(t *testing.T) { + crate := t.TempDir() + if err := os.WriteFile(filepath.Join(crate, "fdl.yml"), []byte(`functions: + oscar: + - default: + name: demo + script: script.sh + environment: + variables: + AGENT_SOUL: YOUR_AGENT_SOUL +`), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(crate, "script.sh"), []byte("#!/bin/sh\n"), 0600); err != nil { + t.Fatal(err) + } + cmd := makeHubDeployCmd() + cmd.SetArgs([]string{"demo", "--local-path", crate, "--preview"}) + if err := cmd.Execute(); err == nil || !strings.Contains(err.Error(), "unresolved agent guidance") { + t.Fatalf("expected unresolved guidance error; got %v", err) + } +} diff --git a/cmd/hub_deploy.go b/cmd/hub_deploy.go index 7ee82ba..af34d6d 100644 --- a/cmd/hub_deploy.go +++ b/cmd/hub_deploy.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "os" + "sort" "strings" "github.com/grycap/oscar-cli/v2/pkg/cluster" @@ -24,6 +25,7 @@ type hubDeployOptions struct { name string localPath string envFile string + preview bool } func (o *hubDeployOptions) applyToClient() []hub.Option { @@ -41,20 +43,8 @@ func (o *hubDeployOptions) applyToClient() []hub.Option { func hubDeployFunc(cmd *cobra.Command, args []string, opts *hubDeployOptions) error { slug := args[0] - - conf, err := config.ReadConfig(configPath) - if err != nil { - return err - } - - clusterName, err := getCluster(cmd, conf) - if err != nil { - return err - } - - clusterCfg := conf.Oscar[clusterName] - var fdl *service.FDL + var err error if strings.TrimSpace(opts.localPath) != "" { if _, err := os.Stat(opts.localPath); err != nil { @@ -64,34 +54,90 @@ func hubDeployFunc(cmd *cobra.Command, args []string, opts *hubDeployOptions) er if err != nil { return err } + if err := hub.MaterializeLocalAgentGuidance(opts.localPath, slug, fdl); err != nil { + return err + } } else { client := hub.NewClient(opts.applyToClient()...) fdl, err = client.FetchFDL(cmd.Context(), slug) if err != nil { return err } + if err := client.MaterializeRemoteAgentGuidance(cmd.Context(), slug, fdl); err != nil { + return err + } + } + var envFileValues map[string]string + if strings.TrimSpace(opts.envFile) != "" { + envFileValues, err = service.ReadEnvFile(opts.envFile) + if err != nil { + return err + } + } + for _, entry := range fdl.Functions.Oscar { + for _, svc := range entry { + service.ApplyEnvFileValuesToService(svc, envFileValues) + if svc == nil { + continue + } + for _, key := range []string{"AGENT_SOUL", "AGENT_SKILLS"} { + if value, ok := svc.Environment.Vars[key]; ok && value == "YOUR_"+key { + return fmt.Errorf("%s contains unresolved agent guidance; provide valid RO-Crate metadata or override it with --env-file", key) + } + } + } + } + // Select once for both preview and deployment. Preserve FDL list order and + // sort keys within an entry so multi-service definitions are deterministic. + var selected *service.FDL + for _, entry := range fdl.Functions.Oscar { + clusterIDs := make([]string, 0, len(entry)) + for clusterID := range entry { + clusterIDs = append(clusterIDs, clusterID) + } + sort.Strings(clusterIDs) + for _, clusterID := range clusterIDs { + svc := entry[clusterID] + if svc == nil { + continue + } + if opts.name != "" { + overrideServiceName(svc, opts.name) + } + selected = new(service.FDL) + *selected = *fdl + selected.Functions.Oscar = []map[string]*types.Service{{clusterID: svc}} + break + } + if selected != nil { + break + } + } + if selected == nil { + return errors.New("the FDL does not contain an OSCAR service definition") + } + if opts.preview { + return printHubPreview(cmd.OutOrStdout(), selected) } - clusterConfig, err := clusterCfg.GetClusterConfig() + conf, err := config.ReadConfig(configPath) if err != nil { return err } - - serviceDef, err := buildServiceFromFDL(fdl, clusterName, clusterCfg, clusterConfig.MinIOProvider) + clusterName, err := getCluster(cmd, conf) if err != nil { return err } + clusterCfg := conf.Oscar[clusterName] - if strings.TrimSpace(opts.envFile) != "" { - envFileValues, err := service.ReadEnvFile(opts.envFile) - if err != nil { - return err - } - service.ApplyEnvFileValuesToService(serviceDef, envFileValues) + clusterConfig, err := clusterCfg.GetClusterConfig() + if err != nil { + return err } - if opts.name != "" { - overrideServiceName(serviceDef, opts.name) + serviceDef, err := buildServiceFromFDL(selected, clusterName, clusterCfg, clusterConfig.MinIOProvider) + if err != nil { + return err } action := "Creating" @@ -140,6 +186,7 @@ func makeHubDeployCmd() *cobra.Command { cmd.Flags().StringVarP(&opts.name, "name", "n", "", "override the OSCAR service and primary bucket names during deployment") cmd.Flags().StringVar(&opts.localPath, "local-path", "", "use a local directory containing the RO-Crate metadata instead of fetching it from GitHub") cmd.Flags().StringVar(&opts.envFile, "env-file", "", "load environment variables and secrets from a dotenv file") + cmd.Flags().BoolVar(&opts.preview, "preview", false, "show the resolved service FDL in YAML (secrets redacted) without accessing a cluster") cmd.Flags().StringP("cluster", "c", "", "set the cluster") if flag := cmd.Flags().Lookup("api-base"); flag != nil { diff --git a/cmd/hub_deploy_test.go b/cmd/hub_deploy_test.go index 6e8785b..b63eeb4 100644 --- a/cmd/hub_deploy_test.go +++ b/cmd/hub_deploy_test.go @@ -53,6 +53,8 @@ functions: fmt.Fprint(w, fdlContent) case "/repos/grycap/oscar-hub/contents/cowsay/script.sh", "/repos/grycap/oscar-hub/contents/crates/cowsay/script.sh": fmt.Fprint(w, scriptContent) + case "/repos/grycap/oscar-hub/contents/crates/cowsay/ro-crate-metadata.json": + http.NotFound(w, r) default: t.Fatalf("unexpected github request: %s", r.URL.Path) } diff --git a/cmd/hub_multi_service_test.go b/cmd/hub_multi_service_test.go new file mode 100644 index 0000000..8dc9578 --- /dev/null +++ b/cmd/hub_multi_service_test.go @@ -0,0 +1,105 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/grycap/oscar/v4/pkg/types" + "gopkg.in/yaml.v3" +) + +func TestHubDeployPreviewMatchesSelectedService(t *testing.T) { + crate := t.TempDir() + fdl := `functions: + oscar: + - zeta: + name: second + script: script.sh + input: + - storage_provider: minio.default + path: second/input + alpha: + name: first + script: script.sh + input: + - storage_provider: minio.default + path: first/input +` + if err := os.WriteFile(filepath.Join(crate, "fdl.yml"), []byte(fdl), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(crate, "script.sh"), []byte("#!/bin/sh\n"), 0600); err != nil { + t.Fatal(err) + } + var deployed types.Service + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && r.URL.Path == "/system/config": + fmt.Fprint(w, `{"name":"oscar","namespace":"oscar","services_namespace":"oscar-svc"}`) + case r.Method == http.MethodGet && r.URL.Path == "/system/services/renamed": + http.NotFound(w, r) + case r.Method == http.MethodPost && r.URL.Path == "/system/services": + if err := json.NewDecoder(r.Body).Decode(&deployed); err != nil { + t.Errorf("decoding deployment: %v", err) + } + w.WriteHeader(http.StatusCreated) + default: + t.Errorf("unexpected cluster request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } + })) + defer server.Close() + configFile := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(configFile, []byte(fmt.Sprintf("oscar:\n test:\n endpoint: %s\ndefault: test\n", server.URL)), 0600); err != nil { + t.Fatal(err) + } + oldConfig := configPath + configPath = configFile + t.Cleanup(func() { configPath = oldConfig }) + + for i := 0; i < 20; i++ { + previewCmd := makeHubDeployCmd() + var output bytes.Buffer + previewCmd.SetOut(&output) + previewCmd.SetArgs([]string{"demo", "--local-path", crate, "--name", "renamed", "--preview"}) + if err := previewCmd.Execute(); err != nil { + t.Fatal(err) + } + var document struct { + Functions struct { + Oscar []map[string]struct { + Name string `yaml:"name"` + Input []struct { + Path string `yaml:"path"` + } `yaml:"input"` + } `yaml:"oscar"` + } `yaml:"functions"` + } + if err := yaml.Unmarshal(output.Bytes(), &document); err != nil { + t.Fatal(err) + } + if len(document.Functions.Oscar) != 1 || len(document.Functions.Oscar[0]) != 1 { + t.Fatalf("preview must contain exactly one service: %s", output.String()) + } + preview, ok := document.Functions.Oscar[0]["alpha"] + if !ok || len(preview.Input) != 1 || preview.Input[0].Path != "renamed/input" { + t.Fatalf("preview did not consistently select alpha: %s", output.String()) + } + + deployCmd := makeHubDeployCmd() + deployCmd.SetOut(&bytes.Buffer{}) + deployCmd.SetArgs([]string{"demo", "--local-path", crate, "--name", "renamed", "--cluster", "test"}) + if err := deployCmd.Execute(); err != nil { + t.Fatal(err) + } + if deployed.Name != preview.Name || len(deployed.Input) != 1 || deployed.Input[0].Path != preview.Input[0].Path { + t.Fatalf("deployment differs from preview: name=%q input=%v; preview=%+v", deployed.Name, deployed.Input, preview) + } + } +} diff --git a/cmd/hub_preview.go b/cmd/hub_preview.go new file mode 100644 index 0000000..b7d781d --- /dev/null +++ b/cmd/hub_preview.go @@ -0,0 +1,130 @@ +package cmd + +import ( + "fmt" + "io" + "strings" + + "github.com/grycap/oscar-cli/v2/pkg/service" + "github.com/grycap/oscar/v4/pkg/types" + "gopkg.in/yaml.v3" +) + +const previewRedacted = "[REDACTED]" + +// printHubPreview renders the original FDL with the resolved service values, +// not the cluster-enriched HTTP request. The original source preserves only +// the fields explicitly configured by the crate rather than adding defaults. +func printHubPreview(out io.Writer, fdl *service.FDL) error { + var data map[string]any + if len(fdl.Source) == 0 { + return fmt.Errorf("original FDL source is unavailable for preview") + } + if err := yaml.Unmarshal(fdl.Source, &data); err != nil { + return fmt.Errorf("parsing original FDL for preview: %w", err) + } + if err := overlayResolvedService(data, fdl); err != nil { + return err + } + redactPreview(data, "") + preview, err := yaml.Marshal(data) + if err != nil { + return fmt.Errorf("formatting resolved FDL: %w", err) + } + _, err = out.Write(preview) + return err +} + +func overlayResolvedService(data map[string]any, fdl *service.FDL) error { + functions, ok := data["functions"].(map[string]any) + if !ok { + return fmt.Errorf("preview FDL has no functions") + } + entries, ok := functions["oscar"].([]any) + if !ok { + return fmt.Errorf("preview FDL has no OSCAR services") + } + for clusterID, svc := range fdl.Functions.Oscar[0] { + for _, raw := range entries { + entry, ok := raw.(map[string]any) + if !ok { + continue + } + doc, ok := entry[clusterID].(map[string]any) + if !ok { + continue + } + doc["name"] = svc.Name + doc["script"] = svc.Script + if environment, ok := doc["environment"].(map[string]any); ok { + for name, values := range map[string]map[string]string{"variables": svc.Environment.Vars, "secrets": svc.Environment.Secrets} { + if original, ok := environment[name].(map[string]any); ok { + for key := range original { + if value, present := values[key]; present { + original[key] = value + } + } + } + } + } + updateStoragePaths(doc["input"], svc.Input) + updateStoragePaths(doc["output"], svc.Output) + if mount, ok := doc["mount"].(map[string]any); ok { + mount["path"] = svc.Mount.Path + } + functions["oscar"] = []any{map[string]any{clusterID: doc}} + return nil + } + } + return fmt.Errorf("resolved service is absent from the original FDL") +} + +func updateStoragePaths(raw any, paths []types.StorageIOConfig) { + items, ok := raw.([]any) + if !ok { + return + } + for i, item := range items { + if i >= len(paths) { + break + } + if entry, ok := item.(map[string]any); ok { + entry["path"] = paths[i].Path + } + } +} + +func redactPreview(value any, parent string) { + switch fields := value.(type) { + case map[string]any: + for key, child := range fields { + if parent == "environment" && key == "secrets" { + if secrets, ok := child.(map[string]any); ok { + for name := range secrets { + secrets[name] = previewRedacted + } + } + continue + } + if isSensitivePreviewKey(key) { + fields[key] = previewRedacted + continue + } + redactPreview(child, key) + } + case []any: + for _, child := range fields { + redactPreview(child, parent) + } + } +} + +func isSensitivePreviewKey(key string) bool { + upper := strings.ToUpper(key) + for _, marker := range []string{"PASSWORD", "SECRET", "TOKEN", "API_KEY", "ACCESS_KEY", "PRIVATE_KEY", "CREDENTIAL"} { + if strings.Contains(upper, marker) { + return true + } + } + return false +} diff --git a/pkg/hub/agent_guidance.go b/pkg/hub/agent_guidance.go new file mode 100644 index 0000000..97132ec --- /dev/null +++ b/pkg/hub/agent_guidance.go @@ -0,0 +1,172 @@ +package hub + +import ( + "context" + "errors" + "fmt" + + "os" + "path" + "path/filepath" + "sort" + "strings" + "unicode/utf8" + + "github.com/grycap/oscar-cli/v2/pkg/service" +) + +// MaterializeAgentGuidance resolves the local guidance declared by OSCAR Agent +// Profile 1.1. Only variables already declared in the FDL are changed. +func MaterializeAgentGuidance(fdl *service.FDL, raw []byte, readFile func(string) ([]byte, error)) error { + crate, err := ParseROCrate(raw) + if err != nil { + return err + } + root, err := crate.datasetNode() + if err != nil { + return err + } + if !hasType(root["@type"], "Agent") { + return nil + } + profile := extractIDs(root["conformsTo"]) + if len(profile) != 1 || profile[0] != "https://github.com/grycap/oscar-agents/tree/devel/profiles/oscar-agent-1.1" { + return fmt.Errorf("unsupported OSCAR agent profile: %v", profile) + } + parts := make(map[string]bool) + for _, id := range extractIDs(root["hasPart"]) { + parts[id] = true + } + resolve := func(id, kind string) (string, error) { + if !parts[id] || !validGuidancePath(id) { + return "", fmt.Errorf("%s %q is not a local crate part", kind, id) + } + entity := crate.entity(id) + if !hasType(entity["@type"], kind) || !hasType(entity["@type"], "File") || entity["encodingFormat"] != "text/markdown" { + return "", fmt.Errorf("%s %q is not a Markdown %s file", kind, id, kind) + } + data, err := readFile(id) + if err != nil { + return "", fmt.Errorf("reading %s %q: %w", kind, id, err) + } + if !utf8.Valid(data) { + return "", fmt.Errorf("%s %q is not UTF-8", kind, id) + } + return string(data), nil + } + var soul, skills string + needSoul, needSkills := false, false + for _, entry := range fdl.Functions.Oscar { + for _, svc := range entry { + if svc == nil { + continue + } + _, s := svc.Environment.Vars["AGENT_SOUL"] + _, k := svc.Environment.Vars["AGENT_SKILLS"] + needSoul = needSoul || s + needSkills = needSkills || k + } + } + if needSoul { + ids := extractIDs(root["agentSoul"]) + if len(ids) != 1 { + return fmt.Errorf("agentSoul must reference exactly one local AgentSoul") + } + soul, err = resolve(ids[0], "AgentSoul") + if err != nil { + return err + } + } + if needSkills { + ids := extractIDs(root["agentSkills"]) + if _, present := root["agentSkills"]; present && len(ids) == 0 { + return fmt.Errorf("agentSkills must reference local AgentSkill files") + } + sort.Strings(ids) + values := make([]string, 0, len(ids)) + for _, id := range ids { + value, err := resolve(id, "AgentSkill") + if err != nil { + return err + } + values = append(values, value) + } + skills = strings.Join(values, "\n\n") + } + for _, entry := range fdl.Functions.Oscar { + for _, svc := range entry { + if svc == nil { + continue + } + if _, ok := svc.Environment.Vars["AGENT_SOUL"]; ok { + svc.Environment.Vars["AGENT_SOUL"] = soul + } + if _, ok := svc.Environment.Vars["AGENT_SKILLS"]; ok { + svc.Environment.Vars["AGENT_SKILLS"] = skills + } + } + } + return nil +} + +func validGuidancePath(id string) bool { + if id == "" || strings.Contains(id, "\\") || strings.Contains(id, ":") || strings.HasPrefix(id, "/") || path.Clean(id) != id { + return false + } + for _, part := range strings.Split(id, "/") { + if part == "" || part == "." || part == ".." { + return false + } + } + return strings.HasSuffix(id, ".md") +} + +// MaterializeLocalAgentGuidance reads metadata next to the selected FDL. +// Ordinary Hub crates without metadata retain their existing behavior. +func MaterializeLocalAgentGuidance(localRoot, slug string, fdl *service.FDL) error { + raw, baseDir, err := loadLocalMetadata(localRoot, slug) + if err != nil { + // Metadata is optional for ordinary FDLs, but malformed metadata is not. + if errors.Is(err, ErrMetadataNotFound) { + return nil + } + return err + } + base, err := filepath.EvalSymlinks(baseDir) + if err != nil { + return err + } + return MaterializeAgentGuidance(fdl, raw, func(id string) ([]byte, error) { + if !validGuidancePath(id) { + return nil, fmt.Errorf("invalid guidance path %q", id) + } + resolved, err := filepath.EvalSymlinks(filepath.Join(baseDir, filepath.FromSlash(id))) + if err != nil { + return nil, err + } + rel, err := filepath.Rel(base, resolved) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) { + return nil, fmt.Errorf("guidance path %q escapes crate", id) + } + return os.ReadFile(resolved) + }) +} + +// MaterializeRemoteAgentGuidance reads only crate-local references from the +// same repository and Git ref used for the FDL. +func (c *Client) MaterializeRemoteAgentGuidance(ctx context.Context, slug string, fdl *service.FDL) error { + repoPath := c.serviceRepoPath(slug) + raw, err := c.getFile(ctx, path.Join(repoPath, metadataFile)) + if errors.Is(err, ErrNotFound) { + return nil + } + if err != nil { + return err + } + return MaterializeAgentGuidance(fdl, raw, func(id string) ([]byte, error) { + if !validGuidancePath(id) { + return nil, fmt.Errorf("invalid guidance path %q", id) + } + return c.getFile(ctx, path.Join(repoPath, id)) + }) +} diff --git a/pkg/hub/agent_guidance_test.go b/pkg/hub/agent_guidance_test.go new file mode 100644 index 0000000..49515c7 --- /dev/null +++ b/pkg/hub/agent_guidance_test.go @@ -0,0 +1,156 @@ +package hub + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/grycap/oscar-cli/v2/pkg/service" + "github.com/grycap/oscar/v4/pkg/types" +) + +func agentFixture(soul string, skills ...string) []byte { + parts := []any{map[string]string{"@id": soul}} + graph := []any{map[string]any{ + "@id": "./", "@type": []string{"Dataset", "Agent"}, + "conformsTo": map[string]string{"@id": "https://github.com/grycap/oscar-agents/tree/devel/profiles/oscar-agent-1.1"}, + "agentSoul": map[string]string{"@id": soul}, + "agentSkills": []any{}, "hasPart": parts, + }} + graph = append(graph, map[string]any{"@id": soul, "@type": []string{"File", "AgentSoul"}, "encodingFormat": "text/markdown"}) + refs := []any{} + for _, id := range skills { + parts = append(parts, map[string]string{"@id": id}) + refs = append(refs, map[string]string{"@id": id}) + graph = append(graph, map[string]any{"@id": id, "@type": []string{"File", "AgentSkill"}, "encodingFormat": "text/markdown"}) + } + graph[0].(map[string]any)["hasPart"] = parts + graph[0].(map[string]any)["agentSkills"] = refs + raw, _ := json.Marshal(map[string]any{"@graph": graph}) + return raw +} + +func agentFDL() *service.FDL { + fdl := &service.FDL{} + fdl.Functions.Oscar = []map[string]*types.Service{{"default": {}}} + fdl.Functions.Oscar[0]["default"].Environment.Vars = map[string]string{"AGENT_SOUL": "YOUR_AGENT_SOUL", "AGENT_SKILLS": "YOUR_AGENT_SKILLS"} + return fdl +} + +func TestMaterializeAgentGuidance(t *testing.T) { + fdl := agentFDL() + files := map[string]string{"SOUL.md": "soul\n", "skills/z/SKILL.md": "z\n", "skills/a/SKILL.md": "a\n"} + err := MaterializeAgentGuidance(fdl, agentFixture("SOUL.md", "skills/z/SKILL.md", "skills/a/SKILL.md"), func(id string) ([]byte, error) { + return []byte(files[id]), nil + }) + if err != nil { + t.Fatal(err) + } + vars := fdl.Functions.Oscar[0]["default"].Environment.Vars + if vars["AGENT_SOUL"] != "soul\n" || vars["AGENT_SKILLS"] != "a\n\n\nz\n" { + t.Fatalf("unexpected materialization: %#v", vars) + } +} + +func TestMaterializeAgentGuidanceRejectsInvalidReference(t *testing.T) { + for _, id := range []string{"../SOUL.md", "/SOUL.md", "https://host/SOUL.md", "skills/../SOUL.md", "SOUL.txt"} { + t.Run(id, func(t *testing.T) { + called := false + err := MaterializeAgentGuidance(agentFDL(), agentFixture(id), func(string) ([]byte, error) { + called = true + return []byte("data"), nil + }) + if err == nil || called { + t.Fatalf("expected rejection before reading %s; err=%v read=%t", id, err, called) + } + }) + } +} + +func TestMaterializeAgentGuidanceDoesNotInjectUndeclared(t *testing.T) { + fdl := agentFDL() + fdl.Functions.Oscar[0]["default"].Environment.Vars = nil + called := false + err := MaterializeAgentGuidance(fdl, agentFixture("SOUL.md"), func(string) ([]byte, error) { + called = true + return nil, nil + }) + if err != nil || called || fdl.Functions.Oscar[0]["default"].Environment.Vars != nil { + t.Fatalf("unexpected undeclared injection: %v", err) + } +} + +func TestMaterializeAgentGuidanceRejectsMissingOrNonUTF8File(t *testing.T) { + metadata := agentFixture("SOUL.md") + for _, tc := range []struct { + name string + data []byte + err error + }{ + {"missing", nil, os.ErrNotExist}, + {"non-utf8", []byte{0xff}, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + fdl := agentFDL() + err := MaterializeAgentGuidance(fdl, metadata, func(string) ([]byte, error) { return tc.data, tc.err }) + if err == nil { + t.Fatal("expected invalid guidance to fail") + } + if fdl.Functions.Oscar[0]["default"].Environment.Vars["AGENT_SOUL"] != "YOUR_AGENT_SOUL" { + t.Fatal("failed resolution changed the FDL") + } + }) + } +} + +func TestMaterializeLocalAgentGuidanceRejectsSymlinkEscape(t *testing.T) { + root := t.TempDir() + outside := filepath.Join(t.TempDir(), "outside.md") + if err := os.WriteFile(outside, []byte("private"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, filepath.Join(root, "SOUL.md")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "ro-crate-metadata.json"), agentFixture("SOUL.md"), 0600); err != nil { + t.Fatal(err) + } + if err := MaterializeLocalAgentGuidance(root, "example", agentFDL()); err == nil || !strings.Contains(err.Error(), "escapes crate") { + t.Fatalf("expected symlink escape error, got %v", err) + } +} + +func TestMaterializeRemoteAgentGuidance(t *testing.T) { + metadata := agentFixture("SOUL.md", "skills/a/SKILL.md") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("ref") != "devel" { + t.Errorf("unexpected ref %s", r.URL.RawQuery) + } + switch r.URL.Path { + case "/repos/grycap/oscar-agents/contents/crates/demo/ro-crate-metadata.json": + _, _ = w.Write(metadata) + case "/repos/grycap/oscar-agents/contents/crates/demo/SOUL.md": + fmt.Fprint(w, "remote soul\n") + case "/repos/grycap/oscar-agents/contents/crates/demo/skills/a/SKILL.md": + fmt.Fprint(w, "remote skill\n") + default: + http.NotFound(w, r) + } + })) + defer server.Close() + client := NewClient(WithOwner("grycap"), WithRepo("oscar-agents"), WithRootPath("crates"), WithRef("devel"), WithBaseAPI(server.URL)) + fdl := agentFDL() + if err := client.MaterializeRemoteAgentGuidance(context.Background(), "demo", fdl); err != nil { + t.Fatal(err) + } + vars := fdl.Functions.Oscar[0]["default"].Environment.Vars + if vars["AGENT_SOUL"] != "remote soul\n" || vars["AGENT_SKILLS"] != "remote skill\n" { + t.Fatalf("unexpected remote values: %#v", vars) + } +} diff --git a/pkg/hub/hub.go b/pkg/hub/hub.go index 0208e49..be03b3b 100644 --- a/pkg/hub/hub.go +++ b/pkg/hub/hub.go @@ -509,6 +509,7 @@ func (c *Client) FetchFDL(ctx context.Context, slug string) (*service.FDL, error if err := yaml.Unmarshal(rawFDL, &parsed); err != nil { return nil, fmt.Errorf("parsing FDL: %w", err) } + parsed.Source = rawFDL if err := c.embedArtifacts(ctx, repoPath, &parsed); err != nil { return nil, err @@ -642,6 +643,7 @@ func readFDLFromFile(path string) (*service.FDL, error) { if err := yaml.Unmarshal(content, fdl); err != nil { return nil, fmt.Errorf("the FDL file %s is not valid, please check its definition", path) } + fdl.Source = content baseDir := filepath.Dir(path) diff --git a/pkg/hub/validate.go b/pkg/hub/validate.go index 65139dd..874021a 100644 --- a/pkg/hub/validate.go +++ b/pkg/hub/validate.go @@ -993,7 +993,7 @@ func loadLocalMetadata(localRoot, slug string) ([]byte, string, error) { } } - return nil, "", fmt.Errorf("ro-crate metadata not found for %s under %s", slug, localRoot) + return nil, "", fmt.Errorf("%w: ro-crate metadata not found for %s under %s", ErrMetadataNotFound, slug, localRoot) } func readFromRepository(ctx context.Context, client *Client, repoPath, relative string) ([]byte, error) { diff --git a/pkg/service/service.go b/pkg/service/service.go index 3170344..6f89eff 100644 --- a/pkg/service/service.go +++ b/pkg/service/service.go @@ -49,6 +49,8 @@ type FDL struct { } `json:"functions" binding:"required"` StorageProviders *types.StorageProviders `json:"storage_providers,omitempty"` Clusters map[string]types.Cluster `json:"clusters,omitempty"` + // Source is the original document for a readable preview; never sent to OSCAR. + Source []byte `json:"-" yaml:"-"` } // ReadFDL reads the content of FDL file and returns a valid FDL struct with the scripts and StorageProviders embedded into the services