diff --git a/.mise-tasks/test-cli b/.mise-tasks/test-cli index 7371848d..246e0230 100755 --- a/.mise-tasks/test-cli +++ b/.mise-tasks/test-cli @@ -18,6 +18,7 @@ echo " ✓ Testing help commands..." $CLI --help > /dev/null $CLI spec --help > /dev/null $CLI arazzo --help > /dev/null +$CLI asyncapi --help > /dev/null $CLI overlay --help > /dev/null # Test all subcommands help @@ -36,6 +37,7 @@ $CLI arazzo list-rules --help > /dev/null $CLI arazzo graph --help > /dev/null $CLI arazzo bootstrap --help > /dev/null $CLI arazzo explore --help > /dev/null +$CLI asyncapi validate --help > /dev/null $CLI overlay apply --help > /dev/null $CLI overlay validate --help > /dev/null $CLI overlay compare --help > /dev/null @@ -203,6 +205,36 @@ if $CLI arazzo validate arazzo/testdata/sources/invalid.arazzo.yaml > /dev/null exit 1 fi $CLI arazzo validate --skip-sources arazzo/testdata/sources/invalid.arazzo.yaml > /dev/null +$CLI arazzo validate arazzo/testdata/sources/async-valid.arazzo.yaml > /dev/null +if $CLI arazzo validate arazzo/testdata/sources/async-invalid.arazzo.yaml > /dev/null 2>&1; then + echo " ❌ Expected arazzo validation to fail for a document that doesn't match its AsyncAPI sources" + exit 1 +fi + +# Test AsyncAPI validation +echo " ✓ Testing asyncapi validation..." +$CLI asyncapi validate asyncapi/testdata/streetlights-3.0.yaml > /dev/null 2>&1 +$CLI asyncapi validate asyncapi/testdata/complete-3.1.yaml > /dev/null 2>&1 +$CLI asyncapi validate --resolve asyncapi/testdata/validate/orders.asyncapi.yaml > /dev/null 2>&1 +$CLI asyncapi validate --resolve --base-uri asyncapi/testdata/validate/orders.asyncapi.yaml < asyncapi/testdata/validate/orders.asyncapi.yaml > /dev/null 2>&1 +# References to other documents aren't followed without --resolve, which is a warning that only fails with --strict +$CLI asyncapi validate asyncapi/testdata/validate/broken-ref.asyncapi.yaml > dist/test/test-asyncapi-unresolved.txt 2>&1 +if ! grep -q "use --resolve to validate them" dist/test/test-asyncapi-unresolved.txt; then + echo " ❌ Expected asyncapi validate to report references it didn't follow" + exit 1 +fi +if $CLI asyncapi validate --strict asyncapi/testdata/validate/orders.asyncapi.yaml > /dev/null 2>&1; then + echo " ❌ Expected asyncapi validate --strict to fail on warnings" + exit 1 +fi +for f in broken-ref invalid v2; do + resolve="" + [ "$f" = "broken-ref" ] && resolve="--resolve" + if $CLI asyncapi validate $resolve asyncapi/testdata/validate/$f.asyncapi.yaml > /dev/null 2>&1; then + echo " ❌ Expected asyncapi validation to fail for $f.asyncapi.yaml" + exit 1 + fi +done # Test arazzo linting echo " ✓ Testing arazzo lint..." @@ -338,6 +370,7 @@ echo " - Validated known good and bad files" echo " - Tested bootstrap, upgrade, inline, clean, sanitize, bundle, join commands" echo " - Compared outputs with expected results" echo " - Tested arazzo validation, lint, list-rules, graph and bootstrap" +echo " - Tested asyncapi validation" echo " - Tested overlay validation, apply, and compare" echo " - Tested error cases and edge conditions" echo " - Validated all generated files" \ No newline at end of file diff --git a/README.md b/README.md index b4f718e5..5ffc82a4 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,10 @@ The `arazzo` package provides an API for working with Arazzo 1.0.x and 1.1.x documents including reading, creating, mutating, walking, validating, linting, upgrading and graphing them, and bootstrapping them from OpenAPI documents. +### [asyncapi](./asyncapi) + +The `asyncapi` package provides an API for working with AsyncAPI 3.0.x and 3.1.x documents including reading, creating, mutating, walking and validating them, resolving references within and across documents, and applying operation and message traits. + ### [openapi](./openapi) The `openapi` package provides an API for working with OpenAPI documents including reading, creating, mutating, walking, validating, upgrading, and linting them. Supports OpenAPI 3.0.x, 3.1.x, and 3.2.x specifications. @@ -86,7 +90,7 @@ The `overlay` package provides an API for working with OpenAPI Overlays includin ## CLI Tool -This repository also provides a comprehensive CLI tool for working with OpenAPI specifications, Arazzo workflows, and OpenAPI overlays. +This repository also provides a comprehensive CLI tool for working with OpenAPI specifications, Arazzo workflows, AsyncAPI documents and OpenAPI overlays. ### Installation @@ -118,7 +122,7 @@ For manual installation, upgrade instructions, custom installation options, and ### Usage -The CLI provides four main command groups: +The CLI provides five main command groups: - **`openapi spec`** - Commands for working with OpenAPI specifications ([documentation](./cmd/openapi/commands/openapi/README.md)) - `bootstrap` - Create a new OpenAPI document with best practice examples @@ -142,7 +146,7 @@ The CLI provides four main command groups: - `upgrade` - Upgrade a Swagger 2.0 specification to OpenAPI 3.0 - **`openapi arazzo`** - Commands for working with Arazzo workflow documents ([documentation](./cmd/openapi/commands/arazzo/README.md)) - - `validate` - Validate an Arazzo workflow document, including against the OpenAPI and Arazzo documents it references + - `validate` - Validate an Arazzo workflow document, including against the OpenAPI, AsyncAPI and Arazzo documents it references - `upgrade` - Upgrade an Arazzo workflow document to the latest supported version (1.1.0) - `lint` - Lint an Arazzo workflow document for semantic issues, style and security concerns, with optional fixes - `list-rules` - List the available Arazzo lint rules @@ -150,6 +154,9 @@ The CLI provides four main command groups: - `bootstrap` - Generate starter Arazzo workflows from an OpenAPI document, or create an example Arazzo document - `explore` - Interactively explore the workflows of an Arazzo document +- **`openapi asyncapi`** - Commands for working with AsyncAPI documents ([documentation](./cmd/openapi/commands/asyncapi/README.md)) + - `validate` - Validate an AsyncAPI 3.x document, optionally following references to other files and URLs + - **`openapi overlay`** - Commands for working with OpenAPI overlays ([documentation](./cmd/openapi/commands/overlay/README.md)) - `apply` - Apply an overlay to an OpenAPI specification - `compare` - Compare two specifications and generate an overlay describing differences @@ -209,6 +216,12 @@ openapi arazzo bootstrap --from ./openapi.yaml ./workflows.arazzo.yaml # Interactively explore the workflows of an Arazzo document openapi arazzo explore ./workflow.arazzo.yaml +# Validate an AsyncAPI document without reading anything outside it +openapi asyncapi validate ./asyncapi.yaml + +# Validate an AsyncAPI document and the files and URLs it references, failing on warnings +openapi asyncapi validate --resolve --strict ./asyncapi.yaml + # Validate a Swagger 2.0 document openapi swagger validate ./api.swagger.yaml diff --git a/arazzo/README.md b/arazzo/README.md index 16d82f95..8867b8ea 100644 --- a/arazzo/README.md +++ b/arazzo/README.md @@ -21,15 +21,27 @@ ## Supported versions -| Arazzo version | Support | -| -------------- | ------- | -| [1.1.x](https://spec.openapis.org/arazzo/v1.1.0) | Read, write, walk and validate, including AsyncAPI steps (`channelPath`, `action`, `correlationId`), `dependsOn`, `timeout`, Selector Objects, action `parameters`, `$self` and the stricter 1.1 runtime expression grammar. AsyncAPI documents are not loaded, so references into them are only checked structurally. | -| [1.0.x](https://spec.openapis.org/arazzo/v1.0.1) | Read, write, walk and validate. | +| Arazzo version | Support | +| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [1.1.x](https://spec.openapis.org/arazzo/v1.1.0) | Read, write, walk and validate, including AsyncAPI steps (`channelPath`, `action`, `correlationId`), `dependsOn`, `timeout`, Selector Objects, action `parameters`, `$self` and the stricter 1.1 runtime expression grammar. AsyncAPI 3.0 and 3.1 sources are checked by `ValidateSources` (see below); AsyncAPI 2.x sources are reported as unsupported and only checked structurally. | +| [1.0.x](https://spec.openapis.org/arazzo/v1.0.1) | Read, write, walk and validate. | Any patch release of a supported minor version is accepted (including prerelease suffixes such as `1.1.0-rc1`). Validation follows the version declared by the document, so using an Arazzo 1.1 feature in a document that declares `arazzo: 1.0.x` is reported as an error. Use `arazzo.Upgrade` (or `openapi arazzo upgrade`) to move a 1.0.x document to 1.1.0. The upgrade pins `jsonpath` and `xpath` criteria to the versions Arazzo 1.0 implied, so their meaning doesn't change. Where the Arazzo Specification text and its JSON Schema disagree, validation follows the specification text. +### AsyncAPI sources + +`LoadSourceDescriptions` loads AsyncAPI 3.0 and 3.1 sources with the [asyncapi](../asyncapi) package and resolves their references, using the same file system and HTTP client as OpenAPI sources. `ValidateSources` then checks AsyncAPI steps against them: + +- `operationId` must be a key of the root `operations` map. Operations in `components` are reusable definitions, not operations of the application, so they don't match. +- `channelPath` must be a JSON Pointer to a channel's key under `/channels` or `/components/channels`, for example `{$sourceDescriptions.events.url}#/channels/orderCreated`. A channel's `address` is not its key. +- `operationPath` can't target an AsyncAPI source, as Arazzo AsyncAPI steps use `operationId` or `channelPath`. +- Header parameters should be declared by the headers schema of one of the messages the step can send or receive (the operation's `messages`, or all messages of its channel), including headers added by message traits. Other parameter locations have no AsyncAPI meaning. Both are reported as warnings. +- A `receive` step with a `requestBody`, or with a `correlationId` when none of its messages declare one, is reported as a warning. + +Some things are deliberately not checked. A step's `action` isn't compared with the AsyncAPI operation's `action`, as the step describes the workflow's side of the exchange and the operation the application's, and Arazzo doesn't define how they relate. Correlation values, payloads, bindings and channel address parameters are runtime concerns. Checks that something isn't declared are skipped when a reference couldn't be resolved or a headers schema uses composition or a non JSON Schema format. + ### Migrating step and workflow outputs Arazzo 1.1 allows an output to be either a runtime expression or a Selector Object, so `arazzo.Outputs` is now a map of `*arazzo.OutputValue` instead of `expression.Expression`: diff --git a/arazzo/linter/rules/source_description_type_test.go b/arazzo/linter/rules/source_description_type_test.go index 065c5ef8..c64952c6 100644 --- a/arazzo/linter/rules/source_description_type_test.go +++ b/arazzo/linter/rules/source_description_type_test.go @@ -57,6 +57,26 @@ func TestSourceDescriptionTypeRule_LoadedSourceFix_Success(t *testing.T) { assert.Equal(t, arazzo.SourceDescriptionType(arazzo.SourceDescriptionTypeArazzo), a.SourceDescriptions[1].Type, "type should be set") } +func TestSourceDescriptionTypeRule_LoadedAsyncAPISourceFix_Success(t *testing.T) { + t.Parallel() + + a := parseDoc(t, sourcesDoc("1.1.0", untypedSources)) + sources, loadErrs := arazzo.LoadSourceDescriptions(t.Context(), a, arazzo.LoadSourcesOptions{ + VirtualFS: fstest.MapFS{ + "typed.yaml": {Data: []byte("openapi: 3.1.0\ninfo:\n title: Typed\n version: 1.0.0\n")}, + "untyped.yaml": {Data: []byte("asyncapi: 3.0.0\ninfo:\n title: Events\n version: 1.0.0\n")}, + }, + }) + require.Empty(t, loadErrs, "sources should load") + + fix := sourceTypeFix(t, a, sources) + assert.False(t, fix.Interactive(), "fix should not need input when the source was loaded") + assert.Equal(t, "Set the type of sourceDescription `untyped` to `asyncapi`", fix.Description(), "description should match") + + require.NoError(t, fix.Apply(a), "fix should apply") + assert.Equal(t, arazzo.SourceDescriptionType(arazzo.SourceDescriptionTypeAsyncAPI), a.SourceDescriptions[1].Type, "type should be set") +} + func TestSourceDescriptionTypeRule_InteractiveFix_Success(t *testing.T) { t.Parallel() diff --git a/arazzo/sources.go b/arazzo/sources.go index dccccf0b..983b0254 100644 --- a/arazzo/sources.go +++ b/arazzo/sources.go @@ -8,8 +8,10 @@ import ( "io" "net/http" "path/filepath" + "strings" "time" + "github.com/speakeasy-api/openapi/asyncapi" "github.com/speakeasy-api/openapi/internal/utils" "github.com/speakeasy-api/openapi/openapi" "github.com/speakeasy-api/openapi/system" @@ -45,6 +47,8 @@ type SourceDocument struct { OpenAPI *openapi.OpenAPI // Arazzo is the loaded document if it is an Arazzo document. Arazzo *Arazzo + // AsyncAPI is the loaded document if it is an AsyncAPI 3.x document, with its references resolved. + AsyncAPI *asyncapi.AsyncAPI } // SourceDocuments are the documents loaded for an Arazzo document's sourceDescriptions, keyed by source description name. @@ -60,12 +64,13 @@ func (s *SourceDocuments) Get(name string) *SourceDocument { return s.documents[name] } -// LoadSourceDescriptions loads the OpenAPI and Arazzo documents referenced by the Arazzo document's +// LoadSourceDescriptions loads the OpenAPI, AsyncAPI and Arazzo documents referenced by the Arazzo document's // sourceDescriptions so the document can be validated against them with ValidateSources. // // Problems loading a source are returned as warnings rather than errors, as a source may be temporarily -// unavailable without the Arazzo document being invalid. AsyncAPI sources are not loaded and are reported with -// a hint. A source description declaring a type that doesn't match the loaded document is reported as an error. +// unavailable without the Arazzo document being invalid. This includes AsyncAPI documents of a version the asyncapi +// package doesn't support, such as 2.x. A source description declaring a type that doesn't match the loaded document +// is reported as an error. func LoadSourceDescriptions(ctx context.Context, a *Arazzo, opts LoadSourcesOptions) (*SourceDocuments, []error) { sources := &SourceDocuments{documents: map[string]*SourceDocument{}} if a == nil { @@ -114,10 +119,6 @@ func loadSourceDescription(ctx context.Context, sd *SourceDescription, base stri return []error{validation.NewValueError(validation.SeverityWarning, validation.RuleValidationInvalidReference, err, core, core.URL)} } - if sd.Type == SourceDescriptionTypeAsyncAPI { - return nil, []error{asyncAPINotCheckedHint(sd)} - } - location, err := resolveSourceLocation(base, sd.URL) if err != nil { return nil, warn(fmt.Errorf("sourceDescription `%s` url can't be resolved: %w", sd.Name, err)) @@ -134,21 +135,26 @@ func loadSourceDescription(ctx context.Context, sd *SourceDescription, base stri return nil, warn(fmt.Errorf("sourceDescription `%s` at `%s` is not an OpenAPI 3.x, AsyncAPI or Arazzo document", sd.Name, location)) case sd.Type != "" && sd.Type != detected: return nil, []error{validation.NewValueError(validation.SeverityError, validation.RuleValidationTypeMismatch, fmt.Errorf("sourceDescription `%s` is declared as type `%s` but `%s` is an %s document", sd.Name, sd.Type, location, detected), core, core.Type)} - case detected == SourceDescriptionTypeAsyncAPI: - return nil, []error{asyncAPINotCheckedHint(sd)} } doc := &SourceDocument{Name: sd.Name, Location: location, Type: detected} - if detected == SourceDescriptionTypeArazzo { + switch detected { + case SourceDescriptionTypeArazzo: doc.Arazzo, _, err = Unmarshal(ctx, bytes.NewReader(data), WithSkipValidation()) - } else { + case SourceDescriptionTypeAsyncAPI: + doc.AsyncAPI, _, err = asyncapi.Unmarshal(ctx, bytes.NewReader(data), asyncapi.WithSkipValidation()) + default: doc.OpenAPI, _, err = openapi.Unmarshal(ctx, bytes.NewReader(data), openapi.WithSkipValidation()) } if err != nil { return nil, warn(fmt.Errorf("sourceDescription `%s` at `%s` could not be parsed: %w", sd.Name, location, err)) } - if doc.OpenAPI == nil { + + switch { + case doc.AsyncAPI != nil: + return loadAsyncAPISource(ctx, doc, opts, warn) + case doc.OpenAPI == nil: return doc, nil } @@ -173,9 +179,39 @@ func resolveSourceLocation(base, ref string) (string, error) { return utils.JoinReference(base, ref) } -func asyncAPINotCheckedHint(sd *SourceDescription) error { - core := sd.GetCore() - return validation.NewValueError(validation.SeverityHint, validation.RuleValidationInvalidReference, fmt.Errorf("sourceDescription `%s` is an AsyncAPI document, steps targeting it are not checked against the source", sd.Name), core, core.URL) +// loadAsyncAPISource checks the AsyncAPI version is supported and resolves the document's references. +func loadAsyncAPISource(ctx context.Context, doc *SourceDocument, opts LoadSourcesOptions, warn func(error) []error) (*SourceDocument, []error) { + if version := doc.AsyncAPI.GetAsyncAPI(); !asyncapi.IsSupportedVersion(version) { + return nil, warn(fmt.Errorf("sourceDescription `%s` is an AsyncAPI %s document, only AsyncAPI %s are supported so steps targeting it are not checked", doc.Name, version, strings.Join(asyncapi.SupportedMinorVersions(), " and "))) + } + + // Unresolved references only reduce how much can be checked, so the source is still usable. + resolveErrs, err := doc.AsyncAPI.ResolveAllReferences(ctx, asyncapi.ResolveAllOptions{ + AsyncAPILocation: doc.Location, + VirtualFS: opts.VirtualFS, + HTTPClient: opts.HTTPClient, + }) + if err == nil { + err = firstResolutionError(resolveErrs) + } + if err != nil { + return doc, warn(fmt.Errorf("sourceDescription `%s` has references that could not be resolved, some checks may be skipped: %w", doc.Name, err)) + } + + return doc, nil +} + +// firstResolutionError returns the first error from resolving an AsyncAPI document's references. Warnings and hints, +// such as schema formats that aren't validated, don't stop anything being checked so they are ignored. +func firstResolutionError(errs []error) error { + for _, err := range errs { + var vErr *validation.Error + if errors.As(err, &vErr) && vErr.Severity != validation.SeverityError { + continue + } + return err + } + return nil } func fetchSource(ctx context.Context, location string, opts LoadSourcesOptions) ([]byte, error) { diff --git a/arazzo/sources_test.go b/arazzo/sources_test.go index 74b70aa3..95b78ff1 100644 --- a/arazzo/sources_test.go +++ b/arazzo/sources_test.go @@ -22,6 +22,12 @@ info: paths: {} ` +const sourcesTestAsyncAPI = `asyncapi: 3.0.0 +info: + title: Events + version: 1.0.0 +` + // mockHTTPClient returns canned responses keyed by URL. type mockHTTPClient struct { responses map[string]string @@ -134,6 +140,21 @@ func TestLoadSourceDescriptions_Success(t *testing.T) { expectedLocation: "https://example.com/openapi.yaml", expectedType: arazzo.SourceDescriptionTypeOpenAPI, }, + { + name: "asyncapi 3.0 source detected from content", + url: "events.yaml", + files: fstest.MapFS{"events.yaml": {Data: []byte(sourcesTestAsyncAPI)}}, + expectedLocation: "events.yaml", + expectedType: arazzo.SourceDescriptionTypeAsyncAPI, + }, + { + name: "declared asyncapi 3.1 source over http", + sourceType: "asyncapi", + url: "https://example.com/events.yaml", + responses: map[string]string{"https://example.com/events.yaml": "asyncapi: 3.1.0\ninfo:\n title: Events\n version: 1.0.0\n"}, + expectedLocation: "https://example.com/events.yaml", + expectedType: arazzo.SourceDescriptionTypeAsyncAPI, + }, } for _, tt := range tests { @@ -155,6 +176,7 @@ func TestLoadSourceDescriptions_Success(t *testing.T) { assert.Equal(t, tt.expectedType, doc.Type, "type should match") assert.Equal(t, tt.expectedType == arazzo.SourceDescriptionTypeOpenAPI, doc.OpenAPI != nil, "OpenAPI document should be set for OpenAPI sources") assert.Equal(t, tt.expectedType == arazzo.SourceDescriptionTypeArazzo, doc.Arazzo != nil, "Arazzo document should be set for Arazzo sources") + assert.Equal(t, tt.expectedType == arazzo.SourceDescriptionTypeAsyncAPI, doc.AsyncAPI != nil, "AsyncAPI document should be set for AsyncAPI sources") }) } } @@ -221,16 +243,24 @@ func TestLoadSourceDescriptions_NotLoaded(t *testing.T) { }, }, { - name: "declared asyncapi source", + name: "unsupported asyncapi 2.x source", + url: "events.yaml", + files: fstest.MapFS{"events.yaml": {Data: []byte("asyncapi: 2.6.0\ninfo:\n title: Events\n version: 1.0.0\nchannels:\n orders:\n publish:\n message:\n payload:\n type: object\n")}}, + expected: []string{"warning: sourceDescription `api` is an AsyncAPI 2.6.0 document, only AsyncAPI 3.0 and 3.1 are supported so steps targeting it are not checked"}, + }, + { + name: "declared asyncapi source is an openapi document", sourceType: "asyncapi", - url: "asyncapi.yaml", - expected: []string{"hint: sourceDescription `api` is an AsyncAPI document, steps targeting it are not checked against the source"}, + url: "petstore.yaml", + files: fstest.MapFS{"petstore.yaml": {Data: []byte(sourcesTestOpenAPI)}}, + expected: []string{"error: sourceDescription `api` is declared as type `asyncapi` but `petstore.yaml` is an openapi document"}, }, { - name: "detected asyncapi source", - url: "events.yaml", - files: fstest.MapFS{"events.yaml": {Data: []byte("asyncapi: 3.0.0\n")}}, - expected: []string{"hint: sourceDescription `api` is an AsyncAPI document, steps targeting it are not checked against the source"}, + name: "declared openapi source is an asyncapi document", + sourceType: "openapi", + url: "events.yaml", + files: fstest.MapFS{"events.yaml": {Data: []byte(sourcesTestAsyncAPI)}}, + expected: []string{"error: sourceDescription `api` is declared as type `openapi` but `events.yaml` is an asyncapi document"}, }, { name: "unknown document", @@ -310,6 +340,49 @@ paths: assert.NotNil(t, sources.Get("api"), "source should still be loaded") } +func TestLoadSourceDescriptions_UnresolvedAsyncAPIReferences_Success(t *testing.T) { + t.Parallel() + + files := fstest.MapFS{"events.yaml": {Data: []byte(`asyncapi: 3.0.0 +info: + title: Events + version: 1.0.0 +channels: + orders: + $ref: "./missing.yaml#/channels/orders" +`)}} + + a := sourcesTestDoc(t, "", "asyncapi", "events.yaml") + sources, errs := arazzo.LoadSourceDescriptions(t.Context(), a, arazzo.LoadSourcesOptions{VirtualFS: files}) + require.Len(t, errs, 1, "should warn about the unresolved reference") + assert.Contains(t, severityMessages(errs)[0], "warning: sourceDescription `api` has references that could not be resolved, some checks may be skipped", "warning should match") + assert.NotNil(t, sources.Get("api").AsyncAPI, "source should still be loaded") +} + +func TestLoadSourceDescriptions_AsyncAPIResolutionWarnings_Success(t *testing.T) { + t.Parallel() + + // A reference to a Protobuf resource isn't resolved and is reported as a warning by the asyncapi package, it + // doesn't stop anything being checked. + files := fstest.MapFS{"events.yaml": {Data: []byte(`asyncapi: 3.0.0 +info: + title: Events + version: 1.0.0 +components: + messages: + Order: + payload: + schemaFormat: application/vnd.google.protobuf;version=3 + schema: + $ref: "./order.proto" +`)}} + + a := sourcesTestDoc(t, "", "asyncapi", "events.yaml") + sources, errs := arazzo.LoadSourceDescriptions(t.Context(), a, arazzo.LoadSourcesOptions{VirtualFS: files}) + assert.Empty(t, errs, "warnings from resolution shouldn't be reported") + assert.NotNil(t, sources.Get("api").AsyncAPI, "source should be loaded") +} + func TestLoadSourceDescriptions_SkipsIncompleteSourceDescriptions_Success(t *testing.T) { t.Parallel() diff --git a/arazzo/sourcevalidation.go b/arazzo/sourcevalidation.go index 666ddd04..61d6cb71 100644 --- a/arazzo/sourcevalidation.go +++ b/arazzo/sourcevalidation.go @@ -25,13 +25,19 @@ var ( // ValidateSources validates the Arazzo document against the documents loaded for its sourceDescriptions (see // LoadSourceDescriptions). It checks that: // -// - operationId, operationPath and workflowId targets exist in the referenced source +// - operationId, operationPath, channelPath and workflowId targets exist in the referenced source // - step parameters match a parameter of the target operation by name and location // - required operation parameters and required request bodies are supplied by the step // - parameters passed to a workflow in an Arazzo source match the workflow's inputs +// - AsyncAPI steps only send headers declared by the target's messages, and a correlationId is only used with +// messages that declare one // -// Sources that weren't loaded (unavailable, or AsyncAPI) are skipped. Problems that may still work at runtime, such -// as a header parameter the operation doesn't declare, are reported as warnings. +// AsyncAPI operations are found by their key in the root operations map and channels by a JSON Pointer to their key +// (not their address). An AsyncAPI step's action is not compared with the AsyncAPI operation's action, as they're +// written from different perspectives. +// +// Sources that weren't loaded (unavailable, or an unsupported AsyncAPI version) are skipped. Problems that may still +// work at runtime, such as a header parameter the operation doesn't declare, are reported as warnings. func (a *Arazzo) ValidateSources(ctx context.Context, sources *SourceDocuments) []error { if a == nil || sources == nil { return nil @@ -84,21 +90,23 @@ func (a *Arazzo) validateStepSources(sources *SourceDocuments, w *Workflow, s *S core := s.GetCore() errs := []error{} - if s.ChannelPath != nil { - _, name, _, _ := s.ChannelPath.GetParts() - // Sources declared as another type are reported by Validate, and AsyncAPI sources aren't loaded, so a loaded - // source with an omitted type is a channelPath into a document that isn't AsyncAPI. - doc := sources.Get(name) - if sd := a.SourceDescriptions.Find(name); sd != nil && sd.Type == "" && doc != nil { - errs = append(errs, validation.NewValueError(validation.SeverityError, validation.RuleValidationInvalidReference, fmt.Errorf("step.channelPath references sourceDescription `%s` which is an %s document, not an AsyncAPI document", name, doc.Type), core, core.ChannelPath)) - } - } - switch { case s.OperationID != nil: - errs = append(errs, a.validateOperationStep(sources, w, s, core.OperationID)...) + sd, doc := a.operationIDSourceDocument(sources, s) + switch { + case doc != nil && doc.AsyncAPI != nil: + errs = append(errs, a.validateAsyncStep(sources, s)...) + default: + // Validate reports action on sources declared as another type, an omitted type is only known once loaded. + if s.Action != nil && sd != nil && doc != nil && sd.Type == "" { + errs = append(errs, validation.NewValueError(validation.SeverityError, validation.RuleValidationInvalidReference, fmt.Errorf("step.action is only applicable to asyncapi steps, sourceDescription `%s` is an %s document", sd.Name, doc.Type), core, core.Action)) + } + errs = append(errs, a.validateOperationStep(sources, w, s, core.OperationID)...) + } case s.OperationPath != nil: errs = append(errs, a.validateOperationStep(sources, w, s, core.OperationPath)...) + case s.ChannelPath != nil: + errs = append(errs, a.validateAsyncStep(sources, s)...) case s.WorkflowID != nil: errs = append(errs, a.validateRemoteWorkflowTarget(sources, "step", s.WorkflowID, s.Parameters, core, core.Parameters, core.WorkflowID)...) } @@ -313,6 +321,9 @@ func (a *Arazzo) findTargetOperation(sources *SourceDocuments, s *Step) (*target if doc == nil { return nil, nil } + if doc.AsyncAPI != nil { + return nil, fmt.Errorf("step.operationPath can't reference AsyncAPI sourceDescription `%s`, use operationId or channelPath for AsyncAPI steps", matches[1]) + } if doc.OpenAPI == nil { return nil, fmt.Errorf("step.operationPath references sourceDescription `%s` which is an %s document, not an OpenAPI document", matches[1], doc.Type) } @@ -323,24 +334,15 @@ func (a *Arazzo) findTargetOperation(sources *SourceDocuments, s *Step) (*target return target, nil } - sd := s.operationSourceDescription(a) - if sd == nil { - return nil, nil - } - doc := sources.Get(sd.Name) - if doc == nil { + sd, doc := a.operationIDSourceDocument(sources, s) + if sd == nil || doc == nil { return nil, nil } if doc.OpenAPI == nil { return nil, fmt.Errorf("step.operationId references sourceDescription `%s` which is an %s document, not an OpenAPI document", sd.Name, doc.Type) } - operationID := s.OperationID.String() - if s.OperationID.IsExpression(expression.WithArazzo11Grammar()) { - _, _, parts, _ := s.OperationID.GetParts() - operationID = strings.Join(parts, ".") - } - + operationID := stepOperationID(s) target := findOperationByID(doc.OpenAPI, operationID) if target == nil { return nil, fmt.Errorf("step.operationId `%s` not found in sourceDescription `%s`", operationID, sd.Name) @@ -348,6 +350,25 @@ func (a *Arazzo) findTargetOperation(sources *SourceDocuments, s *Step) (*target return target, nil } +// operationIDSourceDocument returns the source description targeted by the step's operationId and its loaded +// document. The document is nil if the source description can't be determined or wasn't loaded. +func (a *Arazzo) operationIDSourceDocument(sources *SourceDocuments, s *Step) (*SourceDescription, *SourceDocument) { + sd := s.operationSourceDescription(a) + if sd == nil { + return nil, nil + } + return sd, sources.Get(sd.Name) +} + +// stepOperationID returns the operationId the step targets, without the `$sourceDescriptions..` prefix. +func stepOperationID(s *Step) string { + if s.OperationID.IsExpression(expression.WithArazzo11Grammar()) { + _, _, parts, _ := s.OperationID.GetParts() + return strings.Join(parts, ".") + } + return s.OperationID.String() +} + func findOperationByID(doc *openapi.OpenAPI, operationID string) *targetOperation { find := func(pathItem *openapi.PathItem) *targetOperation { if pathItem == nil { diff --git a/arazzo/sourcevalidation_asyncapi.go b/arazzo/sourcevalidation_asyncapi.go new file mode 100644 index 00000000..5c38793e --- /dev/null +++ b/arazzo/sourcevalidation_asyncapi.go @@ -0,0 +1,245 @@ +package arazzo + +import ( + "fmt" + "strings" + + "github.com/speakeasy-api/openapi/asyncapi" + "github.com/speakeasy-api/openapi/jsonpointer" + "github.com/speakeasy-api/openapi/validation" +) + +// asyncTarget is what an AsyncAPI step (operationId or channelPath) selects in an AsyncAPI source. +type asyncTarget struct { + // messages are the effective (traits applied) messages the step may send or receive. + messages []*asyncapi.Message + // complete is false if any reference needed to find the messages wasn't resolved, in which case messages are + // partial and checks that something is not declared are skipped. + complete bool + // headers are the lower cased header names declared by the messages. Only set if headersKnown is true. + headers map[string]bool + // headersKnown is false if a message's headers schema can't be reduced to a list of properties, for example + // because it uses composition or a non JSON Schema format. + headersKnown bool + // label identifies the target in messages. + label string +} + +// validateAsyncStep checks a step targeting an AsyncAPI source with operationId or channelPath against the source. +func (a *Arazzo) validateAsyncStep(sources *SourceDocuments, s *Step) []error { + core := s.GetCore() + + target, errs := a.findAsyncTarget(sources, s) + if target == nil { + return errs + } + + isReceive := s.Action != nil && *s.Action == StepActionReceive + + for i, parameter := range s.Parameters { + p := a.resolveParameter(parameter) + if p == nil || p.In == nil { + continue + } + + if *p.In != InHeader { + errs = append(errs, validation.NewSliceError(validation.SeverityWarning, validation.RuleValidationOperationParameters, fmt.Errorf("step.parameters `%s` in `%s` has no meaning for AsyncAPI %s, only `header` parameters are sent with messages", p.Name, *p.In, target.label), core, core.Parameters, i)) + continue + } + + if target.complete && target.headersKnown && !target.headers[strings.ToLower(p.Name)] { + errs = append(errs, validation.NewSliceError(validation.SeverityWarning, validation.RuleValidationOperationParameters, fmt.Errorf("step.parameters `%s` in `header` is not a header of any message of %s", p.Name, target.label), core, core.Parameters, i)) + } + } + + if s.RequestBody != nil && isReceive { + errs = append(errs, validation.NewValueError(validation.SeverityWarning, validation.RuleValidationOperationParameters, fmt.Errorf("step.requestBody is not sent by a step with action `receive` targeting %s", target.label), core, core.RequestBody)) + } + + if s.CorrelationID != nil && isReceive && target.complete && !anyMessageHasCorrelationID(target.messages) { + errs = append(errs, validation.NewValueError(validation.SeverityWarning, validation.RuleValidationInvalidReference, fmt.Errorf("step.correlationId is set but no message of %s declares a correlationId", target.label), core, core.CorrelationID)) + } + + return errs +} + +// findAsyncTarget finds what the step's operationId or channelPath selects in an AsyncAPI source. Returns a nil +// target if the source wasn't loaded, the target can't be determined (reported by structural validation) or the +// target is invalid, in which case the returned errors explain why. +func (a *Arazzo) findAsyncTarget(sources *SourceDocuments, s *Step) (*asyncTarget, []error) { + core := s.GetCore() + + if s.ChannelPath != nil { + matches := operationPathRegex.FindStringSubmatch(s.ChannelPath.String()) + if matches == nil { + return nil, nil + } + name, pointer := matches[1], matches[2] + + doc := sources.Get(name) + if doc == nil { + return nil, nil + } + if doc.AsyncAPI == nil { + // Sources declared as another type are reported by Validate. + if sd := a.SourceDescriptions.Find(name); sd != nil && sd.Type == "" { + return nil, []error{validation.NewValueError(validation.SeverityError, validation.RuleValidationInvalidReference, fmt.Errorf("step.channelPath references sourceDescription `%s` which is an %s document, not an AsyncAPI document", name, doc.Type), core, core.ChannelPath)} + } + return nil, nil + } + + referenced := findChannelByPath(doc.AsyncAPI, pointer) + if referenced == nil { + return nil, []error{validation.NewValueError(validation.SeverityError, validation.RuleValidationOperationNotFound, fmt.Errorf("step.channelPath `%s` doesn't reference a channel in sourceDescription `%s`", s.ChannelPath, name), core, core.ChannelPath)} + } + + target := newAsyncTarget(fmt.Sprintf("channel `%s` in sourceDescription `%s`", pointer, name)) + channel := referenced.GetObject() + if channel == nil { + target.complete = false + } else { + target.addChannelMessages(channel) + } + target.collectHeaders(doc.AsyncAPI) + return target, nil + } + + sd, doc := a.operationIDSourceDocument(sources, s) + if sd == nil || doc == nil || doc.AsyncAPI == nil { + return nil, nil + } + + errs := []error{} + // Validate requires action for sources declared as asyncapi, an omitted type is only known once loaded. + if s.Action == nil && sd.Type == "" { + errs = append(errs, validation.NewValueError(validation.SeverityError, validation.RuleValidationRequiredField, fmt.Errorf("step.action is required for asyncapi steps, operationId references sourceDescription `%s` which is an AsyncAPI document", sd.Name), core, core.OperationID)) + } + + // AsyncAPI identifies an application's operations by their key in the root operations map. Operations in + // components are reusable definitions, not operations of the application. + operationID := stepOperationID(s) + referenced, ok := doc.AsyncAPI.GetOperations().Get(operationID) + if !ok || referenced == nil { + return nil, append(errs, validation.NewValueError(validation.SeverityError, validation.RuleValidationOperationNotFound, fmt.Errorf("step.operationId `%s` not found in sourceDescription `%s`", operationID, sd.Name), core, core.OperationID)) + } + + target := newAsyncTarget(fmt.Sprintf("operation `%s` in sourceDescription `%s`", operationID, sd.Name)) + operation := referenced.GetObject() + if operation == nil { + target.complete = false + } else { + target.addOperationMessages(operation) + } + target.collectHeaders(doc.AsyncAPI) + + return target, errs +} + +func newAsyncTarget(label string) *asyncTarget { + return &asyncTarget{complete: true, headers: map[string]bool{}, headersKnown: true, label: label} +} + +// addOperationMessages adds the operation's messages, or all the messages of its channel if it omits `messages`. An +// explicitly empty `messages` list means the operation supports no messages. +func (t *asyncTarget) addOperationMessages(operation *asyncapi.Operation) { + if refs := operation.GetMessages(); refs != nil { + for _, ref := range refs { + t.addMessage(ref.GetMessage()) + } + return + } + + channel := operation.GetChannel().GetChannel() + if channel == nil { + t.complete = false + return + } + t.addChannelMessages(channel) +} + +func (t *asyncTarget) addChannelMessages(channel *asyncapi.Channel) { + for _, referenced := range channel.GetMessages().All() { + t.addMessage(referenced.GetObject()) + } +} + +func (t *asyncTarget) addMessage(message *asyncapi.Message) { + if message == nil { + t.complete = false + return + } + t.messages = append(t.messages, message.GetEffective()) +} + +func (t *asyncTarget) collectHeaders(doc *asyncapi.AsyncAPI) { + for _, message := range t.messages { + names, ok := messageHeaderNames(doc, message) + if !ok { + t.headersKnown = false + continue + } + for name := range names { + t.headers[name] = true + } + } +} + +// messageHeaderNames returns the lower cased names of the headers declared by the message's headers schema. ok is +// false if the schema can't be reduced to a list of properties. +func messageHeaderNames(doc *asyncapi.AsyncAPI, message *asyncapi.Message) (names map[string]bool, ok bool) { + names = map[string]bool{} + + union := message.GetHeaders() + if union == nil { + return names, true + } + if resolved := doc.GetResolvedSchema(union); resolved != nil { + union = resolved.Schema + } + + schema := union.GetSchema() + if schema == nil { + schema = union.GetMultiFormat().GetSchema().GetSchema() + } + + s := schema.GetSchema() + if s == nil || s.Ref != nil || s.Properties == nil || len(s.AllOf) > 0 || len(s.AnyOf) > 0 || len(s.OneOf) > 0 || s.If != nil || s.PatternProperties.Len() > 0 { + return nil, false + } + + for name := range s.Properties.Keys() { + names[strings.ToLower(name)] = true + } + return names, true +} + +func anyMessageHasCorrelationID(messages []*asyncapi.Message) bool { + for _, message := range messages { + if message.GetCorrelationID() != nil { + return true + } + } + return false +} + +// findChannelByPath finds the channel referenced by a JSON Pointer such as `/channels/userSignedUp` or +// `/components/channels/userSignedUp`. Channels are found by their key, not their address. +func findChannelByPath(doc *asyncapi.AsyncAPI, pointer string) *asyncapi.ReferencedChannel { + if !strings.HasPrefix(pointer, "/") { + return nil + } + + tokens := strings.Split(pointer[1:], "/") + for i, token := range tokens { + tokens[i] = jsonpointer.UnescapeString(token) + } + + var channel *asyncapi.ReferencedChannel + switch { + case len(tokens) == 2 && tokens[0] == "channels": + channel, _ = doc.GetChannels().Get(tokens[1]) + case len(tokens) == 3 && tokens[0] == "components" && tokens[1] == "channels": + channel, _ = doc.GetComponents().GetChannels().Get(tokens[2]) + } + return channel +} diff --git a/arazzo/sourcevalidation_asyncapi_test.go b/arazzo/sourcevalidation_asyncapi_test.go new file mode 100644 index 00000000..312ee30e --- /dev/null +++ b/arazzo/sourcevalidation_asyncapi_test.go @@ -0,0 +1,252 @@ +package arazzo_test + +import ( + "bytes" + "testing" + "testing/fstest" + + "github.com/speakeasy-api/openapi/arazzo" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestArazzo_ValidateSources_AsyncAPI_Success(t *testing.T) { + t.Parallel() + + assert.Empty(t, validateSourcesFixture(t, "testdata/sources/async-valid.arazzo.yaml"), "mixed OpenAPI and AsyncAPI workflow should be valid against its sources") +} + +func TestArazzo_ValidateSources_AsyncAPI_Error(t *testing.T) { + t.Parallel() + + expected := []string{ + "error: step.operationId `missing` not found in sourceDescription `orders`", + "error: step.operationId `reusableSend` not found in sourceDescription `orders`", + "error: step.channelPath `{$sourceDescriptions.orders.url}#/channels/orders.confirmed` doesn't reference a channel in sourceDescription `orders`", + "error: step.channelPath `{$sourceDescriptions.orders.url}#/operations/placeOrder` doesn't reference a channel in sourceDescription `orders`", + "error: step.operationPath can't reference AsyncAPI sourceDescription `orders`, use operationId or channelPath for AsyncAPI steps", + "error: step.action is required for asyncapi steps, operationId references sourceDescription `untypedOrders` which is an AsyncAPI document", + "warning: step.parameters `unknownHeader` in `header` is not a header of any message of operation `placeOrder` in sourceDescription `orders`", + "warning: step.parameters `orderId` in `path` has no meaning for AsyncAPI operation `placeOrder` in sourceDescription `orders`, only `header` parameters are sent with messages", + "warning: step.requestBody is not sent by a step with action `receive` targeting operation `confirmOrder` in sourceDescription `orders`", + "warning: step.correlationId is set but no message of channel `/components/channels/orderStatus` in sourceDescription `orders` declares a correlationId", + "warning: step.parameters `requestId` in `header` is not a header of any message of operation `noMessages` in sourceDescription `orders`", + "error: step.action is only applicable to asyncapi steps, sourceDescription `untypedPetstore` is an openapi document", + } + + assert.Equal(t, expected, validateSourcesFixture(t, "testdata/sources/async-invalid.arazzo.yaml"), "source validation errors should match") +} + +const asyncAPIPartialSource = `asyncapi: 3.1.0 +info: + title: Partial + version: 1.0.0 +channels: + events: + address: events + messages: + known: + payload: + type: object + missing: + $ref: "./missing.yaml#/components/messages/Missing" +operations: + listen: + action: receive + channel: + $ref: "#/channels/events" + unresolvedOperation: + $ref: "./missing.yaml#/operations/listen" +` + +const asyncAPIEdgeCasesSource = `asyncapi: 3.1.0 +info: + title: Edge cases + version: 1.0.0 +channels: + refHeaders: + address: ref + messages: + withRefHeaders: + headers: + $ref: "#/components/schemas/Headers" + multiFormatHeaders: + address: multi + messages: + withMultiFormatHeaders: + headers: + schemaFormat: application/schema+json;version=draft-07 + schema: + type: object + properties: + traceId: + type: string + unresolvedChannel: + $ref: "./missing.yaml#/channels/unresolved" +operations: + danglingChannel: + action: send + channel: + $ref: "./missing.yaml#/channels/unresolved" +components: + schemas: + Headers: + type: object + properties: + traceId: + type: string +` + +const asyncAPIEdgeCasesOpenAPI = `openapi: 3.1.0 +info: + title: Petstore + version: 1.0.0 +paths: {} +` + +func TestArazzo_ValidateSources_AsyncAPIEdgeCases_Success(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + step string + expected []string + }{ + { + name: "parameter without a location is skipped", + step: "channelPath: \"{$sourceDescriptions.events.url}#/channels/refHeaders\"\n parameters:\n - name: anything\n value: abc", + expected: []string{}, + }, + { + name: "malformed channelPath is left to structural validation", + step: "channelPath: not-a-path", + expected: []string{}, + }, + { + name: "channelPath to an unknown source is left to structural validation", + step: "channelPath: \"{$sourceDescriptions.unknown.url}#/channels/refHeaders\"", + expected: []string{}, + }, + { + name: "channelPath to a source declared as another type is left to Validate", + step: "channelPath: \"{$sourceDescriptions.petstore.url}#/channels/refHeaders\"", + expected: []string{}, + }, + { + name: "channelPath pointer without a leading slash", + step: "channelPath: \"{$sourceDescriptions.events.url}#channels/refHeaders\"", + expected: []string{"error: step.channelPath `{$sourceDescriptions.events.url}#channels/refHeaders` doesn't reference a channel in sourceDescription `events`"}, + }, + { + name: "unresolved channel skips undeclared header checks", + step: "channelPath: \"{$sourceDescriptions.events.url}#/channels/unresolvedChannel\"\n parameters:\n - name: undeclared\n in: header\n value: abc", + expected: []string{}, + }, + { + name: "operation with an unresolved channel skips undeclared header checks", + step: "operationId: $sourceDescriptions.events.danglingChannel\n parameters:\n - name: undeclared\n in: header\n value: abc", + expected: []string{}, + }, + { + name: "headers schema from a reference", + step: "channelPath: \"{$sourceDescriptions.events.url}#/channels/refHeaders\"\n parameters:\n - name: TraceId\n in: header\n value: abc\n - name: undeclared\n in: header\n value: abc", + expected: []string{"warning: step.parameters `undeclared` in `header` is not a header of any message of channel `/channels/refHeaders` in sourceDescription `events`"}, + }, + { + name: "headers schema in a multi-format schema", + step: "channelPath: \"{$sourceDescriptions.events.url}#/channels/multiFormatHeaders\"\n parameters:\n - name: traceId\n in: header\n value: abc\n - name: undeclared\n in: header\n value: abc", + expected: []string{"warning: step.parameters `undeclared` in `header` is not a header of any message of channel `/channels/multiFormatHeaders` in sourceDescription `events`"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ctx := t.Context() + + doc := `arazzo: 1.1.0 +info: + title: Edge cases + version: 1.0.0 +sourceDescriptions: + - name: events + url: events.yaml + type: asyncapi + - name: petstore + url: petstore.yaml + type: openapi +workflows: + - workflowId: main + steps: + - stepId: step + action: send + ` + tt.step + ` +` + a, _, err := arazzo.Unmarshal(ctx, bytes.NewBufferString(doc), arazzo.WithSkipValidation()) + require.NoError(t, err, "unmarshal should succeed") + + sources, loadErrs := arazzo.LoadSourceDescriptions(ctx, a, arazzo.LoadSourcesOptions{ + VirtualFS: fstest.MapFS{ + "events.yaml": {Data: []byte(asyncAPIEdgeCasesSource)}, + "petstore.yaml": {Data: []byte(asyncAPIEdgeCasesOpenAPI)}, + }, + }) + require.Len(t, loadErrs, 1, "should warn that the AsyncAPI source has unresolved references") + assert.Contains(t, severityMessages(loadErrs)[0], "warning: sourceDescription `events` has references that could not be resolved, some checks may be skipped", "load warning should match") + require.NotNil(t, sources.Get("events"), "AsyncAPI source should be loaded") + + assert.Equal(t, tt.expected, severityMessages(a.ValidateSources(ctx, sources)), "source validation messages should match") + }) + } +} + +func TestArazzo_ValidateSources_AsyncAPIPartialTarget_Success(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + target string + }{ + {name: "operation with an unresolved message", target: "operationId: $sourceDescriptions.events.listen"}, + {name: "unresolved operation", target: "operationId: $sourceDescriptions.events.unresolvedOperation"}, + {name: "channel with an unresolved message", target: "channelPath: \"{$sourceDescriptions.events.url}#/channels/events\""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + ctx := t.Context() + + doc := `arazzo: 1.1.0 +info: + title: Partial + version: 1.0.0 +sourceDescriptions: + - name: events + url: events.yaml + type: asyncapi +workflows: + - workflowId: main + steps: + - stepId: listen + ` + tt.target + ` + action: receive + correlationId: abc + parameters: + - name: anything + in: header + value: abc +` + a, _, err := arazzo.Unmarshal(ctx, bytes.NewBufferString(doc), arazzo.WithSkipValidation()) + require.NoError(t, err, "unmarshal should succeed") + + sources, loadErrs := arazzo.LoadSourceDescriptions(ctx, a, arazzo.LoadSourcesOptions{ + VirtualFS: fstest.MapFS{"events.yaml": {Data: []byte(asyncAPIPartialSource)}}, + }) + require.Len(t, loadErrs, 1, "should warn about the unresolved references") + require.NotNil(t, sources.Get("events"), "source should still be loaded") + + assert.Empty(t, a.ValidateSources(ctx, sources), "undeclared headers and correlation IDs shouldn't be reported for partial targets") + }) + } +} diff --git a/arazzo/testdata/sources/async-invalid.arazzo.yaml b/arazzo/testdata/sources/async-invalid.arazzo.yaml new file mode 100644 index 00000000..03215403 --- /dev/null +++ b/arazzo/testdata/sources/async-invalid.arazzo.yaml @@ -0,0 +1,67 @@ +arazzo: 1.1.0 +info: + title: Invalid AsyncAPI targets + version: 1.0.0 +sourceDescriptions: + - name: orders + url: ./orders.asyncapi.yaml + type: asyncapi + - name: untypedOrders + url: ./orders.asyncapi.yaml + - name: untypedPetstore + url: ./petstore.openapi.yaml +workflows: + - workflowId: main + inputs: + type: object + properties: + correlationId: + type: string + steps: + - stepId: missingOperation + operationId: $sourceDescriptions.orders.missing + action: send + - stepId: componentOperation + operationId: $sourceDescriptions.orders.reusableSend + action: send + - stepId: channelByAddress + channelPath: "{$sourceDescriptions.orders.url}#/channels/orders.confirmed" + action: receive + - stepId: notAChannel + channelPath: "{$sourceDescriptions.orders.url}#/operations/placeOrder" + action: receive + - stepId: operationPathIntoAsyncAPI + operationPath: "{$sourceDescriptions.orders.url}#/operations/placeOrder" + - stepId: untypedWithoutAction + operationId: $sourceDescriptions.untypedOrders.placeOrder + - stepId: undeclaredParameters + operationId: $sourceDescriptions.orders.placeOrder + action: send + parameters: + - name: unknownHeader + in: header + value: abc + - name: orderId + in: path + value: "1" + - stepId: receiveWithBody + operationId: $sourceDescriptions.orders.confirmOrder + action: receive + requestBody: + payload: + orderId: "1" + - stepId: correlationWithoutDeclaration + channelPath: "{$sourceDescriptions.orders.url}#/components/channels/orderStatus" + action: receive + correlationId: $inputs.correlationId + # An explicitly empty messages list doesn't fall back to the channel's messages, which declare requestId. + - stepId: operationWithoutMessages + operationId: $sourceDescriptions.orders.noMessages + action: send + parameters: + - name: requestId + in: header + value: abc + - stepId: actionOnOpenAPI + operationId: $sourceDescriptions.untypedPetstore.listPets + action: send diff --git a/arazzo/testdata/sources/async-valid.arazzo.yaml b/arazzo/testdata/sources/async-valid.arazzo.yaml new file mode 100644 index 00000000..a0c3c45e --- /dev/null +++ b/arazzo/testdata/sources/async-valid.arazzo.yaml @@ -0,0 +1,80 @@ +arazzo: 1.1.0 +info: + title: Mixed OpenAPI and AsyncAPI workflow + version: 1.0.0 +sourceDescriptions: + - name: petstore + url: ./petstore.openapi.yaml + type: openapi + - name: asyncOrderApi + url: ./orders.asyncapi.yaml + type: asyncapi +workflows: + - workflowId: orderPet + inputs: + type: object + properties: + correlationId: + type: string + productDetails: + type: object + properties: + productId: + type: string + quantity: + type: integer + steps: + - stepId: list + operationId: $sourceDescriptions.petstore.listPets + parameters: + - name: limit + in: query + value: 10 + # The async step example from the Arazzo 1.1 specification. + - stepId: placeOrder + description: This step demonstrates the action of sending a message payload to place an order + operationId: $sourceDescriptions.asyncOrderApi.placeOrder + action: send + parameters: + - name: requestId + in: header + value: $inputs.correlationId + requestBody: + payload: + productId: $inputs.productDetails.productId + quantity: $inputs.productDetails.quantity + - stepId: confirmOrder + description: This step demonstrates the action of receiving a message payload to confirm an order + operationId: $sourceDescriptions.asyncOrderApi.confirmOrder + correlationId: $inputs.correlationId + action: receive + dependsOn: + - placeOrder + timeout: 6000 + parameters: + # Declared by a trait of a message in another file, matched case-insensitively. + - name: CorrelationId + in: header + value: $inputs.correlationId + outputs: + # The specification's example uses `$message.payload.orderId`, which its expression grammar doesn't allow. + orderId: $message.payload#/orderId + - stepId: watchStatus + channelPath: "{$sourceDescriptions.asyncOrderApi.url}#/components/channels/orderStatus" + action: receive + - stepId: legacyOrder + channelPath: "{$sourceDescriptions.asyncOrderApi.url}#/channels/orders~1legacy" + action: send + # Headers using composition can't be checked, so any header is accepted. + - stepId: audit + channelPath: "{$sourceDescriptions.asyncOrderApi.url}#/channels/audit" + action: send + parameters: + - name: anything + in: header + value: abc + # The step action is written from the workflow's perspective and the AsyncAPI operation action from the + # application's, so differing actions are not reported. + - stepId: confirmFromWorkflowSide + operationId: $sourceDescriptions.asyncOrderApi.confirmOrder + action: send diff --git a/arazzo/testdata/sources/orders.asyncapi.yaml b/arazzo/testdata/sources/orders.asyncapi.yaml new file mode 100644 index 00000000..17878615 --- /dev/null +++ b/arazzo/testdata/sources/orders.asyncapi.yaml @@ -0,0 +1,79 @@ +asyncapi: 3.0.0 +info: + title: Orders + version: 1.0.0 +channels: + orderRequests: + address: orders/{orderId}/requests + parameters: + orderId: + description: The order ID. + messages: + placeOrder: + $ref: "#/components/messages/PlaceOrder" + orderConfirmations: + address: orders.confirmed + messages: + orderConfirmed: + $ref: "./orders.messages.yaml#/components/messages/OrderConfirmed" + orders/legacy: + address: legacy.orders + messages: + legacyOrder: + payload: + type: object + audit: + address: audit + messages: + auditEvent: + headers: + allOf: + - type: object + properties: + source: + type: string + payload: + type: object +operations: + placeOrder: + action: send + channel: + $ref: "#/channels/orderRequests" + messages: + - $ref: "#/channels/orderRequests/messages/placeOrder" + confirmOrder: + action: receive + channel: + $ref: "#/channels/orderConfirmations" + noMessages: + action: send + channel: + $ref: "#/channels/orderRequests" + messages: [] +components: + channels: + orderStatus: + address: orders.status + messages: + status: + payload: + type: object + operations: + reusableSend: + action: send + channel: + $ref: "#/channels/orderRequests" + messages: + PlaceOrder: + headers: + type: object + properties: + requestId: + type: string + payload: + type: object + properties: + productId: + type: string + quantity: + type: integer diff --git a/arazzo/testdata/sources/orders.messages.yaml b/arazzo/testdata/sources/orders.messages.yaml new file mode 100644 index 00000000..7459a0b8 --- /dev/null +++ b/arazzo/testdata/sources/orders.messages.yaml @@ -0,0 +1,19 @@ +components: + messages: + OrderConfirmed: + payload: + type: object + properties: + orderId: + type: string + correlationId: + location: $message.header#/correlationId + traits: + - $ref: "#/components/messageTraits/Correlated" + messageTraits: + Correlated: + headers: + type: object + properties: + correlationId: + type: string diff --git a/asyncapi/README.md b/asyncapi/README.md index e4df9168..f4c0855c 100644 --- a/asyncapi/README.md +++ b/asyncapi/README.md @@ -2,7 +2,9 @@

An API for working with AsyncAPI 3.x documents including: read, walk, create, mutate, resolve and validate.

> [!NOTE] -> This package is under active development. Its API may still change before it's listed as a supported specification in the repository README. +> This package is new, so its API may still change in minor releases. + +To validate a document from the command line, use [`openapi asyncapi validate`](../cmd/openapi/commands/asyncapi/README.md). ## Supported versions diff --git a/asyncapi/resolve.go b/asyncapi/resolve.go index 6bbea25f..f3d89fd2 100644 --- a/asyncapi/resolve.go +++ b/asyncapi/resolve.go @@ -29,12 +29,18 @@ import ( // each piece of state is written once per call, so contention is negligible, and models stay safe to copy. var resolutionMu sync.RWMutex +// ErrExternalReferencesDisabled is wrapped by the diagnostics reported for references to other documents when +// ResolveAllOptions.DisableExternalRefs is set, so callers can tell references that weren't followed apart from +// broken ones with errors.Is. +var ErrExternalReferencesDisabled = errors.New("external references are disabled") + // ResolveAllOptions are the options available when resolving all references in an AsyncAPI document. type ResolveAllOptions struct { // AsyncAPILocation is the absolute file path or URL of the document. Relative references to other documents are // resolved against it. Without it, only references within the document and absolute references can be resolved. AsyncAPILocation string - // DisableExternalRefs reports references to other documents as errors instead of loading them. + // DisableExternalRefs reports references to other documents as errors instead of loading them. The errors wrap + // ErrExternalReferencesDisabled. DisableExternalRefs bool // VirtualFS is used for file based references. If not provided the local file system is used. VirtualFS system.VirtualFS @@ -537,7 +543,7 @@ func (rc *resolveCall) checkAccess(ref references.Reference, base location) erro return nil } if rc.opts.DisableExternalRefs { - return fmt.Errorf("reference `%s` is to another document and external references are disabled", ref) + return fmt.Errorf("reference `%s` is to another document and %w", ref, ErrExternalReferencesDisabled) } if base.uri == "" && !isAbsoluteLocation(uri) { return fmt.Errorf("relative reference `%s` can't be resolved because the document's location is unknown, set ResolveAllOptions.AsyncAPILocation", ref) diff --git a/asyncapi/resolve_test.go b/asyncapi/resolve_test.go index ca659648..4fdfc991 100644 --- a/asyncapi/resolve_test.go +++ b/asyncapi/resolve_test.go @@ -590,7 +590,10 @@ func TestResolveAllReferences_NoImplicitIO_Success(t *testing.T) { errs, err := a.ResolveAllReferences(t.Context(), asyncapi.ResolveAllOptions{AsyncAPILocation: "api.yaml", DisableExternalRefs: true, VirtualFS: files, HTTPClient: client}) require.NoError(t, err, "resolution should not fail") - assert.Len(t, errs, 2, "disabled external references should be reported") + require.Len(t, errs, 2, "disabled external references should be reported") + for _, e := range errs { + require.ErrorIs(t, e, asyncapi.ErrExternalReferencesDisabled, "disabled references should be identifiable") + } assert.Zero(t, files.opened.Load(), "no files should be read before resolution is allowed") assert.Zero(t, client.requests.Load(), "no requests should be made before resolution is allowed") diff --git a/asyncapi/testdata/validate/broken-ref.asyncapi.yaml b/asyncapi/testdata/validate/broken-ref.asyncapi.yaml new file mode 100644 index 00000000..456930f5 --- /dev/null +++ b/asyncapi/testdata/validate/broken-ref.asyncapi.yaml @@ -0,0 +1,10 @@ +asyncapi: 3.0.0 +info: + title: Orders + version: 1.0.0 +channels: + orders: + address: orders + messages: + orderPlaced: + $ref: "./messages.yaml#/components/messages/Missing" diff --git a/asyncapi/testdata/validate/invalid.asyncapi.yaml b/asyncapi/testdata/validate/invalid.asyncapi.yaml new file mode 100644 index 00000000..1140ee73 --- /dev/null +++ b/asyncapi/testdata/validate/invalid.asyncapi.yaml @@ -0,0 +1,11 @@ +asyncapi: 3.0.0 +info: + title: Orders +channels: + orders: + address: orders +operations: + placeOrder: + action: publish + channel: + $ref: "#/channels/missing" diff --git a/asyncapi/testdata/validate/messages.yaml b/asyncapi/testdata/validate/messages.yaml new file mode 100644 index 00000000..85b71a93 --- /dev/null +++ b/asyncapi/testdata/validate/messages.yaml @@ -0,0 +1,8 @@ +components: + messages: + OrderPlaced: + payload: + type: object + properties: + orderId: + type: string diff --git a/asyncapi/testdata/validate/orders.asyncapi.yaml b/asyncapi/testdata/validate/orders.asyncapi.yaml new file mode 100644 index 00000000..220a5f0b --- /dev/null +++ b/asyncapi/testdata/validate/orders.asyncapi.yaml @@ -0,0 +1,17 @@ +asyncapi: 3.0.0 +info: + title: Orders + version: 1.0.0 +channels: + orders: + address: orders + messages: + orderPlaced: + $ref: "./messages.yaml#/components/messages/OrderPlaced" +operations: + placeOrder: + action: send + channel: + $ref: "#/channels/orders" + messages: + - $ref: "#/channels/orders/messages/orderPlaced" diff --git a/asyncapi/testdata/validate/v2.asyncapi.yaml b/asyncapi/testdata/validate/v2.asyncapi.yaml new file mode 100644 index 00000000..1f987c81 --- /dev/null +++ b/asyncapi/testdata/validate/v2.asyncapi.yaml @@ -0,0 +1,10 @@ +asyncapi: 2.6.0 +info: + title: Orders + version: 1.0.0 +channels: + orders: + publish: + message: + payload: + type: object diff --git a/cmd/openapi/commands/arazzo/README.md b/cmd/openapi/commands/arazzo/README.md index ac21a570..34bdcf3d 100644 --- a/cmd/openapi/commands/arazzo/README.md +++ b/cmd/openapi/commands/arazzo/README.md @@ -48,14 +48,15 @@ This command checks for: - Source description references and validity - Step success and failure action definitions -By default the OpenAPI and Arazzo documents referenced by `sourceDescriptions` are also loaded, and the workflows are checked against them: +By default the OpenAPI, AsyncAPI and Arazzo documents referenced by `sourceDescriptions` are also loaded, and the workflows are checked against them: -- `operationId`, `operationPath` and `workflowId` targets (including `dependsOn` entries) exist +- `operationId`, `operationPath`, `channelPath` and `workflowId` targets (including `dependsOn` entries) exist - Step parameters match the target operation's parameters by name and location - Required parameters and request bodies are supplied - Parameters passed to workflows in other Arazzo documents match their inputs +- AsyncAPI steps only send headers declared by the target's messages, and use `correlationId` with messages that declare one (warnings) -Relative source URLs are resolved against the document's `$self`, or its file location. A source that can't be loaded is reported as a warning, and AsyncAPI sources are reported with a hint and not checked. Only errors make validation fail. +Relative source URLs are resolved against the document's `$self`, or its file location. A source that can't be loaded is reported as a warning, as are AsyncAPI 2.x sources, which aren't supported. Only errors make validation fail. See the [arazzo package README](../../../../arazzo/README.md#asyncapi-sources) for exactly what is checked for AsyncAPI sources. | Flag | Description | | ---------------- | ------------------------------------------------------------------------------------------------------ | diff --git a/cmd/openapi/commands/arazzo/explore_test.go b/cmd/openapi/commands/arazzo/explore_test.go index 53d38cab..2efb9caa 100644 --- a/cmd/openapi/commands/arazzo/explore_test.go +++ b/cmd/openapi/commands/arazzo/explore_test.go @@ -56,10 +56,10 @@ workflows: expectedView: []string{"adoptPet", "findPet", "registerOwner", "Pet adoption v1.0.0 · Arazzo 1.1.0 · 2 workflows"}, }, { - name: "stdin", - inputFile: "-", - stdin: stdinDoc, - expectedView: []string{"piped", "only", "Arazzo vunknown · Arazzo 1.1.0 · 1 workflows"}, + name: "stdin", + inputFile: "-", + stdin: stdinDoc, + expectedView: []string{"piped", "only", "Arazzo vunknown · Arazzo 1.1.0 · 1 workflows"}, expectedStderr: "Note: reading document from stdin; interactive TUI requires /dev/tty for keyboard input.\n" + "⚠️ Found 2 validation errors in document:\n" + " 1. [3:10] error validation-required-field `info.title` is required\n" + diff --git a/cmd/openapi/commands/arazzo/lint_test.go b/cmd/openapi/commands/arazzo/lint_test.go index 7fac991d..5191263b 100644 --- a/cmd/openapi/commands/arazzo/lint_test.go +++ b/cmd/openapi/commands/arazzo/lint_test.go @@ -75,9 +75,9 @@ func TestLintArazzo_Success(t *testing.T) { expectedStdout: []string{`"results"`}, }, { - name: "stdin", - file: "-", - stdin: `arazzo: 1.1.0 + name: "stdin", + file: "-", + stdin: `arazzo: 1.1.0 info: title: Stdin description: Read from stdin. diff --git a/cmd/openapi/commands/arazzo/validate.go b/cmd/openapi/commands/arazzo/validate.go index 752ff552..92fde98d 100644 --- a/cmd/openapi/commands/arazzo/validate.go +++ b/cmd/openapi/commands/arazzo/validate.go @@ -28,16 +28,18 @@ This command will parse and validate the provided Arazzo document, checking for: expressions reference steps, outputs and inputs that exist - Source description references -By default the OpenAPI and Arazzo documents referenced by sourceDescriptions are -loaded (relative URLs are resolved against $self, or the document's location) and -the workflows are checked against them: -- operationId, operationPath and workflowId targets exist +By default the OpenAPI, AsyncAPI and Arazzo documents referenced by +sourceDescriptions are loaded (relative URLs are resolved against $self, or the +document's location) and the workflows are checked against them: +- operationId, operationPath, channelPath and workflowId targets exist - step parameters match the target operation's parameters by name and location - required parameters and request bodies are supplied - parameters passed to workflows match their inputs +- AsyncAPI step header parameters are checked against the headers their + messages declare (warning) -Sources that can't be loaded are reported as warnings, and AsyncAPI sources are -not checked. Use --skip-sources to only validate the document itself, for example +Sources that can't be loaded, including AsyncAPI 2.x sources, are reported as +warnings. Use --skip-sources to only validate the document itself, for example when working offline. Only errors cause validation to fail. Stdin is supported — either pipe data directly or use '-' explicitly: diff --git a/cmd/openapi/commands/arazzo/validate_test.go b/cmd/openapi/commands/arazzo/validate_test.go index bd082fc8..32f7447b 100644 --- a/cmd/openapi/commands/arazzo/validate_test.go +++ b/cmd/openapi/commands/arazzo/validate_test.go @@ -49,10 +49,10 @@ func TestValidateArazzo_Success(t *testing.T) { expectedStderr: []string{"✅ Arazzo document is valid - 0 errors\n"}, }, { - name: "hints don't fail validation", + name: "warnings don't fail validation", file: "-", stdin: validateAsyncAPISourceInput, - expectedStderr: []string{"Validating Arazzo document from stdin", "✅ Arazzo document is valid - 0 errors, 1 warnings or hints:", "1. [7:10] hint validation-invalid-reference sourceDescription `events` is an AsyncAPI document"}, + expectedStderr: []string{"Validating Arazzo document from stdin", "✅ Arazzo document is valid - 0 errors, 1 warnings or hints:", "1. [7:10] warning validation-invalid-reference sourceDescription `events` could not be loaded from `./events.yaml`"}, }, } diff --git a/cmd/openapi/commands/asyncapi/README.md b/cmd/openapi/commands/asyncapi/README.md new file mode 100644 index 00000000..f6ba06a6 --- /dev/null +++ b/cmd/openapi/commands/asyncapi/README.md @@ -0,0 +1,83 @@ +# AsyncAPI Commands + +Commands for working with AsyncAPI documents. + +AsyncAPI documents describe message-driven APIs: the channels an application uses, the operations it performs on them and the messages it sends and receives. These commands work with documents written to the [AsyncAPI Specification](https://www.asyncapi.com/docs/reference/specification/latest) 3.0.x and 3.1.x, using the [asyncapi](../../../../asyncapi) package. + +## Table of Contents + +- [Table of Contents](#table-of-contents) +- [Available Commands](#available-commands) + - [`validate`](#validate) +- [What is and isn't checked](#what-is-and-isnt-checked) +- [Exit status](#exit-status) + +## Available Commands + +### `validate` + +Validate an AsyncAPI document for compliance with the AsyncAPI Specification. + +```bash +# Validate a document without reading anything outside it +openapi asyncapi validate ./asyncapi.yaml + +# Also load and validate the files and URLs the document references +openapi asyncapi validate --resolve ./asyncapi.yaml + +# Fail on warnings as well as errors, for example in CI +openapi asyncapi validate --resolve --strict ./asyncapi.yaml + +# Read from stdin, resolving relative references against where the document lives +cat ./specs/asyncapi.yaml | openapi asyncapi validate --resolve --base-uri ./specs/asyncapi.yaml +``` + +| Flag | Description | +| ------------ | ------------------------------------------------------------------------------------------------------------- | +| `--resolve` | Load references to other files and URLs and validate them. Without it nothing outside the document is read | +| `--base-uri` | File path or URL to resolve relative references against, instead of the file's location. Requires `--resolve` | +| `--strict` | Fail validation on warnings as well as errors | + +Example output for a document that references another file, validated without `--resolve`: + +```text +Validating AsyncAPI document: asyncapi.yaml +✅ AsyncAPI document is valid - 0 errors, 1 warnings: + +1. [10:15] warning validation-invalid-reference reference `./messages.yaml#/components/messages/OrderPlaced` is to another document and external references are disabled + +Not checked: +- 1 references to other documents were not followed, use --resolve to validate them +``` + +## What is and isn't checked + +The command checks: + +- Structural validity, required fields, allowed values and data types +- Schemas written in the AsyncAPI Schema format or JSON Schema Draft 07 +- References within the document, which must exist and point to the right kind of object (with `--resolve`, references to other files and URLs too) +- Operation and message traits, applied in order, including problems that only appear once they're applied +- Rules that span objects, such as root operations using root channels and an operation's messages belonging to its channel + +Some content is preserved but can't be checked. The output lists it under **Not checked** so a passing result isn't mistaken for a complete one: + +- **References to other documents** aren't followed unless `--resolve` is set. They're reported as warnings, since they aren't known to be broken. +- **Schemas in other formats** (such as Avro or Protocol Buffers) and **protocol bindings** are kept as written but not validated. + +Documents declaring a version other than 3.0.x or 3.1.x, including AsyncAPI 2.x, are reported as unsupported and the rest of the document isn't checked. + +When reading from stdin with `--resolve`, the document has no location, so relative references to other documents can't be resolved unless `--base-uri` is set. Absolute file paths and URLs still resolve. + +`--resolve` makes requests to the URLs the document references, with a 30 second timeout. Only use it on documents you trust. + +## Exit status + +| Result | Exit status | +| ------------------------------------------ | ----------- | +| No errors (warnings and hints are allowed) | `0` | +| Warnings, with `--strict` | `1` | +| Errors, or an unsupported version | `1` | +| The document can't be read or parsed | `1` | + +Hints, such as bindings that aren't validated, never fail validation. diff --git a/cmd/openapi/commands/asyncapi/root.go b/cmd/openapi/commands/asyncapi/root.go new file mode 100644 index 00000000..785535a6 --- /dev/null +++ b/cmd/openapi/commands/asyncapi/root.go @@ -0,0 +1,8 @@ +package asyncapi + +import "github.com/spf13/cobra" + +// Apply adds AsyncAPI commands to the provided root command +func Apply(rootCmd *cobra.Command) { + rootCmd.AddCommand(validateCmd) +} diff --git a/cmd/openapi/commands/asyncapi/validate.go b/cmd/openapi/commands/asyncapi/validate.go new file mode 100644 index 00000000..c56f495d --- /dev/null +++ b/cmd/openapi/commands/asyncapi/validate.go @@ -0,0 +1,264 @@ +package asyncapi + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path/filepath" + "time" + + "github.com/speakeasy-api/openapi/asyncapi" + "github.com/speakeasy-api/openapi/cmd/openapi/commands/cmdutil" + "github.com/speakeasy-api/openapi/validation" + "github.com/spf13/cobra" +) + +var validateCmd = &cobra.Command{ + Use: "validate ", + Short: "Validate an AsyncAPI 3.x document", + Long: `Validate an AsyncAPI document for compliance with the AsyncAPI Specification. +AsyncAPI 3.0 and 3.1 are supported. Other versions, including 2.x, are reported as +unsupported and not checked further. + +This command will parse and validate the provided AsyncAPI document, checking for: +- Structural validity, required fields and proper data types +- Schemas written in the AsyncAPI Schema format or JSON Schema Draft 07 +- References within the document, which must exist and point to the right kind of object +- Operation and message traits, applied in order +- Rules spanning objects, such as an operation's messages belonging to its channel + +By default nothing outside the document is read. References to other files or URLs +are reported as warnings and not followed. Use --resolve to load them, and +--base-uri to give a document read from stdin a location to resolve them from. + +The output lists anything that couldn't be checked, such as references that weren't +followed and schemas or bindings in formats that aren't validated. Errors make +validation fail. Warnings only fail with --strict, and hints never do. + +Stdin is supported — either pipe data directly or use '-' explicitly: + cat asyncapi.yaml | openapi asyncapi validate + cat asyncapi.yaml | openapi asyncapi validate --resolve --base-uri ./specs/asyncapi.yaml -`, + Args: cmdutil.StdinOrFileArgs(1, 1), + Run: runValidate, +} + +// validateOptions are the options for validating an AsyncAPI document. +type validateOptions struct { + // resolve loads references to other documents. + resolve bool + // baseURI is the location references are resolved against, overriding the file's location. + baseURI string + // strict fails validation on warnings. + strict bool + // httpClient loads references to URLs. + httpClient *http.Client +} + +var ( + validateResolve bool + validateBaseURI string + validateStrict bool +) + +func init() { + validateCmd.Flags().BoolVar(&validateResolve, "resolve", false, "load references to other files and URLs and validate them") + validateCmd.Flags().StringVar(&validateBaseURI, "base-uri", "", "file path or URL to resolve relative references against, for example when reading from stdin (requires --resolve)") + validateCmd.Flags().BoolVar(&validateStrict, "strict", false, "fail validation on warnings as well as errors") +} + +func runValidate(cmd *cobra.Command, args []string) { + opts := validateOptions{ + resolve: validateResolve, + baseURI: validateBaseURI, + strict: validateStrict, + httpClient: &http.Client{Timeout: 30 * time.Second}, + } + if err := validateAsyncAPI(cmd.Context(), cmdutil.InputFileFromArgs(args), opts, os.Stdin, os.Stderr); err != nil { + cmdutil.Die(err) + } +} + +func validateAsyncAPI(ctx context.Context, file string, opts validateOptions, stdin io.Reader, stderr io.Writer) error { + if opts.baseURI != "" && !opts.resolve { + return errors.New("--base-uri is only used to resolve references to other documents, use it with --resolve") + } + + data, location, err := readInput(file, stdin, stderr) + if err != nil { + return err + } + if opts.baseURI != "" { + location = opts.baseURI + } + if opts.resolve && location == "" { + fmt.Fprintf(stderr, "Note: the document has no location, so relative references to other documents can't be resolved. Use --base-uri to set one.\n") + } + if location != "" && !isURL(location) { + if location, err = filepath.Abs(location); err != nil { + return fmt.Errorf("failed to resolve document location: %w", err) + } + } + + doc, validationErrs, err := asyncapi.Unmarshal(ctx, bytes.NewReader(data)) + if err != nil { + return fmt.Errorf("failed to unmarshal file: %w", err) + } + + // The rest of an unsupported version is checked against the 3.x model, which would only report noise. + if versionErrs := unsupportedVersionErrors(validationErrs); len(versionErrs) > 0 { + fmt.Fprintf(stderr, "❌ AsyncAPI document is not supported:\n\n") + printErrors(stderr, versionErrs) + fmt.Fprintf(stderr, "\nThe rest of the document was not checked.\n") + return errors.New("asyncapi document version is not supported") + } + + resolveErrs, err := doc.ResolveAllReferences(ctx, asyncapi.ResolveAllOptions{ + AsyncAPILocation: location, + DisableExternalRefs: !opts.resolve, + HTTPClient: opts.httpClient, + }) + if err != nil { + return fmt.Errorf("failed to resolve references: %w", err) + } + + summary := summarize(append(validationErrs, resolveErrs...)) + summary.print(stderr) + + switch { + case summary.errors > 0: + return errors.New("asyncapi document validation failed") + case opts.strict && summary.warnings > 0: + return fmt.Errorf("asyncapi document has %d warnings and --strict is set", summary.warnings) + } + return nil +} + +// readInput reads the document from the file or stdin, returning its location (empty for stdin). +func readInput(file string, stdin io.Reader, stderr io.Writer) ([]byte, string, error) { + if cmdutil.IsStdin(file) { + fmt.Fprintf(stderr, "Validating AsyncAPI document from stdin\n") + data, err := io.ReadAll(stdin) + if err != nil { + return nil, "", fmt.Errorf("failed to read stdin: %w", err) + } + return data, "", nil + } + + cleanFile := filepath.Clean(file) + fmt.Fprintf(stderr, "Validating AsyncAPI document: %s\n", cleanFile) + data, err := os.ReadFile(cleanFile) + if err != nil { + return nil, "", fmt.Errorf("failed to open file: %w", err) + } + return data, cleanFile, nil +} + +func isURL(location string) bool { + u, err := url.Parse(location) + return err == nil && (u.Scheme == "http" || u.Scheme == "https") +} + +func unsupportedVersionErrors(errs []error) []error { + versionErrs := []error{} + for _, err := range errs { + var vErr *validation.Error + if errors.As(err, &vErr) && vErr.Rule == validation.RuleValidationSupportedVersion { + versionErrs = append(versionErrs, err) + } + } + return versionErrs +} + +// validationSummary is the result of validating a document, including what couldn't be checked. +type validationSummary struct { + errs []error + errors int + warnings int + hints int + // unfollowed is the number of references to other documents that weren't followed. + unfollowed int + // unvalidatedFormats is the number of schemas, schema references and bindings in formats that aren't validated. + unvalidatedFormats int +} + +func summarize(errs []error) validationSummary { + s := validationSummary{errs: errs} + + for _, err := range errs { + var vErr *validation.Error + if !errors.As(err, &vErr) { + s.errors++ + continue + } + + // A reference that wasn't followed isn't known to be broken, so it's reported as something not checked. + if errors.Is(err, asyncapi.ErrExternalReferencesDisabled) { + vErr.Severity = validation.SeverityWarning + s.unfollowed++ + } + if vErr.Rule == validation.RuleValidationUnsupportedFormat { + s.unvalidatedFormats++ + } + + switch { + case vErr.Severity.Rank() >= validation.SeverityError.Rank(): + s.errors++ + case vErr.Severity == validation.SeverityWarning: + s.warnings++ + default: + s.hints++ + } + } + + validation.SortValidationErrors(s.errs) + return s +} + +func (s validationSummary) print(w io.Writer) { + if s.errors > 0 { + fmt.Fprintf(w, "❌ AsyncAPI document is invalid - %d errors", s.errors) + } else { + fmt.Fprintf(w, "✅ AsyncAPI document is valid - 0 errors") + } + if s.warnings > 0 { + fmt.Fprintf(w, ", %d warnings", s.warnings) + } + if s.hints > 0 { + fmt.Fprintf(w, ", %d hints", s.hints) + } + + if len(s.errs) == 0 { + fmt.Fprintln(w) + return + } + + fmt.Fprintf(w, ":\n\n") + printErrors(w, s.errs) + + if s.unfollowed == 0 && s.unvalidatedFormats == 0 { + return + } + fmt.Fprintf(w, "\nNot checked:\n") + if s.unfollowed > 0 { + fmt.Fprintf(w, "- %d references to other documents were not followed, use --resolve to validate them\n", s.unfollowed) + } + if s.unvalidatedFormats > 0 { + fmt.Fprintf(w, "- %d schemas or bindings are in formats that are preserved but not validated\n", s.unvalidatedFormats) + } +} + +func printErrors(w io.Writer, errs []error) { + for i, err := range errs { + fmt.Fprintf(w, "%d. %s\n", i+1, err.Error()) + } +} + +// GetValidateCommand returns the validate command for external use +func GetValidateCommand() *cobra.Command { + return validateCmd +} diff --git a/cmd/openapi/commands/asyncapi/validate_test.go b/cmd/openapi/commands/asyncapi/validate_test.go new file mode 100644 index 00000000..421c92c7 --- /dev/null +++ b/cmd/openapi/commands/asyncapi/validate_test.go @@ -0,0 +1,233 @@ +package asyncapi + +import ( + "bytes" + "context" + "errors" + "os" + "strings" + "testing" + + "github.com/speakeasy-api/openapi/validation" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const testdata = "../../../../asyncapi/testdata/" + +func readTestdata(t *testing.T, name string) string { + t.Helper() + data, err := os.ReadFile(testdata + name) + require.NoError(t, err, "fixture should load") + return string(data) +} + +func TestValidateAsyncAPI_Success(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + file string + stdin string + opts validateOptions + expectedStderr []string + unexpectedStderr []string + }{ + { + name: "valid document", + file: testdata + "validate/orders.asyncapi.yaml", + opts: validateOptions{resolve: true}, + expectedStderr: []string{"Validating AsyncAPI document: " + testdata + "validate/orders.asyncapi.yaml", "✅ AsyncAPI document is valid - 0 errors\n"}, + unexpectedStderr: []string{"Not checked"}, + }, + { + name: "references to other documents aren't followed by default", + file: testdata + "validate/orders.asyncapi.yaml", + expectedStderr: []string{ + "✅ AsyncAPI document is valid - 0 errors, 2 warnings:", + "1. [10:15] warning validation-invalid-reference reference `./messages.yaml#/components/messages/OrderPlaced` is to another document and external references are disabled", + "Not checked:\n- 2 references to other documents were not followed, use --resolve to validate them", + }, + }, + { + name: "a broken reference to another document isn't reported without --resolve", + file: testdata + "validate/broken-ref.asyncapi.yaml", + expectedStderr: []string{"✅ AsyncAPI document is valid - 0 errors, 1 warnings:", "1 references to other documents were not followed"}, + }, + { + name: "stdin resolved against --base-uri", + file: "-", + stdin: readTestdata(t, "validate/orders.asyncapi.yaml"), + opts: validateOptions{resolve: true, baseURI: testdata + "validate/orders.asyncapi.yaml"}, + expectedStderr: []string{"Validating AsyncAPI document from stdin", "✅ AsyncAPI document is valid - 0 errors\n"}, + unexpectedStderr: []string{"Note:"}, + }, + { + name: "formats that aren't validated are reported as not checked", + file: testdata + "streetlights-3.0.yaml", + expectedStderr: []string{"✅ AsyncAPI document is valid - 0 errors, 1 hints:", "Not checked:\n- 1 schemas or bindings are in formats that are preserved but not validated"}, + }, + { + name: "hints don't fail with --strict", + file: testdata + "streetlights-3.0.yaml", + opts: validateOptions{strict: true}, + expectedStderr: []string{"✅ AsyncAPI document is valid - 0 errors, 1 hints:"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + var stderr bytes.Buffer + err := validateAsyncAPI(t.Context(), tt.file, tt.opts, strings.NewReader(tt.stdin), &stderr) + require.NoError(t, err, "validation should succeed") + for _, expected := range tt.expectedStderr { + assert.Contains(t, stderr.String(), expected, "stderr should contain expected output") + } + for _, unexpected := range tt.unexpectedStderr { + assert.NotContains(t, stderr.String(), unexpected, "stderr should not contain unexpected output") + } + }) + } +} + +type errReader struct{} + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("read failed") +} + +func TestValidateAsyncAPI_Error(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + file string + stdin string + opts validateOptions + expectedErr string + expectedStderr []string + }{ + { + name: "invalid document", + file: testdata + "validate/invalid.asyncapi.yaml", + expectedErr: "asyncapi document validation failed", + expectedStderr: []string{ + "❌ AsyncAPI document is invalid - 3 errors:", + "error validation-required-field `info.version` is required", + "error validation-invalid-reference channel reference `#/channels/missing` target not found", + }, + }, + { + name: "broken reference to another document with --resolve", + file: testdata + "validate/broken-ref.asyncapi.yaml", + opts: validateOptions{resolve: true}, + expectedErr: "asyncapi document validation failed", + expectedStderr: []string{"❌ AsyncAPI document is invalid - 1 errors:", "failed to resolve message reference `./messages.yaml#/components/messages/Missing`"}, + }, + { + name: "unsupported version", + file: testdata + "validate/v2.asyncapi.yaml", + expectedErr: "asyncapi document version is not supported", + expectedStderr: []string{ + "❌ AsyncAPI document is not supported:", + "asyncapi version `2.6.0` is not supported", + "The rest of the document was not checked.", + }, + }, + { + name: "warnings fail with --strict", + file: testdata + "validate/orders.asyncapi.yaml", + opts: validateOptions{strict: true}, + expectedErr: "asyncapi document has 2 warnings and --strict is set", + expectedStderr: []string{"✅ AsyncAPI document is valid - 0 errors, 2 warnings:"}, + }, + { + name: "stdin without a location can't resolve relative references", + file: "-", + stdin: readTestdata(t, "validate/orders.asyncapi.yaml"), + opts: validateOptions{resolve: true}, + expectedErr: "asyncapi document validation failed", + expectedStderr: []string{"Note: the document has no location", "Use --base-uri to set one.", "relative reference `./messages.yaml#/components/messages/OrderPlaced` can't be resolved"}, + }, + { + name: "--base-uri without --resolve", + file: testdata + "validate/orders.asyncapi.yaml", + opts: validateOptions{baseURI: "https://example.com/asyncapi.yaml"}, + expectedErr: "--base-uri is only used to resolve references to other documents, use it with --resolve", + }, + { + name: "missing file", + file: "testdata/missing.asyncapi.yaml", + expectedErr: "failed to open file", + }, + { + name: "unparseable document", + file: "-", + stdin: "[", + expectedErr: "failed to unmarshal file", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + var stderr bytes.Buffer + err := validateAsyncAPI(t.Context(), tt.file, tt.opts, strings.NewReader(tt.stdin), &stderr) + require.Error(t, err, "validation should fail") + assert.Contains(t, err.Error(), tt.expectedErr, "error should match") + for _, expected := range tt.expectedStderr { + assert.Contains(t, stderr.String(), expected, "stderr should contain expected output") + } + }) + } +} + +func TestValidateAsyncAPI_StdinReadError(t *testing.T) { + t.Parallel() + + var stderr bytes.Buffer + err := validateAsyncAPI(t.Context(), "-", validateOptions{}, errReader{}, &stderr) + require.Error(t, err, "validation should fail") + assert.Contains(t, err.Error(), "failed to read stdin", "error should match") +} + +func TestValidateAsyncAPI_CancelledContext_Error(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + + var stderr bytes.Buffer + err := validateAsyncAPI(ctx, testdata+"validate/orders.asyncapi.yaml", validateOptions{}, strings.NewReader(""), &stderr) + require.Error(t, err, "validation should fail") + assert.Equal(t, "failed to resolve references: context canceled", err.Error(), "error should match") +} + +func TestApply_Success(t *testing.T) { + t.Parallel() + + root := &cobra.Command{Use: "openapi"} + Apply(root) + + // The command isn't executed here: on failure it exits the process, so validateAsyncAPI is tested directly. + cmd, _, err := root.Find([]string{"validate"}) + require.NoError(t, err, "validate command should be registered") + assert.Same(t, GetValidateCommand(), cmd, "registered command should be the validate command") + assert.Equal(t, []string{"resolve", "base-uri", "strict"}, []string{ + cmd.Flags().Lookup("resolve").Name, + cmd.Flags().Lookup("base-uri").Name, + cmd.Flags().Lookup("strict").Name, + }, "validate command should register its flags") +} + +func TestSummarize_NonValidationErrors_Success(t *testing.T) { + t.Parallel() + + s := summarize([]error{errors.New("plain error"), &validation.Error{Severity: validation.SeverityHint, UnderlyingError: errors.New("hint")}}) + assert.Equal(t, 1, s.errors, "plain errors should be counted as errors") + assert.Equal(t, 1, s.hints, "hints should be counted") +} diff --git a/cmd/openapi/commands/openapi/lint.go b/cmd/openapi/commands/openapi/lint.go index 25fc2803..ff121f64 100644 --- a/cmd/openapi/commands/openapi/lint.go +++ b/cmd/openapi/commands/openapi/lint.go @@ -282,7 +282,6 @@ func applyFixes(ctx context.Context, fixOpts fix.Options, doc *openapi.OpenAPI, return nil } - // lazyPrompter defers TerminalPrompter creation until an interactive fix is // actually encountered, avoiding unnecessary setup when all fixes are non-interactive. type lazyPrompter struct { diff --git a/cmd/openapi/commands/overlay/validate.go b/cmd/openapi/commands/overlay/validate.go index f7f3de0c..023aa7be 100644 --- a/cmd/openapi/commands/overlay/validate.go +++ b/cmd/openapi/commands/overlay/validate.go @@ -22,7 +22,7 @@ var validateCmd = &cobra.Command{ } return fmt.Errorf("overlay file is required (use --overlay flag, provide as argument, or pipe to stdin)") }, - Run: RunValidateOverlay, + Run: RunValidateOverlay, Example: ` # Validate overlay using positional argument openapi overlay validate overlay.yaml diff --git a/cmd/openapi/go.mod b/cmd/openapi/go.mod index 4bf8b1d2..f0886118 100644 --- a/cmd/openapi/go.mod +++ b/cmd/openapi/go.mod @@ -6,7 +6,7 @@ require ( charm.land/bubbles/v2 v2.2.1 charm.land/bubbletea/v2 v2.1.1 charm.land/lipgloss/v2 v2.1.0 - github.com/speakeasy-api/openapi v1.26.6-0.20261117052855-40c8fb72eeeb + github.com/speakeasy-api/openapi v1.27.1-0.20261118023045-8dde20f424f7 github.com/speakeasy-api/openapi/openapi/linter/customrules v0.0.0-20261117052855-40c8fb72eeeb github.com/spf13/cobra v1.10.2 github.com/stretchr/testify v1.12.1 diff --git a/cmd/openapi/go.sum b/cmd/openapi/go.sum index 1e05e780..200d2313 100644 --- a/cmd/openapi/go.sum +++ b/cmd/openapi/go.sum @@ -70,8 +70,8 @@ github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= github.com/speakeasy-api/jsonpath v0.7.1 h1:vpBDKeT6av0v/g6oTwCfGh27iRDfMPaTQ2GvKK51TkQ= github.com/speakeasy-api/jsonpath v0.7.1/go.mod h1:b9upx/gIKYwyKVcgRxvmdyKwAykzk88FCnNH3cwbw8w= -github.com/speakeasy-api/openapi v1.26.6-0.20261117052855-40c8fb72eeeb h1:NmWFxMfj3+BYGyspzV71NhGCp20A7VMZivP/mvbNBOA= -github.com/speakeasy-api/openapi v1.26.6-0.20261117052855-40c8fb72eeeb/go.mod h1:rEfDPWMo5kZ5g/QDFBuc/oZUA1KArdEnI4AgPsZtWwo= +github.com/speakeasy-api/openapi v1.27.1-0.20261118023045-8dde20f424f7 h1:OBZgYEjwNTnYjBvSS27gSHyCBFTewePFdnoeHemVh9U= +github.com/speakeasy-api/openapi v1.27.1-0.20261118023045-8dde20f424f7/go.mod h1:rEfDPWMo5kZ5g/QDFBuc/oZUA1KArdEnI4AgPsZtWwo= github.com/speakeasy-api/openapi/openapi/linter/customrules v0.0.0-20261117052855-40c8fb72eeeb h1:bBJtMeeIB4SXNFpJazb3DIN3Bsbo2fnhSRxl+ss1IAU= github.com/speakeasy-api/openapi/openapi/linter/customrules v0.0.0-20261117052855-40c8fb72eeeb/go.mod h1:2O20OjykuY535xFwS+xQmR/JngcAh6ZPRDb4qA86JwM= github.com/speakeasy-api/yaml-jsonpath v0.0.0-20261016002013-07e5f48e6d17 h1:GczZJYqsf1WvvdkFvviAaP5wLrqxRPed8TmbKFsoLFk= diff --git a/cmd/openapi/main.go b/cmd/openapi/main.go index 98b8dc88..d7ebb7e2 100644 --- a/cmd/openapi/main.go +++ b/cmd/openapi/main.go @@ -7,6 +7,7 @@ import ( "strings" arazzoCmd "github.com/speakeasy-api/openapi/cmd/openapi/commands/arazzo" + asyncapiCmd "github.com/speakeasy-api/openapi/cmd/openapi/commands/asyncapi" openapiCmd "github.com/speakeasy-api/openapi/cmd/openapi/commands/openapi" overlayCmd "github.com/speakeasy-api/openapi/cmd/openapi/commands/overlay" swaggerCmd "github.com/speakeasy-api/openapi/cmd/openapi/commands/swagger" @@ -60,8 +61,8 @@ func getVersionInfo() (string, string, string) { var rootCmd = &cobra.Command{ Use: "openapi", - Short: "OpenAPI toolkit for working with OpenAPI specifications, overlays, and Arazzo workflows", - Long: `A comprehensive toolkit for working with OpenAPI specifications and Arazzo workflows. + Short: "OpenAPI toolkit for working with OpenAPI specifications, overlays, Arazzo workflows and AsyncAPI documents", + Long: `A comprehensive toolkit for working with OpenAPI specifications, Arazzo workflows and AsyncAPI documents. This CLI provides tools for: @@ -74,6 +75,9 @@ OpenAPI Specifications: Arazzo Workflows: - Validate Arazzo workflow documents for compliance +AsyncAPI Documents: +- Validate AsyncAPI 3.x documents for compliance + OpenAPI Overlays: - Apply overlays to modify OpenAPI specifications - Compare two specifications and generate overlays @@ -124,6 +128,15 @@ Arazzo workflows describe sequences of API calls and their dependencies. These commands help you validate and work with Arazzo documents.`, } +var asyncapiCmds = &cobra.Command{ + Use: "asyncapi", + Short: "Work with AsyncAPI documents", + Long: `Commands for working with AsyncAPI documents. + +AsyncAPI documents describe message-driven APIs: the channels an application uses +and the messages it sends and receives. These commands work with AsyncAPI 3.x.`, +} + func init() { // Get version information (prioritizes ldflags, falls back to build info) currentVersion, currentCommit, currentDate := getVersionInfo() @@ -154,6 +167,9 @@ func init() { // Add Arazzo workflow validation command arazzoCmd.Apply(arazzoCmds) + // Add AsyncAPI commands + asyncapiCmd.Apply(asyncapiCmds) + // Add overlay subcommands using the Apply function overlayCmd.Apply(overlayCmds) @@ -161,6 +177,7 @@ func init() { rootCmd.AddCommand(openapiCmds) rootCmd.AddCommand(swaggerCmds) rootCmd.AddCommand(arazzoCmds) + rootCmd.AddCommand(asyncapiCmds) rootCmd.AddCommand(overlayCmds) // Top-level shortcut: openapi oq → openapi spec query