sdkloom 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +239 -2
- package/kits/allowed-sources.json +24 -0
- package/kits/csharp/kit.json +6 -0
- package/kits/csharp/src/Runtime/Client.cs +295 -0
- package/kits/csharp/src/Runtime/Context.cs +216 -0
- package/kits/csharp/src/Runtime/Errors.cs +121 -0
- package/kits/csharp/src/Runtime/Http.cs +218 -0
- package/kits/csharp/src/Runtime/Json.cs +650 -0
- package/kits/csharp/src/Runtime/Lang.cs +212 -0
- package/kits/csharp/src/Runtime/Models.cs +206 -0
- package/kits/csharp/src/Runtime/Multipart.cs +108 -0
- package/kits/csharp/src/Runtime/Pagination.cs +122 -0
- package/kits/csharp/src/Runtime/Sse.cs +197 -0
- package/kits/csharp/src/Runtime/Testing.cs +375 -0
- package/kits/csharp/src/Runtime/Transport.cs +212 -0
- package/kits/csharp/src/Runtime/Wait.cs +57 -0
- package/kits/csharp/src/Runtime/Webhooks.cs +148 -0
- package/kits/csharp/tests/ClientTests.cs +128 -0
- package/kits/csharp/tests/HttpTests.cs +44 -0
- package/kits/csharp/tests/JsonTests.cs +132 -0
- package/kits/csharp/tests/LangTests.cs +57 -0
- package/kits/csharp/tests/MultipartTests.cs +31 -0
- package/kits/csharp/tests/PaginationTests.cs +93 -0
- package/kits/csharp/tests/SseTests.cs +122 -0
- package/kits/csharp/tests/TestRunner.cs +93 -0
- package/kits/csharp/tests/TestingTests.cs +80 -0
- package/kits/csharp/tests/TransportTests.cs +145 -0
- package/kits/csharp/tests/WaitTests.cs +39 -0
- package/kits/csharp/tests/WebhooksTests.cs +46 -0
- package/kits/csharp/versions.json +12 -0
- package/kits/go/kit.json +6 -0
- package/kits/go/src/sdkruntime/client.go +322 -0
- package/kits/go/src/sdkruntime/context.go +207 -0
- package/kits/go/src/sdkruntime/errors.go +74 -0
- package/kits/go/src/sdkruntime/http.go +261 -0
- package/kits/go/src/sdkruntime/json.go +527 -0
- package/kits/go/src/sdkruntime/lang.go +462 -0
- package/kits/go/src/sdkruntime/multipart.go +75 -0
- package/kits/go/src/sdkruntime/pagination.go +150 -0
- package/kits/go/src/sdkruntime/sse.go +267 -0
- package/kits/go/src/sdkruntime/testing.go +343 -0
- package/kits/go/src/sdkruntime/transport.go +168 -0
- package/kits/go/src/sdkruntime/wait.go +49 -0
- package/kits/go/src/sdkruntime/webhooks.go +129 -0
- package/kits/go/tests/client_test.go +185 -0
- package/kits/go/tests/http_test.go +78 -0
- package/kits/go/tests/json_test.go +127 -0
- package/kits/go/tests/lang_test.go +98 -0
- package/kits/go/tests/multipart_test.go +29 -0
- package/kits/go/tests/pagination_test.go +69 -0
- package/kits/go/tests/sse_test.go +129 -0
- package/kits/go/tests/testing_test.go +121 -0
- package/kits/go/tests/transport_test.go +133 -0
- package/kits/go/tests/wait_test.go +46 -0
- package/kits/go/tests/webhooks_test.go +62 -0
- package/kits/go/versions.json +12 -0
- package/kits/java/kit.json +6 -0
- package/kits/java/src/dev/sdkloom/runtime/ApiException.java +63 -0
- package/kits/java/src/dev/sdkloom/runtime/ArgumentException.java +24 -0
- package/kits/java/src/dev/sdkloom/runtime/Assert.java +72 -0
- package/kits/java/src/dev/sdkloom/runtime/ClientRuntime.java +220 -0
- package/kits/java/src/dev/sdkloom/runtime/Clock.java +39 -0
- package/kits/java/src/dev/sdkloom/runtime/Context.java +79 -0
- package/kits/java/src/dev/sdkloom/runtime/Decode.java +200 -0
- package/kits/java/src/dev/sdkloom/runtime/DecodeException.java +26 -0
- package/kits/java/src/dev/sdkloom/runtime/Decoder.java +16 -0
- package/kits/java/src/dev/sdkloom/runtime/Emitter.java +56 -0
- package/kits/java/src/dev/sdkloom/runtime/ErrorFactory.java +18 -0
- package/kits/java/src/dev/sdkloom/runtime/EventListener.java +20 -0
- package/kits/java/src/dev/sdkloom/runtime/EventStream.java +232 -0
- package/kits/java/src/dev/sdkloom/runtime/FakeClock.java +37 -0
- package/kits/java/src/dev/sdkloom/runtime/Headers.java +42 -0
- package/kits/java/src/dev/sdkloom/runtime/HttpRequest.java +88 -0
- package/kits/java/src/dev/sdkloom/runtime/HttpResponse.java +69 -0
- package/kits/java/src/dev/sdkloom/runtime/JdkTransport.java +97 -0
- package/kits/java/src/dev/sdkloom/runtime/Js.java +230 -0
- package/kits/java/src/dev/sdkloom/runtime/Json.java +281 -0
- package/kits/java/src/dev/sdkloom/runtime/JsonValue.java +15 -0
- package/kits/java/src/dev/sdkloom/runtime/Links.java +62 -0
- package/kits/java/src/dev/sdkloom/runtime/Middleware.java +16 -0
- package/kits/java/src/dev/sdkloom/runtime/MiddlewareEntry.java +43 -0
- package/kits/java/src/dev/sdkloom/runtime/MockRoute.java +111 -0
- package/kits/java/src/dev/sdkloom/runtime/MockTransport.java +62 -0
- package/kits/java/src/dev/sdkloom/runtime/MultipartForm.java +111 -0
- package/kits/java/src/dev/sdkloom/runtime/Next.java +16 -0
- package/kits/java/src/dev/sdkloom/runtime/OperationInfo.java +35 -0
- package/kits/java/src/dev/sdkloom/runtime/OperationMock.java +105 -0
- package/kits/java/src/dev/sdkloom/runtime/OperationSpec.java +125 -0
- package/kits/java/src/dev/sdkloom/runtime/Pages.java +55 -0
- package/kits/java/src/dev/sdkloom/runtime/Pipeline.java +29 -0
- package/kits/java/src/dev/sdkloom/runtime/RawResult.java +31 -0
- package/kits/java/src/dev/sdkloom/runtime/RecordedEvent.java +36 -0
- package/kits/java/src/dev/sdkloom/runtime/SdkInfo.java +38 -0
- package/kits/java/src/dev/sdkloom/runtime/SendOptions.java +34 -0
- package/kits/java/src/dev/sdkloom/runtime/ServerSentEvent.java +58 -0
- package/kits/java/src/dev/sdkloom/runtime/State.java +58 -0
- package/kits/java/src/dev/sdkloom/runtime/Test.java +21 -0
- package/kits/java/src/dev/sdkloom/runtime/TestRunner.java +63 -0
- package/kits/java/src/dev/sdkloom/runtime/Transport.java +16 -0
- package/kits/java/src/dev/sdkloom/runtime/TransportException.java +30 -0
- package/kits/java/src/dev/sdkloom/runtime/UrlConnectionTransport.java +195 -0
- package/kits/java/src/dev/sdkloom/runtime/Urls.java +116 -0
- package/kits/java/src/dev/sdkloom/runtime/Waits.java +53 -0
- package/kits/java/src/dev/sdkloom/runtime/WebhookSignatureException.java +24 -0
- package/kits/java/src/dev/sdkloom/runtime/Webhooks.java +146 -0
- package/kits/java/tests/dev/sdkloom/runtime/ClientTest.java +266 -0
- package/kits/java/tests/dev/sdkloom/runtime/EventStreamTest.java +131 -0
- package/kits/java/tests/dev/sdkloom/runtime/HttpTest.java +95 -0
- package/kits/java/tests/dev/sdkloom/runtime/JdkTransportTest.java +12 -0
- package/kits/java/tests/dev/sdkloom/runtime/JsTest.java +102 -0
- package/kits/java/tests/dev/sdkloom/runtime/JsonTest.java +87 -0
- package/kits/java/tests/dev/sdkloom/runtime/LinksTest.java +22 -0
- package/kits/java/tests/dev/sdkloom/runtime/MultipartFormTest.java +30 -0
- package/kits/java/tests/dev/sdkloom/runtime/PagesTest.java +75 -0
- package/kits/java/tests/dev/sdkloom/runtime/TestData.java +53 -0
- package/kits/java/tests/dev/sdkloom/runtime/TestingTest.java +156 -0
- package/kits/java/tests/dev/sdkloom/runtime/TransportContract.java +201 -0
- package/kits/java/tests/dev/sdkloom/runtime/UrlConnectionTransportTest.java +49 -0
- package/kits/java/tests/dev/sdkloom/runtime/WaitsTest.java +43 -0
- package/kits/java/tests/dev/sdkloom/runtime/WebhooksTest.java +45 -0
- package/kits/java/versions.json +41 -0
- package/kits/python/kit.json +6 -0
- package/kits/python/src/sdkloom_runtime/__init__.py +1 -0
- package/kits/python/src/sdkloom_runtime/client.py +232 -0
- package/kits/python/src/sdkloom_runtime/compat.py +195 -0
- package/kits/python/src/sdkloom_runtime/context.py +134 -0
- package/kits/python/src/sdkloom_runtime/errors.py +65 -0
- package/kits/python/src/sdkloom_runtime/http.py +192 -0
- package/kits/python/src/sdkloom_runtime/lang.py +207 -0
- package/kits/python/src/sdkloom_runtime/models.py +221 -0
- package/kits/python/src/sdkloom_runtime/multipart.py +69 -0
- package/kits/python/src/sdkloom_runtime/pagination.py +61 -0
- package/kits/python/src/sdkloom_runtime/pipeline.py +39 -0
- package/kits/python/src/sdkloom_runtime/sse.py +121 -0
- package/kits/python/src/sdkloom_runtime/testing.py +224 -0
- package/kits/python/src/sdkloom_runtime/transport.py +120 -0
- package/kits/python/src/sdkloom_runtime/wait.py +44 -0
- package/kits/python/src/sdkloom_runtime/webhooks.py +84 -0
- package/kits/python/tests/support.py +28 -0
- package/kits/python/tests/test_client.py +275 -0
- package/kits/python/tests/test_compat.py +87 -0
- package/kits/python/tests/test_http.py +94 -0
- package/kits/python/tests/test_lang.py +104 -0
- package/kits/python/tests/test_models.py +110 -0
- package/kits/python/tests/test_multipart.py +37 -0
- package/kits/python/tests/test_pagination.py +70 -0
- package/kits/python/tests/test_sse.py +61 -0
- package/kits/python/tests/test_testing.py +130 -0
- package/kits/python/tests/test_transport.py +124 -0
- package/kits/python/tests/test_wait.py +46 -0
- package/kits/python/tests/test_webhooks.py +57 -0
- package/kits/python/versions.json +33 -0
- package/kits/rust/kit.json +6 -0
- package/kits/rust/src/runtime/client.rs +212 -0
- package/kits/rust/src/runtime/context.rs +182 -0
- package/kits/rust/src/runtime/crypto.rs +84 -0
- package/kits/rust/src/runtime/errors.rs +147 -0
- package/kits/rust/src/runtime/http.rs +248 -0
- package/kits/rust/src/runtime/json.rs +424 -0
- package/kits/rust/src/runtime/lang.rs +296 -0
- package/kits/rust/src/runtime/mod.rs +30 -0
- package/kits/rust/src/runtime/models.rs +266 -0
- package/kits/rust/src/runtime/multipart.rs +81 -0
- package/kits/rust/src/runtime/pagination.rs +117 -0
- package/kits/rust/src/runtime/sse.rs +195 -0
- package/kits/rust/src/runtime/testing.rs +308 -0
- package/kits/rust/src/runtime/transport.rs +324 -0
- package/kits/rust/src/runtime/wait.rs +29 -0
- package/kits/rust/src/runtime/webhooks.rs +142 -0
- package/kits/rust/tests/client.rs +152 -0
- package/kits/rust/tests/http.rs +44 -0
- package/kits/rust/tests/json.rs +82 -0
- package/kits/rust/tests/lang.rs +74 -0
- package/kits/rust/tests/multipart.rs +21 -0
- package/kits/rust/tests/pagination.rs +61 -0
- package/kits/rust/tests/sse.rs +77 -0
- package/kits/rust/tests/testing.rs +90 -0
- package/kits/rust/tests/transport.rs +218 -0
- package/kits/rust/tests/wait.rs +32 -0
- package/kits/rust/tests/webhooks.rs +73 -0
- package/kits/rust/versions.json +6 -0
- package/kits/typescript/kit.json +6 -0
- package/kits/typescript/src/client.ts +223 -0
- package/kits/typescript/src/context.ts +108 -0
- package/kits/typescript/src/errors.ts +63 -0
- package/kits/typescript/src/helpers.ts +49 -0
- package/kits/typescript/src/http.ts +192 -0
- package/kits/typescript/src/models.ts +139 -0
- package/kits/typescript/src/multipart.ts +66 -0
- package/kits/typescript/src/pagination.ts +54 -0
- package/kits/typescript/src/pipeline.ts +25 -0
- package/kits/typescript/src/sse.ts +102 -0
- package/kits/typescript/src/testing.ts +217 -0
- package/kits/typescript/src/transport.ts +101 -0
- package/kits/typescript/src/wait.ts +36 -0
- package/kits/typescript/src/webhooks.ts +168 -0
- package/kits/typescript/tests/client.test.ts +269 -0
- package/kits/typescript/tests/helpers.test.ts +27 -0
- package/kits/typescript/tests/http.test.ts +80 -0
- package/kits/typescript/tests/models.test.ts +71 -0
- package/kits/typescript/tests/multipart.test.ts +28 -0
- package/kits/typescript/tests/pagination.test.ts +76 -0
- package/kits/typescript/tests/sse.test.ts +82 -0
- package/kits/typescript/tests/testing.test.ts +103 -0
- package/kits/typescript/tests/transport.test.ts +127 -0
- package/kits/typescript/tests/wait.test.ts +31 -0
- package/kits/typescript/tests/webhooks.test.ts +53 -0
- package/kits/typescript/versions.json +15 -0
- package/package.json +37 -4
- package/packages/cli/recipes/apiKeyHeader.ts +16 -0
- package/packages/cli/recipes/apiVersionHeader.ts +16 -0
- package/packages/cli/recipes/basic.ts +13 -0
- package/packages/cli/recipes/bearer.ts +10 -0
- package/packages/cli/recipes/hmacSign.ts +23 -0
- package/packages/cli/recipes/idempotencyKey.ts +19 -0
- package/packages/cli/recipes/oauthClientCredentials.ts +50 -0
- package/packages/cli/recipes/retry.ts +42 -0
- package/packages/cli/recipes/timing.ts +12 -0
- package/packages/cli/recipes/userAgent.ts +8 -0
- package/packages/cli/src/build.js +93 -0
- package/packages/cli/src/commands/build.js +31 -0
- package/packages/cli/src/commands/conformance-check.js +50 -0
- package/packages/cli/src/commands/contract.js +181 -0
- package/packages/cli/src/commands/diff.js +113 -0
- package/packages/cli/src/commands/doctor.js +43 -0
- package/packages/cli/src/commands/import-openapi.js +42 -0
- package/packages/cli/src/commands/init.js +27 -0
- package/packages/cli/src/commands/kit-check.js +145 -0
- package/packages/cli/src/commands/publish.js +81 -0
- package/packages/cli/src/commands/recipe.js +49 -0
- package/packages/cli/src/commands/record.js +181 -0
- package/packages/cli/src/commands/serve.js +156 -0
- package/packages/cli/src/commands/spec-check.js +57 -0
- package/packages/cli/src/commands/test.js +177 -0
- package/packages/cli/src/commands/variants.js +32 -0
- package/packages/cli/src/commands/verify.js +57 -0
- package/packages/cli/src/commands/version.js +63 -0
- package/packages/cli/src/containers.js +82 -0
- package/packages/cli/src/coverage.js +72 -0
- package/packages/cli/src/git.js +25 -0
- package/packages/cli/src/io.js +50 -0
- package/packages/cli/src/java/ScenarioHarness.java +297 -0
- package/packages/cli/src/java/SchemaRoundTrip.java +63 -0
- package/packages/cli/src/java.js +70 -0
- package/packages/cli/src/js/harness.mjs +120 -0
- package/packages/cli/src/kits.js +103 -0
- package/packages/cli/src/languages/csharp.js +274 -0
- package/packages/cli/src/languages/go.js +185 -0
- package/packages/cli/src/languages/index.js +18 -0
- package/packages/cli/src/languages/java.js +187 -0
- package/packages/cli/src/languages/python.js +120 -0
- package/packages/cli/src/languages/rust.js +189 -0
- package/packages/cli/src/languages/types.js +93 -0
- package/packages/cli/src/languages/typescript.js +112 -0
- package/packages/cli/src/main.js +13 -0
- package/packages/cli/src/packaging.js +39 -0
- package/packages/cli/src/portability.js +45 -0
- package/packages/cli/src/profiles.js +55 -0
- package/packages/cli/src/project.js +56 -0
- package/packages/cli/src/python/scenario_harness.py +162 -0
- package/packages/cli/src/python/schema_roundtrip.py +42 -0
- package/packages/cli/src/registries.js +214 -0
- package/packages/cli/src/resolve-core.js +39 -0
- package/packages/cli/src/run.js +133 -0
- package/packages/cli/src/runtimes.js +61 -0
- package/packages/cli/src/scenarios-java.js +82 -0
- package/packages/cli/src/scenarios-javascript.js +54 -0
- package/packages/cli/src/scenarios-python.js +90 -0
- package/packages/cli/src/scenarios.js +183 -0
- package/packages/cli/src/schema.js +84 -0
- package/packages/cli/src/templates.js +85 -0
- package/packages/cli/src/toolchains.js +68 -0
- package/packages/cli/src/transpiled-tests.js +92 -0
- package/packages/codegen/src/canonical-json.js +31 -0
- package/packages/codegen/src/capabilities.js +50 -0
- package/packages/codegen/src/code-writer.js +54 -0
- package/packages/codegen/src/file-tree.js +25 -0
- package/packages/codegen/src/hash.js +6 -0
- package/packages/codegen/src/index.js +16 -0
- package/packages/codegen/src/lock.js +106 -0
- package/packages/conformance/src/case.js +143 -0
- package/packages/conformance/src/checks.js +40 -0
- package/packages/conformance/src/index.js +3 -0
- package/packages/conformance/src/matrix.js +48 -0
- package/packages/conformance/src/suite.js +48 -0
- package/packages/differ/src/diff.js +500 -0
- package/packages/differ/src/index.js +3 -0
- package/packages/differ/src/notes.js +112 -0
- package/packages/differ/src/support.js +34 -0
- package/packages/gen-csharp/src/emit-client.js +397 -0
- package/packages/gen-csharp/src/emit-harness.js +333 -0
- package/packages/gen-csharp/src/emit-mock.js +111 -0
- package/packages/gen-csharp/src/emit-models.js +119 -0
- package/packages/gen-csharp/src/emit-webhooks.js +57 -0
- package/packages/gen-csharp/src/generate.js +245 -0
- package/packages/gen-csharp/src/index.js +5 -0
- package/packages/gen-csharp/src/names.js +284 -0
- package/packages/gen-go/src/emit-client.js +405 -0
- package/packages/gen-go/src/emit-harness.js +294 -0
- package/packages/gen-go/src/emit-mock.js +112 -0
- package/packages/gen-go/src/emit-models.js +146 -0
- package/packages/gen-go/src/emit-webhooks.js +58 -0
- package/packages/gen-go/src/generate.js +205 -0
- package/packages/gen-go/src/index.js +5 -0
- package/packages/gen-go/src/names.js +197 -0
- package/packages/gen-java/src/emit-client.js +441 -0
- package/packages/gen-java/src/emit-models.js +342 -0
- package/packages/gen-java/src/emit-testing.js +123 -0
- package/packages/gen-java/src/emit-webhooks.js +70 -0
- package/packages/gen-java/src/generate.js +244 -0
- package/packages/gen-java/src/index.js +4 -0
- package/packages/gen-java/src/names.js +197 -0
- package/packages/gen-python/src/emit-client.js +272 -0
- package/packages/gen-python/src/emit-models.js +139 -0
- package/packages/gen-python/src/emit-testing.js +93 -0
- package/packages/gen-python/src/emit-webhooks.js +48 -0
- package/packages/gen-python/src/generate.js +237 -0
- package/packages/gen-python/src/index.js +2 -0
- package/packages/gen-python/src/names.js +161 -0
- package/packages/gen-python/src/style.js +67 -0
- package/packages/gen-rust/src/emit-client.js +379 -0
- package/packages/gen-rust/src/emit-harness.js +278 -0
- package/packages/gen-rust/src/emit-mock.js +121 -0
- package/packages/gen-rust/src/emit-models.js +117 -0
- package/packages/gen-rust/src/emit-webhooks.js +58 -0
- package/packages/gen-rust/src/generate.js +243 -0
- package/packages/gen-rust/src/index.js +5 -0
- package/packages/gen-rust/src/names.js +223 -0
- package/packages/gen-typescript/src/emit-client.js +434 -0
- package/packages/gen-typescript/src/emit-models.js +93 -0
- package/packages/gen-typescript/src/emit-package.js +90 -0
- package/packages/gen-typescript/src/emit-testing.js +138 -0
- package/packages/gen-typescript/src/emit-webhooks.js +52 -0
- package/packages/gen-typescript/src/generate.js +70 -0
- package/packages/gen-typescript/src/index.js +3 -0
- package/packages/gen-typescript/src/naming.js +64 -0
- package/packages/gen-typescript/src/runtime.js +81 -0
- package/packages/gen-typescript/src/types.js +136 -0
- package/packages/ir/src/api-surface.js +22 -0
- package/packages/ir/src/checks.js +52 -0
- package/packages/ir/src/index.js +32 -0
- package/packages/ir/src/ir.js +214 -0
- package/packages/ir/src/pages.js +18 -0
- package/packages/ir/src/validate-ir.js +462 -0
- package/packages/ir/src/validate-types.js +140 -0
- package/packages/kit/src/block-parser.js +196 -0
- package/packages/kit/src/index.js +15 -0
- package/packages/kit/src/kit-check.js +203 -0
- package/packages/kit/src/sources.js +53 -0
- package/packages/kit/src/version-policy.js +133 -0
- package/packages/kit/src/version-range.js +132 -0
- package/packages/openapi/src/import.js +292 -0
- package/packages/openapi/src/index.js +1 -0
- package/packages/openapi/src/names.js +50 -0
- package/packages/openapi/src/schemas.js +264 -0
- package/packages/packager/src/archive.js +106 -0
- package/packages/packager/src/crate.js +39 -0
- package/packages/packager/src/gomodule.js +11 -0
- package/packages/packager/src/index.js +9 -0
- package/packages/packager/src/maven.js +85 -0
- package/packages/packager/src/metadata.js +34 -0
- package/packages/packager/src/npm.js +71 -0
- package/packages/packager/src/nuget.js +78 -0
- package/packages/packager/src/sbom.js +56 -0
- package/packages/packager/src/wheel.js +62 -0
- package/packages/spec/src/index.js +11 -0
- package/packages/spec/src/requirements.js +139 -0
- package/packages/transpile/src/ast.js +51 -0
- package/packages/transpile/src/check.js +669 -0
- package/packages/transpile/src/emit-csharp.js +469 -0
- package/packages/transpile/src/emit-go.js +529 -0
- package/packages/transpile/src/emit-java.js +360 -0
- package/packages/transpile/src/emit-python.js +320 -0
- package/packages/transpile/src/emit-rust.js +499 -0
- package/packages/transpile/src/errors.js +15 -0
- package/packages/transpile/src/index.js +13 -0
- package/packages/transpile/src/lexer.js +161 -0
- package/packages/transpile/src/parser.js +543 -0
- package/packages/transpile/src/tests/ast.js +46 -0
- package/packages/transpile/src/tests/parse.js +376 -0
- package/packages/transpile/src/tests/translate.js +849 -0
- package/packages/transpile/src/transpile.js +57 -0
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// sdkloom Rust kit: the transport that sends requests.
|
|
2
|
+
|
|
3
|
+
use super::errors::Error;
|
|
4
|
+
use super::http::{BodyStream, Request, Response};
|
|
5
|
+
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
|
|
6
|
+
use std::net::{TcpStream, ToSocketAddrs};
|
|
7
|
+
use std::time::{Duration, Instant};
|
|
8
|
+
|
|
9
|
+
// @block transport.std
|
|
10
|
+
// @summary The default transport: HTTP/1.1 over std::net; the timeout bounds connecting, each write and the whole response (name resolution is not bounded: std has no timeout for it), an optional HTTP proxy, chunked and sized bodies, and no redirects; non-2xx responses are returned, not errors. A successful body is handed over as it arrives when the caller asks for a stream. The standard library has no TLS: https URLs need a Transport built on a TLS-capable HTTP library (sdkloom adapter rust).
|
|
11
|
+
// @versions >=1.70
|
|
12
|
+
// @source [1] https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.connect_timeout
|
|
13
|
+
// @quote [1] "Opens a TCP connection to a remote host with a timeout."
|
|
14
|
+
// @source [2] https://www.rfc-editor.org/rfc/rfc9112#section-7.1
|
|
15
|
+
// @quote [2] "The chunked transfer coding wraps content in order to transfer it as a series of chunks, each with its own size indicator, followed by an OPTIONAL trailer section containing trailer fields."
|
|
16
|
+
// @source [3] https://www.rfc-editor.org/rfc/rfc9112#section-3.2.2
|
|
17
|
+
// @quote [3] "A server MUST accept the absolute-form in requests even though most HTTP/1.1 clients will only send the absolute-form to a proxy."
|
|
18
|
+
// @retrieved 2026-12-05
|
|
19
|
+
// @tests tests/transport.rs
|
|
20
|
+
// @requirement SDKL-HTTP-004
|
|
21
|
+
|
|
22
|
+
/// How one request is sent.
|
|
23
|
+
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
|
24
|
+
pub struct SendOptions {
|
|
25
|
+
/// Bounds the whole exchange; for a stream, the response head and then each wait for more of the body.
|
|
26
|
+
pub timeout_ms: Option<i64>,
|
|
27
|
+
/// Hand a successful response's body over as it arrives, in Response::stream (event streams).
|
|
28
|
+
pub stream: bool,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// Sends one request and returns its response, whatever the status; it fails only without a response.
|
|
32
|
+
pub trait Transport: Send + Sync {
|
|
33
|
+
fn send(&self, request: &Request, options: &SendOptions) -> Result<Response, Error>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
impl<F> Transport for F
|
|
37
|
+
where
|
|
38
|
+
F: Fn(&Request, &SendOptions) -> Result<Response, Error> + Send + Sync,
|
|
39
|
+
{
|
|
40
|
+
fn send(&self, request: &Request, options: &SendOptions) -> Result<Response, Error> {
|
|
41
|
+
self(request, options)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/// HTTP/1.1 with the standard library; one connection per request.
|
|
46
|
+
#[derive(Clone, Debug, Default)]
|
|
47
|
+
pub struct StdTransport {
|
|
48
|
+
/// "http://host:port" of an HTTP proxy.
|
|
49
|
+
pub proxy: Option<String>,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
struct Target {
|
|
53
|
+
host: String,
|
|
54
|
+
port: u16,
|
|
55
|
+
/// The Host header: brackets kept for IPv6, the port when it is not 80.
|
|
56
|
+
authority: String,
|
|
57
|
+
path: String,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// Longest status or header line accepted; a longer one is a broken or hostile server.
|
|
61
|
+
const MAX_LINE: u64 = 64 * 1024;
|
|
62
|
+
|
|
63
|
+
fn parse(url: &str) -> Result<Target, Error> {
|
|
64
|
+
let rest = if let Some(rest) = url.strip_prefix("http://") {
|
|
65
|
+
rest
|
|
66
|
+
} else if url.starts_with("https://") {
|
|
67
|
+
return Err(Error::transport("network", "https needs a transport with TLS; the standard library has none (see sdkloom adapter rust)"));
|
|
68
|
+
} else {
|
|
69
|
+
return Err(Error::transport("network", format!("unsupported URL {}", url)));
|
|
70
|
+
};
|
|
71
|
+
let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
|
|
72
|
+
let authority = &rest[..end];
|
|
73
|
+
let path = match &rest[end..] {
|
|
74
|
+
"" => "/".to_string(),
|
|
75
|
+
tail if tail.starts_with('/') => tail.to_string(),
|
|
76
|
+
tail => format!("/{}", tail),
|
|
77
|
+
};
|
|
78
|
+
let bad_port = || Error::transport("network", format!("bad port in {}", url));
|
|
79
|
+
let (host, port) = if let Some(inner) = authority.strip_prefix('[') {
|
|
80
|
+
let (address, after) = inner.split_once(']').ok_or_else(|| Error::transport("network", format!("bad IPv6 address in {}", url)))?;
|
|
81
|
+
let port = match after.strip_prefix(':') {
|
|
82
|
+
Some(port) => port.parse::<u16>().map_err(|_| bad_port())?,
|
|
83
|
+
None if after.is_empty() => 80,
|
|
84
|
+
None => return Err(bad_port()),
|
|
85
|
+
};
|
|
86
|
+
(address.to_string(), port)
|
|
87
|
+
} else {
|
|
88
|
+
match authority.rsplit_once(':') {
|
|
89
|
+
Some((host, port)) => (host.to_string(), port.parse::<u16>().map_err(|_| bad_port())?),
|
|
90
|
+
None => (authority.to_string(), 80),
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
let shown = if host.contains(':') { format!("[{}]", host) } else { host.clone() };
|
|
94
|
+
let authority = if port == 80 { shown } else { format!("{}:{}", shown, port) };
|
|
95
|
+
Ok(Target { host, port, authority, path })
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
fn failure(error: std::io::Error) -> Error {
|
|
99
|
+
match error.kind() {
|
|
100
|
+
ErrorKind::TimedOut | ErrorKind::WouldBlock => Error::transport("timeout", error),
|
|
101
|
+
_ => Error::transport("network", error),
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/// A stream whose reads share one deadline: a server that sends a byte now and then cannot hold a call past its timeout.
|
|
106
|
+
struct DeadlineStream {
|
|
107
|
+
stream: TcpStream,
|
|
108
|
+
deadline: Option<Instant>,
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
impl Read for DeadlineStream {
|
|
112
|
+
fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
|
|
113
|
+
if let Some(deadline) = self.deadline {
|
|
114
|
+
let left = deadline.saturating_duration_since(Instant::now());
|
|
115
|
+
if left.is_zero() {
|
|
116
|
+
return Err(std::io::Error::new(ErrorKind::TimedOut, "the call's timeout elapsed"));
|
|
117
|
+
}
|
|
118
|
+
self.stream.set_read_timeout(Some(left))?;
|
|
119
|
+
}
|
|
120
|
+
self.stream.read(buffer)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
fn connect(host: &str, port: u16, timeout: Option<Duration>) -> Result<TcpStream, Error> {
|
|
125
|
+
let addresses = (host, port).to_socket_addrs().map_err(failure)?;
|
|
126
|
+
let mut last = None;
|
|
127
|
+
for address in addresses {
|
|
128
|
+
let attempt = match timeout {
|
|
129
|
+
Some(limit) => TcpStream::connect_timeout(&address, limit),
|
|
130
|
+
None => TcpStream::connect(address),
|
|
131
|
+
};
|
|
132
|
+
match attempt {
|
|
133
|
+
Ok(stream) => return Ok(stream),
|
|
134
|
+
Err(error) => last = Some(error),
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
Err(last.map(failure).unwrap_or_else(|| Error::transport("network", format!("{} has no address", host))))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/// One line, decoded leniently (a Latin-1 header value must not fail the call); None at the end of the stream.
|
|
141
|
+
fn read_line(reader: &mut impl BufRead) -> Result<Option<String>, Error> {
|
|
142
|
+
let mut bytes = Vec::new();
|
|
143
|
+
reader.take(MAX_LINE).read_until(b'\n', &mut bytes).map_err(failure)?;
|
|
144
|
+
if bytes.is_empty() {
|
|
145
|
+
return Ok(None);
|
|
146
|
+
}
|
|
147
|
+
if !bytes.ends_with(b"\n") && bytes.len() as u64 >= MAX_LINE {
|
|
148
|
+
return Err(Error::transport("network", "response line too long"));
|
|
149
|
+
}
|
|
150
|
+
Ok(Some(String::from_utf8_lossy(&bytes).trim_end_matches(['\r', '\n']).to_string()))
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/// Exactly length bytes; memory grows only with what arrives, so a huge Content-Length cannot exhaust it up front.
|
|
154
|
+
fn read_exact_len(reader: &mut impl BufRead, length: u64) -> Result<Vec<u8>, Error> {
|
|
155
|
+
let mut data = Vec::new();
|
|
156
|
+
reader.take(length).read_to_end(&mut data).map_err(failure)?;
|
|
157
|
+
if (data.len() as u64) < length {
|
|
158
|
+
return Err(Error::transport("network", "the response ended early"));
|
|
159
|
+
}
|
|
160
|
+
Ok(data)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
fn read_chunked(reader: &mut impl BufRead) -> Result<Vec<u8>, Error> {
|
|
164
|
+
let mut body = Vec::new();
|
|
165
|
+
loop {
|
|
166
|
+
let line = read_line(reader)?.ok_or_else(|| Error::transport("network", "the response ended early"))?;
|
|
167
|
+
let size = u64::from_str_radix(line.trim().split(';').next().unwrap_or("0"), 16).map_err(|_| Error::transport("network", "bad chunk size"))?;
|
|
168
|
+
if size == 0 {
|
|
169
|
+
// Trailer fields end with an empty line.
|
|
170
|
+
while let Some(trailer) = read_line(reader)? {
|
|
171
|
+
if trailer.trim().is_empty() {
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return Ok(body);
|
|
176
|
+
}
|
|
177
|
+
body.extend(read_exact_len(reader, size)?);
|
|
178
|
+
read_line(reader)?;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/// A chunked body read as it arrives: each read returns bytes of the current chunk.
|
|
183
|
+
struct ChunkedReader<R: BufRead> {
|
|
184
|
+
inner: R,
|
|
185
|
+
left: u64,
|
|
186
|
+
done: bool,
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
fn io_failure(error: Error) -> std::io::Error {
|
|
190
|
+
std::io::Error::new(ErrorKind::InvalidData, error.to_string())
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
impl<R: BufRead> Read for ChunkedReader<R> {
|
|
194
|
+
fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
|
|
195
|
+
if self.done || buffer.is_empty() {
|
|
196
|
+
return Ok(0);
|
|
197
|
+
}
|
|
198
|
+
if self.left == 0 {
|
|
199
|
+
let line = read_line(&mut self.inner).map_err(io_failure)?.ok_or_else(|| std::io::Error::new(ErrorKind::UnexpectedEof, "the response ended early"))?;
|
|
200
|
+
let size = u64::from_str_radix(line.trim().split(';').next().unwrap_or("0"), 16).map_err(|_| std::io::Error::new(ErrorKind::InvalidData, "bad chunk size"))?;
|
|
201
|
+
if size == 0 {
|
|
202
|
+
while let Some(trailer) = read_line(&mut self.inner).map_err(io_failure)? {
|
|
203
|
+
if trailer.trim().is_empty() {
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
self.done = true;
|
|
208
|
+
return Ok(0);
|
|
209
|
+
}
|
|
210
|
+
self.left = size;
|
|
211
|
+
}
|
|
212
|
+
let most = buffer.len().min(self.left.min(usize::MAX as u64) as usize);
|
|
213
|
+
let count = self.inner.read(&mut buffer[..most])?;
|
|
214
|
+
if count == 0 {
|
|
215
|
+
return Err(std::io::Error::new(ErrorKind::UnexpectedEof, "the response ended early"));
|
|
216
|
+
}
|
|
217
|
+
self.left -= count as u64;
|
|
218
|
+
if self.left == 0 {
|
|
219
|
+
read_line(&mut self.inner).map_err(io_failure)?;
|
|
220
|
+
}
|
|
221
|
+
Ok(count)
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/// A status line and its header fields.
|
|
226
|
+
fn read_head(reader: &mut impl BufRead) -> Result<(u16, Vec<(String, String)>), Error> {
|
|
227
|
+
let status_line = read_line(reader)?.unwrap_or_default();
|
|
228
|
+
let status = status_line.split_whitespace().nth(1).and_then(|code| code.parse::<u16>().ok()).ok_or_else(|| Error::transport("network", format!("bad status line {:?}", status_line.trim())))?;
|
|
229
|
+
let mut headers = Vec::new();
|
|
230
|
+
while let Some(line) = read_line(reader)? {
|
|
231
|
+
if line.trim().is_empty() {
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
if let Some((name, value)) = line.split_once(':') {
|
|
235
|
+
headers.push((name.trim().to_string(), value.trim().to_string()));
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
Ok((status, headers))
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/// CR, LF and NUL in a request line or header would let a value add headers of its own.
|
|
242
|
+
fn check_field(what: &str, text: &str) -> Result<(), Error> {
|
|
243
|
+
if text.contains(['\r', '\n', '\0']) {
|
|
244
|
+
return Err(Error::thrown(format!("invalid {}: it contains a line break", what)));
|
|
245
|
+
}
|
|
246
|
+
Ok(())
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
impl Transport for StdTransport {
|
|
250
|
+
fn send(&self, request: &Request, options: &SendOptions) -> Result<Response, Error> {
|
|
251
|
+
check_field("method", &request.method)?;
|
|
252
|
+
check_field("URL", &request.url)?;
|
|
253
|
+
for (name, value) in &request.headers {
|
|
254
|
+
check_field("header name", name)?;
|
|
255
|
+
check_field("header value", value)?;
|
|
256
|
+
}
|
|
257
|
+
let target = parse(&request.url)?;
|
|
258
|
+
let timeout = options.timeout_ms.map(|ms| Duration::from_millis(ms.max(1) as u64));
|
|
259
|
+
let (connect_host, connect_port, request_target) = match &self.proxy {
|
|
260
|
+
Some(proxy) => {
|
|
261
|
+
let via = parse(proxy)?;
|
|
262
|
+
(via.host, via.port, format!("http://{}{}", target.authority, target.path))
|
|
263
|
+
}
|
|
264
|
+
None => (target.host.clone(), target.port, target.path.clone()),
|
|
265
|
+
};
|
|
266
|
+
let mut stream = connect(&connect_host, connect_port, timeout)?;
|
|
267
|
+
stream.set_read_timeout(timeout).map_err(failure)?;
|
|
268
|
+
stream.set_write_timeout(timeout).map_err(failure)?;
|
|
269
|
+
let mut head = format!("{} {} HTTP/1.1\r\nhost: {}\r\nconnection: close\r\n", request.method, request_target, target.authority);
|
|
270
|
+
for (name, value) in &request.headers {
|
|
271
|
+
if !["host", "connection", "content-length", "transfer-encoding"].contains(&name.to_ascii_lowercase().as_str()) {
|
|
272
|
+
head.push_str(&format!("{}: {}\r\n", name, value));
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
let body = request.body.clone().unwrap_or_default();
|
|
276
|
+
if request.body.is_some() || ["POST", "PUT", "PATCH"].contains(&request.method.as_str()) {
|
|
277
|
+
head.push_str(&format!("content-length: {}\r\n", body.len()));
|
|
278
|
+
}
|
|
279
|
+
head.push_str("\r\n");
|
|
280
|
+
stream.write_all(head.as_bytes()).map_err(failure)?;
|
|
281
|
+
stream.write_all(&body).map_err(failure)?;
|
|
282
|
+
stream.flush().map_err(failure)?;
|
|
283
|
+
|
|
284
|
+
let mut reader = BufReader::new(DeadlineStream { stream, deadline: timeout.map(|limit| Instant::now() + limit) });
|
|
285
|
+
// Interim responses (100 Continue, 103 Early Hints) come before the final one.
|
|
286
|
+
let (status, headers) = loop {
|
|
287
|
+
let (status, headers) = read_head(&mut reader)?;
|
|
288
|
+
if !(100..200).contains(&status) || status == 101 {
|
|
289
|
+
break (status, headers);
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
let response = Response::new(status, headers, Vec::new());
|
|
293
|
+
let bodyless = request.method == "HEAD" || status == 204 || status == 304 || (100..200).contains(&status);
|
|
294
|
+
let chunked = response.header("transfer-encoding").map(|value| value.to_ascii_lowercase().contains("chunked")).unwrap_or(false);
|
|
295
|
+
if options.stream && (200..300).contains(&status) && !bodyless {
|
|
296
|
+
// The whole-response deadline ends here; the read timeout still bounds each wait for more of the body.
|
|
297
|
+
reader.get_mut().deadline = None;
|
|
298
|
+
reader.get_ref().stream.set_read_timeout(timeout).map_err(failure)?;
|
|
299
|
+
let length = response.header("content-length").and_then(|value| value.trim().parse::<u64>().ok());
|
|
300
|
+
let stream = if chunked {
|
|
301
|
+
BodyStream::new(ChunkedReader { inner: reader, left: 0, done: false })
|
|
302
|
+
} else if let Some(length) = length {
|
|
303
|
+
BodyStream::new(reader.take(length))
|
|
304
|
+
} else {
|
|
305
|
+
BodyStream::new(reader)
|
|
306
|
+
};
|
|
307
|
+
return Ok(Response { stream: Some(stream), ..response });
|
|
308
|
+
}
|
|
309
|
+
let body = if bodyless {
|
|
310
|
+
Vec::new()
|
|
311
|
+
} else if chunked {
|
|
312
|
+
read_chunked(&mut reader)?
|
|
313
|
+
} else if let Some(length) = response.header("content-length").and_then(|value| value.trim().parse::<u64>().ok()) {
|
|
314
|
+
read_exact_len(&mut reader, length)?
|
|
315
|
+
} else {
|
|
316
|
+
let mut data = Vec::new();
|
|
317
|
+
reader.read_to_end(&mut data).map_err(failure)?;
|
|
318
|
+
data
|
|
319
|
+
};
|
|
320
|
+
Ok(Response { body, ..response })
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// @end
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// sdkloom Rust kit: waiting for a long-running operation.
|
|
2
|
+
|
|
3
|
+
use super::context::Clock;
|
|
4
|
+
use super::errors::Error;
|
|
5
|
+
|
|
6
|
+
// @block lro.wait
|
|
7
|
+
// @summary Waits for a long-running operation: polls until the result says the work is done, sleeping on the client's clock between polls, and fails with Error::WaitTimeout when the next poll would come after the deadline.
|
|
8
|
+
// @versions >=1.70
|
|
9
|
+
// @source [1] https://www.rfc-editor.org/rfc/rfc9110#section-15.3.3
|
|
10
|
+
// @quote [1] "The 202 (Accepted) status code indicates that the request has been accepted for processing, but the processing has not been completed."
|
|
11
|
+
// @retrieved 2026-12-06
|
|
12
|
+
// @tests tests/wait.rs
|
|
13
|
+
// @requirement SDKL-WAIT-001
|
|
14
|
+
|
|
15
|
+
/// Polls until done(result); the first result comes from starting the work.
|
|
16
|
+
pub fn wait_until<R>(first: R, mut poll: impl FnMut(&R) -> Result<R, Error>, done: impl Fn(&R) -> bool, clock: &dyn Clock, interval_ms: i64, timeout_ms: i64) -> Result<R, Error> {
|
|
17
|
+
let deadline = clock.now() + timeout_ms;
|
|
18
|
+
let mut current = first;
|
|
19
|
+
while !done(¤t) {
|
|
20
|
+
if clock.now() + interval_ms > deadline {
|
|
21
|
+
return Err(Error::WaitTimeout(format!("the work did not finish within {} ms", timeout_ms)));
|
|
22
|
+
}
|
|
23
|
+
clock.sleep(interval_ms);
|
|
24
|
+
current = poll(¤t)?;
|
|
25
|
+
}
|
|
26
|
+
Ok(current)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// @end
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// sdkloom Rust kit: verifying the signature of a webhook the API sent.
|
|
2
|
+
|
|
3
|
+
use super::crypto::hmac_sha256;
|
|
4
|
+
use super::errors::Error;
|
|
5
|
+
|
|
6
|
+
// @block webhooks.verify
|
|
7
|
+
// @summary Verifies a webhook's HMAC-SHA256 signature as the definition describes it (signed text from the body and headers, several signatures in one header, an optional timestamp tolerance against replays), comparing in constant time, and fails with Error::WebhookSignature.
|
|
8
|
+
// @versions >=1.70
|
|
9
|
+
// @source [1] https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md
|
|
10
|
+
// @quote [1] "When verifying symmetric signatures, use a constant time comparison function to compare the calculated with the expected signature."
|
|
11
|
+
// @quote [1] "The signature header is a space delimited list of signatures associated with this webhook."
|
|
12
|
+
// @retrieved 2026-12-05
|
|
13
|
+
// @tests tests/webhooks.rs
|
|
14
|
+
// @requirement SDKL-HOOK-001
|
|
15
|
+
|
|
16
|
+
/// How a webhook is signed; the same fields as the definition's hmacSignature().
|
|
17
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
18
|
+
pub struct WebhookSignature {
|
|
19
|
+
pub header: &'static str,
|
|
20
|
+
/// "hex" or "base64".
|
|
21
|
+
pub encoding: &'static str,
|
|
22
|
+
pub prefix: &'static str,
|
|
23
|
+
/// None when the header holds one signature.
|
|
24
|
+
pub separator: Option<&'static str>,
|
|
25
|
+
/// e.g. "{webhook-id}.{webhook-timestamp}.{body}".
|
|
26
|
+
pub signed: &'static str,
|
|
27
|
+
/// The timestamp header and how many seconds it may differ from now; None when the webhook carries no timestamp.
|
|
28
|
+
pub timestamp: Option<(&'static str, i64)>,
|
|
29
|
+
/// "text" or "base64".
|
|
30
|
+
pub secret: &'static str,
|
|
31
|
+
pub secret_prefix: &'static str,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
fn header<'h>(headers: &'h [(String, String)], name: &str) -> Option<&'h str> {
|
|
35
|
+
headers.iter().find(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| value.as_str())
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
fn fail(message: impl Into<String>) -> Error {
|
|
39
|
+
Error::WebhookSignature(message.into())
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
43
|
+
|
|
44
|
+
pub(crate) fn base64_encode(bytes: &[u8]) -> String {
|
|
45
|
+
let mut out = String::new();
|
|
46
|
+
for chunk in bytes.chunks(3) {
|
|
47
|
+
let triple = (u32::from(chunk[0]) << 16) | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) | u32::from(*chunk.get(2).unwrap_or(&0));
|
|
48
|
+
for index in 0..4 {
|
|
49
|
+
if index <= chunk.len() {
|
|
50
|
+
out.push(BASE64[((triple >> (18 - 6 * index)) & 63) as usize] as char);
|
|
51
|
+
} else {
|
|
52
|
+
out.push('=');
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
out
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
fn base64_decode(text: &str) -> Option<Vec<u8>> {
|
|
60
|
+
let bytes = text.as_bytes();
|
|
61
|
+
if bytes.len() % 4 != 0 {
|
|
62
|
+
return None;
|
|
63
|
+
}
|
|
64
|
+
let mut out = Vec::new();
|
|
65
|
+
for (number, chunk) in bytes.chunks(4).enumerate() {
|
|
66
|
+
let last = number == bytes.len() / 4 - 1;
|
|
67
|
+
let padding = chunk.iter().rev().take_while(|byte| **byte == b'=').count();
|
|
68
|
+
if padding > 2 || (padding > 0 && !last) {
|
|
69
|
+
return None;
|
|
70
|
+
}
|
|
71
|
+
let mut triple = 0u32;
|
|
72
|
+
for byte in &chunk[..4 - padding] {
|
|
73
|
+
let value = BASE64.iter().position(|candidate| candidate == byte)? as u32;
|
|
74
|
+
triple = (triple << 6) | value;
|
|
75
|
+
}
|
|
76
|
+
triple <<= 6 * padding as u32;
|
|
77
|
+
out.extend_from_slice(&triple.to_be_bytes()[1..4 - padding]);
|
|
78
|
+
}
|
|
79
|
+
Some(out)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
pub(crate) fn hex(bytes: &[u8]) -> String {
|
|
83
|
+
bytes.iter().map(|byte| format!("{:02x}", byte)).collect()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// Compares in constant time for equal lengths: every byte is looked at.
|
|
87
|
+
fn same(a: &[u8], b: &[u8]) -> bool {
|
|
88
|
+
a.len() == b.len() && a.iter().zip(b).fold(0u8, |diff, (x, y)| diff | (x ^ y)) == 0
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/// Fails with Error::WebhookSignature unless one of the header's signatures is the HMAC of the signed text, made in time.
|
|
92
|
+
pub fn verify_webhook(signature: &WebhookSignature, body: &[u8], headers: &[(String, String)], secret: &str, now_seconds: i64) -> Result<(), Error> {
|
|
93
|
+
if let Some((name, tolerance)) = signature.timestamp {
|
|
94
|
+
let stamp = header(headers, name).unwrap_or("").trim();
|
|
95
|
+
if stamp.is_empty() || stamp.len() > 15 || !stamp.bytes().all(|byte| byte.is_ascii_digit()) {
|
|
96
|
+
return Err(fail(format!("missing or invalid {} header", name)));
|
|
97
|
+
}
|
|
98
|
+
let signed: i64 = stamp.parse().unwrap_or(0);
|
|
99
|
+
if (now_seconds - signed).abs() > tolerance {
|
|
100
|
+
return Err(fail(format!("the webhook was signed at {}, more than {} s from now", stamp, tolerance)));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
let given = header(headers, signature.header).ok_or_else(|| fail(format!("missing {} header", signature.header)))?;
|
|
104
|
+
let mut message = Vec::new();
|
|
105
|
+
let mut rest = signature.signed;
|
|
106
|
+
while let Some(open) = rest.find('{') {
|
|
107
|
+
let close = match rest[open..].find('}') {
|
|
108
|
+
Some(close) => open + close,
|
|
109
|
+
None => break,
|
|
110
|
+
};
|
|
111
|
+
message.extend_from_slice(rest[..open].as_bytes());
|
|
112
|
+
let name = &rest[open + 1..close];
|
|
113
|
+
if name == "body" {
|
|
114
|
+
message.extend_from_slice(body);
|
|
115
|
+
} else {
|
|
116
|
+
message.extend_from_slice(header(headers, name).ok_or_else(|| fail(format!("missing {} header", name)))?.as_bytes());
|
|
117
|
+
}
|
|
118
|
+
rest = &rest[close + 1..];
|
|
119
|
+
}
|
|
120
|
+
message.extend_from_slice(rest.as_bytes());
|
|
121
|
+
let key_text = secret.strip_prefix(signature.secret_prefix).unwrap_or(secret);
|
|
122
|
+
let key = if signature.secret == "base64" { base64_decode(key_text).ok_or_else(|| fail("the secret is not valid base64"))? } else { key_text.as_bytes().to_vec() };
|
|
123
|
+
let digest = hmac_sha256(&key, &message);
|
|
124
|
+
let expected = if signature.encoding == "hex" { hex(&digest) } else { base64_encode(&digest) };
|
|
125
|
+
let candidates: Vec<&str> = match signature.separator {
|
|
126
|
+
Some(separator) => given.split(separator).collect(),
|
|
127
|
+
None => vec![given],
|
|
128
|
+
};
|
|
129
|
+
let mut matched = false;
|
|
130
|
+
for candidate in candidates {
|
|
131
|
+
if let Some(value) = candidate.strip_prefix(signature.prefix) {
|
|
132
|
+
matched |= same(value.as_bytes(), expected.as_bytes());
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if matched {
|
|
136
|
+
Ok(())
|
|
137
|
+
} else {
|
|
138
|
+
Err(fail("no signature matches: the webhook was not signed with this secret, or was changed after signing"))
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// @end
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// @requirement SDKL-ERR-001
|
|
2
|
+
// @requirement SDKL-VERSION-001
|
|
3
|
+
// @requirement SDKL-PIPE-001
|
|
4
|
+
// @requirement SDKL-PIPE-002
|
|
5
|
+
// @requirement SDKL-JSON-002
|
|
6
|
+
use sdkruntime::runtime::context::{emit, LISTENER_ERROR};
|
|
7
|
+
use sdkruntime::runtime::*;
|
|
8
|
+
use std::collections::HashMap;
|
|
9
|
+
use std::sync::{Arc, Mutex};
|
|
10
|
+
|
|
11
|
+
fn not_found(status: u16, body: Json, response: Response) -> Error {
|
|
12
|
+
Error::api_error("NotFound", status, body, response)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
static GET_ITEM: OperationSpec = OperationSpec { name: "getItem", method: "GET", path: "/v1/items/{id}", body: None, result: Some(Kind::Json), errors: &[(404, not_found)], uses: &[], since: None };
|
|
16
|
+
|
|
17
|
+
fn runtime(transport: Arc<MockTransport>, middleware: Vec<MiddlewareEntry>) -> Runtime {
|
|
18
|
+
let clock: Arc<dyn Clock> = FakeClock::new(0);
|
|
19
|
+
Runtime {
|
|
20
|
+
base_url: "https://api.test".into(),
|
|
21
|
+
transport,
|
|
22
|
+
clock: clock.clone(),
|
|
23
|
+
state: Arc::new(State::new(clock)),
|
|
24
|
+
middleware,
|
|
25
|
+
registry: HashMap::new(),
|
|
26
|
+
user_middleware: vec![],
|
|
27
|
+
listeners: vec![],
|
|
28
|
+
timeout_ms: None,
|
|
29
|
+
sdk: SdkInfo { name: "acme".into(), version: "1.0.0".into(), language: "rust".into() },
|
|
30
|
+
api_version: None,
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
#[test]
|
|
35
|
+
fn a_call_sends_url_headers_and_body() {
|
|
36
|
+
let transport = MockTransport::new();
|
|
37
|
+
transport.route("POST", "/v1/items/{id}", None).reply_json(201, &Json::object(vec![("ok", Json::Bool(true))]));
|
|
38
|
+
let spec = OperationSpec { name: "putItem", method: "POST", path: "/v1/items/{id}", body: Some(Kind::Json), result: Some(Kind::Json), errors: &[], uses: &[], since: None };
|
|
39
|
+
let args = Args { path: vec![("id", Json::str("a 1"))], query: vec![("expand", Json::Array(vec![Json::str("x"), Json::str("y")]))], headers: vec![("x-trace", Json::str("t1")), ("x-none", Json::Null)], body: Some(r#"{"name":"ş"}"#.as_bytes().to_vec()) };
|
|
40
|
+
let options = CallOptions { headers: vec![("x-extra".into(), "e".into())], ..CallOptions::default() };
|
|
41
|
+
|
|
42
|
+
let response = call(&runtime(transport.clone(), vec![]), &spec, args, &options).unwrap();
|
|
43
|
+
|
|
44
|
+
assert_eq!(response.status, 201);
|
|
45
|
+
let sent = &transport.calls()[0];
|
|
46
|
+
assert_eq!(sent.url, "https://api.test/v1/items/a%201?expand=x&expand=y");
|
|
47
|
+
assert_eq!(sent.body.as_deref(), Some(r#"{"name":"ş"}"#.as_bytes()));
|
|
48
|
+
for (name, want) in [("accept", "application/json"), ("content-type", "application/json"), ("x-trace", "t1"), ("x-extra", "e")] {
|
|
49
|
+
assert_eq!(sent.header(name).as_deref(), Some(want), "{}", name);
|
|
50
|
+
}
|
|
51
|
+
assert_eq!(sent.header("x-none"), None);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
#[test]
|
|
55
|
+
fn statuses_become_declared_or_generic_errors() {
|
|
56
|
+
let transport = MockTransport::new();
|
|
57
|
+
transport.route("GET", "/v1/items/{id}", Some(Arc::new(|r: &Request| r.url.ends_with("/missing")))).reply_json(404, &Json::object(vec![("message", Json::str("no"))]));
|
|
58
|
+
transport.route("GET", "/v1/items/{id}", Some(Arc::new(|r: &Request| r.url.ends_with("/down")))).reply(503, b"down".to_vec(), vec![("X-Request-Id".into(), "req_1".into())]);
|
|
59
|
+
let rt = runtime(transport, vec![]);
|
|
60
|
+
|
|
61
|
+
let missing = call(&rt, &GET_ITEM, Args { path: vec![("id", Json::str("missing"))], ..Args::default() }, &CallOptions::default()).unwrap_err();
|
|
62
|
+
assert!(missing.is("NotFound"));
|
|
63
|
+
let api = missing.api().unwrap();
|
|
64
|
+
assert_eq!((api.status, api.body.get("message").cloned(), api.retryable()), (404, Some(Json::str("no")), false));
|
|
65
|
+
let down = call(&rt, &GET_ITEM, Args { path: vec![("id", Json::str("down"))], ..Args::default() }, &CallOptions::default()).unwrap_err();
|
|
66
|
+
let api = down.api().unwrap();
|
|
67
|
+
assert_eq!((down.name(), &api.body, api.retryable(), api.request_id.as_deref()), ("ApiError", &Json::str("down"), true, Some("req_1")));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
fn tag(request: Request, next: Next, ctx: &Context) -> Result<Response, Error> {
|
|
71
|
+
let label = sdkruntime::runtime::lang::to_string(&ctx.config("label"))?;
|
|
72
|
+
next(request.with_header(&format!("x-{}", label), &format!("{}:{}:{}", label, ctx.operation.name, ctx.sdk.language)))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
fn retry(request: Request, next: Next, ctx: &Context) -> Result<Response, Error> {
|
|
76
|
+
let response = next(request.clone())?;
|
|
77
|
+
if response.status == 503 {
|
|
78
|
+
ctx.clock.sleep(100);
|
|
79
|
+
ctx.emit("retry", Json::object(vec![("attempt", Json::int(1))]));
|
|
80
|
+
return next(request);
|
|
81
|
+
}
|
|
82
|
+
Ok(response)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
#[test]
|
|
86
|
+
fn middleware_runs_in_order_with_config_and_context() {
|
|
87
|
+
let transport = MockTransport::new();
|
|
88
|
+
transport.route("GET", "/v1/items/{id}", None).reply(503, vec![], vec![]).reply(200, b"{}".to_vec(), vec![]);
|
|
89
|
+
let events = Arc::new(Mutex::new(Vec::new()));
|
|
90
|
+
let seen = events.clone();
|
|
91
|
+
let config = |label: &str| vec![("label".to_string(), Json::str(label))];
|
|
92
|
+
let mut rt = runtime(transport.clone(), vec![entry("sdk", tag, config("sdk")), entry("retry", retry, vec![])]);
|
|
93
|
+
rt.registry.insert("op".into(), entry("op", tag, config("op")));
|
|
94
|
+
rt.user_middleware = vec![entry("user", tag, config("user"))];
|
|
95
|
+
rt.listeners = vec![Arc::new(move |name: &str, _: &Json| seen.lock().unwrap().push(name.to_string()))];
|
|
96
|
+
static WITH_OP: OperationSpec = OperationSpec { name: "getItem", method: "GET", path: "/v1/items/{id}", body: None, result: Some(Kind::Json), errors: &[], uses: &["op"], since: None };
|
|
97
|
+
|
|
98
|
+
let response = call(&rt, &WITH_OP, Args { path: vec![("id", Json::str("1"))], ..Args::default() }, &CallOptions::default()).unwrap();
|
|
99
|
+
|
|
100
|
+
assert_eq!(response.status, 200);
|
|
101
|
+
let second = &transport.calls()[1];
|
|
102
|
+
assert_eq!((second.header("x-sdk").as_deref(), second.header("x-op").as_deref(), second.header("x-user").as_deref()), (Some("sdk:getItem:rust"), Some("op:getItem:rust"), Some("user:getItem:rust")));
|
|
103
|
+
assert_eq!((rt.clock.now(), events.lock().unwrap().clone()), (100, vec!["retry".to_string()]));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
#[test]
|
|
107
|
+
fn listeners_that_panic_are_reported_not_propagated() {
|
|
108
|
+
let seen = Arc::new(Mutex::new(Vec::new()));
|
|
109
|
+
let log = seen.clone();
|
|
110
|
+
let listeners: Vec<EventListener> = vec![
|
|
111
|
+
Arc::new(|name: &str, _: &Json| {
|
|
112
|
+
if name != LISTENER_ERROR {
|
|
113
|
+
panic!("boom")
|
|
114
|
+
}
|
|
115
|
+
}),
|
|
116
|
+
Arc::new(move |name: &str, fields: &Json| log.lock().unwrap().push(format!("{} {}", name, sdkruntime::runtime::lang::js_str(&fields.get("error").cloned().unwrap_or(Json::Null))))),
|
|
117
|
+
];
|
|
118
|
+
let hook = std::panic::take_hook();
|
|
119
|
+
std::panic::set_hook(Box::new(|_| {}));
|
|
120
|
+
emit(&listeners, "http.request", &Json::Object(vec![]));
|
|
121
|
+
std::panic::set_hook(hook);
|
|
122
|
+
assert_eq!(seen.lock().unwrap().clone(), vec!["http.request null".to_string(), "sdkloom.listener_error boom".to_string()]);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
#[test]
|
|
126
|
+
fn state_is_shared_between_threads_and_expires() {
|
|
127
|
+
let clock = FakeClock::new(0);
|
|
128
|
+
let state = Arc::new(State::new(clock.clone()));
|
|
129
|
+
let threads: Vec<_> = (0..8).map(|i| {
|
|
130
|
+
let state = state.clone();
|
|
131
|
+
std::thread::spawn(move || {
|
|
132
|
+
state.set("k", Json::int(i), None);
|
|
133
|
+
let _ = state.get("k");
|
|
134
|
+
})
|
|
135
|
+
}).collect();
|
|
136
|
+
threads.into_iter().for_each(|thread| thread.join().unwrap());
|
|
137
|
+
state.set("token", Json::str("t"), Some(1000));
|
|
138
|
+
clock.advance(999);
|
|
139
|
+
assert_eq!(state.get("token"), Json::str("t"));
|
|
140
|
+
clock.advance(1);
|
|
141
|
+
assert_eq!(state.get("token"), Json::Null);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
#[test]
|
|
145
|
+
fn an_operation_newer_than_the_pinned_api_version_is_refused_and_unknown_versions_too() {
|
|
146
|
+
use sdkruntime::runtime::ApiVersion;
|
|
147
|
+
let version = ApiVersion { header: "api-version".into(), value: "2024-06-20".into(), values: vec!["2024-06-20".into(), "2025-01-01".into()] };
|
|
148
|
+
assert!(version.check("getOrder", Some("2024-06-20")).is_ok());
|
|
149
|
+
assert!(version.check("getOrder", None).is_ok());
|
|
150
|
+
assert_eq!(version.check("refundOrder", Some("2025-01-01")).unwrap_err().to_string(), "refundOrder needs API version 2025-01-01 or later; this client uses 2024-06-20");
|
|
151
|
+
assert_eq!(ApiVersion { value: "1999".into(), ..version }.check("getOrder", None).unwrap_err().name(), "ArgumentError");
|
|
152
|
+
}
|